lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
Java
|
lgpl-2.1
|
eee81351d4d1c32af80fd88a78415fdc910785ce
| 0 |
dmf444/MinecraftForge,Zaggy1024/MinecraftForge,Vorquel/MinecraftForge,Mathe172/MinecraftForge,brubo1/MinecraftForge,RainWarrior/MinecraftForge,fcjailybo/MinecraftForge,shadekiller666/MinecraftForge,mickkay/MinecraftForge,karlthepagan/MinecraftForge,bonii-xx/MinecraftForge,Theerapak/MinecraftForge,jdpadrnos/MinecraftForge,Ghostlyr/MinecraftForge,simon816/MinecraftForge,ThiagoGarciaAlves/MinecraftForge,CrafterKina/MinecraftForge,luacs1998/MinecraftForge,blay09/MinecraftForge
|
/**
* This software is provided under the terms of the Minecraft Forge Public
* License v1.0.
*/
package net.minecraft.src.forge;
import net.minecraft.src.BaseMod;
import net.minecraft.src.Block;
import net.minecraft.src.Chunk;
import net.minecraft.src.ChunkCoordIntPair;
import net.minecraft.src.Entity;
import net.minecraft.src.EntityItem;
import net.minecraft.src.EntityLiving;
import net.minecraft.src.EntityMinecart;
import net.minecraft.src.EntityPlayer;
import net.minecraft.src.IInventory;
import net.minecraft.src.ItemStack;
import net.minecraft.src.Item;
import net.minecraft.src.EnumStatus;
import net.minecraft.src.ModLoader;
import net.minecraft.src.NBTTagCompound;
import net.minecraft.src.NetworkManager;
import net.minecraft.src.Packet;
import net.minecraft.src.Packet131MapData;
import net.minecraft.src.Packet1Login;
import net.minecraft.src.Packet250CustomPayload;
import net.minecraft.src.World;
import net.minecraft.src.forge.packets.PacketEntitySpawn;
import net.minecraft.src.forge.packets.PacketHandlerBase;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.logging.Level;
public class ForgeHooks
{
// List Handling Hooks
// ------------------------------------------------------------
public static void onTakenFromCrafting(EntityPlayer player, ItemStack stack, IInventory craftMatrix)
{
for (ICraftingHandler handler : craftingHandlers)
{
handler.onTakenFromCrafting(player, stack, craftMatrix);
}
}
static LinkedList<ICraftingHandler> craftingHandlers = new LinkedList<ICraftingHandler>();
public static void onDestroyCurrentItem(EntityPlayer player, ItemStack orig)
{
for (IDestroyToolHandler handler : destroyToolHandlers)
{
handler.onDestroyCurrentItem(player, orig);
}
}
static LinkedList<IDestroyToolHandler> destroyToolHandlers = new LinkedList<IDestroyToolHandler>();
public static boolean onUseBonemeal(World world, int blockID, int x, int y, int z)
{
for (IBonemealHandler handler : bonemealHandlers)
{
if (handler.onUseBonemeal(world, blockID, x, y, z))
{
return true;
}
}
return false;
}
static LinkedList<IBonemealHandler> bonemealHandlers = new LinkedList<IBonemealHandler>();
public static boolean onUseHoe(ItemStack hoe, EntityPlayer player, World world, int x, int y, int z)
{
for (IHoeHandler handler : hoeHandlers)
{
if (handler.onUseHoe(hoe, player, world, x, y, z))
{
return true;
}
}
return false;
}
static LinkedList<IHoeHandler> hoeHandlers = new LinkedList<IHoeHandler>();
public static EnumStatus sleepInBedAt(EntityPlayer player, int x, int y, int z)
{
for (ISleepHandler handler : sleepHandlers)
{
EnumStatus status = handler.sleepInBedAt(player, x, y, z);
if (status != null)
{
return status;
}
}
return null;
}
static LinkedList<ISleepHandler> sleepHandlers = new LinkedList<ISleepHandler>();
public static void onMinecartUpdate(EntityMinecart minecart, int x, int y, int z)
{
for (IMinecartHandler handler : minecartHandlers)
{
handler.onMinecartUpdate(minecart, x, y, z);
}
}
public static void onMinecartEntityCollision(EntityMinecart minecart, Entity entity)
{
for (IMinecartHandler handler : minecartHandlers)
{
handler.onMinecartEntityCollision(minecart, entity);
}
}
public static boolean onMinecartInteract(EntityMinecart minecart, EntityPlayer player)
{
boolean canceled = true;
for (IMinecartHandler handler : minecartHandlers)
{
boolean tmp = handler.onMinecartInteract(minecart, player, canceled);
canceled = canceled && tmp;
}
return canceled;
}
static LinkedList<IMinecartHandler> minecartHandlers = new LinkedList<IMinecartHandler>();
public static void onConnect(NetworkManager network)
{
for (IConnectionHandler handler : connectionHandlers)
{
handler.onConnect(network);
}
}
public static void onLogin(NetworkManager network, Packet1Login login)
{
for (IConnectionHandler handler : connectionHandlers)
{
handler.onLogin(network, login);
}
}
public static void onDisconnect(NetworkManager network, String message, Object[] args)
{
for (IConnectionHandler handler : connectionHandlers)
{
handler.onDisconnect(network, message, args);
}
}
static LinkedList<IConnectionHandler> connectionHandlers = new LinkedList<IConnectionHandler>();
public static boolean onItemPickup(EntityPlayer player, EntityItem item)
{
boolean cont = true;
for (IPickupHandler handler : pickupHandlers)
{
cont = cont && handler.onItemPickup(player, item);
if (!cont || item.item.stackSize <= 0)
{
return false;
}
}
return cont;
}
static LinkedList<IPickupHandler> pickupHandlers = new LinkedList<IPickupHandler>();
public static void addActiveChunks(World world, Set<ChunkCoordIntPair> chunkList)
{
for(IChunkLoadHandler loader : chunkLoadHandlers)
{
loader.addActiveChunks(world, chunkList);
}
}
public static boolean canUnloadChunk(Chunk chunk)
{
for(IChunkLoadHandler loader : chunkLoadHandlers)
{
if(!loader.canUnloadChunk(chunk))
{
return false;
}
}
return true;
}
public static boolean canUpdateEntity(Entity entity)
{
for(IChunkLoadHandler loader : chunkLoadHandlers)
{
if(loader.canUpdateEntity(entity))
{
return true;
}
}
return false;
}
static LinkedList<IChunkLoadHandler> chunkLoadHandlers = new LinkedList<IChunkLoadHandler>();
public static boolean onEntityInteract(EntityPlayer player, Entity entity, boolean isAttack)
{
for (IEntityInteractHandler handler : entityInteractHandlers)
{
if (!handler.onEntityInteract(player, entity, isAttack))
{
return false;
}
}
return true;
}
static LinkedList<IEntityInteractHandler> entityInteractHandlers = new LinkedList<IEntityInteractHandler>();
public static String onServerChat(EntityPlayer player, String message)
{
for (IChatHandler handler : chatHandlers)
{
message = handler.onServerChat(player, message);
if (message == null)
{
return null;
}
}
return message;
}
public static boolean onChatCommand(EntityPlayer player, boolean isOp, String command)
{
for (IChatHandler handler : chatHandlers)
{
if (handler.onChatCommand(player, isOp, command))
{
return true;
}
}
return false;
}
public static boolean onServerCommand(Object listener, String username, String command)
{
for (IChatHandler handler : chatHandlers)
{
if (handler.onServerCommand(listener, username, command))
{
return true;
}
}
return false;
}
public static String onServerCommandSay(Object listener, String username, String message)
{
for (IChatHandler handler : chatHandlers)
{
message = handler.onServerCommandSay(listener, username, message);
if (message == null)
{
return null;
}
}
return message;
}
public static String onClientChatRecv(String message)
{
for (IChatHandler handler : chatHandlers)
{
message = handler.onClientChatRecv(message);
if (message == null)
{
return null;
}
}
return message;
}
static LinkedList<IChatHandler> chatHandlers = new LinkedList<IChatHandler>();
public static void onWorldLoad(World world)
{
for (ISaveEventHandler handler : saveHandlers)
{
handler.onWorldLoad(world);
}
}
public static void onWorldSave(World world)
{
for (ISaveEventHandler handler : saveHandlers)
{
handler.onWorldSave(world);
}
}
public static void onChunkLoad(World world, Chunk chunk)
{
for (ISaveEventHandler handler : saveHandlers)
{
handler.onChunkLoad(world, chunk);
}
}
public static void onChunkUnload(World world, Chunk chunk)
{
for (ISaveEventHandler handler : saveHandlers)
{
handler.onChunkUnload(world, chunk);
}
}
public static void onChunkLoadData(World world, Chunk chunk, NBTTagCompound data)
{
for (ISaveEventHandler handler : saveHandlers)
{
handler.onChunkLoadData(world, chunk, data);
}
}
public static void onChunkSaveData(World world, Chunk chunk, NBTTagCompound data)
{
for (ISaveEventHandler handler : saveHandlers)
{
handler.onChunkSaveData(world, chunk, data);
}
}
static LinkedList<ISaveEventHandler> saveHandlers = new LinkedList<ISaveEventHandler>();
public static int getItemBurnTime(ItemStack stack)
{
for (IFuelHandler handler : fuelHandlers)
{
int ret = handler.getItemBurnTime(stack);
if (ret > 0)
{
return ret;
}
}
return 0;
}
static LinkedList<IFuelHandler> fuelHandlers = new LinkedList<IFuelHandler>();
public static boolean onEntitySpawnSpecial(EntityLiving entity, World world, float x, float y, float z)
{
for (ISpecialMobSpawnHandler handler : specialMobSpawnHandlers)
{
if (handler.onSpecialEntitySpawn(entity, world, x, y, z))
{
return true;
}
}
return false;
}
static LinkedList<ISpecialMobSpawnHandler> specialMobSpawnHandlers = new LinkedList<ISpecialMobSpawnHandler>();
// Plant Management
// ------------------------------------------------------------
static class ProbableItem
{
public ProbableItem(int item, int metadata, int quantity, int start, int end)
{
WeightStart = start;
WeightEnd = end;
ItemID = item;
Metadata = metadata;
Quantity = quantity;
}
int WeightStart, WeightEnd;
int ItemID, Metadata;
int Quantity;
}
static ProbableItem getRandomItem(List<ProbableItem> list, int prop)
{
int n = Collections.binarySearch(list, prop, new Comparator()
{
public int compare(Object o1, Object o2)
{
ProbableItem pi = (ProbableItem)o1;
Integer i1 = (Integer)o2;
if (i1 < pi.WeightStart)
{
return 1;
}
if (i1 >= pi.WeightEnd)
{
return -1;
}
return 0;
}
});
if (n < 0)
{
return null;
}
return list.get(n);
}
static List<ProbableItem> plantGrassList;
static int plantGrassWeight;
static List<ProbableItem> seedGrassList;
static int seedGrassWeight;
public static void plantGrassPlant(World world, int x, int y, int z)
{
int index = world.rand.nextInt(plantGrassWeight);
ProbableItem item = getRandomItem(plantGrassList, index);
if (item == null)
{
return;
}
world.setBlockAndMetadataWithNotify(x, y, z, item.ItemID, item.Metadata);
}
public static void addPlantGrass(int item, int metadata, int probability)
{
plantGrassList.add(new ProbableItem(item, metadata, 1, plantGrassWeight, plantGrassWeight + probability));
plantGrassWeight += probability;
}
public static ItemStack getGrassSeed(World world)
{
int index = world.rand.nextInt(seedGrassWeight);
ProbableItem item = getRandomItem(seedGrassList, index);
if (item == null)
{
return null;
}
return new ItemStack(item.ItemID, item.Quantity, item.Metadata);
}
public static void addGrassSeed(int item, int metadata, int quantity, int probability)
{
seedGrassList.add(new ProbableItem(item, metadata, quantity, seedGrassWeight, seedGrassWeight + probability));
seedGrassWeight += probability;
}
// Tool Path
// ------------------------------------------------------------
public static boolean canHarvestBlock(Block block, EntityPlayer player, int metadata)
{
if (block.blockMaterial.isHarvestable())
{
return true;
}
ItemStack stack = player.inventory.getCurrentItem();
if (stack == null)
{
return player.canHarvestBlock(block);
}
List info = (List)toolClasses.get(stack.itemID);
if (info == null)
{
return player.canHarvestBlock(block);
}
Object[] tmp = info.toArray();
String toolClass = (String)tmp[0];
int harvestLevel = (Integer)tmp[1];
Integer blockHarvestLevel = (Integer)toolHarvestLevels.get(Arrays.asList(block.blockID, metadata, toolClass));
if (blockHarvestLevel == null)
{
return player.canHarvestBlock(block);
}
if (blockHarvestLevel > harvestLevel)
{
return false;
}
return true;
}
public static float blockStrength(Block block, EntityPlayer player, int metadata)
{
float hardness = block.getHardness(metadata);
if (hardness < 0.0F)
{
return 0.0F;
}
if (!canHarvestBlock(block, player, metadata))
{
return 1.0F / hardness / 100F;
}
else
{
return player.getCurrentPlayerStrVsBlock(block, metadata) / hardness / 30F;
}
}
public static boolean isToolEffective(ItemStack stack, Block block, int metadata)
{
List toolClass = (List)toolClasses.get(stack.itemID);
if (toolClass == null)
{
return false;
}
return toolEffectiveness.contains(Arrays.asList(block.blockID, metadata, (String)toolClass.get(0)));
}
static void initTools()
{
if (toolInit)
{
return;
}
toolInit = true;
MinecraftForge.setToolClass(Item.pickaxeWood, "pickaxe", 0);
MinecraftForge.setToolClass(Item.pickaxeStone, "pickaxe", 1);
MinecraftForge.setToolClass(Item.pickaxeSteel, "pickaxe", 2);
MinecraftForge.setToolClass(Item.pickaxeGold, "pickaxe", 0);
MinecraftForge.setToolClass(Item.pickaxeDiamond, "pickaxe", 3);
MinecraftForge.setToolClass(Item.axeWood, "axe", 0);
MinecraftForge.setToolClass(Item.axeStone, "axe", 1);
MinecraftForge.setToolClass(Item.axeSteel, "axe", 2);
MinecraftForge.setToolClass(Item.axeGold, "axe", 0);
MinecraftForge.setToolClass(Item.axeDiamond, "axe", 3);
MinecraftForge.setToolClass(Item.shovelWood, "shovel", 0);
MinecraftForge.setToolClass(Item.shovelStone, "shovel", 1);
MinecraftForge.setToolClass(Item.shovelSteel, "shovel", 2);
MinecraftForge.setToolClass(Item.shovelGold, "shovel", 0);
MinecraftForge.setToolClass(Item.shovelDiamond, "shovel", 3);
MinecraftForge.setBlockHarvestLevel(Block.obsidian, "pickaxe", 3);
MinecraftForge.setBlockHarvestLevel(Block.oreDiamond, "pickaxe", 2);
MinecraftForge.setBlockHarvestLevel(Block.blockDiamond, "pickaxe", 2);
MinecraftForge.setBlockHarvestLevel(Block.oreGold, "pickaxe", 2);
MinecraftForge.setBlockHarvestLevel(Block.blockGold, "pickaxe", 2);
MinecraftForge.setBlockHarvestLevel(Block.oreIron, "pickaxe", 1);
MinecraftForge.setBlockHarvestLevel(Block.blockSteel, "pickaxe", 1);
MinecraftForge.setBlockHarvestLevel(Block.oreLapis, "pickaxe", 1);
MinecraftForge.setBlockHarvestLevel(Block.blockLapis, "pickaxe", 1);
MinecraftForge.setBlockHarvestLevel(Block.oreRedstone, "pickaxe", 2);
MinecraftForge.setBlockHarvestLevel(Block.oreRedstoneGlowing, "pickaxe", 2);
MinecraftForge.removeBlockEffectiveness(Block.oreRedstone, "pickaxe");
MinecraftForge.removeBlockEffectiveness(Block.obsidian, "pickaxe");
MinecraftForge.removeBlockEffectiveness(Block.oreRedstoneGlowing, "pickaxe");
Block[] pickeff =
{
Block.cobblestone, Block.stairDouble,
Block.stairSingle, Block.stone,
Block.sandStone, Block.cobblestoneMossy,
Block.oreCoal, Block.ice,
Block.netherrack, Block.oreLapis,
Block.blockLapis
};
for (Block block : pickeff)
{
MinecraftForge.setBlockHarvestLevel(block, "pickaxe", 0);
}
Block[] spadeEff =
{
Block.grass, Block.dirt,
Block.sand, Block.gravel,
Block.snow, Block.blockSnow,
Block.blockClay, Block.tilledField,
Block.slowSand, Block.mycelium
};
for (Block block : spadeEff)
{
MinecraftForge.setBlockHarvestLevel(block, "shovel", 0);
}
Block[] axeEff =
{
Block.planks, Block.bookShelf,
Block.wood, Block.chest,
Block.stairDouble, Block.stairSingle,
Block.pumpkin, Block.pumpkinLantern
};
for (Block block : axeEff)
{
MinecraftForge.setBlockHarvestLevel(block, "axe", 0);
}
}
public static HashMap<Class, EntityTrackerInfo> entityTrackerMap = new HashMap<Class, EntityTrackerInfo>();
/**
* Builds the 'Spawn' packet using the Custom Payload packet on the 'Forge' channel.
* Supports entities that have custom spawn data, as well as the generic 'Owner' construct.
*
* @param entity The entity instance to spawn
* @return The spawn packet, or null if we arn't spawning it.
*/
public static Packet getEntitySpawnPacket(Entity entity)
{
EntityTrackerInfo info = MinecraftForge.getEntityTrackerInfo(entity, false);
if (info == null)
{
return null;
}
PacketEntitySpawn pkt = new PacketEntitySpawn(entity, info.Mod, info.ID);
return pkt.getPacket();
}
public static Hashtable<Integer, NetworkMod> networkMods = new Hashtable<Integer, NetworkMod>();
public static Hashtable<BaseMod, IGuiHandler> guiHandlers = new Hashtable<BaseMod, IGuiHandler>();
public static boolean onArrowLoose(ItemStack itemstack, World world, EntityPlayer player, int heldTime)
{
for (IArrowLooseHandler handler : arrowLooseHandlers)
{
if (handler.onArrowLoose(itemstack, world, player, heldTime))
{
return true;
}
}
return false;
}
public static ArrayList<IArrowLooseHandler> arrowLooseHandlers = new ArrayList<IArrowLooseHandler>();
public static ItemStack onArrowNock(ItemStack itemstack, World world, EntityPlayer player)
{
for (IArrowNockHandler handler : arrowNockHandlers)
{
ItemStack ret = handler.onArrowNock(itemstack, world, player);
if (ret != null)
{
return ret;
}
}
return null;
}
public static ArrayList<IArrowNockHandler> arrowNockHandlers = new ArrayList<IArrowNockHandler>();
//This number is incremented every Minecraft version, and never reset
public static final int majorVersion = 3;
//This number is incremented every official release, and reset every Minecraft version
public static final int minorVersion = 2;
//This number is incremented every time a interface changes, and reset every Minecraft version
public static final int revisionVersion = 3;
//This number is incremented every time Jenkins builds Forge, and never reset. Should always be 0 in the repo code.
public static final int buildVersion = 0;
public static int getMajorVersion()
{
return majorVersion;
}
public static int getMinorVersion()
{
return minorVersion;
}
public static int getRevisionVersion()
{
return revisionVersion;
}
public static int getBuildVersion()
{
return buildVersion;
}
static
{
plantGrassList = new ArrayList<ProbableItem>();
plantGrassList.add(new ProbableItem(Block.plantYellow.blockID, 0, 1, 0, 20));
plantGrassList.add(new ProbableItem(Block.plantRed.blockID, 0, 1, 20, 30));
plantGrassWeight = 30;
seedGrassList = new ArrayList<ProbableItem>();
seedGrassList.add(new ProbableItem(Item.seeds.shiftedIndex, 0, 1, 0, 10));
seedGrassWeight = 10;
System.out.printf("MinecraftForge v%d.%d.%d.%d Initialized\n", majorVersion, minorVersion, revisionVersion, buildVersion);
ModLoader.getLogger().info(String.format("MinecraftForge v%d.%d.%d.%d Initialized\n", majorVersion, minorVersion, revisionVersion, buildVersion));
}
static boolean toolInit = false;
static HashMap toolClasses = new HashMap();
static HashMap toolHarvestLevels = new HashMap();
static HashSet toolEffectiveness = new HashSet();
private static PacketHandlerBase forgePacketHandler = null;
public static void setPacketHandler(PacketHandlerBase handler)
{
if (forgePacketHandler != null)
{
throw new RuntimeException("Attempted to set Forge's Internal packet handler after it was already set");
}
forgePacketHandler = handler;
}
public static PacketHandlerBase getPacketHandler()
{
return forgePacketHandler;
}
public static boolean onItemDataPacket(NetworkManager net, Packet131MapData pkt)
{
NetworkMod mod = MinecraftForge.getModByID(pkt.itemID);
if (mod == null)
{
ModLoader.getLogger().log(Level.WARNING, String.format("Received Unknown MapData packet %d:%d", pkt.itemID, pkt.uniqueID));
return false;
}
mod.onPacketData(net, pkt.uniqueID, pkt.itemData);
return true;
}
}
|
forge/forge_common/net/minecraft/src/forge/ForgeHooks.java
|
/**
* This software is provided under the terms of the Minecraft Forge Public
* License v1.0.
*/
package net.minecraft.src.forge;
import net.minecraft.src.BaseMod;
import net.minecraft.src.Block;
import net.minecraft.src.Chunk;
import net.minecraft.src.ChunkCoordIntPair;
import net.minecraft.src.Entity;
import net.minecraft.src.EntityItem;
import net.minecraft.src.EntityLiving;
import net.minecraft.src.EntityMinecart;
import net.minecraft.src.EntityPlayer;
import net.minecraft.src.IInventory;
import net.minecraft.src.ItemStack;
import net.minecraft.src.Item;
import net.minecraft.src.EnumStatus;
import net.minecraft.src.ModLoader;
import net.minecraft.src.NBTTagCompound;
import net.minecraft.src.NetworkManager;
import net.minecraft.src.Packet;
import net.minecraft.src.Packet131MapData;
import net.minecraft.src.Packet1Login;
import net.minecraft.src.Packet250CustomPayload;
import net.minecraft.src.World;
import net.minecraft.src.forge.packets.PacketEntitySpawn;
import net.minecraft.src.forge.packets.PacketHandlerBase;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.logging.Level;
public class ForgeHooks
{
// List Handling Hooks
// ------------------------------------------------------------
public static void onTakenFromCrafting(EntityPlayer player, ItemStack stack, IInventory craftMatrix)
{
for (ICraftingHandler handler : craftingHandlers)
{
handler.onTakenFromCrafting(player, stack, craftMatrix);
}
}
static LinkedList<ICraftingHandler> craftingHandlers = new LinkedList<ICraftingHandler>();
public static void onDestroyCurrentItem(EntityPlayer player, ItemStack orig)
{
for (IDestroyToolHandler handler : destroyToolHandlers)
{
handler.onDestroyCurrentItem(player, orig);
}
}
static LinkedList<IDestroyToolHandler> destroyToolHandlers = new LinkedList<IDestroyToolHandler>();
public static boolean onUseBonemeal(World world, int blockID, int x, int y, int z)
{
for (IBonemealHandler handler : bonemealHandlers)
{
if (handler.onUseBonemeal(world, blockID, x, y, z))
{
return true;
}
}
return false;
}
static LinkedList<IBonemealHandler> bonemealHandlers = new LinkedList<IBonemealHandler>();
public static boolean onUseHoe(ItemStack hoe, EntityPlayer player, World world, int x, int y, int z)
{
for (IHoeHandler handler : hoeHandlers)
{
if (handler.onUseHoe(hoe, player, world, x, y, z))
{
return true;
}
}
return false;
}
static LinkedList<IHoeHandler> hoeHandlers = new LinkedList<IHoeHandler>();
public static EnumStatus sleepInBedAt(EntityPlayer player, int x, int y, int z)
{
for (ISleepHandler handler : sleepHandlers)
{
EnumStatus status = handler.sleepInBedAt(player, x, y, z);
if (status != null)
{
return status;
}
}
return null;
}
static LinkedList<ISleepHandler> sleepHandlers = new LinkedList<ISleepHandler>();
public static void onMinecartUpdate(EntityMinecart minecart, int x, int y, int z)
{
for (IMinecartHandler handler : minecartHandlers)
{
handler.onMinecartUpdate(minecart, x, y, z);
}
}
public static void onMinecartEntityCollision(EntityMinecart minecart, Entity entity)
{
for (IMinecartHandler handler : minecartHandlers)
{
handler.onMinecartEntityCollision(minecart, entity);
}
}
public static boolean onMinecartInteract(EntityMinecart minecart, EntityPlayer player)
{
boolean canceled = true;
for (IMinecartHandler handler : minecartHandlers)
{
boolean tmp = handler.onMinecartInteract(minecart, player, canceled);
canceled = canceled && tmp;
}
return canceled;
}
static LinkedList<IMinecartHandler> minecartHandlers = new LinkedList<IMinecartHandler>();
public static void onConnect(NetworkManager network)
{
for (IConnectionHandler handler : connectionHandlers)
{
handler.onConnect(network);
}
}
public static void onLogin(NetworkManager network, Packet1Login login)
{
for (IConnectionHandler handler : connectionHandlers)
{
handler.onLogin(network, login);
}
}
public static void onDisconnect(NetworkManager network, String message, Object[] args)
{
for (IConnectionHandler handler : connectionHandlers)
{
handler.onDisconnect(network, message, args);
}
}
static LinkedList<IConnectionHandler> connectionHandlers = new LinkedList<IConnectionHandler>();
public static boolean onItemPickup(EntityPlayer player, EntityItem item)
{
boolean cont = true;
for (IPickupHandler handler : pickupHandlers)
{
cont = cont && handler.onItemPickup(player, item);
if (!cont || item.item.stackSize <= 0)
{
return false;
}
}
return cont;
}
static LinkedList<IPickupHandler> pickupHandlers = new LinkedList<IPickupHandler>();
public static void addActiveChunks(World world, Set<ChunkCoordIntPair> chunkList)
{
for(IChunkLoadHandler loader : chunkLoadHandlers)
{
loader.addActiveChunks(world, chunkList);
}
}
public static boolean canUnloadChunk(Chunk chunk)
{
for(IChunkLoadHandler loader : chunkLoadHandlers)
{
if(!loader.canUnloadChunk(chunk))
{
return false;
}
}
return true;
}
public static boolean canUpdateEntity(Entity entity)
{
for(IChunkLoadHandler loader : chunkLoadHandlers)
{
if(loader.canUpdateEntity(entity))
{
return true;
}
}
return false;
}
static LinkedList<IChunkLoadHandler> chunkLoadHandlers = new LinkedList<IChunkLoadHandler>();
public static boolean onEntityInteract(EntityPlayer player, Entity entity, boolean isAttack)
{
for (IEntityInteractHandler handler : entityInteractHandlers)
{
if (!handler.onEntityInteract(player, entity, isAttack))
{
return false;
}
}
return true;
}
static LinkedList<IEntityInteractHandler> entityInteractHandlers = new LinkedList<IEntityInteractHandler>();
public static String onServerChat(EntityPlayer player, String message)
{
for (IChatHandler handler : chatHandlers)
{
message = handler.onServerChat(player, message);
if (message == null)
{
return null;
}
}
return message;
}
public static boolean onChatCommand(EntityPlayer player, boolean isOp, String command)
{
for (IChatHandler handler : chatHandlers)
{
if (handler.onChatCommand(player, isOp, command))
{
return true;
}
}
return false;
}
public static boolean onServerCommand(Object listener, String username, String command)
{
for (IChatHandler handler : chatHandlers)
{
if (handler.onServerCommand(listener, username, command))
{
return true;
}
}
return false;
}
public static String onServerCommandSay(Object listener, String username, String message)
{
for (IChatHandler handler : chatHandlers)
{
message = handler.onServerCommandSay(listener, username, message);
if (message == null)
{
return null;
}
}
return message;
}
public static String onClientChatRecv(String message)
{
for (IChatHandler handler : chatHandlers)
{
message = handler.onClientChatRecv(message);
if (message == null)
{
return null;
}
}
return message;
}
static LinkedList<IChatHandler> chatHandlers = new LinkedList<IChatHandler>();
public static void onWorldLoad(World world)
{
for (ISaveEventHandler handler : saveHandlers)
{
handler.onWorldLoad(world);
}
}
public static void onWorldSave(World world)
{
for (ISaveEventHandler handler : saveHandlers)
{
handler.onWorldSave(world);
}
}
public static void onChunkLoad(World world, Chunk chunk)
{
for (ISaveEventHandler handler : saveHandlers)
{
handler.onChunkLoad(world, chunk);
}
}
public static void onChunkUnload(World world, Chunk chunk)
{
for (ISaveEventHandler handler : saveHandlers)
{
handler.onChunkUnload(world, chunk);
}
}
public static void onChunkLoadData(World world, Chunk chunk, NBTTagCompound data)
{
for (ISaveEventHandler handler : saveHandlers)
{
handler.onChunkLoadData(world, chunk, data);
}
}
public static void onChunkSaveData(World world, Chunk chunk, NBTTagCompound data)
{
for (ISaveEventHandler handler : saveHandlers)
{
handler.onChunkSaveData(world, chunk, data);
}
}
static LinkedList<ISaveEventHandler> saveHandlers = new LinkedList<ISaveEventHandler>();
public static int getItemBurnTime(ItemStack stack)
{
for (IFuelHandler handler : fuelHandlers)
{
int ret = handler.getItemBurnTime(stack);
if (ret > 0)
{
return ret;
}
}
return 0;
}
static LinkedList<IFuelHandler> fuelHandlers = new LinkedList<IFuelHandler>();
public static boolean onEntitySpawnSpecial(EntityLiving entity, World world, float x, float y, float z)
{
for (ISpecialMobSpawnHandler handler : specialMobSpawnHandlers)
{
if (handler.onSpecialEntitySpawn(entity, world, x, y, z))
{
return true;
}
}
return false;
}
static LinkedList<ISpecialMobSpawnHandler> specialMobSpawnHandlers = new LinkedList<ISpecialMobSpawnHandler>();
// Plant Management
// ------------------------------------------------------------
static class ProbableItem
{
public ProbableItem(int item, int metadata, int quantity, int start, int end)
{
WeightStart = start;
WeightEnd = end;
ItemID = item;
Metadata = metadata;
Quantity = quantity;
}
int WeightStart, WeightEnd;
int ItemID, Metadata;
int Quantity;
}
static ProbableItem getRandomItem(List<ProbableItem> list, int prop)
{
int n = Collections.binarySearch(list, prop, new Comparator()
{
public int compare(Object o1, Object o2)
{
ProbableItem pi = (ProbableItem)o1;
Integer i1 = (Integer)o2;
if (i1 < pi.WeightStart)
{
return 1;
}
if (i1 >= pi.WeightEnd)
{
return -1;
}
return 0;
}
});
if (n < 0)
{
return null;
}
return list.get(n);
}
static List<ProbableItem> plantGrassList;
static int plantGrassWeight;
static List<ProbableItem> seedGrassList;
static int seedGrassWeight;
public static void plantGrassPlant(World world, int x, int y, int z)
{
int index = world.rand.nextInt(plantGrassWeight);
ProbableItem item = getRandomItem(plantGrassList, index);
if (item == null)
{
return;
}
world.setBlockAndMetadataWithNotify(x, y, z, item.ItemID, item.Metadata);
}
public static void addPlantGrass(int item, int metadata, int probability)
{
plantGrassList.add(new ProbableItem(item, metadata, 1, plantGrassWeight, plantGrassWeight + probability));
plantGrassWeight += probability;
}
public static ItemStack getGrassSeed(World world)
{
int index = world.rand.nextInt(seedGrassWeight);
ProbableItem item = getRandomItem(seedGrassList, index);
if (item == null)
{
return null;
}
return new ItemStack(item.ItemID, item.Quantity, item.Metadata);
}
public static void addGrassSeed(int item, int metadata, int quantity, int probability)
{
seedGrassList.add(new ProbableItem(item, metadata, quantity, seedGrassWeight, seedGrassWeight + probability));
seedGrassWeight += probability;
}
// Tool Path
// ------------------------------------------------------------
public static boolean canHarvestBlock(Block block, EntityPlayer player, int metadata)
{
if (block.blockMaterial.isHarvestable())
{
return true;
}
ItemStack stack = player.inventory.getCurrentItem();
if (stack == null)
{
return player.canHarvestBlock(block);
}
List info = (List)toolClasses.get(stack.itemID);
if (info == null)
{
return player.canHarvestBlock(block);
}
Object[] tmp = info.toArray();
String toolClass = (String)tmp[0];
int harvestLevel = (Integer)tmp[1];
Integer blockHarvestLevel = (Integer)toolHarvestLevels.get(Arrays.asList(block.blockID, metadata, toolClass));
if (blockHarvestLevel == null)
{
return player.canHarvestBlock(block);
}
if (blockHarvestLevel > harvestLevel)
{
return false;
}
return true;
}
public static float blockStrength(Block block, EntityPlayer player, int metadata)
{
float hardness = block.getHardness(metadata);
if (hardness < 0.0F)
{
return 0.0F;
}
if (!canHarvestBlock(block, player, metadata))
{
return 1.0F / hardness / 100F;
}
else
{
return player.getCurrentPlayerStrVsBlock(block, metadata) / hardness / 30F;
}
}
public static boolean isToolEffective(ItemStack stack, Block block, int metadata)
{
List toolClass = (List)toolClasses.get(stack.itemID);
if (toolClass == null)
{
return false;
}
return toolEffectiveness.contains(Arrays.asList(block.blockID, metadata, (String)toolClass.get(0)));
}
static void initTools()
{
if (toolInit)
{
return;
}
toolInit = true;
MinecraftForge.setToolClass(Item.pickaxeWood, "pickaxe", 0);
MinecraftForge.setToolClass(Item.pickaxeStone, "pickaxe", 1);
MinecraftForge.setToolClass(Item.pickaxeSteel, "pickaxe", 2);
MinecraftForge.setToolClass(Item.pickaxeGold, "pickaxe", 0);
MinecraftForge.setToolClass(Item.pickaxeDiamond, "pickaxe", 3);
MinecraftForge.setToolClass(Item.axeWood, "axe", 0);
MinecraftForge.setToolClass(Item.axeStone, "axe", 1);
MinecraftForge.setToolClass(Item.axeSteel, "axe", 2);
MinecraftForge.setToolClass(Item.axeGold, "axe", 0);
MinecraftForge.setToolClass(Item.axeDiamond, "axe", 3);
MinecraftForge.setToolClass(Item.shovelWood, "shovel", 0);
MinecraftForge.setToolClass(Item.shovelStone, "shovel", 1);
MinecraftForge.setToolClass(Item.shovelSteel, "shovel", 2);
MinecraftForge.setToolClass(Item.shovelGold, "shovel", 0);
MinecraftForge.setToolClass(Item.shovelDiamond, "shovel", 3);
MinecraftForge.setBlockHarvestLevel(Block.obsidian, "pickaxe", 3);
MinecraftForge.setBlockHarvestLevel(Block.oreDiamond, "pickaxe", 2);
MinecraftForge.setBlockHarvestLevel(Block.blockDiamond, "pickaxe", 2);
MinecraftForge.setBlockHarvestLevel(Block.oreGold, "pickaxe", 2);
MinecraftForge.setBlockHarvestLevel(Block.blockGold, "pickaxe", 2);
MinecraftForge.setBlockHarvestLevel(Block.oreIron, "pickaxe", 1);
MinecraftForge.setBlockHarvestLevel(Block.blockSteel, "pickaxe", 1);
MinecraftForge.setBlockHarvestLevel(Block.oreLapis, "pickaxe", 1);
MinecraftForge.setBlockHarvestLevel(Block.blockLapis, "pickaxe", 1);
MinecraftForge.setBlockHarvestLevel(Block.oreRedstone, "pickaxe", 2);
MinecraftForge.setBlockHarvestLevel(Block.oreRedstoneGlowing, "pickaxe", 2);
MinecraftForge.removeBlockEffectiveness(Block.oreRedstone, "pickaxe");
MinecraftForge.removeBlockEffectiveness(Block.obsidian, "pickaxe");
MinecraftForge.removeBlockEffectiveness(Block.oreRedstoneGlowing, "pickaxe");
Block[] pickeff =
{
Block.cobblestone, Block.stairDouble,
Block.stairSingle, Block.stone,
Block.sandStone, Block.cobblestoneMossy,
Block.oreCoal, Block.ice,
Block.netherrack, Block.oreLapis,
Block.blockLapis
};
for (Block block : pickeff)
{
MinecraftForge.setBlockHarvestLevel(block, "pickaxe", 0);
}
Block[] spadeEff =
{
Block.grass, Block.dirt,
Block.sand, Block.gravel,
Block.snow, Block.blockSnow,
Block.blockClay, Block.tilledField,
Block.slowSand, Block.mycelium
};
for (Block block : spadeEff)
{
MinecraftForge.setBlockHarvestLevel(block, "shovel", 0);
}
Block[] axeEff =
{
Block.planks, Block.bookShelf,
Block.wood, Block.chest,
Block.stairDouble, Block.stairSingle,
Block.pumpkin, Block.pumpkinLantern
};
for (Block block : axeEff)
{
MinecraftForge.setBlockHarvestLevel(block, "axe", 0);
}
}
public static HashMap<Class, EntityTrackerInfo> entityTrackerMap = new HashMap<Class, EntityTrackerInfo>();
/**
* Builds the 'Spawn' packet using the Custom Payload packet on the 'Forge' channel.
* Supports entities that have custom spawn data, as well as the generic 'Owner' construct.
*
* @param entity The entity instance to spawn
* @return The spawn packet, or null if we arn't spawning it.
*/
public static Packet getEntitySpawnPacket(Entity entity)
{
EntityTrackerInfo info = MinecraftForge.getEntityTrackerInfo(entity, false);
if (info == null)
{
return null;
}
PacketEntitySpawn pkt = new PacketEntitySpawn(entity, info.Mod, info.ID);
return pkt.getPacket();
}
public static Hashtable<Integer, NetworkMod> networkMods = new Hashtable<Integer, NetworkMod>();
public static Hashtable<BaseMod, IGuiHandler> guiHandlers = new Hashtable<BaseMod, IGuiHandler>();
public static boolean onArrowLoose(ItemStack itemstack, World world, EntityPlayer player, int heldTime)
{
for (IArrowLooseHandler handler : arrowLooseHandlers)
{
if (handler.onArrowLoose(itemstack, world, player, heldTime))
{
return true;
}
}
return false;
}
public static ArrayList<IArrowLooseHandler> arrowLooseHandlers = new ArrayList<IArrowLooseHandler>();
public static ItemStack onArrowNock(ItemStack itemstack, World world, EntityPlayer player)
{
for (IArrowNockHandler handler : arrowNockHandlers)
{
ItemStack ret = handler.onArrowNock(itemstack, world, player);
if (ret != null)
{
return ret;
}
}
return null;
}
public static ArrayList<IArrowNockHandler> arrowNockHandlers = new ArrayList<IArrowNockHandler>();
//This number is incremented every Minecraft version, and never reset
public static final int majorVersion = 3;
//This number is incremented every official release, and reset every Minecraft version
public static final int minorVersion = 1;
//This number is incremented every time a interface changes, and reset every Minecraft version
public static final int revisionVersion = 3;
//This number is incremented every time Jenkins builds Forge, and never reset. Should always be 0 in the repo code.
public static final int buildVersion = 0;
public static int getMajorVersion()
{
return majorVersion;
}
public static int getMinorVersion()
{
return minorVersion;
}
public static int getRevisionVersion()
{
return revisionVersion;
}
public static int getBuildVersion()
{
return buildVersion;
}
static
{
plantGrassList = new ArrayList<ProbableItem>();
plantGrassList.add(new ProbableItem(Block.plantYellow.blockID, 0, 1, 0, 20));
plantGrassList.add(new ProbableItem(Block.plantRed.blockID, 0, 1, 20, 30));
plantGrassWeight = 30;
seedGrassList = new ArrayList<ProbableItem>();
seedGrassList.add(new ProbableItem(Item.seeds.shiftedIndex, 0, 1, 0, 10));
seedGrassWeight = 10;
System.out.printf("MinecraftForge v%d.%d.%d.%d Initialized\n", majorVersion, minorVersion, revisionVersion, buildVersion);
ModLoader.getLogger().info(String.format("MinecraftForge v%d.%d.%d.%d Initialized\n", majorVersion, minorVersion, revisionVersion, buildVersion));
}
static boolean toolInit = false;
static HashMap toolClasses = new HashMap();
static HashMap toolHarvestLevels = new HashMap();
static HashSet toolEffectiveness = new HashSet();
private static PacketHandlerBase forgePacketHandler = null;
public static void setPacketHandler(PacketHandlerBase handler)
{
if (forgePacketHandler != null)
{
throw new RuntimeException("Attempted to set Forge's Internal packet handler after it was already set");
}
forgePacketHandler = handler;
}
public static PacketHandlerBase getPacketHandler()
{
return forgePacketHandler;
}
public static boolean onItemDataPacket(NetworkManager net, Packet131MapData pkt)
{
NetworkMod mod = MinecraftForge.getModByID(pkt.itemID);
if (mod == null)
{
ModLoader.getLogger().log(Level.WARNING, String.format("Received Unknown MapData packet %d:%d", pkt.itemID, pkt.uniqueID));
return false;
}
mod.onPacketData(net, pkt.uniqueID, pkt.itemData);
return true;
}
}
|
Bump version number for official release.
|
forge/forge_common/net/minecraft/src/forge/ForgeHooks.java
|
Bump version number for official release.
|
<ide><path>orge/forge_common/net/minecraft/src/forge/ForgeHooks.java
<ide> //This number is incremented every Minecraft version, and never reset
<ide> public static final int majorVersion = 3;
<ide> //This number is incremented every official release, and reset every Minecraft version
<del> public static final int minorVersion = 1;
<add> public static final int minorVersion = 2;
<ide> //This number is incremented every time a interface changes, and reset every Minecraft version
<ide> public static final int revisionVersion = 3;
<ide> //This number is incremented every time Jenkins builds Forge, and never reset. Should always be 0 in the repo code.
|
|
Java
|
mit
|
983eb2d40211ba89c8c9f3d23d81f74309d84889
| 0 |
xtianus/yadaframework,xtianus/yadaframework,xtianus/yadaframework,xtianus/yadaframework
|
package net.yadaframework.components;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import net.yadaframework.core.YadaConfiguration;
import net.yadaframework.persistence.entity.YadaAttachedFile;
import net.yadaframework.persistence.entity.YadaManagedFile;
import net.yadaframework.persistence.repository.YadaAttachedFileRepository;
import net.yadaframework.persistence.repository.YadaFileManagerDao;
import net.yadaframework.raw.YadaIntDimension;
/**
* The File Manager handles uploaded files. They are kept in a specific folder where they can be
* chosen to be attached to entities.
*
*/
// Not in YadaWebCMS because used by YadaSession and YadaUtil
@Service
public class YadaFileManager {
private final transient Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired private YadaAttachedFileRepository yadaAttachedFileRepository;
@Autowired private YadaConfiguration config;
@Autowired private YadaUtil yadaUtil;
@Autowired private YadaFileManagerDao yadaFileManagerDao;
protected String COUNTER_SEPARATOR="_";
// Image to return when no image is available
public final static String NOIMAGE_DATA="data:image/jpeg;base64,/9j/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP/sABFEdWNreQABAAQAAAA6AAD/4QMxaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI/PiA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJBZG9iZSBYTVAgQ29yZSA1LjYtYzEzOCA3OS4xNTk4MjQsIDIwMTYvMDkvMTQtMDE6MDk6MDEgICAgICAgICI+IDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+IDxyZGY6RGVzY3JpcHRpb24gcmRmOmFib3V0PSIiIHhtbG5zOnhtcD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLyIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bXA6Q3JlYXRvclRvb2w9IkFkb2JlIFBob3Rvc2hvcCBDQyAyMDE3IChNYWNpbnRvc2gpIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOkM0MzIwODI4RDk5ODExRTc5NkJEQUU4MkU3NzAwMUNEIiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOkM0MzIwODI5RDk5ODExRTc5NkJEQUU4MkU3NzAwMUNEIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6RDQyMjJGN0ZEOTBBMTFFNzk2QkRBRTgyRTc3MDAxQ0QiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6RDQyMjJGODBEOTBBMTFFNzk2QkRBRTgyRTc3MDAxQ0QiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz7/7gAhQWRvYmUAZMAAAAABAwAQAwMGCQAAJ/IAADkCAABIi//bAIQABwUFBQUFBwUFBwoGBQYKCwgHBwgLDQsLCwsLDREMDAwMDAwRDQ8QERAPDRQUFhYUFB0dHR0dICAgICAgICAgIAEHCAgNDA0ZEREZHBYSFhwgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg/8IAEQgDwAPAAwERAAIRAQMRAf/EANQAAQADAQEBAQEAAAAAAAAAAAAFBgcEAwIBCAEBAAAAAAAAAAAAAAAAAAAAABAAAQQBAwQCAgICAgMAAAAAAwECBAUAEzQVECAzFBESYDJQITEiMCWQwNARAAECAgUICAQFBAIDAQAAAAECAwARECExcRIgQbHRIjJyM1GBkcHhQqITYaGSBGBSgiNzMFCyFGJDkMDw8RIBAAAAAAAAAAAAAAAAAAAA0BMBAAEBBgYCAwEBAAMBAAAAAREAEPAhMUFRIGGBkaGxccEwYNFQ4ZDA0PH/2gAMAwEAAhEDEQAAAP6RAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPEhCZOgAEQepJAAiiMPk7yZPoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEcZwTJfwAUI7S4A8CiEaS59kUfZeyRAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAI4zg+i6FiAKEdpcAZ6fBfToB8lJIc0o9gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAARxnBbCsGknUChHaXAijPDSztAB8GZFmLUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACOM4NTKAepfwUI7S4FUK8aYAACkHKaCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACOM4NUOYzcuZYihHaXAphHGiAAAqBDGkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAjjODVD0KuVQ0kph2lwKiQhpIAAKUcJoYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAI4zg1Q9D8M8PU+jtLgQxQTTTqAB+GaE8W4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEcZwaoegOIzc/SyFwPwzk9y+n2AVArRpR1AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAjjODVD0AKuU8tBcAchQTyJw+yIOMvJMgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHMVwtR9AH4VckSYAPkgiLPk7yfPcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAz4nixkcUM6jQwACiEaaAdoBymeFhLYAAfhWyunACQLKWEAzg8QAAX0kAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADNSxFoIszs+jRiQAOYzM+DSTvAKmQB4Gnn2ACikQWwlgQxUy3FmBlxYSaAAJE9QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADNSxFoIszsmiQLcAVkhyFNJO8H4ZmW0qBbiwgEGUU0UkQAVoqhp5+mXFuLGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZqWItBFmdl4KoaWAZ2WUoxpJ3ghyiGnlUIk0UAoZ+F9AAPg8joBlxbixgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGaliLQRZnZqRmJoZInKZyaQZeaSd4KKehdjiM0NGJIGZlhLWAAAAZcdp2gA6S3AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAzUsRaCLM7NWKOdhbirnGW0y40k7zwMwLaSYKSSxdgZkWMtQBlR8AGjEkZcSZJAA9yygAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAzUsRaCLM7NWIUp5phnJcDvMuNJO8rBUToAPg8jTz2M+OkvAByA8TODRiSMuLcWMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAzUsRaCLM7NWPwy8u5TDTjxMuNJO8zYnC2gHmZgWws5XSmmlHUADxMtNGJIy4txYwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADNSxFoIszs1Y+ijkQTxcTwMuNJPMzo0s7QAUoiTSz8M/OQuBMH6RZViKNIO0y4tBPAAHseoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABmpYi0EWZ2asfRClBNFJM8DLjSSsHCaIAARhnRoBMHyVUrhzA9ScLWdgMuPAAAFyLMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAc5+HQfoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABzEOTR7ghj7JYAA8CFJ09AQJ1EoADwIUnj7Is+CXAAABzEOTR7gAgjzAPQkzqAIY9iTAABAnwAACaPcAAAAAAAAAAAAAAAAAAAAAAAAApxWS1lsBVCtGnn6ACqleNLBHmcHUaYfoBGGdGonuUg8S+gAAApxWS1lsABmR+nUfh4nEXQsQM9JAuQAAMuPY6QAC6HcAAAAAAAAAAAAAAAAAAAAAAAAD5MwJ4gzTT6OUzIvxMgAzQsZaAU08CGLwTQBGGdGonuUg8S+gAAHyZgTxBmmn0AZkWcswBWCpmon0Z6SBcgAAZcW4sYAAAAAAAAAAAAAAAAAAAAAAAAAAAIIphphmJdSdBQT2LwARZnppx0HwZgXchjlL8ARhnRqJ7lIPEvoAABBFMNMMxLqToBmRZyzAEWZ2amepnpIFyAABlxbixgAAAAAAAAAAAAAAAAAAAAAAAAAAAoB3FxKWcJoQIMo5qB6ApR4l7BAlNNPI0zs0w6wRhnRqJ7lIPEvoAABQDuLiUs4TQgDMiwlhB4lSPovgM9JAuQAAMuLQTwAPo6QAAAAAAAAAAAAAAAAAAAAAAAAcpmRpB3kaZyaUdx8mYlwLAfBmBeiYBnxIlwBmxNFvBGGdGonuUg8S+gAA5TMjSDvI0zk0o7gZkcgAPsvZNAz0kC5AAAy48AADuNKAAAAAAAAAAAAAAAAAAAAAAAABUyqEqARRZS5AqBHl/IEqBph+nIZmdx7g4j5NPPojDOjUT3KQeJfQAAVMqhKgEUWUuQMyLOWYHmQRSTQiVM9JAuQAAMuLcWMAAAAAAAAAAAAAAAAAAAAAAAAAAH4ZmS5KgEWQJp56HEZsacUglC1gqRBFpAPkphdiwEYZ0aie5SDxL6AAfhmZLkqARZAmnnoZkWcswAM3Jkt5npIFyAABlxbixgAAAAAAAAAAAAAAAAAAAAAAAAAAhygmnHQAeBmJcixgzwlirmmHSfhmRZi0AAohzGiEYZ0aie5SDxL6AAQ5QTTjoAPAzEuRYzMizlmAPAzMtpZjPSQLkAADLi3FjAAAAAAAAAAAAAAAAAAAAAAAAAABRD4L8AAUU4TSAV8pRMF9BClCNPOgAEMUA0c+TOjUT3KQRBLgAmiBPgvwABRThNIMyOg7gfBFHsaIepnpzkmACwksZcdp2gAE+TAAAAAAAAAAAAAAAAAAAAAAAAKqS5JgAEeQZZz1PgqxNEkCFOUsgAB+FVJU7SuFpPshCOAAJUjCXJMAAjyDLOV48QD6O4mT7BXjkAAJokirnmAACZJMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//aAAgBAgABBQH/AOwgf//aAAgBAwABBQH/AOwgf//aAAgBAQABBQH/ANIDMVoR81FwBxyB9kiyBGJFnClr2GsogcddsxLtMFbRCY1zXJ+TWGzytl+sXstt5SeToYwwDl2BpSsY8jmVMx2Op5aYWOYCx5Rozokwctn5LYbPFarVqpeqzrbbyk8nSwlrJNChvlvCAUdnRzWvbY1/r4Az45AlaYX5JYbPLOJ9hCI4JI52yRdLbeUnkyyNoxMiASPH7Hta9pxKA1Kb+vySw2eMRFHPiLFNWy/WL0tt5SeTLt2RGaknuuWfWTVv+s38ksNnjP0lxmygva5jqqXqsy23lJ5MuvNW73uu/wBoO8/JLDZ4z9Mton2QRHBJHO2SK23lJ5Mu2/7QXfSX3XTvk9a37TfySw2eM/TFRFSfEWKatl+sW23lJ5MtA6sRF+FjGSQHsVURJRvYkUof9vySw2eM/TpLjNlBe1zHPe4mUnkz/OTYqxTQJqxHsewjetlYI9GMcR8YCRw/klhs8Z+nW2ifZMpPJ0kxxyRyYhorgyTR1ZdFTFu34efJkYMRDOgQGxU/JZAtcPB41PhvVURUfSIroUD03dXNa5DVEcmOpTYlLIwVKJMEEQW/+SuXJkNlU5SEZk9zmRPalZGmnYftnzDLK9qVkNznResk2gD25WVMt7ydqqiJJuGMwk+WXFc52I5zcFPliyLbDMvU0qShfalZ7UrPalZ7UrPalZ7UrILnPifhs3d0n6ZZbLHIrVgm1ovWQXQAiOe7IOz63R8BHUzAkUJWOR7eyxnqdwQkO8FMJqNgxG46DEdkinYqPY4bqmYpE6H81ZDjyA8XBzi4OcXBzi4OcXBwY2CZ+Gzd3SfpllsstA6Z6U399bk3wOuD91yDs+n+Mkm1z1IfrFkC0D05/uDrayNGOiK5YUVsUXZcRkcMBFCb/PQ/mpdv+Jzd3SfpllsstA6kOIbQk9bE2tLhB0q7IOz6Wh9GKNikeNiDZdB+HQD6EnrbE+8upFqSu17GkaMAQ9T+al2/4nN3dJ+mWWyxWIQT2KN8A2tFySXQAEanMZESPkHZ9LY+pJpw/c+TA+xHyAf2I3SWv2lUjf8AiP5os80RnNSs5qVnNSs5qVke1kFP+HTd3Sfpllssb+tuHTk0pv8AbLo3wymD9jH8OQdnhioETnK50CXCjR+Tg5ycHJeksinP9D9JSfEmkX/Xq/8AbrX7LD+aFXe4Pg84PODzg8DUaJfw6bu6T9Mstljf1tg6kWIbQkZYG1pVaHRiH8OQdnlyf4Y1jnr6snPVk56snHRzsRj1G8REMLLQenMpyfST19SLnqRcLFjIPK/ZYfzUu3/E5u7pP0yy2WN/V7Ue0jFEQcv/AKyOJTn/AMYfw5B2eTT+xJpQ9hGIRhGKIlMf5ZlxH1BDe4b48hkkXYXxZX7LD+al2/4nN3dJ+mWWyxv65cB+khDPQFMH5Jh/DkHZ2B9CLkQOhH7LgH0NEP68jFRFSfBdFfGklivBaxi40g3457G4aziCyVYmk4xjiOiDcGNh/NUGCMHtRc9qLntRc9qLntRcYQZPw6bu6T9Mstljf1y1DqRcrg6MTD+HIOzuD/c1cHWldtgDXi5WH1ouOa17ZNPhY5w9WDIRQVByZHihjJ0P5u6k8X5S4AHYkaOmIiJ/4ppB2Rhc1FwJmHF0PZgjlj2IJJO0xmAFzUXBv1GdH28Vjos8Mt/YYrQC5qLjXI9uSbAMQkeyBJJ/wSDsjC5qLgTMOLsJbRhk5qLnNRc5qLjbiIuCkgP2HswRyxZwpbu51vGY7mouc1Fzmouc1Fzmouc1FwJWnF/J3J/l/wAL8Ux+t0DAFUJkVFTsujf1ED7EjpOP68ZEVcim9c6L89ljssB4cut1U7z/AILk/wAv+F+KY/bK3QYkiQnGTs4ydj4MtmIqtWtnqfrZ76k8vcfzBiSJDeMnZxk7OMnZxk7OMnZDG8Ub+Sc5GtMVTFfE/wCqjlUBkVHJkkKHAqKi1ZtWL2TDa8imB8N6XJ/sSpChTFGoi1Z9aN1sdlgPDl1uqned7nI1piqYr4n/AFUcqgMio5OsrdUni628VqjERwiIqOTLPfUnl7j+al2/8xbH04wBKYyjaoyjURKk+rH6WgNKVUG+kjrYm0IrUVzgCQAcc5GNMRTFqg6UW5D9TVZ9GT1sdlgPDl1uqned9sfTjAEpjKNqjKNREqT6sfrK3VJ4utkqJCwbfqPLPfUnl7j+al2/8xaH1pVMH5flyH6mrT6ErpbA1YzHqN43oRnS4N9jVINWT0tz6ccAlMZERqWAdeL/AIyKb2AdLHZYDw5dbqp3nfaH1pVMH5flyH6mrT6ErrK3VQYQx+1Fz24uPsIbEnz1lrWRFOXpZ76k8vcfzVBgjB7UXPai57UXPai4kmO5f5KSbQAv95BDoRssA68XIZ/Yj4qI5DiUBqg33j49yMaUilJWA0YvSzPrSqYPy/pND68mmP8ADuljssB4cut1U7zukm0AL/eQQ6EbLAOvFyGf2I/SVuuxio10KfGMnSz31J5e4/m7YW7/AJK6PiL8Lyc7OTnZyc7pTH+pOlyD4dVm0pWW5tOPFD7B/wDHSUb14+CmyQM5OdnJzsNILIcEqhK1yPbljssB4cut1U7zuuj4i/C8nOzk52cnO6Ux/qTpK3VL4ujhjdkyrERv9tWvkrJBlnvqTy9x/NS7f+WX+skm1zwK5kkXCxs4WNnCxsn1rIwREcIg3tIzJgfYjoqtUBUMG0NqyqUH9dLo/wDcOP7J+FjZwsbOFjYtLH+HNVrqg+oDLHZYDw5dbqp3nav9ZJNrngVzJIuFjZwsbOFjZPrWRgiI4RBvaRmSt1SeLsnNRsukVfvlnvqTy9x/NS7f+WtD6MVEVygEgA9TDQwnNVjqc/3D0sgaMqtlacT/AGe6OFAAxVREkmU56YPwzstgaUmvPoSssdlgPDl1uqnedtofRioiuUAkAHqYaGE5qsdTn+4clbqk8XUxmAGUilJSiVB5Z76k8vcfzUu3/lrY+pJqw6srttgacmCf15PS3B9wI5USqBqyulofSioiqscSAD2WgNWLkE/sRrHZYDw5dbqPIfGJzUrOalZzUrOalZXTSy1tj6kmrDqyu22BpyYJ/Xk5K3UWcWI3mpWczKxbiWuGOY6xYhZTxjaJmWe+iyyRHc1KzmpWc1KzmpWV8oksWH80WeaIzmpWc1KzmpWc1KzmpWV0sktn8g6lVzoUJIbe2ZESWPg8Exwx49iEZweQoaQ2dJsBZjwVCBN2qiKi0ifMKE6HkgPsB4PGN+jMm13tl4PODzg84PODyFA9NXUqudChJDb2zIiSx8HgmOGMtPql4PODzg8Skbg6mIzGtaxOkqq9k/B5wecHnB5weQonpjx9N938HnB5wecHnB5weQofpt/9Hn//2gAIAQICBj8BYQP/2gAIAQMCBj8BYQP/2gAIAQEBBj8B/wDSA1OqmUprMo3XOwa4Dre6em0X5PtLSoqt2QNcKDYUMNZxS7icmWPGroRX4RstE3mWuK2ZXK8Ikols/wDId4jEk4kmwj8Tu3UYVn9lypXwPTknhEO3CkuOGSRBG4zmQO+MLaSpXQIrARxHVOKsCrjrAiTqCnR2xiaVVnTmMTTsrG8j8TO3UYVCRGaP9dZ/cb3finwyDwiHbhTsn9lFSNcS3W07yu4RgaThHzN9JSsYkm0GPeZ5JtH5fCA6i0fP4Ql1G6oT/Ert1CfumxtJA9y7phLiKlJrEJdRntHQeik8Ih24UKlvL2B12/KhDfmtVebckoUJpUJEQto+Qy1Qtg5ttOg/iV26gA1giJDlLrQe7qjCs/suVK+B6aTwiHbhQ0i8mGk5ioTy0r/OnRCOhU0ns/Ert1CbhBbO9ak9BgoUJKTURH+us/uN7vxT4UHhEO3Chvh74a69By2bld0M8X4lduoTcKP9psbSeZd0wlxFSk1iEuoz2joPRB4RDtwoaX8CIaP/ACl21ZaEflTpMN/CZ7B+JXbqE3CiRrBiQ5S60Hu6owrP7LlSvgemDwiHbhQSN5vb1xMWiEOjzCu/PkzNQELdzE1XCoQ4+bBsDSfxK7dQm4Uls71qT0GChQkpNREArMyBh6hDtwokbIKf+tVaD8PCMKq2V7w6PjAWg4kmwjIP27BmnzrGgQG0CalVAQloeW09Jz/iV26hNwyP9psbSeZd00O3Cn23Oo9BiSxNOZYsMTaVh6Rm7I220quMtcbLIB+Kp9wiS1SR+VNQjA2nEo5hGNe08bT0fAfiZbU8OMSnHP8AR4wB0VZEjWDBKHcKTYMM5fOFKx48QlZLvORhUMSTaDE2yWj8Kx2RsuJN8xritaBdPVE3VlfwFWuMLSQgfD/yWOpS6sJCjIBRh33FqXIiWIz00OKQSlQlIio2xznPqMIU46pSJ7QUokSOUsNOKShGyAkkWW2fGOc59RhpSjiUU1k5C3fyiq/NHOc+owpl1ZWVVpKjOy0ZUzUBnjD9uPcP5jZ4xW4QOhNWiNok3xski6KnCR0Kr0wEPD21nP5TqyFgPLACj5j0xznPqMc5z6jHOc+oxznPqMc5z6jHOc+ow0pRKlEVk3/g57jMO3ih24aRQUm0VGG1+YDCq8VZC3fyiq/NHSo0M8OQj7ccau6HlD/qTi+eqcJdTagzgLTWlQmMktNH9hPq8I9toYlGJvqxq/KKhriplPWJ6YkWU9QlojF9scKvyKs7YKFjCpNoMf6zhmpO4fh0dVLnErTClPJxKCpCsjN8I5fqVrjl+pWuOX6la45fqVrjl+pWuA22JITYPwc9xmHbxQ7cNIoCxuupB67DDjBz7adByEMi1ZxG4Q86bG21SvIoZ4aZmyFu5lGq7NBWoc4/IVQtr8pquzQWTvNWXHIwJ33aurPASKyagICf+w1rV8ckfcp3kVKuhDibUmcToc4laYXx9w/Cj3GYdvFDtw0igODeakeo1GG3MwO1cajkLPlRsDq8YUTvOJUs9lXyoZ4aSBvObA7/AJQltNqzIQltO6kSHVCPuBn2Fd0JUd1Wyq45BTmbAHfAUbGxi67BlFCxNKqiI/bQE/ECvtpc4laYXx9w/Cj3GYdvFDtw0ijAqxSZHrEKQq1JIPVDavMBhVeKFu50iq/NCG86zLXCwLAggdlDPDT7Y3Wqus2wXjY0KrzQtvzSmm8WUIUd5Oyq8UvH/mrTDyuEaf6TnErTBQ2EkEz2p6xG632HXG632HXG632HXG632HXDbakowrUAZA6/we9xmHbxQ7cNIoF0e4LHRPrFRhxg59saDQhgebaNwshTxsbEhefCHOFWihnhoW6bECcFSqyqswEKck4dpWyq3sjm+lWqOb6VaoWpg4m1GYzW3wWTuu2Xil4f81aYeHD35Cr8hq7voc4laYLnuYMJwylPvEc/0eMc/wBHjHP9HjHP9HjCHfdngM5YfH8HvcZh28UO3DSKBdGMbzRxdVhhtzMDXcajQtXlTsp6oRPeXtnrs+UOcKtFDPDQhgWq2lXCyMKAVK6BXHJX9Jjkr+kxyV/SYxKaWlItJSYC07yTMQl1NixOhfQuSh/9fBbP/Ymq8V5HJR9Ijko+kQshlE8J8ooau76HOJWmF8fcPwo9xmHbxQ7cNIoF0FCt1QkeuFNqtQSOyPf86E4f1WCENfmNd2eJCyHOFWihnhoW55bE3CF/cHgTpOQptW6oSMKbVagyMK+3NqdpNxt+dAfTvNW3GEuJqUkzEB1Ge0dB6MlfCdFDV3fQ5xK0wvj7h+FHuMw7eKHbhpFAuoDgsdHzFUFjyFQXC3zYgYReaHOFWihnhhZG8rYT1+FCG84G1ebclLwscFd48IQ7mBkq420EGsG0RiTWwrdPR8DGNs3pNhiTn7S/jZ2xNCgq4zjaUBeYqV7iuhFfzsjBy2vyjPeYCEDEo2AQ22veSK6HOJWmFhxxKDjsUQMwjnN/UI5zf1COc39QjnN/UI5zf1CJtrCwLcJno/Bz3GYdvFDtw0igXUFQ3mji6s9CB5lbZ6/ChzhVooZ4YDIsbFd5hAO6jbV1eOUsDeTtJ6qADvt7J7qClYxJNoMYvtj+hXcY/dQU/HN20ybSVn4CcTePtJ6LTEmk151G00ucStOW7xDR+KtptKr0iKmkD9IiQqH/AIpi65ujMLY3XOwa4S6jdV00lpxK8SegDXHtICgqU9qWs5SnV7qeiN1zsGuErAIChORtpKcKzhMpgCWmChsKCgJ7Uu4nJU6uZSm2UbrnYNcBYsUJ9tAbcCiSMWzLWOiPaQlQVbtAa/6Jdc3RmFsbrnYNcJdRuq6clTZSuaCUmQGbrjdc7Brjdc7Brjdc7BrivEm8apx+0sKPRn7MhTK0rKkynICVYn0wpLYUCkTOKXcTllJSuaTKwa43XOwa43XOwa43XOwa43XOwa43XOwa43XOwa4S6mYSqyf90QwLE7SrzZE8xqhf254099KPuBwK7oQ6PIZ64BFhsyUfbjPtq7oQ35SZquFtK1+bdTeYqrz9kIdzA13Z4mLMh24aaG+FOihP8Y0mBwn+ihgWJ2lXmyJ5jVC/tzxp78l7+RWmCWUYgKjWBpjlepOuOV6k64mppXVXoiYqUI9h4/ujdV0+NLv6f8RDnCNOW5xK0wVMoxJBkawNMcr1J1xyvUnXHK9Sdccr1J1xyvUnXDbbgktIrH9zKlVBNZhbptWZwhcttJ9w3Kq0ShDo8p+WeAoVg1ihbX5hVfmiRtEAHeb2D3fLJW5mnJNwshf3B82ym7PSlgWI2lXnwhalCaUpI+qrROFNm1BlASd5rZN2bIduGmhvhTooT/GNJgcJ/oFSqgmswt02rM4QuW2k+4blVaJQh0eU/LPAUKwaxkPfyK0w7xDRkf7KBJaal/EGEuJtQZwFCw10O/p/xEOcI05bnErTC+PuH959sbztXVnhDQ85lrgtS2CMMvhZCm1WoMo9s7zVXVmpKhuu7QvzwWjY6PmLMhZG8vYT1+EBKayahCGh5BLXQVqqSkTMKdVaszgKO87tdWaEvCxwSN48ICTuO7JvzZDtw00N8KdFCf4xpMDhP9D2xvO1dWeENDzmWuC1LYIwy+FkKbVagyj2zvNVdWbIe/kVph3iGjIdnnkPnQhJtSAKHf0/4iHOEactziVphfH3D+8kDdb2B3/OFvmxOym820JeFjgkbx4Qme45sHrs+dOMbzW11Z4S4neSZjqhLid1QmOulLIsbEzefCPcO61X15qfbG86ZdQthDQ85lrgJFQFQhYG8naT1RMWwh3ORXfnpduGmhvhTooT/GNJgcJ/oEDdb2B3/OFvmxOym820JeFjgkbx4Qme45sHrs+eQ9/IrTDgcWlBKqsRA0xzm/qEc5v6hEy6Dw16ICEDCymuu0npMB1Q/abM7z0Uu/p/xEOcI05bnErTCw44lBx2KIGYRzm/qEc5v6hHOb+oRzm/qEBKXUFRsAUP7mt3OkVX5ombYQjzbyrzQtI3k7SbxQhzzWKvFBSawajC2j5DLVBaNrR+RoK1bqRM9UKcVaszgE7zm2e75Uqlut7A6rfnC3zYnZTebaVt+Wc03GF/bnzbSb89Ltw00N8KdFCf4xpMDhOWt3OkVX5ombYQjzbyrzQtI3k7SbxQhzzWKvFL38itOSCoYki1PTAaSPaWLEZuql39P+IhzhGnLc4lacpnjH9zR9uONXdAItEc30p1RzfSnVHN9KdVCmDYutN48KUfcDzbKr80JB3XNg93zo9sbzpl1C2ENZia7s8SFC3c4FV+aj22l4U2ykO8RzfSnVHN9KdUBTysShVOQGiEOptQZwFprSoTFDtw00N8KdFCf4xpMDhOWj7ccau6ARaI5vpTqjm+lOqOb6U6qFMGxdabx4UvfyK0w5xDRTtJCrxBX9uMDo8osMdBETVzEbKtdDv6f8RDnCNOW5xK0wvj7h/d5myFu5lGq7NBddKkick4ZeMb6+0ao319o1Rvr7RqgOtFSpGSsUvCEuJtQZwlxO6oTFC2/NKabxZExURCHR5hPrzwoDdb2B3/ADhf3B4E99KPtxxq7oS1Ym1RHRG+vtGqN9faNUb6+0aoMlrnmmRqgpVURUYLR3mtBoduGmhvhTooT/GNJgcJypmyFu5lGq7NBddKkick4ZeMb6+0ao319o1Rvr7RqgOtFSpGSsUvCEuJtQZwlxO6oTFD38itMO8Q0ZLoFmKfbXDozSBod/T/AIiHOEactziVphfH3D+7kDec2B3/ACgAVk1CENDyiXXnyFtGxYlBSqpSTIwpg2t1i4+NKpbq9tPXb84eB/6dpPXm7Y6VKPzMIaHlFd+eiZsELd/Mars0LfNqtlNwtycY3Xa+vPCSdxeyrroduGmhvhTooT/GNJgcJyiBvObA7/lAArJqEIaHlEuvPkLaNixKClVSkmRhTBtbrFx8aHv5FaYd4hoyC44ZJH/0oU4q1ZJhx4+cyHV/+0O/p/xEOcI05bnErTC+PuH939sbrVXXngKO61tG/Nle4N10T6xbCFndOyq40h0bzR+RggGpVR0wFHda2uvNSUjed2RdniQtMIaHlHzz5JUN5raF2ehCzvDZVeIduGmhvhTooT/GNJj3UAFVm1G632HXG632HXG632HXG632HXCw4EjBKWGee8mPbG61V154CjutbRvzZXuDddE+sWwhZ3TsquND38itMKS2EkKMzin3ERut9h1xut9h1xVgFw1mJurKv/uiMKBJHmXmEJbRUlIkKHf0/wCIhSmwCVCRxeEo3W+w643W+w643W+w643W+w64UtwAFKpbN3XQ5xK0wUNhJBM9qesRut9h1xut9h1xut9h1xut9h1xut9h1wtTgAKTIYfGf9xKlPzKqzseMKGLGpZrMpa8oIJwEGYVKcc/0eMJQpWMpEsVk6FIVuqEj1xz/R4wU4salGZVKWulKvdwJSJBOGfeIS6p3GEGeHDK7PlSNhip6QzbPjCh7mNK80pV9phTM8OPPbHP9HjCUW4QBO6gOe5gknDLDPOT0jpjn+jxjn+jxjn+jxjn+jxjn+jxhZ9zHjlmlZ1mCpT8yqs7HjChixqWazKWvKCCcBBmFSnHP9HjCUKVjKRLFZOFue9LGoqlh6TPpjn+jxjn+jxjn+jxit6dyfGJqm4f+Rq+UowoASkWAUqe93DilVhnYJdMc/0eMc/0eMc/0eMc/wBHjHP9HjCkY8eIznKWuhS/eliJO709cc/0eMc/0eMc/wBHjHP9HjHP9HjHP9HjCk48eIzslr/9Ho//2gAIAQIDAT8Q/wDsIH//2gAIAQMDAT8Q/wDsIH//2gAIAQEDAT8Q/wDSAwbBgiucYSlhNmVkIwIZgJx4WYoEkEPyKTukgDPDDgGWLlSCoGZe2HlQXD+T6FFuON5fYpARvi8nmgYsQgR+E/Z7vzLMlCEmWh/fDfu1XHu2+RN10A3aIK6gzOfX1Q5iyFXxQMy2mLQDKTZZoY2TkpK+BI1JgJxMfmK56HOJzNz9mu/MsboVCsys9QYnQ++Bfu1XHu2ZYuVKjEUNHfr9UrDgm+YtGAajqbrW00oIBI9GsmKkZqnKimw+JoNVyaTSYTk6j8OH7Ld+ZZkkEDWBHTrypY5cn08msuoxqBmrb92q492xkqIVuaGw0kQl3xv44ZXQI1HCscNQO5mupSq2w5P/AA/ZbvzLAcARHJEpGLicpr8qZKEJMtD+7b92q492x4PJjdg+6BfFMchl8HGIBkz8pPUUhdHrEnkP2W78yy/tqgPOhuX8aV05RolZ6gxOh92L92q492x4Wg3yoTNvxqPO+yk8Db+y3fmWX9tZpoABro6deVLHLk+nk1l1GNQM1V+7Vce7Ypolb8InuhXwIXXzxiNuvyn8p9q16n3+y3fmWX9tYiABCOSNIxcTlNflTJQhJlof3V67Vce7YxSVB8GHgzSAkJI7JWbXgTQYDvwokgSrkBUZaa+MikQMAXmx2IP2W78yy/trYDzobl/GldOUaJS0QQXPQq492xAISiEdRqKrib7Z85KcSqwM1t+6NmOUSNqgS4BU9Ywyib227U+rgN2sT+HzGK7/ALLd+ZZf23BpoABro6deVlx7tqsuZ57xWO0t4YPKpu5cxfKwoaHN296OPmCDxQWzbMpPnV6tEXZYPLsVKwHAZG5L+zfDsMxjOUlSo4kzAl8EcCIAEI5I1J5SvgHSYTT5F0MqGeARiwABE5jSy46eyx80Nwvl9BRrhm6fsUiQ7Rj1cVbq5hi/Lm9f/JYWlIGBOQDSYyFLCRyk2HdCTQwmCVev7ozFJkAFRYwmeJUvREXMhG6r1/dMyAUKrzXgJ/NIuqwHdq5f3QXonCHIKumPTiRKAlTABq0mlHDGJ8jOjzPtWPp5piVd0vumJV3SeqVI1rx+NR0oo2GJ4ny+3ABiEAwBYGNXr+6vX91ev7q9f3V6/ur1/dMDArVcWa/p1w71d+zwMhZh0Nkwamhn7AvnPgJLXZa5B1agRKV+dVs8TwZluwfdSdZaN4YdlMmSQ3DM6mFL9BNySTgyqDokKajV9KDp2GQbroUQdrLDynN4oKEnI+yg4Edp94U4SGMkrkZjrNJXVGYGkMJy2ac/o5W3VuqbbbZCDqN+IggggiJxIkWDPNl/Trh3q79ngZQajoEf9OtRNYADmf8ADgm1/AvdfFRCzxzweJs8TaoFIBKugUz+Yi6DAdijxoRh1wg+adPJxOqxXZqSMp7R2Z4FmoVMZhz/AF1oyZYDNXAKHoMO62fBpwghlw6tgX4aniRwNTU6mFCAGTiWXVury36pXDvV37PAyiJPYQ+hqYWCF0ZPBATKdHC+1QYj4QUeAs8TbI6O2Ob0rF4J8yxQcQL4hFQlwPUMV1J7VNyG+86MPA5Lh05pL3QmJdeOc8UFzKtR+KOx/Yd2a26t1eW/VK4d6u/Z4GSUp6agrCq+clFSaz4A4/Odh6seth5NHGUadYXF0MaBeCQ0BhZ4m3GiR976HSoS5TszsTZC5K8i7srJ1SX3nUhtdHYPgQUUash5P4rq3VKP9QmYDTY4SZMmTHKQpMLpL/T7h3q79ngZeO9VAhBLg5NQIYAHmf8ACyQmKT6HcvioLZhu6HvV3brPE2Z3Ihu6HVwpNpSm6stTGijJCwCTQBbFEsdKcMMyQDJqW+B7R3JtRzT36Lciu5/HB5T3web9rLq3UnUlLAZnmVKjKjKjKi+SblZhymX6fcO9Xfs8DLx3qpIJAPl/+nSpFYOXhk2QcynSw+WWsIIup0Vd26zxNk28WDoDq+qLrWRqY5FXX+quv9Vdf6pLigEB8qUk8CbmMlZckBtOZ0sREQPVEPg0aSBjsHieBRlVc3/nV3/qhoQok4g8rPN+1l1bq8t+qVw71d+zwMvHeqHyVFyENZ8keqKjlcT0s75waAWmLuXagABAIA0Cru3WeJsgJmXjjvnUqTLEu8uAOJV8SRWfBPmGKn7iw9h09rEGTgR73RpWYJuY0xmzX1Fw37us837WXVury36pXDvV37PAy8d6sg1Ex77xFCPNnyCR1w7VFj7CPYPNl3brPE1MKO+ZnpJsn8iZ3Xk8MS8t2/mFNIfUL+qEQTEcRokwSJkjmNJwUbt13rJicMYHMowR1jHPkfuKNg7qXpQMk7ge6FTZsJc50ejEzfEeSkhrgErRxhEAyCqxPWy6t1K2qRImZClXr+6vX91ev7q9f3V6/uj1WQgA85P6dcO9Xfs8DLx3qyLUgPh4M9LJLIHq4ztAsu7dZ4mpm57u/BFQ6lOhl7wOKIUn1tHUksmpPZzN2sMIGASJUqnBxmude9KoOajwGFvJVjelOBNXAvQwOrWD4sMR8zbdW79VAg2qLYNuCDbgg2sg2qDjg2qA4VZe3R7KTl7cP6oGADICDhg2qDaoNqg2qDaoNqg2/wDE3LAoGCpWIJSwnMnHIZiGEYm3BGyVIiSJIqfroQAxoRicUyccpmZYAmNWwmAoowgEkmFtU6UkKhiSThWDMVAkmMOEGECIiuKGEpvYTmMAEc4E42FB+EIhU1oE1QZAIPhfhlgUDBUrEEpYTmTjkMxDCMTwqrtEFVDEnbgJkyacfKH7U5/zHHch4MfgYzACJG9DDVABCxhxhztDSGRjDjkyZMmTJmGDIiOcYwv+pNvBi6A6HuoAzGQ6KQp5Kxl5/wAT6bZAuX9X7rOSFBqZDqUicgKNR4YXccByMPtTrk+QX8UAEGAWQKwzwh2zpGAoGBsJXoFKJoiavDwoAJKJE1HgvTZZd2y0nfu34Zt4MXQHQ91AGYyHRSFPJWMvP+J9PDeu+pmlkwC46i2AANgjNH9qCotkTBErPgE7EzHk/HExdW6seJBmImMRvxQQQQQTEIJBhlcyT/TTaEpsBLWdyIbGh0MKYPiF4blaLcoa5B1KcmGIajiNiLzSToMV3pEEJCOiVP6V6Bj9HDD7L8C/qok4qbkxXV9WzPwYOx29qnIOfORRnblu8OfWp1y33PbDpwXpssu7ZaTv3b8CbQlNgJazuRDY0OhhTB8QvDcrRblDXIOpTkwxDUcR4L138IEMiCDCRAvMaReCHo5dayyEHw4/iiYurdXlv9mxoh+3j9DrWYiKdjV0KbGIrmGDtWZ9Hzhz61ivL9/H7nS2KkF1mXvj1qfERDv+E8Eqo7xn7SaHKWBurAVkRgnd1dXGx7JBtgJazZBDYcjoVGKEn4eGPWoZZx6fmHap0wH3PfDrwXpssu7ZaTv3b8GNEP28fodazERTsauhTYxFcwwdqzPo+cOfWsV5fv4/c6cF67+EDZQD5RQKwYrTZ6J8gH4omLq3V5b/AGaQ098M/pUe8GbqLoe7IZ3j/MO1Y4R/RLUiUvD54H76VhUC+ZTWJwL4hNs8/vP4hWAEn38Ps9LYN49pfQrMTFJoauhRkwwDQMCo1SfWznUkoVCQGRNEoxNEdjh5W3pssu7ZaTv3b8Ehp74Z/So94M3UXQ92QzvH+Ydqxwj+icC9d9FzQhRI0kVev7q5f3SKBaYr5U4BEDkGB4KhpGS5DiD2/jiYurdStqkSJmQpV6/ur1/dXr+6vX903FIRq7AP+mT+Yi6rAd2kpSUyrqtS+QjyD2yshBJeZjqSVliZ1NjMPHPfOwyYaDqJCVnhoHczXUqfExDvnmbF+hTchLWZ9Hyly6VEaO2OT2tgSnvuZSPeDN1Ow92wkR7KO2VTjw7NgOpHa29Nll3bLSd+7cZP5iLqsB3aSlJTKuq1L5CPIPbKyEEl5mOpJWWJnU2Mw8c987b138I1WSigNpMaB+SHiXzIn8cTF1buK4d/9PMt2D7ps5Akg4nJ4IoolVVzccMPVSbw4uVj39LYk4DpMV1J7VLqB6jj9FkK0e0voUo267HHwoAAQGAGhYexLneHk0qqrK4q1h5a4ni5so2xRRZLDIJmMBWVwIbmp1MKeyAbcSSy9Nll3bLSd+7ceZbsH3TZyBJBxOTwRRRKqrm44Yeqk3hxcrHv6W3rvolIg2qDagYOcwH3QkSSdjjR2ihkEvwckSjby0u6ZdR+KJi6t1A66qDaoNqg2qDaoNv9JAUgEq6BTP5iOwwHYp+IYoSGayauBWrVhnAFKBySDVhWQvD0cutKzIviSbIXJXkX8UBRXI6iVpOaDTIOjUupPqH/AOFQA59nN+rZFcu7kfdSYqTmACXPtwK1avCki5DOkxQMpaGyMJU65WDvHZksvTZZd2y0nfu3EgKQCVdApn8xHYYDsU/EMUJDNZNXArVqwzgClA5JBqwrIXh6OXWlZkXxJNl67+IDAfkhzxPLQted8in3+KJi6t1eW/16R0P0HN6UZcoA1XArKCNJrmXV4M+kS2XJ6NFNIFsjDUwce7bWoOI/mHlRvZQk6hw7HmuY64pWklCNViurYiaAVXQKReTIdBgO1RzxZup3PrhwCg+3h9XrU1o7FkejDZemyy7tlpO/duKR0P0HN6UZcoA1XArKCNJrmXV4M+kS2XJ6NFNIFsjDUwce7bWL138IEEw9V0HNrMuqbSzFAxAHxzl7+H4omLq3V5b/AF7GiR7+P0OlR8kOkw88enFhVHpL6NSChvDL0zti3OI7T5ik2Ag7gnsFQSkp+B749LZqQ3WYvth1oEUoAGq1onYprmXV4YqS3SZe2Nk6JPwk9TGr02WXdstJkxAYBSH4ThJkyZMfaHANWfIVjRI9/H6HSo+SHSYeePTiwqj0l9GpBQ3hl6Z2XrvoYaoCZCMLQTpkQF3X7KFuTIcA+BgUTQDjGB9vKi7hg/tsQQtQFIGcJcImTJk4xXIEIg6u6y6t1Sj/AFCZgNNjiJkyZMmFLcBCEnGX+gZjDPSpNqU1Ky1L8IdEDAiebii6tljRIkzsGA8zhkYTEthRSouQiwQvyEAICJyWrDmICys6mFYciOYTdLJx4kASEI6jSkziwZwbTXTbnTDWjSbBhwQjlJtYOOnJqYRNmjfahEieICIiLESgGli+TOpNqU1Ky1L8IdEDAiebii6tljRIkzsGA8zhkYTEtfOLTEkJjvwCImcYcg9qnQCaQdlB3CgAA6FvgNpBmhtxCIiPZFZwCInZZtpLjiUxxxEREdJ2llwRv/6PQ//Z";
// TODO distinguere tra mobile portrait e mobile landscape
// TODO le dimensioni mobile/desktop devono essere configurabili
// TODO mantenere l'immagine caricata nella versione originale
/**
* Remove a managed file from disk and database
* @param managedFile
* @return true when deleted from disk, false when not deleted from disk (could have been deleted from db though)
*/
public boolean delete(YadaManagedFile managedFile) {
return yadaFileManagerDao.delete(managedFile);
}
/**
* Returns the absolute path of a managed file
* @param yadaAttachedFile the attachment
* @param filename the relative file name, can be yadaAttachedFile.getFilename(), yadaAttachedFile.getFilenameDesktop(), yadaAttachedFile.getFilenameMobile()
* @return the File or null
*/
public File getAbsoluteFile(YadaManagedFile managedFile) {
if (managedFile==null) {
return null;
}
return managedFile.getAbsoluteFile();
}
// /**
// * Deletes a file from disk and database
// * @param managedFile the file to delete
// */
// public void delete(YadaManagedFile managedFile) {
// yadaFileManagerDao.delete(managedFile);
// }
/**
* Makes a copy of just the filesystem files. New names are generated from the old ones by appending an incremental number.
* The source YadaAttachedFile is updated with the new names. The old files are not deleted.
* Use case: you clone an instance of YadaAttachedFile with YadaUtil.copyEntity() then you need to copy its files too.
* @param yadaAttachedFile a copy of another YadaAttachedFile
* @return the saved YadaAttachedFile
* @throws IOException
*/
public YadaAttachedFile duplicateFiles(YadaAttachedFile yadaAttachedFile) throws IOException {
if (yadaAttachedFile==null) {
return null;
}
File newFile = null;
File sourceFile = getAbsoluteMobileFile(yadaAttachedFile);
if (sourceFile!=null) {
newFile = YadaUtil.findAvailableName(sourceFile, null);
try (InputStream inputStream = new FileInputStream(sourceFile); OutputStream outputStream = new FileOutputStream(newFile)) {
IOUtils.copy(inputStream, outputStream);
}
yadaAttachedFile.setFilenameMobile(newFile.getName());
}
sourceFile = getAbsoluteDesktopFile(yadaAttachedFile);
if (sourceFile!=null) {
newFile = YadaUtil.findAvailableName(sourceFile, null);
try (InputStream inputStream = new FileInputStream(sourceFile); OutputStream outputStream = new FileOutputStream(newFile)) {
IOUtils.copy(inputStream, outputStream);
}
yadaAttachedFile.setFilenameDesktop(newFile.getName());
}
sourceFile = getAbsoluteFile(yadaAttachedFile);
if (sourceFile!=null) {
newFile = YadaUtil.findAvailableName(sourceFile, null);
try (InputStream inputStream = new FileInputStream(sourceFile); OutputStream outputStream = new FileOutputStream(newFile)) {
IOUtils.copy(inputStream, outputStream);
}
yadaAttachedFile.setFilename(newFile.getName());
}
return yadaAttachedFileRepository.save(yadaAttachedFile);
}
/**
* Returns the absolute path of the mobile file
* @param yadaAttachedFile the attachment
* @return the File or null
*/
public File getAbsoluteMobileFile(YadaAttachedFile yadaAttachedFile) {
if (yadaAttachedFile!=null) {
return getAbsoluteFile(yadaAttachedFile, yadaAttachedFile.getFilenameMobile());
}
return null;
}
/**
* Returns the absolute path of the desktop file
* @param yadaAttachedFile the attachment
* @return the File or null
*/
public File getAbsoluteDesktopFile(YadaAttachedFile yadaAttachedFile) {
if (yadaAttachedFile!=null) {
return getAbsoluteFile(yadaAttachedFile, yadaAttachedFile.getFilenameDesktop());
}
return null;
}
/**
* Returns the absolute path of the default file (no mobile/desktop variant)
* @param yadaAttachedFile the attachment
* @return the File or null
*/
public File getAbsoluteFile(YadaAttachedFile yadaAttachedFile) {
if (yadaAttachedFile!=null) {
return getAbsoluteFile(yadaAttachedFile, yadaAttachedFile.getFilename());
}
return null;
}
/**
* Returns the absolute path of a file
* @param yadaAttachedFile the attachment
* @param filename the relative file name, can be yadaAttachedFile.getFilename(), yadaAttachedFile.getFilenameDesktop(), yadaAttachedFile.getFilenameMobile()
* @return the File or null
*/
public File getAbsoluteFile(YadaAttachedFile yadaAttachedFile, String filename) {
if (filename==null || yadaAttachedFile==null) {
return null;
}
File targetFolder = new File(config.getContentPath(), yadaAttachedFile.getRelativeFolderPath());
return new File(targetFolder, filename);
}
/**
* Deletes from the filesystem all files related to the attachment
* @param yadaAttachedFileId the attachment id
* @see #deleteFileAttachment(YadaAttachedFile)
*/
public void deleteFileAttachment(Long yadaAttachedFileId) {
deleteFileAttachment(yadaAttachedFileRepository.findOne(yadaAttachedFileId));
}
/**
* Deletes from the filesystem all files related to the attachment
* @param yadaAttachedFile the attachment
* @see #deleteFileAttachment(Long)
*/
public void deleteFileAttachment(YadaAttachedFile yadaAttachedFile) {
if (yadaAttachedFile==null) {
return;
}
if (yadaAttachedFile.getFilename() != null) {
getAbsoluteFile(yadaAttachedFile, yadaAttachedFile.getFilename()).delete();
}
if (yadaAttachedFile.getFilenameDesktop() != null) {
getAbsoluteFile(yadaAttachedFile, yadaAttachedFile.getFilenameDesktop()).delete();
}
if (yadaAttachedFile.getFilenameMobile() != null) {
getAbsoluteFile(yadaAttachedFile, yadaAttachedFile.getFilenameMobile()).delete();
}
}
/**
* Deletes from the filesystem all files related to the attachments
* @param yadaAttachedFiles the attachments
*/
public void deleteFileAttachment(List<YadaAttachedFile> yadaAttachedFiles) {
for (YadaAttachedFile yadaAttachedFile : yadaAttachedFiles) {
deleteFileAttachment(yadaAttachedFile);
}
}
/**
* Returns the (relative) url of the mobile image if any, or null
* @param yadaAttachedFile
* @return
*/
public String getMobileImageUrl(YadaAttachedFile yadaAttachedFile) {
if (yadaAttachedFile==null) {
return NOIMAGE_DATA;
}
String imageName = yadaAttachedFile.getFilenameMobile();
if (imageName==null) {
return NOIMAGE_DATA;
}
return computeUrl(yadaAttachedFile, imageName);
}
/**
* Returns the (relative) url of the desktop image. If not defined, falls back to the plain file.
* @param yadaAttachedFile
* @return
*/
public String getDesktopImageUrl(YadaAttachedFile yadaAttachedFile) {
if (yadaAttachedFile==null) {
return NOIMAGE_DATA;
}
String imageName = yadaAttachedFile.getFilenameDesktop();
if (imageName==null) {
return getFileUrl(yadaAttachedFile);
}
return computeUrl(yadaAttachedFile, imageName);
}
/**
* Returns the (relative) url of the file, or null.
* @param yadaAttachedFile
* @return
*/
public String getFileUrl(YadaAttachedFile yadaAttachedFile) {
if (yadaAttachedFile==null) {
return NOIMAGE_DATA;
}
String imageName = yadaAttachedFile.getFilename();
if (imageName==null) {
return NOIMAGE_DATA;
}
return computeUrl(yadaAttachedFile, imageName);
}
private String computeUrl(YadaAttachedFile yadaAttachedFile, String imageName) {
StringBuilder result = new StringBuilder(config.getContentUrl());
result.append(yadaAttachedFile.getRelativeFolderPath())
.append("/")
.append(imageName);
return result.toString();
}
/**
* Uploads a file into the uploads folder.
* @param multipartFile
* @return
* @throws IOException
*/
private File uploadFileInternal(MultipartFile multipartFile) throws IOException {
String originalFilename = multipartFile.getOriginalFilename();
String targetName = YadaUtil.reduceToSafeFilename(originalFilename);
String[] filenameParts = YadaUtil.splitFileNameAndExtension(targetName);
File targetFolder = config.getUploadsFolder();
// Useless: doesn't throw an exception when it fails: targetFolder.mkdirs();
File targetFile = YadaUtil.findAvailableName(targetFolder, filenameParts[0], filenameParts[1], COUNTER_SEPARATOR);
multipartFile.transferTo(targetFile);
// try (InputStream inputStream = multipartFile.getInputStream(); OutputStream outputStream = new FileOutputStream(targetFile)) {
// IOUtils.copy(inputStream, outputStream);
// } catch (IOException e) {
// throw e;
// }
log.debug("File {} uploaded", targetFile.getAbsolutePath());
return targetFile;
}
/**
* Copies a received file to the upload folder. The returned File is the only pointer to the uploaded file.
* @param multipartFile file coming from the http request
* @return the uploaded file with a unique name, or null if the user did not send any file
* @throws IOException
*/
public File uploadFile(MultipartFile multipartFile) throws IOException {
if (multipartFile==null || multipartFile.getSize()==0) {
log.debug("No file sent for upload");
return null;
}
File targetFile = uploadFileInternal(multipartFile);
return targetFile;
}
/**
* Copies a received file to the upload folder. A pointer to the file is stored in the database as
* @param multipartFile file coming from the http request
* @return the uploaded file with a unique name, or null if the user did not send any file
* @throws IOException
*/
public YadaManagedFile manageFile(MultipartFile multipartFile) throws IOException {
return manageFile(multipartFile, null);
}
/**
* Copies a received file to the upload folder. A pointer to the file is stored in the database as
* @param multipartFile file coming from the http request
* @param description a user description for the file
* @return the uploaded file with a unique name, or null if the user did not send any file
* @throws IOException
*/
public YadaManagedFile manageFile(MultipartFile multipartFile, String description) throws IOException {
if (multipartFile==null || multipartFile.getSize()==0) {
log.debug("No file sent for upload");
return null;
}
File targetFile = uploadFileInternal(multipartFile);
YadaManagedFile yadaManagedFile = yadaFileManagerDao.createManagedFile(multipartFile, targetFile, description);
return yadaManagedFile;
}
/**
* Replace the file associated with the current attachment
* @param currentAttachedFile an existing attachment, never null
* @param managedFile the new file to set
* @param multipartFile the original uploaded file, to get the client filename. If null, the client filename is not changed.
* @return
* @throws IOException
*/
public YadaAttachedFile attachReplace(YadaAttachedFile currentAttachedFile, File managedFile, MultipartFile multipartFile, String namePrefix) throws IOException {
return attachReplace(currentAttachedFile, managedFile, multipartFile, namePrefix, null, null, null);
}
/**
* Replace the file associated with the current attachment, only if a file was actually attached
* @param currentAttachedFile an existing attachment, never null
* @param managedFile the new file to set
* @param multipartFile the original uploaded file, to get the client filename. If null, the client filename is not changed.
* @param targetExtension optional, to convert image file formats
* @param desktopWidth optional width for desktop images - when null, the image is not resized
* @param mobileWidth optional width for mobile images - when null, the mobile file is the same as the desktop
* @return YadaAttachedFile if the file is uploaded, null if no file was sent by the user
* @throws IOException
*/
public YadaAttachedFile attachReplace(YadaAttachedFile currentAttachedFile, File managedFile, MultipartFile multipartFile, String namePrefix, String targetExtension, Integer desktopWidth, Integer mobileWidth) throws IOException {
if (managedFile==null) {
return null;
}
deleteFileAttachment(currentAttachedFile); // Delete any previous attached files
String clientFilename = null;
if (multipartFile!=null) {
clientFilename = multipartFile.getOriginalFilename();
}
return attach(currentAttachedFile, managedFile, clientFilename, namePrefix, targetExtension, desktopWidth, mobileWidth);
}
/**
* Copies a managed file to the destination folder, creating a database association to assign to an Entity.
* The name of the file is in the format [basename]managedFileName_id.ext.
* Images are not resized.
* @param managedFile an uploaded file, can be an image or not
* @param multipartFile the original uploaded file, to get the client filename. If null, the client filename is not set.
* @param relativeFolderPath path of the target folder relative to the contents folder
* @param namePrefix prefix to attach before the original file name. Add a separator if you need one. Can be null.
* @return YadaAttachedFile if the file is uploaded, null if no file was sent by the user
* @throws IOException
* @see {@link #attach(File, String, String, String, Integer, Integer)}
*/
public YadaAttachedFile attachNew(File managedFile, MultipartFile multipartFile, String relativeFolderPath, String namePrefix) throws IOException {
return attachNew(managedFile, multipartFile, relativeFolderPath, namePrefix, null, null, null);
}
/**
* Copies (and resizes) a managed file to the destination folder, creating a database association to assign to an Entity.
* The name of the file is in the format [basename]managedFileName_id.ext
* @param managedFile an uploaded file, can be an image or not. When null, nothing is done.
* @param multipartFile the original uploaded file, to get the client filename. If null, the client filename is not changed.
* @param relativeFolderPath path of the target folder relative to the contents folder, starting with a slash /
* @param namePrefix prefix to attach before the original file name. Add a separator if you need one. Can be null.
* @param targetExtension optional, to convert image file formats
* @param desktopWidth optional width for desktop images - when null, the image is not resized
* @param mobileWidth optional width for mobile images - when null, the mobile file is the same as the desktop
* @return YadaAttachedFile if the file is uploaded, null if no file was sent by the user
* @throws IOException
* @see {@link #attach(File, String, String, String)}
*/
public YadaAttachedFile attachNew(File managedFile, MultipartFile multipartFile, String relativeFolderPath, String namePrefix, String targetExtension, Integer desktopWidth, Integer mobileWidth) throws IOException {
String clientFilename = null;
if (multipartFile!=null) {
clientFilename = multipartFile.getOriginalFilename();
}
return attachNew(managedFile, clientFilename, relativeFolderPath, namePrefix, targetExtension, desktopWidth, mobileWidth);
}
/**
* Copies (and resizes) a managed file to the destination folder, creating a database association to assign to an Entity.
* The name of the file is in the format [basename]managedFileName_id.ext
* @param managedFile an uploaded file, can be an image or not. When null, nothing is done.
* @param clientFilename the original client filename. If null, the client filename is not changed.
* @param relativeFolderPath path of the target folder relative to the contents folder, starting with a slash /
* @param namePrefix prefix to attach before the original file name. Add a separator if you need one. Can be null.
* @param targetExtension optional, to convert image file formats
* @param desktopWidth optional width for desktop images - when null, the image is not resized
* @param mobileWidth optional width for mobile images - when null, the mobile file is the same as the desktop
* @return YadaAttachedFile if the file is uploaded, null if no file was sent by the user
* @throws IOException
* @see {@link #attach(File, String, String, String)}
*/
public YadaAttachedFile attachNew(File managedFile, String clientFilename, String relativeFolderPath, String namePrefix, String targetExtension, Integer desktopWidth, Integer mobileWidth) throws IOException {
if (managedFile==null) {
return null;
}
if (!relativeFolderPath.startsWith("/") && !relativeFolderPath.startsWith("\\")) {
relativeFolderPath = "/" + relativeFolderPath;
log.warn("The relativeFolderPath '{}' should have a leading slash (fixed)", relativeFolderPath);
}
YadaAttachedFile yadaAttachedFile = new YadaAttachedFile();
// yadaAttachedFile.setAttachedToId(attachToId);
yadaAttachedFile.setRelativeFolderPath(relativeFolderPath);
// This save should not bee needed anymore because of @PostPersist in YadaAttachedFile
yadaAttachedFile = yadaAttachedFileRepository.save(yadaAttachedFile); // Get the id
File targetFolder = new File(config.getContentPath(), relativeFolderPath);
targetFolder.mkdirs();
return attach(yadaAttachedFile, managedFile, clientFilename, namePrefix, targetExtension, desktopWidth, mobileWidth);
}
/**
* Performs file copy and (for images) resize to different versions
* @param yadaAttachedFile object to fill with values
* @param managedFile an uploaded file, can be an image or not. When null, nothing is done.
* @param clientFilename the client filename. If null, the client filename is not changed.
* @param namePrefix prefix to attach before the original file name to make the target name. Add a separator (like a dash) if you need one. Can be null.
* @param targetExtension optional, to convert image file formats
* @param desktopWidth optional width for desktop images - when null, the image is not resized
* @param mobileWidth optional width for mobile images - when null, the mobile file is the same as the desktop
* @return
* @throws IOException
*/
private YadaAttachedFile attach(YadaAttachedFile yadaAttachedFile, File managedFile, String clientFilename, String namePrefix, String targetExtension, Integer desktopWidth, Integer mobileWidth) throws IOException {
//
yadaAttachedFile.setUploadTimestamp(new Date());
if (clientFilename!=null) {
yadaAttachedFile.setClientFilename(clientFilename);
}
String origExtension = yadaUtil.getFileExtension(yadaAttachedFile.getClientFilename());
if (targetExtension==null) {
targetExtension = origExtension;
}
YadaIntDimension dimension = yadaUtil.getImageDimension(managedFile);
yadaAttachedFile.setImageDimension(dimension);
boolean imageExtensionChanged = origExtension==null || targetExtension.compareToIgnoreCase(origExtension)!=0;
boolean requiresTransofmation = imageExtensionChanged || desktopWidth!=null || mobileWidth!=null;
boolean needToDeleteOriginal = config.isFileManagerDeletingUploads();
//
// If the file does not need resizing, there is just one default filename like "product-mydoc_2631.pdf"
if (!requiresTransofmation) {
File targetFile = yadaAttachedFile.calcAndSetTargetFile(namePrefix, targetExtension, null, YadaAttachedFile.YadaAttachedFileType.DEFAULT);
// File targetFile = new File(targetFolder, targetFilenamePrefix + "." + targetExtension);
if (needToDeleteOriginal) {
// Just move the old file to the new destination
Files.move(managedFile.toPath(), targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
} else {
// Copy bytes
try (InputStream inputStream = new FileInputStream(managedFile); OutputStream outputStream = new FileOutputStream(targetFile)) {
IOUtils.copy(inputStream, outputStream);
} catch (IOException e) {
throw e;
}
}
} else {
// Transformation: copy with imagemagick
// If desktopWidth is null, the image original size does not change.
// The file name is like "product-mydoc_2631_640.jpg"
File targetFile = yadaAttachedFile.calcAndSetTargetFile(namePrefix, targetExtension, desktopWidth, YadaAttachedFile.YadaAttachedFileType.DESKTOP);
resizeAndConvertImageAsNeeded(managedFile, targetFile, desktopWidth);
yadaAttachedFile.setFilename(targetFile.getName());
if (mobileWidth==null) {
yadaAttachedFile.setFilenameMobile(null); // No mobile image
} else {
targetFile = yadaAttachedFile.calcAndSetTargetFile(namePrefix, targetExtension, mobileWidth, YadaAttachedFile.YadaAttachedFileType.MOBILE);
resizeAndConvertImageAsNeeded(managedFile, targetFile, mobileWidth);
}
if (needToDeleteOriginal) {
log.debug("Deleting original file {}", managedFile.getAbsolutePath());
managedFile.delete();
}
}
return yadaAttachedFileRepository.save(yadaAttachedFile);
}
/**
* Perform image format conversion and/or resize, when needed
* @param sourceFile
* @param targetFile
* @param targetWidth resize width, can be null for no resize
*/
private void resizeAndConvertImageAsNeeded(File sourceFile, File targetFile, Integer targetWidth) {
if (targetWidth==null) {
// Convert only
Map<String,String> params = new HashMap<>();
params.put("FILENAMEIN", sourceFile.getAbsolutePath());
params.put("FILENAMEOUT", targetFile.getAbsolutePath());
boolean convert = yadaUtil.exec("config/shell/convert", params);
if (!convert) {
log.error("Image not copied when making attachment: {}", targetFile);
}
} else {
// Resize
Map<String,String> params = new HashMap<>();
params.put("FILENAMEIN", sourceFile.getAbsolutePath());
params.put("FILENAMEOUT", targetFile.getAbsolutePath());
params.put("W", Integer.toString(targetWidth));
params.put("H", ""); // the height must be empty to keep the original proportions and resize based on width
boolean resized = yadaUtil.exec("config/shell/resize", params);
if (!resized) {
log.error("Image not resized when making attachment: {}", targetFile);
}
}
}
}
|
YadaWeb/src/main/java/net/yadaframework/components/YadaFileManager.java
|
package net.yadaframework.components;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import net.yadaframework.core.YadaConfiguration;
import net.yadaframework.persistence.entity.YadaAttachedFile;
import net.yadaframework.persistence.entity.YadaManagedFile;
import net.yadaframework.persistence.repository.YadaAttachedFileRepository;
import net.yadaframework.persistence.repository.YadaFileManagerDao;
import net.yadaframework.raw.YadaIntDimension;
/**
* The File Manager handles uploaded files. They are kept in a specific folder where they can be
* chosen to be attached to entities.
*
*/
// Not in YadaWebCMS because used by YadaSession and YadaUtil
@Service
public class YadaFileManager {
private final transient Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired private YadaAttachedFileRepository yadaAttachedFileRepository;
@Autowired private YadaConfiguration config;
@Autowired private YadaUtil yadaUtil;
@Autowired private YadaFileManagerDao yadaFileManagerDao;
protected String COUNTER_SEPARATOR="_";
// TODO distinguere tra mobile portrait e mobile landscape
// TODO le dimensioni mobile/desktop devono essere configurabili
// TODO mantenere l'immagine caricata nella versione originale
/**
* Remove a managed file from disk and database
* @param managedFile
* @return true when deleted from disk, false when not deleted from disk (could have been deleted from db though)
*/
public boolean delete(YadaManagedFile managedFile) {
return yadaFileManagerDao.delete(managedFile);
}
/**
* Returns the absolute path of a managed file
* @param yadaAttachedFile the attachment
* @param filename the relative file name, can be yadaAttachedFile.getFilename(), yadaAttachedFile.getFilenameDesktop(), yadaAttachedFile.getFilenameMobile()
* @return the File or null
*/
public File getAbsoluteFile(YadaManagedFile managedFile) {
if (managedFile==null) {
return null;
}
return managedFile.getAbsoluteFile();
}
// /**
// * Deletes a file from disk and database
// * @param managedFile the file to delete
// */
// public void delete(YadaManagedFile managedFile) {
// yadaFileManagerDao.delete(managedFile);
// }
/**
* Makes a copy of just the filesystem files. New names are generated from the old ones by appending an incremental number.
* The source YadaAttachedFile is updated with the new names. The old files are not deleted.
* Use case: you clone an instance of YadaAttachedFile with YadaUtil.copyEntity() then you need to copy its files too.
* @param yadaAttachedFile a copy of another YadaAttachedFile
* @return the saved YadaAttachedFile
* @throws IOException
*/
public YadaAttachedFile duplicateFiles(YadaAttachedFile yadaAttachedFile) throws IOException {
if (yadaAttachedFile==null) {
return null;
}
File newFile = null;
File sourceFile = getAbsoluteMobileFile(yadaAttachedFile);
if (sourceFile!=null) {
newFile = YadaUtil.findAvailableName(sourceFile, null);
try (InputStream inputStream = new FileInputStream(sourceFile); OutputStream outputStream = new FileOutputStream(newFile)) {
IOUtils.copy(inputStream, outputStream);
}
yadaAttachedFile.setFilenameMobile(newFile.getName());
}
sourceFile = getAbsoluteDesktopFile(yadaAttachedFile);
if (sourceFile!=null) {
newFile = YadaUtil.findAvailableName(sourceFile, null);
try (InputStream inputStream = new FileInputStream(sourceFile); OutputStream outputStream = new FileOutputStream(newFile)) {
IOUtils.copy(inputStream, outputStream);
}
yadaAttachedFile.setFilenameDesktop(newFile.getName());
}
sourceFile = getAbsoluteFile(yadaAttachedFile);
if (sourceFile!=null) {
newFile = YadaUtil.findAvailableName(sourceFile, null);
try (InputStream inputStream = new FileInputStream(sourceFile); OutputStream outputStream = new FileOutputStream(newFile)) {
IOUtils.copy(inputStream, outputStream);
}
yadaAttachedFile.setFilename(newFile.getName());
}
return yadaAttachedFileRepository.save(yadaAttachedFile);
}
/**
* Returns the absolute path of the mobile file
* @param yadaAttachedFile the attachment
* @return the File or null
*/
public File getAbsoluteMobileFile(YadaAttachedFile yadaAttachedFile) {
if (yadaAttachedFile!=null) {
return getAbsoluteFile(yadaAttachedFile, yadaAttachedFile.getFilenameMobile());
}
return null;
}
/**
* Returns the absolute path of the desktop file
* @param yadaAttachedFile the attachment
* @return the File or null
*/
public File getAbsoluteDesktopFile(YadaAttachedFile yadaAttachedFile) {
if (yadaAttachedFile!=null) {
return getAbsoluteFile(yadaAttachedFile, yadaAttachedFile.getFilenameDesktop());
}
return null;
}
/**
* Returns the absolute path of the default file (no mobile/desktop variant)
* @param yadaAttachedFile the attachment
* @return the File or null
*/
public File getAbsoluteFile(YadaAttachedFile yadaAttachedFile) {
if (yadaAttachedFile!=null) {
return getAbsoluteFile(yadaAttachedFile, yadaAttachedFile.getFilename());
}
return null;
}
/**
* Returns the absolute path of a file
* @param yadaAttachedFile the attachment
* @param filename the relative file name, can be yadaAttachedFile.getFilename(), yadaAttachedFile.getFilenameDesktop(), yadaAttachedFile.getFilenameMobile()
* @return the File or null
*/
public File getAbsoluteFile(YadaAttachedFile yadaAttachedFile, String filename) {
if (filename==null || yadaAttachedFile==null) {
return null;
}
File targetFolder = new File(config.getContentPath(), yadaAttachedFile.getRelativeFolderPath());
return new File(targetFolder, filename);
}
/**
* Deletes from the filesystem all files related to the attachment
* @param yadaAttachedFileId the attachment id
* @see #deleteFileAttachment(YadaAttachedFile)
*/
public void deleteFileAttachment(Long yadaAttachedFileId) {
deleteFileAttachment(yadaAttachedFileRepository.findOne(yadaAttachedFileId));
}
/**
* Deletes from the filesystem all files related to the attachment
* @param yadaAttachedFile the attachment
* @see #deleteFileAttachment(Long)
*/
public void deleteFileAttachment(YadaAttachedFile yadaAttachedFile) {
if (yadaAttachedFile==null) {
return;
}
if (yadaAttachedFile.getFilename() != null) {
getAbsoluteFile(yadaAttachedFile, yadaAttachedFile.getFilename()).delete();
}
if (yadaAttachedFile.getFilenameDesktop() != null) {
getAbsoluteFile(yadaAttachedFile, yadaAttachedFile.getFilenameDesktop()).delete();
}
if (yadaAttachedFile.getFilenameMobile() != null) {
getAbsoluteFile(yadaAttachedFile, yadaAttachedFile.getFilenameMobile()).delete();
}
}
/**
* Deletes from the filesystem all files related to the attachments
* @param yadaAttachedFiles the attachments
*/
public void deleteFileAttachment(List<YadaAttachedFile> yadaAttachedFiles) {
for (YadaAttachedFile yadaAttachedFile : yadaAttachedFiles) {
deleteFileAttachment(yadaAttachedFile);
}
}
/**
* Returns the (relative) url of the mobile image if any, or null
* @param yadaAttachedFile
* @return
*/
public String getMobileImageUrl(YadaAttachedFile yadaAttachedFile) {
if (yadaAttachedFile==null) {
return null;
}
String imageName = yadaAttachedFile.getFilenameMobile();
if (imageName==null) {
return null;
}
return computeUrl(yadaAttachedFile, imageName);
}
/**
* Returns the (relative) url of the desktop image. If not defined, falls back to the plain file.
* @param yadaAttachedFile
* @return
*/
public String getDesktopImageUrl(YadaAttachedFile yadaAttachedFile) {
if (yadaAttachedFile==null) {
return null;
}
String imageName = yadaAttachedFile.getFilenameDesktop();
if (imageName==null) {
return getFileUrl(yadaAttachedFile);
}
return computeUrl(yadaAttachedFile, imageName);
}
/**
* Returns the (relative) url of the file, or null.
* @param yadaAttachedFile
* @return
*/
public String getFileUrl(YadaAttachedFile yadaAttachedFile) {
if (yadaAttachedFile==null) {
return null;
}
String imageName = yadaAttachedFile.getFilename();
if (imageName==null) {
return null;
}
return computeUrl(yadaAttachedFile, imageName);
}
private String computeUrl(YadaAttachedFile yadaAttachedFile, String imageName) {
StringBuilder result = new StringBuilder(config.getContentUrl());
result.append(yadaAttachedFile.getRelativeFolderPath())
.append("/")
.append(imageName);
return result.toString();
}
/**
* Uploads a file into the uploads folder.
* @param multipartFile
* @return
* @throws IOException
*/
private File uploadFileInternal(MultipartFile multipartFile) throws IOException {
String originalFilename = multipartFile.getOriginalFilename();
String targetName = YadaUtil.reduceToSafeFilename(originalFilename);
String[] filenameParts = YadaUtil.splitFileNameAndExtension(targetName);
File targetFolder = config.getUploadsFolder();
// Useless: doesn't throw an exception when it fails: targetFolder.mkdirs();
File targetFile = YadaUtil.findAvailableName(targetFolder, filenameParts[0], filenameParts[1], COUNTER_SEPARATOR);
multipartFile.transferTo(targetFile);
// try (InputStream inputStream = multipartFile.getInputStream(); OutputStream outputStream = new FileOutputStream(targetFile)) {
// IOUtils.copy(inputStream, outputStream);
// } catch (IOException e) {
// throw e;
// }
log.debug("File {} uploaded", targetFile.getAbsolutePath());
return targetFile;
}
/**
* Copies a received file to the upload folder. The returned File is the only pointer to the uploaded file.
* @param multipartFile file coming from the http request
* @return the uploaded file with a unique name, or null if the user did not send any file
* @throws IOException
*/
public File uploadFile(MultipartFile multipartFile) throws IOException {
if (multipartFile==null || multipartFile.getSize()==0) {
log.debug("No file sent for upload");
return null;
}
File targetFile = uploadFileInternal(multipartFile);
return targetFile;
}
/**
* Copies a received file to the upload folder. A pointer to the file is stored in the database as
* @param multipartFile file coming from the http request
* @return the uploaded file with a unique name, or null if the user did not send any file
* @throws IOException
*/
public YadaManagedFile manageFile(MultipartFile multipartFile) throws IOException {
return manageFile(multipartFile, null);
}
/**
* Copies a received file to the upload folder. A pointer to the file is stored in the database as
* @param multipartFile file coming from the http request
* @param description a user description for the file
* @return the uploaded file with a unique name, or null if the user did not send any file
* @throws IOException
*/
public YadaManagedFile manageFile(MultipartFile multipartFile, String description) throws IOException {
if (multipartFile==null || multipartFile.getSize()==0) {
log.debug("No file sent for upload");
return null;
}
File targetFile = uploadFileInternal(multipartFile);
YadaManagedFile yadaManagedFile = yadaFileManagerDao.createManagedFile(multipartFile, targetFile, description);
return yadaManagedFile;
}
/**
* Replace the file associated with the current attachment
* @param currentAttachedFile an existing attachment, never null
* @param managedFile the new file to set
* @param multipartFile the original uploaded file, to get the client filename. If null, the client filename is not changed.
* @return
* @throws IOException
*/
public YadaAttachedFile attachReplace(YadaAttachedFile currentAttachedFile, File managedFile, MultipartFile multipartFile, String namePrefix) throws IOException {
return attachReplace(currentAttachedFile, managedFile, multipartFile, namePrefix, null, null, null);
}
/**
* Replace the file associated with the current attachment, only if a file was actually attached
* @param currentAttachedFile an existing attachment, never null
* @param managedFile the new file to set
* @param multipartFile the original uploaded file, to get the client filename. If null, the client filename is not changed.
* @param targetExtension optional, to convert image file formats
* @param desktopWidth optional width for desktop images - when null, the image is not resized
* @param mobileWidth optional width for mobile images - when null, the mobile file is the same as the desktop
* @return YadaAttachedFile if the file is uploaded, null if no file was sent by the user
* @throws IOException
*/
public YadaAttachedFile attachReplace(YadaAttachedFile currentAttachedFile, File managedFile, MultipartFile multipartFile, String namePrefix, String targetExtension, Integer desktopWidth, Integer mobileWidth) throws IOException {
if (managedFile==null) {
return null;
}
deleteFileAttachment(currentAttachedFile); // Delete any previous attached files
String clientFilename = null;
if (multipartFile!=null) {
clientFilename = multipartFile.getOriginalFilename();
}
return attach(currentAttachedFile, managedFile, clientFilename, namePrefix, targetExtension, desktopWidth, mobileWidth);
}
/**
* Copies a managed file to the destination folder, creating a database association to assign to an Entity.
* The name of the file is in the format [basename]managedFileName_id.ext.
* Images are not resized.
* @param managedFile an uploaded file, can be an image or not
* @param multipartFile the original uploaded file, to get the client filename. If null, the client filename is not set.
* @param relativeFolderPath path of the target folder relative to the contents folder
* @param namePrefix prefix to attach before the original file name. Add a separator if you need one. Can be null.
* @return YadaAttachedFile if the file is uploaded, null if no file was sent by the user
* @throws IOException
* @see {@link #attach(File, String, String, String, Integer, Integer)}
*/
public YadaAttachedFile attachNew(File managedFile, MultipartFile multipartFile, String relativeFolderPath, String namePrefix) throws IOException {
return attachNew(managedFile, multipartFile, relativeFolderPath, namePrefix, null, null, null);
}
/**
* Copies (and resizes) a managed file to the destination folder, creating a database association to assign to an Entity.
* The name of the file is in the format [basename]managedFileName_id.ext
* @param managedFile an uploaded file, can be an image or not. When null, nothing is done.
* @param multipartFile the original uploaded file, to get the client filename. If null, the client filename is not changed.
* @param relativeFolderPath path of the target folder relative to the contents folder, starting with a slash /
* @param namePrefix prefix to attach before the original file name. Add a separator if you need one. Can be null.
* @param targetExtension optional, to convert image file formats
* @param desktopWidth optional width for desktop images - when null, the image is not resized
* @param mobileWidth optional width for mobile images - when null, the mobile file is the same as the desktop
* @return YadaAttachedFile if the file is uploaded, null if no file was sent by the user
* @throws IOException
* @see {@link #attach(File, String, String, String)}
*/
public YadaAttachedFile attachNew(File managedFile, MultipartFile multipartFile, String relativeFolderPath, String namePrefix, String targetExtension, Integer desktopWidth, Integer mobileWidth) throws IOException {
String clientFilename = null;
if (multipartFile!=null) {
clientFilename = multipartFile.getOriginalFilename();
}
return attachNew(managedFile, clientFilename, relativeFolderPath, namePrefix, targetExtension, desktopWidth, mobileWidth);
}
/**
* Copies (and resizes) a managed file to the destination folder, creating a database association to assign to an Entity.
* The name of the file is in the format [basename]managedFileName_id.ext
* @param managedFile an uploaded file, can be an image or not. When null, nothing is done.
* @param clientFilename the original client filename. If null, the client filename is not changed.
* @param relativeFolderPath path of the target folder relative to the contents folder, starting with a slash /
* @param namePrefix prefix to attach before the original file name. Add a separator if you need one. Can be null.
* @param targetExtension optional, to convert image file formats
* @param desktopWidth optional width for desktop images - when null, the image is not resized
* @param mobileWidth optional width for mobile images - when null, the mobile file is the same as the desktop
* @return YadaAttachedFile if the file is uploaded, null if no file was sent by the user
* @throws IOException
* @see {@link #attach(File, String, String, String)}
*/
public YadaAttachedFile attachNew(File managedFile, String clientFilename, String relativeFolderPath, String namePrefix, String targetExtension, Integer desktopWidth, Integer mobileWidth) throws IOException {
if (managedFile==null) {
return null;
}
if (!relativeFolderPath.startsWith("/") && !relativeFolderPath.startsWith("\\")) {
relativeFolderPath = "/" + relativeFolderPath;
log.warn("The relativeFolderPath '{}' should have a leading slash (fixed)", relativeFolderPath);
}
YadaAttachedFile yadaAttachedFile = new YadaAttachedFile();
// yadaAttachedFile.setAttachedToId(attachToId);
yadaAttachedFile.setRelativeFolderPath(relativeFolderPath);
// This save should not bee needed anymore because of @PostPersist in YadaAttachedFile
yadaAttachedFile = yadaAttachedFileRepository.save(yadaAttachedFile); // Get the id
File targetFolder = new File(config.getContentPath(), relativeFolderPath);
targetFolder.mkdirs();
return attach(yadaAttachedFile, managedFile, clientFilename, namePrefix, targetExtension, desktopWidth, mobileWidth);
}
/**
* Performs file copy and (for images) resize to different versions
* @param yadaAttachedFile object to fill with values
* @param managedFile an uploaded file, can be an image or not. When null, nothing is done.
* @param clientFilename the client filename. If null, the client filename is not changed.
* @param namePrefix prefix to attach before the original file name to make the target name. Add a separator (like a dash) if you need one. Can be null.
* @param targetExtension optional, to convert image file formats
* @param desktopWidth optional width for desktop images - when null, the image is not resized
* @param mobileWidth optional width for mobile images - when null, the mobile file is the same as the desktop
* @return
* @throws IOException
*/
private YadaAttachedFile attach(YadaAttachedFile yadaAttachedFile, File managedFile, String clientFilename, String namePrefix, String targetExtension, Integer desktopWidth, Integer mobileWidth) throws IOException {
//
yadaAttachedFile.setUploadTimestamp(new Date());
if (clientFilename!=null) {
yadaAttachedFile.setClientFilename(clientFilename);
}
String origExtension = yadaUtil.getFileExtension(yadaAttachedFile.getClientFilename());
if (targetExtension==null) {
targetExtension = origExtension;
}
YadaIntDimension dimension = yadaUtil.getImageDimension(managedFile);
yadaAttachedFile.setImageDimension(dimension);
boolean imageExtensionChanged = origExtension==null || targetExtension.compareToIgnoreCase(origExtension)!=0;
boolean requiresTransofmation = imageExtensionChanged || desktopWidth!=null || mobileWidth!=null;
boolean needToDeleteOriginal = config.isFileManagerDeletingUploads();
//
// If the file does not need resizing, there is just one default filename like "product-mydoc_2631.pdf"
if (!requiresTransofmation) {
File targetFile = yadaAttachedFile.calcAndSetTargetFile(namePrefix, targetExtension, null, YadaAttachedFile.YadaAttachedFileType.DEFAULT);
// File targetFile = new File(targetFolder, targetFilenamePrefix + "." + targetExtension);
if (needToDeleteOriginal) {
// Just move the old file to the new destination
Files.move(managedFile.toPath(), targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
} else {
// Copy bytes
try (InputStream inputStream = new FileInputStream(managedFile); OutputStream outputStream = new FileOutputStream(targetFile)) {
IOUtils.copy(inputStream, outputStream);
} catch (IOException e) {
throw e;
}
}
} else {
// Transformation: copy with imagemagick
// If desktopWidth is null, the image original size does not change.
// The file name is like "product-mydoc_2631_640.jpg"
File targetFile = yadaAttachedFile.calcAndSetTargetFile(namePrefix, targetExtension, desktopWidth, YadaAttachedFile.YadaAttachedFileType.DESKTOP);
resizeAndConvertImageAsNeeded(managedFile, targetFile, desktopWidth);
yadaAttachedFile.setFilename(targetFile.getName());
if (mobileWidth==null) {
yadaAttachedFile.setFilenameMobile(null); // No mobile image
} else {
targetFile = yadaAttachedFile.calcAndSetTargetFile(namePrefix, targetExtension, mobileWidth, YadaAttachedFile.YadaAttachedFileType.MOBILE);
resizeAndConvertImageAsNeeded(managedFile, targetFile, mobileWidth);
}
if (needToDeleteOriginal) {
log.debug("Deleting original file {}", managedFile.getAbsolutePath());
managedFile.delete();
}
}
return yadaAttachedFileRepository.save(yadaAttachedFile);
}
/**
* Perform image format conversion and/or resize, when needed
* @param sourceFile
* @param targetFile
* @param targetWidth resize width, can be null for no resize
*/
private void resizeAndConvertImageAsNeeded(File sourceFile, File targetFile, Integer targetWidth) {
if (targetWidth==null) {
// Convert only
Map<String,String> params = new HashMap<>();
params.put("FILENAMEIN", sourceFile.getAbsolutePath());
params.put("FILENAMEOUT", targetFile.getAbsolutePath());
boolean convert = yadaUtil.exec("config/shell/convert", params);
if (!convert) {
log.error("Image not copied when making attachment: {}", targetFile);
}
} else {
// Resize
Map<String,String> params = new HashMap<>();
params.put("FILENAMEIN", sourceFile.getAbsolutePath());
params.put("FILENAMEOUT", targetFile.getAbsolutePath());
params.put("W", Integer.toString(targetWidth));
params.put("H", ""); // the height must be empty to keep the original proportions and resize based on width
boolean resized = yadaUtil.exec("config/shell/resize", params);
if (!resized) {
log.error("Image not resized when making attachment: {}", targetFile);
}
}
}
}
|
when yadaAttachedFile is null return an image data
|
YadaWeb/src/main/java/net/yadaframework/components/YadaFileManager.java
|
when yadaAttachedFile is null return an image data
|
<ide><path>adaWeb/src/main/java/net/yadaframework/components/YadaFileManager.java
<ide>
<ide> protected String COUNTER_SEPARATOR="_";
<ide>
<add> // Image to return when no image is available
<add> public final static String NOIMAGE_DATA="data:image/jpeg;base64,/9j/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP/sABFEdWNreQABAAQAAAA6AAD/4QMxaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI/PiA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJBZG9iZSBYTVAgQ29yZSA1LjYtYzEzOCA3OS4xNTk4MjQsIDIwMTYvMDkvMTQtMDE6MDk6MDEgICAgICAgICI+IDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+IDxyZGY6RGVzY3JpcHRpb24gcmRmOmFib3V0PSIiIHhtbG5zOnhtcD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLyIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bXA6Q3JlYXRvclRvb2w9IkFkb2JlIFBob3Rvc2hvcCBDQyAyMDE3IChNYWNpbnRvc2gpIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOkM0MzIwODI4RDk5ODExRTc5NkJEQUU4MkU3NzAwMUNEIiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOkM0MzIwODI5RDk5ODExRTc5NkJEQUU4MkU3NzAwMUNEIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6RDQyMjJGN0ZEOTBBMTFFNzk2QkRBRTgyRTc3MDAxQ0QiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6RDQyMjJGODBEOTBBMTFFNzk2QkRBRTgyRTc3MDAxQ0QiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz7/7gAhQWRvYmUAZMAAAAABAwAQAwMGCQAAJ/IAADkCAABIi//bAIQABwUFBQUFBwUFBwoGBQYKCwgHBwgLDQsLCwsLDREMDAwMDAwRDQ8QERAPDRQUFhYUFB0dHR0dICAgICAgICAgIAEHCAgNDA0ZEREZHBYSFhwgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg/8IAEQgDwAPAAwERAAIRAQMRAf/EANQAAQADAQEBAQEAAAAAAAAAAAAFBgcEAwIBCAEBAAAAAAAAAAAAAAAAAAAAABAAAQQBAwQCAgICAgMAAAAAAwECBAUAEzQVECAzFBESYDJQITEiMCWQwNARAAECAgUICAQFBAIDAQAAAAECAwARECExcRIgQbHRIjJyM1GBkcHhQqITYaGSBGBSgiNzMFCyFGJDkMDw8RIBAAAAAAAAAAAAAAAAAAAA0BMBAAEBBgYCAwEBAAMBAAAAAREAEPAhMUFRIGGBkaGxccEwYNFQ4ZDA0PH/2gAMAwEAAhEDEQAAAP6RAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPEhCZOgAEQepJAAiiMPk7yZPoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEcZwTJfwAUI7S4A8CiEaS59kUfZeyRAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAI4zg+i6FiAKEdpcAZ6fBfToB8lJIc0o9gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAARxnBbCsGknUChHaXAijPDSztAB8GZFmLUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACOM4NTKAepfwUI7S4FUK8aYAACkHKaCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACOM4NUOYzcuZYihHaXAphHGiAAAqBDGkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAjjODVD0KuVQ0kph2lwKiQhpIAAKUcJoYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAI4zg1Q9D8M8PU+jtLgQxQTTTqAB+GaE8W4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEcZwaoegOIzc/SyFwPwzk9y+n2AVArRpR1AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAjjODVD0AKuU8tBcAchQTyJw+yIOMvJMgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHMVwtR9AH4VckSYAPkgiLPk7yfPcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAz4nixkcUM6jQwACiEaaAdoBymeFhLYAAfhWyunACQLKWEAzg8QAAX0kAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADNSxFoIszs+jRiQAOYzM+DSTvAKmQB4Gnn2ACikQWwlgQxUy3FmBlxYSaAAJE9QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADNSxFoIszsmiQLcAVkhyFNJO8H4ZmW0qBbiwgEGUU0UkQAVoqhp5+mXFuLGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZqWItBFmdl4KoaWAZ2WUoxpJ3ghyiGnlUIk0UAoZ+F9AAPg8joBlxbixgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGaliLQRZnZqRmJoZInKZyaQZeaSd4KKehdjiM0NGJIGZlhLWAAAAZcdp2gA6S3AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAzUsRaCLM7NWKOdhbirnGW0y40k7zwMwLaSYKSSxdgZkWMtQBlR8AGjEkZcSZJAA9yygAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAzUsRaCLM7NWIUp5phnJcDvMuNJO8rBUToAPg8jTz2M+OkvAByA8TODRiSMuLcWMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAzUsRaCLM7NWPwy8u5TDTjxMuNJO8zYnC2gHmZgWws5XSmmlHUADxMtNGJIy4txYwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADNSxFoIszs1Y+ijkQTxcTwMuNJPMzo0s7QAUoiTSz8M/OQuBMH6RZViKNIO0y4tBPAAHseoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABmpYi0EWZ2asfRClBNFJM8DLjSSsHCaIAARhnRoBMHyVUrhzA9ScLWdgMuPAAAFyLMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAc5+HQfoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABzEOTR7ghj7JYAA8CFJ09AQJ1EoADwIUnj7Is+CXAAABzEOTR7gAgjzAPQkzqAIY9iTAABAnwAACaPcAAAAAAAAAAAAAAAAAAAAAAAAApxWS1lsBVCtGnn6ACqleNLBHmcHUaYfoBGGdGonuUg8S+gAAApxWS1lsABmR+nUfh4nEXQsQM9JAuQAAMuPY6QAC6HcAAAAAAAAAAAAAAAAAAAAAAAAD5MwJ4gzTT6OUzIvxMgAzQsZaAU08CGLwTQBGGdGonuUg8S+gAAHyZgTxBmmn0AZkWcswBWCpmon0Z6SBcgAAZcW4sYAAAAAAAAAAAAAAAAAAAAAAAAAAAIIphphmJdSdBQT2LwARZnppx0HwZgXchjlL8ARhnRqJ7lIPEvoAABBFMNMMxLqToBmRZyzAEWZ2amepnpIFyAABlxbixgAAAAAAAAAAAAAAAAAAAAAAAAAAAoB3FxKWcJoQIMo5qB6ApR4l7BAlNNPI0zs0w6wRhnRqJ7lIPEvoAABQDuLiUs4TQgDMiwlhB4lSPovgM9JAuQAAMuLQTwAPo6QAAAAAAAAAAAAAAAAAAAAAAAAcpmRpB3kaZyaUdx8mYlwLAfBmBeiYBnxIlwBmxNFvBGGdGonuUg8S+gAA5TMjSDvI0zk0o7gZkcgAPsvZNAz0kC5AAAy48AADuNKAAAAAAAAAAAAAAAAAAAAAAAABUyqEqARRZS5AqBHl/IEqBph+nIZmdx7g4j5NPPojDOjUT3KQeJfQAAVMqhKgEUWUuQMyLOWYHmQRSTQiVM9JAuQAAMuLcWMAAAAAAAAAAAAAAAAAAAAAAAAAAH4ZmS5KgEWQJp56HEZsacUglC1gqRBFpAPkphdiwEYZ0aie5SDxL6AAfhmZLkqARZAmnnoZkWcswAM3Jkt5npIFyAABlxbixgAAAAAAAAAAAAAAAAAAAAAAAAAAhygmnHQAeBmJcixgzwlirmmHSfhmRZi0AAohzGiEYZ0aie5SDxL6AAQ5QTTjoAPAzEuRYzMizlmAPAzMtpZjPSQLkAADLi3FjAAAAAAAAAAAAAAAAAAAAAAAAAABRD4L8AAUU4TSAV8pRMF9BClCNPOgAEMUA0c+TOjUT3KQRBLgAmiBPgvwABRThNIMyOg7gfBFHsaIepnpzkmACwksZcdp2gAE+TAAAAAAAAAAAAAAAAAAAAAAAAKqS5JgAEeQZZz1PgqxNEkCFOUsgAB+FVJU7SuFpPshCOAAJUjCXJMAAjyDLOV48QD6O4mT7BXjkAAJokirnmAACZJMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//aAAgBAgABBQH/AOwgf//aAAgBAwABBQH/AOwgf//aAAgBAQABBQH/ANIDMVoR81FwBxyB9kiyBGJFnClr2GsogcddsxLtMFbRCY1zXJ+TWGzytl+sXstt5SeToYwwDl2BpSsY8jmVMx2Op5aYWOYCx5Rozokwctn5LYbPFarVqpeqzrbbyk8nSwlrJNChvlvCAUdnRzWvbY1/r4Az45AlaYX5JYbPLOJ9hCI4JI52yRdLbeUnkyyNoxMiASPH7Hta9pxKA1Kb+vySw2eMRFHPiLFNWy/WL0tt5SeTLt2RGaknuuWfWTVv+s38ksNnjP0lxmygva5jqqXqsy23lJ5MuvNW73uu/wBoO8/JLDZ4z9Mton2QRHBJHO2SK23lJ5Mu2/7QXfSX3XTvk9a37TfySw2eM/TFRFSfEWKatl+sW23lJ5MtA6sRF+FjGSQHsVURJRvYkUof9vySw2eM/TpLjNlBe1zHPe4mUnkz/OTYqxTQJqxHsewjetlYI9GMcR8YCRw/klhs8Z+nW2ifZMpPJ0kxxyRyYhorgyTR1ZdFTFu34efJkYMRDOgQGxU/JZAtcPB41PhvVURUfSIroUD03dXNa5DVEcmOpTYlLIwVKJMEEQW/+SuXJkNlU5SEZk9zmRPalZGmnYftnzDLK9qVkNznResk2gD25WVMt7ydqqiJJuGMwk+WXFc52I5zcFPliyLbDMvU0qShfalZ7UrPalZ7UrPalZ7UrILnPifhs3d0n6ZZbLHIrVgm1ovWQXQAiOe7IOz63R8BHUzAkUJWOR7eyxnqdwQkO8FMJqNgxG46DEdkinYqPY4bqmYpE6H81ZDjyA8XBzi4OcXBzi4OcXBwY2CZ+Gzd3SfpllsstA6Z6U399bk3wOuD91yDs+n+Mkm1z1IfrFkC0D05/uDrayNGOiK5YUVsUXZcRkcMBFCb/PQ/mpdv+Jzd3SfpllsstA6kOIbQk9bE2tLhB0q7IOz6Wh9GKNikeNiDZdB+HQD6EnrbE+8upFqSu17GkaMAQ9T+al2/4nN3dJ+mWWyxWIQT2KN8A2tFySXQAEanMZESPkHZ9LY+pJpw/c+TA+xHyAf2I3SWv2lUjf8AiP5os80RnNSs5qVnNSs5qVke1kFP+HTd3Sfpllssb+tuHTk0pv8AbLo3wymD9jH8OQdnhioETnK50CXCjR+Tg5ycHJeksinP9D9JSfEmkX/Xq/8AbrX7LD+aFXe4Pg84PODzg8DUaJfw6bu6T9Mstljf1tg6kWIbQkZYG1pVaHRiH8OQdnlyf4Y1jnr6snPVk56snHRzsRj1G8REMLLQenMpyfST19SLnqRcLFjIPK/ZYfzUu3/E5u7pP0yy2WN/V7Ue0jFEQcv/AKyOJTn/AMYfw5B2eTT+xJpQ9hGIRhGKIlMf5ZlxH1BDe4b48hkkXYXxZX7LD+al2/4nN3dJ+mWWyxv65cB+khDPQFMH5Jh/DkHZ2B9CLkQOhH7LgH0NEP68jFRFSfBdFfGklivBaxi40g3457G4aziCyVYmk4xjiOiDcGNh/NUGCMHtRc9qLntRc9qLntRcYQZPw6bu6T9Mstljf1y1DqRcrg6MTD+HIOzuD/c1cHWldtgDXi5WH1ouOa17ZNPhY5w9WDIRQVByZHihjJ0P5u6k8X5S4AHYkaOmIiJ/4ppB2Rhc1FwJmHF0PZgjlj2IJJO0xmAFzUXBv1GdH28Vjos8Mt/YYrQC5qLjXI9uSbAMQkeyBJJ/wSDsjC5qLgTMOLsJbRhk5qLnNRc5qLjbiIuCkgP2HswRyxZwpbu51vGY7mouc1Fzmouc1Fzmouc1FwJWnF/J3J/l/wAL8Ux+t0DAFUJkVFTsujf1ED7EjpOP68ZEVcim9c6L89ljssB4cut1U7z/AILk/wAv+F+KY/bK3QYkiQnGTs4ydj4MtmIqtWtnqfrZ76k8vcfzBiSJDeMnZxk7OMnZxk7OMnZDG8Ub+Sc5GtMVTFfE/wCqjlUBkVHJkkKHAqKi1ZtWL2TDa8imB8N6XJ/sSpChTFGoi1Z9aN1sdlgPDl1uqned7nI1piqYr4n/AFUcqgMio5OsrdUni628VqjERwiIqOTLPfUnl7j+al2/8xbH04wBKYyjaoyjURKk+rH6WgNKVUG+kjrYm0IrUVzgCQAcc5GNMRTFqg6UW5D9TVZ9GT1sdlgPDl1uqned9sfTjAEpjKNqjKNREqT6sfrK3VJ4utkqJCwbfqPLPfUnl7j+al2/8xaH1pVMH5flyH6mrT6ErpbA1YzHqN43oRnS4N9jVINWT0tz6ccAlMZERqWAdeL/AIyKb2AdLHZYDw5dbqp3nfaH1pVMH5flyH6mrT6ErrK3VQYQx+1Fz24uPsIbEnz1lrWRFOXpZ76k8vcfzVBgjB7UXPai57UXPai4kmO5f5KSbQAv95BDoRssA68XIZ/Yj4qI5DiUBqg33j49yMaUilJWA0YvSzPrSqYPy/pND68mmP8ADuljssB4cut1U7zukm0AL/eQQ6EbLAOvFyGf2I/SVuuxio10KfGMnSz31J5e4/m7YW7/AJK6PiL8Lyc7OTnZyc7pTH+pOlyD4dVm0pWW5tOPFD7B/wDHSUb14+CmyQM5OdnJzsNILIcEqhK1yPbljssB4cut1U7zuuj4i/C8nOzk52cnO6Ux/qTpK3VL4ujhjdkyrERv9tWvkrJBlnvqTy9x/NS7f+WX+skm1zwK5kkXCxs4WNnCxsn1rIwREcIg3tIzJgfYjoqtUBUMG0NqyqUH9dLo/wDcOP7J+FjZwsbOFjYtLH+HNVrqg+oDLHZYDw5dbqp3nav9ZJNrngVzJIuFjZwsbOFjZPrWRgiI4RBvaRmSt1SeLsnNRsukVfvlnvqTy9x/NS7f+WtD6MVEVygEgA9TDQwnNVjqc/3D0sgaMqtlacT/AGe6OFAAxVREkmU56YPwzstgaUmvPoSssdlgPDl1uqnedtofRioiuUAkAHqYaGE5qsdTn+4clbqk8XUxmAGUilJSiVB5Z76k8vcfzUu3/lrY+pJqw6srttgacmCf15PS3B9wI5USqBqyulofSioiqscSAD2WgNWLkE/sRrHZYDw5dbqPIfGJzUrOalZzUrOalZXTSy1tj6kmrDqyu22BpyYJ/Xk5K3UWcWI3mpWczKxbiWuGOY6xYhZTxjaJmWe+iyyRHc1KzmpWc1KzmpWV8oksWH80WeaIzmpWc1KzmpWc1KzmpWV0sktn8g6lVzoUJIbe2ZESWPg8Exwx49iEZweQoaQ2dJsBZjwVCBN2qiKi0ifMKE6HkgPsB4PGN+jMm13tl4PODzg84PODyFA9NXUqudChJDb2zIiSx8HgmOGMtPql4PODzg8Skbg6mIzGtaxOkqq9k/B5wecHnB5weQonpjx9N938HnB5wecHnB5weQofpt/9Hn//2gAIAQICBj8BYQP/2gAIAQMCBj8BYQP/2gAIAQEBBj8B/wDSA1OqmUprMo3XOwa4Dre6em0X5PtLSoqt2QNcKDYUMNZxS7icmWPGroRX4RstE3mWuK2ZXK8Ikols/wDId4jEk4kmwj8Tu3UYVn9lypXwPTknhEO3CkuOGSRBG4zmQO+MLaSpXQIrARxHVOKsCrjrAiTqCnR2xiaVVnTmMTTsrG8j8TO3UYVCRGaP9dZ/cb3finwyDwiHbhTsn9lFSNcS3W07yu4RgaThHzN9JSsYkm0GPeZ5JtH5fCA6i0fP4Ql1G6oT/Ert1CfumxtJA9y7phLiKlJrEJdRntHQeik8Ih24UKlvL2B12/KhDfmtVebckoUJpUJEQto+Qy1Qtg5ttOg/iV26gA1giJDlLrQe7qjCs/suVK+B6aTwiHbhQ0i8mGk5ioTy0r/OnRCOhU0ns/Ert1CbhBbO9ak9BgoUJKTURH+us/uN7vxT4UHhEO3Chvh74a69By2bld0M8X4lduoTcKP9psbSeZd0wlxFSk1iEuoz2joPRB4RDtwoaX8CIaP/ACl21ZaEflTpMN/CZ7B+JXbqE3CiRrBiQ5S60Hu6owrP7LlSvgemDwiHbhQSN5vb1xMWiEOjzCu/PkzNQELdzE1XCoQ4+bBsDSfxK7dQm4Uls71qT0GChQkpNREArMyBh6hDtwokbIKf+tVaD8PCMKq2V7w6PjAWg4kmwjIP27BmnzrGgQG0CalVAQloeW09Jz/iV26hNwyP9psbSeZd00O3Cn23Oo9BiSxNOZYsMTaVh6Rm7I220quMtcbLIB+Kp9wiS1SR+VNQjA2nEo5hGNe08bT0fAfiZbU8OMSnHP8AR4wB0VZEjWDBKHcKTYMM5fOFKx48QlZLvORhUMSTaDE2yWj8Kx2RsuJN8xritaBdPVE3VlfwFWuMLSQgfD/yWOpS6sJCjIBRh33FqXIiWIz00OKQSlQlIio2xznPqMIU46pSJ7QUokSOUsNOKShGyAkkWW2fGOc59RhpSjiUU1k5C3fyiq/NHOc+owpl1ZWVVpKjOy0ZUzUBnjD9uPcP5jZ4xW4QOhNWiNok3xski6KnCR0Kr0wEPD21nP5TqyFgPLACj5j0xznPqMc5z6jHOc+oxznPqMc5z6jHOc+ow0pRKlEVk3/g57jMO3ih24aRQUm0VGG1+YDCq8VZC3fyiq/NHSo0M8OQj7ccau6HlD/qTi+eqcJdTagzgLTWlQmMktNH9hPq8I9toYlGJvqxq/KKhriplPWJ6YkWU9QlojF9scKvyKs7YKFjCpNoMf6zhmpO4fh0dVLnErTClPJxKCpCsjN8I5fqVrjl+pWuOX6la45fqVrjl+pWuA22JITYPwc9xmHbxQ7cNIoCxuupB67DDjBz7adByEMi1ZxG4Q86bG21SvIoZ4aZmyFu5lGq7NBWoc4/IVQtr8pquzQWTvNWXHIwJ33aurPASKyagICf+w1rV8ckfcp3kVKuhDibUmcToc4laYXx9w/Cj3GYdvFDtw0igODeakeo1GG3MwO1cajkLPlRsDq8YUTvOJUs9lXyoZ4aSBvObA7/AJQltNqzIQltO6kSHVCPuBn2Fd0JUd1Wyq45BTmbAHfAUbGxi67BlFCxNKqiI/bQE/ECvtpc4laYXx9w/Cj3GYdvFDtw0ijAqxSZHrEKQq1JIPVDavMBhVeKFu50iq/NCG86zLXCwLAggdlDPDT7Y3Wqus2wXjY0KrzQtvzSmm8WUIUd5Oyq8UvH/mrTDyuEaf6TnErTBQ2EkEz2p6xG632HXG632HXG632HXG632HXDbakowrUAZA6/we9xmHbxQ7cNIoF0e4LHRPrFRhxg59saDQhgebaNwshTxsbEhefCHOFWihnhoW6bECcFSqyqswEKck4dpWyq3sjm+lWqOb6VaoWpg4m1GYzW3wWTuu2Xil4f81aYeHD35Cr8hq7voc4laYLnuYMJwylPvEc/0eMc/wBHjHP9HjHP9HjCHfdngM5YfH8HvcZh28UO3DSKBdGMbzRxdVhhtzMDXcajQtXlTsp6oRPeXtnrs+UOcKtFDPDQhgWq2lXCyMKAVK6BXHJX9Jjkr+kxyV/SYxKaWlItJSYC07yTMQl1NixOhfQuSh/9fBbP/Ymq8V5HJR9Ijko+kQshlE8J8ooau76HOJWmF8fcPwo9xmHbxQ7cNIoF0FCt1QkeuFNqtQSOyPf86E4f1WCENfmNd2eJCyHOFWihnhoW55bE3CF/cHgTpOQptW6oSMKbVagyMK+3NqdpNxt+dAfTvNW3GEuJqUkzEB1Ge0dB6MlfCdFDV3fQ5xK0wvj7h+FHuMw7eKHbhpFAuoDgsdHzFUFjyFQXC3zYgYReaHOFWihnhhZG8rYT1+FCG84G1ebclLwscFd48IQ7mBkq420EGsG0RiTWwrdPR8DGNs3pNhiTn7S/jZ2xNCgq4zjaUBeYqV7iuhFfzsjBy2vyjPeYCEDEo2AQ22veSK6HOJWmFhxxKDjsUQMwjnN/UI5zf1COc39QjnN/UI5zf1CJtrCwLcJno/Bz3GYdvFDtw0igXUFQ3mji6s9CB5lbZ6/ChzhVooZ4YDIsbFd5hAO6jbV1eOUsDeTtJ6qADvt7J7qClYxJNoMYvtj+hXcY/dQU/HN20ybSVn4CcTePtJ6LTEmk151G00ucStOW7xDR+KtptKr0iKmkD9IiQqH/AIpi65ujMLY3XOwa4S6jdV00lpxK8SegDXHtICgqU9qWs5SnV7qeiN1zsGuErAIChORtpKcKzhMpgCWmChsKCgJ7Uu4nJU6uZSm2UbrnYNcBYsUJ9tAbcCiSMWzLWOiPaQlQVbtAa/6Jdc3RmFsbrnYNcJdRuq6clTZSuaCUmQGbrjdc7Brjdc7Brjdc7BrivEm8apx+0sKPRn7MhTK0rKkynICVYn0wpLYUCkTOKXcTllJSuaTKwa43XOwa43XOwa43XOwa43XOwa43XOwa43XOwa4S6mYSqyf90QwLE7SrzZE8xqhf254099KPuBwK7oQ6PIZ64BFhsyUfbjPtq7oQ35SZquFtK1+bdTeYqrz9kIdzA13Z4mLMh24aaG+FOihP8Y0mBwn+ihgWJ2lXmyJ5jVC/tzxp78l7+RWmCWUYgKjWBpjlepOuOV6k64mppXVXoiYqUI9h4/ujdV0+NLv6f8RDnCNOW5xK0wVMoxJBkawNMcr1J1xyvUnXHK9Sdccr1J1xyvUnXDbbgktIrH9zKlVBNZhbptWZwhcttJ9w3Kq0ShDo8p+WeAoVg1ihbX5hVfmiRtEAHeb2D3fLJW5mnJNwshf3B82ym7PSlgWI2lXnwhalCaUpI+qrROFNm1BlASd5rZN2bIduGmhvhTooT/GNJgcJ/oFSqgmswt02rM4QuW2k+4blVaJQh0eU/LPAUKwaxkPfyK0w7xDRkf7KBJaal/EGEuJtQZwFCw10O/p/xEOcI05bnErTC+PuH959sbztXVnhDQ85lrgtS2CMMvhZCm1WoMo9s7zVXVmpKhuu7QvzwWjY6PmLMhZG8vYT1+EBKayahCGh5BLXQVqqSkTMKdVaszgKO87tdWaEvCxwSN48ICTuO7JvzZDtw00N8KdFCf4xpMDhP9D2xvO1dWeENDzmWuC1LYIwy+FkKbVagyj2zvNVdWbIe/kVph3iGjIdnnkPnQhJtSAKHf0/4iHOEactziVphfH3D+8kDdb2B3/OFvmxOym820JeFjgkbx4Qme45sHrs+dOMbzW11Z4S4neSZjqhLid1QmOulLIsbEzefCPcO61X15qfbG86ZdQthDQ85lrgJFQFQhYG8naT1RMWwh3ORXfnpduGmhvhTooT/GNJgcJ/oEDdb2B3/OFvmxOym820JeFjgkbx4Qme45sHrs+eQ9/IrTDgcWlBKqsRA0xzm/qEc5v6hEy6Dw16ICEDCymuu0npMB1Q/abM7z0Uu/p/xEOcI05bnErTCw44lBx2KIGYRzm/qEc5v6hHOb+oRzm/qEBKXUFRsAUP7mt3OkVX5ombYQjzbyrzQtI3k7SbxQhzzWKvFBSawajC2j5DLVBaNrR+RoK1bqRM9UKcVaszgE7zm2e75Uqlut7A6rfnC3zYnZTebaVt+Wc03GF/bnzbSb89Ltw00N8KdFCf4xpMDhOWt3OkVX5ombYQjzbyrzQtI3k7SbxQhzzWKvFL38itOSCoYki1PTAaSPaWLEZuql39P+IhzhGnLc4lacpnjH9zR9uONXdAItEc30p1RzfSnVHN9KdVCmDYutN48KUfcDzbKr80JB3XNg93zo9sbzpl1C2ENZia7s8SFC3c4FV+aj22l4U2ykO8RzfSnVHN9KdUBTysShVOQGiEOptQZwFprSoTFDtw00N8KdFCf4xpMDhOWj7ccau6ARaI5vpTqjm+lOqOb6U6qFMGxdabx4UvfyK0w5xDRTtJCrxBX9uMDo8osMdBETVzEbKtdDv6f8RDnCNOW5xK0wvj7h/d5myFu5lGq7NBddKkick4ZeMb6+0ao319o1Rvr7RqgOtFSpGSsUvCEuJtQZwlxO6oTFC2/NKabxZExURCHR5hPrzwoDdb2B3/ADhf3B4E99KPtxxq7oS1Ym1RHRG+vtGqN9faNUb6+0aoMlrnmmRqgpVURUYLR3mtBoduGmhvhTooT/GNJgcJypmyFu5lGq7NBddKkick4ZeMb6+0ao319o1Rvr7RqgOtFSpGSsUvCEuJtQZwlxO6oTFD38itMO8Q0ZLoFmKfbXDozSBod/T/AIiHOEactziVphfH3D+7kDec2B3/ACgAVk1CENDyiXXnyFtGxYlBSqpSTIwpg2t1i4+NKpbq9tPXb84eB/6dpPXm7Y6VKPzMIaHlFd+eiZsELd/Mars0LfNqtlNwtycY3Xa+vPCSdxeyrroduGmhvhTooT/GNJgcJyiBvObA7/lAArJqEIaHlEuvPkLaNixKClVSkmRhTBtbrFx8aHv5FaYd4hoyC44ZJH/0oU4q1ZJhx4+cyHV/+0O/p/xEOcI05bnErTC+PuH939sbrVXXngKO61tG/Nle4N10T6xbCFndOyq40h0bzR+RggGpVR0wFHda2uvNSUjed2RdniQtMIaHlHzz5JUN5raF2ehCzvDZVeIduGmhvhTooT/GNJj3UAFVm1G632HXG632HXG632HXG632HXCw4EjBKWGee8mPbG61V154CjutbRvzZXuDddE+sWwhZ3TsquND38itMKS2EkKMzin3ERut9h1xut9h1xVgFw1mJurKv/uiMKBJHmXmEJbRUlIkKHf0/wCIhSmwCVCRxeEo3W+w643W+w643W+w643W+w64UtwAFKpbN3XQ5xK0wUNhJBM9qesRut9h1xut9h1xut9h1xut9h1xut9h1wtTgAKTIYfGf9xKlPzKqzseMKGLGpZrMpa8oIJwEGYVKcc/0eMJQpWMpEsVk6FIVuqEj1xz/R4wU4salGZVKWulKvdwJSJBOGfeIS6p3GEGeHDK7PlSNhip6QzbPjCh7mNK80pV9phTM8OPPbHP9HjCUW4QBO6gOe5gknDLDPOT0jpjn+jxjn+jxjn+jxjn+jxjn+jxhZ9zHjlmlZ1mCpT8yqs7HjChixqWazKWvKCCcBBmFSnHP9HjCUKVjKRLFZOFue9LGoqlh6TPpjn+jxjn+jxjn+jxit6dyfGJqm4f+Rq+UowoASkWAUqe93DilVhnYJdMc/0eMc/0eMc/0eMc/wBHjHP9HjCkY8eIznKWuhS/eliJO709cc/0eMc/0eMc/wBHjHP9HjHP9HjHP9HjCk48eIzslr/9Ho//2gAIAQIDAT8Q/wDsIH//2gAIAQMDAT8Q/wDsIH//2gAIAQEDAT8Q/wDSAwbBgiucYSlhNmVkIwIZgJx4WYoEkEPyKTukgDPDDgGWLlSCoGZe2HlQXD+T6FFuON5fYpARvi8nmgYsQgR+E/Z7vzLMlCEmWh/fDfu1XHu2+RN10A3aIK6gzOfX1Q5iyFXxQMy2mLQDKTZZoY2TkpK+BI1JgJxMfmK56HOJzNz9mu/MsboVCsys9QYnQ++Bfu1XHu2ZYuVKjEUNHfr9UrDgm+YtGAajqbrW00oIBI9GsmKkZqnKimw+JoNVyaTSYTk6j8OH7Ld+ZZkkEDWBHTrypY5cn08msuoxqBmrb92q492xkqIVuaGw0kQl3xv44ZXQI1HCscNQO5mupSq2w5P/AA/ZbvzLAcARHJEpGLicpr8qZKEJMtD+7b92q492x4PJjdg+6BfFMchl8HGIBkz8pPUUhdHrEnkP2W78yy/tqgPOhuX8aV05RolZ6gxOh92L92q492x4Wg3yoTNvxqPO+yk8Db+y3fmWX9tZpoABro6deVLHLk+nk1l1GNQM1V+7Vce7Ypolb8InuhXwIXXzxiNuvyn8p9q16n3+y3fmWX9tYiABCOSNIxcTlNflTJQhJlof3V67Vce7YxSVB8GHgzSAkJI7JWbXgTQYDvwokgSrkBUZaa+MikQMAXmx2IP2W78yy/trYDzobl/GldOUaJS0QQXPQq492xAISiEdRqKrib7Z85KcSqwM1t+6NmOUSNqgS4BU9Ywyib227U+rgN2sT+HzGK7/ALLd+ZZf23BpoABro6deVlx7tqsuZ57xWO0t4YPKpu5cxfKwoaHN296OPmCDxQWzbMpPnV6tEXZYPLsVKwHAZG5L+zfDsMxjOUlSo4kzAl8EcCIAEI5I1J5SvgHSYTT5F0MqGeARiwABE5jSy46eyx80Nwvl9BRrhm6fsUiQ7Rj1cVbq5hi/Lm9f/JYWlIGBOQDSYyFLCRyk2HdCTQwmCVev7ozFJkAFRYwmeJUvREXMhG6r1/dMyAUKrzXgJ/NIuqwHdq5f3QXonCHIKumPTiRKAlTABq0mlHDGJ8jOjzPtWPp5piVd0vumJV3SeqVI1rx+NR0oo2GJ4ny+3ABiEAwBYGNXr+6vX91ev7q9f3V6/ur1/dMDArVcWa/p1w71d+zwMhZh0Nkwamhn7AvnPgJLXZa5B1agRKV+dVs8TwZluwfdSdZaN4YdlMmSQ3DM6mFL9BNySTgyqDokKajV9KDp2GQbroUQdrLDynN4oKEnI+yg4Edp94U4SGMkrkZjrNJXVGYGkMJy2ac/o5W3VuqbbbZCDqN+IggggiJxIkWDPNl/Trh3q79ngZQajoEf9OtRNYADmf8ADgm1/AvdfFRCzxzweJs8TaoFIBKugUz+Yi6DAdijxoRh1wg+adPJxOqxXZqSMp7R2Z4FmoVMZhz/AF1oyZYDNXAKHoMO62fBpwghlw6tgX4aniRwNTU6mFCAGTiWXVury36pXDvV37PAyiJPYQ+hqYWCF0ZPBATKdHC+1QYj4QUeAs8TbI6O2Ob0rF4J8yxQcQL4hFQlwPUMV1J7VNyG+86MPA5Lh05pL3QmJdeOc8UFzKtR+KOx/Yd2a26t1eW/VK4d6u/Z4GSUp6agrCq+clFSaz4A4/Odh6seth5NHGUadYXF0MaBeCQ0BhZ4m3GiR976HSoS5TszsTZC5K8i7srJ1SX3nUhtdHYPgQUUash5P4rq3VKP9QmYDTY4SZMmTHKQpMLpL/T7h3q79ngZeO9VAhBLg5NQIYAHmf8ACyQmKT6HcvioLZhu6HvV3brPE2Z3Ihu6HVwpNpSm6stTGijJCwCTQBbFEsdKcMMyQDJqW+B7R3JtRzT36Lciu5/HB5T3web9rLq3UnUlLAZnmVKjKjKjKi+SblZhymX6fcO9Xfs8DLx3qpIJAPl/+nSpFYOXhk2QcynSw+WWsIIup0Vd26zxNk28WDoDq+qLrWRqY5FXX+quv9Vdf6pLigEB8qUk8CbmMlZckBtOZ0sREQPVEPg0aSBjsHieBRlVc3/nV3/qhoQok4g8rPN+1l1bq8t+qVw71d+zwMvHeqHyVFyENZ8keqKjlcT0s75waAWmLuXagABAIA0Cru3WeJsgJmXjjvnUqTLEu8uAOJV8SRWfBPmGKn7iw9h09rEGTgR73RpWYJuY0xmzX1Fw37us837WXVury36pXDvV37PAy8d6sg1Ex77xFCPNnyCR1w7VFj7CPYPNl3brPE1MKO+ZnpJsn8iZ3Xk8MS8t2/mFNIfUL+qEQTEcRokwSJkjmNJwUbt13rJicMYHMowR1jHPkfuKNg7qXpQMk7ge6FTZsJc50ejEzfEeSkhrgErRxhEAyCqxPWy6t1K2qRImZClXr+6vX91ev7q9f3V6/uj1WQgA85P6dcO9Xfs8DLx3qyLUgPh4M9LJLIHq4ztAsu7dZ4mpm57u/BFQ6lOhl7wOKIUn1tHUksmpPZzN2sMIGASJUqnBxmude9KoOajwGFvJVjelOBNXAvQwOrWD4sMR8zbdW79VAg2qLYNuCDbgg2sg2qDjg2qA4VZe3R7KTl7cP6oGADICDhg2qDaoNqg2qDaoNqg2/wDE3LAoGCpWIJSwnMnHIZiGEYm3BGyVIiSJIqfroQAxoRicUyccpmZYAmNWwmAoowgEkmFtU6UkKhiSThWDMVAkmMOEGECIiuKGEpvYTmMAEc4E42FB+EIhU1oE1QZAIPhfhlgUDBUrEEpYTmTjkMxDCMTwqrtEFVDEnbgJkyacfKH7U5/zHHch4MfgYzACJG9DDVABCxhxhztDSGRjDjkyZMmTJmGDIiOcYwv+pNvBi6A6HuoAzGQ6KQp5Kxl5/wAT6bZAuX9X7rOSFBqZDqUicgKNR4YXccByMPtTrk+QX8UAEGAWQKwzwh2zpGAoGBsJXoFKJoiavDwoAJKJE1HgvTZZd2y0nfu34Zt4MXQHQ91AGYyHRSFPJWMvP+J9PDeu+pmlkwC46i2AANgjNH9qCotkTBErPgE7EzHk/HExdW6seJBmImMRvxQQQQQTEIJBhlcyT/TTaEpsBLWdyIbGh0MKYPiF4blaLcoa5B1KcmGIajiNiLzSToMV3pEEJCOiVP6V6Bj9HDD7L8C/qok4qbkxXV9WzPwYOx29qnIOfORRnblu8OfWp1y33PbDpwXpssu7ZaTv3b8CbQlNgJazuRDY0OhhTB8QvDcrRblDXIOpTkwxDUcR4L138IEMiCDCRAvMaReCHo5dayyEHw4/iiYurdXlv9mxoh+3j9DrWYiKdjV0KbGIrmGDtWZ9Hzhz61ivL9/H7nS2KkF1mXvj1qfERDv+E8Eqo7xn7SaHKWBurAVkRgnd1dXGx7JBtgJazZBDYcjoVGKEn4eGPWoZZx6fmHap0wH3PfDrwXpssu7ZaTv3b8GNEP28fodazERTsauhTYxFcwwdqzPo+cOfWsV5fv4/c6cF67+EDZQD5RQKwYrTZ6J8gH4omLq3V5b/AGaQ098M/pUe8GbqLoe7IZ3j/MO1Y4R/RLUiUvD54H76VhUC+ZTWJwL4hNs8/vP4hWAEn38Ps9LYN49pfQrMTFJoauhRkwwDQMCo1SfWznUkoVCQGRNEoxNEdjh5W3pssu7ZaTv3b8Ehp74Z/So94M3UXQ92QzvH+Ydqxwj+icC9d9FzQhRI0kVev7q5f3SKBaYr5U4BEDkGB4KhpGS5DiD2/jiYurdStqkSJmQpV6/ur1/dXr+6vX903FIRq7AP+mT+Yi6rAd2kpSUyrqtS+QjyD2yshBJeZjqSVliZ1NjMPHPfOwyYaDqJCVnhoHczXUqfExDvnmbF+hTchLWZ9Hyly6VEaO2OT2tgSnvuZSPeDN1Ow92wkR7KO2VTjw7NgOpHa29Nll3bLSd+7cZP5iLqsB3aSlJTKuq1L5CPIPbKyEEl5mOpJWWJnU2Mw8c987b138I1WSigNpMaB+SHiXzIn8cTF1buK4d/9PMt2D7ps5Akg4nJ4IoolVVzccMPVSbw4uVj39LYk4DpMV1J7VLqB6jj9FkK0e0voUo267HHwoAAQGAGhYexLneHk0qqrK4q1h5a4ni5so2xRRZLDIJmMBWVwIbmp1MKeyAbcSSy9Nll3bLSd+7ceZbsH3TZyBJBxOTwRRRKqrm44Yeqk3hxcrHv6W3rvolIg2qDagYOcwH3QkSSdjjR2ihkEvwckSjby0u6ZdR+KJi6t1A66qDaoNqg2qDaoNv9JAUgEq6BTP5iOwwHYp+IYoSGayauBWrVhnAFKBySDVhWQvD0cutKzIviSbIXJXkX8UBRXI6iVpOaDTIOjUupPqH/AOFQA59nN+rZFcu7kfdSYqTmACXPtwK1avCki5DOkxQMpaGyMJU65WDvHZksvTZZd2y0nfu3EgKQCVdApn8xHYYDsU/EMUJDNZNXArVqwzgClA5JBqwrIXh6OXWlZkXxJNl67+IDAfkhzxPLQted8in3+KJi6t1eW/16R0P0HN6UZcoA1XArKCNJrmXV4M+kS2XJ6NFNIFsjDUwce7bWoOI/mHlRvZQk6hw7HmuY64pWklCNViurYiaAVXQKReTIdBgO1RzxZup3PrhwCg+3h9XrU1o7FkejDZemyy7tlpO/duKR0P0HN6UZcoA1XArKCNJrmXV4M+kS2XJ6NFNIFsjDUwce7bWL138IEEw9V0HNrMuqbSzFAxAHxzl7+H4omLq3V5b/AF7GiR7+P0OlR8kOkw88enFhVHpL6NSChvDL0zti3OI7T5ik2Ag7gnsFQSkp+B749LZqQ3WYvth1oEUoAGq1onYprmXV4YqS3SZe2Nk6JPwk9TGr02WXdstJkxAYBSH4ThJkyZMfaHANWfIVjRI9/H6HSo+SHSYeePTiwqj0l9GpBQ3hl6Z2XrvoYaoCZCMLQTpkQF3X7KFuTIcA+BgUTQDjGB9vKi7hg/tsQQtQFIGcJcImTJk4xXIEIg6u6y6t1Sj/AFCZgNNjiJkyZMmFLcBCEnGX+gZjDPSpNqU1Ky1L8IdEDAiebii6tljRIkzsGA8zhkYTEthRSouQiwQvyEAICJyWrDmICys6mFYciOYTdLJx4kASEI6jSkziwZwbTXTbnTDWjSbBhwQjlJtYOOnJqYRNmjfahEieICIiLESgGli+TOpNqU1Ky1L8IdEDAiebii6tljRIkzsGA8zhkYTEtfOLTEkJjvwCImcYcg9qnQCaQdlB3CgAA6FvgNpBmhtxCIiPZFZwCInZZtpLjiUxxxEREdJ2llwRv/6PQ//Z";
<add>
<ide> // TODO distinguere tra mobile portrait e mobile landscape
<ide> // TODO le dimensioni mobile/desktop devono essere configurabili
<ide> // TODO mantenere l'immagine caricata nella versione originale
<ide> */
<ide> public String getMobileImageUrl(YadaAttachedFile yadaAttachedFile) {
<ide> if (yadaAttachedFile==null) {
<del> return null;
<add> return NOIMAGE_DATA;
<ide> }
<ide> String imageName = yadaAttachedFile.getFilenameMobile();
<ide> if (imageName==null) {
<del> return null;
<add> return NOIMAGE_DATA;
<ide> }
<ide> return computeUrl(yadaAttachedFile, imageName);
<ide> }
<ide> */
<ide> public String getDesktopImageUrl(YadaAttachedFile yadaAttachedFile) {
<ide> if (yadaAttachedFile==null) {
<del> return null;
<add> return NOIMAGE_DATA;
<ide> }
<ide> String imageName = yadaAttachedFile.getFilenameDesktop();
<ide> if (imageName==null) {
<ide> */
<ide> public String getFileUrl(YadaAttachedFile yadaAttachedFile) {
<ide> if (yadaAttachedFile==null) {
<del> return null;
<add> return NOIMAGE_DATA;
<ide> }
<ide> String imageName = yadaAttachedFile.getFilename();
<ide> if (imageName==null) {
<del> return null;
<add> return NOIMAGE_DATA;
<ide> }
<ide> return computeUrl(yadaAttachedFile, imageName);
<ide> }
<ide> }
<ide> }
<ide>
<del>
<ide> }
|
|
Java
|
apache-2.0
|
01dc046f7df5ba4e78962a572f0dd1e7a0a51390
| 0 |
CS-SI/Orekit,petrushy/Orekit,CS-SI/Orekit,petrushy/Orekit
|
/* Copyright 2002-2021 CS GROUP
* Licensed to CS GROUP (CS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* CS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.orekit.files.ccsds.ndm.odm.ocm;
import java.io.IOException;
import org.orekit.files.ccsds.definitions.TimeConverter;
import org.orekit.files.ccsds.section.AbstractWriter;
import org.orekit.files.ccsds.utils.generation.Generator;
import org.orekit.utils.units.Unit;
/** Writer for orbit determination data.
* @author Luc Maisonobe
* @since 11.0
*/
class OrbitDeterminationWriter extends AbstractWriter {
/** Orbit determination block. */
private final OrbitDetermination od;
/** Converter for dates. */
private final TimeConverter timeConverter;
/** Create a writer.
* @param orbitDetermination orbit determination to write
* @param timeConverter converter for dates
*/
OrbitDeterminationWriter(final OrbitDetermination orbitDetermination,
final TimeConverter timeConverter) {
super(OcmDataSubStructureKey.od.name(), OcmDataSubStructureKey.OD.name());
this.od = orbitDetermination;
this.timeConverter = timeConverter;
}
/** {@inheritDoc} */
@Override
protected void writeContent(final Generator generator) throws IOException {
// orbit determination block
generator.writeComments(od.getComments());
// identifiers
generator.writeEntry(OrbitDeterminationKey.OD_ID.name(), od.getId(), false);
generator.writeEntry(OrbitDeterminationKey.OD_PREV_ID.name(), od.getPrevId(), false);
if (od.getMethod() != null) {
final StringBuilder builder = new StringBuilder();
builder.append(od.getMethod().getName());
if (od.getMethod().getTool() != null) {
builder.append(':');
builder.append(od.getMethod().getTool());
}
generator.writeEntry(OrbitDeterminationKey.OD_METHOD.name(), builder.toString(), false);
}
// time
generator.writeEntry(OrbitDeterminationKey.OD_EPOCH.name(), timeConverter, od.getEpoch(), false);
generator.writeEntry(OrbitDeterminationKey.DAYS_SINCE_FIRST_OBS.name(), od.getTimeSinceFirstObservation(), Unit.DAY, false);
generator.writeEntry(OrbitDeterminationKey.DAYS_SINCE_LAST_OBS.name(), od.getTimeSinceLastObservation(), Unit.DAY, false);
generator.writeEntry(OrbitDeterminationKey.RECOMMENDED_OD_SPAN.name(), od.getRecommendedOdSpan(), Unit.DAY, false);
generator.writeEntry(OrbitDeterminationKey.ACTUAL_OD_SPAN.name(), od.getActualOdSpan(), Unit.DAY, false);
// counters
generator.writeEntry(OrbitDeterminationKey.OBS_AVAILABLE.name(), od.getObsAvailable(), false);
generator.writeEntry(OrbitDeterminationKey.OBS_USED.name(), od.getObsUsed(), false);
generator.writeEntry(OrbitDeterminationKey.TRACKS_AVAILABLE.name(), od.getTracksAvailable(), false);
generator.writeEntry(OrbitDeterminationKey.TRACKS_USED.name(), od.getTracksUsed(), false);
generator.writeEntry(OrbitDeterminationKey.MAXIMUM_OBS_GAP.name(), od.getMaximumObsGap(), Unit.DAY, false);
// errors
generator.writeEntry(OrbitDeterminationKey.OD_EPOCH_EIGMAJ.name(), od.getEpochEigenMaj(), Unit.METRE, false);
generator.writeEntry(OrbitDeterminationKey.OD_EPOCH_EIGMED.name(), od.getEpochEigenMed(), Unit.METRE, false);
generator.writeEntry(OrbitDeterminationKey.OD_EPOCH_EIGMIN.name(), od.getEpochEigenMin(), Unit.METRE, false);
generator.writeEntry(OrbitDeterminationKey.OD_MAX_PRED_EIGMAJ.name(), od.getMaxPredictedEigenMaj(), Unit.METRE, false);
generator.writeEntry(OrbitDeterminationKey.OD_MIN_PRED_EIGMIN.name(), od.getMinPredictedEigenMaj(), Unit.METRE, false);
generator.writeEntry(OrbitDeterminationKey.OD_CONFIDENCE.name(), od.getConfidence(), Unit.PERCENT, false);
generator.writeEntry(OrbitDeterminationKey.GDOP.name(), od.getGdop(), Unit.ONE, false);
// parameters
generator.writeEntry(OrbitDeterminationKey.SOLVE_N.name(), od.getSolveN(), false);
generator.writeEntry(OrbitDeterminationKey.SOLVE_STATES.name(), od.getSolveStates(), false);
generator.writeEntry(OrbitDeterminationKey.CONSIDER_N.name(), od.getConsiderN(), false);
generator.writeEntry(OrbitDeterminationKey.CONSIDER_PARAMS.name(), od.getConsiderParameters(), false);
generator.writeEntry(OrbitDeterminationKey.SENSORS_N.name(), od.getSensorsN(), false);
generator.writeEntry(OrbitDeterminationKey.SENSORS.name(), od.getSensors(), false);
// observations
generator.writeEntry(OrbitDeterminationKey.WEIGHTED_RMS.name(), od.getWeightedRms(), Unit.ONE, false);
generator.writeEntry(OrbitDeterminationKey.DATA_TYPES.name(), od.getDataTypes(), false);
}
}
|
src/main/java/org/orekit/files/ccsds/ndm/odm/ocm/OrbitDeterminationWriter.java
|
/* Copyright 2002-2021 CS GROUP
* Licensed to CS GROUP (CS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* CS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.orekit.files.ccsds.ndm.odm.ocm;
import java.io.IOException;
import org.orekit.files.ccsds.definitions.TimeConverter;
import org.orekit.files.ccsds.section.AbstractWriter;
import org.orekit.files.ccsds.utils.generation.Generator;
import org.orekit.utils.units.Unit;
/** Writer for orbit determination data.
* @author Luc Maisonobe
* @since 11.0
*/
class OrbitDeterminationWriter extends AbstractWriter {
/** Orbit determination block. */
private final OrbitDetermination od;
/** Converter for dates. */
private final TimeConverter timeConverter;
/** Create a writer.
* @param orbitDetermination orbit determination to write
* @param timeConverter converter for dates
*/
OrbitDeterminationWriter(final OrbitDetermination orbitDetermination,
final TimeConverter timeConverter) {
super(OcmDataSubStructureKey.od.name(), OcmDataSubStructureKey.OD.name());
this.od = orbitDetermination;
this.timeConverter = timeConverter;
}
/** {@inheritDoc} */
@Override
protected void writeContent(final Generator generator) throws IOException {
// orbit determination block
generator.writeComments(od.getComments());
// identifiers
generator.writeEntry(OrbitDeterminationKey.OD_ID.name(), od.getId(), false);
generator.writeEntry(OrbitDeterminationKey.OD_PREV_ID.name(), od.getPrevId(), false);
generator.writeEntry(OrbitDeterminationKey.OD_METHOD.name(), od.getMethod().getName(), false);
// time
generator.writeEntry(OrbitDeterminationKey.OD_EPOCH.name(), timeConverter, od.getEpoch(), false);
generator.writeEntry(OrbitDeterminationKey.DAYS_SINCE_FIRST_OBS.name(), od.getTimeSinceFirstObservation(), Unit.DAY, false);
generator.writeEntry(OrbitDeterminationKey.DAYS_SINCE_LAST_OBS.name(), od.getTimeSinceLastObservation(), Unit.DAY, false);
generator.writeEntry(OrbitDeterminationKey.RECOMMENDED_OD_SPAN.name(), od.getRecommendedOdSpan(), Unit.DAY, false);
generator.writeEntry(OrbitDeterminationKey.ACTUAL_OD_SPAN.name(), od.getActualOdSpan(), Unit.DAY, false);
// counters
generator.writeEntry(OrbitDeterminationKey.OBS_AVAILABLE.name(), od.getObsAvailable(), false);
generator.writeEntry(OrbitDeterminationKey.OBS_USED.name(), od.getObsUsed(), false);
generator.writeEntry(OrbitDeterminationKey.TRACKS_AVAILABLE.name(), od.getTracksAvailable(), false);
generator.writeEntry(OrbitDeterminationKey.TRACKS_USED.name(), od.getTracksUsed(), false);
generator.writeEntry(OrbitDeterminationKey.MAXIMUM_OBS_GAP.name(), od.getMaximumObsGap(), Unit.DAY, false);
// errors
generator.writeEntry(OrbitDeterminationKey.OD_EPOCH_EIGMAJ.name(), od.getEpochEigenMaj(), Unit.METRE, false);
generator.writeEntry(OrbitDeterminationKey.OD_EPOCH_EIGMED.name(), od.getEpochEigenMed(), Unit.METRE, false);
generator.writeEntry(OrbitDeterminationKey.OD_EPOCH_EIGMIN.name(), od.getEpochEigenMin(), Unit.METRE, false);
generator.writeEntry(OrbitDeterminationKey.OD_MAX_PRED_EIGMAJ.name(), od.getMaxPredictedEigenMaj(), Unit.METRE, false);
generator.writeEntry(OrbitDeterminationKey.OD_MIN_PRED_EIGMIN.name(), od.getMinPredictedEigenMaj(), Unit.METRE, false);
generator.writeEntry(OrbitDeterminationKey.OD_CONFIDENCE.name(), od.getConfidence(), Unit.PERCENT, false);
generator.writeEntry(OrbitDeterminationKey.GDOP.name(), od.getGdop(), Unit.ONE, false);
// parameters
generator.writeEntry(OrbitDeterminationKey.SOLVE_N.name(), od.getSolveN(), false);
generator.writeEntry(OrbitDeterminationKey.SOLVE_STATES.name(), od.getSolveStates(), false);
generator.writeEntry(OrbitDeterminationKey.CONSIDER_N.name(), od.getConsiderN(), false);
generator.writeEntry(OrbitDeterminationKey.CONSIDER_PARAMS.name(), od.getConsiderParameters(), false);
generator.writeEntry(OrbitDeterminationKey.SENSORS_N.name(), od.getSensorsN(), false);
generator.writeEntry(OrbitDeterminationKey.SENSORS.name(), od.getSensors(), false);
// observations
generator.writeEntry(OrbitDeterminationKey.WEIGHTED_RMS.name(), od.getWeightedRms(), Unit.ONE, false);
generator.writeEntry(OrbitDeterminationKey.DATA_TYPES.name(), od.getDataTypes(), false);
}
}
|
Fixed forgotten tool while writing OD_METHOD.
|
src/main/java/org/orekit/files/ccsds/ndm/odm/ocm/OrbitDeterminationWriter.java
|
Fixed forgotten tool while writing OD_METHOD.
|
<ide><path>rc/main/java/org/orekit/files/ccsds/ndm/odm/ocm/OrbitDeterminationWriter.java
<ide> // identifiers
<ide> generator.writeEntry(OrbitDeterminationKey.OD_ID.name(), od.getId(), false);
<ide> generator.writeEntry(OrbitDeterminationKey.OD_PREV_ID.name(), od.getPrevId(), false);
<del> generator.writeEntry(OrbitDeterminationKey.OD_METHOD.name(), od.getMethod().getName(), false);
<add> if (od.getMethod() != null) {
<add> final StringBuilder builder = new StringBuilder();
<add> builder.append(od.getMethod().getName());
<add> if (od.getMethod().getTool() != null) {
<add> builder.append(':');
<add> builder.append(od.getMethod().getTool());
<add> }
<add> generator.writeEntry(OrbitDeterminationKey.OD_METHOD.name(), builder.toString(), false);
<add> }
<ide>
<ide> // time
<ide> generator.writeEntry(OrbitDeterminationKey.OD_EPOCH.name(), timeConverter, od.getEpoch(), false);
|
|
Java
|
apache-2.0
|
ea3590e3ca35e85c6e749f3cfb3174fc7b8c6a63
| 0 |
archiecobbs/jsimpledb,permazen/permazen,archiecobbs/jsimpledb,permazen/permazen,archiecobbs/jsimpledb,permazen/permazen
|
/*
* Copyright (C) 2015 Archie L. Cobbs. All rights reserved.
*/
package io.permazen.parse.expr;
import io.permazen.parse.ParseException;
import io.permazen.parse.ParseSession;
import io.permazen.parse.Parser;
import io.permazen.parse.SpaceParser;
import io.permazen.util.ParseContext;
import java.util.regex.Matcher;
/**
* Parses type cast expressions.
*/
public class CastExprParser implements Parser<Node> {
public static final CastExprParser INSTANCE = new CastExprParser();
private final SpaceParser spaceParser = new SpaceParser();
@Override
public Node parse(ParseSession session, ParseContext ctx, boolean complete) {
// Try cast
final int start = ctx.getIndex();
final Matcher castMatcher = ctx.tryPattern("(?s)\\(\\s*(" + LiteralExprParser.CLASS_NAME_PATTERN + ")\\s*\\)\\s*(?=.)");
while (castMatcher != null) {
final String className = castMatcher.group(1).replaceAll("\\s", "");
// Parse target of cast
final Node target;
try {
target = this.parse(session, ctx, complete); // associates right-to-left
ctx.skipWhitespace();
return new CastNode(new ClassNode(className, true), target);
} catch (ParseException e) {
ctx.setIndex(start);
}
}
// Try lambda
try {
return LambdaExprParser.INSTANCE.parse(session, ctx, complete);
} catch (ParseException e) {
ctx.setIndex(start);
}
// Parse unary
return UnaryExprParser.INSTANCE.parse(session, ctx, complete);
}
}
|
permazen-parse/src/main/java/io/permazen/parse/expr/CastExprParser.java
|
/*
* Copyright (C) 2015 Archie L. Cobbs. All rights reserved.
*/
package io.permazen.parse.expr;
import io.permazen.parse.ParseException;
import io.permazen.parse.ParseSession;
import io.permazen.parse.Parser;
import io.permazen.parse.SpaceParser;
import io.permazen.util.ParseContext;
import java.util.regex.Matcher;
/**
* Parses type cast expressions.
*/
public class CastExprParser implements Parser<Node> {
public static final CastExprParser INSTANCE = new CastExprParser();
private final SpaceParser spaceParser = new SpaceParser();
@Override
public Node parse(ParseSession session, ParseContext ctx, boolean complete) {
// Try cast
final int start = ctx.getIndex();
final Matcher castMatcher = ctx.tryPattern("(?s)\\(\\s*("
+ LiteralExprParser.CLASS_NAME_PATTERN + ")\\s*\\)\\s*(?=.)");
while (castMatcher != null) {
final String className = castMatcher.group(1).replaceAll("\\s", "");
// Parse target of cast
final Node target;
try {
target = this.parse(session, ctx, complete); // associates right-to-left
ctx.skipWhitespace();
return new CastNode(new ClassNode(className, true), target);
} catch (ParseException e) {
ctx.setIndex(start);
}
}
// Try lambda
try {
return LambdaExprParser.INSTANCE.parse(session, ctx, complete);
} catch (ParseException e) {
ctx.setIndex(start);
}
// Parse unary
return UnaryExprParser.INSTANCE.parse(session, ctx, complete);
}
}
|
Code formatting tweak.
|
permazen-parse/src/main/java/io/permazen/parse/expr/CastExprParser.java
|
Code formatting tweak.
|
<ide><path>ermazen-parse/src/main/java/io/permazen/parse/expr/CastExprParser.java
<ide>
<ide> // Try cast
<ide> final int start = ctx.getIndex();
<del> final Matcher castMatcher = ctx.tryPattern("(?s)\\(\\s*("
<del> + LiteralExprParser.CLASS_NAME_PATTERN + ")\\s*\\)\\s*(?=.)");
<add> final Matcher castMatcher = ctx.tryPattern("(?s)\\(\\s*(" + LiteralExprParser.CLASS_NAME_PATTERN + ")\\s*\\)\\s*(?=.)");
<ide> while (castMatcher != null) {
<ide> final String className = castMatcher.group(1).replaceAll("\\s", "");
<ide>
|
|
Java
|
mit
|
5ea3f68c5229913a44671d8fa43425cd76c62357
| 0 |
akhilesh0707/IconEditText,xiaoshi316/IconEditText,bestwpw/IconEditText,Ryan257/IconEditText,KyleBanks/IconEditText,Juneor/IconEditText,ErNaveen/IconEditText,aaaliua/IconEditText,datalink747/IconEditText,android-gems/IconEditText,nguyenhongson03/IconEditText,Chonlakant/IconEditText,honeyflyfish/IconEditText,msoftware/IconEditText
|
package com.kylewbanks.android.iconedittext;
import android.content.Context;
import android.content.res.TypedArray;
import android.text.Editable;
import android.text.InputType;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
/**
* IconTextEdit
*
* An EditText with an Icon beside it.
*
* Created by kylewbanks on 15-09-05.
*/
public class IconEditText extends LinearLayout {
private static final String TAG = IconEditText.class.getSimpleName();
/**
* UI Constants
*/
private static final float ICON_WEIGHT = 0.15f;
private static final float EDIT_TEXT_WEIGHT = 0.85f;
private static final String HINT_PREFIX = " ";
/**
* Resource pointer for the Icon to display.
*/
private Integer _iconResource;
/**
* The Hint text to display.
*/
private String _hint;
/**
* Indicates if the EditText is for a password.
*/
private boolean _isPassword = false;
/**
* UI Components
*/
private ImageView _icon;
private EditText _editText;
/**
* IconTextEdit Constructor
* @param context
*/
public IconEditText(Context context) {
this(context, null);
}
/**
* IconTextEdit Constructor
* @param context
* @param attrs
*/
public IconEditText(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
/**
* IconTextEdit Constructor
* @param context
* @param attrs
* @param defStyleAttr
*/
public IconEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.parseAttributes(context, attrs);
this.initialize();
}
/**
* Parses out the custom attributes.
*
* @param context
* @param attrs
*/
private void parseAttributes(Context context, AttributeSet attrs) {
Log.d(TAG, "parseAttributes()");
if (attrs == null) {
return;
}
TypedArray a = context.getTheme()
.obtainStyledAttributes(attrs, R.styleable.IconEditText, 0, 0);
try {
_iconResource = a.getResourceId(R.styleable.IconEditText_iconSrc, 0);
_hint = a.getString(R.styleable.IconEditText_hint);
_isPassword = a.getBoolean(R.styleable.IconEditText_isPassword, false);
Log.d(TAG, "{ _iconResource: " + _iconResource + ", _hint: " + _hint + ", _isPassword: " + _isPassword + "}");
} catch (Exception ex) {
Log.e(TAG, "Unable to parse attributes due to: " + ex.getMessage());
ex.printStackTrace();
} finally {
a.recycle();
}
}
/**
* Initializes the Icon and TextEdit.
*/
private void initialize() {
Log.d(TAG, "initialize()");
// Mandatory parameters
this.setOrientation(LinearLayout.HORIZONTAL);
// Create the Icon
if (_icon == null) {
_icon = new ImageView(this.getContext());
_icon.setLayoutParams(
new LayoutParams(0, LayoutParams.MATCH_PARENT, ICON_WEIGHT)
);
_icon.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
if (_iconResource != null && _iconResource != 0) {
_icon.setImageResource(_iconResource);
}
this.addView(_icon);
}
// Create the EditText
if (_editText == null) {
_editText = new EditText(this.getContext());
_editText.setInputType(
_isPassword ? InputType.TYPE_TEXT_VARIATION_PASSWORD : InputType.TYPE_TEXT_FLAG_AUTO_CORRECT
);
_editText.setLayoutParams(
new LayoutParams(0, LayoutParams.MATCH_PARENT, EDIT_TEXT_WEIGHT)
);
if (_hint != null) {
_editText.setHint(String.format("%s%s", HINT_PREFIX, _hint.toLowerCase()));
}
this.addView(_editText);
}
}
/**
* Convenience Accessor to the underlying EditText's 'getText()' method.
*
* @return
*/
public Editable getText() {
return _editText.getText();
}
/**
* Returns the underlying EditText.
*
* @return
*/
public EditText getEditText() {
return _editText;
}
/**
* Returns the underlying ImageView displaying the icon.
*
* @return
*/
public ImageView getImageView() {
return _icon;
}
}
|
src/main/java/com/kylewbanks/android/iconedittext/IconEditText.java
|
package com.kylewbanks.android.iconedittext;
import android.content.Context;
import android.content.res.TypedArray;
import android.text.Editable;
import android.text.InputType;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
/**
* IconTextEdit
*
* An EditText with an Icon beside it.
*
* Created by kylewbanks on 15-09-05.
*/
public class IconEditText extends LinearLayout {
private static final String TAG = IconEditText.class.getSimpleName();
/**
* UI Constants
*/
private static final float ICON_WEIGHT = 0.15f;
private static final float EDIT_TEXT_WEIGHT = 0.85f;
private static final String HINT_PREFIX = " ";
/**
* Resource pointer for the Icon to display.
*/
private Integer _iconResource;
/**
* The Hint text to display.
*/
private String _hint;
/**
* Indicates if the EditText is for a password.
*/
private boolean _isPassword = false;
/**
* UI Components
*/
private ImageView _icon;
private EditText _editText;
/**
* IconTextEdit Constructor
* @param context
*/
public IconEditText(Context context) {
this(context, null);
}
/**
* IconTextEdit Constructor
* @param context
* @param attrs
*/
public IconEditText(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
/**
* IconTextEdit Constructor
* @param context
* @param attrs
* @param defStyleAttr
*/
public IconEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.parseAttributes(context, attrs);
this.initialize();
}
/**
* Parses out the custom attributes.
*
* @param context
* @param attrs
*/
private void parseAttributes(Context context, AttributeSet attrs) {
Log.d(TAG, "parseAttributes()");
if (attrs == null) {
return;
}
TypedArray a = context.getTheme()
.obtainStyledAttributes(attrs, R.styleable.IconEditText, 0, 0);
try {
_iconResource = a.getResourceId(R.styleable.IconEditText_iconSrc, 0);
_hint = a.getString(R.styleable.IconEditText_hint);
_isPassword = a.getBoolean(R.styleable.IconEditText_isPassword, false);
Log.d(TAG, "{ _iconResource: " + _iconResource + ", _hint: " + _hint + ", _isPassword: " + _isPassword + "}");
} catch (Exception ex) {
Log.e(TAG, "Unable to parse attributes due to: " + ex.getMessage());
ex.printStackTrace();
} finally {
a.recycle();
}
}
/**
* Initializes the Icon and TextEdit.
*/
private void initialize() {
Log.d(TAG, "initialize()");
// Mandatory parameters
this.setOrientation(LinearLayout.HORIZONTAL);
// Create the Icon
if (_icon == null) {
_icon = new ImageView(this.getContext());
_icon.setLayoutParams(
new LayoutParams(0, LayoutParams.MATCH_PARENT, ICON_WEIGHT)
);
_icon.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
if (_iconResource != null && _iconResource != 0) {
_icon.setImageResource(_iconResource);
}
this.addView(_icon);
}
// Create the EditText
if (_editText == null) {
_editText = new EditText(this.getContext());
_editText.setInputType(
_isPassword ? InputType.TYPE_TEXT_VARIATION_PASSWORD : InputType.TYPE_TEXT_FLAG_AUTO_CORRECT
);
_editText.setLayoutParams(
new LayoutParams(0, LayoutParams.MATCH_PARENT, EDIT_TEXT_WEIGHT)
);
if (_hint != null) {
_editText.setHint(String.format("%s%s", HINT_PREFIX, _hint.toLowerCase()));
}
this.addView(_editText);
}
}
/**
* Convenience Accessor to the underlying EditText's 'getText()' method.
*
* @return
*/
public Editable getText() {
return _editText.getText();
}
}
|
Added accessors for the underlying EditText/ImageView
|
src/main/java/com/kylewbanks/android/iconedittext/IconEditText.java
|
Added accessors for the underlying EditText/ImageView
|
<ide><path>rc/main/java/com/kylewbanks/android/iconedittext/IconEditText.java
<ide> return _editText.getText();
<ide> }
<ide>
<add> /**
<add> * Returns the underlying EditText.
<add> *
<add> * @return
<add> */
<add> public EditText getEditText() {
<add> return _editText;
<add> }
<add>
<add> /**
<add> * Returns the underlying ImageView displaying the icon.
<add> *
<add> * @return
<add> */
<add> public ImageView getImageView() {
<add> return _icon;
<add> }
<add>
<ide> }
|
|
JavaScript
|
mit
|
b1d67284ba0355f7b98f496e550bf85b7f51f5e7
| 0 |
mike-stumpf/chorus.js,mike-stumpf/chorus.js,mike-stumpf/chorus.js
|
/**
* helpers
*/
(function(){
//variables
var dictionary = _chorus.data.dictionary,
defaultConfig = _chorus.defaultConfig;
//functions
/**
* get a random string
* @param length
* @returns {*}
*/
this.generateRandomString = function(length){
var output;
for(output = ''; output.length < length;) {
output += Math.random().toString(36).substr(2, 1);
}
return output;
};
/**
* make a copy of a JS object
* @param from
* @param to
* @returns {*}
*/
this.cloneObject = function(from, to) {
if (from ==+ null || typeof from !== 'object'){
return from;
}
if (from.constructor != Object && from.constructor != Array){
return from;
}
if (from.constructor == Date || from.constructor == RegExp || from.constructor == Function || from.constructor == String || from.constructor == Number || from.constructor == Boolean){
return new from.constructor(from);
}
to = to || new from.constructor();
for (var name in from) {
to[name] = typeof to[name] == 'undefined' ? this.cloneObject(from[name], null) : to[name];
}
return to;
};
/**
* get the config value for the key passed or return the default if none available
* @param key
* @returns {*}
*/
this.getConfigValue = function(key){
if (typeof _chorus.config[key] !== typeof _chorus.defaultConfig[key]){
_chorus.events.sendMessage(dictionary.error_type+' '+key);
}
return typeof _chorus.config[key] === typeof defaultConfig[key]?_chorus.config[key]:defaultConfig[key];
};
/**
* get the object key given the value
* @param object
* @param value
* @returns {string}
*/
this.getKeyFromValue = function(object, value){
for(var prop in object) {
if(object.hasOwnProperty(prop)) {
if(object[prop] === value) {
return prop;
}
}
}
};
/**
* gets the size of a one dimensional object
* @param object
* @returns {number}
*/
this.countObjectLength = function(object){
var key,
i = 0;
for(key in object){
if (object.hasOwnProperty(key)){
i++;
}
}
return i;
};
/**
* capitalize all of the words in a string
* @param string
* @returns {string}
*/
this.capitalize = function(string){
return string.toLowerCase().replace( /\b\w/g, function (m) {
return m.toUpperCase();
});
};
this.mod = function(number,modulus) {
return ((number%modulus)+modulus)%modulus;
};
this.searchComplete = function(callback){
var configCallback = this.getConfigValue('searchCallback');
if (callback && typeof callback !== 'string') {
callback(_chorus.searchResult);
} else if (configCallback && typeof configCallback === 'string') {
window[configCallback](_chorus.searchResult);
}
_chorus.events.dispatchEvent(_chorus.data.customEvents.chorusSearchComplete, 'chorusJS has finished searching scales and chords');
};
}).apply(_chorus.logic.helpers);
/**
* notes
*/
(function(){
//variables
var dictionary = _chorus.data.dictionary,
notes = _chorus.data.notes,
events = _chorus.events,
helpers = _chorus.logic.helpers;
//functions
/**
* get the tone (int) given the note (char)
* @param note
* @returns {number}
*/
this.getToneByNote = function (note){
var tone = notes.letter[note.substring(0,1)],
start = 0;
while (note.indexOf('#',start)!==-1){
start = note.indexOf('#',start)+1;
tone++;
}
start = 0;
while (note.indexOf('b',start)!==-1){
start = note.indexOf('b',start)+1;
tone--;
}
return helpers.mod(tone,12);
};
this.sharpenTone = function(tone){
return helpers.mod(tone + 1,12);
};
this.flattenTone = function(tone){
return helpers.mod(tone - 1,12);
};
/**
* get the flat note from the int
* @param tone
* @returns {string}
*/
this.getFlatNoteByTone = function(tone){
return notes.tone[this.sharpenTone(tone)] + 'b';
};
/**
* get the sharp note from the int
* @param tone
* @returns {string}
*/
this.getSharpNoteByTone = function(tone){
return notes.tone[this.flattenTone(tone)] + '#';
};
/**
* return a note representation of the tone with both sharp and flat values (for the UI grid)
* @param tone
* @returns {*}
*/
this.getNoteByToneDisplay = function(tone){
var letter;
tone = helpers.mod(tone,12);
if (notes.tone.hasOwnProperty(tone)) {
letter = notes.tone[tone];
}
else {
letter = this.getFlatNoteByTone(tone)+' / '+this.getSharpNoteByTone(tone);
}
return letter;
};
/**
* get the note (char) from the tone (int)
* @param tone
* @returns {*}
*/
this.getNoteByToneDefault = function(tone){
var letter;
if (notes.tone.hasOwnProperty(tone)) {
letter = notes.tone[tone];
}
else {
letter = this.getSharpNoteByTone(tone);
}
return letter;
};
/**
* get the note (char) from the tone (int) and either make it sharp or flat by specifying the note
* @param tone
* @param letter
* @returns {*}
*/
this.getNoteByToneForce = function(tone,letter) {
var difference = tone - this.getToneByNote(letter);
if (difference > notes.count.tones/2) {
difference -= notes.count.tones;
}
if (difference < notes.count.tones/2*-1) {
difference += notes.count.tones;
}
if (difference !== 0) {
if (notes.tone.hasOwnProperty(tone)){
return false;
}
if (difference > 0) {
for (var i = 0; i < difference; i++) {
letter += '#';
}
}
else if (difference < 0) {
for (var j = 0; j > difference; j--) {
letter += 'b';
}
}
}
return letter;
};
/**
* get the order of the possible letters, starting at the letter passed in
* and looping around from 'G' to 'A' until reaching the initial letter
* @param letter
* @returns {Array.<*>}
*/
this.getNoteProgression = function(letter){
var pieces = 'ABCDEFG'.split(letter.replace(/b/g,'').replace(/#/g,'').toUpperCase());
return [letter].concat(pieces[1].split(''),pieces[0].split(''));
};
/**
* extract the tone (int) from a DOM classname string using the default class
* @param className
* @returns {string}
*/
this.getToneByClass = function(className){
return className.substring(dictionary.class_tone.length);
};
this.getPianoFromContainer = function(element){
var result;
if (element) {
for (var i = 0; i < element.childNodes.length; i++) {
if (element.childNodes[i].classList.contains(dictionary.class_piano_keyboard)){
result = element.childNodes[i];
}
}
}
return result;
};
/**
* get any tones that are selected in the dom
* @param container
*/
this.getSelectedNotes = function(container){
_chorus.searchResult.containers = [];
var noteData = [],
notes = {
rootTone: '',
selectedTones:[]
},
pianoKeyboard;
//search for selected notes by container id or class
if(container && container.length > 0){
var containerById = document.getElementById(container),
containerByClass = document.getElementsByClassName(container);
if (containerById){
if (containerById.classList.contains('piano')){
pianoKeyboard = this.getPianoFromContainer(containerById);
if (pianoKeyboard){
noteData.push(this.getTonesFromDOM(pianoKeyboard));
}
} else {
noteData.push(this.getTonesFromDOM(containerById));
}
}
else if (containerByClass){
for (var i = 0; i < containerByClass.length; i++){
if (containerByClass[i].classList.contains('piano')){
pianoKeyboard = this.getPianoFromContainer(containerByClass[i]);
if (pianoKeyboard){
noteData.push(this.getTonesFromDOM(pianoKeyboard));
}
} else {
noteData.push(this.getTonesFromDOM(containerByClass[i]));
}
}
}
else {
events.sendMessage(dictionary.error_notFound+'no container found with matching id or class');
}
}
//get selected notes if no container parameter was passed
else {
var containerByDefaultClass = document.getElementsByClassName(dictionary.class_instrument);
for (var j = 0; j < containerByDefaultClass.length; j++){
if (containerByDefaultClass[j].classList.contains('piano')){
pianoKeyboard = this.getPianoFromContainer(containerByDefaultClass[j]);
if (pianoKeyboard){
noteData.push(this.getTonesFromDOM(pianoKeyboard));
}
} else {
noteData.push(this.getTonesFromDOM(containerByDefaultClass[j]));
}
}
}
//remove duplicates
for (var k = 0; k < noteData.length; k++){
if (noteData[k].rootTone.length > 0 || noteData[k].selectedTones.length > 0){
_chorus.searchResult.containers.push(noteData[k].container);
}
if (noteData[k].rootTone.length > 0){
if (notes.rootTone.length < 1){
notes.rootTone = noteData[k].rootTone;
}
else {
events.sendMessage(dictionary.warning_multipleRootNotes);
}
}
for (var l = 0; l < noteData[k].selectedTones.length; l++){
if (notes.selectedTones.indexOf(noteData[k].selectedTones[l]) == -1){
notes.selectedTones.push(noteData[k].selectedTones[l]);
}
}
}
return notes;
};
/**
* find any selected frets or root note frets within a given DOM element
* @type {Function}
*/
this.getTonesFromDOM = function(element){
var parentClassList,
childClassList,
selectedTones = [],
rootTone = '';
if (element) {
for (var i = 0; i < element.childNodes.length; i++) {
if (element.childNodes[i]) {
parentClassList = element.childNodes[i].classList;
if (parentClassList.contains(dictionary.class_string)) {
for (var j = 0; j < element.childNodes[i].childNodes.length; j++) {
childClassList = element.childNodes[i].childNodes[j].classList;
if (childClassList.contains(dictionary.class_selected)) {
selectedTones.push(element.childNodes[i].childNodes[j].getAttribute('data-tone'));
}
else if (childClassList.contains(dictionary.class_root)) {
rootTone = element.childNodes[i].childNodes[j].getAttribute('data-tone');
}
}
} else if (parentClassList.contains(dictionary.class_piano_key)) {
if (parentClassList.contains(dictionary.class_selected)) {
selectedTones.push(element.childNodes[i].getAttribute('data-tone'));
}
else if (parentClassList.contains(dictionary.class_root)) {
rootTone = element.childNodes[i].getAttribute('data-tone');
}
}
}
}
} else {
events.sendMessage(dictionary.error_notFound+'no element found to search');
}
return {
container: element,
selectedTones: selectedTones,
rootTone: rootTone
};
};
/**
* return if the all of the selected tones exist in the scale or chord
* @param dataNotes
* @param selectedNotes
* @returns {boolean}
*/
this.tonesInScaleOrChordHelper = function(dataNotes, selectedNotes){
for(var i = 0; i < selectedNotes.length; i++){
if (dataNotes.indexOf(parseInt(selectedNotes[i])) === -1){
return false;
}
}
return true;
};
/**
* return if the scale contains the selected tones or not
* @param formula
* @param notes
* @returns {boolean}
*/
this.tonesInScaleOrChord = function(formula, notes){
if (notes.rootTone.length > 0){
if (formula.tones[0] == notes.rootTone){
return this.tonesInScaleOrChordHelper(formula.tones,notes.selectedTones);
}
else {
return false;
}
}
else {
return this.tonesInScaleOrChordHelper(formula.tones,notes.selectedTones);
}
};
}).apply(_chorus.logic.notes);
|
src/js/core/chorus.logic.js
|
/**
* helpers
*/
(function(){
//variables
var dictionary = _chorus.data.dictionary,
defaultConfig = _chorus.defaultConfig;
//functions
/**
* get a random string
* @param length
* @returns {*}
*/
this.generateRandomString = function(length){
var output;
for(output = ''; output.length < length;) {
output += Math.random().toString(36).substr(2, 1);
}
return output;
};
/**
* make a copy of a JS object
* @param from
* @param to
* @returns {*}
*/
this.cloneObject = function(from, to) {
if (from ==+ null || typeof from !== 'object'){
return from;
}
if (from.constructor != Object && from.constructor != Array){
return from;
}
if (from.constructor == Date || from.constructor == RegExp || from.constructor == Function || from.constructor == String || from.constructor == Number || from.constructor == Boolean){
return new from.constructor(from);
}
to = to || new from.constructor();
for (var name in from) {
to[name] = typeof to[name] == 'undefined' ? this.cloneObject(from[name], null) : to[name];
}
return to;
};
/**
* get the config value for the key passed or return the default if none available
* @param key
* @returns {*}
*/
this.getConfigValue = function(key){
if (typeof _chorus.config[key] !== typeof _chorus.defaultConfig[key]){
_chorus.events.sendMessage(dictionary.error_type+' '+key);
}
return typeof _chorus.config[key] === typeof defaultConfig[key]?_chorus.config[key]:defaultConfig[key];
};
/**
* get the object key given the value
* @param object
* @param value
* @returns {string}
*/
this.getKeyFromValue = function(object, value){
for(var prop in object) {
if(object.hasOwnProperty(prop)) {
if(object[prop] === value) {
return prop;
}
}
}
};
/**
* gets the size of a one dimensional object
* @param object
* @returns {number}
*/
this.countObjectLength = function(object){
var key,
i = 0;
for(key in object){
if (object.hasOwnProperty(key)){
i++;
}
}
return i;
};
/**
* capitalize all of the words in a string
* @param string
* @returns {string}
*/
this.capitalize = function(string){
return string.toLowerCase().replace( /\b\w/g, function (m) {
return m.toUpperCase();
});
};
this.mod = function(number,modulus) {
return ((number%modulus)+modulus)%modulus;
};
this.searchComplete = function(callback){
var configCallback = this.getConfigValue('searchCallback');
if (callback && typeof callback !== 'string') {
callback(_chorus.searchResult);
} else if (configCallback && typeof configCallback === 'string') {
window[configCallback](_chorus.searchResult);
}
_chorus.events.dispatchEvent(_chorus.data.customEvents.chorusSearchComplete, 'chorusJS has finished searching scales and chords');
};
}).apply(_chorus.logic.helpers);
/**
* notes
*/
(function(){
//variables
var dictionary = _chorus.data.dictionary,
notes = _chorus.data.notes,
events = _chorus.events,
helpers = _chorus.logic.helpers;
//functions
/**
* get the tone (int) given the note (char)
* @param note
* @returns {number}
*/
this.getToneByNote = function (note){
var tone = notes.letter[note.substring(0,1)],
start = 0;
while (note.indexOf('#',start)!==-1){
start = note.indexOf('#',start)+1;
tone++;
}
start = 0;
while (note.indexOf('b',start)!==-1){
start = note.indexOf('b',start)+1;
tone--;
}
return helpers.mod(tone,12);
};
this.sharpenTone = function(tone){
return helpers.mod(tone + 1,12);
};
this.flattenTone = function(tone){
return helpers.mod(tone - 1,12);
};
/**
* get the flat note from the int
* @param tone
* @returns {string}
*/
this.getFlatNoteByTone = function(tone){
return notes.tone[this.sharpenTone(tone)] + 'b';
};
/**
* get the sharp note from the int
* @param tone
* @returns {string}
*/
this.getSharpNoteByTone = function(tone){
return notes.tone[this.flattenTone(tone)] + '#';
};
/**
* return a note representation of the tone with both sharp and flat values (for the UI grid)
* @param tone
* @returns {*}
*/
this.getNoteByToneDisplay = function(tone){
var letter;
tone = helpers.mod(tone,12);
if (notes.tone.hasOwnProperty(tone)) {
letter = notes.tone[tone];
}
else {
letter = this.getFlatNoteByTone(tone)+' / '+this.getSharpNoteByTone(tone);
}
return letter;
};
/**
* get the note (char) from the tone (int)
* @param tone
* @returns {*}
*/
this.getNoteByToneDefault = function(tone){
var letter;
if (notes.tone.hasOwnProperty(tone)) {
letter = notes.tone[tone];
}
else {
letter = this.getSharpNoteByTone(tone);
}
return letter;
};
/**
* get the note (char) from the tone (int) and either make it sharp or flat by specifying the note
* @param tone
* @param letter
* @returns {*}
*/
this.getNoteByToneForce = function(tone,letter) {
var difference = tone - this.getToneByNote(letter);
if (difference > notes.count.tones/2) {
difference -= notes.count.tones;
}
if (difference < notes.count.tones/2*-1) {
difference += notes.count.tones;
}
if (difference !== 0) {
if (notes.tone.hasOwnProperty(tone)){
return false;
}
if (difference > 0) {
for (var i = 0; i < difference; i++) {
letter += '#';
}
}
else if (difference < 0) {
for (var j = 0; j > difference; j--) {
letter += 'b';
}
}
}
return letter;
};
/**
* get the order of the possible letters, starting at the letter passed in
* and looping around from 'G' to 'A' until reaching the initial letter
* @param letter
* @returns {Array.<*>}
*/
this.getNoteProgression = function(letter){
var pieces = 'ABCDEFG'.split(letter.replace(/b/g,'').replace(/#/g,'').toUpperCase());
return [letter].concat(pieces[1].split(''),pieces[0].split(''));
};
/**
* extract the tone (int) from a DOM classname string using the default class
* @param className
* @returns {string}
*/
this.getToneByClass = function(className){
return className.substring(dictionary.class_tone.length);
};
/**
* get any tones that are selected in the dom
* @param container
*/
this.getSelectedNotes = function(container){
_chorus.searchResult.containers = [];
var noteData = [],
notes = {
rootTone: '',
selectedTones:[]
};
//search for selected notes by container id or class
if(container && container.length > 0){
var containerById = document.getElementById(container),
containerByClass = document.getElementsByClassName(container);
if (containerById){
noteData.push(this.getTonesFromDOM(containerById));
}
else if (containerByClass){
for (var i = 0; i < containerByClass.length; i++){
noteData.push(this.getTonesFromDOM(containerByClass[i]));
}
}
else {
events.sendMessage(dictionary.error_notFound+'no container found with matching id or class');
}
}
//get selected notes if no container parameter was passed
else {
var containerByDefaultClass = document.getElementsByClassName(dictionary.class_instrument);
for (var j = 0; j < containerByDefaultClass.length; j++){
noteData.push(this.getTonesFromDOM(containerByDefaultClass[j]));
}
}
//remove duplicates
for (var k = 0; k < noteData.length; k++){
if (noteData[k].rootTone.length > 0 || noteData[k].selectedTones.length > 0){
_chorus.searchResult.containers.push(noteData[k].container);
}
if (noteData[k].rootTone.length > 0){
if (notes.rootTone.length < 1){
notes.rootTone = noteData[k].rootTone;
}
else {
events.sendMessage(dictionary.warning_multipleRootNotes);
}
}
for (var l = 0; l < noteData[k].selectedTones.length; l++){
if (notes.selectedTones.indexOf(noteData[k].selectedTones[l]) == -1){
notes.selectedTones.push(noteData[k].selectedTones[l]);
}
}
}
return notes;
};
/**
* find any selected frets or root note frets within a given DOM element
* @type {Function}
*/
this.getTonesFromDOM = function(element){
var classList,
selectedTones = [],
rootTone = '';
if (element) {
for (var i = 0; i < element.childNodes.length; i++) {
if (element.childNodes[i].classList.contains(dictionary.class_string)) {
if (element.childNodes[i]) {
for (var j = 0; j < element.childNodes[i].childNodes.length; j++) {
classList = element.childNodes[i].childNodes[j].classList;
if (classList.contains(dictionary.class_selected)){
selectedTones.push(element.childNodes[i].childNodes[j].getAttribute('data-tone'));
}
else if (classList.contains(dictionary.class_root)){
rootTone = element.childNodes[i].childNodes[j].getAttribute('data-tone');
}
}
}
}
}
} else {
events.sendMessage(dictionary.error_notFound+'no element found to search');
}
return {
container: element,
selectedTones: selectedTones,
rootTone: rootTone
};
};
/**
* return if the all of the selected tones exist in the scale or chord
* @param dataNotes
* @param selectedNotes
* @returns {boolean}
*/
this.tonesInScaleOrChordHelper = function(dataNotes, selectedNotes){
for(var i = 0; i < selectedNotes.length; i++){
if (dataNotes.indexOf(parseInt(selectedNotes[i])) === -1){
return false;
}
}
return true;
};
/**
* return if the scale contains the selected tones or not
* @param scale
* @param notes
* @returns {boolean}
*/
this.tonesInScaleOrChord = function(scale, notes){
if (notes.rootTone.length > 0){
if (scale.tones[0] == notes.rootTone){
return this.tonesInScaleOrChordHelper(scale.tones,notes.selectedTones);
}
else {
return false;
}
}
else {
return this.tonesInScaleOrChordHelper(scale.tones,notes.selectedTones);
}
};
}).apply(_chorus.logic.notes);
|
piano - bug fix for getting selected notes from dom
|
src/js/core/chorus.logic.js
|
piano - bug fix for getting selected notes from dom
|
<ide><path>rc/js/core/chorus.logic.js
<ide> return className.substring(dictionary.class_tone.length);
<ide> };
<ide>
<add> this.getPianoFromContainer = function(element){
<add> var result;
<add> if (element) {
<add> for (var i = 0; i < element.childNodes.length; i++) {
<add> if (element.childNodes[i].classList.contains(dictionary.class_piano_keyboard)){
<add> result = element.childNodes[i];
<add> }
<add> }
<add> }
<add> return result;
<add> };
<add>
<ide> /**
<ide> * get any tones that are selected in the dom
<ide> * @param container
<ide> notes = {
<ide> rootTone: '',
<ide> selectedTones:[]
<del> };
<add> },
<add> pianoKeyboard;
<ide> //search for selected notes by container id or class
<ide> if(container && container.length > 0){
<ide> var containerById = document.getElementById(container),
<ide> containerByClass = document.getElementsByClassName(container);
<ide> if (containerById){
<del> noteData.push(this.getTonesFromDOM(containerById));
<add> if (containerById.classList.contains('piano')){
<add> pianoKeyboard = this.getPianoFromContainer(containerById);
<add> if (pianoKeyboard){
<add> noteData.push(this.getTonesFromDOM(pianoKeyboard));
<add> }
<add> } else {
<add> noteData.push(this.getTonesFromDOM(containerById));
<add> }
<ide> }
<ide> else if (containerByClass){
<ide> for (var i = 0; i < containerByClass.length; i++){
<del> noteData.push(this.getTonesFromDOM(containerByClass[i]));
<add> if (containerByClass[i].classList.contains('piano')){
<add> pianoKeyboard = this.getPianoFromContainer(containerByClass[i]);
<add> if (pianoKeyboard){
<add> noteData.push(this.getTonesFromDOM(pianoKeyboard));
<add> }
<add> } else {
<add> noteData.push(this.getTonesFromDOM(containerByClass[i]));
<add> }
<ide> }
<ide> }
<ide> else {
<ide> else {
<ide> var containerByDefaultClass = document.getElementsByClassName(dictionary.class_instrument);
<ide> for (var j = 0; j < containerByDefaultClass.length; j++){
<del> noteData.push(this.getTonesFromDOM(containerByDefaultClass[j]));
<add> if (containerByDefaultClass[j].classList.contains('piano')){
<add> pianoKeyboard = this.getPianoFromContainer(containerByDefaultClass[j]);
<add> if (pianoKeyboard){
<add> noteData.push(this.getTonesFromDOM(pianoKeyboard));
<add> }
<add> } else {
<add> noteData.push(this.getTonesFromDOM(containerByDefaultClass[j]));
<add> }
<ide> }
<ide> }
<ide> //remove duplicates
<ide> * @type {Function}
<ide> */
<ide> this.getTonesFromDOM = function(element){
<del> var classList,
<add> var parentClassList,
<add> childClassList,
<ide> selectedTones = [],
<ide> rootTone = '';
<ide> if (element) {
<ide> for (var i = 0; i < element.childNodes.length; i++) {
<del> if (element.childNodes[i].classList.contains(dictionary.class_string)) {
<del> if (element.childNodes[i]) {
<add> if (element.childNodes[i]) {
<add> parentClassList = element.childNodes[i].classList;
<add> if (parentClassList.contains(dictionary.class_string)) {
<ide> for (var j = 0; j < element.childNodes[i].childNodes.length; j++) {
<del> classList = element.childNodes[i].childNodes[j].classList;
<del> if (classList.contains(dictionary.class_selected)){
<add> childClassList = element.childNodes[i].childNodes[j].classList;
<add> if (childClassList.contains(dictionary.class_selected)) {
<ide> selectedTones.push(element.childNodes[i].childNodes[j].getAttribute('data-tone'));
<ide> }
<del> else if (classList.contains(dictionary.class_root)){
<add> else if (childClassList.contains(dictionary.class_root)) {
<ide> rootTone = element.childNodes[i].childNodes[j].getAttribute('data-tone');
<ide> }
<add> }
<add> } else if (parentClassList.contains(dictionary.class_piano_key)) {
<add> if (parentClassList.contains(dictionary.class_selected)) {
<add> selectedTones.push(element.childNodes[i].getAttribute('data-tone'));
<add> }
<add> else if (parentClassList.contains(dictionary.class_root)) {
<add> rootTone = element.childNodes[i].getAttribute('data-tone');
<ide> }
<ide> }
<ide> }
<ide>
<ide> /**
<ide> * return if the scale contains the selected tones or not
<del> * @param scale
<add> * @param formula
<ide> * @param notes
<ide> * @returns {boolean}
<ide> */
<del> this.tonesInScaleOrChord = function(scale, notes){
<add> this.tonesInScaleOrChord = function(formula, notes){
<ide> if (notes.rootTone.length > 0){
<del> if (scale.tones[0] == notes.rootTone){
<del> return this.tonesInScaleOrChordHelper(scale.tones,notes.selectedTones);
<add> if (formula.tones[0] == notes.rootTone){
<add> return this.tonesInScaleOrChordHelper(formula.tones,notes.selectedTones);
<ide> }
<ide> else {
<ide> return false;
<ide> }
<ide> }
<ide> else {
<del> return this.tonesInScaleOrChordHelper(scale.tones,notes.selectedTones);
<add> return this.tonesInScaleOrChordHelper(formula.tones,notes.selectedTones);
<ide> }
<ide> };
<ide>
|
|
Java
|
agpl-3.0
|
7566789072ebe5919770c39753cf4adbcd977e7b
| 0 |
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
|
0c30d15c-2e62-11e5-9284-b827eb9e62be
|
hello.java
|
0c2ad6c6-2e62-11e5-9284-b827eb9e62be
|
0c30d15c-2e62-11e5-9284-b827eb9e62be
|
hello.java
|
0c30d15c-2e62-11e5-9284-b827eb9e62be
|
<ide><path>ello.java
<del>0c2ad6c6-2e62-11e5-9284-b827eb9e62be
<add>0c30d15c-2e62-11e5-9284-b827eb9e62be
|
|
Java
|
lgpl-2.1
|
aceca4db226a10aa3a3252de9b9f0e4a66741890
| 0 |
deegree/deegree3,deegree/deegree3,deegree/deegree3,deegree/deegree3,deegree/deegree3
|
//$HeadURL: svn+ssh://[email protected]/deegree/base/trunk/resources/eclipse/files_template.xml $
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2010 by:
- Department of Geography, University of Bonn -
and
- lat/lon GmbH -
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 2.1 of the License, or (at your option)
any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
e-mail: [email protected]
----------------------------------------------------------------------------*/
package org.deegree.services.wps.provider.jrxml.contentprovider;
import static java.awt.RenderingHints.KEY_ANTIALIASING;
import static java.awt.RenderingHints.KEY_TEXT_ANTIALIASING;
import static java.awt.RenderingHints.VALUE_ANTIALIAS_ON;
import static java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_ON;
import static org.deegree.commons.xml.stax.XMLStreamUtils.nextElement;
import static org.deegree.services.wps.provider.jrxml.JrxmlUtils.JASPERREPORTS_NS;
import static org.deegree.services.wps.provider.jrxml.JrxmlUtils.getAsCodeType;
import static org.deegree.services.wps.provider.jrxml.JrxmlUtils.getAsLanguageStringType;
import static org.deegree.services.wps.provider.jrxml.JrxmlUtils.nsContext;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.media.jai.JAI;
import javax.media.jai.RenderedOp;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.namespace.QName;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.dom.DOMSource;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.commons.io.IOUtils;
import org.deegree.commons.tom.ows.CodeType;
import org.deegree.commons.utils.Pair;
import org.deegree.commons.utils.Triple;
import org.deegree.commons.xml.XMLAdapter;
import org.deegree.commons.xml.XPath;
import org.deegree.cs.coordinatesystems.ICRS;
import org.deegree.cs.persistence.CRSManager;
import org.deegree.feature.Feature;
import org.deegree.feature.xpath.FeatureXPathEvaluator;
import org.deegree.geometry.Envelope;
import org.deegree.geometry.Geometry;
import org.deegree.geometry.standard.DefaultEnvelope;
import org.deegree.geometry.standard.primitive.DefaultPoint;
import org.deegree.gml.GMLVersion;
import org.deegree.gml.feature.StreamFeatureCollection;
import org.deegree.process.jaxb.java.ComplexFormatType;
import org.deegree.process.jaxb.java.ComplexInputDefinition;
import org.deegree.process.jaxb.java.ProcessletInputDefinition;
import org.deegree.protocol.wfs.client.WFSClient;
import org.deegree.protocol.wms.Utils;
import org.deegree.protocol.wms.ops.GetMap;
import org.deegree.remoteows.wms.WMSClient111;
import org.deegree.rendering.r2d.Java2DRenderer;
import org.deegree.rendering.r2d.legends.Legends;
import org.deegree.services.wps.ProcessletException;
import org.deegree.services.wps.ProcessletInputs;
import org.deegree.services.wps.input.ComplexInput;
import org.deegree.services.wps.input.ProcessletInput;
import org.deegree.services.wps.provider.jrxml.JrxmlUtils;
import org.deegree.services.wps.provider.jrxml.jaxb.map.AbstractDatasourceType;
import org.deegree.services.wps.provider.jrxml.jaxb.map.Center;
import org.deegree.services.wps.provider.jrxml.jaxb.map.Detail;
import org.deegree.services.wps.provider.jrxml.jaxb.map.Layer;
import org.deegree.services.wps.provider.jrxml.jaxb.map.Style;
import org.deegree.services.wps.provider.jrxml.jaxb.map.WFSDatasource;
import org.deegree.services.wps.provider.jrxml.jaxb.map.WMSDatasource;
import org.deegree.style.se.parser.SymbologyParser;
import org.deegree.style.styling.Styling;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sun.media.jai.codec.ImageCodec;
import com.sun.media.jai.codec.MemoryCacheSeekableStream;
import com.sun.media.jai.codec.PNGEncodeParam;
import com.sun.media.jai.codec.SeekableStream;
/**
* Provides a map in the jrxml
*
* @author <a href="mailto:[email protected]">Lyn Goltz</a>
* @author last edited by: $Author: lyn $
*
* @version $Revision: $, $Date: $
*/
public class MapContentProvider implements JrxmlContentProvider {
private static final Logger LOG = LoggerFactory.getLogger( MapContentProvider.class );
final static String SCHEMA = "http://www.deegree.org/processprovider/map";
final static String MIME_TYPE = "text/xml";
private static final String PARAM_PREFIX = "map";
final double INCH2M = 0.0254;
private enum SUFFIXES {
LEGEND_SUFFIX( "_legend" ), MAP_SUFFIX( "_img" ), SCALE_SUFFIX( "_scale" ), LAYERLIST_SUFFIX( "_layerlist" ), SCALEBAR_SUFFIX(
"_scalebar" );
private final String text;
private SUFFIXES( String text ) {
this.text = text;
}
private String getText() {
return text;
}
}
@Override
public void inspectInputParametersFromJrxml( List<JAXBElement<? extends ProcessletInputDefinition>> inputs,
XMLAdapter jrxmlAdapter, Map<String, String> parameters,
List<String> handledParameters ) {
// for a wms, parameters starting with 'map' are important. three different types are supported:
// * wmsXYZ_map -> as image parameter
// * wmsXYZ_legend -> as imgage parameter
// * wmsXYZ_layerList -> as frame key
// where XYZ is a string which is the identifier of the process parameter.
List<String> mapIds = new ArrayList<String>();
for ( String parameterName : parameters.keySet() ) {
if ( !handledParameters.contains( parameterName ) ) {
if ( jrxmlAdapter.getElement( jrxmlAdapter.getRootElement(),
new XPath( ".//jasper:image/jasper:imageExpression[text()='$P{"
+ parameterName + "}']", JrxmlUtils.nsContext ) ) != null
|| jrxmlAdapter.getElement( jrxmlAdapter.getRootElement(),
new XPath(
".//jasper:textField/jasper:textFieldExpression[text()='$P{"
+ parameterName + "}']",
JrxmlUtils.nsContext ) ) != null ) {
if ( isMapParameter( parameterName ) ) {
String mapId = getIdentifierFromParameter( parameterName );
if ( !mapIds.contains( mapId ) ) {
mapIds.add( mapId );
}
// TODO: maybe a status information would be the better way?
// remove used parameter
handledParameters.add( parameterName );
}
}
}
}
for ( String mapId : mapIds ) {
LOG.debug( "Found map component with id " + mapId );
ComplexInputDefinition comp = new ComplexInputDefinition();
comp.setTitle( getAsLanguageStringType( mapId ) );
comp.setIdentifier( getAsCodeType( mapId ) );
ComplexFormatType format = new ComplexFormatType();
format.setEncoding( "UTF-8" );
format.setMimeType( MIME_TYPE );
format.setSchema( SCHEMA );
comp.setDefaultFormat( format );
comp.setMaxOccurs( BigInteger.valueOf( 1 ) );
comp.setMinOccurs( BigInteger.valueOf( 0 ) );
inputs.add( new JAXBElement<ComplexInputDefinition>( new QName( "ProcessInput" ),
ComplexInputDefinition.class, comp ) );
}
}
private String getIdentifierFromParameter( String parameter ) {
if ( isMapParameter( parameter ) ) {
for ( SUFFIXES suf : SUFFIXES.values() ) {
if ( parameter.endsWith( suf.getText() ) ) {
parameter = parameter.substring( PARAM_PREFIX.length(), parameter.length() - suf.getText().length() );
}
}
}
return parameter;
}
private String getParameterFromIdentifier( String mapId, SUFFIXES suffix ) {
return PARAM_PREFIX + mapId + suffix.text;
}
private boolean isMapParameter( String imgParameter ) {
boolean hasSuffix = false;
for ( SUFFIXES suf : SUFFIXES.values() ) {
if ( imgParameter.endsWith( suf.getText() ) ) {
hasSuffix = true;
}
}
return hasSuffix && imgParameter.startsWith( PARAM_PREFIX );
}
@Override
public InputStream prepareJrxmlAndReadInputParameters( InputStream jrxml, Map<String, Object> params,
ProcessletInputs in, List<CodeType> processedIds,
Map<String, String> parameters )
throws ProcessletException {
for ( ProcessletInput input : in.getParameters() ) {
if ( !processedIds.contains( input ) && input instanceof ComplexInput ) {
ComplexInput complexIn = (ComplexInput) input;
if ( SCHEMA.equals( complexIn.getSchema() ) && MIME_TYPE.equals( complexIn.getMimeType() ) ) {
String mapId = complexIn.getIdentifier().getCode();
LOG.debug( "Found input parameter " + mapId + " representing a map!" );
try {
// JAXBContext jc = JAXBContext.newInstance( "org.deegree.services.wps.provider.jrxml.jaxb.map"
// );
JAXBContext jc = JAXBContext.newInstance( org.deegree.services.wps.provider.jrxml.jaxb.map.Map.class );
Unmarshaller unmarshaller = jc.createUnmarshaller();
org.deegree.services.wps.provider.jrxml.jaxb.map.Map map = (org.deegree.services.wps.provider.jrxml.jaxb.map.Map) unmarshaller.unmarshal( complexIn.getValueAsXMLStream() );
XMLAdapter jrxmlAdapter = new XMLAdapter( jrxml );
OMElement root = jrxmlAdapter.getRootElement();
List<OrderedDatasource<?>> datasources = anaylizeRequestOrder( map.getDatasources().getWMSDatasourceOrWFSDatasource() );
// MAP
int resolution = map.getResolution().intValue();
String mapKey = getParameterFromIdentifier( mapId, SUFFIXES.MAP_SUFFIX );
if ( parameters.containsKey( mapKey ) ) {
OMElement mapImgRep = jrxmlAdapter.getElement( root,
new XPath(
".//jasper:image[jasper:imageExpression/text()='$P{"
+ mapKey
+ "}']/jasper:reportElement",
nsContext ) );
if ( mapImgRep == null ) {
LOG.info( "Could not find image tag in the jrxml for map parameter '" + mapKey + "'" );
break;
}
int width = jrxmlAdapter.getRequiredNodeAsInteger( mapImgRep, new XPath( "@width",
nsContext ) );
int height = jrxmlAdapter.getRequiredNodeAsInteger( mapImgRep, new XPath( "@height",
nsContext ) );
width = adjustSpan( width, resolution );
height = adjustSpan( height, resolution );
Envelope bbox = calculateBBox( map.getDetail(), mapId, width, height, resolution );
params.put( mapKey, prepareMap( datasources, parameters.get( mapKey ), width, height, bbox ) );
// SCALE
double scale = Utils.calcScaleWMS130( width, height, bbox, bbox.getCoordinateSystem() );
String scaleKey = getParameterFromIdentifier( mapId, SUFFIXES.SCALE_SUFFIX );
if ( parameters.containsKey( scaleKey ) ) {
params.put( scaleKey, convert( scale, parameters.get( scaleKey ) ) );
}
// SCALEBAR
String scalebarKey = getParameterFromIdentifier( mapId, SUFFIXES.SCALEBAR_SUFFIX );
if ( parameters.containsKey( scalebarKey ) ) {
prepareScaleBar( params, scalebarKey, jrxmlAdapter, datasources,
parameters.get( scalebarKey ), bbox, width );
}
}
// LAYERLIST
prepareLayerlist( getParameterFromIdentifier( mapId, SUFFIXES.LAYERLIST_SUFFIX ), jrxmlAdapter,
map, datasources );
// LEGEND
String legendKey = getParameterFromIdentifier( mapId, SUFFIXES.LEGEND_SUFFIX );
if ( parameters.containsKey( legendKey ) ) {
params.put( legendKey,
prepareLegend( legendKey, jrxmlAdapter, datasources,
parameters.get( legendKey ), resolution ) );
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
if ( LOG.isDebugEnabled() ) {
LOG.debug( "Adjusted jrxml: " + jrxmlAdapter.getRootElement() );
}
jrxmlAdapter.getRootElement().serialize( bos );
jrxml = new ByteArrayInputStream( bos.toByteArray() );
} catch ( XMLStreamException e ) {
throw new RuntimeException( e );
} finally {
IOUtils.closeQuietly( bos );
}
} catch ( JAXBException e ) {
String msg = "Could not parse map configuration from parameter '" + complexIn.getIdentifier()
+ "': " + e.getMessage();
LOG.debug( msg, e );
throw new ProcessletException( msg );
} catch ( IOException e ) {
String msg = "Could not read map configuration from parameter '" + complexIn.getIdentifier()
+ "': " + e.getMessage();
LOG.debug( msg, e );
throw new ProcessletException( msg );
} catch ( XMLStreamException e ) {
String msg = "Could not read map configuration as xml from parameter '"
+ complexIn.getIdentifier() + "': " + e.getMessage();
LOG.debug( msg, e );
throw new ProcessletException( msg );
}
processedIds.add( input.getIdentifier() );
}
}
}
return jrxml;
}
private int adjustSpan( int inPxFromJrxml, int resolution ) {
// jasper assumes a resolution of 72 dpi
return new Double( inPxFromJrxml / 72d * resolution ).intValue();
}
private Envelope calculateBBox( Detail detail, String id, int mapWidth, int mapHeight, int dpi )
throws ProcessletException {
ICRS crs = CRSManager.getCRSRef( detail.getCrs() );
Center center = detail.getCenter();
Envelope bbox = null;
if ( center != null ) {
int scaleDenominator = center.getScaleDenominator().intValue();
String[] coords = center.getValue().split( "," );
double pixelSize = INCH2M / dpi;
double w2 = ( scaleDenominator * pixelSize * mapWidth ) / 2d;
double x1 = Double.parseDouble( coords[0] ) - w2;
double x2 = Double.parseDouble( coords[0] ) + w2;
w2 = ( scaleDenominator * pixelSize * mapHeight ) / 2d;
double y1 = Double.parseDouble( coords[1] ) - w2;
double y2 = Double.parseDouble( coords[1] ) + w2;
bbox = new DefaultEnvelope( null, crs, null, new DefaultPoint( null, crs, null, new double[] { x1, y1 } ),
new DefaultPoint( null, crs, null, new double[] { x2, y2 } ) );
} else if ( detail.getBbox() != null ) {
String[] coords = detail.getBbox().split( "," );
double bboxXmin = Double.parseDouble( coords[0] );
double bboxYmin = Double.parseDouble( coords[1] );
double bboxXmax = Double.parseDouble( coords[2] );
double bboxYmax = Double.parseDouble( coords[3] );
double bboxWidth = bboxXmax - bboxXmin;
double bboxHeight = bboxYmax - bboxYmin;
double bboxAspectRatio = bboxWidth / bboxHeight;
double printAspectRatio = ( (double) mapWidth ) / mapHeight;
if ( bboxAspectRatio > printAspectRatio ) {
double centerY = bboxYmin + ( ( bboxYmax - bboxYmin ) / 2d );
double height = bboxWidth * ( 1.0 / printAspectRatio );
double minY = centerY - ( height / 2d );
double maxY = centerY + ( height / 2d );
bbox = new DefaultEnvelope( null, crs, null, new DefaultPoint( null, crs, null, new double[] {
bboxXmin,
minY } ),
new DefaultPoint( null, crs, null, new double[] { bboxXmax, maxY } ) );
} else {
double centerX = bboxXmin + ( ( bboxXmax - bboxXmin ) / 2d );
double width = bboxHeight * printAspectRatio;
double minX = centerX - ( width / 2d );
double maxX = centerX + ( width / 2d );
bbox = new DefaultEnvelope( null, crs, null, new DefaultPoint( null, crs, null,
new double[] { minX, bboxYmin } ),
new DefaultPoint( null, crs, null, new double[] { maxX, bboxYmax } ) );
}
} else {
throw new ProcessletException(
"Could not parse required parameter bbox or center for map component with id '"
+ id + "'." );
}
LOG.debug( "requested and adjusted bbox: {}", bbox );
return bbox;
}
private void prepareScaleBar( Map<String, Object> params, String scalebarKey, XMLAdapter jrxmlAdapter,
List<OrderedDatasource<?>> datasources, String type, Envelope bbox, double mapWidth )
throws ProcessletException {
OMElement sbRep = jrxmlAdapter.getElement( jrxmlAdapter.getRootElement(),
new XPath( ".//jasper:image[jasper:imageExpression/text()='$P{"
+ scalebarKey + "}']/jasper:reportElement", nsContext ) );
if ( sbRep != null ) {
// TODO: rework this!
LOG.debug( "Found scalebar with key '" + scalebarKey + "'." );
int w = jrxmlAdapter.getRequiredNodeAsInteger( sbRep, new XPath( "@width", nsContext ) );
int h = jrxmlAdapter.getRequiredNodeAsInteger( sbRep, new XPath( "@height", nsContext ) );
BufferedImage img = new BufferedImage( w, h, BufferedImage.TYPE_INT_ARGB );
Graphics2D g = img.createGraphics();
String fontName = null;
int fontSize = 8;
int desiredWidth = w - 30;
// calculate scale bar max scale and size
int length = 0;
double lx = 0;
double scale = 0;
for ( int i = 0; i < 100; i++ ) {
double k = 0;
double dec = 30 * Math.pow( 10, i );
for ( int j = 0; j < 9; j++ ) {
k += dec;
double tx = -k * ( mapWidth / bbox.getSpan0() );
if ( Math.abs( tx - lx ) < desiredWidth ) {
length = (int) Math.round( Math.abs( tx - lx ) );
scale = k;
} else {
break;
}
}
}
// draw scale bar base line
g.setStroke( new BasicStroke( ( desiredWidth + 30 ) / 250 ) );
g.setColor( Color.black );
g.drawLine( 10, 30, length + 10, 30 );
double dx = length / 3d;
double vdx = scale / 3;
double div = 1;
String uom = "m";
if ( scale > 1000 ) {
div = 1000;
uom = "km";
}
// draw scale bar scales
if ( fontName == null ) {
fontName = "SANS SERIF";
}
g.setFont( new Font( fontName, Font.PLAIN, fontSize ) );
DecimalFormat df = new DecimalFormat( "##.# " );
DecimalFormat dfWithUom = new DecimalFormat( "##.# " + uom );
for ( int i = 0; i < 4; i++ ) {
String label = i < 3 ? df.format( ( vdx * i ) / div ) : dfWithUom.format( ( vdx * i ) / div );
g.drawString( label, (int) Math.round( 10 + i * dx ) - 8, 10 );
g.drawLine( (int) Math.round( 10 + i * dx ), 30, (int) Math.round( 10 + i * dx ), 20 );
}
for ( int i = 0; i < 7; i++ ) {
g.drawLine( (int) Math.round( 10 + i * dx / 2d ), 30, (int) Math.round( 10 + i * dx / 2d ), 25 );
}
g.dispose();
params.put( scalebarKey, convertImageToReportFormat( type, img ) );
LOG.debug( "added scalebar" );
}
}
private Object convert( double scale, String parameterType ) {
if ( parameterType == null || "java.lang.String".equals( parameterType ) ) {
return Double.toString( scale );
} else if ( "java.lang.Integer".equals( parameterType ) ) {
return new Double( scale ).intValue();
} else if ( "java.lang.Float".equals( parameterType ) ) {
return new Double( scale ).floatValue();
} else if ( "java.lang.Long".equals( parameterType ) ) {
return new Double( scale ).longValue();
} else if ( "java.math.BigDecimal".equals( parameterType ) ) {
return new BigDecimal( scale );
} else if ( "java.lang.Short".equals( parameterType ) ) {
return new Double( scale ).shortValue();
} else if ( "java.lang.Byte".equals( parameterType ) ) {
return new Double( scale ).byteValue();
}
return scale;
}
private Object prepareLegend( String legendKey, XMLAdapter jrxmlAdapter, List<OrderedDatasource<?>> datasources,
String type, int resolution )
throws ProcessletException {
OMElement legendRE = jrxmlAdapter.getElement( jrxmlAdapter.getRootElement(),
new XPath( ".//jasper:image[jasper:imageExpression/text()='$P{"
+ legendKey + "}']/jasper:reportElement", nsContext ) );
if ( legendRE != null ) {
LOG.debug( "Found legend with key '" + legendKey + "'." );
int width = jrxmlAdapter.getRequiredNodeAsInteger( legendRE, new XPath( "@width", nsContext ) );
int height = jrxmlAdapter.getRequiredNodeAsInteger( legendRE, new XPath( "@height", nsContext ) );
width = adjustSpan( width, resolution );
height = adjustSpan( height, resolution );
// TODO: bgcolor?
Color bg = Color.decode( "0xFFFFFF" );
BufferedImage bi = new BufferedImage( width, height, BufferedImage.TYPE_INT_ARGB );
Graphics g = bi.getGraphics();
g.setColor( bg );
g.fillRect( 0, 0, bi.getWidth(), bi.getHeight() );
g.setColor( Color.BLACK );
int k = 0;
for ( int i = 0; i < datasources.size(); i++ ) {
if ( k > bi.getHeight() ) {
LOG.warn( "The necessary legend size is larger than the available legend space." );
}
List<Pair<String, BufferedImage>> legends = datasources.get( i ).getLegends( width );
for ( Pair<String, BufferedImage> legend : legends ) {
BufferedImage img = legend.second;
if ( img != null ) {
if ( img.getWidth( null ) < 50 ) {
// it is assumed that no label is assigned
g.drawImage( img, 0, k, null );
g.drawString( legend.first, img.getWidth( null ) + 10, k + img.getHeight( null ) / 2 );
} else {
g.drawImage( img, 0, k, null );
}
k = k + img.getHeight( null ) + 10;
} else {
g.drawString( "- " + legend.first, 0, k + 10 );
k = k + 20;
}
}
}
g.dispose();
return convertImageToReportFormat( type, bi );
}
return null;
}
private void prepareLayerlist( String layerListKey, XMLAdapter jrxmlAdapter,
org.deegree.services.wps.provider.jrxml.jaxb.map.Map map,
List<OrderedDatasource<?>> datasources ) {
OMElement layerListFrame = jrxmlAdapter.getElement( jrxmlAdapter.getRootElement(),
new XPath(
".//jasper:band/jasper:frame[jasper:reportElement/@key='"
+ layerListKey + "']",
nsContext ) );
if ( layerListFrame != null ) {
LOG.debug( "Found layer list with key '{}' to adjust.", layerListKey );
List<OMElement> elements = jrxmlAdapter.getElements( layerListFrame, new XPath( "jasper:staticText",
nsContext ) );
if ( elements.size() > 1 ) {
OMElement grpTemplate = elements.get( 0 );
OMElement fieldTemplate = elements.get( 1 );
for ( OMElement element : elements ) {
element.detach();
}
XMLAdapter grpAdapter = new XMLAdapter( grpTemplate );
int grpHeight = grpAdapter.getNodeAsInt( grpTemplate, new XPath( "jasper:reportElement/@height",
nsContext ), 15 );
int grpY = grpAdapter.getNodeAsInt( grpTemplate, new XPath( "jasper:reportElement/@y", nsContext ), 0 );
XMLAdapter fieldAdapter = new XMLAdapter( fieldTemplate );
int fieldHeight = fieldAdapter.getNodeAsInt( fieldTemplate, new XPath( "jasper:reportElement/@height",
nsContext ), 15 );
OMFactory factory = OMAbstractFactory.getOMFactory();
// y + height * index
int y = grpY;
for ( OrderedDatasource<?> datasource : datasources ) {
for ( String datasourceKey : datasource.getLayerList().keySet() ) {
OMElement newGrp = createLayerEntry( grpTemplate, y, factory, datasourceKey );
layerListFrame.addChild( newGrp );
y += grpHeight;
for ( String layerName : datasource.getLayerList().get( datasourceKey ) ) {
OMElement newField = createLayerEntry( fieldTemplate, y, factory, layerName );
layerListFrame.addChild( newField );
y += fieldHeight;
}
}
}
} else {
LOG.info( "layerlist frame with key '{}' must have at least two child elements", layerListKey );
}
} else {
LOG.debug( "no layer list with key '{}' found.", layerListKey );
}
}
private OMElement createLayerEntry( OMElement template, int y, OMFactory factory, String text ) {
OMElement newGrp = template.cloneOMElement();
OMElement e = newGrp.getFirstChildWithName( new QName( JASPERREPORTS_NS, "reportElement" ) );
e.addAttribute( "y", Integer.toString( y ), null );
e = newGrp.getFirstChildWithName( new QName( JASPERREPORTS_NS, "text" ) );
// this does not work:
// e.setText( layer );
// it attaches the text, but does not replace
e.getFirstOMChild().detach();
e.addChild( factory.createOMText( e, text ) );
return newGrp;
}
private Object prepareMap( List<OrderedDatasource<?>> datasources, String type, int width, int height, Envelope bbox )
throws ProcessletException {
BufferedImage bi = new BufferedImage( width, height, BufferedImage.TYPE_INT_ARGB );
Graphics g = bi.getGraphics();
for ( OrderedDatasource<?> datasource : datasources ) {
BufferedImage image = datasource.getImage( width, height, bbox );
if ( image != null ) {
g.drawImage( image, 0, 0, null );
}
}
g.dispose();
return convertImageToReportFormat( type, bi );
}
private Object convertImageToReportFormat( String type, BufferedImage bi )
throws ProcessletException {
if ( type != null && type.equals( "java.io.File" ) ) {
return writeImage( bi );
} else if ( type != null && type.equals( "java.net.URL" ) ) {
try {
return writeImage( bi ).toURI().toURL();
} catch ( MalformedURLException e ) {
LOG.error( "Could not create url: ", e );
}
} else if ( type != null && type.equals( "java.io.InputStream" ) ) {
try {
return new FileInputStream( writeImage( bi ) );
} catch ( FileNotFoundException e ) {
LOG.error( "Could not open stream: ", e );
}
} else if ( type != null && type.equals( "java.awt.Image" ) ) {
return bi;
}
return writeImage( bi ).toString();
}
List<OrderedDatasource<?>> anaylizeRequestOrder( List<AbstractDatasourceType> datasources ) {
List<OrderedDatasource<?>> orderedDatasources = new ArrayList<OrderedDatasource<?>>();
for ( AbstractDatasourceType datasource : datasources ) {
if ( datasource instanceof WMSDatasource ) {
WMSDatasource wmsDatasource = (WMSDatasource) datasource;
List<Layer> layers = wmsDatasource.getLayers().getLayer();
int index = 0;
for ( Layer layer : layers ) {
BigInteger position = layer.getPosition();
if ( position != null ) {
int intPos = position.intValue();
WMSOrderedDatasource contains = contains( orderedDatasources, wmsDatasource, intPos );
// splitten! wenn position zwischen zwei
if ( contains != null ) {
List<Layer> orderedLayers = contains.layers;
int i = 0;
for ( Layer orderedLayer : orderedLayers ) {
if ( orderedLayer.getPosition().intValue() < intPos ) {
i++;
}
}
contains.layers.add( i, layer );
contains.min = contains.min < intPos ? contains.min : intPos;
contains.max = contains.max > intPos ? contains.max : intPos;
} else {
List<Layer> newLayerList = new ArrayList<Layer>();
newLayerList.add( layer );
int indexToAdd = getIndexToAdd( orderedDatasources, intPos );
orderedDatasources.add( indexToAdd, new WMSOrderedDatasource( wmsDatasource, newLayerList,
intPos, intPos ) );
}
} else {
WMSOrderedDatasource contains = contains( orderedDatasources, wmsDatasource );
if ( contains != null ) {
contains.layers.add( layer );
} else {
List<Layer> newLayerList = new ArrayList<Layer>();
newLayerList.add( layer );
orderedDatasources.add( new WMSOrderedDatasource( wmsDatasource, newLayerList ) );
}
}
index++;
}
} else if ( datasource instanceof WFSDatasource ) {
WFSDatasource wfsDatasource = (WFSDatasource) datasource;
WFSOrderedDatasource newDatasource = new WFSOrderedDatasource( wfsDatasource );
if ( wfsDatasource.getPosition() != null ) {
int indexToAdd = getIndexToAdd( orderedDatasources, wfsDatasource.getPosition().intValue() );
orderedDatasources.add( indexToAdd, newDatasource );
} else {
orderedDatasources.add( newDatasource );
}
}
}
return orderedDatasources;
}
private int getIndexToAdd( List<OrderedDatasource<?>> orderedDatasources, int intPos ) {
int indexToAdd = 0;
boolean isBetween = false;
for ( OrderedDatasource<?> orderedDatasource : orderedDatasources ) {
if ( orderedDatasource.min > 0 && intPos > orderedDatasource.min && intPos < orderedDatasource.max ) {
indexToAdd++;
isBetween = true;
break;
} else if ( orderedDatasource.min > 0 && intPos > orderedDatasource.max ) {
indexToAdd++;
} else {
break;
}
}
if ( isBetween ) {
OrderedDatasource<?> dsToSplit = orderedDatasources.get( indexToAdd - 1 );
if ( dsToSplit instanceof WMSOrderedDatasource ) {
List<Layer> newLayerListFromSplit = new ArrayList<Layer>();
int newMinPos = 0;
int newMaxPos = 0;
for ( Layer l : ( (WMSOrderedDatasource) dsToSplit ).layers ) {
if ( l.getPosition() != null && l.getPosition().intValue() > intPos ) {
newLayerListFromSplit.add( l );
newMinPos = Math.min( l.getPosition().intValue(), newMinPos );
newMaxPos = Math.max( l.getPosition().intValue(), newMaxPos );
}
}
for ( Layer lToRemove : newLayerListFromSplit ) {
( (WMSOrderedDatasource) dsToSplit ).layers.remove( lToRemove );
}
orderedDatasources.add( indexToAdd, new WMSOrderedDatasource( (WMSDatasource) dsToSplit.datasource,
newLayerListFromSplit, intPos, intPos ) );
}
}
return indexToAdd;
}
private WMSOrderedDatasource contains( List<OrderedDatasource<?>> orderedDatasources, WMSDatasource datasource,
int index ) {
int i = 0;
for ( OrderedDatasource<?> orderedDatasource : orderedDatasources ) {
if ( orderedDatasource.datasource.equals( datasource ) ) {
WMSOrderedDatasource wmsOrderedDatasource = (WMSOrderedDatasource) orderedDatasource;
int maxBefore = Integer.MIN_VALUE;
int minNext = Integer.MIN_VALUE;
if ( i - 1 > 0 && i - 1 < orderedDatasources.size() ) {
maxBefore = orderedDatasources.get( i - 1 ).max;
}
if ( i + 1 < orderedDatasources.size() ) {
minNext = orderedDatasources.get( i + 1 ).min;
}
if ( index > maxBefore && ( minNext < 0 || index < minNext ) ) {
return wmsOrderedDatasource;
}
}
i++;
}
return null;
}
private WMSOrderedDatasource contains( List<OrderedDatasource<?>> orderedDatasources, WMSDatasource datasource ) {
for ( OrderedDatasource<?> orderedDatasource : orderedDatasources ) {
if ( orderedDatasource.datasource.equals( datasource ) ) {
return (WMSOrderedDatasource) orderedDatasource;
}
}
return null;
}
abstract class OrderedDatasource<T extends AbstractDatasourceType> {
// OrderedDatasource
// abstract String getRequest( int width, int height, String bbox, String crs );
int min = Integer.MIN_VALUE;
int max = Integer.MIN_VALUE;
final T datasource;
public OrderedDatasource( T datasource ) {
this.datasource = datasource;
}
public abstract List<Pair<String, BufferedImage>> getLegends( int width )
throws ProcessletException;
public OrderedDatasource( T datasource, int min, int max ) {
this.datasource = datasource;
this.min = min;
this.max = max;
}
abstract BufferedImage getImage( int width, int height, Envelope bbox )
throws ProcessletException;
abstract Map<String, List<String>> getLayerList();
protected org.deegree.style.se.unevaluated.Style getStyle( Style dsStyle )
throws MalformedURLException, FactoryConfigurationError, XMLStreamException,
IOException {
XMLStreamReader reader = null;
if ( dsStyle == null || dsStyle.getNamedStyle() != null ) {
return null;
} else if ( dsStyle.getExternalStyle() != null ) {
URL ex = new URL( dsStyle.getExternalStyle() );
XMLInputFactory fac = XMLInputFactory.newInstance();
reader = fac.createXMLStreamReader( ex.openStream() );
} else if ( dsStyle.getEmbeddedStyle() != null ) {
XMLInputFactory fac = XMLInputFactory.newInstance();
reader = fac.createXMLStreamReader( new DOMSource( dsStyle.getEmbeddedStyle() ) );
nextElement( reader );
nextElement( reader );
}
SymbologyParser symbologyParser = SymbologyParser.INSTANCE;
return symbologyParser.parse( reader );
}
protected BufferedImage getLegendImg( org.deegree.style.se.unevaluated.Style style, int width ) {
Legends legends = new Legends();
Pair<Integer, Integer> legendSize = legends.getLegendSize( style );
if ( legendSize.first < width )
width = legendSize.first;
BufferedImage img = new BufferedImage( width, legendSize.second, BufferedImage.TYPE_INT_ARGB );
Graphics2D g = img.createGraphics();
g.setRenderingHint( KEY_ANTIALIASING, VALUE_ANTIALIAS_ON );
g.setRenderingHint( KEY_TEXT_ANTIALIASING, VALUE_TEXT_ANTIALIAS_ON );
legends.paintLegend( style, width, legendSize.second, g );
g.dispose();
return img;
}
}
class WMSOrderedDatasource extends OrderedDatasource<WMSDatasource> {
List<Layer> layers;
public WMSOrderedDatasource( WMSDatasource datasource, List<Layer> layers ) {
super( datasource );
this.layers = layers;
}
public WMSOrderedDatasource( WMSDatasource datasource, List<Layer> layers, int min, int max ) {
super( datasource, min, max );
this.layers = layers;
}
@Override
BufferedImage getImage( int width, int height, Envelope bbox )
throws ProcessletException {
LOG.debug( "create map image for WMS datasource '{}'", datasource.getName() );
try {
String user = datasource.getAuthentification() != null ? datasource.getAuthentification().getUser()
: null;
String passw = datasource.getAuthentification() != null ? datasource.getAuthentification().getPassword()
: null;
// TODO: version
if ( !"1.1.1".equals( datasource.getVersion() ) ) {
throw new ProcessletException( "WMS version " + datasource.getVersion()
+ " is not yet supported. Supported values are: 1.1.1" );
}
String capUrl = datasource.getUrl() + "?request=GetCapabilities&service=WMS&version=1.1.1";
WMSClient111 wmsClient = new WMSClient111( new URL( capUrl ), 5, 60, user, passw );
List<Pair<String, String>> layerToStyle = new ArrayList<Pair<String, String>>();
for ( Layer l : layers ) {
String style = l.getStyle() != null ? l.getStyle().getNamedStyle() : null;
layerToStyle.add( new Pair<String, String>( l.getName(), style ) );
}
GetMap gm = new GetMap( layerToStyle, width, height, bbox, "image/png", true );
Pair<BufferedImage, String> map = wmsClient.getMap( gm, null, 60, false );
if ( map.first == null )
throw new ProcessletException( "Could not get map from datasource " + datasource.getName() + ": "
+ map.second );
return map.first;
} catch ( MalformedURLException e ) {
String msg = "could not resolve wms url " + datasource.getUrl() + "!";
LOG.error( msg, e );
throw new ProcessletException( msg );
} catch ( Exception e ) {
String msg = "could not get map: " + e.getMessage();
LOG.error( msg, e );
throw new ProcessletException( msg );
}
}
private BufferedImage loadImage( String request )
throws IOException {
LOG.debug( "try to load image from request " + request );
InputStream is = null;
SeekableStream fss = null;
try {
URLConnection conn = new URL( request ).openConnection();
is = conn.getInputStream();
if ( LOG.isDebugEnabled() ) {
File logFile = File.createTempFile( "loadedImg", "response" );
OutputStream logStream = new FileOutputStream( logFile );
byte[] buffer = new byte[1024];
int read = 0;
while ( ( read = is.read( buffer ) ) != -1 ) {
logStream.write( buffer, 0, read );
}
logStream.close();
is = new FileInputStream( logFile );
LOG.debug( "response can be found at " + logFile );
}
try {
fss = new MemoryCacheSeekableStream( is );
RenderedOp ro = JAI.create( "stream", fss );
return ro.getAsBufferedImage();
} catch ( Exception e ) {
LOG.info( "could not load image!" );
return null;
}
} finally {
IOUtils.closeQuietly( fss );
IOUtils.closeQuietly( is );
}
}
@Override
Map<String, List<String>> getLayerList() {
HashMap<String, List<String>> layerList = new HashMap<String, List<String>>();
ArrayList<String> layerNames = new ArrayList<String>( layers.size() );
for ( Layer layer : layers ) {
layerNames.add( layer.getTitle() != null ? layer.getTitle() : layer.getName() );
}
layerList.put( datasource.getName(), layerNames );
return layerList;
}
@Override
public List<Pair<String, BufferedImage>> getLegends( int width )
throws ProcessletException {
List<Pair<String, BufferedImage>> legends = new ArrayList<Pair<String, BufferedImage>>();
for ( Layer layer : layers ) {
String layerName = layer.getName();
try {
BufferedImage bi = null;
org.deegree.style.se.unevaluated.Style style = getStyle( layer.getStyle() );
if ( style != null ) {
bi = getLegendImg( style, width );
} else {
String legendUrl = getLegendUrl( layer );
LOG.debug( "Try to load legend image from WMS {}: ", legendUrl );
try {
bi = loadImage( legendUrl );
} catch ( IOException e ) {
String msg = "Could not create legend for layer: " + layerName;
LOG.error( msg );
throw new ProcessletException( msg );
}
}
legends.add( new Pair<String, BufferedImage>( layerName, bi ) );
} catch ( Exception e ) {
String dsName = datasource.getName() != null ? datasource.getName() : datasource.getUrl();
LOG.info( "Could not create legend image for datasource '" + dsName + "', layer " + layerName + ".",
e );
}
}
return legends;
}
String getLegendUrl( Layer layer ) {
String url = datasource.getUrl();
StringBuilder sb = new StringBuilder();
sb.append( url );
if ( !url.endsWith( "?" ) )
sb.append( '?' );
sb.append( "REQUEST=GetLegendGraphic&" );
sb.append( "SERVICE=WMS&" );
sb.append( "VERSION=" ).append( datasource.getVersion() ).append( '&' );
sb.append( "LAYER=" ).append( layer.getName() ).append( '&' );
sb.append( "TRANSPARENT=" ).append( "TRUE" ).append( '&' );
sb.append( "FORMAT=" ).append( "image/png" ).append( '&' );
if ( layer.getStyle() != null && layer.getStyle().getNamedStyle() != null ) {
sb.append( "STYLE=" ).append( layer.getStyle().getNamedStyle() );
}
return sb.toString();
}
}
class WFSOrderedDatasource extends OrderedDatasource<WFSDatasource> {
public WFSOrderedDatasource( WFSDatasource datasource ) {
super( datasource );
}
public WFSOrderedDatasource( WFSDatasource datasource, int pos ) {
super( datasource, pos, pos );
}
@Override
BufferedImage getImage( int width, int height, Envelope bbox )
throws ProcessletException {
LOG.debug( "create map image for WFS datasource '{}'", datasource.getName() );
try {
String capURL = datasource.getUrl() + "?service=WFS&request=GetCapabilities&version="
+ datasource.getVersion();
WFSClient wfsClient = new WFSClient( new URL( capURL ) );
StreamFeatureCollection features = wfsClient.getFeatures( new QName(
datasource.getFeatureType().getValue(),
datasource.getFeatureType().getValue() ) );
BufferedImage image = new BufferedImage( width, height, BufferedImage.TYPE_INT_ARGB );
Graphics2D g = image.createGraphics();
Java2DRenderer renderer = new Java2DRenderer( g, width, height, bbox, bbox.getCoordinateDimension() /* pixelSize */);
// TODO
// XMLInputFactory fac = XMLInputFactory.newInstance();
// XMLStreamReader reader = fac.createXMLStreamReader( new DOMSource( datasource.getFilter() ) );
// nextElement( reader );
// nextElement( reader );
// Filter filter = Filter110XMLDecoder.parse( reader );
// reader.close();
org.deegree.style.se.unevaluated.Style style = getStyle( datasource.getStyle() );
if ( style != null && features != null ) {
Feature feature = null;
while ( ( feature = features.read() ) != null ) {
LinkedList<Triple<Styling, LinkedList<Geometry>, String>> evaluate = style.evaluate( feature,
new FeatureXPathEvaluator(
GMLVersion.GML_32 ) );
for ( Triple<Styling, LinkedList<Geometry>, String> triple : evaluate ) {
for ( Geometry geom : triple.second ) {
renderer.render( triple.first, geom );
}
}
}
}
g.dispose();
return image;
} catch ( Exception e ) {
String msg = "could nor create image from wfs datasource " + datasource.getName() + ": "
+ e.getMessage();
LOG.error( msg, e );
throw new ProcessletException( msg );
}
}
@Override
Map<String, List<String>> getLayerList() {
HashMap<String, List<String>> layerList = new HashMap<String, List<String>>();
layerList.put( datasource.getName(), new ArrayList<String>() );
return layerList;
}
@Override
public List<Pair<String, BufferedImage>> getLegends( int width ) {
ArrayList<Pair<String, BufferedImage>> legends = new ArrayList<Pair<String, BufferedImage>>();
BufferedImage legend = null;
String name = datasource.getName() != null ? datasource.getName() : datasource.getUrl();
try {
org.deegree.style.se.unevaluated.Style style = getStyle( datasource.getStyle() );
if ( style != null ) {
legend = getLegendImg( style, width );
}
} catch ( Exception e ) {
LOG.debug( "Could not create legend for wfs datasource '{}': {}", name, e.getMessage() );
}
legends.add( new Pair<String, BufferedImage>( name, legend ) );
return legends;
}
}
private File writeImage( BufferedImage bi )
throws ProcessletException {
FileOutputStream fos = null;
try {
File f = File.createTempFile( "image", ".png" );
fos = new FileOutputStream( f );
PNGEncodeParam encodeParam = PNGEncodeParam.getDefaultEncodeParam( bi );
if ( encodeParam instanceof PNGEncodeParam.Palette ) {
PNGEncodeParam.Palette p = (PNGEncodeParam.Palette) encodeParam;
byte[] b = new byte[] { -127 };
p.setPaletteTransparency( b );
}
com.sun.media.jai.codec.ImageEncoder encoder = ImageCodec.createImageEncoder( "PNG", fos, encodeParam );
encoder.encode( bi.getData(), bi.getColorModel() );
LOG.debug( "Wrote image to file: {}", f.toString() );
return f;
} catch ( IOException e ) {
String msg = "Could not write image to file: " + e.getMessage();
LOG.debug( msg, e );
throw new ProcessletException( msg );
} finally {
IOUtils.closeQuietly( fos );
}
}
}
|
deegree-processproviders/deegree-processprovider-jrxml/src/main/java/org/deegree/services/wps/provider/jrxml/contentprovider/MapContentProvider.java
|
//$HeadURL: svn+ssh://[email protected]/deegree/base/trunk/resources/eclipse/files_template.xml $
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2010 by:
- Department of Geography, University of Bonn -
and
- lat/lon GmbH -
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 2.1 of the License, or (at your option)
any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
e-mail: [email protected]
----------------------------------------------------------------------------*/
package org.deegree.services.wps.provider.jrxml.contentprovider;
import static java.awt.RenderingHints.KEY_ANTIALIASING;
import static java.awt.RenderingHints.KEY_TEXT_ANTIALIASING;
import static java.awt.RenderingHints.VALUE_ANTIALIAS_ON;
import static java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_ON;
import static org.deegree.commons.xml.stax.XMLStreamUtils.nextElement;
import static org.deegree.services.wps.provider.jrxml.JrxmlUtils.JASPERREPORTS_NS;
import static org.deegree.services.wps.provider.jrxml.JrxmlUtils.getAsCodeType;
import static org.deegree.services.wps.provider.jrxml.JrxmlUtils.getAsLanguageStringType;
import static org.deegree.services.wps.provider.jrxml.JrxmlUtils.nsContext;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.media.jai.JAI;
import javax.media.jai.RenderedOp;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.namespace.QName;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.dom.DOMSource;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.commons.io.IOUtils;
import org.deegree.commons.tom.ows.CodeType;
import org.deegree.commons.utils.Pair;
import org.deegree.commons.utils.Triple;
import org.deegree.commons.xml.XMLAdapter;
import org.deegree.commons.xml.XPath;
import org.deegree.cs.coordinatesystems.ICRS;
import org.deegree.cs.persistence.CRSManager;
import org.deegree.feature.Feature;
import org.deegree.feature.xpath.FeatureXPathEvaluator;
import org.deegree.geometry.Envelope;
import org.deegree.geometry.Geometry;
import org.deegree.geometry.standard.DefaultEnvelope;
import org.deegree.geometry.standard.primitive.DefaultPoint;
import org.deegree.gml.GMLVersion;
import org.deegree.gml.feature.StreamFeatureCollection;
import org.deegree.process.jaxb.java.ComplexFormatType;
import org.deegree.process.jaxb.java.ComplexInputDefinition;
import org.deegree.process.jaxb.java.ProcessletInputDefinition;
import org.deegree.protocol.wfs.client.WFSClient;
import org.deegree.protocol.wms.Utils;
import org.deegree.protocol.wms.ops.GetMap;
import org.deegree.remoteows.wms.WMSClient111;
import org.deegree.rendering.r2d.Java2DRenderer;
import org.deegree.rendering.r2d.legends.Legends;
import org.deegree.services.wps.ProcessletException;
import org.deegree.services.wps.ProcessletInputs;
import org.deegree.services.wps.input.ComplexInput;
import org.deegree.services.wps.input.ProcessletInput;
import org.deegree.services.wps.provider.jrxml.JrxmlUtils;
import org.deegree.services.wps.provider.jrxml.jaxb.map.AbstractDatasourceType;
import org.deegree.services.wps.provider.jrxml.jaxb.map.Center;
import org.deegree.services.wps.provider.jrxml.jaxb.map.Detail;
import org.deegree.services.wps.provider.jrxml.jaxb.map.Layer;
import org.deegree.services.wps.provider.jrxml.jaxb.map.Style;
import org.deegree.services.wps.provider.jrxml.jaxb.map.WFSDatasource;
import org.deegree.services.wps.provider.jrxml.jaxb.map.WMSDatasource;
import org.deegree.style.se.parser.SymbologyParser;
import org.deegree.style.styling.Styling;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sun.media.jai.codec.ImageCodec;
import com.sun.media.jai.codec.MemoryCacheSeekableStream;
import com.sun.media.jai.codec.PNGEncodeParam;
import com.sun.media.jai.codec.SeekableStream;
/**
* Provides a map in the jrxml
*
* @author <a href="mailto:[email protected]">Lyn Goltz</a>
* @author last edited by: $Author: lyn $
*
* @version $Revision: $, $Date: $
*/
public class MapContentProvider implements JrxmlContentProvider {
private static final Logger LOG = LoggerFactory.getLogger( MapContentProvider.class );
final static String SCHEMA = "http://www.deegree.org/processprovider/map";
final static String MIME_TYPE = "text/xml";
private static final String PARAM_PREFIX = "map";
final double INCH2M = 0.0254;
private enum SUFFIXES {
LEGEND_SUFFIX( "_legend" ), MAP_SUFFIX( "_img" ), SCALE_SUFFIX( "_scale" ), LAYERLIST_SUFFIX( "_layerlist" ), SCALEBAR_SUFFIX(
"_scalebar" );
private final String text;
private SUFFIXES( String text ) {
this.text = text;
}
private String getText() {
return text;
}
}
@Override
public void inspectInputParametersFromJrxml( List<JAXBElement<? extends ProcessletInputDefinition>> inputs,
XMLAdapter jrxmlAdapter, Map<String, String> parameters,
List<String> handledParameters ) {
// for a wms, parameters starting with 'map' are important. three different types are supported:
// * wmsXYZ_map -> as image parameter
// * wmsXYZ_legend -> as imgage parameter
// * wmsXYZ_layerList -> as frame key
// where XYZ is a string which is the identifier of the process parameter.
List<String> mapIds = new ArrayList<String>();
for ( String parameterName : parameters.keySet() ) {
if ( !handledParameters.contains( parameterName ) ) {
if ( jrxmlAdapter.getElement( jrxmlAdapter.getRootElement(),
new XPath( ".//jasper:image/jasper:imageExpression[text()='$P{"
+ parameterName + "}']", JrxmlUtils.nsContext ) ) != null
|| jrxmlAdapter.getElement( jrxmlAdapter.getRootElement(),
new XPath(
".//jasper:textField/jasper:textFieldExpression[text()='$P{"
+ parameterName + "}']",
JrxmlUtils.nsContext ) ) != null ) {
if ( isMapParameter( parameterName ) ) {
String mapId = getIdentifierFromParameter( parameterName );
if ( !mapIds.contains( mapId ) ) {
mapIds.add( mapId );
}
// TODO: maybe a status information would be the better way?
// remove used parameter
handledParameters.add( parameterName );
}
}
}
}
for ( String mapId : mapIds ) {
LOG.debug( "Found map component with id " + mapId );
ComplexInputDefinition comp = new ComplexInputDefinition();
comp.setTitle( getAsLanguageStringType( mapId ) );
comp.setIdentifier( getAsCodeType( mapId ) );
ComplexFormatType format = new ComplexFormatType();
format.setEncoding( "UTF-8" );
format.setMimeType( MIME_TYPE );
format.setSchema( SCHEMA );
comp.setDefaultFormat( format );
comp.setMaxOccurs( BigInteger.valueOf( 1 ) );
comp.setMinOccurs( BigInteger.valueOf( 0 ) );
inputs.add( new JAXBElement<ComplexInputDefinition>( new QName( "ProcessInput" ),
ComplexInputDefinition.class, comp ) );
}
}
private String getIdentifierFromParameter( String parameter ) {
if ( isMapParameter( parameter ) ) {
for ( SUFFIXES suf : SUFFIXES.values() ) {
if ( parameter.endsWith( suf.getText() ) ) {
parameter = parameter.substring( PARAM_PREFIX.length(), parameter.length() - suf.getText().length() );
}
}
}
return parameter;
}
private String getParameterFromIdentifier( String mapId, SUFFIXES suffix ) {
return PARAM_PREFIX + mapId + suffix.text;
}
private boolean isMapParameter( String imgParameter ) {
boolean hasSuffix = false;
for ( SUFFIXES suf : SUFFIXES.values() ) {
if ( imgParameter.endsWith( suf.getText() ) ) {
hasSuffix = true;
}
}
return hasSuffix && imgParameter.startsWith( PARAM_PREFIX );
}
@Override
public InputStream prepareJrxmlAndReadInputParameters( InputStream jrxml, Map<String, Object> params,
ProcessletInputs in, List<CodeType> processedIds,
Map<String, String> parameters )
throws ProcessletException {
for ( ProcessletInput input : in.getParameters() ) {
if ( !processedIds.contains( input ) && input instanceof ComplexInput ) {
ComplexInput complexIn = (ComplexInput) input;
if ( SCHEMA.equals( complexIn.getSchema() ) && MIME_TYPE.equals( complexIn.getMimeType() ) ) {
String mapId = complexIn.getIdentifier().getCode();
LOG.debug( "Found input parameter " + mapId + " representing a map!" );
try {
// JAXBContext jc = JAXBContext.newInstance( "org.deegree.services.wps.provider.jrxml.jaxb.map"
// );
JAXBContext jc = JAXBContext.newInstance( org.deegree.services.wps.provider.jrxml.jaxb.map.Map.class );
Unmarshaller unmarshaller = jc.createUnmarshaller();
org.deegree.services.wps.provider.jrxml.jaxb.map.Map map = (org.deegree.services.wps.provider.jrxml.jaxb.map.Map) unmarshaller.unmarshal( complexIn.getValueAsXMLStream() );
XMLAdapter jrxmlAdapter = new XMLAdapter( jrxml );
OMElement root = jrxmlAdapter.getRootElement();
List<OrderedDatasource<?>> datasources = anaylizeRequestOrder( map.getDatasources().getWMSDatasourceOrWFSDatasource() );
// MAP
int resolution = map.getResolution().intValue();
String mapKey = getParameterFromIdentifier( mapId, SUFFIXES.MAP_SUFFIX );
if ( parameters.containsKey( mapKey ) ) {
OMElement mapImgRep = jrxmlAdapter.getElement( root,
new XPath(
".//jasper:image[jasper:imageExpression/text()='$P{"
+ mapKey
+ "}']/jasper:reportElement",
nsContext ) );
if ( mapImgRep == null ) {
LOG.info( "Could not find image tag in the jrxml for map parameter '" + mapKey + "'" );
break;
}
int width = jrxmlAdapter.getRequiredNodeAsInteger( mapImgRep, new XPath( "@width",
nsContext ) );
int height = jrxmlAdapter.getRequiredNodeAsInteger( mapImgRep, new XPath( "@height",
nsContext ) );
width = adjustSpan( width, resolution );
height = adjustSpan( height, resolution );
Envelope bbox = calculateBBox( map.getDetail(), mapId, width, height, resolution );
params.put( mapKey, prepareMap( datasources, parameters.get( mapKey ), width, height, bbox ) );
// SCALE
double scale = Utils.calcScaleWMS130( width, height, bbox, bbox.getCoordinateSystem() );
String scaleKey = getParameterFromIdentifier( mapId, SUFFIXES.SCALE_SUFFIX );
if ( parameters.containsKey( scaleKey ) ) {
params.put( scaleKey, convert( scale, parameters.get( scaleKey ) ) );
}
// SCALEBAR
String scalebarKey = getParameterFromIdentifier( mapId, SUFFIXES.SCALEBAR_SUFFIX );
if ( parameters.containsKey( scalebarKey ) ) {
prepareScaleBar( params, scalebarKey, jrxmlAdapter, datasources,
parameters.get( scalebarKey ), bbox, width );
}
}
// LAYERLIST
prepareLayerlist( getParameterFromIdentifier( mapId, SUFFIXES.LAYERLIST_SUFFIX ), jrxmlAdapter,
map, datasources );
// LEGEND
String legendKey = getParameterFromIdentifier( mapId, SUFFIXES.LEGEND_SUFFIX );
if ( parameters.containsKey( legendKey ) ) {
params.put( legendKey,
prepareLegend( legendKey, jrxmlAdapter, datasources,
parameters.get( legendKey ), resolution ) );
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
if ( LOG.isDebugEnabled() ) {
LOG.debug( "Adjusted jrxml: " + jrxmlAdapter.getRootElement() );
}
jrxmlAdapter.getRootElement().serialize( bos );
jrxml = new ByteArrayInputStream( bos.toByteArray() );
} catch ( XMLStreamException e ) {
throw new RuntimeException( e );
} finally {
IOUtils.closeQuietly( bos );
}
} catch ( JAXBException e ) {
String msg = "Could not parse map configuration from parameter '" + complexIn.getIdentifier()
+ "': " + e.getMessage();
LOG.debug( msg, e );
throw new ProcessletException( msg );
} catch ( IOException e ) {
String msg = "Could not read map configuration from parameter '" + complexIn.getIdentifier()
+ "': " + e.getMessage();
LOG.debug( msg, e );
throw new ProcessletException( msg );
} catch ( XMLStreamException e ) {
String msg = "Could not read map configuration as xml from parameter '"
+ complexIn.getIdentifier() + "': " + e.getMessage();
LOG.debug( msg, e );
throw new ProcessletException( msg );
}
processedIds.add( input.getIdentifier() );
}
}
}
return jrxml;
}
private int adjustSpan( int inPxFromJrxml, int resolution ) {
// jasper assumes a resolution of 72 dpi
return new Double( inPxFromJrxml / 72d * resolution ).intValue();
}
private Envelope calculateBBox( Detail detail, String id, int mapWidth, int mapHeight, int dpi )
throws ProcessletException {
ICRS crs = CRSManager.getCRSRef( detail.getCrs() );
Center center = detail.getCenter();
Envelope bbox = null;
if ( center != null ) {
int scaleDenominator = center.getScaleDenominator().intValue();
String[] coords = center.getValue().split( "," );
double pixelSize = INCH2M / dpi;
double w2 = ( scaleDenominator * pixelSize * mapWidth ) / 2d;
double x1 = Double.parseDouble( coords[0] ) - w2;
double x2 = Double.parseDouble( coords[0] ) + w2;
w2 = ( scaleDenominator * pixelSize * mapHeight ) / 2d;
double y1 = Double.parseDouble( coords[1] ) - w2;
double y2 = Double.parseDouble( coords[1] ) + w2;
bbox = new DefaultEnvelope( null, crs, null, new DefaultPoint( null, crs, null, new double[] { x1, y1 } ),
new DefaultPoint( null, crs, null, new double[] { x2, y2 } ) );
} else if ( detail.getBbox() != null ) {
String[] coords = detail.getBbox().split( "," );
double bboxXmin = Double.parseDouble( coords[0] );
double bboxYmin = Double.parseDouble( coords[1] );
double bboxXmax = Double.parseDouble( coords[2] );
double bboxYmax = Double.parseDouble( coords[3] );
double bboxWidth = bboxXmax - bboxXmin;
double bboxHeight = bboxYmax - bboxYmin;
double bboxAspectRatio = bboxWidth / bboxHeight;
double printAspectRatio = ( (double) mapWidth ) / mapHeight;
if ( bboxAspectRatio > printAspectRatio ) {
double centerY = bboxYmin + ( ( bboxYmax - bboxYmin ) / 2d );
double height = bboxWidth * ( 1.0 / printAspectRatio );
double minY = centerY - ( height / 2d );
double maxY = centerY + ( height / 2d );
bbox = new DefaultEnvelope( null, crs, null, new DefaultPoint( null, crs, null, new double[] {
bboxXmin,
minY } ),
new DefaultPoint( null, crs, null, new double[] { bboxXmax, maxY } ) );
} else {
double centerX = bboxXmin + ( ( bboxXmax - bboxXmin ) / 2d );
double width = bboxHeight * printAspectRatio;
double minX = centerX - ( width / 2d );
double maxX = centerX + ( width / 2d );
bbox = new DefaultEnvelope( null, crs, null, new DefaultPoint( null, crs, null,
new double[] { minX, bboxYmin } ),
new DefaultPoint( null, crs, null, new double[] { maxX, bboxYmax } ) );
}
} else {
throw new ProcessletException(
"Could not parse required parameter bbox or center for map component with id '"
+ id + "'." );
}
LOG.debug( "requested and adjusted bbox: {}", bbox );
return bbox;
}
private void prepareScaleBar( Map<String, Object> params, String scalebarKey, XMLAdapter jrxmlAdapter,
List<OrderedDatasource<?>> datasources, String type, Envelope bbox, double mapWidth )
throws ProcessletException {
OMElement sbRep = jrxmlAdapter.getElement( jrxmlAdapter.getRootElement(),
new XPath( ".//jasper:image[jasper:imageExpression/text()='$P{"
+ scalebarKey + "}']/jasper:reportElement", nsContext ) );
if ( sbRep != null ) {
// TODO: rework this!
LOG.debug( "Found scalebar with key '" + scalebarKey + "'." );
int w = jrxmlAdapter.getRequiredNodeAsInteger( sbRep, new XPath( "@width", nsContext ) );
int h = jrxmlAdapter.getRequiredNodeAsInteger( sbRep, new XPath( "@height", nsContext ) );
BufferedImage img = new BufferedImage( w, h, BufferedImage.TYPE_INT_ARGB );
Graphics2D g = img.createGraphics();
String fontName = null;
int fontSize = 8;
int desiredWidth = w - 30;
// calculate scale bar max scale and size
int length = 0;
double lx = 0;
double scale = 0;
for ( int i = 0; i < 100; i++ ) {
double k = 0;
double dec = 30 * Math.pow( 10, i );
for ( int j = 0; j < 9; j++ ) {
k += dec;
double tx = -k * ( mapWidth / bbox.getSpan0() );
if ( Math.abs( tx - lx ) < desiredWidth ) {
length = (int) Math.round( Math.abs( tx - lx ) );
scale = k;
} else {
break;
}
}
}
// draw scale bar base line
g.setStroke( new BasicStroke( ( desiredWidth + 30 ) / 250 ) );
g.setColor( Color.black );
g.drawLine( 10, 30, length + 10, 30 );
double dx = length / 3d;
double vdx = scale / 3;
double div = 1;
String uom = "m";
if ( scale > 1000 ) {
div = 1000;
uom = "km";
}
// draw scale bar scales
if ( fontName == null ) {
fontName = "SANS SERIF";
}
g.setFont( new Font( fontName, Font.PLAIN, fontSize ) );
DecimalFormat df = new DecimalFormat( "##.# " );
DecimalFormat dfWithUom = new DecimalFormat( "##.# " + uom );
for ( int i = 0; i < 4; i++ ) {
String label = i < 3 ? df.format( ( vdx * i ) / div ) : dfWithUom.format( ( vdx * i ) / div );
g.drawString( label, (int) Math.round( 10 + i * dx ) - 8, 10 );
g.drawLine( (int) Math.round( 10 + i * dx ), 30, (int) Math.round( 10 + i * dx ), 20 );
}
for ( int i = 0; i < 7; i++ ) {
g.drawLine( (int) Math.round( 10 + i * dx / 2d ), 30, (int) Math.round( 10 + i * dx / 2d ), 25 );
}
g.dispose();
params.put( scalebarKey, convertImageToReportFormat( type, img ) );
LOG.debug( "added scalebar" );
}
}
private Object convert( double scale, String parameterType ) {
if ( parameterType == null || "java.lang.String".equals( parameterType ) ) {
return Double.toString( scale );
} else if ( "java.lang.Integer".equals( parameterType ) ) {
return new Double( scale ).intValue();
} else if ( "java.lang.Float".equals( parameterType ) ) {
return new Double( scale ).floatValue();
} else if ( "java.lang.Long".equals( parameterType ) ) {
return new Double( scale ).longValue();
} else if ( "java.math.BigDecimal".equals( parameterType ) ) {
return new BigDecimal( scale );
} else if ( "java.lang.Short".equals( parameterType ) ) {
return new Double( scale ).shortValue();
} else if ( "java.lang.Byte".equals( parameterType ) ) {
return new Double( scale ).byteValue();
}
return scale;
}
private Object prepareLegend( String legendKey, XMLAdapter jrxmlAdapter, List<OrderedDatasource<?>> datasources,
String type, int resolution )
throws ProcessletException {
OMElement legendRE = jrxmlAdapter.getElement( jrxmlAdapter.getRootElement(),
new XPath( ".//jasper:image[jasper:imageExpression/text()='$P{"
+ legendKey + "}']/jasper:reportElement", nsContext ) );
if ( legendRE != null ) {
LOG.debug( "Found legend with key '" + legendKey + "'." );
int width = jrxmlAdapter.getRequiredNodeAsInteger( legendRE, new XPath( "@width", nsContext ) );
int height = jrxmlAdapter.getRequiredNodeAsInteger( legendRE, new XPath( "@height", nsContext ) );
width = adjustSpan( width, resolution );
height = adjustSpan( height, resolution );
// TODO: bgcolor?
Color bg = Color.decode( "0xFFFFFF" );
BufferedImage bi = new BufferedImage( width, height, BufferedImage.TYPE_INT_ARGB );
Graphics g = bi.getGraphics();
g.setColor( bg );
g.fillRect( 0, 0, bi.getWidth(), bi.getHeight() );
g.setColor( Color.BLACK );
int k = 0;
for ( int i = 0; i < datasources.size(); i++ ) {
if ( k > bi.getHeight() ) {
LOG.warn( "The necessary legend size is larger than the available legend space." );
}
List<Pair<String, BufferedImage>> legends = datasources.get( i ).getLegends( width );
for ( Pair<String, BufferedImage> legend : legends ) {
BufferedImage img = legend.second;
if ( img != null ) {
if ( img.getWidth( null ) < 50 ) {
// it is assumed that no label is assigned
g.drawImage( img, 0, k, null );
g.drawString( legend.first, img.getWidth( null ) + 10, k + img.getHeight( null ) / 2 );
} else {
g.drawImage( img, 0, k, null );
}
k = k + img.getHeight( null ) + 10;
} else {
g.drawString( "- " + legend.first, 0, k + 10 );
k = k + 20;
}
}
}
g.dispose();
return convertImageToReportFormat( type, bi );
}
return null;
}
private void prepareLayerlist( String layerListKey, XMLAdapter jrxmlAdapter,
org.deegree.services.wps.provider.jrxml.jaxb.map.Map map,
List<OrderedDatasource<?>> datasources ) {
OMElement layerListFrame = jrxmlAdapter.getElement( jrxmlAdapter.getRootElement(),
new XPath(
".//jasper:band/jasper:frame[jasper:reportElement/@key='"
+ layerListKey + "']",
nsContext ) );
if ( layerListFrame != null ) {
LOG.debug( "Found layer list with key '{}' to adjust.", layerListKey );
List<OMElement> elements = jrxmlAdapter.getElements( layerListFrame, new XPath( "jasper:staticText",
nsContext ) );
if ( elements.size() > 1 ) {
OMElement grpTemplate = elements.get( 0 );
OMElement fieldTemplate = elements.get( 1 );
for ( OMElement element : elements ) {
element.detach();
}
XMLAdapter grpAdapter = new XMLAdapter( grpTemplate );
int grpHeight = grpAdapter.getNodeAsInt( grpTemplate, new XPath( "jasper:reportElement/@height",
nsContext ), 15 );
int grpY = grpAdapter.getNodeAsInt( grpTemplate, new XPath( "jasper:reportElement/@y", nsContext ), 0 );
XMLAdapter fieldAdapter = new XMLAdapter( fieldTemplate );
int fieldHeight = fieldAdapter.getNodeAsInt( fieldTemplate, new XPath( "jasper:reportElement/@height",
nsContext ), 15 );
OMFactory factory = OMAbstractFactory.getOMFactory();
// y + height * index
int y = grpY;
for ( OrderedDatasource<?> datasource : datasources ) {
for ( String datasourceKey : datasource.getLayerList().keySet() ) {
OMElement newGrp = createLayerEntry( grpTemplate, y, factory, datasourceKey );
layerListFrame.addChild( newGrp );
y += grpHeight;
for ( String layerName : datasource.getLayerList().get( datasourceKey ) ) {
OMElement newField = createLayerEntry( fieldTemplate, y, factory, layerName );
layerListFrame.addChild( newField );
y += fieldHeight;
}
}
}
} else {
LOG.info( "layerlist frame with key '{}' must have at least two child elements", layerListKey );
}
} else {
LOG.debug( "no layer list with key '{}' found.", layerListKey );
}
}
private OMElement createLayerEntry( OMElement template, int y, OMFactory factory, String text ) {
OMElement newGrp = template.cloneOMElement();
OMElement e = newGrp.getFirstChildWithName( new QName( JASPERREPORTS_NS, "reportElement" ) );
e.addAttribute( "y", Integer.toString( y ), null );
e = newGrp.getFirstChildWithName( new QName( JASPERREPORTS_NS, "text" ) );
// this does not work:
// e.setText( layer );
// it attaches the text, but does not replace
e.getFirstOMChild().detach();
e.addChild( factory.createOMText( e, text ) );
return newGrp;
}
private Object prepareMap( List<OrderedDatasource<?>> datasources, String type, int width, int height, Envelope bbox )
throws ProcessletException {
BufferedImage bi = new BufferedImage( width, height, BufferedImage.TYPE_INT_ARGB );
Graphics g = bi.getGraphics();
for ( OrderedDatasource<?> datasource : datasources ) {
BufferedImage image = datasource.getImage( width, height, bbox );
if ( image != null ) {
g.drawImage( image, 0, 0, null );
}
}
g.dispose();
return convertImageToReportFormat( type, bi );
}
private Object convertImageToReportFormat( String type, BufferedImage bi )
throws ProcessletException {
if ( type != null && type.equals( "java.io.File" ) ) {
return writeImage( bi );
} else if ( type != null && type.equals( "java.net.URL" ) ) {
try {
return writeImage( bi ).toURI().toURL();
} catch ( MalformedURLException e ) {
LOG.error( "Could not create url: ", e );
}
} else if ( type != null && type.equals( "java.io.InputStream" ) ) {
try {
return new FileInputStream( writeImage( bi ) );
} catch ( FileNotFoundException e ) {
LOG.error( "Could not open stream: ", e );
}
} else if ( type != null && type.equals( "java.awt.Image" ) ) {
return bi;
}
return writeImage( bi ).toString();
}
List<OrderedDatasource<?>> anaylizeRequestOrder( List<AbstractDatasourceType> datasources ) {
List<OrderedDatasource<?>> orderedDatasources = new ArrayList<OrderedDatasource<?>>();
for ( AbstractDatasourceType datasource : datasources ) {
if ( datasource instanceof WMSDatasource ) {
WMSDatasource wmsDatasource = (WMSDatasource) datasource;
List<Layer> layers = wmsDatasource.getLayers().getLayer();
int index = 0;
for ( Layer layer : layers ) {
BigInteger position = layer.getPosition();
if ( position != null ) {
int intPos = position.intValue();
WMSOrderedDatasource contains = contains( orderedDatasources, wmsDatasource, intPos );
// splitten! wenn position zwischen zwei
if ( contains != null ) {
List<Layer> orderedLayers = contains.layers;
int i = 0;
for ( Layer orderedLayer : orderedLayers ) {
if ( orderedLayer.getPosition().intValue() < intPos ) {
i++;
}
}
contains.layers.add( i, layer );
contains.min = contains.min < intPos ? contains.min : intPos;
contains.max = contains.max > intPos ? contains.max : intPos;
} else {
List<Layer> newLayerList = new ArrayList<Layer>();
newLayerList.add( layer );
int indexToAdd = getIndexToAdd( orderedDatasources, intPos );
orderedDatasources.add( indexToAdd, new WMSOrderedDatasource( wmsDatasource, newLayerList,
intPos, intPos ) );
}
} else {
WMSOrderedDatasource contains = contains( orderedDatasources, wmsDatasource );
if ( contains != null ) {
contains.layers.add( layer );
} else {
List<Layer> newLayerList = new ArrayList<Layer>();
newLayerList.add( layer );
orderedDatasources.add( new WMSOrderedDatasource( wmsDatasource, newLayerList ) );
}
}
index++;
}
} else if ( datasource instanceof WFSDatasource ) {
WFSDatasource wfsDatasource = (WFSDatasource) datasource;
WFSOrderedDatasource newDatasource = new WFSOrderedDatasource( wfsDatasource );
if ( wfsDatasource.getPosition() != null ) {
int indexToAdd = getIndexToAdd( orderedDatasources, wfsDatasource.getPosition().intValue() );
orderedDatasources.add( indexToAdd, newDatasource );
} else {
orderedDatasources.add( newDatasource );
}
}
}
return orderedDatasources;
}
private int getIndexToAdd( List<OrderedDatasource<?>> orderedDatasources, int intPos ) {
int indexToAdd = 0;
boolean isBetween = false;
for ( OrderedDatasource<?> orderedDatasource : orderedDatasources ) {
if ( orderedDatasource.min > 0 && intPos > orderedDatasource.min && intPos < orderedDatasource.max ) {
indexToAdd++;
isBetween = true;
break;
} else if ( orderedDatasource.min > 0 && intPos > orderedDatasource.max ) {
indexToAdd++;
} else {
break;
}
}
if ( isBetween ) {
OrderedDatasource<?> dsToSplit = orderedDatasources.get( indexToAdd - 1 );
if ( dsToSplit instanceof WMSOrderedDatasource ) {
List<Layer> newLayerListFromSplit = new ArrayList<Layer>();
int newMinPos = 0;
int newMaxPos = 0;
for ( Layer l : ( (WMSOrderedDatasource) dsToSplit ).layers ) {
if ( l.getPosition() != null && l.getPosition().intValue() > intPos ) {
newLayerListFromSplit.add( l );
newMinPos = Math.min( l.getPosition().intValue(), newMinPos );
newMaxPos = Math.max( l.getPosition().intValue(), newMaxPos );
}
}
for ( Layer lToRemove : newLayerListFromSplit ) {
( (WMSOrderedDatasource) dsToSplit ).layers.remove( lToRemove );
}
orderedDatasources.add( indexToAdd, new WMSOrderedDatasource( (WMSDatasource) dsToSplit.datasource,
newLayerListFromSplit, intPos, intPos ) );
}
}
return indexToAdd;
}
private WMSOrderedDatasource contains( List<OrderedDatasource<?>> orderedDatasources, WMSDatasource datasource,
int index ) {
int i = 0;
for ( OrderedDatasource<?> orderedDatasource : orderedDatasources ) {
if ( orderedDatasource.datasource.equals( datasource ) ) {
WMSOrderedDatasource wmsOrderedDatasource = (WMSOrderedDatasource) orderedDatasource;
int maxBefore = Integer.MIN_VALUE;
int minNext = Integer.MIN_VALUE;
if ( i - 1 > 0 && i - 1 < orderedDatasources.size() ) {
maxBefore = orderedDatasources.get( i - 1 ).max;
}
if ( i + 1 < orderedDatasources.size() ) {
minNext = orderedDatasources.get( i + 1 ).min;
}
if ( index > maxBefore && ( minNext < 0 || index < minNext ) ) {
return wmsOrderedDatasource;
}
}
i++;
}
return null;
}
private WMSOrderedDatasource contains( List<OrderedDatasource<?>> orderedDatasources, WMSDatasource datasource ) {
for ( OrderedDatasource<?> orderedDatasource : orderedDatasources ) {
if ( orderedDatasource.datasource.equals( datasource ) ) {
return (WMSOrderedDatasource) orderedDatasource;
}
}
return null;
}
abstract class OrderedDatasource<T extends AbstractDatasourceType> {
// OrderedDatasource
// abstract String getRequest( int width, int height, String bbox, String crs );
int min = Integer.MIN_VALUE;
int max = Integer.MIN_VALUE;
final T datasource;
public OrderedDatasource( T datasource ) {
this.datasource = datasource;
}
public abstract List<Pair<String, BufferedImage>> getLegends( int width )
throws ProcessletException;
public OrderedDatasource( T datasource, int min, int max ) {
this.datasource = datasource;
this.min = min;
this.max = max;
}
abstract BufferedImage getImage( int width, int height, Envelope bbox )
throws ProcessletException;
abstract Map<String, List<String>> getLayerList();
protected org.deegree.style.se.unevaluated.Style getStyle( Style dsStyle )
throws MalformedURLException, FactoryConfigurationError, XMLStreamException,
IOException {
XMLStreamReader reader = null;
if ( dsStyle == null || dsStyle.getNamedStyle() != null ) {
return null;
} else if ( dsStyle.getExternalStyle() != null ) {
URL ex = new URL( dsStyle.getExternalStyle() );
XMLInputFactory fac = XMLInputFactory.newInstance();
reader = fac.createXMLStreamReader( ex.openStream() );
} else if ( dsStyle.getEmbeddedStyle() != null ) {
XMLInputFactory fac = XMLInputFactory.newInstance();
reader = fac.createXMLStreamReader( new DOMSource( dsStyle.getEmbeddedStyle() ) );
nextElement( reader );
nextElement( reader );
}
SymbologyParser symbologyParser = SymbologyParser.INSTANCE;
return symbologyParser.parse( reader );
}
protected BufferedImage getLegendImg( org.deegree.style.se.unevaluated.Style style, int width ) {
Legends legends = new Legends();
Pair<Integer, Integer> legendSize = legends.getLegendSize( style );
if ( legendSize.first < width )
width = legendSize.first;
BufferedImage img = new BufferedImage( width, legendSize.second, BufferedImage.TYPE_INT_ARGB );
Graphics2D g = img.createGraphics();
g.setRenderingHint( KEY_ANTIALIASING, VALUE_ANTIALIAS_ON );
g.setRenderingHint( KEY_TEXT_ANTIALIASING, VALUE_TEXT_ANTIALIAS_ON );
legends.paintLegend( style, width, legendSize.second, g );
g.dispose();
return img;
}
}
class WMSOrderedDatasource extends OrderedDatasource<WMSDatasource> {
List<Layer> layers;
public WMSOrderedDatasource( WMSDatasource datasource, List<Layer> layers ) {
super( datasource );
this.layers = layers;
}
public WMSOrderedDatasource( WMSDatasource datasource, List<Layer> layers, int min, int max ) {
super( datasource, min, max );
this.layers = layers;
}
@Override
BufferedImage getImage( int width, int height, Envelope bbox )
throws ProcessletException {
LOG.debug( "create map image for WMS datasource '{}'", datasource.getName() );
try {
String user = datasource.getAuthentification() != null ? datasource.getAuthentification().getUser()
: null;
String passw = datasource.getAuthentification() != null ? datasource.getAuthentification().getPassword()
: null;
// TODO: version
if ( !"1.1.1".equals( datasource.getVersion() ) ) {
throw new ProcessletException( "WMS version " + datasource.getVersion()
+ " is not yet supported. Supported values are: 1.1.1" );
}
String capUrl = datasource.getUrl() + "?request=GetCapabilities&service=WMS&version=1.1.1";
WMSClient111 wmsClient = new WMSClient111( new URL( capUrl ), 5, 60, user, passw );
List<String> layerNames = new ArrayList<String>();
for ( Layer l : layers ) {
layerNames.add( l.getName() );
}
// TODO: styles!
GetMap gm = new GetMap( layerNames, width, height, bbox, bbox.getCoordinateSystem(), "image/png", true );
Pair<BufferedImage, String> map = wmsClient.getMap( gm, null, 60, false );
if ( map.first == null )
LOG.debug( map.second );
return map.first;
} catch ( MalformedURLException e ) {
String msg = "could not reslove wms url " + datasource.getUrl() + "!";
LOG.error( msg, e );
throw new ProcessletException( msg );
} catch ( Exception e ) {
String msg = "could not get map!";
LOG.error( msg, e );
throw new ProcessletException( msg );
}
}
private BufferedImage loadImage( String request )
throws IOException {
LOG.debug( "try to load image from request " + request );
InputStream is = null;
SeekableStream fss = null;
try {
URLConnection conn = new URL( request ).openConnection();
is = conn.getInputStream();
if ( LOG.isDebugEnabled() ) {
File logFile = File.createTempFile( "loadedImg", "response" );
OutputStream logStream = new FileOutputStream( logFile );
byte[] buffer = new byte[1024];
int read = 0;
while ( ( read = is.read( buffer ) ) != -1 ) {
logStream.write( buffer, 0, read );
}
logStream.close();
is = new FileInputStream( logFile );
LOG.debug( "response can be found at " + logFile );
}
try {
fss = new MemoryCacheSeekableStream( is );
RenderedOp ro = JAI.create( "stream", fss );
return ro.getAsBufferedImage();
} catch ( Exception e ) {
LOG.info( "could not load image!" );
return null;
}
} finally {
IOUtils.closeQuietly( fss );
IOUtils.closeQuietly( is );
}
}
@Override
Map<String, List<String>> getLayerList() {
HashMap<String, List<String>> layerList = new HashMap<String, List<String>>();
ArrayList<String> layerNames = new ArrayList<String>( layers.size() );
for ( Layer layer : layers ) {
layerNames.add( layer.getTitle() != null ? layer.getTitle() : layer.getName() );
}
layerList.put( datasource.getName(), layerNames );
return layerList;
}
@Override
public List<Pair<String, BufferedImage>> getLegends( int width )
throws ProcessletException {
List<Pair<String, BufferedImage>> legends = new ArrayList<Pair<String, BufferedImage>>();
for ( Layer layer : layers ) {
String layerName = layer.getName();
try {
BufferedImage bi = null;
org.deegree.style.se.unevaluated.Style style = getStyle( layer.getStyle() );
if ( style != null ) {
bi = getLegendImg( style, width );
} else {
String legendUrl = getLegendUrl( layer );
LOG.debug( "Try to load legend image from WMS {}: ", legendUrl );
try {
bi = loadImage( legendUrl );
} catch ( IOException e ) {
String msg = "Could not create legend for layer: " + layerName;
LOG.error( msg );
throw new ProcessletException( msg );
}
}
legends.add( new Pair<String, BufferedImage>( layerName, bi ) );
} catch ( Exception e ) {
String dsName = datasource.getName() != null ? datasource.getName() : datasource.getUrl();
LOG.info( "Could not create legend image for datasource '" + dsName + "', layer " + layerName + ".",
e );
}
}
return legends;
}
String getLegendUrl( Layer layer ) {
String url = datasource.getUrl();
StringBuilder sb = new StringBuilder();
sb.append( url );
if ( !url.endsWith( "?" ) )
sb.append( '?' );
sb.append( "REQUEST=GetLegendGraphic&" );
sb.append( "SERVICE=WMS&" );
sb.append( "VERSION=" ).append( datasource.getVersion() ).append( '&' );
sb.append( "LAYER=" ).append( layer.getName() ).append( '&' );
sb.append( "TRANSPARENT=" ).append( "TRUE" ).append( '&' );
sb.append( "FORMAT=" ).append( "image/png" );
// .append( '&' );
// STYLES=
return sb.toString();
}
}
class WFSOrderedDatasource extends OrderedDatasource<WFSDatasource> {
public WFSOrderedDatasource( WFSDatasource datasource ) {
super( datasource );
}
public WFSOrderedDatasource( WFSDatasource datasource, int pos ) {
super( datasource, pos, pos );
}
@Override
BufferedImage getImage( int width, int height, Envelope bbox )
throws ProcessletException {
LOG.debug( "create map image for WFS datasource '{}'", datasource.getName() );
try {
String capURL = datasource.getUrl() + "?service=WFS&request=GetCapabilities&version="
+ datasource.getVersion();
WFSClient wfsClient = new WFSClient( new URL( capURL ) );
StreamFeatureCollection features = wfsClient.getFeatures( new QName(
datasource.getFeatureType().getValue(),
datasource.getFeatureType().getValue() ) );
BufferedImage image = new BufferedImage( width, height, BufferedImage.TYPE_INT_ARGB );
Graphics2D g = image.createGraphics();
Java2DRenderer renderer = new Java2DRenderer( g, width, height, bbox, bbox.getCoordinateDimension() /* pixelSize */);
// TODO
// XMLInputFactory fac = XMLInputFactory.newInstance();
// XMLStreamReader reader = fac.createXMLStreamReader( new DOMSource( datasource.getFilter() ) );
// nextElement( reader );
// nextElement( reader );
// Filter filter = Filter110XMLDecoder.parse( reader );
// reader.close();
org.deegree.style.se.unevaluated.Style style = getStyle( datasource.getStyle() );
if ( style != null && features != null ) {
Feature feature = null;
while ( ( feature = features.read() ) != null ) {
LinkedList<Triple<Styling, LinkedList<Geometry>, String>> evaluate = style.evaluate( feature,
new FeatureXPathEvaluator(
GMLVersion.GML_32 ) );
for ( Triple<Styling, LinkedList<Geometry>, String> triple : evaluate ) {
for ( Geometry geom : triple.second ) {
renderer.render( triple.first, geom );
}
}
}
}
g.dispose();
return image;
} catch ( Exception e ) {
String msg = "could nor create image from wfs datasource " + datasource.getName() + ": "
+ e.getMessage();
LOG.error( msg, e );
throw new ProcessletException( msg );
}
}
@Override
Map<String, List<String>> getLayerList() {
HashMap<String, List<String>> layerList = new HashMap<String, List<String>>();
layerList.put( datasource.getName(), new ArrayList<String>() );
return layerList;
}
@Override
public List<Pair<String, BufferedImage>> getLegends( int width ) {
ArrayList<Pair<String, BufferedImage>> legends = new ArrayList<Pair<String, BufferedImage>>();
BufferedImage legend = null;
String name = datasource.getName() != null ? datasource.getName() : datasource.getUrl();
try {
org.deegree.style.se.unevaluated.Style style = getStyle( datasource.getStyle() );
if ( style != null ) {
legend = getLegendImg( style, width );
}
} catch ( Exception e ) {
LOG.debug( "Could not create legend for wfs datasource '{}': {}", name, e.getMessage() );
}
legends.add( new Pair<String, BufferedImage>( name, legend ) );
return legends;
}
}
private File writeImage( BufferedImage bi )
throws ProcessletException {
FileOutputStream fos = null;
try {
File f = File.createTempFile( "image", ".png" );
fos = new FileOutputStream( f );
PNGEncodeParam encodeParam = PNGEncodeParam.getDefaultEncodeParam( bi );
if ( encodeParam instanceof PNGEncodeParam.Palette ) {
PNGEncodeParam.Palette p = (PNGEncodeParam.Palette) encodeParam;
byte[] b = new byte[] { -127 };
p.setPaletteTransparency( b );
}
com.sun.media.jai.codec.ImageEncoder encoder = ImageCodec.createImageEncoder( "PNG", fos, encodeParam );
encoder.encode( bi.getData(), bi.getColorModel() );
LOG.debug( "Wrote image to file: {}", f.toString() );
return f;
} catch ( IOException e ) {
String msg = "Could not write image to file: " + e.getMessage();
LOG.debug( msg, e );
throw new ProcessletException( msg );
} finally {
IOUtils.closeQuietly( fos );
}
}
}
|
support of styles; exception handling
|
deegree-processproviders/deegree-processprovider-jrxml/src/main/java/org/deegree/services/wps/provider/jrxml/contentprovider/MapContentProvider.java
|
support of styles; exception handling
|
<ide><path>eegree-processproviders/deegree-processprovider-jrxml/src/main/java/org/deegree/services/wps/provider/jrxml/contentprovider/MapContentProvider.java
<ide> }
<ide> String capUrl = datasource.getUrl() + "?request=GetCapabilities&service=WMS&version=1.1.1";
<ide> WMSClient111 wmsClient = new WMSClient111( new URL( capUrl ), 5, 60, user, passw );
<del> List<String> layerNames = new ArrayList<String>();
<add> List<Pair<String, String>> layerToStyle = new ArrayList<Pair<String, String>>();
<ide> for ( Layer l : layers ) {
<del> layerNames.add( l.getName() );
<del> }
<del>
<del> // TODO: styles!
<del> GetMap gm = new GetMap( layerNames, width, height, bbox, bbox.getCoordinateSystem(), "image/png", true );
<add> String style = l.getStyle() != null ? l.getStyle().getNamedStyle() : null;
<add> layerToStyle.add( new Pair<String, String>( l.getName(), style ) );
<add> }
<add> GetMap gm = new GetMap( layerToStyle, width, height, bbox, "image/png", true );
<ide> Pair<BufferedImage, String> map = wmsClient.getMap( gm, null, 60, false );
<ide> if ( map.first == null )
<del> LOG.debug( map.second );
<add> throw new ProcessletException( "Could not get map from datasource " + datasource.getName() + ": "
<add> + map.second );
<ide> return map.first;
<ide> } catch ( MalformedURLException e ) {
<del> String msg = "could not reslove wms url " + datasource.getUrl() + "!";
<add> String msg = "could not resolve wms url " + datasource.getUrl() + "!";
<ide> LOG.error( msg, e );
<ide> throw new ProcessletException( msg );
<ide> } catch ( Exception e ) {
<del> String msg = "could not get map!";
<add> String msg = "could not get map: " + e.getMessage();
<ide> LOG.error( msg, e );
<ide> throw new ProcessletException( msg );
<ide> }
<ide> sb.append( "VERSION=" ).append( datasource.getVersion() ).append( '&' );
<ide> sb.append( "LAYER=" ).append( layer.getName() ).append( '&' );
<ide> sb.append( "TRANSPARENT=" ).append( "TRUE" ).append( '&' );
<del> sb.append( "FORMAT=" ).append( "image/png" );
<del> // .append( '&' );
<del> // STYLES=
<add> sb.append( "FORMAT=" ).append( "image/png" ).append( '&' );
<add> if ( layer.getStyle() != null && layer.getStyle().getNamedStyle() != null ) {
<add> sb.append( "STYLE=" ).append( layer.getStyle().getNamedStyle() );
<add> }
<ide> return sb.toString();
<ide> }
<ide> }
|
|
JavaScript
|
mit
|
5dae208b07039649d80060d0f98feae8b0a456b6
| 0 |
ScienceCommons/www,ScienceCommons/www
|
/**
* @jsx React.DOM
*/
'use strict';
var React = require('react/addons');
var ReactTransitionGroup = React.addons.CSSTransitionGroup;
var Link = require('react-router-component').Link;
var Spinner = require('./Spinner.js');
var _ = require('underscore');
var SampleResults = require("../data.js").Articles;
var SearchResult = React.createClass({
/*jshint ignore:start */
render: function() {
var data = this.props.data;
if (data) {
var doi;
if (data.doi) {
doi = (
<span>| doi: <a href={"http://www.plosone.org/article/info"+encodeURIComponent(":doi/"+data.doi)} target="_blank">{data.doi}</a>
</span>
);
}
return (
<li className="search-result" key={data.id}>
<ReactTransitionGroup transitionName="fade">
<div>
<Link className="h3 link" href={"/articles/"+data.id}>{data.title}</Link>
<div className="h5">{data.publication_date} {doi}</div>
</div>
<p>{data.abstract}</p>
</ReactTransitionGroup>
</li>
);
} else {
return (<li />)
}
}
/*jshint ignore:end */
});
var SearchResults = React.createClass({
getInitialState: function() {
return {
results: [],
total: 0,
from: 0,
resultsPerPage: 20,
loading: true
};
},
componentWillMount: function() {
this.fetchResults();
},
componentWillUnmount: function() {
if (this.state.xhr) {
this.state.xhr.abort();
}
},
fetchResults: function() {
// this will be an xhr to our search server
var _this = this;
var query = _this.props.query;
if (!query) {
return
} else {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var res;
try {
res = JSON.parse(xhr.responseText) || {};
} catch (e) {
res = {};
};
_this.setState({
loading: false,
results: res.documents,
total: res.total,
from: res.from,
xhr: null
});
};
xhr.open("get", "http://api.papersearch.org/articles?q="+query+"&from="+this.state.from, true);
xhr.send();
_this.setState({ loading: true, xhr: xhr });
}
},
nextPage: function() {
this.state.from = this.state.from+this.state.resultsPerPage;
this.fetchResults();
},
/*jshint ignore:start */
render: function() {
var content;
var count;
var next;
if (this.state.loading) {
content = <li><Spinner /></li>;
} else if (this.state.total > 0) {
if (this.state.from + this.state.resultsPerPage < this.state.total) {
next = <span className="link" onClick={this.nextPage}>next page</span>;
}
count = <li>Showing {this.state.from+1} to {Math.min(this.state.total, this.state.from+this.state.resultsPerPage)} of {this.state.total} results {next}</li>
content = this.state.results.map(function(result) {
return <SearchResult data={result} />;
});
} else {
content = (
<li>
<h3>Sorry, no results were found</h3>
</li>
);
}
return (
<ul>
{count}
{content}
</ul>
);
}
/*jshint ignore:end */
});
module.exports = SearchResults;
|
src/scripts/components/SearchResults.js
|
/**
* @jsx React.DOM
*/
'use strict';
var React = require('react/addons');
var ReactTransitionGroup = React.addons.CSSTransitionGroup;
var Link = require('react-router-component').Link;
var Spinner = require('./Spinner.js');
var _ = require('underscore');
var SampleResults = require("../data.js").Articles;
var SearchResult = React.createClass({
/*jshint ignore:start */
render: function() {
var data = this.props.data;
if (data) {
var doi;
if (data.doi) {
doi = (
<span>| doi: <a href={"http://www.plosone.org/article/info"+encodeURIComponent(":doi/"+data.doi)} target="_blank">{data.doi}</a>
</span>
);
}
return (
<li className="search-result" key={data.id}>
<ReactTransitionGroup transitionName="fade">
<div>
<Link className="h3 link" href={"/articles/"+data.id}>{data.title}</Link>
<div className="h5">{data.publication_date} {doi}</div>
</div>
<p>{data.abstract}</p>
</ReactTransitionGroup>
</li>
);
} else {
return (<li />)
}
}
/*jshint ignore:end */
});
var SearchResults = React.createClass({
getInitialState: function() {
return {
results: [],
total: 0,
loading: true
};
},
componentWillMount: function() {
this.fetchResults();
},
componentWillUnmount: function() {
if (this.state.xhr) {
this.state.xhr.abort();
}
},
fetchResults: function() {
// this will be an xhr to our search server
var _this = this;
var query = _this.props.query;
if (!query) {
return
} else {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var res;
try {
res = JSON.parse(xhr.responseText) || {};
} catch (e) {
res = {};
};
_this.setState({
loading: false,
results: res.documents,
total: res.total,
from: res.from,
xhr: null
});
};
xhr.open("get", "http://api.papersearch.org/articles?q="+query, true);
xhr.send();
_this.setState({ loading: true, xhr: xhr });
}
},
/*jshint ignore:start */
render: function() {
var content;
var count;
if (this.state.loading) {
content = <li><Spinner /></li>;
} else if (this.state.total > 0) {
count = <li>Showing {this.state.from+1} to {this.state.from+20} of {this.state.total} results</li>
content = this.state.results.map(function(result) {
return <SearchResult data={result} />;
});
} else {
content = (
<li>
<h3>Sorry, no results were found</h3>
</li>
);
}
return (
<ul>
{count}
{content}
}
</ul>
);
}
/*jshint ignore:end */
});
module.exports = SearchResults;
|
SearchResults: allow users to page through results
|
src/scripts/components/SearchResults.js
|
SearchResults: allow users to page through results
|
<ide><path>rc/scripts/components/SearchResults.js
<ide> return {
<ide> results: [],
<ide> total: 0,
<add> from: 0,
<add> resultsPerPage: 20,
<ide> loading: true
<ide> };
<ide> },
<ide> });
<ide> };
<ide>
<del> xhr.open("get", "http://api.papersearch.org/articles?q="+query, true);
<add> xhr.open("get", "http://api.papersearch.org/articles?q="+query+"&from="+this.state.from, true);
<ide> xhr.send();
<ide>
<ide> _this.setState({ loading: true, xhr: xhr });
<ide> }
<ide> },
<add> nextPage: function() {
<add> this.state.from = this.state.from+this.state.resultsPerPage;
<add> this.fetchResults();
<add> },
<ide> /*jshint ignore:start */
<ide> render: function() {
<ide> var content;
<ide> var count;
<add> var next;
<ide>
<ide> if (this.state.loading) {
<ide> content = <li><Spinner /></li>;
<ide> } else if (this.state.total > 0) {
<del> count = <li>Showing {this.state.from+1} to {this.state.from+20} of {this.state.total} results</li>
<add> if (this.state.from + this.state.resultsPerPage < this.state.total) {
<add> next = <span className="link" onClick={this.nextPage}>next page</span>;
<add> }
<add> count = <li>Showing {this.state.from+1} to {Math.min(this.state.total, this.state.from+this.state.resultsPerPage)} of {this.state.total} results {next}</li>
<ide> content = this.state.results.map(function(result) {
<ide> return <SearchResult data={result} />;
<ide> });
<ide> <ul>
<ide> {count}
<ide> {content}
<del> }
<ide> </ul>
<ide> );
<ide> }
|
|
Java
|
bsd-3-clause
|
45adbf8059bf93369d6aad665d54ef1679e71daf
| 0 |
CBIIT/caaers,CBIIT/caaers,CBIIT/caaers,NCIP/caaers,CBIIT/caaers,NCIP/caaers,CBIIT/caaers,NCIP/caaers,NCIP/caaers
|
package gov.nih.nci.cabig.caaers.web.ae;
import gov.nih.nci.cabig.caaers.dao.RoutineAdverseEventReportDao;
import gov.nih.nci.cabig.caaers.dao.ExpeditedAdverseEventReportDao;
import gov.nih.nci.cabig.caaers.dao.StudyParticipantAssignmentDao;
import gov.nih.nci.cabig.caaers.domain.AdverseEvent;
import gov.nih.nci.cabig.caaers.domain.RoutineAdverseEventReport;
import gov.nih.nci.cabig.caaers.domain.ExpeditedAdverseEventReport;
import gov.nih.nci.cabig.caaers.domain.CtcCategory;
import gov.nih.nci.cabig.caaers.domain.Participant;
import gov.nih.nci.cabig.caaers.domain.Study;
import gov.nih.nci.cabig.caaers.domain.StudyParticipantAssignment;
import gov.nih.nci.cabig.caaers.domain.Attribution;
import gov.nih.nci.cabig.caaers.domain.StudySite;
import gov.nih.nci.cabig.caaers.domain.TreatmentInformation;
import gov.nih.nci.cabig.caaers.rules.business.service.AdverseEventEvaluationService;
import gov.nih.nci.cabig.caaers.rules.business.service.AdverseEventEvaluationServiceImpl;
import gov.nih.nci.cabig.ctms.lang.NowFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* @author Krikor Krumlian
*/
public class CreateRoutineAdverseEventCommand implements RoutineAdverseEventInputCommand {
private static final Log log = LogFactory.getLog(CreateRoutineAdverseEventCommand.class);
private ExpeditedAdverseEventReport aeReport;
private RoutineAdverseEventReport aeRoutineReport;
private Participant participant;
private Study study;
private ExpeditedAdverseEventReportDao reportDao;
private RoutineAdverseEventReportDao routineReportDao;
private StudyParticipantAssignmentDao assignmentDao;
private AdverseEventEvaluationService adverseEventEvaluationService;
private Map<String, List<List<Attribution>>> attributionMap;
private NowFactory nowFactory;
private List<CtcCategory> categories;
private String[] ctcCatIds;
private String[] cats;
private String[] ctcTermIds;
public CreateRoutineAdverseEventCommand(
StudyParticipantAssignmentDao assignmentDao, RoutineAdverseEventReportDao routineReportDao,
ExpeditedAdverseEventReportDao reportDao, NowFactory nowFactory
) {
this.assignmentDao = assignmentDao;
this.aeRoutineReport = new RoutineAdverseEventReport();
this.reportDao = reportDao;
this.routineReportDao = routineReportDao;
this.categories = new ArrayList<CtcCategory>();
this.nowFactory = nowFactory;
this.adverseEventEvaluationService = new AdverseEventEvaluationServiceImpl();
}
////// LOGIC
public StudyParticipantAssignment getAssignment() {
if (getParticipant() != null && getStudy() != null) {
return assignmentDao.getAssignment(getParticipant(), getStudy());
} else {
return null;
}
}
private void prepareExpeditedReport()
{
this.aeReport = new ExpeditedAdverseEventReport();
aeReport.setDetectionDate(aeRoutineReport.getStartDate());
this.aeReport.setAssignment(getAssignment());
this.aeReport.setCreatedAt(nowFactory.getNowTimestamp());
}
public void setAeRoutineReport(RoutineAdverseEventReport aeRoutineReport) {
this.aeRoutineReport = aeRoutineReport;
}
// This method deliberately sets only one side of the bidirectional link.
// This is so hibernate will not discover the link from the persistent side
// (assignment) and try to save the report before we want it to.
private void updateReportAssignmentLink() {
getAeRoutineReport().setAssignment(getAssignment());
}
/*
* Will try to find serious AEs if found they will be reported as expedited.
* An AE might be MedDRA or CTC based Rules should take that into consideration
*
* @see gov.nih.nci.cabig.caaers.web.ae.AdverseEventInputCommand#save()
*/
public void save() {
getAssignment().addRoutineReport(getAeRoutineReport());
prepareExpeditedReport();
boolean isExpedited = findExpedited(getAeRoutineReport());
routineReportDao.save(getAeRoutineReport());
if (isExpedited) {
reportDao.save(this.aeReport);
}
}
////// BOUND PROPERTIES
public ExpeditedAdverseEventReport getAeReport() {
return aeReport;
}
public Map<String, List<List<Attribution>>> getAttributionMap() {
return attributionMap;
}
public Participant getParticipant() {
return participant;
}
public void setParticipant(Participant participant) {
this.participant = participant;
updateReportAssignmentLink();
}
public Study getStudy() {
return study;
}
public void setStudy(Study study) {
this.study = study;
// TODO: this is temporary -- need a cleaner way to force this to load
// in same session as study is loaded and/or reassociate study with hib session later
if (study != null) {
this.study.getStudyAgents().size();
this.study.getCtepStudyDiseases().size();
this.study.getStudySites().size();
for(StudySite site : study.getStudySites()){
site.getStudyPersonnels().size();
}
}
updateReportAssignmentLink();
}
@SuppressWarnings("finally")
public boolean findExpedited(RoutineAdverseEventReport raer ){
log.debug("Checking for expedited AEs");
boolean isPopulated = false;
try {
for(AdverseEvent ae : raer.getAdverseEvents() )
{
String message = adverseEventEvaluationService.assesAdverseEvent(ae,study);
if (message.equals("SERIOUS_ADVERSE_EVENT")){
aeReport.addAdverseEvent(ae);
isPopulated = true;
}
}
return isPopulated;
}
catch(Exception e){
throw new RuntimeException("Class Not found Exception", e);
}
finally {
return isPopulated;
}
}
public void setAeReport(ExpeditedAdverseEventReport aeReport) {
this.aeReport = aeReport;
}
public RoutineAdverseEventReport getAeRoutineReport() {
return aeRoutineReport;
}
public List<CtcCategory> getCategories() {
return categories;
}
public void setCategories(List<CtcCategory> categories) {
this.categories = categories;
}
public String[] getCtcCatIds() {
return ctcCatIds;
}
public void setCtcCatIds(String[] ctcCatIds) {
this.ctcCatIds = ctcCatIds;
}
public String[] getCtcTermIds() {
return ctcTermIds;
}
public void setCtcTermIds(String[] ctcTermIds) {
this.ctcTermIds = ctcTermIds;
}
public String[] getCats() {
return cats;
}
public void setCats(String[] cats) {
this.cats = cats;
}
}
|
projects/web/src/main/java/gov/nih/nci/cabig/caaers/web/ae/CreateRoutineAdverseEventCommand.java
|
package gov.nih.nci.cabig.caaers.web.ae;
import gov.nih.nci.cabig.caaers.dao.RoutineAdverseEventReportDao;
import gov.nih.nci.cabig.caaers.dao.ExpeditedAdverseEventReportDao;
import gov.nih.nci.cabig.caaers.dao.StudyParticipantAssignmentDao;
import gov.nih.nci.cabig.caaers.domain.AdverseEvent;
import gov.nih.nci.cabig.caaers.domain.RoutineAdverseEventReport;
import gov.nih.nci.cabig.caaers.domain.ExpeditedAdverseEventReport;
import gov.nih.nci.cabig.caaers.domain.CtcCategory;
import gov.nih.nci.cabig.caaers.domain.Participant;
import gov.nih.nci.cabig.caaers.domain.Study;
import gov.nih.nci.cabig.caaers.domain.StudyParticipantAssignment;
import gov.nih.nci.cabig.caaers.domain.Attribution;
import gov.nih.nci.cabig.caaers.domain.StudySite;
import gov.nih.nci.cabig.caaers.domain.TreatmentInformation;
import gov.nih.nci.cabig.caaers.rules.business.service.AdverseEventEvaluationService;
import gov.nih.nci.cabig.caaers.rules.business.service.AdverseEventEvaluationServiceImpl;
import gov.nih.nci.cabig.ctms.lang.NowFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* @author Krikor Krumlian
*/
public class CreateRoutineAdverseEventCommand implements RoutineAdverseEventInputCommand {
private static final Log log = LogFactory.getLog(CreateRoutineAdverseEventCommand.class);
private ExpeditedAdverseEventReport aeReport;
private RoutineAdverseEventReport aeRoutineReport;
private Participant participant;
private Study study;
private ExpeditedAdverseEventReportDao reportDao;
private RoutineAdverseEventReportDao routineReportDao;
private StudyParticipantAssignmentDao assignmentDao;
private AdverseEventEvaluationService adverseEventEvaluationService;
private Map<String, List<List<Attribution>>> attributionMap;
private NowFactory nowFactory;
private List<CtcCategory> categories;
private String[] ctcCatIds;
private String[] cats;
private String[] ctcTermIds;
public CreateRoutineAdverseEventCommand(
StudyParticipantAssignmentDao assignmentDao, RoutineAdverseEventReportDao routineReportDao,
ExpeditedAdverseEventReportDao reportDao, NowFactory nowFactory
) {
this.assignmentDao = assignmentDao;
this.aeRoutineReport = new RoutineAdverseEventReport();
this.reportDao = reportDao;
this.routineReportDao = routineReportDao;
this.categories = new ArrayList<CtcCategory>();
this.nowFactory = nowFactory;
this.adverseEventEvaluationService = new AdverseEventEvaluationServiceImpl();
}
////// LOGIC
public StudyParticipantAssignment getAssignment() {
if (getParticipant() != null && getStudy() != null) {
return assignmentDao.getAssignment(getParticipant(), getStudy());
} else {
return null;
}
}
private void prepareExpeditedReport()
{
this.aeReport = new ExpeditedAdverseEventReport();
aeReport.setDetectionDate(aeRoutineReport.getStartDate());
this.aeReport.setAssignment(getAssignment());
this.aeReport.setCreatedAt(nowFactory.getNowTimestamp());
}
public void setAeRoutineReport(RoutineAdverseEventReport aeRoutineReport) {
this.aeRoutineReport = aeRoutineReport;
}
// This method deliberately sets only one side of the bidirectional link.
// This is so hibernate will not discover the link from the persistent side
// (assignment) and try to save the report before we want it to.
private void updateReportAssignmentLink() {
getAeRoutineReport().setAssignment(getAssignment());
}
/*
* Will try to find serious AEs if found they will be reported as expedited.
* An AE might be MedDRA or CTC based Rules should take that into consideration
*
* @see gov.nih.nci.cabig.caaers.web.ae.AdverseEventInputCommand#save()
*/
public void save() {
getAssignment().addRoutineReport(getAeRoutineReport());
prepareExpeditedReport();
boolean isExpedited = findExpedited(getAeRoutineReport());
routineReportDao.save(getAeRoutineReport());
if (isExpedited) {
reportDao.save(this.aeReport);
}
}
////// BOUND PROPERTIES
public ExpeditedAdverseEventReport getAeReport() {
return aeReport;
}
public Map<String, List<List<Attribution>>> getAttributionMap() {
return attributionMap;
}
public Participant getParticipant() {
return participant;
}
public void setParticipant(Participant participant) {
this.participant = participant;
updateReportAssignmentLink();
}
public Study getStudy() {
return study;
}
public void setStudy(Study study) {
this.study = study;
// TODO: this is temporary -- need a cleaner way to force this to load
// in same session as study is loaded and/or reassociate study with hib session later
if (study != null) {
this.study.getStudyAgents().size();
this.study.getCtepStudyDiseases().size();
this.study.getStudySites().size();
for(StudySite site : study.getStudySites()){
site.getStudyPersonnels().size();
}
}
updateReportAssignmentLink();
}
@SuppressWarnings("finally")
public boolean findExpedited(RoutineAdverseEventReport raer ){
log.debug("Checking for expedited AEs");
boolean isPopulated = false;
try {
for(AdverseEvent ae : raer.getAdverseEvents() )
{
//String message = adverseEventEvaluationService.assesAdverseEvent(ae,study);
//if (message.equals("SERIOUS_ADVERSE_EVENT")){
aeReport.addAdverseEvent(ae);
isPopulated = true;
//}
}
return isPopulated;
}
catch(Exception e){
throw new RuntimeException("Class Not found Exception", e);
}
finally {
return isPopulated;
}
}
public void setAeReport(ExpeditedAdverseEventReport aeReport) {
this.aeReport = aeReport;
}
public RoutineAdverseEventReport getAeRoutineReport() {
return aeRoutineReport;
}
public List<CtcCategory> getCategories() {
return categories;
}
public void setCategories(List<CtcCategory> categories) {
this.categories = categories;
}
public String[] getCtcCatIds() {
return ctcCatIds;
}
public void setCtcCatIds(String[] ctcCatIds) {
this.ctcCatIds = ctcCatIds;
}
public String[] getCtcTermIds() {
return ctcTermIds;
}
public void setCtcTermIds(String[] ctcTermIds) {
this.ctcTermIds = ctcTermIds;
}
public String[] getCats() {
return cats;
}
public void setCats(String[] cats) {
this.cats = cats;
}
}
|
Removed Commented code , That i used for testing
SVN-Revision: 2789
|
projects/web/src/main/java/gov/nih/nci/cabig/caaers/web/ae/CreateRoutineAdverseEventCommand.java
|
Removed Commented code , That i used for testing
|
<ide><path>rojects/web/src/main/java/gov/nih/nci/cabig/caaers/web/ae/CreateRoutineAdverseEventCommand.java
<ide> try {
<ide> for(AdverseEvent ae : raer.getAdverseEvents() )
<ide> {
<del> //String message = adverseEventEvaluationService.assesAdverseEvent(ae,study);
<del> //if (message.equals("SERIOUS_ADVERSE_EVENT")){
<add> String message = adverseEventEvaluationService.assesAdverseEvent(ae,study);
<add> if (message.equals("SERIOUS_ADVERSE_EVENT")){
<ide> aeReport.addAdverseEvent(ae);
<ide> isPopulated = true;
<del> //}
<add> }
<ide> }
<ide> return isPopulated;
<ide> }
|
|
Java
|
epl-1.0
|
904de70d8669c629b85b5c9611a2f2190126436d
| 0 |
RandallDW/Aruba_plugin,RandallDW/Aruba_plugin,akurtakov/Pydev,akurtakov/Pydev,rgom/Pydev,rajul/Pydev,fabioz/Pydev,rgom/Pydev,fabioz/Pydev,akurtakov/Pydev,rajul/Pydev,fabioz/Pydev,rgom/Pydev,akurtakov/Pydev,akurtakov/Pydev,rajul/Pydev,rgom/Pydev,rajul/Pydev,akurtakov/Pydev,rgom/Pydev,RandallDW/Aruba_plugin,rajul/Pydev,RandallDW/Aruba_plugin,RandallDW/Aruba_plugin,RandallDW/Aruba_plugin,fabioz/Pydev,rajul/Pydev,rgom/Pydev,fabioz/Pydev,fabioz/Pydev
|
/*******************************************************************************
* Copyright (c) 2000, 2011 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.python.pydev.shared_core.partitioner;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.rules.IPartitionTokenScanner;
import org.eclipse.jface.text.rules.IPredicateRule;
import org.eclipse.jface.text.rules.IRule;
import org.eclipse.jface.text.rules.IToken;
/**
* Scanner that exclusively uses predicate rules.
* <p>
* If a partial range is set (see {@link #setPartialRange(IDocument, int, int, String, int)} with
* content type that is not <code>null</code> then this scanner will first try the rules that match
* the given content type.
* </p>
*
* @since 2.0
*/
public class CustomRuleBasedPartitionScanner extends AbstractCustomBufferedRuleBasedScanner implements
IPartitionTokenScanner {
/** The content type of the partition in which to resume scanning. */
protected String fContentType;
/** The offset of the partition inside which to resume. */
protected int fPartitionOffset;
/*
* (non-Javadoc)
* @see com.brainwy.liclipse.editor.epl.rules.IDocumentScanner#getDocument()
*/
public IDocument getDocument() {
return fDocument;
}
/**
* Disallow setting the rules since this scanner
* exclusively uses predicate rules.
*
* @param rules the sequence of rules controlling this scanner
*/
@Override
public void setRules(IRule[] rules) {
throw new UnsupportedOperationException();
}
/*
* @see RuleBasedScanner#setRules(IRule[])
*/
public void setPredicateRules(IPredicateRule[] rules) {
super.setRules(rules);
}
/*
* @see ITokenScanner#setRange(IDocument, int, int)
*/
@Override
public void setRange(IDocument document, int offset, int length) {
setPartialRange(document, offset, length, null, -1);
}
/**
* {@inheritDoc}
* <p>
* If the given content type is not <code>null</code> then this scanner will first try the rules
* that match the given content type.
* </p>
*/
public void setPartialRange(IDocument document, int offset, int length, String contentType, int partitionOffset) {
// lastToken = null;
// lookAhead = null;
fContentType = contentType;
fPartitionOffset = partitionOffset;
if (partitionOffset > -1) {
int delta = offset - partitionOffset;
if (delta > 0) {
super.setRange(document, partitionOffset, length + delta);
fOffset = offset;
return;
}
}
super.setRange(document, offset, length);
}
/*
* @see ITokenScanner#nextToken()
*/
@Override
public IToken nextToken() {
// lastToken = null; //reset the last token
//
// //Check if we looked ahead and already resolved something.
// if (lookAhead != null) {
// lastToken = lookAhead;
// lookAhead = null;
// return lastToken.token;
// }
if (fContentType == null || fRules == null) {
//don't try to resume
return super.nextToken();
}
// inside a partition
fColumn = UNDEFINED;
boolean resume = (fPartitionOffset > -1 && fPartitionOffset < fOffset);
fTokenOffset = resume ? fPartitionOffset : fOffset;
IPredicateRule rule;
IToken token;
for (int i = 0; i < fRules.length; i++) {
rule = (IPredicateRule) fRules[i];
token = rule.getSuccessToken();
if (fContentType.equals(token.getData())) {
token = rule.evaluate(this, resume);
if (!token.isUndefined()) {
fContentType = null;
return token;
}
}
}
// haven't found any rule for this type of partition
fContentType = null;
if (resume) {
fOffset = fPartitionOffset;
}
return super.nextToken();
}
}
|
plugins/org.python.pydev.shared_core/src/org/python/pydev/shared_core/partitioner/CustomRuleBasedPartitionScanner.java
|
/*******************************************************************************
* Copyright (c) 2000, 2011 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.python.pydev.shared_core.partitioner;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.rules.IPartitionTokenScanner;
import org.eclipse.jface.text.rules.IPredicateRule;
import org.eclipse.jface.text.rules.IRule;
import org.eclipse.jface.text.rules.IToken;
/**
* Scanner that exclusively uses predicate rules.
* <p>
* If a partial range is set (see {@link #setPartialRange(IDocument, int, int, String, int)} with
* content type that is not <code>null</code> then this scanner will first try the rules that match
* the given content type.
* </p>
*
* @since 2.0
*/
public class CustomRuleBasedPartitionScanner extends AbstractCustomBufferedRuleBasedScanner implements
IPartitionTokenScanner {
/** The content type of the partition in which to resume scanning. */
protected String fContentType;
/** The offset of the partition inside which to resume. */
protected int fPartitionOffset;
private boolean topLevelRuleHasSubRules = false;
/*
* (non-Javadoc)
* @see com.brainwy.liclipse.editor.epl.rules.IDocumentScanner#getDocument()
*/
public IDocument getDocument() {
return fDocument;
}
/**
* Disallow setting the rules since this scanner
* exclusively uses predicate rules.
*
* @param rules the sequence of rules controlling this scanner
*/
@Override
public void setRules(IRule[] rules) {
throw new UnsupportedOperationException();
}
/*
* @see RuleBasedScanner#setRules(IRule[])
*/
public void setPredicateRules(IPredicateRule[] rules) {
super.setRules(rules);
topLevelRuleHasSubRules = false;
for (IPredicateRule rule : rules) {
if (rule instanceof IRuleWithSubRules) {
topLevelRuleHasSubRules = true;
break;
}
}
}
/*
* @see ITokenScanner#setRange(IDocument, int, int)
*/
@Override
public void setRange(IDocument document, int offset, int length) {
setPartialRange(document, offset, length, null, -1);
}
/**
* {@inheritDoc}
* <p>
* If the given content type is not <code>null</code> then this scanner will first try the rules
* that match the given content type.
* </p>
*/
public void setPartialRange(IDocument document, int offset, int length, String contentType, int partitionOffset) {
// lastToken = null;
// lookAhead = null;
fContentType = contentType;
fPartitionOffset = partitionOffset;
if (partitionOffset > -1) {
int delta = offset - partitionOffset;
if (delta > 0) {
super.setRange(document, partitionOffset, length + delta);
fOffset = offset;
return;
}
} else if (topLevelRuleHasSubRules) {
//No partitions until now...
//When we have complex rules we have to start from the beginning of the document each time in this case.
partitionOffset = 0;
int delta = offset - partitionOffset;
if (delta > 0) {
super.setRange(document, partitionOffset, length + delta);
return;
}
}
super.setRange(document, offset, length);
}
/*
* @see ITokenScanner#nextToken()
*/
@Override
public IToken nextToken() {
// lastToken = null; //reset the last token
//
// //Check if we looked ahead and already resolved something.
// if (lookAhead != null) {
// lastToken = lookAhead;
// lookAhead = null;
// return lastToken.token;
// }
if (fContentType == null || fRules == null) {
//don't try to resume
return super.nextToken();
}
// inside a partition
fColumn = UNDEFINED;
boolean resume = (fPartitionOffset > -1 && fPartitionOffset < fOffset);
fTokenOffset = resume ? fPartitionOffset : fOffset;
IPredicateRule rule;
IToken token;
for (int i = 0; i < fRules.length; i++) {
rule = (IPredicateRule) fRules[i];
token = rule.getSuccessToken();
if (fContentType.equals(token.getData())) {
token = rule.evaluate(this, resume);
if (!token.isUndefined()) {
fContentType = null;
return token;
}
}
}
// haven't found any rule for this type of partition
fContentType = null;
if (resume) {
fOffset = fPartitionOffset;
}
return super.nextToken();
}
}
|
Fixed issue where parsing was always starting at 0 when sub-rules were in the top level.
|
plugins/org.python.pydev.shared_core/src/org/python/pydev/shared_core/partitioner/CustomRuleBasedPartitionScanner.java
|
Fixed issue where parsing was always starting at 0 when sub-rules were in the top level.
|
<ide><path>lugins/org.python.pydev.shared_core/src/org/python/pydev/shared_core/partitioner/CustomRuleBasedPartitionScanner.java
<ide> /** The offset of the partition inside which to resume. */
<ide> protected int fPartitionOffset;
<ide>
<del> private boolean topLevelRuleHasSubRules = false;
<del>
<ide> /*
<ide> * (non-Javadoc)
<ide> * @see com.brainwy.liclipse.editor.epl.rules.IDocumentScanner#getDocument()
<ide> */
<ide> public void setPredicateRules(IPredicateRule[] rules) {
<ide> super.setRules(rules);
<del> topLevelRuleHasSubRules = false;
<del> for (IPredicateRule rule : rules) {
<del> if (rule instanceof IRuleWithSubRules) {
<del> topLevelRuleHasSubRules = true;
<del> break;
<del> }
<del> }
<ide> }
<ide>
<ide> /*
<ide> if (delta > 0) {
<ide> super.setRange(document, partitionOffset, length + delta);
<ide> fOffset = offset;
<del> return;
<del> }
<del> } else if (topLevelRuleHasSubRules) {
<del> //No partitions until now...
<del> //When we have complex rules we have to start from the beginning of the document each time in this case.
<del> partitionOffset = 0;
<del> int delta = offset - partitionOffset;
<del> if (delta > 0) {
<del> super.setRange(document, partitionOffset, length + delta);
<ide> return;
<ide> }
<ide> }
|
|
Java
|
apache-2.0
|
64e80769e421598128d27efb1b22bb41c2183dfc
| 0 |
Nadahar/metadata-extractor,Widen/metadata-extractor,rcketscientist/metadata-extractor,drewnoakes/metadata-extractor,PaytonGarland/metadata-extractor,Nadahar/metadata-extractor
|
/*
* Copyright 2002-2016 Drew Noakes
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* More information about this project is available at:
*
* https://drewnoakes.com/code/exif/
* https://github.com/drewnoakes/metadata-extractor
*/
package com.drew.tools;
import com.adobe.xmp.XMPException;
import com.adobe.xmp.XMPIterator;
import com.adobe.xmp.XMPMeta;
import com.adobe.xmp.properties.XMPPropertyInfo;
import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.jpeg.JpegProcessingException;
import com.drew.lang.StringUtil;
import com.drew.lang.annotations.NotNull;
import com.drew.lang.annotations.Nullable;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.Tag;
import com.drew.metadata.exif.ExifIFD0Directory;
import com.drew.metadata.exif.ExifSubIFDDirectory;
import com.drew.metadata.exif.ExifThumbnailDirectory;
import com.drew.metadata.file.FileMetadataDirectory;
import com.drew.metadata.xmp.XmpDirectory;
import java.io.*;
import java.util.*;
/**
* @author Drew Noakes https://drewnoakes.com
*/
public class ProcessAllImagesInFolderUtility
{
public static void main(String[] args) throws IOException, JpegProcessingException
{
List<String> directories = new ArrayList<String>();
FileHandler handler = null;
PrintStream log = System.out;
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if (arg.equalsIgnoreCase("--text")) {
// If "--text" is specified, write the discovered metadata into a sub-folder relative to the image
handler = new TextFileOutputHandler();
} else if (arg.equalsIgnoreCase("--markdown")) {
// If "--markdown" is specified, write a summary table in markdown format to standard out
handler = new MarkdownTableOutputHandler();
} else if (arg.equalsIgnoreCase("--unknown")) {
// If "--unknown" is specified, write CSV tallying unknown tag counts
handler = new UnknownTagHandler();
} else if (arg.equalsIgnoreCase("--log-file")) {
if (i == args.length - 1) {
printUsage();
System.exit(1);
}
log = new PrintStream(new FileOutputStream(args[++i], false), true);
} else {
// Treat this argument as a directory
directories.add(arg);
}
}
if (directories.isEmpty()) {
System.err.println("Expects one or more directories as arguments.");
printUsage();
System.exit(1);
}
if (handler == null) {
handler = new BasicFileHandler();
}
long start = System.nanoTime();
for (String directory : directories) {
processDirectory(new File(directory), handler, "", log);
}
handler.onScanCompleted(log);
System.out.println(String.format("Completed in %d ms", (System.nanoTime() - start) / 1000000));
if (log != System.out) {
log.close();
}
}
private static void printUsage()
{
System.out.println("Usage:");
System.out.println();
System.out.println(" java com.drew.tools.ProcessAllImagesInFolderUtility [--text|--markdown|--unknown] [--log-file <file-name>]");
}
private static void processDirectory(@NotNull File path, @NotNull FileHandler handler, @NotNull String relativePath, PrintStream log)
{
handler.onStartingDirectory(path);
String[] pathItems = path.list();
if (pathItems == null) {
return;
}
// Order alphabetically so that output is stable across invocations
Arrays.sort(pathItems);
for (String pathItem : pathItems) {
File file = new File(path, pathItem);
if (file.isDirectory()) {
processDirectory(file, handler, relativePath.length() == 0 ? pathItem : relativePath + "/" + pathItem, log);
} else if (handler.shouldProcess(file)) {
handler.onBeforeExtraction(file, log, relativePath);
// Read metadata
final Metadata metadata;
try {
metadata = ImageMetadataReader.readMetadata(file);
} catch (Throwable t) {
handler.onExtractionError(file, t, log);
continue;
}
handler.onExtractionSuccess(file, metadata, relativePath, log);
}
}
}
interface FileHandler
{
/** Called when the scan is about to start processing files in directory <code>path</code>. */
void onStartingDirectory(@NotNull File directoryPath);
/** Called to determine whether the implementation should process <code>filePath</code>. */
boolean shouldProcess(@NotNull File file);
/** Called before extraction is performed on <code>filePath</code>. */
void onBeforeExtraction(@NotNull File file, @NotNull PrintStream log, @NotNull String relativePath);
/** Called when extraction on <code>filePath</code> completed without an exception. */
void onExtractionSuccess(@NotNull File file, @NotNull Metadata metadata, @NotNull String relativePath, @NotNull PrintStream log);
/** Called when extraction on <code>filePath</code> resulted in an exception. */
void onExtractionError(@NotNull File file, @NotNull Throwable throwable, @NotNull PrintStream log);
/** Called when all files have been processed. */
void onScanCompleted(@NotNull PrintStream log);
}
abstract static class FileHandlerBase implements FileHandler
{
private final Set<String> _supportedExtensions = new HashSet<String>(
Arrays.asList(
"jpg", "jpeg", "png", "gif", "bmp", "ico", "webp", "pcx", "ai", "eps",
"nef", "crw", "cr2", "orf", "arw", "raf", "srw", "x3f", "rw2", "rwl",
"tif", "tiff", "psd", "dng"));
private int _processedFileCount = 0;
private int _exceptionCount = 0;
private int _errorCount = 0;
private long _processedByteCount = 0;
public void onStartingDirectory(@NotNull File directoryPath)
{}
public boolean shouldProcess(@NotNull File file)
{
String extension = getExtension(file);
return extension != null && _supportedExtensions.contains(extension.toLowerCase());
}
public void onBeforeExtraction(@NotNull File file, @NotNull PrintStream log, @NotNull String relativePath)
{
_processedFileCount++;
_processedByteCount += file.length();
}
public void onExtractionError(@NotNull File file, @NotNull Throwable throwable, @NotNull PrintStream log)
{
_exceptionCount++;
log.printf("\t[%s] %s\n", throwable.getClass().getName(), throwable.getMessage());
}
public void onExtractionSuccess(@NotNull File file, @NotNull Metadata metadata, @NotNull String relativePath, @NotNull PrintStream log)
{
if (metadata.hasErrors()) {
log.print(file);
log.print('\n');
for (Directory directory : metadata.getDirectories()) {
if (!directory.hasErrors())
continue;
for (String error : directory.getErrors()) {
log.printf("\t[%s] %s\n", directory.getName(), error);
_errorCount++;
}
}
}
}
public void onScanCompleted(@NotNull PrintStream log)
{
if (_processedFileCount > 0) {
log.print(String.format(
"Processed %,d files (%,d bytes) with %,d exceptions and %,d file errors\n",
_processedFileCount, _processedByteCount, _exceptionCount, _errorCount
));
}
}
@Nullable
protected String getExtension(@NotNull File file)
{
String fileName = file.getName();
int i = fileName.lastIndexOf('.');
if (i == -1)
return null;
if (i == fileName.length() - 1)
return null;
return fileName.substring(i + 1);
}
}
/**
* Writes a text file containing the extracted metadata for each input file.
*/
static class TextFileOutputHandler extends FileHandlerBase
{
/** Standardise line ending so that generated files can be more easily diffed. */
private static final String NEW_LINE = "\n";
@Override
public void onStartingDirectory(@NotNull File directoryPath)
{
super.onStartingDirectory(directoryPath);
// Delete any existing 'metadata' folder
File metadataDirectory = new File(directoryPath + "/metadata");
if (metadataDirectory.exists())
deleteRecursively(metadataDirectory);
}
private static void deleteRecursively(File directory)
{
if (!directory.isDirectory())
throw new IllegalArgumentException("Must be a directory.");
if (directory.exists()) {
for (String item : directory.list()) {
File file = new File(item);
if (file.isDirectory())
deleteRecursively(file);
else
file.delete();
}
}
directory.delete();
}
@Override
public void onBeforeExtraction(@NotNull File file, @NotNull PrintStream log, @NotNull String relativePath)
{
super.onBeforeExtraction(file, log, relativePath);
log.print(file.getAbsoluteFile());
log.print(NEW_LINE);
}
@Override
public void onExtractionSuccess(@NotNull File file, @NotNull Metadata metadata, @NotNull String relativePath, @NotNull PrintStream log)
{
super.onExtractionSuccess(file, metadata, relativePath, log);
try {
PrintWriter writer = null;
try
{
writer = openWriter(file);
// Write any errors
if (metadata.hasErrors()) {
for (Directory directory : metadata.getDirectories()) {
if (!directory.hasErrors())
continue;
for (String error : directory.getErrors())
writer.format("[ERROR: %s] %s%s", directory.getName(), error, NEW_LINE);
}
writer.write(NEW_LINE);
}
// Write tag values for each directory
for (Directory directory : metadata.getDirectories()) {
String directoryName = directory.getName();
// Write the directory's tags
for (Tag tag : directory.getTags()) {
String tagName = tag.getTagName();
String description = tag.getDescription();
if (description == null)
description = "";
// Skip the file write-time as this changes based on the time at which the regression test image repository was cloned
if (directory instanceof FileMetadataDirectory && tag.getTagType() == FileMetadataDirectory.TAG_FILE_MODIFIED_DATE)
description = "<omitted for regression testing as checkout dependent>";
writer.format("[%s - %s] %s = %s%s", directoryName, tag.getTagTypeHex(), tagName, description, NEW_LINE);
}
if (directory.getTagCount() != 0)
writer.write(NEW_LINE);
// Special handling for XMP directory data
if (directory instanceof XmpDirectory) {
Collection<XmpDirectory> xmpDirectories = metadata.getDirectoriesOfType(XmpDirectory.class);
boolean wrote = false;
for (XmpDirectory xmpDirectory : xmpDirectories) {
XMPMeta xmpMeta = xmpDirectory.getXMPMeta();
try {
XMPIterator iterator = xmpMeta.iterator();
while (iterator.hasNext()) {
XMPPropertyInfo prop = (XMPPropertyInfo)iterator.next();
writer.format("[XMPMeta - %s] %s = %s%s", prop.getNamespace(), prop.getPath(), prop.getValue(), NEW_LINE);
wrote = true;
}
} catch (XMPException e) {
e.printStackTrace();
}
}
if (wrote)
writer.write(NEW_LINE);
}
}
// Write file structure
writeHierarchyLevel(metadata, writer, null, 0);
writer.write(NEW_LINE);
} finally {
closeWriter(writer);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void writeHierarchyLevel(@NotNull Metadata metadata, @NotNull PrintWriter writer, @Nullable Directory parent, int level)
{
final int indent = 4;
for (Directory child : metadata.getDirectories()) {
if (parent == null) {
if (child.getParent() != null)
continue;
} else if (!parent.equals(child.getParent())) {
continue;
}
for (int i = 0; i < level*indent; i++) {
writer.write(' ');
}
writer.write("- ");
writer.write(child.getName());
writer.write(NEW_LINE);
writeHierarchyLevel(metadata, writer, child, level + 1);
}
}
@Override
public void onExtractionError(@NotNull File file, @NotNull Throwable throwable, @NotNull PrintStream log)
{
super.onExtractionError(file, throwable, log);
try {
PrintWriter writer = null;
try {
writer = openWriter(file);
writer.write("EXCEPTION: " + throwable.getMessage() + NEW_LINE);
writer.write(NEW_LINE);
} finally {
closeWriter(writer);
}
} catch (IOException e) {
log.printf("IO exception writing metadata file: %s%s", e.getMessage(), NEW_LINE);
}
}
@NotNull
private static PrintWriter openWriter(@NotNull File file) throws IOException
{
// Create the output directory if it doesn't exist
File metadataDir = new File(String.format("%s/metadata", file.getParent()));
if (!metadataDir.exists())
metadataDir.mkdir();
String outputPath = String.format("%s/metadata/%s.txt", file.getParent(), file.getName());
Writer writer = new OutputStreamWriter(
new FileOutputStream(outputPath),
"UTF-8"
);
writer.write("FILE: " + file.getName() + NEW_LINE);
writer.write(NEW_LINE);
return new PrintWriter(writer);
}
private static void closeWriter(@Nullable Writer writer) throws IOException
{
if (writer != null) {
writer.write("Generated using metadata-extractor" + NEW_LINE);
writer.write("https://drewnoakes.com/code/exif/" + NEW_LINE);
writer.flush();
writer.close();
}
}
}
/**
* Creates a table describing sample images using Wiki markdown.
*/
static class MarkdownTableOutputHandler extends FileHandlerBase
{
private final Map<String, String> _extensionEquivalence = new HashMap<String, String>();
private final Map<String, List<Row>> _rowListByExtension = new HashMap<String, List<Row>>();
class Row
{
final File file;
final Metadata metadata;
@NotNull final String relativePath;
@Nullable private String manufacturer;
@Nullable private String model;
@Nullable private String exifVersion;
@Nullable private String thumbnail;
@Nullable private String makernote;
Row(@NotNull File file, @NotNull Metadata metadata, @NotNull String relativePath)
{
this.file = file;
this.metadata = metadata;
this.relativePath = relativePath;
ExifIFD0Directory ifd0Dir = metadata.getFirstDirectoryOfType(ExifIFD0Directory.class);
ExifSubIFDDirectory subIfdDir = metadata.getFirstDirectoryOfType(ExifSubIFDDirectory.class);
ExifThumbnailDirectory thumbDir = metadata.getFirstDirectoryOfType(ExifThumbnailDirectory.class);
if (ifd0Dir != null) {
manufacturer = ifd0Dir.getDescription(ExifIFD0Directory.TAG_MAKE);
model = ifd0Dir.getDescription(ExifIFD0Directory.TAG_MODEL);
}
boolean hasMakernoteData = false;
if (subIfdDir != null) {
exifVersion = subIfdDir.getDescription(ExifSubIFDDirectory.TAG_EXIF_VERSION);
hasMakernoteData = subIfdDir.containsTag(ExifSubIFDDirectory.TAG_MAKERNOTE);
}
if (thumbDir != null) {
Integer width = thumbDir.getInteger(ExifThumbnailDirectory.TAG_IMAGE_WIDTH);
Integer height = thumbDir.getInteger(ExifThumbnailDirectory.TAG_IMAGE_HEIGHT);
thumbnail = width != null && height != null
? String.format("Yes (%s x %s)", width, height)
: "Yes";
}
for (Directory directory : metadata.getDirectories()) {
if (directory.getClass().getName().contains("Makernote")) {
makernote = directory.getName().replace("Makernote", "").trim();
}
}
if (makernote == null) {
makernote = hasMakernoteData ? "(Unknown)" : "N/A";
}
}
}
public MarkdownTableOutputHandler()
{
_extensionEquivalence.put("jpeg", "jpg");
}
@Override
public void onExtractionSuccess(@NotNull File file, @NotNull Metadata metadata, @NotNull String relativePath, @NotNull PrintStream log)
{
super.onExtractionSuccess(file, metadata, relativePath, log);
String extension = getExtension(file);
if (extension == null) {
return;
}
// Sanitise the extension
extension = extension.toLowerCase();
if (_extensionEquivalence.containsKey(extension))
extension = _extensionEquivalence.get(extension);
List<Row> list = _rowListByExtension.get(extension);
if (list == null) {
list = new ArrayList<Row>();
_rowListByExtension.put(extension, list);
}
list.add(new Row(file, metadata, relativePath));
}
@Override
public void onScanCompleted(@NotNull PrintStream log)
{
super.onScanCompleted(log);
OutputStream outputStream = null;
PrintStream stream = null;
try {
outputStream = new FileOutputStream("../wiki/ImageDatabaseSummary.md", false);
stream = new PrintStream(outputStream, false);
writeOutput(stream);
stream.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (stream != null)
stream.close();
if (outputStream != null)
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void writeOutput(@NotNull PrintStream stream) throws IOException
{
Writer writer = new OutputStreamWriter(stream);
writer.write("# Image Database Summary\n\n");
for (String extension : _rowListByExtension.keySet()) {
writer.write("## " + extension.toUpperCase() + " Files\n\n");
writer.write("File|Manufacturer|Model|Dir Count|Exif?|Makernote|Thumbnail|All Data\n");
writer.write("----|------------|-----|---------|-----|---------|---------|--------\n");
List<Row> rows = _rowListByExtension.get(extension);
// Order by manufacturer, then model
Collections.sort(rows, new Comparator<Row>() {
public int compare(Row o1, Row o2)
{
int c1 = StringUtil.compare(o1.manufacturer, o2.manufacturer);
return c1 != 0 ? c1 : StringUtil.compare(o1.model, o2.model);
}
});
for (Row row : rows) {
writer.write(String.format("[%s](https://raw.githubusercontent.com/drewnoakes/metadata-extractor-images/master/%s/%s)|%s|%s|%d|%s|%s|%s|[metadata](https://raw.githubusercontent.com/drewnoakes/metadata-extractor-images/master/%s/metadata/%s.txt)\n",
row.file.getName(),
row.relativePath,
StringUtil.urlEncode(row.file.getName()),
row.manufacturer == null ? "" : row.manufacturer,
row.model == null ? "" : row.model,
row.metadata.getDirectoryCount(),
row.exifVersion == null ? "" : row.exifVersion,
row.makernote == null ? "" : row.makernote,
row.thumbnail == null ? "" : row.thumbnail,
row.relativePath,
StringUtil.urlEncode(row.file.getName()).toLowerCase()
));
}
writer.write('\n');
}
writer.flush();
}
}
/**
* Keeps track of unknown tags.
*/
static class UnknownTagHandler extends FileHandlerBase
{
private HashMap<String, HashMap<Integer, Integer>> _occurrenceCountByTagByDirectory = new HashMap<String, HashMap<Integer, Integer>>();
@Override
public void onExtractionSuccess(@NotNull File file, @NotNull Metadata metadata, @NotNull String relativePath, @NotNull PrintStream log)
{
super.onExtractionSuccess(file, metadata, relativePath, log);
for (Directory directory : metadata.getDirectories()) {
for (Tag tag : directory.getTags()) {
// Only interested in unknown tags (those without names)
if (tag.hasTagName())
continue;
HashMap<Integer, Integer> occurrenceCountByTag = _occurrenceCountByTagByDirectory.get(directory.getName());
if (occurrenceCountByTag == null) {
occurrenceCountByTag = new HashMap<Integer, Integer>();
_occurrenceCountByTagByDirectory.put(directory.getName(), occurrenceCountByTag);
}
Integer count = occurrenceCountByTag.get(tag.getTagType());
if (count == null) {
count = 0;
occurrenceCountByTag.put(tag.getTagType(), 0);
}
occurrenceCountByTag.put(tag.getTagType(), count + 1);
}
}
}
@Override
public void onScanCompleted(@NotNull PrintStream log)
{
super.onScanCompleted(log);
for (Map.Entry<String, HashMap<Integer, Integer>> pair1 : _occurrenceCountByTagByDirectory.entrySet()) {
String directoryName = pair1.getKey();
List<Map.Entry<Integer, Integer>> counts = new ArrayList<Map.Entry<Integer, Integer>>(pair1.getValue().entrySet());
Collections.sort(counts, new Comparator<Map.Entry<Integer, Integer>>()
{
public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2)
{
return o2.getValue().compareTo(o1.getValue());
}
});
for (Map.Entry<Integer, Integer> pair2 : counts) {
Integer tagType = pair2.getKey();
Integer count = pair2.getValue();
log.format("%s, 0x%04X, %d\n", directoryName, tagType, count);
}
}
}
}
/**
* Does nothing with the output except enumerate it in memory and format descriptions. This is useful in order to
* flush out any potential exceptions raised during the formatting of extracted value descriptions.
*/
static class BasicFileHandler extends FileHandlerBase
{
@Override
public void onExtractionSuccess(@NotNull File file, @NotNull Metadata metadata, @NotNull String relativePath, @NotNull PrintStream log)
{
super.onExtractionSuccess(file, metadata, relativePath, log);
// Iterate through all values, calling toString to flush out any formatting exceptions
for (Directory directory : metadata.getDirectories()) {
directory.getName();
for (Tag tag : directory.getTags()) {
tag.getTagName();
tag.getDescription();
}
}
}
}
}
|
Source/com/drew/tools/ProcessAllImagesInFolderUtility.java
|
/*
* Copyright 2002-2016 Drew Noakes
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* More information about this project is available at:
*
* https://drewnoakes.com/code/exif/
* https://github.com/drewnoakes/metadata-extractor
*/
package com.drew.tools;
import com.adobe.xmp.XMPException;
import com.adobe.xmp.XMPIterator;
import com.adobe.xmp.XMPMeta;
import com.adobe.xmp.properties.XMPPropertyInfo;
import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.jpeg.JpegProcessingException;
import com.drew.lang.StringUtil;
import com.drew.lang.annotations.NotNull;
import com.drew.lang.annotations.Nullable;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.Tag;
import com.drew.metadata.exif.ExifIFD0Directory;
import com.drew.metadata.exif.ExifSubIFDDirectory;
import com.drew.metadata.exif.ExifThumbnailDirectory;
import com.drew.metadata.file.FileMetadataDirectory;
import com.drew.metadata.xmp.XmpDirectory;
import java.io.*;
import java.util.*;
/**
* @author Drew Noakes https://drewnoakes.com
*/
public class ProcessAllImagesInFolderUtility
{
public static void main(String[] args) throws IOException, JpegProcessingException
{
List<String> directories = new ArrayList<String>();
FileHandler handler = null;
PrintStream log = System.out;
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if (arg.equalsIgnoreCase("--text")) {
// If "--text" is specified, write the discovered metadata into a sub-folder relative to the image
handler = new TextFileOutputHandler();
} else if (arg.equalsIgnoreCase("--markdown")) {
// If "--markdown" is specified, write a summary table in markdown format to standard out
handler = new MarkdownTableOutputHandler();
} else if (arg.equalsIgnoreCase("--unknown")) {
// If "--unknown" is specified, write CSV tallying unknown tag counts
handler = new UnknownTagHandler();
} else if (arg.equalsIgnoreCase("--log-file")) {
if (i == args.length - 1) {
printUsage();
System.exit(1);
}
log = new PrintStream(new FileOutputStream(args[++i], false), true);
} else {
// Treat this argument as a directory
directories.add(arg);
}
}
if (directories.isEmpty()) {
System.err.println("Expects one or more directories as arguments.");
printUsage();
System.exit(1);
}
if (handler == null) {
handler = new BasicFileHandler();
}
long start = System.nanoTime();
for (String directory : directories) {
processDirectory(new File(directory), handler, "", log);
}
handler.onScanCompleted(log);
System.out.println(String.format("Completed in %d ms", (System.nanoTime() - start) / 1000000));
if (log != System.out) {
log.close();
}
}
private static void printUsage()
{
System.out.println("Usage:");
System.out.println();
System.out.println(" java com.drew.tools.ProcessAllImagesInFolderUtility [--text|--markdown|--unknown] [--log-file <file-name>]");
}
private static void processDirectory(@NotNull File path, @NotNull FileHandler handler, @NotNull String relativePath, PrintStream log)
{
handler.onStartingDirectory(path);
String[] pathItems = path.list();
if (pathItems == null) {
return;
}
// Order alphabetically so that output is stable across invocations
Arrays.sort(pathItems);
for (String pathItem : pathItems) {
File file = new File(path, pathItem);
if (file.isDirectory()) {
processDirectory(file, handler, relativePath.length() == 0 ? pathItem : relativePath + "/" + pathItem, log);
} else if (handler.shouldProcess(file)) {
handler.onBeforeExtraction(file, log, relativePath);
// Read metadata
final Metadata metadata;
try {
metadata = ImageMetadataReader.readMetadata(file);
} catch (Throwable t) {
handler.onExtractionError(file, t, log);
continue;
}
handler.onExtractionSuccess(file, metadata, relativePath, log);
}
}
}
interface FileHandler
{
/** Called when the scan is about to start processing files in directory <code>path</code>. */
void onStartingDirectory(@NotNull File directoryPath);
/** Called to determine whether the implementation should process <code>filePath</code>. */
boolean shouldProcess(@NotNull File file);
/** Called before extraction is performed on <code>filePath</code>. */
void onBeforeExtraction(@NotNull File file, @NotNull PrintStream log, @NotNull String relativePath);
/** Called when extraction on <code>filePath</code> completed without an exception. */
void onExtractionSuccess(@NotNull File file, @NotNull Metadata metadata, @NotNull String relativePath, @NotNull PrintStream log);
/** Called when extraction on <code>filePath</code> resulted in an exception. */
void onExtractionError(@NotNull File file, @NotNull Throwable throwable, @NotNull PrintStream log);
/** Called when all files have been processed. */
void onScanCompleted(@NotNull PrintStream log);
}
abstract static class FileHandlerBase implements FileHandler
{
private final Set<String> _supportedExtensions = new HashSet<String>(
Arrays.asList(
"jpg", "jpeg", "png", "gif", "bmp", "ico", "webp", "pcx", "ai", "eps",
"nef", "crw", "cr2", "orf", "arw", "raf", "srw", "x3f", "rw2", "rwl",
"tif", "tiff", "psd", "dng"));
private int _processedFileCount = 0;
private int _exceptionCount = 0;
private int _errorCount = 0;
private long _processedByteCount = 0;
public void onStartingDirectory(@NotNull File directoryPath)
{}
public boolean shouldProcess(@NotNull File file)
{
String extension = getExtension(file);
return extension != null && _supportedExtensions.contains(extension.toLowerCase());
}
public void onBeforeExtraction(@NotNull File file, @NotNull PrintStream log, @NotNull String relativePath)
{
_processedFileCount++;
_processedByteCount += file.length();
}
public void onExtractionError(@NotNull File file, @NotNull Throwable throwable, @NotNull PrintStream log)
{
_exceptionCount++;
log.printf("\t[%s] %s\n", throwable.getClass().getName(), throwable.getMessage());
}
public void onExtractionSuccess(@NotNull File file, @NotNull Metadata metadata, @NotNull String relativePath, @NotNull PrintStream log)
{
if (metadata.hasErrors()) {
log.print(file);
log.print('\n');
for (Directory directory : metadata.getDirectories()) {
if (!directory.hasErrors())
continue;
for (String error : directory.getErrors()) {
log.printf("\t[%s] %s\n", directory.getName(), error);
_errorCount++;
}
}
}
}
public void onScanCompleted(@NotNull PrintStream log)
{
if (_processedFileCount > 0) {
log.print(String.format(
"Processed %,d files (%,d bytes) with %,d exceptions and %,d file errors\n",
_processedFileCount, _processedByteCount, _exceptionCount, _errorCount
));
}
}
@Nullable
protected String getExtension(@NotNull File file)
{
String fileName = file.getName();
int i = fileName.lastIndexOf('.');
if (i == -1)
return null;
if (i == fileName.length() - 1)
return null;
return fileName.substring(i + 1);
}
}
/**
* Writes a text file containing the extracted metadata for each input file.
*/
static class TextFileOutputHandler extends FileHandlerBase
{
/** Standardise line ending so that generated files can be more easily diffed. */
private static final String NEW_LINE = "\n";
@Override
public void onStartingDirectory(@NotNull File directoryPath)
{
super.onStartingDirectory(directoryPath);
// Delete any existing 'metadata' folder
File metadataDirectory = new File(directoryPath + "/metadata");
if (metadataDirectory.exists())
deleteRecursively(metadataDirectory);
}
private static void deleteRecursively(File directory)
{
if (!directory.isDirectory())
throw new IllegalArgumentException("Must be a directory.");
if (directory.exists()) {
for (String item : directory.list()) {
File file = new File(item);
if (file.isDirectory())
deleteRecursively(file);
else
file.delete();
}
}
directory.delete();
}
@Override
public void onBeforeExtraction(@NotNull File file, @NotNull PrintStream log, @NotNull String relativePath)
{
super.onBeforeExtraction(file, log, relativePath);
log.print(file.getAbsoluteFile());
log.print(NEW_LINE);
}
@Override
public void onExtractionSuccess(@NotNull File file, @NotNull Metadata metadata, @NotNull String relativePath, @NotNull PrintStream log)
{
super.onExtractionSuccess(file, metadata, relativePath, log);
try {
PrintWriter writer = null;
try
{
writer = openWriter(file);
// Write any errors
if (metadata.hasErrors()) {
for (Directory directory : metadata.getDirectories()) {
if (!directory.hasErrors())
continue;
for (String error : directory.getErrors())
writer.format("[ERROR: %s] %s%s", directory.getName(), error, NEW_LINE);
}
writer.write(NEW_LINE);
}
// Write tag values for each directory
for (Directory directory : metadata.getDirectories()) {
String directoryName = directory.getName();
// Write the directory's tags
for (Tag tag : directory.getTags()) {
String tagName = tag.getTagName();
String description = tag.getDescription();
if (description == null)
description = "";
// Skip the file write-time as this changes based on the time at which the regression test image repository was cloned
if (directory instanceof FileMetadataDirectory && tag.getTagType() == FileMetadataDirectory.TAG_FILE_MODIFIED_DATE)
description = "<omitted for regression testing as checkout dependent>";
writer.format("[%s - %s] %s = %s%s", directoryName, tag.getTagTypeHex(), tagName, description, NEW_LINE);
}
if (directory.getTagCount() != 0)
writer.write(NEW_LINE);
// Special handling for XMP directory data
if (directory instanceof XmpDirectory) {
Collection<XmpDirectory> xmpDirectories = metadata.getDirectoriesOfType(XmpDirectory.class);
boolean wrote = false;
for (XmpDirectory xmpDirectory : xmpDirectories) {
XMPMeta xmpMeta = xmpDirectory.getXMPMeta();
try {
XMPIterator iterator = xmpMeta.iterator();
while (iterator.hasNext()) {
XMPPropertyInfo prop = (XMPPropertyInfo)iterator.next();
writer.format("[XMPMeta - %s] %s = %s%s", prop.getNamespace(), prop.getPath(), prop.getValue(), NEW_LINE);
wrote = true;
}
} catch (XMPException e) {
e.printStackTrace();
}
}
if (wrote)
writer.write(NEW_LINE);
}
}
// Write file structure
writeHierarchyLevel(metadata, writer, null, 0);
writer.write(NEW_LINE);
} finally {
closeWriter(writer);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void writeHierarchyLevel(@NotNull Metadata metadata, @NotNull PrintWriter writer, @Nullable Directory parent, int level)
{
final int indent = 4;
for (Directory child : metadata.getDirectories()) {
if (parent == null) {
if (child.getParent() != null)
continue;
} else if (!parent.equals(child.getParent())) {
continue;
}
for (int i = 0; i < level*indent; i++) {
writer.write(' ');
}
writer.write("- ");
writer.write(child.getName());
writer.write(NEW_LINE);
writeHierarchyLevel(metadata, writer, child, level + 1);
}
}
@Override
public void onExtractionError(@NotNull File file, @NotNull Throwable throwable, @NotNull PrintStream log)
{
super.onExtractionError(file, throwable, log);
try {
PrintWriter writer = null;
try {
writer = openWriter(file);
writer.write("EXCEPTION: " + throwable.getMessage() + NEW_LINE);
writer.write(NEW_LINE);
} finally {
closeWriter(writer);
}
} catch (IOException e) {
log.printf("IO exception writing metadata file: %s%s", e.getMessage(), NEW_LINE);
}
}
@NotNull
private static PrintWriter openWriter(@NotNull File file) throws IOException
{
// Create the output directory if it doesn't exist
File metadataDir = new File(String.format("%s/metadata", file.getParent()));
if (!metadataDir.exists())
metadataDir.mkdir();
String outputPath = String.format("%s/metadata/%s.txt", file.getParent(), file.getName());
Writer writer = new OutputStreamWriter(
new FileOutputStream(outputPath),
"UTF-8"
);
writer.write("FILE: " + file.getName() + NEW_LINE);
writer.write(NEW_LINE);
return new PrintWriter(writer);
}
private static void closeWriter(@Nullable Writer writer) throws IOException
{
if (writer != null) {
writer.write("Generated using metadata-extractor" + NEW_LINE);
writer.write("https://drewnoakes.com/code/exif/" + NEW_LINE);
writer.flush();
writer.close();
}
}
}
/**
* Creates a table describing sample images using Wiki markdown.
*/
static class MarkdownTableOutputHandler extends FileHandlerBase
{
private final Map<String, String> _extensionEquivalence = new HashMap<String, String>();
private final Map<String, List<Row>> _rowListByExtension = new HashMap<String, List<Row>>();
class Row
{
final File file;
final Metadata metadata;
@NotNull final String relativePath;
@Nullable private String manufacturer;
@Nullable private String model;
@Nullable private String exifVersion;
@Nullable private String thumbnail;
@Nullable private String makernote;
Row(@NotNull File file, @NotNull Metadata metadata, @NotNull String relativePath)
{
this.file = file;
this.metadata = metadata;
this.relativePath = relativePath;
ExifIFD0Directory ifd0Dir = metadata.getFirstDirectoryOfType(ExifIFD0Directory.class);
ExifSubIFDDirectory subIfdDir = metadata.getFirstDirectoryOfType(ExifSubIFDDirectory.class);
ExifThumbnailDirectory thumbDir = metadata.getFirstDirectoryOfType(ExifThumbnailDirectory.class);
if (ifd0Dir != null) {
manufacturer = ifd0Dir.getDescription(ExifIFD0Directory.TAG_MAKE);
model = ifd0Dir.getDescription(ExifIFD0Directory.TAG_MODEL);
}
boolean hasMakernoteData = false;
if (subIfdDir != null) {
exifVersion = subIfdDir.getDescription(ExifSubIFDDirectory.TAG_EXIF_VERSION);
hasMakernoteData = subIfdDir.containsTag(ExifSubIFDDirectory.TAG_MAKERNOTE);
}
if (thumbDir != null) {
Integer width = thumbDir.getInteger(ExifThumbnailDirectory.TAG_IMAGE_WIDTH);
Integer height = thumbDir.getInteger(ExifThumbnailDirectory.TAG_IMAGE_HEIGHT);
thumbnail = width != null && height != null
? String.format("Yes (%s x %s)", width, height)
: "Yes";
}
for (Directory directory : metadata.getDirectories()) {
if (directory.getClass().getName().contains("Makernote")) {
makernote = directory.getName().replace("Makernote", "").trim();
}
}
if (makernote == null) {
makernote = hasMakernoteData ? "(Unknown)" : "N/A";
}
}
}
public MarkdownTableOutputHandler()
{
_extensionEquivalence.put("jpeg", "jpg");
}
@Override
public void onExtractionSuccess(@NotNull File file, @NotNull Metadata metadata, @NotNull String relativePath, @NotNull PrintStream log)
{
super.onExtractionSuccess(file, metadata, relativePath, log);
String extension = getExtension(file);
if (extension == null) {
return;
}
// Sanitise the extension
extension = extension.toLowerCase();
if (_extensionEquivalence.containsKey(extension))
extension =_extensionEquivalence.get(extension);
List<Row> list = _rowListByExtension.get(extension);
if (list == null) {
list = new ArrayList<Row>();
_rowListByExtension.put(extension, list);
}
list.add(new Row(file, metadata, relativePath));
}
@Override
public void onScanCompleted(@NotNull PrintStream log)
{
super.onScanCompleted(log);
OutputStream outputStream = null;
PrintStream stream = null;
try {
outputStream = new FileOutputStream("../wiki/ImageDatabaseSummary.md", false);
stream = new PrintStream(outputStream, false);
writeOutput(stream);
stream.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (stream != null)
stream.close();
if (outputStream != null)
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void writeOutput(@NotNull PrintStream stream) throws IOException
{
Writer writer = new OutputStreamWriter(stream);
writer.write("# Image Database Summary\n\n");
for (String extension : _rowListByExtension.keySet()) {
writer.write("## " + extension.toUpperCase() + " Files\n\n");
writer.write("File|Manufacturer|Model|Dir Count|Exif?|Makernote|Thumbnail|All Data\n");
writer.write("----|------------|-----|---------|-----|---------|---------|--------\n");
List<Row> rows = _rowListByExtension.get(extension);
// Order by manufacturer, then model
Collections.sort(rows, new Comparator<Row>() {
public int compare(Row o1, Row o2)
{
int c1 = StringUtil.compare(o1.manufacturer, o2.manufacturer);
return c1 != 0 ? c1 : StringUtil.compare(o1.model, o2.model);
}
});
for (Row row : rows) {
writer.write(String.format("[%s](https://raw.githubusercontent.com/drewnoakes/metadata-extractor-images/master/%s/%s)|%s|%s|%d|%s|%s|%s|[metadata](https://raw.githubusercontent.com/drewnoakes/metadata-extractor-images/master/%s/metadata/%s.txt)\n",
row.file.getName(),
row.relativePath,
StringUtil.urlEncode(row.file.getName()),
row.manufacturer == null ? "" : row.manufacturer,
row.model == null ? "" : row.model,
row.metadata.getDirectoryCount(),
row.exifVersion == null ? "" : row.exifVersion,
row.makernote == null ? "" : row.makernote,
row.thumbnail == null ? "" : row.thumbnail,
row.relativePath,
StringUtil.urlEncode(row.file.getName()).toLowerCase()
));
}
writer.write('\n');
}
writer.flush();
}
}
/**
* Keeps track of unknown tags.
*/
static class UnknownTagHandler extends FileHandlerBase
{
private HashMap<String, HashMap<Integer, Integer>> _occurrenceCountByTagByDirectory = new HashMap<String, HashMap<Integer, Integer>>();
@Override
public void onExtractionSuccess(@NotNull File file, @NotNull Metadata metadata, @NotNull String relativePath, @NotNull PrintStream log)
{
super.onExtractionSuccess(file, metadata, relativePath, log);
for (Directory directory : metadata.getDirectories()) {
for (Tag tag : directory.getTags()) {
// Only interested in unknown tags (those without names)
if (tag.hasTagName())
continue;
HashMap<Integer, Integer> occurrenceCountByTag = _occurrenceCountByTagByDirectory.get(directory.getName());
if (occurrenceCountByTag == null) {
occurrenceCountByTag = new HashMap<Integer, Integer>();
_occurrenceCountByTagByDirectory.put(directory.getName(), occurrenceCountByTag);
}
Integer count = occurrenceCountByTag.get(tag.getTagType());
if (count == null) {
count = 0;
occurrenceCountByTag.put(tag.getTagType(), 0);
}
occurrenceCountByTag.put(tag.getTagType(), count + 1);
}
}
}
@Override
public void onScanCompleted(@NotNull PrintStream log)
{
super.onScanCompleted(log);
for (Map.Entry<String, HashMap<Integer, Integer>> pair1 : _occurrenceCountByTagByDirectory.entrySet()) {
String directoryName = pair1.getKey();
List<Map.Entry<Integer, Integer>> counts = new ArrayList<Map.Entry<Integer, Integer>>(pair1.getValue().entrySet());
Collections.sort(counts, new Comparator<Map.Entry<Integer, Integer>>()
{
public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2)
{
return o2.getValue().compareTo(o1.getValue());
}
});
for (Map.Entry<Integer, Integer> pair2 : counts) {
Integer tagType = pair2.getKey();
Integer count = pair2.getValue();
log.format("%s, 0x%04X, %d\n", directoryName, tagType, count);
}
}
}
}
/**
* Does nothing with the output except enumerate it in memory and format descriptions. This is useful in order to
* flush out any potential exceptions raised during the formatting of extracted value descriptions.
*/
static class BasicFileHandler extends FileHandlerBase
{
@Override
public void onExtractionSuccess(@NotNull File file, @NotNull Metadata metadata, @NotNull String relativePath, @NotNull PrintStream log)
{
super.onExtractionSuccess(file, metadata, relativePath, log);
// Iterate through all values, calling toString to flush out any formatting exceptions
for (Directory directory : metadata.getDirectories()) {
directory.getName();
for (Tag tag : directory.getTags()) {
tag.getTagName();
tag.getDescription();
}
}
}
}
}
|
Formatting.
|
Source/com/drew/tools/ProcessAllImagesInFolderUtility.java
|
Formatting.
|
<ide><path>ource/com/drew/tools/ProcessAllImagesInFolderUtility.java
<ide> // Sanitise the extension
<ide> extension = extension.toLowerCase();
<ide> if (_extensionEquivalence.containsKey(extension))
<del> extension =_extensionEquivalence.get(extension);
<add> extension = _extensionEquivalence.get(extension);
<ide>
<ide> List<Row> list = _rowListByExtension.get(extension);
<ide> if (list == null) {
|
|
JavaScript
|
mit
|
afd692eea8d89c6640f077554bdc199baef14278
| 0 |
archangel-irk/storage,archangel-irk/storage
|
module.exports = function(config) {
var customLaunchers = {
sl_chrome_35: {
base: 'SauceLabs',
browserName: 'chrome',
version: '35'
},
sl_safari_6: {
base: 'SauceLabs',
browserName: 'safari',
platform: 'OS X 10.8',
version: '6'
},
/*sl_safari_7: {
base: 'SauceLabs',
browserName: 'safari',
platform: 'OS X 10.9',
version: '7'
},*/
sl_ie_9: {
base: 'SauceLabs',
browserName: 'internet explorer',
platform: 'Windows 7',
version: '9'
},
sl_ie_10: {
base: 'SauceLabs',
browserName: 'internet explorer',
platform: 'Windows 7',
version: '10'
},
/*sl_ie_11: {
base: 'SauceLabs',
browserName: 'internet explorer',
platform: 'Windows 7',
version: '11'
},*/
/*sl_android_43: {
base: 'SauceLabs',
browserName: 'android',
platform: 'Linux',
version: '4.3',
deviceName: 'Android',
'device-orientation': 'portrait'
}*/
};
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha', 'chai'],
// list of files / patterns to load in the browser
files: [
'./bin/mongoose.js',
'./test/browser/*.js'
],
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['dots', 'saucelabs'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// Use these custom launchers for starting browsers on Sauce
customLaunchers: customLaunchers,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: Object.keys(customLaunchers),
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true,
sauceLabs: {
testName: 'Storage ' + Date.now(),
'public': 'team',
'passed': true
}
});
};
|
toStudy/mongoose-master/karma.sauce.conf.js
|
module.exports = function(config) {
var customLaunchers = {
sl_chrome_35: {
base: 'SauceLabs',
browserName: 'chrome',
version: '35'
},
sl_safari_6: {
base: 'SauceLabs',
browserName: 'safari',
platform: 'OS X 10.8',
version: '6'
},
/*sl_safari_7: {
base: 'SauceLabs',
browserName: 'safari',
platform: 'OS X 10.9',
version: '7'
},*/
sl_ie_9: {
base: 'SauceLabs',
browserName: 'internet explorer',
platform: 'Windows 7',
version: '9'
},
sl_ie_10: {
base: 'SauceLabs',
browserName: 'internet explorer',
platform: 'Windows 7',
version: '10'
},
/*sl_ie_11: {
base: 'SauceLabs',
browserName: 'internet explorer',
platform: 'Windows 7',
version: '11'
},*/
/*sl_android_43: {
base: 'SauceLabs',
browserName: 'android',
platform: 'Linux',
version: '4.3',
deviceName: 'Android',
'device-orientation': 'portrait'
}*/
};
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha', 'chai'],
// list of files / patterns to load in the browser
files: [
'./bin/mongoose.js',
'./test/browser/*.js'
],
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['dots', 'saucelabs'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// Use these custom launchers for starting browsers on Sauce
customLaunchers: customLaunchers,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: Object.keys(customLaunchers),
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true,
sauceLabs: {
testName: 'Storage ' + Date.now()
}
});
};
|
sauce conf
|
toStudy/mongoose-master/karma.sauce.conf.js
|
sauce conf
|
<ide><path>oStudy/mongoose-master/karma.sauce.conf.js
<ide> singleRun: true,
<ide>
<ide> sauceLabs: {
<del> testName: 'Storage ' + Date.now()
<add> testName: 'Storage ' + Date.now(),
<add> 'public': 'team',
<add> 'passed': true
<ide> }
<ide> });
<ide> };
|
|
Java
|
apache-2.0
|
a8c19bfdbfc728dcbbdf6cf8f0bf05274e0a4724
| 0 |
osundblad/java-type-util
|
/*
* Copyright 2016 Olle Sundblad - [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package se.eris.jtype.cache;
import java.time.LocalDateTime;
import java.time.chrono.ChronoLocalDateTime;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
public final class FaultTolerantCache<K, V> {
private final Map<K, Dated<V>> cache = new ConcurrentHashMap<>();
private final Map<K, LocalDateTime> locks = new HashMap<>();
private final Function<K, Optional<V>> source;
private final CacheParameters<K> cacheParameters;
private final Supplier<LocalDateTime> timeSupplier;
private final ExecutorService executorService = Executors.newCachedThreadPool();
public static <K, V> FaultTolerantCache<K, V> of(final Function<K, Optional<V>> source, final CacheParameters<K> cacheParameters) {
return of(source, cacheParameters, LocalDateTime::now);
}
public static <K, V> FaultTolerantCache<K, V> of(final Function<K, Optional<V>> source, final CacheParameters<K> cacheParameters, final Supplier<LocalDateTime> timeSupplier) {
return new FaultTolerantCache<>(source, cacheParameters, timeSupplier);
}
private FaultTolerantCache(final Function<K, Optional<V>> source, final CacheParameters<K> cacheParameters, final Supplier<LocalDateTime> timeSupplier) {
this.source = source;
this.cacheParameters = cacheParameters;
this.timeSupplier = timeSupplier;
}
public Optional<V> get(final K key) {
final Optional<Dated<V>> opDated = Optional.ofNullable(cache.get(key));
if (!opDated.isPresent()) {
return syncFetch(key);
}
final Dated<V> dated = opDated.get();
final LocalDateTime now = timeSupplier.get();
if (now.isBefore(getEarliestRefetchTime(dated.getDateTime()))) {
return Optional.of(dated.getSubject());
}
if (now.isBefore(getSyncedRefetchTime(dated.getDateTime()))) {
asyncFetch(key);
return Optional.of(dated.getSubject());
}
return syncFetch(key, dated.getSubject());
}
private void asyncFetch(final K key) {
if (lock(key)) {
CompletableFuture
.supplyAsync(() -> syncFetch(key), executorService)
.handle((Optional<V> v, Throwable e) -> unlock(key));
}
}
private synchronized boolean lock(final K key) {
if (locks.containsKey(key)) {
return false;
}
locks.put(key, timeSupplier.get());
return true;
}
private boolean unlock(final K key) {
return locks.remove(key) != null;
}
private Optional<V> syncFetch(final K key, final V defaultValue) {
try {
return syncFetch(key);
} catch (final Exception e) {
return Optional.of(defaultValue);
}
}
private Optional<V> syncFetch(final K key) {
try {
final Optional<V> fetched = source.apply(key);
fetched.ifPresent(v -> put(key, v));
return fetched;
} catch (final RuntimeException e) {
cacheParameters.getSupplierFailedAction().ifPresent(throwableConsumer -> throwableConsumer.accept(key, e));
throw new SupplierFailedException(getSupplierFailedMessage(key), e);
}
}
private ChronoLocalDateTime getSyncedRefetchTime(final ChronoLocalDateTime dateTime) {
return dateTime.plus(cacheParameters.getRefetchSyncPeriod());
}
private ChronoLocalDateTime getEarliestRefetchTime(final ChronoLocalDateTime dateTime) {
return dateTime.plus(cacheParameters.getRefetchAsyncPeriod());
}
private String getSupplierFailedMessage(final K key) {
return "Source " + source + " failed to get key " + key;
}
public Optional<V> getIfPresent(final K key) {
return Optional.ofNullable(cache.get(key)).map(Dated::getSubject);
}
public void put(final K key, final V value) {
cache.put(key, Dated.of(timeSupplier.get(), value));
}
public Map<K, V> getPresent(final Collection<K> keys) {
return cache.entrySet().stream()
.filter(e -> keys.contains(e.getKey()))
.collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().getSubject()));
}
public Map<K, V> getPresentFresh(final Collection<K> keys) {
final ChronoLocalDateTime fetchedAfter = timeSupplier.get().minus(cacheParameters.getRefetchSyncPeriod());
return cache.entrySet().stream()
.filter(e -> keys.contains(e.getKey()))
.filter(e -> e.getValue().getDateTime().isAfter(fetchedAfter))
.collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().getSubject()));
}
}
|
src/main/java/se/eris/jtype/cache/FaultTolerantCache.java
|
/*
* Copyright 2016 Olle Sundblad - [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package se.eris.jtype.cache;
import java.time.LocalDateTime;
import java.time.chrono.ChronoLocalDateTime;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
public final class FaultTolerantCache<K, V> {
private final Map<K, Dated<V>> cache = new ConcurrentHashMap<>();
private final Map<K, LocalDateTime> locks = new HashMap<>();
private final Function<K, Optional<V>> source;
private final CacheParameters<K> cacheParameters;
private final Supplier<LocalDateTime> timeSupplier;
private final ExecutorService executorService = Executors.newCachedThreadPool();
public static <K, V> FaultTolerantCache<K, V> of(final Function<K, Optional<V>> source, final CacheParameters<K> cacheParameters) {
return of(source, cacheParameters, LocalDateTime::now);
}
public static <K, V> FaultTolerantCache<K, V> of(final Function<K, Optional<V>> source, final CacheParameters<K> cacheParameters, final Supplier<LocalDateTime> timeSupplier) {
return new FaultTolerantCache<>(source, cacheParameters, timeSupplier);
}
private FaultTolerantCache(final Function<K, Optional<V>> source, final CacheParameters<K> cacheParameters, final Supplier<LocalDateTime> timeSupplier) {
this.source = source;
this.cacheParameters = cacheParameters;
this.timeSupplier = timeSupplier;
}
public Optional<V> get(final K key) {
final Optional<Dated<V>> opDated = Optional.ofNullable(cache.get(key));
if (!opDated.isPresent()) {
return syncedFetch(key);
}
final Dated<V> dated = opDated.get();
final LocalDateTime now = timeSupplier.get();
if (now.isBefore(getEarliestRefetchTime(dated.getDateTime()))) {
return Optional.of(dated.getSubject());
}
if (now.isBefore(getSyncedRefetchTime(dated.getDateTime()))) {
asyncFetch(key);
return Optional.of(dated.getSubject());
}
return syncedFetch(key, dated.getSubject());
}
private void asyncFetch(final K key) {
if (lock(key)) {
CompletableFuture
.supplyAsync(() -> syncedFetch(key), executorService)
.thenAccept(v -> {
if (v.isPresent()) {
cache.put(key, Dated.of(timeSupplier.get(), v.get()));
} else {
throw new SupplierFailedException(getSupplierFailedMessage(key));
}
});
}
}
private synchronized boolean lock(final K key) {
if (locks.containsKey(key)) {
return false;
}
locks.put(key, timeSupplier.get());
return true;
}
private void unlock(final K key) {
locks.remove(key);
}
private Optional<V> syncedFetch(final K key, final V defaultValue) {
try {
return syncedFetch(key);
} catch (final Exception e) {
return Optional.of(defaultValue);
}
}
private Optional<V> syncedFetch(final K key) {
try {
final Optional<V> fetched = source.apply(key);
fetched.ifPresent(v -> put(key, v));
return fetched;
} catch (final RuntimeException e) {
cacheParameters.getSupplierFailedAction().ifPresent(throwableConsumer -> throwableConsumer.accept(key, e));
throw new SupplierFailedException(getSupplierFailedMessage(key), e);
} finally {
unlock(key);
}
}
private ChronoLocalDateTime getSyncedRefetchTime(final ChronoLocalDateTime dateTime) {
return dateTime.plus(cacheParameters.getRefetchSyncPeriod());
}
private ChronoLocalDateTime getEarliestRefetchTime(final ChronoLocalDateTime dateTime) {
return dateTime.plus(cacheParameters.getRefetchAsyncPeriod());
}
private String getSupplierFailedMessage(final K key) {
return "Source " + source + " failed to get key " + key;
}
public Optional<V> getIfPresent(final K key) {
return Optional.ofNullable(cache.get(key)).map(Dated::getSubject);
}
public void put(final K key, final V value) {
cache.put(key, Dated.of(timeSupplier.get(), value));
}
public Map<K, V> getPresent(final Collection<K> keys) {
return cache.entrySet().stream()
.filter(e -> keys.contains(e.getKey()))
.collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().getSubject()));
}
public Map<K, V> getPresentFresh(final Collection<K> keys) {
final ChronoLocalDateTime fetchedAfter = timeSupplier.get().minus(cacheParameters.getRefetchSyncPeriod());
return cache.entrySet().stream()
.filter(e -> keys.contains(e.getKey()))
.filter(e -> e.getValue().getDateTime().isAfter(fetchedAfter))
.collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().getSubject()));
}
}
|
a little bit better
|
src/main/java/se/eris/jtype/cache/FaultTolerantCache.java
|
a little bit better
|
<ide><path>rc/main/java/se/eris/jtype/cache/FaultTolerantCache.java
<ide> public Optional<V> get(final K key) {
<ide> final Optional<Dated<V>> opDated = Optional.ofNullable(cache.get(key));
<ide> if (!opDated.isPresent()) {
<del> return syncedFetch(key);
<add> return syncFetch(key);
<ide> }
<ide> final Dated<V> dated = opDated.get();
<ide> final LocalDateTime now = timeSupplier.get();
<ide> asyncFetch(key);
<ide> return Optional.of(dated.getSubject());
<ide> }
<del> return syncedFetch(key, dated.getSubject());
<add> return syncFetch(key, dated.getSubject());
<ide> }
<ide>
<ide>
<ide> private void asyncFetch(final K key) {
<ide> if (lock(key)) {
<ide> CompletableFuture
<del> .supplyAsync(() -> syncedFetch(key), executorService)
<del> .thenAccept(v -> {
<del> if (v.isPresent()) {
<del> cache.put(key, Dated.of(timeSupplier.get(), v.get()));
<del> } else {
<del> throw new SupplierFailedException(getSupplierFailedMessage(key));
<del> }
<del> });
<add> .supplyAsync(() -> syncFetch(key), executorService)
<add> .handle((Optional<V> v, Throwable e) -> unlock(key));
<ide> }
<ide> }
<ide>
<ide> return true;
<ide> }
<ide>
<del> private void unlock(final K key) {
<del> locks.remove(key);
<add> private boolean unlock(final K key) {
<add> return locks.remove(key) != null;
<ide> }
<ide>
<del> private Optional<V> syncedFetch(final K key, final V defaultValue) {
<add> private Optional<V> syncFetch(final K key, final V defaultValue) {
<ide> try {
<del> return syncedFetch(key);
<add> return syncFetch(key);
<ide> } catch (final Exception e) {
<ide> return Optional.of(defaultValue);
<ide> }
<ide> }
<ide>
<del> private Optional<V> syncedFetch(final K key) {
<add> private Optional<V> syncFetch(final K key) {
<ide> try {
<ide> final Optional<V> fetched = source.apply(key);
<ide> fetched.ifPresent(v -> put(key, v));
<ide> } catch (final RuntimeException e) {
<ide> cacheParameters.getSupplierFailedAction().ifPresent(throwableConsumer -> throwableConsumer.accept(key, e));
<ide> throw new SupplierFailedException(getSupplierFailedMessage(key), e);
<del> } finally {
<del> unlock(key);
<ide> }
<ide> }
<ide>
|
|
Java
|
apache-2.0
|
114068e9d2e01974d25d70df82f8958a4c1564be
| 0 |
klopfdreh/wicket,freiheit-com/wicket,dashorst/wicket,freiheit-com/wicket,topicusonderwijs/wicket,mosoft521/wicket,mafulafunk/wicket,AlienQueen/wicket,klopfdreh/wicket,dashorst/wicket,freiheit-com/wicket,aldaris/wicket,bitstorm/wicket,AlienQueen/wicket,klopfdreh/wicket,topicusonderwijs/wicket,selckin/wicket,aldaris/wicket,mosoft521/wicket,AlienQueen/wicket,apache/wicket,astrapi69/wicket,mosoft521/wicket,AlienQueen/wicket,AlienQueen/wicket,dashorst/wicket,astrapi69/wicket,mosoft521/wicket,bitstorm/wicket,aldaris/wicket,apache/wicket,mafulafunk/wicket,mosoft521/wicket,topicusonderwijs/wicket,apache/wicket,aldaris/wicket,bitstorm/wicket,astrapi69/wicket,apache/wicket,freiheit-com/wicket,klopfdreh/wicket,bitstorm/wicket,aldaris/wicket,mafulafunk/wicket,topicusonderwijs/wicket,selckin/wicket,dashorst/wicket,astrapi69/wicket,selckin/wicket,selckin/wicket,selckin/wicket,klopfdreh/wicket,apache/wicket,bitstorm/wicket,freiheit-com/wicket,dashorst/wicket,topicusonderwijs/wicket
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.wicket.page;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Request scoped helper class for {@link IPageManager}.
*
* @author Matej Knopp
*/
public abstract class RequestAdapter
{
private static final Logger log = LoggerFactory.getLogger(RequestAdapter.class);
private final IPageManagerContext context;
private final List<IManageablePage> touchedPages = new ArrayList<IManageablePage>();
/**
* Construct.
*
* @param context
* The page manager context
*/
public RequestAdapter(final IPageManagerContext context)
{
this.context = context;
}
/**
* Returns the page with specified id. The page is then cached by {@link RequestAdapter} during
* the rest of request processing.
*
* @param id
* @return page instance or <code>null</code> if the page does not exist.
*/
protected abstract IManageablePage getPage(int id);
/**
* Store the list of stateful pages.
*
* @param touchedPages
*/
protected abstract void storeTouchedPages(List<IManageablePage> touchedPages);
/**
* Notification on new session being created.
*/
protected abstract void newSessionCreated();
/**
* Bind the session
*
* @see IPageManagerContext#bind()
*/
protected void bind()
{
context.bind();
}
/**
* @see IPageManagerContext#setSessionAttribute(String, Serializable)
*
* @param key
* @param value
*/
public void setSessionAttribute(String key, Serializable value)
{
context.setSessionAttribute(key, value);
}
/**
* @see IPageManagerContext#getSessionAttribute(String)
*
* @param key
* @return the session attribute
*/
public Serializable getSessionAttribute(final String key)
{
return context.getSessionAttribute(key);
}
/**
* @see IPageManagerContext#getSessionId()
*
* @return session id
*/
public String getSessionId()
{
return context.getSessionId();
}
/**
*
* @param id
* @return null, if not found
*/
protected IManageablePage findPage(final int id)
{
for (IManageablePage page : touchedPages)
{
if (page.getPageId() == id)
{
return page;
}
}
return null;
}
/**
*
* @param page
*/
protected void touch(final IManageablePage page)
{
if (findPage(page.getPageId()) == null)
{
touchedPages.add(page);
}
}
/**
*
*/
protected void commitRequest()
{
// store pages that are not stateless
if (touchedPages.isEmpty() == false)
{
List<IManageablePage> statefulPages = new ArrayList<IManageablePage>(
touchedPages.size());
for (IManageablePage page : touchedPages)
{
try
{
page.detach();
}
catch (Exception e)
{
log.error("Error detaching page", e);
}
boolean isPageStateless;
try
{
isPageStateless = page.isPageStateless();
}
catch (Exception x)
{
log.warn("An error occurred while checking whether a page is stateless. Assuming it is stateful.", x);
isPageStateless = false;
}
if (isPageStateless == false)
{
statefulPages.add(page);
}
}
if (statefulPages.isEmpty() == false)
{
storeTouchedPages(statefulPages);
}
}
}
}
|
wicket-core/src/main/java/org/apache/wicket/page/RequestAdapter.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.wicket.page;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Request scoped helper class for {@link IPageManager}.
*
* @author Matej Knopp
*/
public abstract class RequestAdapter
{
private static final Logger log = LoggerFactory.getLogger(RequestAdapter.class);
private final IPageManagerContext context;
private final List<IManageablePage> touchedPages = new ArrayList<IManageablePage>();
/**
* Construct.
*
* @param context
* The page manager context
*/
public RequestAdapter(final IPageManagerContext context)
{
this.context = context;
}
/**
* Returns the page with specified id. The page is then cached by {@link RequestAdapter} during
* the rest of request processing.
*
* @param id
* @return page instance or <code>null</code> if the page does not exist.
*/
protected abstract IManageablePage getPage(int id);
/**
* Store the list of stateful pages.
*
* @param touchedPages
*/
protected abstract void storeTouchedPages(List<IManageablePage> touchedPages);
/**
* Notification on new session being created.
*/
protected abstract void newSessionCreated();
/**
* Bind the session
*
* @see IPageManagerContext#bind()
*/
protected void bind()
{
context.bind();
}
/**
* @see IPageManagerContext#setSessionAttribute(String, Serializable)
*
* @param key
* @param value
*/
public void setSessionAttribute(String key, Serializable value)
{
context.setSessionAttribute(key, value);
}
/**
* @see IPageManagerContext#getSessionAttribute(String)
*
* @param key
* @return the session attribute
*/
public Serializable getSessionAttribute(final String key)
{
return context.getSessionAttribute(key);
}
/**
* @see IPageManagerContext#getSessionId()
*
* @return session id
*/
public String getSessionId()
{
return context.getSessionId();
}
/**
*
* @param id
* @return null, if not found
*/
protected IManageablePage findPage(final int id)
{
for (IManageablePage page : touchedPages)
{
if (page.getPageId() == id)
{
return page;
}
}
return null;
}
/**
*
* @param page
*/
protected void touch(final IManageablePage page)
{
if (findPage(page.getPageId()) == null)
{
touchedPages.add(page);
}
}
/**
*
*/
protected void commitRequest()
{
// store pages that are not stateless
if (touchedPages.isEmpty() == false)
{
List<IManageablePage> statefulPages = new ArrayList<IManageablePage>(
touchedPages.size());
for (IManageablePage page : touchedPages)
{
try
{
page.detach();
}
catch (Exception e)
{
log.error("Error detaching page", e);
}
if (!page.isPageStateless())
{
statefulPages.add(page);
}
}
if (statefulPages.isEmpty() == false)
{
storeTouchedPages(statefulPages);
}
}
}
}
|
WICKET-5023 Page store process is broken if an exception occurs at commit request phase.
|
wicket-core/src/main/java/org/apache/wicket/page/RequestAdapter.java
|
WICKET-5023 Page store process is broken if an exception occurs at commit request phase.
|
<ide><path>icket-core/src/main/java/org/apache/wicket/page/RequestAdapter.java
<ide> log.error("Error detaching page", e);
<ide> }
<ide>
<del> if (!page.isPageStateless())
<add> boolean isPageStateless;
<add> try
<add> {
<add> isPageStateless = page.isPageStateless();
<add> }
<add> catch (Exception x)
<add> {
<add> log.warn("An error occurred while checking whether a page is stateless. Assuming it is stateful.", x);
<add> isPageStateless = false;
<add> }
<add> if (isPageStateless == false)
<ide> {
<ide> statefulPages.add(page);
<ide> }
|
|
Java
|
agpl-3.0
|
3bf21479a8c6c2a51d29783203435459e94ecdcc
| 0 |
BloatIt/bloatit,BloatIt/bloatit,BloatIt/bloatit,BloatIt/bloatit,BloatIt/bloatit
|
//
// Copyright (c) 2011 Linkeos.
//
// This file is part of Elveos.org.
// Elveos.org is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// Elveos.org is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
// You should have received a copy of the GNU General Public License along
// with Elveos.org. If not, see http://www.gnu.org/licenses/.
//
package com.bloatit.model;
import java.util.EnumSet;
import com.bloatit.common.Log;
import com.bloatit.data.DaoKudosable;
import com.bloatit.data.DaoKudosable.PopularityState;
import com.bloatit.data.DaoMember.Role;
import com.bloatit.model.right.Action;
import com.bloatit.model.right.AuthenticatedUserToken;
import com.bloatit.model.right.RgtKudosable;
import com.bloatit.model.right.UnauthorizedOperationException;
import com.bloatit.model.right.UnauthorizedOperationException.SpecialCode;
public abstract class Kudosable<T extends DaoKudosable> extends UserContent<T> implements KudosableInterface {
public Kudosable(final T dao) {
super(dao);
}
/*
* (non-Javadoc)
* @see com.bloatit.model.KudosableInterface#canKudos()
*/
@Override
public EnumSet<SpecialCode> canVoteUp() {
return canVote(1);
}
/*
* (non-Javadoc)
* @see com.bloatit.model.KudosableInterface#canUnkudos()
*/
@Override
public EnumSet<SpecialCode> canVoteDown() {
return canVote(-1);
}
private final EnumSet<SpecialCode> canVote(final int sign) {
final EnumSet<SpecialCode> errors = EnumSet.noneOf(SpecialCode.class);
// See if we can kudos.
if (!canAccess(new RgtKudosable.Kudos(), Action.WRITE)) {
errors.add(SpecialCode.NOTHING_SPECIAL);
}
if (getDao().isPopularityLocked()) {
errors.add(SpecialCode.KUDOSABLE_LOCKED);
}
if (getAuthTokenUnprotected() == null) {
errors.add(SpecialCode.AUTHENTICATION_NEEDED);
// Stop tests here: the other tests need an AuthToken
return errors;
}
if (getAuthTokenUnprotected().getMember().getRole() == Role.ADMIN) {
// Stop here. The member is an admin. He must be able to kudos
// everything.
return errors;
}
// I cannot kudos my own content.
if (getRights().isOwner()) {
errors.add(SpecialCode.OWNED_BY_ME);
}
// Only one kudos per person
if (getDao().hasKudosed(getAuthTokenUnprotected().getMember().getDao())) {
errors.add(SpecialCode.ALREADY_VOTED);
}
// Make sure we are in the right position
final Member member = getAuthTokenUnprotected().getMember();
final int influence = member.calculateInfluence();
if (sign == -1 && influence < ModelConfiguration.getKudosableMinInfluenceToUnkudos()) {
errors.add(SpecialCode.INFLUENCE_LOW_ON_VOTE_DOWN);
}
if (sign == 1 && influence < ModelConfiguration.getKudosableMinInfluenceToKudos()) {
errors.add(SpecialCode.INFLUENCE_LOW_ON_VOTE_UP);
}
return errors;
}
/*
* (non-Javadoc)
* @see com.bloatit.model.KudosableInterface#unkudos()
*/
@Override
public final int voteDown() throws UnauthorizedOperationException {
final int vote = vote(-1);
notifyKudos(false);
return vote;
}
/*
* (non-Javadoc)
* @see com.bloatit.model.KudosableInterface#kudos()
*/
@Override
public final int voteUp() throws UnauthorizedOperationException {
final int vote = vote(1);
notifyKudos(true);
return vote;
}
private int vote(final int sign) throws UnauthorizedOperationException {
final EnumSet<SpecialCode> canKudos = canVote(sign);
if (!canKudos.isEmpty()) {
throw new UnauthorizedOperationException(canKudos.iterator().next());
}
// Make sure we are in the right position
final Member member = getAuthToken().getMember();
final int influence = member.calculateInfluence();
if (influence > 0) {
getMember().addToKarma(sign * influence);
calculateNewState(getDao().addKudos(member.getDao(), DaoGetter.get(getAuthToken().getAsTeam()), sign * influence));
}
return influence * sign;
}
private void calculateNewState(final int newPop) {
switch (getState()) {
case PENDING:
if (newPop >= turnValid()) {
setStateUnprotected(PopularityState.VALIDATED);
notifyValid();
} else if (newPop <= turnHidden() && newPop > turnRejected()) {
setStateUnprotected(PopularityState.HIDDEN);
notifyHidden();
} else if (newPop <= turnRejected()) {
setStateUnprotected(PopularityState.REJECTED);
notifyRejected();
}
// NO BREAK IT IS OK !!
case VALIDATED:
if (newPop <= turnPending()) {
setStateUnprotected(PopularityState.PENDING);
notifyPending();
}
break;
case HIDDEN:
case REJECTED:
if (newPop >= turnPending() && newPop < turnValid()) {
setStateUnprotected(PopularityState.PENDING);
notifyPending();
} else if (newPop >= turnValid()) {
setStateUnprotected(PopularityState.VALIDATED);
notifyValid();
} else if (newPop <= turnHidden() && newPop > turnRejected()) {
setStateUnprotected(PopularityState.VALIDATED);
notifyValid();
} else if (newPop <= turnRejected()) {
setStateUnprotected(PopularityState.REJECTED);
notifyRejected();
}
break;
default:
assert false;
break;
}
}
private void setStateUnprotected(final PopularityState newState) {
if (getState() != newState) {
Log.model().info("Kudosable: " + getId() + " change from state: " + this.getState() + ", to: " + newState);
}
getDao().setState(newState);
}
public void setState(final PopularityState newState) throws UnauthorizedOperationException {
if (!getRights().hasAdminUserPrivilege()) {
throw new UnauthorizedOperationException(SpecialCode.ADMIN_ONLY);
}
setStateUnprotected(newState);
}
@Override
public void lockPopularity() throws UnauthorizedOperationException {
if (!getRights().hasAdminUserPrivilege()) {
throw new UnauthorizedOperationException(SpecialCode.ADMIN_ONLY);
}
getDao().lockPopularity();
}
@Override
public void unlockPopularity() throws UnauthorizedOperationException {
if (!getRights().hasAdminUserPrivilege()) {
throw new UnauthorizedOperationException(SpecialCode.ADMIN_ONLY);
}
getDao().unlockPopularity();
}
@Override
public final PopularityState getState() {
return getDao().getState();
}
@Override
public boolean isPopularityLocked() throws UnauthorizedOperationException {
return getDao().isPopularityLocked();
}
@Override
public final int getPopularity() {
return getDao().getPopularity();
}
@Override
public int getUserVoteValue() {
final AuthenticatedUserToken userToken = getAuthTokenUnprotected();
if (getAuthTokenUnprotected() == null) {
return 0;
}
return getDao().getVote(userToken.getMember().getDao());
}
/**
* You can redefine me if you want to customize the state calculation
* limits.
*
* @return The popularity to for a Kudosable to reach to turn to
* {@link PopularityState#PENDING} state.
*/
protected int turnPending() {
return ModelConfiguration.getKudosableDefaultTurnPending();
}
/**
* You can redefine me if you want to customize the state calculation
* limits.
*
* @return The popularity to for a Kudosable to reach to turn to
* {@link PopularityState#VALIDATED} state.
*/
protected int turnValid() {
return ModelConfiguration.getKudosableDefaultTurnValid();
}
/**
* You can redefine me if you want to customize the state calculation
* limits.
*
* @return The popularity to for a Kudosable to reach to turn to
* {@link PopularityState#REJECTED} state.
*/
protected int turnRejected() {
return ModelConfiguration.getKudosableDefaultTurnRejected();
}
/**
* You can redefine me if you want to customize the state calculation
* limits.
*
* @return The popularity to for a Kudosable to reach to turn to
* {@link PopularityState#HIDDEN} state.
*/
protected int turnHidden() {
return ModelConfiguration.getKudosableDefaultTurnHidden();
}
/**
* This method is called each time this Kudosable is kudosed.
*
* @param positif true if it is a kudos false if it is an unKudos.
*/
protected void notifyKudos(final boolean positif) {
// Implement me if you wish
}
/**
* This method is called each time this Kudosable change its state to valid.
*/
protected void notifyValid() {
// Implement me if you wish
}
/**
* This method is called each time this Kudosable change its state to
* pending.
*/
protected void notifyPending() {
// Implement me if you wish
}
/**
* This method is called each time this Kudosable change its state to
* rejected.
*/
protected void notifyRejected() {
// Implement me if you wish
}
/**
* This method is called each time this Kudosable change its state to
* Hidden.
*/
private void notifyHidden() {
// Implement me if you wish
}
}
|
main/src/main/java/com/bloatit/model/Kudosable.java
|
//
// Copyright (c) 2011 Linkeos.
//
// This file is part of Elveos.org.
// Elveos.org is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// Elveos.org is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
// You should have received a copy of the GNU General Public License along
// with Elveos.org. If not, see http://www.gnu.org/licenses/.
//
package com.bloatit.model;
import java.util.EnumSet;
import com.bloatit.common.Log;
import com.bloatit.data.DaoKudosable;
import com.bloatit.data.DaoKudosable.PopularityState;
import com.bloatit.data.DaoMember.Role;
import com.bloatit.model.right.Action;
import com.bloatit.model.right.AuthenticatedUserToken;
import com.bloatit.model.right.RgtKudosable;
import com.bloatit.model.right.UnauthorizedOperationException;
import com.bloatit.model.right.UnauthorizedOperationException.SpecialCode;
public abstract class Kudosable<T extends DaoKudosable> extends UserContent<T> implements KudosableInterface {
public Kudosable(final T dao) {
super(dao);
}
/*
* (non-Javadoc)
* @see com.bloatit.model.KudosableInterface#canKudos()
*/
@Override
public EnumSet<SpecialCode> canVoteUp() {
return canVote(1);
}
/*
* (non-Javadoc)
* @see com.bloatit.model.KudosableInterface#canUnkudos()
*/
@Override
public EnumSet<SpecialCode> canVoteDown() {
return canVote(-1);
}
private final EnumSet<SpecialCode> canVote(final int sign) {
final EnumSet<SpecialCode> errors = EnumSet.noneOf(SpecialCode.class);
// See if we can kudos.
if (!canAccess(new RgtKudosable.Kudos(), Action.WRITE)) {
errors.add(SpecialCode.NOTHING_SPECIAL);
}
if (getDao().isPopularityLocked()) {
errors.add(SpecialCode.KUDOSABLE_LOCKED);
}
if (getAuthTokenUnprotected() == null) {
errors.add(SpecialCode.AUTHENTICATION_NEEDED);
// Stop tests here: the other tests need an AuthToken
return errors;
}
if (getAuthTokenUnprotected().getMember().getRole() == Role.ADMIN) {
// Stop here. The member is an admin. He must be able to kudos
// everything.
return errors;
}
// I cannot kudos my own content.
if (getRights().isOwner()) {
errors.add(SpecialCode.OWNED_BY_ME);
}
// Only one kudos per person
if (getDao().hasKudosed(getAuthTokenUnprotected().getMember().getDao())) {
errors.add(SpecialCode.ALREADY_VOTED);
}
// Make sure we are in the right position
final Member member = getAuthTokenUnprotected().getMember();
final int influence = member.calculateInfluence();
if (sign == -1 && influence < ModelConfiguration.getKudosableMinInfluenceToUnkudos()) {
errors.add(SpecialCode.INFLUENCE_LOW_ON_VOTE_DOWN);
}
if (sign == 1 && influence < ModelConfiguration.getKudosableMinInfluenceToKudos()) {
errors.add(SpecialCode.INFLUENCE_LOW_ON_VOTE_UP);
}
return errors;
}
/*
* (non-Javadoc)
* @see com.bloatit.model.KudosableInterface#unkudos()
*/
@Override
public final int voteDown() throws UnauthorizedOperationException {
final int vote = vote(-1);
notifyKudos(false);
return vote;
}
/*
* (non-Javadoc)
* @see com.bloatit.model.KudosableInterface#kudos()
*/
@Override
public final int voteUp() throws UnauthorizedOperationException {
final int vote = vote(1);
notifyKudos(true);
return vote;
}
private int vote(final int sign) throws UnauthorizedOperationException {
final EnumSet<SpecialCode> canKudos = canVote(sign);
if (!canKudos.isEmpty()) {
throw new UnauthorizedOperationException(canKudos.iterator().next());
}
// Make sure we are in the right position
final Member member = getAuthToken().getMember();
final int influence = member.calculateInfluence();
if (influence > 0) {
getMember().addToKarma(influence);
calculateNewState(getDao().addKudos(member.getDao(), DaoGetter.get(getAuthToken().getAsTeam()), sign * influence));
}
return influence * sign;
}
private void calculateNewState(final int newPop) {
switch (getState()) {
case PENDING:
if (newPop >= turnValid()) {
setStateUnprotected(PopularityState.VALIDATED);
notifyValid();
} else if (newPop <= turnHidden() && newPop > turnRejected()) {
setStateUnprotected(PopularityState.HIDDEN);
notifyHidden();
} else if (newPop <= turnRejected()) {
setStateUnprotected(PopularityState.REJECTED);
notifyRejected();
}
// NO BREAK IT IS OK !!
case VALIDATED:
if (newPop <= turnPending()) {
setStateUnprotected(PopularityState.PENDING);
notifyPending();
}
break;
case HIDDEN:
case REJECTED:
if (newPop >= turnPending() && newPop < turnValid()) {
setStateUnprotected(PopularityState.PENDING);
notifyPending();
} else if (newPop >= turnValid()) {
setStateUnprotected(PopularityState.VALIDATED);
notifyValid();
} else if (newPop <= turnHidden() && newPop > turnRejected()) {
setStateUnprotected(PopularityState.VALIDATED);
notifyValid();
} else if (newPop <= turnRejected()) {
setStateUnprotected(PopularityState.REJECTED);
notifyRejected();
}
break;
default:
assert false;
break;
}
}
private void setStateUnprotected(final PopularityState newState) {
if (getState() != newState) {
Log.model().info("Kudosable: " + getId() + " change from state: " + this.getState() + ", to: " + newState);
}
getDao().setState(newState);
}
public void setState(final PopularityState newState) throws UnauthorizedOperationException {
if (!getRights().hasAdminUserPrivilege()) {
throw new UnauthorizedOperationException(SpecialCode.ADMIN_ONLY);
}
setStateUnprotected(newState);
}
@Override
public void lockPopularity() throws UnauthorizedOperationException {
if (!getRights().hasAdminUserPrivilege()) {
throw new UnauthorizedOperationException(SpecialCode.ADMIN_ONLY);
}
getDao().lockPopularity();
}
@Override
public void unlockPopularity() throws UnauthorizedOperationException {
if (!getRights().hasAdminUserPrivilege()) {
throw new UnauthorizedOperationException(SpecialCode.ADMIN_ONLY);
}
getDao().unlockPopularity();
}
@Override
public final PopularityState getState() {
return getDao().getState();
}
@Override
public boolean isPopularityLocked() throws UnauthorizedOperationException {
return getDao().isPopularityLocked();
}
@Override
public final int getPopularity() {
return getDao().getPopularity();
}
@Override
public int getUserVoteValue() {
final AuthenticatedUserToken userToken = getAuthTokenUnprotected();
if (getAuthTokenUnprotected() == null) {
return 0;
}
return getDao().getVote(userToken.getMember().getDao());
}
/**
* You can redefine me if you want to customize the state calculation
* limits.
*
* @return The popularity to for a Kudosable to reach to turn to
* {@link PopularityState#PENDING} state.
*/
protected int turnPending() {
return ModelConfiguration.getKudosableDefaultTurnPending();
}
/**
* You can redefine me if you want to customize the state calculation
* limits.
*
* @return The popularity to for a Kudosable to reach to turn to
* {@link PopularityState#VALIDATED} state.
*/
protected int turnValid() {
return ModelConfiguration.getKudosableDefaultTurnValid();
}
/**
* You can redefine me if you want to customize the state calculation
* limits.
*
* @return The popularity to for a Kudosable to reach to turn to
* {@link PopularityState#REJECTED} state.
*/
protected int turnRejected() {
return ModelConfiguration.getKudosableDefaultTurnRejected();
}
/**
* You can redefine me if you want to customize the state calculation
* limits.
*
* @return The popularity to for a Kudosable to reach to turn to
* {@link PopularityState#HIDDEN} state.
*/
protected int turnHidden() {
return ModelConfiguration.getKudosableDefaultTurnHidden();
}
/**
* This method is called each time this Kudosable is kudosed.
*
* @param positif true if it is a kudos false if it is an unKudos.
*/
protected void notifyKudos(final boolean positif) {
// Implement me if you wish
}
/**
* This method is called each time this Kudosable change its state to valid.
*/
protected void notifyValid() {
// Implement me if you wish
}
/**
* This method is called each time this Kudosable change its state to
* pending.
*/
protected void notifyPending() {
// Implement me if you wish
}
/**
* This method is called each time this Kudosable change its state to
* rejected.
*/
protected void notifyRejected() {
// Implement me if you wish
}
/**
* This method is called each time this Kudosable change its state to
* Hidden.
*/
private void notifyHidden() {
// Implement me if you wish
}
}
|
fix karma attribution with negative votes
|
main/src/main/java/com/bloatit/model/Kudosable.java
|
fix karma attribution with negative votes
|
<ide><path>ain/src/main/java/com/bloatit/model/Kudosable.java
<ide> final int influence = member.calculateInfluence();
<ide>
<ide> if (influence > 0) {
<del> getMember().addToKarma(influence);
<add> getMember().addToKarma(sign * influence);
<ide> calculateNewState(getDao().addKudos(member.getDao(), DaoGetter.get(getAuthToken().getAsTeam()), sign * influence));
<ide> }
<ide>
|
|
Java
|
apache-2.0
|
46a269fae853f04c557ec7271d0ad3e1b758bad8
| 0 |
michalmac/jsprit,graphhopper/jsprit,muzuro/jsprit,HeinrichFilter/jsprit,balage1551/jsprit,sinhautkarsh2014/winter_jsprit
|
/*******************************************************************************
* Copyright (C) 2014 Stefan Schroeder
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3.0 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package jsprit.examples;
import jsprit.core.algorithm.*;
import jsprit.core.algorithm.acceptor.GreedyAcceptance;
import jsprit.core.algorithm.module.RuinAndRecreateModule;
import jsprit.core.algorithm.recreate.BestInsertionBuilder;
import jsprit.core.algorithm.recreate.InsertionStrategy;
import jsprit.core.algorithm.ruin.RadialRuinStrategyFactory;
import jsprit.core.algorithm.ruin.RandomRuinStrategyFactory;
import jsprit.core.algorithm.ruin.RuinStrategy;
import jsprit.core.algorithm.ruin.distance.AvgServiceAndShipmentDistance;
import jsprit.core.algorithm.selector.SelectBest;
import jsprit.core.algorithm.state.StateManager;
import jsprit.core.algorithm.state.UpdateVariableCosts;
import jsprit.core.algorithm.termination.IterationWithoutImprovementTermination;
import jsprit.core.problem.VehicleRoutingProblem;
import jsprit.core.problem.constraint.ConstraintManager;
import jsprit.core.problem.solution.SolutionCostCalculator;
import jsprit.core.problem.solution.VehicleRoutingProblemSolution;
import jsprit.core.problem.vehicle.InfiniteFleetManagerFactory;
import jsprit.core.problem.vehicle.VehicleFleetManager;
import jsprit.core.reporting.SolutionPrinter;
import jsprit.core.util.Solutions;
import jsprit.instance.reader.SolomonReader;
import jsprit.util.Examples;
import java.util.Collection;
public class BuildAlgorithmFromScratchWithHardAndSoftConstraints {
public static void main(String[] args) {
/*
* some preparation - create output folder
*/
Examples.createOutputFolder();
/*
* Build the problem.
*
* But define a problem-builder first.
*/
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
/*
* A solomonReader reads solomon-instance files, and stores the required information in the builder.
*/
new SolomonReader(vrpBuilder).read("input/C101_solomon.txt");
/*
* Finally, the problem can be built. By default, transportCosts are crowFlyDistances (as usually used for vrp-instances).
*/
VehicleRoutingProblem vrp = vrpBuilder.build();
/*
* Build algorithm
*/
VehicleRoutingAlgorithm vra = buildAlgorithmFromScratch(vrp);
/*
* search solution
*/
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
/*
* print result
*/
SolutionPrinter.print(Solutions.bestOf(solutions));
}
private static VehicleRoutingAlgorithm buildAlgorithmFromScratch(VehicleRoutingProblem vrp) {
/*
* manages route and activity states.
*/
StateManager stateManager = new StateManager(vrp);
/*
* tells stateManager to update load states
*/
stateManager.updateLoadStates();
/*
* tells stateManager to update time-window states
*/
stateManager.updateTimeWindowStates();
/*
* stateManager.addStateUpdater(updater);
* lets you register your own stateUpdater
*/
/*
* updates variable costs once a vehicleRoute has changed (by removing or adding a customer)
*/
stateManager.addStateUpdater(new UpdateVariableCosts(vrp.getActivityCosts(), vrp.getTransportCosts(), stateManager));
/*
* constructs a constraintManager that manages the various hardConstraints (and soon also softConstraints)
*/
ConstraintManager constraintManager = new ConstraintManager(vrp,stateManager);
/*
* tells constraintManager to add timeWindowConstraints
*/
constraintManager.addTimeWindowConstraint();
/*
* tells constraintManager to add loadConstraints
*/
constraintManager.addLoadConstraint();
/*
* add an arbitrary number of hardConstraints by
* constraintManager.addConstraint(...)
*/
/*
* define a fleetManager, here infinite vehicles can be used
*/
VehicleFleetManager fleetManager = new InfiniteFleetManagerFactory(vrp.getVehicles()).createFleetManager();
/*
* define ruin-and-recreate strategies
*
*/
/*
* first, define an insertion-strategy, i.e. bestInsertion
*/
BestInsertionBuilder iBuilder = new BestInsertionBuilder(vrp, fleetManager, stateManager, constraintManager);
/*
* no need to set further options
*/
InsertionStrategy iStrategy = iBuilder.build();
/*
* second, define random-ruin that ruins 50-percent of the selected solution
*/
RuinStrategy randomRuin = new RandomRuinStrategyFactory(0.5).createStrategy(vrp);
/*
* third, define radial-ruin that ruins 30-percent of the selected solution
* the second para defines the distance between two jobs.
*/
RuinStrategy radialRuin = new RadialRuinStrategyFactory(0.3, new AvgServiceAndShipmentDistance(vrp.getTransportCosts())).createStrategy(vrp);
/*
* now define a strategy
*/
/*
* but before define how a generated solution is evaluated
* here: the VariablePlusFixed.... comes out of the box and it does what its name suggests
*/
SolutionCostCalculator solutionCostCalculator = new VariablePlusFixedSolutionCostCalculatorFactory(stateManager).createCalculator();
SearchStrategy firstStrategy = new SearchStrategy("random",new SelectBest(), new GreedyAcceptance(1), solutionCostCalculator);
firstStrategy.addModule(new RuinAndRecreateModule("randomRuinAndBestInsertion", iStrategy, randomRuin));
SearchStrategy secondStrategy = new SearchStrategy("radial",new SelectBest(), new GreedyAcceptance(1), solutionCostCalculator);
secondStrategy.addModule(new RuinAndRecreateModule("radialRuinAndBestInsertion", iStrategy, radialRuin));
/*
* put both strategies together, each with the prob of 0.5 to be selected
*/
SearchStrategyManager searchStrategyManager = new SearchStrategyManager();
searchStrategyManager.addStrategy(firstStrategy, 0.5);
searchStrategyManager.addStrategy(secondStrategy, 0.5);
/*
* construct the algorithm
*/
VehicleRoutingAlgorithm vra = new VehicleRoutingAlgorithm(vrp, searchStrategyManager);
//do not forgett to add the stateManager listening to the algorithm-stages
vra.addListener(stateManager);
//remove empty vehicles after insertion has finished
vra.addListener(new RemoveEmptyVehicles(fleetManager));
/*
* Do not forget to add an initial solution by vra.addInitialSolution(solution);
* or
*/
vra.addInitialSolution(new InsertionInitialSolutionFactory(iStrategy, solutionCostCalculator).createSolution(vrp));
/*
* define the nIterations (by default nIteration=100)
*/
vra.setMaxIterations(1000);
/*
* optionally define a premature termination criterion (by default: not criterion is set)
*/
vra.setPrematureAlgorithmTermination(new IterationWithoutImprovementTermination(100));
return vra;
}
}
|
jsprit-examples/src/main/java/jsprit/examples/BuildAlgorithmFromScratchWithHardAndSoftConstraints.java
|
/*******************************************************************************
* Copyright (C) 2014 Stefan Schroeder
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3.0 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package jsprit.examples;
import jsprit.core.algorithm.*;
import jsprit.core.algorithm.acceptor.GreedyAcceptance;
import jsprit.core.algorithm.module.RuinAndRecreateModule;
import jsprit.core.algorithm.recreate.BestInsertionBuilder;
import jsprit.core.algorithm.recreate.InsertionStrategy;
import jsprit.core.algorithm.ruin.RadialRuinStrategyFactory;
import jsprit.core.algorithm.ruin.RandomRuinStrategyFactory;
import jsprit.core.algorithm.ruin.RuinStrategy;
import jsprit.core.algorithm.ruin.distance.AvgServiceAndShipmentDistance;
import jsprit.core.algorithm.selector.SelectBest;
import jsprit.core.algorithm.state.StateManager;
import jsprit.core.algorithm.state.UpdateVariableCosts;
import jsprit.core.algorithm.termination.IterationWithoutImprovementTermination;
import jsprit.core.problem.VehicleRoutingProblem;
import jsprit.core.problem.constraint.ConstraintManager;
import jsprit.core.problem.solution.SolutionCostCalculator;
import jsprit.core.problem.solution.VehicleRoutingProblemSolution;
import jsprit.core.problem.vehicle.InfiniteFleetManagerFactory;
import jsprit.core.problem.vehicle.VehicleFleetManager;
import jsprit.core.reporting.SolutionPrinter;
import jsprit.core.util.Solutions;
import jsprit.instance.reader.SolomonReader;
import jsprit.util.Examples;
import java.util.Collection;
public class BuildAlgorithmFromScratchWithHardAndSoftConstraints {
public static void main(String[] args) {
/*
* some preparation - create output folder
*/
Examples.createOutputFolder();
/*
* Build the problem.
*
* But define a problem-builder first.
*/
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
/*
* A solomonReader reads solomon-instance files, and stores the required information in the builder.
*/
new SolomonReader(vrpBuilder).read("input/C101_solomon.txt");
/*
* Finally, the problem can be built. By default, transportCosts are crowFlyDistances (as usually used for vrp-instances).
*/
VehicleRoutingProblem vrp = vrpBuilder.build();
/*
* Build algorithm
*/
VehicleRoutingAlgorithm vra = buildAlgorithmFromScratch(vrp);
/*
* search solution
*/
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
/*
* print result
*/
SolutionPrinter.print(Solutions.bestOf(solutions));
}
private static VehicleRoutingAlgorithm buildAlgorithmFromScratch(VehicleRoutingProblem vrp) {
/*
* manages route and activity states.
*/
StateManager stateManager = new StateManager(vrp);
/*
* tells stateManager to update load states
*/
stateManager.updateLoadStates();
/*
* tells stateManager to update time-window states
*/
stateManager.updateTimeWindowStates();
/*
* stateManager.addStateUpdater(updater);
* lets you register your own stateUpdater
*/
/*
* updates variable costs once a vehicleRoute has changed (by removing or adding a customer)
*/
stateManager.addStateUpdater(new UpdateVariableCosts(vrp.getActivityCosts(), vrp.getTransportCosts(), stateManager));
/*
* constructs a constraintManager that manages the various hardConstraints (and soon also softConstraints)
*/
ConstraintManager constraintManager = new ConstraintManager(vrp,stateManager);
/*
* tells constraintManager to add timeWindowConstraints
*/
constraintManager.addTimeWindowConstraint();
/*
* tells constraintManager to add loadConstraints
*/
constraintManager.addLoadConstraint();
/*
* add an arbitrary number of hardConstraints by
* constraintManager.addConstraint(...)
*/
/*
* define a fleetManager, here infinite vehicles can be used
*/
VehicleFleetManager fleetManager = new InfiniteFleetManagerFactory(vrp.getVehicles()).createFleetManager();
/*
* define ruin-and-recreate strategies
*
*/
/*
* first, define an insertion-strategy, i.e. bestInsertion
*/
BestInsertionBuilder iBuilder = new BestInsertionBuilder(vrp, fleetManager, stateManager, constraintManager);
/*
* no need to set further options
*/
InsertionStrategy iStrategy = iBuilder.build();
/*
* second, define random-ruin that ruins 50-percent of the selected solution
*/
RuinStrategy randomRuin = new RandomRuinStrategyFactory(0.5).createStrategy(vrp);
/*
* third, define radial-ruin that ruins 30-percent of the selected solution
* the second para defines the distance between two jobs.
*/
RuinStrategy radialRuin = new RadialRuinStrategyFactory(0.3, new AvgServiceAndShipmentDistance(vrp.getTransportCosts())).createStrategy(vrp);
/*
* now define a strategy
*/
/*
* but before define how a generated solution is evaluated
* here: the VariablePlusFixed.... comes out of the box and it does what its name suggests
*/
SolutionCostCalculator solutionCostCalculator = new VariablePlusFixedSolutionCostCalculatorFactory(stateManager).createCalculator();
SearchStrategy firstStrategy = new SearchStrategy(new SelectBest(), new GreedyAcceptance(1), solutionCostCalculator);
firstStrategy.addModule(new RuinAndRecreateModule("randomRuinAndBestInsertion", iStrategy, randomRuin));
SearchStrategy secondStrategy = new SearchStrategy(new SelectBest(), new GreedyAcceptance(1), solutionCostCalculator);
secondStrategy.addModule(new RuinAndRecreateModule("radialRuinAndBestInsertion", iStrategy, radialRuin));
/*
* put both strategies together, each with the prob of 0.5 to be selected
*/
SearchStrategyManager searchStrategyManager = new SearchStrategyManager();
searchStrategyManager.addStrategy(firstStrategy, 0.5);
searchStrategyManager.addStrategy(secondStrategy, 0.5);
/*
* construct the algorithm
*/
VehicleRoutingAlgorithm vra = new VehicleRoutingAlgorithm(vrp, searchStrategyManager);
//do not forgett to add the stateManager listening to the algorithm-stages
vra.addListener(stateManager);
//remove empty vehicles after insertion has finished
vra.addListener(new RemoveEmptyVehicles(fleetManager));
/*
* Do not forget to add an initial solution by vra.addInitialSolution(solution);
* or
*/
vra.addInitialSolution(new InsertionInitialSolutionFactory(iStrategy, solutionCostCalculator).createSolution(vrp));
/*
* define the nIterations (by default nIteration=100)
*/
vra.setMaxIterations(1000);
/*
* optionally define a premature termination criterion (by default: not criterion is set)
*/
vra.setPrematureAlgorithmTermination(new IterationWithoutImprovementTermination(100));
return vra;
}
}
|
remove compile error
|
jsprit-examples/src/main/java/jsprit/examples/BuildAlgorithmFromScratchWithHardAndSoftConstraints.java
|
remove compile error
|
<ide><path>sprit-examples/src/main/java/jsprit/examples/BuildAlgorithmFromScratchWithHardAndSoftConstraints.java
<ide> */
<ide> SolutionCostCalculator solutionCostCalculator = new VariablePlusFixedSolutionCostCalculatorFactory(stateManager).createCalculator();
<ide>
<del> SearchStrategy firstStrategy = new SearchStrategy(new SelectBest(), new GreedyAcceptance(1), solutionCostCalculator);
<add> SearchStrategy firstStrategy = new SearchStrategy("random",new SelectBest(), new GreedyAcceptance(1), solutionCostCalculator);
<ide> firstStrategy.addModule(new RuinAndRecreateModule("randomRuinAndBestInsertion", iStrategy, randomRuin));
<ide>
<del> SearchStrategy secondStrategy = new SearchStrategy(new SelectBest(), new GreedyAcceptance(1), solutionCostCalculator);
<add> SearchStrategy secondStrategy = new SearchStrategy("radial",new SelectBest(), new GreedyAcceptance(1), solutionCostCalculator);
<ide> secondStrategy.addModule(new RuinAndRecreateModule("radialRuinAndBestInsertion", iStrategy, radialRuin));
<ide>
<ide> /*
|
|
Java
|
apache-2.0
|
89575e552d6f7a11786191f543a56aac557717cb
| 0 |
pmoerenhout/camel,cunningt/camel,tdiesler/camel,nikhilvibhav/camel,apache/camel,nikhilvibhav/camel,pax95/camel,adessaigne/camel,nikhilvibhav/camel,pmoerenhout/camel,apache/camel,pmoerenhout/camel,cunningt/camel,apache/camel,cunningt/camel,pmoerenhout/camel,apache/camel,tadayosi/camel,christophd/camel,tdiesler/camel,tadayosi/camel,tadayosi/camel,apache/camel,nikhilvibhav/camel,adessaigne/camel,pax95/camel,pax95/camel,tadayosi/camel,cunningt/camel,cunningt/camel,tadayosi/camel,pmoerenhout/camel,christophd/camel,pmoerenhout/camel,pax95/camel,christophd/camel,christophd/camel,christophd/camel,tdiesler/camel,christophd/camel,pax95/camel,tdiesler/camel,cunningt/camel,adessaigne/camel,pax95/camel,tadayosi/camel,tdiesler/camel,adessaigne/camel,adessaigne/camel,adessaigne/camel,tdiesler/camel,apache/camel
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.vertx.kafka;
import java.util.Map;
import io.vertx.core.buffer.Buffer;
import io.vertx.kafka.client.consumer.KafkaConsumer;
import io.vertx.kafka.client.consumer.KafkaConsumerRecord;
import org.apache.camel.Exchange;
import org.apache.camel.ExtendedExchange;
import org.apache.camel.Processor;
import org.apache.camel.Suspendable;
import org.apache.camel.component.vertx.kafka.configuration.VertxKafkaConfiguration;
import org.apache.camel.component.vertx.kafka.operations.VertxKafkaConsumerOperations;
import org.apache.camel.spi.Synchronization;
import org.apache.camel.support.DefaultConsumer;
import org.apache.camel.support.SynchronizationAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class VertxKafkaConsumer extends DefaultConsumer implements Suspendable {
private static final Logger LOG = LoggerFactory.getLogger(VertxKafkaConsumer.class);
private Synchronization onCompletion;
private KafkaConsumer<Object, Object> kafkaConsumer;
public VertxKafkaConsumer(final VertxKafkaEndpoint endpoint, final Processor processor) {
super(endpoint, processor);
}
@Override
protected void doInit() throws Exception {
super.doInit();
this.onCompletion = new ConsumerOnCompletion();
}
@Override
protected void doStart() throws Exception {
super.doStart();
String brokers = getEndpoint().getComponent().getVertxKafkaClientFactory().getBootstrapBrokers(getConfiguration());
if (brokers != null) {
LOG.debug("Creating KafkaConsumer connecting to BootstrapBrokers: {}", brokers);
}
// create the consumer client
kafkaConsumer = getEndpoint().getComponent().getVertxKafkaClientFactory()
.getVertxKafkaConsumer(getEndpoint().getVertx(), getConfiguration().createConsumerConfiguration());
// create the consumer operation
final VertxKafkaConsumerOperations consumerOperations
= new VertxKafkaConsumerOperations(kafkaConsumer, getConfiguration());
// process our records
consumerOperations.receiveEvents(this::onEventListener, this::onErrorListener);
}
@Override
protected void doStop() throws Exception {
if (kafkaConsumer != null) {
kafkaConsumer.close();
}
super.doStop();
}
@Override
protected void doSuspend() throws Exception {
if (kafkaConsumer != null) {
kafkaConsumer.pause();
}
}
@Override
protected void doResume() throws Exception {
if (kafkaConsumer != null) {
kafkaConsumer.resume();
}
}
public VertxKafkaConfiguration getConfiguration() {
return getEndpoint().getConfiguration();
}
@Override
public VertxKafkaEndpoint getEndpoint() {
return (VertxKafkaEndpoint) super.getEndpoint();
}
private void onEventListener(final KafkaConsumerRecord<Object, Object> record) {
final Exchange exchange = getEndpoint().createExchange(record);
final Map<String, Buffer> propagatedHeaders
= new VertxKafkaHeadersPropagation(getConfiguration().getHeaderFilterStrategy())
.getPropagatedHeaders(record.headers(), exchange.getIn());
// set propagated headers on exchange
propagatedHeaders.forEach((key, value) -> exchange.getIn().setHeader(key, value));
// add exchange callback
exchange.adapt(ExtendedExchange.class).addOnCompletion(onCompletion);
// send message to next processor in the route
getAsyncProcessor().process(exchange, doneSync -> LOG.trace("Processing exchange [{}] done.", exchange));
}
private void onErrorListener(final Throwable error) {
getExceptionHandler().handleException("Error from Kafka consumer.", error);
}
/**
* Strategy when processing the exchange failed.
*
* @param exchange the exchange
*/
protected void processRollback(Exchange exchange) {
final Exception cause = exchange.getException();
if (cause != null) {
getExceptionHandler().handleException("Error during processing exchange.", exchange, cause);
}
}
private class ConsumerOnCompletion extends SynchronizationAdapter {
@Override
public void onFailure(Exchange exchange) {
processRollback(exchange);
}
}
}
|
components/camel-vertx-kafka/camel-vertx-kafka-component/src/main/java/org/apache/camel/component/vertx/kafka/VertxKafkaConsumer.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.vertx.kafka;
import java.util.Map;
import io.vertx.core.buffer.Buffer;
import io.vertx.kafka.client.consumer.KafkaConsumer;
import io.vertx.kafka.client.consumer.KafkaConsumerRecord;
import org.apache.camel.Exchange;
import org.apache.camel.ExtendedExchange;
import org.apache.camel.Processor;
import org.apache.camel.Suspendable;
import org.apache.camel.component.vertx.kafka.configuration.VertxKafkaConfiguration;
import org.apache.camel.component.vertx.kafka.operations.VertxKafkaConsumerOperations;
import org.apache.camel.spi.Synchronization;
import org.apache.camel.support.DefaultConsumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class VertxKafkaConsumer extends DefaultConsumer implements Suspendable {
private static final Logger LOG = LoggerFactory.getLogger(VertxKafkaConsumer.class);
private KafkaConsumer<Object, Object> kafkaConsumer;
public VertxKafkaConsumer(final VertxKafkaEndpoint endpoint, final Processor processor) {
super(endpoint, processor);
}
@Override
protected void doStart() throws Exception {
super.doStart();
String brokers = getEndpoint().getComponent().getVertxKafkaClientFactory().getBootstrapBrokers(getConfiguration());
if (brokers != null) {
LOG.debug("Creating KafkaConsumer connecting to BootstrapBrokers: {}", brokers);
}
// create the consumer client
kafkaConsumer = getEndpoint().getComponent().getVertxKafkaClientFactory()
.getVertxKafkaConsumer(getEndpoint().getVertx(), getConfiguration().createConsumerConfiguration());
// create the consumer operation
final VertxKafkaConsumerOperations consumerOperations
= new VertxKafkaConsumerOperations(kafkaConsumer, getConfiguration());
// process our records
consumerOperations.receiveEvents(this::onEventListener, this::onErrorListener);
}
@Override
protected void doStop() throws Exception {
if (kafkaConsumer != null) {
kafkaConsumer.close();
}
super.doStop();
}
@Override
protected void doSuspend() throws Exception {
if (kafkaConsumer != null) {
kafkaConsumer.pause();
}
}
@Override
protected void doResume() throws Exception {
if (kafkaConsumer != null) {
kafkaConsumer.resume();
}
}
public VertxKafkaConfiguration getConfiguration() {
return getEndpoint().getConfiguration();
}
@Override
public VertxKafkaEndpoint getEndpoint() {
return (VertxKafkaEndpoint) super.getEndpoint();
}
private void onEventListener(final KafkaConsumerRecord<Object, Object> record) {
final Exchange exchange = getEndpoint().createExchange(record);
final Map<String, Buffer> propagatedHeaders
= new VertxKafkaHeadersPropagation(getConfiguration().getHeaderFilterStrategy())
.getPropagatedHeaders(record.headers(), exchange.getIn());
// set propagated headers on exchange
propagatedHeaders.forEach((key, value) -> exchange.getIn().setHeader(key, value));
// add exchange callback
exchange.adapt(ExtendedExchange.class).addOnCompletion(new Synchronization() {
@Override
public void onComplete(Exchange exchange) {
// at the moment we don't commit the offsets manually, we can add it in the future
}
@Override
public void onFailure(Exchange exchange) {
// we do nothing here
processRollback(exchange);
}
});
// send message to next processor in the route
getAsyncProcessor().process(exchange, doneSync -> LOG.trace("Processing exchange [{}] done.", exchange));
}
private void onErrorListener(final Throwable error) {
final Exchange exchange = getEndpoint().createExchange();
// set the thrown exception
exchange.setException(error);
// log exception if an exception occurred and was not handled
if (exchange.getException() != null) {
getExceptionHandler().handleException("Error processing exchange", exchange,
exchange.getException());
}
}
/**
* Strategy when processing the exchange failed.
*
* @param exchange the exchange
*/
private void processRollback(Exchange exchange) {
final Exception cause = exchange.getException();
if (cause != null) {
getExceptionHandler().handleException("Error during processing exchange.", exchange, cause);
}
}
}
|
CAMEL-16208: camel-vertx-kafka - Optimize a little bit
|
components/camel-vertx-kafka/camel-vertx-kafka-component/src/main/java/org/apache/camel/component/vertx/kafka/VertxKafkaConsumer.java
|
CAMEL-16208: camel-vertx-kafka - Optimize a little bit
|
<ide><path>omponents/camel-vertx-kafka/camel-vertx-kafka-component/src/main/java/org/apache/camel/component/vertx/kafka/VertxKafkaConsumer.java
<ide> import org.apache.camel.component.vertx.kafka.operations.VertxKafkaConsumerOperations;
<ide> import org.apache.camel.spi.Synchronization;
<ide> import org.apache.camel.support.DefaultConsumer;
<add>import org.apache.camel.support.SynchronizationAdapter;
<ide> import org.slf4j.Logger;
<ide> import org.slf4j.LoggerFactory;
<ide>
<ide>
<ide> private static final Logger LOG = LoggerFactory.getLogger(VertxKafkaConsumer.class);
<ide>
<add> private Synchronization onCompletion;
<ide> private KafkaConsumer<Object, Object> kafkaConsumer;
<ide>
<ide> public VertxKafkaConsumer(final VertxKafkaEndpoint endpoint, final Processor processor) {
<ide> super(endpoint, processor);
<add> }
<add>
<add> @Override
<add> protected void doInit() throws Exception {
<add> super.doInit();
<add> this.onCompletion = new ConsumerOnCompletion();
<ide> }
<ide>
<ide> @Override
<ide> propagatedHeaders.forEach((key, value) -> exchange.getIn().setHeader(key, value));
<ide>
<ide> // add exchange callback
<del> exchange.adapt(ExtendedExchange.class).addOnCompletion(new Synchronization() {
<del> @Override
<del> public void onComplete(Exchange exchange) {
<del> // at the moment we don't commit the offsets manually, we can add it in the future
<del> }
<del>
<del> @Override
<del> public void onFailure(Exchange exchange) {
<del> // we do nothing here
<del> processRollback(exchange);
<del> }
<del> });
<add> exchange.adapt(ExtendedExchange.class).addOnCompletion(onCompletion);
<ide> // send message to next processor in the route
<ide> getAsyncProcessor().process(exchange, doneSync -> LOG.trace("Processing exchange [{}] done.", exchange));
<ide> }
<ide>
<ide> private void onErrorListener(final Throwable error) {
<del> final Exchange exchange = getEndpoint().createExchange();
<del>
<del> // set the thrown exception
<del> exchange.setException(error);
<del>
<del> // log exception if an exception occurred and was not handled
<del> if (exchange.getException() != null) {
<del> getExceptionHandler().handleException("Error processing exchange", exchange,
<del> exchange.getException());
<del> }
<add> getExceptionHandler().handleException("Error from Kafka consumer.", error);
<ide> }
<ide>
<ide> /**
<ide> *
<ide> * @param exchange the exchange
<ide> */
<del> private void processRollback(Exchange exchange) {
<add> protected void processRollback(Exchange exchange) {
<ide> final Exception cause = exchange.getException();
<ide> if (cause != null) {
<ide> getExceptionHandler().handleException("Error during processing exchange.", exchange, cause);
<ide> }
<ide> }
<add>
<add> private class ConsumerOnCompletion extends SynchronizationAdapter {
<add>
<add> @Override
<add> public void onFailure(Exchange exchange) {
<add> processRollback(exchange);
<add> }
<add> }
<ide> }
|
|
JavaScript
|
lgpl-2.1
|
56c0d22895be1eaa2d63f695b5c95c33c22a27db
| 0 |
tikiorg/tiki,changi67/tiki,oregional/tiki,oregional/tiki,tikiorg/tiki,tikiorg/tiki,changi67/tiki,oregional/tiki,changi67/tiki,changi67/tiki,oregional/tiki,tikiorg/tiki,changi67/tiki
|
// $Id$
// JavaScript glue for jQuery in Tiki
//
// Tiki 6 - $ is now initialised in jquery.js
// but let's keep $jq available too for legacy custom code
var $jq = $,
$window = $(window),
$document = $(document);
// Escape a string for use as a jQuery selector value, for example an id or a class
function escapeJquery(str) {
return str.replace(/([\!"#\$%&'\(\)\*\+,\.\/:;\?@\[\\\]\^`\{\|\}\~=>])/g, "\\$1");
}
// Check / Uncheck all Checkboxes - overriden from tiki-js.js
function switchCheckboxes (tform, elements_name, state) {
// checkboxes need to have the same name elements_name
// e.g. <input type="checkbox" name="my_ename[]">, will arrive as Array in php.
$(tform).contents().find('input[name="' + escapeJquery(elements_name) + '"]:visible').attr('checked', state).change();
}
// override existing show/hide routines here
// add id's of any elements that don't like being animated here
var jqNoAnimElements = ['help_sections', 'ajaxLoading'];
function show(foo, f, section) {
if ($.inArray(foo, jqNoAnimElements) > -1 || typeof jqueryTiki === 'undefined') { // exceptions that don't animate reliably
$("#" + foo).show();
} else if ($("#" + foo).hasClass("tabcontent")) { // different anim prefs for tabs
showJQ("#" + foo, jqueryTiki.effect_tabs, jqueryTiki.effect_tabs_speed, jqueryTiki.effect_tabs_direction);
} else {
if ($.browser.webkit && !jqueryTiki.effect && $("#role_main #" + foo).length) { // safari/chrome does strange things with default amination in central column
showJQ("#" + foo, "slide", jqueryTiki.effect_speed, jqueryTiki.effect_direction);
} else {
showJQ("#" + foo, jqueryTiki.effect, jqueryTiki.effect_speed, jqueryTiki.effect_direction);
}
}
if (f) {setCookie(foo, "o", section);}
}
function hide(foo, f, section) {
if ($.inArray(foo, jqNoAnimElements) > -1 || typeof jqueryTiki === 'undefined') { // exceptions
$("#" + foo).hide();
} else if ($("#" + foo).hasClass("tabcontent")) {
hideJQ("#" + foo, jqueryTiki.effect_tabs, jqueryTiki.effect_tabs_speed, jqueryTiki.effect_tabs_direction);
} else {
hideJQ("#" + foo, jqueryTiki.effect, jqueryTiki.effect_speed, jqueryTiki.effect_direction);
}
if (f) {
// var wasnot = getCookie(foo, section, 'x') == 'x';
setCookie(foo, "c", section);
// if (wasnot) {
// history.go(0); // used to reload the page with all menu items closed - broken since 3.x
// }
}
}
// flip function... unfortunately didn't use show/hide (ay?)
function flip(foo, style) {
if (style && style !== 'block' || foo === 'help_sections' || foo === 'fgalexplorer' || typeof jqueryTiki === 'undefined') { // TODO find a better way?
$("#" + foo).toggle(); // inlines don't animate reliably (yet) (also help)
if ($("#" + foo).css('display') === 'none') {
setSessionVar('show_' + escape(foo), 'n');
} else {
setSessionVar('show_' + escape(foo), 'y');
}
} else {
if ($("#" + foo).css("display") === "none") {
setSessionVar('show_' + escape(foo), 'y');
show(foo);
}
else {
setSessionVar('show_' + escape(foo), 'n');
hide(foo);
}
}
}
// handle JQ effects
function showJQ(selector, effect, speed, dir) {
if (effect === 'none') {
$(selector).show();
} else if (effect === '' || effect === 'normal') {
$(selector).show(400); // jquery 1.4 no longer seems to understand 'nnormal' as a speed
} else if (effect == 'slide') {
// With jquery 1.4.2 (and less) and IE7, the function slidedown is buggy
// See: http://dev.jquery.com/ticket/3120
if ($.browser.msie && parseInt($.browser.version, 10) == 7) {
$(selector).show(speed);
} else {
$(selector).slideDown(speed);
}
} else if (effect === 'fade') {
$(selector).fadeIn(speed);
} else if (effect.match(/(.*)_ui$/).length > 1) {
$(selector).show(effect.match(/(.*)_ui$/)[1], {direction: dir}, speed);
} else {
$(selector).show();
}
}
function hideJQ(selector, effect, speed, dir) {
if (effect === 'none') {
$(selector).hide();
} else if (effect === '' || effect === 'normal') {
$(selector).hide(400); // jquery 1.4 no longer seems to understand 'nnormal' as a speed
} else if (effect === 'slide') {
$(selector).slideUp(speed);
} else if (effect === 'fade') {
$(selector).fadeOut(speed);
} else if (effect.match(/(.*)_ui$/).length > 1) {
$(selector).hide(effect.match(/(.*)_ui$/)[1], {direction: dir}, speed);
} else {
$(selector).hide();
}
}
// ajax loading indicator
function ajaxLoadingShow(destName) {
var $dest, $loading, pos, x, y, w, h;
if (typeof destName === 'string') {
$dest = $('#' + destName);
} else {
$dest = $(destName);
}
if ($dest.length === 0 || $dest.parents(":hidden").length > 0) {
return;
}
$loading = $('#ajaxLoading');
// find area of destination element
pos = $dest.offset();
// clip to page
if (pos.left + $dest.width() > $window.width()) {
w = $window.width() - pos.left;
} else {
w = $dest.width();
}
if (pos.top + $dest.height() > $window.height()) {
h = $window.height() - pos.top;
} else {
h = $dest.height();
}
x = pos.left + (w / 2) - ($loading.width() / 2);
y = pos.top + (h / 2) - ($loading.height() / 2);
// position loading div
$loading.css('left', x).css('top', y);
// now BG
x = pos.left + ccsValueToInteger($dest.css("margin-left"));
y = pos.top + ccsValueToInteger($dest.css("margin-top"));
w = ccsValueToInteger($dest.css("padding-left")) + $dest.width() + ccsValueToInteger($dest.css("padding-right"));
h = ccsValueToInteger($dest.css("padding-top")) + $dest.height() + ccsValueToInteger($dest.css("padding-bottom"));
$('#ajaxLoadingBG').css('left', pos.left).css('top', pos.top).width(w).height(h).fadeIn("fast");
show('ajaxLoading');
}
function ajaxLoadingHide() {
hide('ajaxLoading');
$('#ajaxLoadingBG').fadeOut("fast");
}
function checkDuplicateRows( button, columnSelector, rowSelector ) {
if (typeof columnSelector === 'undefined') {
columnSelector = "td";
}
if (typeof rowSelector === 'undefined') {
rowSelector = "table:first tr:not(:first)";
}
var $rows = $(button).parents(rowSelector);
$rows.each(function( ix, el ){
if ($("input:checked", el).length === 0) {
var $el = $(el);
var line = $el.find(columnSelector).text();
$rows.each(function( ix, el ){
if ($el[0] !== el && $("input:checked", el).length === 0) {
if (line === $(el).find(columnSelector).text()) {
$(":checkbox:first", el).attr("checked", true);
}
}
});
}
});
}
function setUpClueTips() {
var ctOptions = {splitTitle: '|', cluezIndex: 2000, width: -1, fx: {open: 'fadeIn', openSpeed: 'fast'},
clickThrough: true, hoverIntent: {sensitivity: 3, interval: 100, timeout: 0}};
$.cluetip.setup = {insertionType: 'insertBefore', insertionElement: '#fixedwidth'};
$('.tips[title!=""]').cluetip($.extend(ctOptions, {}));
$('.titletips[title!=""]').cluetip($.extend(ctOptions, {}));
$('.tikihelp[title!=""]').cluetip($.extend(ctOptions, {splitTitle: ':'})); // , width: '150px'
$('[data-cluetip-options]').each(function () {
$(this).cluetip(function () {
return $(this).data("cluetip-body");
}, $.extend($(this).data("cluetip-options"), ctOptions));
});
// unused?
$('.stickytips').cluetip($.extend(ctOptions, {showTitle: false, sticky: false, local: true, hideLocal: true, activation: 'click', cluetipClass: 'fullhtml'}));
// repeats for "tiki" buttons as you cannot set the class and title on the same element with that function (it seems?)
//$('span.button.tips a').cluetip({splitTitle: '|', showTitle: false, width: '150px', cluezIndex: 400, fx: {open: 'fadeIn', openSpeed: 'fast'}, clickThrough: true});
//$('span.button.titletips a').cluetip({splitTitle: '|', cluezIndex: 400, fx: {open: 'fadeIn', openSpeed: 'fast'}, clickThrough: true});
// TODO after 5.0 - these need changes in the {button} Smarty fn
}
$(function() { // JQuery's DOM is ready event - before onload
if (!window.jqueryTiki) window.jqueryTiki = {};
// tooltip functions and setup
if (jqueryTiki.tooltips) { // apply "cluetips" to all .tips class anchors
setUpClueTips();
} // end cluetip setup
// Reflections
if (jqueryTiki.replection) {
$("img.reflect").reflect({});
}
// superfish setup (CSS menu effects)
if (jqueryTiki.superfish) {
$('ul.cssmenu_horiz').supersubs({
minWidth: 11, // minimum width of sub-menus in em units
maxWidth: 20, // maximum width of sub-menus in em units
extraWidth: 1 // extra width can ensure lines don't sometimes turn over
// due to slight rounding differences and font-family
});
$('ul.cssmenu_vert').supersubs({
minWidth: 11, // minimum width of sub-menus in em units
maxWidth: 20, // maximum width of sub-menus in em units
extraWidth: 1 // extra width can ensure lines don't sometimes turn over
// due to slight rounding differences and font-family
});
$('ul.cssmenu_horiz').superfish({
animation: {opacity:'show', height:'show'}, // fade-in and slide-down animation
speed: 'fast', // faster animation speed
onShow: function(){
$(this).moveToWithinWindow();
}
});
$('ul.cssmenu_vert').superfish({
animation: {opacity:'show', height:'show'}, // fade-in and slide-down animation
speed: 'fast', // faster animation speed
onShow: function(){
$(this).moveToWithinWindow();
}
});
}
// tablesorter setup (sortable tables?)
if (jqueryTiki.tablesorter) {
$('.sortable').tablesorter({
widthFixed: true // ??
// widgets: ['zebra'], // stripes (coming soon)
});
}
// ColorBox setup (Shadowbox, actually "<any>box" replacement)
if (jqueryTiki.colorbox) {
$().bind('cbox_complete', function(){
$("#cboxTitle").wrapInner("<div></div>");
});
// Tiki defaults for ColorBox
// for every link containing 'shadowbox' or 'colorbox' in rel attribute
$("a[rel*='box']").colorbox({
transition: "elastic",
maxHeight:"95%",
maxWidth:"95%",
overlayClose: true,
title: true,
current: jqueryTiki.cboxCurrent
});
// now, first let suppose that we want to display images in ColorBox by default:
// this matches rel containg type=img or no type= specified
$("a[rel*='box'][rel*='type=img'], a[rel*='box'][rel!='type=']").colorbox({
photo: true
});
// rel containg slideshow (this one must be without #col1)
$("a[rel*='box'][rel*='slideshow']").colorbox({
photo: true,
slideshow: true,
slideshowSpeed: 3500,
preloading: false,
width: "100%",
height: "100%"
});
// this are the defaults matching all *box links which are not obviously links to images...
// (if we need to support more, add here... otherwise it is possible to override with type=iframe in rel attribute of a link)
// (from here one to speed it up, matches any link in #col1 only - the main content column)
$("#col1 a[rel*='box']:not([rel*='type=img']):not([href*='display']):not([href*='preview']):not([href*='thumb']):not([rel*='slideshow']):not([href*='image']):not([href$='\.jpg']):not([href$='\.jpeg']):not([href$='\.png']):not([href$='\.gif'])").colorbox({
iframe: true,
width: "95%",
height: "95%"
});
// hrefs starting with ftp(s)
$("#col1 a[rel*='box'][href^='ftp://'], #col1 a[rel*='box'][href^='ftps://']").colorbox({
iframe: true,
width: "95%",
height: "95%"
});
// rel containg type=flash
$("#col1 a[rel*='box'][rel*='type=flash']").colorbox({
inline: true,
width: "60%",
height: "60%",
href: function () {
var $el = $("#cb_swf_player");
if ($el.length === 0) {
$el = $("<div id='cb_swf_player' />");
$(document.body).append($("<div />").hide().append($el));
}
//$(this).media.swf(el, { width: 400, height: 300, autoplay: true, src: $(this).attr("href") });
swfobject.embedSWF($(this).attr("href"), "cb_swf_player", "100%", "90%", "9.0.0", "lib/swfobject/expressInstall.swf");
return $("#cb_swf_player");
}
});
// rel with type=iframe (if someone needs to override anything above)
$("#col1 a[rel*='box'][rel*='type=iframe']").colorbox({
iframe: true
});
// inline content: hrefs starting with #
$("#col1 a[rel*='box'][href^='#']").colorbox({
inline: true,
width: "50%",
height: "50%",
href: function(){
return $(this).attr('href');
}
});
// titles (for captions):
// by default get title from the title attribute of the link (in all columns)
$("a[rel*='box'][title]").colorbox({
title: function(){
return $(this).attr('title');
}
});
// but prefer the title from title attribute of a wrapped image if any (in all columns)
$("a[rel*='box'] img[title]").colorbox({
title: function(){
return $(this).attr('title');
},
photo: true, // and if you take title from the image you need photo
href: function(){ // and href as well (for colobox 1.3.6 tiki 5.0)
return $(this).parent().attr("href");
}
});
/* Shadowbox params compatibility extracted using regexp functions */
var re, ret;
// rel containg title param overrides title attribute of the link (shadowbox compatible)
$("#col1 a[rel*='box'][rel*='title=']").colorbox({
title: function () {
re = /(title=([^;\"]+))/i;
ret = $(this).attr("rel").match(re);
return ret[2];
}
});
// rel containg height param (shadowbox compatible)
$("#col1 a[rel*='box'][rel*='height=']").colorbox({
height: function () {
re = /(height=([^;\"]+))/i;
ret = $(this).attr("rel").match(re);
return ret[2];
}
});
// rel containg width param (shadowbox compatible)
$("#col1 a[rel*='box'][rel*='width=']").colorbox({
width: function () {
re = /(width=([^;\"]+))/i;
ret = $(this).attr("rel").match(re);
return ret[2];
}
});
// links generated by the {COLORBOX} plugin
if (jqueryTiki.colorbox) {
$("a[rel^='shadowbox[colorbox']").each(function () {$(this).attr('savedTitle', $(this).attr('title'));});
if (jqueryTiki.tooltips) {
$("a[rel^='shadowbox[colorbox']").cluetip({
splitTitle: '<br />',
cluezIndex: 400,
width: 'auto',
fx: {open: 'fadeIn', openSpeed: 'fast'},
clickThrough: true
});
}
$("a[rel^='shadowbox[colorbox']").colorbox({
title: function() {
return $(this).attr('savedTitle'); // this fix not required is colorbox was disabled
}
});
}
} // end if (jqueryTiki.colorbox)
$.applySelectMenus = function() {
return $('body').applySelectMenus();
};
$.fn.applySelectMenus = function () {
if (jqueryTiki.selectmenu) {
var $smenus, hidden = [];
if (jqueryTiki.selectmenuAll) {
// make all selects into ui selectmenus depending on $prefs['jquery_ui_selectmenu_all']
$smenus = $("select:not([multiple])");
} else {
// or just selectmenu class
$smenus = $("select.selectmenu:not([multiple])");
}
if ($smenus.length) {
$smenus.each(function () {
$.merge(hidden, $(this).parents(":hidden:last"));
});
hidden = $.unique($(hidden));
hidden.show();
$smenus.tiki("selectmenu");
hidden.hide();
}
}
};
if (jqueryTiki.selectmenu) {
$.applySelectMenus();
}
$( function() {
$("#keepOpenCbx").click(function() {
if (this.checked) {
setCookie("fgalKeepOpen", "1");
} else {
setCookie("fgalKeepOpen", "");
}
});
var keepopen = getCookie("fgalKeepOpen");
if (keepopen) {
$("#keepOpenCbx").attr("checked", "checked");
} else {
$("#keepOpenCbx").removeAttr("checked");
}
});
// end fgal fns
$.paginationHelper();
}); // end $document.ready
//For ajax/custom search
$document.bind('pageSearchReady', function() {
$.paginationHelper();
});
// moved from tiki-list_file_gallery.tpl in tiki 6
function checkClose() {
if (!$("#keepOpenCbx").attr("checked")) {
window.close();
} else {
window.blur();
if (window.opener) {
window.opener.focus();
}
}
}
/* Autocomplete assistants */
function parseAutoJSON(data) {
var parsed = [];
return $.map(data, function(row) {
return {
data: row,
value: row,
result: row
};
});
}
/// jquery ui dialog replacements for popup form code
/// need to keep the old non-jq version in tiki-js.js as jq-ui is optional (Tiki 4.0)
/// TODO refactor for 4.n
/* wikiplugin editor */
function popupPluginForm(area_id, type, index, pageName, pluginArgs, bodyContent, edit_icon, selectedMod){
if (!$.ui) {
alert("dev notice: no jq.ui here?");
return popup_plugin_form(area_id, type, index, pageName, pluginArgs, bodyContent, edit_icon); // ??
}
if ($("#" + area_id).length && $("#" + area_id)[0].createTextRange) { // save selection for IE
storeTASelection(area_id);
}
var container = $('<div class="plugin"></div>');
if (!index) {
index = 0;
}
if (!pageName) {
pageName = '';
}
var textarea = $('#' + area_id)[0];
var replaceText = false;
if (!pluginArgs && !bodyContent) {
pluginArgs = {};
bodyContent = "";
dialogSelectElement( area_id, '{' + type.toUpperCase(), '{' + type.toUpperCase() + '}' ) ;
var sel = getTASelection( textarea );
if (sel && sel.length > 0) {
sel = sel.replace(/^\s\s*/, "").replace(/\s\s*$/g, ""); // trim
//alert(sel.length);
if (sel.length > 0 && sel.substring(0, 1) === '{') { // whole plugin selected
var l = type.length;
if (sel.substring(1, l + 1).toUpperCase() === type.toUpperCase()) { // same plugin
var rx = new RegExp("{" + type + "[\\(]?([\\s\\S^\\)]*?)[\\)]?}([\\s\\S]*){" + type + "}", "mi"); // using \s\S matches all chars including lineends
var m = sel.match(rx);
if (!m) {
rx = new RegExp("{" + type + "[\\(]?([\\s\\S^\\)]*?)[\\)]?}([\\s\\S]*)", "mi"); // no closing tag
m = sel.match(rx);
}
if (m) {
var paramStr = m[1];
bodyContent = m[2];
var pm = paramStr.match(/([^=]*)=\"([^\"]*)\"\s?/gi);
if (pm) {
for (var i = 0; i < pm.length; i++) {
var ar = pm[i].split("=");
if (ar.length) { // add cleaned vals to params object
pluginArgs[ar[0].replace(/^[,\s\"\(\)]*/g, "")] = ar[1].replace(/^[,\s\"\(\)]*/g, "").replace(/[,\s\"\(\)]*$/g, "");
}
}
}
}
replaceText = sel;
} else {
if (!confirm("You appear to have selected text for a different plugin, do you wish to continue?")) {
return false;
}
bodyContent = sel;
replaceText = true;
}
} else { // not (this) plugin
if (type == 'mouseover') { // For MOUSEOVER, we want the selected text as label instead of body
bodyContent = '';
pluginArgs = {};
pluginArgs['label'] = sel;
} else {
bodyContent = sel;
}
replaceText = true;
}
} else { // no selection
replaceText = false;
}
}
var form = build_plugin_form(type, index, pageName, pluginArgs, bodyContent, selectedMod);
//with PluginModule, if the user selects another module while the edit form is open
//replace the form with a new one with fields to match the parameters for the module selected
$(form).find('tr select[name="params[module]"]').change(function() {
var npluginArgs = $.parseJSON($(form).find('input[name="args"][type="hidden"]').val());
//this is the newly selected module
var selectedMod = $(form).find('tr select[name="params[module]"]').val();
$('div.plugin input[name="type"][value="' + type + '"]').parent().parent().remove();
popupPluginForm(area_id, type, index, pageName, npluginArgs, bodyContent, edit_icon, selectedMod);
});
var $form = $(form).find('tr input[type=submit]').remove();
container.append(form);
document.body.appendChild(container[0]);
handlePluginFieldsHierarchy(type);
var pfc = container.find('table tr').length; // number of rows (plugin form contents)
var t = container.find('textarea:visible').length;
if (t) {pfc += t * 3;}
if (pfc > 9) {pfc = 9;}
if (pfc < 2) {pfc = 2;}
pfc = pfc / 10; // factor to scale dialog height
var btns = {};
var closeText = tr("Close");
btns[closeText] = function() {
$(this).dialog("close");
};
btns[replaceText ? tr("Replace") : edit_icon ? tr("Submit") : tr("Insert")] = function() {
var meta = tiki_plugins[type];
var params = [];
var edit = edit_icon;
// whether empty required params exist or not
var emptyRequiredParam = false;
for (var i = 0; i < form.elements.length; i++) {
var element = form.elements[i].name;
var matches = element.match(/params\[(.*)\]/);
if (matches === null) {
// it's not a parameter, skip
continue;
}
var param = matches[1];
var val = form.elements[i].value;
// check if fields that are required and visible are not empty
if (meta.params[param]) {
if (meta.params[param].required) {
if (val === '' && $(form.elements[i]).is(':visible')) {
$(form.elements[i]).css('border-color', 'red');
if ($(form.elements[i]).next('.required_param').length === 0) {
$(form.elements[i]).after('<div class="required_param" style="font-size: x-small; color: red;">(required)</div>');
}
emptyRequiredParam = true;
}
else {
// remove required feedback if present
$(form.elements[i]).css('border-color', '');
$(form.elements[i]).next('.required_param').remove();
}
}
}
if (val !== '') {
params.push(param + '="' + val + '"');
}
}
if (emptyRequiredParam) {
return false;
}
var blob, pluginContentTextarea = $("[name=content]", form), pluginContentTextareaEditor = syntaxHighlighter.get(pluginContentTextarea);
var cont = (pluginContentTextareaEditor ? pluginContentTextareaEditor.getValue() : pluginContentTextarea.val());
if (cont.length > 0) {
blob = '{' + type.toUpperCase() + '(' + params.join(' ') + ')}' + cont + '{' + type.toUpperCase() + '}';
} else {
blob = '{' + type.toLowerCase() + ' ' + params.join(' ') + '}';
}
if (edit) {
container.children('form').submit();
} else {
insertAt(area_id, blob, false, false, replaceText);
}
$(this).dialog("close");
$('div.plugin input[name="type"][value="' + type + '"]').parent().parent().remove();
return false;
};
var heading = container.find('h3').hide();
try {
if (container.dialog) {
container.dialog('destroy');
}
} catch( e ) {
// IE throws errors destroying a non-existant dialog
}
container.dialog({
width: $window.width() * 0.6,
height: $window.height() * pfc,
zIndex: 10000,
title: heading.text(),
autoOpen: false,
close: function() {
$('div.plugin input[name="type"][value="' + type + '"]').parent().parent().remove();
var ta = $('#' + area_id);
if (ta) {ta.focus();}
}
}).dialog('option', 'buttons', btns).dialog("open");
//This allows users to create plugin snippets for any plugin using the jQuery event 'plugin_#type#_ready' for document
$document
.trigger({
type: 'plugin_' + type + '_ready',
container: container,
arguments: arguments,
btns: btns
})
.trigger({
type: 'plugin_ready',
container: container,
arguments: arguments,
btns: btns,
type: type
});
}
/*
* Hides all children fields in a wiki-plugin form and
* add javascript events to display them when the appropriate
* values are selected in the parent fields.
*/
function handlePluginFieldsHierarchy(type) {
var pluginParams = tiki_plugins[type]['params'];
var parents = {};
$.each(pluginParams, function(paramName, paramValues) {
if (paramValues.parent) {
var $parent = $('[name$="params[' + paramValues.parent.name + ']"]', '.wikiplugin_edit');
var $row = $('.wikiplugin_edit').find('#param_' + paramName);
$row.addClass('parent_' + paramValues.parent.name + '_' + paramValues.parent.value);
if ($parent.val() != paramValues.parent.value) {
if (!$parent.val() && $("input, select", $row).val()) {
$parent.val(paramValues.parent.value);
} else {
$row.hide();
}
}
if (!parents[paramValues.parent.name]) {
parents[paramValues.parent.name] = {};
parents[paramValues.parent.name]['children'] = [];
parents[paramValues.parent.name]['parentElement'] = $parent;
}
parents[paramValues.parent.name]['children'].push(paramName);
}
});
$.each(parents, function(parentName, parent) {
parent.parentElement.change(function() {
$.each(parent.children, function() {
$('.wikiplugin_edit #param_' + this).hide();
});
$('.wikiplugin_edit .parent_' + parentName + '_' + this.value).show();
});
});
}
/*
* JS only textarea fullscreen function (for Tiki 5+)
*/
$(function() { // if in translation-diff-mode go fullscreen automatically
if ($("#diff_outer").length && !$.trim($(".wikipreview .wikitext").html()).length) { // but not if previewing (TODO better)
toggleFullScreen("editwiki");
}
});
function sideBySideDiff() {
if ($('.side-by-side-fullscreen').size()) {
$('.side-by-side-fullscreen').remove();
return;
}
var $diff = $('#diff_outer').clone(true, true), $zone = $('.edit-zone');
$('body').append($diff.addClass('side-by-side-fullscreen'));
$diff.find('#diff_history').height('');
if ($diff.size()) {
$diff.css({
position: 'fixed',
top: $zone.css('top'),
bottom: $zone.css('bottom'),
right: 0,
overflow: 'auto',
backgroundColor: 'white',
zIndex: 500000,
opacity: 1
});
$diff.height($zone.height());
$diff.width($(window).width() / 2);
$zone.width($(window).width() / 2);
}
}
function toggleFullScreen(area_id) {
if ($("input[name=wysiwyg]").val() === "y") { // quick fix to disable side-by-side translation for wysiwyg
$("#diff_versions").height(200).css("overflow", "auto");
return;
}
var textarea = $("#" + area_id);
//codemirror interation and preservation
var textareaEditor = syntaxHighlighter.get(textarea);
if (textareaEditor) {
syntaxHighlighter.fullscreen(textarea);
sideBySideDiff();
return;
}
$('.TextArea-fullscreen').add(textarea).css('height', '');
//removes wiki command buttons (save, cancel, preview) from fullscreen view
$('.TextArea-fullscreen .actions').remove();
var textareaParent = textarea.parent().parent().toggleClass('TextArea-fullscreen');
$('body').toggleClass('noScroll');
$('.tabs,.rbox-title').toggle();
if (textareaParent.hasClass('TextArea-fullscreen')) {
var win = $window
.data('cm-resize', true),
screen = $('.TextArea-fullscreen'),
toolbar = $('#editwiki_toolbar');
win.resize(function() {
if (win.data('cm-resize') && screen) {
screen.css('height', win.height() + 'px');
textarea
.css('height', ((win.height() - toolbar.height()) - 30) + 'px');
}
})
.resize();
//adds wiki command buttons (save, cancel, preview) to fullscreen view
$('#role_main .actions').clone().appendTo('.TextArea-fullscreen');
} else {
$window.removeData('cm-resize');
}
sideBySideDiff();
}
/* Simple tiki plugin for jQuery
* Helpers for autocomplete and sheet
*/
var xhrCache = {}, lastXhr; // for jq-ui autocomplete
$.fn.tiki = function(func, type, options) {
var opts = {}, opt;
switch (func) {
case "autocomplete":
if (jqueryTiki.autocomplete) {
if (typeof type === 'undefined') { // func and type given
// setup error - alert here?
return null;
}
options = options || {};
var requestData = {};
var url = "";
switch (type) {
case "pagename":
url = "tiki-listpages.php?listonly";
break;
case "groupname":
url = "tiki-ajax_services.php?listonly=groups";
break;
case "username":
url = "tiki-ajax_services.php?listonly=users";
break;
case "usersandcontacts":
url = "tiki-ajax_services.php?listonly=usersandcontacts";
break;
case "userrealname":
url = "tiki-ajax_services.php?listonly=userrealnames";
break;
case "tag":
url = "tiki-ajax_services.php?listonly=tags&separator=+";
break;
case "icon":
url = "tiki-ajax_services.php?listonly=icons&max=" + (opts.max ? opts.max: 10);
opts.formatItem = function(data, i, n, value) {
var ps = value.lastIndexOf("/");
var pd = value.lastIndexOf(".");
return "<img src='" + value + "' /> " + value.substring(ps + 1, pd).replace(/_/m, " ");
};
opts.formatResult = function(data, value) {
return value;
};
break;
case 'trackername':
url = "tiki-ajax_services.php?listonly=trackername";
break;
case 'trackervalue':
if (typeof options.fieldId === "undefined") {
// error
return null;
}
$.extend( requestData, options );
options = {};
url = "list-tracker_field_values_ajax.php";
break;
}
$.extend( opts, { // default options for autocompletes in tiki
minLength: 2,
source: function( request, response ) {
if (options.tiki_replace_term) {
request.term = options.tiki_replace_term.apply(null, [request.term]);
}
var cacheKey = "ac." + type + "." + request.term;
if ( cacheKey in xhrCache ) {
response( xhrCache[ cacheKey ] );
return;
}
request.q = request.term;
$.extend( request, requestData );
lastXhr = $.getJSON( url, request, function( data, status, xhr ) {
xhrCache[ cacheKey ] = data;
if ( xhr === lastXhr ) {
response( data );
}
});
}
});
$.extend(opts, options);
return this.each(function() {
$(this).autocomplete(opts).blur( function() {$(this).removeClass( "ui-autocomplete-loading" );});
// .click( function () {
// $(".ac_results").hide(); // hide the drop down if input clicked on again
// });
});
}
break;
case "carousel":
if (jqueryTiki.carousel) {
opts = {
imagePath: "lib/jquery/infinitecarousel/images/",
autoPilot: true
};
$.extend(opts, options);
return this.each(function() {
$(this).infiniteCarousel(opts);
});
}
break;
case "datepicker":
case "datetimepicker":
if (jqueryTiki.ui) {
switch (type) {
case "jscalendar": // replacements for jscalendar
// timestamp result goes in the options.altField
if (typeof options.altField === "undefined") {
alert("jQuery.ui datepicker jscalendar replacement setup error: options.altField not set for " + $(this).attr("id"));
debugger;
}
opts = {
showOn: "both",
buttonImage: "img/icons/calendar.png",
buttonImageOnly: true,
dateFormat: "yy-mm-dd",
showButtonPanel: true,
altFormat: "@",
onClose: function(dateText, inst) {
$.datepicker._updateAlternate(inst); // make sure the hidden field is up to date
var timestamp = parseInt($(inst.settings.altField).val() / 1000, 10);
if (!timestamp) {
$.datepicker._setDateFromField(inst); // seems to need reminding when starting empty
$.datepicker._updateAlternate(inst);
timestamp = parseInt($(inst.settings.altField).val() / 1000, 10);
}
if (timestamp && inst.settings && inst.settings.timepicker) { // if it's a datetimepicker add on the time
var time = inst.settings.timepicker.hour * 3600 +
inst.settings.timepicker.minute * 60 +
inst.settings.timepicker.second;
timestamp += time;
}
$(inst.settings.altField).val(timestamp ? timestamp : "");
}
};
break;
default:
opts = {
showOn: "both",
buttonImage: "img/icons/calendar.png",
buttonImageOnly: true,
dateFormat: "yy-mm-dd",
showButtonPanel: true,
firstDay: jqueryTiki.firstDayofWeek
};
break;
}
$.extend(opts, options);
if (func === "datetimepicker") {
return this.each(function() {
$(this).datetimepicker(opts);
});
} else {
return this.each(function() {
$(this).datepicker(opts);
});
}
}
break;
case "accordion":
if (jqueryTiki.ui) {
opts = {
autoHeight: false,
collapsible: true,
navigation: true
// change: function(event, ui) {
// // sadly accordion active property is broken in 1.7, but fix is coming in 1.8 so TODO
// setCookie(ui, ui.options.active, "accordion");
// }
};
$.extend(opts, options);
return this.each(function() {
$(this).accordion(opts);
});
}
break;
case "selectmenu":
if (jqueryTiki.selectmenu) {
opts = {
style: 'dropdown',
wrapperElement: "<span />"
};
$.extend(opts, options);
return this.each(function() {
$(this).selectmenu(opts);
});
}
break;
} // end switch(func)
};
/******************************
* Functions for dialog tools *
******************************/
// shared
window.dialogData = [];
var dialogDiv;
function displayDialog( ignored, list, area_id ) {
var i, item, el, obj, tit = "";
var $is_cked = $('#cke_contents_' + area_id).length !== 0;
if (!dialogDiv) {
dialogDiv = document.createElement('div');
document.body.appendChild( dialogDiv );
}
$(dialogDiv).empty();
for( i = 0; i < window.dialogData[list].length; i++ ) {
item = window.dialogData[list][i];
if (item.indexOf("<") === 0) { // form element
el = $(item);
$(dialogDiv).append( el );
} else if (item.indexOf("{") === 0) {
try {
//obj = JSON.parse(item); // safer, but need json2.js lib
obj = eval("("+item+")");
} catch (e) {
alert(e.name + ' - ' + e.message);
}
} else if (item.length > 0) {
tit = item;
}
}
// Selection will be unavailable after context menu shows up - in IE, lock it now.
if ( typeof CKEDITOR !== "undefined" && CKEDITOR.env.ie ) {
var editor = CKEDITOR.instances[area_id];
var selection = editor.getSelection();
if (selection) {selection.lock();}
} else if ($("#" + area_id)[0].createTextRange) { // save selection for IE
storeTASelection(area_id);
}
if (!obj) { obj = {}; }
if (!obj.width) {obj.width = 210;}
obj.bgiframe = true;
obj.autoOpen = false;
obj.zIndex = 10000;
try {
if ($(dialogDiv).dialog) {
$(dialogDiv).dialog('destroy');
}
} catch( e ) {
// IE throws errors destroying a non-existant dialog
}
$(dialogDiv).dialog(obj).dialog('option', 'title', tit).dialog('open');
return false;
}
window.pickerData = [];
var pickerDiv = {};
function displayPicker( closeTo, list, area_id, isSheet, styleType ) {
$('div.toolbars-picker').remove(); // simple toggle
var $closeTo = $(closeTo);
if ($closeTo.hasClass('toolbars-picker-open')) {
$('.toolbars-picker-open').removeClass('toolbars-picker-open');
return false;
}
$closeTo.addClass('toolbars-picker-open');
var textarea = $('#' + area_id);
var coord = $closeTo.offset();
coord.bottom = coord.top + $closeTo.height();
pickerDiv = $('<div class="toolbars-picker ' + list + '" />')
.css('left', coord.left + 'px')
.css('top', (coord.bottom + 8) + 'px')
.appendTo('body');
var prepareLink = function(ins, disp ) {
disp = $(disp);
var link = $( '<a href="#" />' ).append(disp);
if (disp.attr('reset') && isSheet) {
var bgColor = $('div.tiki_sheet:first').css(styleType);
var color = $('div.tiki_sheet:first').css(styleType == 'color' ? 'background-color' : 'color');
disp
.css('background-color', bgColor)
.css('color', color);
link
.addClass('toolbars-picker-reset');
}
if ( isSheet ) {
link
.click(function() {
var I = $(closeTo).attr('instance');
I = parseInt( I ? I : 0, 10 );
if (disp.attr('reset')) {
$.sheet.instance[I].cellChangeStyle(styleType, '');
} else {
$.sheet.instance[I].cellChangeStyle(styleType, disp.css('background-color'));
}
$closeTo.click();
return false;
});
} else {
link.click(function() {
insertAt(area_id, ins);
var textarea = $('#' + area_id);
// quick fix for Firefox 3.5 losing selection on changes to popup
if (typeof textarea.selectionStart != 'undefined') {
var tempSelectionStart = textarea.selectionStart;
var tempSelectionEnd = textarea.selectionEnd;
}
$closeTo.click();
// quick fix for Firefox 3.5 losing selection on changes to popup
if (typeof textarea.selectionStart != 'undefined' && textarea.selectionStart != tempSelectionStart) {
textarea.selectionStart = tempSelectionStart;
}
if (typeof textarea.selectionEnd != 'undefined' && textarea.selectionEnd != tempSelectionEnd) {
textarea.selectionEnd = tempSelectionEnd;
}
return false;
});
}
return link;
};
var chr, $a;
for( var i in window.pickerData[list] ) {
chr = window.pickerData[list][i];
if (list === "specialchar") {
chr = $("<span>" + chr + "</span>");
}
$a = prepareLink( i, chr );
if ($a.length) {
pickerDiv.append($a);
}
}
return false;
}
function dialogSelectElement( area_id, elementStart, elementEnd ) {
if ($('#cke_contents_' + area_id).length !== 0) {return;} // TODO for ckeditor
var $textarea = $('#' + area_id);
var textareaEditor = syntaxHighlighter.get($textarea);
var val = ( textareaEditor ? textareaEditor.getValue() : $textarea.val() );
var pairs = [], pos = 0, s = 0, e = 0;
while (s > -1 && e > -1) { // positions of start/end markers
s = val.indexOf(elementStart, e);
if (s > -1) {
e = val.indexOf(elementEnd, s + elementStart.length);
if (e > -1) {
e += elementEnd.length;
pairs[pairs.length] = [ s, e ];
}
}
}
(textareaEditor ? textareaEditor : $textarea[0]).focus();
var selection = ( textareaEditor ? syntaxHighlighter.selection(textareaEditor, true) : $textarea.selection() );
s = selection.start;
e = selection.end;
var st = $textarea.attr('scrollTop');
for (var i = 0; i < pairs.length; i++) {
if (s >= pairs[i][0] && e <= pairs[i][1]) {
setSelectionRange($textarea[0], pairs[i][0], pairs[i][1]);
break;
}
}
}
function dialogSharedClose( area_id, dialog ) {
$(dialog).dialog("close");
}
// Internal Link
function dialogInternalLinkOpen( area_id ) {
$("#tbWLinkPage").tiki("autocomplete", "pagename");
dialogSelectElement( area_id, '((', '))' ) ;
var s = getTASelection($('#' + area_id)[0]);
var m = /\((.*)\(([^\|]*)\|?([^\|]*)\|?([^\|]*)\|?\)\)/g.exec(s);
if (m && m.length > 4) {
if ($("#tbWLinkRel")) {
$("#tbWLinkRel").val(m[1]);
}
$("#tbWLinkPage").val(m[2]);
if (m[4]) {
if ($("#tbWLinkAnchor")) {
$("#tbWLinkAnchor").val(m[3]);
}
$("#tbWLinkDesc").val(m[4]);
} else {
$("#tbWLinkDesc").val(m[3]);
}
} else {
$("#tbWLinkDesc").val(s);
if ($("#tbWLinkAnchor")) {
$("#tbWLinkAnchor").val("");
}
}
}
function dialogInternalLinkInsert( area_id, dialog ) {
if (!$("#tbWLinkPage").val()) {
alert(tr("Please enter a page name"));
return;
}
var s = "(";
if ($("#tbWLinkRel") && $("#tbWLinkRel").val()) {
s += $("#tbWLinkRel").val();
}
s += "(" + $("#tbWLinkPage").val();
if ($("#tbWLinkAnchor") && $("#tbWLinkAnchor").val()) {
s += "|" + ($("#tbWLinkAnchor").val().indexOf("#") !== 0 ? "#" : "") + $("#tbWLinkAnchor").val();
}
if ($("#tbWLinkDesc").val()) {
s += "|" + $("#tbWLinkDesc").val();
}
s += "))";
insertAt(area_id, s, false, false, true);
dialogSharedClose( area_id, dialog );
}
// External Link
function dialogExternalLinkOpen( area_id ) {
$("#tbWLinkPage").tiki("autocomplete", "pagename");
dialogSelectElement( area_id, '[', ']' ) ;
var s = getTASelection($('#' + area_id)[0]);
var m = /\[([^\|]*)\|?([^\|]*)\|?([^\|]*)\]/g.exec(s);
if (m && m.length > 3) {
$("#tbLinkURL").val(m[1]);
$("#tbLinkDesc").val(m[2]);
if (m[3]) {
if ($("#tbLinkNoCache") && m[3] == "nocache") {
$("#tbLinkNoCache").attr("checked", "checked");
} else {
$("#tbLinkRel").val(m[3]);
}
} else {
$("#tbWLinkDesc").val(m[3]);
}
} else {
if (s.match(/(http|https|ftp)([^ ]+)/ig) == s) { // v simple URL match
$("#tbLinkURL").val(s);
} else {
$("#tbLinkDesc").val(s);
}
}
if (!$("#tbLinkURL").val()) {
$("#tbLinkURL").val("http://");
}
}
function dialogExternalLinkInsert(area_id, dialog) {
var s = "[" + $("#tbLinkURL").val();
if ($("#tbLinkDesc").val()) {
s += "|" + $("#tbLinkDesc").val();
}
if ($("#tbLinkRel").val()) {
s += "|" + $("#tbLinkRel").val();
}
if ($("#tbLinkNoCache") && $("#tbLinkNoCache").attr("checked")) {
s += "|nocache";
}
s += "]";
insertAt(area_id, s, false, false, true);
dialogSharedClose( area_id, dialog );
}
// Table
function dialogTableOpen(area_id, dialog) {
dialogSelectElement( area_id, '||', '||' ) ;
dialog = $(dialog);
var s = getTASelection($('#' + area_id)[0]);
var m = /\|\|([\s\S]*?)\|\|/mg.exec(s);
var vals = [], rows = 3, cols = 3, c, r, i, j;
if (m) {
m = m[1];
m = m.split("\n");
rows = 0;
cols = 1;
for (i = 0; i < m.length; i++) {
var a2 = m[i].split("|");
var a = [];
for (j = 0; j < a2.length; j++) { // links can have | chars in
if (a2[j].indexOf("[") > -1 && a2[j].indexOf("[[") == -1 && a2[j].indexOf("]") == -1) { // external link
a[a.length] = a2[j];
j++;
var k = true;
while (j < a2.length && k) {
a[a.length - 1] += "|" + a2[j];
if (a2[j].indexOf("]") > -1) { // closed
k = false;
} else {
j++;
}
}
} else if (a2[j].search(/\(\S*\(/) > -1 && a2[j].indexOf("))") == -1) {
a[a.length] = a2[j];
j++;
k = true;
while (j < a2.length && k) {
a[a.length - 1] += "|" + a2[j];
if (a2[j].indexOf("))") > -1) { // closed
k = false;
} else {
j++;
}
}
} else {
a[a.length] = a2[j];
}
}
vals[vals.length] = a;
if (a.length > cols) {
cols = a.length;
}
if (a.length) {
rows++;
}
}
}
for (r = 1; r <= rows; r++) {
for (c = 1; c <= cols; c++) {
var v = "";
if (vals.length) {
if (vals[r - 1] && vals[r - 1][c - 1]) {
v = vals[r - 1][c - 1];
} else {
v = " ";
}
} else {
v = " "; //row " + r + ",col " + c + "";
}
var el = $("<input type=\"text\" id=\"tbTableR" + r + "C" + c + "\" class=\"ui-widget-content ui-corner-all\" size=\"10\" style=\"width:" + (90 / cols) + "%\" />")
.val($.trim(v))
.appendTo(dialog);
}
if (r == 1) {
el = $("<img src=\"img/icons/add.png\" />")
.click(function() {
dialog.data("cols", dialog.data("cols") + 1);
for (r = 1; r <= dialog.data("rows"); r++) {
v = "";
var el = $("<input type=\"text\" id=\"tbTableR" + r + "C" + dialog.data("cols") + "\" class=\"ui-widget-content ui-corner-all\" size=\"10\" style=\"width:" + (90 / dialog.data("cols")) + "%\" />")
.val(v);
$("#tbTableR" + r + "C" + (dialog.data("cols") - 1)).after(el);
}
dialog.find("input").width(90 / dialog.data("cols") + "%");
})
.appendTo(dialog);
}
dialog.append("<br />");
}
el = $("<img src=\"img/icons/add.png\" />")
.click(function() {
dialog.data("rows", dialog.data("rows") + 1);
for (c = 1; c <= dialog.data("cols"); c++) {
v = "";
var el = $("<input type=\"text\" id=\"tbTableR" + dialog.data("rows") + "C" + c + "\" class=\"ui-widget-content ui-corner-all\" size=\"10\" value=\"" + v + "\" style=\"width:" + (90 / dialog.data("cols")) + "%\" />")
.insertBefore(this);
}
$(this).before("<br />");
dialog.dialog("option", "height", (dialog.data("rows") + 1) * 1.2 * $("#tbTableR1C1").height() + 130);
})
.appendTo(dialog);
dialog
.data('rows', rows)
.data('cols', cols)
.dialog("option", "width", (cols + 1) * 120 + 50)
.dialog("option", "position", "center");
$("#tbTableR1C1").focus();
}
function dialogTableInsert(area_id, dialog) {
var s = "||", rows, cols, c, r, rows2 = 1, cols2 = 1;
dialog = $(dialog);
rows = dialog.data('rows') || 3;
cols = dialog.data('cols') || 3;
for (r = 1; r <= rows; r++) {
for (c = 1; c <= cols; c++) {
if ($.trim($("#tbTableR" + r + "C" + c).val())) {
if (r > rows2) {
rows2 = r;
}
if (c > cols2) {
cols2 = c;
}
}
}
}
for (r = 1; r <= rows2; r++) {
for (c = 1; c <= cols2; c++) {
var tableData = $("#tbTableR" + r + "C" + c).val();
s += tableData;
if (c < cols2) {
s += (tableData ? '|' : ' | ');
}
}
if (r < rows2) {
s += "\n";
}
}
s += "||";
insertAt(area_id, s, false, false, true);
dialogSharedClose( area_id, dialog );
}
// Find
function dialogFindOpen(area_id) {
var s = getTASelection($('#' + area_id)[0]);
$("#tbFindSearch").val(s).focus();
}
function dialogFindFind( area_id ) {
var ta = $('#' + area_id);
var findInput = $("#tbFindSearch").removeClass("ui-state-error");
var $textareaEditor = syntaxHighlighter.get(ta); //codemirror functionality
if ($textareaEditor) {
syntaxHighlighter.find($textareaEditor, findInput.val());
}
else { //standard functionality
var s, opt, str, re, p = 0, m;
s = findInput.val();
opt = "";
if ($("#tbFindCase").attr("checked")) {
opt += "i";
}
str = ta.val();
re = new RegExp(s, opt);
p = getCaretPos(ta[0]);
if (p && p < str.length) {
m = re.exec(str.substring(p));
}
else {
p = 0;
}
if (!m) {
m = re.exec(str);
p = 0;
}
if (m) {
setSelectionRange(ta[0], m.index + p, m.index + s.length + p);
}
else {
findInput.addClass("ui-state-error");
}
}
}
// Replace
function dialogReplaceOpen(area_id) {
var s = getTASelection($('#' + area_id)[0]);
$("#tbReplaceSearch").val(s).focus();
}
function dialogReplaceReplace( area_id ) {
var findInput = $("#tbReplaceSearch").removeClass("ui-state-error");
var s = findInput.val();
var r = $("#tbReplaceReplace").val();
var opt = "";
if ($("#tbReplaceAll").attr("checked")) {
opt += "g";
}
if ($("#tbReplaceCase").attr("checked")) {
opt += "i";
}
var ta = $('#' + area_id);
var str = ta.val();
var re = new RegExp(s,opt);
var textareaEditor = syntaxHighlighter.get(ta); //codemirror functionality
if (textareaEditor) {
syntaxHighlighter.replace(textareaEditor, s, r);
}
else { //standard functionality
ta.val(str.replace(re, r));
}
}
(function($) {
/**
* Adds annotations to the content of text in ''container'' based on the
* content found in selected dts.
*
* Used in comments.tpl
*/
$.fn.addnotes = function( container ) {
return this.each(function(){
var comment = this;
var text = $('dt:contains("note")', comment).next('dd').text();
var title = $('h6:first', comment).clone();
var body = $('.body:first', comment).clone();
body.find('dt:contains("note")').closest('dl').remove();
if( text.length > 0 ) {
var parents = container.find(':contains("' + text + '")').parent();
var node = container.find(':contains("' + text + '")').not(parents)
.addClass('note-editor-text')
.each( function() {
var child = $('dl.note-list',this);
if( ! child.length ) {
child = $('<dl class="note-list"/>')
.appendTo(this)
.hide();
$(this).click( function() {
child.toggle();
} );
}
child.append( title )
.append( $('<dd/>').append(body) );
} );
}
});
};
/**
* Convert a zone to a note editor by attaching handlers on mouse events.
*/
$.fn.noteeditor = function (editlink, link) {
var hiddenParents = null;
var annote = $(link)
.click( function( e ) {
e.preventDefault();
var $block = $('<div/>');
var annotation = $(this).attr('annotation');
$(this).fadeOut(100);
$block.load(editlink.attr('href'), function () {
var msg = "";
if (annotation.length < 20) {
msg = tr("The text you have selected is quite short. Select a longer piece to ensure the note is associated with the correct text.") + "<br />";
}
msg = "<p class='description comment-info'>" + msg + tr("Tip: Leave the first line as it is, starting with \";note:\". This is required") + "</p>";
$block.prepend($(msg));
$('textarea', this)
.val(';note:' + annotation + "\n\n").focus();
$('form', this).submit(function () {
$.post($(this).attr('action'), $(this).serialize(), function () {
$block.dialog('destroy');
});
return false;
});
$block.dialog({
modal: true,
width: 500,
height: 400
});
});
} )
.appendTo(document.body);
$(this).mouseup(function( e ) {
var range;
if( window.getSelection && window.getSelection().rangeCount ) {
range = window.getSelection().getRangeAt(0);
} else if( window.selection ) {
range = window.selection.getRangeAt(0);
}
if( range ) {
var str = $.trim( range.toString() );
if( str.length && -1 === str.indexOf( "\n" ) ) {
annote.attr('annotation', str);
annote.fadeIn(100).position( {
of: e,
at: 'bottom left',
my: 'top left',
offset: '20 20'
} );
} else {
if (annote.css("display") != "none") {
annote.fadeOut(100);
}
if ($("form.comments").css("display") == "none") {
$("form.comments").show();
}
if (hiddenParents) {
hiddenParents.hide();
hiddenParents = null;
}
}
}
});
};
$.fn.browse_tree = function () {
this.each(function () {
$('.treenode:not(.done)', this)
.addClass('done')
.each(function () {
if (getCookie($('ul:first', this).attr('data-id'), $('ul:first', this).attr('data-prefix')) !== 'o') {
$('ul:first', this).css('display', 'none');
}
if ($('ul:first', this).length) {
var dir = $('ul:first', this).css('display') === 'block' ? 's' : 'e';
$(this).prepend('<span class="flipper ui-icon ui-icon-triangle-1-' + dir + '" style="float: left;"/>');
} else {
$(this).prepend('<span style="float:left;width:16px;height:16px;"/>');
}
});
$('.flipper:not(.done)')
.addClass('done')
.css('cursor', 'pointer')
.click(function () {
var body = $(this).parent().find('ul:first');
if ('block' === body.css('display')) {
$(this).removeClass('ui-icon-triangle-1-s').addClass('ui-icon-triangle-1-e');
body.hide('fast');
setCookie(body.data("id"), "", body.data("prefix"));
} else {
$(this).removeClass('ui-icon-triangle-1-e').addClass('ui-icon-triangle-1-s');
body.show('fast');
setCookie(body.data("id"), "o", body.data("prefix"));
}
});
});
return this;
};
var fancy_filter_create_token = function(value, label) {
var close, token;
close = $('<span class="ui-icon ui-icon-close"/>')
.click(function () {
var ed = $(this).parent().parent();
$(this).parent().remove();
ed.change();
return false;
});
token = $('<span class="token"/>')
.attr('data-value', value)
.text(label)
.attr('contenteditable', false)
.disableSelection()
.append(close);
return token[0];
};
var fancy_filter_build_init = function(editable, str, options) {
if (str === '') {
str = ' ';
}
editable.html(str.replace(/(\d+)/g, '<span>$1</span>'));
if (options && options.map) {
editable.find('span').each(function () {
var val = $(this).text();
$(this).replaceWith(fancy_filter_create_token(val, options.map[val] ? options.map[val] : val));
});
}
};
$jq.fn.fancy_filter = function (operation, options) {
this.each(function () {
switch (operation) {
case 'init':
var editable = $('<div class="fancyfilter"/>'), input = this;
if (editable[0].contentEditable !== null) {
fancy_filter_build_init(editable, $(this).val(), options);
editable.attr('contenteditable', true);
$(this).after(editable).hide();
}
editable
.keyup(function() {
$(this).change();
$(this).mouseup();
})
.change(function () {
$(input).val($('<span/>')
.html(editable.html())
.find('span').each(function() {
$(this).replaceWith(' ' + $(this).attr('data-value') + ' ');
})
.end().text().replace(/\s+/g, ' '));
})
.mouseup(function () {
input.lastRange = window.getSelection().getRangeAt(0);
});
break;
case 'add':
var node = fancy_filter_create_token(options.token, options.label);
if (this.lastRange) {
this.lastRange.deleteContents();
this.lastRange.insertNode(node);
this.lastRange.insertNode(document.createTextNode(options.join));
} else {
$(this).next().append(options.join).append(node);
}
$(this).next().change();
break;
}
});
return this;
};
$.fn.drawGraph = function () {
this.each(function () {
var $this = $(this);
var width = $this.width();
var height = Math.ceil( width * 9 / 16 );
var nodes = $this.data('graph-nodes');
var edges = $this.data('graph-edges');
var g = new Graph;
$.each(nodes, function (k, i) {
g.addNode(i);
});
$.each(edges, function (k, i) {
var style = { directed: true };
if( i.preserve ) {
style.color = 'red';
}
g.addEdge( i.from, i.to, style );
});
var layouter = new Graph.Layout.Spring(g);
layouter.layout();
var renderer = new Graph.Renderer.Raphael($this.attr('id'), g, width, height );
renderer.draw();
});
return this;
};
/**
* Handle textarea and input text selections
* Code from:
*
* jQuery Autocomplete plugin 1.1
* Copyright (c) 2009 Jörn Zaefferer
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* Now deprecated and replaced in Tiki 7 by jquery-ui autocomplete
*/
$.fn.selection = function(start, end) {
if (start !== undefined) {
if (end === undefined) {
end = start;
}
return this.each(function() {
if( this.createTextRange ){
var selRange = this.createTextRange();
if (start == end) {
selRange.move("character", start);
selRange.select();
} else {
selRange.collapse(true);
selRange.moveStart("character", start);
selRange.moveEnd("character", end - start); // moveEnd is relative
selRange.select();
}
} else if( this.setSelectionRange ){
this.setSelectionRange(start, end);
} else if( this.selectionStart ){
this.selectionStart = start;
this.selectionEnd = end;
}
});
}
var field = this[0];
if ( field.createTextRange ) {
// from http://the-stickman.com/web-development/javascript/finding-selection-cursor-position-in-a-textarea-in-internet-explorer/
// The current selection
var range = document.selection.createRange();
// We'll use this as a 'dummy'
var stored_range = range.duplicate();
// Select all text
stored_range.moveToElementText( field );
// Now move 'dummy' end point to end point of original range
stored_range.setEndPoint( 'EndToEnd', range );
// Now we can calculate start and end points
var selectionStart = stored_range.text.length - range.text.length;
var selectionEnd = selectionStart + range.text.length;
return {
start: selectionStart,
end: selectionEnd
}
} else if( field.selectionStart !== undefined ){
return {
start: field.selectionStart,
end: field.selectionEnd
}
}
};
$.fn.comment_toggle = function () {
this.each(function () {
var $target = $(this.hash);
$target.hide();
$(this).click(function () {
if ($target.is(':visible')) {
$target.hide(function () {
$(this).empty();
});
} else {
$target.comment_load($(this).attr('href'));
}
return false;
});
if (location.search.indexOf("comzone=show") > -1) {
var comButton = this;
setTimeout(function() {
$(comButton).click();
}, 500);
}
});
return this;
};
$.fn.comment_load = function (url) {
$('#top .note-list').remove();
this.each(function () {
var comment_container = this;
$(this).load(url, function (response, status) {
$(this).show();
$('.comment.inline dt:contains("note")', this)
.closest('.comment')
.addnotes( $('#top') );
if(jqueryTiki.useInlineComment) {
$('#top').noteeditor($('.comment-form:last a', comment_container), '#note-editor-comment');
}
$(this).on('click', '.comment-form > a', function () {
$('.comment-form form').each(function() { // remove other forms
var $p = $(this).parent();
$p.empty().addClass('button').append($p.data('previous'));
});
$(this).parent().data('previous', $(this)).empty().removeClass('button').load($(this).attr('href'), function () {
var form = $('form', this).submit(function () {
var errors;
$.post(form.attr('action'), $(this).serialize(), function (data, st) {
if (data.threadId) {
$(comment_container).empty().comment_load(url);
$comm_counter = $('span.count_comments');
if ($comm_counter.length != 0) {
var comment_count = parseInt($comm_counter.text()) + 1;
$comm_counter.text(comment_count);
}
} else {
errors = $('ol.errors', form).empty();
if (! errors.length) {
$(':submit', form).after(errors = $('<ol class="errors"/>'));
}
$.each(data.errors, function (k, v) {
errors.append($('<li/>').text(v));
});
}
}, 'json');
return false;
});
//allow syntax highlighting
if ($.fn.flexibleSyntaxHighlighter) {
// console.log(form.find('textarea.wikiedit'));
form.find('textarea.wikiedit').flexibleSyntaxHighlighter();
}
});
return false;
});
$('.button.comment-form.autoshow a').click(); // allow autoshowing of comment forms through autoshow css class
$('.confirm-prompt', this).requireConfirm({
success: function (data) {
if (data.status === 'DONE') {
$(comment_container).empty().comment_load(url);
$comm_counter = $('span.count_comments');
if ($comm_counter.length != 0) {
var comment_count = parseInt($comm_counter.text()) - 1;
$comm_counter.text(comment_count);
}
}
}
});
var match = location.hash.match(/threadId(\d+)/);
if (match) {
var $comment = $(".comment[data-comment-thread-id=" + match[1] + "]");
var top = $comment.offset().top + $comment.height() - $window.height();
$('html, body').animate({
scrollTop: top
}, 2000);
}
});
});
return this;
};
$.fn.input_csv = function (operation, separator, value) {
this.each(function () {
var values = $(this).val().split(separator);
if (values[0] === '') {
values.shift();
}
if (operation === 'add') {
values.push(value);
} else if (operation === 'delete') {
value = String(value);
while (-1 !== $.inArray(value, values)) {
values.splice($.inArray(value, values), 1);
}
}
$(this).val(values.join(separator));
});
return this;
};
$.service = function (controller, action, query) {
var append = '';
if (query) {
append = '?' + $.map(query, function (v, k) {
return k + '=' + escape(v);
}).join('&');
}
if (action) {
return 'tiki-' + controller + '-' + action + append;
} else {
return 'tiki-' + controller + append;
}
};
$.fn.serviceDialog = function (options) {
this.each(function () {
var $dialog = $('<div/>'), origin = this, buttons = {};
$(this).append($dialog).data('serviceDialog', $dialog);
if (! options.hideButtons) {
buttons[tr('OK')] = function () {
$dialog.find('form:visible').submit();
};
buttons[tr('Cancel')] = function () {
$dialog
.dialog('close')
.dialog('destroy');
};
}
$dialog.dialog({
title: options.title,
minWidth: options.width ? options.width : 500,
height: (options.fullscreen ? $window.height() - 20 : (options.height ? options.height : 600)),
width: (options.fullscreen ? $window.width() - 20 : null),
close: function () {
if (options.close) {
options.close.apply([], this);
}
$(this).dialog('destroy').remove();
},
buttons: buttons,
modal: options.modal,
zIndex: options.zIndex
});
$dialog.loadService(options.data, $.extend(options, {origin: origin}));
});
return this;
};
$.fn.loadService = function (data, options) {
var $dialog = this, controller = options.controller, action = options.action, url;
if (typeof data === "string") { // TODO better and refactor
data = JSON.parse('{"' + tiki_decodeURIComponent(data.replace(/&/g, "\",\"").replace(/=/g,"\":\"")).replace(/[\n\r]/g, "") + '"}');
}
if (data && data.controller) {
controller = data.controller;
}
if (data && data.action) {
action = data.action;
}
if (options.origin && $(options.origin).is('a')) {
url = $(options.origin).attr('href');
} else {
url = $.service(controller, action);
}
$dialog.modal(tr("Loading..."));
$.ajax(url, {
data: data,
error: function (jqxhr) {
$dialog.html(jqxhr.responseText);
},
success: function (data) {
$dialog.html(data);
$dialog.find('.ajax').click(function (e) {
$dialog.loadService(null, {origin: this});
return false;
});
$dialog.find('form .submit').hide();
$dialog.find('form:not(.no-ajax)').unbind("submit").submit(function (e) {
var form = this, act;
act = $(form).attr('action');
if (! act) {
act = url;
}
if (typeof $(form).valid === "function") {
if (!$(form).valid()) {
return false;
} else if ($(form).validate().pendingRequest > 0) {
$(form).validate();
setTimeout(function() {$(form).submit();}, 500);
return false;
}
}
$.ajax(act, {
type: 'POST',
dataType: 'json',
data: $(form).serialize(),
success: function (data) {
data = (data ? data : {});
if (data.FORWARD) {
$dialog.loadService(data.FORWARD, options);
} else {
$dialog.dialog('destroy');
}
if (options.success) {
options.success.apply(options.origin, [data]);
}
},
error: function (jqxhr) {
$(form.name).showError(jqxhr);
}
});
return false;
});
if (options.load) {
options.load.apply($dialog[0], [data]);
}
$('.confirm-prompt', this).requireConfirm({
success: function (data) {
if (data.FORWARD) {
$dialog.loadService(data.FORWARD, options);
} else {
$dialog.loadService(options.data, options);
}
}
});
},
complete: function () {
$dialog.modal();
if ($dialog.find('form').size() == 0) {
// If the result contains no form, skip OK/Cancel, and just allow to close
var buttons = $dialog.dialog('option', 'buttons'), n = {};
n[tr('OK')] = buttons[tr('Cancel')];
$dialog.dialog('option', 'buttons', n);
}
}
});
};
$.fn.requireConfirm = function (options) {
this.click(function (e) {
e.preventDefault();
var message = options.message, link = this;
if (! message) {
message = $(this).data('confirm');
}
if (confirm (message)) {
$.ajax($(this).attr('href'), {
type: 'POST',
dataType: 'json',
data: {
'confirm': 1
},
success: function (data) {
options.success.apply(link, [data]);
},
error: function (jqxhr) {
$(link).closest('form').showError(jqxhr);
}
});
}
return false;
});
return this;
};
$.fn.showError = function (message) {
if (message.responseText) {
var data = $.parseJSON(message.responseText);
message = data.message;
}
this.each(function () {
var validate = $(this).closest('form').validate(), errors = {}, field;
if (validate) {
if (! $(this).attr('name')) {
$(this).attr('name', $(this).attr('id'));
}
field = $(this).attr('name');
if (!field) { // element without name or id can't show errors
return;
}
var parts;
if (parts = message.match(/^<!--field\[([^\]]+)\]-->(.*)$/)) {
field = parts[1];
message = parts[2];
}
errors[field] = message;
validate.showErrors(errors);
setTimeout(function () {
$('#error_report li').filter(function () {
return $(this).text() === message;
}).remove();
if ($('#error_report ul').is(':empty')) {
$('#error_report').empty();
}
}, 100);
}
});
return this;
};
$.fn.clearError = function () {
this.each(function () {
$(this).closest('form').find('label.error[for="' + $(this).attr('name') + '"]').remove();
});
return this;
};
$.fn.object_selector = function (filter, threshold) {
var input = this;
this.each(function () {
var $spinner = $(this).parent().modal(" ");
$.getJSON('tiki-searchindex.php', {
filter: filter
}, function (data) {
var $select = $('<select/>'), $autocomplete = $('<input type="text"/>');
$(input).wrap('<div class="object_selector"/>');
$(input).hide();
$select.append('<option/>');
$.each(data, function (key, value) {
$select.append($('<option/>').attr('value', value.object_type + ':' + value.object_id).text(value.title));
});
$(input).after($select);
$select.change(function () {
$(input).data('label', $select.find('option:selected').text());
$(input).val($select.val()).change();
});
if (jqueryTiki.selectmenu) {
var $hidden = $select.parents("fieldset:hidden:last").show();
$select.css("font-size", $.browser.webkit ? "1.4em" : "1.1em") // not sure why webkit is so different, it just is :(
.attr("id", input.attr("id") + "_sel") // bug in selectmenu when no id
.tiki("selectmenu");
$hidden.hide();
}
$spinner.modal();
if ($select.children().length > threshold) {
var filterField = $('<input type="text"/>').width(120).css('marginRight', '1em');
$(input).after(filterField);
filterField.wrap('<label/>').before(tr('Search:')+ ' ');
filterField.keypress(function (e) {
var field = this;
if (e.which === 0 || e.which === 13) {
return false;
}
if (this.searching) {
clearTimeout(this.searching);
this.searching = null;
}
if (this.ajax) {
this.ajax.abort();
this.ajax = null;
$spinner.modal();
}
if (jqueryTiki.selectmenu) {
$select.selectmenu('open');
$(field).focus();
}
this.searching = setTimeout(function () {
var loaded = $(field).val();
if (!loaded || loaded === " ") { // let them get the whole list back?
loaded = "*";
}
if ((loaded === "*" || loaded.length >= 3) && loaded !== $select.data('loaded')) {
$spinner = $(field).parent().modal(" ");
field.ajax = $.getJSON('tiki-searchindex.php', {
filter: $.extend(filter, {autocomplete: loaded})
}, function (data) {
$select.empty();
$select.data('loaded', loaded);
$select.append('<option/>');
$.each(data, function (key, value) {
$select.append($('<option/>').attr('value', value.object_type + ':' + value.object_id).text(value.title));
});
if (jqueryTiki.selectmenu) {
$select.tiki("selectmenu");
$select.selectmenu('open');
$(field).focus();
}
$spinner.modal();
});
}
}, 500);
});
}
});
});
return this;
};
$.fn.sortList = function () {
var list = $(this), items = list.children('li').get();
items.sort(function(a, b) {
var compA = $(a).text().toUpperCase();
var compB = $(b).text().toUpperCase();
return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
})
$.each(items, function(idx, itm) {
list.append(itm);
});
};
$.localStorage = {
store: function (key, value) {
if (window.localStorage) {
window.localStorage[key] = $.toJSON(favoriteList);
}
},
load: function (key, callback, fetch) {
if (window.localStorage && window.localStorage[key]) {
callback($.parseJSON(window.localStorage[key]));
} else {
fetch(function (data) {
window.localStorage[key] = $.toJSON(data);
callback(data);
});
}
}
};
var favoriteList = [];
$.fn.favoriteToggle = function () {
this.find('a')
.each(function () {
var type, obj, isFavorite, link = this;
type = $(this).queryParam('type');
obj = $(this).queryParam('object');
function isFavorite() {
var ret = false;
$.each(favoriteList, function (k, v) {
if (v === type + ':' + obj) {
ret = true;
return false;
}
});
return ret;
}
$(this).empty();
$(this).append(tr('Favorite'));
$(this).prepend($('<img style="vertical-align: top; margin-right: .2em;" />').attr('src', isFavorite() ? 'img/icons/star.png' : 'img/icons/star_grey.png'));
// Toggle class of closest surrounding div for css customization
if (isFavorite()) {
$(this).closest('div').addClass( 'favorite_selected' );
$(this).closest('div').removeClass( 'favorite_unselected' );
} else {
$(this).closest('div').addClass( 'favorite_unselected' );
$(this).closest('div').removeClass( 'favorite_selected' );
}
$(this)
.filter(':not(".register")')
.addClass('register')
.click(function () {
$.getJSON($(this).attr('href'), {
target: isFavorite() ? 0 : 1
}, function (data) {
favoriteList = data.list;
$.localStorage.store('favorites', favoriteList);
$(link).parent().favoriteToggle();
});
return false;
});
});
return this;
};
$.fn.queryParam = function (name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)");
var results = regex.exec(this[0].href);
if(results == null) {
return "";
} else {
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
};
$(function () {
var list = $('.favorite-toggle');
if (list.length > 0) {
$.localStorage.load(
'favorites',
function (data) {
favoriteList = data;
list
.favoriteToggle()
.removeClass('favorite-toggle');
},
function (recv) {
$.getJSON($.service('favorite', 'list'), recv);
}
);
}
});
$.ajaxSetup({
complete: function () {
$('.favorite-toggle')
.favoriteToggle()
.removeClass('favorite-toggle');
}
});
/**
* Show a loading spinner on top of a button (or whatever)
*
* @param empty or jq object $spinner if empty, spinner is added and returned and element "disabled"
* if spinner then spinner is removed and element returned to normal
*
* @return jq object $spinner being shown or null when removing
*/
$.fn.showBusy = function( $spinner ) {
if (!$spinner) {
var pos = $(this).position();
$spinner = $("<img src='img/spinner.gif' alt='" + tr("Wait") + "' class='ajax-spinner' />").
css({
"position": "absolute",
"top": pos.top + ($(this).height() / 2),
"left": pos.left + ($(this).width() / 2) - 8
}).data("target", this);
$(this).parent().find(".ajax-spinner").remove();
$(this).parent().append($spinner);
$(this).attr("disabled", true).css("opacity", 0.5);
return $spinner;
} else {
$($spinner.data("target")).attr("disabled", false).css("opacity", 1);
$spinner.remove();
return null;
}
}
})($jq);
// Prevent memory leaks in IE
// Window isn't included so as not to unbind existing unload events
// More info:
// - http://isaacschlueter.com/2006/10/msie-memory-leaks/
if ( window.attachEvent && !window.addEventListener ) {
window.attachEvent("onunload", function() {
for ( var id in jQuery.cache ) {
var item = jQuery.cache[ id ];
if ( item.handle ) {
if ( item.handle.elem === window ) {
for ( var type in item.events ) {
if ( type !== "unload" ) {
// Try/Catch is to handle iframes being unloaded, see #4280
try {
jQuery.event.remove( item.handle.elem, type );
} catch(e) {}
}
}
} else {
// Try/Catch is to handle iframes being unloaded, see #4280
try {
jQuery.event.remove( item.handle.elem );
} catch(e) {}
}
}
}
});
}
$.modal = function(msg) {
return $('body').modal(msg, {
isEverything: true
});
};
//Makes modal over window or object so ajax can load and user can't prevent action
$.fn.modal = function(msg, s) {
var obj = $(this);
if (!obj.length) {
return; // happens after search index rebuild in some conditions
}
var lastModal = obj.attr('lastModal');
if (!lastModal) {
lastModal = Math.floor(Math.random() * 1000);
obj.attr('lastModal', lastModal);
}
var mid = obj.height() / 2 + obj.offset().top;
if (mid > $window.height()) {
mid = ($window.height() - obj.offset().top) / 2 + obj.offset().top;
}
s = $.extend({
isEverything: false,
top: obj.offset().top,
left: obj.offset().left,
height: obj.height(), //we try to get height here
width: obj.width(),
middle: (mid),
center: (obj.width() / 2 + obj.offset().left)
}, s);
var modal = $('body').find('#modal_' + lastModal);
var spinner = $('<img src="img/spinner.gif" />');
if (!msg) {
modal
.fadeOut(function() {
$(this).remove();
});
obj.removeAttr('lastModal');
return;
}
if (modal.length) {
modal
.find('.dialog')
.html(spinner)
.append(msg);
return;
}
modal = $('<div>' +
'<div class="dialog"></div>' +
'<div class="mask"></div>' +
'</div>')
.addClass('boxes')
.attr('id', 'modal_' + lastModal)
.prependTo('body');
var size = {};
if (s.isEverything) { //if the modal includes the whole page
s = $.extend(s, {
top: 0,
left: 0,
height: $document.height(),
width: $window.width(),
middle: $window.height() / 2,
center: $window.width() / 2
});
}
//Set height and width to mask to fill up the whole screen or the single element
modal.find('.mask')
.css('width', s.width + 'px')
.css('height', s.height + 'px')
.css('top', s.top + 'px')
.css('left', s.left + 'px')
.css('position', 'absolute')
.fadeTo(1,0.01)
.fadeTo(1000,0.8);
var dialog = modal.find('.dialog');
dialog
.append(spinner)
.append(msg)
.css('top', (s.middle - dialog.height() / 2) + 'px')
.css('left', (s.center - dialog.width() / 2) + 'px')
.css('position', 'absolute');
if (s.isEverything) {
dialog
.css('top', (s.middle - dialog.height() / 2) + 'px')
.css('left', (s.center - dialog.width() / 2) + 'px')
.css('position', 'fixed');
}
return obj;
};
//makes the width of an input change to the value
$.fn.valWidth = function() {
var me = $(this);
return me.ready(function() {
var h = me.height();
if (!h) {
h = me.offsetParent().css("font-size");
if (h) {
h = parseInt(h.replace("px", ""));
}
}
me.keyup(function() {
var width = me.val().length * h;
me
.stop()
.animate({
width: (width > h ? width : h)
}, 200);
})
.keyup();
});
};
//For making pagination have the ability to enter page/offset number and go
$.paginationHelper = function() {
$('.pagenums').each(function() {
var me = $(this);
var step = me.find('input.pagenumstep');
var endOffset = (me.find('input.pagenumend').val() - 1) * step.data('step');
var url = step.data('url');
var offset_jsvar = step.data('offset_jsvar');
var offset_arg = step.data('offset_arg');
me.find('span.pagenumstep').replaceWith(
$('<input type="text" style="font-size: inherit; " />')
.val(step.val())
.change(function() {
var newOffset = step.data('step') * ($(this).val() - 1);
if (newOffset >= 0) {
//make sure the offset isn't too high
newOffset = (newOffset > endOffset ? endOffset : newOffset);
//THis is for custom/ajax search handling
window[offset_jsvar] = newOffset;
if (step[0]) {
if (step.attr('onclick')) {
step[0].onclick();
return;
}
}
//if the above behavior isn't there, we update location
document.location = url + offset_arg + "=" + newOffset;
}
})
.keyup(function(e) {
switch(e.which) {
case 13: $(this).blur();
}
})
.valWidth()
);
});
};
//a sudo "onvisible" event
$.fn.visible = function(fn, isOne) {
if (fn) {
$(this).each(function() {
var me = $(this);
if (isOne) {
me.one('visible', fn);
} else {
me.bind('visible', fn);
}
function visibilityHelper() {
if (!me.is(':visible')) {
setTimeout(visibilityHelper, 500);
} else {
me.trigger('visible');
}
}
visibilityHelper();
});
} else {
$(this).trigger('visible');
}
return this;
};
$.download = function(url, data, method){
//url and data options required
if( url && data ){
//data can be string of parameters or array/object
data = typeof data == 'string' ? data : jQuery.param(data);
//split params into form inputs
var inputs = '';
jQuery.each(data.split('&'), function(){
var pair = this.split('=');
inputs+='<input type="hidden" name="'+ pair[0] +'" value="'+ pair[1] +'" />';
});
//send request
jQuery('<form action="'+ url +'" method="'+ (method||'post') +'">'+inputs+'</form>')
.appendTo('body').submit().remove();
};
};
$.uiIcon = function(type) {
return $('<div style="width: 1.4em; height: 1.4em; margin: .2em; display: inline-block; cursor: pointer;">' +
'<span class="ui-icon ui-icon-' + type + '"> </span>' +
'</div>')
.hover(function(){
$(this).addClass('ui-state-highlight');
}, function() {
$(this).removeClass('ui-state-highlight');
});
};
$.uiIconButton = function(type) {
return $.uiIcon(type).addClass('ui-state-default ui-corner-all');
};
$.rangySupported = function(fn) {
if (window.rangy) {
rangy.init();
var cssClassApplierModule = rangy.modules.CssClassApplier;
return fn();
}
};
$.fn.rangy = function(fn) {
var me = $(this);
$.rangySupported(function() {
$document.mouseup(function(e) {
if (me.data('rangyBusy')) return;
var selection = rangy.getSelection();
var html = selection.toHtml();
var text = selection.toString();
if (text.length > 3 && rangy.isUnique(me[0], text)) {
if (fn)
if ($.isFunction(fn))
fn({
text: text,
x: e.pageX,
y: e.pageY
});
}
});
});
return this;
};
$.fn.rangyRestore = function(phrase, fn) {
var me = $(this);
$.rangySupported(function() {
phrase = rangy.setPhrase(me[0], phrase);
if (fn)
if ($.isFunction(fn))
fn(phrase);
});
return this;
};
$.fn.rangyRestoreSelection = function(phrase, fn) {
var me = $(this);
$.rangySupported(function() {
phrase = rangy.setPhraseSelection(me[0], phrase);
if (fn)
if ($.isFunction(fn))
fn(phrase);
});
return this;
};
$.fn.realHighlight = function() {
var o = $(this);
$.rangySupported(function() {
rangy.setPhraseBetweenNodes(o.first(), o.last(), document);
});
return this;
};
$.fn.ajaxEditDraw = function(options) {
var me = $(this).attr('href', 'tiki-ajax_services.php');
//defaults
options = $.extend({
saved: function() {},
closed: function() {}
}, options);
$.modal(tr('Loading editor'));
me.serviceDialog({
title: me.attr('title'),
data: {
controller: 'draw',
action: 'edit',
fileId: me.data('fileid'),
galleryId: me.data('galleryid'),
imgParams: me.data('imgparams'),
raw: true
},
modal: true,
zIndex: 9999,
fullscreen: true,
load: function (data) {
//prevent from happeneing over and over again
if (me.data('drawLoaded')) return false;
me.data('drawLoaded', true);
me.drawing = $('#tiki_draw')
.loadDraw({
fileId: me.data('fileid'),
galleryId: me.data('galleryid'),
name: me.data('name'),
imgParams: me.data('imgparams'),
data: $('#fileData').val()
})
.bind('savedDraw', function(e, o) {
me.data('drawLoaded', false);
me.drawing.parent().dialog('destroy');
me.drawing.remove();
//update the image that did exist in the page with the new one that now exists
var img = $('.pluginImg' + me.data('fileid')).show();
if (img.length < 1) document.location = document.location + '';
var w = img.width(), h = img.height();
if (img.hasClass('regImage')) {
var replacement = $('<div />')
.attr('class', img.attr('class'))
.attr('style', img.attr('style'))
.attr('id', img.attr('id'))
.insertAfter(img);
img.remove();
img = replacement;
}
var src = me.data('src');
$('<div class=\"svgImage\" />')
.load(src ? src : 'tiki-download_file.php?fileId=' + o.fileId + '&display', function() {
$(this)
.css('position', 'absolute')
.fadeTo(0, 0.01)
.prependTo('body')
.find('img,svg')
.scaleImg({
width: w,
height: h
});
img.html($(this).children());
$(this).remove();
});
if (!options.saved) return;
options.saved(o.fileId);
me.data('fileid', o.fileId); // replace fileId on edit button
if (o.imgParams && o.imgParams.fileId) {
o.imgParams.fileId = o.fileId;
me.data('imgparams', o.imgParams);
}
})
.submit(function() {
me.drawing.saveDraw();
return false;
})
.bind('loadedDraw', function() {
//kill the padding around the dialog so it looks like svg-edit is one single box
me.drawing
.parent()
.css('padding', '0px');
var serviceDialog = me.data('serviceDialog');
if (serviceDialog) {
var drawFrame = $('#svgedit');
serviceDialog
.bind('dialogresize', function() {
drawFrame.height(serviceDialog.height() - 4);
})
.trigger('dialogresize');
}
$.modal();
});
me.drawing.find('#drawMenu').remove();
},
close: function() {
if (me.data('drawLoaded')) {
me.data('drawLoaded', false);
me.drawing.remove();
if (!options.closed) return;
options.closed(me);
}
}
});
return false;
};
$.notify = function(msg, settings) {
settings = $.extend({
speed: 10000
},settings);
var notify = $('#notify');
if (!notify.length) {
notify = $('<div id="notify" />')
.css('top', '5px')
.css('right', '5px')
.css('position', 'fixed')
.css('z-index', 9999999)
.css('padding', '5px')
.width($window.width() / 5)
.prependTo('body');
}
var note = $('<div class="notify ui-state-error ui-corner-all ui-widget ui-widget-content" />')
.append(msg)
.css('padding', '5px')
.css('margin', '5px')
.mousedown(function() {
return false;
})
.hover(function() {
$(this)
.stop()
.fadeTo(500, 0.3)
}, function() {
$(this)
.stop()
.fadeTo(500, 1)
})
.prependTo(notify);
setTimeout(function() {
note
.fadeOut()
.slideUp();
//added outside of fadeOut to ensure removal
setTimeout(function() {
note.remove();
}, 1000);
}, settings.speed);
};
function delayedExecutor(delay, callback)
{
var timeout;
return function () {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
timeout = setTimeout(callback, delay);
};
}
/**
* Close (user) sidebar column(s) if no modules are displayed.
* Modules can be hidden at runtime. So, check after the page/DOM model is loaded.
*/
$(function () {
// Do final client side adjustment of the sidebars
/////////////////////////////////////////
var maincol = 'col1';
// Hide left side panel, if no modules are displayed
var left_mods = document.getElementById('left_modules');
if (left_mods != null) {
if (isEmptyText(left_mods.innerHTML)) {
var col = document.getElementById('col2');
if (col != null) {
col.style.display = "none"
}
document.getElementById(maincol).style.marginLeft = '0';
var toggle = document.getElementById("showhide_left_column")
if (toggle != null) {
toggle.style.display = "none";
}
}
}
// Hide right side panel, if no modules are displayed
var right_mods = document.getElementById('right_modules');
if (right_mods != null) {
// alert("right_mods.innerHTML=" + right_mods.innerHTML);
//alert("right_mods.innerText=" + right_mods.innerText);
if (isEmptyText(right_mods.innerHTML)) {
var col = document.getElementById('col3');
if (col != null) {
col.style.display = "none"
}
document.getElementById(maincol).style.marginRight = '0';
var toggle = document.getElementById("showhide_right_column")
if (toggle != null) {
toggle.style.display = "none";
}
}
}
// FF does not support obj.innerText. So, analyze innerHTML, which all browsers seem to support
function isEmptyText(html) {
// Strip HTML tags
/////////////////////////
var strInputCode = html;
// Replace coded-< with <, and coded-> with >
strInputCode = strInputCode.replace(/&(lt|gt);/g, function (strMatch, p1) {
return (p1 == "lt") ? "<" : ">";
});
// Strip tags
var strTagStrippedText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
// Trim whitespace
var text = strTagStrippedText.replace(/^\s+|\s+$/g, "");
return text == null || text.length == 0;
}
});
// try and reposition the menu ul within the browser window
$.fn.moveToWithinWindow = function() {
var $el = $(this);
h = $el.height(),
w = $el.width(),
o = $el.offset(),
po = $el.parent().offset(),
st = $window.scrollTop(),
sl = $window.scrollLeft(),
wh = $window.height(),
ww = $window.width();
if (w + o.left > sl + ww) {
$el.animate({'left': sl + ww - w - po.left}, 'fast');
}
if (h + o.top > st + wh) {
$el.animate({'top': st + wh - (h > wh ? wh : h) - po.top}, 'fast');
} else if (o.top < st) {
$el.animate({'top': st - po.top}, 'fast');
}
};
$.fn.scaleImg = function (max) {
$(this).each(function() {
//Here we want to make sure that the displayed contents is the right size
var img = $(this),
actual = {
height: img.height(),
width: img.width()
},
original = $(this).clone(),
parent = img.parent();
var winner = '';
if (actual.height > max.height) {
winner = 'height';
} else if (actual.width > max.width) {
winner = 'width';
}
//if there is no winner, there is no need to resize
if (winner) {
//we resize both images and svg, we check svg first
var g = img.find('g');
if (g.length) {
img
.attr('preserveAspectRatio', 'xMinYMin meet');
parent
.css('overflow', 'hidden')
.width(max.width)
.height(max.height);
g.attr('transform', 'scale( ' + (100 / (actual[winner] / max[winner]) * 0.01) + ' )');
} else {
//now we resize regular images
if (actual.height > actual.width) {
var h = max.height;
var w = Math.ceil(actual.width / actual.height * max.height);
} else {
var w = max.width;
var h = Math.ceil(actual.height / actual.width * max.width);
}
img.css({ height: h, width: w });
}
img
.css('cursor', "url(img/icons/zoom.gif),auto")
.click(function () {
$('<div/>').append(original).dialog({
modal: true,
width: Math.min($(window).width(), actual.width + 20),
height: Math.min($(window).height(), actual.height + 50)
});
return false;
});
}
});
return this;
};
$.openEditHelp = function (num) {
var edithelp_pos = getCookie("edithelp_position"),
opts = {
width: 460,
height: 500,
title: tr("Help"),
autoOpen: false,
beforeclose: function(event, ui) {
var off = $(this).offsetParent().offset();
setCookie("edithelp_position", parseInt(off.left,10) + "," + parseInt(off.top,10) + "," + $(this).offsetParent().width() + "," + $(this).offsetParent().height());
}
};
if (edithelp_pos) {
edithelp_pos = edithelp_pos.split(",");
}
if (edithelp_pos && edithelp_pos.length) {
opts["position"] = [parseInt(edithelp_pos[0],10), parseInt(edithelp_pos[1],10)];
opts["width"] = parseInt(edithelp_pos[2],10);
opts["height"] = parseInt(edithelp_pos[3],10);
}
try {
if ($("#help_sections").dialog) {
$("#help_sections").dialog("destroy");
}
} catch( e ) {
// IE throws errors destroying a non-existant dialog
}
var help_sections = $("#help_sections")
.dialog(opts)
.dialog("open")
.tabs("select", num);
$document.trigger('editHelpOpened', help_sections);
};
|
lib/jquery_tiki/tiki-jquery.js
|
// $Id$
// JavaScript glue for jQuery in Tiki
//
// Tiki 6 - $ is now initialised in jquery.js
// but let's keep $jq available too for legacy custom code
var $jq = $,
$window = $(window),
$document = $(document);
// Escape a string for use as a jQuery selector value, for example an id or a class
function escapeJquery(str) {
return str.replace(/([\!"#\$%&'\(\)\*\+,\.\/:;\?@\[\\\]\^`\{\|\}\~=>])/g, "\\$1");
}
// Check / Uncheck all Checkboxes - overriden from tiki-js.js
function switchCheckboxes (tform, elements_name, state) {
// checkboxes need to have the same name elements_name
// e.g. <input type="checkbox" name="my_ename[]">, will arrive as Array in php.
$(tform).contents().find('input[name="' + escapeJquery(elements_name) + '"]:visible').attr('checked', state).change();
}
// override existing show/hide routines here
// add id's of any elements that don't like being animated here
var jqNoAnimElements = ['help_sections', 'ajaxLoading'];
function show(foo, f, section) {
if ($.inArray(foo, jqNoAnimElements) > -1 || typeof jqueryTiki === 'undefined') { // exceptions that don't animate reliably
$("#" + foo).show();
} else if ($("#" + foo).hasClass("tabcontent")) { // different anim prefs for tabs
showJQ("#" + foo, jqueryTiki.effect_tabs, jqueryTiki.effect_tabs_speed, jqueryTiki.effect_tabs_direction);
} else {
if ($.browser.webkit && !jqueryTiki.effect && $("#role_main #" + foo).length) { // safari/chrome does strange things with default amination in central column
showJQ("#" + foo, "slide", jqueryTiki.effect_speed, jqueryTiki.effect_direction);
} else {
showJQ("#" + foo, jqueryTiki.effect, jqueryTiki.effect_speed, jqueryTiki.effect_direction);
}
}
if (f) {setCookie(foo, "o", section);}
}
function hide(foo, f, section) {
if ($.inArray(foo, jqNoAnimElements) > -1 || typeof jqueryTiki === 'undefined') { // exceptions
$("#" + foo).hide();
} else if ($("#" + foo).hasClass("tabcontent")) {
hideJQ("#" + foo, jqueryTiki.effect_tabs, jqueryTiki.effect_tabs_speed, jqueryTiki.effect_tabs_direction);
} else {
hideJQ("#" + foo, jqueryTiki.effect, jqueryTiki.effect_speed, jqueryTiki.effect_direction);
}
if (f) {
// var wasnot = getCookie(foo, section, 'x') == 'x';
setCookie(foo, "c", section);
// if (wasnot) {
// history.go(0); // used to reload the page with all menu items closed - broken since 3.x
// }
}
}
// flip function... unfortunately didn't use show/hide (ay?)
function flip(foo, style) {
if (style && style !== 'block' || foo === 'help_sections' || foo === 'fgalexplorer' || typeof jqueryTiki === 'undefined') { // TODO find a better way?
$("#" + foo).toggle(); // inlines don't animate reliably (yet) (also help)
if ($("#" + foo).css('display') === 'none') {
setSessionVar('show_' + escape(foo), 'n');
} else {
setSessionVar('show_' + escape(foo), 'y');
}
} else {
if ($("#" + foo).css("display") === "none") {
setSessionVar('show_' + escape(foo), 'y');
show(foo);
}
else {
setSessionVar('show_' + escape(foo), 'n');
hide(foo);
}
}
}
// handle JQ effects
function showJQ(selector, effect, speed, dir) {
if (effect === 'none') {
$(selector).show();
} else if (effect === '' || effect === 'normal') {
$(selector).show(400); // jquery 1.4 no longer seems to understand 'nnormal' as a speed
} else if (effect == 'slide') {
// With jquery 1.4.2 (and less) and IE7, the function slidedown is buggy
// See: http://dev.jquery.com/ticket/3120
if ($.browser.msie && parseInt($.browser.version, 10) == 7) {
$(selector).show(speed);
} else {
$(selector).slideDown(speed);
}
} else if (effect === 'fade') {
$(selector).fadeIn(speed);
} else if (effect.match(/(.*)_ui$/).length > 1) {
$(selector).show(effect.match(/(.*)_ui$/)[1], {direction: dir}, speed);
} else {
$(selector).show();
}
}
function hideJQ(selector, effect, speed, dir) {
if (effect === 'none') {
$(selector).hide();
} else if (effect === '' || effect === 'normal') {
$(selector).hide(400); // jquery 1.4 no longer seems to understand 'nnormal' as a speed
} else if (effect === 'slide') {
$(selector).slideUp(speed);
} else if (effect === 'fade') {
$(selector).fadeOut(speed);
} else if (effect.match(/(.*)_ui$/).length > 1) {
$(selector).hide(effect.match(/(.*)_ui$/)[1], {direction: dir}, speed);
} else {
$(selector).hide();
}
}
// ajax loading indicator
function ajaxLoadingShow(destName) {
var $dest, $loading, pos, x, y, w, h;
if (typeof destName === 'string') {
$dest = $('#' + destName);
} else {
$dest = $(destName);
}
if ($dest.length === 0 || $dest.parents(":hidden").length > 0) {
return;
}
$loading = $('#ajaxLoading');
// find area of destination element
pos = $dest.offset();
// clip to page
if (pos.left + $dest.width() > $window.width()) {
w = $window.width() - pos.left;
} else {
w = $dest.width();
}
if (pos.top + $dest.height() > $window.height()) {
h = $window.height() - pos.top;
} else {
h = $dest.height();
}
x = pos.left + (w / 2) - ($loading.width() / 2);
y = pos.top + (h / 2) - ($loading.height() / 2);
// position loading div
$loading.css('left', x).css('top', y);
// now BG
x = pos.left + ccsValueToInteger($dest.css("margin-left"));
y = pos.top + ccsValueToInteger($dest.css("margin-top"));
w = ccsValueToInteger($dest.css("padding-left")) + $dest.width() + ccsValueToInteger($dest.css("padding-right"));
h = ccsValueToInteger($dest.css("padding-top")) + $dest.height() + ccsValueToInteger($dest.css("padding-bottom"));
$('#ajaxLoadingBG').css('left', pos.left).css('top', pos.top).width(w).height(h).fadeIn("fast");
show('ajaxLoading');
}
function ajaxLoadingHide() {
hide('ajaxLoading');
$('#ajaxLoadingBG').fadeOut("fast");
}
function checkDuplicateRows( button, columnSelector, rowSelector ) {
if (typeof columnSelector === 'undefined') {
columnSelector = "td";
}
if (typeof rowSelector === 'undefined') {
rowSelector = "table:first tr:not(:first)";
}
var $rows = $(button).parents(rowSelector);
$rows.each(function( ix, el ){
if ($("input:checked", el).length === 0) {
var $el = $(el);
var line = $el.find(columnSelector).text();
$rows.each(function( ix, el ){
if ($el[0] !== el && $("input:checked", el).length === 0) {
if (line === $(el).find(columnSelector).text()) {
$(":checkbox:first", el).attr("checked", true);
}
}
});
}
});
}
function setUpClueTips() {
var ctOptions = {splitTitle: '|', cluezIndex: 2000, width: -1, fx: {open: 'fadeIn', openSpeed: 'fast'},
clickThrough: true, hoverIntent: {sensitivity: 3, interval: 100, timeout: 0}};
$.cluetip.setup = {insertionType: 'insertBefore', insertionElement: '#fixedwidth'};
$('.tips[title!=""]').cluetip($.extend(ctOptions, {}));
$('.titletips[title!=""]').cluetip($.extend(ctOptions, {}));
$('.tikihelp[title!=""]').cluetip($.extend(ctOptions, {splitTitle: ':'})); // , width: '150px'
$('[data-cluetip-options]').each(function () {
$(this).cluetip(function () {
return $(this).data("cluetip-body");
}, $.extend($(this).data("cluetip-options"), ctOptions));
});
// unused?
$('.stickytips').cluetip($.extend(ctOptions, {showTitle: false, sticky: false, local: true, hideLocal: true, activation: 'click', cluetipClass: 'fullhtml'}));
// repeats for "tiki" buttons as you cannot set the class and title on the same element with that function (it seems?)
//$('span.button.tips a').cluetip({splitTitle: '|', showTitle: false, width: '150px', cluezIndex: 400, fx: {open: 'fadeIn', openSpeed: 'fast'}, clickThrough: true});
//$('span.button.titletips a').cluetip({splitTitle: '|', cluezIndex: 400, fx: {open: 'fadeIn', openSpeed: 'fast'}, clickThrough: true});
// TODO after 5.0 - these need changes in the {button} Smarty fn
}
$(function() { // JQuery's DOM is ready event - before onload
if (!window.jqueryTiki) window.jqueryTiki = {};
// tooltip functions and setup
if (jqueryTiki.tooltips) { // apply "cluetips" to all .tips class anchors
setUpClueTips();
} // end cluetip setup
// Reflections
if (jqueryTiki.replection) {
$("img.reflect").reflect({});
}
// superfish setup (CSS menu effects)
if (jqueryTiki.superfish) {
$('ul.cssmenu_horiz').supersubs({
minWidth: 11, // minimum width of sub-menus in em units
maxWidth: 20, // maximum width of sub-menus in em units
extraWidth: 1 // extra width can ensure lines don't sometimes turn over
// due to slight rounding differences and font-family
});
$('ul.cssmenu_vert').supersubs({
minWidth: 11, // minimum width of sub-menus in em units
maxWidth: 20, // maximum width of sub-menus in em units
extraWidth: 1 // extra width can ensure lines don't sometimes turn over
// due to slight rounding differences and font-family
});
$('ul.cssmenu_horiz').superfish({
animation: {opacity:'show', height:'show'}, // fade-in and slide-down animation
speed: 'fast', // faster animation speed
onShow: function(){
$(this).moveToWithinWindow();
}
});
$('ul.cssmenu_vert').superfish({
animation: {opacity:'show', height:'show'}, // fade-in and slide-down animation
speed: 'fast', // faster animation speed
onShow: function(){
$(this).moveToWithinWindow();
}
});
}
// tablesorter setup (sortable tables?)
if (jqueryTiki.tablesorter) {
$('.sortable').tablesorter({
widthFixed: true // ??
// widgets: ['zebra'], // stripes (coming soon)
});
}
// ColorBox setup (Shadowbox, actually "<any>box" replacement)
if (jqueryTiki.colorbox) {
$().bind('cbox_complete', function(){
$("#cboxTitle").wrapInner("<div></div>");
});
// Tiki defaults for ColorBox
// for every link containing 'shadowbox' or 'colorbox' in rel attribute
$("a[rel*='box']").colorbox({
transition: "elastic",
maxHeight:"95%",
maxWidth:"95%",
overlayClose: true,
title: true,
current: jqueryTiki.cboxCurrent
});
// now, first let suppose that we want to display images in ColorBox by default:
// this matches rel containg type=img or no type= specified
$("a[rel*='box'][rel*='type=img'], a[rel*='box'][rel!='type=']").colorbox({
photo: true
});
// rel containg slideshow (this one must be without #col1)
$("a[rel*='box'][rel*='slideshow']").colorbox({
photo: true,
slideshow: true,
slideshowSpeed: 3500,
preloading: false,
width: "100%",
height: "100%"
});
// this are the defaults matching all *box links which are not obviously links to images...
// (if we need to support more, add here... otherwise it is possible to override with type=iframe in rel attribute of a link)
// (from here one to speed it up, matches any link in #col1 only - the main content column)
$("#col1 a[rel*='box']:not([rel*='type=img']):not([href*='display']):not([href*='preview']):not([href*='thumb']):not([rel*='slideshow']):not([href*='image']):not([href$='\.jpg']):not([href$='\.jpeg']):not([href$='\.png']):not([href$='\.gif'])").colorbox({
iframe: true,
width: "95%",
height: "95%"
});
// hrefs starting with ftp(s)
$("#col1 a[rel*='box'][href^='ftp://'], #col1 a[rel*='box'][href^='ftps://']").colorbox({
iframe: true,
width: "95%",
height: "95%"
});
// rel containg type=flash
$("#col1 a[rel*='box'][rel*='type=flash']").colorbox({
inline: true,
width: "60%",
height: "60%",
href: function () {
var $el = $("#cb_swf_player");
if ($el.length === 0) {
$el = $("<div id='cb_swf_player' />");
$(document.body).append($("<div />").hide().append($el));
}
//$(this).media.swf(el, { width: 400, height: 300, autoplay: true, src: $(this).attr("href") });
swfobject.embedSWF($(this).attr("href"), "cb_swf_player", "100%", "90%", "9.0.0", "lib/swfobject/expressInstall.swf");
return $("#cb_swf_player");
}
});
// rel with type=iframe (if someone needs to override anything above)
$("#col1 a[rel*='box'][rel*='type=iframe']").colorbox({
iframe: true
});
// inline content: hrefs starting with #
$("#col1 a[rel*='box'][href^='#']").colorbox({
inline: true,
width: "50%",
height: "50%",
href: function(){
return $(this).attr('href');
}
});
// titles (for captions):
// by default get title from the title attribute of the link (in all columns)
$("a[rel*='box'][title]").colorbox({
title: function(){
return $(this).attr('title');
}
});
// but prefer the title from title attribute of a wrapped image if any (in all columns)
$("a[rel*='box'] img[title]").colorbox({
title: function(){
return $(this).attr('title');
},
photo: true, // and if you take title from the image you need photo
href: function(){ // and href as well (for colobox 1.3.6 tiki 5.0)
return $(this).parent().attr("href");
}
});
/* Shadowbox params compatibility extracted using regexp functions */
var re, ret;
// rel containg title param overrides title attribute of the link (shadowbox compatible)
$("#col1 a[rel*='box'][rel*='title=']").colorbox({
title: function () {
re = /(title=([^;\"]+))/i;
ret = $(this).attr("rel").match(re);
return ret[2];
}
});
// rel containg height param (shadowbox compatible)
$("#col1 a[rel*='box'][rel*='height=']").colorbox({
height: function () {
re = /(height=([^;\"]+))/i;
ret = $(this).attr("rel").match(re);
return ret[2];
}
});
// rel containg width param (shadowbox compatible)
$("#col1 a[rel*='box'][rel*='width=']").colorbox({
width: function () {
re = /(width=([^;\"]+))/i;
ret = $(this).attr("rel").match(re);
return ret[2];
}
});
// links generated by the {COLORBOX} plugin
if (jqueryTiki.colorbox) {
$("a[rel^='shadowbox[colorbox']").each(function () {$(this).attr('savedTitle', $(this).attr('title'));});
if (jqueryTiki.tooltips) {
$("a[rel^='shadowbox[colorbox']").cluetip({
splitTitle: '<br />',
cluezIndex: 400,
width: 'auto',
fx: {open: 'fadeIn', openSpeed: 'fast'},
clickThrough: true
});
}
$("a[rel^='shadowbox[colorbox']").colorbox({
title: function() {
return $(this).attr('savedTitle'); // this fix not required is colorbox was disabled
}
});
}
} // end if (jqueryTiki.colorbox)
$.applySelectMenus = function() {
return $('body').applySelectMenus();
};
$.fn.applySelectMenus = function () {
if (jqueryTiki.selectmenu) {
var $smenus, hidden = [];
if (jqueryTiki.selectmenuAll) {
// make all selects into ui selectmenus depending on $prefs['jquery_ui_selectmenu_all']
$smenus = $("select:not([multiple])");
} else {
// or just selectmenu class
$smenus = $("select.selectmenu:not([multiple])");
}
if ($smenus.length) {
$smenus.each(function () {
$.merge(hidden, $(this).parents(":hidden:last"));
});
hidden = $.unique($(hidden));
hidden.show();
$smenus.tiki("selectmenu");
hidden.hide();
}
}
};
if (jqueryTiki.selectmenu) {
$.applySelectMenus();
}
$( function() {
$("#keepOpenCbx").click(function() {
if (this.checked) {
setCookie("fgalKeepOpen", "1");
} else {
setCookie("fgalKeepOpen", "");
}
});
var keepopen = getCookie("fgalKeepOpen");
if (keepopen) {
$("#keepOpenCbx").attr("checked", "checked");
} else {
$("#keepOpenCbx").removeAttr("checked");
}
});
// end fgal fns
$.paginationHelper();
}); // end $document.ready
//For ajax/custom search
$document.bind('pageSearchReady', function() {
$.paginationHelper();
});
// moved from tiki-list_file_gallery.tpl in tiki 6
function checkClose() {
if (!$("#keepOpenCbx").attr("checked")) {
window.close();
} else {
window.blur();
if (window.opener) {
window.opener.focus();
}
}
}
/* Autocomplete assistants */
function parseAutoJSON(data) {
var parsed = [];
return $.map(data, function(row) {
return {
data: row,
value: row,
result: row
};
});
}
/// jquery ui dialog replacements for popup form code
/// need to keep the old non-jq version in tiki-js.js as jq-ui is optional (Tiki 4.0)
/// TODO refactor for 4.n
/* wikiplugin editor */
function popupPluginForm(area_id, type, index, pageName, pluginArgs, bodyContent, edit_icon, selectedMod){
if (!$.ui) {
alert("dev notice: no jq.ui here?");
return popup_plugin_form(area_id, type, index, pageName, pluginArgs, bodyContent, edit_icon); // ??
}
if ($("#" + area_id).length && $("#" + area_id)[0].createTextRange) { // save selection for IE
storeTASelection(area_id);
}
var container = $('<div class="plugin"></div>');
if (!index) {
index = 0;
}
if (!pageName) {
pageName = '';
}
var textarea = $('#' + area_id)[0];
var replaceText = false;
if (!pluginArgs && !bodyContent) {
pluginArgs = {};
bodyContent = "";
dialogSelectElement( area_id, '{' + type.toUpperCase(), '{' + type.toUpperCase() + '}' ) ;
var sel = getTASelection( textarea );
if (sel && sel.length > 0) {
sel = sel.replace(/^\s\s*/, "").replace(/\s\s*$/g, ""); // trim
//alert(sel.length);
if (sel.length > 0 && sel.substring(0, 1) === '{') { // whole plugin selected
var l = type.length;
if (sel.substring(1, l + 1).toUpperCase() === type.toUpperCase()) { // same plugin
var rx = new RegExp("{" + type + "[\\(]?([\\s\\S^\\)]*?)[\\)]?}([\\s\\S]*){" + type + "}", "mi"); // using \s\S matches all chars including lineends
var m = sel.match(rx);
if (!m) {
rx = new RegExp("{" + type + "[\\(]?([\\s\\S^\\)]*?)[\\)]?}([\\s\\S]*)", "mi"); // no closing tag
m = sel.match(rx);
}
if (m) {
var paramStr = m[1];
bodyContent = m[2];
var pm = paramStr.match(/([^=]*)=\"([^\"]*)\"\s?/gi);
if (pm) {
for (var i = 0; i < pm.length; i++) {
var ar = pm[i].split("=");
if (ar.length) { // add cleaned vals to params object
pluginArgs[ar[0].replace(/^[,\s\"\(\)]*/g, "")] = ar[1].replace(/^[,\s\"\(\)]*/g, "").replace(/[,\s\"\(\)]*$/g, "");
}
}
}
}
replaceText = sel;
} else {
if (!confirm("You appear to have selected text for a different plugin, do you wish to continue?")) {
return false;
}
bodyContent = sel;
replaceText = true;
}
} else { // not (this) plugin
if (type == 'mouseover') { // For MOUSEOVER, we want the selected text as label instead of body
bodyContent = '';
pluginArgs = {};
pluginArgs['label'] = sel;
} else {
bodyContent = sel;
}
replaceText = true;
}
} else { // no selection
replaceText = false;
}
}
var form = build_plugin_form(type, index, pageName, pluginArgs, bodyContent, selectedMod);
//with PluginModule, if the user selects another module while the edit form is open
//replace the form with a new one with fields to match the parameters for the module selected
$(form).find('tr select[name="params[module]"]').change(function() {
var npluginArgs = $.parseJSON($(form).find('input[name="args"][type="hidden"]').val());
//this is the newly selected module
var selectedMod = $(form).find('tr select[name="params[module]"]').val();
$('div.plugin input[name="type"][value="' + type + '"]').parent().parent().remove();
popupPluginForm(area_id, type, index, pageName, npluginArgs, bodyContent, edit_icon, selectedMod);
});
var $form = $(form).find('tr input[type=submit]').remove();
container.append(form);
document.body.appendChild(container[0]);
handlePluginFieldsHierarchy(type);
var pfc = container.find('table tr').length; // number of rows (plugin form contents)
var t = container.find('textarea:visible').length;
if (t) {pfc += t * 3;}
if (pfc > 9) {pfc = 9;}
if (pfc < 2) {pfc = 2;}
pfc = pfc / 10; // factor to scale dialog height
var btns = {};
var closeText = tr("Close");
btns[closeText] = function() {
$(this).dialog("close");
};
btns[replaceText ? tr("Replace") : edit_icon ? tr("Submit") : tr("Insert")] = function() {
var meta = tiki_plugins[type];
var params = [];
var edit = edit_icon;
// whether empty required params exist or not
var emptyRequiredParam = false;
for (var i = 0; i < form.elements.length; i++) {
var element = form.elements[i].name;
var matches = element.match(/params\[(.*)\]/);
if (matches === null) {
// it's not a parameter, skip
continue;
}
var param = matches[1];
var val = form.elements[i].value;
// check if fields that are required and visible are not empty
if (meta.params[param]) {
if (meta.params[param].required) {
if (val === '' && $(form.elements[i]).is(':visible')) {
$(form.elements[i]).css('border-color', 'red');
if ($(form.elements[i]).next('.required_param').length === 0) {
$(form.elements[i]).after('<div class="required_param" style="font-size: x-small; color: red;">(required)</div>');
}
emptyRequiredParam = true;
}
else {
// remove required feedback if present
$(form.elements[i]).css('border-color', '');
$(form.elements[i]).next('.required_param').remove();
}
}
}
if (val !== '') {
params.push(param + '="' + val + '"');
}
}
if (emptyRequiredParam) {
return false;
}
var blob, pluginContentTextarea = $("[name=content]", form), pluginContentTextareaEditor = syntaxHighlighter.get(pluginContentTextarea);
var cont = (pluginContentTextareaEditor ? pluginContentTextareaEditor.getValue() : pluginContentTextarea.val());
if (cont.length > 0) {
blob = '{' + type.toUpperCase() + '(' + params.join(' ') + ')}' + cont + '{' + type.toUpperCase() + '}';
} else {
blob = '{' + type.toLowerCase() + ' ' + params.join(' ') + '}';
}
if (edit) {
container.children('form').submit();
} else {
insertAt(area_id, blob, false, false, replaceText);
}
$(this).dialog("close");
$('div.plugin input[name="type"][value="' + type + '"]').parent().parent().remove();
return false;
};
var heading = container.find('h3').hide();
try {
if (container.dialog) {
container.dialog('destroy');
}
} catch( e ) {
// IE throws errors destroying a non-existant dialog
}
container.dialog({
width: $window.width() * 0.6,
height: $window.height() * pfc,
zIndex: 10000,
title: heading.text(),
autoOpen: false,
close: function() {
$('div.plugin input[name="type"][value="' + type + '"]').parent().parent().remove();
var ta = $('#' + area_id);
if (ta) {ta.focus();}
}
}).dialog('option', 'buttons', btns).dialog("open");
//This allows users to create plugin snippets for any plugin using the jQuery event 'plugin_#type#_ready' for document
$document
.trigger({
type: 'plugin_' + type + '_ready',
container: container,
arguments: arguments,
btns: btns
})
.trigger({
type: 'plugin_ready',
container: container,
arguments: arguments,
btns: btns,
type: type
});
}
/*
* Hides all children fields in a wiki-plugin form and
* add javascript events to display them when the appropriate
* values are selected in the parent fields.
*/
function handlePluginFieldsHierarchy(type) {
var pluginParams = tiki_plugins[type]['params'];
var parents = {};
$.each(pluginParams, function(paramName, paramValues) {
if (paramValues.parent) {
var $parent = $('[name$="params[' + paramValues.parent.name + ']"]', '.wikiplugin_edit');
var $row = $('.wikiplugin_edit').find('#param_' + paramName);
$row.addClass('parent_' + paramValues.parent.name + '_' + paramValues.parent.value);
if ($parent.val() != paramValues.parent.value) {
if (!$parent.val() && $("input, select", $row).val()) {
$parent.val(paramValues.parent.value);
} else {
$row.hide();
}
}
if (!parents[paramValues.parent.name]) {
parents[paramValues.parent.name] = {};
parents[paramValues.parent.name]['children'] = [];
parents[paramValues.parent.name]['parentElement'] = $parent;
}
parents[paramValues.parent.name]['children'].push(paramName);
}
});
$.each(parents, function(parentName, parent) {
parent.parentElement.change(function() {
$.each(parent.children, function() {
$('.wikiplugin_edit #param_' + this).hide();
});
$('.wikiplugin_edit .parent_' + parentName + '_' + this.value).show();
});
});
}
/*
* JS only textarea fullscreen function (for Tiki 5+)
*/
$(function() { // if in translation-diff-mode go fullscreen automatically
if ($("#diff_outer").length && !$.trim($(".wikipreview .wikitext").html()).length) { // but not if previewing (TODO better)
toggleFullScreen("editwiki");
}
});
function sideBySideDiff() {
if ($('.side-by-side-fullscreen').size()) {
$('.side-by-side-fullscreen').remove();
return;
}
var $diff = $('#diff_outer').clone(true, true), $zone = $('.edit-zone');
$('body').append($diff.addClass('side-by-side-fullscreen'));
$diff.find('#diff_history').height('');
if ($diff.size()) {
$diff.css({
position: 'fixed',
top: $zone.css('top'),
bottom: $zone.css('bottom'),
right: 0,
overflow: 'auto',
backgroundColor: 'white',
zIndex: 500000,
opacity: 1
});
$diff.height($zone.height());
$diff.width($(window).width() / 2);
$zone.width($(window).width() / 2);
}
}
function toggleFullScreen(area_id) {
var textarea = $("#" + area_id);
//codemirror interation and preservation
var textareaEditor = syntaxHighlighter.get(textarea);
if (textareaEditor) {
syntaxHighlighter.fullscreen(textarea);
sideBySideDiff();
return;
}
$('.TextArea-fullscreen').add(textarea).css('height', '');
//removes wiki command buttons (save, cancel, preview) from fullscreen view
$('.TextArea-fullscreen .actions').remove();
var textareaParent = textarea.parent().parent().toggleClass('TextArea-fullscreen');
$('body').toggleClass('noScroll');
$('.tabs,.rbox-title').toggle();
if (textareaParent.hasClass('TextArea-fullscreen')) {
var win = $window
.data('cm-resize', true),
screen = $('.TextArea-fullscreen'),
toolbar = $('#editwiki_toolbar');
win.resize(function() {
if (win.data('cm-resize') && screen) {
screen.css('height', win.height() + 'px');
textarea
.css('height', ((win.height() - toolbar.height()) - 30) + 'px');
}
})
.resize();
//adds wiki command buttons (save, cancel, preview) to fullscreen view
$('#role_main .actions').clone().appendTo('.TextArea-fullscreen');
} else {
$window.removeData('cm-resize');
}
sideBySideDiff();
}
/* Simple tiki plugin for jQuery
* Helpers for autocomplete and sheet
*/
var xhrCache = {}, lastXhr; // for jq-ui autocomplete
$.fn.tiki = function(func, type, options) {
var opts = {}, opt;
switch (func) {
case "autocomplete":
if (jqueryTiki.autocomplete) {
if (typeof type === 'undefined') { // func and type given
// setup error - alert here?
return null;
}
options = options || {};
var requestData = {};
var url = "";
switch (type) {
case "pagename":
url = "tiki-listpages.php?listonly";
break;
case "groupname":
url = "tiki-ajax_services.php?listonly=groups";
break;
case "username":
url = "tiki-ajax_services.php?listonly=users";
break;
case "usersandcontacts":
url = "tiki-ajax_services.php?listonly=usersandcontacts";
break;
case "userrealname":
url = "tiki-ajax_services.php?listonly=userrealnames";
break;
case "tag":
url = "tiki-ajax_services.php?listonly=tags&separator=+";
break;
case "icon":
url = "tiki-ajax_services.php?listonly=icons&max=" + (opts.max ? opts.max: 10);
opts.formatItem = function(data, i, n, value) {
var ps = value.lastIndexOf("/");
var pd = value.lastIndexOf(".");
return "<img src='" + value + "' /> " + value.substring(ps + 1, pd).replace(/_/m, " ");
};
opts.formatResult = function(data, value) {
return value;
};
break;
case 'trackername':
url = "tiki-ajax_services.php?listonly=trackername";
break;
case 'trackervalue':
if (typeof options.fieldId === "undefined") {
// error
return null;
}
$.extend( requestData, options );
options = {};
url = "list-tracker_field_values_ajax.php";
break;
}
$.extend( opts, { // default options for autocompletes in tiki
minLength: 2,
source: function( request, response ) {
if (options.tiki_replace_term) {
request.term = options.tiki_replace_term.apply(null, [request.term]);
}
var cacheKey = "ac." + type + "." + request.term;
if ( cacheKey in xhrCache ) {
response( xhrCache[ cacheKey ] );
return;
}
request.q = request.term;
$.extend( request, requestData );
lastXhr = $.getJSON( url, request, function( data, status, xhr ) {
xhrCache[ cacheKey ] = data;
if ( xhr === lastXhr ) {
response( data );
}
});
}
});
$.extend(opts, options);
return this.each(function() {
$(this).autocomplete(opts).blur( function() {$(this).removeClass( "ui-autocomplete-loading" );});
// .click( function () {
// $(".ac_results").hide(); // hide the drop down if input clicked on again
// });
});
}
break;
case "carousel":
if (jqueryTiki.carousel) {
opts = {
imagePath: "lib/jquery/infinitecarousel/images/",
autoPilot: true
};
$.extend(opts, options);
return this.each(function() {
$(this).infiniteCarousel(opts);
});
}
break;
case "datepicker":
case "datetimepicker":
if (jqueryTiki.ui) {
switch (type) {
case "jscalendar": // replacements for jscalendar
// timestamp result goes in the options.altField
if (typeof options.altField === "undefined") {
alert("jQuery.ui datepicker jscalendar replacement setup error: options.altField not set for " + $(this).attr("id"));
debugger;
}
opts = {
showOn: "both",
buttonImage: "img/icons/calendar.png",
buttonImageOnly: true,
dateFormat: "yy-mm-dd",
showButtonPanel: true,
altFormat: "@",
onClose: function(dateText, inst) {
$.datepicker._updateAlternate(inst); // make sure the hidden field is up to date
var timestamp = parseInt($(inst.settings.altField).val() / 1000, 10);
if (!timestamp) {
$.datepicker._setDateFromField(inst); // seems to need reminding when starting empty
$.datepicker._updateAlternate(inst);
timestamp = parseInt($(inst.settings.altField).val() / 1000, 10);
}
if (timestamp && inst.settings && inst.settings.timepicker) { // if it's a datetimepicker add on the time
var time = inst.settings.timepicker.hour * 3600 +
inst.settings.timepicker.minute * 60 +
inst.settings.timepicker.second;
timestamp += time;
}
$(inst.settings.altField).val(timestamp ? timestamp : "");
}
};
break;
default:
opts = {
showOn: "both",
buttonImage: "img/icons/calendar.png",
buttonImageOnly: true,
dateFormat: "yy-mm-dd",
showButtonPanel: true,
firstDay: jqueryTiki.firstDayofWeek
};
break;
}
$.extend(opts, options);
if (func === "datetimepicker") {
return this.each(function() {
$(this).datetimepicker(opts);
});
} else {
return this.each(function() {
$(this).datepicker(opts);
});
}
}
break;
case "accordion":
if (jqueryTiki.ui) {
opts = {
autoHeight: false,
collapsible: true,
navigation: true
// change: function(event, ui) {
// // sadly accordion active property is broken in 1.7, but fix is coming in 1.8 so TODO
// setCookie(ui, ui.options.active, "accordion");
// }
};
$.extend(opts, options);
return this.each(function() {
$(this).accordion(opts);
});
}
break;
case "selectmenu":
if (jqueryTiki.selectmenu) {
opts = {
style: 'dropdown',
wrapperElement: "<span />"
};
$.extend(opts, options);
return this.each(function() {
$(this).selectmenu(opts);
});
}
break;
} // end switch(func)
};
/******************************
* Functions for dialog tools *
******************************/
// shared
window.dialogData = [];
var dialogDiv;
function displayDialog( ignored, list, area_id ) {
var i, item, el, obj, tit = "";
var $is_cked = $('#cke_contents_' + area_id).length !== 0;
if (!dialogDiv) {
dialogDiv = document.createElement('div');
document.body.appendChild( dialogDiv );
}
$(dialogDiv).empty();
for( i = 0; i < window.dialogData[list].length; i++ ) {
item = window.dialogData[list][i];
if (item.indexOf("<") === 0) { // form element
el = $(item);
$(dialogDiv).append( el );
} else if (item.indexOf("{") === 0) {
try {
//obj = JSON.parse(item); // safer, but need json2.js lib
obj = eval("("+item+")");
} catch (e) {
alert(e.name + ' - ' + e.message);
}
} else if (item.length > 0) {
tit = item;
}
}
// Selection will be unavailable after context menu shows up - in IE, lock it now.
if ( typeof CKEDITOR !== "undefined" && CKEDITOR.env.ie ) {
var editor = CKEDITOR.instances[area_id];
var selection = editor.getSelection();
if (selection) {selection.lock();}
} else if ($("#" + area_id)[0].createTextRange) { // save selection for IE
storeTASelection(area_id);
}
if (!obj) { obj = {}; }
if (!obj.width) {obj.width = 210;}
obj.bgiframe = true;
obj.autoOpen = false;
obj.zIndex = 10000;
try {
if ($(dialogDiv).dialog) {
$(dialogDiv).dialog('destroy');
}
} catch( e ) {
// IE throws errors destroying a non-existant dialog
}
$(dialogDiv).dialog(obj).dialog('option', 'title', tit).dialog('open');
return false;
}
window.pickerData = [];
var pickerDiv = {};
function displayPicker( closeTo, list, area_id, isSheet, styleType ) {
$('div.toolbars-picker').remove(); // simple toggle
var $closeTo = $(closeTo);
if ($closeTo.hasClass('toolbars-picker-open')) {
$('.toolbars-picker-open').removeClass('toolbars-picker-open');
return false;
}
$closeTo.addClass('toolbars-picker-open');
var textarea = $('#' + area_id);
var coord = $closeTo.offset();
coord.bottom = coord.top + $closeTo.height();
pickerDiv = $('<div class="toolbars-picker ' + list + '" />')
.css('left', coord.left + 'px')
.css('top', (coord.bottom + 8) + 'px')
.appendTo('body');
var prepareLink = function(ins, disp ) {
disp = $(disp);
var link = $( '<a href="#" />' ).append(disp);
if (disp.attr('reset') && isSheet) {
var bgColor = $('div.tiki_sheet:first').css(styleType);
var color = $('div.tiki_sheet:first').css(styleType == 'color' ? 'background-color' : 'color');
disp
.css('background-color', bgColor)
.css('color', color);
link
.addClass('toolbars-picker-reset');
}
if ( isSheet ) {
link
.click(function() {
var I = $(closeTo).attr('instance');
I = parseInt( I ? I : 0, 10 );
if (disp.attr('reset')) {
$.sheet.instance[I].cellChangeStyle(styleType, '');
} else {
$.sheet.instance[I].cellChangeStyle(styleType, disp.css('background-color'));
}
$closeTo.click();
return false;
});
} else {
link.click(function() {
insertAt(area_id, ins);
var textarea = $('#' + area_id);
// quick fix for Firefox 3.5 losing selection on changes to popup
if (typeof textarea.selectionStart != 'undefined') {
var tempSelectionStart = textarea.selectionStart;
var tempSelectionEnd = textarea.selectionEnd;
}
$closeTo.click();
// quick fix for Firefox 3.5 losing selection on changes to popup
if (typeof textarea.selectionStart != 'undefined' && textarea.selectionStart != tempSelectionStart) {
textarea.selectionStart = tempSelectionStart;
}
if (typeof textarea.selectionEnd != 'undefined' && textarea.selectionEnd != tempSelectionEnd) {
textarea.selectionEnd = tempSelectionEnd;
}
return false;
});
}
return link;
};
var chr, $a;
for( var i in window.pickerData[list] ) {
chr = window.pickerData[list][i];
if (list === "specialchar") {
chr = $("<span>" + chr + "</span>");
}
$a = prepareLink( i, chr );
if ($a.length) {
pickerDiv.append($a);
}
}
return false;
}
function dialogSelectElement( area_id, elementStart, elementEnd ) {
if ($('#cke_contents_' + area_id).length !== 0) {return;} // TODO for ckeditor
var $textarea = $('#' + area_id);
var textareaEditor = syntaxHighlighter.get($textarea);
var val = ( textareaEditor ? textareaEditor.getValue() : $textarea.val() );
var pairs = [], pos = 0, s = 0, e = 0;
while (s > -1 && e > -1) { // positions of start/end markers
s = val.indexOf(elementStart, e);
if (s > -1) {
e = val.indexOf(elementEnd, s + elementStart.length);
if (e > -1) {
e += elementEnd.length;
pairs[pairs.length] = [ s, e ];
}
}
}
(textareaEditor ? textareaEditor : $textarea[0]).focus();
var selection = ( textareaEditor ? syntaxHighlighter.selection(textareaEditor, true) : $textarea.selection() );
s = selection.start;
e = selection.end;
var st = $textarea.attr('scrollTop');
for (var i = 0; i < pairs.length; i++) {
if (s >= pairs[i][0] && e <= pairs[i][1]) {
setSelectionRange($textarea[0], pairs[i][0], pairs[i][1]);
break;
}
}
}
function dialogSharedClose( area_id, dialog ) {
$(dialog).dialog("close");
}
// Internal Link
function dialogInternalLinkOpen( area_id ) {
$("#tbWLinkPage").tiki("autocomplete", "pagename");
dialogSelectElement( area_id, '((', '))' ) ;
var s = getTASelection($('#' + area_id)[0]);
var m = /\((.*)\(([^\|]*)\|?([^\|]*)\|?([^\|]*)\|?\)\)/g.exec(s);
if (m && m.length > 4) {
if ($("#tbWLinkRel")) {
$("#tbWLinkRel").val(m[1]);
}
$("#tbWLinkPage").val(m[2]);
if (m[4]) {
if ($("#tbWLinkAnchor")) {
$("#tbWLinkAnchor").val(m[3]);
}
$("#tbWLinkDesc").val(m[4]);
} else {
$("#tbWLinkDesc").val(m[3]);
}
} else {
$("#tbWLinkDesc").val(s);
if ($("#tbWLinkAnchor")) {
$("#tbWLinkAnchor").val("");
}
}
}
function dialogInternalLinkInsert( area_id, dialog ) {
if (!$("#tbWLinkPage").val()) {
alert(tr("Please enter a page name"));
return;
}
var s = "(";
if ($("#tbWLinkRel") && $("#tbWLinkRel").val()) {
s += $("#tbWLinkRel").val();
}
s += "(" + $("#tbWLinkPage").val();
if ($("#tbWLinkAnchor") && $("#tbWLinkAnchor").val()) {
s += "|" + ($("#tbWLinkAnchor").val().indexOf("#") !== 0 ? "#" : "") + $("#tbWLinkAnchor").val();
}
if ($("#tbWLinkDesc").val()) {
s += "|" + $("#tbWLinkDesc").val();
}
s += "))";
insertAt(area_id, s, false, false, true);
dialogSharedClose( area_id, dialog );
}
// External Link
function dialogExternalLinkOpen( area_id ) {
$("#tbWLinkPage").tiki("autocomplete", "pagename");
dialogSelectElement( area_id, '[', ']' ) ;
var s = getTASelection($('#' + area_id)[0]);
var m = /\[([^\|]*)\|?([^\|]*)\|?([^\|]*)\]/g.exec(s);
if (m && m.length > 3) {
$("#tbLinkURL").val(m[1]);
$("#tbLinkDesc").val(m[2]);
if (m[3]) {
if ($("#tbLinkNoCache") && m[3] == "nocache") {
$("#tbLinkNoCache").attr("checked", "checked");
} else {
$("#tbLinkRel").val(m[3]);
}
} else {
$("#tbWLinkDesc").val(m[3]);
}
} else {
if (s.match(/(http|https|ftp)([^ ]+)/ig) == s) { // v simple URL match
$("#tbLinkURL").val(s);
} else {
$("#tbLinkDesc").val(s);
}
}
if (!$("#tbLinkURL").val()) {
$("#tbLinkURL").val("http://");
}
}
function dialogExternalLinkInsert(area_id, dialog) {
var s = "[" + $("#tbLinkURL").val();
if ($("#tbLinkDesc").val()) {
s += "|" + $("#tbLinkDesc").val();
}
if ($("#tbLinkRel").val()) {
s += "|" + $("#tbLinkRel").val();
}
if ($("#tbLinkNoCache") && $("#tbLinkNoCache").attr("checked")) {
s += "|nocache";
}
s += "]";
insertAt(area_id, s, false, false, true);
dialogSharedClose( area_id, dialog );
}
// Table
function dialogTableOpen(area_id, dialog) {
dialogSelectElement( area_id, '||', '||' ) ;
dialog = $(dialog);
var s = getTASelection($('#' + area_id)[0]);
var m = /\|\|([\s\S]*?)\|\|/mg.exec(s);
var vals = [], rows = 3, cols = 3, c, r, i, j;
if (m) {
m = m[1];
m = m.split("\n");
rows = 0;
cols = 1;
for (i = 0; i < m.length; i++) {
var a2 = m[i].split("|");
var a = [];
for (j = 0; j < a2.length; j++) { // links can have | chars in
if (a2[j].indexOf("[") > -1 && a2[j].indexOf("[[") == -1 && a2[j].indexOf("]") == -1) { // external link
a[a.length] = a2[j];
j++;
var k = true;
while (j < a2.length && k) {
a[a.length - 1] += "|" + a2[j];
if (a2[j].indexOf("]") > -1) { // closed
k = false;
} else {
j++;
}
}
} else if (a2[j].search(/\(\S*\(/) > -1 && a2[j].indexOf("))") == -1) {
a[a.length] = a2[j];
j++;
k = true;
while (j < a2.length && k) {
a[a.length - 1] += "|" + a2[j];
if (a2[j].indexOf("))") > -1) { // closed
k = false;
} else {
j++;
}
}
} else {
a[a.length] = a2[j];
}
}
vals[vals.length] = a;
if (a.length > cols) {
cols = a.length;
}
if (a.length) {
rows++;
}
}
}
for (r = 1; r <= rows; r++) {
for (c = 1; c <= cols; c++) {
var v = "";
if (vals.length) {
if (vals[r - 1] && vals[r - 1][c - 1]) {
v = vals[r - 1][c - 1];
} else {
v = " ";
}
} else {
v = " "; //row " + r + ",col " + c + "";
}
var el = $("<input type=\"text\" id=\"tbTableR" + r + "C" + c + "\" class=\"ui-widget-content ui-corner-all\" size=\"10\" style=\"width:" + (90 / cols) + "%\" />")
.val($.trim(v))
.appendTo(dialog);
}
if (r == 1) {
el = $("<img src=\"img/icons/add.png\" />")
.click(function() {
dialog.data("cols", dialog.data("cols") + 1);
for (r = 1; r <= dialog.data("rows"); r++) {
v = "";
var el = $("<input type=\"text\" id=\"tbTableR" + r + "C" + dialog.data("cols") + "\" class=\"ui-widget-content ui-corner-all\" size=\"10\" style=\"width:" + (90 / dialog.data("cols")) + "%\" />")
.val(v);
$("#tbTableR" + r + "C" + (dialog.data("cols") - 1)).after(el);
}
dialog.find("input").width(90 / dialog.data("cols") + "%");
})
.appendTo(dialog);
}
dialog.append("<br />");
}
el = $("<img src=\"img/icons/add.png\" />")
.click(function() {
dialog.data("rows", dialog.data("rows") + 1);
for (c = 1; c <= dialog.data("cols"); c++) {
v = "";
var el = $("<input type=\"text\" id=\"tbTableR" + dialog.data("rows") + "C" + c + "\" class=\"ui-widget-content ui-corner-all\" size=\"10\" value=\"" + v + "\" style=\"width:" + (90 / dialog.data("cols")) + "%\" />")
.insertBefore(this);
}
$(this).before("<br />");
dialog.dialog("option", "height", (dialog.data("rows") + 1) * 1.2 * $("#tbTableR1C1").height() + 130);
})
.appendTo(dialog);
dialog
.data('rows', rows)
.data('cols', cols)
.dialog("option", "width", (cols + 1) * 120 + 50)
.dialog("option", "position", "center");
$("#tbTableR1C1").focus();
}
function dialogTableInsert(area_id, dialog) {
var s = "||", rows, cols, c, r, rows2 = 1, cols2 = 1;
dialog = $(dialog);
rows = dialog.data('rows') || 3;
cols = dialog.data('cols') || 3;
for (r = 1; r <= rows; r++) {
for (c = 1; c <= cols; c++) {
if ($.trim($("#tbTableR" + r + "C" + c).val())) {
if (r > rows2) {
rows2 = r;
}
if (c > cols2) {
cols2 = c;
}
}
}
}
for (r = 1; r <= rows2; r++) {
for (c = 1; c <= cols2; c++) {
var tableData = $("#tbTableR" + r + "C" + c).val();
s += tableData;
if (c < cols2) {
s += (tableData ? '|' : ' | ');
}
}
if (r < rows2) {
s += "\n";
}
}
s += "||";
insertAt(area_id, s, false, false, true);
dialogSharedClose( area_id, dialog );
}
// Find
function dialogFindOpen(area_id) {
var s = getTASelection($('#' + area_id)[0]);
$("#tbFindSearch").val(s).focus();
}
function dialogFindFind( area_id ) {
var ta = $('#' + area_id);
var findInput = $("#tbFindSearch").removeClass("ui-state-error");
var $textareaEditor = syntaxHighlighter.get(ta); //codemirror functionality
if ($textareaEditor) {
syntaxHighlighter.find($textareaEditor, findInput.val());
}
else { //standard functionality
var s, opt, str, re, p = 0, m;
s = findInput.val();
opt = "";
if ($("#tbFindCase").attr("checked")) {
opt += "i";
}
str = ta.val();
re = new RegExp(s, opt);
p = getCaretPos(ta[0]);
if (p && p < str.length) {
m = re.exec(str.substring(p));
}
else {
p = 0;
}
if (!m) {
m = re.exec(str);
p = 0;
}
if (m) {
setSelectionRange(ta[0], m.index + p, m.index + s.length + p);
}
else {
findInput.addClass("ui-state-error");
}
}
}
// Replace
function dialogReplaceOpen(area_id) {
var s = getTASelection($('#' + area_id)[0]);
$("#tbReplaceSearch").val(s).focus();
}
function dialogReplaceReplace( area_id ) {
var findInput = $("#tbReplaceSearch").removeClass("ui-state-error");
var s = findInput.val();
var r = $("#tbReplaceReplace").val();
var opt = "";
if ($("#tbReplaceAll").attr("checked")) {
opt += "g";
}
if ($("#tbReplaceCase").attr("checked")) {
opt += "i";
}
var ta = $('#' + area_id);
var str = ta.val();
var re = new RegExp(s,opt);
var textareaEditor = syntaxHighlighter.get(ta); //codemirror functionality
if (textareaEditor) {
syntaxHighlighter.replace(textareaEditor, s, r);
}
else { //standard functionality
ta.val(str.replace(re, r));
}
}
(function($) {
/**
* Adds annotations to the content of text in ''container'' based on the
* content found in selected dts.
*
* Used in comments.tpl
*/
$.fn.addnotes = function( container ) {
return this.each(function(){
var comment = this;
var text = $('dt:contains("note")', comment).next('dd').text();
var title = $('h6:first', comment).clone();
var body = $('.body:first', comment).clone();
body.find('dt:contains("note")').closest('dl').remove();
if( text.length > 0 ) {
var parents = container.find(':contains("' + text + '")').parent();
var node = container.find(':contains("' + text + '")').not(parents)
.addClass('note-editor-text')
.each( function() {
var child = $('dl.note-list',this);
if( ! child.length ) {
child = $('<dl class="note-list"/>')
.appendTo(this)
.hide();
$(this).click( function() {
child.toggle();
} );
}
child.append( title )
.append( $('<dd/>').append(body) );
} );
}
});
};
/**
* Convert a zone to a note editor by attaching handlers on mouse events.
*/
$.fn.noteeditor = function (editlink, link) {
var hiddenParents = null;
var annote = $(link)
.click( function( e ) {
e.preventDefault();
var $block = $('<div/>');
var annotation = $(this).attr('annotation');
$(this).fadeOut(100);
$block.load(editlink.attr('href'), function () {
var msg = "";
if (annotation.length < 20) {
msg = tr("The text you have selected is quite short. Select a longer piece to ensure the note is associated with the correct text.") + "<br />";
}
msg = "<p class='description comment-info'>" + msg + tr("Tip: Leave the first line as it is, starting with \";note:\". This is required") + "</p>";
$block.prepend($(msg));
$('textarea', this)
.val(';note:' + annotation + "\n\n").focus();
$('form', this).submit(function () {
$.post($(this).attr('action'), $(this).serialize(), function () {
$block.dialog('destroy');
});
return false;
});
$block.dialog({
modal: true,
width: 500,
height: 400
});
});
} )
.appendTo(document.body);
$(this).mouseup(function( e ) {
var range;
if( window.getSelection && window.getSelection().rangeCount ) {
range = window.getSelection().getRangeAt(0);
} else if( window.selection ) {
range = window.selection.getRangeAt(0);
}
if( range ) {
var str = $.trim( range.toString() );
if( str.length && -1 === str.indexOf( "\n" ) ) {
annote.attr('annotation', str);
annote.fadeIn(100).position( {
of: e,
at: 'bottom left',
my: 'top left',
offset: '20 20'
} );
} else {
if (annote.css("display") != "none") {
annote.fadeOut(100);
}
if ($("form.comments").css("display") == "none") {
$("form.comments").show();
}
if (hiddenParents) {
hiddenParents.hide();
hiddenParents = null;
}
}
}
});
};
$.fn.browse_tree = function () {
this.each(function () {
$('.treenode:not(.done)', this)
.addClass('done')
.each(function () {
if (getCookie($('ul:first', this).attr('data-id'), $('ul:first', this).attr('data-prefix')) !== 'o') {
$('ul:first', this).css('display', 'none');
}
if ($('ul:first', this).length) {
var dir = $('ul:first', this).css('display') === 'block' ? 's' : 'e';
$(this).prepend('<span class="flipper ui-icon ui-icon-triangle-1-' + dir + '" style="float: left;"/>');
} else {
$(this).prepend('<span style="float:left;width:16px;height:16px;"/>');
}
});
$('.flipper:not(.done)')
.addClass('done')
.css('cursor', 'pointer')
.click(function () {
var body = $(this).parent().find('ul:first');
if ('block' === body.css('display')) {
$(this).removeClass('ui-icon-triangle-1-s').addClass('ui-icon-triangle-1-e');
body.hide('fast');
setCookie(body.data("id"), "", body.data("prefix"));
} else {
$(this).removeClass('ui-icon-triangle-1-e').addClass('ui-icon-triangle-1-s');
body.show('fast');
setCookie(body.data("id"), "o", body.data("prefix"));
}
});
});
return this;
};
var fancy_filter_create_token = function(value, label) {
var close, token;
close = $('<span class="ui-icon ui-icon-close"/>')
.click(function () {
var ed = $(this).parent().parent();
$(this).parent().remove();
ed.change();
return false;
});
token = $('<span class="token"/>')
.attr('data-value', value)
.text(label)
.attr('contenteditable', false)
.disableSelection()
.append(close);
return token[0];
};
var fancy_filter_build_init = function(editable, str, options) {
if (str === '') {
str = ' ';
}
editable.html(str.replace(/(\d+)/g, '<span>$1</span>'));
if (options && options.map) {
editable.find('span').each(function () {
var val = $(this).text();
$(this).replaceWith(fancy_filter_create_token(val, options.map[val] ? options.map[val] : val));
});
}
};
$jq.fn.fancy_filter = function (operation, options) {
this.each(function () {
switch (operation) {
case 'init':
var editable = $('<div class="fancyfilter"/>'), input = this;
if (editable[0].contentEditable !== null) {
fancy_filter_build_init(editable, $(this).val(), options);
editable.attr('contenteditable', true);
$(this).after(editable).hide();
}
editable
.keyup(function() {
$(this).change();
$(this).mouseup();
})
.change(function () {
$(input).val($('<span/>')
.html(editable.html())
.find('span').each(function() {
$(this).replaceWith(' ' + $(this).attr('data-value') + ' ');
})
.end().text().replace(/\s+/g, ' '));
})
.mouseup(function () {
input.lastRange = window.getSelection().getRangeAt(0);
});
break;
case 'add':
var node = fancy_filter_create_token(options.token, options.label);
if (this.lastRange) {
this.lastRange.deleteContents();
this.lastRange.insertNode(node);
this.lastRange.insertNode(document.createTextNode(options.join));
} else {
$(this).next().append(options.join).append(node);
}
$(this).next().change();
break;
}
});
return this;
};
$.fn.drawGraph = function () {
this.each(function () {
var $this = $(this);
var width = $this.width();
var height = Math.ceil( width * 9 / 16 );
var nodes = $this.data('graph-nodes');
var edges = $this.data('graph-edges');
var g = new Graph;
$.each(nodes, function (k, i) {
g.addNode(i);
});
$.each(edges, function (k, i) {
var style = { directed: true };
if( i.preserve ) {
style.color = 'red';
}
g.addEdge( i.from, i.to, style );
});
var layouter = new Graph.Layout.Spring(g);
layouter.layout();
var renderer = new Graph.Renderer.Raphael($this.attr('id'), g, width, height );
renderer.draw();
});
return this;
};
/**
* Handle textarea and input text selections
* Code from:
*
* jQuery Autocomplete plugin 1.1
* Copyright (c) 2009 Jörn Zaefferer
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* Now deprecated and replaced in Tiki 7 by jquery-ui autocomplete
*/
$.fn.selection = function(start, end) {
if (start !== undefined) {
if (end === undefined) {
end = start;
}
return this.each(function() {
if( this.createTextRange ){
var selRange = this.createTextRange();
if (start == end) {
selRange.move("character", start);
selRange.select();
} else {
selRange.collapse(true);
selRange.moveStart("character", start);
selRange.moveEnd("character", end - start); // moveEnd is relative
selRange.select();
}
} else if( this.setSelectionRange ){
this.setSelectionRange(start, end);
} else if( this.selectionStart ){
this.selectionStart = start;
this.selectionEnd = end;
}
});
}
var field = this[0];
if ( field.createTextRange ) {
// from http://the-stickman.com/web-development/javascript/finding-selection-cursor-position-in-a-textarea-in-internet-explorer/
// The current selection
var range = document.selection.createRange();
// We'll use this as a 'dummy'
var stored_range = range.duplicate();
// Select all text
stored_range.moveToElementText( field );
// Now move 'dummy' end point to end point of original range
stored_range.setEndPoint( 'EndToEnd', range );
// Now we can calculate start and end points
var selectionStart = stored_range.text.length - range.text.length;
var selectionEnd = selectionStart + range.text.length;
return {
start: selectionStart,
end: selectionEnd
}
} else if( field.selectionStart !== undefined ){
return {
start: field.selectionStart,
end: field.selectionEnd
}
}
};
$.fn.comment_toggle = function () {
this.each(function () {
var $target = $(this.hash);
$target.hide();
$(this).click(function () {
if ($target.is(':visible')) {
$target.hide(function () {
$(this).empty();
});
} else {
$target.comment_load($(this).attr('href'));
}
return false;
});
if (location.search.indexOf("comzone=show") > -1) {
var comButton = this;
setTimeout(function() {
$(comButton).click();
}, 500);
}
});
return this;
};
$.fn.comment_load = function (url) {
$('#top .note-list').remove();
this.each(function () {
var comment_container = this;
$(this).load(url, function (response, status) {
$(this).show();
$('.comment.inline dt:contains("note")', this)
.closest('.comment')
.addnotes( $('#top') );
if(jqueryTiki.useInlineComment) {
$('#top').noteeditor($('.comment-form:last a', comment_container), '#note-editor-comment');
}
$(this).on('click', '.comment-form > a', function () {
$('.comment-form form').each(function() { // remove other forms
var $p = $(this).parent();
$p.empty().addClass('button').append($p.data('previous'));
});
$(this).parent().data('previous', $(this)).empty().removeClass('button').load($(this).attr('href'), function () {
var form = $('form', this).submit(function () {
var errors;
$.post(form.attr('action'), $(this).serialize(), function (data, st) {
if (data.threadId) {
$(comment_container).empty().comment_load(url);
$comm_counter = $('span.count_comments');
if ($comm_counter.length != 0) {
var comment_count = parseInt($comm_counter.text()) + 1;
$comm_counter.text(comment_count);
}
} else {
errors = $('ol.errors', form).empty();
if (! errors.length) {
$(':submit', form).after(errors = $('<ol class="errors"/>'));
}
$.each(data.errors, function (k, v) {
errors.append($('<li/>').text(v));
});
}
}, 'json');
return false;
});
//allow syntax highlighting
if ($.fn.flexibleSyntaxHighlighter) {
// console.log(form.find('textarea.wikiedit'));
form.find('textarea.wikiedit').flexibleSyntaxHighlighter();
}
});
return false;
});
$('.button.comment-form.autoshow a').click(); // allow autoshowing of comment forms through autoshow css class
$('.confirm-prompt', this).requireConfirm({
success: function (data) {
if (data.status === 'DONE') {
$(comment_container).empty().comment_load(url);
$comm_counter = $('span.count_comments');
if ($comm_counter.length != 0) {
var comment_count = parseInt($comm_counter.text()) - 1;
$comm_counter.text(comment_count);
}
}
}
});
var match = location.hash.match(/threadId(\d+)/);
if (match) {
var $comment = $(".comment[data-comment-thread-id=" + match[1] + "]");
var top = $comment.offset().top + $comment.height() - $window.height();
$('html, body').animate({
scrollTop: top
}, 2000);
}
});
});
return this;
};
$.fn.input_csv = function (operation, separator, value) {
this.each(function () {
var values = $(this).val().split(separator);
if (values[0] === '') {
values.shift();
}
if (operation === 'add') {
values.push(value);
} else if (operation === 'delete') {
value = String(value);
while (-1 !== $.inArray(value, values)) {
values.splice($.inArray(value, values), 1);
}
}
$(this).val(values.join(separator));
});
return this;
};
$.service = function (controller, action, query) {
var append = '';
if (query) {
append = '?' + $.map(query, function (v, k) {
return k + '=' + escape(v);
}).join('&');
}
if (action) {
return 'tiki-' + controller + '-' + action + append;
} else {
return 'tiki-' + controller + append;
}
};
$.fn.serviceDialog = function (options) {
this.each(function () {
var $dialog = $('<div/>'), origin = this, buttons = {};
$(this).append($dialog).data('serviceDialog', $dialog);
if (! options.hideButtons) {
buttons[tr('OK')] = function () {
$dialog.find('form:visible').submit();
};
buttons[tr('Cancel')] = function () {
$dialog
.dialog('close')
.dialog('destroy');
};
}
$dialog.dialog({
title: options.title,
minWidth: options.width ? options.width : 500,
height: (options.fullscreen ? $window.height() - 20 : (options.height ? options.height : 600)),
width: (options.fullscreen ? $window.width() - 20 : null),
close: function () {
if (options.close) {
options.close.apply([], this);
}
$(this).dialog('destroy').remove();
},
buttons: buttons,
modal: options.modal,
zIndex: options.zIndex
});
$dialog.loadService(options.data, $.extend(options, {origin: origin}));
});
return this;
};
$.fn.loadService = function (data, options) {
var $dialog = this, controller = options.controller, action = options.action, url;
if (typeof data === "string") { // TODO better and refactor
data = JSON.parse('{"' + tiki_decodeURIComponent(data.replace(/&/g, "\",\"").replace(/=/g,"\":\"")).replace(/[\n\r]/g, "") + '"}');
}
if (data && data.controller) {
controller = data.controller;
}
if (data && data.action) {
action = data.action;
}
if (options.origin && $(options.origin).is('a')) {
url = $(options.origin).attr('href');
} else {
url = $.service(controller, action);
}
$dialog.modal(tr("Loading..."));
$.ajax(url, {
data: data,
error: function (jqxhr) {
$dialog.html(jqxhr.responseText);
},
success: function (data) {
$dialog.html(data);
$dialog.find('.ajax').click(function (e) {
$dialog.loadService(null, {origin: this});
return false;
});
$dialog.find('form .submit').hide();
$dialog.find('form:not(.no-ajax)').unbind("submit").submit(function (e) {
var form = this, act;
act = $(form).attr('action');
if (! act) {
act = url;
}
if (typeof $(form).valid === "function") {
if (!$(form).valid()) {
return false;
} else if ($(form).validate().pendingRequest > 0) {
$(form).validate();
setTimeout(function() {$(form).submit();}, 500);
return false;
}
}
$.ajax(act, {
type: 'POST',
dataType: 'json',
data: $(form).serialize(),
success: function (data) {
data = (data ? data : {});
if (data.FORWARD) {
$dialog.loadService(data.FORWARD, options);
} else {
$dialog.dialog('destroy');
}
if (options.success) {
options.success.apply(options.origin, [data]);
}
},
error: function (jqxhr) {
$(form.name).showError(jqxhr);
}
});
return false;
});
if (options.load) {
options.load.apply($dialog[0], [data]);
}
$('.confirm-prompt', this).requireConfirm({
success: function (data) {
if (data.FORWARD) {
$dialog.loadService(data.FORWARD, options);
} else {
$dialog.loadService(options.data, options);
}
}
});
},
complete: function () {
$dialog.modal();
if ($dialog.find('form').size() == 0) {
// If the result contains no form, skip OK/Cancel, and just allow to close
var buttons = $dialog.dialog('option', 'buttons'), n = {};
n[tr('OK')] = buttons[tr('Cancel')];
$dialog.dialog('option', 'buttons', n);
}
}
});
};
$.fn.requireConfirm = function (options) {
this.click(function (e) {
e.preventDefault();
var message = options.message, link = this;
if (! message) {
message = $(this).data('confirm');
}
if (confirm (message)) {
$.ajax($(this).attr('href'), {
type: 'POST',
dataType: 'json',
data: {
'confirm': 1
},
success: function (data) {
options.success.apply(link, [data]);
},
error: function (jqxhr) {
$(link).closest('form').showError(jqxhr);
}
});
}
return false;
});
return this;
};
$.fn.showError = function (message) {
if (message.responseText) {
var data = $.parseJSON(message.responseText);
message = data.message;
}
this.each(function () {
var validate = $(this).closest('form').validate(), errors = {}, field;
if (validate) {
if (! $(this).attr('name')) {
$(this).attr('name', $(this).attr('id'));
}
field = $(this).attr('name');
if (!field) { // element without name or id can't show errors
return;
}
var parts;
if (parts = message.match(/^<!--field\[([^\]]+)\]-->(.*)$/)) {
field = parts[1];
message = parts[2];
}
errors[field] = message;
validate.showErrors(errors);
setTimeout(function () {
$('#error_report li').filter(function () {
return $(this).text() === message;
}).remove();
if ($('#error_report ul').is(':empty')) {
$('#error_report').empty();
}
}, 100);
}
});
return this;
};
$.fn.clearError = function () {
this.each(function () {
$(this).closest('form').find('label.error[for="' + $(this).attr('name') + '"]').remove();
});
return this;
};
$.fn.object_selector = function (filter, threshold) {
var input = this;
this.each(function () {
var $spinner = $(this).parent().modal(" ");
$.getJSON('tiki-searchindex.php', {
filter: filter
}, function (data) {
var $select = $('<select/>'), $autocomplete = $('<input type="text"/>');
$(input).wrap('<div class="object_selector"/>');
$(input).hide();
$select.append('<option/>');
$.each(data, function (key, value) {
$select.append($('<option/>').attr('value', value.object_type + ':' + value.object_id).text(value.title));
});
$(input).after($select);
$select.change(function () {
$(input).data('label', $select.find('option:selected').text());
$(input).val($select.val()).change();
});
if (jqueryTiki.selectmenu) {
var $hidden = $select.parents("fieldset:hidden:last").show();
$select.css("font-size", $.browser.webkit ? "1.4em" : "1.1em") // not sure why webkit is so different, it just is :(
.attr("id", input.attr("id") + "_sel") // bug in selectmenu when no id
.tiki("selectmenu");
$hidden.hide();
}
$spinner.modal();
if ($select.children().length > threshold) {
var filterField = $('<input type="text"/>').width(120).css('marginRight', '1em');
$(input).after(filterField);
filterField.wrap('<label/>').before(tr('Search:')+ ' ');
filterField.keypress(function (e) {
var field = this;
if (e.which === 0 || e.which === 13) {
return false;
}
if (this.searching) {
clearTimeout(this.searching);
this.searching = null;
}
if (this.ajax) {
this.ajax.abort();
this.ajax = null;
$spinner.modal();
}
if (jqueryTiki.selectmenu) {
$select.selectmenu('open');
$(field).focus();
}
this.searching = setTimeout(function () {
var loaded = $(field).val();
if (!loaded || loaded === " ") { // let them get the whole list back?
loaded = "*";
}
if ((loaded === "*" || loaded.length >= 3) && loaded !== $select.data('loaded')) {
$spinner = $(field).parent().modal(" ");
field.ajax = $.getJSON('tiki-searchindex.php', {
filter: $.extend(filter, {autocomplete: loaded})
}, function (data) {
$select.empty();
$select.data('loaded', loaded);
$select.append('<option/>');
$.each(data, function (key, value) {
$select.append($('<option/>').attr('value', value.object_type + ':' + value.object_id).text(value.title));
});
if (jqueryTiki.selectmenu) {
$select.tiki("selectmenu");
$select.selectmenu('open');
$(field).focus();
}
$spinner.modal();
});
}
}, 500);
});
}
});
});
return this;
};
$.fn.sortList = function () {
var list = $(this), items = list.children('li').get();
items.sort(function(a, b) {
var compA = $(a).text().toUpperCase();
var compB = $(b).text().toUpperCase();
return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
})
$.each(items, function(idx, itm) {
list.append(itm);
});
};
$.localStorage = {
store: function (key, value) {
if (window.localStorage) {
window.localStorage[key] = $.toJSON(favoriteList);
}
},
load: function (key, callback, fetch) {
if (window.localStorage && window.localStorage[key]) {
callback($.parseJSON(window.localStorage[key]));
} else {
fetch(function (data) {
window.localStorage[key] = $.toJSON(data);
callback(data);
});
}
}
};
var favoriteList = [];
$.fn.favoriteToggle = function () {
this.find('a')
.each(function () {
var type, obj, isFavorite, link = this;
type = $(this).queryParam('type');
obj = $(this).queryParam('object');
function isFavorite() {
var ret = false;
$.each(favoriteList, function (k, v) {
if (v === type + ':' + obj) {
ret = true;
return false;
}
});
return ret;
}
$(this).empty();
$(this).append(tr('Favorite'));
$(this).prepend($('<img style="vertical-align: top; margin-right: .2em;" />').attr('src', isFavorite() ? 'img/icons/star.png' : 'img/icons/star_grey.png'));
// Toggle class of closest surrounding div for css customization
if (isFavorite()) {
$(this).closest('div').addClass( 'favorite_selected' );
$(this).closest('div').removeClass( 'favorite_unselected' );
} else {
$(this).closest('div').addClass( 'favorite_unselected' );
$(this).closest('div').removeClass( 'favorite_selected' );
}
$(this)
.filter(':not(".register")')
.addClass('register')
.click(function () {
$.getJSON($(this).attr('href'), {
target: isFavorite() ? 0 : 1
}, function (data) {
favoriteList = data.list;
$.localStorage.store('favorites', favoriteList);
$(link).parent().favoriteToggle();
});
return false;
});
});
return this;
};
$.fn.queryParam = function (name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)");
var results = regex.exec(this[0].href);
if(results == null) {
return "";
} else {
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
};
$(function () {
var list = $('.favorite-toggle');
if (list.length > 0) {
$.localStorage.load(
'favorites',
function (data) {
favoriteList = data;
list
.favoriteToggle()
.removeClass('favorite-toggle');
},
function (recv) {
$.getJSON($.service('favorite', 'list'), recv);
}
);
}
});
$.ajaxSetup({
complete: function () {
$('.favorite-toggle')
.favoriteToggle()
.removeClass('favorite-toggle');
}
});
/**
* Show a loading spinner on top of a button (or whatever)
*
* @param empty or jq object $spinner if empty, spinner is added and returned and element "disabled"
* if spinner then spinner is removed and element returned to normal
*
* @return jq object $spinner being shown or null when removing
*/
$.fn.showBusy = function( $spinner ) {
if (!$spinner) {
var pos = $(this).position();
$spinner = $("<img src='img/spinner.gif' alt='" + tr("Wait") + "' class='ajax-spinner' />").
css({
"position": "absolute",
"top": pos.top + ($(this).height() / 2),
"left": pos.left + ($(this).width() / 2) - 8
}).data("target", this);
$(this).parent().find(".ajax-spinner").remove();
$(this).parent().append($spinner);
$(this).attr("disabled", true).css("opacity", 0.5);
return $spinner;
} else {
$($spinner.data("target")).attr("disabled", false).css("opacity", 1);
$spinner.remove();
return null;
}
}
})($jq);
// Prevent memory leaks in IE
// Window isn't included so as not to unbind existing unload events
// More info:
// - http://isaacschlueter.com/2006/10/msie-memory-leaks/
if ( window.attachEvent && !window.addEventListener ) {
window.attachEvent("onunload", function() {
for ( var id in jQuery.cache ) {
var item = jQuery.cache[ id ];
if ( item.handle ) {
if ( item.handle.elem === window ) {
for ( var type in item.events ) {
if ( type !== "unload" ) {
// Try/Catch is to handle iframes being unloaded, see #4280
try {
jQuery.event.remove( item.handle.elem, type );
} catch(e) {}
}
}
} else {
// Try/Catch is to handle iframes being unloaded, see #4280
try {
jQuery.event.remove( item.handle.elem );
} catch(e) {}
}
}
}
});
}
$.modal = function(msg) {
return $('body').modal(msg, {
isEverything: true
});
};
//Makes modal over window or object so ajax can load and user can't prevent action
$.fn.modal = function(msg, s) {
var obj = $(this);
if (!obj.length) {
return; // happens after search index rebuild in some conditions
}
var lastModal = obj.attr('lastModal');
if (!lastModal) {
lastModal = Math.floor(Math.random() * 1000);
obj.attr('lastModal', lastModal);
}
var mid = obj.height() / 2 + obj.offset().top;
if (mid > $window.height()) {
mid = ($window.height() - obj.offset().top) / 2 + obj.offset().top;
}
s = $.extend({
isEverything: false,
top: obj.offset().top,
left: obj.offset().left,
height: obj.height(), //we try to get height here
width: obj.width(),
middle: (mid),
center: (obj.width() / 2 + obj.offset().left)
}, s);
var modal = $('body').find('#modal_' + lastModal);
var spinner = $('<img src="img/spinner.gif" />');
if (!msg) {
modal
.fadeOut(function() {
$(this).remove();
});
obj.removeAttr('lastModal');
return;
}
if (modal.length) {
modal
.find('.dialog')
.html(spinner)
.append(msg);
return;
}
modal = $('<div>' +
'<div class="dialog"></div>' +
'<div class="mask"></div>' +
'</div>')
.addClass('boxes')
.attr('id', 'modal_' + lastModal)
.prependTo('body');
var size = {};
if (s.isEverything) { //if the modal includes the whole page
s = $.extend(s, {
top: 0,
left: 0,
height: $document.height(),
width: $window.width(),
middle: $window.height() / 2,
center: $window.width() / 2
});
}
//Set height and width to mask to fill up the whole screen or the single element
modal.find('.mask')
.css('width', s.width + 'px')
.css('height', s.height + 'px')
.css('top', s.top + 'px')
.css('left', s.left + 'px')
.css('position', 'absolute')
.fadeTo(1,0.01)
.fadeTo(1000,0.8);
var dialog = modal.find('.dialog');
dialog
.append(spinner)
.append(msg)
.css('top', (s.middle - dialog.height() / 2) + 'px')
.css('left', (s.center - dialog.width() / 2) + 'px')
.css('position', 'absolute');
if (s.isEverything) {
dialog
.css('top', (s.middle - dialog.height() / 2) + 'px')
.css('left', (s.center - dialog.width() / 2) + 'px')
.css('position', 'fixed');
}
return obj;
};
//makes the width of an input change to the value
$.fn.valWidth = function() {
var me = $(this);
return me.ready(function() {
var h = me.height();
if (!h) {
h = me.offsetParent().css("font-size");
if (h) {
h = parseInt(h.replace("px", ""));
}
}
me.keyup(function() {
var width = me.val().length * h;
me
.stop()
.animate({
width: (width > h ? width : h)
}, 200);
})
.keyup();
});
};
//For making pagination have the ability to enter page/offset number and go
$.paginationHelper = function() {
$('.pagenums').each(function() {
var me = $(this);
var step = me.find('input.pagenumstep');
var endOffset = (me.find('input.pagenumend').val() - 1) * step.data('step');
var url = step.data('url');
var offset_jsvar = step.data('offset_jsvar');
var offset_arg = step.data('offset_arg');
me.find('span.pagenumstep').replaceWith(
$('<input type="text" style="font-size: inherit; " />')
.val(step.val())
.change(function() {
var newOffset = step.data('step') * ($(this).val() - 1);
if (newOffset >= 0) {
//make sure the offset isn't too high
newOffset = (newOffset > endOffset ? endOffset : newOffset);
//THis is for custom/ajax search handling
window[offset_jsvar] = newOffset;
if (step[0]) {
if (step.attr('onclick')) {
step[0].onclick();
return;
}
}
//if the above behavior isn't there, we update location
document.location = url + offset_arg + "=" + newOffset;
}
})
.keyup(function(e) {
switch(e.which) {
case 13: $(this).blur();
}
})
.valWidth()
);
});
};
//a sudo "onvisible" event
$.fn.visible = function(fn, isOne) {
if (fn) {
$(this).each(function() {
var me = $(this);
if (isOne) {
me.one('visible', fn);
} else {
me.bind('visible', fn);
}
function visibilityHelper() {
if (!me.is(':visible')) {
setTimeout(visibilityHelper, 500);
} else {
me.trigger('visible');
}
}
visibilityHelper();
});
} else {
$(this).trigger('visible');
}
return this;
};
$.download = function(url, data, method){
//url and data options required
if( url && data ){
//data can be string of parameters or array/object
data = typeof data == 'string' ? data : jQuery.param(data);
//split params into form inputs
var inputs = '';
jQuery.each(data.split('&'), function(){
var pair = this.split('=');
inputs+='<input type="hidden" name="'+ pair[0] +'" value="'+ pair[1] +'" />';
});
//send request
jQuery('<form action="'+ url +'" method="'+ (method||'post') +'">'+inputs+'</form>')
.appendTo('body').submit().remove();
};
};
$.uiIcon = function(type) {
return $('<div style="width: 1.4em; height: 1.4em; margin: .2em; display: inline-block; cursor: pointer;">' +
'<span class="ui-icon ui-icon-' + type + '"> </span>' +
'</div>')
.hover(function(){
$(this).addClass('ui-state-highlight');
}, function() {
$(this).removeClass('ui-state-highlight');
});
};
$.uiIconButton = function(type) {
return $.uiIcon(type).addClass('ui-state-default ui-corner-all');
};
$.rangySupported = function(fn) {
if (window.rangy) {
rangy.init();
var cssClassApplierModule = rangy.modules.CssClassApplier;
return fn();
}
};
$.fn.rangy = function(fn) {
var me = $(this);
$.rangySupported(function() {
$document.mouseup(function(e) {
if (me.data('rangyBusy')) return;
var selection = rangy.getSelection();
var html = selection.toHtml();
var text = selection.toString();
if (text.length > 3 && rangy.isUnique(me[0], text)) {
if (fn)
if ($.isFunction(fn))
fn({
text: text,
x: e.pageX,
y: e.pageY
});
}
});
});
return this;
};
$.fn.rangyRestore = function(phrase, fn) {
var me = $(this);
$.rangySupported(function() {
phrase = rangy.setPhrase(me[0], phrase);
if (fn)
if ($.isFunction(fn))
fn(phrase);
});
return this;
};
$.fn.rangyRestoreSelection = function(phrase, fn) {
var me = $(this);
$.rangySupported(function() {
phrase = rangy.setPhraseSelection(me[0], phrase);
if (fn)
if ($.isFunction(fn))
fn(phrase);
});
return this;
};
$.fn.realHighlight = function() {
var o = $(this);
$.rangySupported(function() {
rangy.setPhraseBetweenNodes(o.first(), o.last(), document);
});
return this;
};
$.fn.ajaxEditDraw = function(options) {
var me = $(this).attr('href', 'tiki-ajax_services.php');
//defaults
options = $.extend({
saved: function() {},
closed: function() {}
}, options);
$.modal(tr('Loading editor'));
me.serviceDialog({
title: me.attr('title'),
data: {
controller: 'draw',
action: 'edit',
fileId: me.data('fileid'),
galleryId: me.data('galleryid'),
imgParams: me.data('imgparams'),
raw: true
},
modal: true,
zIndex: 9999,
fullscreen: true,
load: function (data) {
//prevent from happeneing over and over again
if (me.data('drawLoaded')) return false;
me.data('drawLoaded', true);
me.drawing = $('#tiki_draw')
.loadDraw({
fileId: me.data('fileid'),
galleryId: me.data('galleryid'),
name: me.data('name'),
imgParams: me.data('imgparams'),
data: $('#fileData').val()
})
.bind('savedDraw', function(e, o) {
me.data('drawLoaded', false);
me.drawing.parent().dialog('destroy');
me.drawing.remove();
//update the image that did exist in the page with the new one that now exists
var img = $('.pluginImg' + me.data('fileid')).show();
if (img.length < 1) document.location = document.location + '';
var w = img.width(), h = img.height();
if (img.hasClass('regImage')) {
var replacement = $('<div />')
.attr('class', img.attr('class'))
.attr('style', img.attr('style'))
.attr('id', img.attr('id'))
.insertAfter(img);
img.remove();
img = replacement;
}
var src = me.data('src');
$('<div class=\"svgImage\" />')
.load(src ? src : 'tiki-download_file.php?fileId=' + o.fileId + '&display', function() {
$(this)
.css('position', 'absolute')
.fadeTo(0, 0.01)
.prependTo('body')
.find('img,svg')
.scaleImg({
width: w,
height: h
});
img.html($(this).children());
$(this).remove();
});
if (!options.saved) return;
options.saved(o.fileId);
me.data('fileid', o.fileId); // replace fileId on edit button
if (o.imgParams && o.imgParams.fileId) {
o.imgParams.fileId = o.fileId;
me.data('imgparams', o.imgParams);
}
})
.submit(function() {
me.drawing.saveDraw();
return false;
})
.bind('loadedDraw', function() {
//kill the padding around the dialog so it looks like svg-edit is one single box
me.drawing
.parent()
.css('padding', '0px');
var serviceDialog = me.data('serviceDialog');
if (serviceDialog) {
var drawFrame = $('#svgedit');
serviceDialog
.bind('dialogresize', function() {
drawFrame.height(serviceDialog.height() - 4);
})
.trigger('dialogresize');
}
$.modal();
});
me.drawing.find('#drawMenu').remove();
},
close: function() {
if (me.data('drawLoaded')) {
me.data('drawLoaded', false);
me.drawing.remove();
if (!options.closed) return;
options.closed(me);
}
}
});
return false;
};
$.notify = function(msg, settings) {
settings = $.extend({
speed: 10000
},settings);
var notify = $('#notify');
if (!notify.length) {
notify = $('<div id="notify" />')
.css('top', '5px')
.css('right', '5px')
.css('position', 'fixed')
.css('z-index', 9999999)
.css('padding', '5px')
.width($window.width() / 5)
.prependTo('body');
}
var note = $('<div class="notify ui-state-error ui-corner-all ui-widget ui-widget-content" />')
.append(msg)
.css('padding', '5px')
.css('margin', '5px')
.mousedown(function() {
return false;
})
.hover(function() {
$(this)
.stop()
.fadeTo(500, 0.3)
}, function() {
$(this)
.stop()
.fadeTo(500, 1)
})
.prependTo(notify);
setTimeout(function() {
note
.fadeOut()
.slideUp();
//added outside of fadeOut to ensure removal
setTimeout(function() {
note.remove();
}, 1000);
}, settings.speed);
};
function delayedExecutor(delay, callback)
{
var timeout;
return function () {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
timeout = setTimeout(callback, delay);
};
}
/**
* Close (user) sidebar column(s) if no modules are displayed.
* Modules can be hidden at runtime. So, check after the page/DOM model is loaded.
*/
$(function () {
// Do final client side adjustment of the sidebars
/////////////////////////////////////////
var maincol = 'col1';
// Hide left side panel, if no modules are displayed
var left_mods = document.getElementById('left_modules');
if (left_mods != null) {
if (isEmptyText(left_mods.innerHTML)) {
var col = document.getElementById('col2');
if (col != null) {
col.style.display = "none"
}
document.getElementById(maincol).style.marginLeft = '0';
var toggle = document.getElementById("showhide_left_column")
if (toggle != null) {
toggle.style.display = "none";
}
}
}
// Hide right side panel, if no modules are displayed
var right_mods = document.getElementById('right_modules');
if (right_mods != null) {
// alert("right_mods.innerHTML=" + right_mods.innerHTML);
//alert("right_mods.innerText=" + right_mods.innerText);
if (isEmptyText(right_mods.innerHTML)) {
var col = document.getElementById('col3');
if (col != null) {
col.style.display = "none"
}
document.getElementById(maincol).style.marginRight = '0';
var toggle = document.getElementById("showhide_right_column")
if (toggle != null) {
toggle.style.display = "none";
}
}
}
// FF does not support obj.innerText. So, analyze innerHTML, which all browsers seem to support
function isEmptyText(html) {
// Strip HTML tags
/////////////////////////
var strInputCode = html;
// Replace coded-< with <, and coded-> with >
strInputCode = strInputCode.replace(/&(lt|gt);/g, function (strMatch, p1) {
return (p1 == "lt") ? "<" : ">";
});
// Strip tags
var strTagStrippedText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
// Trim whitespace
var text = strTagStrippedText.replace(/^\s+|\s+$/g, "");
return text == null || text.length == 0;
}
});
// try and reposition the menu ul within the browser window
$.fn.moveToWithinWindow = function() {
var $el = $(this);
h = $el.height(),
w = $el.width(),
o = $el.offset(),
po = $el.parent().offset(),
st = $window.scrollTop(),
sl = $window.scrollLeft(),
wh = $window.height(),
ww = $window.width();
if (w + o.left > sl + ww) {
$el.animate({'left': sl + ww - w - po.left}, 'fast');
}
if (h + o.top > st + wh) {
$el.animate({'top': st + wh - (h > wh ? wh : h) - po.top}, 'fast');
} else if (o.top < st) {
$el.animate({'top': st - po.top}, 'fast');
}
};
$.fn.scaleImg = function (max) {
$(this).each(function() {
//Here we want to make sure that the displayed contents is the right size
var img = $(this),
actual = {
height: img.height(),
width: img.width()
},
original = $(this).clone(),
parent = img.parent();
var winner = '';
if (actual.height > max.height) {
winner = 'height';
} else if (actual.width > max.width) {
winner = 'width';
}
//if there is no winner, there is no need to resize
if (winner) {
//we resize both images and svg, we check svg first
var g = img.find('g');
if (g.length) {
img
.attr('preserveAspectRatio', 'xMinYMin meet');
parent
.css('overflow', 'hidden')
.width(max.width)
.height(max.height);
g.attr('transform', 'scale( ' + (100 / (actual[winner] / max[winner]) * 0.01) + ' )');
} else {
//now we resize regular images
if (actual.height > actual.width) {
var h = max.height;
var w = Math.ceil(actual.width / actual.height * max.height);
} else {
var w = max.width;
var h = Math.ceil(actual.height / actual.width * max.width);
}
img.css({ height: h, width: w });
}
img
.css('cursor', "url(img/icons/zoom.gif),auto")
.click(function () {
$('<div/>').append(original).dialog({
modal: true,
width: Math.min($(window).width(), actual.width + 20),
height: Math.min($(window).height(), actual.height + 50)
});
return false;
});
}
});
return this;
};
$.openEditHelp = function (num) {
var edithelp_pos = getCookie("edithelp_position"),
opts = {
width: 460,
height: 500,
title: tr("Help"),
autoOpen: false,
beforeclose: function(event, ui) {
var off = $(this).offsetParent().offset();
setCookie("edithelp_position", parseInt(off.left,10) + "," + parseInt(off.top,10) + "," + $(this).offsetParent().width() + "," + $(this).offsetParent().height());
}
};
if (edithelp_pos) {
edithelp_pos = edithelp_pos.split(",");
}
if (edithelp_pos && edithelp_pos.length) {
opts["position"] = [parseInt(edithelp_pos[0],10), parseInt(edithelp_pos[1],10)];
opts["width"] = parseInt(edithelp_pos[2],10);
opts["height"] = parseInt(edithelp_pos[3],10);
}
try {
if ($("#help_sections").dialog) {
$("#help_sections").dialog("destroy");
}
} catch( e ) {
// IE throws errors destroying a non-existant dialog
}
var help_sections = $("#help_sections")
.dialog(opts)
.dialog("open")
.tabs("select", num);
$document.trigger('editHelpOpened', help_sections);
};
|
[FIX] translation: Disable full screen side-by-side translation for wysiwyg (messes up the page layout badly)
git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@45255 b456876b-0849-0410-b77d-98878d47e9d5
|
lib/jquery_tiki/tiki-jquery.js
|
[FIX] translation: Disable full screen side-by-side translation for wysiwyg (messes up the page layout badly)
|
<ide><path>ib/jquery_tiki/tiki-jquery.js
<ide> }
<ide>
<ide> function toggleFullScreen(area_id) {
<add>
<add> if ($("input[name=wysiwyg]").val() === "y") { // quick fix to disable side-by-side translation for wysiwyg
<add> $("#diff_versions").height(200).css("overflow", "auto");
<add> return;
<add> }
<add>
<ide> var textarea = $("#" + area_id);
<ide>
<ide> //codemirror interation and preservation
|
|
Java
|
apache-2.0
|
11cbb798a4858d13d4767567d3a672b2d2d0f95a
| 0 |
helyho/Voovan,helyho/Voovan,helyho/Voovan
|
package org.voovan.tools;
import org.voovan.Global;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
/**
* 时间工具类
*
* @author helyho
*
* Voovan Framework.
* WebSite: https://github.com/helyho/Voovan
* Licence: Apache v2 License
*/
public class TDateTime {
public final static long SECOND = TimeUnit.SECONDS.toMillis(1);
public final static long MINUTE = TimeUnit.MINUTES.toMillis(1);
public final static long HOUR = TimeUnit.HOURS.toMillis(1);
public final static long DAY = TimeUnit.DAYS.toMillis(1);
public final static Long BOOT_TIME_MILLS = System.currentTimeMillis();
public final static String STANDER_DATE_TEMPLATE = "yyyy-MM-dd";
public final static String STANDER_TIME_TEMPLATE = "HH:mm:ss";
public final static String STANDER_DATETIME_TEMPLATE = "yyyy-MM-dd HH:mm:ss";
public final static String INTERNTTION_DATETIME_TEMPLATE = "EEE, dd MMM yyyy HH:mm:ss z";
/**
* 获取当前时间
* yyyy-MM-dd HH:mm:ss
* @return 日期字符串
*/
public static String now(){
return format(new Date(),STANDER_DATETIME_TEMPLATE);
}
/**
* 根据特定格式获取当前时间
* @param format 日期格式模板
* @return 日期字符串
*/
public static String now(String format){
return format(new Date(),format);
}
/**
* 时间戳转换
* @param value 待转换的时间戳
* @param timeUnit 时间单位
* @param format 转换格式
* @return 转后的时间
*/
public static String timestamp(long value, TimeUnit timeUnit, String format) {
return format(new Date(timeUnit.toMillis(value)), format);
}
/**
* 时间戳转换
* @param value 待转换的时间戳(毫秒)
* @param format 转换格式
* @return 转后的时间
*/
public static String timestamp(long value, String format) {
return format(new Date(value), format);
}
/**
* 时间戳转换为标准时间格式
* @param value 待转换的时间戳(毫秒)
* @return 转后的时间
*/
public static String timestamp(long value) {
return format(new Date(value));
}
/**
* 格式化日期成字符串
* @param date Date 对象
* @return 日期字符串
*/
public static String format(Date date){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(STANDER_DATETIME_TEMPLATE);
return simpleDateFormat.format(date);
}
/**
* 格式化日期成字符串
* @param date Date 对象
* @param format 日期格式模板
* @return 日期字符串
*/
public static String format(Date date,String format){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
return simpleDateFormat.format(date);
}
/**
* 格式化日期成字符串
* @param date Date 对象
* @param format 日期格式模板
* @param timeZone 所在时区
* @return 日期字符串
*/
public static String format(Date date,String format,String timeZone){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone(timeZone));
return simpleDateFormat.format(date);
}
/**
* 使用特定时区,格式化日期成字符串
* @param date 日期对象
* @param format 日期格式化字符串
* @param timeZone 所在时区
* @param local 所在区域
* @return 日期字符串
*/
public static String format(Date date,String format,String timeZone,Locale local){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format,local);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone(timeZone));
return simpleDateFormat.format(date);
}
/**
* 获取标准的格林威治时间(GMT)
* @param date Date 对象
* @return 日期字符串
*/
public static String formatToGMT(Date date){
return format(date, INTERNTTION_DATETIME_TEMPLATE, "GMT", Locale.ENGLISH);
}
/**
* 从字符串解析时间
* @param source 日期字符串
* @return Date 对象
*/
public static Date parse(String source) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(STANDER_DATETIME_TEMPLATE);
return simpleDateFormatParse(simpleDateFormat, source);
}
/**
* 从字符串解析时间
* @param source 日期字符串
* @param format 日期格式模板
* @return Date 对象
*/
public static Date parse(String source,String format) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
return simpleDateFormatParse(simpleDateFormat, source);
}
/**
* 从字符串解析时间
* @param source 日期字符串
* @param format 日期格式模板
* @param timeZone 所在时区
* @return Date 对象
*/
public static Date parse(String source,String format,String timeZone) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone(timeZone));
return simpleDateFormatParse(simpleDateFormat, source);
}
/**
* 按照特定的时区和地狱从字符串解析时间
* @param source 日期字符串
* @param format 日志格式化字符串
* @param timeZone 所在时区
* @param local 所在区域
* @return 日期字符串
*/
public static Date parse(String source,String format,String timeZone,Locale local) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format, local);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone(timeZone));
return simpleDateFormatParse(simpleDateFormat, source);
}
private static Date simpleDateFormatParse(SimpleDateFormat simpleDateFormat, String source){
try{
return simpleDateFormat.parse(source);
} catch (ParseException e){
throw new org.voovan.tools.exception.ParseException(e);
}
}
/**
* 按格林威治时间(GMT)时间格式获取时间对象
* @param source 日期字符串
* @return Date 对象
*/
public static Date parseToGMT(String source) {
return parse(source, INTERNTTION_DATETIME_TEMPLATE, "GMT", Locale.ENGLISH);
}
/**
* 日期加操作
* @param date 加法的基数日期
* @param millis 微秒
* @return Date 对象
*/
public static Date add(Date date, long millis){
return new Date(date.getTime()+millis);
}
/**
* 日期加操作
* @param time 加法的基数日期
* @param millis 微秒
* @param format 输出的格式
* @return 日期字符串
* @throws ParseException 解析异常
*/
public static String add(String time,long millis,String format) throws ParseException{
Date tmpDate = parse(time, format);
Date resultDate = add(tmpDate, millis);
return format(resultDate, format);
}
/**
* 获取日期中的时间元素
* @param date 日期对象
* @param type 时间元素类型, 例如: Calendar.MINUTE
* @return 时间元素的值
*/
public static int getDateElement(Date date,int type){
Calendar calendar = Calendar.getInstance();
if(date!=null) {
calendar.setTime(date);
}
return calendar.get(type);
}
/**
* 用来获取纳
* 不可用来做精确计时,只能用来做时间标记
* @return 当前的纳秒时间
*/
public static Long currentTimeNanos(){
return BOOT_TIME_MILLS*1000000 + System.nanoTime();
}
/**
* 格式一个差值时间为人类可读
* 如:3600秒, 格式化为: 1h
*
* @param secs 时间秒
* @return 格式化后的时间
*/
public static String formatElapsedSecs(long secs) {
long eTime = secs;
final long days = TimeUnit.SECONDS.toDays(eTime);
eTime -= TimeUnit.DAYS.toSeconds(days);
final long hr = TimeUnit.SECONDS.toHours(eTime);
eTime -= TimeUnit.HOURS.toSeconds(hr);
final long min = TimeUnit.SECONDS.toMinutes(eTime);
eTime -= TimeUnit.MINUTES.toSeconds(min);
final long sec = eTime;
if(days == 0) {
return String.format("%02d:%02d:%02d", hr, min, sec);
} else {
return String.format("%d, %02d:%02d:%02d", days, hr, min, sec);
}
}
}
|
Common/src/main/java/org/voovan/tools/TDateTime.java
|
package org.voovan.tools;
import org.voovan.Global;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
/**
* 时间工具类
*
* @author helyho
*
* Voovan Framework.
* WebSite: https://github.com/helyho/Voovan
* Licence: Apache v2 License
*/
public class TDateTime {
public final static Long BOOT_TIME_MILLS = System.currentTimeMillis();
public final static String STANDER_DATE_TEMPLATE = "yyyy-MM-dd";
public final static String STANDER_TIME_TEMPLATE = "HH:mm:ss";
public final static String STANDER_DATETIME_TEMPLATE = "yyyy-MM-dd HH:mm:ss";
public final static String INTERNTTION_DATETIME_TEMPLATE = "EEE, dd MMM yyyy HH:mm:ss z";
/**
* 获取当前时间
* yyyy-MM-dd HH:mm:ss
* @return 日期字符串
*/
public static String now(){
return format(new Date(),STANDER_DATETIME_TEMPLATE);
}
/**
* 根据特定格式获取当前时间
* @param format 日期格式模板
* @return 日期字符串
*/
public static String now(String format){
return format(new Date(),format);
}
/**
* 时间戳转换
* @param value 待转换的时间戳
* @param timeUnit 时间单位
* @param format 转换格式
* @return 转后的时间
*/
public static String timestamp(long value, TimeUnit timeUnit, String format) {
return format(new Date(timeUnit.toMillis(value)), format);
}
/**
* 时间戳转换
* @param value 待转换的时间戳(毫秒)
* @param format 转换格式
* @return 转后的时间
*/
public static String timestamp(long value, String format) {
return format(new Date(value), format);
}
/**
* 时间戳转换为标准时间格式
* @param value 待转换的时间戳(毫秒)
* @return 转后的时间
*/
public static String timestamp(long value) {
return format(new Date(value));
}
/**
* 格式化日期成字符串
* @param date Date 对象
* @return 日期字符串
*/
public static String format(Date date){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(STANDER_DATETIME_TEMPLATE);
return simpleDateFormat.format(date);
}
/**
* 格式化日期成字符串
* @param date Date 对象
* @param format 日期格式模板
* @return 日期字符串
*/
public static String format(Date date,String format){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
return simpleDateFormat.format(date);
}
/**
* 格式化日期成字符串
* @param date Date 对象
* @param format 日期格式模板
* @param timeZone 所在时区
* @return 日期字符串
*/
public static String format(Date date,String format,String timeZone){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone(timeZone));
return simpleDateFormat.format(date);
}
/**
* 使用特定时区,格式化日期成字符串
* @param date 日期对象
* @param format 日期格式化字符串
* @param timeZone 所在时区
* @param local 所在区域
* @return 日期字符串
*/
public static String format(Date date,String format,String timeZone,Locale local){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format,local);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone(timeZone));
return simpleDateFormat.format(date);
}
/**
* 获取标准的格林威治时间(GMT)
* @param date Date 对象
* @return 日期字符串
*/
public static String formatToGMT(Date date){
return format(date, INTERNTTION_DATETIME_TEMPLATE, "GMT", Locale.ENGLISH);
}
/**
* 从字符串解析时间
* @param source 日期字符串
* @return Date 对象
*/
public static Date parse(String source) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(STANDER_DATETIME_TEMPLATE);
return simpleDateFormatParse(simpleDateFormat, source);
}
/**
* 从字符串解析时间
* @param source 日期字符串
* @param format 日期格式模板
* @return Date 对象
*/
public static Date parse(String source,String format) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
return simpleDateFormatParse(simpleDateFormat, source);
}
/**
* 从字符串解析时间
* @param source 日期字符串
* @param format 日期格式模板
* @param timeZone 所在时区
* @return Date 对象
*/
public static Date parse(String source,String format,String timeZone) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone(timeZone));
return simpleDateFormatParse(simpleDateFormat, source);
}
/**
* 按照特定的时区和地狱从字符串解析时间
* @param source 日期字符串
* @param format 日志格式化字符串
* @param timeZone 所在时区
* @param local 所在区域
* @return 日期字符串
*/
public static Date parse(String source,String format,String timeZone,Locale local) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format, local);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone(timeZone));
return simpleDateFormatParse(simpleDateFormat, source);
}
private static Date simpleDateFormatParse(SimpleDateFormat simpleDateFormat, String source){
try{
return simpleDateFormat.parse(source);
} catch (ParseException e){
throw new org.voovan.tools.exception.ParseException(e);
}
}
/**
* 按格林威治时间(GMT)时间格式获取时间对象
* @param source 日期字符串
* @return Date 对象
*/
public static Date parseToGMT(String source) {
return parse(source, INTERNTTION_DATETIME_TEMPLATE, "GMT", Locale.ENGLISH);
}
/**
* 日期加操作
* @param date 加法的基数日期
* @param millis 微秒
* @return Date 对象
*/
public static Date add(Date date,long millis){
return new Date(date.getTime()+millis);
}
/**
* 日期加操作
* @param time 加法的基数日期
* @param millis 微秒
* @param format 输出的格式
* @return 日期字符串
* @throws ParseException 解析异常
*/
public static String add(String time,long millis,String format) throws ParseException{
Date tmpDate = parse(time, format);
Date resultDate = add(tmpDate, millis);
return format(resultDate, format);
}
/**
* 获取日期中的时间元素
* @param date 日期对象
* @param type 时间元素类型
* @return 时间元素的值
*/
public static int getDateElement(Date date,int type){
Calendar calendar = Calendar.getInstance();
if(date!=null) {
calendar.setTime(date);
}
return calendar.get(type);
}
/**
* 用来获取纳
* 不可用来做精确计时,只能用来做时间标记
* @return 当前的纳秒时间
*/
public static Long currentTimeNanos(){
return BOOT_TIME_MILLS*1000000 + System.nanoTime();
}
/**
* 格式一个差值时间为人类可读
* 如:3600秒, 格式化为: 1h
*
* @param secs 时间秒
* @return 格式化后的时间
*/
public static String formatElapsedSecs(long secs) {
long eTime = secs;
final long days = TimeUnit.SECONDS.toDays(eTime);
eTime -= TimeUnit.DAYS.toSeconds(days);
final long hr = TimeUnit.SECONDS.toHours(eTime);
eTime -= TimeUnit.HOURS.toSeconds(hr);
final long min = TimeUnit.SECONDS.toMinutes(eTime);
eTime -= TimeUnit.MINUTES.toSeconds(min);
final long sec = eTime;
if(days == 0) {
return String.format("%02d:%02d:%02d", hr, min, sec);
} else {
return String.format("%d, %02d:%02d:%02d", days, hr, min, sec);
}
}
}
|
add: 新增时间的静态值
|
Common/src/main/java/org/voovan/tools/TDateTime.java
|
add: 新增时间的静态值
|
<ide><path>ommon/src/main/java/org/voovan/tools/TDateTime.java
<ide>
<ide>
<ide> public class TDateTime {
<add>
<add> public final static long SECOND = TimeUnit.SECONDS.toMillis(1);
<add> public final static long MINUTE = TimeUnit.MINUTES.toMillis(1);
<add> public final static long HOUR = TimeUnit.HOURS.toMillis(1);
<add> public final static long DAY = TimeUnit.DAYS.toMillis(1);
<add>
<ide> public final static Long BOOT_TIME_MILLS = System.currentTimeMillis();
<ide> public final static String STANDER_DATE_TEMPLATE = "yyyy-MM-dd";
<ide> public final static String STANDER_TIME_TEMPLATE = "HH:mm:ss";
<ide> */
<ide> public static String now(){
<ide> return format(new Date(),STANDER_DATETIME_TEMPLATE);
<add>
<add>
<ide> }
<ide>
<ide> /**
<ide> * @param millis 微秒
<ide> * @return Date 对象
<ide> */
<del> public static Date add(Date date,long millis){
<add> public static Date add(Date date, long millis){
<ide> return new Date(date.getTime()+millis);
<ide> }
<ide>
<ide> /**
<ide> * 获取日期中的时间元素
<ide> * @param date 日期对象
<del> * @param type 时间元素类型
<add> * @param type 时间元素类型, 例如: Calendar.MINUTE
<ide> * @return 时间元素的值
<ide> */
<ide> public static int getDateElement(Date date,int type){
|
|
Java
|
apache-2.0
|
622b83800515615a033591c10df5ca05ad7ee911
| 0 |
Wechat-Group/WxJava,Wechat-Group/WxJava
|
package me.chanjar.weixin.cp.bean.external;
import com.google.gson.annotations.SerializedName;
import lombok.Getter;
import lombok.Setter;
import me.chanjar.weixin.common.util.json.WxGsonBuilder;
import me.chanjar.weixin.cp.bean.WxCpBaseResp;
import me.chanjar.weixin.cp.util.json.WxCpGsonBuilder;
import java.io.Serializable;
import java.util.List;
/**
* @author huangxm129
*/
@Getter
@Setter
public class WxCpUserExternalTagGroupList extends WxCpBaseResp {
private static final long serialVersionUID = -3349321791821450679L;
@SerializedName("tag_group")
private List<WxCpUserExternalTagGroupList.TagGroup> tagGroupList;
@Getter
@Setter
public static class TagGroup implements Serializable {
private static final long serialVersionUID = -4301684507150486556L;
@SerializedName("group_id")
private String groupId;
@SerializedName("group_name")
private String groupName;
@SerializedName("create_time")
private Long createTime;
@SerializedName("order")
private Long order;
@SerializedName("deleted")
private Boolean deleted;
@SerializedName("tag")
private List<Tag> tag;
@Getter
@Setter
public static class Tag implements Serializable {
private static final long serialVersionUID = -4301684507150486556L;
/**
* 客户群ID
*/
@SerializedName("id")
private String id;
@SerializedName("name")
private String name;
@SerializedName("create_time")
private Long createTime;
@SerializedName("order")
private Long order;
@SerializedName("deleted")
private Boolean deleted;
}
}
public String toJson() {
return WxGsonBuilder.create().toJson(this);
}
public static WxCpUserExternalTagGroupList fromJson(String json) {
return WxCpGsonBuilder.create().fromJson(json, WxCpUserExternalTagGroupList.class);
}
}
|
weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/external/WxCpUserExternalTagGroupList.java
|
package me.chanjar.weixin.cp.bean.external;
import com.google.gson.annotations.SerializedName;
import lombok.Getter;
import lombok.Setter;
import me.chanjar.weixin.common.util.json.WxGsonBuilder;
import me.chanjar.weixin.cp.bean.WxCpBaseResp;
import me.chanjar.weixin.cp.util.json.WxCpGsonBuilder;
import java.io.Serializable;
import java.util.List;
/**
*
*/
@Getter
@Setter
public class WxCpUserExternalTagGroupList extends WxCpBaseResp {
@SerializedName("tag_group")
private List<WxCpUserExternalTagGroupList.TagGroup> tagGroupList;
@Getter
@Setter
public static class TagGroup implements Serializable {
private static final long serialVersionUID = -4301684507150486556L;
@SerializedName("group_id")
private String groupId;
@SerializedName("group_name")
private String groupName;
@SerializedName("create_time")
private Long createTime;
@SerializedName("order")
private Integer order;
@SerializedName("deleted")
private Boolean deleted;
@SerializedName("tag")
private List<Tag> tag;
@Getter
@Setter
public static class Tag implements Serializable {
private static final long serialVersionUID = -4301684507150486556L;
/**
* 客户群ID
*/
@SerializedName("id")
private String id;
@SerializedName("name")
private String name;
@SerializedName("create_time")
private Long createTime;
@SerializedName("order")
private Integer order;
@SerializedName("deleted")
private Boolean deleted;
}
}
public String toJson() {
return WxGsonBuilder.create().toJson(this);
}
public static WxCpUserExternalTagGroupList fromJson(String json) {
return WxCpGsonBuilder.create().fromJson(json, WxCpUserExternalTagGroupList.class);
}
}
|
:art: 优化代码
|
weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/external/WxCpUserExternalTagGroupList.java
|
:art: 优化代码
|
<ide><path>eixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/external/WxCpUserExternalTagGroupList.java
<ide> import java.util.List;
<ide>
<ide> /**
<del> *
<add> * @author huangxm129
<ide> */
<ide> @Getter
<ide> @Setter
<ide> public class WxCpUserExternalTagGroupList extends WxCpBaseResp {
<add> private static final long serialVersionUID = -3349321791821450679L;
<ide>
<ide> @SerializedName("tag_group")
<ide> private List<WxCpUserExternalTagGroupList.TagGroup> tagGroupList;
<ide> private Long createTime;
<ide>
<ide> @SerializedName("order")
<del> private Integer order;
<add> private Long order;
<ide>
<ide> @SerializedName("deleted")
<ide> private Boolean deleted;
<ide> private Long createTime;
<ide>
<ide> @SerializedName("order")
<del> private Integer order;
<add> private Long order;
<ide>
<ide> @SerializedName("deleted")
<ide> private Boolean deleted;
|
|
Java
|
mpl-2.0
|
db1b8ba4b18e84876fc2b80fe6559c5e0ed6caf3
| 0 |
Tropicraft/Tropicraft,Tropicraft/Tropicraft,Tropicraft/Tropicraft
|
package net.tropicraft.core.common.block;
import java.util.Random;
import javax.annotation.Nullable;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.BlockItemUseContext;
import net.minecraft.item.ItemStack;
import net.minecraft.particles.ParticleTypes;
import net.minecraft.state.EnumProperty;
import net.minecraft.state.StateContainer.Builder;
import net.minecraft.tags.BlockTags;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.Direction;
import net.minecraft.util.IStringSerializable;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.shapes.ISelectionContext;
import net.minecraft.util.math.shapes.VoxelShape;
import net.minecraft.util.math.shapes.VoxelShapes;
import net.minecraft.world.IBlockReader;
import net.minecraft.world.IEnviromentBlockReader;
import net.minecraft.world.IWorld;
import net.minecraft.world.IWorldReader;
import net.minecraft.world.World;
import net.minecraftforge.common.util.Constants;
public class TikiTorchBlock extends Block {
public enum TorchSection implements IStringSerializable {
UPPER, MIDDLE, LOWER;
@Override
public String getName() {
return this.name().toLowerCase();
}
@Override
public String toString() {
return this.getName();
}
};
public static final EnumProperty<TorchSection> SECTION = EnumProperty.create("section", TorchSection.class);
protected static final VoxelShape BASE_SHAPE = VoxelShapes.create(new AxisAlignedBB(0.4000000059604645D, 0.0D, 0.4000000059604645D, 0.6000000238418579D, 0.999999D, 0.6000000238418579D));
protected static final VoxelShape TOP_SHAPE = VoxelShapes.create(new AxisAlignedBB(0.4000000059604645D, 0.0D, 0.4000000059604645D, 0.6000000238418579D, 0.6000000238418579D, 0.6000000238418579D));
public TikiTorchBlock(Block.Properties properties) {
super(properties);
this.setDefaultState(getDefaultState().with(SECTION, TorchSection.UPPER));
}
@Override
protected void fillStateContainer(Builder<Block, BlockState> builder) {
super.fillStateContainer(builder);
builder.add(SECTION);
}
@Override
public VoxelShape getShape(BlockState state, IBlockReader worldIn, BlockPos pos, ISelectionContext context) {
TorchSection section = state.get(SECTION);
if (section == TorchSection.UPPER) {
return TOP_SHAPE;
} else {
return BASE_SHAPE;
}
}
@Override
@Deprecated
public boolean isValidPosition(BlockState state, IWorldReader world, BlockPos pos) {
if (state.get(SECTION) == TorchSection.LOWER) {
return super.isValidPosition(state, world, pos);
} else {
BlockState blockstate = world.getBlockState(pos.down());
if (state.getBlock() != this) return super.isValidPosition(state, world, pos); //Forge: This function is called during world gen and placement, before this block is set, so if we are not 'here' then assume it's the pre-check.
return blockstate.getBlock() == this && blockstate.get(SECTION) == TorchSection.LOWER;
}
}
@Override
public BlockState getStateForPlacement(BlockItemUseContext context) {
BlockPos blockpos = context.getPos();
BlockState ret = getDefaultState().with(SECTION, TorchSection.LOWER);
return blockpos.getY() < context.getWorld().getDimension().getHeight() - 1 && context.getWorld().getBlockState(blockpos.up()).isReplaceable(context) ? ret : null;
}
@Override
@Deprecated
public BlockState updatePostPlacement(BlockState stateIn, Direction facing, BlockState facingState, IWorld worldIn, BlockPos currentPos, BlockPos facingPos) {
TorchSection section = stateIn.get(SECTION);
if (facing.getAxis() != Direction.Axis.Y || section == TorchSection.LOWER != (facing == Direction.UP) || facingState.getBlock() == this && facingState.get(SECTION) != section) {
return section == TorchSection.LOWER && facing == Direction.DOWN && !stateIn.isValidPosition(worldIn, currentPos) ? Blocks.AIR.getDefaultState() : super.updatePostPlacement(stateIn, facing, facingState, worldIn, currentPos, facingPos);
} else {
return Blocks.AIR.getDefaultState();
}
}
@Override
public void onBlockPlacedBy(World worldIn, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) {
TorchSection section = state.get(SECTION);
if (section == TorchSection.UPPER) return;
// Only place top block if it's on a fence
BlockState stateBelow = worldIn.getBlockState(pos.down());
if (stateBelow.getBlock().isIn(BlockTags.FENCES) || stateBelow.getBlock().isIn(BlockTags.WALLS)) {
worldIn.setBlockState(pos, this.getDefaultState().with(SECTION, TorchSection.UPPER), Constants.BlockFlags.DEFAULT);
} else {
worldIn.setBlockState(pos.up(), this.getDefaultState().with(SECTION, TorchSection.MIDDLE), Constants.BlockFlags.DEFAULT);
worldIn.setBlockState(pos.up(2), this.getDefaultState().with(SECTION, TorchSection.UPPER), Constants.BlockFlags.DEFAULT);
}
}
@Override
public void harvestBlock(World worldIn, PlayerEntity player, BlockPos pos, BlockState state, @Nullable TileEntity te, ItemStack stack) {
super.harvestBlock(worldIn, player, pos, Blocks.AIR.getDefaultState(), te, stack);
}
@Override
public void onBlockHarvested(World worldIn, BlockPos pos, BlockState state, PlayerEntity player) {
TorchSection section = state.get(SECTION);
BlockPos blockpos = section == TorchSection.LOWER ? pos.up() : pos.down();
BlockState blockstate = worldIn.getBlockState(blockpos);
if (blockstate.getBlock() == this && blockstate.get(SECTION) != section) {
worldIn.setBlockState(blockpos, Blocks.AIR.getDefaultState(), Constants.BlockFlags.DEFAULT | Constants.BlockFlags.NO_NEIGHBOR_DROPS);
worldIn.playEvent(player, 2001, blockpos, Block.getStateId(blockstate));
if (!worldIn.isRemote && !player.isCreative()) {
spawnDrops(state, worldIn, pos, (TileEntity)null, player, player.getHeldItemMainhand());
spawnDrops(blockstate, worldIn, blockpos, (TileEntity)null, player, player.getHeldItemMainhand());
}
}
super.onBlockHarvested(worldIn, pos, state, player);
}
@Override
public void animateTick(BlockState state, World world, BlockPos pos, Random rand) {
boolean isTop = state.get(SECTION) == TorchSection.UPPER;
if (isTop) {
double d = pos.getX() + 0.5F;
double d1 = pos.getY() + 0.7F;
double d2 = pos.getZ() + 0.5F;
world.addParticle(ParticleTypes.SMOKE, d, d1, d2, 0.0D, 0.0D, 0.0D);
world.addParticle(ParticleTypes.FLAME, d, d1, d2, 0.0D, 0.0D, 0.0D);
}
}
@Override
@Deprecated
public int getLightValue(BlockState state) {
if (state.get(SECTION) == TorchSection.UPPER) {
return 15;
}
return super.getLightValue(state);
}
@Override
public int getLightValue(BlockState state, IEnviromentBlockReader world, BlockPos pos) {
return getLightValue(state);
}
@Override
public BlockRenderLayer getRenderLayer() {
return BlockRenderLayer.CUTOUT;
}
}
|
src/main/java/net/tropicraft/core/common/block/TikiTorchBlock.java
|
package net.tropicraft.core.common.block;
import java.util.Random;
import javax.annotation.Nullable;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.block.FenceBlock;
import net.minecraft.block.WallBlock;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.BlockItemUseContext;
import net.minecraft.item.ItemStack;
import net.minecraft.particles.ParticleTypes;
import net.minecraft.state.EnumProperty;
import net.minecraft.state.StateContainer.Builder;
import net.minecraft.tags.BlockTags;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.Direction;
import net.minecraft.util.IStringSerializable;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.shapes.ISelectionContext;
import net.minecraft.util.math.shapes.VoxelShape;
import net.minecraft.util.math.shapes.VoxelShapes;
import net.minecraft.world.IBlockReader;
import net.minecraft.world.IEnviromentBlockReader;
import net.minecraft.world.IWorld;
import net.minecraft.world.IWorldReader;
import net.minecraft.world.World;
import net.minecraftforge.common.util.Constants;
public class TikiTorchBlock extends Block {
public enum TorchSection implements IStringSerializable {
UPPER, MIDDLE, LOWER;
@Override
public String getName() {
return this.name().toLowerCase();
}
@Override
public String toString() {
return this.getName();
}
};
public static final EnumProperty<TorchSection> SECTION = EnumProperty.create("section", TorchSection.class);
protected static final VoxelShape BASE_SHAPE = VoxelShapes.create(new AxisAlignedBB(0.4000000059604645D, 0.0D, 0.4000000059604645D, 0.6000000238418579D, 0.999999D, 0.6000000238418579D));
protected static final VoxelShape TOP_SHAPE = VoxelShapes.create(new AxisAlignedBB(0.4000000059604645D, 0.0D, 0.4000000059604645D, 0.6000000238418579D, 0.6000000238418579D, 0.6000000238418579D));
public TikiTorchBlock(Block.Properties properties) {
super(properties);
this.setDefaultState(getDefaultState().with(SECTION, TorchSection.UPPER));
}
@Override
protected void fillStateContainer(Builder<Block, BlockState> builder) {
super.fillStateContainer(builder);
builder.add(SECTION);
}
@Override
public VoxelShape getShape(BlockState state, IBlockReader worldIn, BlockPos pos, ISelectionContext context) {
TorchSection section = state.get(SECTION);
if (section == TorchSection.UPPER) {
return TOP_SHAPE;
} else {
return BASE_SHAPE;
}
}
@Override
@Deprecated
public boolean isValidPosition(BlockState state, IWorldReader world, BlockPos pos) {
if (state.get(SECTION) == TorchSection.LOWER) {
return super.isValidPosition(state, world, pos);
} else {
BlockState blockstate = world.getBlockState(pos.down());
if (state.getBlock() != this) return super.isValidPosition(state, world, pos); //Forge: This function is called during world gen and placement, before this block is set, so if we are not 'here' then assume it's the pre-check.
return blockstate.getBlock() == this && blockstate.get(SECTION) == TorchSection.LOWER;
}
}
@Override
public BlockState getStateForPlacement(BlockItemUseContext context) {
BlockPos blockpos = context.getPos();
BlockState ret = getDefaultState().with(SECTION, TorchSection.LOWER);
return blockpos.getY() < context.getWorld().getDimension().getHeight() - 1 && context.getWorld().getBlockState(blockpos.up()).isReplaceable(context) ? ret : null;
}
@Override
@Deprecated
public BlockState updatePostPlacement(BlockState stateIn, Direction facing, BlockState facingState, IWorld worldIn, BlockPos currentPos, BlockPos facingPos) {
TorchSection section = stateIn.get(SECTION);
if (facing.getAxis() != Direction.Axis.Y || section == TorchSection.LOWER != (facing == Direction.UP) || facingState.getBlock() == this && facingState.get(SECTION) != section) {
return section == TorchSection.LOWER && facing == Direction.DOWN && !stateIn.isValidPosition(worldIn, currentPos) ? Blocks.AIR.getDefaultState() : super.updatePostPlacement(stateIn, facing, facingState, worldIn, currentPos, facingPos);
} else {
return Blocks.AIR.getDefaultState();
}
}
@Override
public void onBlockPlacedBy(World worldIn, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) {
TorchSection section = state.get(SECTION);
if (section == TorchSection.UPPER) return;
// Only place top block if it's on a fence
BlockState stateBelow = worldIn.getBlockState(pos.down());
if (stateBelow.getBlock().isIn(BlockTags.FENCES) || stateBelow.getBlock().isIn(BlockTags.WALLS)) {
worldIn.setBlockState(pos, this.getDefaultState().with(SECTION, TorchSection.UPPER), Constants.BlockFlags.DEFAULT);
} else {
worldIn.setBlockState(pos.up(), this.getDefaultState().with(SECTION, TorchSection.MIDDLE), Constants.BlockFlags.DEFAULT);
worldIn.setBlockState(pos.up(2), this.getDefaultState().with(SECTION, TorchSection.UPPER), Constants.BlockFlags.DEFAULT);
}
}
@Override
public void harvestBlock(World worldIn, PlayerEntity player, BlockPos pos, BlockState state, @Nullable TileEntity te, ItemStack stack) {
super.harvestBlock(worldIn, player, pos, Blocks.AIR.getDefaultState(), te, stack);
}
@Override
public void onBlockHarvested(World worldIn, BlockPos pos, BlockState state, PlayerEntity player) {
TorchSection section = state.get(SECTION);
BlockPos blockpos = section == TorchSection.LOWER ? pos.up() : pos.down();
BlockState blockstate = worldIn.getBlockState(blockpos);
if (blockstate.getBlock() == this && blockstate.get(SECTION) != section) {
worldIn.setBlockState(blockpos, Blocks.AIR.getDefaultState(), Constants.BlockFlags.DEFAULT | Constants.BlockFlags.NO_NEIGHBOR_DROPS);
worldIn.playEvent(player, 2001, blockpos, Block.getStateId(blockstate));
if (!worldIn.isRemote && !player.isCreative()) {
spawnDrops(state, worldIn, pos, (TileEntity)null, player, player.getHeldItemMainhand());
spawnDrops(blockstate, worldIn, blockpos, (TileEntity)null, player, player.getHeldItemMainhand());
}
}
super.onBlockHarvested(worldIn, pos, state, player);
}
@Override
public void animateTick(BlockState state, World world, BlockPos pos, Random rand) {
boolean isTop = state.get(SECTION) == TorchSection.UPPER;
if (isTop) {
double d = pos.getX() + 0.5F;
double d1 = pos.getY() + 0.7F;
double d2 = pos.getZ() + 0.5F;
world.addParticle(ParticleTypes.SMOKE, d, d1, d2, 0.0D, 0.0D, 0.0D);
world.addParticle(ParticleTypes.FLAME, d, d1, d2, 0.0D, 0.0D, 0.0D);
}
}
@Override
@Deprecated
public int getLightValue(BlockState state) {
if (state.get(SECTION) == TorchSection.UPPER) {
return 15;
}
return super.getLightValue(state);
}
@Override
public int getLightValue(BlockState state, IEnviromentBlockReader world, BlockPos pos) {
return getLightValue(state);
}
@Override
public BlockRenderLayer getRenderLayer() {
return BlockRenderLayer.CUTOUT;
}
}
|
Fix edge case in tiki torch block causing them to pop in worldgen
|
src/main/java/net/tropicraft/core/common/block/TikiTorchBlock.java
|
Fix edge case in tiki torch block causing them to pop in worldgen
|
<ide><path>rc/main/java/net/tropicraft/core/common/block/TikiTorchBlock.java
<ide> import net.minecraft.block.Block;
<ide> import net.minecraft.block.BlockState;
<ide> import net.minecraft.block.Blocks;
<del>import net.minecraft.block.FenceBlock;
<del>import net.minecraft.block.WallBlock;
<ide> import net.minecraft.entity.LivingEntity;
<ide> import net.minecraft.entity.player.PlayerEntity;
<ide> import net.minecraft.item.BlockItemUseContext;
|
|
Java
|
bsd-2-clause
|
fb0a202ff9acb70d109bdedb2a0668ec018114a6
| 0 |
jwoehr/ublu,jwoehr/ublu,jwoehr/ublu,jwoehr/ublu,jwoehr/ublu
|
/*
* Copyright (c) 2015, Absolute Performance, Inc. http://www.absolute-performance.com
* Copyright (c) 2016, Jack J. Woehr [email protected]
* SoftWoehr LLC PO Box 51, Golden CO 80402-0051 http://www.softwoehr.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package ublu.command;
import com.ibm.as400.access.AS400SecurityException;
import com.ibm.as400.access.ErrorCompletingRequestException;
import com.ibm.as400.access.ObjectDoesNotExistException;
import com.ibm.as400.access.RequestNotSupportedException;
import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import ublu.db.Db;
import ublu.db.ResultSetClosure;
import ublu.util.ArgArray;
import ublu.util.DataSink;
import ublu.util.Tuple;
/**
* Command to instance and execute JDBC Callable Statements.
*
* @author jwoehr
*/
public class CmdCs extends Command {
{
setNameAndDescription("file",
"/4? [-to @var ] [--,-cs @cs] [-dbconnected @db] [[-instance] -sq1 ~@{ SQL code ... }] | [-call] | [-in ~@{index} ~@object] [-inarray ~@{index} ~@array ~@{type_description}] [-innull ~@{index} ~@{type_description}] [-out ~@{index} ~@{type_description} ~@{scale}] [-rs] [-nextrs] [-uc] : instance and execute callable statements which JDBC uses to execute SQL stored procedures");
}
/**
* The functions performed by the file command
*/
protected static enum FUNCTIONS {
/**
* Instance callable statement
*/
INSTANCE,
/**
* Call callable statement
*/
CALL,
/**
* Get the result set
*/
RS,
/**
* Get next of multiple result sets
*/
NEXTRS,
/**
* Get the update count
*/
UC,
/**
* register outparam
*/
OUT,
/**
* Do nothing
*/
NOOP
}
/**
* Create instance
*/
public CmdCs() {
}
/**
* Parse arguments and perform AS400 File operations
*
* @param argArray passed-in arg array
* @return rest of arg array
*/
public ArgArray doCs(ArgArray argArray) {
FUNCTIONS function = FUNCTIONS.INSTANCE;
Object o; // used for unloading tuples
Tuple csTuple;
CallableStatement cs = null;
Tuple dbTuple;
Db db = null;
String sql = null;
Integer index = null;
String sqlTypeName = null;
String typeDescription = null;
Object inParameter;
Integer scale = null;
while (argArray.hasDashCommand() && getCommandResult() != COMMANDRESULT.FAILURE) {
String dashCommand = argArray.parseDashCommand();
switch (dashCommand) {
case "-to":
setDataDest(DataSink.fromSinkName(argArray.next()));
break;
case "--":
case "-cs":
csTuple = argArray.nextTupleOrPop();
o = csTuple.getValue();
if (o instanceof CallableStatement) {
cs = CallableStatement.class.cast(o);
} else {
getLogger().log(Level.SEVERE, "Supplied tuple is not a Callable Statement instance in {0}", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
}
break;
case "-dbconnected":
dbTuple = argArray.nextTupleOrPop();
o = dbTuple.getValue();
if (o instanceof Db) {
db = Db.class.cast(o);
} else {
getLogger().log(Level.SEVERE, "Supplied tuple is not a Database instance in {0}", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
}
break;
case "-instance":
function = FUNCTIONS.INSTANCE;
break;
case "-in":
function = FUNCTIONS.NOOP;
index = argArray.nextIntMaybeQuotationTuplePopString();
inParameter = argArray.nextTupleOrPop().getValue();
break;
case "-inarray":
function = FUNCTIONS.NOOP;
index = argArray.nextIntMaybeQuotationTuplePopString();
inParameter = argArray.nextTupleOrPop().getValue();
sqlTypeName = argArray.nextMaybeQuotationTuplePopString();
break;
case "-innull":
function = FUNCTIONS.NOOP;
index = argArray.nextIntMaybeQuotationTuplePopString();
sqlTypeName = argArray.nextMaybeQuotationTuplePopString();
break;
case "-nextrs":
function = FUNCTIONS.NEXTRS;
break;
case "-out":
function = FUNCTIONS.OUT;
index = argArray.nextIntMaybeQuotationTuplePopString();
sqlTypeName = argArray.nextMaybeQuotationTuplePopString();
break;
case "-scale":
scale = argArray.nextIntMaybeQuotationTuplePopString();
break;
case "-typename":
typeDescription = argArray.nextMaybeQuotationTuplePopString();
break;
case "-rs":
function = FUNCTIONS.RS;
break;
case "-sql":
sql = argArray.nextMaybeQuotationTuplePopString();
break;
case "-uc":
function = FUNCTIONS.UC;
break;
default:
unknownDashCommand(dashCommand);
setCommandResult(COMMANDRESULT.FAILURE);
}
}
if (havingUnknownDashCommand()) {
setCommandResult(COMMANDRESULT.FAILURE);
}
if (getCommandResult() != COMMANDRESULT.FAILURE) {
switch (function) {
case INSTANCE:
if (db == null) {
getLogger().log(Level.SEVERE, "No Database instance supplied via -dbconnected in {0}", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
} else {
try {
cs = db.getConnection().prepareCall(sql);
} catch (SQLException ex) {
getLogger().log(Level.SEVERE,
"Encountered an exception preparing call of SQL " + sql + " in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
if (getCommandResult() != COMMANDRESULT.FAILURE) {
try {
put(cs);
} catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) {
getLogger().log(Level.SEVERE, "Encountered an exception putting Callable Statement in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
}
}
break;
case CALL:
if (cs != null) {
try {
put(cs.execute()); // the boolean result
} catch (SQLException | AS400SecurityException | ErrorCompletingRequestException | IOException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) {
getLogger().log(Level.SEVERE, "Encountered an exception calling Callable Statement in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
} else {
getLogger().log(Level.SEVERE, "No Callable Statement proved to -call in {0}", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
}
break;
case RS:
if (cs != null) {
try {
put(new ResultSetClosure(cs.getConnection(), cs.getResultSet(), cs));
} catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) {
getLogger().log(Level.SEVERE, "Encountered an exception putting result set in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
} else {
getLogger().log(Level.SEVERE, "No Callable Statement proved to -rs in {0}", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
}
break;
case NEXTRS:
if (cs != null) {
try {
if (cs.getMoreResults()) {
put(new ResultSetClosure(cs.getConnection(), cs.getResultSet(), cs));
} else {
put(null);
}
} catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) {
getLogger().log(Level.SEVERE, "Encountered an exception putting result set in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
} else {
getLogger().log(Level.SEVERE, "No Callable Statement proved to -nextrs in {0}", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
}
break;
case UC:
if (cs != null) {
try {
put(cs.getUpdateCount());
} catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) {
getLogger().log(Level.SEVERE, "Encountered an exception putting result set in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
} else {
getLogger().log(Level.SEVERE, "No Callable Statement proved to -uc in {0}", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
}
break;
case OUT:
if (cs != null) {
try {
setOut(cs, index, sqlTypeName, typeDescription, scale);
} catch (SQLException ex) {
getLogger().log(Level.SEVERE, "Encountered an exception registering out param in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
} else {
getLogger().log(Level.SEVERE, "No Callable Statement proved to -out in {0}", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
}
break;
case NOOP:
break;
}
}
return argArray;
}
private boolean setIn(int index, Object inParameter) {
boolean success = false;
return success;
}
private boolean setInArray(int index, Object inParameter, String typeDescription) {
boolean success = false;
return success;
}
private boolean setInNull(int index, String typeDescription) {
boolean success = false;
return success;
}
private void setOut(CallableStatement cs, int index, String typename, String typeDescription, Integer scale) throws SQLException {
int sqlType = typenameToSQLType(typename);
if (typeDescription != null) {
cs.registerOutParameter(index, sqlType, typeDescription);
} else if (scale != null) {
cs.registerOutParameter(index, sqlType, scale);
} else {
cs.registerOutParameter(index, sqlType);
}
}
private Integer typenameToSQLType(String typename) {
Integer sqlType = null;
// java.sql.JDBCType.ordinal(typename); // java 1.8 !!
switch (typename.toUpperCase()) {
case "ARRAY":
sqlType = java.sql.Types.ARRAY;
break;
}
return sqlType;
}
@Override
public ArgArray cmd(ArgArray args
) {
reinit();
return doCs(args);
}
@Override
public COMMANDRESULT getResult() {
return getCommandResult();
}
}
|
src/ublu/command/CmdCs.java
|
/*
* Copyright (c) 2015, Absolute Performance, Inc. http://www.absolute-performance.com
* Copyright (c) 2016, Jack J. Woehr [email protected]
* SoftWoehr LLC PO Box 51, Golden CO 80402-0051 http://www.softwoehr.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package ublu.command;
import com.ibm.as400.access.AS400SecurityException;
import com.ibm.as400.access.ErrorCompletingRequestException;
import com.ibm.as400.access.ObjectDoesNotExistException;
import com.ibm.as400.access.RequestNotSupportedException;
import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import ublu.db.Db;
import ublu.db.ResultSetClosure;
import ublu.util.ArgArray;
import ublu.util.DataSink;
import ublu.util.Tuple;
/**
* Command to instance and execute JDBC Callable Statements.
*
* @author jwoehr
*/
public class CmdCs extends Command {
{
setNameAndDescription("file",
"/4? [-to @var ] [--,-cs @cs] [-dbconnected @db] [[-instance] -sq1 ~@{ SQL code ... }] | [-call] | [-in ~@{index} ~@object] [-inarray ~@{index} ~@array ~@{type_description}] [-innull ~@{index} ~@{type_description}] [-out ~@{index} ~@{type_description} ~@{scale}] [-rs] [-nextrs] [-uc] : instance and execute callable statements which JDBC uses to execute SQL stored procedures");
}
/**
* The functions performed by the file command
*/
protected static enum FUNCTIONS {
/**
* Instance callable statement
*/
INSTANCE,
/**
* Call callable statement
*/
CALL,
/**
* Get the result set
*/
RS,
/**
* Get next of multiple result sets
*/
NEXTRS,
/**
* Get the update count
*/
UC,
/**
* Do nothing
*/
NOOP
}
/**
* Create instance
*/
public CmdCs() {
}
/**
* Parse arguments and perform AS400 File operations
*
* @param argArray passed-in arg array
* @return rest of arg array
*/
public ArgArray doCs(ArgArray argArray) {
FUNCTIONS function = FUNCTIONS.INSTANCE;
Object o; // used for unloading tuples
Tuple csTuple;
CallableStatement cs = null;
Tuple dbTuple;
Db db = null;
String sql = null;
Integer index;
String typeDescription;
Object inParameter;
Integer scale;
while (argArray.hasDashCommand() && getCommandResult() != COMMANDRESULT.FAILURE) {
String dashCommand = argArray.parseDashCommand();
switch (dashCommand) {
case "-to":
setDataDest(DataSink.fromSinkName(argArray.next()));
break;
case "--":
case "-cs":
csTuple = argArray.nextTupleOrPop();
o = csTuple.getValue();
if (o instanceof CallableStatement) {
cs = CallableStatement.class.cast(o);
} else {
getLogger().log(Level.SEVERE, "Supplied tuple is not a Callable Statement instance in {0}", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
}
break;
case "-dbconnected":
dbTuple = argArray.nextTupleOrPop();
o = dbTuple.getValue();
if (o instanceof Db) {
db = Db.class.cast(o);
} else {
getLogger().log(Level.SEVERE, "Supplied tuple is not a Database instance in {0}", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
}
break;
case "-instance":
function = FUNCTIONS.INSTANCE;
break;
case "-in":
function = FUNCTIONS.NOOP;
index = argArray.nextIntMaybeQuotationTuplePopString();
inParameter = argArray.nextTupleOrPop().getValue();
break;
case "-inarray":
function = FUNCTIONS.NOOP;
index = argArray.nextIntMaybeQuotationTuplePopString();
inParameter = argArray.nextTupleOrPop().getValue();
typeDescription = argArray.nextMaybeQuotationTuplePopString();
break;
case "-innull":
function = FUNCTIONS.NOOP;
index = argArray.nextIntMaybeQuotationTuplePopString();
typeDescription = argArray.nextMaybeQuotationTuplePopString();
break;
case "-nextrs":
function = FUNCTIONS.NEXTRS;
break;
case "-out":
function = FUNCTIONS.NOOP;
index = argArray.nextIntMaybeQuotationTuplePopString();
typeDescription = argArray.nextMaybeQuotationTuplePopString();
scale = argArray.nextIntMaybeQuotationTuplePopString();
break;
case "-rs":
function = FUNCTIONS.RS;
break;
case "-sql":
sql = argArray.nextMaybeQuotationTuplePopString();
break;
case "-uc":
function = FUNCTIONS.UC;
break;
default:
unknownDashCommand(dashCommand);
setCommandResult(COMMANDRESULT.FAILURE);
}
}
if (havingUnknownDashCommand()) {
setCommandResult(COMMANDRESULT.FAILURE);
}
if (getCommandResult() != COMMANDRESULT.FAILURE) {
switch (function) {
case INSTANCE:
if (db == null) {
getLogger().log(Level.SEVERE, "No Database instance supplied via -dbconnected in {0}", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
} else {
try {
cs = db.getConnection().prepareCall(sql);
} catch (SQLException ex) {
getLogger().log(Level.SEVERE,
"Encountered an exception preparing call of SQL " + sql + " in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
if (getCommandResult() != COMMANDRESULT.FAILURE) {
try {
put(cs);
} catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) {
getLogger().log(Level.SEVERE, "Encountered an exception putting Callable Statement in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
}
}
break;
case CALL:
if (cs != null) {
try {
put(cs.execute()); // the boolean result
} catch (SQLException | AS400SecurityException | ErrorCompletingRequestException | IOException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) {
getLogger().log(Level.SEVERE, "Encountered an exception calling Callable Statement in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
} else {
getLogger().log(Level.SEVERE, "No Callable Statement proved to -call in {0}", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
}
break;
case RS:
if (cs != null) {
try {
put(new ResultSetClosure(cs.getConnection(), cs.getResultSet(), cs));
} catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) {
getLogger().log(Level.SEVERE, "Encountered an exception putting result set in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
} else {
getLogger().log(Level.SEVERE, "No Callable Statement proved to -rs in {0}", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
}
break;
case NEXTRS:
if (cs != null) {
try {
if (cs.getMoreResults()) {
put(new ResultSetClosure(cs.getConnection(), cs.getResultSet(), cs));
} else {
put(null);
}
} catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) {
getLogger().log(Level.SEVERE, "Encountered an exception putting result set in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
} else {
getLogger().log(Level.SEVERE, "No Callable Statement proved to -nextrs in {0}", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
}
break;
case UC:
if (cs != null) {
try {
put(cs.getUpdateCount());
} catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) {
getLogger().log(Level.SEVERE, "Encountered an exception putting result set in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
} else {
getLogger().log(Level.SEVERE, "No Callable Statement proved to -uc in {0}", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
}
break;
case NOOP:
break;
}
}
return argArray;
}
private boolean setIn(int index, Object inParameter) {
boolean success = false;
return success;
}
private boolean setInArray(int index, Object inParameter, String typeDescription) {
boolean success = false;
return success;
}
private boolean setInNull(int index, String typeDescription) {
boolean success = false;
return success;
}
private boolean setOut() {
boolean success = false;
return success;
}
@Override
public ArgArray cmd(ArgArray args
) {
reinit();
return doCs(args);
}
@Override
public COMMANDRESULT getResult() {
return getCommandResult();
}
}
|
more on CmdCS
|
src/ublu/command/CmdCs.java
|
more on CmdCS
|
<ide><path>rc/ublu/command/CmdCs.java
<ide> */
<ide> UC,
<ide> /**
<add> * register outparam
<add> */
<add> OUT,
<add> /**
<ide> * Do nothing
<ide> */
<ide> NOOP
<ide> Tuple dbTuple;
<ide> Db db = null;
<ide> String sql = null;
<del> Integer index;
<del> String typeDescription;
<add> Integer index = null;
<add> String sqlTypeName = null;
<add> String typeDescription = null;
<ide> Object inParameter;
<del> Integer scale;
<add> Integer scale = null;
<ide> while (argArray.hasDashCommand() && getCommandResult() != COMMANDRESULT.FAILURE) {
<ide> String dashCommand = argArray.parseDashCommand();
<ide> switch (dashCommand) {
<ide> function = FUNCTIONS.NOOP;
<ide> index = argArray.nextIntMaybeQuotationTuplePopString();
<ide> inParameter = argArray.nextTupleOrPop().getValue();
<del> typeDescription = argArray.nextMaybeQuotationTuplePopString();
<add> sqlTypeName = argArray.nextMaybeQuotationTuplePopString();
<ide> break;
<ide> case "-innull":
<ide> function = FUNCTIONS.NOOP;
<ide> index = argArray.nextIntMaybeQuotationTuplePopString();
<del> typeDescription = argArray.nextMaybeQuotationTuplePopString();
<add> sqlTypeName = argArray.nextMaybeQuotationTuplePopString();
<ide> break;
<ide> case "-nextrs":
<ide> function = FUNCTIONS.NEXTRS;
<ide> break;
<ide> case "-out":
<del> function = FUNCTIONS.NOOP;
<add> function = FUNCTIONS.OUT;
<ide> index = argArray.nextIntMaybeQuotationTuplePopString();
<add> sqlTypeName = argArray.nextMaybeQuotationTuplePopString();
<add> break;
<add> case "-scale":
<add> scale = argArray.nextIntMaybeQuotationTuplePopString();
<add> break;
<add> case "-typename":
<ide> typeDescription = argArray.nextMaybeQuotationTuplePopString();
<del> scale = argArray.nextIntMaybeQuotationTuplePopString();
<ide> break;
<ide> case "-rs":
<ide> function = FUNCTIONS.RS;
<ide> setCommandResult(COMMANDRESULT.FAILURE);
<ide> }
<ide> break;
<add> case OUT:
<add> if (cs != null) {
<add> try {
<add> setOut(cs, index, sqlTypeName, typeDescription, scale);
<add> } catch (SQLException ex) {
<add> getLogger().log(Level.SEVERE, "Encountered an exception registering out param in " + getNameAndDescription(), ex);
<add> setCommandResult(COMMANDRESULT.FAILURE);
<add> }
<add> } else {
<add> getLogger().log(Level.SEVERE, "No Callable Statement proved to -out in {0}", getNameAndDescription());
<add> setCommandResult(COMMANDRESULT.FAILURE);
<add> }
<add> break;
<ide> case NOOP:
<ide> break;
<ide> }
<ide> return success;
<ide> }
<ide>
<del> private boolean setOut() {
<del> boolean success = false;
<del> return success;
<add> private void setOut(CallableStatement cs, int index, String typename, String typeDescription, Integer scale) throws SQLException {
<add> int sqlType = typenameToSQLType(typename);
<add> if (typeDescription != null) {
<add> cs.registerOutParameter(index, sqlType, typeDescription);
<add> } else if (scale != null) {
<add> cs.registerOutParameter(index, sqlType, scale);
<add> } else {
<add> cs.registerOutParameter(index, sqlType);
<add> }
<add> }
<add>
<add> private Integer typenameToSQLType(String typename) {
<add> Integer sqlType = null;
<add> // java.sql.JDBCType.ordinal(typename); // java 1.8 !!
<add> switch (typename.toUpperCase()) {
<add> case "ARRAY":
<add> sqlType = java.sql.Types.ARRAY;
<add> break;
<add> }
<add> return sqlType;
<ide> }
<ide>
<ide> @Override
|
|
Java
|
mit
|
a3b870cac134199271c2a066e02c21cfeef3969e
| 0 |
scoheb/gerrit-events,svanoort/gerrit-events,sonyxperiadev/gerrit-events,dpursehouse/gerrit-events,rinrinne/gerrit-events
|
/*
* The MIT License
*
* Copyright 2010 Sony Ericsson Mobile Communications. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.sonyericsson.hudson.plugins.gerrit.gerritevents;
import com.sonyericsson.hudson.plugins.gerrit.gerritevents.dto.GerritEvent;
import com.sonyericsson.hudson.plugins.gerrit.gerritevents.dto.events.ChangeAbandoned;
import com.sonyericsson.hudson.plugins.gerrit.gerritevents.dto.events.PatchsetCreated;
import com.sonyericsson.hudson.plugins.gerrit.gerritevents.ssh.Authentication;
import com.sonyericsson.hudson.plugins.gerrit.gerritevents.ssh.SshAuthenticationException;
import com.sonyericsson.hudson.plugins.gerrit.gerritevents.ssh.SshConnectException;
import com.sonyericsson.hudson.plugins.gerrit.gerritevents.ssh.SshConnection;
import com.sonyericsson.hudson.plugins.gerrit.gerritevents.workers.Coordinator;
import com.sonyericsson.hudson.plugins.gerrit.gerritevents.workers.EventThread;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.sonyericsson.hudson.plugins.gerrit.gerritevents.GerritDefaultValues.*;
/**
* Main class for this module.
* Contains the main loop for connecting and reading streamed events from Gerrit.
*
* @author Robert Sandell <[email protected]>
*/
public class GerritHandler extends Thread implements Coordinator {
/**
* Time to wait between connection attempts.
*/
public static final int CONNECT_SLEEP = 2000;
private static final String CMD_STREAM_EVENTS = "gerrit stream-events";
private static final Logger logger = LoggerFactory.getLogger(GerritHandler.class);
private BlockingQueue<JSONObject> workQueue;
private String gerritHostName;
private int gerritSshPort;
private Authentication authentication;
private int numberOfWorkerThreads;
private final List<GerritEventListener> gerritEventListeners;
private final List<ConnectionListener> connectionListeners;
private final List<EventThread> workers;
private SshConnection sshConnection;
private boolean shutdownInProgress = false;
private boolean connecting = false;
/**
* Creates a GerritHandler with all the default values set.
* @see #DEFAULT_GERRIT_HOSTNAME
* @see #DEFAULT_GERRIT_SSH_PORT
* @see #DEFAULT_GERRIT_USERNAME
* @see #DEFAULT_AUTH_KEY_FILE
* @see #DEFAULT_AUTH_KEY_FILE_PASSWORD
* @see #DEFAULT_NR_OF_WORKER_THREADS
*/
public GerritHandler() {
this(DEFAULT_GERRIT_HOSTNAME,
DEFAULT_GERRIT_SSH_PORT,
new Authentication(DEFAULT_GERRIT_AUTH_KEY_FILE,
DEFAULT_GERRIT_USERNAME,
DEFAULT_GERRIT_AUTH_KEY_FILE_PASSWORD),
DEFAULT_NR_OF_WORKER_THREADS);
}
/**
* Creates a GerritHandler with the specified values and default number of worker threads.
* @param gerritHostName the hostName
* @param gerritSshPort the ssh port that the gerrit server listens to.
* @param authentication the authentication credentials.
*/
public GerritHandler(String gerritHostName,
int gerritSshPort,
Authentication authentication) {
this(gerritHostName,
gerritSshPort,
authentication,
DEFAULT_NR_OF_WORKER_THREADS);
}
/**
* Creates a GerritHandler with the specified values.
* @param gerritHostName the hostName for gerrit.
* @param gerritSshPort the ssh port that the gerrit server listens to.
* @param authentication the authentication credentials.
* @param numberOfWorkerThreads the number of eventthreads.
*/
public GerritHandler(String gerritHostName,
int gerritSshPort,
Authentication authentication,
int numberOfWorkerThreads) {
super("Gerrit Events Reader");
this.gerritHostName = gerritHostName;
this.gerritSshPort = gerritSshPort;
this.authentication = authentication;
this.numberOfWorkerThreads = numberOfWorkerThreads;
workQueue = new LinkedBlockingQueue<JSONObject>();
gerritEventListeners = new LinkedList<GerritEventListener>();
connectionListeners = new LinkedList<ConnectionListener>();
workers = new ArrayList<EventThread>(numberOfWorkerThreads);
for (int i = 0; i < numberOfWorkerThreads; i++) {
workers.add(new EventThread(this, "Gerrit Worker EventThread_" + i));
}
}
/**
* Main loop for connecting and reading Gerrit JSON Events and dispatching them to Workers.
*/
@Override
public void run() {
logger.info("Starting Up...");
//Start the workers
for (EventThread worker : workers) {
//TODO what if nr of workers are increased/decreased in runtime.
worker.start();
}
do {
sshConnection = connect();
if (sshConnection == null) {
//should mean unrecoverable error
for (EventThread worker : workers) {
worker.shutdown();
}
return;
}
BufferedReader br = null;
try {
logger.trace("Executing stream-events command.");
Reader reader = sshConnection.executeCommandReader(CMD_STREAM_EVENTS);
br = new BufferedReader(reader);
String line = "";
logger.info("Ready to receive data from Gerrit");
notifyConnectionEstablished();
do {
logger.debug("Data-line from Gerrit: {}", line);
JSONObject obj = GerritJsonEventFactory.getJsonObjectIfInterestingAndUsable(line);
if (obj != null) {
try {
logger.trace("putting work on queue: {}", obj);
workQueue.put(obj);
} catch (InterruptedException ex) {
logger.warn("Interrupted while putting work on queue!", ex);
//TODO check if shutdown
//TODO try again since it is important
}
}
logger.trace("Reading next line.");
line = br.readLine();
} while (line != null);
} catch (IOException ex) {
logger.error("Stream events command error. ", ex);
} finally {
logger.trace("Connection closed, ended read loop.");
try {
sshConnection.disconnect();
} catch (Exception ex) {
logger.warn("Error when disconnecting sshConnection.", ex);
}
sshConnection = null;
notifyConnectionDown();
if (br != null) {
try {
br.close();
} catch (IOException ex) {
logger.warn("Could not close events reader.", ex);
}
}
}
} while (!shutdownInProgress);
for (EventThread worker : workers) {
worker.shutdown();
}
logger.debug("End of GerritHandler Thread.");
}
/**
* Connects to the Gerrit server and authenticates as a "Hudson user".
* @return not null if everything is well, null if connect and reconnect failed.
*/
private SshConnection connect() {
connecting = true;
while (true) { //TODO do not go on forever.
if (shutdownInProgress) {
connecting = false;
return null;
}
SshConnection ssh = null;
try {
logger.debug("Connecting...");
ssh = new SshConnection(gerritHostName, gerritSshPort, authentication);
notifyConnectionEstablished();
connecting = false;
logger.debug("connection seems ok, returning it.");
return ssh;
} catch (SshConnectException sshConEx) {
logger.error("Could not connect to Gerrit server! "
+ "Host: {} Port: {}", gerritHostName, gerritSshPort);
logger.error(" User: {} KeyFile: {}", authentication.getUsername(), authentication.getPrivateKeyFile());
logger.error("ConnectionException: ", sshConEx);
notifyConnectionDown();
} catch (SshAuthenticationException sshAuthEx) {
logger.error("Could not authenticate to gerrit server!"
+ "\n\tUsername: {}\n\tKeyFile: {}\n\tPassword: {}",
new Object[]{authentication.getUsername(),
authentication.getPrivateKeyFile(),
authentication.getPrivateKeyFilePassword(), });
logger.error("AuthenticationException: ", sshAuthEx);
notifyConnectionDown();
} catch (IOException ex) {
logger.error("Could not connect to Gerrit server! "
+ "Host: {} Port: {}", gerritHostName, gerritSshPort);
logger.error(" User: {} KeyFile: {}", authentication.getUsername(), authentication.getPrivateKeyFile());
logger.error("IOException: ", ex);
notifyConnectionDown();
}
if (ssh != null) {
logger.trace("Disconnecting bad connection.");
try {
//The ssh lib used is starting at least one thread for each connection.
//The thread isn't shutdown properly when the connection goes down,
//so we need to close it "manually"
ssh.disconnect();
} catch(Exception ex) {
logger.warn("Error when disconnecting bad connection.", ex);
} finally {
ssh = null;
}
}
if (shutdownInProgress) {
connecting = false;
return null;
}
//If we end up here, sleep for a while and then go back up in the loop.
logger.trace("Sleeping for a bit.");
try {
Thread.sleep(CONNECT_SLEEP);
} catch (InterruptedException ex) {
logger.warn("Got interrupted while sleeping.", ex);
}
}
}
/**
* Add a GerritEventListener to the list of listeners.
* @param listener the listener to add.
*/
public void addListener(GerritEventListener listener) {
synchronized (gerritEventListeners) {
gerritEventListeners.add(listener);
}
}
/**
* Adds all the provided listeners to the internal list of listeners.
* @param listeners the listeners to add.
*/
public void addEventListeners(Collection<GerritEventListener> listeners) {
synchronized (gerritEventListeners) {
gerritEventListeners.addAll(listeners);
}
}
/**
* Removes a GerritEventListener from the list of listeners.
* @param listener the listener to remove.
*/
public void removeListener(GerritEventListener listener) {
synchronized (gerritEventListeners) {
gerritEventListeners.remove(listener);
}
}
/**
* Removes all event listeners and returns those that where removed.
* @return the former list of listeners.
*/
public List<GerritEventListener> removeAllEventListeners() {
synchronized (gerritEventListeners) {
List<GerritEventListener> listeners = new LinkedList<GerritEventListener>(gerritEventListeners);
gerritEventListeners.clear();
return listeners;
}
}
/**
* Add a ConnectionListener to the list of listeners.
* @param listener the listener to add.
*/
public void addListener(ConnectionListener listener) {
synchronized (connectionListeners) {
connectionListeners.add(listener);
}
}
/**
* Add all ConnectionListeners to the list of listeners.
* @param listeners the listeners to add.
*/
public void addConnectionListeners(Collection<ConnectionListener> listeners) {
synchronized (connectionListeners) {
connectionListeners.addAll(listeners);
}
}
/**
* Removes a ConnectionListener from the list of listeners.
* @param listener the listener to remove.
*/
public void removeListener(ConnectionListener listener) {
synchronized (connectionListeners) {
connectionListeners.remove(listener);
}
}
/**
* Removes all connection listeners and returns those who where remooved.
* @return the list of former listeners.
*/
public List<ConnectionListener> removeAllConnectionListeners() {
synchronized (connectionListeners) {
List<ConnectionListener> listeners = new LinkedList<ConnectionListener>(connectionListeners);
connectionListeners.clear();
return listeners;
}
}
/**
* The authentication credentials for ssh connection.
* @return the credentials.
*/
public Authentication getAuthentication() {
return authentication;
}
/**
* The authentication credentials for ssh connection.
* @param authentication the credentials.
*/
public void setAuthentication(Authentication authentication) {
this.authentication = authentication;
}
/**
* gets the hostname where Gerrit is running.
* @return the hostname.
*/
public String getGerritHostName() {
return gerritHostName;
}
/**
* Sets the hostname where Gerrit is running.
* @param gerritHostName the hostname.
*/
public void setGerritHostName(String gerritHostName) {
this.gerritHostName = gerritHostName;
}
/**
* Gets the port for gerrit ssh commands.
* @return the port nr.
*/
public int getGerritSshPort() {
return gerritSshPort;
}
/**
* Sets the port for gerrit ssh commands.
* @param gerritSshPort the port nr.
*/
public void setGerritSshPort(int gerritSshPort) {
this.gerritSshPort = gerritSshPort;
}
/**
* Gets the number of event worker threads.
* @return the number of threads.
*/
public int getNumberOfWorkerThreads() {
return numberOfWorkerThreads;
}
/**
* Sets the number of worker event threads.
* @param numberOfWorkerThreads the number of threads
*/
public void setNumberOfWorkerThreads(int numberOfWorkerThreads) {
this.numberOfWorkerThreads = numberOfWorkerThreads;
//TODO what if nr of workers are increased/decreased in runtime.
}
@Override
public BlockingQueue<JSONObject> getWorkQueue() {
return workQueue;
}
/**
* Notifies all listeners of a Gerrit event.
* This method is meant to be called by one of the Worker Threads
* {@link com.sonyericsson.hudson.plugins.gerrit.gerritevents.workers.EventThread}
* and not on this Thread which would defeat the purpous of having workers.
* @param event the event.
*/
@Override
public void notifyListeners(GerritEvent event) {
synchronized (gerritEventListeners) {
//Take the performance penalty for synchronization security.
for (GerritEventListener listener : gerritEventListeners) {
notifyListener(listener, event);
}
}
}
/**
* Sub method of {@link #notifyListeners(com.sonyericsson.hudson.plugins.gerrit.gerritevents.dto.GerritEvent) }.
* This is where most of the reflection magic in the event notification is done.
* @param listener the listener to notify
* @param event the event.
*/
private void notifyListener(GerritEventListener listener, GerritEvent event) {
logger.debug("Notifying listener {} of event {}", listener, event);
try {
if (event instanceof PatchsetCreated) {
listener.gerritEvent((PatchsetCreated) event);
} else if (event instanceof ChangeAbandoned) {
listener.gerritEvent((ChangeAbandoned) event);
} else {
listener.gerritEvent(event);
}
} catch (Exception ex) {
logger.error("Exception thrown during event handling.", ex);
}
}
/**
* Sub-method of
* {@link #notifyListener(com.sonyericsson.hudson.plugins.gerrit.gerritevents.GerritEventListener,
* com.sonyericsson.hudson.plugins.gerrit.gerritevents.dto.GerritEvent) .
* It is a convenience method so there is no need to try catch for every occurence.
* @param listener the listener to notify
* @param event the event to fire.
*/
private void notifyListenerDefaultMethod(GerritEventListener listener, GerritEvent event) {
try {
listener.gerritEvent(event);
} catch (Exception ex) {
logger.error("Exception thrown during event handling.", ex);
}
}
/**
* Closes the connection.
* @param join if the method should wait for the thread to finish before returning.
*/
public void shutdown(boolean join) {
if (sshConnection != null) {
logger.info("Shutting down the ssh connection.");
this.shutdownInProgress = true;
sshConnection.disconnect();
if (join) {
try {
this.join();
} catch (InterruptedException ex) {
logger.warn("Got interrupted while waiting for shutdown.", ex);
}
}
} else if (connecting) {
this.shutdownInProgress = true;
if (join) {
try {
this.join();
} catch (InterruptedException ex) {
logger.warn("Got interrupted while waiting for shutdown.", ex);
}
}
} else {
logger.warn("Was told to shutdown without a connection.");
}
}
/**
* Notifies all ConnectionListeners that the connection is down.
*/
protected void notifyConnectionDown() {
synchronized (connectionListeners) {
for (ConnectionListener listener : connectionListeners) {
try {
listener.connectionDown();
} catch (Exception ex) {
logger.error("ConnectionListener threw Exception. ", ex);
}
}
}
}
/**
* Notifies all ConnectionListeners that the connection is established.
*/
protected void notifyConnectionEstablished() {
synchronized (connectionListeners) {
for (ConnectionListener listener : connectionListeners) {
try {
listener.connectionEstablished();
} catch (Exception ex) {
logger.error("ConnectionListener threw Exception. ", ex);
}
}
}
}
}
|
gerrit-events/src/main/java/com/sonyericsson/hudson/plugins/gerrit/gerritevents/GerritHandler.java
|
/*
* The MIT License
*
* Copyright 2010 Sony Ericsson Mobile Communications. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.sonyericsson.hudson.plugins.gerrit.gerritevents;
import com.sonyericsson.hudson.plugins.gerrit.gerritevents.dto.GerritEvent;
import com.sonyericsson.hudson.plugins.gerrit.gerritevents.dto.events.ChangeAbandoned;
import com.sonyericsson.hudson.plugins.gerrit.gerritevents.dto.events.PatchsetCreated;
import com.sonyericsson.hudson.plugins.gerrit.gerritevents.ssh.Authentication;
import com.sonyericsson.hudson.plugins.gerrit.gerritevents.ssh.SshAuthenticationException;
import com.sonyericsson.hudson.plugins.gerrit.gerritevents.ssh.SshConnectException;
import com.sonyericsson.hudson.plugins.gerrit.gerritevents.ssh.SshConnection;
import com.sonyericsson.hudson.plugins.gerrit.gerritevents.workers.Coordinator;
import com.sonyericsson.hudson.plugins.gerrit.gerritevents.workers.EventThread;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.sonyericsson.hudson.plugins.gerrit.gerritevents.GerritDefaultValues.*;
/**
* Main class for this module.
* Contains the main loop for connecting and reading streamed events from Gerrit.
*
* @author Robert Sandell <[email protected]>
*/
public class GerritHandler extends Thread implements Coordinator {
/**
* Time to wait between connection attempts.
*/
public static final int CONNECT_SLEEP = 2000;
private static final String CMD_STREAM_EVENTS = "gerrit stream-events";
private static final Logger logger = LoggerFactory.getLogger(GerritHandler.class);
private BlockingQueue<JSONObject> workQueue;
private String gerritHostName;
private int gerritSshPort;
private Authentication authentication;
private int numberOfWorkerThreads;
private final List<GerritEventListener> gerritEventListeners;
private final List<ConnectionListener> connectionListeners;
private final List<EventThread> workers;
private SshConnection sshConnection;
private boolean shutdownInProgress = false;
private boolean connecting = false;
/**
* Creates a GerritHandler with all the default values set.
* @see #DEFAULT_GERRIT_HOSTNAME
* @see #DEFAULT_GERRIT_SSH_PORT
* @see #DEFAULT_GERRIT_USERNAME
* @see #DEFAULT_AUTH_KEY_FILE
* @see #DEFAULT_AUTH_KEY_FILE_PASSWORD
* @see #DEFAULT_NR_OF_WORKER_THREADS
*/
public GerritHandler() {
this(DEFAULT_GERRIT_HOSTNAME,
DEFAULT_GERRIT_SSH_PORT,
new Authentication(DEFAULT_GERRIT_AUTH_KEY_FILE,
DEFAULT_GERRIT_USERNAME,
DEFAULT_GERRIT_AUTH_KEY_FILE_PASSWORD),
DEFAULT_NR_OF_WORKER_THREADS);
}
/**
* Creates a GerritHandler with the specified values and default number of worker threads.
* @param gerritHostName the hostName
* @param gerritSshPort the ssh port that the gerrit server listens to.
* @param authentication the authentication credentials.
*/
public GerritHandler(String gerritHostName,
int gerritSshPort,
Authentication authentication) {
this(gerritHostName,
gerritSshPort,
authentication,
DEFAULT_NR_OF_WORKER_THREADS);
}
/**
* Creates a GerritHandler with the specified values.
* @param gerritHostName the hostName for gerrit.
* @param gerritSshPort the ssh port that the gerrit server listens to.
* @param authentication the authentication credentials.
* @param numberOfWorkerThreads the number of eventthreads.
*/
public GerritHandler(String gerritHostName,
int gerritSshPort,
Authentication authentication,
int numberOfWorkerThreads) {
super("Gerrit Events Reader");
this.gerritHostName = gerritHostName;
this.gerritSshPort = gerritSshPort;
this.authentication = authentication;
this.numberOfWorkerThreads = numberOfWorkerThreads;
workQueue = new LinkedBlockingQueue<JSONObject>();
gerritEventListeners = new LinkedList<GerritEventListener>();
connectionListeners = new LinkedList<ConnectionListener>();
workers = new ArrayList<EventThread>(numberOfWorkerThreads);
for (int i = 0; i < numberOfWorkerThreads; i++) {
workers.add(new EventThread(this, "Gerrit Worker EventThread_" + i));
}
}
/**
* Main loop for connecting and reading Gerrit JSON Events and dispatching them to Workers.
*/
@Override
public void run() {
logger.info("Starting Up...");
//Start the workers
for (EventThread worker : workers) {
//TODO what if nr of workers are increased/decreased in runtime.
worker.start();
}
do {
sshConnection = connect();
if (sshConnection == null) {
//should mean unrecoverable error
for (EventThread worker : workers) {
worker.shutdown();
}
return;
}
BufferedReader br = null;
try {
logger.trace("Executing stream-events command.");
Reader reader = sshConnection.executeCommandReader(CMD_STREAM_EVENTS);
br = new BufferedReader(reader);
String line = "";
logger.info("Ready to receive data from Gerrit");
notifyConnectionEstablished();
do {
logger.debug("Data-line from Gerrit: {}", line);
JSONObject obj = GerritJsonEventFactory.getJsonObjectIfInterestingAndUsable(line);
if (obj != null) {
try {
logger.trace("putting work on queue: {}", obj);
workQueue.put(obj);
} catch (InterruptedException ex) {
logger.warn("Interrupted while putting work on queue!", ex);
//TODO check if shutdown
//TODO try again since it is important
}
}
logger.trace("Reading next line.");
line = br.readLine();
} while (line != null);
} catch (IOException ex) {
logger.error("Stream events command error. ", ex);
} finally {
logger.trace("Connection closed, ended read loop.");
try {
sshConnection.disconnect();
} catch (Exception ex) {
logger.warn("Error when disconnecting sshConnection.", ex);
}
sshConnection = null;
notifyConnectionDown();
if (br != null) {
try {
br.close();
} catch (IOException ex) {
logger.warn("Could not close events reader.", ex);
}
}
}
} while (!shutdownInProgress);
for (EventThread worker : workers) {
worker.shutdown();
}
logger.debug("End of GerritHandler Thread.");
}
/**
* Connects to the Gerrit server and authenticates as a "Hudson user".
* @return not null if everything is well, null if connect and reconnect failed.
*/
private SshConnection connect() {
connecting = true;
while (true) { //TODO do not go on forever.
if (shutdownInProgress) {
connecting = false;
return null;
}
try {
logger.debug("Connecting...");
SshConnection ssh = new SshConnection(gerritHostName, gerritSshPort, authentication);
notifyConnectionEstablished();
connecting = false;
logger.debug("connection seems ok, returning it.");
return ssh;
} catch (SshConnectException sshConEx) {
logger.error("Could not connect to Gerrit server! "
+ "Host: {} Port: {}", gerritHostName, gerritSshPort);
logger.error(" User: {} KeyFile: {}", authentication.getUsername(), authentication.getPrivateKeyFile());
logger.error("ConnectionException: ", sshConEx);
notifyConnectionDown();
} catch (SshAuthenticationException sshAuthEx) {
logger.error("Could not authenticate to gerrit server!"
+ "\n\tUsername: {}\n\tKeyFile: {}\n\tPassword: {}",
new Object[]{authentication.getUsername(),
authentication.getPrivateKeyFile(),
authentication.getPrivateKeyFilePassword(), });
logger.error("AuthenticationException: ", sshAuthEx);
notifyConnectionDown();
} catch (IOException ex) {
logger.error("Could not connect to Gerrit server! "
+ "Host: {} Port: {}", gerritHostName, gerritSshPort);
logger.error(" User: {} KeyFile: {}", authentication.getUsername(), authentication.getPrivateKeyFile());
logger.error("IOException: ", ex);
notifyConnectionDown();
}
if (shutdownInProgress) {
connecting = false;
return null;
}
//If we end up here, sleep for a while and then go back up in the loop.
logger.trace("Sleeping for a bit.");
try {
Thread.sleep(CONNECT_SLEEP);
} catch (InterruptedException ex) {
logger.warn("Got interrupted while sleeping.", ex);
}
}
}
/**
* Add a GerritEventListener to the list of listeners.
* @param listener the listener to add.
*/
public void addListener(GerritEventListener listener) {
synchronized (gerritEventListeners) {
gerritEventListeners.add(listener);
}
}
/**
* Adds all the provided listeners to the internal list of listeners.
* @param listeners the listeners to add.
*/
public void addEventListeners(Collection<GerritEventListener> listeners) {
synchronized (gerritEventListeners) {
gerritEventListeners.addAll(listeners);
}
}
/**
* Removes a GerritEventListener from the list of listeners.
* @param listener the listener to remove.
*/
public void removeListener(GerritEventListener listener) {
synchronized (gerritEventListeners) {
gerritEventListeners.remove(listener);
}
}
/**
* Removes all event listeners and returns those that where removed.
* @return the former list of listeners.
*/
public List<GerritEventListener> removeAllEventListeners() {
synchronized (gerritEventListeners) {
List<GerritEventListener> listeners = new LinkedList<GerritEventListener>(gerritEventListeners);
gerritEventListeners.clear();
return listeners;
}
}
/**
* Add a ConnectionListener to the list of listeners.
* @param listener the listener to add.
*/
public void addListener(ConnectionListener listener) {
synchronized (connectionListeners) {
connectionListeners.add(listener);
}
}
/**
* Add all ConnectionListeners to the list of listeners.
* @param listeners the listeners to add.
*/
public void addConnectionListeners(Collection<ConnectionListener> listeners) {
synchronized (connectionListeners) {
connectionListeners.addAll(listeners);
}
}
/**
* Removes a ConnectionListener from the list of listeners.
* @param listener the listener to remove.
*/
public void removeListener(ConnectionListener listener) {
synchronized (connectionListeners) {
connectionListeners.remove(listener);
}
}
/**
* Removes all connection listeners and returns those who where remooved.
* @return the list of former listeners.
*/
public List<ConnectionListener> removeAllConnectionListeners() {
synchronized (connectionListeners) {
List<ConnectionListener> listeners = new LinkedList<ConnectionListener>(connectionListeners);
connectionListeners.clear();
return listeners;
}
}
/**
* The authentication credentials for ssh connection.
* @return the credentials.
*/
public Authentication getAuthentication() {
return authentication;
}
/**
* The authentication credentials for ssh connection.
* @param authentication the credentials.
*/
public void setAuthentication(Authentication authentication) {
this.authentication = authentication;
}
/**
* gets the hostname where Gerrit is running.
* @return the hostname.
*/
public String getGerritHostName() {
return gerritHostName;
}
/**
* Sets the hostname where Gerrit is running.
* @param gerritHostName the hostname.
*/
public void setGerritHostName(String gerritHostName) {
this.gerritHostName = gerritHostName;
}
/**
* Gets the port for gerrit ssh commands.
* @return the port nr.
*/
public int getGerritSshPort() {
return gerritSshPort;
}
/**
* Sets the port for gerrit ssh commands.
* @param gerritSshPort the port nr.
*/
public void setGerritSshPort(int gerritSshPort) {
this.gerritSshPort = gerritSshPort;
}
/**
* Gets the number of event worker threads.
* @return the number of threads.
*/
public int getNumberOfWorkerThreads() {
return numberOfWorkerThreads;
}
/**
* Sets the number of worker event threads.
* @param numberOfWorkerThreads the number of threads
*/
public void setNumberOfWorkerThreads(int numberOfWorkerThreads) {
this.numberOfWorkerThreads = numberOfWorkerThreads;
//TODO what if nr of workers are increased/decreased in runtime.
}
@Override
public BlockingQueue<JSONObject> getWorkQueue() {
return workQueue;
}
/**
* Notifies all listeners of a Gerrit event.
* This method is meant to be called by one of the Worker Threads
* {@link com.sonyericsson.hudson.plugins.gerrit.gerritevents.workers.EventThread}
* and not on this Thread which would defeat the purpous of having workers.
* @param event the event.
*/
@Override
public void notifyListeners(GerritEvent event) {
synchronized (gerritEventListeners) {
//Take the performance penalty for synchronization security.
for (GerritEventListener listener : gerritEventListeners) {
notifyListener(listener, event);
}
}
}
/**
* Sub method of {@link #notifyListeners(com.sonyericsson.hudson.plugins.gerrit.gerritevents.dto.GerritEvent) }.
* This is where most of the reflection magic in the event notification is done.
* @param listener the listener to notify
* @param event the event.
*/
private void notifyListener(GerritEventListener listener, GerritEvent event) {
logger.debug("Notifying listener {} of event {}", listener, event);
try {
if (event instanceof PatchsetCreated) {
listener.gerritEvent((PatchsetCreated) event);
} else if (event instanceof ChangeAbandoned) {
listener.gerritEvent((ChangeAbandoned) event);
} else {
listener.gerritEvent(event);
}
} catch (Exception ex) {
logger.error("Exception thrown during event handling.", ex);
}
}
/**
* Sub-method of
* {@link #notifyListener(com.sonyericsson.hudson.plugins.gerrit.gerritevents.GerritEventListener,
* com.sonyericsson.hudson.plugins.gerrit.gerritevents.dto.GerritEvent) .
* It is a convenience method so there is no need to try catch for every occurence.
* @param listener the listener to notify
* @param event the event to fire.
*/
private void notifyListenerDefaultMethod(GerritEventListener listener, GerritEvent event) {
try {
listener.gerritEvent(event);
} catch (Exception ex) {
logger.error("Exception thrown during event handling.", ex);
}
}
/**
* Closes the connection.
* @param join if the method should wait for the thread to finish before returning.
*/
public void shutdown(boolean join) {
if (sshConnection != null) {
logger.info("Shutting down the ssh connection.");
this.shutdownInProgress = true;
sshConnection.disconnect();
if (join) {
try {
this.join();
} catch (InterruptedException ex) {
logger.warn("Got interrupted while waiting for shutdown.", ex);
}
}
} else if (connecting) {
this.shutdownInProgress = true;
if (join) {
try {
this.join();
} catch (InterruptedException ex) {
logger.warn("Got interrupted while waiting for shutdown.", ex);
}
}
} else {
logger.warn("Was told to shutdown without a connection.");
}
}
/**
* Notifies all ConnectionListeners that the connection is down.
*/
protected void notifyConnectionDown() {
synchronized (connectionListeners) {
for (ConnectionListener listener : connectionListeners) {
try {
listener.connectionDown();
} catch (Exception ex) {
logger.error("ConnectionListener threw Exception. ", ex);
}
}
}
}
/**
* Notifies all ConnectionListeners that the connection is established.
*/
protected void notifyConnectionEstablished() {
synchronized (connectionListeners) {
for (ConnectionListener listener : connectionListeners) {
try {
listener.connectionEstablished();
} catch (Exception ex) {
logger.error("ConnectionListener threw Exception. ", ex);
}
}
}
}
}
|
Reconnect thread leak.
The ssh api doesn't close it's threads correctly.
So a disconnect was added so a "bad" connection
doesn't leak any threads when reconnecting.
|
gerrit-events/src/main/java/com/sonyericsson/hudson/plugins/gerrit/gerritevents/GerritHandler.java
|
Reconnect thread leak.
|
<ide><path>errit-events/src/main/java/com/sonyericsson/hudson/plugins/gerrit/gerritevents/GerritHandler.java
<ide> connecting = false;
<ide> return null;
<ide> }
<add> SshConnection ssh = null;
<ide> try {
<ide> logger.debug("Connecting...");
<del> SshConnection ssh = new SshConnection(gerritHostName, gerritSshPort, authentication);
<add> ssh = new SshConnection(gerritHostName, gerritSshPort, authentication);
<ide> notifyConnectionEstablished();
<ide> connecting = false;
<ide> logger.debug("connection seems ok, returning it.");
<ide> notifyConnectionDown();
<ide> }
<ide>
<add> if (ssh != null) {
<add> logger.trace("Disconnecting bad connection.");
<add> try {
<add> //The ssh lib used is starting at least one thread for each connection.
<add> //The thread isn't shutdown properly when the connection goes down,
<add> //so we need to close it "manually"
<add> ssh.disconnect();
<add> } catch(Exception ex) {
<add> logger.warn("Error when disconnecting bad connection.", ex);
<add> } finally {
<add> ssh = null;
<add> }
<add> }
<add>
<ide> if (shutdownInProgress) {
<ide> connecting = false;
<ide> return null;
|
|
Java
|
apache-2.0
|
aa31bc6c313789c344d715b7c1aeea0cd8de47e2
| 0 |
britter/commons-lang,britter/commons-lang,apache/commons-lang,MarkDacek/commons-lang,MarkDacek/commons-lang,apache/commons-lang,arbasha/commons-lang,weston100721/commons-lang,MarkDacek/commons-lang,arbasha/commons-lang,arbasha/commons-lang,weston100721/commons-lang,apache/commons-lang,weston100721/commons-lang,britter/commons-lang
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang3;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* <p>Assists with the serialization process and performs additional functionality based
* on serialization.</p>
*
* <ul>
* <li>Deep clone using serialization
* <li>Serialize managing finally and IOException
* <li>Deserialize managing finally and IOException
* </ul>
*
* <p>This class throws exceptions for invalid {@code null} inputs.
* Each method documents its behaviour in more detail.</p>
*
* <p>#ThreadSafe#</p>
* @since 1.0
*/
public class SerializationUtils {
/**
* <p>SerializationUtils instances should NOT be constructed in standard programming.
* Instead, the class should be used as {@code SerializationUtils.clone(object)}.</p>
*
* <p>This constructor is public to permit tools that require a JavaBean instance
* to operate.</p>
* @since 2.0
*/
public SerializationUtils() {
super();
}
// Clone
//-----------------------------------------------------------------------
/**
* <p>Deep clone an {@code Object} using serialization.</p>
*
* <p>This is many times slower than writing clone methods by hand
* on all objects in your object graph. However, for complex object
* graphs, or for those that don't support deep cloning this can
* be a simple alternative implementation. Of course all the objects
* must be {@code Serializable}.</p>
*
* @param <T> the type of the object involved
* @param object the {@code Serializable} object to clone
* @return the cloned object
* @throws SerializationException (runtime) if the serialization fails
*/
public static <T extends Serializable> T clone(final T object) {
if (object == null) {
return null;
}
final byte[] objectData = serialize(object);
final ByteArrayInputStream bais = new ByteArrayInputStream(objectData);
ClassLoaderAwareObjectInputStream in = null;
try {
// stream closed in the finally
in = new ClassLoaderAwareObjectInputStream(bais, object.getClass().getClassLoader());
/*
* when we serialize and deserialize an object,
* it is reasonable to assume the deserialized object
* is of the same type as the original serialized object
*/
@SuppressWarnings("unchecked") // see above
final T readObject = (T) in.readObject();
return readObject;
} catch (final ClassNotFoundException ex) {
throw new SerializationException("ClassNotFoundException while reading cloned object data", ex);
} catch (final IOException ex) {
throw new SerializationException("IOException while reading cloned object data", ex);
} finally {
try {
if (in != null) {
in.close();
}
} catch (final IOException ex) {
throw new SerializationException("IOException on closing cloned object data InputStream.", ex);
}
}
}
/**
* Performs a serialization roundtrip. Serializes and deserializes the given object, great for testing objects that
* implement {@link Serializable}.
*
* @param <T>
* the type of the object involved
* @param msg
* the object to roundtrip
* @return the serialized and deseralized object
* @since 3.3
*/
@SuppressWarnings("unchecked") // OK, because we serialized a type `T`
public static <T extends Serializable> T roundtrip(final T msg) {
return (T) SerializationUtils.deserialize(SerializationUtils.serialize(msg));
}
// Serialize
//-----------------------------------------------------------------------
/**
* <p>Serializes an {@code Object} to the specified stream.</p>
*
* <p>The stream will be closed once the object is written.
* This avoids the need for a finally clause, and maybe also exception
* handling, in the application code.</p>
*
* <p>The stream passed in is not buffered internally within this method.
* This is the responsibility of your application if desired.</p>
*
* @param obj the object to serialize to bytes, may be null
* @param outputStream the stream to write to, must not be null
* @throws IllegalArgumentException if {@code outputStream} is {@code null}
* @throws SerializationException (runtime) if the serialization fails
*/
public static void serialize(final Serializable obj, final OutputStream outputStream) {
if (outputStream == null) {
throw new IllegalArgumentException("The OutputStream must not be null");
}
ObjectOutputStream out = null;
try {
// stream closed in the finally
out = new ObjectOutputStream(outputStream);
out.writeObject(obj);
} catch (final IOException ex) {
throw new SerializationException(ex);
} finally {
try {
if (out != null) {
out.close();
}
} catch (final IOException ex) { // NOPMD
// ignore close exception
}
}
}
/**
* <p>Serializes an {@code Object} to a byte array for
* storage/serialization.</p>
*
* @param obj the object to serialize to bytes
* @return a byte[] with the converted Serializable
* @throws SerializationException (runtime) if the serialization fails
*/
public static byte[] serialize(final Serializable obj) {
final ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
serialize(obj, baos);
return baos.toByteArray();
}
// Deserialize
//-----------------------------------------------------------------------
/**
* <p>
* Deserializes an {@code Object} from the specified stream.
* </p>
*
* <p>
* The stream will be closed once the object is written. This avoids the need for a finally clause, and maybe also
* exception handling, in the application code.
* </p>
*
* <p>
* The stream passed in is not buffered internally within this method. This is the responsibility of your
* application if desired.
* </p>
*
* <p>
* If the call site incorrectly types the return value, a {@link ClassCastException} is thrown from the call site.
* Without Generics in this declaration, the call site must type cast and can cause the same ClassCastException.
* Note that in both cases, the ClassCastException is in the call site, not in this method.
* </p>
*
* @param <T> the object type to be deserialized
* @param inputStream
* the serialized object input stream, must not be null
* @return the deserialized object
* @throws IllegalArgumentException
* if {@code inputStream} is {@code null}
* @throws SerializationException
* (runtime) if the serialization fails
*/
public static <T> T deserialize(final InputStream inputStream) {
if (inputStream == null) {
throw new IllegalArgumentException("The InputStream must not be null");
}
ObjectInputStream in = null;
try {
// stream closed in the finally
in = new ObjectInputStream(inputStream);
@SuppressWarnings("unchecked") // may fail with CCE if serialised form is incorrect
final T obj = (T) in.readObject();
return obj;
} catch (final ClassCastException ex) {
throw new SerializationException(ex);
} catch (final ClassNotFoundException ex) {
throw new SerializationException(ex);
} catch (final IOException ex) {
throw new SerializationException(ex);
} finally {
try {
if (in != null) {
in.close();
}
} catch (final IOException ex) { // NOPMD
// ignore close exception
}
}
}
/**
* <p>
* Deserializes a single {@code Object} from an array of bytes.
* </p>
*
* <p>
* If the call site incorrectly types the return value, a {@link ClassCastException} is thrown from the call site.
* Without Generics in this declaration, the call site must type cast and can cause the same ClassCastException.
* Note that in both cases, the ClassCastException is in the call site, not in this method.
* </p>
*
* @param <T> the object type to be deserialized
* @param objectData
* the serialized object, must not be null
* @return the deserialized object
* @throws IllegalArgumentException
* if {@code objectData} is {@code null}
* @throws SerializationException
* (runtime) if the serialization fails
*/
public static <T> T deserialize(final byte[] objectData) {
if (objectData == null) {
throw new IllegalArgumentException("The byte[] must not be null");
}
return SerializationUtils.<T>deserialize(new ByteArrayInputStream(objectData));
}
/**
* <p>Custom specialization of the standard JDK {@link java.io.ObjectInputStream}
* that uses a custom <code>ClassLoader</code> to resolve a class.
* If the specified <code>ClassLoader</code> is not able to resolve the class,
* the context classloader of the current thread will be used.
* This way, the standard deserialization work also in web-application
* containers and application servers, no matter in which of the
* <code>ClassLoader</code> the particular class that encapsulates
* serialization/deserialization lives. </p>
*
* <p>For more in-depth information about the problem for which this
* class here is a workaround, see the JIRA issue LANG-626. </p>
*/
static class ClassLoaderAwareObjectInputStream extends ObjectInputStream {
private static final Map<String, Class<?>> primitiveTypes =
new HashMap<String, Class<?>>();
static {
primitiveTypes.put("byte", byte.class);
primitiveTypes.put("short", short.class);
primitiveTypes.put("int", int.class);
primitiveTypes.put("long", long.class);
primitiveTypes.put("float", float.class);
primitiveTypes.put("double", double.class);
primitiveTypes.put("boolean", boolean.class);
primitiveTypes.put("char", char.class);
primitiveTypes.put("void", void.class);
}
private final ClassLoader classLoader;
/**
* Constructor.
* @param in The <code>InputStream</code>.
* @param classLoader classloader to use
* @throws IOException if an I/O error occurs while reading stream header.
* @see java.io.ObjectInputStream
*/
public ClassLoaderAwareObjectInputStream(final InputStream in, final ClassLoader classLoader) throws IOException {
super(in);
this.classLoader = classLoader;
}
/**
* Overriden version that uses the parametrized <code>ClassLoader</code> or the <code>ClassLoader</code>
* of the current <code>Thread</code> to resolve the class.
* @param desc An instance of class <code>ObjectStreamClass</code>.
* @return A <code>Class</code> object corresponding to <code>desc</code>.
* @throws IOException Any of the usual Input/Output exceptions.
* @throws ClassNotFoundException If class of a serialized object cannot be found.
*/
@Override
protected Class<?> resolveClass(final ObjectStreamClass desc) throws IOException, ClassNotFoundException {
final String name = desc.getName();
try {
return Class.forName(name, false, classLoader);
} catch (final ClassNotFoundException ex) {
try {
return Class.forName(name, false, Thread.currentThread().getContextClassLoader());
} catch (final ClassNotFoundException cnfe) {
final Class<?> cls = primitiveTypes.get(name);
if (cls != null) {
return cls;
}
throw cnfe;
}
}
}
}
}
|
src/main/java/org/apache/commons/lang3/SerializationUtils.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang3;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* <p>Assists with the serialization process and performs additional functionality based
* on serialization.</p>
*
* <ul>
* <li>Deep clone using serialization
* <li>Serialize managing finally and IOException
* <li>Deserialize managing finally and IOException
* </ul>
*
* <p>This class throws exceptions for invalid {@code null} inputs.
* Each method documents its behaviour in more detail.</p>
*
* <p>#ThreadSafe#</p>
* @since 1.0
*/
public class SerializationUtils {
/**
* <p>SerializationUtils instances should NOT be constructed in standard programming.
* Instead, the class should be used as {@code SerializationUtils.clone(object)}.</p>
*
* <p>This constructor is public to permit tools that require a JavaBean instance
* to operate.</p>
* @since 2.0
*/
public SerializationUtils() {
super();
}
// Clone
//-----------------------------------------------------------------------
/**
* <p>Deep clone an {@code Object} using serialization.</p>
*
* <p>This is many times slower than writing clone methods by hand
* on all objects in your object graph. However, for complex object
* graphs, or for those that don't support deep cloning this can
* be a simple alternative implementation. Of course all the objects
* must be {@code Serializable}.</p>
*
* @param <T> the type of the object involved
* @param object the {@code Serializable} object to clone
* @return the cloned object
* @throws SerializationException (runtime) if the serialization fails
*/
public static <T extends Serializable> T clone(final T object) {
if (object == null) {
return null;
}
final byte[] objectData = serialize(object);
final ByteArrayInputStream bais = new ByteArrayInputStream(objectData);
ClassLoaderAwareObjectInputStream in = null;
try {
// stream closed in the finally
in = new ClassLoaderAwareObjectInputStream(bais, object.getClass().getClassLoader());
/*
* when we serialize and deserialize an object,
* it is reasonable to assume the deserialized object
* is of the same type as the original serialized object
*/
@SuppressWarnings("unchecked") // see above
final T readObject = (T) in.readObject();
return readObject;
} catch (final ClassNotFoundException ex) {
throw new SerializationException("ClassNotFoundException while reading cloned object data", ex);
} catch (final IOException ex) {
throw new SerializationException("IOException while reading cloned object data", ex);
} finally {
try {
if (in != null) {
in.close();
}
} catch (final IOException ex) {
throw new SerializationException("IOException on closing cloned object data InputStream.", ex);
}
}
}
/**
* Performs a serialization roundtrip. Serializes and deserializes the given object, great for testing objects that
* implement {@link Serializable}.
*
* @param <T>
* the type of the object involved
* @param msg
* the object to roundtrip
* @return the serialized and deseralized object
* @since 3.3
*/
@SuppressWarnings("unchecked") // OK, because we serialized a type `T`
public static <T extends Serializable> T roundtrip(final T msg) {
return (T) SerializationUtils.deserialize(SerializationUtils.serialize(msg));
}
// Serialize
//-----------------------------------------------------------------------
/**
* <p>Serializes an {@code Object} to the specified stream.</p>
*
* <p>The stream will be closed once the object is written.
* This avoids the need for a finally clause, and maybe also exception
* handling, in the application code.</p>
*
* <p>The stream passed in is not buffered internally within this method.
* This is the responsibility of your application if desired.</p>
*
* @param obj the object to serialize to bytes, may be null
* @param outputStream the stream to write to, must not be null
* @throws IllegalArgumentException if {@code outputStream} is {@code null}
* @throws SerializationException (runtime) if the serialization fails
*/
public static void serialize(final Serializable obj, final OutputStream outputStream) {
if (outputStream == null) {
throw new IllegalArgumentException("The OutputStream must not be null");
}
ObjectOutputStream out = null;
try {
// stream closed in the finally
out = new ObjectOutputStream(outputStream);
out.writeObject(obj);
} catch (final IOException ex) {
throw new SerializationException(ex);
} finally {
try {
if (out != null) {
out.close();
}
} catch (final IOException ex) { // NOPMD
// ignore close exception
}
}
}
/**
* <p>Serializes an {@code Object} to a byte array for
* storage/serialization.</p>
*
* @param obj the object to serialize to bytes
* @return a byte[] with the converted Serializable
* @throws SerializationException (runtime) if the serialization fails
*/
public static byte[] serialize(final Serializable obj) {
final ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
serialize(obj, baos);
return baos.toByteArray();
}
// Deserialize
//-----------------------------------------------------------------------
/**
* <p>
* Deserializes an {@code Object} from the specified stream.
* </p>
*
* <p>
* The stream will be closed once the object is written. This avoids the need for a finally clause, and maybe also
* exception handling, in the application code.
* </p>
*
* <p>
* The stream passed in is not buffered internally within this method. This is the responsibility of your
* application if desired.
* </p>
*
* <p>
* If the call site incorrectly types the return value, a {@link ClassCastException} is thrown from the call site.
* Without Generics in this declaration, the call site must type cast and can cause the same ClassCastException.
* Note that in both cases, the ClassCastException is in the call site, not in this method.
* </p>
*
* @param <T> the object type to be deserialized
* @param inputStream
* the serialized object input stream, must not be null
* @return the deserialized object
* @throws IllegalArgumentException
* if {@code inputStream} is {@code null}
* @throws SerializationException
* (runtime) if the serialization fails
*/
public static <T> T deserialize(final InputStream inputStream) {
if (inputStream == null) {
throw new IllegalArgumentException("The InputStream must not be null");
}
ObjectInputStream in = null;
try {
// stream closed in the finally
in = new ObjectInputStream(inputStream);
@SuppressWarnings("unchecked") // may fail with CCE if serialised form is incorrect
final T obj = (T) in.readObject();
return obj;
} catch (final ClassCastException ex) {
throw new SerializationException(ex);
} catch (final ClassNotFoundException ex) {
throw new SerializationException(ex);
} catch (final IOException ex) {
throw new SerializationException(ex);
} finally {
try {
if (in != null) {
in.close();
}
} catch (final IOException ex) { // NOPMD
// ignore close exception
}
}
}
/**
* <p>
* Deserializes a single {@code Object} from an array of bytes.
* </p>
*
* <p>
* If the call site incorrectly types the return value, a {@link ClassCastException} is thrown from the call site.
* Without Generics in this declaration, the call site must type cast and can cause the same ClassCastException.
* Note that in both cases, the ClassCastException is in the call site, not in this method.
* </p>
*
* @param <T> the object type to be deserialized
* @param objectData
* the serialized object, must not be null
* @return the deserialized object
* @throws IllegalArgumentException
* if {@code objectData} is {@code null}
* @throws SerializationException
* (runtime) if the serialization fails
*/
public static <T> T deserialize(final byte[] objectData) {
if (objectData == null) {
throw new IllegalArgumentException("The byte[] must not be null");
}
return SerializationUtils.<T>deserialize(new ByteArrayInputStream(objectData));
}
/**
* <p>Custom specialization of the standard JDK {@link java.io.ObjectInputStream}
* that uses a custom <code>ClassLoader</code> to resolve a class.
* If the specified <code>ClassLoader</code> is not able to resolve the class,
* the context classloader of the current thread will be used.
* This way, the standard deserialization work also in web-application
* containers and application servers, no matter in which of the
* <code>ClassLoader</code> the particular class that encapsulates
* serialization/deserialization lives. </p>
*
* <p>For more in-depth information about the problem for which this
* class here is a workaround, see the JIRA issue LANG-626. </p>
*/
static class ClassLoaderAwareObjectInputStream extends ObjectInputStream {
private static final Map<String, Class<?>> primitiveTypes =
new HashMap<String, Class<?>>();
private final ClassLoader classLoader;
/**
* Constructor.
* @param in The <code>InputStream</code>.
* @param classLoader classloader to use
* @throws IOException if an I/O error occurs while reading stream header.
* @see java.io.ObjectInputStream
*/
public ClassLoaderAwareObjectInputStream(final InputStream in, final ClassLoader classLoader) throws IOException {
super(in);
this.classLoader = classLoader;
primitiveTypes.put("byte", byte.class);
primitiveTypes.put("short", short.class);
primitiveTypes.put("int", int.class);
primitiveTypes.put("long", long.class);
primitiveTypes.put("float", float.class);
primitiveTypes.put("double", double.class);
primitiveTypes.put("boolean", boolean.class);
primitiveTypes.put("char", char.class);
primitiveTypes.put("void", void.class);
}
/**
* Overriden version that uses the parametrized <code>ClassLoader</code> or the <code>ClassLoader</code>
* of the current <code>Thread</code> to resolve the class.
* @param desc An instance of class <code>ObjectStreamClass</code>.
* @return A <code>Class</code> object corresponding to <code>desc</code>.
* @throws IOException Any of the usual Input/Output exceptions.
* @throws ClassNotFoundException If class of a serialized object cannot be found.
*/
@Override
protected Class<?> resolveClass(final ObjectStreamClass desc) throws IOException, ClassNotFoundException {
final String name = desc.getName();
try {
return Class.forName(name, false, classLoader);
} catch (final ClassNotFoundException ex) {
try {
return Class.forName(name, false, Thread.currentThread().getContextClassLoader());
} catch (final ClassNotFoundException cnfe) {
final Class<?> cls = primitiveTypes.get(name);
if (cls != null) {
return cls;
}
throw cnfe;
}
}
}
}
}
|
LANG-1251: SerializationUtils.ClassLoaderAwareObjectInputStream should use static initializer to initialize primitiveTypes map (closes #180)
Modify to use static initializer to initialize primitiveTypes map.
|
src/main/java/org/apache/commons/lang3/SerializationUtils.java
|
LANG-1251: SerializationUtils.ClassLoaderAwareObjectInputStream should use static initializer to initialize primitiveTypes map (closes #180)
|
<ide><path>rc/main/java/org/apache/commons/lang3/SerializationUtils.java
<ide> static class ClassLoaderAwareObjectInputStream extends ObjectInputStream {
<ide> private static final Map<String, Class<?>> primitiveTypes =
<ide> new HashMap<String, Class<?>>();
<add>
<add> static {
<add> primitiveTypes.put("byte", byte.class);
<add> primitiveTypes.put("short", short.class);
<add> primitiveTypes.put("int", int.class);
<add> primitiveTypes.put("long", long.class);
<add> primitiveTypes.put("float", float.class);
<add> primitiveTypes.put("double", double.class);
<add> primitiveTypes.put("boolean", boolean.class);
<add> primitiveTypes.put("char", char.class);
<add> primitiveTypes.put("void", void.class);
<add> }
<add>
<ide> private final ClassLoader classLoader;
<ide>
<ide> /**
<ide> public ClassLoaderAwareObjectInputStream(final InputStream in, final ClassLoader classLoader) throws IOException {
<ide> super(in);
<ide> this.classLoader = classLoader;
<del>
<del> primitiveTypes.put("byte", byte.class);
<del> primitiveTypes.put("short", short.class);
<del> primitiveTypes.put("int", int.class);
<del> primitiveTypes.put("long", long.class);
<del> primitiveTypes.put("float", float.class);
<del> primitiveTypes.put("double", double.class);
<del> primitiveTypes.put("boolean", boolean.class);
<del> primitiveTypes.put("char", char.class);
<del> primitiveTypes.put("void", void.class);
<ide> }
<ide>
<ide> /**
|
|
Java
|
apache-2.0
|
a50a1eaf70394cdbe90a21d9d70a35b15b687917
| 0 |
suntengteng/commons-lang,Ajeet-Ganga/commons-lang,chaoyi66/commons-lang,MarkDacek/commons-lang,Ajeet-Ganga/commons-lang,PascalSchumacher/commons-lang,vanta/commons-lang,PascalSchumacher/commons-lang,jankill/commons-lang,byMan/naya279,jacktan1991/commons-lang,jankill/commons-lang,lovecindy/commons-lang,mohanaraosv/commons-lang,apache/commons-lang,xiwc/commons-lang,jacktan1991/commons-lang,longestname1/commonslang,byMan/naya279,MarkDacek/commons-lang,MuShiiii/commons-lang,vanta/commons-lang,MuShiiii/commons-lang,apache/commons-lang,xuerenlv/commons-lang,xiwc/commons-lang,mohanaraosv/commons-lang,hollycroxton/commons-lang,arbasha/commons-lang,xiwc/commons-lang,arbasha/commons-lang,lovecindy/commons-lang,britter/commons-lang,byMan/naya279,MarkDacek/commons-lang,chaoyi66/commons-lang,apache/commons-lang,lovecindy/commons-lang,suntengteng/commons-lang,weston100721/commons-lang,hollycroxton/commons-lang,mohanaraosv/commons-lang,hollycroxton/commons-lang,PascalSchumacher/commons-lang,weston100721/commons-lang,britter/commons-lang,britter/commons-lang,longestname1/commonslang,jacktan1991/commons-lang,jankill/commons-lang,suntengteng/commons-lang,MuShiiii/commons-lang,Ajeet-Ganga/commons-lang,vanta/commons-lang,weston100721/commons-lang,xuerenlv/commons-lang,chaoyi66/commons-lang,arbasha/commons-lang,longestname1/commonslang,xuerenlv/commons-lang
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang3;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
/**
* <p>Operations on {@link java.lang.String} that are
* <code>null</code> safe.</p>
*
* <ul>
* <li><b>IsEmpty/IsBlank</b>
* - checks if a String contains text</li>
* <li><b>Trim/Strip</b>
* - removes leading and trailing whitespace</li>
* <li><b>Equals</b>
* - compares two strings null-safe</li>
* <li><b>startsWith</b>
* - check if a String starts with a prefix null-safe</li>
* <li><b>endsWith</b>
* - check if a String ends with a suffix null-safe</li>
* <li><b>IndexOf/LastIndexOf/Contains</b>
* - null-safe index-of checks
* <li><b>IndexOfAny/LastIndexOfAny/IndexOfAnyBut/LastIndexOfAnyBut</b>
* - index-of any of a set of Strings</li>
* <li><b>ContainsOnly/ContainsNone/ContainsAny</b>
* - does String contains only/none/any of these characters</li>
* <li><b>Substring/Left/Right/Mid</b>
* - null-safe substring extractions</li>
* <li><b>SubstringBefore/SubstringAfter/SubstringBetween</b>
* - substring extraction relative to other strings</li>
* <li><b>Split/Join</b>
* - splits a String into an array of substrings and vice versa</li>
* <li><b>Remove/Delete</b>
* - removes part of a String</li>
* <li><b>Replace/Overlay</b>
* - Searches a String and replaces one String with another</li>
* <li><b>Chomp/Chop</b>
* - removes the last part of a String</li>
* <li><b>LeftPad/RightPad/Center/Repeat</b>
* - pads a String</li>
* <li><b>UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize</b>
* - changes the case of a String</li>
* <li><b>CountMatches</b>
* - counts the number of occurrences of one String in another</li>
* <li><b>IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable</b>
* - checks the characters in a String</li>
* <li><b>DefaultString</b>
* - protects against a null input String</li>
* <li><b>Reverse/ReverseDelimited</b>
* - reverses a String</li>
* <li><b>Abbreviate</b>
* - abbreviates a string using ellipsis</li>
* <li><b>Difference</b>
* - compares Strings and reports on their differences</li>
* <li><b>LevensteinDistance</b>
* - the number of changes needed to change one String into another</li>
* </ul>
*
* <p>The <code>StringUtils</code> class defines certain words related to
* String handling.</p>
*
* <ul>
* <li>null - <code>null</code></li>
* <li>empty - a zero-length string (<code>""</code>)</li>
* <li>space - the space character (<code>' '</code>, char 32)</li>
* <li>whitespace - the characters defined by {@link Character#isWhitespace(char)}</li>
* <li>trim - the characters <= 32 as in {@link String#trim()}</li>
* </ul>
*
* <p><code>StringUtils</code> handles <code>null</code> input Strings quietly.
* That is to say that a <code>null</code> input will return <code>null</code>.
* Where a <code>boolean</code> or <code>int</code> is being returned
* details vary by method.</p>
*
* <p>A side effect of the <code>null</code> handling is that a
* <code>NullPointerException</code> should be considered a bug in
* <code>StringUtils</code>.</p>
*
* <p>Methods in this class give sample code to explain their operation.
* The symbol <code>*</code> is used to indicate any input including <code>null</code>.</p>
*
* <p>#ThreadSafe#</p>
* @see java.lang.String
* @author Apache Software Foundation
* @author <a href="http://jakarta.apache.org/turbine/">Apache Jakarta Turbine</a>
* @author <a href="mailto:[email protected]">Jon S. Stevens</a>
* @author Daniel L. Rall
* @author <a href="mailto:[email protected]">Greg Coladonato</a>
* @author <a href="mailto:[email protected]">Ed Korthof</a>
* @author <a href="mailto:[email protected]">Rand McNeely</a>
* @author <a href="mailto:[email protected]">Fredrik Westermarck</a>
* @author Holger Krauth
* @author <a href="mailto:[email protected]">Alexander Day Chaffee</a>
* @author <a href="mailto:[email protected]">Henning P. Schmiedehausen</a>
* @author Arun Mammen Thomas
* @author Gary Gregory
* @author Phil Steitz
* @author Al Chou
* @author Michael Davey
* @author Reuben Sivan
* @author Chris Hyzer
* @author Scott Johnson
* @since 1.0
* @version $Id$
*/
//@Immutable
public class StringUtils {
// Performance testing notes (JDK 1.4, Jul03, scolebourne)
// Whitespace:
// Character.isWhitespace() is faster than WHITESPACE.indexOf()
// where WHITESPACE is a string of all whitespace characters
//
// Character access:
// String.charAt(n) versus toCharArray(), then array[n]
// String.charAt(n) is about 15% worse for a 10K string
// They are about equal for a length 50 string
// String.charAt(n) is about 4 times better for a length 3 string
// String.charAt(n) is best bet overall
//
// Append:
// String.concat about twice as fast as StringBuffer.append
// (not sure who tested this)
/**
* The empty String <code>""</code>.
* @since 2.0
*/
public static final String EMPTY = "";
/**
* Represents a failed index search.
* @since 2.1
*/
public static final int INDEX_NOT_FOUND = -1;
/**
* <p>The maximum size to which the padding constant(s) can expand.</p>
*/
private static final int PAD_LIMIT = 8192;
/**
* <p><code>StringUtils</code> instances should NOT be constructed in
* standard programming. Instead, the class should be used as
* <code>StringUtils.trim(" foo ");</code>.</p>
*
* <p>This constructor is public to permit tools that require a JavaBean
* instance to operate.</p>
*/
public StringUtils() {
super();
}
// Empty checks
//-----------------------------------------------------------------------
/**
* <p>Checks if a CharSequence is empty ("") or null.</p>
*
* <pre>
* StringUtils.isEmpty(null) = true
* StringUtils.isEmpty("") = true
* StringUtils.isEmpty(" ") = false
* StringUtils.isEmpty("bob") = false
* StringUtils.isEmpty(" bob ") = false
* </pre>
*
* <p>NOTE: This method changed in Lang version 2.0.
* It no longer trims the CharSequence.
* That functionality is available in isBlank().</p>
*
* @param cs the CharSequence to check, may be null
* @return <code>true</code> if the CharSequence is empty or null
* @since 3.0 Changed signature from isEmpty(String) to isEmpty(CharSequence)
*/
public static boolean isEmpty(CharSequence cs) {
return cs == null || cs.length() == 0;
}
/**
* <p>Checks if a CharSequence is not empty ("") and not null.</p>
*
* <pre>
* StringUtils.isNotEmpty(null) = false
* StringUtils.isNotEmpty("") = false
* StringUtils.isNotEmpty(" ") = true
* StringUtils.isNotEmpty("bob") = true
* StringUtils.isNotEmpty(" bob ") = true
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return <code>true</code> if the CharSequence is not empty and not null
* @since 3.0 Changed signature from isNotEmpty(String) to isNotEmpty(CharSequence)
*/
public static boolean isNotEmpty(CharSequence cs) {
return !StringUtils.isEmpty(cs);
}
/**
* <p>Checks if a CharSequence is whitespace, empty ("") or null.</p>
*
* <pre>
* StringUtils.isBlank(null) = true
* StringUtils.isBlank("") = true
* StringUtils.isBlank(" ") = true
* StringUtils.isBlank("bob") = false
* StringUtils.isBlank(" bob ") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return <code>true</code> if the CharSequence is null, empty or whitespace
* @since 2.0
* @since 3.0 Changed signature from isBlank(String) to isBlank(CharSequence)
*/
public static boolean isBlank(CharSequence cs) {
int strLen;
if (cs == null || (strLen = cs.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(cs.charAt(i)) == false)) {
return false;
}
}
return true;
}
/**
* <p>Checks if a CharSequence is not empty (""), not null and not whitespace only.</p>
*
* <pre>
* StringUtils.isNotBlank(null) = false
* StringUtils.isNotBlank("") = false
* StringUtils.isNotBlank(" ") = false
* StringUtils.isNotBlank("bob") = true
* StringUtils.isNotBlank(" bob ") = true
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return <code>true</code> if the CharSequence is
* not empty and not null and not whitespace
* @since 2.0
* @since 3.0 Changed signature from isNotBlank(String) to isNotBlank(CharSequence)
*/
public static boolean isNotBlank(CharSequence cs) {
return !StringUtils.isBlank(cs);
}
// Trim
//-----------------------------------------------------------------------
/**
* <p>Removes control characters (char <= 32) from both
* ends of this String, handling <code>null</code> by returning
* <code>null</code>.</p>
*
* <p>The String is trimmed using {@link String#trim()}.
* Trim removes start and end characters <= 32.
* To strip whitespace use {@link #strip(String)}.</p>
*
* <p>To trim your choice of characters, use the
* {@link #strip(String, String)} methods.</p>
*
* <pre>
* StringUtils.trim(null) = null
* StringUtils.trim("") = ""
* StringUtils.trim(" ") = ""
* StringUtils.trim("abc") = "abc"
* StringUtils.trim(" abc ") = "abc"
* </pre>
*
* @param str the String to be trimmed, may be null
* @return the trimmed string, <code>null</code> if null String input
*/
public static String trim(String str) {
return str == null ? null : str.trim();
}
/**
* <p>Removes control characters (char <= 32) from both
* ends of this String returning <code>null</code> if the String is
* empty ("") after the trim or if it is <code>null</code>.
*
* <p>The String is trimmed using {@link String#trim()}.
* Trim removes start and end characters <= 32.
* To strip whitespace use {@link #stripToNull(String)}.</p>
*
* <pre>
* StringUtils.trimToNull(null) = null
* StringUtils.trimToNull("") = null
* StringUtils.trimToNull(" ") = null
* StringUtils.trimToNull("abc") = "abc"
* StringUtils.trimToNull(" abc ") = "abc"
* </pre>
*
* @param str the String to be trimmed, may be null
* @return the trimmed String,
* <code>null</code> if only chars <= 32, empty or null String input
* @since 2.0
*/
public static String trimToNull(String str) {
String ts = trim(str);
return isEmpty(ts) ? null : ts;
}
/**
* <p>Removes control characters (char <= 32) from both
* ends of this String returning an empty String ("") if the String
* is empty ("") after the trim or if it is <code>null</code>.
*
* <p>The String is trimmed using {@link String#trim()}.
* Trim removes start and end characters <= 32.
* To strip whitespace use {@link #stripToEmpty(String)}.</p>
*
* <pre>
* StringUtils.trimToEmpty(null) = ""
* StringUtils.trimToEmpty("") = ""
* StringUtils.trimToEmpty(" ") = ""
* StringUtils.trimToEmpty("abc") = "abc"
* StringUtils.trimToEmpty(" abc ") = "abc"
* </pre>
*
* @param str the String to be trimmed, may be null
* @return the trimmed String, or an empty String if <code>null</code> input
* @since 2.0
*/
public static String trimToEmpty(String str) {
return str == null ? EMPTY : str.trim();
}
// Stripping
//-----------------------------------------------------------------------
/**
* <p>Strips whitespace from the start and end of a String.</p>
*
* <p>This is similar to {@link #trim(String)} but removes whitespace.
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.strip(null) = null
* StringUtils.strip("") = ""
* StringUtils.strip(" ") = ""
* StringUtils.strip("abc") = "abc"
* StringUtils.strip(" abc") = "abc"
* StringUtils.strip("abc ") = "abc"
* StringUtils.strip(" abc ") = "abc"
* StringUtils.strip(" ab c ") = "ab c"
* </pre>
*
* @param str the String to remove whitespace from, may be null
* @return the stripped String, <code>null</code> if null String input
*/
public static String strip(String str) {
return strip(str, null);
}
/**
* <p>Strips whitespace from the start and end of a String returning
* <code>null</code> if the String is empty ("") after the strip.</p>
*
* <p>This is similar to {@link #trimToNull(String)} but removes whitespace.
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.stripToNull(null) = null
* StringUtils.stripToNull("") = null
* StringUtils.stripToNull(" ") = null
* StringUtils.stripToNull("abc") = "abc"
* StringUtils.stripToNull(" abc") = "abc"
* StringUtils.stripToNull("abc ") = "abc"
* StringUtils.stripToNull(" abc ") = "abc"
* StringUtils.stripToNull(" ab c ") = "ab c"
* </pre>
*
* @param str the String to be stripped, may be null
* @return the stripped String,
* <code>null</code> if whitespace, empty or null String input
* @since 2.0
*/
public static String stripToNull(String str) {
if (str == null) {
return null;
}
str = strip(str, null);
return str.length() == 0 ? null : str;
}
/**
* <p>Strips whitespace from the start and end of a String returning
* an empty String if <code>null</code> input.</p>
*
* <p>This is similar to {@link #trimToEmpty(String)} but removes whitespace.
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.stripToEmpty(null) = ""
* StringUtils.stripToEmpty("") = ""
* StringUtils.stripToEmpty(" ") = ""
* StringUtils.stripToEmpty("abc") = "abc"
* StringUtils.stripToEmpty(" abc") = "abc"
* StringUtils.stripToEmpty("abc ") = "abc"
* StringUtils.stripToEmpty(" abc ") = "abc"
* StringUtils.stripToEmpty(" ab c ") = "ab c"
* </pre>
*
* @param str the String to be stripped, may be null
* @return the trimmed String, or an empty String if <code>null</code> input
* @since 2.0
*/
public static String stripToEmpty(String str) {
return str == null ? EMPTY : strip(str, null);
}
/**
* <p>Strips any of a set of characters from the start and end of a String.
* This is similar to {@link String#trim()} but allows the characters
* to be stripped to be controlled.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.
* An empty string ("") input returns the empty string.</p>
*
* <p>If the stripChars String is <code>null</code>, whitespace is
* stripped as defined by {@link Character#isWhitespace(char)}.
* Alternatively use {@link #strip(String)}.</p>
*
* <pre>
* StringUtils.strip(null, *) = null
* StringUtils.strip("", *) = ""
* StringUtils.strip("abc", null) = "abc"
* StringUtils.strip(" abc", null) = "abc"
* StringUtils.strip("abc ", null) = "abc"
* StringUtils.strip(" abc ", null) = "abc"
* StringUtils.strip(" abcyx", "xyz") = " abc"
* </pre>
*
* @param str the String to remove characters from, may be null
* @param stripChars the characters to remove, null treated as whitespace
* @return the stripped String, <code>null</code> if null String input
*/
public static String strip(String str, String stripChars) {
if (isEmpty(str)) {
return str;
}
str = stripStart(str, stripChars);
return stripEnd(str, stripChars);
}
/**
* <p>Strips any of a set of characters from the start of a String.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.
* An empty string ("") input returns the empty string.</p>
*
* <p>If the stripChars String is <code>null</code>, whitespace is
* stripped as defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.stripStart(null, *) = null
* StringUtils.stripStart("", *) = ""
* StringUtils.stripStart("abc", "") = "abc"
* StringUtils.stripStart("abc", null) = "abc"
* StringUtils.stripStart(" abc", null) = "abc"
* StringUtils.stripStart("abc ", null) = "abc "
* StringUtils.stripStart(" abc ", null) = "abc "
* StringUtils.stripStart("yxabc ", "xyz") = "abc "
* </pre>
*
* @param str the String to remove characters from, may be null
* @param stripChars the characters to remove, null treated as whitespace
* @return the stripped String, <code>null</code> if null String input
*/
public static String stripStart(String str, String stripChars) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return str;
}
int start = 0;
if (stripChars == null) {
while ((start != strLen) && Character.isWhitespace(str.charAt(start))) {
start++;
}
} else if (stripChars.length() == 0) {
return str;
} else {
while ((start != strLen) && (stripChars.indexOf(str.charAt(start)) != INDEX_NOT_FOUND)) {
start++;
}
}
return str.substring(start);
}
/**
* <p>Strips any of a set of characters from the end of a String.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.
* An empty string ("") input returns the empty string.</p>
*
* <p>If the stripChars String is <code>null</code>, whitespace is
* stripped as defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.stripEnd(null, *) = null
* StringUtils.stripEnd("", *) = ""
* StringUtils.stripEnd("abc", "") = "abc"
* StringUtils.stripEnd("abc", null) = "abc"
* StringUtils.stripEnd(" abc", null) = " abc"
* StringUtils.stripEnd("abc ", null) = "abc"
* StringUtils.stripEnd(" abc ", null) = " abc"
* StringUtils.stripEnd(" abcyx", "xyz") = " abc"
* </pre>
*
* @param str the String to remove characters from, may be null
* @param stripChars the characters to remove, null treated as whitespace
* @return the stripped String, <code>null</code> if null String input
*/
public static String stripEnd(String str, String stripChars) {
int end;
if (str == null || (end = str.length()) == 0) {
return str;
}
if (stripChars == null) {
while ((end != 0) && Character.isWhitespace(str.charAt(end - 1))) {
end--;
}
} else if (stripChars.length() == 0) {
return str;
} else {
while ((end != 0) && (stripChars.indexOf(str.charAt(end - 1)) != INDEX_NOT_FOUND)) {
end--;
}
}
return str.substring(0, end);
}
// StripAll
//-----------------------------------------------------------------------
/**
* <p>Strips whitespace from the start and end of every String in an array.
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <p>A new array is returned each time, except for length zero.
* A <code>null</code> array will return <code>null</code>.
* An empty array will return itself.
* A <code>null</code> array entry will be ignored.</p>
*
* <pre>
* StringUtils.stripAll(null) = null
* StringUtils.stripAll([]) = []
* StringUtils.stripAll(["abc", " abc"]) = ["abc", "abc"]
* StringUtils.stripAll(["abc ", null]) = ["abc", null]
* </pre>
*
* @param strs the array to remove whitespace from, may be null
* @return the stripped Strings, <code>null</code> if null array input
*/
public static String[] stripAll(String[] strs) {
return stripAll(strs, null);
}
/**
* <p>Strips any of a set of characters from the start and end of every
* String in an array.</p>
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <p>A new array is returned each time, except for length zero.
* A <code>null</code> array will return <code>null</code>.
* An empty array will return itself.
* A <code>null</code> array entry will be ignored.
* A <code>null</code> stripChars will strip whitespace as defined by
* {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.stripAll(null, *) = null
* StringUtils.stripAll([], *) = []
* StringUtils.stripAll(["abc", " abc"], null) = ["abc", "abc"]
* StringUtils.stripAll(["abc ", null], null) = ["abc", null]
* StringUtils.stripAll(["abc ", null], "yz") = ["abc ", null]
* StringUtils.stripAll(["yabcz", null], "yz") = ["abc", null]
* </pre>
*
* @param strs the array to remove characters from, may be null
* @param stripChars the characters to remove, null treated as whitespace
* @return the stripped Strings, <code>null</code> if null array input
*/
public static String[] stripAll(String[] strs, String stripChars) {
int strsLen;
if (strs == null || (strsLen = strs.length) == 0) {
return strs;
}
String[] newArr = new String[strsLen];
for (int i = 0; i < strsLen; i++) {
newArr[i] = strip(strs[i], stripChars);
}
return newArr;
}
/**
* <p>Removes the accents from a string. </p>
* <p>NOTE: This is a JDK 1.6 method, it will fail on JDK 1.5. </p>
*
* <pre>
* StringUtils.stripAccents(null) = null
* StringUtils.stripAccents("") = ""
* StringUtils.stripAccents("control") = "control"
* StringUtils.stripAccents("&ecute;clair") = "eclair"
* </pre>
*
* @param input String to be stripped
* @return String without accents on the text
*
* @since 3.0
*/
public static String stripAccents(String input) {
if(input == null) {
return null;
}
if(SystemUtils.isJavaVersionAtLeast(1.6f)) {
// String decomposed = Normalizer.normalize(input, Normalizer.Form.NFD);
// START of 1.5 reflection - in 1.6 use the line commented out above
try {
// get java.text.Normalizer.Form class
Class<?> normalizerFormClass = ClassUtils.getClass("java.text.Normalizer$Form", false);
// get Normlizer class
Class<?> normalizerClass = ClassUtils.getClass("java.text.Normalizer", false);
// get static method on Normalizer
java.lang.reflect.Method method = normalizerClass.getMethod("normalize", CharSequence.class, normalizerFormClass );
// get Normalizer.NFD field
java.lang.reflect.Field nfd = normalizerFormClass.getField("NFD");
// invoke method
String decomposed = (String) method.invoke( null, input, nfd.get(null) );
// END of 1.5 reflection
java.util.regex.Pattern accentPattern = java.util.regex.Pattern.compile("\\p{InCombiningDiacriticalMarks}+");
return accentPattern.matcher(decomposed).replaceAll("");
} catch(ClassNotFoundException cnfe) {
throw new RuntimeException("ClassNotFoundException occurred during 1.6 backcompat code", cnfe);
} catch(NoSuchMethodException nsme) {
throw new RuntimeException("NoSuchMethodException occurred during 1.6 backcompat code", nsme);
} catch(NoSuchFieldException nsfe) {
throw new RuntimeException("NoSuchFieldException occurred during 1.6 backcompat code", nsfe);
} catch(IllegalAccessException iae) {
throw new RuntimeException("IllegalAccessException occurred during 1.6 backcompat code", iae);
} catch(IllegalArgumentException iae) {
throw new RuntimeException("IllegalArgumentException occurred during 1.6 backcompat code", iae);
} catch(java.lang.reflect.InvocationTargetException ite) {
throw new RuntimeException("InvocationTargetException occurred during 1.6 backcompat code", ite);
} catch(SecurityException se) {
throw new RuntimeException("SecurityException occurred during 1.6 backcompat code", se);
}
} else {
throw new UnsupportedOperationException("The stripAccents(String) method is not supported until Java 1.6");
}
}
// Equals
//-----------------------------------------------------------------------
/**
* <p>Compares two CharSequences, returning <code>true</code> if they are equal.</p>
*
* <p><code>null</code>s are handled without exceptions. Two <code>null</code>
* references are considered to be equal. The comparison is case sensitive.</p>
*
* <pre>
* StringUtils.equals(null, null) = true
* StringUtils.equals(null, "abc") = false
* StringUtils.equals("abc", null) = false
* StringUtils.equals("abc", "abc") = true
* StringUtils.equals("abc", "ABC") = false
* </pre>
*
* @see java.lang.String#equals(Object)
* @param cs1 the first CharSequence, may be null
* @param cs2 the second CharSequence, may be null
* @return <code>true</code> if the CharSequences are equal, case sensitive, or
* both <code>null</code>
* @since 3.0 Changed signature from equals(String, String) to equals(CharSequence, CharSequence)
*/
public static boolean equals(CharSequence cs1, CharSequence cs2) {
return cs1 == null ? cs2 == null : cs1.equals(cs2);
}
/**
* <p>Compares two Strings, returning <code>true</code> if they are equal ignoring
* the case.</p>
*
* <p><code>null</code>s are handled without exceptions. Two <code>null</code>
* references are considered equal. Comparison is case insensitive.</p>
*
* <pre>
* StringUtils.equalsIgnoreCase(null, null) = true
* StringUtils.equalsIgnoreCase(null, "abc") = false
* StringUtils.equalsIgnoreCase("abc", null) = false
* StringUtils.equalsIgnoreCase("abc", "abc") = true
* StringUtils.equalsIgnoreCase("abc", "ABC") = true
* </pre>
*
* @see java.lang.String#equalsIgnoreCase(String)
* @param str1 the first String, may be null
* @param str2 the second String, may be null
* @return <code>true</code> if the Strings are equal, case insensitive, or
* both <code>null</code>
*/
public static boolean equalsIgnoreCase(String str1, String str2) {
return str1 == null ? str2 == null : str1.equalsIgnoreCase(str2);
}
// IndexOf
//-----------------------------------------------------------------------
/**
* <p>Finds the first index within a String, handling <code>null</code>.
* This method uses {@link String#indexOf(int)}.</p>
*
* <p>A <code>null</code> or empty ("") String will return <code>INDEX_NOT_FOUND (-1)</code>.</p>
*
* <pre>
* StringUtils.indexOf(null, *) = -1
* StringUtils.indexOf("", *) = -1
* StringUtils.indexOf("aabaabaa", 'a') = 0
* StringUtils.indexOf("aabaabaa", 'b') = 2
* </pre>
*
* @param str the String to check, may be null
* @param searchChar the character to find
* @return the first index of the search character,
* -1 if no match or <code>null</code> string input
* @since 2.0
*/
public static int indexOf(String str, int searchChar) {
if (isEmpty(str)) {
return INDEX_NOT_FOUND;
}
return str.indexOf(searchChar);
}
/**
* <p>Finds the first index within a String from a start position,
* handling <code>null</code>.
* This method uses {@link String#indexOf(int, int)}.</p>
*
* <p>A <code>null</code> or empty ("") String will return <code>(INDEX_NOT_FOUND) -1</code>.
* A negative start position is treated as zero.
* A start position greater than the string length returns <code>-1</code>.</p>
*
* <pre>
* StringUtils.indexOf(null, *, *) = -1
* StringUtils.indexOf("", *, *) = -1
* StringUtils.indexOf("aabaabaa", 'b', 0) = 2
* StringUtils.indexOf("aabaabaa", 'b', 3) = 5
* StringUtils.indexOf("aabaabaa", 'b', 9) = -1
* StringUtils.indexOf("aabaabaa", 'b', -1) = 2
* </pre>
*
* @param str the String to check, may be null
* @param searchChar the character to find
* @param startPos the start position, negative treated as zero
* @return the first index of the search character,
* -1 if no match or <code>null</code> string input
* @since 2.0
*/
public static int indexOf(String str, int searchChar, int startPos) {
if (isEmpty(str)) {
return INDEX_NOT_FOUND;
}
return str.indexOf(searchChar, startPos);
}
/**
* <p>Finds the first index within a String, handling <code>null</code>.
* This method uses {@link String#indexOf(String)}.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.</p>
*
* <pre>
* StringUtils.indexOf(null, *) = -1
* StringUtils.indexOf(*, null) = -1
* StringUtils.indexOf("", "") = 0
* StringUtils.indexOf("", *) = -1 (except when * = "")
* StringUtils.indexOf("aabaabaa", "a") = 0
* StringUtils.indexOf("aabaabaa", "b") = 2
* StringUtils.indexOf("aabaabaa", "ab") = 1
* StringUtils.indexOf("aabaabaa", "") = 0
* </pre>
*
* @param str the String to check, may be null
* @param searchStr the String to find, may be null
* @return the first index of the search String,
* -1 if no match or <code>null</code> string input
* @since 2.0
*/
public static int indexOf(String str, String searchStr) {
if (str == null || searchStr == null) {
return INDEX_NOT_FOUND;
}
return str.indexOf(searchStr);
}
/**
* <p>Finds the first index within a String, handling <code>null</code>.
* This method uses {@link String#indexOf(String, int)}.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.
* A negative start position is treated as zero.
* An empty ("") search String always matches.
* A start position greater than the string length only matches
* an empty search String.</p>
*
* <pre>
* StringUtils.indexOf(null, *, *) = -1
* StringUtils.indexOf(*, null, *) = -1
* StringUtils.indexOf("", "", 0) = 0
* StringUtils.indexOf("", *, 0) = -1 (except when * = "")
* StringUtils.indexOf("aabaabaa", "a", 0) = 0
* StringUtils.indexOf("aabaabaa", "b", 0) = 2
* StringUtils.indexOf("aabaabaa", "ab", 0) = 1
* StringUtils.indexOf("aabaabaa", "b", 3) = 5
* StringUtils.indexOf("aabaabaa", "b", 9) = -1
* StringUtils.indexOf("aabaabaa", "b", -1) = 2
* StringUtils.indexOf("aabaabaa", "", 2) = 2
* StringUtils.indexOf("abc", "", 9) = 3
* </pre>
*
* @param str the String to check, may be null
* @param searchStr the String to find, may be null
* @param startPos the start position, negative treated as zero
* @return the first index of the search String,
* -1 if no match or <code>null</code> string input
* @since 2.0
*/
public static int indexOf(String str, String searchStr, int startPos) {
if (str == null || searchStr == null) {
return INDEX_NOT_FOUND;
}
return str.indexOf(searchStr, startPos);
}
/**
* <p>Finds the n-th index within a String, handling <code>null</code>.
* This method uses {@link String#indexOf(String)}.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.</p>
*
* <pre>
* StringUtils.ordinalIndexOf(null, *, *) = -1
* StringUtils.ordinalIndexOf(*, null, *) = -1
* StringUtils.ordinalIndexOf("", "", *) = 0
* StringUtils.ordinalIndexOf("aabaabaa", "a", 1) = 0
* StringUtils.ordinalIndexOf("aabaabaa", "a", 2) = 1
* StringUtils.ordinalIndexOf("aabaabaa", "b", 1) = 2
* StringUtils.ordinalIndexOf("aabaabaa", "b", 2) = 5
* StringUtils.ordinalIndexOf("aabaabaa", "ab", 1) = 1
* StringUtils.ordinalIndexOf("aabaabaa", "ab", 2) = 4
* StringUtils.ordinalIndexOf("aabaabaa", "", 1) = 0
* StringUtils.ordinalIndexOf("aabaabaa", "", 2) = 0
* </pre>
*
* <p>Note that 'head(String str, int n)' may be implemented as: </p>
*
* <pre>
* str.substring(0, lastOrdinalIndexOf(str, "\n", n))
* </pre>
*
* @param str the String to check, may be null
* @param searchStr the String to find, may be null
* @param ordinal the n-th <code>searchStr</code> to find
* @return the n-th index of the search String,
* <code>-1</code> (<code>INDEX_NOT_FOUND</code>) if no match or <code>null</code> string input
* @since 2.1
*/
public static int ordinalIndexOf(String str, String searchStr, int ordinal) {
return ordinalIndexOf(str, searchStr, ordinal, false);
}
/**
* <p>Finds the n-th index within a String, handling <code>null</code>.
* This method uses {@link String#indexOf(String)}.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.</p>
*
* @param str the String to check, may be null
* @param searchStr the String to find, may be null
* @param ordinal the n-th <code>searchStr</code> to find
* @param lastIndex true if lastOrdinalIndexOf() otherwise false if ordinalIndexOf()
* @return the n-th index of the search String,
* <code>-1</code> (<code>INDEX_NOT_FOUND</code>) if no match or <code>null</code> string input
*/
// Shared code between ordinalIndexOf(String,String,int) and lastOrdinalIndexOf(String,String,int)
private static int ordinalIndexOf(String str, String searchStr, int ordinal, boolean lastIndex) {
if (str == null || searchStr == null || ordinal <= 0) {
return INDEX_NOT_FOUND;
}
if (searchStr.length() == 0) {
return lastIndex ? str.length() : 0;
}
int found = 0;
int index = lastIndex ? str.length() : INDEX_NOT_FOUND;
do {
if(lastIndex) {
index = str.lastIndexOf(searchStr, index - 1);
} else {
index = str.indexOf(searchStr, index + 1);
}
if (index < 0) {
return index;
}
found++;
} while (found < ordinal);
return index;
}
/**
* <p>Case in-sensitive find of the first index within a String.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.
* A negative start position is treated as zero.
* An empty ("") search String always matches.
* A start position greater than the string length only matches
* an empty search String.</p>
*
* <pre>
* StringUtils.indexOfIgnoreCase(null, *) = -1
* StringUtils.indexOfIgnoreCase(*, null) = -1
* StringUtils.indexOfIgnoreCase("", "") = 0
* StringUtils.indexOfIgnoreCase("aabaabaa", "a") = 0
* StringUtils.indexOfIgnoreCase("aabaabaa", "b") = 2
* StringUtils.indexOfIgnoreCase("aabaabaa", "ab") = 1
* </pre>
*
* @param str the String to check, may be null
* @param searchStr the String to find, may be null
* @return the first index of the search String,
* -1 if no match or <code>null</code> string input
* @since 2.5
*/
public static int indexOfIgnoreCase(String str, String searchStr) {
return indexOfIgnoreCase(str, searchStr, 0);
}
/**
* <p>Case in-sensitive find of the first index within a String
* from the specified position.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.
* A negative start position is treated as zero.
* An empty ("") search String always matches.
* A start position greater than the string length only matches
* an empty search String.</p>
*
* <pre>
* StringUtils.indexOfIgnoreCase(null, *, *) = -1
* StringUtils.indexOfIgnoreCase(*, null, *) = -1
* StringUtils.indexOfIgnoreCase("", "", 0) = 0
* StringUtils.indexOfIgnoreCase("aabaabaa", "A", 0) = 0
* StringUtils.indexOfIgnoreCase("aabaabaa", "B", 0) = 2
* StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 0) = 1
* StringUtils.indexOfIgnoreCase("aabaabaa", "B", 3) = 5
* StringUtils.indexOfIgnoreCase("aabaabaa", "B", 9) = -1
* StringUtils.indexOfIgnoreCase("aabaabaa", "B", -1) = 2
* StringUtils.indexOfIgnoreCase("aabaabaa", "", 2) = 2
* StringUtils.indexOfIgnoreCase("abc", "", 9) = 3
* </pre>
*
* @param str the String to check, may be null
* @param searchStr the String to find, may be null
* @param startPos the start position, negative treated as zero
* @return the first index of the search String,
* -1 if no match or <code>null</code> string input
* @since 2.5
*/
public static int indexOfIgnoreCase(String str, String searchStr, int startPos) {
if (str == null || searchStr == null) {
return INDEX_NOT_FOUND;
}
if (startPos < 0) {
startPos = 0;
}
int endLimit = (str.length() - searchStr.length()) + 1;
if (startPos > endLimit) {
return INDEX_NOT_FOUND;
}
if (searchStr.length() == 0) {
return startPos;
}
for (int i = startPos; i < endLimit; i++) {
if (str.regionMatches(true, i, searchStr, 0, searchStr.length())) {
return i;
}
}
return INDEX_NOT_FOUND;
}
// LastIndexOf
//-----------------------------------------------------------------------
/**
* <p>Finds the last index within a String, handling <code>null</code>.
* This method uses {@link String#lastIndexOf(int)}.</p>
*
* <p>A <code>null</code> or empty ("") String will return <code>-1</code>.</p>
*
* <pre>
* StringUtils.lastIndexOf(null, *) = -1
* StringUtils.lastIndexOf("", *) = -1
* StringUtils.lastIndexOf("aabaabaa", 'a') = 7
* StringUtils.lastIndexOf("aabaabaa", 'b') = 5
* </pre>
*
* @param str the String to check, may be null
* @param searchChar the character to find
* @return the last index of the search character,
* -1 if no match or <code>null</code> string input
* @since 2.0
*/
public static int lastIndexOf(String str, int searchChar) {
if (isEmpty(str)) {
return INDEX_NOT_FOUND;
}
return str.lastIndexOf(searchChar);
}
/**
* <p>Finds the last index within a String from a start position,
* handling <code>null</code>.
* This method uses {@link String#lastIndexOf(int, int)}.</p>
*
* <p>A <code>null</code> or empty ("") String will return <code>-1</code>.
* A negative start position returns <code>-1</code>.
* A start position greater than the string length searches the whole string.</p>
*
* <pre>
* StringUtils.lastIndexOf(null, *, *) = -1
* StringUtils.lastIndexOf("", *, *) = -1
* StringUtils.lastIndexOf("aabaabaa", 'b', 8) = 5
* StringUtils.lastIndexOf("aabaabaa", 'b', 4) = 2
* StringUtils.lastIndexOf("aabaabaa", 'b', 0) = -1
* StringUtils.lastIndexOf("aabaabaa", 'b', 9) = 5
* StringUtils.lastIndexOf("aabaabaa", 'b', -1) = -1
* StringUtils.lastIndexOf("aabaabaa", 'a', 0) = 0
* </pre>
*
* @param str the String to check, may be null
* @param searchChar the character to find
* @param startPos the start position
* @return the last index of the search character,
* -1 if no match or <code>null</code> string input
* @since 2.0
*/
public static int lastIndexOf(String str, int searchChar, int startPos) {
if (isEmpty(str)) {
return INDEX_NOT_FOUND;
}
return str.lastIndexOf(searchChar, startPos);
}
/**
* <p>Finds the last index within a String, handling <code>null</code>.
* This method uses {@link String#lastIndexOf(String)}.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.</p>
*
* <pre>
* StringUtils.lastIndexOf(null, *) = -1
* StringUtils.lastIndexOf(*, null) = -1
* StringUtils.lastIndexOf("", "") = 0
* StringUtils.lastIndexOf("aabaabaa", "a") = 7
* StringUtils.lastIndexOf("aabaabaa", "b") = 4
* StringUtils.lastIndexOf("aabaabaa", "ab") = 5
* StringUtils.lastIndexOf("aabaabaa", "") = 8
* </pre>
*
* @param str the String to check, may be null
* @param searchStr the String to find, may be null
* @return the last index of the search String,
* -1 if no match or <code>null</code> string input
* @since 2.0
*/
public static int lastIndexOf(String str, String searchStr) {
if (str == null || searchStr == null) {
return INDEX_NOT_FOUND;
}
return str.lastIndexOf(searchStr);
}
/**
* <p>Finds the n-th last index within a String, handling <code>null</code>.
* This method uses {@link String#lastIndexOf(String)}.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.</p>
*
* <pre>
* StringUtils.lastOrdinalIndexOf(null, *, *) = -1
* StringUtils.lastOrdinalIndexOf(*, null, *) = -1
* StringUtils.lastOrdinalIndexOf("", "", *) = 0
* StringUtils.lastOrdinalIndexOf("aabaabaa", "a", 1) = 7
* StringUtils.lastOrdinalIndexOf("aabaabaa", "a", 2) = 6
* StringUtils.lastOrdinalIndexOf("aabaabaa", "b", 1) = 5
* StringUtils.lastOrdinalIndexOf("aabaabaa", "b", 2) = 2
* StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 1) = 4
* StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 2) = 1
* StringUtils.lastOrdinalIndexOf("aabaabaa", "", 1) = 8
* StringUtils.lastOrdinalIndexOf("aabaabaa", "", 2) = 8
* </pre>
*
* <p>Note that 'tail(String str, int n)' may be implemented as: </p>
*
* <pre>
* str.substring(lastOrdinalIndexOf(str, "\n", n) + 1)
* </pre>
*
* @param str the String to check, may be null
* @param searchStr the String to find, may be null
* @param ordinal the n-th last <code>searchStr</code> to find
* @return the n-th last index of the search String,
* <code>-1</code> (<code>INDEX_NOT_FOUND</code>) if no match or <code>null</code> string input
* @since 2.5
*/
public static int lastOrdinalIndexOf(String str, String searchStr, int ordinal) {
return ordinalIndexOf(str, searchStr, ordinal, true);
}
/**
* <p>Finds the first index within a String, handling <code>null</code>.
* This method uses {@link String#lastIndexOf(String, int)}.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.
* A negative start position returns <code>-1</code>.
* An empty ("") search String always matches unless the start position is negative.
* A start position greater than the string length searches the whole string.</p>
*
* <pre>
* StringUtils.lastIndexOf(null, *, *) = -1
* StringUtils.lastIndexOf(*, null, *) = -1
* StringUtils.lastIndexOf("aabaabaa", "a", 8) = 7
* StringUtils.lastIndexOf("aabaabaa", "b", 8) = 5
* StringUtils.lastIndexOf("aabaabaa", "ab", 8) = 4
* StringUtils.lastIndexOf("aabaabaa", "b", 9) = 5
* StringUtils.lastIndexOf("aabaabaa", "b", -1) = -1
* StringUtils.lastIndexOf("aabaabaa", "a", 0) = 0
* StringUtils.lastIndexOf("aabaabaa", "b", 0) = -1
* </pre>
*
* @param str the String to check, may be null
* @param searchStr the String to find, may be null
* @param startPos the start position, negative treated as zero
* @return the first index of the search String,
* -1 if no match or <code>null</code> string input
* @since 2.0
*/
public static int lastIndexOf(String str, String searchStr, int startPos) {
if (str == null || searchStr == null) {
return INDEX_NOT_FOUND;
}
return str.lastIndexOf(searchStr, startPos);
}
/**
* <p>Case in-sensitive find of the last index within a String.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.
* A negative start position returns <code>-1</code>.
* An empty ("") search String always matches unless the start position is negative.
* A start position greater than the string length searches the whole string.</p>
*
* <pre>
* StringUtils.lastIndexOfIgnoreCase(null, *) = -1
* StringUtils.lastIndexOfIgnoreCase(*, null) = -1
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A") = 7
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B") = 5
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "AB") = 4
* </pre>
*
* @param str the String to check, may be null
* @param searchStr the String to find, may be null
* @return the first index of the search String,
* -1 if no match or <code>null</code> string input
* @since 2.5
*/
public static int lastIndexOfIgnoreCase(String str, String searchStr) {
if (str == null || searchStr == null) {
return INDEX_NOT_FOUND;
}
return lastIndexOfIgnoreCase(str, searchStr, str.length());
}
/**
* <p>Case in-sensitive find of the last index within a String
* from the specified position.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.
* A negative start position returns <code>-1</code>.
* An empty ("") search String always matches unless the start position is negative.
* A start position greater than the string length searches the whole string.</p>
*
* <pre>
* StringUtils.lastIndexOfIgnoreCase(null, *, *) = -1
* StringUtils.lastIndexOfIgnoreCase(*, null, *) = -1
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A", 8) = 7
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 8) = 5
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "AB", 8) = 4
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 9) = 5
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", -1) = -1
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A", 0) = 0
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 0) = -1
* </pre>
*
* @param str the String to check, may be null
* @param searchStr the String to find, may be null
* @param startPos the start position
* @return the first index of the search String,
* -1 if no match or <code>null</code> string input
* @since 2.5
*/
public static int lastIndexOfIgnoreCase(String str, String searchStr, int startPos) {
if (str == null || searchStr == null) {
return INDEX_NOT_FOUND;
}
if (startPos > (str.length() - searchStr.length())) {
startPos = str.length() - searchStr.length();
}
if (startPos < 0) {
return INDEX_NOT_FOUND;
}
if (searchStr.length() == 0) {
return startPos;
}
for (int i = startPos; i >= 0; i--) {
if (str.regionMatches(true, i, searchStr, 0, searchStr.length())) {
return i;
}
}
return INDEX_NOT_FOUND;
}
// Contains
//-----------------------------------------------------------------------
/**
* <p>Checks if String contains a search character, handling <code>null</code>.
* This method uses {@link String#indexOf(int)}.</p>
*
* <p>A <code>null</code> or empty ("") String will return <code>false</code>.</p>
*
* <pre>
* StringUtils.contains(null, *) = false
* StringUtils.contains("", *) = false
* StringUtils.contains("abc", 'a') = true
* StringUtils.contains("abc", 'z') = false
* </pre>
*
* @param str the String to check, may be null
* @param searchChar the character to find
* @return true if the String contains the search character,
* false if not or <code>null</code> string input
* @since 2.0
*/
public static boolean contains(String str, int searchChar) {
if (isEmpty(str)) {
return false;
}
return str.indexOf(searchChar) >= 0;
}
/**
* <p>Checks if String contains a search String, handling <code>null</code>.
* This method uses {@link String#indexOf(String)}.</p>
*
* <p>A <code>null</code> String will return <code>false</code>.</p>
*
* <pre>
* StringUtils.contains(null, *) = false
* StringUtils.contains(*, null) = false
* StringUtils.contains("", "") = true
* StringUtils.contains("abc", "") = true
* StringUtils.contains("abc", "a") = true
* StringUtils.contains("abc", "z") = false
* </pre>
*
* @param str the String to check, may be null
* @param searchStr the String to find, may be null
* @return true if the String contains the search String,
* false if not or <code>null</code> string input
* @since 2.0
*/
public static boolean contains(String str, String searchStr) {
if (str == null || searchStr == null) {
return false;
}
return str.indexOf(searchStr) >= 0;
}
/**
* <p>Checks if String contains a search String irrespective of case,
* handling <code>null</code>. Case-insensitivity is defined as by
* {@link String#equalsIgnoreCase(String)}.
*
* <p>A <code>null</code> String will return <code>false</code>.</p>
*
* <pre>
* StringUtils.contains(null, *) = false
* StringUtils.contains(*, null) = false
* StringUtils.contains("", "") = true
* StringUtils.contains("abc", "") = true
* StringUtils.contains("abc", "a") = true
* StringUtils.contains("abc", "z") = false
* StringUtils.contains("abc", "A") = true
* StringUtils.contains("abc", "Z") = false
* </pre>
*
* @param str the String to check, may be null
* @param searchStr the String to find, may be null
* @return true if the String contains the search String irrespective of
* case or false if not or <code>null</code> string input
*/
public static boolean containsIgnoreCase(String str, String searchStr) {
if (str == null || searchStr == null) {
return false;
}
int len = searchStr.length();
int max = str.length() - len;
for (int i = 0; i <= max; i++) {
if (str.regionMatches(true, i, searchStr, 0, len)) {
return true;
}
}
return false;
}
// IndexOfAny chars
//-----------------------------------------------------------------------
/**
* <p>Search a CharSequence to find the first index of any
* character in the given set of characters.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.
* A <code>null</code> or zero length search array will return <code>-1</code>.</p>
*
* <pre>
* StringUtils.indexOfAny(null, *) = -1
* StringUtils.indexOfAny("", *) = -1
* StringUtils.indexOfAny(*, null) = -1
* StringUtils.indexOfAny(*, []) = -1
* StringUtils.indexOfAny("zzabyycdxx",['z','a']) = 0
* StringUtils.indexOfAny("zzabyycdxx",['b','y']) = 3
* StringUtils.indexOfAny("aba", ['z']) = -1
* </pre>
*
* @param cs the CharSequence to check, may be null
* @param searchChars the chars to search for, may be null
* @return the index of any of the chars, -1 if no match or null input
* @since 2.0
* @since 3.0 Changed signature from indexOfAny(String, char[]) to indexOfAny(CharSequence, char[])
*/
public static int indexOfAny(CharSequence cs, char[] searchChars) {
if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) {
return INDEX_NOT_FOUND;
}
int csLen = cs.length();
int csLast = csLen - 1;
int searchLen = searchChars.length;
int searchLast = searchLen - 1;
for (int i = 0; i < csLen; i++) {
char ch = cs.charAt(i);
for (int j = 0; j < searchLen; j++) {
if (searchChars[j] == ch) {
if (i < csLast && j < searchLast && Character.isHighSurrogate(ch)) {
// ch is a supplementary character
if (searchChars[j + 1] == cs.charAt(i + 1)) {
return i;
}
} else {
return i;
}
}
}
}
return INDEX_NOT_FOUND;
}
/**
* <p>Search a CharSequence to find the first index of any
* character in the given set of characters.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.
* A <code>null</code> search string will return <code>-1</code>.</p>
*
* <pre>
* StringUtils.indexOfAny(null, *) = -1
* StringUtils.indexOfAny("", *) = -1
* StringUtils.indexOfAny(*, null) = -1
* StringUtils.indexOfAny(*, "") = -1
* StringUtils.indexOfAny("zzabyycdxx", "za") = 0
* StringUtils.indexOfAny("zzabyycdxx", "by") = 3
* StringUtils.indexOfAny("aba","z") = -1
* </pre>
*
* @param cs the CharSequence to check, may be null
* @param searchChars the chars to search for, may be null
* @return the index of any of the chars, -1 if no match or null input
* @since 2.0
* @since 3.0 Changed signature from indexOfAny(String, String) to indexOfAny(CharSequence, String)
*/
public static int indexOfAny(CharSequence cs, String searchChars) {
if (isEmpty(cs) || isEmpty(searchChars)) {
return INDEX_NOT_FOUND;
}
return indexOfAny(cs, searchChars.toCharArray());
}
// ContainsAny
//-----------------------------------------------------------------------
/**
* <p>Checks if the CharSequence contains any character in the given
* set of characters.</p>
*
* <p>A <code>null</code> CharSequence will return <code>false</code>.
* A <code>null</code> or zero length search array will return <code>false</code>.</p>
*
* <pre>
* StringUtils.containsAny(null, *) = false
* StringUtils.containsAny("", *) = false
* StringUtils.containsAny(*, null) = false
* StringUtils.containsAny(*, []) = false
* StringUtils.containsAny("zzabyycdxx",['z','a']) = true
* StringUtils.containsAny("zzabyycdxx",['b','y']) = true
* StringUtils.containsAny("aba", ['z']) = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @param searchChars the chars to search for, may be null
* @return the <code>true</code> if any of the chars are found,
* <code>false</code> if no match or null input
* @since 2.4
*/
public static boolean containsAny(String cs, char[] searchChars) {
if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) {
return false;
}
int csLength = cs.length();
int searchLength = searchChars.length;
int csLast = csLength - 1;
int searchLast = searchLength - 1;
for (int i = 0; i < csLength; i++) {
char ch = cs.charAt(i);
for (int j = 0; j < searchLength; j++) {
if (searchChars[j] == ch) {
if (Character.isHighSurrogate(ch)) {
if (j == searchLast) {
// missing low surrogate, fine, like String.indexOf(String)
return true;
}
if (i < csLast && searchChars[j + 1] == cs.charAt(i + 1)) {
return true;
}
} else {
// ch is in the Basic Multilingual Plane
return true;
}
}
}
}
return false;
}
/**
* <p>
* Checks if the CharSequence contains any character in the given set of characters.
* </p>
*
* <p>
* A <code>null</code> CharSequence will return <code>false</code>. A <code>null</code> search CharSequence will return
* <code>false</code>.
* </p>
*
* <pre>
* StringUtils.containsAny(null, *) = false
* StringUtils.containsAny("", *) = false
* StringUtils.containsAny(*, null) = false
* StringUtils.containsAny(*, "") = false
* StringUtils.containsAny("zzabyycdxx", "za") = true
* StringUtils.containsAny("zzabyycdxx", "by") = true
* StringUtils.containsAny("aba","z") = false
* </pre>
*
* @param cs
* the CharSequence to check, may be null
* @param searchChars
* the chars to search for, may be null
* @return the <code>true</code> if any of the chars are found, <code>false</code> if no match or null input
* @since 2.4
*/
public static boolean containsAny(String cs, String searchChars) {
if (searchChars == null) {
return false;
}
return containsAny(cs, searchChars.toCharArray());
}
// IndexOfAnyBut chars
//-----------------------------------------------------------------------
/**
* <p>Searches a CharSequence to find the first index of any
* character not in the given set of characters.</p>
*
* <p>A <code>null</code> CharSequence will return <code>-1</code>.
* A <code>null</code> or zero length search array will return <code>-1</code>.</p>
*
* <pre>
* StringUtils.indexOfAnyBut(null, *) = -1
* StringUtils.indexOfAnyBut("", *) = -1
* StringUtils.indexOfAnyBut(*, null) = -1
* StringUtils.indexOfAnyBut(*, []) = -1
* StringUtils.indexOfAnyBut("zzabyycdxx",'za') = 3
* StringUtils.indexOfAnyBut("zzabyycdxx", '') = 0
* StringUtils.indexOfAnyBut("aba", 'ab') = -1
* </pre>
*
* @param cs the CharSequence to check, may be null
* @param searchChars the chars to search for, may be null
* @return the index of any of the chars, -1 if no match or null input
* @since 2.0
* @since 3.0 Changed signature from indexOfAnyBut(String, char[]) to indexOfAnyBut(CharSequence, char[])
*/
public static int indexOfAnyBut(CharSequence cs, char[] searchChars) {
if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) {
return INDEX_NOT_FOUND;
}
int csLen = cs.length();
int csLast = csLen - 1;
int searchLen = searchChars.length;
int searchLast = searchLen - 1;
outer:
for (int i = 0; i < csLen; i++) {
char ch = cs.charAt(i);
for (int j = 0; j < searchLen; j++) {
if (searchChars[j] == ch) {
if (i < csLast && j < searchLast && Character.isHighSurrogate(ch)) {
if (searchChars[j + 1] == cs.charAt(i + 1)) {
continue outer;
}
} else {
continue outer;
}
}
}
return i;
}
return INDEX_NOT_FOUND;
}
/**
* <p>Search a String to find the first index of any
* character not in the given set of characters.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.
* A <code>null</code> search string will return <code>-1</code>.</p>
*
* <pre>
* StringUtils.indexOfAnyBut(null, *) = -1
* StringUtils.indexOfAnyBut("", *) = -1
* StringUtils.indexOfAnyBut(*, null) = -1
* StringUtils.indexOfAnyBut(*, "") = -1
* StringUtils.indexOfAnyBut("zzabyycdxx", "za") = 3
* StringUtils.indexOfAnyBut("zzabyycdxx", "") = 0
* StringUtils.indexOfAnyBut("aba","ab") = -1
* </pre>
*
* @param str the String to check, may be null
* @param searchChars the chars to search for, may be null
* @return the index of any of the chars, -1 if no match or null input
* @since 2.0
*/
public static int indexOfAnyBut(String str, String searchChars) {
if (isEmpty(str) || isEmpty(searchChars)) {
return INDEX_NOT_FOUND;
}
int strLen = str.length();
for (int i = 0; i < strLen; i++) {
char ch = str.charAt(i);
boolean chFound = searchChars.indexOf(ch) >= 0;
if (i + 1 < strLen && Character.isHighSurrogate(ch)) {
char ch2 = str.charAt(i + 1);
if (chFound && searchChars.indexOf(ch2) < 0) {
return i;
}
} else {
if (!chFound) {
return i;
}
}
}
return INDEX_NOT_FOUND;
}
// ContainsOnly
//-----------------------------------------------------------------------
/**
* <p>Checks if the CharSequence contains only certain characters.</p>
*
* <p>A <code>null</code> CharSequence will return <code>false</code>.
* A <code>null</code> valid character array will return <code>false</code>.
* An empty CharSequence (length()=0) always returns <code>true</code>.</p>
*
* <pre>
* StringUtils.containsOnly(null, *) = false
* StringUtils.containsOnly(*, null) = false
* StringUtils.containsOnly("", *) = true
* StringUtils.containsOnly("ab", '') = false
* StringUtils.containsOnly("abab", 'abc') = true
* StringUtils.containsOnly("ab1", 'abc') = false
* StringUtils.containsOnly("abz", 'abc') = false
* </pre>
*
* @param cs the String to check, may be null
* @param valid an array of valid chars, may be null
* @return true if it only contains valid chars and is non-null
* @since 3.0 Changed signature from containsOnly(String, char[]) to containsOnly(CharSequence, char[])
*/
public static boolean containsOnly(CharSequence cs, char[] valid) {
// All these pre-checks are to maintain API with an older version
if (valid == null || cs == null) {
return false;
}
if (cs.length() == 0) {
return true;
}
if (valid.length == 0) {
return false;
}
return indexOfAnyBut(cs, valid) == INDEX_NOT_FOUND;
}
/**
* <p>Checks if the CharSequence contains only certain characters.</p>
*
* <p>A <code>null</code> CharSequence will return <code>false</code>.
* A <code>null</code> valid character String will return <code>false</code>.
* An empty String (length()=0) always returns <code>true</code>.</p>
*
* <pre>
* StringUtils.containsOnly(null, *) = false
* StringUtils.containsOnly(*, null) = false
* StringUtils.containsOnly("", *) = true
* StringUtils.containsOnly("ab", "") = false
* StringUtils.containsOnly("abab", "abc") = true
* StringUtils.containsOnly("ab1", "abc") = false
* StringUtils.containsOnly("abz", "abc") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @param validChars a String of valid chars, may be null
* @return true if it only contains valid chars and is non-null
* @since 2.0
* @since 3.0 Changed signature from containsOnly(String, String) to containsOnly(CharSequence, String)
*/
public static boolean containsOnly(CharSequence cs, String validChars) {
if (cs == null || validChars == null) {
return false;
}
return containsOnly(cs, validChars.toCharArray());
}
// ContainsNone
//-----------------------------------------------------------------------
/**
* <p>Checks that the CharSequence does not contain certain characters.</p>
*
* <p>A <code>null</code> CharSequence will return <code>true</code>.
* A <code>null</code> invalid character array will return <code>true</code>.
* An empty CharSequence (length()=0) always returns true.</p>
*
* <pre>
* StringUtils.containsNone(null, *) = true
* StringUtils.containsNone(*, null) = true
* StringUtils.containsNone("", *) = true
* StringUtils.containsNone("ab", '') = true
* StringUtils.containsNone("abab", 'xyz') = true
* StringUtils.containsNone("ab1", 'xyz') = true
* StringUtils.containsNone("abz", 'xyz') = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @param searchChars an array of invalid chars, may be null
* @return true if it contains none of the invalid chars, or is null
* @since 2.0
* @since 3.0 Changed signature from containsNone(String, char[]) to containsNone(CharSequence, char[])
*/
public static boolean containsNone(CharSequence cs, char[] searchChars) {
if (cs == null || searchChars == null) {
return true;
}
int csLen = cs.length();
int csLast = csLen - 1;
int searchLen = searchChars.length;
int searchLast = searchLen - 1;
for (int i = 0; i < csLen; i++) {
char ch = cs.charAt(i);
for (int j = 0; j < searchLen; j++) {
if (searchChars[j] == ch) {
if (Character.isHighSurrogate(ch)) {
if (j == searchLast) {
// missing low surrogate, fine, like String.indexOf(String)
return false;
}
if (i < csLast && searchChars[j + 1] == cs.charAt(i + 1)) {
return false;
}
} else {
// ch is in the Basic Multilingual Plane
return false;
}
}
}
}
return true;
}
/**
* <p>Checks that the CharSequence does not contain certain characters.</p>
*
* <p>A <code>null</code> CharSequence will return <code>true</code>.
* A <code>null</code> invalid character array will return <code>true</code>.
* An empty String ("") always returns true.</p>
*
* <pre>
* StringUtils.containsNone(null, *) = true
* StringUtils.containsNone(*, null) = true
* StringUtils.containsNone("", *) = true
* StringUtils.containsNone("ab", "") = true
* StringUtils.containsNone("abab", "xyz") = true
* StringUtils.containsNone("ab1", "xyz") = true
* StringUtils.containsNone("abz", "xyz") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @param invalidChars a String of invalid chars, may be null
* @return true if it contains none of the invalid chars, or is null
* @since 2.0
* @since 3.0 Changed signature from containsNone(String, String) to containsNone(CharSequence, String)
*/
public static boolean containsNone(CharSequence cs, String invalidChars) {
if (cs == null || invalidChars == null) {
return true;
}
return containsNone(cs, invalidChars.toCharArray());
}
// IndexOfAny strings
//-----------------------------------------------------------------------
/**
* <p>Find the first index of any of a set of potential substrings.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.
* A <code>null</code> or zero length search array will return <code>-1</code>.
* A <code>null</code> search array entry will be ignored, but a search
* array containing "" will return <code>0</code> if <code>str</code> is not
* null. This method uses {@link String#indexOf(String)}.</p>
*
* <pre>
* StringUtils.indexOfAny(null, *) = -1
* StringUtils.indexOfAny(*, null) = -1
* StringUtils.indexOfAny(*, []) = -1
* StringUtils.indexOfAny("zzabyycdxx", ["ab","cd"]) = 2
* StringUtils.indexOfAny("zzabyycdxx", ["cd","ab"]) = 2
* StringUtils.indexOfAny("zzabyycdxx", ["mn","op"]) = -1
* StringUtils.indexOfAny("zzabyycdxx", ["zab","aby"]) = 1
* StringUtils.indexOfAny("zzabyycdxx", [""]) = 0
* StringUtils.indexOfAny("", [""]) = 0
* StringUtils.indexOfAny("", ["a"]) = -1
* </pre>
*
* @param str the String to check, may be null
* @param searchStrs the Strings to search for, may be null
* @return the first index of any of the searchStrs in str, -1 if no match
*/
public static int indexOfAny(String str, String[] searchStrs) {
if (str == null || searchStrs == null) {
return INDEX_NOT_FOUND;
}
int sz = searchStrs.length;
// String's can't have a MAX_VALUEth index.
int ret = Integer.MAX_VALUE;
int tmp = 0;
for (int i = 0; i < sz; i++) {
String search = searchStrs[i];
if (search == null) {
continue;
}
tmp = str.indexOf(search);
if (tmp == INDEX_NOT_FOUND) {
continue;
}
if (tmp < ret) {
ret = tmp;
}
}
return (ret == Integer.MAX_VALUE) ? INDEX_NOT_FOUND : ret;
}
/**
* <p>Find the latest index of any of a set of potential substrings.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.
* A <code>null</code> search array will return <code>-1</code>.
* A <code>null</code> or zero length search array entry will be ignored,
* but a search array containing "" will return the length of <code>str</code>
* if <code>str</code> is not null. This method uses {@link String#indexOf(String)}</p>
*
* <pre>
* StringUtils.lastIndexOfAny(null, *) = -1
* StringUtils.lastIndexOfAny(*, null) = -1
* StringUtils.lastIndexOfAny(*, []) = -1
* StringUtils.lastIndexOfAny(*, [null]) = -1
* StringUtils.lastIndexOfAny("zzabyycdxx", ["ab","cd"]) = 6
* StringUtils.lastIndexOfAny("zzabyycdxx", ["cd","ab"]) = 6
* StringUtils.lastIndexOfAny("zzabyycdxx", ["mn","op"]) = -1
* StringUtils.lastIndexOfAny("zzabyycdxx", ["mn","op"]) = -1
* StringUtils.lastIndexOfAny("zzabyycdxx", ["mn",""]) = 10
* </pre>
*
* @param str the String to check, may be null
* @param searchStrs the Strings to search for, may be null
* @return the last index of any of the Strings, -1 if no match
*/
public static int lastIndexOfAny(String str, String[] searchStrs) {
if (str == null || searchStrs == null) {
return INDEX_NOT_FOUND;
}
int sz = searchStrs.length;
int ret = INDEX_NOT_FOUND;
int tmp = 0;
for (int i = 0; i < sz; i++) {
String search = searchStrs[i];
if (search == null) {
continue;
}
tmp = str.lastIndexOf(search);
if (tmp > ret) {
ret = tmp;
}
}
return ret;
}
// Substring
//-----------------------------------------------------------------------
/**
* <p>Gets a substring from the specified String avoiding exceptions.</p>
*
* <p>A negative start position can be used to start <code>n</code>
* characters from the end of the String.</p>
*
* <p>A <code>null</code> String will return <code>null</code>.
* An empty ("") String will return "".</p>
*
* <pre>
* StringUtils.substring(null, *) = null
* StringUtils.substring("", *) = ""
* StringUtils.substring("abc", 0) = "abc"
* StringUtils.substring("abc", 2) = "c"
* StringUtils.substring("abc", 4) = ""
* StringUtils.substring("abc", -2) = "bc"
* StringUtils.substring("abc", -4) = "abc"
* </pre>
*
* @param str the String to get the substring from, may be null
* @param start the position to start from, negative means
* count back from the end of the String by this many characters
* @return substring from start position, <code>null</code> if null String input
*/
public static String substring(String str, int start) {
if (str == null) {
return null;
}
// handle negatives, which means last n characters
if (start < 0) {
start = str.length() + start; // remember start is negative
}
if (start < 0) {
start = 0;
}
if (start > str.length()) {
return EMPTY;
}
return str.substring(start);
}
/**
* <p>Gets a substring from the specified String avoiding exceptions.</p>
*
* <p>A negative start position can be used to start/end <code>n</code>
* characters from the end of the String.</p>
*
* <p>The returned substring starts with the character in the <code>start</code>
* position and ends before the <code>end</code> position. All position counting is
* zero-based -- i.e., to start at the beginning of the string use
* <code>start = 0</code>. Negative start and end positions can be used to
* specify offsets relative to the end of the String.</p>
*
* <p>If <code>start</code> is not strictly to the left of <code>end</code>, ""
* is returned.</p>
*
* <pre>
* StringUtils.substring(null, *, *) = null
* StringUtils.substring("", * , *) = "";
* StringUtils.substring("abc", 0, 2) = "ab"
* StringUtils.substring("abc", 2, 0) = ""
* StringUtils.substring("abc", 2, 4) = "c"
* StringUtils.substring("abc", 4, 6) = ""
* StringUtils.substring("abc", 2, 2) = ""
* StringUtils.substring("abc", -2, -1) = "b"
* StringUtils.substring("abc", -4, 2) = "ab"
* </pre>
*
* @param str the String to get the substring from, may be null
* @param start the position to start from, negative means
* count back from the end of the String by this many characters
* @param end the position to end at (exclusive), negative means
* count back from the end of the String by this many characters
* @return substring from start position to end positon,
* <code>null</code> if null String input
*/
public static String substring(String str, int start, int end) {
if (str == null) {
return null;
}
// handle negatives
if (end < 0) {
end = str.length() + end; // remember end is negative
}
if (start < 0) {
start = str.length() + start; // remember start is negative
}
// check length next
if (end > str.length()) {
end = str.length();
}
// if start is greater than end, return ""
if (start > end) {
return EMPTY;
}
if (start < 0) {
start = 0;
}
if (end < 0) {
end = 0;
}
return str.substring(start, end);
}
// Left/Right/Mid
//-----------------------------------------------------------------------
/**
* <p>Gets the leftmost <code>len</code> characters of a String.</p>
*
* <p>If <code>len</code> characters are not available, or the
* String is <code>null</code>, the String will be returned without
* an exception. An exception is thrown if len is negative.</p>
*
* <pre>
* StringUtils.left(null, *) = null
* StringUtils.left(*, -ve) = ""
* StringUtils.left("", *) = ""
* StringUtils.left("abc", 0) = ""
* StringUtils.left("abc", 2) = "ab"
* StringUtils.left("abc", 4) = "abc"
* </pre>
*
* @param str the String to get the leftmost characters from, may be null
* @param len the length of the required String, must be zero or positive
* @return the leftmost characters, <code>null</code> if null String input
*/
public static String left(String str, int len) {
if (str == null) {
return null;
}
if (len < 0) {
return EMPTY;
}
if (str.length() <= len) {
return str;
}
return str.substring(0, len);
}
/**
* <p>Gets the rightmost <code>len</code> characters of a String.</p>
*
* <p>If <code>len</code> characters are not available, or the String
* is <code>null</code>, the String will be returned without an
* an exception. An exception is thrown if len is negative.</p>
*
* <pre>
* StringUtils.right(null, *) = null
* StringUtils.right(*, -ve) = ""
* StringUtils.right("", *) = ""
* StringUtils.right("abc", 0) = ""
* StringUtils.right("abc", 2) = "bc"
* StringUtils.right("abc", 4) = "abc"
* </pre>
*
* @param str the String to get the rightmost characters from, may be null
* @param len the length of the required String, must be zero or positive
* @return the rightmost characters, <code>null</code> if null String input
*/
public static String right(String str, int len) {
if (str == null) {
return null;
}
if (len < 0) {
return EMPTY;
}
if (str.length() <= len) {
return str;
}
return str.substring(str.length() - len);
}
/**
* <p>Gets <code>len</code> characters from the middle of a String.</p>
*
* <p>If <code>len</code> characters are not available, the remainder
* of the String will be returned without an exception. If the
* String is <code>null</code>, <code>null</code> will be returned.
* An exception is thrown if len is negative.</p>
*
* <pre>
* StringUtils.mid(null, *, *) = null
* StringUtils.mid(*, *, -ve) = ""
* StringUtils.mid("", 0, *) = ""
* StringUtils.mid("abc", 0, 2) = "ab"
* StringUtils.mid("abc", 0, 4) = "abc"
* StringUtils.mid("abc", 2, 4) = "c"
* StringUtils.mid("abc", 4, 2) = ""
* StringUtils.mid("abc", -2, 2) = "ab"
* </pre>
*
* @param str the String to get the characters from, may be null
* @param pos the position to start from, negative treated as zero
* @param len the length of the required String, must be zero or positive
* @return the middle characters, <code>null</code> if null String input
*/
public static String mid(String str, int pos, int len) {
if (str == null) {
return null;
}
if (len < 0 || pos > str.length()) {
return EMPTY;
}
if (pos < 0) {
pos = 0;
}
if (str.length() <= (pos + len)) {
return str.substring(pos);
}
return str.substring(pos, pos + len);
}
// SubStringAfter/SubStringBefore
//-----------------------------------------------------------------------
/**
* <p>Gets the substring before the first occurrence of a separator.
* The separator is not returned.</p>
*
* <p>A <code>null</code> string input will return <code>null</code>.
* An empty ("") string input will return the empty string.
* A <code>null</code> separator will return the input string.</p>
*
* <p>If nothing is found, the string input is returned.</p>
*
* <pre>
* StringUtils.substringBefore(null, *) = null
* StringUtils.substringBefore("", *) = ""
* StringUtils.substringBefore("abc", "a") = ""
* StringUtils.substringBefore("abcba", "b") = "a"
* StringUtils.substringBefore("abc", "c") = "ab"
* StringUtils.substringBefore("abc", "d") = "abc"
* StringUtils.substringBefore("abc", "") = ""
* StringUtils.substringBefore("abc", null) = "abc"
* </pre>
*
* @param str the String to get a substring from, may be null
* @param separator the String to search for, may be null
* @return the substring before the first occurrence of the separator,
* <code>null</code> if null String input
* @since 2.0
*/
public static String substringBefore(String str, String separator) {
if (isEmpty(str) || separator == null) {
return str;
}
if (separator.length() == 0) {
return EMPTY;
}
int pos = str.indexOf(separator);
if (pos == INDEX_NOT_FOUND) {
return str;
}
return str.substring(0, pos);
}
/**
* <p>Gets the substring after the first occurrence of a separator.
* The separator is not returned.</p>
*
* <p>A <code>null</code> string input will return <code>null</code>.
* An empty ("") string input will return the empty string.
* A <code>null</code> separator will return the empty string if the
* input string is not <code>null</code>.</p>
*
* <p>If nothing is found, the empty string is returned.</p>
*
* <pre>
* StringUtils.substringAfter(null, *) = null
* StringUtils.substringAfter("", *) = ""
* StringUtils.substringAfter(*, null) = ""
* StringUtils.substringAfter("abc", "a") = "bc"
* StringUtils.substringAfter("abcba", "b") = "cba"
* StringUtils.substringAfter("abc", "c") = ""
* StringUtils.substringAfter("abc", "d") = ""
* StringUtils.substringAfter("abc", "") = "abc"
* </pre>
*
* @param str the String to get a substring from, may be null
* @param separator the String to search for, may be null
* @return the substring after the first occurrence of the separator,
* <code>null</code> if null String input
* @since 2.0
*/
public static String substringAfter(String str, String separator) {
if (isEmpty(str)) {
return str;
}
if (separator == null) {
return EMPTY;
}
int pos = str.indexOf(separator);
if (pos == INDEX_NOT_FOUND) {
return EMPTY;
}
return str.substring(pos + separator.length());
}
/**
* <p>Gets the substring before the last occurrence of a separator.
* The separator is not returned.</p>
*
* <p>A <code>null</code> string input will return <code>null</code>.
* An empty ("") string input will return the empty string.
* An empty or <code>null</code> separator will return the input string.</p>
*
* <p>If nothing is found, the string input is returned.</p>
*
* <pre>
* StringUtils.substringBeforeLast(null, *) = null
* StringUtils.substringBeforeLast("", *) = ""
* StringUtils.substringBeforeLast("abcba", "b") = "abc"
* StringUtils.substringBeforeLast("abc", "c") = "ab"
* StringUtils.substringBeforeLast("a", "a") = ""
* StringUtils.substringBeforeLast("a", "z") = "a"
* StringUtils.substringBeforeLast("a", null) = "a"
* StringUtils.substringBeforeLast("a", "") = "a"
* </pre>
*
* @param str the String to get a substring from, may be null
* @param separator the String to search for, may be null
* @return the substring before the last occurrence of the separator,
* <code>null</code> if null String input
* @since 2.0
*/
public static String substringBeforeLast(String str, String separator) {
if (isEmpty(str) || isEmpty(separator)) {
return str;
}
int pos = str.lastIndexOf(separator);
if (pos == INDEX_NOT_FOUND) {
return str;
}
return str.substring(0, pos);
}
/**
* <p>Gets the substring after the last occurrence of a separator.
* The separator is not returned.</p>
*
* <p>A <code>null</code> string input will return <code>null</code>.
* An empty ("") string input will return the empty string.
* An empty or <code>null</code> separator will return the empty string if
* the input string is not <code>null</code>.</p>
*
* <p>If nothing is found, the empty string is returned.</p>
*
* <pre>
* StringUtils.substringAfterLast(null, *) = null
* StringUtils.substringAfterLast("", *) = ""
* StringUtils.substringAfterLast(*, "") = ""
* StringUtils.substringAfterLast(*, null) = ""
* StringUtils.substringAfterLast("abc", "a") = "bc"
* StringUtils.substringAfterLast("abcba", "b") = "a"
* StringUtils.substringAfterLast("abc", "c") = ""
* StringUtils.substringAfterLast("a", "a") = ""
* StringUtils.substringAfterLast("a", "z") = ""
* </pre>
*
* @param str the String to get a substring from, may be null
* @param separator the String to search for, may be null
* @return the substring after the last occurrence of the separator,
* <code>null</code> if null String input
* @since 2.0
*/
public static String substringAfterLast(String str, String separator) {
if (isEmpty(str)) {
return str;
}
if (isEmpty(separator)) {
return EMPTY;
}
int pos = str.lastIndexOf(separator);
if (pos == INDEX_NOT_FOUND || pos == (str.length() - separator.length())) {
return EMPTY;
}
return str.substring(pos + separator.length());
}
// Substring between
//-----------------------------------------------------------------------
/**
* <p>Gets the String that is nested in between two instances of the
* same String.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.
* A <code>null</code> tag returns <code>null</code>.</p>
*
* <pre>
* StringUtils.substringBetween(null, *) = null
* StringUtils.substringBetween("", "") = ""
* StringUtils.substringBetween("", "tag") = null
* StringUtils.substringBetween("tagabctag", null) = null
* StringUtils.substringBetween("tagabctag", "") = ""
* StringUtils.substringBetween("tagabctag", "tag") = "abc"
* </pre>
*
* @param str the String containing the substring, may be null
* @param tag the String before and after the substring, may be null
* @return the substring, <code>null</code> if no match
* @since 2.0
*/
public static String substringBetween(String str, String tag) {
return substringBetween(str, tag, tag);
}
/**
* <p>Gets the String that is nested in between two Strings.
* Only the first match is returned.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.
* A <code>null</code> open/close returns <code>null</code> (no match).
* An empty ("") open and close returns an empty string.</p>
*
* <pre>
* StringUtils.substringBetween("wx[b]yz", "[", "]") = "b"
* StringUtils.substringBetween(null, *, *) = null
* StringUtils.substringBetween(*, null, *) = null
* StringUtils.substringBetween(*, *, null) = null
* StringUtils.substringBetween("", "", "") = ""
* StringUtils.substringBetween("", "", "]") = null
* StringUtils.substringBetween("", "[", "]") = null
* StringUtils.substringBetween("yabcz", "", "") = ""
* StringUtils.substringBetween("yabcz", "y", "z") = "abc"
* StringUtils.substringBetween("yabczyabcz", "y", "z") = "abc"
* </pre>
*
* @param str the String containing the substring, may be null
* @param open the String before the substring, may be null
* @param close the String after the substring, may be null
* @return the substring, <code>null</code> if no match
* @since 2.0
*/
public static String substringBetween(String str, String open, String close) {
if (str == null || open == null || close == null) {
return null;
}
int start = str.indexOf(open);
if (start != INDEX_NOT_FOUND) {
int end = str.indexOf(close, start + open.length());
if (end != INDEX_NOT_FOUND) {
return str.substring(start + open.length(), end);
}
}
return null;
}
/**
* <p>Searches a String for substrings delimited by a start and end tag,
* returning all matching substrings in an array.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.
* A <code>null</code> open/close returns <code>null</code> (no match).
* An empty ("") open/close returns <code>null</code> (no match).</p>
*
* <pre>
* StringUtils.substringsBetween("[a][b][c]", "[", "]") = ["a","b","c"]
* StringUtils.substringsBetween(null, *, *) = null
* StringUtils.substringsBetween(*, null, *) = null
* StringUtils.substringsBetween(*, *, null) = null
* StringUtils.substringsBetween("", "[", "]") = []
* </pre>
*
* @param str the String containing the substrings, null returns null, empty returns empty
* @param open the String identifying the start of the substring, empty returns null
* @param close the String identifying the end of the substring, empty returns null
* @return a String Array of substrings, or <code>null</code> if no match
* @since 2.3
*/
public static String[] substringsBetween(String str, String open, String close) {
if (str == null || isEmpty(open) || isEmpty(close)) {
return null;
}
int strLen = str.length();
if (strLen == 0) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
int closeLen = close.length();
int openLen = open.length();
List<String> list = new ArrayList<String>();
int pos = 0;
while (pos < (strLen - closeLen)) {
int start = str.indexOf(open, pos);
if (start < 0) {
break;
}
start += openLen;
int end = str.indexOf(close, start);
if (end < 0) {
break;
}
list.add(str.substring(start, end));
pos = end + closeLen;
}
if (list.isEmpty()) {
return null;
}
return list.toArray(new String [list.size()]);
}
// Nested extraction
//-----------------------------------------------------------------------
// Splitting
//-----------------------------------------------------------------------
/**
* <p>Splits the provided text into an array, using whitespace as the
* separator.
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as one separator.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.split(null) = null
* StringUtils.split("") = []
* StringUtils.split("abc def") = ["abc", "def"]
* StringUtils.split("abc def") = ["abc", "def"]
* StringUtils.split(" abc ") = ["abc"]
* </pre>
*
* @param str the String to parse, may be null
* @return an array of parsed Strings, <code>null</code> if null String input
*/
public static String[] split(String str) {
return split(str, null, -1);
}
/**
* <p>Splits the provided text into an array, separator specified.
* This is an alternative to using StringTokenizer.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as one separator.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.split(null, *) = null
* StringUtils.split("", *) = []
* StringUtils.split("a.b.c", '.') = ["a", "b", "c"]
* StringUtils.split("a..b.c", '.') = ["a", "b", "c"]
* StringUtils.split("a:b:c", '.') = ["a:b:c"]
* StringUtils.split("a b c", ' ') = ["a", "b", "c"]
* </pre>
*
* @param str the String to parse, may be null
* @param separatorChar the character used as the delimiter
* @return an array of parsed Strings, <code>null</code> if null String input
* @since 2.0
*/
public static String[] split(String str, char separatorChar) {
return splitWorker(str, separatorChar, false);
}
/**
* <p>Splits the provided text into an array, separators specified.
* This is an alternative to using StringTokenizer.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as one separator.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.
* A <code>null</code> separatorChars splits on whitespace.</p>
*
* <pre>
* StringUtils.split(null, *) = null
* StringUtils.split("", *) = []
* StringUtils.split("abc def", null) = ["abc", "def"]
* StringUtils.split("abc def", " ") = ["abc", "def"]
* StringUtils.split("abc def", " ") = ["abc", "def"]
* StringUtils.split("ab:cd:ef", ":") = ["ab", "cd", "ef"]
* </pre>
*
* @param str the String to parse, may be null
* @param separatorChars the characters used as the delimiters,
* <code>null</code> splits on whitespace
* @return an array of parsed Strings, <code>null</code> if null String input
*/
public static String[] split(String str, String separatorChars) {
return splitWorker(str, separatorChars, -1, false);
}
/**
* <p>Splits the provided text into an array with a maximum length,
* separators specified.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as one separator.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.
* A <code>null</code> separatorChars splits on whitespace.</p>
*
* <p>If more than <code>max</code> delimited substrings are found, the last
* returned string includes all characters after the first <code>max - 1</code>
* returned strings (including separator characters).</p>
*
* <pre>
* StringUtils.split(null, *, *) = null
* StringUtils.split("", *, *) = []
* StringUtils.split("ab de fg", null, 0) = ["ab", "cd", "ef"]
* StringUtils.split("ab de fg", null, 0) = ["ab", "cd", "ef"]
* StringUtils.split("ab:cd:ef", ":", 0) = ["ab", "cd", "ef"]
* StringUtils.split("ab:cd:ef", ":", 2) = ["ab", "cd:ef"]
* </pre>
*
* @param str the String to parse, may be null
* @param separatorChars the characters used as the delimiters,
* <code>null</code> splits on whitespace
* @param max the maximum number of elements to include in the
* array. A zero or negative value implies no limit
* @return an array of parsed Strings, <code>null</code> if null String input
*/
public static String[] split(String str, String separatorChars, int max) {
return splitWorker(str, separatorChars, max, false);
}
/**
* <p>Splits the provided text into an array, separator string specified.</p>
*
* <p>The separator(s) will not be included in the returned String array.
* Adjacent separators are treated as one separator.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.
* A <code>null</code> separator splits on whitespace.</p>
*
* <pre>
* StringUtils.splitByWholeSeparator(null, *) = null
* StringUtils.splitByWholeSeparator("", *) = []
* StringUtils.splitByWholeSeparator("ab de fg", null) = ["ab", "de", "fg"]
* StringUtils.splitByWholeSeparator("ab de fg", null) = ["ab", "de", "fg"]
* StringUtils.splitByWholeSeparator("ab:cd:ef", ":") = ["ab", "cd", "ef"]
* StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-") = ["ab", "cd", "ef"]
* </pre>
*
* @param str the String to parse, may be null
* @param separator String containing the String to be used as a delimiter,
* <code>null</code> splits on whitespace
* @return an array of parsed Strings, <code>null</code> if null String was input
*/
public static String[] splitByWholeSeparator(String str, String separator) {
return splitByWholeSeparatorWorker( str, separator, -1, false ) ;
}
/**
* <p>Splits the provided text into an array, separator string specified.
* Returns a maximum of <code>max</code> substrings.</p>
*
* <p>The separator(s) will not be included in the returned String array.
* Adjacent separators are treated as one separator.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.
* A <code>null</code> separator splits on whitespace.</p>
*
* <pre>
* StringUtils.splitByWholeSeparator(null, *, *) = null
* StringUtils.splitByWholeSeparator("", *, *) = []
* StringUtils.splitByWholeSeparator("ab de fg", null, 0) = ["ab", "de", "fg"]
* StringUtils.splitByWholeSeparator("ab de fg", null, 0) = ["ab", "de", "fg"]
* StringUtils.splitByWholeSeparator("ab:cd:ef", ":", 2) = ["ab", "cd:ef"]
* StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-", 5) = ["ab", "cd", "ef"]
* StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-", 2) = ["ab", "cd-!-ef"]
* </pre>
*
* @param str the String to parse, may be null
* @param separator String containing the String to be used as a delimiter,
* <code>null</code> splits on whitespace
* @param max the maximum number of elements to include in the returned
* array. A zero or negative value implies no limit.
* @return an array of parsed Strings, <code>null</code> if null String was input
*/
public static String[] splitByWholeSeparator( String str, String separator, int max ) {
return splitByWholeSeparatorWorker(str, separator, max, false);
}
/**
* <p>Splits the provided text into an array, separator string specified. </p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as separators for empty tokens.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.
* A <code>null</code> separator splits on whitespace.</p>
*
* <pre>
* StringUtils.splitByWholeSeparatorPreserveAllTokens(null, *) = null
* StringUtils.splitByWholeSeparatorPreserveAllTokens("", *) = []
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null) = ["ab", "de", "fg"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null) = ["ab", "", "", "de", "fg"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab:cd:ef", ":") = ["ab", "cd", "ef"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab-!-cd-!-ef", "-!-") = ["ab", "cd", "ef"]
* </pre>
*
* @param str the String to parse, may be null
* @param separator String containing the String to be used as a delimiter,
* <code>null</code> splits on whitespace
* @return an array of parsed Strings, <code>null</code> if null String was input
* @since 2.4
*/
public static String[] splitByWholeSeparatorPreserveAllTokens(String str, String separator) {
return splitByWholeSeparatorWorker(str, separator, -1, true);
}
/**
* <p>Splits the provided text into an array, separator string specified.
* Returns a maximum of <code>max</code> substrings.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as separators for empty tokens.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.
* A <code>null</code> separator splits on whitespace.</p>
*
* <pre>
* StringUtils.splitByWholeSeparatorPreserveAllTokens(null, *, *) = null
* StringUtils.splitByWholeSeparatorPreserveAllTokens("", *, *) = []
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null, 0) = ["ab", "de", "fg"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null, 0) = ["ab", "", "", "de", "fg"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab:cd:ef", ":", 2) = ["ab", "cd:ef"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab-!-cd-!-ef", "-!-", 5) = ["ab", "cd", "ef"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab-!-cd-!-ef", "-!-", 2) = ["ab", "cd-!-ef"]
* </pre>
*
* @param str the String to parse, may be null
* @param separator String containing the String to be used as a delimiter,
* <code>null</code> splits on whitespace
* @param max the maximum number of elements to include in the returned
* array. A zero or negative value implies no limit.
* @return an array of parsed Strings, <code>null</code> if null String was input
* @since 2.4
*/
public static String[] splitByWholeSeparatorPreserveAllTokens(String str, String separator, int max) {
return splitByWholeSeparatorWorker(str, separator, max, true);
}
/**
* Performs the logic for the <code>splitByWholeSeparatorPreserveAllTokens</code> methods.
*
* @param str the String to parse, may be <code>null</code>
* @param separator String containing the String to be used as a delimiter,
* <code>null</code> splits on whitespace
* @param max the maximum number of elements to include in the returned
* array. A zero or negative value implies no limit.
* @param preserveAllTokens if <code>true</code>, adjacent separators are
* treated as empty token separators; if <code>false</code>, adjacent
* separators are treated as one separator.
* @return an array of parsed Strings, <code>null</code> if null String input
* @since 2.4
*/
private static String[] splitByWholeSeparatorWorker(String str, String separator, int max,
boolean preserveAllTokens)
{
if (str == null) {
return null;
}
int len = str.length();
if (len == 0) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
if ((separator == null) || (EMPTY.equals(separator))) {
// Split on whitespace.
return splitWorker(str, null, max, preserveAllTokens);
}
int separatorLength = separator.length();
ArrayList<String> substrings = new ArrayList<String>();
int numberOfSubstrings = 0;
int beg = 0;
int end = 0;
while (end < len) {
end = str.indexOf(separator, beg);
if (end > -1) {
if (end > beg) {
numberOfSubstrings += 1;
if (numberOfSubstrings == max) {
end = len;
substrings.add(str.substring(beg));
} else {
// The following is OK, because String.substring( beg, end ) excludes
// the character at the position 'end'.
substrings.add(str.substring(beg, end));
// Set the starting point for the next search.
// The following is equivalent to beg = end + (separatorLength - 1) + 1,
// which is the right calculation:
beg = end + separatorLength;
}
} else {
// We found a consecutive occurrence of the separator, so skip it.
if (preserveAllTokens) {
numberOfSubstrings += 1;
if (numberOfSubstrings == max) {
end = len;
substrings.add(str.substring(beg));
} else {
substrings.add(EMPTY);
}
}
beg = end + separatorLength;
}
} else {
// String.substring( beg ) goes from 'beg' to the end of the String.
substrings.add(str.substring(beg));
end = len;
}
}
return substrings.toArray(new String[substrings.size()]);
}
// -----------------------------------------------------------------------
/**
* <p>Splits the provided text into an array, using whitespace as the
* separator, preserving all tokens, including empty tokens created by
* adjacent separators. This is an alternative to using StringTokenizer.
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as separators for empty tokens.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.splitPreserveAllTokens(null) = null
* StringUtils.splitPreserveAllTokens("") = []
* StringUtils.splitPreserveAllTokens("abc def") = ["abc", "def"]
* StringUtils.splitPreserveAllTokens("abc def") = ["abc", "", "def"]
* StringUtils.splitPreserveAllTokens(" abc ") = ["", "abc", ""]
* </pre>
*
* @param str the String to parse, may be <code>null</code>
* @return an array of parsed Strings, <code>null</code> if null String input
* @since 2.1
*/
public static String[] splitPreserveAllTokens(String str) {
return splitWorker(str, null, -1, true);
}
/**
* <p>Splits the provided text into an array, separator specified,
* preserving all tokens, including empty tokens created by adjacent
* separators. This is an alternative to using StringTokenizer.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as separators for empty tokens.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.splitPreserveAllTokens(null, *) = null
* StringUtils.splitPreserveAllTokens("", *) = []
* StringUtils.splitPreserveAllTokens("a.b.c", '.') = ["a", "b", "c"]
* StringUtils.splitPreserveAllTokens("a..b.c", '.') = ["a", "", "b", "c"]
* StringUtils.splitPreserveAllTokens("a:b:c", '.') = ["a:b:c"]
* StringUtils.splitPreserveAllTokens("a\tb\nc", null) = ["a", "b", "c"]
* StringUtils.splitPreserveAllTokens("a b c", ' ') = ["a", "b", "c"]
* StringUtils.splitPreserveAllTokens("a b c ", ' ') = ["a", "b", "c", ""]
* StringUtils.splitPreserveAllTokens("a b c ", ' ') = ["a", "b", "c", "", ""]
* StringUtils.splitPreserveAllTokens(" a b c", ' ') = ["", a", "b", "c"]
* StringUtils.splitPreserveAllTokens(" a b c", ' ') = ["", "", a", "b", "c"]
* StringUtils.splitPreserveAllTokens(" a b c ", ' ') = ["", a", "b", "c", ""]
* </pre>
*
* @param str the String to parse, may be <code>null</code>
* @param separatorChar the character used as the delimiter,
* <code>null</code> splits on whitespace
* @return an array of parsed Strings, <code>null</code> if null String input
* @since 2.1
*/
public static String[] splitPreserveAllTokens(String str, char separatorChar) {
return splitWorker(str, separatorChar, true);
}
/**
* Performs the logic for the <code>split</code> and
* <code>splitPreserveAllTokens</code> methods that do not return a
* maximum array length.
*
* @param str the String to parse, may be <code>null</code>
* @param separatorChar the separate character
* @param preserveAllTokens if <code>true</code>, adjacent separators are
* treated as empty token separators; if <code>false</code>, adjacent
* separators are treated as one separator.
* @return an array of parsed Strings, <code>null</code> if null String input
*/
private static String[] splitWorker(String str, char separatorChar, boolean preserveAllTokens) {
// Performance tuned for 2.0 (JDK1.4)
if (str == null) {
return null;
}
int len = str.length();
if (len == 0) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
List<String> list = new ArrayList<String>();
int i = 0, start = 0;
boolean match = false;
boolean lastMatch = false;
while (i < len) {
if (str.charAt(i) == separatorChar) {
if (match || preserveAllTokens) {
list.add(str.substring(start, i));
match = false;
lastMatch = true;
}
start = ++i;
continue;
}
lastMatch = false;
match = true;
i++;
}
if (match || (preserveAllTokens && lastMatch)) {
list.add(str.substring(start, i));
}
return list.toArray(new String[list.size()]);
}
/**
* <p>Splits the provided text into an array, separators specified,
* preserving all tokens, including empty tokens created by adjacent
* separators. This is an alternative to using StringTokenizer.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as separators for empty tokens.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.
* A <code>null</code> separatorChars splits on whitespace.</p>
*
* <pre>
* StringUtils.splitPreserveAllTokens(null, *) = null
* StringUtils.splitPreserveAllTokens("", *) = []
* StringUtils.splitPreserveAllTokens("abc def", null) = ["abc", "def"]
* StringUtils.splitPreserveAllTokens("abc def", " ") = ["abc", "def"]
* StringUtils.splitPreserveAllTokens("abc def", " ") = ["abc", "", def"]
* StringUtils.splitPreserveAllTokens("ab:cd:ef", ":") = ["ab", "cd", "ef"]
* StringUtils.splitPreserveAllTokens("ab:cd:ef:", ":") = ["ab", "cd", "ef", ""]
* StringUtils.splitPreserveAllTokens("ab:cd:ef::", ":") = ["ab", "cd", "ef", "", ""]
* StringUtils.splitPreserveAllTokens("ab::cd:ef", ":") = ["ab", "", cd", "ef"]
* StringUtils.splitPreserveAllTokens(":cd:ef", ":") = ["", cd", "ef"]
* StringUtils.splitPreserveAllTokens("::cd:ef", ":") = ["", "", cd", "ef"]
* StringUtils.splitPreserveAllTokens(":cd:ef:", ":") = ["", cd", "ef", ""]
* </pre>
*
* @param str the String to parse, may be <code>null</code>
* @param separatorChars the characters used as the delimiters,
* <code>null</code> splits on whitespace
* @return an array of parsed Strings, <code>null</code> if null String input
* @since 2.1
*/
public static String[] splitPreserveAllTokens(String str, String separatorChars) {
return splitWorker(str, separatorChars, -1, true);
}
/**
* <p>Splits the provided text into an array with a maximum length,
* separators specified, preserving all tokens, including empty tokens
* created by adjacent separators.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as separators for empty tokens.
* Adjacent separators are treated as one separator.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.
* A <code>null</code> separatorChars splits on whitespace.</p>
*
* <p>If more than <code>max</code> delimited substrings are found, the last
* returned string includes all characters after the first <code>max - 1</code>
* returned strings (including separator characters).</p>
*
* <pre>
* StringUtils.splitPreserveAllTokens(null, *, *) = null
* StringUtils.splitPreserveAllTokens("", *, *) = []
* StringUtils.splitPreserveAllTokens("ab de fg", null, 0) = ["ab", "cd", "ef"]
* StringUtils.splitPreserveAllTokens("ab de fg", null, 0) = ["ab", "cd", "ef"]
* StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 0) = ["ab", "cd", "ef"]
* StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 2) = ["ab", "cd:ef"]
* StringUtils.splitPreserveAllTokens("ab de fg", null, 2) = ["ab", " de fg"]
* StringUtils.splitPreserveAllTokens("ab de fg", null, 3) = ["ab", "", " de fg"]
* StringUtils.splitPreserveAllTokens("ab de fg", null, 4) = ["ab", "", "", "de fg"]
* </pre>
*
* @param str the String to parse, may be <code>null</code>
* @param separatorChars the characters used as the delimiters,
* <code>null</code> splits on whitespace
* @param max the maximum number of elements to include in the
* array. A zero or negative value implies no limit
* @return an array of parsed Strings, <code>null</code> if null String input
* @since 2.1
*/
public static String[] splitPreserveAllTokens(String str, String separatorChars, int max) {
return splitWorker(str, separatorChars, max, true);
}
/**
* Performs the logic for the <code>split</code> and
* <code>splitPreserveAllTokens</code> methods that return a maximum array
* length.
*
* @param str the String to parse, may be <code>null</code>
* @param separatorChars the separate character
* @param max the maximum number of elements to include in the
* array. A zero or negative value implies no limit.
* @param preserveAllTokens if <code>true</code>, adjacent separators are
* treated as empty token separators; if <code>false</code>, adjacent
* separators are treated as one separator.
* @return an array of parsed Strings, <code>null</code> if null String input
*/
private static String[] splitWorker(String str, String separatorChars, int max, boolean preserveAllTokens) {
// Performance tuned for 2.0 (JDK1.4)
// Direct code is quicker than StringTokenizer.
// Also, StringTokenizer uses isSpace() not isWhitespace()
if (str == null) {
return null;
}
int len = str.length();
if (len == 0) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
List<String> list = new ArrayList<String>();
int sizePlus1 = 1;
int i = 0, start = 0;
boolean match = false;
boolean lastMatch = false;
if (separatorChars == null) {
// Null separator means use whitespace
while (i < len) {
if (Character.isWhitespace(str.charAt(i))) {
if (match || preserveAllTokens) {
lastMatch = true;
if (sizePlus1++ == max) {
i = len;
lastMatch = false;
}
list.add(str.substring(start, i));
match = false;
}
start = ++i;
continue;
}
lastMatch = false;
match = true;
i++;
}
} else if (separatorChars.length() == 1) {
// Optimise 1 character case
char sep = separatorChars.charAt(0);
while (i < len) {
if (str.charAt(i) == sep) {
if (match || preserveAllTokens) {
lastMatch = true;
if (sizePlus1++ == max) {
i = len;
lastMatch = false;
}
list.add(str.substring(start, i));
match = false;
}
start = ++i;
continue;
}
lastMatch = false;
match = true;
i++;
}
} else {
// standard case
while (i < len) {
if (separatorChars.indexOf(str.charAt(i)) >= 0) {
if (match || preserveAllTokens) {
lastMatch = true;
if (sizePlus1++ == max) {
i = len;
lastMatch = false;
}
list.add(str.substring(start, i));
match = false;
}
start = ++i;
continue;
}
lastMatch = false;
match = true;
i++;
}
}
if (match || (preserveAllTokens && lastMatch)) {
list.add(str.substring(start, i));
}
return list.toArray(new String[list.size()]);
}
/**
* <p>Splits a String by Character type as returned by
* <code>java.lang.Character.getType(char)</code>. Groups of contiguous
* characters of the same type are returned as complete tokens.
* <pre>
* StringUtils.splitByCharacterType(null) = null
* StringUtils.splitByCharacterType("") = []
* StringUtils.splitByCharacterType("ab de fg") = ["ab", " ", "de", " ", "fg"]
* StringUtils.splitByCharacterType("ab de fg") = ["ab", " ", "de", " ", "fg"]
* StringUtils.splitByCharacterType("ab:cd:ef") = ["ab", ":", "cd", ":", "ef"]
* StringUtils.splitByCharacterType("number5") = ["number", "5"]
* StringUtils.splitByCharacterType("fooBar") = ["foo", "B", "ar"]
* StringUtils.splitByCharacterType("foo200Bar") = ["foo", "200", "B", "ar"]
* StringUtils.splitByCharacterType("ASFRules") = ["ASFR", "ules"]
* </pre>
* @param str the String to split, may be <code>null</code>
* @return an array of parsed Strings, <code>null</code> if null String input
* @since 2.4
*/
public static String[] splitByCharacterType(String str) {
return splitByCharacterType(str, false);
}
/**
* <p>Splits a String by Character type as returned by
* <code>java.lang.Character.getType(char)</code>. Groups of contiguous
* characters of the same type are returned as complete tokens, with the
* following exception: the character of type
* <code>Character.UPPERCASE_LETTER</code>, if any, immediately
* preceding a token of type <code>Character.LOWERCASE_LETTER</code>
* will belong to the following token rather than to the preceding, if any,
* <code>Character.UPPERCASE_LETTER</code> token.
* <pre>
* StringUtils.splitByCharacterTypeCamelCase(null) = null
* StringUtils.splitByCharacterTypeCamelCase("") = []
* StringUtils.splitByCharacterTypeCamelCase("ab de fg") = ["ab", " ", "de", " ", "fg"]
* StringUtils.splitByCharacterTypeCamelCase("ab de fg") = ["ab", " ", "de", " ", "fg"]
* StringUtils.splitByCharacterTypeCamelCase("ab:cd:ef") = ["ab", ":", "cd", ":", "ef"]
* StringUtils.splitByCharacterTypeCamelCase("number5") = ["number", "5"]
* StringUtils.splitByCharacterTypeCamelCase("fooBar") = ["foo", "Bar"]
* StringUtils.splitByCharacterTypeCamelCase("foo200Bar") = ["foo", "200", "Bar"]
* StringUtils.splitByCharacterTypeCamelCase("ASFRules") = ["ASF", "Rules"]
* </pre>
* @param str the String to split, may be <code>null</code>
* @return an array of parsed Strings, <code>null</code> if null String input
* @since 2.4
*/
public static String[] splitByCharacterTypeCamelCase(String str) {
return splitByCharacterType(str, true);
}
/**
* <p>Splits a String by Character type as returned by
* <code>java.lang.Character.getType(char)</code>. Groups of contiguous
* characters of the same type are returned as complete tokens, with the
* following exception: if <code>camelCase</code> is <code>true</code>,
* the character of type <code>Character.UPPERCASE_LETTER</code>, if any,
* immediately preceding a token of type <code>Character.LOWERCASE_LETTER</code>
* will belong to the following token rather than to the preceding, if any,
* <code>Character.UPPERCASE_LETTER</code> token.
* @param str the String to split, may be <code>null</code>
* @param camelCase whether to use so-called "camel-case" for letter types
* @return an array of parsed Strings, <code>null</code> if null String input
* @since 2.4
*/
private static String[] splitByCharacterType(String str, boolean camelCase) {
if (str == null) {
return null;
}
if (str.length() == 0) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
char[] c = str.toCharArray();
List<String> list = new ArrayList<String>();
int tokenStart = 0;
int currentType = Character.getType(c[tokenStart]);
for (int pos = tokenStart + 1; pos < c.length; pos++) {
int type = Character.getType(c[pos]);
if (type == currentType) {
continue;
}
if (camelCase && type == Character.LOWERCASE_LETTER && currentType == Character.UPPERCASE_LETTER) {
int newTokenStart = pos - 1;
if (newTokenStart != tokenStart) {
list.add(new String(c, tokenStart, newTokenStart - tokenStart));
tokenStart = newTokenStart;
}
} else {
list.add(new String(c, tokenStart, pos - tokenStart));
tokenStart = pos;
}
currentType = type;
}
list.add(new String(c, tokenStart, c.length - tokenStart));
return list.toArray(new String[list.size()]);
}
// Joining
//-----------------------------------------------------------------------
/**
* <p>Joins the provided elements into a single String. </p>
*
* <p>No separator is added to the joined String.
* Null objects or empty string elements are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.concat("a", "b", "c") = "abc"
* StringUtils.concat(null, "", "a") = "a"
* </pre>
*
* @param elements the values to join together
* @return the concatenated String
* @since 3.0
*/
public static String concat(Object... elements) {
return join(elements, null);
}
/**
* <p>Joins the provided elements into a single String, with the specified
* separator between each element. </p>
*
* <p>No separator is added before or after the joined String.
* Null objects or empty string elements are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.concatWith(".", "a", "b", "c") = "a.b.c"
* StringUtils.concatWith("", null, "", "a") = "a"
* </pre>
*
* @param separator the value to put between elements
* @param elements the values to join together
* @return the concatenated String
* @since 3.0
*/
public static String concatWith(String separator, Object... elements) {
return join(elements, separator);
}
/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* <p>No separator is added to the joined String.
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null) = null
* StringUtils.join([]) = ""
* StringUtils.join([null]) = ""
* StringUtils.join(["a", "b", "c"]) = "abc"
* StringUtils.join([null, "", "a"]) = "a"
* </pre>
*
* @param array the array of values to join together, may be null
* @return the joined String, <code>null</code> if null array input
* @since 2.0
*/
public static String join(Object[] array) {
return join(array, null);
}
/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* <p>No delimiter is added before or after the list.
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join(["a", "b", "c"], ';') = "a;b;c"
* StringUtils.join(["a", "b", "c"], null) = "abc"
* StringUtils.join([null, "", "a"], ';') = ";;a"
* </pre>
*
* @param array the array of values to join together, may be null
* @param separator the separator character to use
* @return the joined String, <code>null</code> if null array input
* @since 2.0
*/
public static String join(Object[] array, char separator) {
if (array == null) {
return null;
}
return join(array, separator, 0, array.length);
}
/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* <p>No delimiter is added before or after the list.
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join(["a", "b", "c"], ';') = "a;b;c"
* StringUtils.join(["a", "b", "c"], null) = "abc"
* StringUtils.join([null, "", "a"], ';') = ";;a"
* </pre>
*
* @param array the array of values to join together, may be null
* @param separator the separator character to use
* @param startIndex the first index to start joining from. It is
* an error to pass in an end index past the end of the array
* @param endIndex the index to stop joining from (exclusive). It is
* an error to pass in an end index past the end of the array
* @return the joined String, <code>null</code> if null array input
* @since 2.0
*/
public static String join(Object[] array, char separator, int startIndex, int endIndex) {
if (array == null) {
return null;
}
int bufSize = (endIndex - startIndex);
if (bufSize <= 0) {
return EMPTY;
}
bufSize *= ((array[startIndex] == null ? 16 : array[startIndex].toString().length()) + 1);
StringBuilder buf = new StringBuilder(bufSize);
for (int i = startIndex; i < endIndex; i++) {
if (i > startIndex) {
buf.append(separator);
}
if (array[i] != null) {
buf.append(array[i]);
}
}
return buf.toString();
}
/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* <p>No delimiter is added before or after the list.
* A <code>null</code> separator is the same as an empty String ("").
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join(["a", "b", "c"], "--") = "a--b--c"
* StringUtils.join(["a", "b", "c"], null) = "abc"
* StringUtils.join(["a", "b", "c"], "") = "abc"
* StringUtils.join([null, "", "a"], ',') = ",,a"
* </pre>
*
* @param array the array of values to join together, may be null
* @param separator the separator character to use, null treated as ""
* @return the joined String, <code>null</code> if null array input
*/
public static String join(Object[] array, String separator) {
if (array == null) {
return null;
}
return join(array, separator, 0, array.length);
}
/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* <p>No delimiter is added before or after the list.
* A <code>null</code> separator is the same as an empty String ("").
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join(["a", "b", "c"], "--") = "a--b--c"
* StringUtils.join(["a", "b", "c"], null) = "abc"
* StringUtils.join(["a", "b", "c"], "") = "abc"
* StringUtils.join([null, "", "a"], ',') = ",,a"
* </pre>
*
* @param array the array of values to join together, may be null
* @param separator the separator character to use, null treated as ""
* @param startIndex the first index to start joining from. It is
* an error to pass in an end index past the end of the array
* @param endIndex the index to stop joining from (exclusive). It is
* an error to pass in an end index past the end of the array
* @return the joined String, <code>null</code> if null array input
*/
public static String join(Object[] array, String separator, int startIndex, int endIndex) {
if (array == null) {
return null;
}
if (separator == null) {
separator = EMPTY;
}
// endIndex - startIndex > 0: Len = NofStrings *(len(firstString) + len(separator))
// (Assuming that all Strings are roughly equally long)
int bufSize = (endIndex - startIndex);
if (bufSize <= 0) {
return EMPTY;
}
bufSize *= ((array[startIndex] == null ? 16 : array[startIndex].toString().length())
+ separator.length());
StringBuilder buf = new StringBuilder(bufSize);
for (int i = startIndex; i < endIndex; i++) {
if (i > startIndex) {
buf.append(separator);
}
if (array[i] != null) {
buf.append(array[i]);
}
}
return buf.toString();
}
/**
* <p>Joins the elements of the provided <code>Iterator</code> into
* a single String containing the provided elements.</p>
*
* <p>No delimiter is added before or after the list. Null objects or empty
* strings within the iteration are represented by empty strings.</p>
*
* <p>See the examples here: {@link #join(Object[],char)}. </p>
*
* @param iterator the <code>Iterator</code> of values to join together, may be null
* @param separator the separator character to use
* @return the joined String, <code>null</code> if null iterator input
* @since 2.0
*/
public static String join(Iterator<?> iterator, char separator) {
// handle null, zero and one elements before building a buffer
if (iterator == null) {
return null;
}
if (!iterator.hasNext()) {
return EMPTY;
}
Object first = iterator.next();
if (!iterator.hasNext()) {
return ObjectUtils.toString(first);
}
// two or more elements
StringBuilder buf = new StringBuilder(256); // Java default is 16, probably too small
if (first != null) {
buf.append(first);
}
while (iterator.hasNext()) {
buf.append(separator);
Object obj = iterator.next();
if (obj != null) {
buf.append(obj);
}
}
return buf.toString();
}
/**
* <p>Joins the elements of the provided <code>Iterator</code> into
* a single String containing the provided elements.</p>
*
* <p>No delimiter is added before or after the list.
* A <code>null</code> separator is the same as an empty String ("").</p>
*
* <p>See the examples here: {@link #join(Object[],String)}. </p>
*
* @param iterator the <code>Iterator</code> of values to join together, may be null
* @param separator the separator character to use, null treated as ""
* @return the joined String, <code>null</code> if null iterator input
*/
public static String join(Iterator<?> iterator, String separator) {
// handle null, zero and one elements before building a buffer
if (iterator == null) {
return null;
}
if (!iterator.hasNext()) {
return EMPTY;
}
Object first = iterator.next();
if (!iterator.hasNext()) {
return ObjectUtils.toString(first);
}
// two or more elements
StringBuilder buf = new StringBuilder(256); // Java default is 16, probably too small
if (first != null) {
buf.append(first);
}
while (iterator.hasNext()) {
if (separator != null) {
buf.append(separator);
}
Object obj = iterator.next();
if (obj != null) {
buf.append(obj);
}
}
return buf.toString();
}
/**
* <p>Joins the elements of the provided <code>Iterable</code> into
* a single String containing the provided elements.</p>
*
* <p>No delimiter is added before or after the list. Null objects or empty
* strings within the iteration are represented by empty strings.</p>
*
* <p>See the examples here: {@link #join(Object[],char)}. </p>
*
* @param iterable the <code>Iterable</code> providing the values to join together, may be null
* @param separator the separator character to use
* @return the joined String, <code>null</code> if null iterator input
* @since 2.3
*/
public static String join(Iterable<?> iterable, char separator) {
if (iterable == null) {
return null;
}
return join(iterable.iterator(), separator);
}
/**
* <p>Joins the elements of the provided <code>Iterable</code> into
* a single String containing the provided elements.</p>
*
* <p>No delimiter is added before or after the list.
* A <code>null</code> separator is the same as an empty String ("").</p>
*
* <p>See the examples here: {@link #join(Object[],String)}. </p>
*
* @param iterable the <code>Iterable</code> providing the values to join together, may be null
* @param separator the separator character to use, null treated as ""
* @return the joined String, <code>null</code> if null iterator input
* @since 2.3
*/
public static String join(Iterable<?> iterable, String separator) {
if (iterable == null) {
return null;
}
return join(iterable.iterator(), separator);
}
// Delete
//-----------------------------------------------------------------------
/**
* <p>Deletes all whitespaces from a String as defined by
* {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.deleteWhitespace(null) = null
* StringUtils.deleteWhitespace("") = ""
* StringUtils.deleteWhitespace("abc") = "abc"
* StringUtils.deleteWhitespace(" ab c ") = "abc"
* </pre>
*
* @param str the String to delete whitespace from, may be null
* @return the String without whitespaces, <code>null</code> if null String input
*/
public static String deleteWhitespace(String str) {
if (isEmpty(str)) {
return str;
}
int sz = str.length();
char[] chs = new char[sz];
int count = 0;
for (int i = 0; i < sz; i++) {
if (!Character.isWhitespace(str.charAt(i))) {
chs[count++] = str.charAt(i);
}
}
if (count == sz) {
return str;
}
return new String(chs, 0, count);
}
// Remove
//-----------------------------------------------------------------------
/**
* <p>Removes a substring only if it is at the begining of a source string,
* otherwise returns the source string.</p>
*
* <p>A <code>null</code> source string will return <code>null</code>.
* An empty ("") source string will return the empty string.
* A <code>null</code> search string will return the source string.</p>
*
* <pre>
* StringUtils.removeStart(null, *) = null
* StringUtils.removeStart("", *) = ""
* StringUtils.removeStart(*, null) = *
* StringUtils.removeStart("www.domain.com", "www.") = "domain.com"
* StringUtils.removeStart("domain.com", "www.") = "domain.com"
* StringUtils.removeStart("www.domain.com", "domain") = "www.domain.com"
* StringUtils.removeStart("abc", "") = "abc"
* </pre>
*
* @param str the source String to search, may be null
* @param remove the String to search for and remove, may be null
* @return the substring with the string removed if found,
* <code>null</code> if null String input
* @since 2.1
*/
public static String removeStart(String str, String remove) {
if (isEmpty(str) || isEmpty(remove)) {
return str;
}
if (str.startsWith(remove)){
return str.substring(remove.length());
}
return str;
}
/**
* <p>Case insensitive removal of a substring if it is at the begining of a source string,
* otherwise returns the source string.</p>
*
* <p>A <code>null</code> source string will return <code>null</code>.
* An empty ("") source string will return the empty string.
* A <code>null</code> search string will return the source string.</p>
*
* <pre>
* StringUtils.removeStartIgnoreCase(null, *) = null
* StringUtils.removeStartIgnoreCase("", *) = ""
* StringUtils.removeStartIgnoreCase(*, null) = *
* StringUtils.removeStartIgnoreCase("www.domain.com", "www.") = "domain.com"
* StringUtils.removeStartIgnoreCase("www.domain.com", "WWW.") = "domain.com"
* StringUtils.removeStartIgnoreCase("domain.com", "www.") = "domain.com"
* StringUtils.removeStartIgnoreCase("www.domain.com", "domain") = "www.domain.com"
* StringUtils.removeStartIgnoreCase("abc", "") = "abc"
* </pre>
*
* @param str the source String to search, may be null
* @param remove the String to search for (case insensitive) and remove, may be null
* @return the substring with the string removed if found,
* <code>null</code> if null String input
* @since 2.4
*/
public static String removeStartIgnoreCase(String str, String remove) {
if (isEmpty(str) || isEmpty(remove)) {
return str;
}
if (startsWithIgnoreCase(str, remove)) {
return str.substring(remove.length());
}
return str;
}
/**
* <p>Removes a substring only if it is at the end of a source string,
* otherwise returns the source string.</p>
*
* <p>A <code>null</code> source string will return <code>null</code>.
* An empty ("") source string will return the empty string.
* A <code>null</code> search string will return the source string.</p>
*
* <pre>
* StringUtils.removeEnd(null, *) = null
* StringUtils.removeEnd("", *) = ""
* StringUtils.removeEnd(*, null) = *
* StringUtils.removeEnd("www.domain.com", ".com.") = "www.domain.com"
* StringUtils.removeEnd("www.domain.com", ".com") = "www.domain"
* StringUtils.removeEnd("www.domain.com", "domain") = "www.domain.com"
* StringUtils.removeEnd("abc", "") = "abc"
* </pre>
*
* @param str the source String to search, may be null
* @param remove the String to search for and remove, may be null
* @return the substring with the string removed if found,
* <code>null</code> if null String input
* @since 2.1
*/
public static String removeEnd(String str, String remove) {
if (isEmpty(str) || isEmpty(remove)) {
return str;
}
if (str.endsWith(remove)) {
return str.substring(0, str.length() - remove.length());
}
return str;
}
/**
* <p>Case insensitive removal of a substring if it is at the end of a source string,
* otherwise returns the source string.</p>
*
* <p>A <code>null</code> source string will return <code>null</code>.
* An empty ("") source string will return the empty string.
* A <code>null</code> search string will return the source string.</p>
*
* <pre>
* StringUtils.removeEndIgnoreCase(null, *) = null
* StringUtils.removeEndIgnoreCase("", *) = ""
* StringUtils.removeEndIgnoreCase(*, null) = *
* StringUtils.removeEndIgnoreCase("www.domain.com", ".com.") = "www.domain.com"
* StringUtils.removeEndIgnoreCase("www.domain.com", ".com") = "www.domain"
* StringUtils.removeEndIgnoreCase("www.domain.com", "domain") = "www.domain.com"
* StringUtils.removeEndIgnoreCase("abc", "") = "abc"
* StringUtils.removeEndIgnoreCase("www.domain.com", ".COM") = "www.domain")
* StringUtils.removeEndIgnoreCase("www.domain.COM", ".com") = "www.domain")
* </pre>
*
* @param str the source String to search, may be null
* @param remove the String to search for (case insensitive) and remove, may be null
* @return the substring with the string removed if found,
* <code>null</code> if null String input
* @since 2.4
*/
public static String removeEndIgnoreCase(String str, String remove) {
if (isEmpty(str) || isEmpty(remove)) {
return str;
}
if (endsWithIgnoreCase(str, remove)) {
return str.substring(0, str.length() - remove.length());
}
return str;
}
/**
* <p>Removes all occurrences of a substring from within the source string.</p>
*
* <p>A <code>null</code> source string will return <code>null</code>.
* An empty ("") source string will return the empty string.
* A <code>null</code> remove string will return the source string.
* An empty ("") remove string will return the source string.</p>
*
* <pre>
* StringUtils.remove(null, *) = null
* StringUtils.remove("", *) = ""
* StringUtils.remove(*, null) = *
* StringUtils.remove(*, "") = *
* StringUtils.remove("queued", "ue") = "qd"
* StringUtils.remove("queued", "zz") = "queued"
* </pre>
*
* @param str the source String to search, may be null
* @param remove the String to search for and remove, may be null
* @return the substring with the string removed if found,
* <code>null</code> if null String input
* @since 2.1
*/
public static String remove(String str, String remove) {
if (isEmpty(str) || isEmpty(remove)) {
return str;
}
return replace(str, remove, EMPTY, -1);
}
/**
* <p>Removes all occurrences of a character from within the source string.</p>
*
* <p>A <code>null</code> source string will return <code>null</code>.
* An empty ("") source string will return the empty string.</p>
*
* <pre>
* StringUtils.remove(null, *) = null
* StringUtils.remove("", *) = ""
* StringUtils.remove("queued", 'u') = "qeed"
* StringUtils.remove("queued", 'z') = "queued"
* </pre>
*
* @param str the source String to search, may be null
* @param remove the char to search for and remove, may be null
* @return the substring with the char removed if found,
* <code>null</code> if null String input
* @since 2.1
*/
public static String remove(String str, char remove) {
if (isEmpty(str) || str.indexOf(remove) == INDEX_NOT_FOUND) {
return str;
}
char[] chars = str.toCharArray();
int pos = 0;
for (int i = 0; i < chars.length; i++) {
if (chars[i] != remove) {
chars[pos++] = chars[i];
}
}
return new String(chars, 0, pos);
}
// Replacing
//-----------------------------------------------------------------------
/**
* <p>Replaces a String with another String inside a larger String, once.</p>
*
* <p>A <code>null</code> reference passed to this method is a no-op.</p>
*
* <pre>
* StringUtils.replaceOnce(null, *, *) = null
* StringUtils.replaceOnce("", *, *) = ""
* StringUtils.replaceOnce("any", null, *) = "any"
* StringUtils.replaceOnce("any", *, null) = "any"
* StringUtils.replaceOnce("any", "", *) = "any"
* StringUtils.replaceOnce("aba", "a", null) = "aba"
* StringUtils.replaceOnce("aba", "a", "") = "ba"
* StringUtils.replaceOnce("aba", "a", "z") = "zba"
* </pre>
*
* @see #replace(String text, String searchString, String replacement, int max)
* @param text text to search and replace in, may be null
* @param searchString the String to search for, may be null
* @param replacement the String to replace with, may be null
* @return the text with any replacements processed,
* <code>null</code> if null String input
*/
public static String replaceOnce(String text, String searchString, String replacement) {
return replace(text, searchString, replacement, 1);
}
/**
* <p>Replaces all occurrences of a String within another String.</p>
*
* <p>A <code>null</code> reference passed to this method is a no-op.</p>
*
* <pre>
* StringUtils.replace(null, *, *) = null
* StringUtils.replace("", *, *) = ""
* StringUtils.replace("any", null, *) = "any"
* StringUtils.replace("any", *, null) = "any"
* StringUtils.replace("any", "", *) = "any"
* StringUtils.replace("aba", "a", null) = "aba"
* StringUtils.replace("aba", "a", "") = "b"
* StringUtils.replace("aba", "a", "z") = "zbz"
* </pre>
*
* @see #replace(String text, String searchString, String replacement, int max)
* @param text text to search and replace in, may be null
* @param searchString the String to search for, may be null
* @param replacement the String to replace it with, may be null
* @return the text with any replacements processed,
* <code>null</code> if null String input
*/
public static String replace(String text, String searchString, String replacement) {
return replace(text, searchString, replacement, -1);
}
/**
* <p>Replaces a String with another String inside a larger String,
* for the first <code>max</code> values of the search String.</p>
*
* <p>A <code>null</code> reference passed to this method is a no-op.</p>
*
* <pre>
* StringUtils.replace(null, *, *, *) = null
* StringUtils.replace("", *, *, *) = ""
* StringUtils.replace("any", null, *, *) = "any"
* StringUtils.replace("any", *, null, *) = "any"
* StringUtils.replace("any", "", *, *) = "any"
* StringUtils.replace("any", *, *, 0) = "any"
* StringUtils.replace("abaa", "a", null, -1) = "abaa"
* StringUtils.replace("abaa", "a", "", -1) = "b"
* StringUtils.replace("abaa", "a", "z", 0) = "abaa"
* StringUtils.replace("abaa", "a", "z", 1) = "zbaa"
* StringUtils.replace("abaa", "a", "z", 2) = "zbza"
* StringUtils.replace("abaa", "a", "z", -1) = "zbzz"
* </pre>
*
* @param text text to search and replace in, may be null
* @param searchString the String to search for, may be null
* @param replacement the String to replace it with, may be null
* @param max maximum number of values to replace, or <code>-1</code> if no maximum
* @return the text with any replacements processed,
* <code>null</code> if null String input
*/
public static String replace(String text, String searchString, String replacement, int max) {
if (isEmpty(text) || isEmpty(searchString) || replacement == null || max == 0) {
return text;
}
int start = 0;
int end = text.indexOf(searchString, start);
if (end == INDEX_NOT_FOUND) {
return text;
}
int replLength = searchString.length();
int increase = replacement.length() - replLength;
increase = (increase < 0 ? 0 : increase);
increase *= (max < 0 ? 16 : (max > 64 ? 64 : max));
StringBuilder buf = new StringBuilder(text.length() + increase);
while (end != INDEX_NOT_FOUND) {
buf.append(text.substring(start, end)).append(replacement);
start = end + replLength;
if (--max == 0) {
break;
}
end = text.indexOf(searchString, start);
}
buf.append(text.substring(start));
return buf.toString();
}
/**
* <p>
* Replaces all occurrences of Strings within another String.
* </p>
*
* <p>
* A <code>null</code> reference passed to this method is a no-op, or if
* any "search string" or "string to replace" is null, that replace will be
* ignored. This will not repeat. For repeating replaces, call the
* overloaded method.
* </p>
*
* <pre>
* StringUtils.replaceEach(null, *, *) = null
* StringUtils.replaceEach("", *, *) = ""
* StringUtils.replaceEach("aba", null, null) = "aba"
* StringUtils.replaceEach("aba", new String[0], null) = "aba"
* StringUtils.replaceEach("aba", null, new String[0]) = "aba"
* StringUtils.replaceEach("aba", new String[]{"a"}, null) = "aba"
* StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""}) = "b"
* StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"}) = "aba"
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}) = "wcte"
* (example of how it does not repeat)
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}) = "dcte"
* </pre>
*
* @param text
* text to search and replace in, no-op if null
* @param searchList
* the Strings to search for, no-op if null
* @param replacementList
* the Strings to replace them with, no-op if null
* @return the text with any replacements processed, <code>null</code> if
* null String input
* @throws IndexOutOfBoundsException
* if the lengths of the arrays are not the same (null is ok,
* and/or size 0)
* @since 2.4
*/
public static String replaceEach(String text, String[] searchList, String[] replacementList) {
return replaceEach(text, searchList, replacementList, false, 0);
}
/**
* <p>
* Replaces all occurrences of Strings within another String.
* </p>
*
* <p>
* A <code>null</code> reference passed to this method is a no-op, or if
* any "search string" or "string to replace" is null, that replace will be
* ignored. This will not repeat. For repeating replaces, call the
* overloaded method.
* </p>
*
* <pre>
* StringUtils.replaceEach(null, *, *, *) = null
* StringUtils.replaceEach("", *, *, *) = ""
* StringUtils.replaceEach("aba", null, null, *) = "aba"
* StringUtils.replaceEach("aba", new String[0], null, *) = "aba"
* StringUtils.replaceEach("aba", null, new String[0], *) = "aba"
* StringUtils.replaceEach("aba", new String[]{"a"}, null, *) = "aba"
* StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""}, *) = "b"
* StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"}, *) = "aba"
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}, *) = "wcte"
* (example of how it repeats)
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}, false) = "dcte"
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}, true) = "tcte"
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "ab"}, true) = IllegalArgumentException
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "ab"}, false) = "dcabe"
* </pre>
*
* @param text
* text to search and replace in, no-op if null
* @param searchList
* the Strings to search for, no-op if null
* @param replacementList
* the Strings to replace them with, no-op if null
* @return the text with any replacements processed, <code>null</code> if
* null String input
* @throws IllegalArgumentException
* if the search is repeating and there is an endless loop due
* to outputs of one being inputs to another
* @throws IndexOutOfBoundsException
* if the lengths of the arrays are not the same (null is ok,
* and/or size 0)
* @since 2.4
*/
public static String replaceEachRepeatedly(String text, String[] searchList, String[] replacementList) {
// timeToLive should be 0 if not used or nothing to replace, else it's
// the length of the replace array
int timeToLive = searchList == null ? 0 : searchList.length;
return replaceEach(text, searchList, replacementList, true, timeToLive);
}
/**
* <p>
* Replaces all occurrences of Strings within another String.
* </p>
*
* <p>
* A <code>null</code> reference passed to this method is a no-op, or if
* any "search string" or "string to replace" is null, that replace will be
* ignored.
* </p>
*
* <pre>
* StringUtils.replaceEach(null, *, *, *) = null
* StringUtils.replaceEach("", *, *, *) = ""
* StringUtils.replaceEach("aba", null, null, *) = "aba"
* StringUtils.replaceEach("aba", new String[0], null, *) = "aba"
* StringUtils.replaceEach("aba", null, new String[0], *) = "aba"
* StringUtils.replaceEach("aba", new String[]{"a"}, null, *) = "aba"
* StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""}, *) = "b"
* StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"}, *) = "aba"
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}, *) = "wcte"
* (example of how it repeats)
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}, false) = "dcte"
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}, true) = "tcte"
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "ab"}, *) = IllegalArgumentException
* </pre>
*
* @param text
* text to search and replace in, no-op if null
* @param searchList
* the Strings to search for, no-op if null
* @param replacementList
* the Strings to replace them with, no-op if null
* @param repeat if true, then replace repeatedly
* until there are no more possible replacements or timeToLive < 0
* @param timeToLive
* if less than 0 then there is a circular reference and endless
* loop
* @return the text with any replacements processed, <code>null</code> if
* null String input
* @throws IllegalArgumentException
* if the search is repeating and there is an endless loop due
* to outputs of one being inputs to another
* @throws IndexOutOfBoundsException
* if the lengths of the arrays are not the same (null is ok,
* and/or size 0)
* @since 2.4
*/
private static String replaceEach(String text, String[] searchList, String[] replacementList,
boolean repeat, int timeToLive)
{
// mchyzer Performance note: This creates very few new objects (one major goal)
// let me know if there are performance requests, we can create a harness to measure
if (text == null || text.length() == 0 || searchList == null ||
searchList.length == 0 || replacementList == null || replacementList.length == 0)
{
return text;
}
// if recursing, this shouldnt be less than 0
if (timeToLive < 0) {
throw new IllegalStateException("TimeToLive of " + timeToLive + " is less than 0: " + text);
}
int searchLength = searchList.length;
int replacementLength = replacementList.length;
// make sure lengths are ok, these need to be equal
if (searchLength != replacementLength) {
throw new IllegalArgumentException("Search and Replace array lengths don't match: "
+ searchLength
+ " vs "
+ replacementLength);
}
// keep track of which still have matches
boolean[] noMoreMatchesForReplIndex = new boolean[searchLength];
// index on index that the match was found
int textIndex = -1;
int replaceIndex = -1;
int tempIndex = -1;
// index of replace array that will replace the search string found
// NOTE: logic duplicated below START
for (int i = 0; i < searchLength; i++) {
if (noMoreMatchesForReplIndex[i] || searchList[i] == null ||
searchList[i].length() == 0 || replacementList[i] == null)
{
continue;
}
tempIndex = text.indexOf(searchList[i]);
// see if we need to keep searching for this
if (tempIndex == -1) {
noMoreMatchesForReplIndex[i] = true;
} else {
if (textIndex == -1 || tempIndex < textIndex) {
textIndex = tempIndex;
replaceIndex = i;
}
}
}
// NOTE: logic mostly below END
// no search strings found, we are done
if (textIndex == -1) {
return text;
}
int start = 0;
// get a good guess on the size of the result buffer so it doesnt have to double if it goes over a bit
int increase = 0;
// count the replacement text elements that are larger than their corresponding text being replaced
for (int i = 0; i < searchList.length; i++) {
if (searchList[i] == null || replacementList[i] == null) {
continue;
}
int greater = replacementList[i].length() - searchList[i].length();
if (greater > 0) {
increase += 3 * greater; // assume 3 matches
}
}
// have upper-bound at 20% increase, then let Java take over
increase = Math.min(increase, text.length() / 5);
StringBuilder buf = new StringBuilder(text.length() + increase);
while (textIndex != -1) {
for (int i = start; i < textIndex; i++) {
buf.append(text.charAt(i));
}
buf.append(replacementList[replaceIndex]);
start = textIndex + searchList[replaceIndex].length();
textIndex = -1;
replaceIndex = -1;
tempIndex = -1;
// find the next earliest match
// NOTE: logic mostly duplicated above START
for (int i = 0; i < searchLength; i++) {
if (noMoreMatchesForReplIndex[i] || searchList[i] == null ||
searchList[i].length() == 0 || replacementList[i] == null)
{
continue;
}
tempIndex = text.indexOf(searchList[i], start);
// see if we need to keep searching for this
if (tempIndex == -1) {
noMoreMatchesForReplIndex[i] = true;
} else {
if (textIndex == -1 || tempIndex < textIndex) {
textIndex = tempIndex;
replaceIndex = i;
}
}
}
// NOTE: logic duplicated above END
}
int textLength = text.length();
for (int i = start; i < textLength; i++) {
buf.append(text.charAt(i));
}
String result = buf.toString();
if (!repeat) {
return result;
}
return replaceEach(result, searchList, replacementList, repeat, timeToLive - 1);
}
// Replace, character based
//-----------------------------------------------------------------------
/**
* <p>Replaces all occurrences of a character in a String with another.
* This is a null-safe version of {@link String#replace(char, char)}.</p>
*
* <p>A <code>null</code> string input returns <code>null</code>.
* An empty ("") string input returns an empty string.</p>
*
* <pre>
* StringUtils.replaceChars(null, *, *) = null
* StringUtils.replaceChars("", *, *) = ""
* StringUtils.replaceChars("abcba", 'b', 'y') = "aycya"
* StringUtils.replaceChars("abcba", 'z', 'y') = "abcba"
* </pre>
*
* @param str String to replace characters in, may be null
* @param searchChar the character to search for, may be null
* @param replaceChar the character to replace, may be null
* @return modified String, <code>null</code> if null string input
* @since 2.0
*/
public static String replaceChars(String str, char searchChar, char replaceChar) {
if (str == null) {
return null;
}
return str.replace(searchChar, replaceChar);
}
/**
* <p>Replaces multiple characters in a String in one go.
* This method can also be used to delete characters.</p>
*
* <p>For example:<br />
* <code>replaceChars("hello", "ho", "jy") = jelly</code>.</p>
*
* <p>A <code>null</code> string input returns <code>null</code>.
* An empty ("") string input returns an empty string.
* A null or empty set of search characters returns the input string.</p>
*
* <p>The length of the search characters should normally equal the length
* of the replace characters.
* If the search characters is longer, then the extra search characters
* are deleted.
* If the search characters is shorter, then the extra replace characters
* are ignored.</p>
*
* <pre>
* StringUtils.replaceChars(null, *, *) = null
* StringUtils.replaceChars("", *, *) = ""
* StringUtils.replaceChars("abc", null, *) = "abc"
* StringUtils.replaceChars("abc", "", *) = "abc"
* StringUtils.replaceChars("abc", "b", null) = "ac"
* StringUtils.replaceChars("abc", "b", "") = "ac"
* StringUtils.replaceChars("abcba", "bc", "yz") = "ayzya"
* StringUtils.replaceChars("abcba", "bc", "y") = "ayya"
* StringUtils.replaceChars("abcba", "bc", "yzx") = "ayzya"
* </pre>
*
* @param str String to replace characters in, may be null
* @param searchChars a set of characters to search for, may be null
* @param replaceChars a set of characters to replace, may be null
* @return modified String, <code>null</code> if null string input
* @since 2.0
*/
public static String replaceChars(String str, String searchChars, String replaceChars) {
if (isEmpty(str) || isEmpty(searchChars)) {
return str;
}
if (replaceChars == null) {
replaceChars = EMPTY;
}
boolean modified = false;
int replaceCharsLength = replaceChars.length();
int strLength = str.length();
StringBuilder buf = new StringBuilder(strLength);
for (int i = 0; i < strLength; i++) {
char ch = str.charAt(i);
int index = searchChars.indexOf(ch);
if (index >= 0) {
modified = true;
if (index < replaceCharsLength) {
buf.append(replaceChars.charAt(index));
}
} else {
buf.append(ch);
}
}
if (modified) {
return buf.toString();
}
return str;
}
// Overlay
//-----------------------------------------------------------------------
/**
* <p>Overlays part of a String with another String.</p>
*
* <p>A <code>null</code> string input returns <code>null</code>.
* A negative index is treated as zero.
* An index greater than the string length is treated as the string length.
* The start index is always the smaller of the two indices.</p>
*
* <pre>
* StringUtils.overlay(null, *, *, *) = null
* StringUtils.overlay("", "abc", 0, 0) = "abc"
* StringUtils.overlay("abcdef", null, 2, 4) = "abef"
* StringUtils.overlay("abcdef", "", 2, 4) = "abef"
* StringUtils.overlay("abcdef", "", 4, 2) = "abef"
* StringUtils.overlay("abcdef", "zzzz", 2, 4) = "abzzzzef"
* StringUtils.overlay("abcdef", "zzzz", 4, 2) = "abzzzzef"
* StringUtils.overlay("abcdef", "zzzz", -1, 4) = "zzzzef"
* StringUtils.overlay("abcdef", "zzzz", 2, 8) = "abzzzz"
* StringUtils.overlay("abcdef", "zzzz", -2, -3) = "zzzzabcdef"
* StringUtils.overlay("abcdef", "zzzz", 8, 10) = "abcdefzzzz"
* </pre>
*
* @param str the String to do overlaying in, may be null
* @param overlay the String to overlay, may be null
* @param start the position to start overlaying at
* @param end the position to stop overlaying before
* @return overlayed String, <code>null</code> if null String input
* @since 2.0
*/
public static String overlay(String str, String overlay, int start, int end) {
if (str == null) {
return null;
}
if (overlay == null) {
overlay = EMPTY;
}
int len = str.length();
if (start < 0) {
start = 0;
}
if (start > len) {
start = len;
}
if (end < 0) {
end = 0;
}
if (end > len) {
end = len;
}
if (start > end) {
int temp = start;
start = end;
end = temp;
}
return new StringBuilder(len + start - end + overlay.length() + 1)
.append(str.substring(0, start))
.append(overlay)
.append(str.substring(end))
.toString();
}
// Chomping
//-----------------------------------------------------------------------
/**
* <p>Removes one newline from end of a String if it's there,
* otherwise leave it alone. A newline is "<code>\n</code>",
* "<code>\r</code>", or "<code>\r\n</code>".</p>
*
* <p>NOTE: This method changed in 2.0.
* It now more closely matches Perl chomp.</p>
*
* <pre>
* StringUtils.chomp(null) = null
* StringUtils.chomp("") = ""
* StringUtils.chomp("abc \r") = "abc "
* StringUtils.chomp("abc\n") = "abc"
* StringUtils.chomp("abc\r\n") = "abc"
* StringUtils.chomp("abc\r\n\r\n") = "abc\r\n"
* StringUtils.chomp("abc\n\r") = "abc\n"
* StringUtils.chomp("abc\n\rabc") = "abc\n\rabc"
* StringUtils.chomp("\r") = ""
* StringUtils.chomp("\n") = ""
* StringUtils.chomp("\r\n") = ""
* </pre>
*
* @param str the String to chomp a newline from, may be null
* @return String without newline, <code>null</code> if null String input
*/
public static String chomp(String str) {
if (isEmpty(str)) {
return str;
}
if (str.length() == 1) {
char ch = str.charAt(0);
if (ch == CharUtils.CR || ch == CharUtils.LF) {
return EMPTY;
}
return str;
}
int lastIdx = str.length() - 1;
char last = str.charAt(lastIdx);
if (last == CharUtils.LF) {
if (str.charAt(lastIdx - 1) == CharUtils.CR) {
lastIdx--;
}
} else if (last != CharUtils.CR) {
lastIdx++;
}
return str.substring(0, lastIdx);
}
/**
* <p>Removes <code>separator</code> from the end of
* <code>str</code> if it's there, otherwise leave it alone.</p>
*
* <p>NOTE: This method changed in version 2.0.
* It now more closely matches Perl chomp.
* For the previous behavior, use {@link #substringBeforeLast(String, String)}.
* This method uses {@link String#endsWith(String)}.</p>
*
* <pre>
* StringUtils.chomp(null, *) = null
* StringUtils.chomp("", *) = ""
* StringUtils.chomp("foobar", "bar") = "foo"
* StringUtils.chomp("foobar", "baz") = "foobar"
* StringUtils.chomp("foo", "foo") = ""
* StringUtils.chomp("foo ", "foo") = "foo "
* StringUtils.chomp(" foo", "foo") = " "
* StringUtils.chomp("foo", "foooo") = "foo"
* StringUtils.chomp("foo", "") = "foo"
* StringUtils.chomp("foo", null) = "foo"
* </pre>
*
* @param str the String to chomp from, may be null
* @param separator separator String, may be null
* @return String without trailing separator, <code>null</code> if null String input
*/
public static String chomp(String str, String separator) {
if (isEmpty(str) || separator == null) {
return str;
}
if (str.endsWith(separator)) {
return str.substring(0, str.length() - separator.length());
}
return str;
}
// Chopping
//-----------------------------------------------------------------------
/**
* <p>Remove the last character from a String.</p>
*
* <p>If the String ends in <code>\r\n</code>, then remove both
* of them.</p>
*
* <pre>
* StringUtils.chop(null) = null
* StringUtils.chop("") = ""
* StringUtils.chop("abc \r") = "abc "
* StringUtils.chop("abc\n") = "abc"
* StringUtils.chop("abc\r\n") = "abc"
* StringUtils.chop("abc") = "ab"
* StringUtils.chop("abc\nabc") = "abc\nab"
* StringUtils.chop("a") = ""
* StringUtils.chop("\r") = ""
* StringUtils.chop("\n") = ""
* StringUtils.chop("\r\n") = ""
* </pre>
*
* @param str the String to chop last character from, may be null
* @return String without last character, <code>null</code> if null String input
*/
public static String chop(String str) {
if (str == null) {
return null;
}
int strLen = str.length();
if (strLen < 2) {
return EMPTY;
}
int lastIdx = strLen - 1;
String ret = str.substring(0, lastIdx);
char last = str.charAt(lastIdx);
if (last == CharUtils.LF) {
if (ret.charAt(lastIdx - 1) == CharUtils.CR) {
return ret.substring(0, lastIdx - 1);
}
}
return ret;
}
// Conversion
//-----------------------------------------------------------------------
// Padding
//-----------------------------------------------------------------------
/**
* <p>Repeat a String <code>repeat</code> times to form a
* new String.</p>
*
* <pre>
* StringUtils.repeat(null, 2) = null
* StringUtils.repeat("", 0) = ""
* StringUtils.repeat("", 2) = ""
* StringUtils.repeat("a", 3) = "aaa"
* StringUtils.repeat("ab", 2) = "abab"
* StringUtils.repeat("a", -2) = ""
* </pre>
*
* @param str the String to repeat, may be null
* @param repeat number of times to repeat str, negative treated as zero
* @return a new String consisting of the original String repeated,
* <code>null</code> if null String input
* @since 2.5
*/
public static String repeat(String str, int repeat) {
// Performance tuned for 2.0 (JDK1.4)
if (str == null) {
return null;
}
if (repeat <= 0) {
return EMPTY;
}
int inputLength = str.length();
if (repeat == 1 || inputLength == 0) {
return str;
}
if (inputLength == 1 && repeat <= PAD_LIMIT) {
return padding(repeat, str.charAt(0));
}
int outputLength = inputLength * repeat;
switch (inputLength) {
case 1 :
char ch = str.charAt(0);
char[] output1 = new char[outputLength];
for (int i = repeat - 1; i >= 0; i--) {
output1[i] = ch;
}
return new String(output1);
case 2 :
char ch0 = str.charAt(0);
char ch1 = str.charAt(1);
char[] output2 = new char[outputLength];
for (int i = repeat * 2 - 2; i >= 0; i--, i--) {
output2[i] = ch0;
output2[i + 1] = ch1;
}
return new String(output2);
default :
StringBuilder buf = new StringBuilder(outputLength);
for (int i = 0; i < repeat; i++) {
buf.append(str);
}
return buf.toString();
}
}
/**
* <p>Repeat a String <code>repeat</code> times to form a
* new String, with a String separator injected each time. </p>
*
* <pre>
* StringUtils.repeat(null, null, 2) = null
* StringUtils.repeat(null, "x", 2) = null
* StringUtils.repeat("", null, 0) = ""
* StringUtils.repeat("", "", 2) = ""
* StringUtils.repeat("", "x", 3) = "xxx"
* StringUtils.repeat("?", ", ", 3) = "?, ?, ?"
* </pre>
*
* @param str the String to repeat, may be null
* @param separator the String to inject, may be null
* @param repeat number of times to repeat str, negative treated as zero
* @return a new String consisting of the original String repeated,
* <code>null</code> if null String input
*/
public static String repeat(String str, String separator, int repeat) {
if(str == null || separator == null) {
return repeat(str, repeat);
} else {
// given that repeat(String, int) is quite optimized, better to rely on it than try and splice this into it
String result = repeat(str + separator, repeat);
return removeEnd(result, separator);
}
}
/**
* <p>Returns padding using the specified delimiter repeated
* to a given length.</p>
*
* <pre>
* StringUtils.padding(0, 'e') = ""
* StringUtils.padding(3, 'e') = "eee"
* StringUtils.padding(-2, 'e') = IndexOutOfBoundsException
* </pre>
*
* <p>Note: this method doesn't not support padding with
* <a href="http://www.unicode.org/glossary/#supplementary_character">Unicode Supplementary Characters</a>
* as they require a pair of <code>char</code>s to be represented.
* If you are needing to support full I18N of your applications
* consider using {@link #repeat(String, int)} instead.
* </p>
*
* @param repeat number of times to repeat delim
* @param padChar character to repeat
* @return String with repeated character
* @throws IndexOutOfBoundsException if <code>repeat < 0</code>
* @see #repeat(String, int)
*/
private static String padding(int repeat, char padChar) throws IndexOutOfBoundsException {
if (repeat < 0) {
throw new IndexOutOfBoundsException("Cannot pad a negative amount: " + repeat);
}
final char[] buf = new char[repeat];
for (int i = 0; i < buf.length; i++) {
buf[i] = padChar;
}
return new String(buf);
}
/**
* <p>Right pad a String with spaces (' ').</p>
*
* <p>The String is padded to the size of <code>size</code>.</p>
*
* <pre>
* StringUtils.rightPad(null, *) = null
* StringUtils.rightPad("", 3) = " "
* StringUtils.rightPad("bat", 3) = "bat"
* StringUtils.rightPad("bat", 5) = "bat "
* StringUtils.rightPad("bat", 1) = "bat"
* StringUtils.rightPad("bat", -1) = "bat"
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @return right padded String or original String if no padding is necessary,
* <code>null</code> if null String input
*/
public static String rightPad(String str, int size) {
return rightPad(str, size, ' ');
}
/**
* <p>Right pad a String with a specified character.</p>
*
* <p>The String is padded to the size of <code>size</code>.</p>
*
* <pre>
* StringUtils.rightPad(null, *, *) = null
* StringUtils.rightPad("", 3, 'z') = "zzz"
* StringUtils.rightPad("bat", 3, 'z') = "bat"
* StringUtils.rightPad("bat", 5, 'z') = "batzz"
* StringUtils.rightPad("bat", 1, 'z') = "bat"
* StringUtils.rightPad("bat", -1, 'z') = "bat"
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @param padChar the character to pad with
* @return right padded String or original String if no padding is necessary,
* <code>null</code> if null String input
* @since 2.0
*/
public static String rightPad(String str, int size, char padChar) {
if (str == null) {
return null;
}
int pads = size - str.length();
if (pads <= 0) {
return str; // returns original String when possible
}
if (pads > PAD_LIMIT) {
return rightPad(str, size, String.valueOf(padChar));
}
return str.concat(padding(pads, padChar));
}
/**
* <p>Right pad a String with a specified String.</p>
*
* <p>The String is padded to the size of <code>size</code>.</p>
*
* <pre>
* StringUtils.rightPad(null, *, *) = null
* StringUtils.rightPad("", 3, "z") = "zzz"
* StringUtils.rightPad("bat", 3, "yz") = "bat"
* StringUtils.rightPad("bat", 5, "yz") = "batyz"
* StringUtils.rightPad("bat", 8, "yz") = "batyzyzy"
* StringUtils.rightPad("bat", 1, "yz") = "bat"
* StringUtils.rightPad("bat", -1, "yz") = "bat"
* StringUtils.rightPad("bat", 5, null) = "bat "
* StringUtils.rightPad("bat", 5, "") = "bat "
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @param padStr the String to pad with, null or empty treated as single space
* @return right padded String or original String if no padding is necessary,
* <code>null</code> if null String input
*/
public static String rightPad(String str, int size, String padStr) {
if (str == null) {
return null;
}
if (isEmpty(padStr)) {
padStr = " ";
}
int padLen = padStr.length();
int strLen = str.length();
int pads = size - strLen;
if (pads <= 0) {
return str; // returns original String when possible
}
if (padLen == 1 && pads <= PAD_LIMIT) {
return rightPad(str, size, padStr.charAt(0));
}
if (pads == padLen) {
return str.concat(padStr);
} else if (pads < padLen) {
return str.concat(padStr.substring(0, pads));
} else {
char[] padding = new char[pads];
char[] padChars = padStr.toCharArray();
for (int i = 0; i < pads; i++) {
padding[i] = padChars[i % padLen];
}
return str.concat(new String(padding));
}
}
/**
* <p>Left pad a String with spaces (' ').</p>
*
* <p>The String is padded to the size of <code>size</code>.</p>
*
* <pre>
* StringUtils.leftPad(null, *) = null
* StringUtils.leftPad("", 3) = " "
* StringUtils.leftPad("bat", 3) = "bat"
* StringUtils.leftPad("bat", 5) = " bat"
* StringUtils.leftPad("bat", 1) = "bat"
* StringUtils.leftPad("bat", -1) = "bat"
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @return left padded String or original String if no padding is necessary,
* <code>null</code> if null String input
*/
public static String leftPad(String str, int size) {
return leftPad(str, size, ' ');
}
/**
* <p>Left pad a String with a specified character.</p>
*
* <p>Pad to a size of <code>size</code>.</p>
*
* <pre>
* StringUtils.leftPad(null, *, *) = null
* StringUtils.leftPad("", 3, 'z') = "zzz"
* StringUtils.leftPad("bat", 3, 'z') = "bat"
* StringUtils.leftPad("bat", 5, 'z') = "zzbat"
* StringUtils.leftPad("bat", 1, 'z') = "bat"
* StringUtils.leftPad("bat", -1, 'z') = "bat"
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @param padChar the character to pad with
* @return left padded String or original String if no padding is necessary,
* <code>null</code> if null String input
* @since 2.0
*/
public static String leftPad(String str, int size, char padChar) {
if (str == null) {
return null;
}
int pads = size - str.length();
if (pads <= 0) {
return str; // returns original String when possible
}
if (pads > PAD_LIMIT) {
return leftPad(str, size, String.valueOf(padChar));
}
return padding(pads, padChar).concat(str);
}
/**
* <p>Left pad a String with a specified String.</p>
*
* <p>Pad to a size of <code>size</code>.</p>
*
* <pre>
* StringUtils.leftPad(null, *, *) = null
* StringUtils.leftPad("", 3, "z") = "zzz"
* StringUtils.leftPad("bat", 3, "yz") = "bat"
* StringUtils.leftPad("bat", 5, "yz") = "yzbat"
* StringUtils.leftPad("bat", 8, "yz") = "yzyzybat"
* StringUtils.leftPad("bat", 1, "yz") = "bat"
* StringUtils.leftPad("bat", -1, "yz") = "bat"
* StringUtils.leftPad("bat", 5, null) = " bat"
* StringUtils.leftPad("bat", 5, "") = " bat"
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @param padStr the String to pad with, null or empty treated as single space
* @return left padded String or original String if no padding is necessary,
* <code>null</code> if null String input
*/
public static String leftPad(String str, int size, String padStr) {
if (str == null) {
return null;
}
if (isEmpty(padStr)) {
padStr = " ";
}
int padLen = padStr.length();
int strLen = str.length();
int pads = size - strLen;
if (pads <= 0) {
return str; // returns original String when possible
}
if (padLen == 1 && pads <= PAD_LIMIT) {
return leftPad(str, size, padStr.charAt(0));
}
if (pads == padLen) {
return padStr.concat(str);
} else if (pads < padLen) {
return padStr.substring(0, pads).concat(str);
} else {
char[] padding = new char[pads];
char[] padChars = padStr.toCharArray();
for (int i = 0; i < pads; i++) {
padding[i] = padChars[i % padLen];
}
return new String(padding).concat(str);
}
}
/**
* Gets a CharSequence length or <code>0</code> if the CharSequence is
* <code>null</code>.
*
* @param cs
* a CharSequence or <code>null</code>
* @return CharSequence length or <code>0</code> if the CharSequence is
* <code>null</code>.
* @since 2.4
* @deprecated See {@link CharSequenceUtils#length(CharSequence)}
* @since 3.0 Changed signature from length(String) to length(CharSequence)
*/
public static int length(CharSequence cs) {
return CharSequenceUtils.length(cs);
}
// Centering
//-----------------------------------------------------------------------
/**
* <p>Centers a String in a larger String of size <code>size</code>
* using the space character (' ').<p>
*
* <p>If the size is less than the String length, the String is returned.
* A <code>null</code> String returns <code>null</code>.
* A negative size is treated as zero.</p>
*
* <p>Equivalent to <code>center(str, size, " ")</code>.</p>
*
* <pre>
* StringUtils.center(null, *) = null
* StringUtils.center("", 4) = " "
* StringUtils.center("ab", -1) = "ab"
* StringUtils.center("ab", 4) = " ab "
* StringUtils.center("abcd", 2) = "abcd"
* StringUtils.center("a", 4) = " a "
* </pre>
*
* @param str the String to center, may be null
* @param size the int size of new String, negative treated as zero
* @return centered String, <code>null</code> if null String input
*/
public static String center(String str, int size) {
return center(str, size, ' ');
}
/**
* <p>Centers a String in a larger String of size <code>size</code>.
* Uses a supplied character as the value to pad the String with.</p>
*
* <p>If the size is less than the String length, the String is returned.
* A <code>null</code> String returns <code>null</code>.
* A negative size is treated as zero.</p>
*
* <pre>
* StringUtils.center(null, *, *) = null
* StringUtils.center("", 4, ' ') = " "
* StringUtils.center("ab", -1, ' ') = "ab"
* StringUtils.center("ab", 4, ' ') = " ab"
* StringUtils.center("abcd", 2, ' ') = "abcd"
* StringUtils.center("a", 4, ' ') = " a "
* StringUtils.center("a", 4, 'y') = "yayy"
* </pre>
*
* @param str the String to center, may be null
* @param size the int size of new String, negative treated as zero
* @param padChar the character to pad the new String with
* @return centered String, <code>null</code> if null String input
* @since 2.0
*/
public static String center(String str, int size, char padChar) {
if (str == null || size <= 0) {
return str;
}
int strLen = str.length();
int pads = size - strLen;
if (pads <= 0) {
return str;
}
str = leftPad(str, strLen + pads / 2, padChar);
str = rightPad(str, size, padChar);
return str;
}
/**
* <p>Centers a String in a larger String of size <code>size</code>.
* Uses a supplied String as the value to pad the String with.</p>
*
* <p>If the size is less than the String length, the String is returned.
* A <code>null</code> String returns <code>null</code>.
* A negative size is treated as zero.</p>
*
* <pre>
* StringUtils.center(null, *, *) = null
* StringUtils.center("", 4, " ") = " "
* StringUtils.center("ab", -1, " ") = "ab"
* StringUtils.center("ab", 4, " ") = " ab"
* StringUtils.center("abcd", 2, " ") = "abcd"
* StringUtils.center("a", 4, " ") = " a "
* StringUtils.center("a", 4, "yz") = "yayz"
* StringUtils.center("abc", 7, null) = " abc "
* StringUtils.center("abc", 7, "") = " abc "
* </pre>
*
* @param str the String to center, may be null
* @param size the int size of new String, negative treated as zero
* @param padStr the String to pad the new String with, must not be null or empty
* @return centered String, <code>null</code> if null String input
* @throws IllegalArgumentException if padStr is <code>null</code> or empty
*/
public static String center(String str, int size, String padStr) {
if (str == null || size <= 0) {
return str;
}
if (isEmpty(padStr)) {
padStr = " ";
}
int strLen = str.length();
int pads = size - strLen;
if (pads <= 0) {
return str;
}
str = leftPad(str, strLen + pads / 2, padStr);
str = rightPad(str, size, padStr);
return str;
}
// Case conversion
//-----------------------------------------------------------------------
/**
* <p>Converts a String to upper case as per {@link String#toUpperCase()}.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.upperCase(null) = null
* StringUtils.upperCase("") = ""
* StringUtils.upperCase("aBc") = "ABC"
* </pre>
*
* <p><strong>Note:</strong> As described in the documentation for {@link String#toUpperCase()},
* the result of this method is affected by the current locale.
* For platform-independent case transformations, the method {@link #lowerCase(String, Locale)}
* should be used with a specific locale (e.g. {@link Locale#ENGLISH}).</p>
*
* @param str the String to upper case, may be null
* @return the upper cased String, <code>null</code> if null String input
*/
public static String upperCase(String str) {
if (str == null) {
return null;
}
return str.toUpperCase();
}
/**
* <p>Converts a String to upper case as per {@link String#toUpperCase(Locale)}.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.upperCase(null, Locale.ENGLISH) = null
* StringUtils.upperCase("", Locale.ENGLISH) = ""
* StringUtils.upperCase("aBc", Locale.ENGLISH) = "ABC"
* </pre>
*
* @param str the String to upper case, may be null
* @param locale the locale that defines the case transformation rules, must not be null
* @return the upper cased String, <code>null</code> if null String input
* @since 2.5
*/
public static String upperCase(String str, Locale locale) {
if (str == null) {
return null;
}
return str.toUpperCase(locale);
}
/**
* <p>Converts a String to lower case as per {@link String#toLowerCase()}.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.lowerCase(null) = null
* StringUtils.lowerCase("") = ""
* StringUtils.lowerCase("aBc") = "abc"
* </pre>
*
* <p><strong>Note:</strong> As described in the documentation for {@link String#toLowerCase()},
* the result of this method is affected by the current locale.
* For platform-independent case transformations, the method {@link #lowerCase(String, Locale)}
* should be used with a specific locale (e.g. {@link Locale#ENGLISH}).</p>
*
* @param str the String to lower case, may be null
* @return the lower cased String, <code>null</code> if null String input
*/
public static String lowerCase(String str) {
if (str == null) {
return null;
}
return str.toLowerCase();
}
/**
* <p>Converts a String to lower case as per {@link String#toLowerCase(Locale)}.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.lowerCase(null, Locale.ENGLISH) = null
* StringUtils.lowerCase("", Locale.ENGLISH) = ""
* StringUtils.lowerCase("aBc", Locale.ENGLISH) = "abc"
* </pre>
*
* @param str the String to lower case, may be null
* @param locale the locale that defines the case transformation rules, must not be null
* @return the lower cased String, <code>null</code> if null String input
* @since 2.5
*/
public static String lowerCase(String str, Locale locale) {
if (str == null) {
return null;
}
return str.toLowerCase(locale);
}
/**
* <p>Capitalizes a String changing the first letter to title case as
* per {@link Character#toTitleCase(char)}. No other letters are changed.</p>
*
* <p>For a word based algorithm, see {@link org.apache.commons.lang3.text.WordUtils#capitalize(String)}.
* A <code>null</code> input String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.capitalize(null) = null
* StringUtils.capitalize("") = ""
* StringUtils.capitalize("cat") = "Cat"
* StringUtils.capitalize("cAt") = "CAt"
* </pre>
*
* @param cs the String to capitalize, may be null
* @return the capitalized String, <code>null</code> if null String input
* @see org.apache.commons.lang3.text.WordUtils#capitalize(String)
* @see #uncapitalize(CharSequence)
* @since 2.0
* @since 3.0 Changed signature from capitalize(String) to capitalize(CharSequence)
*/
public static String capitalize(CharSequence cs) {
if (cs == null ) {
return null;
}
int strLen;
if ((strLen = cs.length()) == 0) {
return cs.toString();
}
return new StringBuilder(strLen)
.append(Character.toTitleCase(cs.charAt(0)))
.append(CharSequenceUtils.subSequence(cs, 1))
.toString();
}
/**
* <p>Uncapitalizes a CharSequence changing the first letter to title case as
* per {@link Character#toLowerCase(char)}. No other letters are changed.</p>
*
* <p>For a word based algorithm, see {@link org.apache.commons.lang3.text.WordUtils#uncapitalize(String)}.
* A <code>null</code> input String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.uncapitalize(null) = null
* StringUtils.uncapitalize("") = ""
* StringUtils.uncapitalize("Cat") = "cat"
* StringUtils.uncapitalize("CAT") = "cAT"
* </pre>
*
* @param cs the String to uncapitalize, may be null
* @return the uncapitalized String, <code>null</code> if null String input
* @see org.apache.commons.lang3.text.WordUtils#uncapitalize(String)
* @see #capitalize(CharSequence)
* @since 2.0
* @since 3.0 Changed signature from uncapitalize(String) to uncapitalize(CharSequence)
*/
public static String uncapitalize(CharSequence cs) {
if (cs == null ) {
return null;
}
int strLen;
if ((strLen = cs.length()) == 0) {
return cs.toString();
}
return new StringBuilder(strLen)
.append(Character.toLowerCase(cs.charAt(0)))
.append(CharSequenceUtils.subSequence(cs, 1))
.toString();
}
/**
* <p>Swaps the case of a String changing upper and title case to
* lower case, and lower case to upper case.</p>
*
* <ul>
* <li>Upper case character converts to Lower case</li>
* <li>Title case character converts to Lower case</li>
* <li>Lower case character converts to Upper case</li>
* </ul>
*
* <p>For a word based algorithm, see {@link org.apache.commons.lang3.text.WordUtils#swapCase(String)}.
* A <code>null</code> input String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.swapCase(null) = null
* StringUtils.swapCase("") = ""
* StringUtils.swapCase("The dog has a BONE") = "tHE DOG HAS A bone"
* </pre>
*
* <p>NOTE: This method changed in Lang version 2.0.
* It no longer performs a word based algorithm.
* If you only use ASCII, you will notice no change.
* That functionality is available in org.apache.commons.lang3.text.WordUtils.</p>
*
* @param str the String to swap case, may be null
* @return the changed String, <code>null</code> if null String input
*/
public static String swapCase(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return str;
}
StringBuilder buffer = new StringBuilder(strLen);
char ch = 0;
for (int i = 0; i < strLen; i++) {
ch = str.charAt(i);
if (Character.isUpperCase(ch)) {
ch = Character.toLowerCase(ch);
} else if (Character.isTitleCase(ch)) {
ch = Character.toLowerCase(ch);
} else if (Character.isLowerCase(ch)) {
ch = Character.toUpperCase(ch);
}
buffer.append(ch);
}
return buffer.toString();
}
// Count matches
//-----------------------------------------------------------------------
/**
* <p>Counts how many times the substring appears in the larger String.</p>
*
* <p>A <code>null</code> or empty ("") String input returns <code>0</code>.</p>
*
* <pre>
* StringUtils.countMatches(null, *) = 0
* StringUtils.countMatches("", *) = 0
* StringUtils.countMatches("abba", null) = 0
* StringUtils.countMatches("abba", "") = 0
* StringUtils.countMatches("abba", "a") = 2
* StringUtils.countMatches("abba", "ab") = 1
* StringUtils.countMatches("abba", "xxx") = 0
* </pre>
*
* @param str the String to check, may be null
* @param sub the substring to count, may be null
* @return the number of occurrences, 0 if either String is <code>null</code>
*/
public static int countMatches(String str, String sub) {
if (isEmpty(str) || isEmpty(sub)) {
return 0;
}
int count = 0;
int idx = 0;
while ((idx = str.indexOf(sub, idx)) != INDEX_NOT_FOUND) {
count++;
idx += sub.length();
}
return count;
}
// Character Tests
//-----------------------------------------------------------------------
/**
* <p>Checks if the CharSequence contains only unicode letters.</p>
*
* <p><code>null</code> will return <code>false</code>.
* An empty CharSequence (length()=0) will return <code>true</code>.</p>
*
* <pre>
* StringUtils.isAlpha(null) = false
* StringUtils.isAlpha("") = true
* StringUtils.isAlpha(" ") = false
* StringUtils.isAlpha("abc") = true
* StringUtils.isAlpha("ab2c") = false
* StringUtils.isAlpha("ab-c") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return <code>true</code> if only contains letters, and is non-null
* @since 3.0 Changed signature from isAlpha(String) to isAlpha(CharSequence)
*/
public static boolean isAlpha(CharSequence cs) {
if (cs == null) {
return false;
}
int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (Character.isLetter(cs.charAt(i)) == false) {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only unicode letters and
* space (' ').</p>
*
* <p><code>null</code> will return <code>false</code>
* An empty CharSequence (length()=0) will return <code>true</code>.</p>
*
* <pre>
* StringUtils.isAlphaSpace(null) = false
* StringUtils.isAlphaSpace("") = true
* StringUtils.isAlphaSpace(" ") = true
* StringUtils.isAlphaSpace("abc") = true
* StringUtils.isAlphaSpace("ab c") = true
* StringUtils.isAlphaSpace("ab2c") = false
* StringUtils.isAlphaSpace("ab-c") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return <code>true</code> if only contains letters and space,
* and is non-null
* @since 3.0 Changed signature from isAlphaSpace(String) to isAlphaSpace(CharSequence)
*/
public static boolean isAlphaSpace(CharSequence cs) {
if (cs == null) {
return false;
}
int sz = cs.length();
for (int i = 0; i < sz; i++) {
if ((Character.isLetter(cs.charAt(i)) == false) && (cs.charAt(i) != ' ')) {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only unicode letters or digits.</p>
*
* <p><code>null</code> will return <code>false</code>.
* An empty CharSequence (length()=0) will return <code>true</code>.</p>
*
* <pre>
* StringUtils.isAlphanumeric(null) = false
* StringUtils.isAlphanumeric("") = true
* StringUtils.isAlphanumeric(" ") = false
* StringUtils.isAlphanumeric("abc") = true
* StringUtils.isAlphanumeric("ab c") = false
* StringUtils.isAlphanumeric("ab2c") = true
* StringUtils.isAlphanumeric("ab-c") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return <code>true</code> if only contains letters or digits,
* and is non-null
* @since 3.0 Changed signature from isAlphanumeric(String) to isAlphanumeric(CharSequence)
*/
public static boolean isAlphanumeric(CharSequence cs) {
if (cs == null) {
return false;
}
int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (Character.isLetterOrDigit(cs.charAt(i)) == false) {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only unicode letters, digits
* or space (<code>' '</code>).</p>
*
* <p><code>null</code> will return <code>false</code>.
* An empty CharSequence (length()=0) will return <code>true</code>.</p>
*
* <pre>
* StringUtils.isAlphanumeric(null) = false
* StringUtils.isAlphanumeric("") = true
* StringUtils.isAlphanumeric(" ") = true
* StringUtils.isAlphanumeric("abc") = true
* StringUtils.isAlphanumeric("ab c") = true
* StringUtils.isAlphanumeric("ab2c") = true
* StringUtils.isAlphanumeric("ab-c") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return <code>true</code> if only contains letters, digits or space,
* and is non-null
* @since 3.0 Changed signature from isAlphanumericSpace(String) to isAlphanumericSpace(CharSequence)
*/
public static boolean isAlphanumericSpace(CharSequence cs) {
if (cs == null) {
return false;
}
int sz = cs.length();
for (int i = 0; i < sz; i++) {
if ((Character.isLetterOrDigit(cs.charAt(i)) == false) && (cs.charAt(i) != ' ')) {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only ASCII printable characters.</p>
*
* <p><code>null</code> will return <code>false</code>.
* An empty CharSequence (length()=0) will return <code>true</code>.</p>
*
* <pre>
* StringUtils.isAsciiPrintable(null) = false
* StringUtils.isAsciiPrintable("") = true
* StringUtils.isAsciiPrintable(" ") = true
* StringUtils.isAsciiPrintable("Ceki") = true
* StringUtils.isAsciiPrintable("ab2c") = true
* StringUtils.isAsciiPrintable("!ab-c~") = true
* StringUtils.isAsciiPrintable("\u0020") = true
* StringUtils.isAsciiPrintable("\u0021") = true
* StringUtils.isAsciiPrintable("\u007e") = true
* StringUtils.isAsciiPrintable("\u007f") = false
* StringUtils.isAsciiPrintable("Ceki G\u00fclc\u00fc") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return <code>true</code> if every character is in the range
* 32 thru 126
* @since 2.1
* @since 3.0 Changed signature from isAsciiPrintable(String) to isAsciiPrintable(CharSequence)
*/
public static boolean isAsciiPrintable(CharSequence cs) {
if (cs == null) {
return false;
}
int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (CharUtils.isAsciiPrintable(cs.charAt(i)) == false) {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only unicode digits.
* A decimal point is not a unicode digit and returns false.</p>
*
* <p><code>null</code> will return <code>false</code>.
* An empty CharSequence (length()=0) will return <code>true</code>.</p>
*
* <pre>
* StringUtils.isNumeric(null) = false
* StringUtils.isNumeric("") = true
* StringUtils.isNumeric(" ") = false
* StringUtils.isNumeric("123") = true
* StringUtils.isNumeric("12 3") = false
* StringUtils.isNumeric("ab2c") = false
* StringUtils.isNumeric("12-3") = false
* StringUtils.isNumeric("12.3") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return <code>true</code> if only contains digits, and is non-null
* @since 3.0 Changed signature from isNumeric(String) to isNumeric(CharSequence)
*/
public static boolean isNumeric(CharSequence cs) {
if (cs == null) {
return false;
}
int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (Character.isDigit(cs.charAt(i)) == false) {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only unicode digits or space
* (<code>' '</code>).
* A decimal point is not a unicode digit and returns false.</p>
*
* <p><code>null</code> will return <code>false</code>.
* An empty CharSequence (length()=0) will return <code>true</code>.</p>
*
* <pre>
* StringUtils.isNumeric(null) = false
* StringUtils.isNumeric("") = true
* StringUtils.isNumeric(" ") = true
* StringUtils.isNumeric("123") = true
* StringUtils.isNumeric("12 3") = true
* StringUtils.isNumeric("ab2c") = false
* StringUtils.isNumeric("12-3") = false
* StringUtils.isNumeric("12.3") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return <code>true</code> if only contains digits or space,
* and is non-null
* @since 3.0 Changed signature from isNumericSpace(String) to isNumericSpace(CharSequence)
*/
public static boolean isNumericSpace(CharSequence cs) {
if (cs == null) {
return false;
}
int sz = cs.length();
for (int i = 0; i < sz; i++) {
if ((Character.isDigit(cs.charAt(i)) == false) && (cs.charAt(i) != ' ')) {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only whitespace.</p>
*
* <p><code>null</code> will return <code>false</code>.
* An empty CharSequence (length()=0) will return <code>true</code>.</p>
*
* <pre>
* StringUtils.isWhitespace(null) = false
* StringUtils.isWhitespace("") = true
* StringUtils.isWhitespace(" ") = true
* StringUtils.isWhitespace("abc") = false
* StringUtils.isWhitespace("ab2c") = false
* StringUtils.isWhitespace("ab-c") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return <code>true</code> if only contains whitespace, and is non-null
* @since 2.0
* @since 3.0 Changed signature from isWhitespace(String) to isWhitespace(CharSequence)
*/
public static boolean isWhitespace(CharSequence cs) {
if (cs == null) {
return false;
}
int sz = cs.length();
for (int i = 0; i < sz; i++) {
if ((Character.isWhitespace(cs.charAt(i)) == false)) {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only lowercase characters.</p>
*
* <p><code>null</code> will return <code>false</code>.
* An empty CharSequence (length()=0) will return <code>false</code>.</p>
*
* <pre>
* StringUtils.isAllLowerCase(null) = false
* StringUtils.isAllLowerCase("") = false
* StringUtils.isAllLowerCase(" ") = false
* StringUtils.isAllLowerCase("abc") = true
* StringUtils.isAllLowerCase("abC") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return <code>true</code> if only contains lowercase characters, and is non-null
* @since 2.5
* @since 3.0 Changed signature from isAllLowerCase(String) to isAllLowerCase(CharSequence)
*/
public static boolean isAllLowerCase(CharSequence cs) {
if (cs == null || isEmpty(cs)) {
return false;
}
int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (Character.isLowerCase(cs.charAt(i)) == false) {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only uppercase characters.</p>
*
* <p><code>null</code> will return <code>false</code>.
* An empty String (length()=0) will return <code>false</code>.</p>
*
* <pre>
* StringUtils.isAllUpperCase(null) = false
* StringUtils.isAllUpperCase("") = false
* StringUtils.isAllUpperCase(" ") = false
* StringUtils.isAllUpperCase("ABC") = true
* StringUtils.isAllUpperCase("aBC") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return <code>true</code> if only contains uppercase characters, and is non-null
* @since 2.5
* @since 3.0 Changed signature from isAllUpperCase(String) to isAllUpperCase(CharSequence)
*/
public static boolean isAllUpperCase(CharSequence cs) {
if (cs == null || isEmpty(cs)) {
return false;
}
int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (Character.isUpperCase(cs.charAt(i)) == false) {
return false;
}
}
return true;
}
// Defaults
//-----------------------------------------------------------------------
/**
* <p>Returns either the passed in String,
* or if the String is <code>null</code>, an empty String ("").</p>
*
* <pre>
* StringUtils.defaultString(null) = ""
* StringUtils.defaultString("") = ""
* StringUtils.defaultString("bat") = "bat"
* </pre>
*
* @see ObjectUtils#toString(Object)
* @see String#valueOf(Object)
* @param str the String to check, may be null
* @return the passed in String, or the empty String if it
* was <code>null</code>
*/
public static String defaultString(String str) {
return str == null ? EMPTY : str;
}
/**
* <p>Returns either the passed in String, or if the String is
* <code>null</code>, the value of <code>defaultStr</code>.</p>
*
* <pre>
* StringUtils.defaultString(null, "NULL") = "NULL"
* StringUtils.defaultString("", "NULL") = ""
* StringUtils.defaultString("bat", "NULL") = "bat"
* </pre>
*
* @see ObjectUtils#toString(Object,String)
* @see String#valueOf(Object)
* @param str the String to check, may be null
* @param defaultStr the default String to return
* if the input is <code>null</code>, may be null
* @return the passed in String, or the default if it was <code>null</code>
*/
public static String defaultString(String str, String defaultStr) {
return str == null ? defaultStr : str;
}
/**
* <p>Returns either the passed in CharSequence, or if the CharSequence is
* empty or <code>null</code>, the value of <code>defaultStr</code>.</p>
*
* <pre>
* StringUtils.defaultIfEmpty(null, "NULL") = "NULL"
* StringUtils.defaultIfEmpty("", "NULL") = "NULL"
* StringUtils.defaultIfEmpty("bat", "NULL") = "bat"
* StringUtils.defaultIfEmpty("", null) = null
* </pre>
* @param <T> the specific kind of CharSequence
* @param str the CharSequence to check, may be null
* @param defaultStr the default CharSequence to return
* if the input is empty ("") or <code>null</code>, may be null
* @return the passed in CharSequence, or the default
* @see StringUtils#defaultString(String, String)
*/
public static <T extends CharSequence> T defaultIfEmpty(T str, T defaultStr) {
return StringUtils.isEmpty(str) ? defaultStr : str;
}
// Reversing
//-----------------------------------------------------------------------
/**
* <p>Reverses a String as per {@link StringBuilder#reverse()}.</p>
*
* <p>A <code>null</code> String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.reverse(null) = null
* StringUtils.reverse("") = ""
* StringUtils.reverse("bat") = "tab"
* </pre>
*
* @param str the String to reverse, may be null
* @return the reversed String, <code>null</code> if null String input
*/
public static String reverse(String str) {
if (str == null) {
return null;
}
return new StringBuilder(str).reverse().toString();
}
/**
* <p>Reverses a String that is delimited by a specific character.</p>
*
* <p>The Strings between the delimiters are not reversed.
* Thus java.lang.String becomes String.lang.java (if the delimiter
* is <code>'.'</code>).</p>
*
* <pre>
* StringUtils.reverseDelimited(null, *) = null
* StringUtils.reverseDelimited("", *) = ""
* StringUtils.reverseDelimited("a.b.c", 'x') = "a.b.c"
* StringUtils.reverseDelimited("a.b.c", ".") = "c.b.a"
* </pre>
*
* @param str the String to reverse, may be null
* @param separatorChar the separator character to use
* @return the reversed String, <code>null</code> if null String input
* @since 2.0
*/
public static String reverseDelimited(String str, char separatorChar) {
if (str == null) {
return null;
}
// could implement manually, but simple way is to reuse other,
// probably slower, methods.
String[] strs = split(str, separatorChar);
ArrayUtils.reverse(strs);
return join(strs, separatorChar);
}
// Abbreviating
//-----------------------------------------------------------------------
/**
* <p>Abbreviates a String using ellipses. This will turn
* "Now is the time for all good men" into "Now is the time for..."</p>
*
* <p>Specifically:
* <ul>
* <li>If <code>str</code> is less than <code>maxWidth</code> characters
* long, return it.</li>
* <li>Else abbreviate it to <code>(substring(str, 0, max-3) + "...")</code>.</li>
* <li>If <code>maxWidth</code> is less than <code>4</code>, throw an
* <code>IllegalArgumentException</code>.</li>
* <li>In no case will it return a String of length greater than
* <code>maxWidth</code>.</li>
* </ul>
* </p>
*
* <pre>
* StringUtils.abbreviate(null, *) = null
* StringUtils.abbreviate("", 4) = ""
* StringUtils.abbreviate("abcdefg", 6) = "abc..."
* StringUtils.abbreviate("abcdefg", 7) = "abcdefg"
* StringUtils.abbreviate("abcdefg", 8) = "abcdefg"
* StringUtils.abbreviate("abcdefg", 4) = "a..."
* StringUtils.abbreviate("abcdefg", 3) = IllegalArgumentException
* </pre>
*
* @param str the String to check, may be null
* @param maxWidth maximum length of result String, must be at least 4
* @return abbreviated String, <code>null</code> if null String input
* @throws IllegalArgumentException if the width is too small
* @since 2.0
*/
public static String abbreviate(String str, int maxWidth) {
return abbreviate(str, 0, maxWidth);
}
/**
* <p>Abbreviates a String using ellipses. This will turn
* "Now is the time for all good men" into "...is the time for..."</p>
*
* <p>Works like <code>abbreviate(String, int)</code>, but allows you to specify
* a "left edge" offset. Note that this left edge is not necessarily going to
* be the leftmost character in the result, or the first character following the
* ellipses, but it will appear somewhere in the result.
*
* <p>In no case will it return a String of length greater than
* <code>maxWidth</code>.</p>
*
* <pre>
* StringUtils.abbreviate(null, *, *) = null
* StringUtils.abbreviate("", 0, 4) = ""
* StringUtils.abbreviate("abcdefghijklmno", -1, 10) = "abcdefg..."
* StringUtils.abbreviate("abcdefghijklmno", 0, 10) = "abcdefg..."
* StringUtils.abbreviate("abcdefghijklmno", 1, 10) = "abcdefg..."
* StringUtils.abbreviate("abcdefghijklmno", 4, 10) = "abcdefg..."
* StringUtils.abbreviate("abcdefghijklmno", 5, 10) = "...fghi..."
* StringUtils.abbreviate("abcdefghijklmno", 6, 10) = "...ghij..."
* StringUtils.abbreviate("abcdefghijklmno", 8, 10) = "...ijklmno"
* StringUtils.abbreviate("abcdefghijklmno", 10, 10) = "...ijklmno"
* StringUtils.abbreviate("abcdefghijklmno", 12, 10) = "...ijklmno"
* StringUtils.abbreviate("abcdefghij", 0, 3) = IllegalArgumentException
* StringUtils.abbreviate("abcdefghij", 5, 6) = IllegalArgumentException
* </pre>
*
* @param str the String to check, may be null
* @param offset left edge of source String
* @param maxWidth maximum length of result String, must be at least 4
* @return abbreviated String, <code>null</code> if null String input
* @throws IllegalArgumentException if the width is too small
* @since 2.0
*/
public static String abbreviate(String str, int offset, int maxWidth) {
if (str == null) {
return null;
}
if (maxWidth < 4) {
throw new IllegalArgumentException("Minimum abbreviation width is 4");
}
if (str.length() <= maxWidth) {
return str;
}
if (offset > str.length()) {
offset = str.length();
}
if ((str.length() - offset) < (maxWidth - 3)) {
offset = str.length() - (maxWidth - 3);
}
final String abrevMarker = "...";
if (offset <= 4) {
return str.substring(0, maxWidth - 3) + abrevMarker;
}
if (maxWidth < 7) {
throw new IllegalArgumentException("Minimum abbreviation width with offset is 7");
}
if ((offset + (maxWidth - 3)) < str.length()) {
return abrevMarker + abbreviate(str.substring(offset), maxWidth - 3);
}
return abrevMarker + str.substring(str.length() - (maxWidth - 3));
}
/**
* <p>Abbreviates a String to the length passed, replacing the middle characters with the supplied
* replacement String.</p>
*
* <p>This abbreviation only occurs if the following criteria is met:
* <ul>
* <li>Neither the String for abbreviation nor the replacement String are null or empty </li>
* <li>The length to truncate to is less than the length of the supplied String</li>
* <li>The length to truncate to is greater than 0</li>
* <li>The abbreviated String will have enough room for the length supplied replacement String
* and the first and last characters of the supplied String for abbreviation</li>
* </ul>
* Otherwise, the returned String will be the same as the supplied String for abbreviation.
* </p>
*
* <pre>
* StringUtils.abbreviateMiddle(null, null, 0) = null
* StringUtils.abbreviateMiddle("abc", null, 0) = "abc"
* StringUtils.abbreviateMiddle("abc", ".", 0) = "abc"
* StringUtils.abbreviateMiddle("abc", ".", 3) = "abc"
* StringUtils.abbreviateMiddle("abcdef", ".", 4) = "ab.f"
* </pre>
*
* @param str the String to abbreviate, may be null
* @param middle the String to replace the middle characters with, may be null
* @param length the length to abbreviate <code>str</code> to.
* @return the abbreviated String if the above criteria is met, or the original String supplied for abbreviation.
* @since 2.5
*/
public static String abbreviateMiddle(String str, String middle, int length) {
if (isEmpty(str) || isEmpty(middle)) {
return str;
}
if (length >= str.length() || length < (middle.length()+2)) {
return str;
}
int targetSting = length-middle.length();
int startOffset = targetSting/2+targetSting%2;
int endOffset = str.length()-targetSting/2;
StringBuilder builder = new StringBuilder(length);
builder.append(str.substring(0,startOffset));
builder.append(middle);
builder.append(str.substring(endOffset));
return builder.toString();
}
// Difference
//-----------------------------------------------------------------------
/**
* <p>Compares two Strings, and returns the portion where they differ.
* (More precisely, return the remainder of the second String,
* starting from where it's different from the first.)</p>
*
* <p>For example,
* <code>difference("i am a machine", "i am a robot") -> "robot"</code>.</p>
*
* <pre>
* StringUtils.difference(null, null) = null
* StringUtils.difference("", "") = ""
* StringUtils.difference("", "abc") = "abc"
* StringUtils.difference("abc", "") = ""
* StringUtils.difference("abc", "abc") = ""
* StringUtils.difference("ab", "abxyz") = "xyz"
* StringUtils.difference("abcde", "abxyz") = "xyz"
* StringUtils.difference("abcde", "xyz") = "xyz"
* </pre>
*
* @param str1 the first String, may be null
* @param str2 the second String, may be null
* @return the portion of str2 where it differs from str1; returns the
* empty String if they are equal
* @since 2.0
*/
public static String difference(String str1, String str2) {
if (str1 == null) {
return str2;
}
if (str2 == null) {
return str1;
}
int at = indexOfDifference(str1, str2);
if (at == INDEX_NOT_FOUND) {
return EMPTY;
}
return str2.substring(at);
}
/**
* <p>Compares two CharSequences, and returns the index at which the
* CharSequences begin to differ.</p>
*
* <p>For example,
* <code>indexOfDifference("i am a machine", "i am a robot") -> 7</code></p>
*
* <pre>
* StringUtils.indexOfDifference(null, null) = -1
* StringUtils.indexOfDifference("", "") = -1
* StringUtils.indexOfDifference("", "abc") = 0
* StringUtils.indexOfDifference("abc", "") = 0
* StringUtils.indexOfDifference("abc", "abc") = -1
* StringUtils.indexOfDifference("ab", "abxyz") = 2
* StringUtils.indexOfDifference("abcde", "abxyz") = 2
* StringUtils.indexOfDifference("abcde", "xyz") = 0
* </pre>
*
* @param cs1 the first CharSequence, may be null
* @param cs2 the second CharSequence, may be null
* @return the index where cs1 and cs2 begin to differ; -1 if they are equal
* @since 2.0
* @since 3.0 Changed signature from indexOfDifference(String, String) to indexOfDifference(CharSequence, CharSequence)
*/
public static int indexOfDifference(CharSequence cs1, CharSequence cs2) {
if (cs1 == cs2) {
return INDEX_NOT_FOUND;
}
if (cs1 == null || cs2 == null) {
return 0;
}
int i;
for (i = 0; i < cs1.length() && i < cs2.length(); ++i) {
if (cs1.charAt(i) != cs2.charAt(i)) {
break;
}
}
if (i < cs2.length() || i < cs1.length()) {
return i;
}
return INDEX_NOT_FOUND;
}
/**
* <p>Compares all CharSequences in an array and returns the index at which the
* CharSequences begin to differ.</p>
*
* <p>For example,
* <code>indexOfDifference(new String[] {"i am a machine", "i am a robot"}) -> 7</code></p>
*
* <pre>
* StringUtils.indexOfDifference(null) = -1
* StringUtils.indexOfDifference(new String[] {}) = -1
* StringUtils.indexOfDifference(new String[] {"abc"}) = -1
* StringUtils.indexOfDifference(new String[] {null, null}) = -1
* StringUtils.indexOfDifference(new String[] {"", ""}) = -1
* StringUtils.indexOfDifference(new String[] {"", null}) = 0
* StringUtils.indexOfDifference(new String[] {"abc", null, null}) = 0
* StringUtils.indexOfDifference(new String[] {null, null, "abc"}) = 0
* StringUtils.indexOfDifference(new String[] {"", "abc"}) = 0
* StringUtils.indexOfDifference(new String[] {"abc", ""}) = 0
* StringUtils.indexOfDifference(new String[] {"abc", "abc"}) = -1
* StringUtils.indexOfDifference(new String[] {"abc", "a"}) = 1
* StringUtils.indexOfDifference(new String[] {"ab", "abxyz"}) = 2
* StringUtils.indexOfDifference(new String[] {"abcde", "abxyz"}) = 2
* StringUtils.indexOfDifference(new String[] {"abcde", "xyz"}) = 0
* StringUtils.indexOfDifference(new String[] {"xyz", "abcde"}) = 0
* StringUtils.indexOfDifference(new String[] {"i am a machine", "i am a robot"}) = 7
* </pre>
*
* @param css array of CharSequences, entries may be null
* @return the index where the strings begin to differ; -1 if they are all equal
* @since 2.4
* @since 3.0 Changed signature from indexOfDifference(String...) to indexOfDifference(CharSequence...)
*/
public static int indexOfDifference(CharSequence... css) {
if (css == null || css.length <= 1) {
return INDEX_NOT_FOUND;
}
boolean anyStringNull = false;
boolean allStringsNull = true;
int arrayLen = css.length;
int shortestStrLen = Integer.MAX_VALUE;
int longestStrLen = 0;
// find the min and max string lengths; this avoids checking to make
// sure we are not exceeding the length of the string each time through
// the bottom loop.
for (int i = 0; i < arrayLen; i++) {
if (css[i] == null) {
anyStringNull = true;
shortestStrLen = 0;
} else {
allStringsNull = false;
shortestStrLen = Math.min(css[i].length(), shortestStrLen);
longestStrLen = Math.max(css[i].length(), longestStrLen);
}
}
// handle lists containing all nulls or all empty strings
if (allStringsNull || (longestStrLen == 0 && !anyStringNull)) {
return INDEX_NOT_FOUND;
}
// handle lists containing some nulls or some empty strings
if (shortestStrLen == 0) {
return 0;
}
// find the position with the first difference across all strings
int firstDiff = -1;
for (int stringPos = 0; stringPos < shortestStrLen; stringPos++) {
char comparisonChar = css[0].charAt(stringPos);
for (int arrayPos = 1; arrayPos < arrayLen; arrayPos++) {
if (css[arrayPos].charAt(stringPos) != comparisonChar) {
firstDiff = stringPos;
break;
}
}
if (firstDiff != -1) {
break;
}
}
if (firstDiff == -1 && shortestStrLen != longestStrLen) {
// we compared all of the characters up to the length of the
// shortest string and didn't find a match, but the string lengths
// vary, so return the length of the shortest string.
return shortestStrLen;
}
return firstDiff;
}
/**
* <p>Compares all Strings in an array and returns the initial sequence of
* characters that is common to all of them.</p>
*
* <p>For example,
* <code>getCommonPrefix(new String[] {"i am a machine", "i am a robot"}) -> "i am a "</code></p>
*
* <pre>
* StringUtils.getCommonPrefix(null) = ""
* StringUtils.getCommonPrefix(new String[] {}) = ""
* StringUtils.getCommonPrefix(new String[] {"abc"}) = "abc"
* StringUtils.getCommonPrefix(new String[] {null, null}) = ""
* StringUtils.getCommonPrefix(new String[] {"", ""}) = ""
* StringUtils.getCommonPrefix(new String[] {"", null}) = ""
* StringUtils.getCommonPrefix(new String[] {"abc", null, null}) = ""
* StringUtils.getCommonPrefix(new String[] {null, null, "abc"}) = ""
* StringUtils.getCommonPrefix(new String[] {"", "abc"}) = ""
* StringUtils.getCommonPrefix(new String[] {"abc", ""}) = ""
* StringUtils.getCommonPrefix(new String[] {"abc", "abc"}) = "abc"
* StringUtils.getCommonPrefix(new String[] {"abc", "a"}) = "a"
* StringUtils.getCommonPrefix(new String[] {"ab", "abxyz"}) = "ab"
* StringUtils.getCommonPrefix(new String[] {"abcde", "abxyz"}) = "ab"
* StringUtils.getCommonPrefix(new String[] {"abcde", "xyz"}) = ""
* StringUtils.getCommonPrefix(new String[] {"xyz", "abcde"}) = ""
* StringUtils.getCommonPrefix(new String[] {"i am a machine", "i am a robot"}) = "i am a "
* </pre>
*
* @param strs array of String objects, entries may be null
* @return the initial sequence of characters that are common to all Strings
* in the array; empty String if the array is null, the elements are all null
* or if there is no common prefix.
* @since 2.4
*/
public static String getCommonPrefix(String... strs) {
if (strs == null || strs.length == 0) {
return EMPTY;
}
int smallestIndexOfDiff = indexOfDifference(strs);
if (smallestIndexOfDiff == INDEX_NOT_FOUND) {
// all strings were identical
if (strs[0] == null) {
return EMPTY;
}
return strs[0];
} else if (smallestIndexOfDiff == 0) {
// there were no common initial characters
return EMPTY;
} else {
// we found a common initial character sequence
return strs[0].substring(0, smallestIndexOfDiff);
}
}
// Misc
//-----------------------------------------------------------------------
/**
* <p>Find the Levenshtein distance between two Strings.</p>
*
* <p>This is the number of changes needed to change one String into
* another, where each change is a single character modification (deletion,
* insertion or substitution).</p>
*
* <p>The previous implementation of the Levenshtein distance algorithm
* was from <a href="http://www.merriampark.com/ld.htm">http://www.merriampark.com/ld.htm</a></p>
*
* <p>Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError
* which can occur when my Java implementation is used with very large strings.<br>
* This implementation of the Levenshtein distance algorithm
* is from <a href="http://www.merriampark.com/ldjava.htm">http://www.merriampark.com/ldjava.htm</a></p>
*
* <pre>
* StringUtils.getLevenshteinDistance(null, *) = IllegalArgumentException
* StringUtils.getLevenshteinDistance(*, null) = IllegalArgumentException
* StringUtils.getLevenshteinDistance("","") = 0
* StringUtils.getLevenshteinDistance("","a") = 1
* StringUtils.getLevenshteinDistance("aaapppp", "") = 7
* StringUtils.getLevenshteinDistance("frog", "fog") = 1
* StringUtils.getLevenshteinDistance("fly", "ant") = 3
* StringUtils.getLevenshteinDistance("elephant", "hippo") = 7
* StringUtils.getLevenshteinDistance("hippo", "elephant") = 7
* StringUtils.getLevenshteinDistance("hippo", "zzzzzzzz") = 8
* StringUtils.getLevenshteinDistance("hello", "hallo") = 1
* </pre>
*
* @param s the first String, must not be null
* @param t the second String, must not be null
* @return result distance
* @throws IllegalArgumentException if either String input <code>null</code>
* @since 3.0 Changed signature from getLevenshteinDistance(String, String) to getLevenshteinDistance(CharSequence, CharSequence)
*/
public static int getLevenshteinDistance(CharSequence s, CharSequence t) {
if (s == null || t == null) {
throw new IllegalArgumentException("Strings must not be null");
}
/*
The difference between this impl. and the previous is that, rather
than creating and retaining a matrix of size s.length()+1 by t.length()+1,
we maintain two single-dimensional arrays of length s.length()+1. The first, d,
is the 'current working' distance array that maintains the newest distance cost
counts as we iterate through the characters of String s. Each time we increment
the index of String t we are comparing, d is copied to p, the second int[]. Doing so
allows us to retain the previous cost counts as required by the algorithm (taking
the minimum of the cost count to the left, up one, and diagonally up and to the left
of the current cost count being calculated). (Note that the arrays aren't really
copied anymore, just switched...this is clearly much better than cloning an array
or doing a System.arraycopy() each time through the outer loop.)
Effectively, the difference between the two implementations is this one does not
cause an out of memory condition when calculating the LD over two very large strings.
*/
int n = s.length(); // length of s
int m = t.length(); // length of t
if (n == 0) {
return m;
} else if (m == 0) {
return n;
}
if (n > m) {
// swap the input strings to consume less memory
CharSequence tmp = s;
s = t;
t = tmp;
n = m;
m = t.length();
}
int p[] = new int[n+1]; //'previous' cost array, horizontally
int d[] = new int[n+1]; // cost array, horizontally
int _d[]; //placeholder to assist in swapping p and d
// indexes into strings s and t
int i; // iterates through s
int j; // iterates through t
char t_j; // jth character of t
int cost; // cost
for (i = 0; i<=n; i++) {
p[i] = i;
}
for (j = 1; j<=m; j++) {
t_j = t.charAt(j-1);
d[0] = j;
for (i=1; i<=n; i++) {
cost = s.charAt(i-1)==t_j ? 0 : 1;
// minimum of cell to the left+1, to the top+1, diagonally left and up +cost
d[i] = Math.min(Math.min(d[i-1]+1, p[i]+1), p[i-1]+cost);
}
// copy current distance counts to 'previous row' distance counts
_d = p;
p = d;
d = _d;
}
// our last action in the above loop was to switch d and p, so p now
// actually has the most recent cost counts
return p[n];
}
/**
* <p>Gets the minimum of three <code>int</code> values.</p>
*
* @param a value 1
* @param b value 2
* @param c value 3
* @return the smallest of the values
*/
/*
private static int min(int a, int b, int c) {
// Method copied from NumberUtils to avoid dependency on subpackage
if (b < a) {
a = b;
}
if (c < a) {
a = c;
}
return a;
}
*/
// startsWith
//-----------------------------------------------------------------------
/**
* <p>Check if a String starts with a specified prefix.</p>
*
* <p><code>null</code>s are handled without exceptions. Two <code>null</code>
* references are considered to be equal. The comparison is case sensitive.</p>
*
* <pre>
* StringUtils.startsWith(null, null) = true
* StringUtils.startsWith(null, "abc") = false
* StringUtils.startsWith("abcdef", null) = false
* StringUtils.startsWith("abcdef", "abc") = true
* StringUtils.startsWith("ABCDEF", "abc") = false
* </pre>
*
* @see java.lang.String#startsWith(String)
* @param str the String to check, may be null
* @param prefix the prefix to find, may be null
* @return <code>true</code> if the String starts with the prefix, case sensitive, or
* both <code>null</code>
* @since 2.4
*/
public static boolean startsWith(String str, String prefix) {
return startsWith(str, prefix, false);
}
/**
* <p>Case insensitive check if a String starts with a specified prefix.</p>
*
* <p><code>null</code>s are handled without exceptions. Two <code>null</code>
* references are considered to be equal. The comparison is case insensitive.</p>
*
* <pre>
* StringUtils.startsWithIgnoreCase(null, null) = true
* StringUtils.startsWithIgnoreCase(null, "abc") = false
* StringUtils.startsWithIgnoreCase("abcdef", null) = false
* StringUtils.startsWithIgnoreCase("abcdef", "abc") = true
* StringUtils.startsWithIgnoreCase("ABCDEF", "abc") = true
* </pre>
*
* @see java.lang.String#startsWith(String)
* @param str the String to check, may be null
* @param prefix the prefix to find, may be null
* @return <code>true</code> if the String starts with the prefix, case insensitive, or
* both <code>null</code>
* @since 2.4
*/
public static boolean startsWithIgnoreCase(String str, String prefix) {
return startsWith(str, prefix, true);
}
/**
* <p>Check if a String starts with a specified prefix (optionally case insensitive).</p>
*
* @see java.lang.String#startsWith(String)
* @param str the String to check, may be null
* @param prefix the prefix to find, may be null
* @param ignoreCase inidicates whether the compare should ignore case
* (case insensitive) or not.
* @return <code>true</code> if the String starts with the prefix or
* both <code>null</code>
*/
private static boolean startsWith(String str, String prefix, boolean ignoreCase) {
if (str == null || prefix == null) {
return (str == null && prefix == null);
}
if (prefix.length() > str.length()) {
return false;
}
return str.regionMatches(ignoreCase, 0, prefix, 0, prefix.length());
}
/**
* <p>Check if a String starts with any of an array of specified strings.</p>
*
* <pre>
* StringUtils.startsWithAny(null, null) = false
* StringUtils.startsWithAny(null, new String[] {"abc"}) = false
* StringUtils.startsWithAny("abcxyz", null) = false
* StringUtils.startsWithAny("abcxyz", new String[] {""}) = false
* StringUtils.startsWithAny("abcxyz", new String[] {"abc"}) = true
* StringUtils.startsWithAny("abcxyz", new String[] {null, "xyz", "abc"}) = true
* </pre>
*
* @param string the String to check, may be null
* @param searchStrings the Strings to find, may be null or empty
* @return <code>true</code> if the String starts with any of the the prefixes, case insensitive, or
* both <code>null</code>
* @since 2.5
*/
public static boolean startsWithAny(String string, String... searchStrings) {
if (isEmpty(string) || ArrayUtils.isEmpty(searchStrings)) {
return false;
}
for (int i = 0; i < searchStrings.length; i++) {
String searchString = searchStrings[i];
if (StringUtils.startsWith(string, searchString)) {
return true;
}
}
return false;
}
// endsWith
//-----------------------------------------------------------------------
/**
* <p>Check if a String ends with a specified suffix.</p>
*
* <p><code>null</code>s are handled without exceptions. Two <code>null</code>
* references are considered to be equal. The comparison is case sensitive.</p>
*
* <pre>
* StringUtils.endsWith(null, null) = true
* StringUtils.endsWith(null, "def") = false
* StringUtils.endsWith("abcdef", null) = false
* StringUtils.endsWith("abcdef", "def") = true
* StringUtils.endsWith("ABCDEF", "def") = false
* StringUtils.endsWith("ABCDEF", "cde") = false
* </pre>
*
* @see java.lang.String#endsWith(String)
* @param str the String to check, may be null
* @param suffix the suffix to find, may be null
* @return <code>true</code> if the String ends with the suffix, case sensitive, or
* both <code>null</code>
* @since 2.4
*/
public static boolean endsWith(String str, String suffix) {
return endsWith(str, suffix, false);
}
/**
* <p>Case insensitive check if a String ends with a specified suffix.</p>
*
* <p><code>null</code>s are handled without exceptions. Two <code>null</code>
* references are considered to be equal. The comparison is case insensitive.</p>
*
* <pre>
* StringUtils.endsWithIgnoreCase(null, null) = true
* StringUtils.endsWithIgnoreCase(null, "def") = false
* StringUtils.endsWithIgnoreCase("abcdef", null) = false
* StringUtils.endsWithIgnoreCase("abcdef", "def") = true
* StringUtils.endsWithIgnoreCase("ABCDEF", "def") = true
* StringUtils.endsWithIgnoreCase("ABCDEF", "cde") = false
* </pre>
*
* @see java.lang.String#endsWith(String)
* @param str the String to check, may be null
* @param suffix the suffix to find, may be null
* @return <code>true</code> if the String ends with the suffix, case insensitive, or
* both <code>null</code>
* @since 2.4
*/
public static boolean endsWithIgnoreCase(String str, String suffix) {
return endsWith(str, suffix, true);
}
/**
* <p>Check if a String ends with a specified suffix (optionally case insensitive).</p>
*
* @see java.lang.String#endsWith(String)
* @param str the String to check, may be null
* @param suffix the suffix to find, may be null
* @param ignoreCase inidicates whether the compare should ignore case
* (case insensitive) or not.
* @return <code>true</code> if the String starts with the prefix or
* both <code>null</code>
*/
private static boolean endsWith(String str, String suffix, boolean ignoreCase) {
if (str == null || suffix == null) {
return str == null && suffix == null;
}
if (suffix.length() > str.length()) {
return false;
}
int strOffset = str.length() - suffix.length();
return str.regionMatches(ignoreCase, strOffset, suffix, 0, suffix.length());
}
}
|
src/main/java/org/apache/commons/lang3/StringUtils.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang3;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
/**
* <p>Operations on {@link java.lang.String} that are
* <code>null</code> safe.</p>
*
* <ul>
* <li><b>IsEmpty/IsBlank</b>
* - checks if a String contains text</li>
* <li><b>Trim/Strip</b>
* - removes leading and trailing whitespace</li>
* <li><b>Equals</b>
* - compares two strings null-safe</li>
* <li><b>startsWith</b>
* - check if a String starts with a prefix null-safe</li>
* <li><b>endsWith</b>
* - check if a String ends with a suffix null-safe</li>
* <li><b>IndexOf/LastIndexOf/Contains</b>
* - null-safe index-of checks
* <li><b>IndexOfAny/LastIndexOfAny/IndexOfAnyBut/LastIndexOfAnyBut</b>
* - index-of any of a set of Strings</li>
* <li><b>ContainsOnly/ContainsNone/ContainsAny</b>
* - does String contains only/none/any of these characters</li>
* <li><b>Substring/Left/Right/Mid</b>
* - null-safe substring extractions</li>
* <li><b>SubstringBefore/SubstringAfter/SubstringBetween</b>
* - substring extraction relative to other strings</li>
* <li><b>Split/Join</b>
* - splits a String into an array of substrings and vice versa</li>
* <li><b>Remove/Delete</b>
* - removes part of a String</li>
* <li><b>Replace/Overlay</b>
* - Searches a String and replaces one String with another</li>
* <li><b>Chomp/Chop</b>
* - removes the last part of a String</li>
* <li><b>LeftPad/RightPad/Center/Repeat</b>
* - pads a String</li>
* <li><b>UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize</b>
* - changes the case of a String</li>
* <li><b>CountMatches</b>
* - counts the number of occurrences of one String in another</li>
* <li><b>IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable</b>
* - checks the characters in a String</li>
* <li><b>DefaultString</b>
* - protects against a null input String</li>
* <li><b>Reverse/ReverseDelimited</b>
* - reverses a String</li>
* <li><b>Abbreviate</b>
* - abbreviates a string using ellipsis</li>
* <li><b>Difference</b>
* - compares Strings and reports on their differences</li>
* <li><b>LevensteinDistance</b>
* - the number of changes needed to change one String into another</li>
* </ul>
*
* <p>The <code>StringUtils</code> class defines certain words related to
* String handling.</p>
*
* <ul>
* <li>null - <code>null</code></li>
* <li>empty - a zero-length string (<code>""</code>)</li>
* <li>space - the space character (<code>' '</code>, char 32)</li>
* <li>whitespace - the characters defined by {@link Character#isWhitespace(char)}</li>
* <li>trim - the characters <= 32 as in {@link String#trim()}</li>
* </ul>
*
* <p><code>StringUtils</code> handles <code>null</code> input Strings quietly.
* That is to say that a <code>null</code> input will return <code>null</code>.
* Where a <code>boolean</code> or <code>int</code> is being returned
* details vary by method.</p>
*
* <p>A side effect of the <code>null</code> handling is that a
* <code>NullPointerException</code> should be considered a bug in
* <code>StringUtils</code>.</p>
*
* <p>Methods in this class give sample code to explain their operation.
* The symbol <code>*</code> is used to indicate any input including <code>null</code>.</p>
*
* <p>#ThreadSafe#</p>
* @see java.lang.String
* @author Apache Software Foundation
* @author <a href="http://jakarta.apache.org/turbine/">Apache Jakarta Turbine</a>
* @author <a href="mailto:[email protected]">Jon S. Stevens</a>
* @author Daniel L. Rall
* @author <a href="mailto:[email protected]">Greg Coladonato</a>
* @author <a href="mailto:[email protected]">Ed Korthof</a>
* @author <a href="mailto:[email protected]">Rand McNeely</a>
* @author <a href="mailto:[email protected]">Fredrik Westermarck</a>
* @author Holger Krauth
* @author <a href="mailto:[email protected]">Alexander Day Chaffee</a>
* @author <a href="mailto:[email protected]">Henning P. Schmiedehausen</a>
* @author Arun Mammen Thomas
* @author Gary Gregory
* @author Phil Steitz
* @author Al Chou
* @author Michael Davey
* @author Reuben Sivan
* @author Chris Hyzer
* @author Scott Johnson
* @since 1.0
* @version $Id$
*/
//@Immutable
public class StringUtils {
// Performance testing notes (JDK 1.4, Jul03, scolebourne)
// Whitespace:
// Character.isWhitespace() is faster than WHITESPACE.indexOf()
// where WHITESPACE is a string of all whitespace characters
//
// Character access:
// String.charAt(n) versus toCharArray(), then array[n]
// String.charAt(n) is about 15% worse for a 10K string
// They are about equal for a length 50 string
// String.charAt(n) is about 4 times better for a length 3 string
// String.charAt(n) is best bet overall
//
// Append:
// String.concat about twice as fast as StringBuffer.append
// (not sure who tested this)
/**
* The empty String <code>""</code>.
* @since 2.0
*/
public static final String EMPTY = "";
/**
* Represents a failed index search.
* @since 2.1
*/
public static final int INDEX_NOT_FOUND = -1;
/**
* <p>The maximum size to which the padding constant(s) can expand.</p>
*/
private static final int PAD_LIMIT = 8192;
/**
* <p><code>StringUtils</code> instances should NOT be constructed in
* standard programming. Instead, the class should be used as
* <code>StringUtils.trim(" foo ");</code>.</p>
*
* <p>This constructor is public to permit tools that require a JavaBean
* instance to operate.</p>
*/
public StringUtils() {
super();
}
// Empty checks
//-----------------------------------------------------------------------
/**
* <p>Checks if a CharSequence is empty ("") or null.</p>
*
* <pre>
* StringUtils.isEmpty(null) = true
* StringUtils.isEmpty("") = true
* StringUtils.isEmpty(" ") = false
* StringUtils.isEmpty("bob") = false
* StringUtils.isEmpty(" bob ") = false
* </pre>
*
* <p>NOTE: This method changed in Lang version 2.0.
* It no longer trims the CharSequence.
* That functionality is available in isBlank().</p>
*
* @param cs the CharSequence to check, may be null
* @return <code>true</code> if the CharSequence is empty or null
* @since 3.0 Changed signature from isEmpty(String) to isEmpty(CharSequence)
*/
public static boolean isEmpty(CharSequence cs) {
return cs == null || cs.length() == 0;
}
/**
* <p>Checks if a CharSequence is not empty ("") and not null.</p>
*
* <pre>
* StringUtils.isNotEmpty(null) = false
* StringUtils.isNotEmpty("") = false
* StringUtils.isNotEmpty(" ") = true
* StringUtils.isNotEmpty("bob") = true
* StringUtils.isNotEmpty(" bob ") = true
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return <code>true</code> if the CharSequence is not empty and not null
* @since 3.0 Changed signature from isNotEmpty(String) to isNotEmpty(CharSequence)
*/
public static boolean isNotEmpty(CharSequence cs) {
return !StringUtils.isEmpty(cs);
}
/**
* <p>Checks if a CharSequence is whitespace, empty ("") or null.</p>
*
* <pre>
* StringUtils.isBlank(null) = true
* StringUtils.isBlank("") = true
* StringUtils.isBlank(" ") = true
* StringUtils.isBlank("bob") = false
* StringUtils.isBlank(" bob ") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return <code>true</code> if the CharSequence is null, empty or whitespace
* @since 2.0
* @since 3.0 Changed signature from isBlank(String) to isBlank(CharSequence)
*/
public static boolean isBlank(CharSequence cs) {
int strLen;
if (cs == null || (strLen = cs.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(cs.charAt(i)) == false)) {
return false;
}
}
return true;
}
/**
* <p>Checks if a CharSequence is not empty (""), not null and not whitespace only.</p>
*
* <pre>
* StringUtils.isNotBlank(null) = false
* StringUtils.isNotBlank("") = false
* StringUtils.isNotBlank(" ") = false
* StringUtils.isNotBlank("bob") = true
* StringUtils.isNotBlank(" bob ") = true
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return <code>true</code> if the CharSequence is
* not empty and not null and not whitespace
* @since 2.0
* @since 3.0 Changed signature from isNotBlank(String) to isNotBlank(CharSequence)
*/
public static boolean isNotBlank(CharSequence cs) {
return !StringUtils.isBlank(cs);
}
// Trim
//-----------------------------------------------------------------------
/**
* <p>Removes control characters (char <= 32) from both
* ends of this String, handling <code>null</code> by returning
* <code>null</code>.</p>
*
* <p>The String is trimmed using {@link String#trim()}.
* Trim removes start and end characters <= 32.
* To strip whitespace use {@link #strip(String)}.</p>
*
* <p>To trim your choice of characters, use the
* {@link #strip(String, String)} methods.</p>
*
* <pre>
* StringUtils.trim(null) = null
* StringUtils.trim("") = ""
* StringUtils.trim(" ") = ""
* StringUtils.trim("abc") = "abc"
* StringUtils.trim(" abc ") = "abc"
* </pre>
*
* @param str the String to be trimmed, may be null
* @return the trimmed string, <code>null</code> if null String input
*/
public static String trim(String str) {
return str == null ? null : str.trim();
}
/**
* <p>Removes control characters (char <= 32) from both
* ends of this String returning <code>null</code> if the String is
* empty ("") after the trim or if it is <code>null</code>.
*
* <p>The String is trimmed using {@link String#trim()}.
* Trim removes start and end characters <= 32.
* To strip whitespace use {@link #stripToNull(String)}.</p>
*
* <pre>
* StringUtils.trimToNull(null) = null
* StringUtils.trimToNull("") = null
* StringUtils.trimToNull(" ") = null
* StringUtils.trimToNull("abc") = "abc"
* StringUtils.trimToNull(" abc ") = "abc"
* </pre>
*
* @param str the String to be trimmed, may be null
* @return the trimmed String,
* <code>null</code> if only chars <= 32, empty or null String input
* @since 2.0
*/
public static String trimToNull(String str) {
String ts = trim(str);
return isEmpty(ts) ? null : ts;
}
/**
* <p>Removes control characters (char <= 32) from both
* ends of this String returning an empty String ("") if the String
* is empty ("") after the trim or if it is <code>null</code>.
*
* <p>The String is trimmed using {@link String#trim()}.
* Trim removes start and end characters <= 32.
* To strip whitespace use {@link #stripToEmpty(String)}.</p>
*
* <pre>
* StringUtils.trimToEmpty(null) = ""
* StringUtils.trimToEmpty("") = ""
* StringUtils.trimToEmpty(" ") = ""
* StringUtils.trimToEmpty("abc") = "abc"
* StringUtils.trimToEmpty(" abc ") = "abc"
* </pre>
*
* @param str the String to be trimmed, may be null
* @return the trimmed String, or an empty String if <code>null</code> input
* @since 2.0
*/
public static String trimToEmpty(String str) {
return str == null ? EMPTY : str.trim();
}
// Stripping
//-----------------------------------------------------------------------
/**
* <p>Strips whitespace from the start and end of a String.</p>
*
* <p>This is similar to {@link #trim(String)} but removes whitespace.
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.strip(null) = null
* StringUtils.strip("") = ""
* StringUtils.strip(" ") = ""
* StringUtils.strip("abc") = "abc"
* StringUtils.strip(" abc") = "abc"
* StringUtils.strip("abc ") = "abc"
* StringUtils.strip(" abc ") = "abc"
* StringUtils.strip(" ab c ") = "ab c"
* </pre>
*
* @param str the String to remove whitespace from, may be null
* @return the stripped String, <code>null</code> if null String input
*/
public static String strip(String str) {
return strip(str, null);
}
/**
* <p>Strips whitespace from the start and end of a String returning
* <code>null</code> if the String is empty ("") after the strip.</p>
*
* <p>This is similar to {@link #trimToNull(String)} but removes whitespace.
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.stripToNull(null) = null
* StringUtils.stripToNull("") = null
* StringUtils.stripToNull(" ") = null
* StringUtils.stripToNull("abc") = "abc"
* StringUtils.stripToNull(" abc") = "abc"
* StringUtils.stripToNull("abc ") = "abc"
* StringUtils.stripToNull(" abc ") = "abc"
* StringUtils.stripToNull(" ab c ") = "ab c"
* </pre>
*
* @param str the String to be stripped, may be null
* @return the stripped String,
* <code>null</code> if whitespace, empty or null String input
* @since 2.0
*/
public static String stripToNull(String str) {
if (str == null) {
return null;
}
str = strip(str, null);
return str.length() == 0 ? null : str;
}
/**
* <p>Strips whitespace from the start and end of a String returning
* an empty String if <code>null</code> input.</p>
*
* <p>This is similar to {@link #trimToEmpty(String)} but removes whitespace.
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.stripToEmpty(null) = ""
* StringUtils.stripToEmpty("") = ""
* StringUtils.stripToEmpty(" ") = ""
* StringUtils.stripToEmpty("abc") = "abc"
* StringUtils.stripToEmpty(" abc") = "abc"
* StringUtils.stripToEmpty("abc ") = "abc"
* StringUtils.stripToEmpty(" abc ") = "abc"
* StringUtils.stripToEmpty(" ab c ") = "ab c"
* </pre>
*
* @param str the String to be stripped, may be null
* @return the trimmed String, or an empty String if <code>null</code> input
* @since 2.0
*/
public static String stripToEmpty(String str) {
return str == null ? EMPTY : strip(str, null);
}
/**
* <p>Strips any of a set of characters from the start and end of a String.
* This is similar to {@link String#trim()} but allows the characters
* to be stripped to be controlled.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.
* An empty string ("") input returns the empty string.</p>
*
* <p>If the stripChars String is <code>null</code>, whitespace is
* stripped as defined by {@link Character#isWhitespace(char)}.
* Alternatively use {@link #strip(String)}.</p>
*
* <pre>
* StringUtils.strip(null, *) = null
* StringUtils.strip("", *) = ""
* StringUtils.strip("abc", null) = "abc"
* StringUtils.strip(" abc", null) = "abc"
* StringUtils.strip("abc ", null) = "abc"
* StringUtils.strip(" abc ", null) = "abc"
* StringUtils.strip(" abcyx", "xyz") = " abc"
* </pre>
*
* @param str the String to remove characters from, may be null
* @param stripChars the characters to remove, null treated as whitespace
* @return the stripped String, <code>null</code> if null String input
*/
public static String strip(String str, String stripChars) {
if (isEmpty(str)) {
return str;
}
str = stripStart(str, stripChars);
return stripEnd(str, stripChars);
}
/**
* <p>Strips any of a set of characters from the start of a String.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.
* An empty string ("") input returns the empty string.</p>
*
* <p>If the stripChars String is <code>null</code>, whitespace is
* stripped as defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.stripStart(null, *) = null
* StringUtils.stripStart("", *) = ""
* StringUtils.stripStart("abc", "") = "abc"
* StringUtils.stripStart("abc", null) = "abc"
* StringUtils.stripStart(" abc", null) = "abc"
* StringUtils.stripStart("abc ", null) = "abc "
* StringUtils.stripStart(" abc ", null) = "abc "
* StringUtils.stripStart("yxabc ", "xyz") = "abc "
* </pre>
*
* @param str the String to remove characters from, may be null
* @param stripChars the characters to remove, null treated as whitespace
* @return the stripped String, <code>null</code> if null String input
*/
public static String stripStart(String str, String stripChars) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return str;
}
int start = 0;
if (stripChars == null) {
while ((start != strLen) && Character.isWhitespace(str.charAt(start))) {
start++;
}
} else if (stripChars.length() == 0) {
return str;
} else {
while ((start != strLen) && (stripChars.indexOf(str.charAt(start)) != INDEX_NOT_FOUND)) {
start++;
}
}
return str.substring(start);
}
/**
* <p>Strips any of a set of characters from the end of a String.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.
* An empty string ("") input returns the empty string.</p>
*
* <p>If the stripChars String is <code>null</code>, whitespace is
* stripped as defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.stripEnd(null, *) = null
* StringUtils.stripEnd("", *) = ""
* StringUtils.stripEnd("abc", "") = "abc"
* StringUtils.stripEnd("abc", null) = "abc"
* StringUtils.stripEnd(" abc", null) = " abc"
* StringUtils.stripEnd("abc ", null) = "abc"
* StringUtils.stripEnd(" abc ", null) = " abc"
* StringUtils.stripEnd(" abcyx", "xyz") = " abc"
* </pre>
*
* @param str the String to remove characters from, may be null
* @param stripChars the characters to remove, null treated as whitespace
* @return the stripped String, <code>null</code> if null String input
*/
public static String stripEnd(String str, String stripChars) {
int end;
if (str == null || (end = str.length()) == 0) {
return str;
}
if (stripChars == null) {
while ((end != 0) && Character.isWhitespace(str.charAt(end - 1))) {
end--;
}
} else if (stripChars.length() == 0) {
return str;
} else {
while ((end != 0) && (stripChars.indexOf(str.charAt(end - 1)) != INDEX_NOT_FOUND)) {
end--;
}
}
return str.substring(0, end);
}
// StripAll
//-----------------------------------------------------------------------
/**
* <p>Strips whitespace from the start and end of every String in an array.
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <p>A new array is returned each time, except for length zero.
* A <code>null</code> array will return <code>null</code>.
* An empty array will return itself.
* A <code>null</code> array entry will be ignored.</p>
*
* <pre>
* StringUtils.stripAll(null) = null
* StringUtils.stripAll([]) = []
* StringUtils.stripAll(["abc", " abc"]) = ["abc", "abc"]
* StringUtils.stripAll(["abc ", null]) = ["abc", null]
* </pre>
*
* @param strs the array to remove whitespace from, may be null
* @return the stripped Strings, <code>null</code> if null array input
*/
public static String[] stripAll(String[] strs) {
return stripAll(strs, null);
}
/**
* <p>Strips any of a set of characters from the start and end of every
* String in an array.</p>
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <p>A new array is returned each time, except for length zero.
* A <code>null</code> array will return <code>null</code>.
* An empty array will return itself.
* A <code>null</code> array entry will be ignored.
* A <code>null</code> stripChars will strip whitespace as defined by
* {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.stripAll(null, *) = null
* StringUtils.stripAll([], *) = []
* StringUtils.stripAll(["abc", " abc"], null) = ["abc", "abc"]
* StringUtils.stripAll(["abc ", null], null) = ["abc", null]
* StringUtils.stripAll(["abc ", null], "yz") = ["abc ", null]
* StringUtils.stripAll(["yabcz", null], "yz") = ["abc", null]
* </pre>
*
* @param strs the array to remove characters from, may be null
* @param stripChars the characters to remove, null treated as whitespace
* @return the stripped Strings, <code>null</code> if null array input
*/
public static String[] stripAll(String[] strs, String stripChars) {
int strsLen;
if (strs == null || (strsLen = strs.length) == 0) {
return strs;
}
String[] newArr = new String[strsLen];
for (int i = 0; i < strsLen; i++) {
newArr[i] = strip(strs[i], stripChars);
}
return newArr;
}
/**
* <p>Removes the accents from a string. </p>
* <p>NOTE: This is a JDK 1.6 method, it will fail on JDK 1.5. </p>
*
* <pre>
* StringUtils.stripAccents(null) = null
* StringUtils.stripAccents("") = ""
* StringUtils.stripAccents("control") = "control"
* StringUtils.stripAccents("&ecute;clair") = "eclair"
* </pre>
*
* @param input String to be stripped
* @return String without accents on the text
*
* @since 3.0
*/
public static String stripAccents(String input) {
if(input == null) {
return null;
}
if(SystemUtils.isJavaVersionAtLeast(1.6f)) {
// String decomposed = Normalizer.normalize(input, Normalizer.Form.NFD);
// START of 1.5 reflection - in 1.6 use the line commented out above
try {
// get java.text.Normalizer.Form class
Class<?> normalizerFormClass = ClassUtils.getClass("java.text.Normalizer$Form", false);
// get Normlizer class
Class<?> normalizerClass = ClassUtils.getClass("java.text.Normalizer", false);
// get static method on Normalizer
java.lang.reflect.Method method = normalizerClass.getMethod("normalize", CharSequence.class, normalizerFormClass );
// get Normalizer.NFD field
java.lang.reflect.Field nfd = normalizerFormClass.getField("NFD");
// invoke method
String decomposed = (String) method.invoke( null, input, nfd.get(null) );
// END of 1.5 reflection
java.util.regex.Pattern accentPattern = java.util.regex.Pattern.compile("\\p{InCombiningDiacriticalMarks}+");
return accentPattern.matcher(decomposed).replaceAll("");
} catch(ClassNotFoundException cnfe) {
throw new RuntimeException("ClassNotFoundException occurred during 1.6 backcompat code", cnfe);
} catch(NoSuchMethodException nsme) {
throw new RuntimeException("NoSuchMethodException occurred during 1.6 backcompat code", nsme);
} catch(NoSuchFieldException nsfe) {
throw new RuntimeException("NoSuchFieldException occurred during 1.6 backcompat code", nsfe);
} catch(IllegalAccessException iae) {
throw new RuntimeException("IllegalAccessException occurred during 1.6 backcompat code", iae);
} catch(IllegalArgumentException iae) {
throw new RuntimeException("IllegalArgumentException occurred during 1.6 backcompat code", iae);
} catch(java.lang.reflect.InvocationTargetException ite) {
throw new RuntimeException("InvocationTargetException occurred during 1.6 backcompat code", ite);
} catch(SecurityException se) {
throw new RuntimeException("SecurityException occurred during 1.6 backcompat code", se);
}
} else {
throw new UnsupportedOperationException("The stripAccents(String) method is not supported until Java 1.6");
}
}
// Equals
//-----------------------------------------------------------------------
/**
* <p>Compares two CharSequences, returning <code>true</code> if they are equal.</p>
*
* <p><code>null</code>s are handled without exceptions. Two <code>null</code>
* references are considered to be equal. The comparison is case sensitive.</p>
*
* <pre>
* StringUtils.equals(null, null) = true
* StringUtils.equals(null, "abc") = false
* StringUtils.equals("abc", null) = false
* StringUtils.equals("abc", "abc") = true
* StringUtils.equals("abc", "ABC") = false
* </pre>
*
* @see java.lang.String#equals(Object)
* @param cs1 the first CharSequence, may be null
* @param cs2 the second CharSequence, may be null
* @return <code>true</code> if the CharSequences are equal, case sensitive, or
* both <code>null</code>
* @since 3.0 Changed signature from equals(String, String) to equals(CharSequence, CharSequence)
*/
public static boolean equals(CharSequence cs1, CharSequence cs2) {
return cs1 == null ? cs2 == null : cs1.equals(cs2);
}
/**
* <p>Compares two Strings, returning <code>true</code> if they are equal ignoring
* the case.</p>
*
* <p><code>null</code>s are handled without exceptions. Two <code>null</code>
* references are considered equal. Comparison is case insensitive.</p>
*
* <pre>
* StringUtils.equalsIgnoreCase(null, null) = true
* StringUtils.equalsIgnoreCase(null, "abc") = false
* StringUtils.equalsIgnoreCase("abc", null) = false
* StringUtils.equalsIgnoreCase("abc", "abc") = true
* StringUtils.equalsIgnoreCase("abc", "ABC") = true
* </pre>
*
* @see java.lang.String#equalsIgnoreCase(String)
* @param str1 the first String, may be null
* @param str2 the second String, may be null
* @return <code>true</code> if the Strings are equal, case insensitive, or
* both <code>null</code>
*/
public static boolean equalsIgnoreCase(String str1, String str2) {
return str1 == null ? str2 == null : str1.equalsIgnoreCase(str2);
}
// IndexOf
//-----------------------------------------------------------------------
/**
* <p>Finds the first index within a String, handling <code>null</code>.
* This method uses {@link String#indexOf(int)}.</p>
*
* <p>A <code>null</code> or empty ("") String will return <code>INDEX_NOT_FOUND (-1)</code>.</p>
*
* <pre>
* StringUtils.indexOf(null, *) = -1
* StringUtils.indexOf("", *) = -1
* StringUtils.indexOf("aabaabaa", 'a') = 0
* StringUtils.indexOf("aabaabaa", 'b') = 2
* </pre>
*
* @param str the String to check, may be null
* @param searchChar the character to find
* @return the first index of the search character,
* -1 if no match or <code>null</code> string input
* @since 2.0
*/
public static int indexOf(String str, int searchChar) {
if (isEmpty(str)) {
return INDEX_NOT_FOUND;
}
return str.indexOf(searchChar);
}
/**
* <p>Finds the first index within a String from a start position,
* handling <code>null</code>.
* This method uses {@link String#indexOf(int, int)}.</p>
*
* <p>A <code>null</code> or empty ("") String will return <code>(INDEX_NOT_FOUND) -1</code>.
* A negative start position is treated as zero.
* A start position greater than the string length returns <code>-1</code>.</p>
*
* <pre>
* StringUtils.indexOf(null, *, *) = -1
* StringUtils.indexOf("", *, *) = -1
* StringUtils.indexOf("aabaabaa", 'b', 0) = 2
* StringUtils.indexOf("aabaabaa", 'b', 3) = 5
* StringUtils.indexOf("aabaabaa", 'b', 9) = -1
* StringUtils.indexOf("aabaabaa", 'b', -1) = 2
* </pre>
*
* @param str the String to check, may be null
* @param searchChar the character to find
* @param startPos the start position, negative treated as zero
* @return the first index of the search character,
* -1 if no match or <code>null</code> string input
* @since 2.0
*/
public static int indexOf(String str, int searchChar, int startPos) {
if (isEmpty(str)) {
return INDEX_NOT_FOUND;
}
return str.indexOf(searchChar, startPos);
}
/**
* <p>Finds the first index within a String, handling <code>null</code>.
* This method uses {@link String#indexOf(String)}.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.</p>
*
* <pre>
* StringUtils.indexOf(null, *) = -1
* StringUtils.indexOf(*, null) = -1
* StringUtils.indexOf("", "") = 0
* StringUtils.indexOf("", *) = -1 (except when * = "")
* StringUtils.indexOf("aabaabaa", "a") = 0
* StringUtils.indexOf("aabaabaa", "b") = 2
* StringUtils.indexOf("aabaabaa", "ab") = 1
* StringUtils.indexOf("aabaabaa", "") = 0
* </pre>
*
* @param str the String to check, may be null
* @param searchStr the String to find, may be null
* @return the first index of the search String,
* -1 if no match or <code>null</code> string input
* @since 2.0
*/
public static int indexOf(String str, String searchStr) {
if (str == null || searchStr == null) {
return INDEX_NOT_FOUND;
}
return str.indexOf(searchStr);
}
/**
* <p>Finds the first index within a String, handling <code>null</code>.
* This method uses {@link String#indexOf(String, int)}.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.
* A negative start position is treated as zero.
* An empty ("") search String always matches.
* A start position greater than the string length only matches
* an empty search String.</p>
*
* <pre>
* StringUtils.indexOf(null, *, *) = -1
* StringUtils.indexOf(*, null, *) = -1
* StringUtils.indexOf("", "", 0) = 0
* StringUtils.indexOf("", *, 0) = -1 (except when * = "")
* StringUtils.indexOf("aabaabaa", "a", 0) = 0
* StringUtils.indexOf("aabaabaa", "b", 0) = 2
* StringUtils.indexOf("aabaabaa", "ab", 0) = 1
* StringUtils.indexOf("aabaabaa", "b", 3) = 5
* StringUtils.indexOf("aabaabaa", "b", 9) = -1
* StringUtils.indexOf("aabaabaa", "b", -1) = 2
* StringUtils.indexOf("aabaabaa", "", 2) = 2
* StringUtils.indexOf("abc", "", 9) = 3
* </pre>
*
* @param str the String to check, may be null
* @param searchStr the String to find, may be null
* @param startPos the start position, negative treated as zero
* @return the first index of the search String,
* -1 if no match or <code>null</code> string input
* @since 2.0
*/
public static int indexOf(String str, String searchStr, int startPos) {
if (str == null || searchStr == null) {
return INDEX_NOT_FOUND;
}
return str.indexOf(searchStr, startPos);
}
/**
* <p>Finds the n-th index within a String, handling <code>null</code>.
* This method uses {@link String#indexOf(String)}.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.</p>
*
* <pre>
* StringUtils.ordinalIndexOf(null, *, *) = -1
* StringUtils.ordinalIndexOf(*, null, *) = -1
* StringUtils.ordinalIndexOf("", "", *) = 0
* StringUtils.ordinalIndexOf("aabaabaa", "a", 1) = 0
* StringUtils.ordinalIndexOf("aabaabaa", "a", 2) = 1
* StringUtils.ordinalIndexOf("aabaabaa", "b", 1) = 2
* StringUtils.ordinalIndexOf("aabaabaa", "b", 2) = 5
* StringUtils.ordinalIndexOf("aabaabaa", "ab", 1) = 1
* StringUtils.ordinalIndexOf("aabaabaa", "ab", 2) = 4
* StringUtils.ordinalIndexOf("aabaabaa", "", 1) = 0
* StringUtils.ordinalIndexOf("aabaabaa", "", 2) = 0
* </pre>
*
* <p>Note that 'head(String str, int n)' may be implemented as: </p>
*
* <pre>
* str.substring(0, lastOrdinalIndexOf(str, "\n", n))
* </pre>
*
* @param str the String to check, may be null
* @param searchStr the String to find, may be null
* @param ordinal the n-th <code>searchStr</code> to find
* @return the n-th index of the search String,
* <code>-1</code> (<code>INDEX_NOT_FOUND</code>) if no match or <code>null</code> string input
* @since 2.1
*/
public static int ordinalIndexOf(String str, String searchStr, int ordinal) {
return ordinalIndexOf(str, searchStr, ordinal, false);
}
/**
* <p>Finds the n-th index within a String, handling <code>null</code>.
* This method uses {@link String#indexOf(String)}.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.</p>
*
* @param str the String to check, may be null
* @param searchStr the String to find, may be null
* @param ordinal the n-th <code>searchStr</code> to find
* @param lastIndex true if lastOrdinalIndexOf() otherwise false if ordinalIndexOf()
* @return the n-th index of the search String,
* <code>-1</code> (<code>INDEX_NOT_FOUND</code>) if no match or <code>null</code> string input
*/
// Shared code between ordinalIndexOf(String,String,int) and lastOrdinalIndexOf(String,String,int)
private static int ordinalIndexOf(String str, String searchStr, int ordinal, boolean lastIndex) {
if (str == null || searchStr == null || ordinal <= 0) {
return INDEX_NOT_FOUND;
}
if (searchStr.length() == 0) {
return lastIndex ? str.length() : 0;
}
int found = 0;
int index = lastIndex ? str.length() : INDEX_NOT_FOUND;
do {
if(lastIndex) {
index = str.lastIndexOf(searchStr, index - 1);
} else {
index = str.indexOf(searchStr, index + 1);
}
if (index < 0) {
return index;
}
found++;
} while (found < ordinal);
return index;
}
/**
* <p>Case in-sensitive find of the first index within a String.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.
* A negative start position is treated as zero.
* An empty ("") search String always matches.
* A start position greater than the string length only matches
* an empty search String.</p>
*
* <pre>
* StringUtils.indexOfIgnoreCase(null, *) = -1
* StringUtils.indexOfIgnoreCase(*, null) = -1
* StringUtils.indexOfIgnoreCase("", "") = 0
* StringUtils.indexOfIgnoreCase("aabaabaa", "a") = 0
* StringUtils.indexOfIgnoreCase("aabaabaa", "b") = 2
* StringUtils.indexOfIgnoreCase("aabaabaa", "ab") = 1
* </pre>
*
* @param str the String to check, may be null
* @param searchStr the String to find, may be null
* @return the first index of the search String,
* -1 if no match or <code>null</code> string input
* @since 2.5
*/
public static int indexOfIgnoreCase(String str, String searchStr) {
return indexOfIgnoreCase(str, searchStr, 0);
}
/**
* <p>Case in-sensitive find of the first index within a String
* from the specified position.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.
* A negative start position is treated as zero.
* An empty ("") search String always matches.
* A start position greater than the string length only matches
* an empty search String.</p>
*
* <pre>
* StringUtils.indexOfIgnoreCase(null, *, *) = -1
* StringUtils.indexOfIgnoreCase(*, null, *) = -1
* StringUtils.indexOfIgnoreCase("", "", 0) = 0
* StringUtils.indexOfIgnoreCase("aabaabaa", "A", 0) = 0
* StringUtils.indexOfIgnoreCase("aabaabaa", "B", 0) = 2
* StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 0) = 1
* StringUtils.indexOfIgnoreCase("aabaabaa", "B", 3) = 5
* StringUtils.indexOfIgnoreCase("aabaabaa", "B", 9) = -1
* StringUtils.indexOfIgnoreCase("aabaabaa", "B", -1) = 2
* StringUtils.indexOfIgnoreCase("aabaabaa", "", 2) = 2
* StringUtils.indexOfIgnoreCase("abc", "", 9) = 3
* </pre>
*
* @param str the String to check, may be null
* @param searchStr the String to find, may be null
* @param startPos the start position, negative treated as zero
* @return the first index of the search String,
* -1 if no match or <code>null</code> string input
* @since 2.5
*/
public static int indexOfIgnoreCase(String str, String searchStr, int startPos) {
if (str == null || searchStr == null) {
return INDEX_NOT_FOUND;
}
if (startPos < 0) {
startPos = 0;
}
int endLimit = (str.length() - searchStr.length()) + 1;
if (startPos > endLimit) {
return INDEX_NOT_FOUND;
}
if (searchStr.length() == 0) {
return startPos;
}
for (int i = startPos; i < endLimit; i++) {
if (str.regionMatches(true, i, searchStr, 0, searchStr.length())) {
return i;
}
}
return INDEX_NOT_FOUND;
}
// LastIndexOf
//-----------------------------------------------------------------------
/**
* <p>Finds the last index within a String, handling <code>null</code>.
* This method uses {@link String#lastIndexOf(int)}.</p>
*
* <p>A <code>null</code> or empty ("") String will return <code>-1</code>.</p>
*
* <pre>
* StringUtils.lastIndexOf(null, *) = -1
* StringUtils.lastIndexOf("", *) = -1
* StringUtils.lastIndexOf("aabaabaa", 'a') = 7
* StringUtils.lastIndexOf("aabaabaa", 'b') = 5
* </pre>
*
* @param str the String to check, may be null
* @param searchChar the character to find
* @return the last index of the search character,
* -1 if no match or <code>null</code> string input
* @since 2.0
*/
public static int lastIndexOf(String str, int searchChar) {
if (isEmpty(str)) {
return INDEX_NOT_FOUND;
}
return str.lastIndexOf(searchChar);
}
/**
* <p>Finds the last index within a String from a start position,
* handling <code>null</code>.
* This method uses {@link String#lastIndexOf(int, int)}.</p>
*
* <p>A <code>null</code> or empty ("") String will return <code>-1</code>.
* A negative start position returns <code>-1</code>.
* A start position greater than the string length searches the whole string.</p>
*
* <pre>
* StringUtils.lastIndexOf(null, *, *) = -1
* StringUtils.lastIndexOf("", *, *) = -1
* StringUtils.lastIndexOf("aabaabaa", 'b', 8) = 5
* StringUtils.lastIndexOf("aabaabaa", 'b', 4) = 2
* StringUtils.lastIndexOf("aabaabaa", 'b', 0) = -1
* StringUtils.lastIndexOf("aabaabaa", 'b', 9) = 5
* StringUtils.lastIndexOf("aabaabaa", 'b', -1) = -1
* StringUtils.lastIndexOf("aabaabaa", 'a', 0) = 0
* </pre>
*
* @param str the String to check, may be null
* @param searchChar the character to find
* @param startPos the start position
* @return the last index of the search character,
* -1 if no match or <code>null</code> string input
* @since 2.0
*/
public static int lastIndexOf(String str, int searchChar, int startPos) {
if (isEmpty(str)) {
return INDEX_NOT_FOUND;
}
return str.lastIndexOf(searchChar, startPos);
}
/**
* <p>Finds the last index within a String, handling <code>null</code>.
* This method uses {@link String#lastIndexOf(String)}.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.</p>
*
* <pre>
* StringUtils.lastIndexOf(null, *) = -1
* StringUtils.lastIndexOf(*, null) = -1
* StringUtils.lastIndexOf("", "") = 0
* StringUtils.lastIndexOf("aabaabaa", "a") = 7
* StringUtils.lastIndexOf("aabaabaa", "b") = 4
* StringUtils.lastIndexOf("aabaabaa", "ab") = 5
* StringUtils.lastIndexOf("aabaabaa", "") = 8
* </pre>
*
* @param str the String to check, may be null
* @param searchStr the String to find, may be null
* @return the last index of the search String,
* -1 if no match or <code>null</code> string input
* @since 2.0
*/
public static int lastIndexOf(String str, String searchStr) {
if (str == null || searchStr == null) {
return INDEX_NOT_FOUND;
}
return str.lastIndexOf(searchStr);
}
/**
* <p>Finds the n-th last index within a String, handling <code>null</code>.
* This method uses {@link String#lastIndexOf(String)}.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.</p>
*
* <pre>
* StringUtils.lastOrdinalIndexOf(null, *, *) = -1
* StringUtils.lastOrdinalIndexOf(*, null, *) = -1
* StringUtils.lastOrdinalIndexOf("", "", *) = 0
* StringUtils.lastOrdinalIndexOf("aabaabaa", "a", 1) = 7
* StringUtils.lastOrdinalIndexOf("aabaabaa", "a", 2) = 6
* StringUtils.lastOrdinalIndexOf("aabaabaa", "b", 1) = 5
* StringUtils.lastOrdinalIndexOf("aabaabaa", "b", 2) = 2
* StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 1) = 4
* StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 2) = 1
* StringUtils.lastOrdinalIndexOf("aabaabaa", "", 1) = 8
* StringUtils.lastOrdinalIndexOf("aabaabaa", "", 2) = 8
* </pre>
*
* <p>Note that 'tail(String str, int n)' may be implemented as: </p>
*
* <pre>
* str.substring(lastOrdinalIndexOf(str, "\n", n) + 1)
* </pre>
*
* @param str the String to check, may be null
* @param searchStr the String to find, may be null
* @param ordinal the n-th last <code>searchStr</code> to find
* @return the n-th last index of the search String,
* <code>-1</code> (<code>INDEX_NOT_FOUND</code>) if no match or <code>null</code> string input
* @since 2.5
*/
public static int lastOrdinalIndexOf(String str, String searchStr, int ordinal) {
return ordinalIndexOf(str, searchStr, ordinal, true);
}
/**
* <p>Finds the first index within a String, handling <code>null</code>.
* This method uses {@link String#lastIndexOf(String, int)}.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.
* A negative start position returns <code>-1</code>.
* An empty ("") search String always matches unless the start position is negative.
* A start position greater than the string length searches the whole string.</p>
*
* <pre>
* StringUtils.lastIndexOf(null, *, *) = -1
* StringUtils.lastIndexOf(*, null, *) = -1
* StringUtils.lastIndexOf("aabaabaa", "a", 8) = 7
* StringUtils.lastIndexOf("aabaabaa", "b", 8) = 5
* StringUtils.lastIndexOf("aabaabaa", "ab", 8) = 4
* StringUtils.lastIndexOf("aabaabaa", "b", 9) = 5
* StringUtils.lastIndexOf("aabaabaa", "b", -1) = -1
* StringUtils.lastIndexOf("aabaabaa", "a", 0) = 0
* StringUtils.lastIndexOf("aabaabaa", "b", 0) = -1
* </pre>
*
* @param str the String to check, may be null
* @param searchStr the String to find, may be null
* @param startPos the start position, negative treated as zero
* @return the first index of the search String,
* -1 if no match or <code>null</code> string input
* @since 2.0
*/
public static int lastIndexOf(String str, String searchStr, int startPos) {
if (str == null || searchStr == null) {
return INDEX_NOT_FOUND;
}
return str.lastIndexOf(searchStr, startPos);
}
/**
* <p>Case in-sensitive find of the last index within a String.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.
* A negative start position returns <code>-1</code>.
* An empty ("") search String always matches unless the start position is negative.
* A start position greater than the string length searches the whole string.</p>
*
* <pre>
* StringUtils.lastIndexOfIgnoreCase(null, *) = -1
* StringUtils.lastIndexOfIgnoreCase(*, null) = -1
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A") = 7
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B") = 5
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "AB") = 4
* </pre>
*
* @param str the String to check, may be null
* @param searchStr the String to find, may be null
* @return the first index of the search String,
* -1 if no match or <code>null</code> string input
* @since 2.5
*/
public static int lastIndexOfIgnoreCase(String str, String searchStr) {
if (str == null || searchStr == null) {
return INDEX_NOT_FOUND;
}
return lastIndexOfIgnoreCase(str, searchStr, str.length());
}
/**
* <p>Case in-sensitive find of the last index within a String
* from the specified position.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.
* A negative start position returns <code>-1</code>.
* An empty ("") search String always matches unless the start position is negative.
* A start position greater than the string length searches the whole string.</p>
*
* <pre>
* StringUtils.lastIndexOfIgnoreCase(null, *, *) = -1
* StringUtils.lastIndexOfIgnoreCase(*, null, *) = -1
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A", 8) = 7
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 8) = 5
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "AB", 8) = 4
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 9) = 5
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", -1) = -1
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A", 0) = 0
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 0) = -1
* </pre>
*
* @param str the String to check, may be null
* @param searchStr the String to find, may be null
* @param startPos the start position
* @return the first index of the search String,
* -1 if no match or <code>null</code> string input
* @since 2.5
*/
public static int lastIndexOfIgnoreCase(String str, String searchStr, int startPos) {
if (str == null || searchStr == null) {
return INDEX_NOT_FOUND;
}
if (startPos > (str.length() - searchStr.length())) {
startPos = str.length() - searchStr.length();
}
if (startPos < 0) {
return INDEX_NOT_FOUND;
}
if (searchStr.length() == 0) {
return startPos;
}
for (int i = startPos; i >= 0; i--) {
if (str.regionMatches(true, i, searchStr, 0, searchStr.length())) {
return i;
}
}
return INDEX_NOT_FOUND;
}
// Contains
//-----------------------------------------------------------------------
/**
* <p>Checks if String contains a search character, handling <code>null</code>.
* This method uses {@link String#indexOf(int)}.</p>
*
* <p>A <code>null</code> or empty ("") String will return <code>false</code>.</p>
*
* <pre>
* StringUtils.contains(null, *) = false
* StringUtils.contains("", *) = false
* StringUtils.contains("abc", 'a') = true
* StringUtils.contains("abc", 'z') = false
* </pre>
*
* @param str the String to check, may be null
* @param searchChar the character to find
* @return true if the String contains the search character,
* false if not or <code>null</code> string input
* @since 2.0
*/
public static boolean contains(String str, int searchChar) {
if (isEmpty(str)) {
return false;
}
return str.indexOf(searchChar) >= 0;
}
/**
* <p>Checks if String contains a search String, handling <code>null</code>.
* This method uses {@link String#indexOf(String)}.</p>
*
* <p>A <code>null</code> String will return <code>false</code>.</p>
*
* <pre>
* StringUtils.contains(null, *) = false
* StringUtils.contains(*, null) = false
* StringUtils.contains("", "") = true
* StringUtils.contains("abc", "") = true
* StringUtils.contains("abc", "a") = true
* StringUtils.contains("abc", "z") = false
* </pre>
*
* @param str the String to check, may be null
* @param searchStr the String to find, may be null
* @return true if the String contains the search String,
* false if not or <code>null</code> string input
* @since 2.0
*/
public static boolean contains(String str, String searchStr) {
if (str == null || searchStr == null) {
return false;
}
return str.indexOf(searchStr) >= 0;
}
/**
* <p>Checks if String contains a search String irrespective of case,
* handling <code>null</code>. Case-insensitivity is defined as by
* {@link String#equalsIgnoreCase(String)}.
*
* <p>A <code>null</code> String will return <code>false</code>.</p>
*
* <pre>
* StringUtils.contains(null, *) = false
* StringUtils.contains(*, null) = false
* StringUtils.contains("", "") = true
* StringUtils.contains("abc", "") = true
* StringUtils.contains("abc", "a") = true
* StringUtils.contains("abc", "z") = false
* StringUtils.contains("abc", "A") = true
* StringUtils.contains("abc", "Z") = false
* </pre>
*
* @param str the String to check, may be null
* @param searchStr the String to find, may be null
* @return true if the String contains the search String irrespective of
* case or false if not or <code>null</code> string input
*/
public static boolean containsIgnoreCase(String str, String searchStr) {
if (str == null || searchStr == null) {
return false;
}
int len = searchStr.length();
int max = str.length() - len;
for (int i = 0; i <= max; i++) {
if (str.regionMatches(true, i, searchStr, 0, len)) {
return true;
}
}
return false;
}
// IndexOfAny chars
//-----------------------------------------------------------------------
/**
* <p>Search a CharSequence to find the first index of any
* character in the given set of characters.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.
* A <code>null</code> or zero length search array will return <code>-1</code>.</p>
*
* <pre>
* StringUtils.indexOfAny(null, *) = -1
* StringUtils.indexOfAny("", *) = -1
* StringUtils.indexOfAny(*, null) = -1
* StringUtils.indexOfAny(*, []) = -1
* StringUtils.indexOfAny("zzabyycdxx",['z','a']) = 0
* StringUtils.indexOfAny("zzabyycdxx",['b','y']) = 3
* StringUtils.indexOfAny("aba", ['z']) = -1
* </pre>
*
* @param cs the CharSequence to check, may be null
* @param searchChars the chars to search for, may be null
* @return the index of any of the chars, -1 if no match or null input
* @since 2.0
* @since 3.0 Changed signature from indexOfAny(String, char[]) to indexOfAny(CharSequence, char[])
*/
public static int indexOfAny(CharSequence cs, char[] searchChars) {
if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) {
return INDEX_NOT_FOUND;
}
int csLen = cs.length();
int csLast = csLen - 1;
int searchLen = searchChars.length;
int searchLast = searchLen - 1;
for (int i = 0; i < csLen; i++) {
char ch = cs.charAt(i);
for (int j = 0; j < searchLen; j++) {
if (searchChars[j] == ch) {
if (i < csLast && j < searchLast && Character.isHighSurrogate(ch)) {
// ch is a supplementary character
if (searchChars[j + 1] == cs.charAt(i + 1)) {
return i;
}
} else {
return i;
}
}
}
}
return INDEX_NOT_FOUND;
}
/**
* <p>Search a CharSequence to find the first index of any
* character in the given set of characters.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.
* A <code>null</code> search string will return <code>-1</code>.</p>
*
* <pre>
* StringUtils.indexOfAny(null, *) = -1
* StringUtils.indexOfAny("", *) = -1
* StringUtils.indexOfAny(*, null) = -1
* StringUtils.indexOfAny(*, "") = -1
* StringUtils.indexOfAny("zzabyycdxx", "za") = 0
* StringUtils.indexOfAny("zzabyycdxx", "by") = 3
* StringUtils.indexOfAny("aba","z") = -1
* </pre>
*
* @param cs the CharSequence to check, may be null
* @param searchChars the chars to search for, may be null
* @return the index of any of the chars, -1 if no match or null input
* @since 2.0
* @since 3.0 Changed signature from indexOfAny(String, String) to indexOfAny(CharSequence, String)
*/
public static int indexOfAny(CharSequence cs, String searchChars) {
if (isEmpty(cs) || isEmpty(searchChars)) {
return INDEX_NOT_FOUND;
}
return indexOfAny(cs, searchChars.toCharArray());
}
// ContainsAny
//-----------------------------------------------------------------------
/**
* <p>Checks if the CharSequence contains any character in the given
* set of characters.</p>
*
* <p>A <code>null</code> CharSequence will return <code>false</code>.
* A <code>null</code> or zero length search array will return <code>false</code>.</p>
*
* <pre>
* StringUtils.containsAny(null, *) = false
* StringUtils.containsAny("", *) = false
* StringUtils.containsAny(*, null) = false
* StringUtils.containsAny(*, []) = false
* StringUtils.containsAny("zzabyycdxx",['z','a']) = true
* StringUtils.containsAny("zzabyycdxx",['b','y']) = true
* StringUtils.containsAny("aba", ['z']) = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @param searchChars the chars to search for, may be null
* @return the <code>true</code> if any of the chars are found,
* <code>false</code> if no match or null input
* @since 2.4
*/
public static boolean containsAny(String cs, char[] searchChars) {
if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) {
return false;
}
int csLength = cs.length();
int searchLength = searchChars.length;
int csLast = csLength - 1;
int searchLast = searchLength - 1;
for (int i = 0; i < csLength; i++) {
char ch = cs.charAt(i);
for (int j = 0; j < searchLength; j++) {
if (searchChars[j] == ch) {
if (Character.isHighSurrogate(ch)) {
if (j == searchLast) {
// missing low surrogate, fine, like String.indexOf(String)
return true;
}
if (i < csLast && searchChars[j + 1] == cs.charAt(i + 1)) {
return true;
}
} else {
// ch is in the Basic Multilingual Plane
return true;
}
}
}
}
return false;
}
/**
* <p>
* Checks if the CharSequence contains any character in the given set of characters.
* </p>
*
* <p>
* A <code>null</code> CharSequence will return <code>false</code>. A <code>null</code> search CharSequence will return
* <code>false</code>.
* </p>
*
* <pre>
* StringUtils.containsAny(null, *) = false
* StringUtils.containsAny("", *) = false
* StringUtils.containsAny(*, null) = false
* StringUtils.containsAny(*, "") = false
* StringUtils.containsAny("zzabyycdxx", "za") = true
* StringUtils.containsAny("zzabyycdxx", "by") = true
* StringUtils.containsAny("aba","z") = false
* </pre>
*
* @param cs
* the CharSequence to check, may be null
* @param searchChars
* the chars to search for, may be null
* @return the <code>true</code> if any of the chars are found, <code>false</code> if no match or null input
* @since 2.4
*/
public static boolean containsAny(String cs, String searchChars) {
if (searchChars == null) {
return false;
}
return containsAny(cs, searchChars.toCharArray());
}
// IndexOfAnyBut chars
//-----------------------------------------------------------------------
/**
* <p>Searches a CharSequence to find the first index of any
* character not in the given set of characters.</p>
*
* <p>A <code>null</code> CharSequence will return <code>-1</code>.
* A <code>null</code> or zero length search array will return <code>-1</code>.</p>
*
* <pre>
* StringUtils.indexOfAnyBut(null, *) = -1
* StringUtils.indexOfAnyBut("", *) = -1
* StringUtils.indexOfAnyBut(*, null) = -1
* StringUtils.indexOfAnyBut(*, []) = -1
* StringUtils.indexOfAnyBut("zzabyycdxx",'za') = 3
* StringUtils.indexOfAnyBut("zzabyycdxx", '') = 0
* StringUtils.indexOfAnyBut("aba", 'ab') = -1
* </pre>
*
* @param cs the CharSequence to check, may be null
* @param searchChars the chars to search for, may be null
* @return the index of any of the chars, -1 if no match or null input
* @since 2.0
* @since 3.0 Changed signature from indexOfAnyBut(String, char[]) to indexOfAnyBut(CharSequence, char[])
*/
public static int indexOfAnyBut(CharSequence cs, char[] searchChars) {
if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) {
return INDEX_NOT_FOUND;
}
int csLen = cs.length();
int csLast = csLen - 1;
int searchLen = searchChars.length;
int searchLast = searchLen - 1;
outer:
for (int i = 0; i < csLen; i++) {
char ch = cs.charAt(i);
for (int j = 0; j < searchLen; j++) {
if (searchChars[j] == ch) {
if (i < csLast && j < searchLast && Character.isHighSurrogate(ch)) {
if (searchChars[j + 1] == cs.charAt(i + 1)) {
continue outer;
}
} else {
continue outer;
}
}
}
return i;
}
return INDEX_NOT_FOUND;
}
/**
* <p>Search a String to find the first index of any
* character not in the given set of characters.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.
* A <code>null</code> search string will return <code>-1</code>.</p>
*
* <pre>
* StringUtils.indexOfAnyBut(null, *) = -1
* StringUtils.indexOfAnyBut("", *) = -1
* StringUtils.indexOfAnyBut(*, null) = -1
* StringUtils.indexOfAnyBut(*, "") = -1
* StringUtils.indexOfAnyBut("zzabyycdxx", "za") = 3
* StringUtils.indexOfAnyBut("zzabyycdxx", "") = 0
* StringUtils.indexOfAnyBut("aba","ab") = -1
* </pre>
*
* @param str the String to check, may be null
* @param searchChars the chars to search for, may be null
* @return the index of any of the chars, -1 if no match or null input
* @since 2.0
*/
public static int indexOfAnyBut(String str, String searchChars) {
if (isEmpty(str) || isEmpty(searchChars)) {
return INDEX_NOT_FOUND;
}
int strLen = str.length();
for (int i = 0; i < strLen; i++) {
char ch = str.charAt(i);
boolean chFound = searchChars.indexOf(ch) >= 0;
if (i + 1 < strLen && Character.isHighSurrogate(ch)) {
char ch2 = str.charAt(i + 1);
if (chFound && searchChars.indexOf(ch2) < 0) {
return i;
}
} else {
if (!chFound) {
return i;
}
}
}
return INDEX_NOT_FOUND;
}
// ContainsOnly
//-----------------------------------------------------------------------
/**
* <p>Checks if the CharSequence contains only certain characters.</p>
*
* <p>A <code>null</code> CharSequence will return <code>false</code>.
* A <code>null</code> valid character array will return <code>false</code>.
* An empty CharSequence (length()=0) always returns <code>true</code>.</p>
*
* <pre>
* StringUtils.containsOnly(null, *) = false
* StringUtils.containsOnly(*, null) = false
* StringUtils.containsOnly("", *) = true
* StringUtils.containsOnly("ab", '') = false
* StringUtils.containsOnly("abab", 'abc') = true
* StringUtils.containsOnly("ab1", 'abc') = false
* StringUtils.containsOnly("abz", 'abc') = false
* </pre>
*
* @param cs the String to check, may be null
* @param valid an array of valid chars, may be null
* @return true if it only contains valid chars and is non-null
* @since 3.0 Changed signature from containsOnly(String, char[]) to containsOnly(CharSequence, char[])
*/
public static boolean containsOnly(CharSequence cs, char[] valid) {
// All these pre-checks are to maintain API with an older version
if (valid == null || cs == null) {
return false;
}
if (cs.length() == 0) {
return true;
}
if (valid.length == 0) {
return false;
}
return indexOfAnyBut(cs, valid) == INDEX_NOT_FOUND;
}
/**
* <p>Checks if the CharSequence contains only certain characters.</p>
*
* <p>A <code>null</code> CharSequence will return <code>false</code>.
* A <code>null</code> valid character String will return <code>false</code>.
* An empty String (length()=0) always returns <code>true</code>.</p>
*
* <pre>
* StringUtils.containsOnly(null, *) = false
* StringUtils.containsOnly(*, null) = false
* StringUtils.containsOnly("", *) = true
* StringUtils.containsOnly("ab", "") = false
* StringUtils.containsOnly("abab", "abc") = true
* StringUtils.containsOnly("ab1", "abc") = false
* StringUtils.containsOnly("abz", "abc") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @param validChars a String of valid chars, may be null
* @return true if it only contains valid chars and is non-null
* @since 2.0
* @since 3.0 Changed signature from containsOnly(String, String) to containsOnly(CharSequence, String)
*/
public static boolean containsOnly(CharSequence cs, String validChars) {
if (cs == null || validChars == null) {
return false;
}
return containsOnly(cs, validChars.toCharArray());
}
// ContainsNone
//-----------------------------------------------------------------------
/**
* <p>Checks that the CharSequence does not contain certain characters.</p>
*
* <p>A <code>null</code> CharSequence will return <code>true</code>.
* A <code>null</code> invalid character array will return <code>true</code>.
* An empty CharSequence (length()=0) always returns true.</p>
*
* <pre>
* StringUtils.containsNone(null, *) = true
* StringUtils.containsNone(*, null) = true
* StringUtils.containsNone("", *) = true
* StringUtils.containsNone("ab", '') = true
* StringUtils.containsNone("abab", 'xyz') = true
* StringUtils.containsNone("ab1", 'xyz') = true
* StringUtils.containsNone("abz", 'xyz') = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @param searchChars an array of invalid chars, may be null
* @return true if it contains none of the invalid chars, or is null
* @since 2.0
* @since 3.0 Changed signature from containsNone(String, char[]) to containsNone(CharSequence, char[])
*/
public static boolean containsNone(CharSequence cs, char[] searchChars) {
if (cs == null || searchChars == null) {
return true;
}
int csLen = cs.length();
int csLast = csLen - 1;
int searchLen = searchChars.length;
int searchLast = searchLen - 1;
for (int i = 0; i < csLen; i++) {
char ch = cs.charAt(i);
for (int j = 0; j < searchLen; j++) {
if (searchChars[j] == ch) {
if (Character.isHighSurrogate(ch)) {
if (j == searchLast) {
// missing low surrogate, fine, like String.indexOf(String)
return false;
}
if (i < csLast && searchChars[j + 1] == cs.charAt(i + 1)) {
return false;
}
} else {
// ch is in the Basic Multilingual Plane
return false;
}
}
}
}
return true;
}
/**
* <p>Checks that the CharSequence does not contain certain characters.</p>
*
* <p>A <code>null</code> CharSequence will return <code>true</code>.
* A <code>null</code> invalid character array will return <code>true</code>.
* An empty String ("") always returns true.</p>
*
* <pre>
* StringUtils.containsNone(null, *) = true
* StringUtils.containsNone(*, null) = true
* StringUtils.containsNone("", *) = true
* StringUtils.containsNone("ab", "") = true
* StringUtils.containsNone("abab", "xyz") = true
* StringUtils.containsNone("ab1", "xyz") = true
* StringUtils.containsNone("abz", "xyz") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @param invalidChars a String of invalid chars, may be null
* @return true if it contains none of the invalid chars, or is null
* @since 2.0
* @since 3.0 Changed signature from containsNone(String, String) to containsNone(CharSequence, String)
*/
public static boolean containsNone(CharSequence cs, String invalidChars) {
if (cs == null || invalidChars == null) {
return true;
}
return containsNone(cs, invalidChars.toCharArray());
}
// IndexOfAny strings
//-----------------------------------------------------------------------
/**
* <p>Find the first index of any of a set of potential substrings.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.
* A <code>null</code> or zero length search array will return <code>-1</code>.
* A <code>null</code> search array entry will be ignored, but a search
* array containing "" will return <code>0</code> if <code>str</code> is not
* null. This method uses {@link String#indexOf(String)}.</p>
*
* <pre>
* StringUtils.indexOfAny(null, *) = -1
* StringUtils.indexOfAny(*, null) = -1
* StringUtils.indexOfAny(*, []) = -1
* StringUtils.indexOfAny("zzabyycdxx", ["ab","cd"]) = 2
* StringUtils.indexOfAny("zzabyycdxx", ["cd","ab"]) = 2
* StringUtils.indexOfAny("zzabyycdxx", ["mn","op"]) = -1
* StringUtils.indexOfAny("zzabyycdxx", ["zab","aby"]) = 1
* StringUtils.indexOfAny("zzabyycdxx", [""]) = 0
* StringUtils.indexOfAny("", [""]) = 0
* StringUtils.indexOfAny("", ["a"]) = -1
* </pre>
*
* @param str the String to check, may be null
* @param searchStrs the Strings to search for, may be null
* @return the first index of any of the searchStrs in str, -1 if no match
*/
public static int indexOfAny(String str, String[] searchStrs) {
if (str == null || searchStrs == null) {
return INDEX_NOT_FOUND;
}
int sz = searchStrs.length;
// String's can't have a MAX_VALUEth index.
int ret = Integer.MAX_VALUE;
int tmp = 0;
for (int i = 0; i < sz; i++) {
String search = searchStrs[i];
if (search == null) {
continue;
}
tmp = str.indexOf(search);
if (tmp == INDEX_NOT_FOUND) {
continue;
}
if (tmp < ret) {
ret = tmp;
}
}
return (ret == Integer.MAX_VALUE) ? INDEX_NOT_FOUND : ret;
}
/**
* <p>Find the latest index of any of a set of potential substrings.</p>
*
* <p>A <code>null</code> String will return <code>-1</code>.
* A <code>null</code> search array will return <code>-1</code>.
* A <code>null</code> or zero length search array entry will be ignored,
* but a search array containing "" will return the length of <code>str</code>
* if <code>str</code> is not null. This method uses {@link String#indexOf(String)}</p>
*
* <pre>
* StringUtils.lastIndexOfAny(null, *) = -1
* StringUtils.lastIndexOfAny(*, null) = -1
* StringUtils.lastIndexOfAny(*, []) = -1
* StringUtils.lastIndexOfAny(*, [null]) = -1
* StringUtils.lastIndexOfAny("zzabyycdxx", ["ab","cd"]) = 6
* StringUtils.lastIndexOfAny("zzabyycdxx", ["cd","ab"]) = 6
* StringUtils.lastIndexOfAny("zzabyycdxx", ["mn","op"]) = -1
* StringUtils.lastIndexOfAny("zzabyycdxx", ["mn","op"]) = -1
* StringUtils.lastIndexOfAny("zzabyycdxx", ["mn",""]) = 10
* </pre>
*
* @param str the String to check, may be null
* @param searchStrs the Strings to search for, may be null
* @return the last index of any of the Strings, -1 if no match
*/
public static int lastIndexOfAny(String str, String[] searchStrs) {
if (str == null || searchStrs == null) {
return INDEX_NOT_FOUND;
}
int sz = searchStrs.length;
int ret = INDEX_NOT_FOUND;
int tmp = 0;
for (int i = 0; i < sz; i++) {
String search = searchStrs[i];
if (search == null) {
continue;
}
tmp = str.lastIndexOf(search);
if (tmp > ret) {
ret = tmp;
}
}
return ret;
}
// Substring
//-----------------------------------------------------------------------
/**
* <p>Gets a substring from the specified String avoiding exceptions.</p>
*
* <p>A negative start position can be used to start <code>n</code>
* characters from the end of the String.</p>
*
* <p>A <code>null</code> String will return <code>null</code>.
* An empty ("") String will return "".</p>
*
* <pre>
* StringUtils.substring(null, *) = null
* StringUtils.substring("", *) = ""
* StringUtils.substring("abc", 0) = "abc"
* StringUtils.substring("abc", 2) = "c"
* StringUtils.substring("abc", 4) = ""
* StringUtils.substring("abc", -2) = "bc"
* StringUtils.substring("abc", -4) = "abc"
* </pre>
*
* @param str the String to get the substring from, may be null
* @param start the position to start from, negative means
* count back from the end of the String by this many characters
* @return substring from start position, <code>null</code> if null String input
*/
public static String substring(String str, int start) {
if (str == null) {
return null;
}
// handle negatives, which means last n characters
if (start < 0) {
start = str.length() + start; // remember start is negative
}
if (start < 0) {
start = 0;
}
if (start > str.length()) {
return EMPTY;
}
return str.substring(start);
}
/**
* <p>Gets a substring from the specified String avoiding exceptions.</p>
*
* <p>A negative start position can be used to start/end <code>n</code>
* characters from the end of the String.</p>
*
* <p>The returned substring starts with the character in the <code>start</code>
* position and ends before the <code>end</code> position. All position counting is
* zero-based -- i.e., to start at the beginning of the string use
* <code>start = 0</code>. Negative start and end positions can be used to
* specify offsets relative to the end of the String.</p>
*
* <p>If <code>start</code> is not strictly to the left of <code>end</code>, ""
* is returned.</p>
*
* <pre>
* StringUtils.substring(null, *, *) = null
* StringUtils.substring("", * , *) = "";
* StringUtils.substring("abc", 0, 2) = "ab"
* StringUtils.substring("abc", 2, 0) = ""
* StringUtils.substring("abc", 2, 4) = "c"
* StringUtils.substring("abc", 4, 6) = ""
* StringUtils.substring("abc", 2, 2) = ""
* StringUtils.substring("abc", -2, -1) = "b"
* StringUtils.substring("abc", -4, 2) = "ab"
* </pre>
*
* @param str the String to get the substring from, may be null
* @param start the position to start from, negative means
* count back from the end of the String by this many characters
* @param end the position to end at (exclusive), negative means
* count back from the end of the String by this many characters
* @return substring from start position to end positon,
* <code>null</code> if null String input
*/
public static String substring(String str, int start, int end) {
if (str == null) {
return null;
}
// handle negatives
if (end < 0) {
end = str.length() + end; // remember end is negative
}
if (start < 0) {
start = str.length() + start; // remember start is negative
}
// check length next
if (end > str.length()) {
end = str.length();
}
// if start is greater than end, return ""
if (start > end) {
return EMPTY;
}
if (start < 0) {
start = 0;
}
if (end < 0) {
end = 0;
}
return str.substring(start, end);
}
// Left/Right/Mid
//-----------------------------------------------------------------------
/**
* <p>Gets the leftmost <code>len</code> characters of a String.</p>
*
* <p>If <code>len</code> characters are not available, or the
* String is <code>null</code>, the String will be returned without
* an exception. An exception is thrown if len is negative.</p>
*
* <pre>
* StringUtils.left(null, *) = null
* StringUtils.left(*, -ve) = ""
* StringUtils.left("", *) = ""
* StringUtils.left("abc", 0) = ""
* StringUtils.left("abc", 2) = "ab"
* StringUtils.left("abc", 4) = "abc"
* </pre>
*
* @param str the String to get the leftmost characters from, may be null
* @param len the length of the required String, must be zero or positive
* @return the leftmost characters, <code>null</code> if null String input
*/
public static String left(String str, int len) {
if (str == null) {
return null;
}
if (len < 0) {
return EMPTY;
}
if (str.length() <= len) {
return str;
}
return str.substring(0, len);
}
/**
* <p>Gets the rightmost <code>len</code> characters of a String.</p>
*
* <p>If <code>len</code> characters are not available, or the String
* is <code>null</code>, the String will be returned without an
* an exception. An exception is thrown if len is negative.</p>
*
* <pre>
* StringUtils.right(null, *) = null
* StringUtils.right(*, -ve) = ""
* StringUtils.right("", *) = ""
* StringUtils.right("abc", 0) = ""
* StringUtils.right("abc", 2) = "bc"
* StringUtils.right("abc", 4) = "abc"
* </pre>
*
* @param str the String to get the rightmost characters from, may be null
* @param len the length of the required String, must be zero or positive
* @return the rightmost characters, <code>null</code> if null String input
*/
public static String right(String str, int len) {
if (str == null) {
return null;
}
if (len < 0) {
return EMPTY;
}
if (str.length() <= len) {
return str;
}
return str.substring(str.length() - len);
}
/**
* <p>Gets <code>len</code> characters from the middle of a String.</p>
*
* <p>If <code>len</code> characters are not available, the remainder
* of the String will be returned without an exception. If the
* String is <code>null</code>, <code>null</code> will be returned.
* An exception is thrown if len is negative.</p>
*
* <pre>
* StringUtils.mid(null, *, *) = null
* StringUtils.mid(*, *, -ve) = ""
* StringUtils.mid("", 0, *) = ""
* StringUtils.mid("abc", 0, 2) = "ab"
* StringUtils.mid("abc", 0, 4) = "abc"
* StringUtils.mid("abc", 2, 4) = "c"
* StringUtils.mid("abc", 4, 2) = ""
* StringUtils.mid("abc", -2, 2) = "ab"
* </pre>
*
* @param str the String to get the characters from, may be null
* @param pos the position to start from, negative treated as zero
* @param len the length of the required String, must be zero or positive
* @return the middle characters, <code>null</code> if null String input
*/
public static String mid(String str, int pos, int len) {
if (str == null) {
return null;
}
if (len < 0 || pos > str.length()) {
return EMPTY;
}
if (pos < 0) {
pos = 0;
}
if (str.length() <= (pos + len)) {
return str.substring(pos);
}
return str.substring(pos, pos + len);
}
// SubStringAfter/SubStringBefore
//-----------------------------------------------------------------------
/**
* <p>Gets the substring before the first occurrence of a separator.
* The separator is not returned.</p>
*
* <p>A <code>null</code> string input will return <code>null</code>.
* An empty ("") string input will return the empty string.
* A <code>null</code> separator will return the input string.</p>
*
* <p>If nothing is found, the string input is returned.</p>
*
* <pre>
* StringUtils.substringBefore(null, *) = null
* StringUtils.substringBefore("", *) = ""
* StringUtils.substringBefore("abc", "a") = ""
* StringUtils.substringBefore("abcba", "b") = "a"
* StringUtils.substringBefore("abc", "c") = "ab"
* StringUtils.substringBefore("abc", "d") = "abc"
* StringUtils.substringBefore("abc", "") = ""
* StringUtils.substringBefore("abc", null) = "abc"
* </pre>
*
* @param str the String to get a substring from, may be null
* @param separator the String to search for, may be null
* @return the substring before the first occurrence of the separator,
* <code>null</code> if null String input
* @since 2.0
*/
public static String substringBefore(String str, String separator) {
if (isEmpty(str) || separator == null) {
return str;
}
if (separator.length() == 0) {
return EMPTY;
}
int pos = str.indexOf(separator);
if (pos == INDEX_NOT_FOUND) {
return str;
}
return str.substring(0, pos);
}
/**
* <p>Gets the substring after the first occurrence of a separator.
* The separator is not returned.</p>
*
* <p>A <code>null</code> string input will return <code>null</code>.
* An empty ("") string input will return the empty string.
* A <code>null</code> separator will return the empty string if the
* input string is not <code>null</code>.</p>
*
* <p>If nothing is found, the empty string is returned.</p>
*
* <pre>
* StringUtils.substringAfter(null, *) = null
* StringUtils.substringAfter("", *) = ""
* StringUtils.substringAfter(*, null) = ""
* StringUtils.substringAfter("abc", "a") = "bc"
* StringUtils.substringAfter("abcba", "b") = "cba"
* StringUtils.substringAfter("abc", "c") = ""
* StringUtils.substringAfter("abc", "d") = ""
* StringUtils.substringAfter("abc", "") = "abc"
* </pre>
*
* @param str the String to get a substring from, may be null
* @param separator the String to search for, may be null
* @return the substring after the first occurrence of the separator,
* <code>null</code> if null String input
* @since 2.0
*/
public static String substringAfter(String str, String separator) {
if (isEmpty(str)) {
return str;
}
if (separator == null) {
return EMPTY;
}
int pos = str.indexOf(separator);
if (pos == INDEX_NOT_FOUND) {
return EMPTY;
}
return str.substring(pos + separator.length());
}
/**
* <p>Gets the substring before the last occurrence of a separator.
* The separator is not returned.</p>
*
* <p>A <code>null</code> string input will return <code>null</code>.
* An empty ("") string input will return the empty string.
* An empty or <code>null</code> separator will return the input string.</p>
*
* <p>If nothing is found, the string input is returned.</p>
*
* <pre>
* StringUtils.substringBeforeLast(null, *) = null
* StringUtils.substringBeforeLast("", *) = ""
* StringUtils.substringBeforeLast("abcba", "b") = "abc"
* StringUtils.substringBeforeLast("abc", "c") = "ab"
* StringUtils.substringBeforeLast("a", "a") = ""
* StringUtils.substringBeforeLast("a", "z") = "a"
* StringUtils.substringBeforeLast("a", null) = "a"
* StringUtils.substringBeforeLast("a", "") = "a"
* </pre>
*
* @param str the String to get a substring from, may be null
* @param separator the String to search for, may be null
* @return the substring before the last occurrence of the separator,
* <code>null</code> if null String input
* @since 2.0
*/
public static String substringBeforeLast(String str, String separator) {
if (isEmpty(str) || isEmpty(separator)) {
return str;
}
int pos = str.lastIndexOf(separator);
if (pos == INDEX_NOT_FOUND) {
return str;
}
return str.substring(0, pos);
}
/**
* <p>Gets the substring after the last occurrence of a separator.
* The separator is not returned.</p>
*
* <p>A <code>null</code> string input will return <code>null</code>.
* An empty ("") string input will return the empty string.
* An empty or <code>null</code> separator will return the empty string if
* the input string is not <code>null</code>.</p>
*
* <p>If nothing is found, the empty string is returned.</p>
*
* <pre>
* StringUtils.substringAfterLast(null, *) = null
* StringUtils.substringAfterLast("", *) = ""
* StringUtils.substringAfterLast(*, "") = ""
* StringUtils.substringAfterLast(*, null) = ""
* StringUtils.substringAfterLast("abc", "a") = "bc"
* StringUtils.substringAfterLast("abcba", "b") = "a"
* StringUtils.substringAfterLast("abc", "c") = ""
* StringUtils.substringAfterLast("a", "a") = ""
* StringUtils.substringAfterLast("a", "z") = ""
* </pre>
*
* @param str the String to get a substring from, may be null
* @param separator the String to search for, may be null
* @return the substring after the last occurrence of the separator,
* <code>null</code> if null String input
* @since 2.0
*/
public static String substringAfterLast(String str, String separator) {
if (isEmpty(str)) {
return str;
}
if (isEmpty(separator)) {
return EMPTY;
}
int pos = str.lastIndexOf(separator);
if (pos == INDEX_NOT_FOUND || pos == (str.length() - separator.length())) {
return EMPTY;
}
return str.substring(pos + separator.length());
}
// Substring between
//-----------------------------------------------------------------------
/**
* <p>Gets the String that is nested in between two instances of the
* same String.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.
* A <code>null</code> tag returns <code>null</code>.</p>
*
* <pre>
* StringUtils.substringBetween(null, *) = null
* StringUtils.substringBetween("", "") = ""
* StringUtils.substringBetween("", "tag") = null
* StringUtils.substringBetween("tagabctag", null) = null
* StringUtils.substringBetween("tagabctag", "") = ""
* StringUtils.substringBetween("tagabctag", "tag") = "abc"
* </pre>
*
* @param str the String containing the substring, may be null
* @param tag the String before and after the substring, may be null
* @return the substring, <code>null</code> if no match
* @since 2.0
*/
public static String substringBetween(String str, String tag) {
return substringBetween(str, tag, tag);
}
/**
* <p>Gets the String that is nested in between two Strings.
* Only the first match is returned.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.
* A <code>null</code> open/close returns <code>null</code> (no match).
* An empty ("") open and close returns an empty string.</p>
*
* <pre>
* StringUtils.substringBetween("wx[b]yz", "[", "]") = "b"
* StringUtils.substringBetween(null, *, *) = null
* StringUtils.substringBetween(*, null, *) = null
* StringUtils.substringBetween(*, *, null) = null
* StringUtils.substringBetween("", "", "") = ""
* StringUtils.substringBetween("", "", "]") = null
* StringUtils.substringBetween("", "[", "]") = null
* StringUtils.substringBetween("yabcz", "", "") = ""
* StringUtils.substringBetween("yabcz", "y", "z") = "abc"
* StringUtils.substringBetween("yabczyabcz", "y", "z") = "abc"
* </pre>
*
* @param str the String containing the substring, may be null
* @param open the String before the substring, may be null
* @param close the String after the substring, may be null
* @return the substring, <code>null</code> if no match
* @since 2.0
*/
public static String substringBetween(String str, String open, String close) {
if (str == null || open == null || close == null) {
return null;
}
int start = str.indexOf(open);
if (start != INDEX_NOT_FOUND) {
int end = str.indexOf(close, start + open.length());
if (end != INDEX_NOT_FOUND) {
return str.substring(start + open.length(), end);
}
}
return null;
}
/**
* <p>Searches a String for substrings delimited by a start and end tag,
* returning all matching substrings in an array.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.
* A <code>null</code> open/close returns <code>null</code> (no match).
* An empty ("") open/close returns <code>null</code> (no match).</p>
*
* <pre>
* StringUtils.substringsBetween("[a][b][c]", "[", "]") = ["a","b","c"]
* StringUtils.substringsBetween(null, *, *) = null
* StringUtils.substringsBetween(*, null, *) = null
* StringUtils.substringsBetween(*, *, null) = null
* StringUtils.substringsBetween("", "[", "]") = []
* </pre>
*
* @param str the String containing the substrings, null returns null, empty returns empty
* @param open the String identifying the start of the substring, empty returns null
* @param close the String identifying the end of the substring, empty returns null
* @return a String Array of substrings, or <code>null</code> if no match
* @since 2.3
*/
public static String[] substringsBetween(String str, String open, String close) {
if (str == null || isEmpty(open) || isEmpty(close)) {
return null;
}
int strLen = str.length();
if (strLen == 0) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
int closeLen = close.length();
int openLen = open.length();
List<String> list = new ArrayList<String>();
int pos = 0;
while (pos < (strLen - closeLen)) {
int start = str.indexOf(open, pos);
if (start < 0) {
break;
}
start += openLen;
int end = str.indexOf(close, start);
if (end < 0) {
break;
}
list.add(str.substring(start, end));
pos = end + closeLen;
}
if (list.isEmpty()) {
return null;
}
return list.toArray(new String [list.size()]);
}
// Nested extraction
//-----------------------------------------------------------------------
// Splitting
//-----------------------------------------------------------------------
/**
* <p>Splits the provided text into an array, using whitespace as the
* separator.
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as one separator.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.split(null) = null
* StringUtils.split("") = []
* StringUtils.split("abc def") = ["abc", "def"]
* StringUtils.split("abc def") = ["abc", "def"]
* StringUtils.split(" abc ") = ["abc"]
* </pre>
*
* @param str the String to parse, may be null
* @return an array of parsed Strings, <code>null</code> if null String input
*/
public static String[] split(String str) {
return split(str, null, -1);
}
/**
* <p>Splits the provided text into an array, separator specified.
* This is an alternative to using StringTokenizer.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as one separator.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.split(null, *) = null
* StringUtils.split("", *) = []
* StringUtils.split("a.b.c", '.') = ["a", "b", "c"]
* StringUtils.split("a..b.c", '.') = ["a", "b", "c"]
* StringUtils.split("a:b:c", '.') = ["a:b:c"]
* StringUtils.split("a b c", ' ') = ["a", "b", "c"]
* </pre>
*
* @param str the String to parse, may be null
* @param separatorChar the character used as the delimiter
* @return an array of parsed Strings, <code>null</code> if null String input
* @since 2.0
*/
public static String[] split(String str, char separatorChar) {
return splitWorker(str, separatorChar, false);
}
/**
* <p>Splits the provided text into an array, separators specified.
* This is an alternative to using StringTokenizer.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as one separator.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.
* A <code>null</code> separatorChars splits on whitespace.</p>
*
* <pre>
* StringUtils.split(null, *) = null
* StringUtils.split("", *) = []
* StringUtils.split("abc def", null) = ["abc", "def"]
* StringUtils.split("abc def", " ") = ["abc", "def"]
* StringUtils.split("abc def", " ") = ["abc", "def"]
* StringUtils.split("ab:cd:ef", ":") = ["ab", "cd", "ef"]
* </pre>
*
* @param str the String to parse, may be null
* @param separatorChars the characters used as the delimiters,
* <code>null</code> splits on whitespace
* @return an array of parsed Strings, <code>null</code> if null String input
*/
public static String[] split(String str, String separatorChars) {
return splitWorker(str, separatorChars, -1, false);
}
/**
* <p>Splits the provided text into an array with a maximum length,
* separators specified.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as one separator.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.
* A <code>null</code> separatorChars splits on whitespace.</p>
*
* <p>If more than <code>max</code> delimited substrings are found, the last
* returned string includes all characters after the first <code>max - 1</code>
* returned strings (including separator characters).</p>
*
* <pre>
* StringUtils.split(null, *, *) = null
* StringUtils.split("", *, *) = []
* StringUtils.split("ab de fg", null, 0) = ["ab", "cd", "ef"]
* StringUtils.split("ab de fg", null, 0) = ["ab", "cd", "ef"]
* StringUtils.split("ab:cd:ef", ":", 0) = ["ab", "cd", "ef"]
* StringUtils.split("ab:cd:ef", ":", 2) = ["ab", "cd:ef"]
* </pre>
*
* @param str the String to parse, may be null
* @param separatorChars the characters used as the delimiters,
* <code>null</code> splits on whitespace
* @param max the maximum number of elements to include in the
* array. A zero or negative value implies no limit
* @return an array of parsed Strings, <code>null</code> if null String input
*/
public static String[] split(String str, String separatorChars, int max) {
return splitWorker(str, separatorChars, max, false);
}
/**
* <p>Splits the provided text into an array, separator string specified.</p>
*
* <p>The separator(s) will not be included in the returned String array.
* Adjacent separators are treated as one separator.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.
* A <code>null</code> separator splits on whitespace.</p>
*
* <pre>
* StringUtils.splitByWholeSeparator(null, *) = null
* StringUtils.splitByWholeSeparator("", *) = []
* StringUtils.splitByWholeSeparator("ab de fg", null) = ["ab", "de", "fg"]
* StringUtils.splitByWholeSeparator("ab de fg", null) = ["ab", "de", "fg"]
* StringUtils.splitByWholeSeparator("ab:cd:ef", ":") = ["ab", "cd", "ef"]
* StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-") = ["ab", "cd", "ef"]
* </pre>
*
* @param str the String to parse, may be null
* @param separator String containing the String to be used as a delimiter,
* <code>null</code> splits on whitespace
* @return an array of parsed Strings, <code>null</code> if null String was input
*/
public static String[] splitByWholeSeparator(String str, String separator) {
return splitByWholeSeparatorWorker( str, separator, -1, false ) ;
}
/**
* <p>Splits the provided text into an array, separator string specified.
* Returns a maximum of <code>max</code> substrings.</p>
*
* <p>The separator(s) will not be included in the returned String array.
* Adjacent separators are treated as one separator.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.
* A <code>null</code> separator splits on whitespace.</p>
*
* <pre>
* StringUtils.splitByWholeSeparator(null, *, *) = null
* StringUtils.splitByWholeSeparator("", *, *) = []
* StringUtils.splitByWholeSeparator("ab de fg", null, 0) = ["ab", "de", "fg"]
* StringUtils.splitByWholeSeparator("ab de fg", null, 0) = ["ab", "de", "fg"]
* StringUtils.splitByWholeSeparator("ab:cd:ef", ":", 2) = ["ab", "cd:ef"]
* StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-", 5) = ["ab", "cd", "ef"]
* StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-", 2) = ["ab", "cd-!-ef"]
* </pre>
*
* @param str the String to parse, may be null
* @param separator String containing the String to be used as a delimiter,
* <code>null</code> splits on whitespace
* @param max the maximum number of elements to include in the returned
* array. A zero or negative value implies no limit.
* @return an array of parsed Strings, <code>null</code> if null String was input
*/
public static String[] splitByWholeSeparator( String str, String separator, int max ) {
return splitByWholeSeparatorWorker(str, separator, max, false);
}
/**
* <p>Splits the provided text into an array, separator string specified. </p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as separators for empty tokens.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.
* A <code>null</code> separator splits on whitespace.</p>
*
* <pre>
* StringUtils.splitByWholeSeparatorPreserveAllTokens(null, *) = null
* StringUtils.splitByWholeSeparatorPreserveAllTokens("", *) = []
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null) = ["ab", "de", "fg"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null) = ["ab", "", "", "de", "fg"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab:cd:ef", ":") = ["ab", "cd", "ef"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab-!-cd-!-ef", "-!-") = ["ab", "cd", "ef"]
* </pre>
*
* @param str the String to parse, may be null
* @param separator String containing the String to be used as a delimiter,
* <code>null</code> splits on whitespace
* @return an array of parsed Strings, <code>null</code> if null String was input
* @since 2.4
*/
public static String[] splitByWholeSeparatorPreserveAllTokens(String str, String separator) {
return splitByWholeSeparatorWorker(str, separator, -1, true);
}
/**
* <p>Splits the provided text into an array, separator string specified.
* Returns a maximum of <code>max</code> substrings.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as separators for empty tokens.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.
* A <code>null</code> separator splits on whitespace.</p>
*
* <pre>
* StringUtils.splitByWholeSeparatorPreserveAllTokens(null, *, *) = null
* StringUtils.splitByWholeSeparatorPreserveAllTokens("", *, *) = []
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null, 0) = ["ab", "de", "fg"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null, 0) = ["ab", "", "", "de", "fg"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab:cd:ef", ":", 2) = ["ab", "cd:ef"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab-!-cd-!-ef", "-!-", 5) = ["ab", "cd", "ef"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab-!-cd-!-ef", "-!-", 2) = ["ab", "cd-!-ef"]
* </pre>
*
* @param str the String to parse, may be null
* @param separator String containing the String to be used as a delimiter,
* <code>null</code> splits on whitespace
* @param max the maximum number of elements to include in the returned
* array. A zero or negative value implies no limit.
* @return an array of parsed Strings, <code>null</code> if null String was input
* @since 2.4
*/
public static String[] splitByWholeSeparatorPreserveAllTokens(String str, String separator, int max) {
return splitByWholeSeparatorWorker(str, separator, max, true);
}
/**
* Performs the logic for the <code>splitByWholeSeparatorPreserveAllTokens</code> methods.
*
* @param str the String to parse, may be <code>null</code>
* @param separator String containing the String to be used as a delimiter,
* <code>null</code> splits on whitespace
* @param max the maximum number of elements to include in the returned
* array. A zero or negative value implies no limit.
* @param preserveAllTokens if <code>true</code>, adjacent separators are
* treated as empty token separators; if <code>false</code>, adjacent
* separators are treated as one separator.
* @return an array of parsed Strings, <code>null</code> if null String input
* @since 2.4
*/
private static String[] splitByWholeSeparatorWorker(String str, String separator, int max,
boolean preserveAllTokens)
{
if (str == null) {
return null;
}
int len = str.length();
if (len == 0) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
if ((separator == null) || (EMPTY.equals(separator))) {
// Split on whitespace.
return splitWorker(str, null, max, preserveAllTokens);
}
int separatorLength = separator.length();
ArrayList<String> substrings = new ArrayList<String>();
int numberOfSubstrings = 0;
int beg = 0;
int end = 0;
while (end < len) {
end = str.indexOf(separator, beg);
if (end > -1) {
if (end > beg) {
numberOfSubstrings += 1;
if (numberOfSubstrings == max) {
end = len;
substrings.add(str.substring(beg));
} else {
// The following is OK, because String.substring( beg, end ) excludes
// the character at the position 'end'.
substrings.add(str.substring(beg, end));
// Set the starting point for the next search.
// The following is equivalent to beg = end + (separatorLength - 1) + 1,
// which is the right calculation:
beg = end + separatorLength;
}
} else {
// We found a consecutive occurrence of the separator, so skip it.
if (preserveAllTokens) {
numberOfSubstrings += 1;
if (numberOfSubstrings == max) {
end = len;
substrings.add(str.substring(beg));
} else {
substrings.add(EMPTY);
}
}
beg = end + separatorLength;
}
} else {
// String.substring( beg ) goes from 'beg' to the end of the String.
substrings.add(str.substring(beg));
end = len;
}
}
return substrings.toArray(new String[substrings.size()]);
}
// -----------------------------------------------------------------------
/**
* <p>Splits the provided text into an array, using whitespace as the
* separator, preserving all tokens, including empty tokens created by
* adjacent separators. This is an alternative to using StringTokenizer.
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as separators for empty tokens.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.splitPreserveAllTokens(null) = null
* StringUtils.splitPreserveAllTokens("") = []
* StringUtils.splitPreserveAllTokens("abc def") = ["abc", "def"]
* StringUtils.splitPreserveAllTokens("abc def") = ["abc", "", "def"]
* StringUtils.splitPreserveAllTokens(" abc ") = ["", "abc", ""]
* </pre>
*
* @param str the String to parse, may be <code>null</code>
* @return an array of parsed Strings, <code>null</code> if null String input
* @since 2.1
*/
public static String[] splitPreserveAllTokens(String str) {
return splitWorker(str, null, -1, true);
}
/**
* <p>Splits the provided text into an array, separator specified,
* preserving all tokens, including empty tokens created by adjacent
* separators. This is an alternative to using StringTokenizer.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as separators for empty tokens.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.splitPreserveAllTokens(null, *) = null
* StringUtils.splitPreserveAllTokens("", *) = []
* StringUtils.splitPreserveAllTokens("a.b.c", '.') = ["a", "b", "c"]
* StringUtils.splitPreserveAllTokens("a..b.c", '.') = ["a", "", "b", "c"]
* StringUtils.splitPreserveAllTokens("a:b:c", '.') = ["a:b:c"]
* StringUtils.splitPreserveAllTokens("a\tb\nc", null) = ["a", "b", "c"]
* StringUtils.splitPreserveAllTokens("a b c", ' ') = ["a", "b", "c"]
* StringUtils.splitPreserveAllTokens("a b c ", ' ') = ["a", "b", "c", ""]
* StringUtils.splitPreserveAllTokens("a b c ", ' ') = ["a", "b", "c", "", ""]
* StringUtils.splitPreserveAllTokens(" a b c", ' ') = ["", a", "b", "c"]
* StringUtils.splitPreserveAllTokens(" a b c", ' ') = ["", "", a", "b", "c"]
* StringUtils.splitPreserveAllTokens(" a b c ", ' ') = ["", a", "b", "c", ""]
* </pre>
*
* @param str the String to parse, may be <code>null</code>
* @param separatorChar the character used as the delimiter,
* <code>null</code> splits on whitespace
* @return an array of parsed Strings, <code>null</code> if null String input
* @since 2.1
*/
public static String[] splitPreserveAllTokens(String str, char separatorChar) {
return splitWorker(str, separatorChar, true);
}
/**
* Performs the logic for the <code>split</code> and
* <code>splitPreserveAllTokens</code> methods that do not return a
* maximum array length.
*
* @param str the String to parse, may be <code>null</code>
* @param separatorChar the separate character
* @param preserveAllTokens if <code>true</code>, adjacent separators are
* treated as empty token separators; if <code>false</code>, adjacent
* separators are treated as one separator.
* @return an array of parsed Strings, <code>null</code> if null String input
*/
private static String[] splitWorker(String str, char separatorChar, boolean preserveAllTokens) {
// Performance tuned for 2.0 (JDK1.4)
if (str == null) {
return null;
}
int len = str.length();
if (len == 0) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
List<String> list = new ArrayList<String>();
int i = 0, start = 0;
boolean match = false;
boolean lastMatch = false;
while (i < len) {
if (str.charAt(i) == separatorChar) {
if (match || preserveAllTokens) {
list.add(str.substring(start, i));
match = false;
lastMatch = true;
}
start = ++i;
continue;
}
lastMatch = false;
match = true;
i++;
}
if (match || (preserveAllTokens && lastMatch)) {
list.add(str.substring(start, i));
}
return list.toArray(new String[list.size()]);
}
/**
* <p>Splits the provided text into an array, separators specified,
* preserving all tokens, including empty tokens created by adjacent
* separators. This is an alternative to using StringTokenizer.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as separators for empty tokens.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.
* A <code>null</code> separatorChars splits on whitespace.</p>
*
* <pre>
* StringUtils.splitPreserveAllTokens(null, *) = null
* StringUtils.splitPreserveAllTokens("", *) = []
* StringUtils.splitPreserveAllTokens("abc def", null) = ["abc", "def"]
* StringUtils.splitPreserveAllTokens("abc def", " ") = ["abc", "def"]
* StringUtils.splitPreserveAllTokens("abc def", " ") = ["abc", "", def"]
* StringUtils.splitPreserveAllTokens("ab:cd:ef", ":") = ["ab", "cd", "ef"]
* StringUtils.splitPreserveAllTokens("ab:cd:ef:", ":") = ["ab", "cd", "ef", ""]
* StringUtils.splitPreserveAllTokens("ab:cd:ef::", ":") = ["ab", "cd", "ef", "", ""]
* StringUtils.splitPreserveAllTokens("ab::cd:ef", ":") = ["ab", "", cd", "ef"]
* StringUtils.splitPreserveAllTokens(":cd:ef", ":") = ["", cd", "ef"]
* StringUtils.splitPreserveAllTokens("::cd:ef", ":") = ["", "", cd", "ef"]
* StringUtils.splitPreserveAllTokens(":cd:ef:", ":") = ["", cd", "ef", ""]
* </pre>
*
* @param str the String to parse, may be <code>null</code>
* @param separatorChars the characters used as the delimiters,
* <code>null</code> splits on whitespace
* @return an array of parsed Strings, <code>null</code> if null String input
* @since 2.1
*/
public static String[] splitPreserveAllTokens(String str, String separatorChars) {
return splitWorker(str, separatorChars, -1, true);
}
/**
* <p>Splits the provided text into an array with a maximum length,
* separators specified, preserving all tokens, including empty tokens
* created by adjacent separators.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as separators for empty tokens.
* Adjacent separators are treated as one separator.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.
* A <code>null</code> separatorChars splits on whitespace.</p>
*
* <p>If more than <code>max</code> delimited substrings are found, the last
* returned string includes all characters after the first <code>max - 1</code>
* returned strings (including separator characters).</p>
*
* <pre>
* StringUtils.splitPreserveAllTokens(null, *, *) = null
* StringUtils.splitPreserveAllTokens("", *, *) = []
* StringUtils.splitPreserveAllTokens("ab de fg", null, 0) = ["ab", "cd", "ef"]
* StringUtils.splitPreserveAllTokens("ab de fg", null, 0) = ["ab", "cd", "ef"]
* StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 0) = ["ab", "cd", "ef"]
* StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 2) = ["ab", "cd:ef"]
* StringUtils.splitPreserveAllTokens("ab de fg", null, 2) = ["ab", " de fg"]
* StringUtils.splitPreserveAllTokens("ab de fg", null, 3) = ["ab", "", " de fg"]
* StringUtils.splitPreserveAllTokens("ab de fg", null, 4) = ["ab", "", "", "de fg"]
* </pre>
*
* @param str the String to parse, may be <code>null</code>
* @param separatorChars the characters used as the delimiters,
* <code>null</code> splits on whitespace
* @param max the maximum number of elements to include in the
* array. A zero or negative value implies no limit
* @return an array of parsed Strings, <code>null</code> if null String input
* @since 2.1
*/
public static String[] splitPreserveAllTokens(String str, String separatorChars, int max) {
return splitWorker(str, separatorChars, max, true);
}
/**
* Performs the logic for the <code>split</code> and
* <code>splitPreserveAllTokens</code> methods that return a maximum array
* length.
*
* @param str the String to parse, may be <code>null</code>
* @param separatorChars the separate character
* @param max the maximum number of elements to include in the
* array. A zero or negative value implies no limit.
* @param preserveAllTokens if <code>true</code>, adjacent separators are
* treated as empty token separators; if <code>false</code>, adjacent
* separators are treated as one separator.
* @return an array of parsed Strings, <code>null</code> if null String input
*/
private static String[] splitWorker(String str, String separatorChars, int max, boolean preserveAllTokens) {
// Performance tuned for 2.0 (JDK1.4)
// Direct code is quicker than StringTokenizer.
// Also, StringTokenizer uses isSpace() not isWhitespace()
if (str == null) {
return null;
}
int len = str.length();
if (len == 0) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
List<String> list = new ArrayList<String>();
int sizePlus1 = 1;
int i = 0, start = 0;
boolean match = false;
boolean lastMatch = false;
if (separatorChars == null) {
// Null separator means use whitespace
while (i < len) {
if (Character.isWhitespace(str.charAt(i))) {
if (match || preserveAllTokens) {
lastMatch = true;
if (sizePlus1++ == max) {
i = len;
lastMatch = false;
}
list.add(str.substring(start, i));
match = false;
}
start = ++i;
continue;
}
lastMatch = false;
match = true;
i++;
}
} else if (separatorChars.length() == 1) {
// Optimise 1 character case
char sep = separatorChars.charAt(0);
while (i < len) {
if (str.charAt(i) == sep) {
if (match || preserveAllTokens) {
lastMatch = true;
if (sizePlus1++ == max) {
i = len;
lastMatch = false;
}
list.add(str.substring(start, i));
match = false;
}
start = ++i;
continue;
}
lastMatch = false;
match = true;
i++;
}
} else {
// standard case
while (i < len) {
if (separatorChars.indexOf(str.charAt(i)) >= 0) {
if (match || preserveAllTokens) {
lastMatch = true;
if (sizePlus1++ == max) {
i = len;
lastMatch = false;
}
list.add(str.substring(start, i));
match = false;
}
start = ++i;
continue;
}
lastMatch = false;
match = true;
i++;
}
}
if (match || (preserveAllTokens && lastMatch)) {
list.add(str.substring(start, i));
}
return list.toArray(new String[list.size()]);
}
/**
* <p>Splits a String by Character type as returned by
* <code>java.lang.Character.getType(char)</code>. Groups of contiguous
* characters of the same type are returned as complete tokens.
* <pre>
* StringUtils.splitByCharacterType(null) = null
* StringUtils.splitByCharacterType("") = []
* StringUtils.splitByCharacterType("ab de fg") = ["ab", " ", "de", " ", "fg"]
* StringUtils.splitByCharacterType("ab de fg") = ["ab", " ", "de", " ", "fg"]
* StringUtils.splitByCharacterType("ab:cd:ef") = ["ab", ":", "cd", ":", "ef"]
* StringUtils.splitByCharacterType("number5") = ["number", "5"]
* StringUtils.splitByCharacterType("fooBar") = ["foo", "B", "ar"]
* StringUtils.splitByCharacterType("foo200Bar") = ["foo", "200", "B", "ar"]
* StringUtils.splitByCharacterType("ASFRules") = ["ASFR", "ules"]
* </pre>
* @param str the String to split, may be <code>null</code>
* @return an array of parsed Strings, <code>null</code> if null String input
* @since 2.4
*/
public static String[] splitByCharacterType(String str) {
return splitByCharacterType(str, false);
}
/**
* <p>Splits a String by Character type as returned by
* <code>java.lang.Character.getType(char)</code>. Groups of contiguous
* characters of the same type are returned as complete tokens, with the
* following exception: the character of type
* <code>Character.UPPERCASE_LETTER</code>, if any, immediately
* preceding a token of type <code>Character.LOWERCASE_LETTER</code>
* will belong to the following token rather than to the preceding, if any,
* <code>Character.UPPERCASE_LETTER</code> token.
* <pre>
* StringUtils.splitByCharacterTypeCamelCase(null) = null
* StringUtils.splitByCharacterTypeCamelCase("") = []
* StringUtils.splitByCharacterTypeCamelCase("ab de fg") = ["ab", " ", "de", " ", "fg"]
* StringUtils.splitByCharacterTypeCamelCase("ab de fg") = ["ab", " ", "de", " ", "fg"]
* StringUtils.splitByCharacterTypeCamelCase("ab:cd:ef") = ["ab", ":", "cd", ":", "ef"]
* StringUtils.splitByCharacterTypeCamelCase("number5") = ["number", "5"]
* StringUtils.splitByCharacterTypeCamelCase("fooBar") = ["foo", "Bar"]
* StringUtils.splitByCharacterTypeCamelCase("foo200Bar") = ["foo", "200", "Bar"]
* StringUtils.splitByCharacterTypeCamelCase("ASFRules") = ["ASF", "Rules"]
* </pre>
* @param str the String to split, may be <code>null</code>
* @return an array of parsed Strings, <code>null</code> if null String input
* @since 2.4
*/
public static String[] splitByCharacterTypeCamelCase(String str) {
return splitByCharacterType(str, true);
}
/**
* <p>Splits a String by Character type as returned by
* <code>java.lang.Character.getType(char)</code>. Groups of contiguous
* characters of the same type are returned as complete tokens, with the
* following exception: if <code>camelCase</code> is <code>true</code>,
* the character of type <code>Character.UPPERCASE_LETTER</code>, if any,
* immediately preceding a token of type <code>Character.LOWERCASE_LETTER</code>
* will belong to the following token rather than to the preceding, if any,
* <code>Character.UPPERCASE_LETTER</code> token.
* @param str the String to split, may be <code>null</code>
* @param camelCase whether to use so-called "camel-case" for letter types
* @return an array of parsed Strings, <code>null</code> if null String input
* @since 2.4
*/
private static String[] splitByCharacterType(String str, boolean camelCase) {
if (str == null) {
return null;
}
if (str.length() == 0) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
char[] c = str.toCharArray();
List<String> list = new ArrayList<String>();
int tokenStart = 0;
int currentType = Character.getType(c[tokenStart]);
for (int pos = tokenStart + 1; pos < c.length; pos++) {
int type = Character.getType(c[pos]);
if (type == currentType) {
continue;
}
if (camelCase && type == Character.LOWERCASE_LETTER && currentType == Character.UPPERCASE_LETTER) {
int newTokenStart = pos - 1;
if (newTokenStart != tokenStart) {
list.add(new String(c, tokenStart, newTokenStart - tokenStart));
tokenStart = newTokenStart;
}
} else {
list.add(new String(c, tokenStart, pos - tokenStart));
tokenStart = pos;
}
currentType = type;
}
list.add(new String(c, tokenStart, c.length - tokenStart));
return list.toArray(new String[list.size()]);
}
// Joining
//-----------------------------------------------------------------------
/**
* <p>Joins the provided elements into a single String. </p>
*
* <p>No separator is added to the joined String.
* Null objects or empty string elements are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.concat("a", "b", "c") = "abc"
* StringUtils.concat(null, "", "a") = "a"
* </pre>
*
* @param elements the values to join together
* @return the concatenated String
* @since 3.0
*/
public static String concat(Object... elements) {
return join(elements, null);
}
/**
* <p>Joins the provided elements into a single String, with the specified
* separator between each element. </p>
*
* <p>No separator is added before or after the joined String.
* Null objects or empty string elements are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.concatWith(".", "a", "b", "c") = "a.b.c"
* StringUtils.concatWith("", null, "", "a") = "a"
* </pre>
*
* @param separator the value to put between elements
* @param elements the values to join together
* @return the concatenated String
* @since 3.0
*/
public static String concatWith(String separator, Object... elements) {
return join(elements, separator);
}
/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* <p>No separator is added to the joined String.
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null) = null
* StringUtils.join([]) = ""
* StringUtils.join([null]) = ""
* StringUtils.join(["a", "b", "c"]) = "abc"
* StringUtils.join([null, "", "a"]) = "a"
* </pre>
*
* @param array the array of values to join together, may be null
* @return the joined String, <code>null</code> if null array input
* @since 2.0
*/
public static String join(Object[] array) {
return join(array, null);
}
/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* <p>No delimiter is added before or after the list.
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join(["a", "b", "c"], ';') = "a;b;c"
* StringUtils.join(["a", "b", "c"], null) = "abc"
* StringUtils.join([null, "", "a"], ';') = ";;a"
* </pre>
*
* @param array the array of values to join together, may be null
* @param separator the separator character to use
* @return the joined String, <code>null</code> if null array input
* @since 2.0
*/
public static String join(Object[] array, char separator) {
if (array == null) {
return null;
}
return join(array, separator, 0, array.length);
}
/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* <p>No delimiter is added before or after the list.
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join(["a", "b", "c"], ';') = "a;b;c"
* StringUtils.join(["a", "b", "c"], null) = "abc"
* StringUtils.join([null, "", "a"], ';') = ";;a"
* </pre>
*
* @param array the array of values to join together, may be null
* @param separator the separator character to use
* @param startIndex the first index to start joining from. It is
* an error to pass in an end index past the end of the array
* @param endIndex the index to stop joining from (exclusive). It is
* an error to pass in an end index past the end of the array
* @return the joined String, <code>null</code> if null array input
* @since 2.0
*/
public static String join(Object[] array, char separator, int startIndex, int endIndex) {
if (array == null) {
return null;
}
int bufSize = (endIndex - startIndex);
if (bufSize <= 0) {
return EMPTY;
}
bufSize *= ((array[startIndex] == null ? 16 : array[startIndex].toString().length()) + 1);
StringBuilder buf = new StringBuilder(bufSize);
for (int i = startIndex; i < endIndex; i++) {
if (i > startIndex) {
buf.append(separator);
}
if (array[i] != null) {
buf.append(array[i]);
}
}
return buf.toString();
}
/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* <p>No delimiter is added before or after the list.
* A <code>null</code> separator is the same as an empty String ("").
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join(["a", "b", "c"], "--") = "a--b--c"
* StringUtils.join(["a", "b", "c"], null) = "abc"
* StringUtils.join(["a", "b", "c"], "") = "abc"
* StringUtils.join([null, "", "a"], ',') = ",,a"
* </pre>
*
* @param array the array of values to join together, may be null
* @param separator the separator character to use, null treated as ""
* @return the joined String, <code>null</code> if null array input
*/
public static String join(Object[] array, String separator) {
if (array == null) {
return null;
}
return join(array, separator, 0, array.length);
}
/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* <p>No delimiter is added before or after the list.
* A <code>null</code> separator is the same as an empty String ("").
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join(["a", "b", "c"], "--") = "a--b--c"
* StringUtils.join(["a", "b", "c"], null) = "abc"
* StringUtils.join(["a", "b", "c"], "") = "abc"
* StringUtils.join([null, "", "a"], ',') = ",,a"
* </pre>
*
* @param array the array of values to join together, may be null
* @param separator the separator character to use, null treated as ""
* @param startIndex the first index to start joining from. It is
* an error to pass in an end index past the end of the array
* @param endIndex the index to stop joining from (exclusive). It is
* an error to pass in an end index past the end of the array
* @return the joined String, <code>null</code> if null array input
*/
public static String join(Object[] array, String separator, int startIndex, int endIndex) {
if (array == null) {
return null;
}
if (separator == null) {
separator = EMPTY;
}
// endIndex - startIndex > 0: Len = NofStrings *(len(firstString) + len(separator))
// (Assuming that all Strings are roughly equally long)
int bufSize = (endIndex - startIndex);
if (bufSize <= 0) {
return EMPTY;
}
bufSize *= ((array[startIndex] == null ? 16 : array[startIndex].toString().length())
+ separator.length());
StringBuilder buf = new StringBuilder(bufSize);
for (int i = startIndex; i < endIndex; i++) {
if (i > startIndex) {
buf.append(separator);
}
if (array[i] != null) {
buf.append(array[i]);
}
}
return buf.toString();
}
/**
* <p>Joins the elements of the provided <code>Iterator</code> into
* a single String containing the provided elements.</p>
*
* <p>No delimiter is added before or after the list. Null objects or empty
* strings within the iteration are represented by empty strings.</p>
*
* <p>See the examples here: {@link #join(Object[],char)}. </p>
*
* @param iterator the <code>Iterator</code> of values to join together, may be null
* @param separator the separator character to use
* @return the joined String, <code>null</code> if null iterator input
* @since 2.0
*/
public static String join(Iterator<?> iterator, char separator) {
// handle null, zero and one elements before building a buffer
if (iterator == null) {
return null;
}
if (!iterator.hasNext()) {
return EMPTY;
}
Object first = iterator.next();
if (!iterator.hasNext()) {
return ObjectUtils.toString(first);
}
// two or more elements
StringBuilder buf = new StringBuilder(256); // Java default is 16, probably too small
if (first != null) {
buf.append(first);
}
while (iterator.hasNext()) {
buf.append(separator);
Object obj = iterator.next();
if (obj != null) {
buf.append(obj);
}
}
return buf.toString();
}
/**
* <p>Joins the elements of the provided <code>Iterator</code> into
* a single String containing the provided elements.</p>
*
* <p>No delimiter is added before or after the list.
* A <code>null</code> separator is the same as an empty String ("").</p>
*
* <p>See the examples here: {@link #join(Object[],String)}. </p>
*
* @param iterator the <code>Iterator</code> of values to join together, may be null
* @param separator the separator character to use, null treated as ""
* @return the joined String, <code>null</code> if null iterator input
*/
public static String join(Iterator<?> iterator, String separator) {
// handle null, zero and one elements before building a buffer
if (iterator == null) {
return null;
}
if (!iterator.hasNext()) {
return EMPTY;
}
Object first = iterator.next();
if (!iterator.hasNext()) {
return ObjectUtils.toString(first);
}
// two or more elements
StringBuilder buf = new StringBuilder(256); // Java default is 16, probably too small
if (first != null) {
buf.append(first);
}
while (iterator.hasNext()) {
if (separator != null) {
buf.append(separator);
}
Object obj = iterator.next();
if (obj != null) {
buf.append(obj);
}
}
return buf.toString();
}
/**
* <p>Joins the elements of the provided <code>Iterable</code> into
* a single String containing the provided elements.</p>
*
* <p>No delimiter is added before or after the list. Null objects or empty
* strings within the iteration are represented by empty strings.</p>
*
* <p>See the examples here: {@link #join(Object[],char)}. </p>
*
* @param iterable the <code>Iterable</code> providing the values to join together, may be null
* @param separator the separator character to use
* @return the joined String, <code>null</code> if null iterator input
* @since 2.3
*/
public static String join(Iterable<?> iterable, char separator) {
if (iterable == null) {
return null;
}
return join(iterable.iterator(), separator);
}
/**
* <p>Joins the elements of the provided <code>Iterable</code> into
* a single String containing the provided elements.</p>
*
* <p>No delimiter is added before or after the list.
* A <code>null</code> separator is the same as an empty String ("").</p>
*
* <p>See the examples here: {@link #join(Object[],String)}. </p>
*
* @param iterable the <code>Iterable</code> providing the values to join together, may be null
* @param separator the separator character to use, null treated as ""
* @return the joined String, <code>null</code> if null iterator input
* @since 2.3
*/
public static String join(Iterable<?> iterable, String separator) {
if (iterable == null) {
return null;
}
return join(iterable.iterator(), separator);
}
// Delete
//-----------------------------------------------------------------------
/**
* <p>Deletes all whitespaces from a String as defined by
* {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.deleteWhitespace(null) = null
* StringUtils.deleteWhitespace("") = ""
* StringUtils.deleteWhitespace("abc") = "abc"
* StringUtils.deleteWhitespace(" ab c ") = "abc"
* </pre>
*
* @param str the String to delete whitespace from, may be null
* @return the String without whitespaces, <code>null</code> if null String input
*/
public static String deleteWhitespace(String str) {
if (isEmpty(str)) {
return str;
}
int sz = str.length();
char[] chs = new char[sz];
int count = 0;
for (int i = 0; i < sz; i++) {
if (!Character.isWhitespace(str.charAt(i))) {
chs[count++] = str.charAt(i);
}
}
if (count == sz) {
return str;
}
return new String(chs, 0, count);
}
// Remove
//-----------------------------------------------------------------------
/**
* <p>Removes a substring only if it is at the begining of a source string,
* otherwise returns the source string.</p>
*
* <p>A <code>null</code> source string will return <code>null</code>.
* An empty ("") source string will return the empty string.
* A <code>null</code> search string will return the source string.</p>
*
* <pre>
* StringUtils.removeStart(null, *) = null
* StringUtils.removeStart("", *) = ""
* StringUtils.removeStart(*, null) = *
* StringUtils.removeStart("www.domain.com", "www.") = "domain.com"
* StringUtils.removeStart("domain.com", "www.") = "domain.com"
* StringUtils.removeStart("www.domain.com", "domain") = "www.domain.com"
* StringUtils.removeStart("abc", "") = "abc"
* </pre>
*
* @param str the source String to search, may be null
* @param remove the String to search for and remove, may be null
* @return the substring with the string removed if found,
* <code>null</code> if null String input
* @since 2.1
*/
public static String removeStart(String str, String remove) {
if (isEmpty(str) || isEmpty(remove)) {
return str;
}
if (str.startsWith(remove)){
return str.substring(remove.length());
}
return str;
}
/**
* <p>Case insensitive removal of a substring if it is at the begining of a source string,
* otherwise returns the source string.</p>
*
* <p>A <code>null</code> source string will return <code>null</code>.
* An empty ("") source string will return the empty string.
* A <code>null</code> search string will return the source string.</p>
*
* <pre>
* StringUtils.removeStartIgnoreCase(null, *) = null
* StringUtils.removeStartIgnoreCase("", *) = ""
* StringUtils.removeStartIgnoreCase(*, null) = *
* StringUtils.removeStartIgnoreCase("www.domain.com", "www.") = "domain.com"
* StringUtils.removeStartIgnoreCase("www.domain.com", "WWW.") = "domain.com"
* StringUtils.removeStartIgnoreCase("domain.com", "www.") = "domain.com"
* StringUtils.removeStartIgnoreCase("www.domain.com", "domain") = "www.domain.com"
* StringUtils.removeStartIgnoreCase("abc", "") = "abc"
* </pre>
*
* @param str the source String to search, may be null
* @param remove the String to search for (case insensitive) and remove, may be null
* @return the substring with the string removed if found,
* <code>null</code> if null String input
* @since 2.4
*/
public static String removeStartIgnoreCase(String str, String remove) {
if (isEmpty(str) || isEmpty(remove)) {
return str;
}
if (startsWithIgnoreCase(str, remove)) {
return str.substring(remove.length());
}
return str;
}
/**
* <p>Removes a substring only if it is at the end of a source string,
* otherwise returns the source string.</p>
*
* <p>A <code>null</code> source string will return <code>null</code>.
* An empty ("") source string will return the empty string.
* A <code>null</code> search string will return the source string.</p>
*
* <pre>
* StringUtils.removeEnd(null, *) = null
* StringUtils.removeEnd("", *) = ""
* StringUtils.removeEnd(*, null) = *
* StringUtils.removeEnd("www.domain.com", ".com.") = "www.domain.com"
* StringUtils.removeEnd("www.domain.com", ".com") = "www.domain"
* StringUtils.removeEnd("www.domain.com", "domain") = "www.domain.com"
* StringUtils.removeEnd("abc", "") = "abc"
* </pre>
*
* @param str the source String to search, may be null
* @param remove the String to search for and remove, may be null
* @return the substring with the string removed if found,
* <code>null</code> if null String input
* @since 2.1
*/
public static String removeEnd(String str, String remove) {
if (isEmpty(str) || isEmpty(remove)) {
return str;
}
if (str.endsWith(remove)) {
return str.substring(0, str.length() - remove.length());
}
return str;
}
/**
* <p>Case insensitive removal of a substring if it is at the end of a source string,
* otherwise returns the source string.</p>
*
* <p>A <code>null</code> source string will return <code>null</code>.
* An empty ("") source string will return the empty string.
* A <code>null</code> search string will return the source string.</p>
*
* <pre>
* StringUtils.removeEndIgnoreCase(null, *) = null
* StringUtils.removeEndIgnoreCase("", *) = ""
* StringUtils.removeEndIgnoreCase(*, null) = *
* StringUtils.removeEndIgnoreCase("www.domain.com", ".com.") = "www.domain.com"
* StringUtils.removeEndIgnoreCase("www.domain.com", ".com") = "www.domain"
* StringUtils.removeEndIgnoreCase("www.domain.com", "domain") = "www.domain.com"
* StringUtils.removeEndIgnoreCase("abc", "") = "abc"
* StringUtils.removeEndIgnoreCase("www.domain.com", ".COM") = "www.domain")
* StringUtils.removeEndIgnoreCase("www.domain.COM", ".com") = "www.domain")
* </pre>
*
* @param str the source String to search, may be null
* @param remove the String to search for (case insensitive) and remove, may be null
* @return the substring with the string removed if found,
* <code>null</code> if null String input
* @since 2.4
*/
public static String removeEndIgnoreCase(String str, String remove) {
if (isEmpty(str) || isEmpty(remove)) {
return str;
}
if (endsWithIgnoreCase(str, remove)) {
return str.substring(0, str.length() - remove.length());
}
return str;
}
/**
* <p>Removes all occurrences of a substring from within the source string.</p>
*
* <p>A <code>null</code> source string will return <code>null</code>.
* An empty ("") source string will return the empty string.
* A <code>null</code> remove string will return the source string.
* An empty ("") remove string will return the source string.</p>
*
* <pre>
* StringUtils.remove(null, *) = null
* StringUtils.remove("", *) = ""
* StringUtils.remove(*, null) = *
* StringUtils.remove(*, "") = *
* StringUtils.remove("queued", "ue") = "qd"
* StringUtils.remove("queued", "zz") = "queued"
* </pre>
*
* @param str the source String to search, may be null
* @param remove the String to search for and remove, may be null
* @return the substring with the string removed if found,
* <code>null</code> if null String input
* @since 2.1
*/
public static String remove(String str, String remove) {
if (isEmpty(str) || isEmpty(remove)) {
return str;
}
return replace(str, remove, EMPTY, -1);
}
/**
* <p>Removes all occurrences of a character from within the source string.</p>
*
* <p>A <code>null</code> source string will return <code>null</code>.
* An empty ("") source string will return the empty string.</p>
*
* <pre>
* StringUtils.remove(null, *) = null
* StringUtils.remove("", *) = ""
* StringUtils.remove("queued", 'u') = "qeed"
* StringUtils.remove("queued", 'z') = "queued"
* </pre>
*
* @param str the source String to search, may be null
* @param remove the char to search for and remove, may be null
* @return the substring with the char removed if found,
* <code>null</code> if null String input
* @since 2.1
*/
public static String remove(String str, char remove) {
if (isEmpty(str) || str.indexOf(remove) == INDEX_NOT_FOUND) {
return str;
}
char[] chars = str.toCharArray();
int pos = 0;
for (int i = 0; i < chars.length; i++) {
if (chars[i] != remove) {
chars[pos++] = chars[i];
}
}
return new String(chars, 0, pos);
}
// Replacing
//-----------------------------------------------------------------------
/**
* <p>Replaces a String with another String inside a larger String, once.</p>
*
* <p>A <code>null</code> reference passed to this method is a no-op.</p>
*
* <pre>
* StringUtils.replaceOnce(null, *, *) = null
* StringUtils.replaceOnce("", *, *) = ""
* StringUtils.replaceOnce("any", null, *) = "any"
* StringUtils.replaceOnce("any", *, null) = "any"
* StringUtils.replaceOnce("any", "", *) = "any"
* StringUtils.replaceOnce("aba", "a", null) = "aba"
* StringUtils.replaceOnce("aba", "a", "") = "ba"
* StringUtils.replaceOnce("aba", "a", "z") = "zba"
* </pre>
*
* @see #replace(String text, String searchString, String replacement, int max)
* @param text text to search and replace in, may be null
* @param searchString the String to search for, may be null
* @param replacement the String to replace with, may be null
* @return the text with any replacements processed,
* <code>null</code> if null String input
*/
public static String replaceOnce(String text, String searchString, String replacement) {
return replace(text, searchString, replacement, 1);
}
/**
* <p>Replaces all occurrences of a String within another String.</p>
*
* <p>A <code>null</code> reference passed to this method is a no-op.</p>
*
* <pre>
* StringUtils.replace(null, *, *) = null
* StringUtils.replace("", *, *) = ""
* StringUtils.replace("any", null, *) = "any"
* StringUtils.replace("any", *, null) = "any"
* StringUtils.replace("any", "", *) = "any"
* StringUtils.replace("aba", "a", null) = "aba"
* StringUtils.replace("aba", "a", "") = "b"
* StringUtils.replace("aba", "a", "z") = "zbz"
* </pre>
*
* @see #replace(String text, String searchString, String replacement, int max)
* @param text text to search and replace in, may be null
* @param searchString the String to search for, may be null
* @param replacement the String to replace it with, may be null
* @return the text with any replacements processed,
* <code>null</code> if null String input
*/
public static String replace(String text, String searchString, String replacement) {
return replace(text, searchString, replacement, -1);
}
/**
* <p>Replaces a String with another String inside a larger String,
* for the first <code>max</code> values of the search String.</p>
*
* <p>A <code>null</code> reference passed to this method is a no-op.</p>
*
* <pre>
* StringUtils.replace(null, *, *, *) = null
* StringUtils.replace("", *, *, *) = ""
* StringUtils.replace("any", null, *, *) = "any"
* StringUtils.replace("any", *, null, *) = "any"
* StringUtils.replace("any", "", *, *) = "any"
* StringUtils.replace("any", *, *, 0) = "any"
* StringUtils.replace("abaa", "a", null, -1) = "abaa"
* StringUtils.replace("abaa", "a", "", -1) = "b"
* StringUtils.replace("abaa", "a", "z", 0) = "abaa"
* StringUtils.replace("abaa", "a", "z", 1) = "zbaa"
* StringUtils.replace("abaa", "a", "z", 2) = "zbza"
* StringUtils.replace("abaa", "a", "z", -1) = "zbzz"
* </pre>
*
* @param text text to search and replace in, may be null
* @param searchString the String to search for, may be null
* @param replacement the String to replace it with, may be null
* @param max maximum number of values to replace, or <code>-1</code> if no maximum
* @return the text with any replacements processed,
* <code>null</code> if null String input
*/
public static String replace(String text, String searchString, String replacement, int max) {
if (isEmpty(text) || isEmpty(searchString) || replacement == null || max == 0) {
return text;
}
int start = 0;
int end = text.indexOf(searchString, start);
if (end == INDEX_NOT_FOUND) {
return text;
}
int replLength = searchString.length();
int increase = replacement.length() - replLength;
increase = (increase < 0 ? 0 : increase);
increase *= (max < 0 ? 16 : (max > 64 ? 64 : max));
StringBuilder buf = new StringBuilder(text.length() + increase);
while (end != INDEX_NOT_FOUND) {
buf.append(text.substring(start, end)).append(replacement);
start = end + replLength;
if (--max == 0) {
break;
}
end = text.indexOf(searchString, start);
}
buf.append(text.substring(start));
return buf.toString();
}
/**
* <p>
* Replaces all occurrences of Strings within another String.
* </p>
*
* <p>
* A <code>null</code> reference passed to this method is a no-op, or if
* any "search string" or "string to replace" is null, that replace will be
* ignored. This will not repeat. For repeating replaces, call the
* overloaded method.
* </p>
*
* <pre>
* StringUtils.replaceEach(null, *, *) = null
* StringUtils.replaceEach("", *, *) = ""
* StringUtils.replaceEach("aba", null, null) = "aba"
* StringUtils.replaceEach("aba", new String[0], null) = "aba"
* StringUtils.replaceEach("aba", null, new String[0]) = "aba"
* StringUtils.replaceEach("aba", new String[]{"a"}, null) = "aba"
* StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""}) = "b"
* StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"}) = "aba"
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}) = "wcte"
* (example of how it does not repeat)
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}) = "dcte"
* </pre>
*
* @param text
* text to search and replace in, no-op if null
* @param searchList
* the Strings to search for, no-op if null
* @param replacementList
* the Strings to replace them with, no-op if null
* @return the text with any replacements processed, <code>null</code> if
* null String input
* @throws IndexOutOfBoundsException
* if the lengths of the arrays are not the same (null is ok,
* and/or size 0)
* @since 2.4
*/
public static String replaceEach(String text, String[] searchList, String[] replacementList) {
return replaceEach(text, searchList, replacementList, false, 0);
}
/**
* <p>
* Replaces all occurrences of Strings within another String.
* </p>
*
* <p>
* A <code>null</code> reference passed to this method is a no-op, or if
* any "search string" or "string to replace" is null, that replace will be
* ignored. This will not repeat. For repeating replaces, call the
* overloaded method.
* </p>
*
* <pre>
* StringUtils.replaceEach(null, *, *, *) = null
* StringUtils.replaceEach("", *, *, *) = ""
* StringUtils.replaceEach("aba", null, null, *) = "aba"
* StringUtils.replaceEach("aba", new String[0], null, *) = "aba"
* StringUtils.replaceEach("aba", null, new String[0], *) = "aba"
* StringUtils.replaceEach("aba", new String[]{"a"}, null, *) = "aba"
* StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""}, *) = "b"
* StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"}, *) = "aba"
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}, *) = "wcte"
* (example of how it repeats)
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}, false) = "dcte"
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}, true) = "tcte"
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "ab"}, true) = IllegalArgumentException
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "ab"}, false) = "dcabe"
* </pre>
*
* @param text
* text to search and replace in, no-op if null
* @param searchList
* the Strings to search for, no-op if null
* @param replacementList
* the Strings to replace them with, no-op if null
* @return the text with any replacements processed, <code>null</code> if
* null String input
* @throws IllegalArgumentException
* if the search is repeating and there is an endless loop due
* to outputs of one being inputs to another
* @throws IndexOutOfBoundsException
* if the lengths of the arrays are not the same (null is ok,
* and/or size 0)
* @since 2.4
*/
public static String replaceEachRepeatedly(String text, String[] searchList, String[] replacementList) {
// timeToLive should be 0 if not used or nothing to replace, else it's
// the length of the replace array
int timeToLive = searchList == null ? 0 : searchList.length;
return replaceEach(text, searchList, replacementList, true, timeToLive);
}
/**
* <p>
* Replaces all occurrences of Strings within another String.
* </p>
*
* <p>
* A <code>null</code> reference passed to this method is a no-op, or if
* any "search string" or "string to replace" is null, that replace will be
* ignored.
* </p>
*
* <pre>
* StringUtils.replaceEach(null, *, *, *) = null
* StringUtils.replaceEach("", *, *, *) = ""
* StringUtils.replaceEach("aba", null, null, *) = "aba"
* StringUtils.replaceEach("aba", new String[0], null, *) = "aba"
* StringUtils.replaceEach("aba", null, new String[0], *) = "aba"
* StringUtils.replaceEach("aba", new String[]{"a"}, null, *) = "aba"
* StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""}, *) = "b"
* StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"}, *) = "aba"
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}, *) = "wcte"
* (example of how it repeats)
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}, false) = "dcte"
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}, true) = "tcte"
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "ab"}, *) = IllegalArgumentException
* </pre>
*
* @param text
* text to search and replace in, no-op if null
* @param searchList
* the Strings to search for, no-op if null
* @param replacementList
* the Strings to replace them with, no-op if null
* @param repeat if true, then replace repeatedly
* until there are no more possible replacements or timeToLive < 0
* @param timeToLive
* if less than 0 then there is a circular reference and endless
* loop
* @return the text with any replacements processed, <code>null</code> if
* null String input
* @throws IllegalArgumentException
* if the search is repeating and there is an endless loop due
* to outputs of one being inputs to another
* @throws IndexOutOfBoundsException
* if the lengths of the arrays are not the same (null is ok,
* and/or size 0)
* @since 2.4
*/
private static String replaceEach(String text, String[] searchList, String[] replacementList,
boolean repeat, int timeToLive)
{
// mchyzer Performance note: This creates very few new objects (one major goal)
// let me know if there are performance requests, we can create a harness to measure
if (text == null || text.length() == 0 || searchList == null ||
searchList.length == 0 || replacementList == null || replacementList.length == 0)
{
return text;
}
// if recursing, this shouldnt be less than 0
if (timeToLive < 0) {
throw new IllegalStateException("TimeToLive of " + timeToLive + " is less than 0: " + text);
}
int searchLength = searchList.length;
int replacementLength = replacementList.length;
// make sure lengths are ok, these need to be equal
if (searchLength != replacementLength) {
throw new IllegalArgumentException("Search and Replace array lengths don't match: "
+ searchLength
+ " vs "
+ replacementLength);
}
// keep track of which still have matches
boolean[] noMoreMatchesForReplIndex = new boolean[searchLength];
// index on index that the match was found
int textIndex = -1;
int replaceIndex = -1;
int tempIndex = -1;
// index of replace array that will replace the search string found
// NOTE: logic duplicated below START
for (int i = 0; i < searchLength; i++) {
if (noMoreMatchesForReplIndex[i] || searchList[i] == null ||
searchList[i].length() == 0 || replacementList[i] == null)
{
continue;
}
tempIndex = text.indexOf(searchList[i]);
// see if we need to keep searching for this
if (tempIndex == -1) {
noMoreMatchesForReplIndex[i] = true;
} else {
if (textIndex == -1 || tempIndex < textIndex) {
textIndex = tempIndex;
replaceIndex = i;
}
}
}
// NOTE: logic mostly below END
// no search strings found, we are done
if (textIndex == -1) {
return text;
}
int start = 0;
// get a good guess on the size of the result buffer so it doesnt have to double if it goes over a bit
int increase = 0;
// count the replacement text elements that are larger than their corresponding text being replaced
for (int i = 0; i < searchList.length; i++) {
if (searchList[i] == null || replacementList[i] == null) {
continue;
}
int greater = replacementList[i].length() - searchList[i].length();
if (greater > 0) {
increase += 3 * greater; // assume 3 matches
}
}
// have upper-bound at 20% increase, then let Java take over
increase = Math.min(increase, text.length() / 5);
StringBuilder buf = new StringBuilder(text.length() + increase);
while (textIndex != -1) {
for (int i = start; i < textIndex; i++) {
buf.append(text.charAt(i));
}
buf.append(replacementList[replaceIndex]);
start = textIndex + searchList[replaceIndex].length();
textIndex = -1;
replaceIndex = -1;
tempIndex = -1;
// find the next earliest match
// NOTE: logic mostly duplicated above START
for (int i = 0; i < searchLength; i++) {
if (noMoreMatchesForReplIndex[i] || searchList[i] == null ||
searchList[i].length() == 0 || replacementList[i] == null)
{
continue;
}
tempIndex = text.indexOf(searchList[i], start);
// see if we need to keep searching for this
if (tempIndex == -1) {
noMoreMatchesForReplIndex[i] = true;
} else {
if (textIndex == -1 || tempIndex < textIndex) {
textIndex = tempIndex;
replaceIndex = i;
}
}
}
// NOTE: logic duplicated above END
}
int textLength = text.length();
for (int i = start; i < textLength; i++) {
buf.append(text.charAt(i));
}
String result = buf.toString();
if (!repeat) {
return result;
}
return replaceEach(result, searchList, replacementList, repeat, timeToLive - 1);
}
// Replace, character based
//-----------------------------------------------------------------------
/**
* <p>Replaces all occurrences of a character in a String with another.
* This is a null-safe version of {@link String#replace(char, char)}.</p>
*
* <p>A <code>null</code> string input returns <code>null</code>.
* An empty ("") string input returns an empty string.</p>
*
* <pre>
* StringUtils.replaceChars(null, *, *) = null
* StringUtils.replaceChars("", *, *) = ""
* StringUtils.replaceChars("abcba", 'b', 'y') = "aycya"
* StringUtils.replaceChars("abcba", 'z', 'y') = "abcba"
* </pre>
*
* @param str String to replace characters in, may be null
* @param searchChar the character to search for, may be null
* @param replaceChar the character to replace, may be null
* @return modified String, <code>null</code> if null string input
* @since 2.0
*/
public static String replaceChars(String str, char searchChar, char replaceChar) {
if (str == null) {
return null;
}
return str.replace(searchChar, replaceChar);
}
/**
* <p>Replaces multiple characters in a String in one go.
* This method can also be used to delete characters.</p>
*
* <p>For example:<br />
* <code>replaceChars("hello", "ho", "jy") = jelly</code>.</p>
*
* <p>A <code>null</code> string input returns <code>null</code>.
* An empty ("") string input returns an empty string.
* A null or empty set of search characters returns the input string.</p>
*
* <p>The length of the search characters should normally equal the length
* of the replace characters.
* If the search characters is longer, then the extra search characters
* are deleted.
* If the search characters is shorter, then the extra replace characters
* are ignored.</p>
*
* <pre>
* StringUtils.replaceChars(null, *, *) = null
* StringUtils.replaceChars("", *, *) = ""
* StringUtils.replaceChars("abc", null, *) = "abc"
* StringUtils.replaceChars("abc", "", *) = "abc"
* StringUtils.replaceChars("abc", "b", null) = "ac"
* StringUtils.replaceChars("abc", "b", "") = "ac"
* StringUtils.replaceChars("abcba", "bc", "yz") = "ayzya"
* StringUtils.replaceChars("abcba", "bc", "y") = "ayya"
* StringUtils.replaceChars("abcba", "bc", "yzx") = "ayzya"
* </pre>
*
* @param str String to replace characters in, may be null
* @param searchChars a set of characters to search for, may be null
* @param replaceChars a set of characters to replace, may be null
* @return modified String, <code>null</code> if null string input
* @since 2.0
*/
public static String replaceChars(String str, String searchChars, String replaceChars) {
if (isEmpty(str) || isEmpty(searchChars)) {
return str;
}
if (replaceChars == null) {
replaceChars = EMPTY;
}
boolean modified = false;
int replaceCharsLength = replaceChars.length();
int strLength = str.length();
StringBuilder buf = new StringBuilder(strLength);
for (int i = 0; i < strLength; i++) {
char ch = str.charAt(i);
int index = searchChars.indexOf(ch);
if (index >= 0) {
modified = true;
if (index < replaceCharsLength) {
buf.append(replaceChars.charAt(index));
}
} else {
buf.append(ch);
}
}
if (modified) {
return buf.toString();
}
return str;
}
// Overlay
//-----------------------------------------------------------------------
/**
* <p>Overlays part of a String with another String.</p>
*
* <p>A <code>null</code> string input returns <code>null</code>.
* A negative index is treated as zero.
* An index greater than the string length is treated as the string length.
* The start index is always the smaller of the two indices.</p>
*
* <pre>
* StringUtils.overlay(null, *, *, *) = null
* StringUtils.overlay("", "abc", 0, 0) = "abc"
* StringUtils.overlay("abcdef", null, 2, 4) = "abef"
* StringUtils.overlay("abcdef", "", 2, 4) = "abef"
* StringUtils.overlay("abcdef", "", 4, 2) = "abef"
* StringUtils.overlay("abcdef", "zzzz", 2, 4) = "abzzzzef"
* StringUtils.overlay("abcdef", "zzzz", 4, 2) = "abzzzzef"
* StringUtils.overlay("abcdef", "zzzz", -1, 4) = "zzzzef"
* StringUtils.overlay("abcdef", "zzzz", 2, 8) = "abzzzz"
* StringUtils.overlay("abcdef", "zzzz", -2, -3) = "zzzzabcdef"
* StringUtils.overlay("abcdef", "zzzz", 8, 10) = "abcdefzzzz"
* </pre>
*
* @param str the String to do overlaying in, may be null
* @param overlay the String to overlay, may be null
* @param start the position to start overlaying at
* @param end the position to stop overlaying before
* @return overlayed String, <code>null</code> if null String input
* @since 2.0
*/
public static String overlay(String str, String overlay, int start, int end) {
if (str == null) {
return null;
}
if (overlay == null) {
overlay = EMPTY;
}
int len = str.length();
if (start < 0) {
start = 0;
}
if (start > len) {
start = len;
}
if (end < 0) {
end = 0;
}
if (end > len) {
end = len;
}
if (start > end) {
int temp = start;
start = end;
end = temp;
}
return new StringBuilder(len + start - end + overlay.length() + 1)
.append(str.substring(0, start))
.append(overlay)
.append(str.substring(end))
.toString();
}
// Chomping
//-----------------------------------------------------------------------
/**
* <p>Removes one newline from end of a String if it's there,
* otherwise leave it alone. A newline is "<code>\n</code>",
* "<code>\r</code>", or "<code>\r\n</code>".</p>
*
* <p>NOTE: This method changed in 2.0.
* It now more closely matches Perl chomp.</p>
*
* <pre>
* StringUtils.chomp(null) = null
* StringUtils.chomp("") = ""
* StringUtils.chomp("abc \r") = "abc "
* StringUtils.chomp("abc\n") = "abc"
* StringUtils.chomp("abc\r\n") = "abc"
* StringUtils.chomp("abc\r\n\r\n") = "abc\r\n"
* StringUtils.chomp("abc\n\r") = "abc\n"
* StringUtils.chomp("abc\n\rabc") = "abc\n\rabc"
* StringUtils.chomp("\r") = ""
* StringUtils.chomp("\n") = ""
* StringUtils.chomp("\r\n") = ""
* </pre>
*
* @param str the String to chomp a newline from, may be null
* @return String without newline, <code>null</code> if null String input
*/
public static String chomp(String str) {
if (isEmpty(str)) {
return str;
}
if (str.length() == 1) {
char ch = str.charAt(0);
if (ch == CharUtils.CR || ch == CharUtils.LF) {
return EMPTY;
}
return str;
}
int lastIdx = str.length() - 1;
char last = str.charAt(lastIdx);
if (last == CharUtils.LF) {
if (str.charAt(lastIdx - 1) == CharUtils.CR) {
lastIdx--;
}
} else if (last != CharUtils.CR) {
lastIdx++;
}
return str.substring(0, lastIdx);
}
/**
* <p>Removes <code>separator</code> from the end of
* <code>str</code> if it's there, otherwise leave it alone.</p>
*
* <p>NOTE: This method changed in version 2.0.
* It now more closely matches Perl chomp.
* For the previous behavior, use {@link #substringBeforeLast(String, String)}.
* This method uses {@link String#endsWith(String)}.</p>
*
* <pre>
* StringUtils.chomp(null, *) = null
* StringUtils.chomp("", *) = ""
* StringUtils.chomp("foobar", "bar") = "foo"
* StringUtils.chomp("foobar", "baz") = "foobar"
* StringUtils.chomp("foo", "foo") = ""
* StringUtils.chomp("foo ", "foo") = "foo "
* StringUtils.chomp(" foo", "foo") = " "
* StringUtils.chomp("foo", "foooo") = "foo"
* StringUtils.chomp("foo", "") = "foo"
* StringUtils.chomp("foo", null) = "foo"
* </pre>
*
* @param str the String to chomp from, may be null
* @param separator separator String, may be null
* @return String without trailing separator, <code>null</code> if null String input
*/
public static String chomp(String str, String separator) {
if (isEmpty(str) || separator == null) {
return str;
}
if (str.endsWith(separator)) {
return str.substring(0, str.length() - separator.length());
}
return str;
}
// Chopping
//-----------------------------------------------------------------------
/**
* <p>Remove the last character from a String.</p>
*
* <p>If the String ends in <code>\r\n</code>, then remove both
* of them.</p>
*
* <pre>
* StringUtils.chop(null) = null
* StringUtils.chop("") = ""
* StringUtils.chop("abc \r") = "abc "
* StringUtils.chop("abc\n") = "abc"
* StringUtils.chop("abc\r\n") = "abc"
* StringUtils.chop("abc") = "ab"
* StringUtils.chop("abc\nabc") = "abc\nab"
* StringUtils.chop("a") = ""
* StringUtils.chop("\r") = ""
* StringUtils.chop("\n") = ""
* StringUtils.chop("\r\n") = ""
* </pre>
*
* @param str the String to chop last character from, may be null
* @return String without last character, <code>null</code> if null String input
*/
public static String chop(String str) {
if (str == null) {
return null;
}
int strLen = str.length();
if (strLen < 2) {
return EMPTY;
}
int lastIdx = strLen - 1;
String ret = str.substring(0, lastIdx);
char last = str.charAt(lastIdx);
if (last == CharUtils.LF) {
if (ret.charAt(lastIdx - 1) == CharUtils.CR) {
return ret.substring(0, lastIdx - 1);
}
}
return ret;
}
// Conversion
//-----------------------------------------------------------------------
// Padding
//-----------------------------------------------------------------------
/**
* <p>Repeat a String <code>repeat</code> times to form a
* new String.</p>
*
* <pre>
* StringUtils.repeat(null, 2) = null
* StringUtils.repeat("", 0) = ""
* StringUtils.repeat("", 2) = ""
* StringUtils.repeat("a", 3) = "aaa"
* StringUtils.repeat("ab", 2) = "abab"
* StringUtils.repeat("a", -2) = ""
* </pre>
*
* @param str the String to repeat, may be null
* @param repeat number of times to repeat str, negative treated as zero
* @return a new String consisting of the original String repeated,
* <code>null</code> if null String input
* @since 2.5
*/
public static String repeat(String str, int repeat) {
// Performance tuned for 2.0 (JDK1.4)
if (str == null) {
return null;
}
if (repeat <= 0) {
return EMPTY;
}
int inputLength = str.length();
if (repeat == 1 || inputLength == 0) {
return str;
}
if (inputLength == 1 && repeat <= PAD_LIMIT) {
return padding(repeat, str.charAt(0));
}
int outputLength = inputLength * repeat;
switch (inputLength) {
case 1 :
char ch = str.charAt(0);
char[] output1 = new char[outputLength];
for (int i = repeat - 1; i >= 0; i--) {
output1[i] = ch;
}
return new String(output1);
case 2 :
char ch0 = str.charAt(0);
char ch1 = str.charAt(1);
char[] output2 = new char[outputLength];
for (int i = repeat * 2 - 2; i >= 0; i--, i--) {
output2[i] = ch0;
output2[i + 1] = ch1;
}
return new String(output2);
default :
StringBuilder buf = new StringBuilder(outputLength);
for (int i = 0; i < repeat; i++) {
buf.append(str);
}
return buf.toString();
}
}
/**
* <p>Repeat a String <code>repeat</code> times to form a
* new String, with a String separator injected each time. </p>
*
* <pre>
* StringUtils.repeat(null, null, 2) = null
* StringUtils.repeat(null, "x", 2) = null
* StringUtils.repeat("", null, 0) = ""
* StringUtils.repeat("", "", 2) = ""
* StringUtils.repeat("", "x", 3) = "xxx"
* StringUtils.repeat("?", ", ", 3) = "?, ?, ?"
* </pre>
*
* @param str the String to repeat, may be null
* @param separator the String to inject, may be null
* @param repeat number of times to repeat str, negative treated as zero
* @return a new String consisting of the original String repeated,
* <code>null</code> if null String input
*/
public static String repeat(String str, String separator, int repeat) {
if(str == null || separator == null) {
return repeat(str, repeat);
} else {
// given that repeat(String, int) is quite optimized, better to rely on it than try and splice this into it
String result = repeat(str + separator, repeat);
return removeEnd(result, separator);
}
}
/**
* <p>Returns padding using the specified delimiter repeated
* to a given length.</p>
*
* <pre>
* StringUtils.padding(0, 'e') = ""
* StringUtils.padding(3, 'e') = "eee"
* StringUtils.padding(-2, 'e') = IndexOutOfBoundsException
* </pre>
*
* <p>Note: this method doesn't not support padding with
* <a href="http://www.unicode.org/glossary/#supplementary_character">Unicode Supplementary Characters</a>
* as they require a pair of <code>char</code>s to be represented.
* If you are needing to support full I18N of your applications
* consider using {@link #repeat(String, int)} instead.
* </p>
*
* @param repeat number of times to repeat delim
* @param padChar character to repeat
* @return String with repeated character
* @throws IndexOutOfBoundsException if <code>repeat < 0</code>
* @see #repeat(String, int)
*/
private static String padding(int repeat, char padChar) throws IndexOutOfBoundsException {
if (repeat < 0) {
throw new IndexOutOfBoundsException("Cannot pad a negative amount: " + repeat);
}
final char[] buf = new char[repeat];
for (int i = 0; i < buf.length; i++) {
buf[i] = padChar;
}
return new String(buf);
}
/**
* <p>Right pad a String with spaces (' ').</p>
*
* <p>The String is padded to the size of <code>size</code>.</p>
*
* <pre>
* StringUtils.rightPad(null, *) = null
* StringUtils.rightPad("", 3) = " "
* StringUtils.rightPad("bat", 3) = "bat"
* StringUtils.rightPad("bat", 5) = "bat "
* StringUtils.rightPad("bat", 1) = "bat"
* StringUtils.rightPad("bat", -1) = "bat"
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @return right padded String or original String if no padding is necessary,
* <code>null</code> if null String input
*/
public static String rightPad(String str, int size) {
return rightPad(str, size, ' ');
}
/**
* <p>Right pad a String with a specified character.</p>
*
* <p>The String is padded to the size of <code>size</code>.</p>
*
* <pre>
* StringUtils.rightPad(null, *, *) = null
* StringUtils.rightPad("", 3, 'z') = "zzz"
* StringUtils.rightPad("bat", 3, 'z') = "bat"
* StringUtils.rightPad("bat", 5, 'z') = "batzz"
* StringUtils.rightPad("bat", 1, 'z') = "bat"
* StringUtils.rightPad("bat", -1, 'z') = "bat"
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @param padChar the character to pad with
* @return right padded String or original String if no padding is necessary,
* <code>null</code> if null String input
* @since 2.0
*/
public static String rightPad(String str, int size, char padChar) {
if (str == null) {
return null;
}
int pads = size - str.length();
if (pads <= 0) {
return str; // returns original String when possible
}
if (pads > PAD_LIMIT) {
return rightPad(str, size, String.valueOf(padChar));
}
return str.concat(padding(pads, padChar));
}
/**
* <p>Right pad a String with a specified String.</p>
*
* <p>The String is padded to the size of <code>size</code>.</p>
*
* <pre>
* StringUtils.rightPad(null, *, *) = null
* StringUtils.rightPad("", 3, "z") = "zzz"
* StringUtils.rightPad("bat", 3, "yz") = "bat"
* StringUtils.rightPad("bat", 5, "yz") = "batyz"
* StringUtils.rightPad("bat", 8, "yz") = "batyzyzy"
* StringUtils.rightPad("bat", 1, "yz") = "bat"
* StringUtils.rightPad("bat", -1, "yz") = "bat"
* StringUtils.rightPad("bat", 5, null) = "bat "
* StringUtils.rightPad("bat", 5, "") = "bat "
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @param padStr the String to pad with, null or empty treated as single space
* @return right padded String or original String if no padding is necessary,
* <code>null</code> if null String input
*/
public static String rightPad(String str, int size, String padStr) {
if (str == null) {
return null;
}
if (isEmpty(padStr)) {
padStr = " ";
}
int padLen = padStr.length();
int strLen = str.length();
int pads = size - strLen;
if (pads <= 0) {
return str; // returns original String when possible
}
if (padLen == 1 && pads <= PAD_LIMIT) {
return rightPad(str, size, padStr.charAt(0));
}
if (pads == padLen) {
return str.concat(padStr);
} else if (pads < padLen) {
return str.concat(padStr.substring(0, pads));
} else {
char[] padding = new char[pads];
char[] padChars = padStr.toCharArray();
for (int i = 0; i < pads; i++) {
padding[i] = padChars[i % padLen];
}
return str.concat(new String(padding));
}
}
/**
* <p>Left pad a String with spaces (' ').</p>
*
* <p>The String is padded to the size of <code>size</code>.</p>
*
* <pre>
* StringUtils.leftPad(null, *) = null
* StringUtils.leftPad("", 3) = " "
* StringUtils.leftPad("bat", 3) = "bat"
* StringUtils.leftPad("bat", 5) = " bat"
* StringUtils.leftPad("bat", 1) = "bat"
* StringUtils.leftPad("bat", -1) = "bat"
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @return left padded String or original String if no padding is necessary,
* <code>null</code> if null String input
*/
public static String leftPad(String str, int size) {
return leftPad(str, size, ' ');
}
/**
* <p>Left pad a String with a specified character.</p>
*
* <p>Pad to a size of <code>size</code>.</p>
*
* <pre>
* StringUtils.leftPad(null, *, *) = null
* StringUtils.leftPad("", 3, 'z') = "zzz"
* StringUtils.leftPad("bat", 3, 'z') = "bat"
* StringUtils.leftPad("bat", 5, 'z') = "zzbat"
* StringUtils.leftPad("bat", 1, 'z') = "bat"
* StringUtils.leftPad("bat", -1, 'z') = "bat"
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @param padChar the character to pad with
* @return left padded String or original String if no padding is necessary,
* <code>null</code> if null String input
* @since 2.0
*/
public static String leftPad(String str, int size, char padChar) {
if (str == null) {
return null;
}
int pads = size - str.length();
if (pads <= 0) {
return str; // returns original String when possible
}
if (pads > PAD_LIMIT) {
return leftPad(str, size, String.valueOf(padChar));
}
return padding(pads, padChar).concat(str);
}
/**
* <p>Left pad a String with a specified String.</p>
*
* <p>Pad to a size of <code>size</code>.</p>
*
* <pre>
* StringUtils.leftPad(null, *, *) = null
* StringUtils.leftPad("", 3, "z") = "zzz"
* StringUtils.leftPad("bat", 3, "yz") = "bat"
* StringUtils.leftPad("bat", 5, "yz") = "yzbat"
* StringUtils.leftPad("bat", 8, "yz") = "yzyzybat"
* StringUtils.leftPad("bat", 1, "yz") = "bat"
* StringUtils.leftPad("bat", -1, "yz") = "bat"
* StringUtils.leftPad("bat", 5, null) = " bat"
* StringUtils.leftPad("bat", 5, "") = " bat"
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @param padStr the String to pad with, null or empty treated as single space
* @return left padded String or original String if no padding is necessary,
* <code>null</code> if null String input
*/
public static String leftPad(String str, int size, String padStr) {
if (str == null) {
return null;
}
if (isEmpty(padStr)) {
padStr = " ";
}
int padLen = padStr.length();
int strLen = str.length();
int pads = size - strLen;
if (pads <= 0) {
return str; // returns original String when possible
}
if (padLen == 1 && pads <= PAD_LIMIT) {
return leftPad(str, size, padStr.charAt(0));
}
if (pads == padLen) {
return padStr.concat(str);
} else if (pads < padLen) {
return padStr.substring(0, pads).concat(str);
} else {
char[] padding = new char[pads];
char[] padChars = padStr.toCharArray();
for (int i = 0; i < pads; i++) {
padding[i] = padChars[i % padLen];
}
return new String(padding).concat(str);
}
}
/**
* Gets a CharSequence length or <code>0</code> if the CharSequence is
* <code>null</code>.
*
* @param cs
* a CharSequence or <code>null</code>
* @return CharSequence length or <code>0</code> if the CharSequence is
* <code>null</code>.
* @since 2.4
* @deprecated See {@link CharSequenceUtils#length(CharSequence)}
* @since 3.0 Changed signature from length(String) to length(CharSequence)
*/
public static int length(CharSequence cs) {
return CharSequenceUtils.length(cs);
}
// Centering
//-----------------------------------------------------------------------
/**
* <p>Centers a String in a larger String of size <code>size</code>
* using the space character (' ').<p>
*
* <p>If the size is less than the String length, the String is returned.
* A <code>null</code> String returns <code>null</code>.
* A negative size is treated as zero.</p>
*
* <p>Equivalent to <code>center(str, size, " ")</code>.</p>
*
* <pre>
* StringUtils.center(null, *) = null
* StringUtils.center("", 4) = " "
* StringUtils.center("ab", -1) = "ab"
* StringUtils.center("ab", 4) = " ab "
* StringUtils.center("abcd", 2) = "abcd"
* StringUtils.center("a", 4) = " a "
* </pre>
*
* @param str the String to center, may be null
* @param size the int size of new String, negative treated as zero
* @return centered String, <code>null</code> if null String input
*/
public static String center(String str, int size) {
return center(str, size, ' ');
}
/**
* <p>Centers a String in a larger String of size <code>size</code>.
* Uses a supplied character as the value to pad the String with.</p>
*
* <p>If the size is less than the String length, the String is returned.
* A <code>null</code> String returns <code>null</code>.
* A negative size is treated as zero.</p>
*
* <pre>
* StringUtils.center(null, *, *) = null
* StringUtils.center("", 4, ' ') = " "
* StringUtils.center("ab", -1, ' ') = "ab"
* StringUtils.center("ab", 4, ' ') = " ab"
* StringUtils.center("abcd", 2, ' ') = "abcd"
* StringUtils.center("a", 4, ' ') = " a "
* StringUtils.center("a", 4, 'y') = "yayy"
* </pre>
*
* @param str the String to center, may be null
* @param size the int size of new String, negative treated as zero
* @param padChar the character to pad the new String with
* @return centered String, <code>null</code> if null String input
* @since 2.0
*/
public static String center(String str, int size, char padChar) {
if (str == null || size <= 0) {
return str;
}
int strLen = str.length();
int pads = size - strLen;
if (pads <= 0) {
return str;
}
str = leftPad(str, strLen + pads / 2, padChar);
str = rightPad(str, size, padChar);
return str;
}
/**
* <p>Centers a String in a larger String of size <code>size</code>.
* Uses a supplied String as the value to pad the String with.</p>
*
* <p>If the size is less than the String length, the String is returned.
* A <code>null</code> String returns <code>null</code>.
* A negative size is treated as zero.</p>
*
* <pre>
* StringUtils.center(null, *, *) = null
* StringUtils.center("", 4, " ") = " "
* StringUtils.center("ab", -1, " ") = "ab"
* StringUtils.center("ab", 4, " ") = " ab"
* StringUtils.center("abcd", 2, " ") = "abcd"
* StringUtils.center("a", 4, " ") = " a "
* StringUtils.center("a", 4, "yz") = "yayz"
* StringUtils.center("abc", 7, null) = " abc "
* StringUtils.center("abc", 7, "") = " abc "
* </pre>
*
* @param str the String to center, may be null
* @param size the int size of new String, negative treated as zero
* @param padStr the String to pad the new String with, must not be null or empty
* @return centered String, <code>null</code> if null String input
* @throws IllegalArgumentException if padStr is <code>null</code> or empty
*/
public static String center(String str, int size, String padStr) {
if (str == null || size <= 0) {
return str;
}
if (isEmpty(padStr)) {
padStr = " ";
}
int strLen = str.length();
int pads = size - strLen;
if (pads <= 0) {
return str;
}
str = leftPad(str, strLen + pads / 2, padStr);
str = rightPad(str, size, padStr);
return str;
}
// Case conversion
//-----------------------------------------------------------------------
/**
* <p>Converts a String to upper case as per {@link String#toUpperCase()}.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.upperCase(null) = null
* StringUtils.upperCase("") = ""
* StringUtils.upperCase("aBc") = "ABC"
* </pre>
*
* <p><strong>Note:</strong> As described in the documentation for {@link String#toUpperCase()},
* the result of this method is affected by the current locale.
* For platform-independent case transformations, the method {@link #lowerCase(String, Locale)}
* should be used with a specific locale (e.g. {@link Locale#ENGLISH}).</p>
*
* @param str the String to upper case, may be null
* @return the upper cased String, <code>null</code> if null String input
*/
public static String upperCase(String str) {
if (str == null) {
return null;
}
return str.toUpperCase();
}
/**
* <p>Converts a String to upper case as per {@link String#toUpperCase(Locale)}.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.upperCase(null, Locale.ENGLISH) = null
* StringUtils.upperCase("", Locale.ENGLISH) = ""
* StringUtils.upperCase("aBc", Locale.ENGLISH) = "ABC"
* </pre>
*
* @param str the String to upper case, may be null
* @param locale the locale that defines the case transformation rules, must not be null
* @return the upper cased String, <code>null</code> if null String input
* @since 2.5
*/
public static String upperCase(String str, Locale locale) {
if (str == null) {
return null;
}
return str.toUpperCase(locale);
}
/**
* <p>Converts a String to lower case as per {@link String#toLowerCase()}.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.lowerCase(null) = null
* StringUtils.lowerCase("") = ""
* StringUtils.lowerCase("aBc") = "abc"
* </pre>
*
* <p><strong>Note:</strong> As described in the documentation for {@link String#toLowerCase()},
* the result of this method is affected by the current locale.
* For platform-independent case transformations, the method {@link #lowerCase(String, Locale)}
* should be used with a specific locale (e.g. {@link Locale#ENGLISH}).</p>
*
* @param str the String to lower case, may be null
* @return the lower cased String, <code>null</code> if null String input
*/
public static String lowerCase(String str) {
if (str == null) {
return null;
}
return str.toLowerCase();
}
/**
* <p>Converts a String to lower case as per {@link String#toLowerCase(Locale)}.</p>
*
* <p>A <code>null</code> input String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.lowerCase(null, Locale.ENGLISH) = null
* StringUtils.lowerCase("", Locale.ENGLISH) = ""
* StringUtils.lowerCase("aBc", Locale.ENGLISH) = "abc"
* </pre>
*
* @param str the String to lower case, may be null
* @param locale the locale that defines the case transformation rules, must not be null
* @return the lower cased String, <code>null</code> if null String input
* @since 2.5
*/
public static String lowerCase(String str, Locale locale) {
if (str == null) {
return null;
}
return str.toLowerCase(locale);
}
/**
* <p>Capitalizes a String changing the first letter to title case as
* per {@link Character#toTitleCase(char)}. No other letters are changed.</p>
*
* <p>For a word based algorithm, see {@link org.apache.commons.lang3.text.WordUtils#capitalize(String)}.
* A <code>null</code> input String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.capitalize(null) = null
* StringUtils.capitalize("") = ""
* StringUtils.capitalize("cat") = "Cat"
* StringUtils.capitalize("cAt") = "CAt"
* </pre>
*
* @param cs the String to capitalize, may be null
* @return the capitalized String, <code>null</code> if null String input
* @see org.apache.commons.lang3.text.WordUtils#capitalize(String)
* @see #uncapitalize(CharSequence)
* @since 2.0
* @since 3.0 Changed signature from capitalize(String) to capitalize(CharSequence)
*/
public static String capitalize(CharSequence cs) {
if (cs == null ) {
return null;
}
int strLen;
if ((strLen = cs.length()) == 0) {
return cs.toString();
}
return new StringBuilder(strLen)
.append(Character.toTitleCase(cs.charAt(0)))
.append(CharSequenceUtils.subSequence(cs, 1))
.toString();
}
/**
* <p>Uncapitalizes a CharSequence changing the first letter to title case as
* per {@link Character#toLowerCase(char)}. No other letters are changed.</p>
*
* <p>For a word based algorithm, see {@link org.apache.commons.lang3.text.WordUtils#uncapitalize(String)}.
* A <code>null</code> input String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.uncapitalize(null) = null
* StringUtils.uncapitalize("") = ""
* StringUtils.uncapitalize("Cat") = "cat"
* StringUtils.uncapitalize("CAT") = "cAT"
* </pre>
*
* @param cs the String to uncapitalize, may be null
* @return the uncapitalized String, <code>null</code> if null String input
* @see org.apache.commons.lang3.text.WordUtils#uncapitalize(String)
* @see #capitalize(CharSequence)
* @since 2.0
* @since 3.0 Changed signature from uncapitalize(String) to uncapitalize(CharSequence)
*/
public static String uncapitalize(CharSequence cs) {
if (cs == null ) {
return null;
}
int strLen;
if ((strLen = cs.length()) == 0) {
return cs.toString();
}
return new StringBuilder(strLen)
.append(Character.toLowerCase(cs.charAt(0)))
.append(CharSequenceUtils.subSequence(cs, 1))
.toString();
}
/**
* <p>Swaps the case of a String changing upper and title case to
* lower case, and lower case to upper case.</p>
*
* <ul>
* <li>Upper case character converts to Lower case</li>
* <li>Title case character converts to Lower case</li>
* <li>Lower case character converts to Upper case</li>
* </ul>
*
* <p>For a word based algorithm, see {@link org.apache.commons.lang3.text.WordUtils#swapCase(String)}.
* A <code>null</code> input String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.swapCase(null) = null
* StringUtils.swapCase("") = ""
* StringUtils.swapCase("The dog has a BONE") = "tHE DOG HAS A bone"
* </pre>
*
* <p>NOTE: This method changed in Lang version 2.0.
* It no longer performs a word based algorithm.
* If you only use ASCII, you will notice no change.
* That functionality is available in org.apache.commons.lang3.text.WordUtils.</p>
*
* @param str the String to swap case, may be null
* @return the changed String, <code>null</code> if null String input
*/
public static String swapCase(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return str;
}
StringBuilder buffer = new StringBuilder(strLen);
char ch = 0;
for (int i = 0; i < strLen; i++) {
ch = str.charAt(i);
if (Character.isUpperCase(ch)) {
ch = Character.toLowerCase(ch);
} else if (Character.isTitleCase(ch)) {
ch = Character.toLowerCase(ch);
} else if (Character.isLowerCase(ch)) {
ch = Character.toUpperCase(ch);
}
buffer.append(ch);
}
return buffer.toString();
}
// Count matches
//-----------------------------------------------------------------------
/**
* <p>Counts how many times the substring appears in the larger String.</p>
*
* <p>A <code>null</code> or empty ("") String input returns <code>0</code>.</p>
*
* <pre>
* StringUtils.countMatches(null, *) = 0
* StringUtils.countMatches("", *) = 0
* StringUtils.countMatches("abba", null) = 0
* StringUtils.countMatches("abba", "") = 0
* StringUtils.countMatches("abba", "a") = 2
* StringUtils.countMatches("abba", "ab") = 1
* StringUtils.countMatches("abba", "xxx") = 0
* </pre>
*
* @param str the String to check, may be null
* @param sub the substring to count, may be null
* @return the number of occurrences, 0 if either String is <code>null</code>
*/
public static int countMatches(String str, String sub) {
if (isEmpty(str) || isEmpty(sub)) {
return 0;
}
int count = 0;
int idx = 0;
while ((idx = str.indexOf(sub, idx)) != INDEX_NOT_FOUND) {
count++;
idx += sub.length();
}
return count;
}
// Character Tests
//-----------------------------------------------------------------------
/**
* <p>Checks if the CharSequence contains only unicode letters.</p>
*
* <p><code>null</code> will return <code>false</code>.
* An empty CharSequence (length()=0) will return <code>true</code>.</p>
*
* <pre>
* StringUtils.isAlpha(null) = false
* StringUtils.isAlpha("") = true
* StringUtils.isAlpha(" ") = false
* StringUtils.isAlpha("abc") = true
* StringUtils.isAlpha("ab2c") = false
* StringUtils.isAlpha("ab-c") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return <code>true</code> if only contains letters, and is non-null
* @since 3.0 Changed signature from isAlpha(String) to isAlpha(CharSequence)
*/
public static boolean isAlpha(CharSequence cs) {
if (cs == null) {
return false;
}
int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (Character.isLetter(cs.charAt(i)) == false) {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only unicode letters and
* space (' ').</p>
*
* <p><code>null</code> will return <code>false</code>
* An empty CharSequence (length()=0) will return <code>true</code>.</p>
*
* <pre>
* StringUtils.isAlphaSpace(null) = false
* StringUtils.isAlphaSpace("") = true
* StringUtils.isAlphaSpace(" ") = true
* StringUtils.isAlphaSpace("abc") = true
* StringUtils.isAlphaSpace("ab c") = true
* StringUtils.isAlphaSpace("ab2c") = false
* StringUtils.isAlphaSpace("ab-c") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return <code>true</code> if only contains letters and space,
* and is non-null
* @since 3.0 Changed signature from isAlphaSpace(String) to isAlphaSpace(CharSequence)
*/
public static boolean isAlphaSpace(CharSequence cs) {
if (cs == null) {
return false;
}
int sz = cs.length();
for (int i = 0; i < sz; i++) {
if ((Character.isLetter(cs.charAt(i)) == false) && (cs.charAt(i) != ' ')) {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only unicode letters or digits.</p>
*
* <p><code>null</code> will return <code>false</code>.
* An empty CharSequence (length()=0) will return <code>true</code>.</p>
*
* <pre>
* StringUtils.isAlphanumeric(null) = false
* StringUtils.isAlphanumeric("") = true
* StringUtils.isAlphanumeric(" ") = false
* StringUtils.isAlphanumeric("abc") = true
* StringUtils.isAlphanumeric("ab c") = false
* StringUtils.isAlphanumeric("ab2c") = true
* StringUtils.isAlphanumeric("ab-c") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return <code>true</code> if only contains letters or digits,
* and is non-null
* @since 3.0 Changed signature from isAlphanumeric(String) to isAlphanumeric(CharSequence)
*/
public static boolean isAlphanumeric(CharSequence cs) {
if (cs == null) {
return false;
}
int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (Character.isLetterOrDigit(cs.charAt(i)) == false) {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only unicode letters, digits
* or space (<code>' '</code>).</p>
*
* <p><code>null</code> will return <code>false</code>.
* An empty CharSequence (length()=0) will return <code>true</code>.</p>
*
* <pre>
* StringUtils.isAlphanumeric(null) = false
* StringUtils.isAlphanumeric("") = true
* StringUtils.isAlphanumeric(" ") = true
* StringUtils.isAlphanumeric("abc") = true
* StringUtils.isAlphanumeric("ab c") = true
* StringUtils.isAlphanumeric("ab2c") = true
* StringUtils.isAlphanumeric("ab-c") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return <code>true</code> if only contains letters, digits or space,
* and is non-null
* @since 3.0 Changed signature from isAlphanumericSpace(String) to isAlphanumericSpace(CharSequence)
*/
public static boolean isAlphanumericSpace(CharSequence cs) {
if (cs == null) {
return false;
}
int sz = cs.length();
for (int i = 0; i < sz; i++) {
if ((Character.isLetterOrDigit(cs.charAt(i)) == false) && (cs.charAt(i) != ' ')) {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only ASCII printable characters.</p>
*
* <p><code>null</code> will return <code>false</code>.
* An empty CharSequence (length()=0) will return <code>true</code>.</p>
*
* <pre>
* StringUtils.isAsciiPrintable(null) = false
* StringUtils.isAsciiPrintable("") = true
* StringUtils.isAsciiPrintable(" ") = true
* StringUtils.isAsciiPrintable("Ceki") = true
* StringUtils.isAsciiPrintable("ab2c") = true
* StringUtils.isAsciiPrintable("!ab-c~") = true
* StringUtils.isAsciiPrintable("\u0020") = true
* StringUtils.isAsciiPrintable("\u0021") = true
* StringUtils.isAsciiPrintable("\u007e") = true
* StringUtils.isAsciiPrintable("\u007f") = false
* StringUtils.isAsciiPrintable("Ceki G\u00fclc\u00fc") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return <code>true</code> if every character is in the range
* 32 thru 126
* @since 2.1
* @since 3.0 Changed signature from isAsciiPrintable(String) to isAsciiPrintable(CharSequence)
*/
public static boolean isAsciiPrintable(CharSequence cs) {
if (cs == null) {
return false;
}
int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (CharUtils.isAsciiPrintable(cs.charAt(i)) == false) {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only unicode digits.
* A decimal point is not a unicode digit and returns false.</p>
*
* <p><code>null</code> will return <code>false</code>.
* An empty CharSequence (length()=0) will return <code>true</code>.</p>
*
* <pre>
* StringUtils.isNumeric(null) = false
* StringUtils.isNumeric("") = true
* StringUtils.isNumeric(" ") = false
* StringUtils.isNumeric("123") = true
* StringUtils.isNumeric("12 3") = false
* StringUtils.isNumeric("ab2c") = false
* StringUtils.isNumeric("12-3") = false
* StringUtils.isNumeric("12.3") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return <code>true</code> if only contains digits, and is non-null
* @since 3.0 Changed signature from isNumeric(String) to isNumeric(CharSequence)
*/
public static boolean isNumeric(CharSequence cs) {
if (cs == null) {
return false;
}
int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (Character.isDigit(cs.charAt(i)) == false) {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only unicode digits or space
* (<code>' '</code>).
* A decimal point is not a unicode digit and returns false.</p>
*
* <p><code>null</code> will return <code>false</code>.
* An empty CharSequence (length()=0) will return <code>true</code>.</p>
*
* <pre>
* StringUtils.isNumeric(null) = false
* StringUtils.isNumeric("") = true
* StringUtils.isNumeric(" ") = true
* StringUtils.isNumeric("123") = true
* StringUtils.isNumeric("12 3") = true
* StringUtils.isNumeric("ab2c") = false
* StringUtils.isNumeric("12-3") = false
* StringUtils.isNumeric("12.3") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return <code>true</code> if only contains digits or space,
* and is non-null
* @since 3.0 Changed signature from isNumericSpace(String) to isNumericSpace(CharSequence)
*/
public static boolean isNumericSpace(CharSequence cs) {
if (cs == null) {
return false;
}
int sz = cs.length();
for (int i = 0; i < sz; i++) {
if ((Character.isDigit(cs.charAt(i)) == false) && (cs.charAt(i) != ' ')) {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only whitespace.</p>
*
* <p><code>null</code> will return <code>false</code>.
* An empty CharSequence (length()=0) will return <code>true</code>.</p>
*
* <pre>
* StringUtils.isWhitespace(null) = false
* StringUtils.isWhitespace("") = true
* StringUtils.isWhitespace(" ") = true
* StringUtils.isWhitespace("abc") = false
* StringUtils.isWhitespace("ab2c") = false
* StringUtils.isWhitespace("ab-c") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return <code>true</code> if only contains whitespace, and is non-null
* @since 2.0
* @since 3.0 Changed signature from isWhitespace(String) to isWhitespace(CharSequence)
*/
public static boolean isWhitespace(CharSequence cs) {
if (cs == null) {
return false;
}
int sz = cs.length();
for (int i = 0; i < sz; i++) {
if ((Character.isWhitespace(cs.charAt(i)) == false)) {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only lowercase characters.</p>
*
* <p><code>null</code> will return <code>false</code>.
* An empty CharSequence (length()=0) will return <code>false</code>.</p>
*
* <pre>
* StringUtils.isAllLowerCase(null) = false
* StringUtils.isAllLowerCase("") = false
* StringUtils.isAllLowerCase(" ") = false
* StringUtils.isAllLowerCase("abc") = true
* StringUtils.isAllLowerCase("abC") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return <code>true</code> if only contains lowercase characters, and is non-null
* @since 2.5
* @since 3.0 Changed signature from isAllLowerCase(String) to isAllLowerCase(CharSequence)
*/
public static boolean isAllLowerCase(CharSequence cs) {
if (cs == null || isEmpty(cs)) {
return false;
}
int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (Character.isLowerCase(cs.charAt(i)) == false) {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only uppercase characters.</p>
*
* <p><code>null</code> will return <code>false</code>.
* An empty String (length()=0) will return <code>false</code>.</p>
*
* <pre>
* StringUtils.isAllUpperCase(null) = false
* StringUtils.isAllUpperCase("") = false
* StringUtils.isAllUpperCase(" ") = false
* StringUtils.isAllUpperCase("ABC") = true
* StringUtils.isAllUpperCase("aBC") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return <code>true</code> if only contains uppercase characters, and is non-null
* @since 2.5
* @since 3.0 Changed signature from isAllUpperCase(String) to isAllUpperCase(CharSequence)
*/
public static boolean isAllUpperCase(CharSequence cs) {
if (cs == null || isEmpty(cs)) {
return false;
}
int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (Character.isUpperCase(cs.charAt(i)) == false) {
return false;
}
}
return true;
}
// Defaults
//-----------------------------------------------------------------------
/**
* <p>Returns either the passed in String,
* or if the String is <code>null</code>, an empty String ("").</p>
*
* <pre>
* StringUtils.defaultString(null) = ""
* StringUtils.defaultString("") = ""
* StringUtils.defaultString("bat") = "bat"
* </pre>
*
* @see ObjectUtils#toString(Object)
* @see String#valueOf(Object)
* @param str the String to check, may be null
* @return the passed in String, or the empty String if it
* was <code>null</code>
*/
public static String defaultString(String str) {
return str == null ? EMPTY : str;
}
/**
* <p>Returns either the passed in String, or if the String is
* <code>null</code>, the value of <code>defaultStr</code>.</p>
*
* <pre>
* StringUtils.defaultString(null, "NULL") = "NULL"
* StringUtils.defaultString("", "NULL") = ""
* StringUtils.defaultString("bat", "NULL") = "bat"
* </pre>
*
* @see ObjectUtils#toString(Object,String)
* @see String#valueOf(Object)
* @param str the String to check, may be null
* @param defaultStr the default String to return
* if the input is <code>null</code>, may be null
* @return the passed in String, or the default if it was <code>null</code>
*/
public static String defaultString(String str, String defaultStr) {
return str == null ? defaultStr : str;
}
/**
* <p>Returns either the passed in CharSequence, or if the CharSequence is
* empty or <code>null</code>, the value of <code>defaultStr</code>.</p>
*
* <pre>
* StringUtils.defaultIfEmpty(null, "NULL") = "NULL"
* StringUtils.defaultIfEmpty("", "NULL") = "NULL"
* StringUtils.defaultIfEmpty("bat", "NULL") = "bat"
* StringUtils.defaultIfEmpty("", null) = null
* </pre>
* @param <T> the specific kind of CharSequence
* @param str the CharSequence to check, may be null
* @param defaultStr the default CharSequence to return
* if the input is empty ("") or <code>null</code>, may be null
* @return the passed in CharSequence, or the default
* @see StringUtils#defaultString(String, String)
*/
public static <T extends CharSequence> T defaultIfEmpty(T str, T defaultStr) {
return StringUtils.isEmpty(str) ? defaultStr : str;
}
// Reversing
//-----------------------------------------------------------------------
/**
* <p>Reverses a String as per {@link StringBuilder#reverse()}.</p>
*
* <p>A <code>null</code> String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.reverse(null) = null
* StringUtils.reverse("") = ""
* StringUtils.reverse("bat") = "tab"
* </pre>
*
* @param str the String to reverse, may be null
* @return the reversed String, <code>null</code> if null String input
*/
public static String reverse(String str) {
if (str == null) {
return null;
}
return new StringBuilder(str).reverse().toString();
}
/**
* <p>Reverses a String that is delimited by a specific character.</p>
*
* <p>The Strings between the delimiters are not reversed.
* Thus java.lang.String becomes String.lang.java (if the delimiter
* is <code>'.'</code>).</p>
*
* <pre>
* StringUtils.reverseDelimited(null, *) = null
* StringUtils.reverseDelimited("", *) = ""
* StringUtils.reverseDelimited("a.b.c", 'x') = "a.b.c"
* StringUtils.reverseDelimited("a.b.c", ".") = "c.b.a"
* </pre>
*
* @param str the String to reverse, may be null
* @param separatorChar the separator character to use
* @return the reversed String, <code>null</code> if null String input
* @since 2.0
*/
public static String reverseDelimited(String str, char separatorChar) {
if (str == null) {
return null;
}
// could implement manually, but simple way is to reuse other,
// probably slower, methods.
String[] strs = split(str, separatorChar);
ArrayUtils.reverse(strs);
return join(strs, separatorChar);
}
// Abbreviating
//-----------------------------------------------------------------------
/**
* <p>Abbreviates a String using ellipses. This will turn
* "Now is the time for all good men" into "Now is the time for..."</p>
*
* <p>Specifically:
* <ul>
* <li>If <code>str</code> is less than <code>maxWidth</code> characters
* long, return it.</li>
* <li>Else abbreviate it to <code>(substring(str, 0, max-3) + "...")</code>.</li>
* <li>If <code>maxWidth</code> is less than <code>4</code>, throw an
* <code>IllegalArgumentException</code>.</li>
* <li>In no case will it return a String of length greater than
* <code>maxWidth</code>.</li>
* </ul>
* </p>
*
* <pre>
* StringUtils.abbreviate(null, *) = null
* StringUtils.abbreviate("", 4) = ""
* StringUtils.abbreviate("abcdefg", 6) = "abc..."
* StringUtils.abbreviate("abcdefg", 7) = "abcdefg"
* StringUtils.abbreviate("abcdefg", 8) = "abcdefg"
* StringUtils.abbreviate("abcdefg", 4) = "a..."
* StringUtils.abbreviate("abcdefg", 3) = IllegalArgumentException
* </pre>
*
* @param str the String to check, may be null
* @param maxWidth maximum length of result String, must be at least 4
* @return abbreviated String, <code>null</code> if null String input
* @throws IllegalArgumentException if the width is too small
* @since 2.0
*/
public static String abbreviate(String str, int maxWidth) {
return abbreviate(str, 0, maxWidth);
}
/**
* <p>Abbreviates a String using ellipses. This will turn
* "Now is the time for all good men" into "...is the time for..."</p>
*
* <p>Works like <code>abbreviate(String, int)</code>, but allows you to specify
* a "left edge" offset. Note that this left edge is not necessarily going to
* be the leftmost character in the result, or the first character following the
* ellipses, but it will appear somewhere in the result.
*
* <p>In no case will it return a String of length greater than
* <code>maxWidth</code>.</p>
*
* <pre>
* StringUtils.abbreviate(null, *, *) = null
* StringUtils.abbreviate("", 0, 4) = ""
* StringUtils.abbreviate("abcdefghijklmno", -1, 10) = "abcdefg..."
* StringUtils.abbreviate("abcdefghijklmno", 0, 10) = "abcdefg..."
* StringUtils.abbreviate("abcdefghijklmno", 1, 10) = "abcdefg..."
* StringUtils.abbreviate("abcdefghijklmno", 4, 10) = "abcdefg..."
* StringUtils.abbreviate("abcdefghijklmno", 5, 10) = "...fghi..."
* StringUtils.abbreviate("abcdefghijklmno", 6, 10) = "...ghij..."
* StringUtils.abbreviate("abcdefghijklmno", 8, 10) = "...ijklmno"
* StringUtils.abbreviate("abcdefghijklmno", 10, 10) = "...ijklmno"
* StringUtils.abbreviate("abcdefghijklmno", 12, 10) = "...ijklmno"
* StringUtils.abbreviate("abcdefghij", 0, 3) = IllegalArgumentException
* StringUtils.abbreviate("abcdefghij", 5, 6) = IllegalArgumentException
* </pre>
*
* @param str the String to check, may be null
* @param offset left edge of source String
* @param maxWidth maximum length of result String, must be at least 4
* @return abbreviated String, <code>null</code> if null String input
* @throws IllegalArgumentException if the width is too small
* @since 2.0
*/
public static String abbreviate(String str, int offset, int maxWidth) {
if (str == null) {
return null;
}
if (maxWidth < 4) {
throw new IllegalArgumentException("Minimum abbreviation width is 4");
}
if (str.length() <= maxWidth) {
return str;
}
if (offset > str.length()) {
offset = str.length();
}
if ((str.length() - offset) < (maxWidth - 3)) {
offset = str.length() - (maxWidth - 3);
}
final String abrevMarker = "...";
if (offset <= 4) {
return str.substring(0, maxWidth - 3) + abrevMarker;
}
if (maxWidth < 7) {
throw new IllegalArgumentException("Minimum abbreviation width with offset is 7");
}
if ((offset + (maxWidth - 3)) < str.length()) {
return abrevMarker + abbreviate(str.substring(offset), maxWidth - 3);
}
return abrevMarker + str.substring(str.length() - (maxWidth - 3));
}
/**
* <p>Abbreviates a String to the length passed, replacing the middle characters with the supplied
* replacement String.</p>
*
* <p>This abbreviation only occurs if the following criteria is met:
* <ul>
* <li>Neither the String for abbreviation nor the replacement String are null or empty </li>
* <li>The length to truncate to is less than the length of the supplied String</li>
* <li>The length to truncate to is greater than 0</li>
* <li>The abbreviated String will have enough room for the length supplied replacement String
* and the first and last characters of the supplied String for abbreviation</li>
* </ul>
* Otherwise, the returned String will be the same as the supplied String for abbreviation.
* </p>
*
* <pre>
* StringUtils.abbreviateMiddle(null, null, 0) = null
* StringUtils.abbreviateMiddle("abc", null, 0) = "abc"
* StringUtils.abbreviateMiddle("abc", ".", 0) = "abc"
* StringUtils.abbreviateMiddle("abc", ".", 3) = "abc"
* StringUtils.abbreviateMiddle("abcdef", ".", 4) = "ab.f"
* </pre>
*
* @param str the String to abbreviate, may be null
* @param middle the String to replace the middle characters with, may be null
* @param length the length to abbreviate <code>str</code> to.
* @return the abbreviated String if the above criteria is met, or the original String supplied for abbreviation.
* @since 2.5
*/
public static String abbreviateMiddle(String str, String middle, int length) {
if (isEmpty(str) || isEmpty(middle)) {
return str;
}
if (length >= str.length() || length < (middle.length()+2)) {
return str;
}
int targetSting = length-middle.length();
int startOffset = targetSting/2+targetSting%2;
int endOffset = str.length()-targetSting/2;
StringBuilder builder = new StringBuilder(length);
builder.append(str.substring(0,startOffset));
builder.append(middle);
builder.append(str.substring(endOffset));
return builder.toString();
}
// Difference
//-----------------------------------------------------------------------
/**
* <p>Compares two Strings, and returns the portion where they differ.
* (More precisely, return the remainder of the second String,
* starting from where it's different from the first.)</p>
*
* <p>For example,
* <code>difference("i am a machine", "i am a robot") -> "robot"</code>.</p>
*
* <pre>
* StringUtils.difference(null, null) = null
* StringUtils.difference("", "") = ""
* StringUtils.difference("", "abc") = "abc"
* StringUtils.difference("abc", "") = ""
* StringUtils.difference("abc", "abc") = ""
* StringUtils.difference("ab", "abxyz") = "xyz"
* StringUtils.difference("abcde", "abxyz") = "xyz"
* StringUtils.difference("abcde", "xyz") = "xyz"
* </pre>
*
* @param str1 the first String, may be null
* @param str2 the second String, may be null
* @return the portion of str2 where it differs from str1; returns the
* empty String if they are equal
* @since 2.0
*/
public static String difference(String str1, String str2) {
if (str1 == null) {
return str2;
}
if (str2 == null) {
return str1;
}
int at = indexOfDifference(str1, str2);
if (at == INDEX_NOT_FOUND) {
return EMPTY;
}
return str2.substring(at);
}
/**
* <p>Compares two CharSequences, and returns the index at which the
* CharSequences begin to differ.</p>
*
* <p>For example,
* <code>indexOfDifference("i am a machine", "i am a robot") -> 7</code></p>
*
* <pre>
* StringUtils.indexOfDifference(null, null) = -1
* StringUtils.indexOfDifference("", "") = -1
* StringUtils.indexOfDifference("", "abc") = 0
* StringUtils.indexOfDifference("abc", "") = 0
* StringUtils.indexOfDifference("abc", "abc") = -1
* StringUtils.indexOfDifference("ab", "abxyz") = 2
* StringUtils.indexOfDifference("abcde", "abxyz") = 2
* StringUtils.indexOfDifference("abcde", "xyz") = 0
* </pre>
*
* @param cs1 the first CharSequence, may be null
* @param cs2 the second CharSequence, may be null
* @return the index where cs1 and cs2 begin to differ; -1 if they are equal
* @since 2.0
* @since 3.0 Changed signature from indexOfDifference(String, String) to indexOfDifference(CharSequence, CharSequence)
*/
public static int indexOfDifference(CharSequence cs1, CharSequence cs2) {
if (cs1 == cs2) {
return INDEX_NOT_FOUND;
}
if (cs1 == null || cs2 == null) {
return 0;
}
int i;
for (i = 0; i < cs1.length() && i < cs2.length(); ++i) {
if (cs1.charAt(i) != cs2.charAt(i)) {
break;
}
}
if (i < cs2.length() || i < cs1.length()) {
return i;
}
return INDEX_NOT_FOUND;
}
/**
* <p>Compares all CharSequences in an array and returns the index at which the
* CharSequences begin to differ.</p>
*
* <p>For example,
* <code>indexOfDifference(new String[] {"i am a machine", "i am a robot"}) -> 7</code></p>
*
* <pre>
* StringUtils.indexOfDifference(null) = -1
* StringUtils.indexOfDifference(new String[] {}) = -1
* StringUtils.indexOfDifference(new String[] {"abc"}) = -1
* StringUtils.indexOfDifference(new String[] {null, null}) = -1
* StringUtils.indexOfDifference(new String[] {"", ""}) = -1
* StringUtils.indexOfDifference(new String[] {"", null}) = 0
* StringUtils.indexOfDifference(new String[] {"abc", null, null}) = 0
* StringUtils.indexOfDifference(new String[] {null, null, "abc"}) = 0
* StringUtils.indexOfDifference(new String[] {"", "abc"}) = 0
* StringUtils.indexOfDifference(new String[] {"abc", ""}) = 0
* StringUtils.indexOfDifference(new String[] {"abc", "abc"}) = -1
* StringUtils.indexOfDifference(new String[] {"abc", "a"}) = 1
* StringUtils.indexOfDifference(new String[] {"ab", "abxyz"}) = 2
* StringUtils.indexOfDifference(new String[] {"abcde", "abxyz"}) = 2
* StringUtils.indexOfDifference(new String[] {"abcde", "xyz"}) = 0
* StringUtils.indexOfDifference(new String[] {"xyz", "abcde"}) = 0
* StringUtils.indexOfDifference(new String[] {"i am a machine", "i am a robot"}) = 7
* </pre>
*
* @param css array of CharSequences, entries may be null
* @return the index where the strings begin to differ; -1 if they are all equal
* @since 2.4
* @since 3.0 Changed signature from indexOfDifference(String...) to indexOfDifference(CharSequence...)
*/
public static int indexOfDifference(CharSequence... css) {
if (css == null || css.length <= 1) {
return INDEX_NOT_FOUND;
}
boolean anyStringNull = false;
boolean allStringsNull = true;
int arrayLen = css.length;
int shortestStrLen = Integer.MAX_VALUE;
int longestStrLen = 0;
// find the min and max string lengths; this avoids checking to make
// sure we are not exceeding the length of the string each time through
// the bottom loop.
for (int i = 0; i < arrayLen; i++) {
if (css[i] == null) {
anyStringNull = true;
shortestStrLen = 0;
} else {
allStringsNull = false;
shortestStrLen = Math.min(css[i].length(), shortestStrLen);
longestStrLen = Math.max(css[i].length(), longestStrLen);
}
}
// handle lists containing all nulls or all empty strings
if (allStringsNull || (longestStrLen == 0 && !anyStringNull)) {
return INDEX_NOT_FOUND;
}
// handle lists containing some nulls or some empty strings
if (shortestStrLen == 0) {
return 0;
}
// find the position with the first difference across all strings
int firstDiff = -1;
for (int stringPos = 0; stringPos < shortestStrLen; stringPos++) {
char comparisonChar = css[0].charAt(stringPos);
for (int arrayPos = 1; arrayPos < arrayLen; arrayPos++) {
if (css[arrayPos].charAt(stringPos) != comparisonChar) {
firstDiff = stringPos;
break;
}
}
if (firstDiff != -1) {
break;
}
}
if (firstDiff == -1 && shortestStrLen != longestStrLen) {
// we compared all of the characters up to the length of the
// shortest string and didn't find a match, but the string lengths
// vary, so return the length of the shortest string.
return shortestStrLen;
}
return firstDiff;
}
/**
* <p>Compares all Strings in an array and returns the initial sequence of
* characters that is common to all of them.</p>
*
* <p>For example,
* <code>getCommonPrefix(new String[] {"i am a machine", "i am a robot"}) -> "i am a "</code></p>
*
* <pre>
* StringUtils.getCommonPrefix(null) = ""
* StringUtils.getCommonPrefix(new String[] {}) = ""
* StringUtils.getCommonPrefix(new String[] {"abc"}) = "abc"
* StringUtils.getCommonPrefix(new String[] {null, null}) = ""
* StringUtils.getCommonPrefix(new String[] {"", ""}) = ""
* StringUtils.getCommonPrefix(new String[] {"", null}) = ""
* StringUtils.getCommonPrefix(new String[] {"abc", null, null}) = ""
* StringUtils.getCommonPrefix(new String[] {null, null, "abc"}) = ""
* StringUtils.getCommonPrefix(new String[] {"", "abc"}) = ""
* StringUtils.getCommonPrefix(new String[] {"abc", ""}) = ""
* StringUtils.getCommonPrefix(new String[] {"abc", "abc"}) = "abc"
* StringUtils.getCommonPrefix(new String[] {"abc", "a"}) = "a"
* StringUtils.getCommonPrefix(new String[] {"ab", "abxyz"}) = "ab"
* StringUtils.getCommonPrefix(new String[] {"abcde", "abxyz"}) = "ab"
* StringUtils.getCommonPrefix(new String[] {"abcde", "xyz"}) = ""
* StringUtils.getCommonPrefix(new String[] {"xyz", "abcde"}) = ""
* StringUtils.getCommonPrefix(new String[] {"i am a machine", "i am a robot"}) = "i am a "
* </pre>
*
* @param strs array of String objects, entries may be null
* @return the initial sequence of characters that are common to all Strings
* in the array; empty String if the array is null, the elements are all null
* or if there is no common prefix.
* @since 2.4
*/
public static String getCommonPrefix(String... strs) {
if (strs == null || strs.length == 0) {
return EMPTY;
}
int smallestIndexOfDiff = indexOfDifference(strs);
if (smallestIndexOfDiff == INDEX_NOT_FOUND) {
// all strings were identical
if (strs[0] == null) {
return EMPTY;
}
return strs[0];
} else if (smallestIndexOfDiff == 0) {
// there were no common initial characters
return EMPTY;
} else {
// we found a common initial character sequence
return strs[0].substring(0, smallestIndexOfDiff);
}
}
// Misc
//-----------------------------------------------------------------------
/**
* <p>Find the Levenshtein distance between two Strings.</p>
*
* <p>This is the number of changes needed to change one String into
* another, where each change is a single character modification (deletion,
* insertion or substitution).</p>
*
* <p>The previous implementation of the Levenshtein distance algorithm
* was from <a href="http://www.merriampark.com/ld.htm">http://www.merriampark.com/ld.htm</a></p>
*
* <p>Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError
* which can occur when my Java implementation is used with very large strings.<br>
* This implementation of the Levenshtein distance algorithm
* is from <a href="http://www.merriampark.com/ldjava.htm">http://www.merriampark.com/ldjava.htm</a></p>
*
* <pre>
* StringUtils.getLevenshteinDistance(null, *) = IllegalArgumentException
* StringUtils.getLevenshteinDistance(*, null) = IllegalArgumentException
* StringUtils.getLevenshteinDistance("","") = 0
* StringUtils.getLevenshteinDistance("","a") = 1
* StringUtils.getLevenshteinDistance("aaapppp", "") = 7
* StringUtils.getLevenshteinDistance("frog", "fog") = 1
* StringUtils.getLevenshteinDistance("fly", "ant") = 3
* StringUtils.getLevenshteinDistance("elephant", "hippo") = 7
* StringUtils.getLevenshteinDistance("hippo", "elephant") = 7
* StringUtils.getLevenshteinDistance("hippo", "zzzzzzzz") = 8
* StringUtils.getLevenshteinDistance("hello", "hallo") = 1
* </pre>
*
* @param s the first String, must not be null
* @param t the second String, must not be null
* @return result distance
* @throws IllegalArgumentException if either String input <code>null</code>
* @since 3.0 Changed signature from getLevenshteinDistance(String, String) to getLevenshteinDistance(CharSequence, CharSequence)
*/
public static int getLevenshteinDistance(CharSequence s, CharSequence t) {
if (s == null || t == null) {
throw new IllegalArgumentException("Strings must not be null");
}
/*
The difference between this impl. and the previous is that, rather
than creating and retaining a matrix of size s.length()+1 by t.length()+1,
we maintain two single-dimensional arrays of length s.length()+1. The first, d,
is the 'current working' distance array that maintains the newest distance cost
counts as we iterate through the characters of String s. Each time we increment
the index of String t we are comparing, d is copied to p, the second int[]. Doing so
allows us to retain the previous cost counts as required by the algorithm (taking
the minimum of the cost count to the left, up one, and diagonally up and to the left
of the current cost count being calculated). (Note that the arrays aren't really
copied anymore, just switched...this is clearly much better than cloning an array
or doing a System.arraycopy() each time through the outer loop.)
Effectively, the difference between the two implementations is this one does not
cause an out of memory condition when calculating the LD over two very large strings.
*/
int n = s.length(); // length of s
int m = t.length(); // length of t
if (n == 0) {
return m;
} else if (m == 0) {
return n;
}
if (n > m) {
// swap the input strings to consume less memory
CharSequence tmp = s;
s = t;
t = tmp;
n = m;
m = t.length();
}
int p[] = new int[n+1]; //'previous' cost array, horizontally
int d[] = new int[n+1]; // cost array, horizontally
int _d[]; //placeholder to assist in swapping p and d
// indexes into strings s and t
int i; // iterates through s
int j; // iterates through t
char t_j; // jth character of t
int cost; // cost
for (i = 0; i<=n; i++) {
p[i] = i;
}
for (j = 1; j<=m; j++) {
t_j = t.charAt(j-1);
d[0] = j;
for (i=1; i<=n; i++) {
cost = s.charAt(i-1)==t_j ? 0 : 1;
// minimum of cell to the left+1, to the top+1, diagonally left and up +cost
d[i] = Math.min(Math.min(d[i-1]+1, p[i]+1), p[i-1]+cost);
}
// copy current distance counts to 'previous row' distance counts
_d = p;
p = d;
d = _d;
}
// our last action in the above loop was to switch d and p, so p now
// actually has the most recent cost counts
return p[n];
}
/**
* <p>Gets the minimum of three <code>int</code> values.</p>
*
* @param a value 1
* @param b value 2
* @param c value 3
* @return the smallest of the values
*/
/*
private static int min(int a, int b, int c) {
// Method copied from NumberUtils to avoid dependency on subpackage
if (b < a) {
a = b;
}
if (c < a) {
a = c;
}
return a;
}
*/
// startsWith
//-----------------------------------------------------------------------
/**
* <p>Check if a String starts with a specified prefix.</p>
*
* <p><code>null</code>s are handled without exceptions. Two <code>null</code>
* references are considered to be equal. The comparison is case sensitive.</p>
*
* <pre>
* StringUtils.startsWith(null, null) = true
* StringUtils.startsWith(null, "abc") = false
* StringUtils.startsWith("abcdef", null) = false
* StringUtils.startsWith("abcdef", "abc") = true
* StringUtils.startsWith("ABCDEF", "abc") = false
* </pre>
*
* @see java.lang.String#startsWith(String)
* @param str the String to check, may be null
* @param prefix the prefix to find, may be null
* @return <code>true</code> if the String starts with the prefix, case sensitive, or
* both <code>null</code>
* @since 2.4
*/
public static boolean startsWith(String str, String prefix) {
return startsWith(str, prefix, false);
}
/**
* <p>Case insensitive check if a String starts with a specified prefix.</p>
*
* <p><code>null</code>s are handled without exceptions. Two <code>null</code>
* references are considered to be equal. The comparison is case insensitive.</p>
*
* <pre>
* StringUtils.startsWithIgnoreCase(null, null) = true
* StringUtils.startsWithIgnoreCase(null, "abc") = false
* StringUtils.startsWithIgnoreCase("abcdef", null) = false
* StringUtils.startsWithIgnoreCase("abcdef", "abc") = true
* StringUtils.startsWithIgnoreCase("ABCDEF", "abc") = true
* </pre>
*
* @see java.lang.String#startsWith(String)
* @param str the String to check, may be null
* @param prefix the prefix to find, may be null
* @return <code>true</code> if the String starts with the prefix, case insensitive, or
* both <code>null</code>
* @since 2.4
*/
public static boolean startsWithIgnoreCase(String str, String prefix) {
return startsWith(str, prefix, true);
}
/**
* <p>Check if a String starts with a specified prefix (optionally case insensitive).</p>
*
* @see java.lang.String#startsWith(String)
* @param str the String to check, may be null
* @param prefix the prefix to find, may be null
* @param ignoreCase inidicates whether the compare should ignore case
* (case insensitive) or not.
* @return <code>true</code> if the String starts with the prefix or
* both <code>null</code>
*/
private static boolean startsWith(String str, String prefix, boolean ignoreCase) {
if (str == null || prefix == null) {
return (str == null && prefix == null);
}
if (prefix.length() > str.length()) {
return false;
}
return str.regionMatches(ignoreCase, 0, prefix, 0, prefix.length());
}
/**
* <p>Check if a String starts with any of an array of specified strings.</p>
*
* <pre>
* StringUtils.startsWithAny(null, null) = false
* StringUtils.startsWithAny(null, new String[] {"abc"}) = false
* StringUtils.startsWithAny("abcxyz", null) = false
* StringUtils.startsWithAny("abcxyz", new String[] {""}) = false
* StringUtils.startsWithAny("abcxyz", new String[] {"abc"}) = true
* StringUtils.startsWithAny("abcxyz", new String[] {null, "xyz", "abc"}) = true
* </pre>
*
* @param string the String to check, may be null
* @param searchStrings the Strings to find, may be null or empty
* @return <code>true</code> if the String starts with any of the the prefixes, case insensitive, or
* both <code>null</code>
* @since 2.5
*/
public static boolean startsWithAny(String string, String[] searchStrings) {
if (isEmpty(string) || ArrayUtils.isEmpty(searchStrings)) {
return false;
}
for (int i = 0; i < searchStrings.length; i++) {
String searchString = searchStrings[i];
if (StringUtils.startsWith(string, searchString)) {
return true;
}
}
return false;
}
// endsWith
//-----------------------------------------------------------------------
/**
* <p>Check if a String ends with a specified suffix.</p>
*
* <p><code>null</code>s are handled without exceptions. Two <code>null</code>
* references are considered to be equal. The comparison is case sensitive.</p>
*
* <pre>
* StringUtils.endsWith(null, null) = true
* StringUtils.endsWith(null, "def") = false
* StringUtils.endsWith("abcdef", null) = false
* StringUtils.endsWith("abcdef", "def") = true
* StringUtils.endsWith("ABCDEF", "def") = false
* StringUtils.endsWith("ABCDEF", "cde") = false
* </pre>
*
* @see java.lang.String#endsWith(String)
* @param str the String to check, may be null
* @param suffix the suffix to find, may be null
* @return <code>true</code> if the String ends with the suffix, case sensitive, or
* both <code>null</code>
* @since 2.4
*/
public static boolean endsWith(String str, String suffix) {
return endsWith(str, suffix, false);
}
/**
* <p>Case insensitive check if a String ends with a specified suffix.</p>
*
* <p><code>null</code>s are handled without exceptions. Two <code>null</code>
* references are considered to be equal. The comparison is case insensitive.</p>
*
* <pre>
* StringUtils.endsWithIgnoreCase(null, null) = true
* StringUtils.endsWithIgnoreCase(null, "def") = false
* StringUtils.endsWithIgnoreCase("abcdef", null) = false
* StringUtils.endsWithIgnoreCase("abcdef", "def") = true
* StringUtils.endsWithIgnoreCase("ABCDEF", "def") = true
* StringUtils.endsWithIgnoreCase("ABCDEF", "cde") = false
* </pre>
*
* @see java.lang.String#endsWith(String)
* @param str the String to check, may be null
* @param suffix the suffix to find, may be null
* @return <code>true</code> if the String ends with the suffix, case insensitive, or
* both <code>null</code>
* @since 2.4
*/
public static boolean endsWithIgnoreCase(String str, String suffix) {
return endsWith(str, suffix, true);
}
/**
* <p>Check if a String ends with a specified suffix (optionally case insensitive).</p>
*
* @see java.lang.String#endsWith(String)
* @param str the String to check, may be null
* @param suffix the suffix to find, may be null
* @param ignoreCase inidicates whether the compare should ignore case
* (case insensitive) or not.
* @return <code>true</code> if the String starts with the prefix or
* both <code>null</code>
*/
private static boolean endsWith(String str, String suffix, boolean ignoreCase) {
if (str == null || suffix == null) {
return str == null && suffix == null;
}
if (suffix.length() > str.length()) {
return false;
}
int strOffset = str.length() - suffix.length();
return str.regionMatches(ignoreCase, strOffset, suffix, 0, suffix.length());
}
}
|
Moving the startsWithAny method from (String, String[]) to (String, String...)
git-svn-id: bab3daebc4e66440cbcc4aded890e63215874748@931452 13f79535-47bb-0310-9956-ffa450edef68
|
src/main/java/org/apache/commons/lang3/StringUtils.java
|
Moving the startsWithAny method from (String, String[]) to (String, String...)
|
<ide><path>rc/main/java/org/apache/commons/lang3/StringUtils.java
<ide> * both <code>null</code>
<ide> * @since 2.5
<ide> */
<del> public static boolean startsWithAny(String string, String[] searchStrings) {
<add> public static boolean startsWithAny(String string, String... searchStrings) {
<ide> if (isEmpty(string) || ArrayUtils.isEmpty(searchStrings)) {
<ide> return false;
<ide> }
|
|
JavaScript
|
mit
|
cc9d633894ce5ce36af1ee7bc52b484d5aeb4392
| 0 |
stefanpenner/broccoli-funnel,joliss/broccoli-funnel,hjdivad/broccoli-funnel,broccolijs/broccoli-funnel,greyhwndz/broccoli-funnel,tsing80/broccoli-funnel,timmfin/broccoli-funnel
|
'use strict';
var fs = require('fs');
var RSVP = require('rsvp');
var path = require('path');
var rimraf = RSVP.denodeify(require('rimraf'));
var mkdirp = require('mkdirp');
var walkSync = require('walk-sync');
var CoreObject = require('core-object');
var symlinkOrCopy = require('symlink-or-copy');
var generateRandomString = require('./lib/generate-random-string');
function makeDictionary() {
var cache = Object.create(null);
cache['_dict'] = null;
delete cache['_dict'];
return cache;
}
function Funnel(inputTree, options) {
this.inputTree = inputTree;
this._includeFileCache = makeDictionary();
this._destinationPathCache = makeDictionary();
this._tmpDir = path.resolve(path.join(this.tmpRoot, 'funnel-dest_' + generateRandomString(6) + '.tmp'));
var keys = Object.keys(options || {});
for (var i = 0, l = keys.length; i < l; i++) {
var key = keys[i];
this[key] = options[key];
}
this.setupDestPaths();
if (this.files && !Array.isArray(this.files)) {
throw new Error('Invalid files option, it must be an array.');
}
if (this.include && !Array.isArray(this.include)) {
throw new Error('Invalid include option, it must be an array.');
}
if (this.exclude && !Array.isArray(this.exclude)) {
throw new Error('Invalid exclude option, it must be an array.');
}
this._instantiatedStack = (new Error()).stack;
}
Funnel.__proto__ = CoreObject;
Funnel.prototype.constructor = Funnel;
Funnel.prototype.tmpRoot = 'tmp';
Funnel.prototype.setupDestPaths = function() {
this.destDir = this.destDir || '/';
this.destPath = path.join(this._tmpDir, this.destDir);
if (this.destPath[this.destPath.length -1] === '/') {
this.destPath = this.destPath.slice(0, -1);
}
};
Funnel.prototype.shouldLinkRoots = function() {
return !this.files && !this.include && !this.exclude && !this.getDestinationPath;
};
Funnel.prototype.read = function(readTree) {
var inputTree = this.inputTree;
return RSVP.Promise.resolve()
.then(this.cleanup.bind(this))
.then(function() {
return readTree(inputTree);
})
.then(this.handleReadTree.bind(this));
};
Funnel.prototype.handleReadTree = function(inputTreeRoot) {
var inputPath = inputTreeRoot;
if (this.srcDir) {
inputPath = path.join(inputTreeRoot, this.srcDir);
}
if (this.shouldLinkRoots()) {
this._copy(inputPath, this.destPath);
} else {
mkdirp.sync(this._tmpDir);
this.processFilters(inputPath);
}
return this._tmpDir;
};
Funnel.prototype.cleanup = function() {
// must be sync until https://github.com/broccolijs/broccoli/pull/197 lands
if (fs.existsSync(this._tmpDir)) {
return rimraf.sync(this._tmpDir);
}
};
Funnel.prototype.processFilters = function(inputPath) {
var files = walkSync(inputPath);
var relativePath, destRelativePath, fullInputPath, fullOutputPath;
for (var i = 0, l = files.length; i < l; i++) {
relativePath = files[i];
if (this.includeFile(relativePath)) {
fullInputPath = path.join(inputPath, relativePath);
destRelativePath = this.lookupDestinationPath(relativePath);
fullOutputPath = path.join(this.destPath, destRelativePath);
this._copy(fullInputPath, fullOutputPath);
}
}
};
Funnel.prototype.lookupDestinationPath = function(relativePath) {
if (this._destinationPathCache[relativePath] !== undefined) {
return this._destinationPathCache[relativePath];
}
if (this.getDestinationPath) {
return this._destinationPathCache[relativePath] = this.getDestinationPath(relativePath);
}
return this._destinationPathCache[relativePath] = relativePath;
};
Funnel.prototype.includeFile = function(relativePath) {
var includeFileCache = this._includeFileCache;
if (includeFileCache[relativePath] !== undefined) {
return includeFileCache[relativePath];
}
// do not include directories, only files
if (relativePath[relativePath.length - 1] === '/') {
return includeFileCache[relativePath] = false;
}
var i, l;
// Check for specific files listing
if (this.files) {
return includeFileCache[relativePath] = this.files.indexOf(relativePath) > -1;
}
// Check exclude patterns
if (this.exclude) {
for (i = 0, l = this.exclude.length; i < l; i++) {
// An exclude pattern that returns true should be ignored
if (this.exclude[i].test(relativePath) === true) {
return includeFileCache[relativePath] = false;
}
}
}
// Check include patterns
if (this.include && this.include.length > 0) {
for (i = 0, l = this.include.length; i < l; i++) {
// An include pattern that returns true (and wasn't excluded at all)
// should _not_ be ignored
if (this.include[i].test(relativePath) === true) {
return includeFileCache[relativePath] = true;
}
}
// If no include patterns were matched, ignore this file.
return includeFileCache[relativePath] = false;
}
// Otherwise, don't ignore this file
return includeFileCache[relativePath] = true;
};
Funnel.prototype._copy = function(sourcePath, destPath) {
var destDir = path.dirname(destPath);
if (!fs.existsSync(destDir)) {
mkdirp.sync(destDir);
}
symlinkOrCopy.sync(sourcePath, destPath);
};
module.exports = Funnel;
|
index.js
|
'use strict';
var fs = require('fs');
var RSVP = require('rsvp');
var path = require('path');
var rimraf = RSVP.denodeify(require('rimraf'));
var mkdirp = require('mkdirp');
var walkSync = require('walk-sync');
var CoreObject = require('core-object');
var symlinkOrCopy = require('symlink-or-copy');
var generateRandomString = require('./lib/generate-random-string');
function makeDictionary() {
var cache = Object.create(null);
cache['_dict'] = null;
delete cache['_dict'];
return cache;
}
function Funnel(inputTree, options) {
this.inputTree = inputTree;
this._includeFileCache = makeDictionary();
this._destinationPathCache = makeDictionary();
this._tmpDir = path.resolve(path.join(this.tmpRoot, 'funnel-dest_' + generateRandomString(6) + '.tmp'));
var keys = Object.keys(options || {});
for (var i = 0, l = keys.length; i < l; i++) {
var key = keys[i];
this[key] = options[key];
}
this.setupDestPaths();
if (this.files && !Array.isArray(this.files)) {
throw new Error('Invalid files option, it must be an array.');
}
if (this.include && !Array.isArray(this.include)) {
throw new Error('Invalid include option, it must be an array.');
}
if (this.exclude && !Array.isArray(this.exclude)) {
throw new Error('Invalid exclude option, it must be an array.');
}
this._instantiatedStack = (new Error()).stack
}
Funnel.__proto__ = CoreObject;
Funnel.prototype.constructor = Funnel;
Funnel.prototype.tmpRoot = 'tmp';
Funnel.prototype.setupDestPaths = function() {
this.destDir = this.destDir || '/';
this.destPath = path.join(this._tmpDir, this.destDir);
if (this.destPath[this.destPath.length -1] === '/') {
this.destPath = this.destPath.slice(0, -1);
}
};
Funnel.prototype.shouldLinkRoots = function() {
return !this.files && !this.include && !this.exclude && !this.getDestinationPath;
};
Funnel.prototype.read = function(readTree) {
var inputTree = this.inputTree;
return RSVP.Promise.resolve()
.then(this.cleanup.bind(this))
.then(function() {
return readTree(inputTree);
})
.then(this.handleReadTree.bind(this));
};
Funnel.prototype.handleReadTree = function(inputTreeRoot) {
var inputPath = inputTreeRoot;
if (this.srcDir) {
inputPath = path.join(inputTreeRoot, this.srcDir);
}
if (this.shouldLinkRoots()) {
this._copy(inputPath, this.destPath);
} else {
mkdirp.sync(this._tmpDir);
this.processFilters(inputPath);
}
return this._tmpDir;
};
Funnel.prototype.cleanup = function() {
// must be sync until https://github.com/broccolijs/broccoli/pull/197 lands
if (fs.existsSync(this._tmpDir)) {
return rimraf.sync(this._tmpDir);
}
};
Funnel.prototype.processFilters = function(inputPath) {
var files = walkSync(inputPath);
var relativePath, destRelativePath, fullInputPath, fullOutputPath;
for (var i = 0, l = files.length; i < l; i++) {
relativePath = files[i];
if (this.includeFile(relativePath)) {
fullInputPath = path.join(inputPath, relativePath);
destRelativePath = this.lookupDestinationPath(relativePath);
fullOutputPath = path.join(this.destPath, destRelativePath);
this._copy(fullInputPath, fullOutputPath);
}
}
};
Funnel.prototype.lookupDestinationPath = function(relativePath) {
if (this._destinationPathCache[relativePath] !== undefined) {
return this._destinationPathCache[relativePath];
}
if (this.getDestinationPath) {
return this._destinationPathCache[relativePath] = this.getDestinationPath(relativePath);
}
return this._destinationPathCache[relativePath] = relativePath;
};
Funnel.prototype.includeFile = function(relativePath) {
var includeFileCache = this._includeFileCache;
if (includeFileCache[relativePath] !== undefined) {
return includeFileCache[relativePath];
}
// do not include directories, only files
if (relativePath[relativePath.length - 1] === '/') {
return includeFileCache[relativePath] = false;
}
var i, l;
// Check for specific files listing
if (this.files) {
return includeFileCache[relativePath] = this.files.indexOf(relativePath) > -1;
}
// Check exclude patterns
if (this.exclude) {
for (i = 0, l = this.exclude.length; i < l; i++) {
// An exclude pattern that returns true should be ignored
if (this.exclude[i].test(relativePath) === true) {
return includeFileCache[relativePath] = false;
}
}
}
// Check include patterns
if (this.include && this.include.length > 0) {
for (i = 0, l = this.include.length; i < l; i++) {
// An include pattern that returns true (and wasn't excluded at all)
// should _not_ be ignored
if (this.include[i].test(relativePath) === true) {
return includeFileCache[relativePath] = true;
}
}
// If no include patterns were matched, ignore this file.
return includeFileCache[relativePath] = false;
}
// Otherwise, don't ignore this file
return includeFileCache[relativePath] = true;
};
Funnel.prototype._copy = function(sourcePath, destPath) {
var destDir = path.dirname(destPath);
if (!fs.existsSync(destDir)) {
mkdirp.sync(destDir);
}
symlinkOrCopy.sync(sourcePath, destPath);
};
module.exports = Funnel;
|
Fix JSHint error.
|
index.js
|
Fix JSHint error.
|
<ide><path>ndex.js
<ide> throw new Error('Invalid exclude option, it must be an array.');
<ide> }
<ide>
<del> this._instantiatedStack = (new Error()).stack
<add> this._instantiatedStack = (new Error()).stack;
<ide> }
<ide>
<ide> Funnel.__proto__ = CoreObject;
|
|
Java
|
apache-2.0
|
e91b4107887fbd58053bdf34f7f2cb2a1e1915e6
| 0 |
MatthewTamlin/Spyglass
|
package com.matthewtamlin.spyglass.processor.validation;
import com.matthewtamlin.java_utilities.testing.Tested;
import com.matthewtamlin.spyglass.common.annotations.use_annotations.UseNull;
import com.matthewtamlin.spyglass.processor.annotation_retrievers.UseAnnoRetriever;
import com.matthewtamlin.spyglass.processor.code_generation.GetArgumentGenerator;
import com.matthewtamlin.spyglass.processor.core.AnnotationRegistry;
import com.matthewtamlin.spyglass.processor.core.CoreHelpers;
import com.matthewtamlin.spyglass.processor.mirror_helpers.TypeMirrorHelper;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeName;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Elements;
import static com.matthewtamlin.java_utilities.checkers.NullChecker.checkNotNull;
import static javax.lang.model.element.Modifier.PRIVATE;
import static javax.lang.model.element.Modifier.STATIC;
@Tested(testMethod = "automated")
public class Validator {
private final List<Rule> rules = new ArrayList<>();
{
// Check element is a method
rules.add(new Rule() {
@Override
public void checkElement(final Element element) throws ValidationException {
if (element.getKind() != ElementKind.METHOD) {
final String message = "Spyglass annotations must only be applied to methods.";
throw new ValidationException(message);
}
}
});
// Check for multiple handler annotations
rules.add(new Rule() {
@Override
public void checkElement(final Element element) throws ValidationException {
if (countCombinedHandlerAnnotations(element) > 1) {
final String message = "Methods must not have multiple handler annotations.";
throw new ValidationException(message);
}
}
});
// Check for multiple default annotations
rules.add(new Rule() {
@Override
public void checkElement(final Element element) throws ValidationException {
if (countDefaultAnnotations(element) > 1) {
final String message = "Methods must not have multiple default annotations.";
throw new ValidationException(message);
}
}
});
// Check for a default annotation without a handler annotation
rules.add(new Rule() {
@Override
public void checkElement(final Element element) throws ValidationException {
final int handlerCount = countCombinedHandlerAnnotations(element);
final int defaultCount = countDefaultAnnotations(element);
if (handlerCount == 0 && defaultCount == 1) {
final String message = "Methods without handler annotations must not have default annotations.";
throw new ValidationException(message);
}
}
});
// Check for call handlers with defaults
rules.add(new Rule() {
@Override
public void checkElement(final Element element) throws ValidationException {
final int callHandlerCount = countCallHandlerAnnotations(element);
final int defaultCount = countDefaultAnnotations(element);
if (callHandlerCount == 1 && defaultCount == 1) {
final String message = "Methods with handlers annotations that pass no value must not have " +
"default annotations.";
throw new ValidationException(message);
}
}
});
// Check parameter count exceeds 1 minimum for value handlers
rules.add(new Rule() {
@Override
public void checkElement(final Element element) throws ValidationException {
if (countValueHandlerAnnotations(element) == 1) {
final int paramCount = ((ExecutableElement) element).getParameters().size();
if (paramCount < 1) {
final String message = "Methods with handler annotations that pass a value must have at least" +
" one parameter.";
throw new ValidationException(message);
}
}
}
});
// Check for parameters with multiple use annotations
rules.add(new Rule() {
@Override
public void checkElement(final Element element) throws ValidationException {
final Map<Integer, Set<Annotation>> useAnnotations = getUseAnnotations(
(ExecutableElement) element);
for (final Integer paramIndex : useAnnotations.keySet()) {
if (useAnnotations.get(paramIndex).size() > 1) {
final String message = "Parameters must not have multiple use annotations.";
throw new ValidationException(message);
}
}
}
});
// Check correct number of parameters have use annotations (value handlers case)
rules.add(new Rule() {
@Override
public void checkElement(final Element element) throws ValidationException {
if (countValueHandlerAnnotations(element) == 1) {
final int paramCount = ((ExecutableElement) element).getParameters().size();
final int annotatedParamCount = countNonEmptySets(
getUseAnnotations((ExecutableElement) element).values());
if (annotatedParamCount != paramCount - 1) {
final String message = "Methods with handler annotations which pass a value must have use " +
"annotations on every parameter except one.";
throw new ValidationException(message);
}
}
}
});
// Check correct number of parameters have use annotations (call handlers case)
rules.add(new Rule() {
@Override
public void checkElement(final Element element) throws ValidationException {
if (countCallHandlerAnnotations(element) == 1) {
final int paramCount = ((ExecutableElement) element).getParameters().size();
final int annotatedParamCount = countNonEmptySets(
getUseAnnotations((ExecutableElement) element).values());
if (annotatedParamCount != paramCount) {
final String message = "Methods with handler annotations which pass no value must have " +
"use annotations on every parameter.";
throw new ValidationException(message);
}
}
}
});
// Check correct modifiers are applied to annotation methods
rules.add(new Rule() {
@Override
public void checkElement(final Element element) throws ValidationException {
if (element.getModifiers().contains(PRIVATE)) {
throw new ValidationException("Methods with handler annotations must have public, protected, or " +
"default access. Private methods are not compatible with the Spyglass Framework.");
}
}
});
// Check for methods which are members of non-static inner classes (recursively)
rules.add(new Rule() {
@Override
public void checkElement(final Element element) throws ValidationException {
if (!checkParentsRecursively(element)) {
throw new ValidationException("Methods with handler annotations must be accessible from static " +
"context.");
}
}
//TODO need to look into making this method better
private boolean checkParentsRecursively(final Element element) {
final TypeElement parent = (TypeElement) element.getEnclosingElement();
if (parent == null) {
return true;
}
switch (parent.getNestingKind()) {
case TOP_LEVEL:
return true;
case MEMBER:
return parent.getModifiers().contains(STATIC);
case LOCAL:
return false;
case ANONYMOUS:
return false;
}
throw new RuntimeException("Should never get here.");
}
});
// Check that use annotations are compatible with recipient parameter types
rules.add(new Rule() {
@Override
public void checkElement(final Element element) throws ValidationException {
for (final VariableElement parameter : ((ExecutableElement) element).getParameters()) {
if (UseAnnoRetriever.hasAnnotation(parameter)) {
final boolean paramHasUseNullAnno = UseAnnoRetriever
.getAnnotation(parameter)
.getAnnotationType()
.toString()
.equals(UseNull.class.getName());
if (paramHasUseNullAnno) {
checkUseNullCase(parameter);
} else {
checkGeneralCase(parameter);
}
}
}
}
private void checkUseNullCase(final VariableElement parameter) throws ValidationException {
if (typeMirrorHelper.isPrimitive(parameter.asType())) {
throw new ValidationException("UseNull annotations cannot be applied to primitive parameters.");
}
}
private void checkGeneralCase(final VariableElement parameter) throws ValidationException {
final TypeMirror recipientType = parameter.asType();
final AnnotationMirror useAnno = UseAnnoRetriever.getAnnotation(parameter);
final GetArgumentGenerator generator = new GetArgumentGenerator(coreHelpers);
final MethodSpec suppliedMethod = generator.generateFor(useAnno, 0);
final TypeMirror suppliedType = elementUtil
.getTypeElement(suppliedMethod.returnType.toString())
.asType();
if (typeMirrorHelper.isNumber(suppliedType)) {
if (!typeMirrorHelper.isNumber(recipientType) &&
!typeMirrorHelper.isCharacter(recipientType) &&
!typeMirrorHelper.isAssignable(suppliedType, recipientType)) {
throw new ValidationException("A use annotation was applied to a parameter incorrectly.");
}
} else if (typeMirrorHelper.isBoolean(suppliedType)) {
if (!typeMirrorHelper.isBoolean(recipientType) &&
!typeMirrorHelper.isAssignable(suppliedType, recipientType)) {
throw new ValidationException("A use annotation was incorrectly to a parameter incorrectly.");
}
} else {
if (!typeMirrorHelper.isAssignable(suppliedType, recipientType)) {
throw new ValidationException("A use annotation was incorrectly to a parameter incorrectly.");
}
}
}
});
}
private CoreHelpers coreHelpers;
private Elements elementUtil;
private TypeMirrorHelper typeMirrorHelper;
public Validator(final CoreHelpers coreHelpers) {
this.coreHelpers = checkNotNull(coreHelpers, "Argument \'coreHelpers\' cannot be null.");
this.elementUtil = coreHelpers.getElementHelper();
this.typeMirrorHelper = coreHelpers.getTypeMirrorHelper();
}
public void validateElement(final Element element) throws ValidationException {
for (final Rule rule : rules) {
rule.checkElement(element);
}
}
private static int countCallHandlerAnnotations(final Element e) {
int count = 0;
for (final Class<? extends Annotation> annotation : AnnotationRegistry.CALL_HANDLER_ANNOS) {
if (e.getAnnotation(annotation) != null) {
count++;
}
}
return count;
}
private static int countValueHandlerAnnotations(final Element e) {
int count = 0;
for (final Class<? extends Annotation> annotation : AnnotationRegistry.VALUE_HANDLER_ANNOS) {
if (e.getAnnotation(annotation) != null) {
count++;
}
}
return count;
}
private static int countCombinedHandlerAnnotations(final Element e) {
return countCallHandlerAnnotations(e) + countValueHandlerAnnotations(e);
}
private static int countDefaultAnnotations(final Element e) {
int count = 0;
for (final Class<? extends Annotation> annotation : AnnotationRegistry.DEFAULT_ANNOS) {
if (e.getAnnotation(annotation) != null) {
count++;
}
}
return count;
}
private static Map<Integer, Set<Annotation>> getUseAnnotations(
final ExecutableElement element) {
final Map<Integer, Set<Annotation>> useAnnotations = new HashMap<>();
final List<? extends VariableElement> params = element.getParameters();
for (int i = 0; i < params.size(); i++) {
useAnnotations.put(i, new HashSet<Annotation>());
for (final Class<? extends Annotation> annotation : AnnotationRegistry.USE_ANNOS) {
final Annotation foundAnnotation = params.get(i).getAnnotation(annotation);
if (foundAnnotation != null) {
useAnnotations.get(i).add(foundAnnotation);
}
}
}
return useAnnotations;
}
private static int countNonEmptySets(final Collection<? extends Set> collection) {
int count = 0;
for (final Set<?> s : collection) {
if (!s.isEmpty()) {
count++;
}
}
return count;
}
private interface Rule {
public void checkElement(Element element) throws ValidationException;
}
}
|
processor/src/main/java/com/matthewtamlin/spyglass/processor/validation/Validator.java
|
package com.matthewtamlin.spyglass.processor.validation;
import com.matthewtamlin.java_utilities.testing.Tested;
import com.matthewtamlin.spyglass.processor.core.AnnotationRegistry;
import com.matthewtamlin.spyglass.processor.core.CoreHelpers;
import com.matthewtamlin.spyglass.processor.mirror_helpers.TypeMirrorHelper;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import static com.matthewtamlin.java_utilities.checkers.NullChecker.checkNotNull;
import static javax.lang.model.element.Modifier.PRIVATE;
import static javax.lang.model.element.Modifier.STATIC;
@Tested(testMethod = "automated")
public class Validator {
private final List<Rule> rules = new ArrayList<>();
{
// Check element is a method
rules.add(new Rule() {
@Override
public void checkElement(final Element element) throws ValidationException {
if (element.getKind() != ElementKind.METHOD) {
final String message = "Spyglass annotations must only be applied to methods.";
throw new ValidationException(message);
}
}
});
// Check for multiple handler annotations
rules.add(new Rule() {
@Override
public void checkElement(final Element element) throws ValidationException {
if (countCombinedHandlerAnnotations(element) > 1) {
final String message = "Methods must not have multiple handler annotations.";
throw new ValidationException(message);
}
}
});
// Check for multiple default annotations
rules.add(new Rule() {
@Override
public void checkElement(final Element element) throws ValidationException {
if (countDefaultAnnotations(element) > 1) {
final String message = "Methods must not have multiple default annotations.";
throw new ValidationException(message);
}
}
});
// Check for a default annotation without a handler annotation
rules.add(new Rule() {
@Override
public void checkElement(final Element element) throws ValidationException {
final int handlerCount = countCombinedHandlerAnnotations(element);
final int defaultCount = countDefaultAnnotations(element);
if (handlerCount == 0 && defaultCount == 1) {
final String message = "Methods without handler annotations must not have default annotations.";
throw new ValidationException(message);
}
}
});
// Check for call handlers with defaults
rules.add(new Rule() {
@Override
public void checkElement(final Element element) throws ValidationException {
final int callHandlerCount = countCallHandlerAnnotations(element);
final int defaultCount = countDefaultAnnotations(element);
if (callHandlerCount == 1 && defaultCount == 1) {
final String message = "Methods with handlers annotations that pass no value must not have " +
"default annotations.";
throw new ValidationException(message);
}
}
});
// Check parameter count exceeds 1 minimum for value handlers
rules.add(new Rule() {
@Override
public void checkElement(final Element element) throws ValidationException {
if (countValueHandlerAnnotations(element) == 1) {
final int paramCount = ((ExecutableElement) element).getParameters().size();
if (paramCount < 1) {
final String message = "Methods with handler annotations that pass a value must have at least" +
" one parameter.";
throw new ValidationException(message);
}
}
}
});
// Check for parameters with multiple use annotations
rules.add(new Rule() {
@Override
public void checkElement(final Element element) throws ValidationException {
final Map<Integer, Set<Annotation>> useAnnotations = getUseAnnotations(
(ExecutableElement) element);
for (final Integer paramIndex : useAnnotations.keySet()) {
if (useAnnotations.get(paramIndex).size() > 1) {
final String message = "Parameters must not have multiple use annotations.";
throw new ValidationException(message);
}
}
}
});
// Check correct number of parameters have use annotations (value handlers case)
rules.add(new Rule() {
@Override
public void checkElement(final Element element) throws ValidationException {
if (countValueHandlerAnnotations(element) == 1) {
final int paramCount = ((ExecutableElement) element).getParameters().size();
final int annotatedParamCount = countNonEmptySets(
getUseAnnotations((ExecutableElement) element).values());
if (annotatedParamCount != paramCount - 1) {
final String message = "Methods with handler annotations which pass a value must have use " +
"annotations on every parameter except one.";
throw new ValidationException(message);
}
}
}
});
// Check correct number of parameters have use annotations (call handlers case)
rules.add(new Rule() {
@Override
public void checkElement(final Element element) throws ValidationException {
if (countCallHandlerAnnotations(element) == 1) {
final int paramCount = ((ExecutableElement) element).getParameters().size();
final int annotatedParamCount = countNonEmptySets(
getUseAnnotations((ExecutableElement) element).values());
if (annotatedParamCount != paramCount) {
final String message = "Methods with handler annotations which pass no value must have " +
"use annotations on every parameter.";
throw new ValidationException(message);
}
}
}
});
// Check correct modifiers are applied to annotation methods
rules.add(new Rule() {
@Override
public void checkElement(final Element element) throws ValidationException {
if (element.getModifiers().contains(PRIVATE)) {
throw new ValidationException("Methods with handler annotations must have public, protected, or " +
"default access. Private methods are not compatible with the Spyglass Framework.");
}
}
});
// Check for methods which are members of non-static inner classes (recursively)
rules.add(new Rule() {
@Override
public void checkElement(final Element element) throws ValidationException {
if (!checkParentsRecursively(element)) {
throw new ValidationException("Methods with handler annotations must be accessible from static " +
"context.");
}
}
//TODO need to look into making this method better
private boolean checkParentsRecursively(final Element element) {
final TypeElement parent = (TypeElement) element.getEnclosingElement();
if (parent == null) {
return true;
}
switch (parent.getNestingKind()) {
case TOP_LEVEL:
return true;
case MEMBER:
return parent.getModifiers().contains(STATIC);
case LOCAL:
return false;
case ANONYMOUS:
return false;
}
throw new RuntimeException("Should never get here.");
}
});
}
private TypeMirrorHelper typeMirrorHelper;
public Validator(final CoreHelpers coreHelpers) {
checkNotNull(coreHelpers, "Argument \'coreHelpers\' cannot be null.");
typeMirrorHelper = coreHelpers.getTypeMirrorHelper();
}
public void validateElement(final Element element) throws ValidationException {
for (final Rule rule : rules) {
rule.checkElement(element);
}
}
private static int countCallHandlerAnnotations(final Element e) {
int count = 0;
for (final Class<? extends Annotation> annotation : AnnotationRegistry.CALL_HANDLER_ANNOS) {
if (e.getAnnotation(annotation) != null) {
count++;
}
}
return count;
}
private static int countValueHandlerAnnotations(final Element e) {
int count = 0;
for (final Class<? extends Annotation> annotation : AnnotationRegistry.VALUE_HANDLER_ANNOS) {
if (e.getAnnotation(annotation) != null) {
count++;
}
}
return count;
}
private static int countCombinedHandlerAnnotations(final Element e) {
return countCallHandlerAnnotations(e) + countValueHandlerAnnotations(e);
}
private static int countDefaultAnnotations(final Element e) {
int count = 0;
for (final Class<? extends Annotation> annotation : AnnotationRegistry.DEFAULT_ANNOS) {
if (e.getAnnotation(annotation) != null) {
count++;
}
}
return count;
}
private static Map<Integer, Set<Annotation>> getUseAnnotations(
final ExecutableElement element) {
final Map<Integer, Set<Annotation>> useAnnotations = new HashMap<>();
final List<? extends VariableElement> params = element.getParameters();
for (int i = 0; i < params.size(); i++) {
useAnnotations.put(i, new HashSet<Annotation>());
for (final Class<? extends Annotation> annotation : AnnotationRegistry.USE_ANNOS) {
final Annotation foundAnnotation = params.get(i).getAnnotation(annotation);
if (foundAnnotation != null) {
useAnnotations.get(i).add(foundAnnotation);
}
}
}
return useAnnotations;
}
private static int countNonEmptySets(final Collection<? extends Set> collection) {
int count = 0;
for (final Set<?> s : collection) {
if (!s.isEmpty()) {
count++;
}
}
return count;
}
private interface Rule {
public void checkElement(Element element) throws ValidationException;
}
}
|
Added validation logic for use annotations
|
processor/src/main/java/com/matthewtamlin/spyglass/processor/validation/Validator.java
|
Added validation logic for use annotations
|
<ide><path>rocessor/src/main/java/com/matthewtamlin/spyglass/processor/validation/Validator.java
<ide>
<ide>
<ide> import com.matthewtamlin.java_utilities.testing.Tested;
<add>import com.matthewtamlin.spyglass.common.annotations.use_annotations.UseNull;
<add>import com.matthewtamlin.spyglass.processor.annotation_retrievers.UseAnnoRetriever;
<add>import com.matthewtamlin.spyglass.processor.code_generation.GetArgumentGenerator;
<ide> import com.matthewtamlin.spyglass.processor.core.AnnotationRegistry;
<ide> import com.matthewtamlin.spyglass.processor.core.CoreHelpers;
<ide> import com.matthewtamlin.spyglass.processor.mirror_helpers.TypeMirrorHelper;
<add>import com.squareup.javapoet.MethodSpec;
<add>import com.squareup.javapoet.TypeName;
<ide>
<ide> import java.lang.annotation.Annotation;
<ide> import java.util.ArrayList;
<ide> import java.util.Map;
<ide> import java.util.Set;
<ide>
<add>import javax.lang.model.element.AnnotationMirror;
<ide> import javax.lang.model.element.Element;
<ide> import javax.lang.model.element.ElementKind;
<ide> import javax.lang.model.element.ExecutableElement;
<ide> import javax.lang.model.element.TypeElement;
<ide> import javax.lang.model.element.VariableElement;
<add>import javax.lang.model.type.TypeMirror;
<add>import javax.lang.model.util.Elements;
<ide>
<ide> import static com.matthewtamlin.java_utilities.checkers.NullChecker.checkNotNull;
<ide> import static javax.lang.model.element.Modifier.PRIVATE;
<ide> throw new RuntimeException("Should never get here.");
<ide> }
<ide> });
<del> }
<add>
<add> // Check that use annotations are compatible with recipient parameter types
<add> rules.add(new Rule() {
<add> @Override
<add> public void checkElement(final Element element) throws ValidationException {
<add> for (final VariableElement parameter : ((ExecutableElement) element).getParameters()) {
<add> if (UseAnnoRetriever.hasAnnotation(parameter)) {
<add> final boolean paramHasUseNullAnno = UseAnnoRetriever
<add> .getAnnotation(parameter)
<add> .getAnnotationType()
<add> .toString()
<add> .equals(UseNull.class.getName());
<add>
<add> if (paramHasUseNullAnno) {
<add> checkUseNullCase(parameter);
<add> } else {
<add> checkGeneralCase(parameter);
<add> }
<add> }
<add> }
<add> }
<add>
<add> private void checkUseNullCase(final VariableElement parameter) throws ValidationException {
<add> if (typeMirrorHelper.isPrimitive(parameter.asType())) {
<add> throw new ValidationException("UseNull annotations cannot be applied to primitive parameters.");
<add> }
<add> }
<add>
<add> private void checkGeneralCase(final VariableElement parameter) throws ValidationException {
<add> final TypeMirror recipientType = parameter.asType();
<add>
<add> final AnnotationMirror useAnno = UseAnnoRetriever.getAnnotation(parameter);
<add>
<add> final GetArgumentGenerator generator = new GetArgumentGenerator(coreHelpers);
<add> final MethodSpec suppliedMethod = generator.generateFor(useAnno, 0);
<add>
<add> final TypeMirror suppliedType = elementUtil
<add> .getTypeElement(suppliedMethod.returnType.toString())
<add> .asType();
<add>
<add> if (typeMirrorHelper.isNumber(suppliedType)) {
<add> if (!typeMirrorHelper.isNumber(recipientType) &&
<add> !typeMirrorHelper.isCharacter(recipientType) &&
<add> !typeMirrorHelper.isAssignable(suppliedType, recipientType)) {
<add>
<add> throw new ValidationException("A use annotation was applied to a parameter incorrectly.");
<add> }
<add> } else if (typeMirrorHelper.isBoolean(suppliedType)) {
<add> if (!typeMirrorHelper.isBoolean(recipientType) &&
<add> !typeMirrorHelper.isAssignable(suppliedType, recipientType)) {
<add>
<add> throw new ValidationException("A use annotation was incorrectly to a parameter incorrectly.");
<add> }
<add> } else {
<add> if (!typeMirrorHelper.isAssignable(suppliedType, recipientType)) {
<add> throw new ValidationException("A use annotation was incorrectly to a parameter incorrectly.");
<add> }
<add> }
<add> }
<add> });
<add> }
<add>
<add> private CoreHelpers coreHelpers;
<add>
<add> private Elements elementUtil;
<ide>
<ide> private TypeMirrorHelper typeMirrorHelper;
<ide>
<ide> public Validator(final CoreHelpers coreHelpers) {
<del> checkNotNull(coreHelpers, "Argument \'coreHelpers\' cannot be null.");
<del>
<del> typeMirrorHelper = coreHelpers.getTypeMirrorHelper();
<add> this.coreHelpers = checkNotNull(coreHelpers, "Argument \'coreHelpers\' cannot be null.");
<add> this.elementUtil = coreHelpers.getElementHelper();
<add> this.typeMirrorHelper = coreHelpers.getTypeMirrorHelper();
<ide> }
<ide>
<ide> public void validateElement(final Element element) throws ValidationException {
|
|
Java
|
apache-2.0
|
11a0c43f25904a4e9bf21a1cb02726454c81cadd
| 0 |
Ongawa/cloracion
|
package org.ongawa.peru.chlorination.persistence.db;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.jooq.DSLContext;
import org.jooq.Record;
import org.jooq.Result;
import org.jooq.SQLDialect;
import org.jooq.impl.DSL;
import org.ongawa.peru.chlorination.persistence.db.jooq.tables.Subbasin;
import org.ongawa.peru.chlorination.persistence.elements.SubBasin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DataSource {
/**
* @author Kiko
*/
private static DataSource datasource;
private static Logger log;
static{
datasource = null;
log = LoggerFactory.getLogger(DataSource.class);
}
public static DataSource getInstance(){
if(datasource == null)
datasource = new DataSource();
return datasource;
}
private Connection connection;
private DataSource(){
}
private SubBasin readSubBasin(Record record){
SubBasin subBasin = new SubBasin(record.getValue(Subbasin.SUBBASIN.IDSUBBASIN), record.getValue(Subbasin.SUBBASIN.NAME));
return subBasin;
}
public List<SubBasin> getSubBasins(){
List<SubBasin> subBasins = null;
try {
this.connection = ConnectionsPool.getInstance().getConnection();
subBasins = new ArrayList<SubBasin>();
DSLContext create = DSL.using(this.connection, SQLDialect.H2);
Result<Record> result = create.select().from(Subbasin.SUBBASIN).fetch();
SubBasin subBasin;
for(Record record : result){
subBasin = this.readSubBasin(record);
subBasins.add(subBasin);
}
this.connection.close();
} catch (SQLException e) {
log.warn(e.toString());
}
return subBasins;
}
public SubBasin getSubBasin(int idSubBasin){
SubBasin subBasin = null;
try {
this.connection = ConnectionsPool.getInstance().getConnection();
DSLContext create = DSL.using(this.connection, SQLDialect.H2);
Result<Record> result = create.select().from(Subbasin.SUBBASIN).where(Subbasin.SUBBASIN.IDSUBBASIN.eq(idSubBasin)).limit(1).fetch();
for(Record record : result){
subBasin = this.readSubBasin(record);
break;
}
} catch (SQLException e) {
log.warn(e.toString());
}
return subBasin;
}
public SubBasin getSubBasin(String name){
SubBasin subBasin = null;
try {
this.connection = ConnectionsPool.getInstance().getConnection();
DSLContext create = DSL.using(this.connection, SQLDialect.H2);
Result<Record> result = create.select().from(Subbasin.SUBBASIN).where(Subbasin.SUBBASIN.NAME.eq(name)).limit(1).fetch();
for(Record record : result){
subBasin = this.readSubBasin(record);
break;
}
} catch (SQLException e) {
log.warn(e.toString());
}
return subBasin;
}
}
|
src/main/java/org/ongawa/peru/chlorination/persistence/db/DataSource.java
|
package org.ongawa.peru.chlorination.persistence.db;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.jooq.DSLContext;
import org.jooq.Record;
import org.jooq.Result;
import org.jooq.SQLDialect;
import org.jooq.impl.DSL;
import org.ongawa.peru.chlorination.persistence.db.jooq.tables.Subbasin;
import org.ongawa.peru.chlorination.persistence.elements.SubBasin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DataSource {
private static DataSource datasource;
private static Logger log;
static{
datasource = null;
log = LoggerFactory.getLogger(DataSource.class);
}
public static DataSource getInstance(){
if(datasource == null)
datasource = new DataSource();
return datasource;
}
private Connection connection;
private DataSource(){
}
private SubBasin readSubBasin(Record record){
SubBasin subBasin = new SubBasin(record.getValue(Subbasin.SUBBASIN.IDSUBBASIN), record.getValue(Subbasin.SUBBASIN.NAME));
return subBasin;
}
public List<SubBasin> getSubBasins(){
List<SubBasin> subBasins = null;
try {
this.connection = ConnectionsPool.getInstance().getConnection();
subBasins = new ArrayList<SubBasin>();
DSLContext create = DSL.using(this.connection, SQLDialect.H2);
Result<Record> result = create.select().from(Subbasin.SUBBASIN).fetch();
SubBasin subBasin;
for(Record record : result){
subBasin = this.readSubBasin(record);
subBasins.add(subBasin);
}
this.connection.close();
} catch (SQLException e) {
log.warn(e.toString());
}
return subBasins;
}
public SubBasin getSubBasin(int idSubBasin){
SubBasin subBasin = null;
try {
this.connection = ConnectionsPool.getInstance().getConnection();
DSLContext create = DSL.using(this.connection, SQLDialect.H2);
Result<Record> result = create.select().from(Subbasin.SUBBASIN).where(Subbasin.SUBBASIN.IDSUBBASIN.eq(idSubBasin)).limit(1).fetch();
for(Record record : result){
subBasin = this.readSubBasin(record);
break;
}
} catch (SQLException e) {
log.warn(e.toString());
}
return subBasin;
}
public SubBasin getSubBasin(String name){
SubBasin subBasin = null;
try {
this.connection = ConnectionsPool.getInstance().getConnection();
DSLContext create = DSL.using(this.connection, SQLDialect.H2);
Result<Record> result = create.select().from(Subbasin.SUBBASIN).where(Subbasin.SUBBASIN.NAME.eq(name)).limit(1).fetch();
for(Record record : result){
subBasin = this.readSubBasin(record);
break;
}
} catch (SQLException e) {
log.warn(e.toString());
}
return subBasin;
}
}
|
Update DataSource.java
|
src/main/java/org/ongawa/peru/chlorination/persistence/db/DataSource.java
|
Update DataSource.java
|
<ide><path>rc/main/java/org/ongawa/peru/chlorination/persistence/db/DataSource.java
<ide> import org.slf4j.LoggerFactory;
<ide>
<ide> public class DataSource {
<add> /**
<add> * @author Kiko
<add> */
<ide>
<ide> private static DataSource datasource;
<ide> private static Logger log;
|
|
Java
|
mit
|
9fdaa4bc87c7c08cf1e0b68f44dda9782c39559f
| 0 |
adrenalinee/sample,adrenalinee/sample
|
package com.malibu.sample.springSecurity.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.malibu.sample.springSecurity.entity.User;
import com.malibu.sample.springSecurity.repository.UserRepository;
@Service
public class UserService {
@Autowired
UserRepository userRepository;
@Transactional(readOnly=true)
public Iterable<User> getAll() {
return userRepository.findAll();
}
@Transactional(readOnly=true)
public User get(String userId) {
return userRepository.findOne(userId);
}
}
|
sample-spring-security/src/main/java/com/malibu/sample/springSecurity/service/UserService.java
|
package com.malibu.sample.springSecurity.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.malibu.sample.springSecurity.entity.User;
import com.malibu.sample.springSecurity.repository.UserRepository;
@Service
public class UserService {
@Autowired
UserRepository userRepository;
@Transactional(readOnly=true)
public Iterable<User> getAll() {
return userRepository.findAll();
}
@Transactional
public User get(String userId) {
return userRepository.findOne(userId);
}
}
|
Update UserService.java
|
sample-spring-security/src/main/java/com/malibu/sample/springSecurity/service/UserService.java
|
Update UserService.java
|
<ide><path>ample-spring-security/src/main/java/com/malibu/sample/springSecurity/service/UserService.java
<ide> return userRepository.findAll();
<ide> }
<ide>
<del> @Transactional
<add> @Transactional(readOnly=true)
<ide> public User get(String userId) {
<ide> return userRepository.findOne(userId);
<ide> }
|
|
Java
|
apache-2.0
|
d37cf57635f5e266d253172d059dcd7397a91567
| 0 |
google/data-transfer-project,google/data-transfer-project,google/data-transfer-project,google/data-transfer-project,google/data-transfer-project
|
/*
* Copyright 2018 The Data Transfer Project Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dataportabilityproject.datatransfer.flickr.photos;
import com.flickr4java.flickr.Flickr;
import com.flickr4java.flickr.FlickrException;
import com.flickr4java.flickr.REST;
import com.flickr4java.flickr.RequestContext;
import com.flickr4java.flickr.auth.Auth;
import com.flickr4java.flickr.photosets.Photoset;
import com.flickr4java.flickr.photosets.PhotosetsInterface;
import com.flickr4java.flickr.uploader.UploadMetaData;
import com.flickr4java.flickr.uploader.Uploader;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collection;
import java.util.UUID;
import org.dataportabilityproject.spi.cloud.storage.JobStore;
import org.dataportabilityproject.spi.transfer.provider.ImportResult;
import org.dataportabilityproject.spi.transfer.provider.ImportResult.ResultType;
import org.dataportabilityproject.spi.transfer.provider.Importer;
import org.dataportabilityproject.spi.transfer.types.TempPhotosData;
import org.dataportabilityproject.types.transfer.auth.AppCredentials;
import org.dataportabilityproject.types.transfer.auth.AuthData;
import org.dataportabilityproject.types.transfer.models.photos.PhotoAlbum;
import org.dataportabilityproject.types.transfer.models.photos.PhotoModel;
import org.dataportabilityproject.types.transfer.models.photos.PhotosContainerResource;
public class FlickrPhotosImporter implements Importer<AuthData, PhotosContainerResource> {
@VisibleForTesting static final String COPY_PREFIX = "Copy of - ";
@VisibleForTesting static final String DEFAULT_ALBUM = "Default";
private final JobStore jobStore;
private final Flickr flickr;
private final Uploader uploader;
private final ImageStreamProvider imageStreamProvider;
private final PhotosetsInterface photosetsInterface;
public FlickrPhotosImporter(AppCredentials appCredentials, JobStore jobStore) {
this.jobStore = jobStore;
this.flickr = new Flickr(appCredentials.getKey(), appCredentials.getSecret(), new REST());
this.uploader = flickr.getUploader();
this.imageStreamProvider = new ImageStreamProvider();
this.photosetsInterface = flickr.getPhotosetsInterface();
}
@VisibleForTesting
FlickrPhotosImporter(Flickr flickr, JobStore jobstore, ImageStreamProvider imageStreamProvider) {
this.flickr = flickr;
this.imageStreamProvider = imageStreamProvider;
this.jobStore = jobstore;
this.uploader = flickr.getUploader();
this.photosetsInterface = flickr.getPhotosetsInterface();
}
@Override
public ImportResult importItem(UUID jobId, AuthData authData, PhotosContainerResource data) {
Auth auth;
try {
auth = FlickrUtils.getAuth(authData, flickr);
} catch (FlickrException e) {
return new ImportResult(
ImportResult.ResultType.ERROR, "Error authorizing Flickr Auth: " + e.getErrorMessage());
}
RequestContext.getRequestContext().setAuth(auth);
TempPhotosData tempPhotosData = jobStore.findData(TempPhotosData.class, jobId);
if (tempPhotosData == null) {
tempPhotosData = new TempPhotosData(jobId);
jobStore.create(jobId, tempPhotosData);
}
Preconditions.checkArgument(
data.getAlbums() != null || data.getPhotos() != null,
"" + "Error: There is no data to import");
if (data.getAlbums() != null) {
importAlbums(data.getAlbums(), tempPhotosData);
jobStore.update(jobId, tempPhotosData);
}
if (data.getPhotos() != null) {
for (PhotoModel photo : data.getPhotos()) {
try {
importSinglePhoto(jobId, photo);
} catch (FlickrException | IOException e) {
return new ImportResult(ResultType.ERROR, "Error importing photo " + e.getMessage());
}
}
}
return new ImportResult(ImportResult.ResultType.OK);
}
// Store any album data in the cache because Flickr only allows you to create an album with a
// photo in it, so we have to wait for the first photo to create the album
private void importAlbums(Collection<PhotoAlbum> albums, TempPhotosData tempPhotosData) {
for (PhotoAlbum album : albums) {
tempPhotosData.addTempAlbumMapping(album.getId(), album);
}
}
private void importSinglePhoto(UUID id, PhotoModel photo) throws FlickrException, IOException {
String photoId = uploadPhoto(photo);
String oldAlbumId = photo.getAlbumId();
// If the photo wasn't associated with an album, we don't have to do anything else, since we've
// already uploaded it above. This will mean it lives in the user's cameraroll and not in an album.
// If the uploadPhoto() call fails above, an exception will be thrown, so we don't have to worry
// about the photo not being uploaded here.
if (Strings.isNullOrEmpty(oldAlbumId)) {
return;
}
TempPhotosData tempData = jobStore.findData(TempPhotosData.class, id);
String newAlbumId = tempData.lookupNewAlbumId(oldAlbumId);
if (Strings.isNullOrEmpty(newAlbumId)) {
// This means that we havent created the new album yet, create the photoset
PhotoAlbum album = tempData.lookupTempAlbum(oldAlbumId);
// TODO: handle what happens if the album doesn't exist. One of the things we can do here is
// throw them into a default album or add a finalize() step in the Importer which can deal
// with these (in case the album exists later).
Preconditions.checkArgument(album != null, "Album not found: {}", oldAlbumId);
Photoset photoset =
photosetsInterface.create(COPY_PREFIX + album.getName(), album.getDescription(), photoId);
// Update the temp mapping to reflect that we've created the album
tempData.addAlbumId(oldAlbumId, photoset.getId());
tempData.removeTempPhotoAlbum(oldAlbumId);
} else {
// We've already created the album this photo belongs in, simply add it to the new album
photosetsInterface.addPhoto(newAlbumId, photoId);
}
jobStore.update(id, tempData);
}
private String uploadPhoto(PhotoModel photo) throws IOException, FlickrException {
BufferedInputStream inStream = imageStreamProvider.get(photo.getFetchableUrl());
UploadMetaData uploadMetaData =
new UploadMetaData()
.setAsync(false)
.setPublicFlag(false)
.setFriendFlag(false)
.setFamilyFlag(false)
.setTitle(COPY_PREFIX + photo.getTitle())
.setDescription(photo.getDescription());
return uploader.upload(inStream, uploadMetaData);
}
@VisibleForTesting
class ImageStreamProvider {
/**
* Gets an input stream to an image, given its URL. Used by {@link FlickrPhotosImporter} to
* upload the image.
*/
public BufferedInputStream get(String urlStr) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
return new BufferedInputStream(conn.getInputStream());
}
}
}
|
extensions/data-transfer/portability-data-transfer-flickr/src/main/java/org/dataportabilityproject/datatransfer/flickr/photos/FlickrPhotosImporter.java
|
/*
* Copyright 2018 The Data Transfer Project Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dataportabilityproject.datatransfer.flickr.photos;
import com.flickr4java.flickr.Flickr;
import com.flickr4java.flickr.FlickrException;
import com.flickr4java.flickr.REST;
import com.flickr4java.flickr.RequestContext;
import com.flickr4java.flickr.auth.Auth;
import com.flickr4java.flickr.photosets.Photoset;
import com.flickr4java.flickr.photosets.PhotosetsInterface;
import com.flickr4java.flickr.uploader.UploadMetaData;
import com.flickr4java.flickr.uploader.Uploader;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collection;
import java.util.UUID;
import org.dataportabilityproject.spi.cloud.storage.JobStore;
import org.dataportabilityproject.spi.transfer.provider.ImportResult;
import org.dataportabilityproject.spi.transfer.provider.ImportResult.ResultType;
import org.dataportabilityproject.spi.transfer.provider.Importer;
import org.dataportabilityproject.spi.transfer.types.TempPhotosData;
import org.dataportabilityproject.types.transfer.auth.AppCredentials;
import org.dataportabilityproject.types.transfer.auth.AuthData;
import org.dataportabilityproject.types.transfer.models.photos.PhotoAlbum;
import org.dataportabilityproject.types.transfer.models.photos.PhotoModel;
import org.dataportabilityproject.types.transfer.models.photos.PhotosContainerResource;
public class FlickrPhotosImporter implements Importer<AuthData, PhotosContainerResource> {
@VisibleForTesting static final String COPY_PREFIX = "Copy of - ";
@VisibleForTesting static final String DEFAULT_ALBUM = "Default";
private final JobStore jobStore;
private final Flickr flickr;
private final Uploader uploader;
private final ImageStreamProvider imageStreamProvider;
private final PhotosetsInterface photosetsInterface;
public FlickrPhotosImporter(AppCredentials appCredentials, JobStore jobStore) {
this.jobStore = jobStore;
this.flickr = new Flickr(appCredentials.getKey(), appCredentials.getSecret(), new REST());
this.uploader = flickr.getUploader();
this.imageStreamProvider = new ImageStreamProvider();
this.photosetsInterface = flickr.getPhotosetsInterface();
}
@VisibleForTesting
FlickrPhotosImporter(Flickr flickr, JobStore jobstore, ImageStreamProvider imageStreamProvider) {
this.flickr = flickr;
this.imageStreamProvider = imageStreamProvider;
this.jobStore = jobstore;
this.uploader = flickr.getUploader();
this.photosetsInterface = flickr.getPhotosetsInterface();
}
@Override
public ImportResult importItem(UUID jobId, AuthData authData, PhotosContainerResource data) {
Auth auth;
try {
auth = FlickrUtils.getAuth(authData, flickr);
} catch (FlickrException e) {
return new ImportResult(
ImportResult.ResultType.ERROR, "Error authorizing Flickr Auth: " + e.getErrorMessage());
}
RequestContext.getRequestContext().setAuth(auth);
TempPhotosData tempPhotosData = jobStore.findData(TempPhotosData.class, jobId);
if (tempPhotosData == null) {
tempPhotosData = new TempPhotosData(jobId);
jobStore.create(jobId, tempPhotosData);
}
Preconditions.checkArgument(
data.getAlbums() != null || data.getPhotos() != null,
"" + "Error: There is no data to import");
if (data.getAlbums() != null) {
importAlbums(data.getAlbums(), tempPhotosData);
jobStore.update(jobId, tempPhotosData);
}
if (data.getPhotos() != null) {
for (PhotoModel photo : data.getPhotos()) {
try {
importSinglePhoto(jobId, photo);
} catch (FlickrException | IOException e) {
return new ImportResult(ResultType.ERROR, "Error importing photo " + e.getMessage());
}
}
}
return new ImportResult(ImportResult.ResultType.OK);
}
// Store any album data in the cache because Flickr only allows you to create an album with a
// photo in it, so we have to wait for the first photo to create the album
private void importAlbums(Collection<PhotoAlbum> albums, TempPhotosData tempPhotosData) {
for (PhotoAlbum album : albums) {
tempPhotosData.addTempAlbumMapping(album.getId(), album);
}
}
private void importSinglePhoto(UUID id, PhotoModel photo) throws FlickrException, IOException {
String photoId = uploadPhoto(photo);
// TODO: what happens when the photo isn't associated with an album?
String oldAlbumId = photo.getAlbumId();
Preconditions.checkArgument(
!Strings.isNullOrEmpty(oldAlbumId), "Photo is not associated with an AlbumId");
TempPhotosData tempData = jobStore.findData(TempPhotosData.class, id);
String newAlbumId = tempData.lookupNewAlbumId(oldAlbumId);
if (Strings.isNullOrEmpty(newAlbumId)) {
// This means that we havent created the new album yet, create the photoset
PhotoAlbum album = tempData.lookupTempAlbum(oldAlbumId);
// TODO: handle what happens if the album doesn't exit?
Preconditions.checkArgument(album != null, "Album not found: {}", oldAlbumId);
Photoset photoset =
photosetsInterface.create(COPY_PREFIX + album.getName(), album.getDescription(), photoId);
// Update the temp mapping to reflect that we've created the album
tempData.addAlbumId(oldAlbumId, photoset.getId());
tempData.removeTempPhotoAlbum(oldAlbumId);
} else {
// We've already created the album this photo belongs in, simply add it to the new album
photosetsInterface.addPhoto(newAlbumId, photoId);
}
jobStore.update(id, tempData);
}
private String uploadPhoto(PhotoModel photo) throws IOException, FlickrException {
BufferedInputStream inStream = imageStreamProvider.get(photo.getFetchableUrl());
UploadMetaData uploadMetaData =
new UploadMetaData()
.setAsync(false)
.setPublicFlag(false)
.setFriendFlag(false)
.setFamilyFlag(false)
.setTitle(COPY_PREFIX + photo.getTitle())
.setDescription(photo.getDescription());
return uploader.upload(inStream, uploadMetaData);
}
@VisibleForTesting
class ImageStreamProvider {
/**
* Gets an input stream to an image, given its URL. Used by {@link FlickrPhotosImporter} to
* upload the image.
*/
public BufferedInputStream get(String urlStr) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
return new BufferedInputStream(conn.getInputStream());
}
}
}
|
handle case where photo isnt associated to an album at import in flickr (#341)
* handle case where photo isnt associated to an album at import in flickr
|
extensions/data-transfer/portability-data-transfer-flickr/src/main/java/org/dataportabilityproject/datatransfer/flickr/photos/FlickrPhotosImporter.java
|
handle case where photo isnt associated to an album at import in flickr (#341)
|
<ide><path>xtensions/data-transfer/portability-data-transfer-flickr/src/main/java/org/dataportabilityproject/datatransfer/flickr/photos/FlickrPhotosImporter.java
<ide> private void importSinglePhoto(UUID id, PhotoModel photo) throws FlickrException, IOException {
<ide> String photoId = uploadPhoto(photo);
<ide>
<del> // TODO: what happens when the photo isn't associated with an album?
<ide> String oldAlbumId = photo.getAlbumId();
<del> Preconditions.checkArgument(
<del> !Strings.isNullOrEmpty(oldAlbumId), "Photo is not associated with an AlbumId");
<add>
<add> // If the photo wasn't associated with an album, we don't have to do anything else, since we've
<add> // already uploaded it above. This will mean it lives in the user's cameraroll and not in an album.
<add> // If the uploadPhoto() call fails above, an exception will be thrown, so we don't have to worry
<add> // about the photo not being uploaded here.
<add> if (Strings.isNullOrEmpty(oldAlbumId)) {
<add> return;
<add> }
<ide>
<ide> TempPhotosData tempData = jobStore.findData(TempPhotosData.class, id);
<ide> String newAlbumId = tempData.lookupNewAlbumId(oldAlbumId);
<ide> if (Strings.isNullOrEmpty(newAlbumId)) {
<ide> // This means that we havent created the new album yet, create the photoset
<ide> PhotoAlbum album = tempData.lookupTempAlbum(oldAlbumId);
<del> // TODO: handle what happens if the album doesn't exit?
<add>
<add> // TODO: handle what happens if the album doesn't exist. One of the things we can do here is
<add> // throw them into a default album or add a finalize() step in the Importer which can deal
<add> // with these (in case the album exists later).
<ide> Preconditions.checkArgument(album != null, "Album not found: {}", oldAlbumId);
<ide>
<ide> Photoset photoset =
|
|
Java
|
apache-2.0
|
4e9f4a5b415cd0f74af1f3e6ee8a8b0ad28afc78
| 0 |
basheersubei/swift-t,basheersubei/swift-t,JohnPJenkins/swift-t,blue42u/swift-t,JohnPJenkins/swift-t,JohnPJenkins/swift-t,swift-lang/swift-t,blue42u/swift-t,swift-lang/swift-t,JohnPJenkins/swift-t,basheersubei/swift-t,JohnPJenkins/swift-t,basheersubei/swift-t,blue42u/swift-t,swift-lang/swift-t,JohnPJenkins/swift-t,basheersubei/swift-t,basheersubei/swift-t,swift-lang/swift-t,blue42u/swift-t,JohnPJenkins/swift-t,blue42u/swift-t,swift-lang/swift-t,blue42u/swift-t,blue42u/swift-t,swift-lang/swift-t,swift-lang/swift-t,basheersubei/swift-t
|
package exm.stc.ic.tree;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import exm.stc.common.CompilerBackend;
import exm.stc.common.exceptions.STCRuntimeError;
import exm.stc.common.lang.Arg;
import exm.stc.common.lang.Arg.ArgKind;
import exm.stc.common.lang.ExecContext;
import exm.stc.common.lang.Operators.UpdateMode;
import exm.stc.common.lang.RefCounting;
import exm.stc.common.lang.RefCounting.RefCountType;
import exm.stc.common.lang.TaskMode;
import exm.stc.common.lang.Types;
import exm.stc.common.lang.Types.StructType;
import exm.stc.common.lang.Types.Type;
import exm.stc.common.lang.Types.Typed;
import exm.stc.common.lang.Var;
import exm.stc.common.lang.Var.Alloc;
import exm.stc.common.lang.Var.VarCount;
import exm.stc.common.util.Out;
import exm.stc.common.util.Pair;
import exm.stc.common.util.TernaryLogic.Ternary;
import exm.stc.ic.ICUtil;
import exm.stc.ic.aliases.Alias;
import exm.stc.ic.aliases.Alias.AliasTransform;
import exm.stc.ic.componentaliases.Component;
import exm.stc.ic.componentaliases.ComponentAlias;
import exm.stc.ic.opt.valuenumber.ComputedValue.ArgCV;
import exm.stc.ic.opt.valuenumber.ValLoc;
import exm.stc.ic.opt.valuenumber.ValLoc.Closed;
import exm.stc.ic.opt.valuenumber.ValLoc.IsAssign;
import exm.stc.ic.opt.valuenumber.ValLoc.IsValCopy;
import exm.stc.ic.refcount.RefCountsToPlace;
import exm.stc.ic.tree.ICInstructions.Instruction;
import exm.stc.ic.tree.ICTree.Function;
import exm.stc.ic.tree.ICTree.GenInfo;
import exm.stc.ic.tree.ICTree.Program;
import exm.stc.ic.tree.ICTree.RenameMode;
import exm.stc.ic.tree.ICTree.Statement;
/**
* Class to represent builtin Turbine operations with fixed number
* of arguments
*/
public class TurbineOp extends Instruction {
/** Private constructor: use static methods to create */
private TurbineOp(Opcode op, List<Var> outputs, List<Arg> inputs) {
super(op);
this.outputs = initArgList(outputs);
this.inputs = initArgList(inputs);
}
private static Class<? extends Object> SINGLETON_LIST =
Collections.singletonList(null).getClass();
/**
* Initialize args as list that support .set() operation.
* @param args
* @return
*/
private static <T> List<T> initArgList(List<T> args) {
if (args.isEmpty()) {
// Nothing will be mutated in list, so use placeholder
return Collections.emptyList();
} else if (SINGLETON_LIST.isInstance(args)) {
// Avoid known-bad list classes
return new ArrayList<T>(args);
} else {
return args;
}
}
private TurbineOp(Opcode op, Var output, Arg ...inputs) {
this(op, Arrays.asList(output), Arrays.asList(inputs));
}
private TurbineOp(Opcode op, List<Var> outputs, Arg ...inputs) {
this(op, outputs, Arrays.asList(inputs));
}
private List<Var> outputs; /** Variables that are modified by this instruction */
private List<Arg> inputs; /** Variables that are read-only */
@Override
public String toString() {
String result = op.toString().toLowerCase();
for (Var o: outputs) {
result += " " + o.name();
}
for (Arg i: inputs) {
result += " " + i.toString();
}
return result;
}
@Override
public void generate(Logger logger, CompilerBackend gen, GenInfo info) {
// Recreate calls that were used to generate this instruction
switch (op) {
case STORE_SCALAR:
gen.assignScalar(getOutput(0), getInput(0));
break;
case STORE_FILE:
gen.assignFile(getOutput(0), getInput(0), getInput(1));
break;
case STORE_REF:
gen.assignReference(getOutput(0), getInput(0).getVar());
break;
case STORE_ARRAY:
gen.assignArray(getOutput(0), getInput(0));
break;
case STORE_BAG:
gen.assignBag(getOutput(0), getInput(0));
break;
case STORE_STRUCT:
gen.assignStruct(getOutput(0), getInput(0));
break;
case STORE_RECURSIVE:
gen.assignRecursive(getOutput(0), getInput(0));
break;
case ARR_RETRIEVE:
gen.arrayRetrieve(getOutput(0), getInput(0).getVar(),
getInput(1), getInput(2));
break;
case ARR_CREATE_ALIAS:
gen.arrayCreateAlias(getOutput(0), getInput(0).getVar(),
getInput(1));
break;
case ARR_COPY_OUT_IMM:
gen.arrayCopyOutImm(getOutput(0), getInput(0).getVar(), getInput(1));
break;
case ARR_COPY_OUT_FUTURE:
gen.arrayCopyOutFuture(getOutput(0), getInput(0).getVar(),
getInput(1).getVar());
break;
case AREF_COPY_OUT_IMM:
gen.arrayRefCopyOutImm(getOutput(0), getInput(0).getVar(), getInput(1));
break;
case AREF_COPY_OUT_FUTURE:
gen.arrayRefCopyOutFuture(getOutput(0), getInput(0).getVar(),
getInput(1).getVar());
break;
case ARR_CONTAINS:
gen.arrayContains(getOutput(0), getInput(0).getVar(), getInput(1));
break;
case CONTAINER_SIZE:
gen.containerSize(getOutput(0), getInput(0).getVar());
break;
case ARR_LOCAL_CONTAINS:
gen.arrayLocalContains(getOutput(0), getInput(0).getVar(), getInput(1));
break;
case CONTAINER_LOCAL_SIZE:
gen.containerLocalSize(getOutput(0), getInput(0).getVar());
break;
case ARR_STORE:
gen.arrayStore(getOutput(0), getInput(0), getInput(1),
getInputs().size() == 3 ? getInput(2) : Arg.ZERO);
break;
case ARR_STORE_FUTURE:
gen.arrayStoreFuture(getOutput(0), getInput(0).getVar(),
getInput(1),
getInputs().size() == 3 ? getInput(2) : Arg.ONE);
break;
case AREF_STORE_IMM:
gen.arrayRefStoreImm(getOutput(0), getInput(0), getInput(1));
break;
case AREF_STORE_FUTURE:
gen.arrayRefStoreFuture(getOutput(0), getInput(0).getVar(), getInput(1));
break;
case ARR_COPY_IN_IMM:
gen.arrayCopyInImm(getOutput(0), getInput(0), getInput(1).getVar(),
getInputs().size() == 3 ? getInput(2) : Arg.ONE);
break;
case ARR_COPY_IN_FUTURE:
gen.arrayCopyInFuture(getOutput(0), getInput(0).getVar(),
getInput(1).getVar(),
getInputs().size() == 3 ? getInput(2) : Arg.ONE);
break;
case AREF_COPY_IN_IMM:
gen.arrayRefCopyInImm(getOutput(0), getInput(0), getInput(1).getVar());
break;
case AREF_COPY_IN_FUTURE:
gen.arrayRefCopyInFuture(getOutput(0),
getInput(0).getVar(), getInput(1).getVar());
break;
case ARRAY_BUILD: {
assert (getInputs().size() % 2 == 0);
int elemCount = getInputs().size() / 2;
List<Arg> keys = new ArrayList<Arg>(elemCount);
List<Arg> vals = new ArrayList<Arg>(elemCount);
for (int i = 0; i < elemCount; i++) {
keys.add(getInput(i * 2));
vals.add(getInput(i * 2 + 1));
}
gen.arrayBuild(getOutput(0), keys, vals);
break;
}
case ASYNC_COPY: {
gen.asyncCopy(getOutput(0), getInput(0).getVar());
break;
}
case SYNC_COPY: {
gen.syncCopy(getOutput(0), getInput(0).getVar());
break;
}
case BAG_INSERT:
gen.bagInsert(getOutput(0), getInput(0), getInput(1));
break;
case STRUCT_CREATE_ALIAS:
gen.structCreateAlias(getOutput(0), getInput(0).getVar(),
Arg.extractStrings(getInputsTail(1)));
break;
case STRUCT_RETRIEVE_SUB:
gen.structRetrieveSub(getOutput(0), getInput(0).getVar(), Arg.extractStrings(getInputsTail(2)),
getInput(1));
break;
case STRUCT_COPY_OUT:
gen.structCopyOut(getOutput(0), getInput(0).getVar(),
Arg.extractStrings(getInputsTail(1)));
break;
case STRUCTREF_COPY_OUT:
gen.structRefCopyOut(getOutput(0), getInput(0).getVar(),
Arg.extractStrings(getInputsTail(1)));
break;
case STRUCT_INIT_FIELDS: {
// Need to unpack variables from flat input list
Out<List<List<String>>> fieldPaths = new Out<List<List<String>>>();
Out<List<Arg>> fieldVals = new Out<List<Arg>>();
Arg writeDecr = unpackStructInitArgs(fieldPaths, null, fieldVals);
gen.structInitFields(getOutput(0), fieldPaths.val, fieldVals.val, writeDecr);
break;
}
case STRUCT_LOCAL_BUILD: {
Out<List<List<String>>> fieldPaths = new Out<List<List<String>>>();
Out<List<Arg>> fieldVals = new Out<List<Arg>>();
unpackStructBuildArgs(fieldPaths, null, fieldVals);
gen.buildStructLocal(getOutput(0), fieldPaths.val, fieldVals.val);
break;
}
case STRUCT_STORE_SUB:
gen.structStore(getOutput(0), Arg.extractStrings(getInputsTail(1)),
getInput(0));
break;
case STRUCT_COPY_IN:
gen.structCopyIn(getOutput(0), Arg.extractStrings(getInputsTail(1)),
getInput(0).getVar());
break;
case STRUCTREF_STORE_SUB:
gen.structRefStoreSub(getOutput(0), Arg.extractStrings(getInputsTail(1)),
getInput(0));
break;
case STRUCTREF_COPY_IN:
gen.structRefCopyIn(getOutput(0), Arg.extractStrings(getInputsTail(1)),
getInput(0).getVar());
break;
case DEREF_SCALAR:
gen.dereferenceScalar(getOutput(0), getInput(0).getVar());
break;
case DEREF_FILE:
gen.dereferenceFile(getOutput(0), getInput(0).getVar());
break;
case LOAD_REF:
gen.retrieveRef(getOutput(0), getInput(0).getVar(), getInput(1),
getInput(2), getInputs().size() == 4 ? getInput(3) : Arg.ZERO);
break;
case COPY_REF:
gen.makeAlias(getOutput(0), getInput(0).getVar());
break;
case ARR_CREATE_NESTED_FUTURE:
gen.arrayCreateNestedFuture(getOutput(0), getOutput(1),
getInput(0).getVar());
break;
case AREF_CREATE_NESTED_FUTURE:
gen.arrayRefCreateNestedFuture(getOutput(0), getOutput(1),
getInput(0).getVar());
break;
case AREF_CREATE_NESTED_IMM:
gen.arrayRefCreateNestedImm(getOutput(0), getOutput(1), getInput(0));
break;
case ARR_CREATE_NESTED_IMM:
gen.arrayCreateNestedImm(getOutput(0), getOutput(1), getInput(0),
getInput(1), getInput(2));
break;
case ARR_CREATE_BAG:
gen.arrayCreateBag(getOutput(0), getOutput(1), getInput(0),
getInput(1), getInput(2));
break;
case LOAD_SCALAR:
gen.retrieveScalar(getOutput(0), getInput(0).getVar(),
getInputs().size() == 2 ? getInput(1) : Arg.ZERO);
break;
case LOAD_FILE:
gen.retrieveFile(getOutput(0), getInput(0).getVar(),
getInputs().size() == 2 ? getInput(1) : Arg.ZERO);
break;
case LOAD_ARRAY:
gen.retrieveArray(getOutput(0), getInput(0).getVar(),
getInputs().size() == 2 ? getInput(1) : Arg.ZERO);
break;
case LOAD_STRUCT:
gen.retrieveStruct(getOutput(0), getInput(0).getVar(),
getInputs().size() == 2 ? getInput(1) : Arg.ZERO);
break;
case LOAD_BAG:
gen.retrieveBag(getOutput(0), getInput(0).getVar(),
getInputs().size() == 2 ? getInput(1) : Arg.ZERO);
break;
case LOAD_RECURSIVE:
gen.retrieveRecursive(getOutput(0), getInput(0).getVar(),
getInputs().size() == 2 ? getInput(1) : Arg.ZERO);
break;
case FREE_BLOB:
gen.freeBlob(getOutput(0));
break;
case DECR_LOCAL_FILE_REF:
gen.decrLocalFileRef(getInput(0).getVar());
break;
case INIT_UPDATEABLE_FLOAT:
gen.initUpdateable(getOutput(0), getInput(0));
break;
case LATEST_VALUE:
gen.latestValue(getOutput(0), getInput(0).getVar());
break;
case UPDATE_INCR:
gen.update(getOutput(0), UpdateMode.INCR, getInput(0).getVar());
break;
case UPDATE_MIN:
gen.update(getOutput(0), UpdateMode.MIN, getInput(0).getVar());
break;
case UPDATE_SCALE:
gen.update(getOutput(0), UpdateMode.SCALE, getInput(0).getVar());
break;
case UPDATE_INCR_IMM:
gen.updateImm(getOutput(0), UpdateMode.INCR, getInput(0));
break;
case UPDATE_MIN_IMM:
gen.updateImm(getOutput(0), UpdateMode.MIN, getInput(0));
break;
case UPDATE_SCALE_IMM:
gen.updateImm(getOutput(0), UpdateMode.SCALE, getInput(0));
break;
case GET_FILENAME_ALIAS:
gen.getFileNameAlias(getOutput(0), getInput(0).getVar());
break;
case COPY_IN_FILENAME:
gen.copyInFilename(getOutput(0), getInput(0).getVar());
break;
case GET_LOCAL_FILENAME:
gen.getLocalFileName(getOutput(0), getInput(0).getVar());
break;
case IS_MAPPED:
gen.isMapped(getOutput(0), getInput(0).getVar());
break;
case GET_FILENAME_VAL:
gen.getFilenameVal(getOutput(0), getInput(0).getVar());
break;
case SET_FILENAME_VAL:
gen.setFilenameVal(getOutput(0), getInput(0));
break;
case CHOOSE_TMP_FILENAME:
gen.chooseTmpFilename(getOutput(0));
break;
case INIT_LOCAL_OUTPUT_FILE:
gen.initLocalOutputFile(getOutput(0), getInput(0), getInput(1));
break;
case COPY_FILE_CONTENTS:
gen.copyFileContents(getOutput(0), getInput(0).getVar());
break;
case CHECKPOINT_WRITE_ENABLED:
gen.checkpointWriteEnabled(getOutput(0));
break;
case CHECKPOINT_LOOKUP_ENABLED:
gen.checkpointLookupEnabled(getOutput(0));
break;
case WRITE_CHECKPOINT:
gen.writeCheckpoint(getInput(0), getInput(1));
break;
case LOOKUP_CHECKPOINT:
gen.lookupCheckpoint(getOutput(0), getOutput(1), getInput(0));
break;
case PACK_VALUES:
gen.packValues(getOutput(0), getInputs());
break;
case UNPACK_VALUES:
gen.unpackValues(getOutputs(), getInput(0));
break;
case UNPACK_ARRAY_TO_FLAT:
gen.unpackArrayToFlat(getOutput(0), getInput(0));
break;
default:
throw new STCRuntimeError("didn't expect to see op " +
op.toString() + " here");
}
}
/**
* Look up value of array index immediately
* @param dst
* @param arrayVar
* @param arrIx
* @param decrRead
* @return
*/
public static Instruction arrayRetrieve(Var dst, Var arrayVar,
Arg arrIx, Arg decrRead) {
assert(dst.storage() == Alloc.LOCAL || dst.storage() == Alloc.ALIAS);
assert(Types.isArray(arrayVar));
assert(Types.isArrayKeyVal(arrayVar, arrIx));
assert(Types.isElemValType(arrayVar, dst));
assert(decrRead.isImmediateInt());
return new TurbineOp(Opcode.ARR_RETRIEVE,
dst, arrayVar.asArg(), arrIx, decrRead);
}
/**
* Copy out value of array once set
* @param dst
* @param arrayRefVar
* @param arrIx
* @return
*/
public static Instruction arrayRefCopyOutImm(Var dst,
Var arrayRefVar, Arg arrIx) {
assert(Types.isArrayRef(arrayRefVar));
assert(Types.isArrayKeyVal(arrayRefVar, arrIx));
assert(Types.isElemType(arrayRefVar, dst));
assert(!Types.isMutableRef(dst)); // Doesn't acquire write ref
return new TurbineOp(Opcode.AREF_COPY_OUT_IMM,
dst, arrayRefVar.asArg(), arrIx);
}
public static Instruction arrayCreateAlias(Var dst, Var arrayVar,
Arg arrIx) {
assert(Types.isArray(arrayVar));
assert(Types.isArrayKeyVal(arrayVar, arrIx));
assert(Types.isElemType(arrayVar, dst)) : arrayVar + " " + dst;
assert(dst.storage() == Alloc.ALIAS);
return new TurbineOp(Opcode.ARR_CREATE_ALIAS,
dst, arrayVar.asArg(), arrIx);
}
/**
* Copy out value of field from array once set
* @param dst
* @param arrayVar
* @param arrIx
* @return
*/
public static Instruction arrayCopyOutImm(Var dst, Var arrayVar,
Arg arrIx) {
assert(Types.isArray(arrayVar));
assert(Types.isArrayKeyVal(arrayVar, arrIx)) :
arrayVar.type() + " " + arrIx.type();
assert(Types.isElemType(arrayVar, dst)) : arrayVar + " " + dst;
assert(!Types.isMutableRef(dst)) : dst; // Doesn't acquire write ref
return new TurbineOp(Opcode.ARR_COPY_OUT_IMM,
dst, arrayVar.asArg(), arrIx);
}
/**
* Copy out value of field from array once set
* @param dst
* @param arrayVar
* @param indexVar
* @return
*/
public static TurbineOp arrayCopyOutFuture(Var dst, Var arrayVar,
Var indexVar) {
assert(Types.isArray(arrayVar));
assert(Types.isArrayKeyFuture(arrayVar, indexVar));
assert(Types.isElemType(arrayVar, dst));
assert(!Types.isMutableRef(dst)); // Doesn't acquire write ref
return new TurbineOp(Opcode.ARR_COPY_OUT_FUTURE,
dst, arrayVar.asArg(), indexVar.asArg());
}
/**
* Copy out value of field from array once set
* @param dst
* @param arrayRefVar
* @param indexVar
* @return
*/
public static TurbineOp arrayRefCopyOutFuture(Var dst, Var arrayRefVar,
Var indexVar) {
assert(Types.isArrayRef(arrayRefVar));
assert(Types.isArrayKeyFuture(arrayRefVar, indexVar));
assert(Types.isElemType(arrayRefVar, dst));
assert(!Types.isMutableRef(dst)); // Doesn't acquire write ref
return new TurbineOp(Opcode.AREF_COPY_OUT_FUTURE, dst,
arrayRefVar.asArg(), indexVar.asArg());
}
public static Instruction arrayContains(Var out, Var array, Arg ix) {
assert(Types.isBoolVal(out));
assert(Types.isArray(array));
assert(Types.isArrayKeyVal(array, ix));
return new TurbineOp(Opcode.ARR_CONTAINS, out, array.asArg(), ix);
}
public static Instruction containerSize(Var out, Var container) {
assert(Types.isIntVal(out));
assert(Types.isContainer(container));
return new TurbineOp(Opcode.CONTAINER_SIZE, out, container.asArg());
}
public static Instruction arrayLocalContains(Var out, Var array, Arg ix) {
assert(Types.isBoolVal(out));
assert(Types.isArrayLocal(array));
assert(Types.isArrayKeyVal(array, ix));
return new TurbineOp(Opcode.ARR_LOCAL_CONTAINS, out, array.asArg(), ix);
}
public static Instruction containerLocalSize(Var out, Var container) {
assert(Types.isIntVal(out));
assert(Types.isContainerLocal(container));
return new TurbineOp(Opcode.CONTAINER_LOCAL_SIZE, out, container.asArg());
}
public static Instruction arrayStore(Var array,
Arg ix, Arg member) {
assert(Types.isArray(array.type()));
assert(Types.isArrayKeyVal(array, ix));
assert(Types.isElemValType(array, member)) :
member.toStringTyped() + " " + array;
return new TurbineOp(Opcode.ARR_STORE, array, ix, member);
}
public static Instruction arrayStoreFuture(Var array,
Var ix, Arg member) {
assert(Types.isArray(array));
assert(Types.isArrayKeyFuture(array, ix));
assert(Types.isElemValType(array, member));
return new TurbineOp(Opcode.ARR_STORE_FUTURE,
array, ix.asArg(), member);
}
/**
* Store via a mutable array reference
* @param array
* @param ix
* @param member
* @return
*/
public static Instruction arrayRefStoreImm(Var array, Arg ix, Arg member) {
assert(Types.isArrayRef(array, true));
assert(Types.isArrayKeyVal(array, ix));
assert(Types.isElemValType(array, member));
return new TurbineOp(Opcode.AREF_STORE_IMM,
array, ix, member);
}
/**
* Store via a mutable array reference
* @param array
* @param ix
* @param member
* @return
*/
public static Instruction arrayRefStoreFuture(Var array, Var ix, Arg member) {
assert(Types.isArrayRef(array, true));
assert(Types.isArrayKeyFuture(array, ix));
assert(Types.isElemValType(array, member));
return new TurbineOp(Opcode.AREF_STORE_FUTURE,
array, ix.asArg(), member);
}
/**
* Copy a value into an array member
* @param array
* @param ix
* @param member
* @return
*/
public static Instruction arrayCopyInImm(Var array,
Arg ix, Var member) {
assert(Types.isArray(array));
assert(Types.isArrayKeyVal(array, ix));
assert(Types.isElemType(array, member));
return new TurbineOp(Opcode.ARR_COPY_IN_IMM,
array, ix, member.asArg());
}
/**
* Copy a value into an array member
* @param array
* @param ix
* @param member
* @return
*/
public static Instruction arrayCopyInFuture(Var array, Var ix, Var member) {
assert(Types.isArray(array.type()));
assert(Types.isArrayKeyFuture(array, ix));
assert(Types.isElemType(array, member));
return new TurbineOp(Opcode.ARR_COPY_IN_FUTURE, array, ix.asArg(),
member.asArg());
}
/**
* Copy in a value to an array reference
* @param outerArray
* @param array
* @param ix
* @param member
* @return
*/
public static Instruction arrayRefCopyInImm(Var array, Arg ix, Var member) {
assert(Types.isArrayKeyVal(array, ix));
assert(Types.isArrayRef(array, true));
assert(Types.isElemType(array, member));
return new TurbineOp(Opcode.AREF_COPY_IN_IMM,
array, ix, member.asArg());
}
public static Instruction arrayRefCopyInFuture(Var array, Var ix,
Var member) {
assert(Types.isArrayKeyFuture(array, ix));
assert(Types.isArrayRef(array, true));
assert(Types.isElemType(array, member));
return new TurbineOp(Opcode.AREF_COPY_IN_FUTURE,
array, ix.asArg(), member.asArg());
}
/**
* Build an array in one hit.
* @param array
* @param keys key values for array (NOT futures)
* @param vals
*/
public static Instruction arrayBuild(Var array, List<Arg> keys, List<Arg> vals) {
assert(Types.isArray(array.type()));
int elemCount = keys.size();
assert(vals.size() == elemCount);
ArrayList<Arg> inputs = new ArrayList<Arg>(elemCount * 2);
for (int i = 0; i < elemCount; i++) {
Arg key = keys.get(i);
Arg val = vals.get(i);
assert(Types.isArrayKeyVal(array, key));
assert(Types.isElemValType(array, val));
inputs.add(key);
inputs.add(val);
}
return new TurbineOp(Opcode.ARRAY_BUILD, array.asList(), inputs);
}
/**
* Generic async copy instruction for non-local data
*/
public static Instruction asyncCopy(Var dst, Var src) {
assert(src.type().assignableTo(dst.type()));
assert(dst.storage() != Alloc.LOCAL);
return new TurbineOp(Opcode.ASYNC_COPY, dst, src.asArg());
}
/**
* Generic sync copy instruction for non-local data.
* Assumes input data closed
*/
public static Instruction syncCopy(Var dst, Var src) {
assert(src.type().assignableTo(dst.type()));
assert(dst.storage() != Alloc.LOCAL);
return new TurbineOp(Opcode.SYNC_COPY, dst, src.asArg());
}
/**
* Add something to a bag
* @param bag
* @param elem
* @param writersDecr
* @return
*/
public static Instruction bagInsert(Var bag, Arg elem, Arg writersDecr) {
assert(Types.isBag(bag));
assert(Types.isElemValType(bag, elem)) : bag + " " + elem + ":" + elem.type();
assert(writersDecr.isImmediateInt());
return new TurbineOp(Opcode.BAG_INSERT, bag, elem, writersDecr);
}
/**
* Retrieve value of a struct entry
*
* TODO: for case of ref entries, separate op to get writable reference?
* @param dst
* @param structVar
* @param fields
* @param readDecr
* @return
*/
public static Instruction structRetrieveSub(Var dst, Var structVar,
List<String> fields, Arg readDecr) {
assert(Types.isStruct(structVar));
assert(Types.isStructFieldVal(structVar, fields, dst)) :
"(" + structVar.name() + ":" + structVar.type() + ")." + fields
+ " => " + dst;
assert (readDecr.isImmediateInt());
List<Arg> in = new ArrayList<Arg>(fields.size() + 1);
in.add(structVar.asArg());
in.add(readDecr);
for (String field: fields) {
in.add(Arg.createStringLit(field));
}
return new TurbineOp(Opcode.STRUCT_RETRIEVE_SUB, dst.asList(), in);
}
public static Instruction structCreateAlias(Var fieldAlias, Var structVar,
List<String> fields) {
assert(Types.isStruct(structVar));
assert(Types.isStructField(structVar, fields, fieldAlias)):
structVar + " " + fields + " " + fieldAlias;
assert(fieldAlias.storage() == Alloc.ALIAS) : fieldAlias;
List<Arg> in = new ArrayList<Arg>(fields.size() + 1);
in.add(structVar.asArg());
for (String field: fields) {
in.add(Arg.createStringLit(field));
}
return new TurbineOp(Opcode.STRUCT_CREATE_ALIAS, fieldAlias.asList(), in);
}
/**
* Copy out value of field from a struct to a destination variable
* @param dst
* @param struct
* @param fields
* @return
*/
public static Instruction structCopyOut(Var dst, Var struct,
List<String> fields) {
// TODO: support piggybacked refcount ops for this and other struct operations
assert(Types.isStruct(struct));
assert(Types.isStructField(struct, fields, dst));
List<Arg> in = new ArrayList<Arg>(fields.size() + 1);
in.add(struct.asArg());
for (String field: fields) {
in.add(Arg.createStringLit(field));
}
return new TurbineOp(Opcode.STRUCT_COPY_OUT, dst.asList(), in);
}
/**
* Copy out value of field from a struct to a destination variable
* @param dst
* @param struct
* @param fields
* @return
*/
public static Instruction structRefCopyOut(Var dst, Var struct,
List<String> fields) {
assert(Types.isStructRef(struct));
assert(Types.isStructField(struct, fields, dst));
List<Arg> in = new ArrayList<Arg>(fields.size() + 1);
in.add(struct.asArg());
for (String field: fields) {
in.add(Arg.createStringLit(field));
}
return new TurbineOp(Opcode.STRUCTREF_COPY_OUT, dst.asList(), in);
}
/**
* Store directly to a field of a struct
* @param structVar
* @param fields
* @param fieldVal
* @return
*/
public static Instruction structStoreSub(Var structVar,
List<String> fields, Arg fieldVal) {
assert(Types.isStruct(structVar)) : structVar;
assert(Types.isStructFieldVal(structVar, fields, fieldVal));
List<Arg> in = new ArrayList<Arg>(fields.size() + 1);
in.add(fieldVal);
for (String field: fields) {
in.add(Arg.createStringLit(field));
}
return new TurbineOp(Opcode.STRUCT_STORE_SUB, structVar.asList(), in);
}
/**
* Copy a value into a field of a struct
* @param structVar
* @param fields
* @param fieldVar
* @return
*/
public static Instruction structCopyIn(Var structVar,
List<String> fields, Var fieldVar) {
assert(Types.isStruct(structVar));
assert(Types.isStructField(structVar, fields, fieldVar));
List<Arg> in = new ArrayList<Arg>(fields.size() + 1);
for (String field: fields) {
in.add(Arg.createStringLit(field));
}
in.add(fieldVar.asArg());
return new TurbineOp(Opcode.STRUCT_COPY_IN, structVar.asList(), in);
}
public static Instruction structRefStoreSub(Var structVar,
List<String> fields, Arg fieldVal) {
List<Arg> in = new ArrayList<Arg>(fields.size() + 1);
for (String field: fields) {
in.add(Arg.createStringLit(field));
}
in.add(fieldVal);
return new TurbineOp(Opcode.STRUCTREF_STORE_SUB, structVar.asList(), in);
}
/**
* Copy a value into a field of the struct referenced by structRef
* @param structRef
* @param fieldVar
* @return
*/
public static Instruction structRefCopyIn(Var structRef,
List<String> fields, Var fieldVar) {
assert(Types.isStructRef(structRef, true));
assert(Types.isStructField(structRef, fields, fieldVar));
List<Arg> in = new ArrayList<Arg>(fields.size() + 1);
for (String field: fields) {
in.add(Arg.createStringLit(field));
}
in.add(fieldVar.asArg());
return new TurbineOp(Opcode.STRUCTREF_COPY_IN, structRef.asList(), in);
}
/**
* Assign any scalar data type
* @param dst shared scalar
* @param src local scalar value
* @return
*/
public static Instruction assignScalar(Var dst, Arg src) {
assert(Types.isScalarFuture(dst)) : dst;
assert(Types.isScalarValue(src));
assert(src.type().assignableTo(Types.retrievedType(dst)));
return new TurbineOp(Opcode.STORE_SCALAR, dst, src);
}
/**
* Assign a file future from a file value
*
* NOTE: the setFilename parameter is not strictly necessary: at runtime
* we could set the filename conditionally on the file not being
* mapped. However, making it explicit simplifies correct optimisation
* @param dst
* @param src
* @param setFilename if true, set filename, if false assume already
* has filename, just close the file.
* @return
*/
public static Instruction assignFile(Var dst, Arg src, Arg setFilename) {
assert(Types.isFile(dst.type()));
assert(src.isVar());
assert(Types.isFileVal(src.getVar()));
assert(setFilename.isImmediateBool());
if (setFilename.isBoolVal() && setFilename.getBoolLit()) {
// Sanity check that we're not setting mapped file
assert(dst.isMapped() != Ternary.TRUE);
}
return new TurbineOp(Opcode.STORE_FILE, dst, src,
setFilename);
}
/**
* Store array directly from local array representation to shared.
* Does not follow refs, e.g. if it is an array of refs, dst must
* be a local array of refs
* @param dst
* @param src
* @return
*/
public static Instruction assignArray(Var dst, Arg src) {
assert(Types.isArray(dst.type())) : dst;
assert(Types.isArrayLocal(src.type())) : src + " " + src.type();
assert(Types.arrayKeyType(src).assignableTo(Types.arrayKeyType(dst)));
assert(Types.containerElemType(src.type()).assignableTo(
Types.containerElemType(dst)));
return new TurbineOp(Opcode.STORE_ARRAY, dst, src);
}
/**
* Store bag directly from local bag representation to shared.
* Does not follow refs, e.g. if it is a bag of refs, dst must
* be a local bag of refs
* @param dst
* @param src
* @return
*/
public static Instruction assignBag(Var dst, Arg src) {
assert(Types.isBag(dst)) : dst;
assert(Types.isBagLocal(src.type())) : src.type();
assert(Types.containerElemType(src.type()).assignableTo(
Types.containerElemType(dst)));
return new TurbineOp(Opcode.STORE_BAG, dst, src);
}
public static Statement structLocalBuild(Var struct,
List<List<String>> fieldPaths, List<Arg> fieldVals) {
assert(Types.isStructLocal(struct));
List<Arg> inputs = new ArrayList<Arg>();
packFieldData(struct, fieldPaths, fieldVals, inputs);
return new TurbineOp(Opcode.STRUCT_LOCAL_BUILD, struct.asList(), inputs);
}
/**
* Initialize all struct fields that need initialization,
* e.g. references to other data.
* Should be called only once on each struct that needs
* initialization.
* @param struct
* @param fields
* @param writeDecr
*/
public static TurbineOp structInitFields(Var struct,
List<List<String>> fieldPaths, List<Arg> fieldVals, Arg writeDecr) {
assert(Types.isStruct(struct));
assert(writeDecr.isImmediateInt());
List<Arg> inputs = new ArrayList<Arg>();
packFieldData(struct, fieldPaths, fieldVals, inputs);
inputs.add(writeDecr);
return new TurbineOp(Opcode.STRUCT_INIT_FIELDS, struct.asList(), inputs);
}
/**
*
* @param fieldPaths if null, not filled
* @param fieldPathsArgs if null, not filled
* @param fieldVals if null, not filled
* @return writeDecr
*/
public Arg unpackStructInitArgs(Out<List<List<String>>> fieldPaths,
Out<List<List<Arg>>> fieldPathsArgs,
Out<List<Arg>> fieldVals) {
assert(op == Opcode.STRUCT_INIT_FIELDS) : op;
List<Arg> packedFieldData = inputs.subList(0, inputs.size() - 1);
unpackFieldData(packedFieldData, fieldPaths, fieldPathsArgs, fieldVals);
Arg writeDecr = getInput(inputs.size() - 1);
return writeDecr;
}
public void unpackStructBuildArgs(Out<List<List<String>>> fieldPaths,
Out<List<List<Arg>>> fieldPathsArgs,
Out<List<Arg>> fieldVals) {
assert(op == Opcode.STRUCT_LOCAL_BUILD) : op;
List<Arg> packedFieldData = inputs;
unpackFieldData(packedFieldData, fieldPaths, fieldPathsArgs, fieldVals);
}
/**
* Pack info about struct fields into arg list
* @param struct
* @param fieldPaths
* @param fieldVals
* @param result
*/
private static void packFieldData(Typed structType,
List<List<String>> fieldPaths, List<Arg> fieldVals, List<Arg> result) {
assert(fieldPaths.size() == fieldVals.size());
for (int i = 0; i < fieldPaths.size(); i++) {
List<String> fieldPath = fieldPaths.get(i);
Arg fieldVal = fieldVals.get(i);
assert(Types.isStructFieldVal(structType, fieldPath, fieldVal))
: structType + " " + fieldPath + " " + fieldVal.getVar() + "\n"
+ structType.type();
// encode lists with length prefixed
result.add(Arg.createIntLit(fieldPath.size()));
for (String field: fieldPath) {
result.add(Arg.createStringLit(field));
}
result.add(fieldVal);
}
}
private static void unpackFieldData(List<Arg> packedFieldData,
Out<List<List<String>>> fieldPaths, Out<List<List<Arg>>> fieldPathsArgs,
Out<List<Arg>> fieldVals) {
if (fieldPaths != null) {
fieldPaths.val = new ArrayList<List<String>>();
}
if (fieldPathsArgs != null) {
fieldPathsArgs.val = new ArrayList<List<Arg>>();
}
if (fieldVals != null) {
fieldVals.val = new ArrayList<Arg>();
}
int pos = 0;
while (pos < packedFieldData.size()) {
long pathLength = packedFieldData.get(pos).getIntLit();
assert(pathLength > 0 && pathLength <= Integer.MAX_VALUE);
pos++;
List<String> fieldPath = (fieldPaths == null) ? null:
new ArrayList<String>((int)pathLength);
List<Arg> fieldPathArgs = (fieldPathsArgs == null) ? null:
new ArrayList<Arg>((int)pathLength);
for (int i = 0; i < pathLength; i++) {
if (fieldPath != null) {
fieldPath.add(packedFieldData.get(pos).getStringLit());
}
if (fieldPathArgs != null) {
fieldPathArgs.add(packedFieldData.get(pos));
}
pos++;
}
Arg fieldVal = packedFieldData.get(pos);
pos++;
if (fieldPaths != null) {
fieldPaths.val.add(fieldPath);
}
if (fieldPathsArgs != null) {
fieldPathsArgs.val.add(fieldPathArgs);
}
if (fieldVals != null) {
fieldVals.val.add(fieldVal);
}
}
}
/**
* Store struct directly from local struct representation to shared.
* Does not follow refs.
* @param dst
* @param src
* @return
*/
public static Instruction assignStruct(Var dst, Arg src) {
assert(Types.isStruct(dst)) : dst;
assert(Types.isStructLocal(src)) : src.type();
assert(StructType.sharedStruct((StructType)src.type().getImplType())
.assignableTo(dst.type()));
return new TurbineOp(Opcode.STORE_STRUCT, dst, src);
}
/**
* Retrieve any scalar type to local value
* @param dst
* @param src closed scalar value
* @return
*/
public static Instruction retrieveScalar(Var dst, Var src) {
assert(Types.isScalarValue(dst));
assert(Types.isScalarFuture(src.type()));
assert(Types.retrievedType(src).assignableTo(dst.type()));
return new TurbineOp(Opcode.LOAD_SCALAR, dst, src.asArg());
}
/**
* Retrieve a file value from a file future
* @param target
* @param src
* @return
*/
public static Instruction retrieveFile(Var target, Var src) {
assert(Types.isFile(src.type()));
assert(Types.isFileVal(target));
return new TurbineOp(Opcode.LOAD_FILE, target, src.asArg());
}
/**
* Retrieve an array directly to a local array, without following
* any references
* @param dst
* @param src non-recursively closed array
* @return
*/
public static Instruction retrieveArray(Var dst, Var src) {
assert(Types.isArray(src.type()));
assert(Types.isArrayLocal(dst));
assert(Types.containerElemType(src.type()).assignableTo(
Types.containerElemType(dst)));
return new TurbineOp(Opcode.LOAD_ARRAY, dst, src.asArg());
}
/**
* Retrieve a bag directly to a local bag, without following
* any references
* @param dst
* @param src non-recursively closed bag
* @return
*/
public static Instruction retrieveBag(Var target, Var src) {
assert(Types.isBag(src.type()));
assert(Types.isBagLocal(target));
assert(Types.containerElemType(src.type()).assignableTo(
Types.containerElemType(target)));
return new TurbineOp(Opcode.LOAD_BAG, target, src.asArg());
}
/**
* Retrieve a struct directly to a local struct, without following
* any references
* @param dst
* @param src non-recursively closed struct
* @return
*/
public static Instruction retrieveStruct(Var dst, Var src) {
assert(Types.isStruct(src.type()));
assert(Types.isStructLocal(dst));
assert(StructType.localStruct((StructType)src.type().getImplType())
.assignableTo(dst.type()));
return new TurbineOp(Opcode.LOAD_STRUCT, dst, src.asArg());
}
/**
* Store a completely unpacked array/bag/etc to the standard shared
* representation
* @param target
* @param src
* @return
*/
public static Instruction storeRecursive(Var target, Arg src) {
assert(Types.isContainer(target));
assert(Types.isContainerLocal(src.type()));
assert(src.type().assignableTo(
Types.unpackedContainerType(target)));
return new TurbineOp(Opcode.STORE_RECURSIVE, target, src);
}
/**
* Retrieve an array/bag/etc, following all references to included.
* src must be recursively closed
* @param target
* @param src
* @return
*/
public static Instruction retrieveRecursive(Var target, Var src) {
assert(Types.isContainer(src));
assert(Types.isContainerLocal(target));
Type unpackedSrcType = Types.unpackedContainerType(src);
assert(unpackedSrcType.assignableTo(target.type())) :
unpackedSrcType + " => " + target;
return new TurbineOp(Opcode.LOAD_RECURSIVE, target, src.asArg());
}
public static Instruction freeBlob(Var blobVal) {
// View refcounted var as output
return new TurbineOp(Opcode.FREE_BLOB, blobVal);
}
public static Instruction decrLocalFileRef(Var fileVal) {
assert(Types.isFileVal(fileVal));
// We should only be freeing local file refs if we allocated a temporary
assert(fileVal.type().fileKind().supportsTmpImmediate());
// View all as inputs: only used in cleanupaction context
return new TurbineOp(Opcode.DECR_LOCAL_FILE_REF, Collections.<Var>emptyList(),
fileVal.asArg());
}
/**
* Store a reference
* @param dst reference to store to
* @param src some datastore object
* @return
*/
public static Instruction storeRef(Var dst, Var src) {
// TODO: refcounts to transfer. Implied by output type?
assert(Types.isRef(dst));
assert(src.type().assignableTo(Types.retrievedType(dst)));
return new TurbineOp(Opcode.STORE_REF, dst, src.asArg());
}
/**
* Helper to generate appropriate store instruction for any type
* if possible
* @param dst
* @param src
* @return
*/
public static Instruction storeAny(Var dst, Arg src) {
assert(src.type().assignableTo(Types.retrievedType(dst)));
if (Types.isRef(dst)) {
assert(src.isVar());
return storeRef(dst, src.getVar());
} else if (Types.isPrimFuture(dst)) {
// Regular store?
return storePrim(dst, src);
} else if (Types.isArray(dst)) {
assert(src.isVar());
return assignArray(dst, src);
} else if (Types.isBag(dst)) {
assert(src.isVar());
return assignBag(dst, src);
} else if (Types.isStruct(dst)) {
assert(src.isVar());
return assignStruct(dst, src);
} else {
throw new STCRuntimeError("Don't know how to store to " + dst);
}
}
/**
* Helper to generate appropriate instruction for primitive type
* @param dst
* @param src
* @return
*/
public static Instruction storePrim(Var dst, Arg src) {
assert(Types.isPrimFuture(dst));
assert(src.type().assignableTo(Types.retrievedType(dst)));
if (Types.isScalarFuture(dst)) {
return assignScalar(dst, src);
} else if (Types.isFile(dst)) {
// TODO: is this right to always close?
return assignFile(dst, src, Arg.TRUE);
} else {
throw new STCRuntimeError("method to set " +
dst.type().typeName() + " is not known yet");
}
}
public static Instruction derefScalar(Var target, Var src) {
return new TurbineOp(Opcode.DEREF_SCALAR, target, src.asArg());
}
public static Instruction derefFile(Var target, Var src) {
return new TurbineOp(Opcode.DEREF_FILE, target, src.asArg());
}
/**
* Retrieve a reference to a local handle
* @param dst alias variable to hold handle to referenced data
* @param src Closed reference
* @param acquireRead num of read refcounts to acquire
* @param acquireWrite num of write refcounts to acquire
* @return
*/
public static Instruction retrieveRef(Var dst, Var src,
long acquireRead, long acquireWrite) {
assert(Types.isRef(src.type()));
assert(acquireRead >= 0);
assert(acquireWrite >= 0);
if (acquireWrite > 0) {
assert(Types.isAssignableRefTo(src.type(), dst.type(), true));
} else {
assert(Types.isAssignableRefTo(src.type(), dst.type()));
}
assert(dst.storage() == Alloc.ALIAS);
return new TurbineOp(Opcode.LOAD_REF, dst, src.asArg(),
Arg.createIntLit(acquireRead), Arg.createIntLit(acquireWrite));
}
public static Instruction copyRef(Var dst, Var src) {
return new TurbineOp(Opcode.COPY_REF, dst, src.asArg());
}
/**
* Create a nested array and assign result id to output reference.
* Read and write refcount is passed to output reference.
* @param arrayResult
* @param array
* @param ix
* @return
*/
public static Instruction arrayCreateNestedFuture(Var arrayResult,
Var array, Var ix) {
assert(Types.isArrayRef(arrayResult.type(), true));
assert(arrayResult.storage() != Alloc.ALIAS);
assert(Types.isArray(array.type()));
assert(Types.isArrayKeyFuture(array, ix));
assert(!Types.isConstRef(arrayResult)); // Should be mutable if ref
// Both arrays are modified, so outputs
return new TurbineOp(Opcode.ARR_CREATE_NESTED_FUTURE,
Arrays.asList(arrayResult, array), ix.asArg());
}
/**
* Create a nested array inside the current one, or return current
* nested array if not present. Acquire read + write reference
* to nested array.
* @param arrayResult
* @param arrayVar
* @param arrIx
* @return
*/
public static Instruction arrayCreateNestedImm(Var arrayResult,
Var arrayVar, Arg arrIx) {
assert(Types.isArray(arrayResult.type()));
assert(Types.isArray(arrayVar.type()));
assert(arrayResult.storage() == Alloc.ALIAS);
assert(Types.isArrayKeyVal(arrayVar, arrIx));
Arg readAcquire = Arg.ONE;
Arg writeAcquire = Arg.ONE;
// Both arrays are modified, so outputs
return new TurbineOp(Opcode.ARR_CREATE_NESTED_IMM,
Arrays.asList(arrayResult, arrayVar),
arrIx, readAcquire, writeAcquire);
}
public static Instruction arrayRefCreateNestedComputed(Var arrayResult,
Var array, Var ix) {
assert(Types.isArrayRef(arrayResult.type(), true)): arrayResult;
assert(arrayResult.storage() != Alloc.ALIAS);
assert(Types.isArrayRef(array.type(), true)): array;
assert(Types.isArrayKeyFuture(array, ix));
assert(!Types.isConstRef(arrayResult)); // Should be mutable if ref
// Returns nested array, modifies outer array and
// reference counts outmost array
return new TurbineOp(Opcode.AREF_CREATE_NESTED_FUTURE,
Arrays.asList(arrayResult, array),
ix.asArg());
}
/**
*
* @param arrayResult
* @param outerArray
* @param array
* @param ix
* @return
*/
public static Instruction arrayRefCreateNestedImmIx(Var arrayResult,
Var array, Arg ix) {
assert(Types.isArrayRef(arrayResult.type(), true)): arrayResult;
assert(arrayResult.storage() != Alloc.ALIAS);
assert(Types.isArrayRef(array.type(), true)): array;
assert(Types.isArrayKeyVal(array, ix));
assert(!Types.isConstRef(arrayResult)); // Should be mutable if ref
return new TurbineOp(Opcode.AREF_CREATE_NESTED_IMM,
// Returns nested array, modifies outer array and
// reference counts outmost array
Arrays.asList(arrayResult, array),
ix);
}
/**
* Create a nested bag inside an array
* @param bag
* @param arr
* @param key
* @return
*/
public static Instruction arrayCreateBag(Var bag,
Var arr, Arg key) {
assert(Types.isBag(bag));
assert(Types.isArray(arr));
assert(Types.isArrayKeyVal(arr, key));
assert(bag.storage() == Alloc.ALIAS);
// Both arrays are modified, so outputs
return new TurbineOp(Opcode.ARR_CREATE_BAG,
Arrays.asList(bag, arr),
key, Arg.ZERO, Arg.ZERO);
}
public static Instruction initUpdateableFloat(Var updateable, Arg val) {
return new TurbineOp(Opcode.INIT_UPDATEABLE_FLOAT, updateable, val);
}
public static Instruction latestValue(Var result, Var updateable) {
return new TurbineOp(Opcode.LATEST_VALUE, result, updateable.asArg());
}
public static Instruction update(Var updateable,
UpdateMode updateMode, Var val) {
Opcode op;
switch (updateMode) {
case MIN:
op = Opcode.UPDATE_MIN;
break;
case INCR:
op = Opcode.UPDATE_INCR;
break;
case SCALE:
op = Opcode.UPDATE_SCALE;
break;
default:
throw new STCRuntimeError("Unknown UpdateMode" + updateMode);
}
return new TurbineOp(op, updateable, val.asArg());
}
public static Instruction updateImm(Var updateable,
UpdateMode updateMode, Arg val) {
Opcode op;
switch (updateMode) {
case MIN:
op = Opcode.UPDATE_MIN_IMM;
break;
case INCR:
op = Opcode.UPDATE_INCR_IMM;
break;
case SCALE:
op = Opcode.UPDATE_SCALE_IMM;
break;
default:
throw new STCRuntimeError("Unknown UpdateMode"
+ updateMode);
}
return new TurbineOp(op, updateable, val);
}
public static Instruction getFileNameAlias(Var filename, Var file) {
return new TurbineOp(Opcode.GET_FILENAME_ALIAS, filename, file.asArg());
}
public static Instruction copyInFilename(Var file, Var filename) {
return new TurbineOp(Opcode.COPY_IN_FILENAME, file, filename.asArg());
}
public static Instruction getLocalFileName(Var filename, Var file) {
assert(Types.isFileVal(file));
assert(Types.isStringVal(filename));
return new TurbineOp(Opcode.GET_LOCAL_FILENAME, filename, file.asArg());
}
public static Instruction getFilenameVal(Var filenameVal, Var file) {
assert(Types.isStringVal(filenameVal));
assert(Types.isFile(file));
return new TurbineOp(Opcode.GET_FILENAME_VAL, filenameVal, file.asArg());
}
/**
* Set the filename of a file
* TODO: take additional disable variable that avoids setting if not
* mapped, to aid optimiser
* @param file
* @param filenameVal
* @return
*/
public static Instruction setFilenameVal(Var file, Arg filenameVal) {
assert(Types.isFile(file.type()));
assert(filenameVal.isImmediateString());
return new TurbineOp(Opcode.SET_FILENAME_VAL, file, filenameVal);
}
public static Instruction copyFileContents(Var target, Var src) {
return new TurbineOp(Opcode.COPY_FILE_CONTENTS, target, src.asArg());
}
/**
* Check if file is mapped
* @param isMapped
* @param file
* @return
*/
public static Instruction isMapped(Var isMapped, Var file) {
assert(Types.isBoolVal(isMapped));
assert(Types.isFile(file));
return new TurbineOp(Opcode.IS_MAPPED, isMapped, file.asArg());
}
public static Instruction chooseTmpFilename(Var filenameVal) {
return new TurbineOp(Opcode.CHOOSE_TMP_FILENAME, filenameVal);
}
public static Instruction initLocalOutFile(Var localOutFile,
Arg outFilename, Arg isMapped) {
assert(Types.isFileVal(localOutFile));
assert(Types.isStringVal(outFilename.type()));
assert(Types.isBoolVal(isMapped.type()));
return new TurbineOp(Opcode.INIT_LOCAL_OUTPUT_FILE, localOutFile.asList(),
outFilename, isMapped);
}
public static Instruction checkpointLookupEnabled(Var v) {
return new TurbineOp(Opcode.CHECKPOINT_LOOKUP_ENABLED, v);
}
public static Instruction checkpointWriteEnabled(Var v) {
return new TurbineOp(Opcode.CHECKPOINT_WRITE_ENABLED, v);
}
public static Instruction writeCheckpoint(Arg key, Arg value) {
assert(Types.isBlobVal(key.type()));
assert(Types.isBlobVal(value.type()));
return new TurbineOp(Opcode.WRITE_CHECKPOINT, Var.NONE, key, value);
}
public static Instruction lookupCheckpoint(Var checkpointExists, Var value,
Arg key) {
assert(Types.isBoolVal(checkpointExists));
assert(Types.isBlobVal(value));
assert(Types.isBlobVal(key.type()));
return new TurbineOp(Opcode.LOOKUP_CHECKPOINT,
Arrays.asList(checkpointExists, value), key);
}
public static Instruction packValues(Var packedValues, List<Arg> values) {
for (Arg val: values) {
assert(val.isConstant() || val.getVar().storage() == Alloc.LOCAL);
}
return new TurbineOp(Opcode.PACK_VALUES, packedValues.asList(), values);
}
public static Instruction unpackValues(List<Var> values, Arg packedValues) {
for (Var val: values) {
assert(val.storage() == Alloc.LOCAL);
}
return new TurbineOp(Opcode.UNPACK_VALUES, values, packedValues);
}
public static Instruction unpackArrayToFlat(Var flatLocalArray, Arg inputArray) {
return new TurbineOp(Opcode.UNPACK_ARRAY_TO_FLAT, flatLocalArray, inputArray);
}
@Override
public void renameVars(Map<Var, Arg> renames, RenameMode mode) {
if (mode == RenameMode.VALUE) {
// Fall through
} else if (mode == RenameMode.REPLACE_VAR) {
// Straightforward replacement
ICUtil.replaceVarsInList(renames, outputs, false);
} else {
assert(mode == RenameMode.REFERENCE);
for (int i = 0; i < outputs.size(); i++) {
Var output = outputs.get(i);
if (renames.containsKey(output)) {
// Avoid replacing aliases that were initialized
boolean isInit = false;
for (Pair<Var, Instruction.InitType> p: getInitialized()) {
if (output.equals(p.val1)) {
isInit = true;
break;
}
}
if (!isInit) {
Arg repl = renames.get(output);
if (repl.isVar()) {
outputs.set(i, repl.getVar());
}
}
}
}
}
renameInputs(renames);
}
public void renameInputs(Map<Var, Arg> renames) {
ICUtil.replaceArgsInList(renames, inputs);
}
@Override
public boolean hasSideEffects() {
switch (op) {
// The direct container write functions only mutate their output argument
// so effect can be tracked back to output var
case STRUCT_INIT_FIELDS:
case STRUCT_STORE_SUB:
case STRUCT_COPY_IN:
case STRUCTREF_STORE_SUB:
case STRUCTREF_COPY_IN:
case ARRAY_BUILD:
case ARR_STORE_FUTURE:
case ARR_COPY_IN_FUTURE:
case ARR_STORE:
case ARR_COPY_IN_IMM:
case AREF_STORE_FUTURE:
case AREF_COPY_IN_FUTURE:
case AREF_STORE_IMM:
case AREF_COPY_IN_IMM:
case SYNC_COPY:
case ASYNC_COPY:
return false;
case BAG_INSERT:
return false;
case UPDATE_INCR:
case UPDATE_MIN:
case UPDATE_SCALE:
case UPDATE_INCR_IMM:
case UPDATE_MIN_IMM:
case UPDATE_SCALE_IMM:
case INIT_UPDATEABLE_FLOAT:
return true;
case STORE_SCALAR:
case STORE_FILE:
case STORE_ARRAY:
case STORE_BAG:
case STORE_STRUCT:
case STORE_RECURSIVE:
case DEREF_SCALAR:
case DEREF_FILE:
case LOAD_SCALAR:
case LOAD_FILE:
case LOAD_ARRAY:
case LOAD_BAG:
case LOAD_STRUCT:
case LOAD_RECURSIVE:
case STRUCT_LOCAL_BUILD:
return false;
case ARR_COPY_OUT_IMM:
case ARR_COPY_OUT_FUTURE:
case AREF_COPY_OUT_FUTURE:
case AREF_COPY_OUT_IMM:
case ARR_CONTAINS:
case CONTAINER_SIZE:
case ARR_LOCAL_CONTAINS:
case CONTAINER_LOCAL_SIZE:
return false;
case GET_FILENAME_ALIAS:
// Only effect is setting alias var
return false;
case GET_LOCAL_FILENAME:
return false;
case GET_FILENAME_VAL:
return false;
case IS_MAPPED:
// will always returns same result for same var
return false;
case CHOOSE_TMP_FILENAME:
// Non-deterministic
return true;
case SET_FILENAME_VAL:
case COPY_IN_FILENAME:
// Only effect is in file output var
return false;
case COPY_FILE_CONTENTS:
// Only effect is to modify file represented by output var
return false;
case INIT_LOCAL_OUTPUT_FILE:
// If the output is mapped, we want to retain the file,
// so we treat this as having side-effects
if (getInput(1).isBoolVal() && getInput(1).getBoolLit() == false) {
// Definitely unmapped
return false;
} else {
// Maybe mapped
return true;
}
case LOAD_REF:
case STORE_REF:
case COPY_REF:
case STRUCT_CREATE_ALIAS:
case STRUCT_RETRIEVE_SUB:
case STRUCT_COPY_OUT:
case STRUCTREF_COPY_OUT:
case ARR_RETRIEVE:
case LATEST_VALUE:
case ARR_CREATE_ALIAS:
// Always has alias as output because the instructions initialises
// the aliases
return false;
case ARR_CREATE_NESTED_FUTURE:
case AREF_CREATE_NESTED_FUTURE:
case ARR_CREATE_NESTED_IMM:
case AREF_CREATE_NESTED_IMM:
case ARR_CREATE_BAG:
/* It might seem like these nested creation primitives have a
* side-effect, but for optimisation purposes they can be treated as
* side-effect free, as the side-effect is only relevant if the array
* created is subsequently used in a store operation
*/
return false;
case FREE_BLOB:
case DECR_LOCAL_FILE_REF:
/*
* Reference counting ops can have side-effect
*/
return true;
case WRITE_CHECKPOINT:
// Writing checkpoint is a side-effect
return true;
case LOOKUP_CHECKPOINT:
case PACK_VALUES:
case UNPACK_VALUES:
case UNPACK_ARRAY_TO_FLAT:
case CHECKPOINT_WRITE_ENABLED:
case CHECKPOINT_LOOKUP_ENABLED:
return false;
default:
throw new STCRuntimeError("Need to add opcode " + op.toString()
+ " to hasSideEffects");
}
}
public boolean canChangeTiming() {
return !hasSideEffects() && op != Opcode.LATEST_VALUE;
}
@Override
public List<Var> getOutputs() {
return Collections.unmodifiableList(outputs);
}
@Override
public Arg getInput(int i) {
return inputs.get(i);
}
@Override
public Var getOutput(int i) {
return outputs.get(i);
}
@Override
public List<Arg> getInputs() {
return Collections.unmodifiableList(inputs);
}
public List<Arg> getInputsTail(int start) {
return Collections.unmodifiableList(inputs.subList(start, inputs.size()));
}
public void setInput(int i, Arg arg) {
this.inputs.set(i, arg);
}
@Override
public MakeImmRequest canMakeImmediate(Set<Var> closedVars,
Set<ArgCV> closedLocations, Set<Var> valueAvail, boolean waitForClose) {
boolean insertRefWaitForClose = waitForClose;
// Try to take advantage of closed variables
switch (op) {
case ARR_COPY_OUT_IMM: {
// If array is closed or this index already inserted,
// don't need to block on array.
// NOTE: could try to reduce other forms to this in one step,
// but its probably just easier to do it in multiple steps
// on subsequent passes
Var arr = getInput(0).getVar();
if (closedVars.contains(arr)) {
// Don't request to wait for close - whole array doesn't need to be
// closed
return new MakeImmRequest(null, Collections.<Var>emptyList());
}
break;
}
case ARR_COPY_OUT_FUTURE: {
Var index = getInput(1).getVar();
if (waitForClose || closedVars.contains(index)) {
return new MakeImmRequest(null, Arrays.asList(index));
}
break;
}
case AREF_COPY_OUT_FUTURE: {
Var arr = getInput(0).getVar();
Var ix = getInput(1).getVar();
// We will take either the index or the dereferenced array
List<Var> req = mkImmVarList(waitForClose, closedVars, arr, ix);
if (req.size() > 0) {
return new MakeImmRequest(null, req);
}
break;
}
case AREF_COPY_OUT_IMM: {
// Could skip using reference
Var arrRef = getInput(0).getVar();
if (waitForClose || closedVars.contains(arrRef)) {
return new MakeImmRequest(null, Arrays.asList(arrRef));
}
break;
}
case ARR_CONTAINS: {
Var arr = getInput(0).getVar();
// check to see if local version of array available
// (Already assuming array closed)
if (valueAvail.contains(arr)) {
return new MakeImmRequest(null, Arrays.asList(arr));
}
break;
}
case CONTAINER_SIZE: {
Var cont = getInput(0).getVar();
// check to see if local version of container available
// (Already assuming array closed)
if (valueAvail.contains(cont)) {
return new MakeImmRequest(null, Arrays.asList(cont));
}
break;
}
case STRUCT_COPY_IN: {
Var val = getInput(0).getVar();
if (waitForClose || closedVars.contains(val)) {
return new MakeImmRequest(null, val.asList());
}
break;
}
case STRUCTREF_COPY_IN: {
Var structRef = getOutput(0);
Var val = getInput(0).getVar();
List<Var> vs = mkImmVarList(waitForClose, closedVars,
Arrays.asList(structRef, val));
if (vs.size() > 0) {
return new MakeImmRequest(null, vs);
}
break;
}
case STRUCTREF_STORE_SUB: {
Var structRef = getOutput(0);
if (waitForClose || closedVars.contains(structRef)) {
return new MakeImmRequest(null, structRef.asList());
}
break;
}
case STRUCT_COPY_OUT: {
// If struct is closed or this field already set, don't needto block
Var struct = getInput(0).getVar();
if (closedVars.contains(struct)) {
// Don't request to wait for close - whole struct doesn't need to be
// closed
return new MakeImmRequest(null, Collections.<Var>emptyList());
}
break;
}
case STRUCTREF_COPY_OUT: {
Var structRef = getInput(0).getVar();
if (waitForClose || closedVars.contains(structRef)) {
return new MakeImmRequest(null, structRef.asList());
}
break;
}
case ARR_COPY_IN_IMM: {
// See if we can get deref arg
Var mem = getInput(1).getVar();
List<Var> vs = mkImmVarList(waitForClose, closedVars, mem.asList());
if (vs.size() > 0) {
return new MakeImmRequest(null, vs);
}
break;
}
case ARR_STORE_FUTURE:
case ARR_COPY_IN_FUTURE: {
Var ix = getInput(0).getVar();
Arg val = getInput(1);
List<Var> vs;
if (op == Opcode.ARR_STORE_FUTURE) {
vs = ix.asList();
} else {
assert(op == Opcode.ARR_COPY_IN_FUTURE);
vs = Arrays.asList(ix, val.getVar());
}
vs = mkImmVarList(waitForClose, closedVars, vs);
if (vs.size() > 0) {
return new MakeImmRequest(null, vs);
}
break;
}
case AREF_STORE_IMM:
case AREF_COPY_IN_IMM: {
List<Var> vs;
Var arrRef = getOutput(0);
Arg mem = getInput(1);
if (op == Opcode.AREF_STORE_IMM) {
vs = arrRef.asList();
} else {
assert(op == Opcode.AREF_COPY_IN_IMM);
vs = Arrays.asList(arrRef, mem.getVar());
}
vs = mkImmVarList(insertRefWaitForClose, closedVars, vs);
if (vs.size() > 0) {
return new MakeImmRequest(null, vs);
}
break;
}
case AREF_STORE_FUTURE:
case AREF_COPY_IN_FUTURE: {
Var arrRef = getOutput(0);
Var ix = getInput(0).getVar();
Arg mem = getInput(1);
List<Var> req;
if (op == Opcode.AREF_STORE_FUTURE) {
req = Arrays.asList(arrRef, ix);
} else {
assert(op == Opcode.AREF_COPY_IN_FUTURE);
req = Arrays.asList(arrRef, ix, mem.getVar());
}
// We will take either the index or the dereferenced array
req = mkImmVarList(insertRefWaitForClose, closedVars, req);
if (req.size() > 0) {
return new MakeImmRequest(null, req);
}
break;
}
case ARR_CREATE_NESTED_FUTURE: {
// Try to get immediate index
Var ix = getInput(0).getVar();
if (waitForClose || closedVars.contains(ix)) {
return new MakeImmRequest(null, Arrays.asList(ix));
}
break;
}
case AREF_CREATE_NESTED_IMM: {
Var arrRef = getOutput(1);
if (waitForClose || closedVars.contains(arrRef)) {
return new MakeImmRequest(null, Arrays.asList(arrRef));
}
break;
}
case AREF_CREATE_NESTED_FUTURE: {
Var arrRef = getOutput(1);
Var ix = getInput(0).getVar();
List<Var> req5 = mkImmVarList(waitForClose, closedVars, arrRef, ix);
if (req5.size() > 0) {
return new MakeImmRequest(null, req5);
}
break;
}
case ASYNC_COPY: {
// See if we can get closed container/struct
List<Var> req = mkImmVarList(waitForClose, closedVars,
getInput(0).getVar());
if (req.size() > 0) {
// Wait for vars only
return MakeImmRequest.waitOnly(req);
}
break;
}
case SYNC_COPY: {
// TODO: would be nice to switch to explicit load/store if container
// datum is small enough
Var dst = getOutput(0);
Var src = getInput(0).getVar();
if (Types.isPrimFuture(dst) || Types.isStruct(dst) ||
Types.isRef(dst)) {
// Small data
if (waitForClose || closedVars.contains(src)) {
return new MakeImmRequest(null, src.asList());
}
}
break;
}
case COPY_IN_FILENAME: {
Var filenameIn = getInput(0).getVar();
if (waitForClose || closedVars.contains(filenameIn)) {
return new MakeImmRequest(null, filenameIn.asList());
}
break;
}
case UPDATE_INCR:
case UPDATE_MIN:
case UPDATE_SCALE: {
Var newVal = getInput(0).getVar();
if (waitForClose || closedVars.contains(newVal)) {
return new MakeImmRequest(null, newVal.asList());
}
break;
}
default:
// fall through
break;
}
return null;
}
private List<Var> mkImmVarList(boolean waitForClose,
Set<Var> closedVars, Var... args) {
return mkImmVarList(waitForClose, closedVars, Arrays.asList(args));
}
private List<Var> mkImmVarList(boolean waitForClose,
Set<Var> closedVars, List<Var> args) {
ArrayList<Var> req = new ArrayList<Var>(args.size());
for (Var v: args) {
if (waitForClose || closedVars.contains(v)) {
req.add(v);
}
}
return req;
}
@Override
public MakeImmChange makeImmediate(VarCreator creator,
List<Fetched<Var>> out,
List<Fetched<Arg>> values) {
switch (op) {
case ARR_COPY_OUT_IMM: {
assert(values.size() == 0) : values;
// Input should be unchanged
Var arr = getInput(0).getVar();
// Output switched from ref to value
Var origOut = getOutput(0);
Var valOut = creator.createDerefTmp(origOut);
Instruction newI = arrayRetrieve(valOut, arr, getInput(1), Arg.ZERO);
return new MakeImmChange(valOut, origOut, newI);
}
case ARR_COPY_OUT_FUTURE: {
assert(values.size() == 1);
Arg newIx = values.get(0).fetched;
return new MakeImmChange(
arrayCopyOutImm(getOutput(0), getInput(0).getVar(), newIx));
}
case AREF_COPY_OUT_FUTURE: {
assert(values.size() == 1 || values.size() == 2);
Var mem = getOutput(0);
Var arrRef = getInput(0).getVar();
Var ix = getInput(1).getVar();
Arg newIx = Fetched.findFetched(values, ix);
Var newArr = Fetched.findFetchedVar(values, arrRef);
Instruction inst;
// Could be either array ref, index, or both
if (newIx != null && newArr != null) {
inst = arrayCopyOutImm(mem, newArr, newIx);
} else if (newIx != null && newArr == null){
inst = arrayRefCopyOutImm(mem, arrRef, newIx);
} else {
assert(newIx == null && newArr != null);
inst = arrayCopyOutFuture(mem, newArr, ix);
}
return new MakeImmChange(inst);
}
case AREF_COPY_OUT_IMM: {
assert(values.size() == 1);
// Switch from ref to plain array
Var newArr = values.get(0).fetched.getVar();
return new MakeImmChange(
arrayCopyOutImm(getOutput(0), newArr, getInput(1)));
}
case ARR_CONTAINS: {
Var localArr = values.get(0).fetched.getVar();
return new MakeImmChange(
arrayLocalContains(getOutput(0), localArr, getInput(1)));
}
case CONTAINER_SIZE: {
Var localCont = values.get(0).fetched.getVar();
return new MakeImmChange(
containerLocalSize(getOutput(0), localCont));
}
case STRUCT_COPY_IN: {
assert(values.size() == 1);
Arg derefMember = values.get(0).fetched;
List<String> fields = Arg.extractStrings(getInputsTail(1));
return new MakeImmChange(
structStoreSub(getOutput(0), fields, derefMember));
}
case STRUCTREF_STORE_SUB: {
assert(values.size() == 1);
Var structRef = getOutput(0);
Var newStruct = Fetched.findFetchedVar(values, structRef);
List<String> fields = Arg.extractStrings(getInputsTail(1));
return new MakeImmChange(
structStoreSub(newStruct, fields, getInput(0)));
}
case STRUCTREF_COPY_IN: {
Var structRef = getOutput(0);
Var val = getInput(0).getVar();
Var newStruct = Fetched.findFetchedVar(values, structRef);
Arg newVal = Fetched.findFetched(values, val);
List<String> fields = Arg.extractStrings(getInputsTail(1));
Instruction newI;
if (newStruct != null && newVal != null) {
newI = structStoreSub(newStruct, fields, newVal);
} else if (newStruct != null && newVal == null) {
newI = structCopyIn(newStruct, fields, val);
} else {
assert(newStruct == null && newVal != null);
newI = structRefStoreSub(structRef, fields, newVal);
}
return new MakeImmChange(newI);
}
case STRUCT_COPY_OUT: {
assert(values.size() == 0);
// Input should be unchanged
Var arr = getInput(0).getVar();
// Output switched from ref to value
Var origOut = getOutput(0);
List<String> fields = Arg.extractStrings(getInputsTail(1));
Var valOut = creator.createDerefTmp(origOut);
Instruction newI = structRetrieveSub(valOut, arr, fields, Arg.ZERO);
return new MakeImmChange(valOut, origOut, newI);
}
case STRUCTREF_COPY_OUT: {
assert(values.size() == 1);
Var structRef = getInput(0).getVar();
Var newStruct = Fetched.findFetchedVar(values, structRef);
List<String> fields = Arg.extractStrings(getInputsTail(1));
return new MakeImmChange(
structCopyOut(getOutput(0), newStruct, fields));
}
case ARR_COPY_IN_IMM: {
assert(values.size() == 1);
Arg derefMember = values.get(0).fetched;
return new MakeImmChange(
arrayStore(getOutput(0), getInput(0), derefMember));
}
case ARR_STORE_FUTURE: {
assert(values.size() == 1);
Arg fetchedIx = values.get(0).fetched;
return new MakeImmChange(
arrayStore(getOutput(0), fetchedIx, getInput(1)));
}
case ARR_COPY_IN_FUTURE: {
Var arr = getOutput(0);
Var ix = getInput(0).getVar();
Var mem = getInput(1).getVar();
Arg newIx = Fetched.findFetched(values, ix);
Arg newMem = Fetched.findFetched(values, mem);
Instruction inst;
if (newIx != null && newMem != null) {
inst = arrayStore(arr, newIx, newMem);
} else if (newIx != null && newMem == null) {
inst = arrayCopyInImm(arr, newIx, mem);
} else {
assert(newIx == null && newMem != null);
inst = arrayStoreFuture(arr, ix, newMem);
}
return new MakeImmChange(inst);
}
case AREF_STORE_IMM: {
assert(values.size() == 1);
Var newOut = values.get(0).fetched.getVar();
// Switch from ref to plain array
return new MakeImmChange(arrayStore(newOut, getInput(0), getInput(1)));
}
case AREF_COPY_IN_IMM: {
Var arrRef = getOutput(0);
Arg ix = getInput(0);
Var mem = getInput(1).getVar();
Var newArr = Fetched.findFetchedVar(values, arrRef);
Arg newMem = Fetched.findFetched(values, mem);
Instruction newI;
if (newArr != null && newMem != null) {
newI = arrayStore(newArr, ix, newMem);
} else if (newArr != null && newMem == null) {
newI = arrayCopyInImm(newArr, ix, mem);
} else {
assert(newArr == null && newMem != null);
newI = arrayRefStoreImm(arrRef, ix, newMem);
}
return new MakeImmChange(newI);
}
case AREF_STORE_FUTURE:
case AREF_COPY_IN_FUTURE: {
Var arrRef = getOutput(0);
Var ix = getInput(0).getVar();
Arg mem = getInput(1);
// Various combinations are possible
Var newArr = Fetched.findFetchedVar(values, arrRef);
Arg newIx = Fetched.findFetched(values, ix);
Arg derefMem = null;
if (mem.isVar()) {
derefMem = Fetched.findFetched(values, mem.getVar());
}
Instruction inst;
if (derefMem != null || op == Opcode.AREF_STORE_FUTURE) {
if (derefMem == null) {
assert(op == Opcode.AREF_STORE_FUTURE);
// It was already dereferenced
derefMem = mem;
}
if (newArr != null && newIx != null) {
inst = arrayStore(newArr, newIx, derefMem);
} else if (newArr != null && newIx == null) {
inst = arrayStoreFuture(newArr, ix, derefMem);
} else if (newArr == null && newIx != null) {
inst = arrayRefStoreImm(arrRef, newIx, derefMem);
} else {
assert(newArr == null && newIx == null);
inst = arrayRefStoreFuture(arrRef, ix, derefMem);
}
} else {
Var memVar = mem.getVar();
assert(op == Opcode.AREF_COPY_IN_FUTURE);
if (newArr != null && newIx != null) {
inst = arrayCopyInImm(newArr, newIx, memVar);
} else if (newArr != null && newIx == null) {
inst = arrayCopyInFuture(newArr, ix, memVar);
} else {
assert(newArr == null && newIx != null) :
this + " | " + newArr + " " + newIx;
inst = arrayRefCopyInImm(arrRef, newIx, memVar);
}
}
return new MakeImmChange(inst);
}
case ARR_CREATE_NESTED_FUTURE: {
assert(values.size() == 1);
Arg ix = values.get(0).fetched;
Var oldResult = getOutput(0);
Var oldArray = getOutput(1);
assert(Types.isArrayKeyVal(oldArray, ix)) : oldArray + " " + ix.type();
// Output type of instruction changed from ref to direct
// array handle
assert(Types.isArrayRef(oldResult.type()));
Var newOut = creator.createDerefTmp(oldResult);
return new MakeImmChange(newOut, oldResult,
arrayCreateNestedImm(newOut, oldArray, ix));
}
case AREF_CREATE_NESTED_FUTURE: {
assert(values.size() == 1 || values.size() == 2);
Var arrResult = getOutput(0);
Var arrRef = getOutput(1);
Var ix = getInput(0).getVar();
Var newArr = Fetched.findFetchedVar(values, arrRef);
Arg newIx = Fetched.findFetched(values, ix);
if (newArr != null && newIx != null) {
Var oldOut = getOutput(0);
assert(Types.isArrayRef(oldOut.type()));
Var newOut = creator.createDerefTmp(arrResult);
return new MakeImmChange(newOut, oldOut,
arrayCreateNestedImm(newOut, newArr, newIx));
} else if (newArr != null && newIx == null) {
return new MakeImmChange(
arrayCreateNestedFuture(arrResult, newArr, ix));
} else {
assert(newArr == null && newIx != null);
return new MakeImmChange(
arrayRefCreateNestedImmIx(arrResult, arrRef, newIx));
}
}
case AREF_CREATE_NESTED_IMM: {
assert(values.size() == 1);
Var newArr = values.get(0).fetched.getVar();
Arg ix = getInput(0);
Var arrResult = getOutput(0);
assert(Types.isArray(newArr));
assert(Types.isArrayRef(arrResult.type()));
Var newOut3 = creator.createDerefTmp(arrResult);
assert(Types.isArrayKeyVal(newArr, ix));
return new MakeImmChange(newOut3, arrResult,
arrayCreateNestedImm(newOut3, newArr, getInput(0)));
}
case ASYNC_COPY: {
// data is closed: replace with sync version
return new MakeImmChange(
syncCopy(getOutput(0), getInput(0).getVar()));
}
case SYNC_COPY: {
assert(values.get(0).original.equals(getInput(0).getVar()));
Arg val = values.get(0).fetched;
return new MakeImmChange(
TurbineOp.storeAny(getOutput(0), val));
}
case COPY_IN_FILENAME: {
return new MakeImmChange(
setFilenameVal(getOutput(0), values.get(0).fetched));
}
case UPDATE_INCR:
case UPDATE_MIN:
case UPDATE_SCALE: {
assert(values.size() == 1);
UpdateMode mode;
switch (op) {
case UPDATE_INCR:
mode = UpdateMode.INCR;
break;
case UPDATE_MIN:
mode = UpdateMode.MIN;
break;
case UPDATE_SCALE:
mode = UpdateMode.SCALE;
break;
default:
throw new STCRuntimeError("op: " + op +
" ... shouldn't be here");
}
return new MakeImmChange(null, null, TurbineOp.updateImm(
getOutput(0), mode, values.get(0).fetched));
}
default:
// fall through
break;
}
throw new STCRuntimeError("Couldn't make inst "
+ this.toString() + " immediate with vars: "
+ values.toString());
}
@SuppressWarnings("unchecked")
@Override
public List<Pair<Var, Instruction.InitType>> getInitialized() {
switch (op) {
case LOAD_REF:
case COPY_REF:
case ARR_CREATE_NESTED_IMM:
case ARR_CREATE_BAG:
case GET_FILENAME_ALIAS:
// Initialises alias
return Arrays.asList(Pair.create(getOutput(0), InitType.FULL));
case ARR_RETRIEVE:
case ARR_CREATE_ALIAS:
case STRUCT_RETRIEVE_SUB:
case STRUCT_CREATE_ALIAS:{
// May initialise alias if we're looking up a reference
Var output = getOutput(0);
if (output.storage() == Alloc.ALIAS) {
return Arrays.asList(Pair.create(output, InitType.FULL));
} else {
return Collections.emptyList();
}
}
case STRUCT_INIT_FIELDS: {
// Initializes struct fields that we assume are present
Var struct = getOutput(0);
return Arrays.asList(Pair.create(struct, InitType.FULL));
}
case INIT_UPDATEABLE_FLOAT:
// Initializes updateable
return Arrays.asList(Pair.create(getOutput(0), InitType.FULL));
case INIT_LOCAL_OUTPUT_FILE:
case LOAD_FILE:
// Initializes output file value
return Arrays.asList(Pair.create(getOutput(0), InitType.FULL));
default:
return Collections.emptyList();
}
}
/**
* @return list of outputs for which previous value is read
*/
public List<Var> getReadOutputs(Map<String, Function> fns) {
switch (op) {
case ARR_CREATE_NESTED_IMM:
case ARR_CREATE_NESTED_FUTURE:
// In create_nested instructions the
// second array being inserted into is needed
return Arrays.asList(getOutput(1));
case ARR_CREATE_BAG:
// the array being inserted into
return getOutput(1).asList();
case AREF_CREATE_NESTED_IMM:
case AREF_CREATE_NESTED_FUTURE:
// In ref_create_nested instructions the
// second array being inserted into is needed
return Arrays.asList(getOutput(1));
default:
return Var.NONE;
}
}
public List<Var> getModifiedOutputs() {
switch (op) {
case ARR_CREATE_NESTED_IMM:
case ARR_CREATE_NESTED_FUTURE:
case AREF_CREATE_NESTED_IMM:
case AREF_CREATE_NESTED_FUTURE:
case ARR_CREATE_BAG:
// In create_nested instructions only the
// first output (the created array) is needed
return Collections.singletonList(getOutput(0));
default:
return this.getOutputs();
}
}
@Override
public List<Component> getModifiedComponents() {
switch (op) {
case AREF_COPY_IN_FUTURE:
case AREF_COPY_IN_IMM:
case AREF_STORE_FUTURE:
case AREF_STORE_IMM:
case STRUCTREF_COPY_IN:
case STRUCTREF_STORE_SUB:
// This functions modify the datum referred to by the output reference
return new Component(getOutput(0), Component.DEREF).asList();
default:
return null;
}
}
/**
* @return List of outputs that are piecewise assigned
*/
public List<Var> getPiecewiseAssignedOutputs() {
switch (op) {
case ARR_STORE_FUTURE:
case ARR_COPY_IN_FUTURE:
case ARR_STORE:
case ARR_COPY_IN_IMM:
case AREF_STORE_FUTURE:
case AREF_COPY_IN_FUTURE:
case AREF_STORE_IMM:
case AREF_COPY_IN_IMM:
// All outputs are piecewise assigned
return getOutputs();
case ARR_CREATE_NESTED_FUTURE:
case ARR_CREATE_NESTED_IMM:
case ARR_CREATE_BAG:
case AREF_CREATE_NESTED_FUTURE:
case AREF_CREATE_NESTED_IMM: {
// All arrays except the newly created array;
List<Var> outputs = getOutputs();
return outputs.subList(1, outputs.size());
}
case STRUCT_STORE_SUB:
case STRUCT_COPY_IN:
case STRUCTREF_STORE_SUB:
case STRUCTREF_COPY_IN:
return getOutputs();
case COPY_IN_FILENAME:
case SET_FILENAME_VAL:
// File's filename might be modified
return getOutput(0).asList();
case STORE_FILE: {
Arg setFilename = getInput(1);
if (setFilename.isBoolVal() && setFilename.getBoolLit()) {
// Assign whole file
return Var.NONE;
} else {
// Assigned filename separately
return getOutput(0).asList();
}
}
default:
return Var.NONE;
}
}
@Override
public List<Var> getBlockingInputs(Program prog) {
if (getMode() == TaskMode.SYNC) {
return Var.NONE;
}
// If async, assume that all scalar input vars are blocked on
ArrayList<Var> blocksOn = new ArrayList<Var>();
for (Arg oa: getInputs()) {
if (oa.kind == ArgKind.VAR) {
Var v = oa.getVar();
Type t = v.type();
if (Types.isPrimFuture(t) || Types.isRef(t)) {
blocksOn.add(v);
} else if (Types.isPrimValue(t) || Types.isStruct(t) ||
Types.isContainer(t) || Types.isPrimUpdateable(t)) {
// No turbine ops block on these types
} else {
throw new STCRuntimeError("Don't handle type "
+ t.toString() + " here");
}
}
}
return blocksOn;
}
@Override
public TaskMode getMode() {
switch (op) {
case STORE_SCALAR:
case STORE_FILE:
case STORE_ARRAY:
case STORE_BAG:
case STORE_STRUCT:
case STORE_RECURSIVE:
case LOAD_SCALAR:
case LOAD_FILE:
case LOAD_ARRAY:
case LOAD_BAG:
case LOAD_STRUCT:
case LOAD_RECURSIVE:
case UPDATE_INCR:
case UPDATE_MIN:
case UPDATE_SCALE:
case UPDATE_INCR_IMM:
case UPDATE_MIN_IMM:
case UPDATE_SCALE_IMM:
case INIT_UPDATEABLE_FLOAT:
case LATEST_VALUE:
case ARR_STORE:
case STRUCT_INIT_FIELDS:
case STRUCT_STORE_SUB:
case STRUCT_RETRIEVE_SUB:
case STRUCT_CREATE_ALIAS:
case ARR_CREATE_ALIAS:
case ARR_CREATE_NESTED_IMM:
case ARR_CREATE_BAG:
case STORE_REF:
case LOAD_REF:
case FREE_BLOB:
case DECR_LOCAL_FILE_REF:
case GET_FILENAME_ALIAS:
case GET_LOCAL_FILENAME:
case IS_MAPPED:
case COPY_FILE_CONTENTS:
case ARR_RETRIEVE:
case COPY_REF:
case CHOOSE_TMP_FILENAME:
case GET_FILENAME_VAL:
case SET_FILENAME_VAL:
case INIT_LOCAL_OUTPUT_FILE:
case ARRAY_BUILD:
case SYNC_COPY:
case BAG_INSERT:
case CHECKPOINT_WRITE_ENABLED:
case CHECKPOINT_LOOKUP_ENABLED:
case LOOKUP_CHECKPOINT:
case WRITE_CHECKPOINT:
case PACK_VALUES:
case UNPACK_VALUES:
case UNPACK_ARRAY_TO_FLAT:
case ARR_CONTAINS:
case CONTAINER_SIZE:
case ARR_LOCAL_CONTAINS:
case CONTAINER_LOCAL_SIZE:
case STRUCT_LOCAL_BUILD:
return TaskMode.SYNC;
case ARR_COPY_IN_IMM:
case ARR_STORE_FUTURE:
case ARR_COPY_IN_FUTURE:
case AREF_STORE_FUTURE:
case AREF_COPY_IN_FUTURE:
case AREF_STORE_IMM:
case AREF_COPY_IN_IMM:
case AREF_COPY_OUT_FUTURE:
case AREF_COPY_OUT_IMM:
case ARR_COPY_OUT_IMM:
case DEREF_SCALAR:
case DEREF_FILE:
case ARR_COPY_OUT_FUTURE:
case AREF_CREATE_NESTED_FUTURE:
case ARR_CREATE_NESTED_FUTURE:
case AREF_CREATE_NESTED_IMM:
case ASYNC_COPY:
case STRUCT_COPY_IN:
case STRUCTREF_STORE_SUB:
case STRUCTREF_COPY_IN:
case STRUCT_COPY_OUT:
case STRUCTREF_COPY_OUT:
case COPY_IN_FILENAME:
return TaskMode.LOCAL;
default:
throw new STCRuntimeError("Need to add opcode " + op.toString()
+ " to getMode");
}
}
@Override
public List<ExecContext> supportedContexts() {
switch (op) {
case LOAD_ARRAY:
case LOAD_BAG:
case LOAD_FILE:
case LOAD_RECURSIVE:
case LOAD_REF:
case LOAD_SCALAR:
case LOAD_STRUCT:
case LATEST_VALUE:
case STORE_ARRAY:
case STORE_BAG:
case STORE_FILE:
case STORE_RECURSIVE:
case STORE_REF:
case STORE_SCALAR:
case STORE_STRUCT:
case ARRAY_BUILD:
// Loads and stores can run anywhere
return ExecContext.ALL;
case SET_FILENAME_VAL:
case GET_FILENAME_VAL:
case COPY_IN_FILENAME:
// Filename loads and stores can run anywhere
return ExecContext.ALL;
case INIT_LOCAL_OUTPUT_FILE:
case INIT_UPDATEABLE_FLOAT:
// Init operations can run anywhere
return ExecContext.ALL;
case UPDATE_INCR:
case UPDATE_INCR_IMM:
case UPDATE_MIN:
case UPDATE_MIN_IMM:
case UPDATE_SCALE:
case UPDATE_SCALE_IMM:
// Update operations can run anywhere
return ExecContext.ALL;
case COPY_REF:
case STRUCT_CREATE_ALIAS:
case GET_FILENAME_ALIAS:
case ARR_CREATE_ALIAS:
// Alias can be created anywhere
return ExecContext.ALL;
case DEREF_FILE:
case DEREF_SCALAR:
// Deref can be done anywhere
return ExecContext.ALL;
case ARR_CONTAINS:
case ARR_COPY_IN_FUTURE:
case ARR_COPY_IN_IMM:
case ARR_COPY_OUT_FUTURE:
case ARR_COPY_OUT_IMM:
case ARR_CREATE_NESTED_FUTURE:
case ARR_CREATE_NESTED_IMM:
case ARR_LOCAL_CONTAINS:
case ARR_RETRIEVE:
case ARR_STORE:
case ARR_STORE_FUTURE:
case ARR_CREATE_BAG:
case AREF_COPY_IN_FUTURE:
case AREF_COPY_IN_IMM:
case AREF_COPY_OUT_FUTURE:
case AREF_COPY_OUT_IMM:
case AREF_CREATE_NESTED_FUTURE:
case AREF_CREATE_NESTED_IMM:
case AREF_STORE_FUTURE:
case AREF_STORE_IMM:
case BAG_INSERT:
case CONTAINER_SIZE:
case CONTAINER_LOCAL_SIZE:
// Array ops can be done anywhere
return ExecContext.ALL;
case STRUCT_COPY_IN:
case STRUCT_COPY_OUT:
case STRUCT_INIT_FIELDS:
case STRUCT_RETRIEVE_SUB:
case STRUCT_STORE_SUB:
case STRUCTREF_COPY_IN:
case STRUCTREF_COPY_OUT:
case STRUCTREF_STORE_SUB:
// Struct ops can be done anywhere
return ExecContext.ALL;
case ASYNC_COPY:
// Copy ops can be done anywhere
return ExecContext.ALL;
case SYNC_COPY:
// Copy ops can be done anywhere
return ExecContext.ALL;
case CHECKPOINT_LOOKUP_ENABLED:
case CHECKPOINT_WRITE_ENABLED:
case CHOOSE_TMP_FILENAME:
case IS_MAPPED:
case GET_LOCAL_FILENAME:
// Utility operations can be done anywhere
return ExecContext.ALL;
case COPY_FILE_CONTENTS:
// Copying a file can take some time - only do on worker
return ExecContext.WORKER_LIST;
case DECR_LOCAL_FILE_REF:
case FREE_BLOB:
// Local refcount manipulations
return ExecContext.ALL;
case LOOKUP_CHECKPOINT:
return ExecContext.ALL;
case PACK_VALUES:
case UNPACK_ARRAY_TO_FLAT:
case UNPACK_VALUES:
case STRUCT_LOCAL_BUILD:
return ExecContext.ALL;
case WRITE_CHECKPOINT:
// Should checkpoint data where it is created
return ExecContext.ALL;
default:
throw new STCRuntimeError("Missing: " + op);
}
}
@Override
public boolean isCheap() {
switch (op) {
case LOAD_ARRAY:
case LOAD_BAG:
case LOAD_FILE:
case LOAD_RECURSIVE:
case LOAD_REF:
case LOAD_SCALAR:
case LOAD_STRUCT:
case LATEST_VALUE:
case STORE_ARRAY:
case STORE_BAG:
case STORE_FILE:
case STORE_RECURSIVE:
case STORE_REF:
case STORE_SCALAR:
case STORE_STRUCT:
case ARRAY_BUILD:
// Loads and stores aren't too expensive
return true;
case SET_FILENAME_VAL:
case GET_FILENAME_VAL:
case COPY_IN_FILENAME:
// Filename loads and stores aren't expensive
return true;
case INIT_LOCAL_OUTPUT_FILE:
case INIT_UPDATEABLE_FLOAT:
// Init operations
return true;
case UPDATE_INCR:
case UPDATE_INCR_IMM:
case UPDATE_MIN:
case UPDATE_MIN_IMM:
case UPDATE_SCALE:
case UPDATE_SCALE_IMM:
// Update operations
return true;
case COPY_REF:
case STRUCT_CREATE_ALIAS:
case GET_FILENAME_ALIAS:
case ARR_CREATE_ALIAS:
// Creating alias is cheap
return true;
case DEREF_FILE:
case DEREF_SCALAR:
// Spawning deref is cheap
return true;
case ARR_CONTAINS:
case ARR_COPY_IN_FUTURE:
case ARR_COPY_IN_IMM:
case ARR_COPY_OUT_FUTURE:
case ARR_COPY_OUT_IMM:
case ARR_CREATE_NESTED_FUTURE:
case ARR_CREATE_NESTED_IMM:
case ARR_LOCAL_CONTAINS:
case ARR_RETRIEVE:
case ARR_STORE:
case ARR_STORE_FUTURE:
case ARR_CREATE_BAG:
case AREF_COPY_IN_FUTURE:
case AREF_COPY_IN_IMM:
case AREF_COPY_OUT_FUTURE:
case AREF_COPY_OUT_IMM:
case AREF_CREATE_NESTED_FUTURE:
case AREF_CREATE_NESTED_IMM:
case AREF_STORE_FUTURE:
case AREF_STORE_IMM:
case BAG_INSERT:
case CONTAINER_SIZE:
case CONTAINER_LOCAL_SIZE:
// Container operations aren't too expensive
return true;
case STRUCT_COPY_IN:
case STRUCT_COPY_OUT:
case STRUCT_INIT_FIELDS:
case STRUCT_RETRIEVE_SUB:
case STRUCT_STORE_SUB:
case STRUCTREF_COPY_IN:
case STRUCTREF_COPY_OUT:
case STRUCTREF_STORE_SUB:
// Struct operations aren't too expensive
return true;
case ASYNC_COPY:
// Spawning the task isn't expensive
return true;
case SYNC_COPY:
// Copying a large container may be expensive
return false;
case CHECKPOINT_LOOKUP_ENABLED:
case CHECKPOINT_WRITE_ENABLED:
case CHOOSE_TMP_FILENAME:
case IS_MAPPED:
case GET_LOCAL_FILENAME:
// Utility operations are cheap
return true;
case COPY_FILE_CONTENTS:
// Copying a file can take some time
return false;
case DECR_LOCAL_FILE_REF:
case FREE_BLOB:
// Local refcount manipulations
return true;
case LOOKUP_CHECKPOINT:
return true;
case PACK_VALUES:
case UNPACK_ARRAY_TO_FLAT:
case UNPACK_VALUES:
case STRUCT_LOCAL_BUILD:
return true;
case WRITE_CHECKPOINT:
// May require I/O
return false;
default:
throw new STCRuntimeError("Missing: " + op);
}
}
@Override
public boolean isProgressEnabling() {
switch (op) {
case LOAD_ARRAY:
case LOAD_BAG:
case LOAD_FILE:
case LOAD_RECURSIVE:
case LOAD_REF:
case LOAD_SCALAR:
case LOAD_STRUCT:
case LATEST_VALUE:
case GET_FILENAME_VAL:
// Loads don't do anything
return false;
case STORE_ARRAY:
case STORE_BAG:
case STORE_FILE:
case STORE_RECURSIVE:
case STORE_REF:
case STORE_SCALAR:
case STORE_STRUCT:
case ARRAY_BUILD:
case SET_FILENAME_VAL:
case COPY_IN_FILENAME:
// Stores can enable progress
return true;
case INIT_LOCAL_OUTPUT_FILE:
case INIT_UPDATEABLE_FLOAT:
case STRUCT_INIT_FIELDS:
// Init operations don't enable progress
return false;
case UPDATE_INCR:
case UPDATE_INCR_IMM:
case UPDATE_MIN:
case UPDATE_MIN_IMM:
case UPDATE_SCALE:
case UPDATE_SCALE_IMM:
// Don't want to defer updates
return true;
case COPY_REF:
case STRUCT_CREATE_ALIAS:
case GET_FILENAME_ALIAS:
case ARR_CREATE_ALIAS:
// Creating alias doesn't make progress
return false;
case DEREF_FILE:
case DEREF_SCALAR:
// Deref assigns future
return true;
case ARR_COPY_IN_FUTURE:
case ARR_COPY_IN_IMM:
case ARR_STORE:
case ARR_STORE_FUTURE:
case AREF_COPY_IN_FUTURE:
case AREF_COPY_IN_IMM:
case AREF_STORE_FUTURE:
case AREF_STORE_IMM:
case BAG_INSERT:
// Adding to container can enable progress
return true;
case ARR_CREATE_NESTED_FUTURE:
case ARR_CREATE_NESTED_IMM:
case AREF_CREATE_NESTED_FUTURE:
case AREF_CREATE_NESTED_IMM:
case ARR_CREATE_BAG:
// Creating nested containers can release write refcount on outer
return true;
case ARR_CONTAINS:
case ARR_LOCAL_CONTAINS:
case ARR_RETRIEVE:
case CONTAINER_SIZE:
case CONTAINER_LOCAL_SIZE:
// Retrieving from array won't enable progress
return false;
case ARR_COPY_OUT_FUTURE:
case ARR_COPY_OUT_IMM:
case AREF_COPY_OUT_FUTURE:
case AREF_COPY_OUT_IMM:
// Copying to future can enable progress
return true;
case STRUCT_COPY_IN:
case STRUCT_STORE_SUB:
case STRUCTREF_COPY_IN:
case STRUCTREF_STORE_SUB:
// Adding to struct can enable progress
return true;
case STRUCT_RETRIEVE_SUB:
// Retrieving from struct won't enable progress
return false;
case STRUCT_COPY_OUT:
case STRUCTREF_COPY_OUT:
// Copying to future can enable progress
return true;
case ASYNC_COPY:
// Copying can enable progress
return true;
case SYNC_COPY:
// Copying can enable progress
return true;
case CHECKPOINT_LOOKUP_ENABLED:
case CHECKPOINT_WRITE_ENABLED:
case CHOOSE_TMP_FILENAME:
case IS_MAPPED:
case GET_LOCAL_FILENAME:
// Utility operations don't enable progress
return true;
case COPY_FILE_CONTENTS:
// Copying a file doesn't assign future
return false;
case DECR_LOCAL_FILE_REF:
case FREE_BLOB:
// Local refcount manipulations
return false;
case LOOKUP_CHECKPOINT:
return false;
case PACK_VALUES:
case UNPACK_ARRAY_TO_FLAT:
case UNPACK_VALUES:
case STRUCT_LOCAL_BUILD:
return false;
case WRITE_CHECKPOINT:
// Don't defer writing checkpoint
return true;
default:
throw new STCRuntimeError("Missing: " + op);
}
}
@Override
public List<ValLoc> getResults() {
switch(op) {
case LOAD_SCALAR:
case LOAD_REF:
case LOAD_FILE:
case LOAD_ARRAY:
case LOAD_BAG:
case LOAD_STRUCT:
case LOAD_RECURSIVE: {
Arg src = getInput(0);
Var dst = getOutput(0);
Closed outIsClosed;
if (op == Opcode.LOAD_REF) {
outIsClosed = Closed.MAYBE_NOT;
} else {
outIsClosed = Closed.YES_NOT_RECURSIVE;
}
if (op == Opcode.LOAD_REF) {
// use standard deref value
return ValLoc.derefCompVal(dst, src.getVar(), IsValCopy.NO,
IsAssign.NO).asList();
} else {
return vanillaResult(outIsClosed, IsAssign.NO).asList();
}
}
case STORE_REF:
case STORE_SCALAR:
case STORE_FILE:
case STORE_ARRAY:
case STORE_BAG:
case STORE_STRUCT:
case STORE_RECURSIVE: {
// add assign so we can avoid recreating future
// (closed b/c this instruction closes val immediately)
ValLoc assign = vanillaResult(Closed.YES_NOT_RECURSIVE,
IsAssign.TO_LOCATION);
// add retrieve so we can avoid retrieving later
Arg dst = getOutput(0).asArg();
Arg src = getInput(0);
if (op == Opcode.STORE_REF) {
// Use standard dereference computed value
ValLoc retrieve = ValLoc.derefCompVal(src.getVar(), dst.getVar(),
IsValCopy.NO, IsAssign.NO);
return Arrays.asList(retrieve, assign);
} else {
return assign.asList();
}
}
case IS_MAPPED: {
// Closed because we don't need to wait to check mapping
ValLoc vanilla = vanillaResult(Closed.YES_NOT_RECURSIVE,
IsAssign.TO_LOCATION);
assert(vanilla != null);
Var fileVar = getInput(0).getVar();
if (fileVar.isMapped() == Ternary.MAYBE) {
return vanilla.asList();
} else {
// We know the value already, so check it's a constant
Arg result = Arg.createBoolLit(fileVar.isMapped() == Ternary.TRUE);
return Arrays.asList(vanilla,
ValLoc.makeCopy(getOutput(0), result, IsAssign.NO));
}
}
case GET_FILENAME_ALIAS: {
Arg filename = getOutput(0).asArg();
Var file = getInput(0).getVar();
return ValLoc.makeFilename(filename, file).asList();
}
case COPY_IN_FILENAME: {
Arg filename = getInput(0);
Var file = getOutput(0);
return ValLoc.makeFilename(filename, file).asList();
}
case GET_LOCAL_FILENAME: {
return ValLoc.makeFilenameLocal(getOutput(0).asArg(),
getInput(0).getVar(), IsAssign.TO_LOCATION).asList();
}
case SET_FILENAME_VAL: {
Var file = getOutput(0);
Arg val = getInput(0);
return ValLoc.makeFilenameVal(file, val, IsAssign.TO_VALUE).asList();
}
case GET_FILENAME_VAL: {
Var file = getInput(0).getVar();
Var val = getOutput(0);
return ValLoc.makeFilenameVal(file, val.asArg(), IsAssign.NO).asList();
}
case DEREF_SCALAR:
case DEREF_FILE: {
return ValLoc.derefCompVal(getOutput(0), getInput(0).getVar(),
IsValCopy.YES, IsAssign.NO).asList();
}
case STRUCT_CREATE_ALIAS:
case STRUCT_COPY_OUT:
case STRUCTREF_COPY_OUT: {
// Ops that lookup field in struct somehow
Var struct = getInput(0).getVar();
List<Arg> fields = getInputsTail(1);
ValLoc copyV = ValLoc.makeStructFieldCopyResult(getOutput(0),
struct, fields);
if (op == Opcode.STRUCT_CREATE_ALIAS) {
// Create values to repr both alias and value
ValLoc aliasV = ValLoc.makeStructFieldAliasResult(getOutput(0),
struct, fields);
return Arrays.asList(aliasV, copyV);
} else {
// Not an alias - copy val only
return copyV.asList();
}
}
case STRUCT_RETRIEVE_SUB: {
Var struct = getInput(0).getVar();
List<Arg> fields = getInputsTail(2);
return ValLoc.makeStructFieldValResult(getOutput(0).asArg(),
struct, fields).asList();
}
case STRUCT_INIT_FIELDS: {
List<ValLoc> results = new ArrayList<ValLoc>();
Out<List<List<Arg>>> fieldPaths = new Out<List<List<Arg>>>();
Out<List<Arg>> fieldVals = new Out<List<Arg>>();
unpackStructInitArgs(null, fieldPaths, fieldVals);
Var struct = getOutput(0);
assert(fieldPaths.val.size() == fieldVals.val.size());
for (int i = 0; i < fieldPaths.val.size(); i++) {
results.add(ValLoc.makeStructFieldValResult(fieldVals.val.get(i),
struct, fieldPaths.val.get(i)));
}
return results;
}
case STRUCT_STORE_SUB:
case STRUCTREF_STORE_SUB: {
Var struct = getOutput(0);
Arg val = getInput(0);
List<Arg> fields;
if (op == Opcode.STRUCT_STORE_SUB) {
fields = getInputsTail(1);
} else {
assert(op == Opcode.STRUCTREF_STORE_SUB);
fields = getInputsTail(1);
}
return ValLoc.makeStructFieldValResult(val, struct, fields).asList();
}
case STRUCT_COPY_IN:
case STRUCTREF_COPY_IN: {
Var struct = getOutput(0);
Var val = getInput(0).getVar();
List<Arg> fields = getInputsTail(1);
return ValLoc.makeStructFieldCopyResult(val, struct, fields).asList();
}
case ARR_STORE:
case ARR_STORE_FUTURE:
case AREF_STORE_IMM:
case AREF_STORE_FUTURE:
case ARR_COPY_IN_IMM:
case ARR_COPY_IN_FUTURE:
case AREF_COPY_IN_IMM:
case AREF_COPY_IN_FUTURE: {
// STORE <out array> <in index> <in var>
Var arr;
arr = getOutput(0);
Arg ix = getInput(0);
Arg member = getInput(1);
boolean insertingVal = isArrayValStore(op);
return Arrays.asList(ValLoc.makeArrayResult(arr, ix, member,
insertingVal, IsAssign.TO_VALUE));
}
case ARRAY_BUILD: {
Var arr = getOutput(0);
List<ValLoc> res = new ArrayList<ValLoc>();
// Computed value for whole array
res.add(ValLoc.buildResult(op, getInputs(), arr.asArg(),
Closed.YES_NOT_RECURSIVE, IsAssign.NO));
// For individual array elements
assert(getInputs().size() % 2 == 0);
int elemCount = getInputs().size() / 2;
for (int i = 0; i < elemCount; i++) {
Arg key = getInput(2 * i);
Arg val = getInput(2 * i + 1);
res.add(ValLoc.makeArrayResult(arr, key, val, true,
IsAssign.TO_VALUE));
}
res.add(ValLoc.makeContainerSizeCV(arr,
Arg.createIntLit(elemCount), false, IsAssign.NO));
return res;
}
case ARR_CREATE_ALIAS:
case ARR_RETRIEVE:
case ARR_COPY_OUT_IMM:
case ARR_COPY_OUT_FUTURE:
case AREF_COPY_OUT_FUTURE:
case AREF_COPY_OUT_IMM: {
// LOAD <out var> <in array> <in index>
Var arr = getInput(0).getVar();
Arg ix = getInput(1);
Var contents = getOutput(0);
if (op == Opcode.ARR_RETRIEVE) {
// This just retrieves the item immediately
return ValLoc.makeArrayResult(arr, ix, contents.asArg(),
true, IsAssign.NO).asList();
} else if (op == Opcode.ARR_CREATE_ALIAS) {
ValLoc memVal = ValLoc.makeArrayResult(arr, ix, contents.asArg(),
false, IsAssign.NO);
ValLoc memAlias = ValLoc.makeArrayAlias(arr, ix, contents.asArg(),
IsAssign.NO);
return Arrays.asList(memVal, memAlias);
} else {
assert (Types.isElemType(arr, contents));
// Will assign the reference
return ValLoc.makeArrayResult(arr, ix, contents.asArg(), false,
IsAssign.TO_LOCATION).asList();
}
}
case ARR_CREATE_NESTED_FUTURE:
case ARR_CREATE_NESTED_IMM:
case AREF_CREATE_NESTED_FUTURE:
case AREF_CREATE_NESTED_IMM:
case ARR_CREATE_BAG: {
// CREATE_NESTED <out inner array> <in array> <in index>
// OR
// CREATE_BAG <out inner bag> <in array> <in index>
Var nestedArr = getOutput(0);
Var arr = getOutput(1);
Arg ix = getInput(0);
List<ValLoc> res = new ArrayList<ValLoc>();
boolean returnsNonRef = op == Opcode.ARR_CREATE_NESTED_IMM ||
op == Opcode.ARR_CREATE_BAG;
// Mark as not substitutable since this op may have
// side-effect of creating array
res.add(ValLoc.makeArrayResult(arr, ix, nestedArr.asArg(),
returnsNonRef, IsAssign.NO));
res.add(ValLoc.makeCreateNestedResult(arr, ix, nestedArr,
returnsNonRef));
return res;
}
case SYNC_COPY:
case ASYNC_COPY: {
return ValLoc.makeCopy(getOutput(0), getInput(0),
IsAssign.TO_LOCATION).asList();
}
case COPY_REF: {
Var srcRef = getInput(0).getVar();
return ValLoc.makeAlias(getOutput(0), srcRef).asList();
}
case LOOKUP_CHECKPOINT:
case UNPACK_VALUES: {
// Both have multiple outputs
List<ValLoc> res = new ArrayList<ValLoc>(outputs.size());
for (int i = 0; i < outputs.size(); i++) {
Var out = outputs.get(i);
res.add(ValLoc.buildResult(op,
(Object)i, getInput(0).asList(), out.asArg(),
Closed.YES_RECURSIVE, IsValCopy.NO, IsAssign.NO));
}
return res;
}
case PACK_VALUES:
return vanillaResult(Closed.YES_NOT_RECURSIVE, IsAssign.NO).asList();
case CHECKPOINT_LOOKUP_ENABLED:
case CHECKPOINT_WRITE_ENABLED:
return vanillaResult(Closed.YES_NOT_RECURSIVE, IsAssign.NO).asList();
case UNPACK_ARRAY_TO_FLAT:
return vanillaResult(Closed.YES_NOT_RECURSIVE, IsAssign.NO).asList();
case ARR_CONTAINS:
case CONTAINER_SIZE:
case ARR_LOCAL_CONTAINS:
case CONTAINER_LOCAL_SIZE:
return vanillaResult(Closed.YES_NOT_RECURSIVE, IsAssign.NO).asList();
case STRUCT_LOCAL_BUILD:
// Worth optimising?
return null;
default:
return null;
}
}
private boolean isArrayValStore(Opcode op) {
switch (op) {
case ARR_STORE:
case ARR_STORE_FUTURE:
case AREF_STORE_IMM:
case AREF_STORE_FUTURE:
return true;
default:
return false;
}
}
/**
* Create the "standard" computed value
* assume 1 output arg
* @return
*/
private ValLoc vanillaResult(Closed closed, IsAssign isAssign) {
assert(outputs.size() == 1);
return ValLoc.buildResult(op, inputs, outputs.get(0).asArg(), closed,
isAssign);
}
@Override
public List<Var> getClosedOutputs() {
if (op == Opcode.ARRAY_BUILD || op == Opcode.SYNC_COPY ||
op == Opcode.SYNC_COPY) {
// Output array should be closed
return Collections.singletonList(getOutput(0));
} else if (op == Opcode.STORE_REF) {
return Collections.singletonList(getOutput(0));
}
return super.getClosedOutputs();
}
@Override
public Instruction clone() {
return new TurbineOp(op, new ArrayList<Var>(outputs),
new ArrayList<Arg>(inputs));
}
@Override
public Pair<List<VarCount>, List<VarCount>> inRefCounts(
Map<String, Function> functions) {
switch (op) {
case STORE_REF:
return Pair.create(VarCount.one(getInput(0).getVar()).asList(),
VarCount.NONE);
case ARRAY_BUILD: {
List<VarCount> readIncr = new ArrayList<VarCount>();
for (int i = 0; i < getInputs().size() / 2; i++) {
// Skip keys and only get values
Arg elem = getInput(i * 2 + 1);
// Container gets reference to member
if (elem.isVar() && RefCounting.trackReadRefCount(elem.getVar())) {
readIncr.add(VarCount.one(elem.getVar()));
}
}
Var arr = getOutput(0);
return Pair.create(readIncr, VarCount.one(arr).asList());
}
case ASYNC_COPY:
case SYNC_COPY: {
// Need to pass in refcount for var to be copied, and write
// refcount for assigned var if write refcounti tracked
List<VarCount> writeRefs;
if (RefCounting.trackWriteRefCount(getOutput(0))) {
writeRefs = VarCount.one(getOutput(0)).asList();
} else {
writeRefs = VarCount.NONE;
}
return Pair.create(VarCount.one(getInput(0).getVar()).asList(),
writeRefs);
}
case STORE_BAG:
case STORE_ARRAY:
case STORE_STRUCT:
case STORE_RECURSIVE: {
// Inputs stored into array need to have refcount incremented
// This finalizes array so will consume refcount
return Pair.create(VarCount.one(getInput(0).getVar()).asList(),
VarCount.one(getOutput(0)).asList());
}
case DEREF_SCALAR:
case DEREF_FILE: {
// Increment refcount of ref var
return Pair.create(VarCount.one(getInput(0).getVar()).asList(),
VarCount.NONE);
}
case AREF_COPY_OUT_FUTURE:
case ARR_COPY_OUT_FUTURE: {
// Array and index
return Pair.create(Arrays.asList(
VarCount.one(getInput(0).getVar()), VarCount.one(getInput(1).getVar())),
VarCount.NONE);
}
case AREF_COPY_OUT_IMM:
case ARR_COPY_OUT_IMM: {
// Array only
return Pair.create(
VarCount.one(getInput(0).getVar()).asList(),
VarCount.NONE);
}
case ARR_CONTAINS:
case CONTAINER_SIZE: {
// Executes immediately, doesn't need refcount
return Pair.create(VarCount.NONE, VarCount.NONE);
}
case ARR_RETRIEVE: {
VarCount readDecr = new VarCount(getInput(0).getVar(),
getInput(2).getIntLit());
return Pair.create(readDecr.asList(), VarCount.NONE);
}
case ARR_STORE: {
Arg mem = getInput(1);
// Increment reference to memberif needed
List<VarCount> readIncr;
if (mem.isVar() && RefCounting.trackReadRefCount(mem.getVar())) {
readIncr = VarCount.one(mem.getVar()).asList();
} else {
readIncr = VarCount.NONE;
}
return Pair.create(readIncr, VarCount.NONE);
}
case ARR_COPY_IN_IMM: {
// Increment reference to member ref
// Increment writers count on array
Var mem = getInput(1).getVar();
return Pair.create(VarCount.one(mem).asList(),
VarCount.one(getOutput(0)).asList());
}
case ARR_STORE_FUTURE:
case ARR_COPY_IN_FUTURE: {
// Increment reference to member/member ref and index future
// Increment writers count on array
Var arr = getInput(0).getVar();
Arg mem = getInput(1);
List<VarCount> readIncr;
if (mem.isVar() && RefCounting.trackReadRefCount(mem.getVar())) {
readIncr = Arrays.asList(VarCount.one(arr),
VarCount.one(mem.getVar()));
} else {
readIncr = VarCount.one(arr).asList();
}
return Pair.create(readIncr, VarCount.one((getOutput(0))).asList());
}
case AREF_STORE_IMM:
case AREF_COPY_IN_IMM:
case AREF_STORE_FUTURE:
case AREF_COPY_IN_FUTURE: {
Arg ix = getInput(0);
Arg mem = getInput(1);
Var arrayRef = getOutput(0);
List<VarCount> readers = new ArrayList<VarCount>(3);
readers.add(VarCount.one(arrayRef));
if (mem.isVar() && RefCounting.trackReadRefCount(mem.getVar())) {
readers.add(VarCount.one(mem.getVar()));
}
if (op == Opcode.AREF_STORE_FUTURE ||
op == Opcode.AREF_COPY_IN_FUTURE) {
readers.add(VarCount.one(ix.getVar()));
} else {
assert(op == Opcode.AREF_STORE_IMM ||
op == Opcode.AREF_COPY_IN_IMM);
}
// Management of reference counts from array ref is handled by runtime
return Pair.create(readers, VarCount.NONE);
}
case ARR_CREATE_NESTED_FUTURE: {
Var srcArray = getOutput(1);
Var ix = getInput(0).getVar();
return Pair.create(VarCount.one(ix).asList(),
VarCount.one(srcArray).asList());
}
case AREF_CREATE_NESTED_IMM:
case AREF_CREATE_NESTED_FUTURE: {
Var arr = getOutput(1);
Arg ixArg = getInput(0);
List<VarCount> readVars;
if (op == Opcode.AREF_CREATE_NESTED_IMM) {
readVars = VarCount.one(arr).asList();
} else {
assert(op == Opcode.AREF_CREATE_NESTED_FUTURE);
readVars = Arrays.asList(VarCount.one(arr),
VarCount.one(ixArg.getVar()));
}
// Management of reference counts from array ref is handled by runtime
return Pair.create(readVars, VarCount.NONE);
}
case BAG_INSERT: {
Arg mem = getInput(0);
List<VarCount> readers = VarCount.NONE;
if (mem.isVar() && RefCounting.trackReadRefCount(mem.getVar())) {
readers = VarCount.one(mem.getVar()).asList();
}
return Pair.create(readers, VarCount.NONE);
}
case STRUCT_INIT_FIELDS: {
Out<List<Arg>> fieldVals = new Out<List<Arg>>();
unpackStructInitArgs(null, null, fieldVals);
List<VarCount> readIncr = new ArrayList<VarCount>();
List<VarCount> writeIncr = new ArrayList<VarCount>();
for (Arg fieldVal: fieldVals.val) {
if (fieldVal.isVar()) {
// Need to acquire refcount to pass to struct
Var fieldVar = fieldVal.getVar();
if (RefCounting.trackReadRefCount(fieldVar)) {
readIncr.add(VarCount.one(fieldVar));
}
if (RefCounting.trackWriteRefCount(fieldVar)) {
writeIncr.add(VarCount.one(fieldVar));
}
}
}
return Pair.create(readIncr, writeIncr);
}
case STRUCTREF_COPY_OUT:
case STRUCT_COPY_OUT: {
// Array only
return Pair.create(VarCount.one(getInput(0).getVar()).asList(),
VarCount.NONE);
}
case STRUCT_STORE_SUB:
case STRUCT_COPY_IN:
case STRUCTREF_STORE_SUB:
case STRUCTREF_COPY_IN:
// Do nothing: reference count tracker can track variables
// across struct boundaries
// TODO: still right?
return Pair.create(VarCount.NONE, VarCount.NONE);
case COPY_REF: {
return Pair.create(VarCount.one(getInput(0).getVar()).asList(),
VarCount.one(getInput(0).getVar()).asList());
}
case COPY_IN_FILENAME: {
// Read for input filename
return Pair.create(VarCount.one(getInput(0).getVar()).asList(),
VarCount.NONE);
}
case UPDATE_INCR:
case UPDATE_MIN:
case UPDATE_SCALE:
// Consumes a read refcount for the input argument and
// write refcount for updated variable
return Pair.create(VarCount.one(getInput(0).getVar()).asList(),
VarCount.one(getOutput(0)).asList());
default:
// Default is nothing
return Pair.create(VarCount.NONE, VarCount.NONE);
}
}
@Override
public Pair<List<VarCount>, List<VarCount>> outRefCounts(
Map<String, Function> functions) {
switch (this.op) {
case COPY_REF: {
// We incremented refcounts for orig. var, now need to decrement
// refcount on alias vars
Var newAlias = getOutput(0);
return Pair.create(VarCount.one(newAlias).asList(),
VarCount.one(newAlias).asList());
}
case LOAD_REF: {
// Load_ref will increment reference count of referand
Var v = getOutput(0);
long readRefs = getInput(1).getIntLit();
long writeRefs = getInput(2).getIntLit();
// TODO: return actual # of refs
return Pair.create(new VarCount(v, readRefs).asList(),
new VarCount(v, writeRefs).asList());
}
case STRUCT_RETRIEVE_SUB: {
// Gives back a read refcount to the result if relevant
// TODO: change to optionally get back write increment?
return Pair.create(VarCount.one(getOutput(0)).asList(),
VarCount.NONE);
}
case ARR_RETRIEVE: {
// Gives back a refcount to the result if relevant
return Pair.create(VarCount.one(getOutput(0)).asList(), VarCount.NONE);
}
case ARR_CREATE_NESTED_IMM: {
long readIncr = getInput(1).getIntLit();
long writeIncr = getInput(2).getIntLit();
Var resultArr = getOutput(0);
return Pair.create(new VarCount(resultArr, readIncr).asList(),
new VarCount(resultArr, writeIncr).asList());
}
// TODO: other array/struct retrieval funcs
default:
return Pair.create(VarCount.NONE, VarCount.NONE);
}
}
@Override
public Var tryPiggyback(RefCountsToPlace increments, RefCountType type) {
switch (op) {
case LOAD_SCALAR:
case LOAD_FILE:
case LOAD_ARRAY:
case LOAD_BAG:
case LOAD_STRUCT:
case LOAD_RECURSIVE: {
Var inVar = getInput(0).getVar();
if (type == RefCountType.READERS) {
long amt = increments.getCount(inVar);
if (amt < 0) {
assert(getInputs().size() == 1);
// Add extra arg
this.inputs = Arrays.asList(getInput(0),
Arg.createIntLit(amt * -1));
return inVar;
}
}
break;
}
case LOAD_REF:
Var inVar = getInput(0).getVar();
if (type == RefCountType.READERS) {
long amt = increments.getCount(inVar);
if (amt < 0) {
assert(getInputs().size() == 3);
// Add extra arg
this.inputs = Arrays.asList(getInput(0), getInput(1), getInput(2),
Arg.createIntLit(amt * -1));
return inVar;
}
}
break;
case ARR_STORE:
case ARR_COPY_IN_IMM:
case ARR_STORE_FUTURE:
case ARR_COPY_IN_FUTURE: {
Var arr = getOutput(0);
if (type == RefCountType.WRITERS) {
long amt = increments.getCount(arr);
if (amt < 0) {
assert(getInputs().size() == 2);
// All except the fully immediate version decrement by 1 by default
int defaultDecr = op == Opcode.ARR_STORE ? 0 : 1;
Arg decrArg = Arg.createIntLit(amt * -1 + defaultDecr);
this.inputs = Arrays.asList(getInput(0), getInput(1), decrArg);
return arr;
}
}
break;
}
case ARR_RETRIEVE: {
Var arr = getInput(0).getVar();
assert(getInputs().size() == 3);
return tryPiggyBackHelper(increments, type, arr, 2, -1);
}
case ARR_CREATE_NESTED_IMM:
case ARR_CREATE_BAG: {
// Instruction can give additional refcounts back
Var nested = getOutput(0);
assert(getInputs().size() == 3);
// TODO: piggyback decrements here
// TODO: only works if we default to giving back refcounts
return tryPiggyBackHelper(increments, type, nested, 1, 2);
}
case BAG_INSERT: {
Var bag = getOutput(0);
return tryPiggyBackHelper(increments, type, bag, -1, 1);
}
case STRUCT_INIT_FIELDS:
return tryPiggyBackHelper(increments, type, getOutput(0), -1,
inputs.size() - 1);
case STRUCT_RETRIEVE_SUB:
return tryPiggyBackHelper(increments, type, getInput(0).getVar(),
1, -1);
default:
// Do nothing
}
// Fall through to here if can do nothing
return null;
}
/**
* Try to piggyback by applying refcount to an argument
* @param increments
* @param type
* @param var the variable with refcount being managed
* @param readDecrInput input index of read refcount arg, negative if none
* @param writeDecrInput input index of write refcount arg, negative if none
* @return
*/
private Var tryPiggyBackHelper(RefCountsToPlace increments,
RefCountType type, Var var, int readDecrInput, int writeDecrInput) {
long amt = increments.getCount(var);
if (amt < 0) {
// Which argument is increment
int inputPos;
if (type == RefCountType.READERS) {
inputPos = readDecrInput;
} else {
assert(type == RefCountType.WRITERS);
inputPos = writeDecrInput;
}
if (inputPos < 0) {
// No input
return null;
}
assert(inputPos < inputs.size());
Arg oldAmt = getInput(inputPos);
if (oldAmt.isIntVal()) {
setInput(inputPos, Arg.createIntLit(oldAmt.getIntLit() - amt));
return var;
}
}
return null;
}
@Override
public List<Alias> getAliases() {
switch (this.op) {
case ARR_CREATE_ALIAS:
return Alias.makeArrayAlias(getInput(0).getVar(), getInput(1),
getOutput(0), AliasTransform.IDENTITY);
case STRUCT_CREATE_ALIAS:
return Alias.makeStructAliases2(getInput(0).getVar(), getInputsTail(1),
getOutput(0), AliasTransform.IDENTITY);
case STRUCT_INIT_FIELDS: {
Out<List<List<String>>> fieldPaths = new Out<List<List<String>>>();
Out<List<Arg>> fieldVals = new Out<List<Arg>>();
List<Alias> aliases = new ArrayList<Alias>();
unpackStructInitArgs(fieldPaths, null, fieldVals);
assert (fieldPaths.val.size() == fieldVals.val.size());
for (int i = 0; i < fieldPaths.val.size(); i++) {
List<String> fieldPath = fieldPaths.val.get(i);
Arg fieldVal = fieldVals.val.get(i);
if (fieldVal.isVar()) {
aliases.addAll(Alias.makeStructAliases(getOutput(0), fieldPath,
fieldVal.getVar(), AliasTransform.RETRIEVE));
}
}
return aliases;
}
case STRUCT_RETRIEVE_SUB:
return Alias.makeStructAliases2(getInput(0).getVar(), getInputsTail(2),
getOutput(0), AliasTransform.RETRIEVE);
case STRUCT_STORE_SUB:
if (getInput(0).isVar()) {
return Alias.makeStructAliases2(getOutput(0), getInputsTail(1),
getInput(0).getVar(), AliasTransform.RETRIEVE);
}
break;
case STRUCT_COPY_OUT:
return Alias.makeStructAliases2(getInput(0).getVar(), getInputsTail(1),
getOutput(0), AliasTransform.COPY);
case STRUCT_COPY_IN:
return Alias.makeStructAliases2(getOutput(0), getInputsTail(1),
getInput(0).getVar(), AliasTransform.COPY);
case STORE_REF: {
// need to track if ref is alias to struct field
Var ref = getOutput(0);
Var val = getInput(0).getVar();
return new Alias(ref, Collections.<String>emptyList(),
AliasTransform.RETRIEVE, val).asList();
}
case LOAD_REF: {
// need to track if ref is alias to struct field
Var val = getOutput(0);
Var ref = getInput(0).getVar();
return new Alias(ref, Collections.<String>emptyList(),
AliasTransform.RETRIEVE, val).asList();
}
case COPY_REF: {
// need to track if ref is alias to struct field
Var ref1 = getOutput(0);
Var ref2 = getInput(0).getVar();
return Arrays.asList(
new Alias(ref1, Collections.<String>emptyList(),
AliasTransform.COPY, ref2),
new Alias(ref2, Collections.<String>emptyList(),
AliasTransform.COPY, ref1));
}
case GET_FILENAME_ALIAS: {
return new Alias(getInput(0).getVar(), Alias.FILENAME_PATH,
AliasTransform.IDENTITY, getOutput(0)).asList();
}
default:
// Opcode not relevant
break;
}
return Alias.NONE;
}
@Override
public List<ComponentAlias> getComponentAliases() {
switch (op) {
case ARR_CREATE_NESTED_IMM:
case ARR_CREATE_BAG:
// From inner object to immediately enclosing
return new ComponentAlias(getOutput(1), Component.deref(getInput(0).asList()),
getOutput(0)).asList();
case ARR_CREATE_NESTED_FUTURE: {
// From inner array to immediately enclosing
return new ComponentAlias(getOutput(1), getInput(0).asList(),
getOutput(0)).asList();
}
case AREF_CREATE_NESTED_IMM:
case AREF_CREATE_NESTED_FUTURE: {
List<Arg> key = Arrays.asList(Component.DEREF, getInput(0));
// From inner array to immediately enclosing
return new ComponentAlias(getOutput(1), key, getOutput(0)).asList();
}
case AREF_STORE_FUTURE:
case AREF_STORE_IMM:
case ARR_STORE:
case ARR_STORE_FUTURE: {
Var arr = getOutput(0);
if (Types.isRef(Types.arrayKeyType(arr))) {
Arg ix = getInput(0);
List<Arg> key;
if (Types.isArrayRef(arr)) {
// Mark extra dereference
key = Arrays.asList(Component.DEREF, ix, Component.DEREF);
} else {
key = Arrays.asList(ix, Component.DEREF);
}
return new ComponentAlias(arr, key, getInput(1).getVar()).asList();
}
break;
}
case ARR_COPY_IN_FUTURE:
case ARR_COPY_IN_IMM:
case AREF_COPY_IN_FUTURE:
case AREF_COPY_IN_IMM: {
Var arr = getOutput(0);
if (Types.isRef(Types.arrayKeyType(arr))) {
Arg ix = getInput(0);
List<Arg> key;
if (Types.isArrayRef(arr)) {
// Mark extra dereference
key = Arrays.asList(Component.DEREF, ix);
} else {
key = ix.asList();
}
return new ComponentAlias(arr, key, getInput(1).getVar()).asList();
}
break;
}
case ARR_CREATE_ALIAS: {
return new ComponentAlias(getInput(0).getVar(), getInput(1),
getOutput(0)).asList();
}
case ARR_COPY_OUT_FUTURE:
case ARR_COPY_OUT_IMM:
case AREF_COPY_OUT_FUTURE:
case AREF_COPY_OUT_IMM: {
Var arr = getInput(0).getVar();
if (Types.isRef(Types.arrayKeyType(arr))) {
Arg ix = getInput(1);
List<Arg> key;
if (Types.isArrayRef(arr)) {
// Mark extra dereference
key = Arrays.asList(Component.DEREF, ix);
} else {
key = ix.asList();
}
return new ComponentAlias(arr, key, getOutput(0)).asList();
}
break;
}
case LOAD_REF:
// If reference was a part of something, modifying the
// dereferenced object will modify the whole
return ComponentAlias.ref(getOutput(0), getInput(0).getVar()).asList();
case COPY_REF:
return ComponentAlias.directAlias(getOutput(0), getInput(0).getVar()).asList();
case STORE_REF:
// Sometimes a reference is filled in
return ComponentAlias.ref(getInput(0).getVar(), getOutput(0)).asList();
case STRUCT_INIT_FIELDS: {
Out<List<List<Arg>>> fieldPaths = new Out<List<List<Arg>>>();
Out<List<Arg>> fieldVals = new Out<List<Arg>>();
List<ComponentAlias> aliases = new ArrayList<ComponentAlias>();
unpackStructInitArgs(null, fieldPaths, fieldVals);
assert (fieldPaths.val.size() == fieldVals.val.size());
Var struct = getOutput(0);
for (int i = 0; i < fieldPaths.val.size(); i++) {
List<Arg> fieldPath = fieldPaths.val.get(i);
Arg fieldVal = fieldVals.val.get(i);
if (fieldVal.isVar()) {
if (Alias.fieldIsRef(struct, Arg.extractStrings(fieldPath))) {
aliases.add(new ComponentAlias(struct, Component.deref(fieldPath),
fieldVal.getVar()));
}
}
}
return aliases;
}
case STRUCT_CREATE_ALIAS: {
// Output is alias for part of struct
List<Arg> fields = getInputsTail(1);
return new ComponentAlias(getInput(0).getVar(), fields,
getOutput(0)).asList();
}
case STRUCTREF_STORE_SUB:
case STRUCT_STORE_SUB:
if (Alias.fieldIsRef(getOutput(0),
Arg.extractStrings(getInputsTail(1)))) {
List<Arg> fields = getInputsTail(1);
if (op == Opcode.STRUCTREF_STORE_SUB) {
// Mark extra dereference
fields = new ArrayList<Arg>(fields);
fields.add(0, Component.DEREF);
}
return new ComponentAlias(getOutput(0), Component.deref(fields),
getInput(0).getVar()).asList();
}
break;
case STRUCT_RETRIEVE_SUB:
if (Alias.fieldIsRef(getInput(0).getVar(),
Arg.extractStrings(getInputsTail(2)))) {
List<Arg> fields = getInputsTail(1);
return new ComponentAlias(getInput(0).getVar(), Component.deref(fields),
getOutput(0)).asList();
}
break;
case STRUCTREF_COPY_IN:
case STRUCT_COPY_IN:
if (Alias.fieldIsRef(getOutput(0),
Arg.extractStrings(getInputsTail(1)))) {
List<Arg> fields = getInputsTail(1);
if (op == Opcode.STRUCTREF_COPY_IN) {
// Mark extra dereference
fields = new ArrayList<Arg>(fields);
fields.add(0, Component.DEREF);
}
return new ComponentAlias(getOutput(0),
fields, getInput(0).getVar()).asList();
}
break;
case STRUCTREF_COPY_OUT:
case STRUCT_COPY_OUT:
if (Alias.fieldIsRef(getInput(0).getVar(),
Arg.extractStrings(getInputsTail(1)))) {
List<Arg> fields = getInputsTail(1);
return new ComponentAlias(getInput(0).getVar(),
fields, getOutput(0)).asList();
}
break;
default:
// Return nothing
break;
}
return Collections.emptyList();
}
public boolean isIdempotent() {
switch (op) {
case ARR_CREATE_NESTED_FUTURE:
case ARR_CREATE_NESTED_IMM:
case AREF_CREATE_NESTED_FUTURE:
case AREF_CREATE_NESTED_IMM:
case ARR_CREATE_BAG:
return true;
default:
return false;
}
}
/**
* Instruction class specifically for reference counting operations with
* defaults derived from TurbineOp
*/
public static class RefCountOp extends TurbineOp {
/**
* Direction of change (increment or decrement)
*/
public static enum RCDir {
INCR,
DECR;
public static RCDir fromAmount(long amount) {
if (amount >= 0) {
return INCR;
} else {
return DECR;
}
}
};
public RefCountOp(Var target, RCDir dir, RefCountType type, Arg amount) {
super(getRefCountOp(dir, type), Var.NONE,
Arrays.asList(target.asArg(), amount));
}
public static RefCountOp decrWriters(Var target, Arg amount) {
return new RefCountOp(target, RCDir.DECR, RefCountType.WRITERS, amount);
}
public static RefCountOp incrWriters(Var target, Arg amount) {
return new RefCountOp(target, RCDir.INCR, RefCountType.WRITERS, amount);
}
public static RefCountOp decrRef(Var target, Arg amount) {
return new RefCountOp(target, RCDir.DECR, RefCountType.READERS, amount);
}
public static RefCountOp incrRef(Var target, Arg amount) {
return new RefCountOp(target, RCDir.INCR, RefCountType.READERS, amount);
}
public static RefCountOp decrRef(RefCountType rcType, Var v, Arg amount) {
return new RefCountOp(v, RCDir.DECR, rcType, amount);
}
public static RefCountOp incrRef(RefCountType rcType, Var v, Arg amount) {
return new RefCountOp(v, RCDir.INCR, rcType, amount);
}
public static RefCountType getRCType(Opcode op) {
assert(isRefcountOp(op));
if (op == Opcode.INCR_READERS || op == Opcode.DECR_READERS) {
return RefCountType.READERS;
} else {
assert(op == Opcode.INCR_WRITERS || op == Opcode.DECR_WRITERS);
return RefCountType.WRITERS;
}
}
public static Var getRCTarget(Instruction refcountOp) {
assert(isRefcountOp(refcountOp.op));
return refcountOp.getInput(0).getVar();
}
public static Arg getRCAmount(Instruction refcountOp) {
assert(isRefcountOp(refcountOp.op));
return refcountOp.getInput(1);
}
private static Opcode getRefCountOp(RCDir dir, RefCountType type) {
if (type == RefCountType.READERS) {
if (dir == RCDir.INCR) {
return Opcode.INCR_READERS;
} else {
assert(dir == RCDir.DECR);
return Opcode.DECR_READERS;
}
} else {
assert(type == RefCountType.WRITERS);
if (dir == RCDir.INCR) {
return Opcode.INCR_WRITERS;
} else {
assert(dir == RCDir.DECR);
return Opcode.DECR_WRITERS;
}
}
}
private static RCDir getRefcountDir(Opcode op) {
if (isIncrement(op)) {
return RCDir.INCR;
} else {
assert(isDecrement(op));
return RCDir.DECR;
}
}
public static boolean isIncrement(Opcode op) {
return (op == Opcode.INCR_READERS || op == Opcode.INCR_WRITERS);
}
public static boolean isDecrement(Opcode op) {
return (op == Opcode.DECR_READERS || op == Opcode.DECR_WRITERS);
}
public static boolean isRefcountOp(Opcode op) {
return isIncrement(op) || isDecrement(op);
}
@Override
public void generate(Logger logger, CompilerBackend gen, GenInfo info) {
switch (op) {
case DECR_WRITERS:
gen.decrWriters(getRCTarget(this), getRCAmount(this));
break;
case INCR_WRITERS:
gen.incrWriters(getRCTarget(this), getRCAmount(this));
break;
case DECR_READERS:
gen.decrRef(getRCTarget(this), getRCAmount(this));
break;
case INCR_READERS:
gen.incrRef(getRCTarget(this), getRCAmount(this));
break;
default:
throw new STCRuntimeError("Unknown op type: " + op);
}
}
@Override
public TaskMode getMode() {
// Executes right away
return TaskMode.SYNC;
}
@Override
public List<ExecContext> supportedContexts() {
return ExecContext.ALL;
}
@Override
public boolean isCheap() {
return true;
}
@Override
public boolean isProgressEnabling() {
// Decrementing write refcount can close
return getRCType(op) == RefCountType.WRITERS;
}
@Override
public boolean hasSideEffects() {
// Model refcount change as side-effect
return true;
}
@Override
public Instruction clone() {
return new RefCountOp(getRCTarget(this), getRefcountDir(this.op),
getRCType(this.op), getRCAmount(this));
}
}
}
|
code/src/exm/stc/ic/tree/TurbineOp.java
|
package exm.stc.ic.tree;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import exm.stc.common.CompilerBackend;
import exm.stc.common.exceptions.STCRuntimeError;
import exm.stc.common.lang.Arg;
import exm.stc.common.lang.Arg.ArgKind;
import exm.stc.common.lang.ExecContext;
import exm.stc.common.lang.Operators.UpdateMode;
import exm.stc.common.lang.RefCounting;
import exm.stc.common.lang.RefCounting.RefCountType;
import exm.stc.common.lang.TaskMode;
import exm.stc.common.lang.Types;
import exm.stc.common.lang.Types.StructType;
import exm.stc.common.lang.Types.Type;
import exm.stc.common.lang.Types.Typed;
import exm.stc.common.lang.Var;
import exm.stc.common.lang.Var.Alloc;
import exm.stc.common.lang.Var.VarCount;
import exm.stc.common.util.Out;
import exm.stc.common.util.Pair;
import exm.stc.common.util.TernaryLogic.Ternary;
import exm.stc.ic.ICUtil;
import exm.stc.ic.aliases.Alias;
import exm.stc.ic.aliases.Alias.AliasTransform;
import exm.stc.ic.componentaliases.Component;
import exm.stc.ic.componentaliases.ComponentAlias;
import exm.stc.ic.opt.valuenumber.ComputedValue.ArgCV;
import exm.stc.ic.opt.valuenumber.ValLoc;
import exm.stc.ic.opt.valuenumber.ValLoc.Closed;
import exm.stc.ic.opt.valuenumber.ValLoc.IsAssign;
import exm.stc.ic.opt.valuenumber.ValLoc.IsValCopy;
import exm.stc.ic.refcount.RefCountsToPlace;
import exm.stc.ic.tree.ICInstructions.Instruction;
import exm.stc.ic.tree.ICTree.Function;
import exm.stc.ic.tree.ICTree.GenInfo;
import exm.stc.ic.tree.ICTree.Program;
import exm.stc.ic.tree.ICTree.RenameMode;
import exm.stc.ic.tree.ICTree.Statement;
/**
* Class to represent builtin Turbine operations with fixed number
* of arguments
*/
public class TurbineOp extends Instruction {
/** Private constructor: use static methods to create */
private TurbineOp(Opcode op, List<Var> outputs, List<Arg> inputs) {
super(op);
this.outputs = initArgList(outputs);
this.inputs = initArgList(inputs);
}
private static Class<? extends Object> SINGLETON_LIST =
Collections.singletonList(null).getClass();
/**
* Initialize args as list that support .set() operation.
* @param args
* @return
*/
private static <T> List<T> initArgList(List<T> args) {
if (args.isEmpty()) {
// Nothing will be mutated in list, so use placeholder
return Collections.emptyList();
} else if (SINGLETON_LIST.isInstance(args)) {
// Avoid known-bad list classes
return new ArrayList<T>(args);
} else {
return args;
}
}
private TurbineOp(Opcode op, Var output, Arg ...inputs) {
this(op, Arrays.asList(output), Arrays.asList(inputs));
}
private TurbineOp(Opcode op, List<Var> outputs, Arg ...inputs) {
this(op, outputs, Arrays.asList(inputs));
}
private List<Var> outputs; /** Variables that are modified by this instruction */
private List<Arg> inputs; /** Variables that are read-only */
@Override
public String toString() {
String result = op.toString().toLowerCase();
for (Var o: outputs) {
result += " " + o.name();
}
for (Arg i: inputs) {
result += " " + i.toString();
}
return result;
}
@Override
public void generate(Logger logger, CompilerBackend gen, GenInfo info) {
// Recreate calls that were used to generate this instruction
switch (op) {
case STORE_SCALAR:
gen.assignScalar(getOutput(0), getInput(0));
break;
case STORE_FILE:
gen.assignFile(getOutput(0), getInput(0), getInput(1));
break;
case STORE_REF:
gen.assignReference(getOutput(0), getInput(0).getVar());
break;
case STORE_ARRAY:
gen.assignArray(getOutput(0), getInput(0));
break;
case STORE_BAG:
gen.assignBag(getOutput(0), getInput(0));
break;
case STORE_STRUCT:
gen.assignStruct(getOutput(0), getInput(0));
break;
case STORE_RECURSIVE:
gen.assignRecursive(getOutput(0), getInput(0));
break;
case ARR_RETRIEVE:
gen.arrayRetrieve(getOutput(0), getInput(0).getVar(),
getInput(1), getInput(2));
break;
case ARR_CREATE_ALIAS:
gen.arrayCreateAlias(getOutput(0), getInput(0).getVar(),
getInput(1));
break;
case ARR_COPY_OUT_IMM:
gen.arrayCopyOutImm(getOutput(0), getInput(0).getVar(), getInput(1));
break;
case ARR_COPY_OUT_FUTURE:
gen.arrayCopyOutFuture(getOutput(0), getInput(0).getVar(),
getInput(1).getVar());
break;
case AREF_COPY_OUT_IMM:
gen.arrayRefCopyOutImm(getOutput(0), getInput(0).getVar(), getInput(1));
break;
case AREF_COPY_OUT_FUTURE:
gen.arrayRefCopyOutFuture(getOutput(0), getInput(0).getVar(),
getInput(1).getVar());
break;
case ARR_CONTAINS:
gen.arrayContains(getOutput(0), getInput(0).getVar(), getInput(1));
break;
case CONTAINER_SIZE:
gen.containerSize(getOutput(0), getInput(0).getVar());
break;
case ARR_LOCAL_CONTAINS:
gen.arrayLocalContains(getOutput(0), getInput(0).getVar(), getInput(1));
break;
case CONTAINER_LOCAL_SIZE:
gen.containerLocalSize(getOutput(0), getInput(0).getVar());
break;
case ARR_STORE:
gen.arrayStore(getOutput(0), getInput(0), getInput(1),
getInputs().size() == 3 ? getInput(2) : Arg.ZERO);
break;
case ARR_STORE_FUTURE:
gen.arrayStoreFuture(getOutput(0), getInput(0).getVar(),
getInput(1),
getInputs().size() == 3 ? getInput(2) : Arg.ONE);
break;
case AREF_STORE_IMM:
gen.arrayRefStoreImm(getOutput(0), getInput(0), getInput(1));
break;
case AREF_STORE_FUTURE:
gen.arrayRefStoreFuture(getOutput(0), getInput(0).getVar(), getInput(1));
break;
case ARR_COPY_IN_IMM:
gen.arrayCopyInImm(getOutput(0), getInput(0), getInput(1).getVar(),
getInputs().size() == 3 ? getInput(2) : Arg.ONE);
break;
case ARR_COPY_IN_FUTURE:
gen.arrayCopyInFuture(getOutput(0), getInput(0).getVar(),
getInput(1).getVar(),
getInputs().size() == 3 ? getInput(2) : Arg.ONE);
break;
case AREF_COPY_IN_IMM:
gen.arrayRefCopyInImm(getOutput(0), getInput(0), getInput(1).getVar());
break;
case AREF_COPY_IN_FUTURE:
gen.arrayRefCopyInFuture(getOutput(0),
getInput(0).getVar(), getInput(1).getVar());
break;
case ARRAY_BUILD: {
assert (getInputs().size() % 2 == 0);
int elemCount = getInputs().size() / 2;
List<Arg> keys = new ArrayList<Arg>(elemCount);
List<Arg> vals = new ArrayList<Arg>(elemCount);
for (int i = 0; i < elemCount; i++) {
keys.add(getInput(i * 2));
vals.add(getInput(i * 2 + 1));
}
gen.arrayBuild(getOutput(0), keys, vals);
break;
}
case ASYNC_COPY: {
gen.asyncCopy(getOutput(0), getInput(0).getVar());
break;
}
case SYNC_COPY: {
gen.syncCopy(getOutput(0), getInput(0).getVar());
break;
}
case BAG_INSERT:
gen.bagInsert(getOutput(0), getInput(0), getInput(1));
break;
case STRUCT_CREATE_ALIAS:
gen.structCreateAlias(getOutput(0), getInput(0).getVar(),
Arg.extractStrings(getInputsTail(1)));
break;
case STRUCT_RETRIEVE_SUB:
gen.structRetrieveSub(getOutput(0), getInput(0).getVar(), Arg.extractStrings(getInputsTail(2)),
getInput(1));
break;
case STRUCT_COPY_OUT:
gen.structCopyOut(getOutput(0), getInput(0).getVar(),
Arg.extractStrings(getInputsTail(1)));
break;
case STRUCTREF_COPY_OUT:
gen.structRefCopyOut(getOutput(0), getInput(0).getVar(),
Arg.extractStrings(getInputsTail(1)));
break;
case STRUCT_INIT_FIELDS: {
// Need to unpack variables from flat input list
Out<List<List<String>>> fieldPaths = new Out<List<List<String>>>();
Out<List<Arg>> fieldVals = new Out<List<Arg>>();
Arg writeDecr = unpackStructInitArgs(fieldPaths, null, fieldVals);
gen.structInitFields(getOutput(0), fieldPaths.val, fieldVals.val, writeDecr);
break;
}
case STRUCT_LOCAL_BUILD: {
Out<List<List<String>>> fieldPaths = new Out<List<List<String>>>();
Out<List<Arg>> fieldVals = new Out<List<Arg>>();
unpackStructBuildArgs(fieldPaths, null, fieldVals);
gen.buildStructLocal(getOutput(0), fieldPaths.val, fieldVals.val);
break;
}
case STRUCT_STORE_SUB:
gen.structStore(getOutput(0), Arg.extractStrings(getInputsTail(1)),
getInput(0));
break;
case STRUCT_COPY_IN:
gen.structCopyIn(getOutput(0), Arg.extractStrings(getInputsTail(1)),
getInput(0).getVar());
break;
case STRUCTREF_STORE_SUB:
gen.structRefStoreSub(getOutput(0), Arg.extractStrings(getInputsTail(1)),
getInput(0));
break;
case STRUCTREF_COPY_IN:
gen.structRefCopyIn(getOutput(0), Arg.extractStrings(getInputsTail(1)),
getInput(0).getVar());
break;
case DEREF_SCALAR:
gen.dereferenceScalar(getOutput(0), getInput(0).getVar());
break;
case DEREF_FILE:
gen.dereferenceFile(getOutput(0), getInput(0).getVar());
break;
case LOAD_REF:
gen.retrieveRef(getOutput(0), getInput(0).getVar(), getInput(1),
getInput(2), getInputs().size() == 4 ? getInput(3) : Arg.ZERO);
break;
case COPY_REF:
gen.makeAlias(getOutput(0), getInput(0).getVar());
break;
case ARR_CREATE_NESTED_FUTURE:
gen.arrayCreateNestedFuture(getOutput(0), getOutput(1),
getInput(0).getVar());
break;
case AREF_CREATE_NESTED_FUTURE:
gen.arrayRefCreateNestedFuture(getOutput(0), getOutput(1),
getInput(0).getVar());
break;
case AREF_CREATE_NESTED_IMM:
gen.arrayRefCreateNestedImm(getOutput(0), getOutput(1), getInput(0));
break;
case ARR_CREATE_NESTED_IMM:
gen.arrayCreateNestedImm(getOutput(0), getOutput(1), getInput(0),
getInput(1), getInput(2));
break;
case ARR_CREATE_BAG:
gen.arrayCreateBag(getOutput(0), getOutput(1), getInput(0),
getInput(1), getInput(2));
break;
case LOAD_SCALAR:
gen.retrieveScalar(getOutput(0), getInput(0).getVar(),
getInputs().size() == 2 ? getInput(1) : Arg.ZERO);
break;
case LOAD_FILE:
gen.retrieveFile(getOutput(0), getInput(0).getVar(),
getInputs().size() == 2 ? getInput(1) : Arg.ZERO);
break;
case LOAD_ARRAY:
gen.retrieveArray(getOutput(0), getInput(0).getVar(),
getInputs().size() == 2 ? getInput(1) : Arg.ZERO);
break;
case LOAD_STRUCT:
gen.retrieveStruct(getOutput(0), getInput(0).getVar(),
getInputs().size() == 2 ? getInput(1) : Arg.ZERO);
break;
case LOAD_BAG:
gen.retrieveBag(getOutput(0), getInput(0).getVar(),
getInputs().size() == 2 ? getInput(1) : Arg.ZERO);
break;
case LOAD_RECURSIVE:
gen.retrieveRecursive(getOutput(0), getInput(0).getVar(),
getInputs().size() == 2 ? getInput(1) : Arg.ZERO);
break;
case FREE_BLOB:
gen.freeBlob(getOutput(0));
break;
case DECR_LOCAL_FILE_REF:
gen.decrLocalFileRef(getInput(0).getVar());
break;
case INIT_UPDATEABLE_FLOAT:
gen.initUpdateable(getOutput(0), getInput(0));
break;
case LATEST_VALUE:
gen.latestValue(getOutput(0), getInput(0).getVar());
break;
case UPDATE_INCR:
gen.update(getOutput(0), UpdateMode.INCR, getInput(0).getVar());
break;
case UPDATE_MIN:
gen.update(getOutput(0), UpdateMode.MIN, getInput(0).getVar());
break;
case UPDATE_SCALE:
gen.update(getOutput(0), UpdateMode.SCALE, getInput(0).getVar());
break;
case UPDATE_INCR_IMM:
gen.updateImm(getOutput(0), UpdateMode.INCR, getInput(0));
break;
case UPDATE_MIN_IMM:
gen.updateImm(getOutput(0), UpdateMode.MIN, getInput(0));
break;
case UPDATE_SCALE_IMM:
gen.updateImm(getOutput(0), UpdateMode.SCALE, getInput(0));
break;
case GET_FILENAME_ALIAS:
gen.getFileNameAlias(getOutput(0), getInput(0).getVar());
break;
case COPY_IN_FILENAME:
gen.copyInFilename(getOutput(0), getInput(0).getVar());
break;
case GET_LOCAL_FILENAME:
gen.getLocalFileName(getOutput(0), getInput(0).getVar());
break;
case IS_MAPPED:
gen.isMapped(getOutput(0), getInput(0).getVar());
break;
case GET_FILENAME_VAL:
gen.getFilenameVal(getOutput(0), getInput(0).getVar());
break;
case SET_FILENAME_VAL:
gen.setFilenameVal(getOutput(0), getInput(0));
break;
case CHOOSE_TMP_FILENAME:
gen.chooseTmpFilename(getOutput(0));
break;
case INIT_LOCAL_OUTPUT_FILE:
gen.initLocalOutputFile(getOutput(0), getInput(0), getInput(1));
break;
case COPY_FILE_CONTENTS:
gen.copyFileContents(getOutput(0), getInput(0).getVar());
break;
case CHECKPOINT_WRITE_ENABLED:
gen.checkpointWriteEnabled(getOutput(0));
break;
case CHECKPOINT_LOOKUP_ENABLED:
gen.checkpointLookupEnabled(getOutput(0));
break;
case WRITE_CHECKPOINT:
gen.writeCheckpoint(getInput(0), getInput(1));
break;
case LOOKUP_CHECKPOINT:
gen.lookupCheckpoint(getOutput(0), getOutput(1), getInput(0));
break;
case PACK_VALUES:
gen.packValues(getOutput(0), getInputs());
break;
case UNPACK_VALUES:
gen.unpackValues(getOutputs(), getInput(0));
break;
case UNPACK_ARRAY_TO_FLAT:
gen.unpackArrayToFlat(getOutput(0), getInput(0));
break;
default:
throw new STCRuntimeError("didn't expect to see op " +
op.toString() + " here");
}
}
/**
* Look up value of array index immediately
* @param dst
* @param arrayVar
* @param arrIx
* @param decrRead
* @return
*/
public static Instruction arrayRetrieve(Var dst, Var arrayVar,
Arg arrIx, Arg decrRead) {
assert(dst.storage() == Alloc.LOCAL || dst.storage() == Alloc.ALIAS);
assert(Types.isArray(arrayVar));
assert(Types.isArrayKeyVal(arrayVar, arrIx));
assert(Types.isElemValType(arrayVar, dst));
assert(decrRead.isImmediateInt());
return new TurbineOp(Opcode.ARR_RETRIEVE,
dst, arrayVar.asArg(), arrIx, decrRead);
}
/**
* Copy out value of array once set
* @param dst
* @param arrayRefVar
* @param arrIx
* @return
*/
public static Instruction arrayRefCopyOutImm(Var dst,
Var arrayRefVar, Arg arrIx) {
assert(Types.isArrayRef(arrayRefVar));
assert(Types.isArrayKeyVal(arrayRefVar, arrIx));
assert(Types.isElemType(arrayRefVar, dst));
assert(!Types.isMutableRef(dst)); // Doesn't acquire write ref
return new TurbineOp(Opcode.AREF_COPY_OUT_IMM,
dst, arrayRefVar.asArg(), arrIx);
}
public static Instruction arrayCreateAlias(Var dst, Var arrayVar,
Arg arrIx) {
assert(Types.isArray(arrayVar));
assert(Types.isArrayKeyVal(arrayVar, arrIx));
assert(Types.isElemType(arrayVar, dst)) : arrayVar + " " + dst;
assert(dst.storage() == Alloc.ALIAS);
return new TurbineOp(Opcode.ARR_CREATE_ALIAS,
dst, arrayVar.asArg(), arrIx);
}
/**
* Copy out value of field from array once set
* @param dst
* @param arrayVar
* @param arrIx
* @return
*/
public static Instruction arrayCopyOutImm(Var dst, Var arrayVar,
Arg arrIx) {
assert(Types.isArray(arrayVar));
assert(Types.isArrayKeyVal(arrayVar, arrIx)) :
arrayVar.type() + " " + arrIx.type();
assert(Types.isElemType(arrayVar, dst)) : arrayVar + " " + dst;
assert(!Types.isMutableRef(dst)) : dst; // Doesn't acquire write ref
return new TurbineOp(Opcode.ARR_COPY_OUT_IMM,
dst, arrayVar.asArg(), arrIx);
}
/**
* Copy out value of field from array once set
* @param dst
* @param arrayVar
* @param indexVar
* @return
*/
public static TurbineOp arrayCopyOutFuture(Var dst, Var arrayVar,
Var indexVar) {
assert(Types.isArray(arrayVar));
assert(Types.isArrayKeyFuture(arrayVar, indexVar));
assert(Types.isElemType(arrayVar, dst));
assert(!Types.isMutableRef(dst)); // Doesn't acquire write ref
return new TurbineOp(Opcode.ARR_COPY_OUT_FUTURE,
dst, arrayVar.asArg(), indexVar.asArg());
}
/**
* Copy out value of field from array once set
* @param dst
* @param arrayRefVar
* @param indexVar
* @return
*/
public static TurbineOp arrayRefCopyOutFuture(Var dst, Var arrayRefVar,
Var indexVar) {
assert(Types.isArrayRef(arrayRefVar));
assert(Types.isArrayKeyFuture(arrayRefVar, indexVar));
assert(Types.isElemType(arrayRefVar, dst));
assert(!Types.isMutableRef(dst)); // Doesn't acquire write ref
return new TurbineOp(Opcode.AREF_COPY_OUT_FUTURE, dst,
arrayRefVar.asArg(), indexVar.asArg());
}
public static Instruction arrayContains(Var out, Var array, Arg ix) {
assert(Types.isBoolVal(out));
assert(Types.isArray(array));
assert(Types.isArrayKeyVal(array, ix));
return new TurbineOp(Opcode.ARR_CONTAINS, out, array.asArg(), ix);
}
public static Instruction containerSize(Var out, Var container) {
assert(Types.isIntVal(out));
assert(Types.isContainer(container));
return new TurbineOp(Opcode.CONTAINER_SIZE, out, container.asArg());
}
public static Instruction arrayLocalContains(Var out, Var array, Arg ix) {
assert(Types.isBoolVal(out));
assert(Types.isArrayLocal(array));
assert(Types.isArrayKeyVal(array, ix));
return new TurbineOp(Opcode.ARR_LOCAL_CONTAINS, out, array.asArg(), ix);
}
public static Instruction containerLocalSize(Var out, Var container) {
assert(Types.isIntVal(out));
assert(Types.isContainerLocal(container));
return new TurbineOp(Opcode.CONTAINER_LOCAL_SIZE, out, container.asArg());
}
public static Instruction arrayStore(Var array,
Arg ix, Arg member) {
assert(Types.isArray(array.type()));
assert(Types.isArrayKeyVal(array, ix));
assert(Types.isElemValType(array, member)) :
member.toStringTyped() + " " + array;
return new TurbineOp(Opcode.ARR_STORE, array, ix, member);
}
public static Instruction arrayStoreFuture(Var array,
Var ix, Arg member) {
assert(Types.isArray(array));
assert(Types.isArrayKeyFuture(array, ix));
assert(Types.isElemValType(array, member));
return new TurbineOp(Opcode.ARR_STORE_FUTURE,
array, ix.asArg(), member);
}
/**
* Store via a mutable array reference
* @param array
* @param ix
* @param member
* @return
*/
public static Instruction arrayRefStoreImm(Var array, Arg ix, Arg member) {
assert(Types.isArrayRef(array, true));
assert(Types.isArrayKeyVal(array, ix));
assert(Types.isElemValType(array, member));
return new TurbineOp(Opcode.AREF_STORE_IMM,
array, ix, member);
}
/**
* Store via a mutable array reference
* @param array
* @param ix
* @param member
* @return
*/
public static Instruction arrayRefStoreFuture(Var array, Var ix, Arg member) {
assert(Types.isArrayRef(array, true));
assert(Types.isArrayKeyFuture(array, ix));
assert(Types.isElemValType(array, member));
return new TurbineOp(Opcode.AREF_STORE_FUTURE,
array, ix.asArg(), member);
}
/**
* Copy a value into an array member
* @param array
* @param ix
* @param member
* @return
*/
public static Instruction arrayCopyInImm(Var array,
Arg ix, Var member) {
assert(Types.isArray(array));
assert(Types.isArrayKeyVal(array, ix));
assert(Types.isElemType(array, member));
return new TurbineOp(Opcode.ARR_COPY_IN_IMM,
array, ix, member.asArg());
}
/**
* Copy a value into an array member
* @param array
* @param ix
* @param member
* @return
*/
public static Instruction arrayCopyInFuture(Var array, Var ix, Var member) {
assert(Types.isArray(array.type()));
assert(Types.isArrayKeyFuture(array, ix));
assert(Types.isElemType(array, member));
return new TurbineOp(Opcode.ARR_COPY_IN_FUTURE, array, ix.asArg(),
member.asArg());
}
/**
* Copy in a value to an array reference
* @param outerArray
* @param array
* @param ix
* @param member
* @return
*/
public static Instruction arrayRefCopyInImm(Var array, Arg ix, Var member) {
assert(Types.isArrayKeyVal(array, ix));
assert(Types.isArrayRef(array, true));
assert(Types.isElemType(array, member));
return new TurbineOp(Opcode.AREF_COPY_IN_IMM,
array, ix, member.asArg());
}
public static Instruction arrayRefCopyInFuture(Var array, Var ix,
Var member) {
assert(Types.isArrayKeyFuture(array, ix));
assert(Types.isArrayRef(array, true));
assert(Types.isElemType(array, member));
return new TurbineOp(Opcode.AREF_COPY_IN_FUTURE,
array, ix.asArg(), member.asArg());
}
/**
* Build an array in one hit.
* @param array
* @param keys key values for array (NOT futures)
* @param vals
*/
public static Instruction arrayBuild(Var array, List<Arg> keys, List<Arg> vals) {
assert(Types.isArray(array.type()));
int elemCount = keys.size();
assert(vals.size() == elemCount);
ArrayList<Arg> inputs = new ArrayList<Arg>(elemCount * 2);
for (int i = 0; i < elemCount; i++) {
Arg key = keys.get(i);
Arg val = vals.get(i);
assert(Types.isArrayKeyVal(array, key));
assert(Types.isElemValType(array, val));
inputs.add(key);
inputs.add(val);
}
return new TurbineOp(Opcode.ARRAY_BUILD, array.asList(), inputs);
}
/**
* Generic async copy instruction for non-local data
*/
public static Instruction asyncCopy(Var dst, Var src) {
assert(src.type().assignableTo(dst.type()));
assert(dst.storage() != Alloc.LOCAL);
return new TurbineOp(Opcode.ASYNC_COPY, dst, src.asArg());
}
/**
* Generic sync copy instruction for non-local data.
* Assumes input data closed
*/
public static Instruction syncCopy(Var dst, Var src) {
assert(src.type().assignableTo(dst.type()));
assert(dst.storage() != Alloc.LOCAL);
return new TurbineOp(Opcode.SYNC_COPY, dst, src.asArg());
}
/**
* Add something to a bag
* @param bag
* @param elem
* @param writersDecr
* @return
*/
public static Instruction bagInsert(Var bag, Arg elem, Arg writersDecr) {
assert(Types.isBag(bag));
assert(Types.isElemValType(bag, elem)) : bag + " " + elem + ":" + elem.type();
assert(writersDecr.isImmediateInt());
return new TurbineOp(Opcode.BAG_INSERT, bag, elem, writersDecr);
}
/**
* Retrieve value of a struct entry
*
* TODO: for case of ref entries, separate op to get writable reference?
* @param dst
* @param structVar
* @param fields
* @param readDecr
* @return
*/
public static Instruction structRetrieveSub(Var dst, Var structVar,
List<String> fields, Arg readDecr) {
assert(Types.isStruct(structVar));
assert(Types.isStructFieldVal(structVar, fields, dst)) :
"(" + structVar.name() + ":" + structVar.type() + ")." + fields
+ " => " + dst;
assert (readDecr.isImmediateInt());
List<Arg> in = new ArrayList<Arg>(fields.size() + 1);
in.add(structVar.asArg());
in.add(readDecr);
for (String field: fields) {
in.add(Arg.createStringLit(field));
}
return new TurbineOp(Opcode.STRUCT_RETRIEVE_SUB, dst.asList(), in);
}
public static Instruction structCreateAlias(Var fieldAlias, Var structVar,
List<String> fields) {
assert(Types.isStruct(structVar));
assert(Types.isStructField(structVar, fields, fieldAlias)):
structVar + " " + fields + " " + fieldAlias;
assert(fieldAlias.storage() == Alloc.ALIAS) : fieldAlias;
List<Arg> in = new ArrayList<Arg>(fields.size() + 1);
in.add(structVar.asArg());
for (String field: fields) {
in.add(Arg.createStringLit(field));
}
return new TurbineOp(Opcode.STRUCT_CREATE_ALIAS, fieldAlias.asList(), in);
}
/**
* Copy out value of field from a struct to a destination variable
* @param dst
* @param struct
* @param fields
* @return
*/
public static Instruction structCopyOut(Var dst, Var struct,
List<String> fields) {
// TODO: support piggybacked refcount ops for this and other struct operations
assert(Types.isStruct(struct));
assert(Types.isStructField(struct, fields, dst));
List<Arg> in = new ArrayList<Arg>(fields.size() + 1);
in.add(struct.asArg());
for (String field: fields) {
in.add(Arg.createStringLit(field));
}
return new TurbineOp(Opcode.STRUCT_COPY_OUT, dst.asList(), in);
}
/**
* Copy out value of field from a struct to a destination variable
* @param dst
* @param struct
* @param fields
* @return
*/
public static Instruction structRefCopyOut(Var dst, Var struct,
List<String> fields) {
assert(Types.isStructRef(struct));
assert(Types.isStructField(struct, fields, dst));
List<Arg> in = new ArrayList<Arg>(fields.size() + 1);
in.add(struct.asArg());
for (String field: fields) {
in.add(Arg.createStringLit(field));
}
return new TurbineOp(Opcode.STRUCTREF_COPY_OUT, dst.asList(), in);
}
/**
* Store directly to a field of a struct
* @param structVar
* @param fields
* @param fieldVal
* @return
*/
public static Instruction structStoreSub(Var structVar,
List<String> fields, Arg fieldVal) {
assert(Types.isStruct(structVar)) : structVar;
assert(Types.isStructFieldVal(structVar, fields, fieldVal));
List<Arg> in = new ArrayList<Arg>(fields.size() + 1);
in.add(fieldVal);
for (String field: fields) {
in.add(Arg.createStringLit(field));
}
return new TurbineOp(Opcode.STRUCT_STORE_SUB, structVar.asList(), in);
}
/**
* Copy a value into a field of a struct
* @param structVar
* @param fields
* @param fieldVar
* @return
*/
public static Instruction structCopyIn(Var structVar,
List<String> fields, Var fieldVar) {
assert(Types.isStruct(structVar));
assert(Types.isStructField(structVar, fields, fieldVar));
List<Arg> in = new ArrayList<Arg>(fields.size() + 1);
for (String field: fields) {
in.add(Arg.createStringLit(field));
}
in.add(fieldVar.asArg());
return new TurbineOp(Opcode.STRUCT_COPY_IN, structVar.asList(), in);
}
public static Instruction structRefStoreSub(Var structVar,
List<String> fields, Arg fieldVal) {
List<Arg> in = new ArrayList<Arg>(fields.size() + 1);
for (String field: fields) {
in.add(Arg.createStringLit(field));
}
in.add(fieldVal);
return new TurbineOp(Opcode.STRUCTREF_STORE_SUB, structVar.asList(), in);
}
/**
* Copy a value into a field of the struct referenced by structRef
* @param structRef
* @param fieldVar
* @return
*/
public static Instruction structRefCopyIn(Var structRef,
List<String> fields, Var fieldVar) {
assert(Types.isStructRef(structRef, true));
assert(Types.isStructField(structRef, fields, fieldVar));
List<Arg> in = new ArrayList<Arg>(fields.size() + 1);
for (String field: fields) {
in.add(Arg.createStringLit(field));
}
in.add(fieldVar.asArg());
return new TurbineOp(Opcode.STRUCTREF_COPY_IN, structRef.asList(), in);
}
/**
* Assign any scalar data type
* @param dst shared scalar
* @param src local scalar value
* @return
*/
public static Instruction assignScalar(Var dst, Arg src) {
assert(Types.isScalarFuture(dst)) : dst;
assert(Types.isScalarValue(src));
assert(src.type().assignableTo(Types.retrievedType(dst)));
return new TurbineOp(Opcode.STORE_SCALAR, dst, src);
}
/**
* Assign a file future from a file value
*
* NOTE: the setFilename parameter is not strictly necessary: at runtime
* we could set the filename conditionally on the file not being
* mapped. However, making it explicit simplifies correct optimisation
* @param dst
* @param src
* @param setFilename if true, set filename, if false assume already
* has filename, just close the file.
* @return
*/
public static Instruction assignFile(Var dst, Arg src, Arg setFilename) {
assert(Types.isFile(dst.type()));
assert(src.isVar());
assert(Types.isFileVal(src.getVar()));
assert(setFilename.isImmediateBool());
if (setFilename.isBoolVal() && setFilename.getBoolLit()) {
// Sanity check that we're not setting mapped file
assert(dst.isMapped() != Ternary.TRUE);
}
return new TurbineOp(Opcode.STORE_FILE, dst, src,
setFilename);
}
/**
* Store array directly from local array representation to shared.
* Does not follow refs, e.g. if it is an array of refs, dst must
* be a local array of refs
* @param dst
* @param src
* @return
*/
public static Instruction assignArray(Var dst, Arg src) {
assert(Types.isArray(dst.type())) : dst;
assert(Types.isArrayLocal(src.type())) : src + " " + src.type();
assert(Types.arrayKeyType(src).assignableTo(Types.arrayKeyType(dst)));
assert(Types.containerElemType(src.type()).assignableTo(
Types.containerElemType(dst)));
return new TurbineOp(Opcode.STORE_ARRAY, dst, src);
}
/**
* Store bag directly from local bag representation to shared.
* Does not follow refs, e.g. if it is a bag of refs, dst must
* be a local bag of refs
* @param dst
* @param src
* @return
*/
public static Instruction assignBag(Var dst, Arg src) {
assert(Types.isBag(dst)) : dst;
assert(Types.isBagLocal(src.type())) : src.type();
assert(Types.containerElemType(src.type()).assignableTo(
Types.containerElemType(dst)));
return new TurbineOp(Opcode.STORE_BAG, dst, src);
}
public static Statement structLocalBuild(Var struct,
List<List<String>> fieldPaths, List<Arg> fieldVals) {
assert(Types.isStructLocal(struct));
List<Arg> inputs = new ArrayList<Arg>();
packFieldData(struct, fieldPaths, fieldVals, inputs);
return new TurbineOp(Opcode.STRUCT_LOCAL_BUILD, struct.asList(), inputs);
}
/**
* Initialize all struct fields that need initialization,
* e.g. references to other data.
* Should be called only once on each struct that needs
* initialization.
* @param struct
* @param fields
* @param writeDecr
*/
public static TurbineOp structInitFields(Var struct,
List<List<String>> fieldPaths, List<Arg> fieldVals, Arg writeDecr) {
assert(Types.isStruct(struct));
assert(writeDecr.isImmediateInt());
List<Arg> inputs = new ArrayList<Arg>();
packFieldData(struct, fieldPaths, fieldVals, inputs);
inputs.add(writeDecr);
return new TurbineOp(Opcode.STRUCT_INIT_FIELDS, struct.asList(), inputs);
}
/**
*
* @param fieldPaths if null, not filled
* @param fieldPathsArgs if null, not filled
* @param fieldVals if null, not filled
* @return writeDecr
*/
public Arg unpackStructInitArgs(Out<List<List<String>>> fieldPaths,
Out<List<List<Arg>>> fieldPathsArgs,
Out<List<Arg>> fieldVals) {
assert(op == Opcode.STRUCT_INIT_FIELDS) : op;
List<Arg> packedFieldData = inputs.subList(0, inputs.size() - 1);
unpackFieldData(packedFieldData, fieldPaths, fieldPathsArgs, fieldVals);
Arg writeDecr = getInput(inputs.size() - 1);
return writeDecr;
}
public void unpackStructBuildArgs(Out<List<List<String>>> fieldPaths,
Out<List<List<Arg>>> fieldPathsArgs,
Out<List<Arg>> fieldVals) {
assert(op == Opcode.STRUCT_LOCAL_BUILD) : op;
List<Arg> packedFieldData = inputs;
unpackFieldData(packedFieldData, fieldPaths, fieldPathsArgs, fieldVals);
}
/**
* Pack info about struct fields into arg list
* @param struct
* @param fieldPaths
* @param fieldVals
* @param result
*/
private static void packFieldData(Typed structType,
List<List<String>> fieldPaths, List<Arg> fieldVals, List<Arg> result) {
assert(fieldPaths.size() == fieldVals.size());
for (int i = 0; i < fieldPaths.size(); i++) {
List<String> fieldPath = fieldPaths.get(i);
Arg fieldVal = fieldVals.get(i);
assert(Types.isStructFieldVal(structType, fieldPath, fieldVal))
: structType + " " + fieldPath + " " + fieldVal.getVar() + "\n"
+ structType.type();
// encode lists with length prefixed
result.add(Arg.createIntLit(fieldPath.size()));
for (String field: fieldPath) {
result.add(Arg.createStringLit(field));
}
result.add(fieldVal);
}
}
private static void unpackFieldData(List<Arg> packedFieldData,
Out<List<List<String>>> fieldPaths, Out<List<List<Arg>>> fieldPathsArgs,
Out<List<Arg>> fieldVals) {
if (fieldPaths != null) {
fieldPaths.val = new ArrayList<List<String>>();
}
if (fieldPathsArgs != null) {
fieldPathsArgs.val = new ArrayList<List<Arg>>();
}
if (fieldVals != null) {
fieldVals.val = new ArrayList<Arg>();
}
int pos = 0;
while (pos < packedFieldData.size()) {
long pathLength = packedFieldData.get(pos).getIntLit();
assert(pathLength > 0 && pathLength <= Integer.MAX_VALUE);
pos++;
List<String> fieldPath = (fieldPaths == null) ? null:
new ArrayList<String>((int)pathLength);
List<Arg> fieldPathArgs = (fieldPathsArgs == null) ? null:
new ArrayList<Arg>((int)pathLength);
for (int i = 0; i < pathLength; i++) {
if (fieldPath != null) {
fieldPath.add(packedFieldData.get(pos).getStringLit());
}
if (fieldPathArgs != null) {
fieldPathArgs.add(packedFieldData.get(pos));
}
pos++;
}
Arg fieldVal = packedFieldData.get(pos);
pos++;
if (fieldPaths != null) {
fieldPaths.val.add(fieldPath);
}
if (fieldPathsArgs != null) {
fieldPathsArgs.val.add(fieldPathArgs);
}
if (fieldVals != null) {
fieldVals.val.add(fieldVal);
}
}
}
/**
* Store struct directly from local struct representation to shared.
* Does not follow refs.
* @param dst
* @param src
* @return
*/
public static Instruction assignStruct(Var dst, Arg src) {
assert(Types.isStruct(dst)) : dst;
assert(Types.isStructLocal(src)) : src.type();
assert(StructType.sharedStruct((StructType)src.type().getImplType())
.assignableTo(dst.type()));
return new TurbineOp(Opcode.STORE_STRUCT, dst, src);
}
/**
* Retrieve any scalar type to local value
* @param dst
* @param src closed scalar value
* @return
*/
public static Instruction retrieveScalar(Var dst, Var src) {
assert(Types.isScalarValue(dst));
assert(Types.isScalarFuture(src.type()));
assert(Types.retrievedType(src).assignableTo(dst.type()));
return new TurbineOp(Opcode.LOAD_SCALAR, dst, src.asArg());
}
/**
* Retrieve a file value from a file future
* @param target
* @param src
* @return
*/
public static Instruction retrieveFile(Var target, Var src) {
assert(Types.isFile(src.type()));
assert(Types.isFileVal(target));
return new TurbineOp(Opcode.LOAD_FILE, target, src.asArg());
}
/**
* Retrieve an array directly to a local array, without following
* any references
* @param dst
* @param src non-recursively closed array
* @return
*/
public static Instruction retrieveArray(Var dst, Var src) {
assert(Types.isArray(src.type()));
assert(Types.isArrayLocal(dst));
assert(Types.containerElemType(src.type()).assignableTo(
Types.containerElemType(dst)));
return new TurbineOp(Opcode.LOAD_ARRAY, dst, src.asArg());
}
/**
* Retrieve a bag directly to a local bag, without following
* any references
* @param dst
* @param src non-recursively closed bag
* @return
*/
public static Instruction retrieveBag(Var target, Var src) {
assert(Types.isBag(src.type()));
assert(Types.isBagLocal(target));
assert(Types.containerElemType(src.type()).assignableTo(
Types.containerElemType(target)));
return new TurbineOp(Opcode.LOAD_BAG, target, src.asArg());
}
/**
* Retrieve a struct directly to a local struct, without following
* any references
* @param dst
* @param src non-recursively closed struct
* @return
*/
public static Instruction retrieveStruct(Var dst, Var src) {
assert(Types.isStruct(src.type()));
assert(Types.isStructLocal(dst));
assert(StructType.localStruct((StructType)src.type().getImplType())
.assignableTo(dst.type()));
return new TurbineOp(Opcode.LOAD_STRUCT, dst, src.asArg());
}
/**
* Store a completely unpacked array/bag/etc to the standard shared
* representation
* @param target
* @param src
* @return
*/
public static Instruction storeRecursive(Var target, Arg src) {
assert(Types.isContainer(target));
assert(Types.isContainerLocal(src.type()));
assert(src.type().assignableTo(
Types.unpackedContainerType(target)));
return new TurbineOp(Opcode.STORE_RECURSIVE, target, src);
}
/**
* Retrieve an array/bag/etc, following all references to included.
* src must be recursively closed
* @param target
* @param src
* @return
*/
public static Instruction retrieveRecursive(Var target, Var src) {
assert(Types.isContainer(src));
assert(Types.isContainerLocal(target));
Type unpackedSrcType = Types.unpackedContainerType(src);
assert(unpackedSrcType.assignableTo(target.type())) :
unpackedSrcType + " => " + target;
return new TurbineOp(Opcode.LOAD_RECURSIVE, target, src.asArg());
}
public static Instruction freeBlob(Var blobVal) {
// View refcounted var as output
return new TurbineOp(Opcode.FREE_BLOB, blobVal);
}
public static Instruction decrLocalFileRef(Var fileVal) {
assert(Types.isFileVal(fileVal));
// We should only be freeing local file refs if we allocated a temporary
assert(fileVal.type().fileKind().supportsTmpImmediate());
// View all as inputs: only used in cleanupaction context
return new TurbineOp(Opcode.DECR_LOCAL_FILE_REF, Collections.<Var>emptyList(),
fileVal.asArg());
}
/**
* Store a reference
* @param dst reference to store to
* @param src some datastore object
* @return
*/
public static Instruction storeRef(Var dst, Var src) {
// TODO: refcounts to transfer. Implied by output type?
assert(Types.isRef(dst));
assert(src.type().assignableTo(Types.retrievedType(dst)));
return new TurbineOp(Opcode.STORE_REF, dst, src.asArg());
}
/**
* Helper to generate appropriate store instruction for any type
* if possible
* @param dst
* @param src
* @return
*/
public static Instruction storeAny(Var dst, Arg src) {
assert(src.type().assignableTo(Types.retrievedType(dst)));
if (Types.isRef(dst)) {
assert(src.isVar());
return storeRef(dst, src.getVar());
} else if (Types.isPrimFuture(dst)) {
// Regular store?
return storePrim(dst, src);
} else if (Types.isArray(dst)) {
assert(src.isVar());
return assignArray(dst, src);
} else if (Types.isBag(dst)) {
assert(src.isVar());
return assignBag(dst, src);
} else if (Types.isStruct(dst)) {
assert(src.isVar());
return assignStruct(dst, src);
} else {
throw new STCRuntimeError("Don't know how to store to " + dst);
}
}
/**
* Helper to generate appropriate instruction for primitive type
* @param dst
* @param src
* @return
*/
public static Instruction storePrim(Var dst, Arg src) {
assert(Types.isPrimFuture(dst));
assert(src.type().assignableTo(Types.retrievedType(dst)));
if (Types.isScalarFuture(dst)) {
return assignScalar(dst, src);
} else if (Types.isFile(dst)) {
// TODO: is this right to always close?
return assignFile(dst, src, Arg.TRUE);
} else {
throw new STCRuntimeError("method to set " +
dst.type().typeName() + " is not known yet");
}
}
public static Instruction derefScalar(Var target, Var src) {
return new TurbineOp(Opcode.DEREF_SCALAR, target, src.asArg());
}
public static Instruction derefFile(Var target, Var src) {
return new TurbineOp(Opcode.DEREF_FILE, target, src.asArg());
}
/**
* Retrieve a reference to a local handle
* @param dst alias variable to hold handle to referenced data
* @param src Closed reference
* @param acquireRead num of read refcounts to acquire
* @param acquireWrite num of write refcounts to acquire
* @return
*/
public static Instruction retrieveRef(Var dst, Var src,
long acquireRead, long acquireWrite) {
assert(Types.isRef(src.type()));
assert(acquireRead >= 0);
assert(acquireWrite >= 0);
if (acquireWrite > 0) {
assert(Types.isAssignableRefTo(src.type(), dst.type(), true));
} else {
assert(Types.isAssignableRefTo(src.type(), dst.type()));
}
assert(dst.storage() == Alloc.ALIAS);
return new TurbineOp(Opcode.LOAD_REF, dst, src.asArg(),
Arg.createIntLit(acquireRead), Arg.createIntLit(acquireWrite));
}
public static Instruction copyRef(Var dst, Var src) {
return new TurbineOp(Opcode.COPY_REF, dst, src.asArg());
}
/**
* Create a nested array and assign result id to output reference.
* Read and write refcount is passed to output reference.
* @param arrayResult
* @param array
* @param ix
* @return
*/
public static Instruction arrayCreateNestedFuture(Var arrayResult,
Var array, Var ix) {
assert(Types.isArrayRef(arrayResult.type(), true));
assert(arrayResult.storage() != Alloc.ALIAS);
assert(Types.isArray(array.type()));
assert(Types.isArrayKeyFuture(array, ix));
assert(!Types.isConstRef(arrayResult)); // Should be mutable if ref
// Both arrays are modified, so outputs
return new TurbineOp(Opcode.ARR_CREATE_NESTED_FUTURE,
Arrays.asList(arrayResult, array), ix.asArg());
}
/**
* Create a nested array inside the current one, or return current
* nested array if not present. Acquire read + write reference
* to nested array. (TODO)
* @param arrayResult
* @param arrayVar
* @param arrIx
* @return
*/
public static Instruction arrayCreateNestedImm(Var arrayResult,
Var arrayVar, Arg arrIx) {
assert(Types.isArray(arrayResult.type()));
assert(Types.isArray(arrayVar.type()));
assert(arrayResult.storage() == Alloc.ALIAS);
assert(Types.isArrayKeyVal(arrayVar, arrIx));
// Both arrays are modified, so outputs
return new TurbineOp(Opcode.ARR_CREATE_NESTED_IMM,
Arrays.asList(arrayResult, arrayVar),
arrIx, Arg.ZERO, Arg.ZERO);
}
public static Instruction arrayRefCreateNestedComputed(Var arrayResult,
Var array, Var ix) {
assert(Types.isArrayRef(arrayResult.type(), true)): arrayResult;
assert(arrayResult.storage() != Alloc.ALIAS);
assert(Types.isArrayRef(array.type(), true)): array;
assert(Types.isArrayKeyFuture(array, ix));
assert(!Types.isConstRef(arrayResult)); // Should be mutable if ref
// Returns nested array, modifies outer array and
// reference counts outmost array
return new TurbineOp(Opcode.AREF_CREATE_NESTED_FUTURE,
Arrays.asList(arrayResult, array),
ix.asArg());
}
/**
*
* @param arrayResult
* @param outerArray
* @param array
* @param ix
* @return
*/
public static Instruction arrayRefCreateNestedImmIx(Var arrayResult,
Var array, Arg ix) {
assert(Types.isArrayRef(arrayResult.type(), true)): arrayResult;
assert(arrayResult.storage() != Alloc.ALIAS);
assert(Types.isArrayRef(array.type(), true)): array;
assert(Types.isArrayKeyVal(array, ix));
assert(!Types.isConstRef(arrayResult)); // Should be mutable if ref
return new TurbineOp(Opcode.AREF_CREATE_NESTED_IMM,
// Returns nested array, modifies outer array and
// reference counts outmost array
Arrays.asList(arrayResult, array),
ix);
}
/**
* Create a nested bag inside an array
* @param bag
* @param arr
* @param key
* @return
*/
public static Instruction arrayCreateBag(Var bag,
Var arr, Arg key) {
assert(Types.isBag(bag));
assert(Types.isArray(arr));
assert(Types.isArrayKeyVal(arr, key));
assert(bag.storage() == Alloc.ALIAS);
// Both arrays are modified, so outputs
return new TurbineOp(Opcode.ARR_CREATE_BAG,
Arrays.asList(bag, arr),
key, Arg.ZERO, Arg.ZERO);
}
public static Instruction initUpdateableFloat(Var updateable, Arg val) {
return new TurbineOp(Opcode.INIT_UPDATEABLE_FLOAT, updateable, val);
}
public static Instruction latestValue(Var result, Var updateable) {
return new TurbineOp(Opcode.LATEST_VALUE, result, updateable.asArg());
}
public static Instruction update(Var updateable,
UpdateMode updateMode, Var val) {
Opcode op;
switch (updateMode) {
case MIN:
op = Opcode.UPDATE_MIN;
break;
case INCR:
op = Opcode.UPDATE_INCR;
break;
case SCALE:
op = Opcode.UPDATE_SCALE;
break;
default:
throw new STCRuntimeError("Unknown UpdateMode" + updateMode);
}
return new TurbineOp(op, updateable, val.asArg());
}
public static Instruction updateImm(Var updateable,
UpdateMode updateMode, Arg val) {
Opcode op;
switch (updateMode) {
case MIN:
op = Opcode.UPDATE_MIN_IMM;
break;
case INCR:
op = Opcode.UPDATE_INCR_IMM;
break;
case SCALE:
op = Opcode.UPDATE_SCALE_IMM;
break;
default:
throw new STCRuntimeError("Unknown UpdateMode"
+ updateMode);
}
return new TurbineOp(op, updateable, val);
}
public static Instruction getFileNameAlias(Var filename, Var file) {
return new TurbineOp(Opcode.GET_FILENAME_ALIAS, filename, file.asArg());
}
public static Instruction copyInFilename(Var file, Var filename) {
return new TurbineOp(Opcode.COPY_IN_FILENAME, file, filename.asArg());
}
public static Instruction getLocalFileName(Var filename, Var file) {
assert(Types.isFileVal(file));
assert(Types.isStringVal(filename));
return new TurbineOp(Opcode.GET_LOCAL_FILENAME, filename, file.asArg());
}
public static Instruction getFilenameVal(Var filenameVal, Var file) {
assert(Types.isStringVal(filenameVal));
assert(Types.isFile(file));
return new TurbineOp(Opcode.GET_FILENAME_VAL, filenameVal, file.asArg());
}
/**
* Set the filename of a file
* TODO: take additional disable variable that avoids setting if not
* mapped, to aid optimiser
* @param file
* @param filenameVal
* @return
*/
public static Instruction setFilenameVal(Var file, Arg filenameVal) {
assert(Types.isFile(file.type()));
assert(filenameVal.isImmediateString());
return new TurbineOp(Opcode.SET_FILENAME_VAL, file, filenameVal);
}
public static Instruction copyFileContents(Var target, Var src) {
return new TurbineOp(Opcode.COPY_FILE_CONTENTS, target, src.asArg());
}
/**
* Check if file is mapped
* @param isMapped
* @param file
* @return
*/
public static Instruction isMapped(Var isMapped, Var file) {
assert(Types.isBoolVal(isMapped));
assert(Types.isFile(file));
return new TurbineOp(Opcode.IS_MAPPED, isMapped, file.asArg());
}
public static Instruction chooseTmpFilename(Var filenameVal) {
return new TurbineOp(Opcode.CHOOSE_TMP_FILENAME, filenameVal);
}
public static Instruction initLocalOutFile(Var localOutFile,
Arg outFilename, Arg isMapped) {
assert(Types.isFileVal(localOutFile));
assert(Types.isStringVal(outFilename.type()));
assert(Types.isBoolVal(isMapped.type()));
return new TurbineOp(Opcode.INIT_LOCAL_OUTPUT_FILE, localOutFile.asList(),
outFilename, isMapped);
}
public static Instruction checkpointLookupEnabled(Var v) {
return new TurbineOp(Opcode.CHECKPOINT_LOOKUP_ENABLED, v);
}
public static Instruction checkpointWriteEnabled(Var v) {
return new TurbineOp(Opcode.CHECKPOINT_WRITE_ENABLED, v);
}
public static Instruction writeCheckpoint(Arg key, Arg value) {
assert(Types.isBlobVal(key.type()));
assert(Types.isBlobVal(value.type()));
return new TurbineOp(Opcode.WRITE_CHECKPOINT, Var.NONE, key, value);
}
public static Instruction lookupCheckpoint(Var checkpointExists, Var value,
Arg key) {
assert(Types.isBoolVal(checkpointExists));
assert(Types.isBlobVal(value));
assert(Types.isBlobVal(key.type()));
return new TurbineOp(Opcode.LOOKUP_CHECKPOINT,
Arrays.asList(checkpointExists, value), key);
}
public static Instruction packValues(Var packedValues, List<Arg> values) {
for (Arg val: values) {
assert(val.isConstant() || val.getVar().storage() == Alloc.LOCAL);
}
return new TurbineOp(Opcode.PACK_VALUES, packedValues.asList(), values);
}
public static Instruction unpackValues(List<Var> values, Arg packedValues) {
for (Var val: values) {
assert(val.storage() == Alloc.LOCAL);
}
return new TurbineOp(Opcode.UNPACK_VALUES, values, packedValues);
}
public static Instruction unpackArrayToFlat(Var flatLocalArray, Arg inputArray) {
return new TurbineOp(Opcode.UNPACK_ARRAY_TO_FLAT, flatLocalArray, inputArray);
}
@Override
public void renameVars(Map<Var, Arg> renames, RenameMode mode) {
if (mode == RenameMode.VALUE) {
// Fall through
} else if (mode == RenameMode.REPLACE_VAR) {
// Straightforward replacement
ICUtil.replaceVarsInList(renames, outputs, false);
} else {
assert(mode == RenameMode.REFERENCE);
for (int i = 0; i < outputs.size(); i++) {
Var output = outputs.get(i);
if (renames.containsKey(output)) {
// Avoid replacing aliases that were initialized
boolean isInit = false;
for (Pair<Var, Instruction.InitType> p: getInitialized()) {
if (output.equals(p.val1)) {
isInit = true;
break;
}
}
if (!isInit) {
Arg repl = renames.get(output);
if (repl.isVar()) {
outputs.set(i, repl.getVar());
}
}
}
}
}
renameInputs(renames);
}
public void renameInputs(Map<Var, Arg> renames) {
ICUtil.replaceArgsInList(renames, inputs);
}
@Override
public boolean hasSideEffects() {
switch (op) {
// The direct container write functions only mutate their output argument
// so effect can be tracked back to output var
case STRUCT_INIT_FIELDS:
case STRUCT_STORE_SUB:
case STRUCT_COPY_IN:
case STRUCTREF_STORE_SUB:
case STRUCTREF_COPY_IN:
case ARRAY_BUILD:
case ARR_STORE_FUTURE:
case ARR_COPY_IN_FUTURE:
case ARR_STORE:
case ARR_COPY_IN_IMM:
case AREF_STORE_FUTURE:
case AREF_COPY_IN_FUTURE:
case AREF_STORE_IMM:
case AREF_COPY_IN_IMM:
case SYNC_COPY:
case ASYNC_COPY:
return false;
case BAG_INSERT:
return false;
case UPDATE_INCR:
case UPDATE_MIN:
case UPDATE_SCALE:
case UPDATE_INCR_IMM:
case UPDATE_MIN_IMM:
case UPDATE_SCALE_IMM:
case INIT_UPDATEABLE_FLOAT:
return true;
case STORE_SCALAR:
case STORE_FILE:
case STORE_ARRAY:
case STORE_BAG:
case STORE_STRUCT:
case STORE_RECURSIVE:
case DEREF_SCALAR:
case DEREF_FILE:
case LOAD_SCALAR:
case LOAD_FILE:
case LOAD_ARRAY:
case LOAD_BAG:
case LOAD_STRUCT:
case LOAD_RECURSIVE:
case STRUCT_LOCAL_BUILD:
return false;
case ARR_COPY_OUT_IMM:
case ARR_COPY_OUT_FUTURE:
case AREF_COPY_OUT_FUTURE:
case AREF_COPY_OUT_IMM:
case ARR_CONTAINS:
case CONTAINER_SIZE:
case ARR_LOCAL_CONTAINS:
case CONTAINER_LOCAL_SIZE:
return false;
case GET_FILENAME_ALIAS:
// Only effect is setting alias var
return false;
case GET_LOCAL_FILENAME:
return false;
case GET_FILENAME_VAL:
return false;
case IS_MAPPED:
// will always returns same result for same var
return false;
case CHOOSE_TMP_FILENAME:
// Non-deterministic
return true;
case SET_FILENAME_VAL:
case COPY_IN_FILENAME:
// Only effect is in file output var
return false;
case COPY_FILE_CONTENTS:
// Only effect is to modify file represented by output var
return false;
case INIT_LOCAL_OUTPUT_FILE:
// If the output is mapped, we want to retain the file,
// so we treat this as having side-effects
if (getInput(1).isBoolVal() && getInput(1).getBoolLit() == false) {
// Definitely unmapped
return false;
} else {
// Maybe mapped
return true;
}
case LOAD_REF:
case STORE_REF:
case COPY_REF:
case STRUCT_CREATE_ALIAS:
case STRUCT_RETRIEVE_SUB:
case STRUCT_COPY_OUT:
case STRUCTREF_COPY_OUT:
case ARR_RETRIEVE:
case LATEST_VALUE:
case ARR_CREATE_ALIAS:
// Always has alias as output because the instructions initialises
// the aliases
return false;
case ARR_CREATE_NESTED_FUTURE:
case AREF_CREATE_NESTED_FUTURE:
case ARR_CREATE_NESTED_IMM:
case AREF_CREATE_NESTED_IMM:
case ARR_CREATE_BAG:
/* It might seem like these nested creation primitives have a
* side-effect, but for optimisation purposes they can be treated as
* side-effect free, as the side-effect is only relevant if the array
* created is subsequently used in a store operation
*/
return false;
case FREE_BLOB:
case DECR_LOCAL_FILE_REF:
/*
* Reference counting ops can have side-effect
*/
return true;
case WRITE_CHECKPOINT:
// Writing checkpoint is a side-effect
return true;
case LOOKUP_CHECKPOINT:
case PACK_VALUES:
case UNPACK_VALUES:
case UNPACK_ARRAY_TO_FLAT:
case CHECKPOINT_WRITE_ENABLED:
case CHECKPOINT_LOOKUP_ENABLED:
return false;
default:
throw new STCRuntimeError("Need to add opcode " + op.toString()
+ " to hasSideEffects");
}
}
public boolean canChangeTiming() {
return !hasSideEffects() && op != Opcode.LATEST_VALUE;
}
@Override
public List<Var> getOutputs() {
return Collections.unmodifiableList(outputs);
}
@Override
public Arg getInput(int i) {
return inputs.get(i);
}
@Override
public Var getOutput(int i) {
return outputs.get(i);
}
@Override
public List<Arg> getInputs() {
return Collections.unmodifiableList(inputs);
}
public List<Arg> getInputsTail(int start) {
return Collections.unmodifiableList(inputs.subList(start, inputs.size()));
}
public void setInput(int i, Arg arg) {
this.inputs.set(i, arg);
}
@Override
public MakeImmRequest canMakeImmediate(Set<Var> closedVars,
Set<ArgCV> closedLocations, Set<Var> valueAvail, boolean waitForClose) {
boolean insertRefWaitForClose = waitForClose;
// Try to take advantage of closed variables
switch (op) {
case ARR_COPY_OUT_IMM: {
// If array is closed or this index already inserted,
// don't need to block on array.
// NOTE: could try to reduce other forms to this in one step,
// but its probably just easier to do it in multiple steps
// on subsequent passes
Var arr = getInput(0).getVar();
if (closedVars.contains(arr)) {
// Don't request to wait for close - whole array doesn't need to be
// closed
return new MakeImmRequest(null, Collections.<Var>emptyList());
}
break;
}
case ARR_COPY_OUT_FUTURE: {
Var index = getInput(1).getVar();
if (waitForClose || closedVars.contains(index)) {
return new MakeImmRequest(null, Arrays.asList(index));
}
break;
}
case AREF_COPY_OUT_FUTURE: {
Var arr = getInput(0).getVar();
Var ix = getInput(1).getVar();
// We will take either the index or the dereferenced array
List<Var> req = mkImmVarList(waitForClose, closedVars, arr, ix);
if (req.size() > 0) {
return new MakeImmRequest(null, req);
}
break;
}
case AREF_COPY_OUT_IMM: {
// Could skip using reference
Var arrRef = getInput(0).getVar();
if (waitForClose || closedVars.contains(arrRef)) {
return new MakeImmRequest(null, Arrays.asList(arrRef));
}
break;
}
case ARR_CONTAINS: {
Var arr = getInput(0).getVar();
// check to see if local version of array available
// (Already assuming array closed)
if (valueAvail.contains(arr)) {
return new MakeImmRequest(null, Arrays.asList(arr));
}
break;
}
case CONTAINER_SIZE: {
Var cont = getInput(0).getVar();
// check to see if local version of container available
// (Already assuming array closed)
if (valueAvail.contains(cont)) {
return new MakeImmRequest(null, Arrays.asList(cont));
}
break;
}
case STRUCT_COPY_IN: {
Var val = getInput(0).getVar();
if (waitForClose || closedVars.contains(val)) {
return new MakeImmRequest(null, val.asList());
}
break;
}
case STRUCTREF_COPY_IN: {
Var structRef = getOutput(0);
Var val = getInput(0).getVar();
List<Var> vs = mkImmVarList(waitForClose, closedVars,
Arrays.asList(structRef, val));
if (vs.size() > 0) {
return new MakeImmRequest(null, vs);
}
break;
}
case STRUCTREF_STORE_SUB: {
Var structRef = getOutput(0);
if (waitForClose || closedVars.contains(structRef)) {
return new MakeImmRequest(null, structRef.asList());
}
break;
}
case STRUCT_COPY_OUT: {
// If struct is closed or this field already set, don't needto block
Var struct = getInput(0).getVar();
if (closedVars.contains(struct)) {
// Don't request to wait for close - whole struct doesn't need to be
// closed
return new MakeImmRequest(null, Collections.<Var>emptyList());
}
break;
}
case STRUCTREF_COPY_OUT: {
Var structRef = getInput(0).getVar();
if (waitForClose || closedVars.contains(structRef)) {
return new MakeImmRequest(null, structRef.asList());
}
break;
}
case ARR_COPY_IN_IMM: {
// See if we can get deref arg
Var mem = getInput(1).getVar();
List<Var> vs = mkImmVarList(waitForClose, closedVars, mem.asList());
if (vs.size() > 0) {
return new MakeImmRequest(null, vs);
}
break;
}
case ARR_STORE_FUTURE:
case ARR_COPY_IN_FUTURE: {
Var ix = getInput(0).getVar();
Arg val = getInput(1);
List<Var> vs;
if (op == Opcode.ARR_STORE_FUTURE) {
vs = ix.asList();
} else {
assert(op == Opcode.ARR_COPY_IN_FUTURE);
vs = Arrays.asList(ix, val.getVar());
}
vs = mkImmVarList(waitForClose, closedVars, vs);
if (vs.size() > 0) {
return new MakeImmRequest(null, vs);
}
break;
}
case AREF_STORE_IMM:
case AREF_COPY_IN_IMM: {
List<Var> vs;
Var arrRef = getOutput(0);
Arg mem = getInput(1);
if (op == Opcode.AREF_STORE_IMM) {
vs = arrRef.asList();
} else {
assert(op == Opcode.AREF_COPY_IN_IMM);
vs = Arrays.asList(arrRef, mem.getVar());
}
vs = mkImmVarList(insertRefWaitForClose, closedVars, vs);
if (vs.size() > 0) {
return new MakeImmRequest(null, vs);
}
break;
}
case AREF_STORE_FUTURE:
case AREF_COPY_IN_FUTURE: {
Var arrRef = getOutput(0);
Var ix = getInput(0).getVar();
Arg mem = getInput(1);
List<Var> req;
if (op == Opcode.AREF_STORE_FUTURE) {
req = Arrays.asList(arrRef, ix);
} else {
assert(op == Opcode.AREF_COPY_IN_FUTURE);
req = Arrays.asList(arrRef, ix, mem.getVar());
}
// We will take either the index or the dereferenced array
req = mkImmVarList(insertRefWaitForClose, closedVars, req);
if (req.size() > 0) {
return new MakeImmRequest(null, req);
}
break;
}
case ARR_CREATE_NESTED_FUTURE: {
// Try to get immediate index
Var ix = getInput(0).getVar();
if (waitForClose || closedVars.contains(ix)) {
return new MakeImmRequest(null, Arrays.asList(ix));
}
break;
}
case AREF_CREATE_NESTED_IMM: {
Var arrRef = getOutput(1);
if (waitForClose || closedVars.contains(arrRef)) {
return new MakeImmRequest(null, Arrays.asList(arrRef));
}
break;
}
case AREF_CREATE_NESTED_FUTURE: {
Var arrRef = getOutput(1);
Var ix = getInput(0).getVar();
List<Var> req5 = mkImmVarList(waitForClose, closedVars, arrRef, ix);
if (req5.size() > 0) {
return new MakeImmRequest(null, req5);
}
break;
}
case ASYNC_COPY: {
// See if we can get closed container/struct
List<Var> req = mkImmVarList(waitForClose, closedVars,
getInput(0).getVar());
if (req.size() > 0) {
// Wait for vars only
return MakeImmRequest.waitOnly(req);
}
break;
}
case SYNC_COPY: {
// TODO: would be nice to switch to explicit load/store if container
// datum is small enough
Var dst = getOutput(0);
Var src = getInput(0).getVar();
if (Types.isPrimFuture(dst) || Types.isStruct(dst) ||
Types.isRef(dst)) {
// Small data
if (waitForClose || closedVars.contains(src)) {
return new MakeImmRequest(null, src.asList());
}
}
break;
}
case COPY_IN_FILENAME: {
Var filenameIn = getInput(0).getVar();
if (waitForClose || closedVars.contains(filenameIn)) {
return new MakeImmRequest(null, filenameIn.asList());
}
break;
}
case UPDATE_INCR:
case UPDATE_MIN:
case UPDATE_SCALE: {
Var newVal = getInput(0).getVar();
if (waitForClose || closedVars.contains(newVal)) {
return new MakeImmRequest(null, newVal.asList());
}
break;
}
default:
// fall through
break;
}
return null;
}
private List<Var> mkImmVarList(boolean waitForClose,
Set<Var> closedVars, Var... args) {
return mkImmVarList(waitForClose, closedVars, Arrays.asList(args));
}
private List<Var> mkImmVarList(boolean waitForClose,
Set<Var> closedVars, List<Var> args) {
ArrayList<Var> req = new ArrayList<Var>(args.size());
for (Var v: args) {
if (waitForClose || closedVars.contains(v)) {
req.add(v);
}
}
return req;
}
@Override
public MakeImmChange makeImmediate(VarCreator creator,
List<Fetched<Var>> out,
List<Fetched<Arg>> values) {
switch (op) {
case ARR_COPY_OUT_IMM: {
assert(values.size() == 0) : values;
// Input should be unchanged
Var arr = getInput(0).getVar();
// Output switched from ref to value
Var origOut = getOutput(0);
Var valOut = creator.createDerefTmp(origOut);
Instruction newI = arrayRetrieve(valOut, arr, getInput(1), Arg.ZERO);
return new MakeImmChange(valOut, origOut, newI);
}
case ARR_COPY_OUT_FUTURE: {
assert(values.size() == 1);
Arg newIx = values.get(0).fetched;
return new MakeImmChange(
arrayCopyOutImm(getOutput(0), getInput(0).getVar(), newIx));
}
case AREF_COPY_OUT_FUTURE: {
assert(values.size() == 1 || values.size() == 2);
Var mem = getOutput(0);
Var arrRef = getInput(0).getVar();
Var ix = getInput(1).getVar();
Arg newIx = Fetched.findFetched(values, ix);
Var newArr = Fetched.findFetchedVar(values, arrRef);
Instruction inst;
// Could be either array ref, index, or both
if (newIx != null && newArr != null) {
inst = arrayCopyOutImm(mem, newArr, newIx);
} else if (newIx != null && newArr == null){
inst = arrayRefCopyOutImm(mem, arrRef, newIx);
} else {
assert(newIx == null && newArr != null);
inst = arrayCopyOutFuture(mem, newArr, ix);
}
return new MakeImmChange(inst);
}
case AREF_COPY_OUT_IMM: {
assert(values.size() == 1);
// Switch from ref to plain array
Var newArr = values.get(0).fetched.getVar();
return new MakeImmChange(
arrayCopyOutImm(getOutput(0), newArr, getInput(1)));
}
case ARR_CONTAINS: {
Var localArr = values.get(0).fetched.getVar();
return new MakeImmChange(
arrayLocalContains(getOutput(0), localArr, getInput(1)));
}
case CONTAINER_SIZE: {
Var localCont = values.get(0).fetched.getVar();
return new MakeImmChange(
containerLocalSize(getOutput(0), localCont));
}
case STRUCT_COPY_IN: {
assert(values.size() == 1);
Arg derefMember = values.get(0).fetched;
List<String> fields = Arg.extractStrings(getInputsTail(1));
return new MakeImmChange(
structStoreSub(getOutput(0), fields, derefMember));
}
case STRUCTREF_STORE_SUB: {
assert(values.size() == 1);
Var structRef = getOutput(0);
Var newStruct = Fetched.findFetchedVar(values, structRef);
List<String> fields = Arg.extractStrings(getInputsTail(1));
return new MakeImmChange(
structStoreSub(newStruct, fields, getInput(0)));
}
case STRUCTREF_COPY_IN: {
Var structRef = getOutput(0);
Var val = getInput(0).getVar();
Var newStruct = Fetched.findFetchedVar(values, structRef);
Arg newVal = Fetched.findFetched(values, val);
List<String> fields = Arg.extractStrings(getInputsTail(1));
Instruction newI;
if (newStruct != null && newVal != null) {
newI = structStoreSub(newStruct, fields, newVal);
} else if (newStruct != null && newVal == null) {
newI = structCopyIn(newStruct, fields, val);
} else {
assert(newStruct == null && newVal != null);
newI = structRefStoreSub(structRef, fields, newVal);
}
return new MakeImmChange(newI);
}
case STRUCT_COPY_OUT: {
assert(values.size() == 0);
// Input should be unchanged
Var arr = getInput(0).getVar();
// Output switched from ref to value
Var origOut = getOutput(0);
List<String> fields = Arg.extractStrings(getInputsTail(1));
Var valOut = creator.createDerefTmp(origOut);
Instruction newI = structRetrieveSub(valOut, arr, fields, Arg.ZERO);
return new MakeImmChange(valOut, origOut, newI);
}
case STRUCTREF_COPY_OUT: {
assert(values.size() == 1);
Var structRef = getInput(0).getVar();
Var newStruct = Fetched.findFetchedVar(values, structRef);
List<String> fields = Arg.extractStrings(getInputsTail(1));
return new MakeImmChange(
structCopyOut(getOutput(0), newStruct, fields));
}
case ARR_COPY_IN_IMM: {
assert(values.size() == 1);
Arg derefMember = values.get(0).fetched;
return new MakeImmChange(
arrayStore(getOutput(0), getInput(0), derefMember));
}
case ARR_STORE_FUTURE: {
assert(values.size() == 1);
Arg fetchedIx = values.get(0).fetched;
return new MakeImmChange(
arrayStore(getOutput(0), fetchedIx, getInput(1)));
}
case ARR_COPY_IN_FUTURE: {
Var arr = getOutput(0);
Var ix = getInput(0).getVar();
Var mem = getInput(1).getVar();
Arg newIx = Fetched.findFetched(values, ix);
Arg newMem = Fetched.findFetched(values, mem);
Instruction inst;
if (newIx != null && newMem != null) {
inst = arrayStore(arr, newIx, newMem);
} else if (newIx != null && newMem == null) {
inst = arrayCopyInImm(arr, newIx, mem);
} else {
assert(newIx == null && newMem != null);
inst = arrayStoreFuture(arr, ix, newMem);
}
return new MakeImmChange(inst);
}
case AREF_STORE_IMM: {
assert(values.size() == 1);
Var newOut = values.get(0).fetched.getVar();
// Switch from ref to plain array
return new MakeImmChange(arrayStore(newOut, getInput(0), getInput(1)));
}
case AREF_COPY_IN_IMM: {
Var arrRef = getOutput(0);
Arg ix = getInput(0);
Var mem = getInput(1).getVar();
Var newArr = Fetched.findFetchedVar(values, arrRef);
Arg newMem = Fetched.findFetched(values, mem);
Instruction newI;
if (newArr != null && newMem != null) {
newI = arrayStore(newArr, ix, newMem);
} else if (newArr != null && newMem == null) {
newI = arrayCopyInImm(newArr, ix, mem);
} else {
assert(newArr == null && newMem != null);
newI = arrayRefStoreImm(arrRef, ix, newMem);
}
return new MakeImmChange(newI);
}
case AREF_STORE_FUTURE:
case AREF_COPY_IN_FUTURE: {
Var arrRef = getOutput(0);
Var ix = getInput(0).getVar();
Arg mem = getInput(1);
// Various combinations are possible
Var newArr = Fetched.findFetchedVar(values, arrRef);
Arg newIx = Fetched.findFetched(values, ix);
Arg derefMem = null;
if (mem.isVar()) {
derefMem = Fetched.findFetched(values, mem.getVar());
}
Instruction inst;
if (derefMem != null || op == Opcode.AREF_STORE_FUTURE) {
if (derefMem == null) {
assert(op == Opcode.AREF_STORE_FUTURE);
// It was already dereferenced
derefMem = mem;
}
if (newArr != null && newIx != null) {
inst = arrayStore(newArr, newIx, derefMem);
} else if (newArr != null && newIx == null) {
inst = arrayStoreFuture(newArr, ix, derefMem);
} else if (newArr == null && newIx != null) {
inst = arrayRefStoreImm(arrRef, newIx, derefMem);
} else {
assert(newArr == null && newIx == null);
inst = arrayRefStoreFuture(arrRef, ix, derefMem);
}
} else {
Var memVar = mem.getVar();
assert(op == Opcode.AREF_COPY_IN_FUTURE);
if (newArr != null && newIx != null) {
inst = arrayCopyInImm(newArr, newIx, memVar);
} else if (newArr != null && newIx == null) {
inst = arrayCopyInFuture(newArr, ix, memVar);
} else {
assert(newArr == null && newIx != null) :
this + " | " + newArr + " " + newIx;
inst = arrayRefCopyInImm(arrRef, newIx, memVar);
}
}
return new MakeImmChange(inst);
}
case ARR_CREATE_NESTED_FUTURE: {
assert(values.size() == 1);
Arg ix = values.get(0).fetched;
Var oldResult = getOutput(0);
Var oldArray = getOutput(1);
assert(Types.isArrayKeyVal(oldArray, ix)) : oldArray + " " + ix.type();
// Output type of instruction changed from ref to direct
// array handle
assert(Types.isArrayRef(oldResult.type()));
Var newOut = creator.createDerefTmp(oldResult);
return new MakeImmChange(newOut, oldResult,
arrayCreateNestedImm(newOut, oldArray, ix));
}
case AREF_CREATE_NESTED_FUTURE: {
assert(values.size() == 1 || values.size() == 2);
Var arrResult = getOutput(0);
Var arrRef = getOutput(1);
Var ix = getInput(0).getVar();
Var newArr = Fetched.findFetchedVar(values, arrRef);
Arg newIx = Fetched.findFetched(values, ix);
if (newArr != null && newIx != null) {
Var oldOut = getOutput(0);
assert(Types.isArrayRef(oldOut.type()));
Var newOut = creator.createDerefTmp(arrResult);
return new MakeImmChange(newOut, oldOut,
arrayCreateNestedImm(newOut, newArr, newIx));
} else if (newArr != null && newIx == null) {
return new MakeImmChange(
arrayCreateNestedFuture(arrResult, newArr, ix));
} else {
assert(newArr == null && newIx != null);
return new MakeImmChange(
arrayRefCreateNestedImmIx(arrResult, arrRef, newIx));
}
}
case AREF_CREATE_NESTED_IMM: {
assert(values.size() == 1);
Var newArr = values.get(0).fetched.getVar();
Arg ix = getInput(0);
Var arrResult = getOutput(0);
assert(Types.isArray(newArr));
assert(Types.isArrayRef(arrResult.type()));
Var newOut3 = creator.createDerefTmp(arrResult);
assert(Types.isArrayKeyVal(newArr, ix));
return new MakeImmChange(newOut3, arrResult,
arrayCreateNestedImm(newOut3, newArr, getInput(0)));
}
case ASYNC_COPY: {
// data is closed: replace with sync version
return new MakeImmChange(
syncCopy(getOutput(0), getInput(0).getVar()));
}
case SYNC_COPY: {
assert(values.get(0).original.equals(getInput(0).getVar()));
Arg val = values.get(0).fetched;
return new MakeImmChange(
TurbineOp.storeAny(getOutput(0), val));
}
case COPY_IN_FILENAME: {
return new MakeImmChange(
setFilenameVal(getOutput(0), values.get(0).fetched));
}
case UPDATE_INCR:
case UPDATE_MIN:
case UPDATE_SCALE: {
assert(values.size() == 1);
UpdateMode mode;
switch (op) {
case UPDATE_INCR:
mode = UpdateMode.INCR;
break;
case UPDATE_MIN:
mode = UpdateMode.MIN;
break;
case UPDATE_SCALE:
mode = UpdateMode.SCALE;
break;
default:
throw new STCRuntimeError("op: " + op +
" ... shouldn't be here");
}
return new MakeImmChange(null, null, TurbineOp.updateImm(
getOutput(0), mode, values.get(0).fetched));
}
default:
// fall through
break;
}
throw new STCRuntimeError("Couldn't make inst "
+ this.toString() + " immediate with vars: "
+ values.toString());
}
@SuppressWarnings("unchecked")
@Override
public List<Pair<Var, Instruction.InitType>> getInitialized() {
switch (op) {
case LOAD_REF:
case COPY_REF:
case ARR_CREATE_NESTED_IMM:
case ARR_CREATE_BAG:
case GET_FILENAME_ALIAS:
// Initialises alias
return Arrays.asList(Pair.create(getOutput(0), InitType.FULL));
case ARR_RETRIEVE:
case ARR_CREATE_ALIAS:
case STRUCT_RETRIEVE_SUB:
case STRUCT_CREATE_ALIAS:{
// May initialise alias if we're looking up a reference
Var output = getOutput(0);
if (output.storage() == Alloc.ALIAS) {
return Arrays.asList(Pair.create(output, InitType.FULL));
} else {
return Collections.emptyList();
}
}
case STRUCT_INIT_FIELDS: {
// Initializes struct fields that we assume are present
Var struct = getOutput(0);
return Arrays.asList(Pair.create(struct, InitType.FULL));
}
case INIT_UPDATEABLE_FLOAT:
// Initializes updateable
return Arrays.asList(Pair.create(getOutput(0), InitType.FULL));
case INIT_LOCAL_OUTPUT_FILE:
case LOAD_FILE:
// Initializes output file value
return Arrays.asList(Pair.create(getOutput(0), InitType.FULL));
default:
return Collections.emptyList();
}
}
/**
* @return list of outputs for which previous value is read
*/
public List<Var> getReadOutputs(Map<String, Function> fns) {
switch (op) {
case ARR_CREATE_NESTED_IMM:
case ARR_CREATE_NESTED_FUTURE:
// In create_nested instructions the
// second array being inserted into is needed
return Arrays.asList(getOutput(1));
case ARR_CREATE_BAG:
// the array being inserted into
return getOutput(1).asList();
case AREF_CREATE_NESTED_IMM:
case AREF_CREATE_NESTED_FUTURE:
// In ref_create_nested instructions the
// second array being inserted into is needed
return Arrays.asList(getOutput(1));
default:
return Var.NONE;
}
}
public List<Var> getModifiedOutputs() {
switch (op) {
case ARR_CREATE_NESTED_IMM:
case ARR_CREATE_NESTED_FUTURE:
case AREF_CREATE_NESTED_IMM:
case AREF_CREATE_NESTED_FUTURE:
case ARR_CREATE_BAG:
// In create_nested instructions only the
// first output (the created array) is needed
return Collections.singletonList(getOutput(0));
default:
return this.getOutputs();
}
}
@Override
public List<Component> getModifiedComponents() {
switch (op) {
case AREF_COPY_IN_FUTURE:
case AREF_COPY_IN_IMM:
case AREF_STORE_FUTURE:
case AREF_STORE_IMM:
case STRUCTREF_COPY_IN:
case STRUCTREF_STORE_SUB:
// This functions modify the datum referred to by the output reference
return new Component(getOutput(0), Component.DEREF).asList();
default:
return null;
}
}
/**
* @return List of outputs that are piecewise assigned
*/
public List<Var> getPiecewiseAssignedOutputs() {
switch (op) {
case ARR_STORE_FUTURE:
case ARR_COPY_IN_FUTURE:
case ARR_STORE:
case ARR_COPY_IN_IMM:
case AREF_STORE_FUTURE:
case AREF_COPY_IN_FUTURE:
case AREF_STORE_IMM:
case AREF_COPY_IN_IMM:
// All outputs are piecewise assigned
return getOutputs();
case ARR_CREATE_NESTED_FUTURE:
case ARR_CREATE_NESTED_IMM:
case ARR_CREATE_BAG:
case AREF_CREATE_NESTED_FUTURE:
case AREF_CREATE_NESTED_IMM: {
// All arrays except the newly created array;
List<Var> outputs = getOutputs();
return outputs.subList(1, outputs.size());
}
case STRUCT_STORE_SUB:
case STRUCT_COPY_IN:
case STRUCTREF_STORE_SUB:
case STRUCTREF_COPY_IN:
return getOutputs();
case COPY_IN_FILENAME:
case SET_FILENAME_VAL:
// File's filename might be modified
return getOutput(0).asList();
case STORE_FILE: {
Arg setFilename = getInput(1);
if (setFilename.isBoolVal() && setFilename.getBoolLit()) {
// Assign whole file
return Var.NONE;
} else {
// Assigned filename separately
return getOutput(0).asList();
}
}
default:
return Var.NONE;
}
}
@Override
public List<Var> getBlockingInputs(Program prog) {
if (getMode() == TaskMode.SYNC) {
return Var.NONE;
}
// If async, assume that all scalar input vars are blocked on
ArrayList<Var> blocksOn = new ArrayList<Var>();
for (Arg oa: getInputs()) {
if (oa.kind == ArgKind.VAR) {
Var v = oa.getVar();
Type t = v.type();
if (Types.isPrimFuture(t) || Types.isRef(t)) {
blocksOn.add(v);
} else if (Types.isPrimValue(t) || Types.isStruct(t) ||
Types.isContainer(t) || Types.isPrimUpdateable(t)) {
// No turbine ops block on these types
} else {
throw new STCRuntimeError("Don't handle type "
+ t.toString() + " here");
}
}
}
return blocksOn;
}
@Override
public TaskMode getMode() {
switch (op) {
case STORE_SCALAR:
case STORE_FILE:
case STORE_ARRAY:
case STORE_BAG:
case STORE_STRUCT:
case STORE_RECURSIVE:
case LOAD_SCALAR:
case LOAD_FILE:
case LOAD_ARRAY:
case LOAD_BAG:
case LOAD_STRUCT:
case LOAD_RECURSIVE:
case UPDATE_INCR:
case UPDATE_MIN:
case UPDATE_SCALE:
case UPDATE_INCR_IMM:
case UPDATE_MIN_IMM:
case UPDATE_SCALE_IMM:
case INIT_UPDATEABLE_FLOAT:
case LATEST_VALUE:
case ARR_STORE:
case STRUCT_INIT_FIELDS:
case STRUCT_STORE_SUB:
case STRUCT_RETRIEVE_SUB:
case STRUCT_CREATE_ALIAS:
case ARR_CREATE_ALIAS:
case ARR_CREATE_NESTED_IMM:
case ARR_CREATE_BAG:
case STORE_REF:
case LOAD_REF:
case FREE_BLOB:
case DECR_LOCAL_FILE_REF:
case GET_FILENAME_ALIAS:
case GET_LOCAL_FILENAME:
case IS_MAPPED:
case COPY_FILE_CONTENTS:
case ARR_RETRIEVE:
case COPY_REF:
case CHOOSE_TMP_FILENAME:
case GET_FILENAME_VAL:
case SET_FILENAME_VAL:
case INIT_LOCAL_OUTPUT_FILE:
case ARRAY_BUILD:
case SYNC_COPY:
case BAG_INSERT:
case CHECKPOINT_WRITE_ENABLED:
case CHECKPOINT_LOOKUP_ENABLED:
case LOOKUP_CHECKPOINT:
case WRITE_CHECKPOINT:
case PACK_VALUES:
case UNPACK_VALUES:
case UNPACK_ARRAY_TO_FLAT:
case ARR_CONTAINS:
case CONTAINER_SIZE:
case ARR_LOCAL_CONTAINS:
case CONTAINER_LOCAL_SIZE:
case STRUCT_LOCAL_BUILD:
return TaskMode.SYNC;
case ARR_COPY_IN_IMM:
case ARR_STORE_FUTURE:
case ARR_COPY_IN_FUTURE:
case AREF_STORE_FUTURE:
case AREF_COPY_IN_FUTURE:
case AREF_STORE_IMM:
case AREF_COPY_IN_IMM:
case AREF_COPY_OUT_FUTURE:
case AREF_COPY_OUT_IMM:
case ARR_COPY_OUT_IMM:
case DEREF_SCALAR:
case DEREF_FILE:
case ARR_COPY_OUT_FUTURE:
case AREF_CREATE_NESTED_FUTURE:
case ARR_CREATE_NESTED_FUTURE:
case AREF_CREATE_NESTED_IMM:
case ASYNC_COPY:
case STRUCT_COPY_IN:
case STRUCTREF_STORE_SUB:
case STRUCTREF_COPY_IN:
case STRUCT_COPY_OUT:
case STRUCTREF_COPY_OUT:
case COPY_IN_FILENAME:
return TaskMode.LOCAL;
default:
throw new STCRuntimeError("Need to add opcode " + op.toString()
+ " to getMode");
}
}
@Override
public List<ExecContext> supportedContexts() {
switch (op) {
case LOAD_ARRAY:
case LOAD_BAG:
case LOAD_FILE:
case LOAD_RECURSIVE:
case LOAD_REF:
case LOAD_SCALAR:
case LOAD_STRUCT:
case LATEST_VALUE:
case STORE_ARRAY:
case STORE_BAG:
case STORE_FILE:
case STORE_RECURSIVE:
case STORE_REF:
case STORE_SCALAR:
case STORE_STRUCT:
case ARRAY_BUILD:
// Loads and stores can run anywhere
return ExecContext.ALL;
case SET_FILENAME_VAL:
case GET_FILENAME_VAL:
case COPY_IN_FILENAME:
// Filename loads and stores can run anywhere
return ExecContext.ALL;
case INIT_LOCAL_OUTPUT_FILE:
case INIT_UPDATEABLE_FLOAT:
// Init operations can run anywhere
return ExecContext.ALL;
case UPDATE_INCR:
case UPDATE_INCR_IMM:
case UPDATE_MIN:
case UPDATE_MIN_IMM:
case UPDATE_SCALE:
case UPDATE_SCALE_IMM:
// Update operations can run anywhere
return ExecContext.ALL;
case COPY_REF:
case STRUCT_CREATE_ALIAS:
case GET_FILENAME_ALIAS:
case ARR_CREATE_ALIAS:
// Alias can be created anywhere
return ExecContext.ALL;
case DEREF_FILE:
case DEREF_SCALAR:
// Deref can be done anywhere
return ExecContext.ALL;
case ARR_CONTAINS:
case ARR_COPY_IN_FUTURE:
case ARR_COPY_IN_IMM:
case ARR_COPY_OUT_FUTURE:
case ARR_COPY_OUT_IMM:
case ARR_CREATE_NESTED_FUTURE:
case ARR_CREATE_NESTED_IMM:
case ARR_LOCAL_CONTAINS:
case ARR_RETRIEVE:
case ARR_STORE:
case ARR_STORE_FUTURE:
case ARR_CREATE_BAG:
case AREF_COPY_IN_FUTURE:
case AREF_COPY_IN_IMM:
case AREF_COPY_OUT_FUTURE:
case AREF_COPY_OUT_IMM:
case AREF_CREATE_NESTED_FUTURE:
case AREF_CREATE_NESTED_IMM:
case AREF_STORE_FUTURE:
case AREF_STORE_IMM:
case BAG_INSERT:
case CONTAINER_SIZE:
case CONTAINER_LOCAL_SIZE:
// Array ops can be done anywhere
return ExecContext.ALL;
case STRUCT_COPY_IN:
case STRUCT_COPY_OUT:
case STRUCT_INIT_FIELDS:
case STRUCT_RETRIEVE_SUB:
case STRUCT_STORE_SUB:
case STRUCTREF_COPY_IN:
case STRUCTREF_COPY_OUT:
case STRUCTREF_STORE_SUB:
// Struct ops can be done anywhere
return ExecContext.ALL;
case ASYNC_COPY:
// Copy ops can be done anywhere
return ExecContext.ALL;
case SYNC_COPY:
// Copy ops can be done anywhere
return ExecContext.ALL;
case CHECKPOINT_LOOKUP_ENABLED:
case CHECKPOINT_WRITE_ENABLED:
case CHOOSE_TMP_FILENAME:
case IS_MAPPED:
case GET_LOCAL_FILENAME:
// Utility operations can be done anywhere
return ExecContext.ALL;
case COPY_FILE_CONTENTS:
// Copying a file can take some time - only do on worker
return ExecContext.WORKER_LIST;
case DECR_LOCAL_FILE_REF:
case FREE_BLOB:
// Local refcount manipulations
return ExecContext.ALL;
case LOOKUP_CHECKPOINT:
return ExecContext.ALL;
case PACK_VALUES:
case UNPACK_ARRAY_TO_FLAT:
case UNPACK_VALUES:
case STRUCT_LOCAL_BUILD:
return ExecContext.ALL;
case WRITE_CHECKPOINT:
// Should checkpoint data where it is created
return ExecContext.ALL;
default:
throw new STCRuntimeError("Missing: " + op);
}
}
@Override
public boolean isCheap() {
switch (op) {
case LOAD_ARRAY:
case LOAD_BAG:
case LOAD_FILE:
case LOAD_RECURSIVE:
case LOAD_REF:
case LOAD_SCALAR:
case LOAD_STRUCT:
case LATEST_VALUE:
case STORE_ARRAY:
case STORE_BAG:
case STORE_FILE:
case STORE_RECURSIVE:
case STORE_REF:
case STORE_SCALAR:
case STORE_STRUCT:
case ARRAY_BUILD:
// Loads and stores aren't too expensive
return true;
case SET_FILENAME_VAL:
case GET_FILENAME_VAL:
case COPY_IN_FILENAME:
// Filename loads and stores aren't expensive
return true;
case INIT_LOCAL_OUTPUT_FILE:
case INIT_UPDATEABLE_FLOAT:
// Init operations
return true;
case UPDATE_INCR:
case UPDATE_INCR_IMM:
case UPDATE_MIN:
case UPDATE_MIN_IMM:
case UPDATE_SCALE:
case UPDATE_SCALE_IMM:
// Update operations
return true;
case COPY_REF:
case STRUCT_CREATE_ALIAS:
case GET_FILENAME_ALIAS:
case ARR_CREATE_ALIAS:
// Creating alias is cheap
return true;
case DEREF_FILE:
case DEREF_SCALAR:
// Spawning deref is cheap
return true;
case ARR_CONTAINS:
case ARR_COPY_IN_FUTURE:
case ARR_COPY_IN_IMM:
case ARR_COPY_OUT_FUTURE:
case ARR_COPY_OUT_IMM:
case ARR_CREATE_NESTED_FUTURE:
case ARR_CREATE_NESTED_IMM:
case ARR_LOCAL_CONTAINS:
case ARR_RETRIEVE:
case ARR_STORE:
case ARR_STORE_FUTURE:
case ARR_CREATE_BAG:
case AREF_COPY_IN_FUTURE:
case AREF_COPY_IN_IMM:
case AREF_COPY_OUT_FUTURE:
case AREF_COPY_OUT_IMM:
case AREF_CREATE_NESTED_FUTURE:
case AREF_CREATE_NESTED_IMM:
case AREF_STORE_FUTURE:
case AREF_STORE_IMM:
case BAG_INSERT:
case CONTAINER_SIZE:
case CONTAINER_LOCAL_SIZE:
// Container operations aren't too expensive
return true;
case STRUCT_COPY_IN:
case STRUCT_COPY_OUT:
case STRUCT_INIT_FIELDS:
case STRUCT_RETRIEVE_SUB:
case STRUCT_STORE_SUB:
case STRUCTREF_COPY_IN:
case STRUCTREF_COPY_OUT:
case STRUCTREF_STORE_SUB:
// Struct operations aren't too expensive
return true;
case ASYNC_COPY:
// Spawning the task isn't expensive
return true;
case SYNC_COPY:
// Copying a large container may be expensive
return false;
case CHECKPOINT_LOOKUP_ENABLED:
case CHECKPOINT_WRITE_ENABLED:
case CHOOSE_TMP_FILENAME:
case IS_MAPPED:
case GET_LOCAL_FILENAME:
// Utility operations are cheap
return true;
case COPY_FILE_CONTENTS:
// Copying a file can take some time
return false;
case DECR_LOCAL_FILE_REF:
case FREE_BLOB:
// Local refcount manipulations
return true;
case LOOKUP_CHECKPOINT:
return true;
case PACK_VALUES:
case UNPACK_ARRAY_TO_FLAT:
case UNPACK_VALUES:
case STRUCT_LOCAL_BUILD:
return true;
case WRITE_CHECKPOINT:
// May require I/O
return false;
default:
throw new STCRuntimeError("Missing: " + op);
}
}
@Override
public boolean isProgressEnabling() {
switch (op) {
case LOAD_ARRAY:
case LOAD_BAG:
case LOAD_FILE:
case LOAD_RECURSIVE:
case LOAD_REF:
case LOAD_SCALAR:
case LOAD_STRUCT:
case LATEST_VALUE:
case GET_FILENAME_VAL:
// Loads don't do anything
return false;
case STORE_ARRAY:
case STORE_BAG:
case STORE_FILE:
case STORE_RECURSIVE:
case STORE_REF:
case STORE_SCALAR:
case STORE_STRUCT:
case ARRAY_BUILD:
case SET_FILENAME_VAL:
case COPY_IN_FILENAME:
// Stores can enable progress
return true;
case INIT_LOCAL_OUTPUT_FILE:
case INIT_UPDATEABLE_FLOAT:
case STRUCT_INIT_FIELDS:
// Init operations don't enable progress
return false;
case UPDATE_INCR:
case UPDATE_INCR_IMM:
case UPDATE_MIN:
case UPDATE_MIN_IMM:
case UPDATE_SCALE:
case UPDATE_SCALE_IMM:
// Don't want to defer updates
return true;
case COPY_REF:
case STRUCT_CREATE_ALIAS:
case GET_FILENAME_ALIAS:
case ARR_CREATE_ALIAS:
// Creating alias doesn't make progress
return false;
case DEREF_FILE:
case DEREF_SCALAR:
// Deref assigns future
return true;
case ARR_COPY_IN_FUTURE:
case ARR_COPY_IN_IMM:
case ARR_STORE:
case ARR_STORE_FUTURE:
case AREF_COPY_IN_FUTURE:
case AREF_COPY_IN_IMM:
case AREF_STORE_FUTURE:
case AREF_STORE_IMM:
case BAG_INSERT:
// Adding to container can enable progress
return true;
case ARR_CREATE_NESTED_FUTURE:
case ARR_CREATE_NESTED_IMM:
case AREF_CREATE_NESTED_FUTURE:
case AREF_CREATE_NESTED_IMM:
case ARR_CREATE_BAG:
// Creating nested containers can release write refcount on outer
return true;
case ARR_CONTAINS:
case ARR_LOCAL_CONTAINS:
case ARR_RETRIEVE:
case CONTAINER_SIZE:
case CONTAINER_LOCAL_SIZE:
// Retrieving from array won't enable progress
return false;
case ARR_COPY_OUT_FUTURE:
case ARR_COPY_OUT_IMM:
case AREF_COPY_OUT_FUTURE:
case AREF_COPY_OUT_IMM:
// Copying to future can enable progress
return true;
case STRUCT_COPY_IN:
case STRUCT_STORE_SUB:
case STRUCTREF_COPY_IN:
case STRUCTREF_STORE_SUB:
// Adding to struct can enable progress
return true;
case STRUCT_RETRIEVE_SUB:
// Retrieving from struct won't enable progress
return false;
case STRUCT_COPY_OUT:
case STRUCTREF_COPY_OUT:
// Copying to future can enable progress
return true;
case ASYNC_COPY:
// Copying can enable progress
return true;
case SYNC_COPY:
// Copying can enable progress
return true;
case CHECKPOINT_LOOKUP_ENABLED:
case CHECKPOINT_WRITE_ENABLED:
case CHOOSE_TMP_FILENAME:
case IS_MAPPED:
case GET_LOCAL_FILENAME:
// Utility operations don't enable progress
return true;
case COPY_FILE_CONTENTS:
// Copying a file doesn't assign future
return false;
case DECR_LOCAL_FILE_REF:
case FREE_BLOB:
// Local refcount manipulations
return false;
case LOOKUP_CHECKPOINT:
return false;
case PACK_VALUES:
case UNPACK_ARRAY_TO_FLAT:
case UNPACK_VALUES:
case STRUCT_LOCAL_BUILD:
return false;
case WRITE_CHECKPOINT:
// Don't defer writing checkpoint
return true;
default:
throw new STCRuntimeError("Missing: " + op);
}
}
@Override
public List<ValLoc> getResults() {
switch(op) {
case LOAD_SCALAR:
case LOAD_REF:
case LOAD_FILE:
case LOAD_ARRAY:
case LOAD_BAG:
case LOAD_STRUCT:
case LOAD_RECURSIVE: {
Arg src = getInput(0);
Var dst = getOutput(0);
Closed outIsClosed;
if (op == Opcode.LOAD_REF) {
outIsClosed = Closed.MAYBE_NOT;
} else {
outIsClosed = Closed.YES_NOT_RECURSIVE;
}
if (op == Opcode.LOAD_REF) {
// use standard deref value
return ValLoc.derefCompVal(dst, src.getVar(), IsValCopy.NO,
IsAssign.NO).asList();
} else {
return vanillaResult(outIsClosed, IsAssign.NO).asList();
}
}
case STORE_REF:
case STORE_SCALAR:
case STORE_FILE:
case STORE_ARRAY:
case STORE_BAG:
case STORE_STRUCT:
case STORE_RECURSIVE: {
// add assign so we can avoid recreating future
// (closed b/c this instruction closes val immediately)
ValLoc assign = vanillaResult(Closed.YES_NOT_RECURSIVE,
IsAssign.TO_LOCATION);
// add retrieve so we can avoid retrieving later
Arg dst = getOutput(0).asArg();
Arg src = getInput(0);
if (op == Opcode.STORE_REF) {
// Use standard dereference computed value
ValLoc retrieve = ValLoc.derefCompVal(src.getVar(), dst.getVar(),
IsValCopy.NO, IsAssign.NO);
return Arrays.asList(retrieve, assign);
} else {
return assign.asList();
}
}
case IS_MAPPED: {
// Closed because we don't need to wait to check mapping
ValLoc vanilla = vanillaResult(Closed.YES_NOT_RECURSIVE,
IsAssign.TO_LOCATION);
assert(vanilla != null);
Var fileVar = getInput(0).getVar();
if (fileVar.isMapped() == Ternary.MAYBE) {
return vanilla.asList();
} else {
// We know the value already, so check it's a constant
Arg result = Arg.createBoolLit(fileVar.isMapped() == Ternary.TRUE);
return Arrays.asList(vanilla,
ValLoc.makeCopy(getOutput(0), result, IsAssign.NO));
}
}
case GET_FILENAME_ALIAS: {
Arg filename = getOutput(0).asArg();
Var file = getInput(0).getVar();
return ValLoc.makeFilename(filename, file).asList();
}
case COPY_IN_FILENAME: {
Arg filename = getInput(0);
Var file = getOutput(0);
return ValLoc.makeFilename(filename, file).asList();
}
case GET_LOCAL_FILENAME: {
return ValLoc.makeFilenameLocal(getOutput(0).asArg(),
getInput(0).getVar(), IsAssign.TO_LOCATION).asList();
}
case SET_FILENAME_VAL: {
Var file = getOutput(0);
Arg val = getInput(0);
return ValLoc.makeFilenameVal(file, val, IsAssign.TO_VALUE).asList();
}
case GET_FILENAME_VAL: {
Var file = getInput(0).getVar();
Var val = getOutput(0);
return ValLoc.makeFilenameVal(file, val.asArg(), IsAssign.NO).asList();
}
case DEREF_SCALAR:
case DEREF_FILE: {
return ValLoc.derefCompVal(getOutput(0), getInput(0).getVar(),
IsValCopy.YES, IsAssign.NO).asList();
}
case STRUCT_CREATE_ALIAS:
case STRUCT_COPY_OUT:
case STRUCTREF_COPY_OUT: {
// Ops that lookup field in struct somehow
Var struct = getInput(0).getVar();
List<Arg> fields = getInputsTail(1);
ValLoc copyV = ValLoc.makeStructFieldCopyResult(getOutput(0),
struct, fields);
if (op == Opcode.STRUCT_CREATE_ALIAS) {
// Create values to repr both alias and value
ValLoc aliasV = ValLoc.makeStructFieldAliasResult(getOutput(0),
struct, fields);
return Arrays.asList(aliasV, copyV);
} else {
// Not an alias - copy val only
return copyV.asList();
}
}
case STRUCT_RETRIEVE_SUB: {
Var struct = getInput(0).getVar();
List<Arg> fields = getInputsTail(2);
return ValLoc.makeStructFieldValResult(getOutput(0).asArg(),
struct, fields).asList();
}
case STRUCT_INIT_FIELDS: {
List<ValLoc> results = new ArrayList<ValLoc>();
Out<List<List<Arg>>> fieldPaths = new Out<List<List<Arg>>>();
Out<List<Arg>> fieldVals = new Out<List<Arg>>();
unpackStructInitArgs(null, fieldPaths, fieldVals);
Var struct = getOutput(0);
assert(fieldPaths.val.size() == fieldVals.val.size());
for (int i = 0; i < fieldPaths.val.size(); i++) {
results.add(ValLoc.makeStructFieldValResult(fieldVals.val.get(i),
struct, fieldPaths.val.get(i)));
}
return results;
}
case STRUCT_STORE_SUB:
case STRUCTREF_STORE_SUB: {
Var struct = getOutput(0);
Arg val = getInput(0);
List<Arg> fields;
if (op == Opcode.STRUCT_STORE_SUB) {
fields = getInputsTail(1);
} else {
assert(op == Opcode.STRUCTREF_STORE_SUB);
fields = getInputsTail(1);
}
return ValLoc.makeStructFieldValResult(val, struct, fields).asList();
}
case STRUCT_COPY_IN:
case STRUCTREF_COPY_IN: {
Var struct = getOutput(0);
Var val = getInput(0).getVar();
List<Arg> fields = getInputsTail(1);
return ValLoc.makeStructFieldCopyResult(val, struct, fields).asList();
}
case ARR_STORE:
case ARR_STORE_FUTURE:
case AREF_STORE_IMM:
case AREF_STORE_FUTURE:
case ARR_COPY_IN_IMM:
case ARR_COPY_IN_FUTURE:
case AREF_COPY_IN_IMM:
case AREF_COPY_IN_FUTURE: {
// STORE <out array> <in index> <in var>
Var arr;
arr = getOutput(0);
Arg ix = getInput(0);
Arg member = getInput(1);
boolean insertingVal = isArrayValStore(op);
return Arrays.asList(ValLoc.makeArrayResult(arr, ix, member,
insertingVal, IsAssign.TO_VALUE));
}
case ARRAY_BUILD: {
Var arr = getOutput(0);
List<ValLoc> res = new ArrayList<ValLoc>();
// Computed value for whole array
res.add(ValLoc.buildResult(op, getInputs(), arr.asArg(),
Closed.YES_NOT_RECURSIVE, IsAssign.NO));
// For individual array elements
assert(getInputs().size() % 2 == 0);
int elemCount = getInputs().size() / 2;
for (int i = 0; i < elemCount; i++) {
Arg key = getInput(2 * i);
Arg val = getInput(2 * i + 1);
res.add(ValLoc.makeArrayResult(arr, key, val, true,
IsAssign.TO_VALUE));
}
res.add(ValLoc.makeContainerSizeCV(arr,
Arg.createIntLit(elemCount), false, IsAssign.NO));
return res;
}
case ARR_CREATE_ALIAS:
case ARR_RETRIEVE:
case ARR_COPY_OUT_IMM:
case ARR_COPY_OUT_FUTURE:
case AREF_COPY_OUT_FUTURE:
case AREF_COPY_OUT_IMM: {
// LOAD <out var> <in array> <in index>
Var arr = getInput(0).getVar();
Arg ix = getInput(1);
Var contents = getOutput(0);
if (op == Opcode.ARR_RETRIEVE) {
// This just retrieves the item immediately
return ValLoc.makeArrayResult(arr, ix, contents.asArg(),
true, IsAssign.NO).asList();
} else if (op == Opcode.ARR_CREATE_ALIAS) {
ValLoc memVal = ValLoc.makeArrayResult(arr, ix, contents.asArg(),
false, IsAssign.NO);
ValLoc memAlias = ValLoc.makeArrayAlias(arr, ix, contents.asArg(),
IsAssign.NO);
return Arrays.asList(memVal, memAlias);
} else {
assert (Types.isElemType(arr, contents));
// Will assign the reference
return ValLoc.makeArrayResult(arr, ix, contents.asArg(), false,
IsAssign.TO_LOCATION).asList();
}
}
case ARR_CREATE_NESTED_FUTURE:
case ARR_CREATE_NESTED_IMM:
case AREF_CREATE_NESTED_FUTURE:
case AREF_CREATE_NESTED_IMM:
case ARR_CREATE_BAG: {
// CREATE_NESTED <out inner array> <in array> <in index>
// OR
// CREATE_BAG <out inner bag> <in array> <in index>
Var nestedArr = getOutput(0);
Var arr = getOutput(1);
Arg ix = getInput(0);
List<ValLoc> res = new ArrayList<ValLoc>();
boolean returnsNonRef = op == Opcode.ARR_CREATE_NESTED_IMM ||
op == Opcode.ARR_CREATE_BAG;
// Mark as not substitutable since this op may have
// side-effect of creating array
res.add(ValLoc.makeArrayResult(arr, ix, nestedArr.asArg(),
returnsNonRef, IsAssign.NO));
res.add(ValLoc.makeCreateNestedResult(arr, ix, nestedArr,
returnsNonRef));
return res;
}
case SYNC_COPY:
case ASYNC_COPY: {
return ValLoc.makeCopy(getOutput(0), getInput(0),
IsAssign.TO_LOCATION).asList();
}
case COPY_REF: {
Var srcRef = getInput(0).getVar();
return ValLoc.makeAlias(getOutput(0), srcRef).asList();
}
case LOOKUP_CHECKPOINT:
case UNPACK_VALUES: {
// Both have multiple outputs
List<ValLoc> res = new ArrayList<ValLoc>(outputs.size());
for (int i = 0; i < outputs.size(); i++) {
Var out = outputs.get(i);
res.add(ValLoc.buildResult(op,
(Object)i, getInput(0).asList(), out.asArg(),
Closed.YES_RECURSIVE, IsValCopy.NO, IsAssign.NO));
}
return res;
}
case PACK_VALUES:
return vanillaResult(Closed.YES_NOT_RECURSIVE, IsAssign.NO).asList();
case CHECKPOINT_LOOKUP_ENABLED:
case CHECKPOINT_WRITE_ENABLED:
return vanillaResult(Closed.YES_NOT_RECURSIVE, IsAssign.NO).asList();
case UNPACK_ARRAY_TO_FLAT:
return vanillaResult(Closed.YES_NOT_RECURSIVE, IsAssign.NO).asList();
case ARR_CONTAINS:
case CONTAINER_SIZE:
case ARR_LOCAL_CONTAINS:
case CONTAINER_LOCAL_SIZE:
return vanillaResult(Closed.YES_NOT_RECURSIVE, IsAssign.NO).asList();
case STRUCT_LOCAL_BUILD:
// Worth optimising?
return null;
default:
return null;
}
}
private boolean isArrayValStore(Opcode op) {
switch (op) {
case ARR_STORE:
case ARR_STORE_FUTURE:
case AREF_STORE_IMM:
case AREF_STORE_FUTURE:
return true;
default:
return false;
}
}
/**
* Create the "standard" computed value
* assume 1 output arg
* @return
*/
private ValLoc vanillaResult(Closed closed, IsAssign isAssign) {
assert(outputs.size() == 1);
return ValLoc.buildResult(op, inputs, outputs.get(0).asArg(), closed,
isAssign);
}
@Override
public List<Var> getClosedOutputs() {
if (op == Opcode.ARRAY_BUILD || op == Opcode.SYNC_COPY ||
op == Opcode.SYNC_COPY) {
// Output array should be closed
return Collections.singletonList(getOutput(0));
} else if (op == Opcode.STORE_REF) {
return Collections.singletonList(getOutput(0));
}
return super.getClosedOutputs();
}
@Override
public Instruction clone() {
return new TurbineOp(op, new ArrayList<Var>(outputs),
new ArrayList<Arg>(inputs));
}
@Override
public Pair<List<VarCount>, List<VarCount>> inRefCounts(
Map<String, Function> functions) {
switch (op) {
case STORE_REF:
return Pair.create(VarCount.one(getInput(0).getVar()).asList(),
VarCount.NONE);
case ARRAY_BUILD: {
List<VarCount> readIncr = new ArrayList<VarCount>();
for (int i = 0; i < getInputs().size() / 2; i++) {
// Skip keys and only get values
Arg elem = getInput(i * 2 + 1);
// Container gets reference to member
if (elem.isVar() && RefCounting.trackReadRefCount(elem.getVar())) {
readIncr.add(VarCount.one(elem.getVar()));
}
}
Var arr = getOutput(0);
return Pair.create(readIncr, VarCount.one(arr).asList());
}
case ASYNC_COPY:
case SYNC_COPY: {
// Need to pass in refcount for var to be copied, and write
// refcount for assigned var if write refcounti tracked
List<VarCount> writeRefs;
if (RefCounting.trackWriteRefCount(getOutput(0))) {
writeRefs = VarCount.one(getOutput(0)).asList();
} else {
writeRefs = VarCount.NONE;
}
return Pair.create(VarCount.one(getInput(0).getVar()).asList(),
writeRefs);
}
case STORE_BAG:
case STORE_ARRAY:
case STORE_STRUCT:
case STORE_RECURSIVE: {
// Inputs stored into array need to have refcount incremented
// This finalizes array so will consume refcount
return Pair.create(VarCount.one(getInput(0).getVar()).asList(),
VarCount.one(getOutput(0)).asList());
}
case DEREF_SCALAR:
case DEREF_FILE: {
// Increment refcount of ref var
return Pair.create(VarCount.one(getInput(0).getVar()).asList(),
VarCount.NONE);
}
case AREF_COPY_OUT_FUTURE:
case ARR_COPY_OUT_FUTURE: {
// Array and index
return Pair.create(Arrays.asList(
VarCount.one(getInput(0).getVar()), VarCount.one(getInput(1).getVar())),
VarCount.NONE);
}
case AREF_COPY_OUT_IMM:
case ARR_COPY_OUT_IMM: {
// Array only
return Pair.create(
VarCount.one(getInput(0).getVar()).asList(),
VarCount.NONE);
}
case ARR_CONTAINS:
case CONTAINER_SIZE: {
// Executes immediately, doesn't need refcount
return Pair.create(VarCount.NONE, VarCount.NONE);
}
case ARR_RETRIEVE: {
VarCount readDecr = new VarCount(getInput(0).getVar(),
getInput(2).getIntLit());
return Pair.create(readDecr.asList(), VarCount.NONE);
}
case ARR_STORE: {
Arg mem = getInput(1);
// Increment reference to memberif needed
List<VarCount> readIncr;
if (mem.isVar() && RefCounting.trackReadRefCount(mem.getVar())) {
readIncr = VarCount.one(mem.getVar()).asList();
} else {
readIncr = VarCount.NONE;
}
return Pair.create(readIncr, VarCount.NONE);
}
case ARR_COPY_IN_IMM: {
// Increment reference to member ref
// Increment writers count on array
Var mem = getInput(1).getVar();
return Pair.create(VarCount.one(mem).asList(),
VarCount.one(getOutput(0)).asList());
}
case ARR_STORE_FUTURE:
case ARR_COPY_IN_FUTURE: {
// Increment reference to member/member ref and index future
// Increment writers count on array
Var arr = getInput(0).getVar();
Arg mem = getInput(1);
List<VarCount> readIncr;
if (mem.isVar() && RefCounting.trackReadRefCount(mem.getVar())) {
readIncr = Arrays.asList(VarCount.one(arr),
VarCount.one(mem.getVar()));
} else {
readIncr = VarCount.one(arr).asList();
}
return Pair.create(readIncr, VarCount.one((getOutput(0))).asList());
}
case AREF_STORE_IMM:
case AREF_COPY_IN_IMM:
case AREF_STORE_FUTURE:
case AREF_COPY_IN_FUTURE: {
Arg ix = getInput(0);
Arg mem = getInput(1);
Var arrayRef = getOutput(0);
List<VarCount> readers = new ArrayList<VarCount>(3);
readers.add(VarCount.one(arrayRef));
if (mem.isVar() && RefCounting.trackReadRefCount(mem.getVar())) {
readers.add(VarCount.one(mem.getVar()));
}
if (op == Opcode.AREF_STORE_FUTURE ||
op == Opcode.AREF_COPY_IN_FUTURE) {
readers.add(VarCount.one(ix.getVar()));
} else {
assert(op == Opcode.AREF_STORE_IMM ||
op == Opcode.AREF_COPY_IN_IMM);
}
// Management of reference counts from array ref is handled by runtime
return Pair.create(readers, VarCount.NONE);
}
case ARR_CREATE_NESTED_FUTURE: {
Var srcArray = getOutput(1);
Var ix = getInput(0).getVar();
return Pair.create(VarCount.one(ix).asList(),
VarCount.one(srcArray).asList());
}
case AREF_CREATE_NESTED_IMM:
case AREF_CREATE_NESTED_FUTURE: {
Var arr = getOutput(1);
Arg ixArg = getInput(0);
List<VarCount> readVars;
if (op == Opcode.AREF_CREATE_NESTED_IMM) {
readVars = VarCount.one(arr).asList();
} else {
assert(op == Opcode.AREF_CREATE_NESTED_FUTURE);
readVars = Arrays.asList(VarCount.one(arr),
VarCount.one(ixArg.getVar()));
}
// Management of reference counts from array ref is handled by runtime
return Pair.create(readVars, VarCount.NONE);
}
case BAG_INSERT: {
Arg mem = getInput(0);
List<VarCount> readers = VarCount.NONE;
if (mem.isVar() && RefCounting.trackReadRefCount(mem.getVar())) {
readers = VarCount.one(mem.getVar()).asList();
}
return Pair.create(readers, VarCount.NONE);
}
case STRUCT_INIT_FIELDS: {
Out<List<Arg>> fieldVals = new Out<List<Arg>>();
unpackStructInitArgs(null, null, fieldVals);
List<VarCount> readIncr = new ArrayList<VarCount>();
List<VarCount> writeIncr = new ArrayList<VarCount>();
for (Arg fieldVal: fieldVals.val) {
if (fieldVal.isVar()) {
// Need to acquire refcount to pass to struct
Var fieldVar = fieldVal.getVar();
if (RefCounting.trackReadRefCount(fieldVar)) {
readIncr.add(VarCount.one(fieldVar));
}
if (RefCounting.trackWriteRefCount(fieldVar)) {
writeIncr.add(VarCount.one(fieldVar));
}
}
}
return Pair.create(readIncr, writeIncr);
}
case STRUCTREF_COPY_OUT:
case STRUCT_COPY_OUT: {
// Array only
return Pair.create(VarCount.one(getInput(0).getVar()).asList(),
VarCount.NONE);
}
case STRUCT_STORE_SUB:
case STRUCT_COPY_IN:
case STRUCTREF_STORE_SUB:
case STRUCTREF_COPY_IN:
// Do nothing: reference count tracker can track variables
// across struct boundaries
// TODO: still right?
return Pair.create(VarCount.NONE, VarCount.NONE);
case COPY_REF: {
return Pair.create(VarCount.one(getInput(0).getVar()).asList(),
VarCount.one(getInput(0).getVar()).asList());
}
case COPY_IN_FILENAME: {
// Read for input filename
return Pair.create(VarCount.one(getInput(0).getVar()).asList(),
VarCount.NONE);
}
case UPDATE_INCR:
case UPDATE_MIN:
case UPDATE_SCALE:
// Consumes a read refcount for the input argument and
// write refcount for updated variable
return Pair.create(VarCount.one(getInput(0).getVar()).asList(),
VarCount.one(getOutput(0)).asList());
default:
// Default is nothing
return Pair.create(VarCount.NONE, VarCount.NONE);
}
}
@Override
public Pair<List<VarCount>, List<VarCount>> outRefCounts(
Map<String, Function> functions) {
switch (this.op) {
case COPY_REF: {
// We incremented refcounts for orig. var, now need to decrement
// refcount on alias vars
Var newAlias = getOutput(0);
return Pair.create(VarCount.one(newAlias).asList(),
VarCount.one(newAlias).asList());
}
case LOAD_REF: {
// Load_ref will increment reference count of referand
Var v = getOutput(0);
long readRefs = getInput(1).getIntLit();
long writeRefs = getInput(2).getIntLit();
// TODO: return actual # of refs
return Pair.create(new VarCount(v, readRefs).asList(),
new VarCount(v, writeRefs).asList());
}
case STRUCT_RETRIEVE_SUB: {
// Gives back a read refcount to the result if relevant
// TODO: change to optionally get back write increment?
return Pair.create(VarCount.one(getOutput(0)).asList(),
VarCount.NONE);
}
case ARR_RETRIEVE: {
// Gives back a refcount to the result if relevant
return Pair.create(VarCount.one(getOutput(0)).asList(), VarCount.NONE);
}
// TODO: create_nested_imm
// TODO: other array/struct retrieval funcs
default:
return Pair.create(VarCount.NONE, VarCount.NONE);
}
}
@Override
public Var tryPiggyback(RefCountsToPlace increments, RefCountType type) {
switch (op) {
case LOAD_SCALAR:
case LOAD_FILE:
case LOAD_ARRAY:
case LOAD_BAG:
case LOAD_STRUCT:
case LOAD_RECURSIVE: {
Var inVar = getInput(0).getVar();
if (type == RefCountType.READERS) {
long amt = increments.getCount(inVar);
if (amt < 0) {
assert(getInputs().size() == 1);
// Add extra arg
this.inputs = Arrays.asList(getInput(0),
Arg.createIntLit(amt * -1));
return inVar;
}
}
break;
}
case LOAD_REF:
Var inVar = getInput(0).getVar();
if (type == RefCountType.READERS) {
long amt = increments.getCount(inVar);
if (amt < 0) {
assert(getInputs().size() == 3);
// Add extra arg
this.inputs = Arrays.asList(getInput(0), getInput(1), getInput(2),
Arg.createIntLit(amt * -1));
return inVar;
}
}
break;
case ARR_STORE:
case ARR_COPY_IN_IMM:
case ARR_STORE_FUTURE:
case ARR_COPY_IN_FUTURE: {
Var arr = getOutput(0);
if (type == RefCountType.WRITERS) {
long amt = increments.getCount(arr);
if (amt < 0) {
assert(getInputs().size() == 2);
// All except the fully immediate version decrement by 1 by default
int defaultDecr = op == Opcode.ARR_STORE ? 0 : 1;
Arg decrArg = Arg.createIntLit(amt * -1 + defaultDecr);
this.inputs = Arrays.asList(getInput(0), getInput(1), decrArg);
return arr;
}
}
break;
}
case ARR_RETRIEVE: {
Var arr = getInput(0).getVar();
assert(getInputs().size() == 3);
return tryPiggyBackHelper(increments, type, arr, 2, -1);
}
case ARR_CREATE_NESTED_IMM:
case ARR_CREATE_BAG: {
// Instruction can give additional refcounts back
Var nested = getOutput(0);
assert(getInputs().size() == 3);
// TODO: piggyback decrements here
// TODO: only works if we default to giving back refcounts
return tryPiggyBackHelper(increments, type, nested, 1, 2);
}
case BAG_INSERT: {
Var bag = getOutput(0);
return tryPiggyBackHelper(increments, type, bag, -1, 1);
}
case STRUCT_INIT_FIELDS:
return tryPiggyBackHelper(increments, type, getOutput(0), -1,
inputs.size() - 1);
case STRUCT_RETRIEVE_SUB:
return tryPiggyBackHelper(increments, type, getInput(0).getVar(),
1, -1);
default:
// Do nothing
}
// Fall through to here if can do nothing
return null;
}
/**
* Try to piggyback by applying refcount to an argument
* @param increments
* @param type
* @param var the variable with refcount being managed
* @param readDecrInput input index of read refcount arg, negative if none
* @param writeDecrInput input index of write refcount arg, negative if none
* @return
*/
private Var tryPiggyBackHelper(RefCountsToPlace increments,
RefCountType type, Var var, int readDecrInput, int writeDecrInput) {
long amt = increments.getCount(var);
if (amt < 0) {
// Which argument is increment
int inputPos;
if (type == RefCountType.READERS) {
inputPos = readDecrInput;
} else {
assert(type == RefCountType.WRITERS);
inputPos = writeDecrInput;
}
if (inputPos < 0) {
// No input
return null;
}
assert(inputPos < inputs.size());
Arg oldAmt = getInput(inputPos);
if (oldAmt.isIntVal()) {
setInput(inputPos, Arg.createIntLit(oldAmt.getIntLit() - amt));
return var;
}
}
return null;
}
@Override
public List<Alias> getAliases() {
switch (this.op) {
case ARR_CREATE_ALIAS:
return Alias.makeArrayAlias(getInput(0).getVar(), getInput(1),
getOutput(0), AliasTransform.IDENTITY);
case STRUCT_CREATE_ALIAS:
return Alias.makeStructAliases2(getInput(0).getVar(), getInputsTail(1),
getOutput(0), AliasTransform.IDENTITY);
case STRUCT_INIT_FIELDS: {
Out<List<List<String>>> fieldPaths = new Out<List<List<String>>>();
Out<List<Arg>> fieldVals = new Out<List<Arg>>();
List<Alias> aliases = new ArrayList<Alias>();
unpackStructInitArgs(fieldPaths, null, fieldVals);
assert (fieldPaths.val.size() == fieldVals.val.size());
for (int i = 0; i < fieldPaths.val.size(); i++) {
List<String> fieldPath = fieldPaths.val.get(i);
Arg fieldVal = fieldVals.val.get(i);
if (fieldVal.isVar()) {
aliases.addAll(Alias.makeStructAliases(getOutput(0), fieldPath,
fieldVal.getVar(), AliasTransform.RETRIEVE));
}
}
return aliases;
}
case STRUCT_RETRIEVE_SUB:
return Alias.makeStructAliases2(getInput(0).getVar(), getInputsTail(2),
getOutput(0), AliasTransform.RETRIEVE);
case STRUCT_STORE_SUB:
if (getInput(0).isVar()) {
return Alias.makeStructAliases2(getOutput(0), getInputsTail(1),
getInput(0).getVar(), AliasTransform.RETRIEVE);
}
break;
case STRUCT_COPY_OUT:
return Alias.makeStructAliases2(getInput(0).getVar(), getInputsTail(1),
getOutput(0), AliasTransform.COPY);
case STRUCT_COPY_IN:
return Alias.makeStructAliases2(getOutput(0), getInputsTail(1),
getInput(0).getVar(), AliasTransform.COPY);
case STORE_REF: {
// need to track if ref is alias to struct field
Var ref = getOutput(0);
Var val = getInput(0).getVar();
return new Alias(ref, Collections.<String>emptyList(),
AliasTransform.RETRIEVE, val).asList();
}
case LOAD_REF: {
// need to track if ref is alias to struct field
Var val = getOutput(0);
Var ref = getInput(0).getVar();
return new Alias(ref, Collections.<String>emptyList(),
AliasTransform.RETRIEVE, val).asList();
}
case COPY_REF: {
// need to track if ref is alias to struct field
Var ref1 = getOutput(0);
Var ref2 = getInput(0).getVar();
return Arrays.asList(
new Alias(ref1, Collections.<String>emptyList(),
AliasTransform.COPY, ref2),
new Alias(ref2, Collections.<String>emptyList(),
AliasTransform.COPY, ref1));
}
case GET_FILENAME_ALIAS: {
return new Alias(getInput(0).getVar(), Alias.FILENAME_PATH,
AliasTransform.IDENTITY, getOutput(0)).asList();
}
default:
// Opcode not relevant
break;
}
return Alias.NONE;
}
@Override
public List<ComponentAlias> getComponentAliases() {
switch (op) {
case ARR_CREATE_NESTED_IMM:
case ARR_CREATE_BAG:
// From inner object to immediately enclosing
return new ComponentAlias(getOutput(1), Component.deref(getInput(0).asList()),
getOutput(0)).asList();
case ARR_CREATE_NESTED_FUTURE: {
// From inner array to immediately enclosing
return new ComponentAlias(getOutput(1), getInput(0).asList(),
getOutput(0)).asList();
}
case AREF_CREATE_NESTED_IMM:
case AREF_CREATE_NESTED_FUTURE: {
List<Arg> key = Arrays.asList(Component.DEREF, getInput(0));
// From inner array to immediately enclosing
return new ComponentAlias(getOutput(1), key, getOutput(0)).asList();
}
case AREF_STORE_FUTURE:
case AREF_STORE_IMM:
case ARR_STORE:
case ARR_STORE_FUTURE: {
Var arr = getOutput(0);
if (Types.isRef(Types.arrayKeyType(arr))) {
Arg ix = getInput(0);
List<Arg> key;
if (Types.isArrayRef(arr)) {
// Mark extra dereference
key = Arrays.asList(Component.DEREF, ix, Component.DEREF);
} else {
key = Arrays.asList(ix, Component.DEREF);
}
return new ComponentAlias(arr, key, getInput(1).getVar()).asList();
}
break;
}
case ARR_COPY_IN_FUTURE:
case ARR_COPY_IN_IMM:
case AREF_COPY_IN_FUTURE:
case AREF_COPY_IN_IMM: {
Var arr = getOutput(0);
if (Types.isRef(Types.arrayKeyType(arr))) {
Arg ix = getInput(0);
List<Arg> key;
if (Types.isArrayRef(arr)) {
// Mark extra dereference
key = Arrays.asList(Component.DEREF, ix);
} else {
key = ix.asList();
}
return new ComponentAlias(arr, key, getInput(1).getVar()).asList();
}
break;
}
case ARR_CREATE_ALIAS: {
return new ComponentAlias(getInput(0).getVar(), getInput(1),
getOutput(0)).asList();
}
case ARR_COPY_OUT_FUTURE:
case ARR_COPY_OUT_IMM:
case AREF_COPY_OUT_FUTURE:
case AREF_COPY_OUT_IMM: {
Var arr = getInput(0).getVar();
if (Types.isRef(Types.arrayKeyType(arr))) {
Arg ix = getInput(1);
List<Arg> key;
if (Types.isArrayRef(arr)) {
// Mark extra dereference
key = Arrays.asList(Component.DEREF, ix);
} else {
key = ix.asList();
}
return new ComponentAlias(arr, key, getOutput(0)).asList();
}
break;
}
case LOAD_REF:
// If reference was a part of something, modifying the
// dereferenced object will modify the whole
return ComponentAlias.ref(getOutput(0), getInput(0).getVar()).asList();
case COPY_REF:
return ComponentAlias.directAlias(getOutput(0), getInput(0).getVar()).asList();
case STORE_REF:
// Sometimes a reference is filled in
return ComponentAlias.ref(getInput(0).getVar(), getOutput(0)).asList();
case STRUCT_INIT_FIELDS: {
Out<List<List<Arg>>> fieldPaths = new Out<List<List<Arg>>>();
Out<List<Arg>> fieldVals = new Out<List<Arg>>();
List<ComponentAlias> aliases = new ArrayList<ComponentAlias>();
unpackStructInitArgs(null, fieldPaths, fieldVals);
assert (fieldPaths.val.size() == fieldVals.val.size());
Var struct = getOutput(0);
for (int i = 0; i < fieldPaths.val.size(); i++) {
List<Arg> fieldPath = fieldPaths.val.get(i);
Arg fieldVal = fieldVals.val.get(i);
if (fieldVal.isVar()) {
if (Alias.fieldIsRef(struct, Arg.extractStrings(fieldPath))) {
aliases.add(new ComponentAlias(struct, Component.deref(fieldPath),
fieldVal.getVar()));
}
}
}
return aliases;
}
case STRUCT_CREATE_ALIAS: {
// Output is alias for part of struct
List<Arg> fields = getInputsTail(1);
return new ComponentAlias(getInput(0).getVar(), fields,
getOutput(0)).asList();
}
case STRUCTREF_STORE_SUB:
case STRUCT_STORE_SUB:
if (Alias.fieldIsRef(getOutput(0),
Arg.extractStrings(getInputsTail(1)))) {
List<Arg> fields = getInputsTail(1);
if (op == Opcode.STRUCTREF_STORE_SUB) {
// Mark extra dereference
fields = new ArrayList<Arg>(fields);
fields.add(0, Component.DEREF);
}
return new ComponentAlias(getOutput(0), Component.deref(fields),
getInput(0).getVar()).asList();
}
break;
case STRUCT_RETRIEVE_SUB:
if (Alias.fieldIsRef(getInput(0).getVar(),
Arg.extractStrings(getInputsTail(2)))) {
List<Arg> fields = getInputsTail(1);
return new ComponentAlias(getInput(0).getVar(), Component.deref(fields),
getOutput(0)).asList();
}
break;
case STRUCTREF_COPY_IN:
case STRUCT_COPY_IN:
if (Alias.fieldIsRef(getOutput(0),
Arg.extractStrings(getInputsTail(1)))) {
List<Arg> fields = getInputsTail(1);
if (op == Opcode.STRUCTREF_COPY_IN) {
// Mark extra dereference
fields = new ArrayList<Arg>(fields);
fields.add(0, Component.DEREF);
}
return new ComponentAlias(getOutput(0),
fields, getInput(0).getVar()).asList();
}
break;
case STRUCTREF_COPY_OUT:
case STRUCT_COPY_OUT:
if (Alias.fieldIsRef(getInput(0).getVar(),
Arg.extractStrings(getInputsTail(1)))) {
List<Arg> fields = getInputsTail(1);
return new ComponentAlias(getInput(0).getVar(),
fields, getOutput(0)).asList();
}
break;
default:
// Return nothing
break;
}
return Collections.emptyList();
}
public boolean isIdempotent() {
switch (op) {
case ARR_CREATE_NESTED_FUTURE:
case ARR_CREATE_NESTED_IMM:
case AREF_CREATE_NESTED_FUTURE:
case AREF_CREATE_NESTED_IMM:
case ARR_CREATE_BAG:
return true;
default:
return false;
}
}
/**
* Instruction class specifically for reference counting operations with
* defaults derived from TurbineOp
*/
public static class RefCountOp extends TurbineOp {
/**
* Direction of change (increment or decrement)
*/
public static enum RCDir {
INCR,
DECR;
public static RCDir fromAmount(long amount) {
if (amount >= 0) {
return INCR;
} else {
return DECR;
}
}
};
public RefCountOp(Var target, RCDir dir, RefCountType type, Arg amount) {
super(getRefCountOp(dir, type), Var.NONE,
Arrays.asList(target.asArg(), amount));
}
public static RefCountOp decrWriters(Var target, Arg amount) {
return new RefCountOp(target, RCDir.DECR, RefCountType.WRITERS, amount);
}
public static RefCountOp incrWriters(Var target, Arg amount) {
return new RefCountOp(target, RCDir.INCR, RefCountType.WRITERS, amount);
}
public static RefCountOp decrRef(Var target, Arg amount) {
return new RefCountOp(target, RCDir.DECR, RefCountType.READERS, amount);
}
public static RefCountOp incrRef(Var target, Arg amount) {
return new RefCountOp(target, RCDir.INCR, RefCountType.READERS, amount);
}
public static RefCountOp decrRef(RefCountType rcType, Var v, Arg amount) {
return new RefCountOp(v, RCDir.DECR, rcType, amount);
}
public static RefCountOp incrRef(RefCountType rcType, Var v, Arg amount) {
return new RefCountOp(v, RCDir.INCR, rcType, amount);
}
public static RefCountType getRCType(Opcode op) {
assert(isRefcountOp(op));
if (op == Opcode.INCR_READERS || op == Opcode.DECR_READERS) {
return RefCountType.READERS;
} else {
assert(op == Opcode.INCR_WRITERS || op == Opcode.DECR_WRITERS);
return RefCountType.WRITERS;
}
}
public static Var getRCTarget(Instruction refcountOp) {
assert(isRefcountOp(refcountOp.op));
return refcountOp.getInput(0).getVar();
}
public static Arg getRCAmount(Instruction refcountOp) {
assert(isRefcountOp(refcountOp.op));
return refcountOp.getInput(1);
}
private static Opcode getRefCountOp(RCDir dir, RefCountType type) {
if (type == RefCountType.READERS) {
if (dir == RCDir.INCR) {
return Opcode.INCR_READERS;
} else {
assert(dir == RCDir.DECR);
return Opcode.DECR_READERS;
}
} else {
assert(type == RefCountType.WRITERS);
if (dir == RCDir.INCR) {
return Opcode.INCR_WRITERS;
} else {
assert(dir == RCDir.DECR);
return Opcode.DECR_WRITERS;
}
}
}
private static RCDir getRefcountDir(Opcode op) {
if (isIncrement(op)) {
return RCDir.INCR;
} else {
assert(isDecrement(op));
return RCDir.DECR;
}
}
public static boolean isIncrement(Opcode op) {
return (op == Opcode.INCR_READERS || op == Opcode.INCR_WRITERS);
}
public static boolean isDecrement(Opcode op) {
return (op == Opcode.DECR_READERS || op == Opcode.DECR_WRITERS);
}
public static boolean isRefcountOp(Opcode op) {
return isIncrement(op) || isDecrement(op);
}
@Override
public void generate(Logger logger, CompilerBackend gen, GenInfo info) {
switch (op) {
case DECR_WRITERS:
gen.decrWriters(getRCTarget(this), getRCAmount(this));
break;
case INCR_WRITERS:
gen.incrWriters(getRCTarget(this), getRCAmount(this));
break;
case DECR_READERS:
gen.decrRef(getRCTarget(this), getRCAmount(this));
break;
case INCR_READERS:
gen.incrRef(getRCTarget(this), getRCAmount(this));
break;
default:
throw new STCRuntimeError("Unknown op type: " + op);
}
}
@Override
public TaskMode getMode() {
// Executes right away
return TaskMode.SYNC;
}
@Override
public List<ExecContext> supportedContexts() {
return ExecContext.ALL;
}
@Override
public boolean isCheap() {
return true;
}
@Override
public boolean isProgressEnabling() {
// Decrementing write refcount can close
return getRCType(op) == RefCountType.WRITERS;
}
@Override
public boolean hasSideEffects() {
// Model refcount change as side-effect
return true;
}
@Override
public Instruction clone() {
return new RefCountOp(getRCTarget(this), getRefcountDir(this.op),
getRCType(this.op), getRCAmount(this));
}
}
}
|
Return refcounts from create_nested_imm
git-svn-id: 0c5512015aa96f7d3f5c3ad598bd98edc52008b1@11557 dc4e9af1-7f46-4ead-bba6-71afc04862de
|
code/src/exm/stc/ic/tree/TurbineOp.java
|
Return refcounts from create_nested_imm
|
<ide><path>ode/src/exm/stc/ic/tree/TurbineOp.java
<ide> /**
<ide> * Create a nested array inside the current one, or return current
<ide> * nested array if not present. Acquire read + write reference
<del> * to nested array. (TODO)
<add> * to nested array.
<ide> * @param arrayResult
<ide> * @param arrayVar
<ide> * @param arrIx
<ide> assert(Types.isArray(arrayVar.type()));
<ide> assert(arrayResult.storage() == Alloc.ALIAS);
<ide> assert(Types.isArrayKeyVal(arrayVar, arrIx));
<add> Arg readAcquire = Arg.ONE;
<add> Arg writeAcquire = Arg.ONE;
<add>
<ide> // Both arrays are modified, so outputs
<ide> return new TurbineOp(Opcode.ARR_CREATE_NESTED_IMM,
<ide> Arrays.asList(arrayResult, arrayVar),
<del> arrIx, Arg.ZERO, Arg.ZERO);
<add> arrIx, readAcquire, writeAcquire);
<ide> }
<ide>
<ide> public static Instruction arrayRefCreateNestedComputed(Var arrayResult,
<ide> // Gives back a refcount to the result if relevant
<ide> return Pair.create(VarCount.one(getOutput(0)).asList(), VarCount.NONE);
<ide> }
<del> // TODO: create_nested_imm
<add> case ARR_CREATE_NESTED_IMM: {
<add> long readIncr = getInput(1).getIntLit();
<add> long writeIncr = getInput(2).getIntLit();
<add> Var resultArr = getOutput(0);
<add> return Pair.create(new VarCount(resultArr, readIncr).asList(),
<add> new VarCount(resultArr, writeIncr).asList());
<add> }
<ide> // TODO: other array/struct retrieval funcs
<ide> default:
<ide> return Pair.create(VarCount.NONE, VarCount.NONE);
|
|
Java
|
apache-2.0
|
7e8ce880953ed7cb61f4062b19f74023fc1d5d15
| 0 |
candyam5522/eureka,candyam5522/eureka,candyam5522/eureka,jsons/eureka
|
package edu.emory.cci.aiw.cvrg.eureka.services.resource;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import javax.mail.MessagingException;
import javax.servlet.ServletException;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Inject;
import com.sun.jersey.api.client.ClientResponse.Status;
import edu.emory.cci.aiw.cvrg.eureka.common.entity.Role;
import edu.emory.cci.aiw.cvrg.eureka.common.entity.User;
import edu.emory.cci.aiw.cvrg.eureka.common.entity.UserRequest;
import edu.emory.cci.aiw.cvrg.eureka.services.dao.RoleDao;
import edu.emory.cci.aiw.cvrg.eureka.services.dao.UserDao;
import edu.emory.cci.aiw.cvrg.eureka.services.email.EmailSender;
/**
* RESTful end-point for {@link User} related methods.
*
* @author hrathod
*
*/
@Path("/user")
public class UserResource {
/**
* The class logger.
*/
private static final Logger LOGGER = LoggerFactory
.getLogger(UserResource.class);
/**
* Data access object to work with User objects.
*/
private final UserDao userDao;
/**
* Data access object to work with Role objects.
*/
private final RoleDao roleDao;
/**
* Used to send emails to the user when needed.
*/
private final EmailSender emailSender;
/**
* Create a UserResource object with a User DAO and a Role DAO.
*
* @param inUserDao DAO used to access {@link User} related functionality.
* @param inRoleDao DAO used to access {@link Role} related functionality.
* @param inEmailSender Used to send emails to the user when necessary.
*/
@Inject
public UserResource(UserDao inUserDao, RoleDao inRoleDao,
EmailSender inEmailSender) {
this.userDao = inUserDao;
this.roleDao = inRoleDao;
this.emailSender = inEmailSender;
}
/**
* Get a list of all users in the system.
*
* @return A list of {@link User} objects.
*/
@Path("/list")
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<User> getUsers() {
LOGGER.debug("Returning list of users");
return this.userDao.getUsers();
}
/**
* Get a user by the user's identification number.
*
* @param inId The identification number for the user to fetch.
* @return The user referenced by the identification number.
* @throws ServletException Thrown if the identification number string can
* not be properly converted to a {@link Long}.
*/
@Path("/byid/{id}")
@GET
@Produces(MediaType.APPLICATION_JSON)
public User getUserById(@PathParam("id") long inId) throws ServletException {
return this.userDao.get(Long.valueOf(inId));
}
/**
* Get a user using the username.
*
* @param inName The of the user to fetch.
* @return The user corresponding to the given name.
* @throws ServletException Thrown if the given name does not match any user
* in the system.
*/
@Path("/byname/{name}")
@GET
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public User getUserByName(@PathParam("name") String inName)
throws ServletException {
return this.userDao.get(inName);
}
/**
* Add a new user to the system.
*
* @param userRequest Object containing all the information about the user
* to add.
* @return A "Bad Request" error if the user does not pass validation, a
* "Created" response with a link to the user page if successful.
*/
@Path("/add")
@POST
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces(MediaType.TEXT_PLAIN)
public Response addUser(final UserRequest userRequest) {
Response response = null;
if (validateUserRequest(userRequest)) {
User user = new User();
user.setEmail(userRequest.getEmail());
user.setFirstName(userRequest.getFirstName());
user.setLastName(userRequest.getLastName());
user.setOrganization(userRequest.getOrganization());
user.setPassword(userRequest.getPassword());
user.setRoles(this.getDefaultRoles());
LOGGER.debug("Saving new user {0}", user.getEmail());
this.userDao.save(user);
try {
LOGGER.debug("Sending email to {0}", user.getEmail());
this.emailSender.sendMessage(user.getEmail());
} catch (MessagingException e) {
System.out.println("ERROR SENDING EMAIL: " + e.getMessage());
e.printStackTrace();
}
response = Response.created(URI.create("/" + user.getId())).build();
} else {
response = Response.status(Status.BAD_REQUEST)
.entity("Invalid user request.").build();
}
return response;
}
/**
* Change a user's password.
*
* @param inId The unique identifier for the user.
* @param oldPassword The old password for the user.
* @param newPassword The new password for the user.
* @return {@link Status#OK} if the password update is successful,
* {@link Status#BAD_REQUEST} if the current password does not
* match, or if the user does not exist.
*/
@Path("/passwd/{id}")
@GET
public Response changePassword(@PathParam("id") final Long inId,
@QueryParam("oldPassword") final String oldPassword,
@QueryParam("newPassword") final String newPassword) {
Response response;
User user = this.userDao.get(inId);
if (user.getPassword().equals(oldPassword)) {
user.setPassword(newPassword);
this.userDao.save(user);
response = Response.ok().build();
} else {
response = Response.status(Status.BAD_REQUEST)
.entity("Password mismatch").build();
}
return response;
}
/**
* Put an updated user to the system.
*
* @param user Object containing all the information about the user to add.
* @return A "Created" response with a link to the user page if successful.
*
*/
@Path("/put")
@PUT
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces(MediaType.TEXT_PLAIN)
public Response putUser(final User user) {
Response response = null;
User updateUser = this.userDao.get(user.getId());
List<Role> roles = user.getRoles();
List<Role> updatedRoles = new ArrayList<Role>();
for (Role r : roles) {
Role updatedRole = this.roleDao.getRoleById(r.getId());
updatedRoles.add(updatedRole);
}
updateUser.setRoles(updatedRoles);
updateUser.setActive(user.isActive());
if (this.validateUpdatedUser(updateUser)) {
this.userDao.save(updateUser);
response = Response.created(URI.create("/" + updateUser.getId()))
.build();
} else {
response = Response.notModified("Invalid user").build();
}
return response;
}
/**
* Mark a user as verified.
*
* @param inId The unique identifier for the user to be verified.
* @return An HTTP OK response if the user is modified, or a server error if
* the user can not be modified properly.
*/
@Path("/verify/{id}")
@PUT
public Response verifyUser(@PathParam("id") final Long inId) {
Response response = Response.ok().build();
User user = this.userDao.get(inId);
if (user != null) {
user.setVerified(true);
this.userDao.save(user);
} else {
response = Response.notModified("Invalid user").build();
}
return response;
}
/**
* Mark a user as active.
*
* @param inId the unique identifier of the user to be made active.
* @return An HTTP OK response if the modification is completed normall, or
* a server error if the user cannot be modified properly.
*/
@Path("/activate/{id}")
@PUT
public Response activateUser(@PathParam("id") final Long inId) {
Response response = Response.ok().build();
User user = this.userDao.get(inId);
if (user != null) {
user.setActive(true);
this.userDao.save(user);
} else {
response = Response.status(Status.BAD_REQUEST).entity("Invalid ID")
.build();
}
return response;
}
/**
* Validate a {@link UserRequest} object. Two rules are implemented: 1) The
* email addresses in the two email fields must match, and 2) The passwords
* in the two password fields must match.
*
* @param userRequest The {@link UserRequest} object to validate.
* @return True if the request is valid, and false otherwise.
*/
private static boolean validateUserRequest(UserRequest userRequest) {
boolean result = true;
// make sure the email addresses are not null, and match each other
if ((userRequest.getEmail() == null)
|| (userRequest.getVerifyEmail() == null)
|| (!userRequest.getEmail()
.equals(userRequest.getVerifyEmail()))) {
result = false;
}
// make sure the passwords are not null, and match each other
if ((userRequest.getPassword() == null)
|| (userRequest.getVerifyPassword() == null)
|| (!userRequest.getPassword().equals(
userRequest.getVerifyPassword()))) {
result = false;
}
return result;
}
/**
* Validate that a user being updated does not violate any rules.
*
* @param user The user to be validate.
* @return True if the user is valid, false otherwise.
*/
private boolean validateUpdatedUser(User user) {
boolean result = true;
// a super user can not be de-activated or stripped of admin rights
if (user.isSuperUser()) {
if (user.isActive() == false) {
result = false;
}
Role adminRole = this.roleDao.getRoleByName("admin");
if (!user.getRoles().contains(adminRole)) {
result = false;
}
}
return result;
}
/**
* Get a set of default roles to be added to a newly created user.
*
* @return A list of default roles.
*/
private List<Role> getDefaultRoles() {
List<Role> defaultRoles = new ArrayList<Role>();
for (Role role : this.roleDao.getRoles()) {
if (role.isDefaultRole() == Boolean.TRUE) {
defaultRoles.add(role);
}
}
return defaultRoles;
}
}
|
eureka-services/src/main/java/edu/emory/cci/aiw/cvrg/eureka/services/resource/UserResource.java
|
package edu.emory.cci.aiw.cvrg.eureka.services.resource;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import javax.mail.MessagingException;
import javax.servlet.ServletException;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.google.inject.Inject;
import com.sun.jersey.api.client.ClientResponse.Status;
import edu.emory.cci.aiw.cvrg.eureka.common.entity.Role;
import edu.emory.cci.aiw.cvrg.eureka.common.entity.User;
import edu.emory.cci.aiw.cvrg.eureka.common.entity.UserRequest;
import edu.emory.cci.aiw.cvrg.eureka.services.dao.RoleDao;
import edu.emory.cci.aiw.cvrg.eureka.services.dao.UserDao;
import edu.emory.cci.aiw.cvrg.eureka.services.email.EmailSender;
/**
* RESTful end-point for {@link User} related methods.
*
* @author hrathod
*
*/
@Path("/user")
public class UserResource {
/**
* Data access object to work with User objects.
*/
private final UserDao userDao;
/**
* Data access object to work with Role objects.
*/
private final RoleDao roleDao;
/**
* Used to send emails to the user when needed.
*/
private final EmailSender emailSender;
/**
* Create a UserResource object with a User DAO and a Role DAO.
*
* @param inUserDao DAO used to access {@link User} related functionality.
* @param inRoleDao DAO used to access {@link Role} related functionality.
* @param inEmailSender Used to send emails to the user when necessary.
*/
@Inject
public UserResource(UserDao inUserDao, RoleDao inRoleDao,
EmailSender inEmailSender) {
this.userDao = inUserDao;
this.roleDao = inRoleDao;
this.emailSender = inEmailSender;
}
/**
* Get a list of all users in the system.
*
* @return A list of {@link User} objects.
*/
@Path("/list")
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<User> getUsers() {
return this.userDao.getUsers();
}
/**
* Get a user by the user's identification number.
*
* @param inId The identification number for the user to fetch.
* @return The user referenced by the identification number.
* @throws ServletException Thrown if the identification number string can
* not be properly converted to a {@link Long}.
*/
@Path("/byid/{id}")
@GET
@Produces(MediaType.APPLICATION_JSON)
public User getUserById(@PathParam("id") long inId) throws ServletException {
return this.userDao.get(Long.valueOf(inId));
}
/**
* Get a user using the username.
*
* @param inName The of the user to fetch.
* @return The user corresponding to the given name.
* @throws ServletException Thrown if the given name does not match any user
* in the system.
*/
@Path("/byname/{name}")
@GET
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public User getUserByName(@PathParam("name") String inName)
throws ServletException {
return this.userDao.get(inName);
}
/**
* Add a new user to the system.
*
* @param userRequest Object containing all the information about the user
* to add.
* @return A "Bad Request" error if the user does not pass validation, a
* "Created" response with a link to the user page if successful.
*/
@Path("/add")
@POST
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces(MediaType.TEXT_PLAIN)
public Response addUser(final UserRequest userRequest) {
Response response = null;
if (validateUserRequest(userRequest)) {
User user = new User();
user.setEmail(userRequest.getEmail());
user.setFirstName(userRequest.getFirstName());
user.setLastName(userRequest.getLastName());
user.setOrganization(userRequest.getOrganization());
user.setPassword(userRequest.getPassword());
user.setRoles(this.getDefaultRoles());
this.userDao.save(user);
try {
this.emailSender.sendMessage(user.getEmail());
} catch (MessagingException e) {
System.out.println("ERROR SENDING EMAIL: " + e.getMessage());
e.printStackTrace();
}
response = Response.created(URI.create("/" + user.getId())).build();
} else {
response = Response.status(Status.BAD_REQUEST)
.entity("Invalid user request.").build();
}
return response;
}
/**
* Change a user's password.
*
* @param inId The unique identifier for the user.
* @param oldPassword The old password for the user.
* @param newPassword The new password for the user.
* @return {@link Status#OK} if the password update is successful,
* {@link Status#BAD_REQUEST} if the current password does not
* match, or if the user does not exist.
*/
@Path("/passwd/{id}")
@GET
public Response changePassword(@PathParam("id") final Long inId,
@QueryParam("oldPassword") final String oldPassword,
@QueryParam("newPassword") final String newPassword) {
Response response;
User user = this.userDao.get(inId);
if (user.getPassword().equals(oldPassword)) {
user.setPassword(newPassword);
this.userDao.save(user);
response = Response.ok().build();
} else {
response = Response.status(Status.BAD_REQUEST)
.entity("Password mismatch").build();
}
return response;
}
/**
* Put an updated user to the system.
*
* @param user Object containing all the information about the user to add.
* @return A "Created" response with a link to the user page if successful.
*
*/
@Path("/put")
@PUT
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces(MediaType.TEXT_PLAIN)
public Response putUser(final User user) {
Response response = null;
User updateUser = this.userDao.get(user.getId());
List<Role> roles = user.getRoles();
List<Role> updatedRoles = new ArrayList<Role>();
for (Role r : roles) {
Role updatedRole = this.roleDao.getRoleById(r.getId());
updatedRoles.add(updatedRole);
}
updateUser.setRoles(updatedRoles);
updateUser.setActive(user.isActive());
if (this.validateUpdatedUser(updateUser)) {
this.userDao.save(updateUser);
response = Response.created(URI.create("/" + updateUser.getId()))
.build();
} else {
response = Response.notModified("Invalid user").build();
}
return response;
}
/**
* Mark a user as verified.
*
* @param inId The unique identifier for the user to be verified.
* @return An HTTP OK response if the user is modified, or a server error if
* the user can not be modified properly.
*/
@Path("/verify/{id}")
@PUT
public Response verifyUser(@PathParam("id") final Long inId) {
Response response = Response.ok().build();
User user = this.userDao.get(inId);
if (user != null) {
user.setVerified(true);
this.userDao.save(user);
} else {
response = Response.notModified("Invalid user").build();
}
return response;
}
/**
* Mark a user as active.
*
* @param inId the unique identifier of the user to be made active.
* @return An HTTP OK response if the modification is completed normall, or
* a server error if the user cannot be modified properly.
*/
@Path("/activate/{id}")
@PUT
public Response activateUser(@PathParam("id") final Long inId) {
Response response = Response.ok().build();
User user = this.userDao.get(inId);
if (user != null) {
user.setActive(true);
this.userDao.save(user);
} else {
response = Response.status(Status.BAD_REQUEST).entity("Invalid ID")
.build();
}
return response;
}
/**
* Validate a {@link UserRequest} object. Two rules are implemented: 1) The
* email addresses in the two email fields must match, and 2) The passwords
* in the two password fields must match.
*
* @param userRequest The {@link UserRequest} object to validate.
* @return True if the request is valid, and false otherwise.
*/
private static boolean validateUserRequest(UserRequest userRequest) {
boolean result = true;
// make sure the email addresses are not null, and match each other
if ((userRequest.getEmail() == null)
|| (userRequest.getVerifyEmail() == null)
|| (!userRequest.getEmail()
.equals(userRequest.getVerifyEmail()))) {
result = false;
}
// make sure the passwords are not null, and match each other
if ((userRequest.getPassword() == null)
|| (userRequest.getVerifyPassword() == null)
|| (!userRequest.getPassword().equals(
userRequest.getVerifyPassword()))) {
result = false;
}
return result;
}
/**
* Validate that a user being updated does not violate any rules.
*
* @param user The user to be validate.
* @return True if the user is valid, false otherwise.
*/
private boolean validateUpdatedUser(User user) {
boolean result = true;
// a super user can not be de-activated or stripped of admin rights
if (user.isSuperUser()) {
if (user.isActive() == false) {
result = false;
}
Role adminRole = this.roleDao.getRoleByName("admin");
if (!user.getRoles().contains(adminRole)) {
result = false;
}
}
return result;
}
/**
* Get a set of default roles to be added to a newly created user.
*
* @return A list of default roles.
*/
private List<Role> getDefaultRoles() {
List<Role> defaultRoles = new ArrayList<Role>();
for (Role role : this.roleDao.getRoles()) {
if (role.isDefaultRole() == Boolean.TRUE) {
defaultRoles.add(role);
}
}
return defaultRoles;
}
}
|
Added some logging.
|
eureka-services/src/main/java/edu/emory/cci/aiw/cvrg/eureka/services/resource/UserResource.java
|
Added some logging.
|
<ide><path>ureka-services/src/main/java/edu/emory/cci/aiw/cvrg/eureka/services/resource/UserResource.java
<ide> import javax.ws.rs.core.MediaType;
<ide> import javax.ws.rs.core.Response;
<ide>
<add>import org.slf4j.Logger;
<add>import org.slf4j.LoggerFactory;
<add>
<ide> import com.google.inject.Inject;
<ide> import com.sun.jersey.api.client.ClientResponse.Status;
<ide>
<ide> public class UserResource {
<ide>
<ide> /**
<add> * The class logger.
<add> */
<add> private static final Logger LOGGER = LoggerFactory
<add> .getLogger(UserResource.class);
<add> /**
<ide> * Data access object to work with User objects.
<ide> */
<ide> private final UserDao userDao;
<ide> @GET
<ide> @Produces(MediaType.APPLICATION_JSON)
<ide> public List<User> getUsers() {
<add> LOGGER.debug("Returning list of users");
<ide> return this.userDao.getUsers();
<ide> }
<ide>
<ide> user.setOrganization(userRequest.getOrganization());
<ide> user.setPassword(userRequest.getPassword());
<ide> user.setRoles(this.getDefaultRoles());
<add> LOGGER.debug("Saving new user {0}", user.getEmail());
<ide> this.userDao.save(user);
<ide> try {
<add> LOGGER.debug("Sending email to {0}", user.getEmail());
<ide> this.emailSender.sendMessage(user.getEmail());
<ide> } catch (MessagingException e) {
<ide> System.out.println("ERROR SENDING EMAIL: " + e.getMessage());
|
|
JavaScript
|
apache-2.0
|
50168cfb07f2648287f159cec10ddca850e1503c
| 0 |
dorellang/insight,dorellang/insight,dorellang/insight
|
niclabs.insight.quadtree.PointQuadTree = (function () {
/**
* Construct a Point Quadtree
*
* See {@link http://en.wikipedia.org/wiki/Quadtree}
*
* @class niclabs.insight.quadtree.PointQuadTree
* @param {niclabs.insight.quadtree.Bounds} bounds - bounding box for the quadtree
* @param {integer} [capacity=50] - number of points that each node in the quadtree accepts before dividing
* @param {integer} [depth=40] - max depth of the quadtree
*/
var PointQuadTree = function (bounds, capacity, depth) {
capacity = capacity || 50;
depth = depth || 40;
var points = [];
// Children (also quadtrees)
var northWest, northEast, southWest, southEast;
/**
* Subdivide the tree
*
* @memberof niclabs.insight.quadtree.PointQuadTree
* @access private
*/
function subdivide() {
northWest = PointQuadTree(niclabs.insight.quadtree.Bounds(bounds.min, bounds.center), capacity, depth - 1);
northEast = PointQuadTree(niclabs.insight.quadtree.Bounds(
{x: bounds.center.x, y: bounds.min.y},
{x: bounds.max.x, y: bounds.center.y}),
capacity, depth - 1);
southWest = PointQuadTree(niclabs.insight.quadtree.Bounds(
{x: bounds.min.x, y: bounds.center.y},
{x: bounds.center.x, y: bounds.max.y}),
capacity, depth - 1);
southEast = PointQuadTree(niclabs.insight.quadtree.Bounds(bounds.center, bounds.max, capacity, depth - 1));
}
var self = {
/**
* Capacity for the quadtree
*
* @memberof niclabs.insight.quadtree.PointQuadTree
* @member {integer}
*/
get capacity() {
return capacity;
},
/**
* Boundary of the quadtree
* @memberof niclabs.insight.quadtree.PointQuadTree
* @member {niclabs.insight.quadtree.Bounds}
*/
get bounds() {
return bounds;
},
/**
* Insert a new point in the quadtree
*
* @memberof niclabs.insight.quadtree.PointQuadTree
* @param {niclabs.insight.quadtree.Point} point - new point to insert
* @returns {boolean} true if the point could be inserted (point belongs in the bounds of the quadtree)
*/
insert: function (point) {
// Ignore objects that do not belong in this quad tree
if (!bounds.contains(point)) {
return false; // object cannot be added
}
// If there is space in this quad tree, add the object here
if (points.length < capacity || depth <= 0) {
points.push(point);
return true;
}
// Otherwise, subdivide and then add the point to whichever node will accept it
if (northWest === undefined)
subdivide();
if (northWest.insert(point)) return true;
if (northEast.insert(point)) return true;
if (southWest.insert(point)) return true;
if (southEast.insert(point)) return true;
// Otherwise, the point cannot be inserted for some unknown reason (this should never happen)
return false;
},
/**
* Return all the points in the specified bounding box
*
* @memberof niclabs.insight.quadtree.PointQuadTree
* @param {niclabs.insight.quadtree.Bounds} range - spatial range to search
* @returns {niclabs.insight.quadtree.Point[]} list of points in the given range
*/
query: function(range, pointsInRange) {
pointsInRange = typeof pointsInRange === 'undefined' ? [] : pointsInRange;
if (!bounds.intersects(range)) {
return pointsInRange; // Empty list
}
// Check points at this level
for (var i = 0; i < points.length; i++) {
if (range.contains(points[i])) {
pointsInRange.push(points[i]);
}
}
// Terminate here if there are no children
if (northWest === undefined)
return pointsInRange;
// Otherwise add the points from the children
northWest.query(range, pointsInRange);
northEast.query(range, pointsInRange);
southWest.query(range, pointsInRange);
southEast.query(range, pointsInRange);
// Otherwise add the points from the children
return pointsInRange;
}
};
return self;
};
return PointQuadTree;
})();
|
src/niclabs/insight/quadtree/point-quadtree.js
|
niclabs.insight.quadtree.PointQuadTree = (function () {
/**
* Construct a Point Quadtree
*
* See {@link http://en.wikipedia.org/wiki/Quadtree}
*
* @class niclabs.insight.quadtree.PointQuadTree
* @param {niclabs.insight.quadtree.Bounds} bounds - bounding box for the quadtree
* @param {integer} [capacity=100] - number of points that each node in the quadtree accepts before dividing
* @param {integer} [depth=22] - max depth of the quadtree
*/
var PointQuadTree = function (bounds, capacity, depth) {
capacity = capacity || 100;
depth = depth || 22;
var points = [];
// Children (also quadtrees)
var northWest, northEast, southWest, southEast;
/**
* Subdivide the tree
*
* @memberof niclabs.insight.quadtree.PointQuadTree
* @access private
*/
function subdivide() {
northWest = PointQuadTree(niclabs.insight.quadtree.Bounds(bounds.min, bounds.center), capacity, depth - 1);
northEast = PointQuadTree(niclabs.insight.quadtree.Bounds(
{x: bounds.center.x, y: bounds.min.y},
{x: bounds.max.x, y: bounds.center.y}),
capacity, depth - 1);
southWest = PointQuadTree(niclabs.insight.quadtree.Bounds(
{x: bounds.min.x, y: bounds.center.y},
{x: bounds.center.x, y: bounds.max.y}),
capacity, depth - 1);
southEast = PointQuadTree(niclabs.insight.quadtree.Bounds(bounds.center, bounds.max, capacity, depth - 1));
}
var self = {
/**
* Capacity for the quadtree
*
* @memberof niclabs.insight.quadtree.PointQuadTree
* @member {integer}
*/
get capacity() {
return capacity;
},
/**
* Boundary of the quadtree
* @memberof niclabs.insight.quadtree.PointQuadTree
* @member {niclabs.insight.quadtree.Bounds}
*/
get bounds() {
return bounds;
},
/**
* Insert a new point in the quadtree
*
* @memberof niclabs.insight.quadtree.PointQuadTree
* @param {niclabs.insight.quadtree.Point} point - new point to insert
* @returns {boolean} true if the point could be inserted (point belongs in the bounds of the quadtree)
*/
insert: function (point) {
// Ignore objects that do not belong in this quad tree
if (!bounds.contains(point)) {
return false; // object cannot be added
}
// If there is space in this quad tree, add the object here
if (points.length < capacity || depth <= 0) {
points.push(point);
return true;
}
// Otherwise, subdivide and then add the point to whichever node will accept it
if (northWest === undefined)
subdivide();
if (northWest.insert(point)) return true;
if (northEast.insert(point)) return true;
if (southWest.insert(point)) return true;
if (southEast.insert(point)) return true;
// Otherwise, the point cannot be inserted for some unknown reason (this should never happen)
return false;
},
/**
* Return all the points in the specified bounding box
*
* @memberof niclabs.insight.quadtree.PointQuadTree
* @param {niclabs.insight.quadtree.Bounds} range - spatial range to search
* @returns {niclabs.insight.quadtree.Point[]} list of points in the given range
*/
query: function(range, pointsInRange) {
pointsInRange = typeof pointsInRange === 'undefined' ? [] : pointsInRange;
if (!bounds.intersects(range)) {
return pointsInRange; // Empty list
}
// Check points at this level
for (var i = 0; i < points.length; i++) {
if (range.contains(points[i])) {
pointsInRange.push(points[i]);
}
}
// Terminate here if there are no children
if (northWest === undefined)
return pointsInRange;
// Otherwise add the points from the children
northWest.query(range, pointsInRange);
northEast.query(range, pointsInRange);
southWest.query(range, pointsInRange);
southEast.query(range, pointsInRange);
// Otherwise add the points from the children
return pointsInRange;
}
};
return self;
};
return PointQuadTree;
})();
|
Modified the quadtree defaults
|
src/niclabs/insight/quadtree/point-quadtree.js
|
Modified the quadtree defaults
|
<ide><path>rc/niclabs/insight/quadtree/point-quadtree.js
<ide> *
<ide> * @class niclabs.insight.quadtree.PointQuadTree
<ide> * @param {niclabs.insight.quadtree.Bounds} bounds - bounding box for the quadtree
<del> * @param {integer} [capacity=100] - number of points that each node in the quadtree accepts before dividing
<del> * @param {integer} [depth=22] - max depth of the quadtree
<add> * @param {integer} [capacity=50] - number of points that each node in the quadtree accepts before dividing
<add> * @param {integer} [depth=40] - max depth of the quadtree
<ide> */
<ide> var PointQuadTree = function (bounds, capacity, depth) {
<del> capacity = capacity || 100;
<del> depth = depth || 22;
<add> capacity = capacity || 50;
<add> depth = depth || 40;
<ide>
<ide> var points = [];
<ide>
|
|
Java
|
apache-2.0
|
c8d6033e013160bd8097cd40f8be242b8f9d28e7
| 0 |
TheEuropeanLibrary/MAIA
|
package org.theeuropeanlibrary.maia.tel.model.provider;
import com.fasterxml.jackson.databind.jsonschema.JsonSchema;
import java.io.File;
import java.util.List;
import java.util.UUID;
import junit.framework.Assert;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
import org.theeuropeanlibrary.maia.common.Entity.QualifiedValue;
import org.theeuropeanlibrary.maia.common.definitions.Provider;
import org.theeuropeanlibrary.maia.converter.json.EntityObjectMapper;
import org.theeuropeanlibrary.maia.converter.json.ProviderEntityJsonConverter;
import org.theeuropeanlibrary.maia.tel.model.common.Coordinate;
import org.theeuropeanlibrary.maia.tel.model.common.qualifier.Country;
import org.theeuropeanlibrary.maia.tel.model.common.qualifier.Language;
import org.theeuropeanlibrary.maia.tel.model.common.qualifier.NameType;
import org.theeuropeanlibrary.maia.tel.model.provider.definitions.ConsortiumType;
import org.theeuropeanlibrary.maia.tel.model.provider.definitions.ContactRelation;
import org.theeuropeanlibrary.maia.tel.model.provider.definitions.DatasetRelation;
import org.theeuropeanlibrary.maia.tel.model.provider.definitions.EntityRelation;
import org.theeuropeanlibrary.maia.tel.model.provider.definitions.LibraryOrganization;
import org.theeuropeanlibrary.maia.tel.model.provider.definitions.LinkType;
import org.theeuropeanlibrary.maia.tel.model.provider.definitions.MembershipType;
import org.theeuropeanlibrary.maia.tel.model.provider.definitions.PortalStatus;
import org.theeuropeanlibrary.maia.tel.model.provider.definitions.ProviderRelationType;
import org.theeuropeanlibrary.maia.tel.model.provider.definitions.ProviderType;
/**
* This class tests conversion from and to xml representations for the The
* European Library provider.
*
* @author Markus Muhr ([email protected])
* @since 28.10.2014
*/
public class ProviderJsonConverterTest {
@Test
public void encodeDecodeProviderTest() throws Exception {
EntityObjectMapper mapper = new EntityObjectMapper(ProviderRegistry.getInstance(), null, null);
ProviderEntityJsonConverter converter = new ProviderEntityJsonConverter(mapper);
// JsonSchema jsonSchema = mapper.generateJsonSchema(Provider.class);
// String schemaStr = jsonSchema.toString();
////// System.out.println(schemaStr);
// FileUtils.writeStringToFile(new File("/home/markus/NetBeansProjects/MAIA/tel/model/src/main/resources/provider-schema.json"), schemaStr);
String id = "prov_0";
String name = "TEL";
String otherName = "Europeana";
Provider<String> provider = new Provider<>();
provider.setId(id);
provider.addValue(ProviderKeys.PROVIDER, new EntityRelation("TEL", "The European Library"));
provider.addValue(ProviderKeys.PROVIDER, new EntityRelation("EU", "Europeana"), ProviderRelationType.AGGREGATOR);
provider.addValue(ProviderKeys.LINK, "http://test.html", LinkType.LOGO);
provider.addValue(ProviderKeys.LINK, "http://test2.html", LinkType.OPENING);
provider.addValue(ProviderKeys.IDENTIFIER, id);
provider.addValue(ProviderKeys.NAME, name, NameType.ACRONYM, Language.ENG);
provider.addValue(ProviderKeys.NAME, otherName, NameType.ACRONYM, Language.ENG);
provider.addValue(ProviderKeys.COUNTRY, Country.SE);
provider.addValue(ProviderKeys.PHONE, "555-12345678");
provider.addValue(ProviderKeys.EMAIL, "[email protected]");
provider.addValue(ProviderKeys.CONSORTIUM_TYPE, ConsortiumType.PURCHASING);
ContactRelation cR1 = new ContactRelation(UUID.randomUUID().toString(), "Markus Muhr");
cR1.setRole("Manager");
// cR1.setEmail("[email protected]");
provider.addValue(ProviderKeys.CONTACT, cR1);
// Provider<String> prov = ProviderRegistry.getInstance().getFilterFactory().getFilterForName("general").filter(provider);
String enc = converter.encode(provider);
// System.out.println(enc);
// FileUtils.writeStringToFile(new File("/home/markus/NetBeansProjects/MAIA/tel/model/src/main/resources/provider.json"), enc);
Provider<String> providerDecoded = converter.decode(enc);
List<QualifiedValue<String>> nameField = providerDecoded.getQualifiedValues(ProviderKeys.NAME);
QualifiedValue<String> decodedBase = nameField.get(0);
Assert.assertEquals(id, provider.getId());
Assert.assertEquals(name, decodedBase.getValue());
}
private void createProviders() {
Provider<String> provider = new Provider<>();
provider.setId("1");
provider.addValue(ProviderKeys.IDENTIFIER, "P01264");
provider.addValue(ProviderKeys.NAME, "The British Library", NameType.MAIN, Language.ENG);
provider.addValue(ProviderKeys.NAME, "NL United Kingdom", NameType.INTERNAL, Language.ENG);
provider.addValue(ProviderKeys.NAME, "BL", NameType.ACRONYM, Language.ENG);
provider.addValue(ProviderKeys.COUNTRY, Country.GB);
provider.addValue(ProviderKeys.PROVIDER_TYPE, ProviderType.NATIONAL_LIBRARY);
provider.addValue(ProviderKeys.MEMBER, true);
provider.addValue(ProviderKeys.MEMBERSHIP_TYPE, MembershipType.MEMBERS);
provider.addValue(ProviderKeys.LIBRARY_ORGANIZATION, LibraryOrganization.CENL);
provider.addValue(ProviderKeys.PORTAL_STATUS, PortalStatus.LIVE);
provider.addValue(ProviderKeys.COORDINATE, new Coordinate(51.5294, -0.1269));
provider.addValue(ProviderKeys.LINK, "http://www.bl.uk/images/bl_logo_100.gif", LinkType.LOGO);
provider.addValue(ProviderKeys.LINK, "www.bl.uk/", LinkType.WEBSITE);
provider.addValue(ProviderKeys.LINK, "http://www.bl.uk/aboutus/contact/index.html", LinkType.CONTACTS);
provider.addValue(ProviderKeys.LINK, "http://www.bl.uk/aboutus/quickinfo/loc/stp/opening/index.html#reading", LinkType.OPENING);
provider.addValue(ProviderKeys.LINK, "http://en.wikipedia.org/wiki/British_Library", LinkType.WIKIPEDIA_ENGLISH);
provider.addValue(ProviderKeys.LINK, "http://en.wikipedia.org/wiki/British_Library", LinkType.WIKIPEDIA_NATIVE);
provider.addValue(ProviderKeys.IMAGE, "http://upload.wikimedia.org/wikipedia/commons/thumb/2/22/British_library_london.jpg/230px-British_library_london.jpg");
provider.addValue(ProviderKeys.IMAGE, "http://www.theeuropeanlibrary.org/exhibition/buildings/images/pictures/uk_l04.jpg");
provider.addValue(ProviderKeys.IMAGE, "http://search.theeuropeanlibrary.org/images/treasure");
provider.addValue(ProviderKeys.CONTACT, new ContactRelation("11", "Roly Keating", "Director or Deputy Director", "", ""));
provider.addValue(ProviderKeys.CONTACT, new ContactRelation("12", "Janet Zmroczek", "Collections Contact", "", ""));
provider.addValue(ProviderKeys.CONTACT, new ContactRelation("13", "Corine Deliot", "Technical contact", "", ""));
provider.addValue(ProviderKeys.CONTACT, new ContactRelation("14", "Rossitza Atanassova", "Marketing Contact", "", ""));
provider.addValue(ProviderKeys.CONTACT, new ContactRelation("15", "Library Coordinator Group", "Janet Zmroczek", "", ""));
provider.addValue(ProviderKeys.DATASET, new DatasetRelation("21", "British Library integrated catalogue - Online catalogues of printed and electronic resources", "a0037", "Live"));
provider.addValue(ProviderKeys.DATASET, new DatasetRelation("22", "EC1914 BL-Printed Literary Sources", "a0554", "Internal"));
provider.addValue(ProviderKeys.PROJECT, new EntityRelation("31", "EC1914"));
}
}
|
tel/model/src/test/java/org/theeuropeanlibrary/maia/tel/model/provider/ProviderJsonConverterTest.java
|
package org.theeuropeanlibrary.maia.tel.model.provider;
import com.fasterxml.jackson.databind.jsonschema.JsonSchema;
import java.io.File;
import java.util.List;
import java.util.UUID;
import junit.framework.Assert;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
import org.theeuropeanlibrary.maia.common.Entity.QualifiedValue;
import org.theeuropeanlibrary.maia.common.definitions.Provider;
import org.theeuropeanlibrary.maia.converter.json.EntityObjectMapper;
import org.theeuropeanlibrary.maia.converter.json.ProviderEntityJsonConverter;
import org.theeuropeanlibrary.maia.tel.model.common.Coordinate;
import org.theeuropeanlibrary.maia.tel.model.common.qualifier.Country;
import org.theeuropeanlibrary.maia.tel.model.common.qualifier.Language;
import org.theeuropeanlibrary.maia.tel.model.common.qualifier.NameType;
import org.theeuropeanlibrary.maia.tel.model.provider.definitions.ConsortiumType;
import org.theeuropeanlibrary.maia.tel.model.provider.definitions.ContactRelation;
import org.theeuropeanlibrary.maia.tel.model.provider.definitions.DatasetRelation;
import org.theeuropeanlibrary.maia.tel.model.provider.definitions.EntityRelation;
import org.theeuropeanlibrary.maia.tel.model.provider.definitions.LibraryOrganization;
import org.theeuropeanlibrary.maia.tel.model.provider.definitions.LinkType;
import org.theeuropeanlibrary.maia.tel.model.provider.definitions.MembershipType;
import org.theeuropeanlibrary.maia.tel.model.provider.definitions.PortalStatus;
import org.theeuropeanlibrary.maia.tel.model.provider.definitions.ProviderRelationType;
import org.theeuropeanlibrary.maia.tel.model.provider.definitions.ProviderType;
/**
* This class tests conversion from and to xml representations for the The
* European Library provider.
*
* @author Markus Muhr ([email protected])
* @since 28.10.2014
*/
public class ProviderJsonConverterTest {
@Test
public void encodeDecodeProviderTest() throws Exception {
EntityObjectMapper mapper = new EntityObjectMapper(ProviderRegistry.getInstance(), null, null);
ProviderEntityJsonConverter converter = new ProviderEntityJsonConverter(mapper);
JsonSchema jsonSchema = mapper.generateJsonSchema(Provider.class);
String schemaStr = jsonSchema.toString();
//// System.out.println(schemaStr);
FileUtils.writeStringToFile(new File("/home/markus/NetBeansProjects/MAIA/tel/model/src/main/resources/provider-schema.json"), schemaStr);
String id = "prov_0";
String name = "TEL";
String otherName = "Europeana";
Provider<String> provider = new Provider<>();
provider.setId(id);
provider.addValue(ProviderKeys.PROVIDER, new EntityRelation("TEL", "The European Library"));
provider.addValue(ProviderKeys.PROVIDER, new EntityRelation("EU", "Europeana"), ProviderRelationType.AGGREGATOR);
provider.addValue(ProviderKeys.LINK, "http://test.html", LinkType.LOGO);
provider.addValue(ProviderKeys.LINK, "http://test2.html", LinkType.OPENING);
provider.addValue(ProviderKeys.IDENTIFIER, id);
provider.addValue(ProviderKeys.NAME, name, NameType.ACRONYM, Language.ENG);
provider.addValue(ProviderKeys.NAME, otherName, NameType.ACRONYM, Language.ENG);
provider.addValue(ProviderKeys.COUNTRY, Country.SE);
provider.addValue(ProviderKeys.PHONE, "555-12345678");
provider.addValue(ProviderKeys.EMAIL, "[email protected]");
provider.addValue(ProviderKeys.CONSORTIUM_TYPE, ConsortiumType.PURCHASING);
ContactRelation cR1 = new ContactRelation(UUID.randomUUID().toString(), "Markus Muhr");
cR1.setRole("Manager");
// cR1.setEmail("[email protected]");
provider.addValue(ProviderKeys.CONTACT, cR1);
// Provider<String> prov = ProviderRegistry.getInstance().getFilterFactory().getFilterForName("general").filter(provider);
String enc = converter.encode(provider);
// System.out.println(enc);
FileUtils.writeStringToFile(new File("/home/markus/NetBeansProjects/MAIA/tel/model/src/main/resources/provider.json"), enc);
Provider<String> providerDecoded = converter.decode(enc);
List<QualifiedValue<String>> nameField = providerDecoded.getQualifiedValues(ProviderKeys.NAME);
QualifiedValue<String> decodedBase = nameField.get(0);
Assert.assertEquals(id, provider.getId());
Assert.assertEquals(name, decodedBase.getValue());
}
private void createProviders() {
Provider<String> provider = new Provider<>();
provider.setId("1");
provider.addValue(ProviderKeys.IDENTIFIER, "P01264");
provider.addValue(ProviderKeys.NAME, "The British Library", NameType.MAIN, Language.ENG);
provider.addValue(ProviderKeys.NAME, "NL United Kingdom", NameType.INTERNAL, Language.ENG);
provider.addValue(ProviderKeys.NAME, "BL", NameType.ACRONYM, Language.ENG);
provider.addValue(ProviderKeys.COUNTRY, Country.GB);
provider.addValue(ProviderKeys.PROVIDER_TYPE, ProviderType.NATIONAL_LIBRARY);
provider.addValue(ProviderKeys.MEMBER, true);
provider.addValue(ProviderKeys.MEMBERSHIP_TYPE, MembershipType.MEMBERS);
provider.addValue(ProviderKeys.LIBRARY_ORGANIZATION, LibraryOrganization.CENL);
provider.addValue(ProviderKeys.PORTAL_STATUS, PortalStatus.LIVE);
provider.addValue(ProviderKeys.COORDINATE, new Coordinate(51.5294, -0.1269));
provider.addValue(ProviderKeys.LINK, "http://www.bl.uk/images/bl_logo_100.gif", LinkType.LOGO);
provider.addValue(ProviderKeys.LINK, "www.bl.uk/", LinkType.WEBSITE);
provider.addValue(ProviderKeys.LINK, "http://www.bl.uk/aboutus/contact/index.html", LinkType.CONTACTS);
provider.addValue(ProviderKeys.LINK, "http://www.bl.uk/aboutus/quickinfo/loc/stp/opening/index.html#reading", LinkType.OPENING);
provider.addValue(ProviderKeys.LINK, "http://en.wikipedia.org/wiki/British_Library", LinkType.WIKIPEDIA_ENGLISH);
provider.addValue(ProviderKeys.LINK, "http://en.wikipedia.org/wiki/British_Library", LinkType.WIKIPEDIA_NATIVE);
provider.addValue(ProviderKeys.IMAGE, "http://upload.wikimedia.org/wikipedia/commons/thumb/2/22/British_library_london.jpg/230px-British_library_london.jpg");
provider.addValue(ProviderKeys.IMAGE, "http://www.theeuropeanlibrary.org/exhibition/buildings/images/pictures/uk_l04.jpg");
provider.addValue(ProviderKeys.IMAGE, "http://search.theeuropeanlibrary.org/images/treasure");
provider.addValue(ProviderKeys.CONTACT, new ContactRelation("11", "Roly Keating", "Director or Deputy Director", "", ""));
provider.addValue(ProviderKeys.CONTACT, new ContactRelation("12", "Janet Zmroczek", "Collections Contact", "", ""));
provider.addValue(ProviderKeys.CONTACT, new ContactRelation("13", "Corine Deliot", "Technical contact", "", ""));
provider.addValue(ProviderKeys.CONTACT, new ContactRelation("14", "Rossitza Atanassova", "Marketing Contact", "", ""));
provider.addValue(ProviderKeys.CONTACT, new ContactRelation("15", "Library Coordinator Group", "Janet Zmroczek", "", ""));
provider.addValue(ProviderKeys.DATASET, new DatasetRelation("21", "British Library integrated catalogue - Online catalogues of printed and electronic resources", "a0037", "Live"));
provider.addValue(ProviderKeys.DATASET, new DatasetRelation("22", "EC1914 BL-Printed Literary Sources", "a0554", "Internal"));
provider.addValue(ProviderKeys.PROJECT, new EntityRelation("31", "EC1914"));
}
}
|
no writing
|
tel/model/src/test/java/org/theeuropeanlibrary/maia/tel/model/provider/ProviderJsonConverterTest.java
|
no writing
|
<ide><path>el/model/src/test/java/org/theeuropeanlibrary/maia/tel/model/provider/ProviderJsonConverterTest.java
<ide> EntityObjectMapper mapper = new EntityObjectMapper(ProviderRegistry.getInstance(), null, null);
<ide> ProviderEntityJsonConverter converter = new ProviderEntityJsonConverter(mapper);
<ide>
<del> JsonSchema jsonSchema = mapper.generateJsonSchema(Provider.class);
<del> String schemaStr = jsonSchema.toString();
<del>//// System.out.println(schemaStr);
<del> FileUtils.writeStringToFile(new File("/home/markus/NetBeansProjects/MAIA/tel/model/src/main/resources/provider-schema.json"), schemaStr);
<add>// JsonSchema jsonSchema = mapper.generateJsonSchema(Provider.class);
<add>// String schemaStr = jsonSchema.toString();
<add>////// System.out.println(schemaStr);
<add>// FileUtils.writeStringToFile(new File("/home/markus/NetBeansProjects/MAIA/tel/model/src/main/resources/provider-schema.json"), schemaStr);
<ide> String id = "prov_0";
<ide> String name = "TEL";
<ide> String otherName = "Europeana";
<ide>
<ide> String enc = converter.encode(provider);
<ide> // System.out.println(enc);
<del> FileUtils.writeStringToFile(new File("/home/markus/NetBeansProjects/MAIA/tel/model/src/main/resources/provider.json"), enc);
<add>// FileUtils.writeStringToFile(new File("/home/markus/NetBeansProjects/MAIA/tel/model/src/main/resources/provider.json"), enc);
<ide> Provider<String> providerDecoded = converter.decode(enc);
<ide>
<ide> List<QualifiedValue<String>> nameField = providerDecoded.getQualifiedValues(ProviderKeys.NAME);
|
|
Java
|
mit
|
e0a1b5ba0eefd9a151f2b3e20f3cd2e4a00f74fa
| 0 |
kmdouglass/Micro-Manager,kmdouglass/Micro-Manager
|
/**
*
* Karl Bellve
* Biomedical Imaging Group
* University of Massachusetts Medical School
* [email protected]
* http://big.umassmed.edu/
*
*/
package edu.umassmed.big;
import java.util.Vector;
public class SBSPlate {
public enum SBSPlateTypes { // currently only 96 well plates has been tested
SBS_24_WELL (6,4,18000,"24 Microplate"),
SBS_96_WELL (12,8,9000,"96 Microplate"),
SBS_384_WELL (24,16,4500,"384 Microplate"),
SBS_1536_WELL (48,32,2250,"1536 Microplate");
SBSPlateTypes( int X, int Y, int wellSpacing, String Name) {
this.X = X;
this.Y = Y;
this.wellSpacing = wellSpacing;
this.Name = Name;
}
public int getX() { return X; }
public int getY() { return Y; }
public int getXY() { return X * Y; }
public int getWellSpacing() { return wellSpacing; }
public String getWellPlateName() { return Name; }
private int X; // 1 indexed
private int Y; // 1 indexed
private int wellSpacing;
private String Name;
}
class Well{
private Boolean bSkip = false;
double[] position;
private Vector<double[]> wellPositionList = new Vector<double[]>();
Well(Boolean skip) {
this.bSkip = skip;
}
Well(double X, double Y, double Z) {
this.bSkip = false;
position = new double[3];
position[0] = X;
position[1] = Y;
position[2] = Z;
this.wellPositionList.add(position);
}
void addPosition(double X, double Y,double Z) {
this.bSkip = false;
position = new double[3];
position[0] = X;
position[1] = Y;
position[2] = Z;
this.wellPositionList.add(position);
}
Boolean skipWell()
{
return bSkip;
}
void skipWell(Boolean skip)
{
bSkip = skip;
}
}
private SBSPlateTypes plateSize = SBSPlateTypes.SBS_96_WELL;
private int[] firstWell = {0,0}; // 0 indexed
private int[] lastWell = {11,7}; // 0 indexed
private int[] currentWell = {0,0};
private Well[][] wellArray;
private double[] A1Position = {0,0}; // if stage can't be zeroed, then use this an an offset, in microns.
private Vector<double[]> globalPositionList = new Vector<double[]>();
public SBSPlate () {
initialize (SBSPlateTypes.SBS_96_WELL, 0, 0);
}
public SBSPlate (SBSPlateTypes platesize) {
initialize (platesize,0,0);
}
public SBSPlate (SBSPlateTypes platesize, double x, double y) {
initialize (platesize,x,y);
}
public SBSPlate (int Size) {
SBSPlateTypes platesize;
switch (Size) {
case 24: {
platesize = SBSPlate.SBSPlateTypes.SBS_24_WELL;;
break;
}
default:
case 96: {
platesize = SBSPlate.SBSPlateTypes.SBS_96_WELL;
break;
}
case 384: {
platesize = SBSPlate.SBSPlateTypes.SBS_384_WELL;
break;
}
case 1536: {
platesize = SBSPlate.SBSPlateTypes.SBS_1536_WELL;
break;
}
}
initialize (platesize, 0, 0);
}
public SBSPlate (int Size, double x, double y) {
SBSPlateTypes platesize;
switch (Size) {
case 24: {
platesize = SBSPlate.SBSPlateTypes.SBS_24_WELL;;
break;
}
default:
case 96: {
platesize = SBSPlate.SBSPlateTypes.SBS_96_WELL;
break;
}
case 384: {
platesize = SBSPlate.SBSPlateTypes.SBS_384_WELL;
break;
}
case 1536: {
platesize = SBSPlate.SBSPlateTypes.SBS_1536_WELL;
break;
}
}
initialize (platesize, x, y);
}
public void initialize (SBSPlateTypes platesize, double x, double y) {
setPlateType(platesize);
firstWell[0] = 0;
firstWell[1] = 0;
lastWell[0] = this.plateSize.getX() - 1;
lastWell[1] = this.plateSize.getY() - 1;
A1Position[0] = x;
A1Position[1] = y;
wellArray = new Well[this.plateSize.getX()][this.plateSize.getY()];
}
public SBSPlateTypes getPlateType() {
return this.plateSize;
}
public String getWellPlateName() {
return this.plateSize.getWellPlateName();
}
public void setPlateType(SBSPlateTypes platesize) {
this.plateSize = platesize;
}
public int getWellSpacing() {
return this.plateSize.getWellSpacing();
}
public int[] getFirstWell() {
// switch to 1 index
int[] firstWell = { 0, 0 };
firstWell[0] = this.firstWell[0] + 1;
firstWell[1] = this.firstWell[1] + 1;
return firstWell;
}
public int[] getLastWell() {
// switch to 1 index
int[] lastWell = { 1, 1 };
lastWell[0] = this.lastWell[0] + 1;
lastWell[1] = this.lastWell[1] + 1;
return lastWell;
}
public void setFirstWell(int x, int y) {
if (x > this.plateSize.getX()) x = this.plateSize.getX();
if (y > this.plateSize.getY()) y = this.plateSize.getY();
// switch to 0 indexed
x--;y--;
if (x < 0) x = 0;
if (y < 0) y = 0;
if (x >= lastWell[0]) x = lastWell[0];
if (y >= lastWell[1]) y = lastWell[1];
firstWell[0] = x;
firstWell[1] = y;
currentWell[0] = x;
// if odd, we need to move the first well to the bottom
if (currentWell[0] % 2 == 0 || currentWell[0] == 0) {
currentWell[1] = y;
}
else {
currentWell[1] = lastWell[1]; // start at the bottom of the column, instead of the top
}
}
/**
* Sets the Absolute position, in microns, of well A1. This needs to be set if the center of well A1 is not at 0,0.
*
* @param x micron coordinate the longest dimension of the wellplate at well A1
* @param y micron coordinate the shortest dimension of the wellplate at well A1
*/
public void setPositionA1(double x, double y) {
A1Position[0] = x;
A1Position[1] = y;
}
public void setLastWell(int x, int y) {
if (x > this.plateSize.getX()) x = this.plateSize.getX();
if (y > this.plateSize.getY()) y = this.plateSize.getY();
//switch to 0 index
x--;y--;
if (x <= firstWell[0]) x = firstWell[0];
if (y <= firstWell[1]) y = firstWell[1];
lastWell[0] = x;
lastWell[1] = y;
currentWell[0] = firstWell[0];
currentWell[1] = firstWell[1];
}
/**
* Adds global offset, values need to be relative to center of well
*
* @param X coordinate of the longest dimension of the well plate in microns
* @param Y coordinate of the shortest dimension of the well plate in microns
* @param Z focus depth in microns
*/
public void addPosition (double X, double Y, double Z) {
double[] position ={0,0,0};
position[0] = X;
position[1] = Y;
position[2] = Z;
globalPositionList.add(position);
}
/**
* Adds local offset of the current position, values need to be relative to center of well
*
* @param X coordinate of the longest dimension of the well plate in microns
* @param Y coordinate of the shortest dimension of the well plate in microns
* @param Z focus depth in microns
* @param well number within the plate, or within region of the plate if first and last wells are set
*/
public void addPosition (double X, double Y, double Z, int well) {
// switch to 0 indexed
int[] coordinates = {0,0};
double[] position = {0,0,0};
coordinates = getPlateCoordinates(well); // returns 1 indexed
// convert to 0 indexed
coordinates[0]--;
coordinates[1]--;
position[0] = X;
position[1] = Y;
position[2] = Z;
if (wellArray[coordinates[0]][coordinates[1]] == null) {
wellArray[coordinates[0]][coordinates[1]] = new Well(X,Y,Z);
}
else {
wellArray[coordinates[0]][coordinates[1]].wellPositionList.add(position);
}
}
/**
* Clears all global positions
*
*/
public void clearPositions(){
globalPositionList.clear();
}
/**
* Clears all position for a given well if they exist
*
* @param well
*/
public void clearPositions(int well){
int[] coordinates = {0,0};
coordinates = getPlateCoordinates(well); // returns 1 indexed
// convert to 0 indexed
coordinates[0]--;
coordinates[1]--;
if (wellArray[coordinates[0]][coordinates[1]] != null) {
wellArray[coordinates[0]][coordinates[1]].wellPositionList.clear();
}
}
/**
*
* @param skip set to TRUE if you want ignore the current well.
*/
public void skipWell(Boolean skip) {
if (wellArray[currentWell[0]][currentWell[1]] == null){
wellArray[currentWell[0]][currentWell[1]] = new Well(skip);
}
else {
wellArray[currentWell[0]][currentWell[1]].skipWell(skip);
}
}
/**
*
* @param well
* @return returns TRUE if a well should be skipped, or false if it shouldn't be skipped
*/
public Boolean skipWell(int well) {
int[] coordinates = {0,0};
coordinates = getPlateCoordinates(well); // returns 1 indexed
// convert to 0 indexed
coordinates[0]--;
coordinates[1]--;
if (wellArray[coordinates[0]][coordinates[1]] == null){
// if Well class doesn't exist, then don't skip well
return false;
}
else {
return (wellArray[coordinates[0]][coordinates[1]].skipWell());
}
}
/**
* Returns the SBS label associated with a well
* @param well number within the plate, or within region of the plate if first and last wells are set
* @return returns String SBS name
*/
public String getWellLabel(int well) {
int[] coordinates = {0,0};
int X,Y;
String xLabel;
String yLabel;
// convert position into X and Y coordinates
coordinates = getPlateCoordinates(well);
X = coordinates[0];
Y = coordinates[1];
if (X < 0 || Y < 0) {
return ("Out of Bounds!");
}
if (X < 10) xLabel = "0" + Integer.toString(X);
else xLabel = Integer.toString(X);
if (Y <= 26) yLabel = "" + (char)(Y+64);
else yLabel = "A" + (char)(Y+38);
return (yLabel + xLabel);
}
public int getNumberOfWells() {
int wells;
wells = (1 + this.lastWell[1] - this.firstWell[1]) * (1 + this.lastWell[0] - this.firstWell[0]);
return wells;
}
/**
* checks the number of positions of the current well. It will check the position list for the current well and if that exits, return that.
* <p>
* Otherwise it will return the number of positions of the global list.
*
* @return number of positions within then current well
*/
public int getNumberOfWellPositions() {
if (wellArray[currentWell[0]][currentWell[1]] == null){
// if Well class doesn't exist, then check global list
return ((globalPositionList.size() > 0) ? globalPositionList.size() : 1);
}
else {
if (wellArray[currentWell[0]][currentWell[1]].wellPositionList.size() > 0) return (wellArray[currentWell[0]][currentWell[1]].wellPositionList.size());
else return ((globalPositionList.size() > 0) ? globalPositionList.size() : 1);
}
}
/**
* checks the number of positions of a given well. It will check the position list for the current well and if that exits, return that.
* <p>
* Otherwise it will return the number of positions of the global list.
*
* @param well number within the plate, or within region of the plate if first and last wells are set
* @return number of positions within a well
*/
public int getNumberOfWellPositions(int well) {
int[] coordinates = {0,0};
coordinates = getPlateCoordinates(well); // returns 1 indexed
// convert to 0 indexed
coordinates[0]--;
coordinates[1]--;
if (wellArray[coordinates[0]][coordinates[1]] != null){
if (wellArray[coordinates[0]][coordinates[1]].wellPositionList.size() > 0)
return (wellArray[coordinates[0]][coordinates[1]].wellPositionList.size());
}
return ((globalPositionList.size() > 0) ? globalPositionList.size() : 1);
}
/**
* Returns next well position within the current well. Position is absolute position including plate position.
*
* @param index
* @return X,Y,Z in microns
*/
public double[] getNextWellPosition(int index) {
double[] position = {0,0,0}; // returns microns position
position[0] = ((currentWell[0]) * this.plateSize.getWellSpacing()) + A1Position[0];
position[1] = ((currentWell[1]) * this.plateSize.getWellSpacing()) + A1Position[1];
position[2] = 0;
if (index < 0) {
System.err.println("getNextWellPosition: Well index out of bounds");
return position;
}
if (wellArray[currentWell[0]][currentWell[1]] != null) {
if (index < wellArray[currentWell[0]][currentWell[1]].wellPositionList.size()) {
position[0] += wellArray[currentWell[0]][currentWell[1]].wellPositionList.get(index)[0];
position[1] += wellArray[currentWell[0]][currentWell[1]].wellPositionList.get(index)[1];
position[2] += wellArray[currentWell[0]][currentWell[1]].wellPositionList.get(index)[2];
} else {
if (index < globalPositionList.size()) {
position[0] += globalPositionList.get(index)[0];
position[1] += globalPositionList.get(index)[1];
position[2] += globalPositionList.get(index)[2];
} else System.err.println("getNextWellPosition: Global Well index out of bounds " + globalPositionList.size());
}
}
else {
if (index < globalPositionList.size()) {
position[0] += globalPositionList.get(index)[0];
position[1] += globalPositionList.get(index)[1];
position[2] += globalPositionList.get(index)[2];
} else System.err.println("getNextWellPosition: Global Well index out of bounds " + globalPositionList.size());
}
return (position);
}
public double[] getFirstPlatePosition(){
double[] position = {0,0,0}; // returns microns position
position = getPlatePosition(firstWell[0],firstWell[1]);
return position;
}
/**
* Returns the X, and Y coordinates of the center of the current well in microns.
*
* @param X coordinate position of the current well in microns
* @param Y coordinate position of the current well in microns
* @return returns an two double array containing X, Y coordinates of a well in microns
*/
public double[] getPlatePosition (int X, int Y) {
double[] position = {0,0,0}; // X, Y, Z
// switch to 0 indexed
X--;Y--;
position[0] = (X * this.plateSize.getWellSpacing()) + A1Position[0];
position[1] = (Y * this.plateSize.getWellSpacing()) + A1Position[1];
position[2] = 0;
if (wellArray[X][Y] == null){
// if Well class doesn't exist, then check global list
if (globalPositionList.size() >= 1) {
position[0] += globalPositionList.get(0)[0];
position[1] += globalPositionList.get(0)[1];
position[2] += globalPositionList.get(0)[2];
}
}
else {
if (wellArray[firstWell[0]][firstWell[1]].wellPositionList.size() >= 1) {
position[0] += wellArray[X][Y].wellPositionList.get(0)[0];
position[1] += wellArray[X][Y].wellPositionList.get(0)[1];
position[2] += wellArray[X][Y].wellPositionList.get(0)[2];
}
}
return position;
}
/**
* This function is deprecated. Please use getNextPlatePosition()
* @return
*/
public double[] getNextPosition() {
return (getNextPlatePosition());
}
/**
* Returns the position, in microns, of the next well, based on position of the last well.
*
* @return either the first position for that well, and if it that does not exist, returns the first global position of that well, which
* is usually the center of that well, if not defined.
*
*/
public double[] getNextPlatePosition() {
double[] position = {0,0,0}; // returns microns position
if (firstWell[0] % 2 == 0 || firstWell[0] == 0) {
if (currentWell[0] % 2 == 0 || currentWell[0] == 0) {
currentWell[1]++;
if (currentWell[1] > lastWell[1]) {
currentWell[1] = lastWell[1];
currentWell[0]++;
}
}
else {
currentWell[1]--;
if (currentWell[1] < firstWell[1]) {
//reset Y, increment X
currentWell[1] = firstWell[1];
currentWell[0]++;
}
}
}
else {
if (currentWell[0] % 2 == 0 || currentWell[0] == 0) {
currentWell[1]--;
if (currentWell[1] < firstWell[1]) {
//reset Y, increment X
currentWell[1] = firstWell[1];
currentWell[0]++;
}
}
else {
currentWell[1]++;
if (currentWell[1] > lastWell[1]) {
currentWell[1] = lastWell[1];
currentWell[0]++;
}
}
}
if (currentWell[0] > lastWell[0]) {
currentWell[0] = firstWell[0];
currentWell[1] = firstWell[1];
}
position[0] = ((currentWell[0]) * this.plateSize.getWellSpacing()) + A1Position[0];
position[1] = ((currentWell[1]) * this.plateSize.getWellSpacing()) + A1Position[1];
position[2] = 0;
if (wellArray[currentWell[0]][currentWell[1]] == null){
// if Well class doesn't exist, then check global list
if (globalPositionList.size() >= 1) {
position[0] += globalPositionList.get(0)[0];
position[1] += globalPositionList.get(0)[1];
position[2] += globalPositionList.get(0)[2];
}
}
else {
if (wellArray[currentWell[0]][currentWell[1]].wellPositionList.size() >= 1) {
position[0] += wellArray[currentWell[0]][currentWell[1]].wellPositionList.get(0)[0];
position[1] += wellArray[currentWell[0]][currentWell[1]].wellPositionList.get(0)[1];
position[2] += wellArray[currentWell[0]][currentWell[1]].wellPositionList.get(0)[2];
}
}
return position;
}
/**
* Returns the X and Y coordinates of a well
*
* @param well number within the plate, or within region of the plate if first and last wells are set
* @return 1 indexed coordinates based on well plate or sub region of well plate
*/
public int[] getPlateCoordinates(int well) {
// out of bounds set to 0,0
int[] coordinates = {-1,-1};
int plateSize = this.plateSize.getXY();
if (well >= plateSize) {
return coordinates;
}
else if (well < 0) return coordinates;
else {
// Well is 0 indexed, while lastWell is 0 indexed
coordinates[0] = 1 + firstWell[0] + (well/ (lastWell[1] - firstWell[1] + 1));
// Well is 0 indexed, while lastWell is 0 indexed
coordinates[1] = 1 + firstWell[1] + (well% (lastWell[1] - firstWell[1] + 1));
}
// reverse well position because we reverse direction on odd rows in reference to starting column, which may not be the first column
int even = coordinates[0]- firstWell[0]; // position is 1 indexed, firstWell is 0 indexed.
if (even % 2 == 0) {
coordinates[1] = (lastWell[1] + 1) - (coordinates[1] - firstWell[1] - 1);
}
return coordinates;
}
}
|
plugins/Big/src/edu/umassmed/big/SBSPlate.java
|
package edu.umassmed.big;
public class SBSPlate {
public enum SBSPlateTypes { // currently only 96 well plates has been tested
SBS_24_WELL (6,4,18000,"24 Microplate"),
SBS_96_WELL (12,8,9000,"96 Microplate"),
SBS_384_WELL (24,16,4500,"384 Microplate"),
SBS_1536_WELL (48,32,2250,"1536 Microplate");
SBSPlateTypes( int X, int Y, int wellSpacing, String Name) {
this.X = X;
this.Y = Y;
this.wellSpacing = wellSpacing;
this.Name = Name;
}
private int X; // 1 indexed
private int Y; // 1 indexed
private int wellSpacing;
private String Name;
public int getX() { return X; }
public int getY() { return Y; }
public int getWellSpacing() { return wellSpacing; }
public String getWellPlateName() { return Name; }
}
private SBSPlateTypes plateSize = SBSPlateTypes.SBS_96_WELL;
private int[] firstWell = {0,0}; // 0 indexed
private int[] lastWell = {11,7}; // 0 indexed
private int[] currentWell = {0,0};
private double[] A1Position = {0,0}; // if stage can't be zeroed, then use this an an offset, in microns.
public SBSPlate () {
initialize (SBSPlateTypes.SBS_96_WELL, 0, 0);
}
public SBSPlate (SBSPlateTypes platesize) {
initialize (platesize,0,0);
}
public SBSPlate (SBSPlateTypes platesize, double x, double y) {
initialize (platesize,x,y);
}
public SBSPlate (int Size) {
SBSPlateTypes platesize;
switch (Size) {
case 24: {
platesize = SBSPlate.SBSPlateTypes.SBS_24_WELL;;
break;
}
default:
case 96: {
platesize = SBSPlate.SBSPlateTypes.SBS_96_WELL;
break;
}
case 384: {
platesize = SBSPlate.SBSPlateTypes.SBS_384_WELL;
break;
}
case 1536: {
platesize = SBSPlate.SBSPlateTypes.SBS_1536_WELL;
break;
}
}
initialize (platesize, 0, 0);
}
public SBSPlate (int Size, double x, double y) {
SBSPlateTypes platesize;
switch (Size) {
case 24: {
platesize = SBSPlate.SBSPlateTypes.SBS_24_WELL;;
break;
}
default:
case 96: {
platesize = SBSPlate.SBSPlateTypes.SBS_96_WELL;
break;
}
case 384: {
platesize = SBSPlate.SBSPlateTypes.SBS_384_WELL;
break;
}
case 1536: {
platesize = SBSPlate.SBSPlateTypes.SBS_1536_WELL;
break;
}
}
initialize (platesize, x, y);
}
public void initialize (SBSPlateTypes platesize, double x, double y) {
setPlateType(platesize);
firstWell[0] = 0;
firstWell[1] = 0;
lastWell[0] = this.plateSize.getX() - 1;
lastWell[1] = this.plateSize.getY() - 1;
A1Position[0] = x;
A1Position[1] = y;
}
public SBSPlateTypes getPlateType() {
return this.plateSize;
}
public String getWellPlateName() {
return this.plateSize.getWellPlateName();
}
public void setPlateType(SBSPlateTypes platesize) {
this.plateSize = platesize;
}
public int getWellSpacing() {
return this.plateSize.getWellSpacing();
}
public int[] getFirstWell() {
// switch to 1 index
int[]firstWell = { 0, 0 };
firstWell[0] = this.firstWell[0] + 1;
firstWell[1] = this.firstWell[1] + 1;
return firstWell;
}
public int[] getLastWell() {
// switch to 1 index
int[]lastWell = { 1, 1 };
lastWell[0] = this.lastWell[0] + 1;
lastWell[1] = this.lastWell[1] + 1;
return lastWell;
}
public void setFirstWell(int x, int y) {
if (x > this.plateSize.getX()) x = this.plateSize.getX();
if (y > this.plateSize.getY()) y = this.plateSize.getY();
// switch to 0 indexed
x--;y--;
if (x < 0) x = 0;
if (y < 0) y = 0;
if (x >= lastWell[0]) x = lastWell[0];
if (y >= lastWell[1]) y = lastWell[1];
firstWell[0] = x;
firstWell[1] = y;
currentWell[0] = x;
// if odd, we need to move the first well to the bottom
if (currentWell[0] % 2 == 0 || currentWell[0] == 0) {
currentWell[1] = y;
}
else {
currentWell[1] = lastWell[1]; // start at the bottom of the column, instead of the top
}
}
public void setFirstWell(int[] firstwell) {
setFirstWell(firstwell[0],firstwell[1]);
}
public void setPositionA1(int x, int y) {
A1Position[0] = x;
A1Position[1] = y;
}
public void setLastWell(int x, int y) {
if (x > this.plateSize.getX()) x = this.plateSize.getX();
if (y > this.plateSize.getY()) y = this.plateSize.getY();
//switch to 0 index
x--;y--;
if (x <= firstWell[0]) x = firstWell[0];
if (y <= firstWell[1]) y = firstWell[1];
lastWell[0] = x;
lastWell[1] = y;
currentWell[0] = firstWell[0];
currentWell[1] = firstWell[1];
}
public void setLastWell(int[] lastcell) {
setLastWell(lastcell[0],lastcell[1]);
}
// Not implemented yet
public int[] getWellPosition (int well) {
int[] position = {0,0};
//position = getPosition (well[0],well[1]);
return position;
}
public double[] getWellPosition (int X, int Y) {
double[] position = {0,0};
// switch to 0 indexed
X--;Y--;
position[0] = (X * this.plateSize.getWellSpacing()) + A1Position[0];
position[1] = (Y * this.plateSize.getWellSpacing()) + A1Position[1];
return position;
}
public String getWellLabel(int well) {
String xLabel;
String yLabel;
// convert position into X and Y coordinates
SBSPlateTypes plateType = getPlateType();
int plateSize = plateType.getX() * plateType.getY();
if (well > plateSize) {
return ("Out of Bounds!");
}
else if (well < 1) return ("Out of Bounds!");
else {
int X = firstWell[0] + (((well - 1) / plateType.getY()) + 1);
int Y = firstWell[1] + ((well % plateType.getY()));
if (Y == 0) {
Y = plateType.getY();
}
// reverse labels because we reverse direction on odd rows in reference to starting column, which may not be the first column
int even = X - firstWell[0];
if (even % 2 == 0) {
Y = plateType.getY() - (Y - 1);
}
if (X < 10) xLabel = "0" + Integer.toString(X);
else xLabel = Integer.toString(X);
if (Y <= 26) yLabel = "" + (char)(Y+64);
else {
yLabel = "A" + (char)(Y+38);
}
}
return (yLabel + xLabel);
}
public int getNumberOfWells() {
int Positions;
Positions = (1 + this.lastWell[1] - this.firstWell[1]) * (1 + this.lastWell[0] - this.firstWell[0]);
return Positions;
}
public double[] getNextPosition() {
double[] position = {0,0}; // returns microns position
if (firstWell[0] % 2 == 0 || firstWell[0] == 0) {
if (currentWell[0] % 2 == 0 || currentWell[0] == 0) {
currentWell[1]++;
if (currentWell[1] > lastWell[1]) {
currentWell[1] = lastWell[1];
currentWell[0]++;
}
}
else {
currentWell[1]--;
if (currentWell[1] < firstWell[1]) {
//reset Y, increment X
currentWell[1] = firstWell[1];
currentWell[0]++;
}
}
}
else {
if (currentWell[0] % 2 == 0 || currentWell[0] == 0) {
currentWell[1]--;
if (currentWell[1] < firstWell[1]) {
//reset Y, increment X
currentWell[1] = firstWell[1];
currentWell[0]++;
}
}
else {
currentWell[1]++;
if (currentWell[1] > lastWell[1]) {
currentWell[1] = lastWell[1];
currentWell[0]++;
}
}
}
if (currentWell[0] > lastWell[0]) {
currentWell[0] = firstWell[0];
currentWell[1] = firstWell[1];
}
position[0] = ((currentWell[0]) * this.plateSize.getWellSpacing()) + A1Position[0];
position[1] = ((currentWell[1]) * this.plateSize.getWellSpacing()) + A1Position[1];
return position;
}
}
|
added ability to save locations per well, as well as per plate. The later overrides the former. Wells can be skipped. Beta. Use at own risk
git-svn-id: 03a8048b5ee8463be5048a3801110fb50f378627@7262 d0ab736e-dc22-4aeb-8dc9-08def0aa14fd
|
plugins/Big/src/edu/umassmed/big/SBSPlate.java
|
added ability to save locations per well, as well as per plate. The later overrides the former. Wells can be skipped. Beta. Use at own risk
|
<ide><path>lugins/Big/src/edu/umassmed/big/SBSPlate.java
<add>/**
<add> *
<add> * Karl Bellve
<add> * Biomedical Imaging Group
<add> * University of Massachusetts Medical School
<add> * [email protected]
<add> * http://big.umassmed.edu/
<add> *
<add> */
<add>
<ide> package edu.umassmed.big;
<del>
<add>import java.util.Vector;
<ide>
<ide>
<ide> public class SBSPlate {
<ide> this.wellSpacing = wellSpacing;
<ide> this.Name = Name;
<ide> }
<add> public int getX() { return X; }
<add> public int getY() { return Y; }
<add> public int getXY() { return X * Y; }
<add> public int getWellSpacing() { return wellSpacing; }
<add> public String getWellPlateName() { return Name; }
<ide> private int X; // 1 indexed
<ide> private int Y; // 1 indexed
<ide> private int wellSpacing;
<ide> private String Name;
<del> public int getX() { return X; }
<del> public int getY() { return Y; }
<del> public int getWellSpacing() { return wellSpacing; }
<del> public String getWellPlateName() { return Name; }
<add> }
<add>
<add> class Well{
<add> private Boolean bSkip = false;
<add> double[] position;
<add> private Vector<double[]> wellPositionList = new Vector<double[]>();
<add> Well(Boolean skip) {
<add> this.bSkip = skip;
<add> }
<add> Well(double X, double Y, double Z) {
<add> this.bSkip = false;
<add> position = new double[3];
<add> position[0] = X;
<add> position[1] = Y;
<add> position[2] = Z;
<add> this.wellPositionList.add(position);
<add> }
<add> void addPosition(double X, double Y,double Z) {
<add> this.bSkip = false;
<add> position = new double[3];
<add> position[0] = X;
<add> position[1] = Y;
<add> position[2] = Z;
<add> this.wellPositionList.add(position);
<add>
<add> }
<add> Boolean skipWell()
<add> {
<add> return bSkip;
<add> }
<add> void skipWell(Boolean skip)
<add> {
<add> bSkip = skip;
<add> }
<ide> }
<ide>
<ide> private SBSPlateTypes plateSize = SBSPlateTypes.SBS_96_WELL;
<ide> private int[] firstWell = {0,0}; // 0 indexed
<ide> private int[] lastWell = {11,7}; // 0 indexed
<ide> private int[] currentWell = {0,0};
<add> private Well[][] wellArray;
<ide> private double[] A1Position = {0,0}; // if stage can't be zeroed, then use this an an offset, in microns.
<del>
<add> private Vector<double[]> globalPositionList = new Vector<double[]>();
<ide>
<ide> public SBSPlate () {
<ide> initialize (SBSPlateTypes.SBS_96_WELL, 0, 0);
<ide> lastWell[1] = this.plateSize.getY() - 1;
<ide> A1Position[0] = x;
<ide> A1Position[1] = y;
<add> wellArray = new Well[this.plateSize.getX()][this.plateSize.getY()];
<ide> }
<ide> public SBSPlateTypes getPlateType() {
<ide> return this.plateSize;
<ide> }
<ide> public int[] getFirstWell() {
<ide> // switch to 1 index
<del> int[]firstWell = { 0, 0 };
<add> int[] firstWell = { 0, 0 };
<ide> firstWell[0] = this.firstWell[0] + 1;
<ide> firstWell[1] = this.firstWell[1] + 1;
<ide> return firstWell;
<ide> }
<ide> public int[] getLastWell() {
<ide> // switch to 1 index
<del> int[]lastWell = { 1, 1 };
<add> int[] lastWell = { 1, 1 };
<ide> lastWell[0] = this.lastWell[0] + 1;
<ide> lastWell[1] = this.lastWell[1] + 1;
<ide> return lastWell;
<ide> currentWell[1] = lastWell[1]; // start at the bottom of the column, instead of the top
<ide> }
<ide> }
<del> public void setFirstWell(int[] firstwell) {
<del> setFirstWell(firstwell[0],firstwell[1]);
<del> }
<del>
<del> public void setPositionA1(int x, int y) {
<add> /**
<add> * Sets the Absolute position, in microns, of well A1. This needs to be set if the center of well A1 is not at 0,0.
<add> *
<add> * @param x micron coordinate the longest dimension of the wellplate at well A1
<add> * @param y micron coordinate the shortest dimension of the wellplate at well A1
<add> */
<add> public void setPositionA1(double x, double y) {
<ide> A1Position[0] = x;
<ide> A1Position[1] = y;
<ide> }
<add>
<ide> public void setLastWell(int x, int y) {
<ide> if (x > this.plateSize.getX()) x = this.plateSize.getX();
<ide> if (y > this.plateSize.getY()) y = this.plateSize.getY();
<ide> currentWell[0] = firstWell[0];
<ide> currentWell[1] = firstWell[1];
<ide> }
<del> public void setLastWell(int[] lastcell) {
<del> setLastWell(lastcell[0],lastcell[1]);
<del> }
<del>
<del> // Not implemented yet
<del> public int[] getWellPosition (int well) {
<del> int[] position = {0,0};
<del>
<del> //position = getPosition (well[0],well[1]);
<add>
<add> /**
<add> * Adds global offset, values need to be relative to center of well
<add> *
<add> * @param X coordinate of the longest dimension of the well plate in microns
<add> * @param Y coordinate of the shortest dimension of the well plate in microns
<add> * @param Z focus depth in microns
<add> */
<add> public void addPosition (double X, double Y, double Z) {
<add> double[] position ={0,0,0};
<add>
<add> position[0] = X;
<add> position[1] = Y;
<add> position[2] = Z;
<add>
<add> globalPositionList.add(position);
<add> }
<add>
<add> /**
<add> * Adds local offset of the current position, values need to be relative to center of well
<add> *
<add> * @param X coordinate of the longest dimension of the well plate in microns
<add> * @param Y coordinate of the shortest dimension of the well plate in microns
<add> * @param Z focus depth in microns
<add> * @param well number within the plate, or within region of the plate if first and last wells are set
<add> */
<add> public void addPosition (double X, double Y, double Z, int well) {
<add> // switch to 0 indexed
<add> int[] coordinates = {0,0};
<add> double[] position = {0,0,0};
<add>
<add> coordinates = getPlateCoordinates(well); // returns 1 indexed
<add> // convert to 0 indexed
<add> coordinates[0]--;
<add> coordinates[1]--;
<add>
<add> position[0] = X;
<add> position[1] = Y;
<add> position[2] = Z;
<add>
<add> if (wellArray[coordinates[0]][coordinates[1]] == null) {
<add> wellArray[coordinates[0]][coordinates[1]] = new Well(X,Y,Z);
<add> }
<add> else {
<add> wellArray[coordinates[0]][coordinates[1]].wellPositionList.add(position);
<add> }
<add> }
<add> /**
<add> * Clears all global positions
<add> *
<add> */
<add> public void clearPositions(){
<add> globalPositionList.clear();
<add> }
<add> /**
<add> * Clears all position for a given well if they exist
<add> *
<add> * @param well
<add> */
<add> public void clearPositions(int well){
<add> int[] coordinates = {0,0};
<add>
<add> coordinates = getPlateCoordinates(well); // returns 1 indexed
<add> // convert to 0 indexed
<add> coordinates[0]--;
<add> coordinates[1]--;
<add>
<add> if (wellArray[coordinates[0]][coordinates[1]] != null) {
<add> wellArray[coordinates[0]][coordinates[1]].wellPositionList.clear();
<add> }
<add> }
<add> /**
<add> *
<add> * @param skip set to TRUE if you want ignore the current well.
<add> */
<add> public void skipWell(Boolean skip) {
<add> if (wellArray[currentWell[0]][currentWell[1]] == null){
<add> wellArray[currentWell[0]][currentWell[1]] = new Well(skip);
<add> }
<add> else {
<add> wellArray[currentWell[0]][currentWell[1]].skipWell(skip);
<add> }
<add> }
<add> /**
<add> *
<add> * @param well
<add> * @return returns TRUE if a well should be skipped, or false if it shouldn't be skipped
<add> */
<add> public Boolean skipWell(int well) {
<add> int[] coordinates = {0,0};
<add>
<add> coordinates = getPlateCoordinates(well); // returns 1 indexed
<add> // convert to 0 indexed
<add> coordinates[0]--;
<add> coordinates[1]--;
<add>
<add> if (wellArray[coordinates[0]][coordinates[1]] == null){
<add> // if Well class doesn't exist, then don't skip well
<add> return false;
<add> }
<add> else {
<add> return (wellArray[coordinates[0]][coordinates[1]].skipWell());
<add> }
<add> }
<add> /**
<add> * Returns the SBS label associated with a well
<add> * @param well number within the plate, or within region of the plate if first and last wells are set
<add> * @return returns String SBS name
<add> */
<add> public String getWellLabel(int well) {
<add> int[] coordinates = {0,0};
<add> int X,Y;
<add> String xLabel;
<add> String yLabel;
<add> // convert position into X and Y coordinates
<add>
<add> coordinates = getPlateCoordinates(well);
<add> X = coordinates[0];
<add> Y = coordinates[1];
<add>
<add> if (X < 0 || Y < 0) {
<add> return ("Out of Bounds!");
<add> }
<add>
<add> if (X < 10) xLabel = "0" + Integer.toString(X);
<add> else xLabel = Integer.toString(X);
<add>
<add> if (Y <= 26) yLabel = "" + (char)(Y+64);
<add> else yLabel = "A" + (char)(Y+38);
<add>
<add> return (yLabel + xLabel);
<add> }
<add>
<add> public int getNumberOfWells() {
<add> int wells;
<add>
<add> wells = (1 + this.lastWell[1] - this.firstWell[1]) * (1 + this.lastWell[0] - this.firstWell[0]);
<add>
<add> return wells;
<add> }
<add> /**
<add> * checks the number of positions of the current well. It will check the position list for the current well and if that exits, return that.
<add> * <p>
<add> * Otherwise it will return the number of positions of the global list.
<add> *
<add> * @return number of positions within then current well
<add> */
<add> public int getNumberOfWellPositions() {
<add>
<add> if (wellArray[currentWell[0]][currentWell[1]] == null){
<add> // if Well class doesn't exist, then check global list
<add> return ((globalPositionList.size() > 0) ? globalPositionList.size() : 1);
<add> }
<add> else {
<add> if (wellArray[currentWell[0]][currentWell[1]].wellPositionList.size() > 0) return (wellArray[currentWell[0]][currentWell[1]].wellPositionList.size());
<add> else return ((globalPositionList.size() > 0) ? globalPositionList.size() : 1);
<add> }
<add> }
<add> /**
<add> * checks the number of positions of a given well. It will check the position list for the current well and if that exits, return that.
<add> * <p>
<add> * Otherwise it will return the number of positions of the global list.
<add> *
<add> * @param well number within the plate, or within region of the plate if first and last wells are set
<add> * @return number of positions within a well
<add> */
<add> public int getNumberOfWellPositions(int well) {
<add> int[] coordinates = {0,0};
<add>
<add> coordinates = getPlateCoordinates(well); // returns 1 indexed
<add> // convert to 0 indexed
<add> coordinates[0]--;
<add> coordinates[1]--;
<add>
<add>
<add> if (wellArray[coordinates[0]][coordinates[1]] != null){
<add> if (wellArray[coordinates[0]][coordinates[1]].wellPositionList.size() > 0)
<add> return (wellArray[coordinates[0]][coordinates[1]].wellPositionList.size());
<add> }
<add>
<add> return ((globalPositionList.size() > 0) ? globalPositionList.size() : 1);
<add> }
<add> /**
<add> * Returns next well position within the current well. Position is absolute position including plate position.
<add> *
<add> * @param index
<add> * @return X,Y,Z in microns
<add> */
<add> public double[] getNextWellPosition(int index) {
<add> double[] position = {0,0,0}; // returns microns position
<add>
<add> position[0] = ((currentWell[0]) * this.plateSize.getWellSpacing()) + A1Position[0];
<add> position[1] = ((currentWell[1]) * this.plateSize.getWellSpacing()) + A1Position[1];
<add> position[2] = 0;
<add>
<add> if (index < 0) {
<add> System.err.println("getNextWellPosition: Well index out of bounds");
<add> return position;
<add> }
<add>
<add> if (wellArray[currentWell[0]][currentWell[1]] != null) {
<add> if (index < wellArray[currentWell[0]][currentWell[1]].wellPositionList.size()) {
<add> position[0] += wellArray[currentWell[0]][currentWell[1]].wellPositionList.get(index)[0];
<add> position[1] += wellArray[currentWell[0]][currentWell[1]].wellPositionList.get(index)[1];
<add> position[2] += wellArray[currentWell[0]][currentWell[1]].wellPositionList.get(index)[2];
<add> } else {
<add> if (index < globalPositionList.size()) {
<add> position[0] += globalPositionList.get(index)[0];
<add> position[1] += globalPositionList.get(index)[1];
<add> position[2] += globalPositionList.get(index)[2];
<add> } else System.err.println("getNextWellPosition: Global Well index out of bounds " + globalPositionList.size());
<add> }
<add> }
<add> else {
<add> if (index < globalPositionList.size()) {
<add> position[0] += globalPositionList.get(index)[0];
<add> position[1] += globalPositionList.get(index)[1];
<add> position[2] += globalPositionList.get(index)[2];
<add> } else System.err.println("getNextWellPosition: Global Well index out of bounds " + globalPositionList.size());
<add> }
<add>
<add> return (position);
<add> }
<add> public double[] getFirstPlatePosition(){
<add> double[] position = {0,0,0}; // returns microns position
<add>
<add> position = getPlatePosition(firstWell[0],firstWell[1]);
<ide>
<ide> return position;
<del> }
<del> public double[] getWellPosition (int X, int Y) {
<del> double[] position = {0,0};
<add> }
<add> /**
<add> * Returns the X, and Y coordinates of the center of the current well in microns.
<add> *
<add> * @param X coordinate position of the current well in microns
<add> * @param Y coordinate position of the current well in microns
<add> * @return returns an two double array containing X, Y coordinates of a well in microns
<add> */
<add> public double[] getPlatePosition (int X, int Y) {
<add> double[] position = {0,0,0}; // X, Y, Z
<ide> // switch to 0 indexed
<ide> X--;Y--;
<ide> position[0] = (X * this.plateSize.getWellSpacing()) + A1Position[0];
<ide> position[1] = (Y * this.plateSize.getWellSpacing()) + A1Position[1];
<add> position[2] = 0;
<add>
<add>
<add> if (wellArray[X][Y] == null){
<add> // if Well class doesn't exist, then check global list
<add> if (globalPositionList.size() >= 1) {
<add> position[0] += globalPositionList.get(0)[0];
<add> position[1] += globalPositionList.get(0)[1];
<add> position[2] += globalPositionList.get(0)[2];
<add> }
<add> }
<add> else {
<add> if (wellArray[firstWell[0]][firstWell[1]].wellPositionList.size() >= 1) {
<add> position[0] += wellArray[X][Y].wellPositionList.get(0)[0];
<add> position[1] += wellArray[X][Y].wellPositionList.get(0)[1];
<add> position[2] += wellArray[X][Y].wellPositionList.get(0)[2];
<add> }
<add> }
<ide>
<ide> return position;
<ide> }
<del> public String getWellLabel(int well) {
<del> String xLabel;
<del> String yLabel;
<del> // convert position into X and Y coordinates
<del> SBSPlateTypes plateType = getPlateType();
<del> int plateSize = plateType.getX() * plateType.getY();
<del> if (well > plateSize) {
<del> return ("Out of Bounds!");
<del> }
<del> else if (well < 1) return ("Out of Bounds!");
<del> else {
<del> int X = firstWell[0] + (((well - 1) / plateType.getY()) + 1);
<del> int Y = firstWell[1] + ((well % plateType.getY()));
<del> if (Y == 0) {
<del> Y = plateType.getY();
<del> }
<del> // reverse labels because we reverse direction on odd rows in reference to starting column, which may not be the first column
<del> int even = X - firstWell[0];
<del> if (even % 2 == 0) {
<del> Y = plateType.getY() - (Y - 1);
<del> }
<del> if (X < 10) xLabel = "0" + Integer.toString(X);
<del> else xLabel = Integer.toString(X);
<del>
<del> if (Y <= 26) yLabel = "" + (char)(Y+64);
<del> else {
<del> yLabel = "A" + (char)(Y+38);
<del> }
<del> }
<del>
<del> return (yLabel + xLabel);
<del> }
<del> public int getNumberOfWells() {
<del> int Positions;
<del>
<del> Positions = (1 + this.lastWell[1] - this.firstWell[1]) * (1 + this.lastWell[0] - this.firstWell[0]);
<del>
<del> return Positions;
<del> }
<add> /**
<add> * This function is deprecated. Please use getNextPlatePosition()
<add> * @return
<add> */
<ide> public double[] getNextPosition() {
<del> double[] position = {0,0}; // returns microns position
<add> return (getNextPlatePosition());
<add> }
<add> /**
<add> * Returns the position, in microns, of the next well, based on position of the last well.
<add> *
<add> * @return either the first position for that well, and if it that does not exist, returns the first global position of that well, which
<add> * is usually the center of that well, if not defined.
<add> *
<add> */
<add> public double[] getNextPlatePosition() {
<add> double[] position = {0,0,0}; // returns microns position
<ide>
<ide> if (firstWell[0] % 2 == 0 || firstWell[0] == 0) {
<ide> if (currentWell[0] % 2 == 0 || currentWell[0] == 0) {
<ide> }
<ide> position[0] = ((currentWell[0]) * this.plateSize.getWellSpacing()) + A1Position[0];
<ide> position[1] = ((currentWell[1]) * this.plateSize.getWellSpacing()) + A1Position[1];
<add> position[2] = 0;
<add>
<add> if (wellArray[currentWell[0]][currentWell[1]] == null){
<add> // if Well class doesn't exist, then check global list
<add> if (globalPositionList.size() >= 1) {
<add> position[0] += globalPositionList.get(0)[0];
<add> position[1] += globalPositionList.get(0)[1];
<add> position[2] += globalPositionList.get(0)[2];
<add> }
<add> }
<add> else {
<add> if (wellArray[currentWell[0]][currentWell[1]].wellPositionList.size() >= 1) {
<add> position[0] += wellArray[currentWell[0]][currentWell[1]].wellPositionList.get(0)[0];
<add> position[1] += wellArray[currentWell[0]][currentWell[1]].wellPositionList.get(0)[1];
<add> position[2] += wellArray[currentWell[0]][currentWell[1]].wellPositionList.get(0)[2];
<add> }
<add> }
<ide>
<ide> return position;
<ide> }
<add> /**
<add> * Returns the X and Y coordinates of a well
<add> *
<add> * @param well number within the plate, or within region of the plate if first and last wells are set
<add> * @return 1 indexed coordinates based on well plate or sub region of well plate
<add> */
<add> public int[] getPlateCoordinates(int well) {
<add> // out of bounds set to 0,0
<add> int[] coordinates = {-1,-1};
<add>
<add> int plateSize = this.plateSize.getXY();
<add> if (well >= plateSize) {
<add> return coordinates;
<add> }
<add> else if (well < 0) return coordinates;
<add> else {
<add> // Well is 0 indexed, while lastWell is 0 indexed
<add> coordinates[0] = 1 + firstWell[0] + (well/ (lastWell[1] - firstWell[1] + 1));
<add> // Well is 0 indexed, while lastWell is 0 indexed
<add> coordinates[1] = 1 + firstWell[1] + (well% (lastWell[1] - firstWell[1] + 1));
<add> }
<add>
<add> // reverse well position because we reverse direction on odd rows in reference to starting column, which may not be the first column
<add> int even = coordinates[0]- firstWell[0]; // position is 1 indexed, firstWell is 0 indexed.
<add> if (even % 2 == 0) {
<add> coordinates[1] = (lastWell[1] + 1) - (coordinates[1] - firstWell[1] - 1);
<add> }
<add>
<add> return coordinates;
<add> }
<ide> }
<add>
<add>
<add>
<add>
|
|
Java
|
bsd-3-clause
|
eb5cc3e881e9c04158eb6419106f2189460227ee
| 0 |
EmilHernvall/tregmine,EmilHernvall/tregmine,Clunker5/tregmine-2.0,EmilHernvall/tregmine,Clunker5/tregmine-2.0
|
package info.tregmine.basiccommands;
import info.tregmine.api.TregminePlayer;
import info.tregmine.currency.Wallet;
//import net.minecraft.server.v1_4_6.Item;
import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.FireworkEffect;
//import org.bukkit.FireworkEffect;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
//import org.bukkit.entity.Firework;
//import org.bukkit.entity.EntityType;
//import org.bukkit.entity.Firework;
//import org.bukkit.block.BlockFace;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
//import org.bukkit.event.entity.EntityChangeBlockEvent;
//import org.bukkit.event.hanging.HangingEvent;
//import org.bukkit.event.hanging.HangingPlaceEvent;
import org.bukkit.event.player.PlayerInteractEvent;
//import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
//import org.bukkit.event.player.PlayerListener;
//import org.bukkit.inventory.meta.FireworkMeta;
public class BasicCommandsBlock implements Listener {
private final BasicCommands plugin;
public BasicCommandsBlock(BasicCommands instance) {
this.plugin = instance;
plugin.getServer();
}
public void colorFirework(TregminePlayer player, Color c, int button, Block block) {
if (info.tregmine.api.math.Checksum.block(block) == button) {
if (!this.plugin.firework.containsKey(player.getName())) {
this.plugin.firework.put(player.getName(), new info.tregmine.api.firework.createFirwork());
}
info.tregmine.api.firework.createFirwork FireWork = this.plugin.firework.get(player.getName());
FireWork.addColor(c);
player.sendMessage(ChatColor.AQUA + FireWork.colorToString(c) + " added");
}
}
public void fadeFirework(TregminePlayer player, Color c, int button, Block block) {
if (info.tregmine.api.math.Checksum.block(block) == button) {
if (!this.plugin.firework.containsKey(player.getName())) {
this.plugin.firework.put(player.getName(), new info.tregmine.api.firework.createFirwork());
}
info.tregmine.api.firework.createFirwork FireWork = this.plugin.firework.get(player.getName());
FireWork.fadeTo(c);
player.sendMessage(ChatColor.AQUA + "Changed fade color to " + FireWork.colorToString(c));
}
}
@EventHandler
public void fireWorkButton(PlayerInteractEvent event) {
if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
TregminePlayer player = this.plugin.tregmine.getPlayer(event.getPlayer());
Block block = event.getClickedBlock();
this.colorFirework(player, Color.WHITE, -1845477288, block);
this.colorFirework(player, Color.AQUA, -337925479, block);
this.colorFirework(player, Color.PURPLE, 1169626330, block);
this.colorFirework(player, Color.BLUE, -1617789157, block);
this.colorFirework(player, Color.FUCHSIA, -1541627631, block);
this.colorFirework(player, Color.BLACK, 38377012, block);
this.colorFirework(player, Color.ORANGE, 1938955831, block);
this.colorFirework(player, Color.YELLOW, -1934654641, block);
this.colorFirework(player, Color.LIME, -1738141136, block);
this.colorFirework(player, Color.GRAY, -1345114126, block);
this.colorFirework(player, Color.SILVER, -1148600621, block);
this.colorFirework(player, Color.GREEN, -952087116, block);
this.colorFirework(player, Color.RED, -755573611, block);
this.colorFirework(player, Color.MAROON, -1469174797, block);
this.colorFirework(player, Color.TEAL, 1967285645, block);
this.colorFirework(player, Color.NAVY, -2131168146, block);
this.colorFirework(player, Color.OLIVE, -2038282101, block);
this.fadeFirework(player, Color.WHITE, 327843995, block);
this.fadeFirework(player, Color.AQUA, 100155864, block);
this.fadeFirework(player, Color.PURPLE, -96357641, block);
this.fadeFirework(player, Color.BLUE, -292871146, block);
this.fadeFirework(player, Color.FUCHSIA, 689696379, block);
this.fadeFirework(player, Color.BLACK, -1078925166, block);
this.fadeFirework(player, Color.ORANGE, 524357500, block);
this.fadeFirework(player, Color.YELLOW, -561837485, block);
this.fadeFirework(player, Color.LIME, -2069389294, block);
this.fadeFirework(player, Color.GRAY, 493182874, block);
this.fadeFirework(player, Color.SILVER, 296669369, block);
this.fadeFirework(player, Color.GREEN, -685898156, block);
this.fadeFirework(player, Color.RED, -882411661, block);
this.fadeFirework(player, Color.MAROON, -489384651, block);
this.fadeFirework(player, Color.TEAL, 1804221178, block);
this.fadeFirework(player, Color.NAVY, 1607707673, block);
this.fadeFirework(player, Color.OLIVE, -983194309, block);
// Reset colors -565613610
if (info.tregmine.api.math.Checksum.block(block) == -565613610) {
this.plugin.firework.put(player.getName(), new info.tregmine.api.firework.createFirwork());
player.sendMessage(ChatColor.AQUA + "You have now rested everyting and need to start from scratch");
}
// duration 1 button
if (info.tregmine.api.math.Checksum.block(block) == -1938184705) {
if (!this.plugin.firework.containsKey(player.getName())) {
this.plugin.firework.put(player.getName(), new info.tregmine.api.firework.createFirwork());
}
info.tregmine.api.firework.createFirwork FireWork = this.plugin.firework.get(player.getName());
FireWork.duration(1);
player.sendMessage(ChatColor.AQUA + "Changed duration to 1");
}
// duration 2 button
if (info.tregmine.api.math.Checksum.block(block) == -430632896) {
if (!this.plugin.firework.containsKey(player.getName())) {
this.plugin.firework.put(player.getName(), new info.tregmine.api.firework.createFirwork());
}
info.tregmine.api.firework.createFirwork FireWork = this.plugin.firework.get(player.getName());
FireWork.duration(2);
player.sendMessage(ChatColor.AQUA + "Changed duration to 2");
}
// duration 3 button
if (info.tregmine.api.math.Checksum.block(block) == 1076918913) {
if (!this.plugin.firework.containsKey(player.getName())) {
this.plugin.firework.put(player.getName(), new info.tregmine.api.firework.createFirwork());
}
info.tregmine.api.firework.createFirwork FireWork = this.plugin.firework.get(player.getName());
FireWork.duration(3);
player.sendMessage(ChatColor.AQUA + "Changed duration to 3");
}
// Large ball effect button
if (info.tregmine.api.math.Checksum.block(block) == 367026419) {
if (!this.plugin.firework.containsKey(player.getName())) {
this.plugin.firework.put(player.getName(), new info.tregmine.api.firework.createFirwork());
}
info.tregmine.api.firework.createFirwork FireWork = this.plugin.firework.get(player.getName());
FireWork.addType(FireworkEffect.Type.BALL_LARGE);
player.sendMessage(ChatColor.AQUA + "Changed to huge ball effect");
}
if (info.tregmine.api.math.Checksum.block(block) == 956566934) {
if (!this.plugin.firework.containsKey(player.getName())) {
this.plugin.firework.put(player.getName(), new info.tregmine.api.firework.createFirwork());
}
info.tregmine.api.firework.createFirwork FireWork = this.plugin.firework.get(player.getName());
FireWork.addType(FireworkEffect.Type.BURST);
player.sendMessage(ChatColor.AQUA + "Changed to burst effect");
}
if (info.tregmine.api.math.Checksum.block(block) == 563539924) {
if (!this.plugin.firework.containsKey(player.getName())) {
this.plugin.firework.put(player.getName(), new info.tregmine.api.firework.createFirwork());
}
info.tregmine.api.firework.createFirwork FireWork = this.plugin.firework.get(player.getName());
FireWork.addType(FireworkEffect.Type.STAR);
player.sendMessage(ChatColor.AQUA + "Changed to star effect");
}
if (info.tregmine.api.math.Checksum.block(block) == 760053429) {
if (!this.plugin.firework.containsKey(player.getName())) {
this.plugin.firework.put(player.getName(), new info.tregmine.api.firework.createFirwork());
}
info.tregmine.api.firework.createFirwork FireWork = this.plugin.firework.get(player.getName());
FireWork.addType(FireworkEffect.Type.CREEPER);
player.sendMessage(ChatColor.AQUA + "Changed to creeper effect");
}
// Preview button
if (info.tregmine.api.math.Checksum.block(block) == -1250389219) {
if (!this.plugin.firework.containsKey(player.getName())) {
player.sendMessage(ChatColor.RED + "You most go and set some fireworks propertys first");
return;
}
Location loc = new Location(block.getWorld(), -1444, 40, 5471);
info.tregmine.api.firework.createFirwork FireWork = this.plugin.firework.get(player.getName());
FireWork.shoot(loc);
}
if (info.tregmine.api.math.Checksum.block(block) == 656425969) {
if (!this.plugin.firework.containsKey(player.getName())) {
this.plugin.firework.put(player.getName(), new info.tregmine.api.firework.createFirwork());
}
info.tregmine.api.firework.createFirwork FireWork = this.plugin.firework.get(player.getName());
Wallet wallet = new Wallet(player.getName());
if ( wallet.take(2000) ) {
PlayerInventory inv = player.getInventory();
inv.addItem(FireWork.getAsStack(5));
player.sendMessage(ChatColor.AQUA + "you got 5 fireworks and " + ChatColor.GOLD + "2000" + ChatColor.AQUA + " Tregs was taken from you");
this.plugin.log.info(player.getName() + ":2000");
} else {
player.sendMessage("I'm sorry but you can't afford the 2000 tregs");
}
}
}
}
@EventHandler
public void onPlayerInteract(PlayerInteractEvent event) {
if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
Player player = event.getPlayer();
Block block = event.getClickedBlock();
Location loc = block.getLocation();
if (player.getItemInHand().getType() == Material.BOOK) {
player.sendMessage(ChatColor.DARK_AQUA + "Type: " + ChatColor.AQUA + block.getType().toString() + " ("+ ChatColor.BLUE + block.getType().getId() + ChatColor.DARK_AQUA + ")" );
player.sendMessage(ChatColor.DARK_AQUA +"Data: " + ChatColor.AQUA + (int) block.getData() );
player.sendMessage(
ChatColor.RED +"X" +
ChatColor.WHITE + ", " +
ChatColor.GREEN + "Y" +
ChatColor.WHITE + ", " +
ChatColor.BLUE + "Z" +
ChatColor.WHITE + ": " +
ChatColor.RED + loc.getBlockX() +
ChatColor.WHITE + ", " +
ChatColor.GREEN + loc.getBlockY() +
ChatColor.WHITE + ", " +
ChatColor.BLUE + loc.getBlockZ()
);
try {
player.sendMessage(ChatColor.DARK_AQUA +"Biome: " + ChatColor.AQUA + block.getBiome().toString() );
} catch (Exception e) {
player.sendMessage(ChatColor.DARK_AQUA +"Biome: " + ChatColor.AQUA + "NULL" );
}
// player.sendMessage(ChatColor.DARK_AQUA +"Light: " + ChatColor.AQUA + (int) block.getFace(BlockFace.UP).getLightLevel() );
player.sendMessage(ChatColor.DARK_AQUA +"Hash2d: " + ChatColor.AQUA + info.tregmine.api.math.Checksum.flat(block) );
player.sendMessage(ChatColor.DARK_AQUA +"Hash3d: " + ChatColor.AQUA + info.tregmine.api.math.Checksum.block(block) );
plugin.log.info("BlockHash2d: " + info.tregmine.api.math.Checksum.flat(block) );
plugin.log.info("BlockHash3d: " + info.tregmine.api.math.Checksum.block(block) );
plugin.log.info("POS: " + loc.getBlockX() + ", " + loc.getBlockY() + ", " + loc.getBlockZ());
}
}
}
}
|
BasicCommands/src/info/tregmine/basiccommands/BasicCommandsBlock.java
|
package info.tregmine.basiccommands;
import info.tregmine.api.TregminePlayer;
import info.tregmine.currency.Wallet;
//import net.minecraft.server.v1_4_6.Item;
import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.FireworkEffect;
//import org.bukkit.FireworkEffect;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
//import org.bukkit.entity.Firework;
//import org.bukkit.entity.EntityType;
//import org.bukkit.entity.Firework;
//import org.bukkit.block.BlockFace;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
//import org.bukkit.event.entity.EntityChangeBlockEvent;
//import org.bukkit.event.hanging.HangingEvent;
//import org.bukkit.event.hanging.HangingPlaceEvent;
import org.bukkit.event.player.PlayerInteractEvent;
//import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
//import org.bukkit.event.player.PlayerListener;
//import org.bukkit.inventory.meta.FireworkMeta;
public class BasicCommandsBlock implements Listener {
private final BasicCommands plugin;
public BasicCommandsBlock(BasicCommands instance) {
this.plugin = instance;
plugin.getServer();
}
public void colorFirework(TregminePlayer player, Color c, int button, Block block) {
if (info.tregmine.api.math.Checksum.block(block) == button) {
if (!this.plugin.firework.containsKey(player.getName())) {
this.plugin.firework.put(player.getName(), new info.tregmine.api.firework.createFirwork());
}
info.tregmine.api.firework.createFirwork FireWork = this.plugin.firework.get(player.getName());
FireWork.addColor(c);
player.sendMessage(ChatColor.AQUA + FireWork.colorToString(c) + " added");
}
}
public void fadeFirework(TregminePlayer player, Color c, int button, Block block) {
if (info.tregmine.api.math.Checksum.block(block) == button) {
if (!this.plugin.firework.containsKey(player.getName())) {
this.plugin.firework.put(player.getName(), new info.tregmine.api.firework.createFirwork());
}
info.tregmine.api.firework.createFirwork FireWork = this.plugin.firework.get(player.getName());
FireWork.fadeTo(c);
player.sendMessage(ChatColor.AQUA + "Changed fade color to " + FireWork.colorToString(c));
}
}
@EventHandler
public void fireWorkButton(PlayerInteractEvent event) {
if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
TregminePlayer player = this.plugin.tregmine.getPlayer(event.getPlayer());
Block block = event.getClickedBlock();
this.colorFirework(player, Color.WHITE, -1845477288, block);
this.colorFirework(player, Color.AQUA, -337925479, block);
this.colorFirework(player, Color.PURPLE, 1169626330, block);
this.colorFirework(player, Color.BLUE, -1617789157, block);
this.colorFirework(player, Color.FUCHSIA, -1541627631, block);
this.colorFirework(player, Color.BLACK, 38377012, block);
this.colorFirework(player, Color.ORANGE, 1938955831, block);
this.colorFirework(player, Color.YELLOW, -1934654641, block);
this.colorFirework(player, Color.LIME, -1738141136, block);
this.colorFirework(player, Color.GRAY, -1345114126, block);
this.colorFirework(player, Color.SILVER, -1148600621, block);
this.colorFirework(player, Color.GREEN, -952087116, block);
this.colorFirework(player, Color.RED, -755573611, block);
this.colorFirework(player, Color.MAROON, -1469174797, block);
this.colorFirework(player, Color.TEAL, 1967285645, block);
this.colorFirework(player, Color.NAVY, -2131168146, block);
this.colorFirework(player, Color.OLIVE, -2038282101, block);
this.fadeFirework(player, Color.WHITE, 327843995, block);
this.fadeFirework(player, Color.AQUA, 100155864, block);
this.fadeFirework(player, Color.PURPLE, -96357641, block);
this.fadeFirework(player, Color.BLUE, -292871146, block);
this.fadeFirework(player, Color.FUCHSIA, 689696379, block);
this.fadeFirework(player, Color.BLACK, -1078925166, block);
this.fadeFirework(player, Color.ORANGE, 524357500, block);
this.fadeFirework(player, Color.YELLOW, -561837485, block);
this.fadeFirework(player, Color.LIME, -2069389294, block);
this.fadeFirework(player, Color.GRAY, 493182874, block);
this.fadeFirework(player, Color.SILVER, 296669369, block);
this.fadeFirework(player, Color.GREEN, -685898156, block);
this.fadeFirework(player, Color.RED, -882411661, block);
this.fadeFirework(player, Color.MAROON, -489384651, block);
this.fadeFirework(player, Color.TEAL, 1804221178, block);
this.fadeFirework(player, Color.NAVY, 1607707673, block);
this.fadeFirework(player, Color.OLIVE, -983194309, block);
// Reset colors -565613610
if (info.tregmine.api.math.Checksum.block(block) == -565613610) {
this.plugin.firework.put(player.getName(), new info.tregmine.api.firework.createFirwork());
player.sendMessage(ChatColor.AQUA + "You have now rested everyting and need to start from scratch");
}
// duration 1 button
if (info.tregmine.api.math.Checksum.block(block) == -1938184705) {
if (!this.plugin.firework.containsKey(player.getName())) {
this.plugin.firework.put(player.getName(), new info.tregmine.api.firework.createFirwork());
}
info.tregmine.api.firework.createFirwork FireWork = this.plugin.firework.get(player.getName());
FireWork.duration(1);
player.sendMessage(ChatColor.AQUA + "Changed duration to 1");
}
// duration 2 button
if (info.tregmine.api.math.Checksum.block(block) == -430632896) {
if (!this.plugin.firework.containsKey(player.getName())) {
this.plugin.firework.put(player.getName(), new info.tregmine.api.firework.createFirwork());
}
info.tregmine.api.firework.createFirwork FireWork = this.plugin.firework.get(player.getName());
FireWork.duration(2);
player.sendMessage(ChatColor.AQUA + "Changed duration to 2");
}
// duration 3 button
if (info.tregmine.api.math.Checksum.block(block) == 1076918913) {
if (!this.plugin.firework.containsKey(player.getName())) {
this.plugin.firework.put(player.getName(), new info.tregmine.api.firework.createFirwork());
}
info.tregmine.api.firework.createFirwork FireWork = this.plugin.firework.get(player.getName());
FireWork.duration(3);
player.sendMessage(ChatColor.AQUA + "Changed duration to 3");
}
// Large ball effect button
if (info.tregmine.api.math.Checksum.block(block) == 367026419) {
if (!this.plugin.firework.containsKey(player.getName())) {
this.plugin.firework.put(player.getName(), new info.tregmine.api.firework.createFirwork());
}
info.tregmine.api.firework.createFirwork FireWork = this.plugin.firework.get(player.getName());
FireWork.addType(FireworkEffect.Type.BALL_LARGE);
player.sendMessage(ChatColor.AQUA + "Changed to huge ball effect");
}
if (info.tregmine.api.math.Checksum.block(block) == 956566934) {
if (!this.plugin.firework.containsKey(player.getName())) {
this.plugin.firework.put(player.getName(), new info.tregmine.api.firework.createFirwork());
}
info.tregmine.api.firework.createFirwork FireWork = this.plugin.firework.get(player.getName());
FireWork.addType(FireworkEffect.Type.BURST);
player.sendMessage(ChatColor.AQUA + "Changed to burst effect");
}
if (info.tregmine.api.math.Checksum.block(block) == 563539924) {
if (!this.plugin.firework.containsKey(player.getName())) {
this.plugin.firework.put(player.getName(), new info.tregmine.api.firework.createFirwork());
}
info.tregmine.api.firework.createFirwork FireWork = this.plugin.firework.get(player.getName());
FireWork.addType(FireworkEffect.Type.STAR);
player.sendMessage(ChatColor.AQUA + "Changed to star effect");
}
if (info.tregmine.api.math.Checksum.block(block) == 760053429) {
if (!this.plugin.firework.containsKey(player.getName())) {
this.plugin.firework.put(player.getName(), new info.tregmine.api.firework.createFirwork());
}
info.tregmine.api.firework.createFirwork FireWork = this.plugin.firework.get(player.getName());
FireWork.addType(FireworkEffect.Type.CREEPER);
player.sendMessage(ChatColor.AQUA + "Changed to creeper effect");
}
if (info.tregmine.api.math.Checksum.block(block) == 656425969) {
if (!this.plugin.firework.containsKey(player.getName())) {
this.plugin.firework.put(player.getName(), new info.tregmine.api.firework.createFirwork());
}
info.tregmine.api.firework.createFirwork FireWork = this.plugin.firework.get(player.getName());
Wallet wallet = new Wallet(player.getName());
if ( wallet.take(2000) ) {
PlayerInventory inv = player.getInventory();
inv.addItem(FireWork.getAsStack(5));
player.sendMessage(ChatColor.AQUA + "you got 5 fireworks and " + ChatColor.GOLD + "2000" + ChatColor.AQUA + " Tregs was taken from you");
this.plugin.log.info(player.getName() + ":2000");
} else {
player.sendMessage("I'm sorry but you can't afford the 2000 tregs");
}
}
}
}
@EventHandler
public void onPlayerInteract(PlayerInteractEvent event) {
if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
Player player = event.getPlayer();
Block block = event.getClickedBlock();
Location loc = block.getLocation();
if (player.getItemInHand().getType() == Material.BOOK) {
player.sendMessage(ChatColor.DARK_AQUA + "Type: " + ChatColor.AQUA + block.getType().toString() + " ("+ ChatColor.BLUE + block.getType().getId() + ChatColor.DARK_AQUA + ")" );
player.sendMessage(ChatColor.DARK_AQUA +"Data: " + ChatColor.AQUA + (int) block.getData() );
player.sendMessage(
ChatColor.RED +"X" +
ChatColor.WHITE + ", " +
ChatColor.GREEN + "Y" +
ChatColor.WHITE + ", " +
ChatColor.BLUE + "Z" +
ChatColor.WHITE + ": " +
ChatColor.RED + loc.getBlockX() +
ChatColor.WHITE + ", " +
ChatColor.GREEN + loc.getBlockY() +
ChatColor.WHITE + ", " +
ChatColor.BLUE + loc.getBlockZ()
);
try {
player.sendMessage(ChatColor.DARK_AQUA +"Biome: " + ChatColor.AQUA + block.getBiome().toString() );
} catch (Exception e) {
player.sendMessage(ChatColor.DARK_AQUA +"Biome: " + ChatColor.AQUA + "NULL" );
}
// player.sendMessage(ChatColor.DARK_AQUA +"Light: " + ChatColor.AQUA + (int) block.getFace(BlockFace.UP).getLightLevel() );
player.sendMessage(ChatColor.DARK_AQUA +"Hash2d: " + ChatColor.AQUA + info.tregmine.api.math.Checksum.flat(block) );
player.sendMessage(ChatColor.DARK_AQUA +"Hash3d: " + ChatColor.AQUA + info.tregmine.api.math.Checksum.block(block) );
plugin.log.info("BlockHash2d: " + info.tregmine.api.math.Checksum.flat(block) );
plugin.log.info("BlockHash3d: " + info.tregmine.api.math.Checksum.block(block) );
plugin.log.info("POS: " + loc.getBlockX() + ", " + loc.getBlockY() + ", " + loc.getBlockZ());
}
}
}
}
|
added preview button
|
BasicCommands/src/info/tregmine/basiccommands/BasicCommandsBlock.java
|
added preview button
|
<ide><path>asicCommands/src/info/tregmine/basiccommands/BasicCommandsBlock.java
<ide> player.sendMessage(ChatColor.AQUA + "Changed to creeper effect");
<ide> }
<ide>
<del>
<add> // Preview button
<add> if (info.tregmine.api.math.Checksum.block(block) == -1250389219) {
<add> if (!this.plugin.firework.containsKey(player.getName())) {
<add> player.sendMessage(ChatColor.RED + "You most go and set some fireworks propertys first");
<add> return;
<add> }
<add>
<add> Location loc = new Location(block.getWorld(), -1444, 40, 5471);
<add> info.tregmine.api.firework.createFirwork FireWork = this.plugin.firework.get(player.getName());
<add> FireWork.shoot(loc);
<add> }
<add>
<add>
<add>
<ide> if (info.tregmine.api.math.Checksum.block(block) == 656425969) {
<ide> if (!this.plugin.firework.containsKey(player.getName())) {
<ide> this.plugin.firework.put(player.getName(), new info.tregmine.api.firework.createFirwork());
|
|
Java
|
mit
|
038acb134ace0434669123c40353414e4defa66d
| 0 |
MrCreosote/workspace_deluxe,kbase/workspace_deluxe,MrCreosote/workspace_deluxe,kbase/workspace_deluxe,MrCreosote/workspace_deluxe,kbase/workspace_deluxe,MrCreosote/workspace_deluxe,kbase/workspace_deluxe,MrCreosote/workspace_deluxe,MrCreosote/workspace_deluxe,kbase/workspace_deluxe,MrCreosote/workspace_deluxe,kbase/workspace_deluxe,kbase/workspace_deluxe
|
package us.kbase.typedobj.core;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import us.kbase.common.service.UObject;
import us.kbase.typedobj.idref.WsIdReference;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* This is main validation algorithm.
* @author rsutormin
*/
public class JsonTokenValidationSchema {
enum Type {
object, array, string, integer, number
}
private String id; // For all: id
//private String description; // For all: description
private Type type; // For all: type
private String originalType; // For all: original-type
private IdRefDescr idReference; // For scalars and mappings: id-reference
private JsonNode searchableWsSubset; // For structures: searchable-ws-subset
private Map<String, JsonTokenValidationSchema> objectProperties; // For structures: properties
private JsonTokenValidationSchema objectAdditionalPropertiesType; // For mapping value type: additionalProperties
private boolean objectAdditionalPropertiesBoolean; // For structures: additionalProperties
private Map<String, Integer> objectRequired; // For structures: required
private JsonTokenValidationSchema arrayItems; // For list: items (one type for all items)
private List<JsonTokenValidationSchema> arrayItemList; // For tuple: items (list of types)
private Integer arrayMinItems; // For tuple: minItems
private Integer arrayMaxItems; // For tuple: maxItems
private NumberRange numberRange;
private IntRange intRange;
@SuppressWarnings("unchecked")
public static JsonTokenValidationSchema parseJsonSchema(String document)
throws JsonParseException, JsonMappingException, IOException {
Map<String, Object> data = new ObjectMapper().readValue(document, Map.class);
return parseJsonSchema(data);
}
/**
* Method parses json schema of some typed object and constructs structure
* containing everything necessary for validation of selected typed object.
*/
@SuppressWarnings("unchecked")
public static JsonTokenValidationSchema parseJsonSchema(Map<String, Object> data) {
JsonTokenValidationSchema ret = new JsonTokenValidationSchema();
ret.id = (String)data.get("id");
//ret.description = (String)data.get("description");
ret.type = Type.valueOf("" + data.get("type"));
ret.originalType = (String)data.get("original-type");
if (data.containsKey("id-reference")) {
Map<String, Object> idInfo = (Map<String, Object>)data.get("id-reference");
String idType = (String)idInfo.get("id-type"); // the id-type must be defined
String[] validTypeDefNames = null;
if (idType.equals(WsIdReference.typestring)) {
List<String> validNames = (List<String>)idInfo.get("valid-typedef-names");
if (validNames == null)
throw new RuntimeException("cannot create WsIdReference; invalid IdReference info; 'valid-typedef-names' field is required");
validTypeDefNames = validNames.toArray(new String[validNames.size()]);
}
ret.idReference = new IdRefDescr(idType, validTypeDefNames);
}
if (ret.type == Type.object) {
if (data.containsKey("searchable-ws-subset"))
ret.searchableWsSubset = UObject.transformObjectToJackson(data.get("searchable-ws-subset"));
ret.objectProperties = new LinkedHashMap<String, JsonTokenValidationSchema>();
Map<String, Object> props = (Map<String, Object>)data.get("properties");
if (props != null) {
for (Map.Entry<String, Object> entry : props.entrySet()) {
String prop = entry.getKey();
Map<String, Object> propType = (Map<String, Object>)entry.getValue();
ret.objectProperties.put(prop, parseJsonSchema(propType));
}
}
Object addProps = data.get("additionalProperties");
if (addProps != null) {
if (addProps instanceof Map) {
ret.objectAdditionalPropertiesType = parseJsonSchema((Map<String, Object>)addProps);
ret.objectAdditionalPropertiesBoolean = true;
} else {
ret.objectAdditionalPropertiesBoolean = (Boolean)addProps;
}
}
ret.objectRequired = new LinkedHashMap<String, Integer>();
List<String> reqList = (List<String>)data.get("required");
if (reqList != null) {
for (String reqItem : reqList)
ret.objectRequired.put(reqItem, ret.objectRequired.size());
}
} else if (ret.type == Type.array) {
Object items = data.get("items");
if (items instanceof Map) {
ret.arrayItems = parseJsonSchema((Map<String, Object>)items);
} else {
List<Map<String, Object>> itemList = (List<Map<String, Object>>)items;
ret.arrayItemList = new ArrayList<JsonTokenValidationSchema>();
for (Map<String, Object> item : itemList)
ret.arrayItemList.add(parseJsonSchema(item));
}
if (data.get("minItems") != null)
ret.arrayMinItems = Integer.parseInt("" + data.get("minItems"));
if (data.get("maxItems") != null)
ret.arrayMaxItems = Integer.parseInt("" + data.get("maxItems"));
} else if (ret.type == Type.number) {
ret.numberRange = new NumberRange(data);
} else if (ret.type == Type.integer) {
ret.intRange = new IntRange(data);
}
return ret;
}
/**
* Method validates object described by tokens provided by json parser against
* selected type this schema object was created for.
* @param jp json parser providing tokens of validated object
* @param stat statistics of token types observed for testing
* @param lst callback used for resulting features registration
* @param refRoot another result collecting tree schema for id-reference relabeling
* @throws JsonParseException
* @throws IOException
* @throws JsonTokenValidationException
*/
public void checkJsonData(JsonParser jp, JsonTokenValidationListener lst,
IdRefNode refRoot)
throws JsonParseException, IOException, JsonTokenValidationException {
checkJsonData(jp, lst, new ArrayList<String>(), new ArrayList<IdRefNode>(Arrays.asList(refRoot)));
jp.close();
}
private void checkJsonData(JsonParser jp, JsonTokenValidationListener lst,
List<String> path, List<IdRefNode> refPath)
throws JsonParseException, IOException, JsonTokenValidationException {
jp.nextToken();
checkJsonDataWithoutFirst(jp, lst, path, refPath);
}
private void checkJsonDataWithoutFirst(JsonParser jp, JsonTokenValidationListener lst,
List<String> path, List<IdRefNode> refPath)
throws JsonParseException, IOException, JsonTokenValidationException {
// This is main recursive validation procedure. The idea is we enter here every time we observe
// token starting nested block (which could be only mapping or array) or token for basic scalar
// values (integer, floating, string, boolean and null). According to structure of nested blocks
// in observed tokens we trevel by nested nodes in json schema and add nested nodes into output
// id-reference relabeling tree (only if id referencing annotation is present for branch we
// visit now in json schema).
if (type == Type.object) {
// mapping (object) is expected in json schema
if (searchableWsSubset != null) {
// seachable ws-subset description is defined for this object/mapping
lst.addSearchableWsSubsetMessage(searchableWsSubset);
}
// add new level to json path we are visiting now, every field of this object will
// change this '{' value into name of this field, so exact character ('{') is not
// important, we just shift depth of path into deeper level
path.add("{");
try {
JsonToken t = jp.getCurrentToken();
if (t == null || t != JsonToken.START_OBJECT) {
// we expect mapping (object) but in real data we observe token of different type
throw new JsonTokenValidationException(generateError(type, t, path));
}
// flags for usage (true) or not usage (false) of fields having positions in this
// array coded in objectRequired map
boolean[] reqPropUsage = new boolean[objectRequired.size()];
// count of true values in reqPropUsage
int reqPropUsageCount = 0;
// in following loop we process all fields of opened object
while (true) {
t = jp.nextToken();
if (t == JsonToken.END_OBJECT) {
// end of object, go out of loop
break;
} else if (t != JsonToken.FIELD_NAME) {
// every time we here we expect next field since rest of this loop is for
// processing of value for this field
throw new JsonTokenValidationException("Object field name is expected but found " + t);
}
// name of object field (key of mapping)
String fieldName = jp.getCurrentName();
// set current path pointing to this field
path.set(path.size() - 1, fieldName);
// if this field is required we mark it as visited
if (objectRequired.containsKey(fieldName)) {
reqPropUsageCount++;
reqPropUsage[objectRequired.get(fieldName)] = true;
}
// we need to find json-schema node describing value of this field
JsonTokenValidationSchema childType = objectProperties.get(fieldName);
if (childType == null) {
if (!objectAdditionalPropertiesBoolean) {
if (objectProperties.size() > 0)
lst.addError("Object field name [" + fieldName + "] is not in allowed " +
"object properties: " + objectProperties.keySet());
}
childType = objectAdditionalPropertiesType;
}
if (childType == null) {
// if we don't have such schema it means we don't need to validate it, just skip it
skipValue(jp);
} else {
// otherwise we execute validation recursively for child json-schema node
childType.checkJsonData(jp, lst, path, refPath);
}
// and finally we can add this key (field) as requiring id-reference relabeling in
// case there was defined idReference property in json-schema node describing this
// object (mapping)
if (idReference != null) {
WsIdReference ref = createRef(fieldName, idReference, path.subList(0, path.size() - 1), true);
if (ref != null) {
// this line adds id-reference into flat list which will be used to extract resolved
// values from workspace db
lst.addIdRefMessage(ref);
// this line adds id-reference into tree structure that will be used for actual
// relabeling in object tokens based on list of resolved values constructed by workspace
getIdRefNode(path, refPath).setParentKeyRef(fieldName);
}
}
}
// check whether all required fields were occured
if (reqPropUsageCount != reqPropUsage.length) {
List<String> absentProperties = new ArrayList<String>();
for (Map.Entry<String, Integer> entry : objectRequired.entrySet())
if (!reqPropUsage[entry.getValue()])
absentProperties.add(entry.getKey());
lst.addError("Object doesn't have required fields : " + absentProperties);
}
} finally {
// shift (if necessary) depth of id-reference related result tree
while (refPath.size() > path.size())
refPath.remove(refPath.size() - 1);
// shift depth of path by 1 level up (closer to root)
path.remove(path.size() - 1);
}
} else if (type == Type.array) {
// array (list) is expected in json data based on json schema of selected type
JsonToken t = jp.getCurrentToken();
if (t == null || t != JsonToken.START_ARRAY) {
// but token of some other type is observed
throw new JsonTokenValidationException(generateError(type, t, path));
}
// add next level in path corresponding to this array, this value should be
// incremented every time we jump to next array item
path.add("-1");
try {
int itemPos = 0;
// following flag means that we have more items in real data than we have
// described in scheme, we use this flag in order to skip not described
// items and jump to next data, because we collect error messages rather
// than just throw one of them
boolean skipAll = false;
while (true) {
if (arrayMaxItems != null && itemPos > arrayMaxItems) {
// too many items in real data comparing to limitation in json schema
lst.addError("Array contains more than " + arrayMaxItems + " items");
skipAll = true;
}
t = jp.nextToken();
if (t == JsonToken.END_ARRAY)
break;
// if we are here then we see in real data next item of this array (list)
// let's increment last path element according to position of this item in array
path.set(path.size() - 1, "" + itemPos);
JsonTokenValidationSchema childType = arrayItems;
if ((!skipAll) && childType == null && arrayItemList != null && itemPos < arrayItemList.size())
childType = arrayItemList.get(itemPos);
if (skipAll || childType == null) {
// if we have more items than we expect or we didn't specify types for
// some of them then we skip real data of these items
skipValueWithoutFirst(jp);
} else {
// otherwise we execute recursive validation for current item
childType.checkJsonDataWithoutFirst(jp, lst, path, refPath);
}
itemPos++;
}
// check if we have too less items than we define in schema limitations (if any)
if (arrayMinItems != null && itemPos < arrayMinItems)
lst.addError("Array contains less than " + arrayMinItems + " items");
} finally {
// shift (if necessary) depth of id-reference related result tree
while (refPath.size() > path.size())
refPath.remove(refPath.size() - 1);
// shift depth of path by 1 level up (closer to root)
path.remove(path.size() - 1);
}
} else if (type == Type.string) {
// string value is expecting
JsonToken t = jp.getCurrentToken();
if (t != JsonToken.VALUE_STRING) { // but found something else
if (t != JsonToken.VALUE_NULL || idReference != null) // we allow nulls but not for references
lst.addError(generateError(type, t, path));
}
if (idReference != null) {
// we can add this string value as requiring id-reference relabeling in case
// there was defined idReference property in json-schema node describing this
// string value
WsIdReference ref = createRef(jp.getText(), idReference, path, false);
if (ref != null) {
// this line adds id-reference into flat list which will be used to extract resolved
// values from workspace db
lst.addIdRefMessage(ref);
getIdRefNode(path, refPath).setScalarValueRef(jp.getText());
}
}
} else if (type == Type.integer) {
// integer value is expected
JsonToken t = jp.getCurrentToken();
if ((t != JsonToken.VALUE_NUMBER_INT) && (t != JsonToken.VALUE_NULL)) // but found something else
lst.addError(generateError(type, t, path));
if(intRange!=null)
intRange.checkValue(jp, lst, path);
} else if (type == Type.number) {
// floating point value is expected
JsonToken t = jp.getCurrentToken();
if ((t != JsonToken.VALUE_NUMBER_FLOAT) && (t != JsonToken.VALUE_NUMBER_INT) && (t != JsonToken.VALUE_NULL)) // but found something else
lst.addError(generateError(type, t, path));
if(numberRange!=null)
numberRange.checkValue(jp, lst, path);
} else {
lst.addError("Unsupported node type: " + type);
}
}
private static String generateError(Type expectedType, JsonToken actualToken, List<String> path) {
String expected = expectedType == Type.number ? "float" : expectedType.toString();
String actual = tokenToType(actualToken);
return "instance type ("+actual+") does not match any allowed primitive type " +
"(allowed: [\""+expected+"\"]), at " + getPathText(path);
}
private static String tokenToType(JsonToken t) {
switch (t) {
case START_OBJECT:
return "object";
case END_OBJECT:
return "object end";
case START_ARRAY:
return "array";
case END_ARRAY:
return "array end";
case FIELD_NAME:
return "object field";
case VALUE_NUMBER_FLOAT:
return "float";
case VALUE_NUMBER_INT:
return "integer";
case VALUE_STRING:
return "string";
case VALUE_NULL:
return "null";
case VALUE_TRUE:
return "boolean";
case VALUE_FALSE:
return "boolean";
default:
return t.asString();
}
}
private static String getPathText(List<String> path) {
StringBuilder ret = new StringBuilder();
for (String part : path)
ret.append('/').append(part);
return ret.toString();
}
private static IdRefNode getIdRefNode(List<String> path, List<IdRefNode> refPath) {
if (refPath.size() == 0 || refPath.size() > path.size() + 1)
throw new IllegalStateException("Reference branch path has wrong length: " + refPath.size());
while (refPath.size() > 1 && !refPath.get(refPath.size() - 1).getLastPathLocation().equals(path.get(refPath.size() - 2))) {
refPath.remove(refPath.size() - 1);
}
while (refPath.size() <= path.size()) {
int pos = refPath.size() - 1;
IdRefNode parent = refPath.get(pos);
String key = path.get(pos);
IdRefNode child = new IdRefNode(key);
parent.addChild(key, child);
refPath.add(child);
}
return refPath.get(path.size());
}
private static WsIdReference createRef(String id, IdRefDescr idInfo, List<String> path, boolean isFieldName) {
// construct the IdReference object
if (idInfo.idType.equals(WsIdReference.typestring)) {
return new WsIdReference(id, idInfo.validTypeDefNames, isFieldName);
}
return null;
}
private static void skipValue(JsonParser jp) throws JsonParseException, IOException, JsonTokenValidationException {
jp.nextToken();
skipValueWithoutFirst(jp);
}
private static void skipValueWithoutFirst(JsonParser jp) throws JsonParseException, IOException, JsonTokenValidationException {
JsonToken t = jp.getCurrentToken();
if (t == JsonToken.START_OBJECT) {
while (true) {
t = jp.nextToken();
if (t == JsonToken.END_OBJECT) {
break;
}
skipValue(jp);
}
} else if (t == JsonToken.START_ARRAY) {
while (true) {
t = jp.nextToken();
if (t == JsonToken.END_ARRAY)
break;
skipValueWithoutFirst(jp);
}
}
}
public String getId() {
return id;
}
public Type getType() {
return type;
}
public String getOriginalType() {
return originalType;
}
public String getIdReferenceType() {
return idReference == null ? null : idReference.idType;
}
public String[] getIdReferenceValidTypeDefNames() {
return idReference == null ? null : idReference.validTypeDefNames;
}
public JsonNode getSearchableWsSubset() {
return searchableWsSubset;
}
public Map<String, JsonTokenValidationSchema> getObjectProperties() {
return objectProperties;
}
public JsonTokenValidationSchema getObjectAdditionalPropertiesType() {
return objectAdditionalPropertiesType;
}
public boolean isObjectAdditionalPropertiesBoolean() {
return objectAdditionalPropertiesBoolean;
}
public Map<String, Integer> getObjectRequired() {
return objectRequired;
}
public JsonTokenValidationSchema getArrayItems() {
return arrayItems;
}
public List<JsonTokenValidationSchema> getArrayItemList() {
return arrayItemList;
}
public Integer getArrayMinItems() {
return arrayMinItems;
}
public Integer getArrayMaxItems() {
return arrayMaxItems;
}
private static class IdRefDescr {
String idType;
String[] validTypeDefNames;
public IdRefDescr(String idType, String[] validTypeDefNames) {
this.idType = idType;
this.validTypeDefNames = validTypeDefNames;
}
}
private static abstract class Range {
protected boolean minValueDefined;
protected boolean maxValueDefined;
protected boolean exclusiveMin;
protected boolean exclusiveMax;
protected Range() {
minValueDefined=false;
maxValueDefined=false;
exclusiveMin = false;
exclusiveMax = false;
}
abstract void checkValue(JsonParser jp, JsonTokenValidationListener lst, List<String> path) throws JsonTokenValidationException;
}
private static class NumberRange extends Range {
double minValue;
double maxValue;
public NumberRange(Map<String, Object> data) {
minValue=0; maxValue=0;
if(data.get("minimum") != null) {
minValueDefined = true;
minValue = Double.parseDouble("" + data.get("minimum"));
if(data.get("exclusiveMinimum") != null)
exclusiveMin = true;
else
exclusiveMin = false;
}
if(data.get("maximum") != null) {
maxValueDefined = true;
maxValue = Double.parseDouble("" + data.get("maximum"));
if(data.get("exclusiveMaximum") != null)
exclusiveMax = true;
else
exclusiveMax = false;
}
}
@Override
void checkValue(JsonParser jp, JsonTokenValidationListener lst, List<String> path) throws JsonTokenValidationException {
System.out.println("checking float value: "+this);
try {
// first attempt to check range assuming it is a double value
double value = jp.getDoubleValue();
if(minValueDefined) {
if(exclusiveMin) {
if( !(value>minValue) ) {
lst.addError("Number value given ("+value+") was less than minimum value accepted ("+minValue+", exclusive) at "+getPathText(path));
}
} else {
if( !(value>=minValue) ) {
lst.addError("Number value given ("+value+") was less than minimum value accepted ("+maxValue+", inclusive) at "+getPathText(path));
}
}
}
if(maxValueDefined) {
if(exclusiveMin) {
if( !(value<maxValue)) {
lst.addError("Number value given ("+value+") was more than maximum value accepted ("+maxValue+", exclusive) at "+getPathText(path));
}
} else {
if( !(value<=maxValue) ) {
lst.addError("Number value given ("+value+") was more than maximum value accepted ("+maxValue+", inclusive) at "+getPathText(path));
}
}
}
} catch (IOException e) {
// if we encountered an exception, then there was probably a buffer overflow
//jp.getDecimalValue();
}
}
@Override
public String toString() {
String s = "";
if(minValueDefined) {
if(exclusiveMin) s+="("; else s+="[";
s+=minValue+",";
} else s+= "inf,";
if(maxValueDefined) {
s+=maxValue;
if(exclusiveMax) s+=")"; else s+="]";
} else s+= "inf";
return s;
}
}
private static class IntRange extends Range {
long minValue;
long maxValue;
public IntRange(Map<String, Object> data) {
minValue=0; maxValue=0;
if(data.get("minimum") != null) {
minValueDefined = true;
minValue = Long.parseLong("" + data.get("minimum"));
if(data.get("exclusiveMinimum") != null)
exclusiveMin = true;
else
exclusiveMin = false;
}
if(data.get("maximum") != null) {
maxValueDefined = true;
maxValue = Long.parseLong("" + data.get("maximum"));
if(data.get("exclusiveMaximum") != null)
exclusiveMax = true;
else
exclusiveMax = false;
}
}
@Override
void checkValue(JsonParser jp, JsonTokenValidationListener lst, List<String> path) throws JsonTokenValidationException {
System.out.println("checking int value: "+this);
try {
// first attempt to check range assuming it is a double value
double value = jp.getLongValue();
if(minValueDefined) {
if(exclusiveMin) {
if( !(value>minValue) ) {
lst.addError("Integer value given ("+value+") was less than minimum value accepted ("+minValue+", exclusive) at "+getPathText(path));
}
} else {
if( !(value>=minValue) ) {
lst.addError("Integer value given ("+value+") was less than minimum value accepted ("+maxValue+", inclusive) at "+getPathText(path));
}
}
}
if(maxValueDefined) {
if(exclusiveMin) {
if( !(value<maxValue) ) {
lst.addError("Integer value given ("+value+") was more than maximum value accepted ("+maxValue+", exclusive) at "+getPathText(path));
}
} else {
if( !(value<=maxValue) ) {
lst.addError("Integer value given ("+value+") was more than maximum value accepted ("+maxValue+", inclusive) at "+getPathText(path));
}
}
}
} catch (IOException e) {
// if we encountered an exception, then there was probably a buffer overflow
//jp.getDecimalValue();
}
}
@Override
public String toString() {
String s = "";
if(minValueDefined) {
if(exclusiveMin) s+="("; else s+="[";
s+=minValue+",";
} else s+= "inf,";
if(maxValueDefined) {
s+=maxValue;
if(exclusiveMax) s+=")"; else s+="]";
} else s+= "inf";
return s;
}
}
}
|
src/us/kbase/typedobj/core/JsonTokenValidationSchema.java
|
package us.kbase.typedobj.core;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import us.kbase.common.service.UObject;
import us.kbase.typedobj.idref.WsIdReference;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* This is main validation algorithm.
* @author rsutormin
*/
public class JsonTokenValidationSchema {
enum Type {
object, array, string, integer, number
}
private String id; // For all: id
//private String description; // For all: description
private Type type; // For all: type
private String originalType; // For all: original-type
private IdRefDescr idReference; // For scalars and mappings: id-reference
private JsonNode searchableWsSubset; // For structures: searchable-ws-subset
private Map<String, JsonTokenValidationSchema> objectProperties; // For structures: properties
private JsonTokenValidationSchema objectAdditionalPropertiesType; // For mapping value type: additionalProperties
private boolean objectAdditionalPropertiesBoolean; // For structures: additionalProperties
private Map<String, Integer> objectRequired; // For structures: required
private JsonTokenValidationSchema arrayItems; // For list: items (one type for all items)
private List<JsonTokenValidationSchema> arrayItemList; // For tuple: items (list of types)
private Integer arrayMinItems; // For tuple: minItems
private Integer arrayMaxItems; // For tuple: maxItems
private NumberRange numberRange;
private IntRange intRange;
@SuppressWarnings("unchecked")
public static JsonTokenValidationSchema parseJsonSchema(String document)
throws JsonParseException, JsonMappingException, IOException {
Map<String, Object> data = new ObjectMapper().readValue(document, Map.class);
return parseJsonSchema(data);
}
/**
* Method parses json schema of some typed object and constructs structure
* containing everything necessary for validation of selected typed object.
*/
@SuppressWarnings("unchecked")
public static JsonTokenValidationSchema parseJsonSchema(Map<String, Object> data) {
JsonTokenValidationSchema ret = new JsonTokenValidationSchema();
ret.id = (String)data.get("id");
//ret.description = (String)data.get("description");
ret.type = Type.valueOf("" + data.get("type"));
ret.originalType = (String)data.get("original-type");
if (data.containsKey("id-reference")) {
Map<String, Object> idInfo = (Map<String, Object>)data.get("id-reference");
String idType = (String)idInfo.get("id-type"); // the id-type must be defined
String[] validTypeDefNames = null;
if (idType.equals(WsIdReference.typestring)) {
List<String> validNames = (List<String>)idInfo.get("valid-typedef-names");
if (validNames == null)
throw new RuntimeException("cannot create WsIdReference; invalid IdReference info; 'valid-typedef-names' field is required");
validTypeDefNames = validNames.toArray(new String[validNames.size()]);
}
ret.idReference = new IdRefDescr(idType, validTypeDefNames);
}
if (ret.type == Type.object) {
if (data.containsKey("searchable-ws-subset"))
ret.searchableWsSubset = UObject.transformObjectToJackson(data.get("searchable-ws-subset"));
ret.objectProperties = new LinkedHashMap<String, JsonTokenValidationSchema>();
Map<String, Object> props = (Map<String, Object>)data.get("properties");
if (props != null) {
for (Map.Entry<String, Object> entry : props.entrySet()) {
String prop = entry.getKey();
Map<String, Object> propType = (Map<String, Object>)entry.getValue();
ret.objectProperties.put(prop, parseJsonSchema(propType));
}
}
Object addProps = data.get("additionalProperties");
if (addProps != null) {
if (addProps instanceof Map) {
ret.objectAdditionalPropertiesType = parseJsonSchema((Map<String, Object>)addProps);
ret.objectAdditionalPropertiesBoolean = true;
} else {
ret.objectAdditionalPropertiesBoolean = (Boolean)addProps;
}
}
ret.objectRequired = new LinkedHashMap<String, Integer>();
List<String> reqList = (List<String>)data.get("required");
if (reqList != null) {
for (String reqItem : reqList)
ret.objectRequired.put(reqItem, ret.objectRequired.size());
}
} else if (ret.type == Type.array) {
Object items = data.get("items");
if (items instanceof Map) {
ret.arrayItems = parseJsonSchema((Map<String, Object>)items);
} else {
List<Map<String, Object>> itemList = (List<Map<String, Object>>)items;
ret.arrayItemList = new ArrayList<JsonTokenValidationSchema>();
for (Map<String, Object> item : itemList)
ret.arrayItemList.add(parseJsonSchema(item));
}
if (data.get("minItems") != null)
ret.arrayMinItems = Integer.parseInt("" + data.get("minItems"));
if (data.get("maxItems") != null)
ret.arrayMaxItems = Integer.parseInt("" + data.get("maxItems"));
} else if (ret.type == Type.number) {
ret.numberRange = new NumberRange(data);
} else if (ret.type == Type.integer) {
ret.intRange = new IntRange(data);
}
return ret;
}
/**
* Method validates object described by tokens provided by json parser against
* selected type this schema object was created for.
* @param jp json parser providing tokens of validated object
* @param stat statistics of token types observed for testing
* @param lst callback used for resulting features registration
* @param refRoot another result collecting tree schema for id-reference relabeling
* @throws JsonParseException
* @throws IOException
* @throws JsonTokenValidationException
*/
public void checkJsonData(JsonParser jp, JsonTokenValidationListener lst,
IdRefNode refRoot)
throws JsonParseException, IOException, JsonTokenValidationException {
checkJsonData(jp, lst, new ArrayList<String>(), new ArrayList<IdRefNode>(Arrays.asList(refRoot)));
jp.close();
}
private void checkJsonData(JsonParser jp, JsonTokenValidationListener lst,
List<String> path, List<IdRefNode> refPath)
throws JsonParseException, IOException, JsonTokenValidationException {
jp.nextToken();
checkJsonDataWithoutFirst(jp, lst, path, refPath);
}
private void checkJsonDataWithoutFirst(JsonParser jp, JsonTokenValidationListener lst,
List<String> path, List<IdRefNode> refPath)
throws JsonParseException, IOException, JsonTokenValidationException {
// This is main recursive validation procedure. The idea is we enter here every time we observe
// token starting nested block (which could be only mapping or array) or token for basic scalar
// values (integer, floating, string, boolean and null). According to structure of nested blocks
// in observed tokens we trevel by nested nodes in json schema and add nested nodes into output
// id-reference relabeling tree (only if id referencing annotation is present for branch we
// visit now in json schema).
if (type == Type.object) {
// mapping (object) is expected in json schema
if (searchableWsSubset != null) {
// seachable ws-subset description is defined for this object/mapping
lst.addSearchableWsSubsetMessage(searchableWsSubset);
}
// add new level to json path we are visiting now, every field of this object will
// change this '{' value into name of this field, so exact character ('{') is not
// important, we just shift depth of path into deeper level
path.add("{");
try {
JsonToken t = jp.getCurrentToken();
if (t == null || t != JsonToken.START_OBJECT) {
// we expect mapping (object) but in real data we observe token of different type
throw new JsonTokenValidationException(generateError(type, t, path));
}
// flags for usage (true) or not usage (false) of fields having positions in this
// array coded in objectRequired map
boolean[] reqPropUsage = new boolean[objectRequired.size()];
// count of true values in reqPropUsage
int reqPropUsageCount = 0;
// in following loop we process all fields of opened object
while (true) {
t = jp.nextToken();
if (t == JsonToken.END_OBJECT) {
// end of object, go out of loop
break;
} else if (t != JsonToken.FIELD_NAME) {
// every time we here we expect next field since rest of this loop is for
// processing of value for this field
throw new JsonTokenValidationException("Object field name is expected but found " + t);
}
// name of object field (key of mapping)
String fieldName = jp.getCurrentName();
// set current path pointing to this field
path.set(path.size() - 1, fieldName);
// if this field is required we mark it as visited
if (objectRequired.containsKey(fieldName)) {
reqPropUsageCount++;
reqPropUsage[objectRequired.get(fieldName)] = true;
}
// we need to find json-schema node describing value of this field
JsonTokenValidationSchema childType = objectProperties.get(fieldName);
if (childType == null) {
if (!objectAdditionalPropertiesBoolean) {
if (objectProperties.size() > 0)
lst.addError("Object field name [" + fieldName + "] is not in allowed " +
"object properties: " + objectProperties.keySet());
}
childType = objectAdditionalPropertiesType;
}
if (childType == null) {
// if we don't have such schema it means we don't need to validate it, just skip it
skipValue(jp);
} else {
// otherwise we execute validation recursively for child json-schema node
childType.checkJsonData(jp, lst, path, refPath);
}
// and finally we can add this key (field) as requiring id-reference relabeling in
// case there was defined idReference property in json-schema node describing this
// object (mapping)
if (idReference != null) {
WsIdReference ref = createRef(fieldName, idReference, path.subList(0, path.size() - 1), true);
if (ref != null) {
// this line adds id-reference into flat list which will be used to extract resolved
// values from workspace db
lst.addIdRefMessage(ref);
// this line adds id-reference into tree structure that will be used for actual
// relabeling in object tokens based on list of resolved values constructed by workspace
getIdRefNode(path, refPath).setParentKeyRef(fieldName);
}
}
}
// check whether all required fields were occured
if (reqPropUsageCount != reqPropUsage.length) {
List<String> absentProperties = new ArrayList<String>();
for (Map.Entry<String, Integer> entry : objectRequired.entrySet())
if (!reqPropUsage[entry.getValue()])
absentProperties.add(entry.getKey());
lst.addError("Object doesn't have required fields : " + absentProperties);
}
} finally {
// shift (if necessary) depth of id-reference related result tree
while (refPath.size() > path.size())
refPath.remove(refPath.size() - 1);
// shift depth of path by 1 level up (closer to root)
path.remove(path.size() - 1);
}
} else if (type == Type.array) {
// array (list) is expected in json data based on json schema of selected type
JsonToken t = jp.getCurrentToken();
if (t == null || t != JsonToken.START_ARRAY) {
// but token of some other type is observed
throw new JsonTokenValidationException(generateError(type, t, path));
}
// add next level in path corresponding to this array, this value should be
// incremented every time we jump to next array item
path.add("-1");
try {
int itemPos = 0;
// following flag means that we have more items in real data than we have
// described in scheme, we use this flag in order to skip not described
// items and jump to next data, because we collect error messages rather
// than just throw one of them
boolean skipAll = false;
while (true) {
if (arrayMaxItems != null && itemPos > arrayMaxItems) {
// too many items in real data comparing to limitation in json schema
lst.addError("Array contains more than " + arrayMaxItems + " items");
skipAll = true;
}
t = jp.nextToken();
if (t == JsonToken.END_ARRAY)
break;
// if we are here then we see in real data next item of this array (list)
// let's increment last path element according to position of this item in array
path.set(path.size() - 1, "" + itemPos);
JsonTokenValidationSchema childType = arrayItems;
if ((!skipAll) && childType == null && arrayItemList != null && itemPos < arrayItemList.size())
childType = arrayItemList.get(itemPos);
if (skipAll || childType == null) {
// if we have more items than we expect or we didn't specify types for
// some of them then we skip real data of these items
skipValueWithoutFirst(jp);
} else {
// otherwise we execute recursive validation for current item
childType.checkJsonDataWithoutFirst(jp, lst, path, refPath);
}
itemPos++;
}
// check if we have too less items than we define in schema limitations (if any)
if (arrayMinItems != null && itemPos < arrayMinItems)
lst.addError("Array contains less than " + arrayMinItems + " items");
} finally {
// shift (if necessary) depth of id-reference related result tree
while (refPath.size() > path.size())
refPath.remove(refPath.size() - 1);
// shift depth of path by 1 level up (closer to root)
path.remove(path.size() - 1);
}
} else if (type == Type.string) {
// string value is expecting
JsonToken t = jp.getCurrentToken();
if (t != JsonToken.VALUE_STRING) { // but found something else
if (t != JsonToken.VALUE_NULL || idReference != null) // we allow nulls but not for references
lst.addError(generateError(type, t, path));
}
if (idReference != null) {
// we can add this string value as requiring id-reference relabeling in case
// there was defined idReference property in json-schema node describing this
// string value
WsIdReference ref = createRef(jp.getText(), idReference, path, false);
if (ref != null) {
// this line adds id-reference into flat list which will be used to extract resolved
// values from workspace db
lst.addIdRefMessage(ref);
getIdRefNode(path, refPath).setScalarValueRef(jp.getText());
}
}
} else if (type == Type.integer) {
// integer value is expected
JsonToken t = jp.getCurrentToken();
if ((t != JsonToken.VALUE_NUMBER_INT) && (t != JsonToken.VALUE_NULL)) // but found something else
lst.addError(generateError(type, t, path));
if(intRange!=null)
intRange.checkValue(jp, lst, path);
} else if (type == Type.number) {
// floating point value is expected
JsonToken t = jp.getCurrentToken();
if ((t != JsonToken.VALUE_NUMBER_FLOAT) && (t != JsonToken.VALUE_NULL)) // but found something else
lst.addError(generateError(type, t, path));
if(numberRange!=null)
numberRange.checkValue(jp, lst, path);
} else {
lst.addError("Unsupported node type: " + type);
}
}
private static String generateError(Type expectedType, JsonToken actualToken, List<String> path) {
String expected = expectedType == Type.number ? "float" : expectedType.toString();
String actual = tokenToType(actualToken);
return "instance type ("+actual+") does not match any allowed primitive type " +
"(allowed: [\""+expected+"\"]), at " + getPathText(path);
}
private static String tokenToType(JsonToken t) {
switch (t) {
case START_OBJECT:
return "object";
case END_OBJECT:
return "object end";
case START_ARRAY:
return "array";
case END_ARRAY:
return "array end";
case FIELD_NAME:
return "object field";
case VALUE_NUMBER_FLOAT:
return "float";
case VALUE_NUMBER_INT:
return "integer";
case VALUE_STRING:
return "string";
case VALUE_NULL:
return "null";
case VALUE_TRUE:
return "boolean";
case VALUE_FALSE:
return "boolean";
default:
return t.asString();
}
}
private static String getPathText(List<String> path) {
StringBuilder ret = new StringBuilder();
for (String part : path)
ret.append('/').append(part);
return ret.toString();
}
private static IdRefNode getIdRefNode(List<String> path, List<IdRefNode> refPath) {
if (refPath.size() == 0 || refPath.size() > path.size() + 1)
throw new IllegalStateException("Reference branch path has wrong length: " + refPath.size());
while (refPath.size() > 1 && !refPath.get(refPath.size() - 1).getLastPathLocation().equals(path.get(refPath.size() - 2))) {
refPath.remove(refPath.size() - 1);
}
while (refPath.size() <= path.size()) {
int pos = refPath.size() - 1;
IdRefNode parent = refPath.get(pos);
String key = path.get(pos);
IdRefNode child = new IdRefNode(key);
parent.addChild(key, child);
refPath.add(child);
}
return refPath.get(path.size());
}
private static WsIdReference createRef(String id, IdRefDescr idInfo, List<String> path, boolean isFieldName) {
// construct the IdReference object
if (idInfo.idType.equals(WsIdReference.typestring)) {
return new WsIdReference(id, idInfo.validTypeDefNames, isFieldName);
}
return null;
}
private static void skipValue(JsonParser jp) throws JsonParseException, IOException, JsonTokenValidationException {
jp.nextToken();
skipValueWithoutFirst(jp);
}
private static void skipValueWithoutFirst(JsonParser jp) throws JsonParseException, IOException, JsonTokenValidationException {
JsonToken t = jp.getCurrentToken();
if (t == JsonToken.START_OBJECT) {
while (true) {
t = jp.nextToken();
if (t == JsonToken.END_OBJECT) {
break;
}
skipValue(jp);
}
} else if (t == JsonToken.START_ARRAY) {
while (true) {
t = jp.nextToken();
if (t == JsonToken.END_ARRAY)
break;
skipValueWithoutFirst(jp);
}
}
}
public String getId() {
return id;
}
public Type getType() {
return type;
}
public String getOriginalType() {
return originalType;
}
public String getIdReferenceType() {
return idReference == null ? null : idReference.idType;
}
public String[] getIdReferenceValidTypeDefNames() {
return idReference == null ? null : idReference.validTypeDefNames;
}
public JsonNode getSearchableWsSubset() {
return searchableWsSubset;
}
public Map<String, JsonTokenValidationSchema> getObjectProperties() {
return objectProperties;
}
public JsonTokenValidationSchema getObjectAdditionalPropertiesType() {
return objectAdditionalPropertiesType;
}
public boolean isObjectAdditionalPropertiesBoolean() {
return objectAdditionalPropertiesBoolean;
}
public Map<String, Integer> getObjectRequired() {
return objectRequired;
}
public JsonTokenValidationSchema getArrayItems() {
return arrayItems;
}
public List<JsonTokenValidationSchema> getArrayItemList() {
return arrayItemList;
}
public Integer getArrayMinItems() {
return arrayMinItems;
}
public Integer getArrayMaxItems() {
return arrayMaxItems;
}
private static class IdRefDescr {
String idType;
String[] validTypeDefNames;
public IdRefDescr(String idType, String[] validTypeDefNames) {
this.idType = idType;
this.validTypeDefNames = validTypeDefNames;
}
}
private static abstract class Range {
protected boolean minValueDefined;
protected boolean maxValueDefined;
protected boolean exclusiveMin;
protected boolean exclusiveMax;
protected Range() {
minValueDefined=false;
maxValueDefined=false;
exclusiveMin = false;
exclusiveMax = false;
}
abstract void checkValue(JsonParser jp, JsonTokenValidationListener lst, List<String> path) throws JsonTokenValidationException;
}
private static class NumberRange extends Range {
double minValue;
double maxValue;
public NumberRange(Map<String, Object> data) {
minValue=0; maxValue=0;
if(data.get("minimum") != null) {
minValueDefined = true;
minValue = Double.parseDouble("" + data.get("minimum"));
if(data.get("exclusiveMinimum") != null)
exclusiveMin = true;
else
exclusiveMin = false;
}
if(data.get("maximum") != null) {
maxValueDefined = true;
maxValue = Double.parseDouble("" + data.get("maximum"));
if(data.get("exclusiveMaximum") != null)
exclusiveMax = true;
else
exclusiveMax = false;
}
}
@Override
void checkValue(JsonParser jp, JsonTokenValidationListener lst, List<String> path) throws JsonTokenValidationException {
System.out.println("checking value"+this);
try {
// first attempt to check range assuming it is a double value
double value = jp.getDoubleValue();
if(minValueDefined) {
if(exclusiveMin) {
if(value<=minValue) {
lst.addError("Number value given ("+value+") was less than minimum value accepted ("+minValue+", "+" exclusive) at "+getPathText(path));
}
} else {
if(value<=minValue) {
lst.addError("Number value given ("+value+") was less than minimum value accepted ("+maxValue+", "+" inclusive) at "+getPathText(path));
}
}
}
if(maxValueDefined) {
if(exclusiveMin) {
if(value>=maxValue) {
lst.addError("Number value given ("+value+") was more than maximum value accepted ("+maxValue+", "+" exclusive) at "+getPathText(path));
}
} else {
if(value<=minValue) {
lst.addError("Number value given ("+value+") was more than maximum value accepted ("+maxValue+", "+" inclusive) at "+getPathText(path));
}
}
}
} catch (IOException e) {
// if we encountered an exception, then there was probably a buffer overflow
//jp.getDecimalValue();
}
}
@Override
public String toString() {
String s = "";
if(minValueDefined) {
if(exclusiveMin) s+="("; else s+="[";
s+=minValue+",";
} else s+= "inf,";
if(maxValueDefined) {
s+=maxValue;
if(exclusiveMax) s+=")"; else s+="]";
} else s+= "inf";
return s;
}
}
private static class IntRange extends Range {
long minValue;
long maxValue;
public IntRange(Map<String, Object> data) {
minValue=0; maxValue=0;
if(data.get("minimum") != null) {
minValueDefined = true;
minValue = Long.parseLong("" + data.get("minimum"));
if(data.get("exclusiveMinimum") != null)
exclusiveMin = true;
else
exclusiveMin = false;
}
if(data.get("maximum") != null) {
maxValueDefined = true;
maxValue = Long.parseLong("" + data.get("maximum"));
if(data.get("exclusiveMaximum") != null)
exclusiveMax = true;
else
exclusiveMax = false;
}
}
@Override
void checkValue(JsonParser jp, JsonTokenValidationListener lst, List<String> path) throws JsonTokenValidationException {
System.out.println("checking value"+this);
try {
// first attempt to check range assuming it is a double value
double value = jp.getLongValue();
if(minValueDefined) {
if(exclusiveMin) {
if(value<=minValue) {
lst.addError("Integer value given ("+value+") was less than minimum value accepted ("+minValue+", "+" exclusive) at "+getPathText(path));
}
} else {
if(value<=minValue) {
lst.addError("Integer value given ("+value+") was less than minimum value accepted ("+maxValue+", "+" inclusive) at "+getPathText(path));
}
}
}
if(maxValueDefined) {
if(exclusiveMin) {
if(value>=maxValue) {
lst.addError("Integer value given ("+value+") was more than maximum value accepted ("+maxValue+", "+" exclusive) at "+getPathText(path));
}
} else {
if(value<=minValue) {
lst.addError("Integer value given ("+value+") was more than maximum value accepted ("+maxValue+", "+" inclusive) at "+getPathText(path));
}
}
}
} catch (IOException e) {
// if we encountered an exception, then there was probably a buffer overflow
//jp.getDecimalValue();
}
}
}
}
|
minor changes to range check logic
|
src/us/kbase/typedobj/core/JsonTokenValidationSchema.java
|
minor changes to range check logic
|
<ide><path>rc/us/kbase/typedobj/core/JsonTokenValidationSchema.java
<ide> } else if (type == Type.number) {
<ide> // floating point value is expected
<ide> JsonToken t = jp.getCurrentToken();
<del> if ((t != JsonToken.VALUE_NUMBER_FLOAT) && (t != JsonToken.VALUE_NULL)) // but found something else
<add> if ((t != JsonToken.VALUE_NUMBER_FLOAT) && (t != JsonToken.VALUE_NUMBER_INT) && (t != JsonToken.VALUE_NULL)) // but found something else
<ide> lst.addError(generateError(type, t, path));
<ide> if(numberRange!=null)
<ide> numberRange.checkValue(jp, lst, path);
<ide>
<ide> @Override
<ide> void checkValue(JsonParser jp, JsonTokenValidationListener lst, List<String> path) throws JsonTokenValidationException {
<del> System.out.println("checking value"+this);
<add> System.out.println("checking float value: "+this);
<ide> try {
<ide> // first attempt to check range assuming it is a double value
<ide> double value = jp.getDoubleValue();
<ide> if(minValueDefined) {
<ide> if(exclusiveMin) {
<del> if(value<=minValue) {
<del> lst.addError("Number value given ("+value+") was less than minimum value accepted ("+minValue+", "+" exclusive) at "+getPathText(path));
<add> if( !(value>minValue) ) {
<add> lst.addError("Number value given ("+value+") was less than minimum value accepted ("+minValue+", exclusive) at "+getPathText(path));
<ide> }
<ide> } else {
<del> if(value<=minValue) {
<del> lst.addError("Number value given ("+value+") was less than minimum value accepted ("+maxValue+", "+" inclusive) at "+getPathText(path));
<add> if( !(value>=minValue) ) {
<add> lst.addError("Number value given ("+value+") was less than minimum value accepted ("+maxValue+", inclusive) at "+getPathText(path));
<ide> }
<ide> }
<ide> }
<ide> if(maxValueDefined) {
<ide> if(exclusiveMin) {
<del> if(value>=maxValue) {
<del> lst.addError("Number value given ("+value+") was more than maximum value accepted ("+maxValue+", "+" exclusive) at "+getPathText(path));
<add> if( !(value<maxValue)) {
<add> lst.addError("Number value given ("+value+") was more than maximum value accepted ("+maxValue+", exclusive) at "+getPathText(path));
<ide> }
<ide> } else {
<del> if(value<=minValue) {
<del> lst.addError("Number value given ("+value+") was more than maximum value accepted ("+maxValue+", "+" inclusive) at "+getPathText(path));
<add> if( !(value<=maxValue) ) {
<add> lst.addError("Number value given ("+value+") was more than maximum value accepted ("+maxValue+", inclusive) at "+getPathText(path));
<ide> }
<ide> }
<ide> }
<ide>
<ide> @Override
<ide> void checkValue(JsonParser jp, JsonTokenValidationListener lst, List<String> path) throws JsonTokenValidationException {
<del> System.out.println("checking value"+this);
<add> System.out.println("checking int value: "+this);
<ide> try {
<ide> // first attempt to check range assuming it is a double value
<ide> double value = jp.getLongValue();
<ide> if(minValueDefined) {
<ide> if(exclusiveMin) {
<del> if(value<=minValue) {
<del> lst.addError("Integer value given ("+value+") was less than minimum value accepted ("+minValue+", "+" exclusive) at "+getPathText(path));
<add> if( !(value>minValue) ) {
<add> lst.addError("Integer value given ("+value+") was less than minimum value accepted ("+minValue+", exclusive) at "+getPathText(path));
<ide> }
<ide> } else {
<del> if(value<=minValue) {
<del> lst.addError("Integer value given ("+value+") was less than minimum value accepted ("+maxValue+", "+" inclusive) at "+getPathText(path));
<add> if( !(value>=minValue) ) {
<add> lst.addError("Integer value given ("+value+") was less than minimum value accepted ("+maxValue+", inclusive) at "+getPathText(path));
<ide> }
<ide> }
<ide> }
<ide> if(maxValueDefined) {
<ide> if(exclusiveMin) {
<del> if(value>=maxValue) {
<del> lst.addError("Integer value given ("+value+") was more than maximum value accepted ("+maxValue+", "+" exclusive) at "+getPathText(path));
<add> if( !(value<maxValue) ) {
<add> lst.addError("Integer value given ("+value+") was more than maximum value accepted ("+maxValue+", exclusive) at "+getPathText(path));
<ide> }
<ide> } else {
<del> if(value<=minValue) {
<del> lst.addError("Integer value given ("+value+") was more than maximum value accepted ("+maxValue+", "+" inclusive) at "+getPathText(path));
<add> if( !(value<=maxValue) ) {
<add> lst.addError("Integer value given ("+value+") was more than maximum value accepted ("+maxValue+", inclusive) at "+getPathText(path));
<ide> }
<ide> }
<ide> }
<ide> //jp.getDecimalValue();
<ide> }
<ide> }
<del> }
<add>
<add> @Override
<add> public String toString() {
<add> String s = "";
<add> if(minValueDefined) {
<add> if(exclusiveMin) s+="("; else s+="[";
<add> s+=minValue+",";
<add> } else s+= "inf,";
<add> if(maxValueDefined) {
<add> s+=maxValue;
<add> if(exclusiveMax) s+=")"; else s+="]";
<add> } else s+= "inf";
<add> return s;
<add> }
<add> }
<add>
<add>
<ide> }
|
|
JavaScript
|
mit
|
1a647b8625572e7f2d7613ec4f6d97626461de5a
| 0 |
webhook/webhook-cms,marloscarmo/webhook-cms,webhook/webhook-cms,marloscarmo/webhook-cms
|
import validateControl from 'appkit/utils/validators';
import getItemModelName from 'appkit/utils/model';
import SearchIndex from 'appkit/utils/search-index';
export default Ember.ObjectController.extend(Ember.Evented, {
controlTypeGroups: null,
editingControl : null,
isEditing : false,
contentTypes : null,
relationTypes : null,
addedControls : Ember.A([]),
removedControls : Ember.A([]),
changedNameControls: Ember.A([]),
changedRadioControls: Ember.A([]),
removedControlsApproved: null,
changedControlNamessApproved: null,
validateControls: function () {
this.get('controls').setEach('widgetIsValid', true);
this.get('controls').setEach('widgetErrors', Ember.A([]));
var names = this.get('controls').mapBy('name').sort(),
dupes = [];
for (var i = 0; i < names.length - 1; i++) {
if (names[i + 1] === names[i]) {
dupes.push(names[i]);
}
}
dupes = dupes.uniq();
this.get('controls').filter(function (control, index) {
return dupes.indexOf(control.get('name')) >= 0;
}).setEach('widgetIsValid', false);
this.get('controls').rejectBy('widgetIsValid').setEach('widgetErrors', Ember.A(['Duplicate name.']));
this.get('controls').filterBy('controlType.widget', 'relation').forEach(function (control) {
if (!control.get('meta.data.contentTypeId')) {
control.set('widgetIsValid', false);
control.get('widgetErrors').addObject('You must select a related content type.');
}
});
},
updateOrder: function (originalIndex, newIndex) {
var controls = this.get('model.controls'),
control = controls.objectAt(originalIndex);
controls.removeAt(originalIndex);
controls.insertAt(newIndex, control);
},
addControlAtIndex: function (controlTypeId, index) {
this.store.find('control-type', controlTypeId).then(function (controlType) {
this.addControl(controlType, index);
}.bind(this));
},
addControl: function (controlType, index) {
var controls, control;
controls = this.get('model.controls');
control = this.store.createRecord('control', {
label : controlType.get('name'),
controlType: controlType,
showInCms : (controls.filterBy('showInCms').get('length') < 3)
});
control.set('widgetIsValid', true);
var meta = this.store.createRecord('meta-data');
switch (controlType.get('widget')) {
case 'instruction':
control.set('showInCms', false);
break;
case 'radio':
meta.set('data', {
options: [
{ value: 'Option 1' },
{ value: 'Option 2' }
]
});
break;
case 'select':
meta.set('data', {
defaultValue: '',
options: [
{ value: '' },
{ value: 'Option 1' }
]
});
break;
case 'checkbox':
meta.set('data', {
options: [
{ label: 'Option 1' },
{ label: 'Option 2' }
]
});
break;
case 'wysiwyg':
meta.set('data', {
image: true,
link : true,
quote: true,
table: true,
video: true
});
break;
case 'rating':
meta.set('data', {
min: 0,
max: 5,
step: 0.5
});
break;
case 'tabular':
meta.set('data', {
options: [
{ value: 'Column 1' },
{ value: 'Column 2' }
]
});
var value = Ember.A([]);
var emptyRow = Ember.A([]);
meta.get('data.options').forEach(function () {
emptyRow.pushObject("");
});
value.pushObject(emptyRow);
control.set('value', value);
break;
case 'relation':
meta.set('data', {
contentTypeId: null
});
break;
}
control.set('meta', meta);
if (index) {
controls.insertAt(index, control);
} else {
controls.pushObject(control);
}
this.get('addedControls').addObject(control);
},
updateRelations: function () {
Ember.Logger.info('Looking for relationships to update.');
// Store relation promises here
var relationUpdates = Ember.A([]);
var removedRelations = this.get('removedControls').filterBy('controlType.widget', 'relation');
Ember.Logger.info('Need to remove ' + removedRelations.get('length') + ' reverse relationships.');
removedRelations.forEach(function (control) {
Ember.Logger.info('Attempting to remove `' + control.get('meta.data.reverseName') + '` from `' + control.get('meta.data.contentTypeId') + '`');
var relationPromise = new Ember.RSVP.Promise(function (resolve, reject) {
this.get('store').find('contentType', control.get('meta.data.contentTypeId')).then(function (contentType) {
var controls = contentType.get('controls');
var controlToRemove = controls.filterBy('name', control.get('meta.data.reverseName')).get('firstObject');
controls.removeObject(controlToRemove);
contentType.save().then(function () {
Ember.Logger.info('Successfully removed `' + control.get('meta.data.reverseName') + '` from `' + control.get('meta.data.contentTypeId') + '`');
Ember.run(null, resolve);
}, function (error) {
Ember.run(null, reject, error);
});
}, function (error) {
Ember.run(null, reject, error);
});
}.bind(this));
relationUpdates.push(relationPromise);
}.bind(this));
var addedRelations = this.get('addedControls').filterBy('controlType.widget', 'relation');
Ember.Logger.info('Need to add ' + addedRelations.get('length') + ' reverse relationships.');
addedRelations.forEach(function (localControl) {
Ember.Logger.info('Attempting to add reverse relationship of `' + localControl.get('name') + '` to `' + localControl.get('meta.data.contentTypeId') + '`');
var relationPromise = new Ember.RSVP.Promise(function (resolve, reject) {
this.get('store').find('contentType', localControl.get('meta.data.contentTypeId')).then(function (contentType) {
var foreignControls = contentType.get('controls');
var foreignRelations = foreignControls.filterBy('controlType.widget', 'relation');
this.store.find('control-type', 'relation').then(function (controlType) {
var control = this.store.createRecord('control', {
label : this.get('model.name'),
controlType: controlType,
meta: this.store.createRecord('meta-data', {
data: {
contentTypeId: this.get('model.id'),
reverseName: localControl.get('name')
}
})
});
// The new reverse relation control must have a unique name
var counter = 1;
while (foreignControls.getEach('name').indexOf(control.get('name')) >= 0) {
counter = counter + 1;
control.set('label', this.get('model.name') + ' ' + counter);
}
Ember.Logger.info('Setting unique name for reverse relationship: `' + control.get('name') + '` on `' + contentType.get('id') + '`');
// Remember reverse relation name in meta data
localControl.set('meta.data.reverseName', control.get('name'));
// Add new relation control to the stack
contentType.get('controls').pushObject(control);
contentType.save().then(function (contentType) {
Ember.Logger.info('Reverse relationship of `' + localControl.get('name') + '` to `' + localControl.get('meta.data.contentTypeId') + '` successfully added.');
Ember.run(null, resolve);
}, function (error) {
Ember.run(null, reject, error);
});
}.bind(this));
}.bind(this));
}.bind(this));
relationUpdates.push(relationPromise);
}.bind(this));
var changedRelations = this.get('changedNameControls').filterBy('controlType.widget', 'relation');
Ember.Logger.info('Need to update ' + changedRelations.get('length') + ' reverse relationships.');
changedRelations.forEach(function (localControl) {
Ember.Logger.info('Attempting to update reverse relationship of `' + localControl.get('name') + '` to `' + localControl.get('meta.data.contentTypeId') + '`');
var relationPromise = new Ember.RSVP.Promise(function (resolve, reject) {
this.get('store').find('contentType', localControl.get('meta.data.contentTypeId')).then(function (contentType) {
var foreignControls = contentType.get('controls');
var foreignRelations = foreignControls.filterBy('controlType.widget', 'relation');
foreignControls.filterBy('name', localControl.get('meta.data.reverseName')).setEach('meta.data.reverseName', localControl.get('name'));
contentType.save().then(function (contentType) {
Ember.Logger.info('`' + contentType.get('name') + '` updated.');
Ember.run(null, resolve);
});
}.bind(this));
}.bind(this));
}.bind(this));
return relationUpdates;
},
updateItems: function () {
// if the content type is new, we do not need to do anything
if (this.get('model.isNew')) {
return;
}
var changedNameControls = this.get('changedNameControls');
var removedControls = this.get('removedControls');
var changedRadioControls = this.get('changedRadioControls');
var contentType = this.get('model');
// if we didn't remove controls or change control names we do not need to update anything
if (!removedControls.get('length') && !changedNameControls.get('length') && !changedRadioControls.get('length')) {
Ember.Logger.info('Item updates not needed');
return;
}
var itemModelName = getItemModelName(contentType);
Ember.Logger.info('Updating `' + itemModelName + '` item data and search indices for', removedControls.get('length'), 'removed controls,', changedNameControls.get('length'), 'renamed controls, and', changedRadioControls.get('length'), 'changed radio controls.');
var updateData = function (item) {
var itemData = item.get('data');
changedNameControls.forEach(function (control) {
itemData[control.get('name')] = itemData[control.get('originalName')] === undefined ? null : itemData[control.get('originalName')];
itemData[control.get('originalName')] = null;
});
removedControls.forEach(function (control) {
itemData[control.get('originalName')] = null;
});
changedRadioControls.forEach(function (control) {
if (itemData[control.get('name')]) {
itemData[control.get('name')] = control.get('values').get(itemData[control.get('name')]) ? control.get('values').get(itemData[control.get('name')]) : itemData[control.get('name')];
}
});
item.set('data', itemData);
item.save().then(function (savedItem) {
Ember.Logger.info('Data updates applied to', savedItem.get('id'));
SearchIndex.indexItem(savedItem, contentType);
});
};
if (contentType.get('oneOff')) {
this.store.find(itemModelName, contentType.get('id')).then(function (item) {
updateData(item);
});
} else {
this.store.find(itemModelName).then(function (items) {
items.forEach(function (item) {
updateData(item);
});
});
}
},
promptConfirmChanges: function () {
if (this.get('removedControls.length') || this.get('changedNameControls.length') || this.get('changedRadioControls.length')) {
Ember.Logger.info('Prompt for changed control confirmation.');
this.toggleProperty('confirmChangedControlsPrompt');
} else {
this.saveType();
}
},
// we have updated associated items, we're go for type saving.
saveType: function () {
var wasNew = this.get('model.isNew');
// update relationships
// check if we changes relationship widget names
var relationUpdates = this.updateRelations();
// When all the relationships are updated, save this contentType.
Ember.RSVP.Promise.all(relationUpdates).then(function () {
Ember.Logger.info('Saving contentType `' + this.get('model.name') + '`');
this.get('model').save().then(function (contentType) {
if (contentType.get('oneOff')) {
this.transitionToRoute('wh.content.type.index', contentType);
this.send('notify', 'success', 'Form saved!');
} else {
if (wasNew) {
window.ENV.sendGruntCommand('scaffolding:' + contentType.get('id'), function () {
this.send('notify', 'success', 'Scaffolding for ' + contentType.get('name') + ' built.');
}.bind(this));
// Acknowledge scaffolding
this.toggleProperty('initialScaffoldingPrompt');
} else {
// ask if they want to rebuild scaffolding
this.toggleProperty('scaffoldingPrompt');
}
}
}.bind(this), function (error) {
Ember.Logger.error(error);
if (window.trackJs) {
window.trackJs.log("Attempted to save form.", this.get('model'));
window.trackJs.track(error);
}
this.send('notify', 'danger', 'There was an error while saving.');
}.bind(this));
}.bind(this));
},
actions: {
updateType: function () {
Ember.Logger.info('Saving content type', this.get('model.id'));
this.set('isEditing', false);
this.validateControls();
if (this.get('model.controls').isAny('widgetIsValid', false)) {
Ember.Logger.info('The following controls are invalid:', this.get('model.controls').filterBy('widgetIsValid', false).getEach('name'));
return;
}
var formController = this;
var contentType = this.get('model');
// reset changedNameControls in case they backed out and decided to change the name back.
formController.set('changedNameControls', Ember.A([]));
// reset changedRadioControls in case they backed out and decided to change the values back
formController.set('changedRadioControls', Ember.A([]));
contentType.get('controls').forEach(function (control) {
// See if we changed any control names
if (control.get('originalName') && control.get('originalName') !== control.get('name')) {
formController.get('changedNameControls').addObject(control);
}
// See if we changed any radio values
if (control.get('controlType.widget') === 'radio') {
var changedRadioControls = null;
control.get('meta.data.options').getEach('value').forEach(function (value, index) {
var originalValue = control.get('originalOptions').objectAt(index);
if (originalValue && originalValue !== value) {
if (!changedRadioControls) {
changedRadioControls = Ember.Object.create({
name: control.get('name'),
values: Ember.Object.create()
});
}
changedRadioControls.get('values').set(originalValue, value);
}
});
if (changedRadioControls) {
formController.get('changedRadioControls').addObject(changedRadioControls);
}
}
// we don't want to store checkbox values to the db when we save
if (control.get('controlType.widget') === 'checkbox') {
control.get('meta.data.options').setEach('value', null);
}
// hax
// firebase doesn't like undefined values and for some reason `_super` is
// being added to arrays in ember with undefined value
if (Ember.isArray(control.get('meta.data.options'))) {
control.set('meta.data.options', control.get('meta.data.options').toArray());
Ember.run.sync();
delete control.get('meta.data.options').__nextSuper;
}
});
this.promptConfirmChanges();
},
addControl: function (controlType, index) {
this.addControl.apply(this, arguments);
},
deleteControl: function (control) {
if (this.get('addedControls').indexOf(control) >= 0) {
this.get('addedControls').removeObject(control);
} else {
this.get('removedControls').addObject(control);
}
control.set('justDeleted', true);
Ember.run.later(this, function () {
this.get('model.controls').removeObject(control);
}, 500);
this.set('editingControl', null);
this.send('stopEditing');
},
editControl: function (control) {
if (!control.get('meta')) {
control.set('meta', this.store.createRecord('meta-data', { data: {} }));
}
this.set('editingControl', control);
this.set('isEditing', true);
},
stopEditing: function () {
this.set('isEditing', false);
},
startEditing: function () {
this.send('editControl', this.get('editingControl') || this.get('model.controls.firstObject'));
},
addOption: function (array) {
array.pushObject({});
var control = this.get('editingControl');
if (control.get('controlType.widget') === 'tabular') {
control.get('value').forEach(function (row) {
row.pushObject("");
});
}
},
removeOption: function (array, option) {
var control = this.get('editingControl');
if (control.get('controlType.widget') === 'tabular') {
var optionIndex = array.indexOf(option);
control.get('value').forEach(function (row) {
row.removeAt(optionIndex);
});
}
array.removeObject(option);
},
quitForm: function () {
// changed your mind on a new contentType? BALEETED
if (this.get('model.isNew')) {
this.get('model').deleteRecord();
}
this.transitionToRoute('wh.content.all-types');
},
acknoledgeScaffolding: function () {
this.transitionToRoute('wh.content.type.index', this.get('model'));
},
forceScaffolding: function () {
window.ENV.sendGruntCommand('scaffolding_force:' + this.get('model.id'), function () {
this.send('notify', 'success', 'Scaffolding for ' + this.get('model.name') + ' built.');
}.bind(this));
this.transitionToRoute('wh.content.type.index', this.get('model'));
},
abortScaffolding: function () {
this.transitionToRoute('wh.content.type.index', this.get('model'));
},
confirmChangedControls: function () {
this.toggleProperty('confirmChangedControlsPrompt');
this.updateItems();
this.saveType();
},
rejectChangedControls: function () {
this.toggleProperty('confirmChangedControlsPrompt');
}
}
});
|
app/controllers/form.js
|
import validateControl from 'appkit/utils/validators';
import getItemModelName from 'appkit/utils/model';
import SearchIndex from 'appkit/utils/search-index';
export default Ember.ObjectController.extend(Ember.Evented, {
controlTypeGroups: null,
editingControl : null,
isEditing : false,
contentTypes : null,
relationTypes : null,
addedControls : Ember.A([]),
removedControls : Ember.A([]),
changedNameControls: Ember.A([]),
changedRadioControls: Ember.A([]),
removedControlsApproved: null,
changedControlNamessApproved: null,
validateControls: function () {
this.get('controls').setEach('widgetIsValid', true);
this.get('controls').setEach('widgetErrors', Ember.A([]));
var names = this.get('controls').mapBy('name').sort(),
dupes = [];
for (var i = 0; i < names.length - 1; i++) {
if (names[i + 1] === names[i]) {
dupes.push(names[i]);
}
}
dupes = dupes.uniq();
this.get('controls').filter(function (control, index) {
return dupes.indexOf(control.get('name')) >= 0;
}).setEach('widgetIsValid', false);
this.get('controls').rejectBy('widgetIsValid').setEach('widgetErrors', Ember.A(['Duplicate name.']));
this.get('controls').filterBy('controlType.widget', 'relation').forEach(function (control) {
if (!control.get('meta.data.contentTypeId')) {
control.set('widgetIsValid', false);
control.get('widgetErrors').addObject('You must select a related content type.');
}
});
},
updateOrder: function (originalIndex, newIndex) {
var controls = this.get('model.controls'),
control = controls.objectAt(originalIndex);
controls.removeAt(originalIndex);
controls.insertAt(newIndex, control);
},
addControlAtIndex: function (controlTypeId, index) {
this.store.find('control-type', controlTypeId).then(function (controlType) {
this.addControl(controlType, index);
}.bind(this));
},
addControl: function (controlType, index) {
var controls, control;
controls = this.get('model.controls');
control = this.store.createRecord('control', {
label : controlType.get('name'),
controlType: controlType,
showInCms : (controls.filterBy('showInCms').get('length') < 3)
});
control.set('widgetIsValid', true);
var meta = this.store.createRecord('meta-data');
switch (controlType.get('widget')) {
case 'instruction':
control.set('showInCms', false);
break;
case 'radio':
meta.set('data', {
options: [
{ value: 'Option 1' },
{ value: 'Option 2' }
]
});
break;
case 'select':
meta.set('data', {
defaultValue: '',
options: [
{ value: '' },
{ value: 'Option 1' }
]
});
break;
case 'checkbox':
meta.set('data', {
options: [
{ label: 'Option 1' },
{ label: 'Option 2' }
]
});
break;
case 'wysiwyg':
meta.set('data', {
image: true,
link : true,
quote: true,
table: true,
video: true
});
break;
case 'rating':
meta.set('data', {
min: 0,
max: 5,
step: 0.5
});
break;
case 'tabular':
meta.set('data', {
options: [
{ value: 'Column 1' },
{ value: 'Column 2' }
]
});
var value = Ember.A([]);
var emptyRow = Ember.A([]);
meta.get('data.options').forEach(function () {
emptyRow.pushObject("");
});
value.pushObject(emptyRow);
control.set('value', value);
break;
case 'relation':
meta.set('data', {
contentTypeId: null
});
break;
}
control.set('meta', meta);
if (index) {
controls.insertAt(index, control);
} else {
controls.pushObject(control);
}
this.get('addedControls').addObject(control);
},
updateRelations: function () {
Ember.Logger.info('Looking for relationships to update.');
// Store relation promises here
var relationUpdates = Ember.A([]);
var removedRelations = this.get('removedControls').filterBy('controlType.widget', 'relation');
Ember.Logger.info('Need to remove ' + removedRelations.get('length') + ' reverse relationships.');
removedRelations.forEach(function (control) {
Ember.Logger.info('Attempting to remove `' + control.get('meta.data.reverseName') + '` from `' + control.get('meta.data.contentTypeId') + '`');
var relationPromise = new Ember.RSVP.Promise(function (resolve, reject) {
this.get('store').find('contentType', control.get('meta.data.contentTypeId')).then(function (contentType) {
var controls = contentType.get('controls');
var controlToRemove = controls.filterBy('name', control.get('meta.data.reverseName')).get('firstObject');
controls.removeObject(controlToRemove);
contentType.save().then(function () {
Ember.Logger.info('Successfully removed `' + control.get('meta.data.reverseName') + '` from `' + control.get('meta.data.contentTypeId') + '`');
Ember.run(null, resolve);
}, function (error) {
Ember.run(null, reject, error);
});
}, function (error) {
Ember.run(null, reject, error);
});
}.bind(this));
relationUpdates.push(relationPromise);
}.bind(this));
var addedRelations = this.get('addedControls').filterBy('controlType.widget', 'relation');
Ember.Logger.info('Need to add ' + addedRelations.get('length') + ' reverse relationships.');
addedRelations.forEach(function (localControl) {
Ember.Logger.info('Attempting to add reverse relationship of `' + localControl.get('name') + '` to `' + localControl.get('meta.data.contentTypeId') + '`');
var relationPromise = new Ember.RSVP.Promise(function (resolve, reject) {
this.get('store').find('contentType', localControl.get('meta.data.contentTypeId')).then(function (contentType) {
var foreignControls = contentType.get('controls');
var foreignRelations = foreignControls.filterBy('controlType.widget', 'relation');
this.store.find('control-type', 'relation').then(function (controlType) {
var control = this.store.createRecord('control', {
label : this.get('model.name'),
controlType: controlType,
meta: this.store.createRecord('meta-data', {
data: {
contentTypeId: this.get('model.id'),
reverseName: localControl.get('name')
}
})
});
// The new reverse relation control must have a unique name
var counter = 1;
while (foreignControls.getEach('name').indexOf(control.get('name')) >= 0) {
counter = counter + 1;
control.set('label', this.get('model.name') + ' ' + counter);
}
Ember.Logger.info('Setting unique name for reverse relationship: `' + control.get('name') + '` on `' + contentType.get('id') + '`');
// Remember reverse relation name in meta data
localControl.set('meta.data.reverseName', control.get('name'));
// Add new relation control to the stack
contentType.get('controls').pushObject(control);
contentType.save().then(function (contentType) {
Ember.Logger.info('Reverse relationship of `' + localControl.get('name') + '` to `' + localControl.get('meta.data.contentTypeId') + '` successfully added.');
Ember.run(null, resolve);
}, function (error) {
Ember.run(null, reject, error);
});
}.bind(this));
}.bind(this));
}.bind(this));
relationUpdates.push(relationPromise);
}.bind(this));
var changedRelations = this.get('changedNameControls').filterBy('controlType.widget', 'relation');
Ember.Logger.info('Need to update ' + changedRelations.get('length') + ' reverse relationships.');
changedRelations.forEach(function (localControl) {
Ember.Logger.info('Attempting to update reverse relationship of `' + localControl.get('name') + '` to `' + localControl.get('meta.data.contentTypeId') + '`');
var relationPromise = new Ember.RSVP.Promise(function (resolve, reject) {
this.get('store').find('contentType', localControl.get('meta.data.contentTypeId')).then(function (contentType) {
var foreignControls = contentType.get('controls');
var foreignRelations = foreignControls.filterBy('controlType.widget', 'relation');
foreignControls.filterBy('name', localControl.get('meta.data.reverseName')).setEach('meta.data.reverseName', localControl.get('name'));
contentType.save().then(function (contentType) {
Ember.Logger.info('`' + contentType.get('name') + '` updated.');
Ember.run(null, resolve);
});
}.bind(this));
}.bind(this));
}.bind(this));
return relationUpdates;
},
updateItems: function () {
// if the content type is new, we do not need to do anything
if (this.get('model.isNew')) {
return;
}
var changedNameControls = this.get('changedNameControls');
var removedControls = this.get('removedControls');
var changedRadioControls = this.get('changedRadioControls');
var contentType = this.get('model');
// if we didn't remove controls or change control names we do not need to update anything
if (!removedControls.get('length') && !changedNameControls.get('length') && !changedRadioControls.get('length')) {
Ember.Logger.info('Item updates not needed');
return;
}
var itemModelName = getItemModelName(contentType);
Ember.Logger.info('Updating `' + itemModelName + '` item data and search indices for', removedControls.get('length'), 'removed controls,', changedNameControls.get('length'), 'renamed controls, and', changedRadioControls.get('length'), 'changed radio controls.');
this.store.find(itemModelName).then(function (items) {
items.forEach(function (item) {
var itemData = item.get('data');
changedNameControls.forEach(function (control) {
itemData[control.get('name')] = itemData[control.get('originalName')] === undefined ? null : itemData[control.get('originalName')];
itemData[control.get('originalName')] = null;
});
removedControls.forEach(function (control) {
itemData[control.get('originalName')] = null;
});
changedRadioControls.forEach(function (control) {
if (itemData[control.get('name')]) {
itemData[control.get('name')] = control.get('values').get(itemData[control.get('name')]) ? control.get('values').get(itemData[control.get('name')]) : itemData[control.get('name')];
}
});
item.set('data', itemData);
item.save().then(function (savedItem) {
Ember.Logger.info('Data updates applied to', savedItem.get('id'));
SearchIndex.indexItem(savedItem, contentType);
});
});
});
},
promptConfirmChanges: function () {
if (this.get('removedControls.length') || this.get('changedNameControls.length') || this.get('changedRadioControls.length')) {
Ember.Logger.info('Prompt for changed control confirmation.');
this.toggleProperty('confirmChangedControlsPrompt');
} else {
this.saveType();
}
},
// we have updated associated items, we're go for type saving.
saveType: function () {
var wasNew = this.get('model.isNew');
// update relationships
// check if we changes relationship widget names
var relationUpdates = this.updateRelations();
// When all the relationships are updated, save this contentType.
Ember.RSVP.Promise.all(relationUpdates).then(function () {
Ember.Logger.info('Saving contentType `' + this.get('model.name') + '`');
this.get('model').save().then(function (contentType) {
if (contentType.get('oneOff')) {
this.transitionToRoute('wh.content.type.index', contentType);
this.send('notify', 'success', 'Form saved!');
} else {
if (wasNew) {
window.ENV.sendGruntCommand('scaffolding:' + contentType.get('id'), function () {
this.send('notify', 'success', 'Scaffolding for ' + contentType.get('name') + ' built.');
}.bind(this));
// Acknowledge scaffolding
this.toggleProperty('initialScaffoldingPrompt');
} else {
// ask if they want to rebuild scaffolding
this.toggleProperty('scaffoldingPrompt');
}
}
}.bind(this), function (error) {
Ember.Logger.error(error);
if (window.trackJs) {
window.trackJs.log("Attempted to save form.", this.get('model'));
window.trackJs.track(error);
}
this.send('notify', 'danger', 'There was an error while saving.');
}.bind(this));
}.bind(this));
},
actions: {
updateType: function () {
Ember.Logger.info('Saving content type', this.get('model.id'));
this.set('isEditing', false);
this.validateControls();
if (this.get('model.controls').isAny('widgetIsValid', false)) {
Ember.Logger.info('The following controls are invalid:', this.get('model.controls').filterBy('widgetIsValid', false).getEach('name'));
return;
}
var formController = this;
var contentType = this.get('model');
// reset changedNameControls in case they backed out and decided to change the name back.
formController.set('changedNameControls', Ember.A([]));
// reset changedRadioControls in case they backed out and decided to change the values back
formController.set('changedRadioControls', Ember.A([]));
contentType.get('controls').forEach(function (control) {
// See if we changed any control names
if (control.get('originalName') && control.get('originalName') !== control.get('name')) {
formController.get('changedNameControls').addObject(control);
}
// See if we changed any radio values
if (control.get('controlType.widget') === 'radio') {
var changedRadioControls = null;
control.get('meta.data.options').getEach('value').forEach(function (value, index) {
var originalValue = control.get('originalOptions').objectAt(index);
if (originalValue && originalValue !== value) {
if (!changedRadioControls) {
changedRadioControls = Ember.Object.create({
name: control.get('name'),
values: Ember.Object.create()
});
}
changedRadioControls.get('values').set(originalValue, value);
}
});
if (changedRadioControls) {
formController.get('changedRadioControls').addObject(changedRadioControls);
}
}
// we don't want to store checkbox values to the db when we save
if (control.get('controlType.widget') === 'checkbox') {
control.get('meta.data.options').setEach('value', null);
}
// hax
// firebase doesn't like undefined values and for some reason `_super` is
// being added to arrays in ember with undefined value
if (Ember.isArray(control.get('meta.data.options'))) {
control.set('meta.data.options', control.get('meta.data.options').toArray());
Ember.run.sync();
delete control.get('meta.data.options').__nextSuper;
}
});
this.promptConfirmChanges();
},
addControl: function (controlType, index) {
this.addControl.apply(this, arguments);
},
deleteControl: function (control) {
if (this.get('addedControls').indexOf(control) >= 0) {
this.get('addedControls').removeObject(control);
} else {
this.get('removedControls').addObject(control);
}
control.set('justDeleted', true);
Ember.run.later(this, function () {
this.get('model.controls').removeObject(control);
}, 500);
this.set('editingControl', null);
this.send('stopEditing');
},
editControl: function (control) {
if (!control.get('meta')) {
control.set('meta', this.store.createRecord('meta-data', { data: {} }));
}
this.set('editingControl', control);
this.set('isEditing', true);
},
stopEditing: function () {
this.set('isEditing', false);
},
startEditing: function () {
this.send('editControl', this.get('editingControl') || this.get('model.controls.firstObject'));
},
addOption: function (array) {
array.pushObject({});
var control = this.get('editingControl');
if (control.get('controlType.widget') === 'tabular') {
control.get('value').forEach(function (row) {
row.pushObject("");
});
}
},
removeOption: function (array, option) {
var control = this.get('editingControl');
if (control.get('controlType.widget') === 'tabular') {
var optionIndex = array.indexOf(option);
control.get('value').forEach(function (row) {
row.removeAt(optionIndex);
});
}
array.removeObject(option);
},
quitForm: function () {
// changed your mind on a new contentType? BALEETED
if (this.get('model.isNew')) {
this.get('model').deleteRecord();
}
this.transitionToRoute('wh.content.all-types');
},
acknoledgeScaffolding: function () {
this.transitionToRoute('wh.content.type.index', this.get('model'));
},
forceScaffolding: function () {
window.ENV.sendGruntCommand('scaffolding_force:' + this.get('model.id'), function () {
this.send('notify', 'success', 'Scaffolding for ' + this.get('model.name') + ' built.');
}.bind(this));
this.transitionToRoute('wh.content.type.index', this.get('model'));
},
abortScaffolding: function () {
this.transitionToRoute('wh.content.type.index', this.get('model'));
},
confirmChangedControls: function () {
this.toggleProperty('confirmChangedControlsPrompt');
this.updateItems();
this.saveType();
},
rejectChangedControls: function () {
this.toggleProperty('confirmChangedControlsPrompt');
}
}
});
|
one off special case for data updates when changing control names
|
app/controllers/form.js
|
one off special case for data updates when changing control names
|
<ide><path>pp/controllers/form.js
<ide> var itemModelName = getItemModelName(contentType);
<ide>
<ide> Ember.Logger.info('Updating `' + itemModelName + '` item data and search indices for', removedControls.get('length'), 'removed controls,', changedNameControls.get('length'), 'renamed controls, and', changedRadioControls.get('length'), 'changed radio controls.');
<del> this.store.find(itemModelName).then(function (items) {
<del> items.forEach(function (item) {
<del> var itemData = item.get('data');
<del>
<del> changedNameControls.forEach(function (control) {
<del> itemData[control.get('name')] = itemData[control.get('originalName')] === undefined ? null : itemData[control.get('originalName')];
<del> itemData[control.get('originalName')] = null;
<del> });
<del>
<del> removedControls.forEach(function (control) {
<del> itemData[control.get('originalName')] = null;
<del> });
<del>
<del> changedRadioControls.forEach(function (control) {
<del> if (itemData[control.get('name')]) {
<del> itemData[control.get('name')] = control.get('values').get(itemData[control.get('name')]) ? control.get('values').get(itemData[control.get('name')]) : itemData[control.get('name')];
<del> }
<del> });
<del>
<del> item.set('data', itemData);
<del> item.save().then(function (savedItem) {
<del> Ember.Logger.info('Data updates applied to', savedItem.get('id'));
<del> SearchIndex.indexItem(savedItem, contentType);
<del> });
<del> });
<del> });
<add>
<add> var updateData = function (item) {
<add> var itemData = item.get('data');
<add>
<add> changedNameControls.forEach(function (control) {
<add> itemData[control.get('name')] = itemData[control.get('originalName')] === undefined ? null : itemData[control.get('originalName')];
<add> itemData[control.get('originalName')] = null;
<add> });
<add>
<add> removedControls.forEach(function (control) {
<add> itemData[control.get('originalName')] = null;
<add> });
<add>
<add> changedRadioControls.forEach(function (control) {
<add> if (itemData[control.get('name')]) {
<add> itemData[control.get('name')] = control.get('values').get(itemData[control.get('name')]) ? control.get('values').get(itemData[control.get('name')]) : itemData[control.get('name')];
<add> }
<add> });
<add>
<add> item.set('data', itemData);
<add> item.save().then(function (savedItem) {
<add> Ember.Logger.info('Data updates applied to', savedItem.get('id'));
<add> SearchIndex.indexItem(savedItem, contentType);
<add> });
<add> };
<add>
<add> if (contentType.get('oneOff')) {
<add> this.store.find(itemModelName, contentType.get('id')).then(function (item) {
<add> updateData(item);
<add> });
<add> } else {
<add> this.store.find(itemModelName).then(function (items) {
<add> items.forEach(function (item) {
<add> updateData(item);
<add> });
<add> });
<add> }
<ide>
<ide> },
<ide>
|
|
Java
|
apache-2.0
|
8f7515ba863d8416be55d1dadc1f05bb91f0539f
| 0 |
jskonst/PlatypusJS,AlexeyKashintsev/PlatypusJS,altsoft/PlatypusJS,marat-gainullin/PlatypusJS,altsoft/PlatypusJS,marat-gainullin/platypus-js,marat-gainullin/PlatypusJS,vadimv/PlatypusJS,marat-gainullin/platypus-js,AlexeyKashintsev/PlatypusJS,marat-gainullin/platypus-js,vadimv/PlatypusJS,marat-gainullin/PlatypusJS,vadimv/PlatypusJS,AlexeyKashintsev/PlatypusJS,altsoft/PlatypusJS,vadimv/PlatypusJS,jskonst/PlatypusJS,AlexeyKashintsev/PlatypusJS,jskonst/PlatypusJS,jskonst/PlatypusJS
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.eas.deploy;
import com.eas.client.DatabasesClient;
import com.eas.client.DbClient;
import com.eas.deploy.project.PlatypusSettings;
import com.eas.xml.dom.Source2XmlDom;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.w3c.dom.Document;
/**
*
* @author vv
*/
public class BaseDeployer {
public static final String PLATYPUS_SETTINGS_FILE = "platypus.xml";// NOI18N
public static final String COMMON_ENCODING_NAME = "utf-8";// NOI18N
protected static final String LOCKED_MSG = "Deployer is locked.";
protected File dir;
protected DbClient client;
protected File projectSettingsFile;
protected boolean silentMode;
protected PlatypusSettings settings;
protected PrintWriter out = new PrintWriter(System.out, true);
protected PrintWriter err = new PrintWriter(System.err, true);
protected boolean busy;
public BaseDeployer() {
}
public BaseDeployer(File aDir, DbClient aClient) {
if (!aDir.isDirectory()) {
throw new IllegalArgumentException("Target path is not for directory: " + aDir.getAbsolutePath()); // NOI18N
}
dir = aDir;
client = aClient;
projectSettingsFile = new File(dir, PLATYPUS_SETTINGS_FILE);
}
public BaseDeployer(String aDirPath) {
if (aDirPath == null) {
throw new NullPointerException("Target path is null"); // NOI18N
}
if (aDirPath.isEmpty()) {
throw new IllegalArgumentException("Target path is empty"); // NOI18N
}
dir = new File(aDirPath);
if (!dir.isDirectory()) {
throw new IllegalArgumentException("Target path is not for directory: " + dir.getAbsolutePath()); // NOI18N
}
projectSettingsFile = new File(dir, PLATYPUS_SETTINGS_FILE);
}
/**
* Sets default messages output
*
* @param anOut Print destination
*/
public void setOut(PrintWriter anOut) {
out = anOut;
}
/**
* Sets default error messages output
*
* @param anErr Print destination
*/
public void setErr(PrintWriter anErr) {
err = anErr;
}
public void setSilentMode(boolean silent) {
silentMode = silent;
}
public boolean isSilentMode(boolean silent) {
return silentMode;
}
public boolean isBusy() {
return busy;
}
protected void checkDbClient() throws DeployException {
if (client == null) {
client = createDbClient();
}
//Check database connection
if (client == null) {
throw new DeployException("Can't connect to database - check connection settings."); // NOI18N
}
}
private DbClient createDbClient() {
try {
checkSettings();
return new DatabasesClient(settings.getDbSettings());
} catch (Exception ex) {
Logger.getLogger(Deployer.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
protected void checkSettings() throws Exception {
if (settings == null) {
//Read project configuration
FileInputStream fstream = new FileInputStream(projectSettingsFile);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream, COMMON_ENCODING_NAME));
Document doc = Source2XmlDom.transform(br);
settings = PlatypusSettings.valueOf(doc);
}
}
}
|
application/src/components/PlatypusDeploy/src/com/eas/deploy/BaseDeployer.java
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.eas.deploy;
import com.eas.client.DatabasesClient;
import com.eas.client.DbClient;
import com.eas.deploy.project.PlatypusSettings;
import com.eas.xml.dom.Source2XmlDom;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.w3c.dom.Document;
/**
*
* @author vv
*/
public class BaseDeployer {
public static final String PLATYPUS_SETTINGS_FILE = "platypus.xml";// NOI18N
public static final String COMMON_ENCODING_NAME = "utf-8";// NOI18N
protected static final String LOCKED_MSG = "Deployer is locked.";
protected File dir;
protected DbClient client;
protected File projectSettingsFile;
protected boolean silentMode;
protected PlatypusSettings settings;
protected PrintWriter out = new PrintWriter(System.out, true);
protected PrintWriter err = new PrintWriter(System.err, true);
protected boolean busy;
public BaseDeployer() {
}
public BaseDeployer(File aDir, DbClient aClient) {
if (!aDir.isDirectory()) {
throw new IllegalArgumentException("Project path is not for directory: " + aDir.getAbsolutePath()); // NOI18N
}
dir = aDir;
client = aClient;
projectSettingsFile = new File(dir, PLATYPUS_SETTINGS_FILE);
}
public BaseDeployer(String aDirPath) {
if (aDirPath == null) {
throw new NullPointerException("Target path is null"); // NOI18N
}
if (aDirPath.isEmpty()) {
throw new IllegalArgumentException("Target path is empty"); // NOI18N
}
dir = new File(aDirPath);
if (!dir.isDirectory()) {
throw new IllegalArgumentException("Target path is not for directory: " + dir.getAbsolutePath()); // NOI18N
}
projectSettingsFile = new File(dir, PLATYPUS_SETTINGS_FILE);
}
/**
* Sets default messages output
*
* @param anOut Print destination
*/
public void setOut(PrintWriter anOut) {
out = anOut;
}
/**
* Sets default error messages output
*
* @param anErr Print destination
*/
public void setErr(PrintWriter anErr) {
err = anErr;
}
public void setSilentMode(boolean silent) {
silentMode = silent;
}
public boolean isSilentMode(boolean silent) {
return silentMode;
}
public boolean isBusy() {
return busy;
}
protected void checkDbClient() throws DeployException {
if (client == null) {
client = createDbClient();
}
//Check database connection
if (client == null) {
throw new DeployException("Can't connect to database - check connection settings."); // NOI18N
}
}
private DbClient createDbClient() {
try {
checkSettings();
return new DatabasesClient(settings.getDbSettings());
} catch (Exception ex) {
Logger.getLogger(Deployer.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
protected void checkSettings() throws Exception {
if (settings == null) {
//Read project configuration
FileInputStream fstream = new FileInputStream(projectSettingsFile);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream, COMMON_ENCODING_NAME));
Document doc = Source2XmlDom.transform(br);
settings = PlatypusSettings.valueOf(doc);
}
}
}
|
Migrator target directory changed.
|
application/src/components/PlatypusDeploy/src/com/eas/deploy/BaseDeployer.java
|
Migrator target directory changed.
|
<ide><path>pplication/src/components/PlatypusDeploy/src/com/eas/deploy/BaseDeployer.java
<ide>
<ide> public BaseDeployer(File aDir, DbClient aClient) {
<ide> if (!aDir.isDirectory()) {
<del> throw new IllegalArgumentException("Project path is not for directory: " + aDir.getAbsolutePath()); // NOI18N
<add> throw new IllegalArgumentException("Target path is not for directory: " + aDir.getAbsolutePath()); // NOI18N
<ide> }
<ide> dir = aDir;
<ide> client = aClient;
|
|
Java
|
lgpl-2.1
|
4ead4890a18b61cbf1d863d45bcf4e2661096fb3
| 0 |
emckee2006/biojava,biojava/biojava,emckee2006/biojava,biojava/biojava,heuermh/biojava,heuermh/biojava,sbliven/biojava-sbliven,sbliven/biojava-sbliven,biojava/biojava,sbliven/biojava-sbliven,emckee2006/biojava,heuermh/biojava
|
/*
* BioJava development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
*/
package org.biojava.nbio.core.sequence.io;
import org.biojava.nbio.core.exceptions.CompoundNotFoundException;
import org.biojava.nbio.core.sequence.DNASequence;
import org.biojava.nbio.core.sequence.ProteinSequence;
import org.biojava.nbio.core.sequence.RNASequence;
import org.biojava.nbio.core.sequence.Strand;
import org.biojava.nbio.core.sequence.compound.*;
import org.biojava.nbio.core.sequence.features.FeatureInterface;
import org.biojava.nbio.core.sequence.features.Qualifier;
import org.biojava.nbio.core.sequence.location.template.AbstractLocation;
import org.biojava.nbio.core.sequence.template.AbstractSequence;
import org.junit.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
/**
*
* @author Scooter Willis <willishf at gmail dot com>
* @author Jacek Grzebyta
* @author Philippe Soares
*/
public class GenbankReaderTest {
private final static Logger logger = LoggerFactory.getLogger(GenbankReaderTest.class);
public GenbankReaderTest() {
}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of process method, of class GenbankReader.
*/
@Test
public void testProcess() throws Exception {
logger.info("process protein");
InputStream inStream = this.getClass().getResourceAsStream("/BondFeature.gb");
assertNotNull(inStream);
GenbankReader<ProteinSequence, AminoAcidCompound> genbankProtein
= new GenbankReader<>(
inStream,
new GenericGenbankHeaderParser<>(),
new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet())
);
LinkedHashMap<String, ProteinSequence> proteinSequences = genbankProtein.process();
assertThat(proteinSequences.get("NP_000257").getComments().get(0),is(
"VALIDATED REFSEQ: This record has undergone validation or\n" +
"preliminary review. The reference sequence was derived from\n" +
"AL034370.1, X65882.1 and BE139596.1.\n" +
"Summary: NDP is the genetic locus identified as harboring mutations\n" +
"that result in Norrie disease. Norrie disease is a rare genetic\n" +
"disorder characterized by bilateral congenital blindness that is\n" +
"caused by a vascularized mass behind each lens due to a\n" +
"maldeveloped retina (pseudoglioma).\n" +
"Publication Note: This RefSeq record includes a subset of the\n" +
"publications that are available for this gene. Please see the\n" +
"Entrez Gene record to access additional publications."));
assertThat(proteinSequences.get("NP_000257").getReferences().size(),is(11));
assertThat(proteinSequences.get("NP_000257").getReferences().get(0).getAuthors(),
is("Lev,D., Weigl,Y., Hasan,M., Gak,E., Davidovich,M., Vinkler,C.,\n" +
"Leshinsky-Silver,E., Lerman-Sagie,T. and Watemberg,N."));
assertThat(proteinSequences.get("NP_000257").getReferences().get(1).getTitle(),
is("Novel mutations in Norrie disease gene in Japanese patients with\n" +
"Norrie disease and familial exudative vitreoretinopathy"));
assertThat(proteinSequences.get("NP_000257").getReferences().get(10).getJournal(),
is("Nat. Genet. 1 (3), 199-203 (1992)"));
assertNotNull(proteinSequences);
assertEquals(1, proteinSequences.size());
ProteinSequence proteinSequence = proteinSequences.get("NP_000257");
assertNotNull(proteinSequences.get("NP_000257"));
assertEquals("NP_000257", proteinSequence.getAccession().getID());
assertEquals("4557789", proteinSequence.getAccession().getIdentifier());
assertEquals("GENBANK", proteinSequence.getAccession().getDataSource().name());
assertEquals(1, proteinSequence.getAccession().getVersion().intValue());
assertTrue(genbankProtein.isClosed());
logger.info("process DNA");
inStream = this.getClass().getResourceAsStream("/NM_000266.gb");
assertNotNull(inStream);
GenbankReader<DNASequence, NucleotideCompound> genbankDNA
= new GenbankReader<>(
inStream,
new GenericGenbankHeaderParser<>(),
new DNASequenceCreator(DNACompoundSet.getDNACompoundSet())
);
LinkedHashMap<String, DNASequence> dnaSequences = genbankDNA.process();
assertNotNull(dnaSequences);
assertEquals(1, dnaSequences.size());
DNASequence dnaSequence = dnaSequences.get("NM_000266");
assertNotNull(dnaSequences.get("NM_000266"));
assertEquals("NM_000266", dnaSequence.getAccession().getID());
assertEquals("223671892", dnaSequence.getAccession().getIdentifier());
assertEquals("GENBANK", dnaSequence.getAccession().getDataSource().name());
assertEquals(3, dnaSequence.getAccession().getVersion().intValue());
assertTrue(genbankDNA.isClosed());
}
/**
* Test the process method with a number of sequences to be read at each call.
* The underlying {@link InputStream} should remain open until the last call.
*/
@Test
public void testPartialProcess() throws IOException, CompoundNotFoundException {
CheckableInputStream inStream = new CheckableInputStream(this.getClass().getResourceAsStream("/two-dnaseqs.gb"));
GenbankReader<DNASequence, NucleotideCompound> genbankDNA
= new GenbankReader<>(
inStream,
new GenericGenbankHeaderParser<>(),
new DNASequenceCreator(DNACompoundSet.getDNACompoundSet())
);
// First call to process(1) returns the first sequence
LinkedHashMap<String, DNASequence> dnaSequences = genbankDNA.process(1);
assertFalse(inStream.isclosed());
assertNotNull(dnaSequences);
assertEquals(1, dnaSequences.size());
assertNotNull(dnaSequences.get("vPetite"));
// Second call to process(1) returns the second sequence
dnaSequences = genbankDNA.process(1);
assertFalse(inStream.isclosed());
assertNotNull(dnaSequences);
assertEquals(1, dnaSequences.size());
assertNotNull(dnaSequences.get("sbFDR"));
assertFalse(genbankDNA.isClosed());
genbankDNA.close();
assertTrue(genbankDNA.isClosed());
assertTrue(inStream.isclosed());
}
@Test
public void CDStest() throws Exception {
logger.info("CDS Test");
CheckableInputStream inStream = new CheckableInputStream(this.getClass().getResourceAsStream("/BondFeature.gb"));
assertNotNull(inStream);
GenbankReader<ProteinSequence, AminoAcidCompound> GenbankProtein
= new GenbankReader<>(
inStream,
new GenericGenbankHeaderParser<>(),
new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet())
);
LinkedHashMap<String, ProteinSequence> proteinSequences = GenbankProtein.process();
assertTrue(inStream.isclosed());
Assert.assertTrue(proteinSequences.size() == 1);
logger.debug("protein sequences: {}", proteinSequences);
ProteinSequence protein = new ArrayList<>(proteinSequences.values()).get(0);
FeatureInterface<AbstractSequence<AminoAcidCompound>, AminoAcidCompound> cdsFeature = protein.getFeaturesByType("CDS").get(0);
String codedBy = cdsFeature.getQualifiers().get("coded_by").get(0).getValue();
Map<String, List<Qualifier>> quals = cdsFeature.getQualifiers();
List<Qualifier> dbrefs = quals.get("db_xref");
Assert.assertNotNull(codedBy);
Assert.assertTrue(!codedBy.isEmpty());
assertEquals("NM_000266.2:503..904", codedBy);
assertEquals(5, dbrefs.size());
}
private DNASequence readGenbankResource(final String resource) throws IOException, CompoundNotFoundException {
InputStream inputStream = getClass().getResourceAsStream(resource);
GenbankReader<DNASequence, NucleotideCompound> genbankDNA
= new GenbankReader<>(
inputStream,
new GenericGenbankHeaderParser<>(),
new DNASequenceCreator(DNACompoundSet.getDNACompoundSet())
);
LinkedHashMap<String, DNASequence> dnaSequences = genbankDNA.process();
return dnaSequences.values().iterator().next();
}
private RNASequence readGenbankRNAResource(final String resource) throws IOException, CompoundNotFoundException {
InputStream inputStream = getClass().getResourceAsStream(resource);
GenbankReader<RNASequence, NucleotideCompound> genbankRNA
= new GenbankReader<>(
inputStream,
new GenericGenbankHeaderParser<>(),
new RNASequenceCreator(RNACompoundSet.getRNACompoundSet())
);
LinkedHashMap<String, RNASequence> rnaSequences = genbankRNA.process();
return rnaSequences.values().iterator().next();
}
private ProteinSequence readGenbankProteinResource(final String resource) throws IOException, CompoundNotFoundException {
InputStream inputStream = getClass().getResourceAsStream(resource);
GenbankReader<ProteinSequence, AminoAcidCompound> genbankProtein
= new GenbankReader<>(
inputStream,
new GenericGenbankHeaderParser<>(),
new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet())
);
LinkedHashMap<String, ProteinSequence> proteinSequences = genbankProtein.process();
return proteinSequences.values().iterator().next();
}
private AbstractSequence<?> readUnknownGenbankResource(final String resource) throws IOException, CompoundNotFoundException {
InputStream inputStream = getClass().getResourceAsStream(resource);
GenbankSequenceParser genbankParser = new GenbankSequenceParser();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String seqString = genbankParser.getSequence(bufferedReader, 0);
String compoundSet = genbankParser.getCompoundType().getClass().getSimpleName();
if (compoundSet.equals("AminoAcidCompoundSet")) {
return readGenbankProteinResource(resource);
} else if (compoundSet.equals("RNACompoundSet")) {
return readGenbankRNAResource(resource);
} else {
return readGenbankResource(resource);
}
}
@Test
public void testNcbiExpandedAccessionFormats() throws IOException, CompoundNotFoundException {
DNASequence header0 = readGenbankResource("/empty_header0.gb");
assertEquals("CP032762 5868661 bp DNA circular BCT 15-OCT-2018", header0.getOriginalHeader());
DNASequence header1 = readGenbankResource("/empty_header1.gb");
assertEquals("AZZZAA02123456789 9999999999 bp DNA linear PRI 15-OCT-2018", header1.getOriginalHeader());
DNASequence header2 = readGenbankResource("/empty_header2.gb");
assertEquals("AZZZAA02123456789 10000000000 bp DNA linear PRI 15-OCT-2018", header2.getOriginalHeader());
}
@Test
public void testLegacyLocusCompatable() throws IOException, CompoundNotFoundException {
// Testing opening a genbank file with uppercase units, strand and topology
AbstractSequence header0 = readUnknownGenbankResource("/org/biojava/nbio/core/sequence/io/uppercase_locus0.gb");
assertEquals("ABC12.3_DE 7071 BP DS-DNA CIRCULAR SYN 22-JUL-1994", header0.getOriginalHeader());
assertEquals("ABC12.3_DE", header0.getAccession().getID());
assertEquals("DNACompoundSet", header0.getCompoundSet().getClass().getSimpleName());
// Testing uppercase SS strand
AbstractSequence header1 = readUnknownGenbankResource("/org/biojava/nbio/core/sequence/io//uppercase_locus1.gb");
assertEquals("ABC12.3_DE 7071 BP SS-DNA CIRCULAR SYN 13-JUL-1994", header1.getOriginalHeader());
assertEquals("ABC12.3_DE", header1.getAccession().getID());
assertEquals("DNACompoundSet", header0.getCompoundSet().getClass().getSimpleName());
// Testing uppercase MS strand
AbstractSequence header2 = readUnknownGenbankResource("/org/biojava/nbio/core/sequence/io//uppercase_locus2.gb");
assertEquals("ABC12.3_DE 7071 BP MS-DNA CIRCULAR SYN 13-JUL-1994", header2.getOriginalHeader());
assertEquals("ABC12.3_DE", header2.getAccession().getID());
assertEquals("DNACompoundSet", header0.getCompoundSet().getClass().getSimpleName());
// Testing uppercase LINEAR topology
AbstractSequence header3 = readUnknownGenbankResource("/org/biojava/nbio/core/sequence/io//uppercase_locus3.gb");
assertEquals("ABC12.3_DE 7071 BP DNA LINEAR SYN 22-JUL-1994", header3.getOriginalHeader());
assertEquals("ABC12.3_DE", header3.getAccession().getID());
assertEquals("DNACompoundSet", header0.getCompoundSet().getClass().getSimpleName());
// Testing uppercase units with no strand or topology
AbstractSequence header4 = readUnknownGenbankResource("/org/biojava/nbio/core/sequence/io//uppercase_locus4.gb");
assertEquals("ABC12.3_DE 7071 BP RNA SYN 13-JUL-1994", header4.getOriginalHeader());
assertEquals("ABC12.3_DE", header4.getAccession().getID());
assertEquals("RNACompoundSet", header4.getCompoundSet().getClass().getSimpleName());
// Testing uppercase units with no strand, topology, division or date
AbstractSequence header5 = readUnknownGenbankResource("/org/biojava/nbio/core/sequence/io//uppercase_locus5.gb");
assertEquals("ABC12.3_DE 7071 BP DNA", header5.getOriginalHeader());
assertEquals("ABC12.3_DE", header5.getAccession().getID());
// Testing uppercase units with no strand, molecule type, topology, division or date
AbstractSequence header6 = readUnknownGenbankResource("/org/biojava/nbio/core/sequence/io//uppercase_locus6.gb");
assertEquals("ABC12.3_DE 7071 BP", header6.getOriginalHeader());
assertEquals("ABC12.3_DE", header6.getAccession().getID());
assertEquals("DNACompoundSet", header0.getCompoundSet().getClass().getSimpleName());
// Testing uppercase protein units
AbstractSequence header7 = readUnknownGenbankResource("/org/biojava/nbio/core/sequence/io//uppercase_locus7.gb");
assertEquals("ABC12.3_DE 7071 AA Protein", header7.getOriginalHeader());
assertEquals("ABC12.3_DE", header7.getAccession().getID());
assertEquals("AminoAcidCompoundSet", header7.getCompoundSet().getClass().getSimpleName());
}
@Test
public void readSequenceWithZeroSpanFeature() throws IOException, CompoundNotFoundException {
logger.info("make or read genbank file error when feature spans zero point of circular sequence (issue #855)");
final DNASequence seq = readGenbankResource("/feature-spans-zero-point-circular-sequence.gb");
assertNotNull(seq);
final FeatureInterface<AbstractSequence<NucleotideCompound>, NucleotideCompound> f = seq.getFeatures().get(33);
final AbstractLocation fLocation = f.getLocations();
assertEquals(true, fLocation.isCircular());
assertEquals(7028, (int)fLocation.getStart().getPosition());
assertEquals(286, (int)fLocation.getEnd().getPosition());
assertEquals(Strand.NEGATIVE, fLocation.getStrand());
}
/**
* Helper class to be able to verify the closed state of the input stream.
*/
private class CheckableInputStream extends BufferedInputStream {
private boolean closed;
CheckableInputStream(InputStream in) {
super(in);
closed = false;
}
@Override
public void close() throws IOException {
super.close();
closed = true;
}
boolean isclosed() {
return closed;
}
}
}
|
biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/GenbankReaderTest.java
|
/*
* BioJava development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
*/
package org.biojava.nbio.core.sequence.io;
import org.biojava.nbio.core.exceptions.CompoundNotFoundException;
import org.biojava.nbio.core.sequence.DNASequence;
import org.biojava.nbio.core.sequence.ProteinSequence;
import org.biojava.nbio.core.sequence.RNASequence;
import org.biojava.nbio.core.sequence.Strand;
import org.biojava.nbio.core.sequence.compound.*;
import org.biojava.nbio.core.sequence.features.FeatureInterface;
import org.biojava.nbio.core.sequence.features.Qualifier;
import org.biojava.nbio.core.sequence.location.template.AbstractLocation;
import org.biojava.nbio.core.sequence.template.AbstractSequence;
import org.junit.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
/**
*
* @author Scooter Willis <willishf at gmail dot com>
* @author Jacek Grzebyta
* @author Philippe Soares
*/
public class GenbankReaderTest {
private final static Logger logger = LoggerFactory.getLogger(GenbankReaderTest.class);
public GenbankReaderTest() {
}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of process method, of class GenbankReader.
*/
@Test
public void testProcess() throws Exception {
logger.info("process protein");
InputStream inStream = this.getClass().getResourceAsStream("/BondFeature.gb");
assertNotNull(inStream);
GenbankReader<ProteinSequence, AminoAcidCompound> genbankProtein
= new GenbankReader<>(
inStream,
new GenericGenbankHeaderParser<>(),
new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet())
);
LinkedHashMap<String, ProteinSequence> proteinSequences = genbankProtein.process();
assertThat(proteinSequences.get("NP_000257").getComments().get(0),is(
"VALIDATED REFSEQ: This record has undergone validation or\n" +
"preliminary review. The reference sequence was derived from\n" +
"AL034370.1, X65882.1 and BE139596.1.\n" +
"Summary: NDP is the genetic locus identified as harboring mutations\n" +
"that result in Norrie disease. Norrie disease is a rare genetic\n" +
"disorder characterized by bilateral congenital blindness that is\n" +
"caused by a vascularized mass behind each lens due to a\n" +
"maldeveloped retina (pseudoglioma).\n" +
"Publication Note: This RefSeq record includes a subset of the\n" +
"publications that are available for this gene. Please see the\n" +
"Entrez Gene record to access additional publications."));
assertThat(proteinSequences.get("NP_000257").getReferences().size(),is(11));
assertThat(proteinSequences.get("NP_000257").getReferences().get(0).getAuthors(),
is("Lev,D., Weigl,Y., Hasan,M., Gak,E., Davidovich,M., Vinkler,C.,\n" +
"Leshinsky-Silver,E., Lerman-Sagie,T. and Watemberg,N."));
assertThat(proteinSequences.get("NP_000257").getReferences().get(1).getTitle(),
is("Novel mutations in Norrie disease gene in Japanese patients with\n" +
"Norrie disease and familial exudative vitreoretinopathy"));
assertThat(proteinSequences.get("NP_000257").getReferences().get(10).getJournal(),
is("Nat. Genet. 1 (3), 199-203 (1992)"));
assertNotNull(proteinSequences);
assertEquals(1, proteinSequences.size());
ProteinSequence proteinSequence = proteinSequences.get("NP_000257");
assertNotNull(proteinSequences.get("NP_000257"));
assertEquals("NP_000257", proteinSequence.getAccession().getID());
assertEquals("4557789", proteinSequence.getAccession().getIdentifier());
assertEquals("GENBANK", proteinSequence.getAccession().getDataSource().name());
assertEquals(1, proteinSequence.getAccession().getVersion().intValue());
assertTrue(genbankProtein.isClosed());
logger.info("process DNA");
inStream = this.getClass().getResourceAsStream("/NM_000266.gb");
assertNotNull(inStream);
GenbankReader<DNASequence, NucleotideCompound> genbankDNA
= new GenbankReader<>(
inStream,
new GenericGenbankHeaderParser<>(),
new DNASequenceCreator(DNACompoundSet.getDNACompoundSet())
);
LinkedHashMap<String, DNASequence> dnaSequences = genbankDNA.process();
assertNotNull(dnaSequences);
assertEquals(1, dnaSequences.size());
DNASequence dnaSequence = dnaSequences.get("NM_000266");
assertNotNull(dnaSequences.get("NM_000266"));
assertEquals("NM_000266", dnaSequence.getAccession().getID());
assertEquals("223671892", dnaSequence.getAccession().getIdentifier());
assertEquals("GENBANK", dnaSequence.getAccession().getDataSource().name());
assertEquals(3, dnaSequence.getAccession().getVersion().intValue());
assertTrue(genbankDNA.isClosed());
}
/**
* Test the process method with a number of sequences to be read at each call.
* The underlying {@link InputStream} should remain open until the last call.
*/
@Test
public void testPartialProcess() throws IOException, CompoundNotFoundException, NoSuchFieldException {
CheckableInputStream inStream = new CheckableInputStream(this.getClass().getResourceAsStream("/two-dnaseqs.gb"));
GenbankReader<DNASequence, NucleotideCompound> genbankDNA
= new GenbankReader<>(
inStream,
new GenericGenbankHeaderParser<>(),
new DNASequenceCreator(DNACompoundSet.getDNACompoundSet())
);
// First call to process(1) returns the first sequence
LinkedHashMap<String, DNASequence> dnaSequences = genbankDNA.process(1);
assertFalse(inStream.isclosed());
assertNotNull(dnaSequences);
assertEquals(1, dnaSequences.size());
assertNotNull(dnaSequences.get("vPetite"));
// Second call to process(1) returns the second sequence
dnaSequences = genbankDNA.process(1);
assertFalse(inStream.isclosed());
assertNotNull(dnaSequences);
assertEquals(1, dnaSequences.size());
assertNotNull(dnaSequences.get("sbFDR"));
assertFalse(genbankDNA.isClosed());
genbankDNA.close();
assertTrue(genbankDNA.isClosed());
assertTrue(inStream.isclosed());
}
@Test
public void CDStest() throws Exception {
logger.info("CDS Test");
CheckableInputStream inStream = new CheckableInputStream(this.getClass().getResourceAsStream("/BondFeature.gb"));
assertNotNull(inStream);
GenbankReader<ProteinSequence, AminoAcidCompound> GenbankProtein
= new GenbankReader<>(
inStream,
new GenericGenbankHeaderParser<>(),
new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet())
);
LinkedHashMap<String, ProteinSequence> proteinSequences = GenbankProtein.process();
assertTrue(inStream.isclosed());
Assert.assertTrue(proteinSequences.size() == 1);
logger.debug("protein sequences: {}", proteinSequences);
ProteinSequence protein = new ArrayList<>(proteinSequences.values()).get(0);
FeatureInterface<AbstractSequence<AminoAcidCompound>, AminoAcidCompound> cdsFeature = protein.getFeaturesByType("CDS").get(0);
String codedBy = cdsFeature.getQualifiers().get("coded_by").get(0).getValue();
Map<String, List<Qualifier>> quals = cdsFeature.getQualifiers();
List<Qualifier> dbrefs = quals.get("db_xref");
Assert.assertNotNull(codedBy);
Assert.assertTrue(!codedBy.isEmpty());
assertEquals("NM_000266.2:503..904", codedBy);
assertEquals(5, dbrefs.size());
}
private DNASequence readGenbankResource(final String resource) throws IOException, CompoundNotFoundException {
InputStream inputStream = getClass().getResourceAsStream(resource);
GenbankReader<DNASequence, NucleotideCompound> genbankDNA
= new GenbankReader<>(
inputStream,
new GenericGenbankHeaderParser<>(),
new DNASequenceCreator(DNACompoundSet.getDNACompoundSet())
);
LinkedHashMap<String, DNASequence> dnaSequences = genbankDNA.process();
return dnaSequences.values().iterator().next();
}
private RNASequence readGenbankRNAResource(final String resource) throws IOException, CompoundNotFoundException {
InputStream inputStream = getClass().getResourceAsStream(resource);
GenbankReader<RNASequence, NucleotideCompound> genbankRNA
= new GenbankReader<>(
inputStream,
new GenericGenbankHeaderParser<>(),
new RNASequenceCreator(RNACompoundSet.getRNACompoundSet())
);
LinkedHashMap<String, RNASequence> rnaSequences = genbankRNA.process();
return rnaSequences.values().iterator().next();
}
private ProteinSequence readGenbankProteinResource(final String resource) throws IOException, CompoundNotFoundException {
InputStream inputStream = getClass().getResourceAsStream(resource);
GenbankReader<ProteinSequence, AminoAcidCompound> genbankProtein
= new GenbankReader<>(
inputStream,
new GenericGenbankHeaderParser<>(),
new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet())
);
LinkedHashMap<String, ProteinSequence> proteinSequences = genbankProtein.process();
return proteinSequences.values().iterator().next();
}
private AbstractSequence<?> readUnknownGenbankResource(final String resource) throws IOException, CompoundNotFoundException {
InputStream inputStream = getClass().getResourceAsStream(resource);
GenbankSequenceParser genbankParser = new GenbankSequenceParser();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String seqString = genbankParser.getSequence(bufferedReader, 0);
String compoundSet = genbankParser.getCompoundType().getClass().getSimpleName();
if (compoundSet.equals("AminoAcidCompoundSet")) {
return readGenbankProteinResource(resource);
} else if (compoundSet.equals("RNACompoundSet")) {
return readGenbankRNAResource(resource);
} else {
return readGenbankResource(resource);
}
}
@Test
public void testNcbiExpandedAccessionFormats() throws IOException, CompoundNotFoundException {
DNASequence header0 = readGenbankResource("/empty_header0.gb");
assertEquals("CP032762 5868661 bp DNA circular BCT 15-OCT-2018", header0.getOriginalHeader());
DNASequence header1 = readGenbankResource("/empty_header1.gb");
assertEquals("AZZZAA02123456789 9999999999 bp DNA linear PRI 15-OCT-2018", header1.getOriginalHeader());
DNASequence header2 = readGenbankResource("/empty_header2.gb");
assertEquals("AZZZAA02123456789 10000000000 bp DNA linear PRI 15-OCT-2018", header2.getOriginalHeader());
}
@Test
public void testLegacyLocusCompatable() throws IOException, CompoundNotFoundException {
// Testing opening a genbank file with uppercase units, strand and topology
AbstractSequence header0 = readUnknownGenbankResource("/org/biojava/nbio/core/sequence/io/uppercase_locus0.gb");
assertEquals("ABC12.3_DE 7071 BP DS-DNA CIRCULAR SYN 22-JUL-1994", header0.getOriginalHeader());
assertEquals("ABC12.3_DE", header0.getAccession().getID());
assertEquals("DNACompoundSet", header0.getCompoundSet().getClass().getSimpleName());
// Testing uppercase SS strand
AbstractSequence header1 = readUnknownGenbankResource("/org/biojava/nbio/core/sequence/io//uppercase_locus1.gb");
assertEquals("ABC12.3_DE 7071 BP SS-DNA CIRCULAR SYN 13-JUL-1994", header1.getOriginalHeader());
assertEquals("ABC12.3_DE", header1.getAccession().getID());
assertEquals("DNACompoundSet", header0.getCompoundSet().getClass().getSimpleName());
// Testing uppercase MS strand
AbstractSequence header2 = readUnknownGenbankResource("/org/biojava/nbio/core/sequence/io//uppercase_locus2.gb");
assertEquals("ABC12.3_DE 7071 BP MS-DNA CIRCULAR SYN 13-JUL-1994", header2.getOriginalHeader());
assertEquals("ABC12.3_DE", header2.getAccession().getID());
assertEquals("DNACompoundSet", header0.getCompoundSet().getClass().getSimpleName());
// Testing uppercase LINEAR topology
AbstractSequence header3 = readUnknownGenbankResource("/org/biojava/nbio/core/sequence/io//uppercase_locus3.gb");
assertEquals("ABC12.3_DE 7071 BP DNA LINEAR SYN 22-JUL-1994", header3.getOriginalHeader());
assertEquals("ABC12.3_DE", header3.getAccession().getID());
assertEquals("DNACompoundSet", header0.getCompoundSet().getClass().getSimpleName());
// Testing uppercase units with no strand or topology
AbstractSequence header4 = readUnknownGenbankResource("/org/biojava/nbio/core/sequence/io//uppercase_locus4.gb");
assertEquals("ABC12.3_DE 7071 BP RNA SYN 13-JUL-1994", header4.getOriginalHeader());
assertEquals("ABC12.3_DE", header4.getAccession().getID());
assertEquals("RNACompoundSet", header4.getCompoundSet().getClass().getSimpleName());
// Testing uppercase units with no strand, topology, division or date
AbstractSequence header5 = readUnknownGenbankResource("/org/biojava/nbio/core/sequence/io//uppercase_locus5.gb");
assertEquals("ABC12.3_DE 7071 BP DNA", header5.getOriginalHeader());
assertEquals("ABC12.3_DE", header5.getAccession().getID());
// Testing uppercase units with no strand, molecule type, topology, division or date
AbstractSequence header6 = readUnknownGenbankResource("/org/biojava/nbio/core/sequence/io//uppercase_locus6.gb");
assertEquals("ABC12.3_DE 7071 BP", header6.getOriginalHeader());
assertEquals("ABC12.3_DE", header6.getAccession().getID());
assertEquals("DNACompoundSet", header0.getCompoundSet().getClass().getSimpleName());
// Testing uppercase protein units
AbstractSequence header7 = readUnknownGenbankResource("/org/biojava/nbio/core/sequence/io//uppercase_locus7.gb");
assertEquals("ABC12.3_DE 7071 AA Protein", header7.getOriginalHeader());
assertEquals("ABC12.3_DE", header7.getAccession().getID());
assertEquals("AminoAcidCompoundSet", header7.getCompoundSet().getClass().getSimpleName());
}
@Test
public void readSequenceWithZeroSpanFeature() throws IOException, CompoundNotFoundException {
logger.info("make or read genbank file error when feature spans zero point of circular sequence (issue #855)");
final DNASequence seq = readGenbankResource("/feature-spans-zero-point-circular-sequence.gb");
assertNotNull(seq);
final FeatureInterface<AbstractSequence<NucleotideCompound>, NucleotideCompound> f = seq.getFeatures().get(33);
final AbstractLocation fLocation = f.getLocations();
assertEquals(true, fLocation.isCircular());
assertEquals(7028, (int)fLocation.getStart().getPosition());
assertEquals(286, (int)fLocation.getEnd().getPosition());
assertEquals(Strand.NEGATIVE, fLocation.getStrand());
}
/**
* Helper class to be able to verify the closed state of the input stream.
*/
private class CheckableInputStream extends BufferedInputStream {
private boolean closed;
CheckableInputStream(InputStream in) {
super(in);
closed = false;
}
@Override
public void close() throws IOException {
super.close();
closed = true;
}
boolean isclosed() {
return closed;
}
}
}
|
deleted unneeded Exception
|
biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/GenbankReaderTest.java
|
deleted unneeded Exception
|
<ide><path>iojava-core/src/test/java/org/biojava/nbio/core/sequence/io/GenbankReaderTest.java
<ide> * The underlying {@link InputStream} should remain open until the last call.
<ide> */
<ide> @Test
<del> public void testPartialProcess() throws IOException, CompoundNotFoundException, NoSuchFieldException {
<add> public void testPartialProcess() throws IOException, CompoundNotFoundException {
<ide> CheckableInputStream inStream = new CheckableInputStream(this.getClass().getResourceAsStream("/two-dnaseqs.gb"));
<ide>
<ide> GenbankReader<DNASequence, NucleotideCompound> genbankDNA
|
|
Java
|
apache-2.0
|
ed5a90727342ea61e099ff413eefc2e843f9f6b2
| 0 |
asedunov/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,ibinti/intellij-community,xfournet/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,da1z/intellij-community,xfournet/intellij-community,allotria/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,suncycheng/intellij-community,allotria/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,da1z/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,apixandru/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,apixandru/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,allotria/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,da1z/intellij-community,da1z/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,apixandru/intellij-community,da1z/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,da1z/intellij-community,allotria/intellij-community,da1z/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,apixandru/intellij-community,da1z/intellij-community,xfournet/intellij-community,ibinti/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,allotria/intellij-community,allotria/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,ibinti/intellij-community,ibinti/intellij-community,xfournet/intellij-community,apixandru/intellij-community,asedunov/intellij-community,allotria/intellij-community,asedunov/intellij-community,apixandru/intellij-community,da1z/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,allotria/intellij-community,da1z/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,allotria/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,xfournet/intellij-community,vvv1559/intellij-community
|
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testFramework;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.application.RunResult;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.module.ModifiableModuleModel;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.module.ModuleType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.projectRoots.SdkModificator;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.roots.impl.ContentEntryImpl;
import com.intellij.openapi.roots.impl.libraries.ProjectLibraryTable;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.roots.libraries.LibraryTable;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.*;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileFactory;
import com.intellij.psi.impl.DebugUtil;
import com.intellij.psi.impl.source.PsiFileImpl;
import com.intellij.psi.stubs.StubTree;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.model.JpsElement;
import org.jetbrains.jps.model.java.JavaSourceRootType;
import org.jetbrains.jps.model.module.JpsModuleSourceRootType;
import org.junit.Assert;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class PsiTestUtil {
public static VirtualFile createTestProjectStructure(Project project,
Module module,
String rootPath,
Collection<File> filesToDelete) throws Exception {
return createTestProjectStructure(project, module, rootPath, filesToDelete, true);
}
public static VirtualFile createTestProjectStructure(Project project, Module module, Collection<File> filesToDelete) throws IOException {
return createTestProjectStructure(project, module, null, filesToDelete, true);
}
public static VirtualFile createTestProjectStructure(Project project,
Module module,
String rootPath,
Collection<File> filesToDelete,
boolean addProjectRoots) throws IOException {
VirtualFile vDir = createTestProjectStructure(module, rootPath, filesToDelete, addProjectRoots);
PsiDocumentManager.getInstance(project).commitAllDocuments();
return vDir;
}
public static VirtualFile createTestProjectStructure(Module module,
String rootPath,
Collection<File> filesToDelete,
boolean addProjectRoots) throws IOException {
return createTestProjectStructure("unitTest", module, rootPath, filesToDelete, addProjectRoots);
}
public static VirtualFile createTestProjectStructure(String tempName,
Module module,
String rootPath,
Collection<File> filesToDelete,
boolean addProjectRoots) throws IOException {
File dir = FileUtil.createTempDirectory(tempName, null, false);
filesToDelete.add(dir);
VirtualFile vDir = LocalFileSystem.getInstance().refreshAndFindFileByPath(dir.getCanonicalPath().replace(File.separatorChar, '/'));
assert vDir != null && vDir.isDirectory() : dir;
PlatformTestCase.synchronizeTempDirVfs(vDir);
EdtTestUtil.runInEdtAndWait(() -> {
WriteAction.run(() -> {
if (rootPath != null) {
VirtualFile vDir1 = LocalFileSystem.getInstance().findFileByPath(rootPath.replace(File.separatorChar, '/'));
if (vDir1 == null) {
throw new Exception(rootPath + " not found");
}
VfsUtil.copyDirectory(null, vDir1, vDir, null);
}
if (addProjectRoots) {
addSourceContentToRoots(module, vDir);
}
});
});
return vDir;
}
public static void removeAllRoots(@NotNull Module module, Sdk jdk) {
ModuleRootModificationUtil.updateModel(module, model -> {
model.clear();
model.setSdk(jdk);
});
}
public static void addSourceContentToRoots(Module module, @NotNull VirtualFile vDir) {
addSourceContentToRoots(module, vDir, false);
}
public static void addSourceContentToRoots(Module module, @NotNull VirtualFile vDir, boolean testSource) {
ModuleRootModificationUtil.updateModel(module, model -> model.addContentEntry(vDir).addSourceFolder(vDir, testSource));
}
public static void addSourceRoot(Module module, VirtualFile vDir) {
addSourceRoot(module, vDir, false);
}
public static void addSourceRoot(Module module, VirtualFile vDir, boolean isTestSource) {
addSourceRoot(module, vDir, isTestSource ? JavaSourceRootType.TEST_SOURCE : JavaSourceRootType.SOURCE);
}
public static <P extends JpsElement> void addSourceRoot(Module module, VirtualFile vDir, @NotNull JpsModuleSourceRootType<P> rootType) {
addSourceRoot(module, vDir, rootType, rootType.createDefaultProperties());
}
public static <P extends JpsElement> void addSourceRoot(Module module,
VirtualFile vDir,
@NotNull JpsModuleSourceRootType<P> rootType,
P properties) {
ModuleRootModificationUtil.updateModel(module, model -> {
ContentEntry entry = findContentEntry(model, vDir);
if (entry == null) entry = model.addContentEntry(vDir);
entry.addSourceFolder(vDir, rootType, properties);
});
}
@Nullable
private static ContentEntry findContentEntry(ModuleRootModel rootModel, VirtualFile file) {
return ContainerUtil.find(rootModel.getContentEntries(), object -> {
VirtualFile entryRoot = object.getFile();
return entryRoot != null && VfsUtilCore.isAncestor(entryRoot, file, false);
});
}
public static ContentEntry addContentRoot(Module module, VirtualFile vDir) {
ModuleRootModificationUtil.updateModel(module, model -> model.addContentEntry(vDir));
for (ContentEntry entry : ModuleRootManager.getInstance(module).getContentEntries()) {
if (Comparing.equal(entry.getFile(), vDir)) {
Assert.assertFalse(((ContentEntryImpl)entry).isDisposed());
return entry;
}
}
return null;
}
public static void addExcludedRoot(Module module, VirtualFile dir) {
ModuleRootModificationUtil.updateModel(module, model -> ApplicationManager.getApplication().runReadAction(() -> {
findContentEntryWithAssertion(model, dir).addExcludeFolder(dir);
}));
}
@NotNull
private static ContentEntry findContentEntryWithAssertion(ModifiableRootModel model, VirtualFile dir) {
ContentEntry entry = findContentEntry(model, dir);
if (entry == null) {
throw new RuntimeException(dir + " is not under content roots: " + Arrays.toString(model.getContentRoots()));
}
return entry;
}
public static void removeContentEntry(Module module, VirtualFile contentRoot) {
ModuleRootModificationUtil.updateModel(module, model -> model.removeContentEntry(findContentEntryWithAssertion(model, contentRoot)));
}
public static void removeSourceRoot(Module module, VirtualFile root) {
ModuleRootModificationUtil.updateModel(module, model -> {
ContentEntry entry = findContentEntryWithAssertion(model, root);
for (SourceFolder sourceFolder : entry.getSourceFolders()) {
if (root.equals(sourceFolder.getFile())) {
entry.removeSourceFolder(sourceFolder);
break;
}
}
});
}
public static void removeExcludedRoot(Module module, VirtualFile root) {
ModuleRootModificationUtil.updateModel(module, model -> {
ContentEntry entry = findContentEntryWithAssertion(model, root);
entry.removeExcludeFolder(root.getUrl());
});
}
public static void checkFileStructure(PsiFile file) throws IncorrectOperationException {
String originalTree = DebugUtil.psiTreeToString(file, false);
PsiFile dummyFile = PsiFileFactory.getInstance(file.getProject()).createFileFromText(file.getName(), file.getFileType(), file.getText());
String reparsedTree = DebugUtil.psiTreeToString(dummyFile, false);
Assert.assertEquals(reparsedTree, originalTree);
}
public static void checkPsiMatchesTextIgnoringWhitespace(PsiFile file) throws IncorrectOperationException {
String originalTree = DebugUtil.psiTreeToString(file, true);
PsiFile dummyFile = PsiFileFactory.getInstance(file.getProject()).createFileFromText(file.getName(), file.getFileType(), file.getText());
String reparsedTree = DebugUtil.psiTreeToString(dummyFile, true);
Assert.assertEquals(reparsedTree, originalTree);
Document document = file.getViewProvider().getDocument();
if (document != null && !PsiDocumentManager.getInstance(file.getProject()).isCommitted(document)) {
PsiDocumentManager.getInstance(file.getProject()).commitDocument(document);
checkPsiMatchesTextIgnoringWhitespace(file);
}
}
public static void addLibrary(Module module, String libPath) {
File file = new File(libPath);
String libName = file.getName();
addLibrary(module, libName, file.getParent(), libName);
}
public static void addLibrary(Module module, String libName, String libPath, String... jarArr) {
ModuleRootModificationUtil.updateModel(module, model -> addLibrary(module, model, libName, libPath, jarArr));
}
public static void addProjectLibrary(Module module, String libName, VirtualFile... classesRoots) {
addProjectLibrary(module, libName, Arrays.asList(classesRoots), Collections.emptyList());
}
public static Library addProjectLibrary(Module module, String libName, List<VirtualFile> classesRoots, List<VirtualFile> sourceRoots) {
Ref<Library> result = Ref.create();
ModuleRootModificationUtil.updateModel(module, model -> result.set(addProjectLibrary(module, model, libName, classesRoots, sourceRoots)));
return result.get();
}
private static Library addProjectLibrary(Module module,
ModifiableRootModel model,
String libName,
List<VirtualFile> classesRoots,
List<VirtualFile> sourceRoots) {
LibraryTable libraryTable = ProjectLibraryTable.getInstance(module.getProject());
RunResult<Library> result = new WriteAction<Library>() {
@Override
protected void run(@NotNull Result<Library> result) throws Throwable {
Library library = libraryTable.createLibrary(libName);
Library.ModifiableModel libraryModel = library.getModifiableModel();
try {
for (VirtualFile root : classesRoots) {
libraryModel.addRoot(root, OrderRootType.CLASSES);
}
for (VirtualFile root : sourceRoots) {
libraryModel.addRoot(root, OrderRootType.SOURCES);
}
libraryModel.commit();
}
catch (Throwable t) {
//noinspection SSBasedInspection
libraryModel.dispose();
throw t;
}
model.addLibraryEntry(library);
OrderEntry[] orderEntries = model.getOrderEntries();
OrderEntry last = orderEntries[orderEntries.length - 1];
System.arraycopy(orderEntries, 0, orderEntries, 1, orderEntries.length - 1);
orderEntries[0] = last;
model.rearrangeOrderEntries(orderEntries);
result.setResult(library);
}
}.execute();
result.throwException();
return result.getResultObject();
}
public static void addLibrary(Module module,
ModifiableRootModel model,
String libName,
String libPath,
String... jarArr) {
List<VirtualFile> classesRoots = new ArrayList<>();
for (String jar : jarArr) {
if (!libPath.endsWith("/") && !jar.startsWith("/")) {
jar = "/" + jar;
}
String path = libPath + jar;
VirtualFile root;
if (path.endsWith(".jar")) {
root = JarFileSystem.getInstance().refreshAndFindFileByPath(path + "!/");
}
else {
root = LocalFileSystem.getInstance().refreshAndFindFileByPath(path);
}
assert root != null : "Library root folder not found: " + path + "!/";
classesRoots.add(root);
}
addProjectLibrary(module, model, libName, classesRoots, Collections.emptyList());
}
public static void addLibrary(Module module,
String libName, String libDir,
String[] classRoots,
String[] sourceRoots) {
String proto = (classRoots.length > 0 ? classRoots[0] : sourceRoots[0]).endsWith(".jar!/") ? JarFileSystem.PROTOCOL : LocalFileSystem.PROTOCOL;
String parentUrl = VirtualFileManager.constructUrl(proto, libDir);
List<String> classesUrls = new ArrayList<>();
List<String> sourceUrls = new ArrayList<>();
for (String classRoot : classRoots) {
classesUrls.add(parentUrl + classRoot);
}
for (String sourceRoot : sourceRoots) {
sourceUrls.add(parentUrl + sourceRoot);
}
ModuleRootModificationUtil.addModuleLibrary(module, libName, classesUrls, sourceUrls);
}
public static Module addModule(Project project, ModuleType type, String name, VirtualFile root) {
return new WriteCommandAction<Module>(project) {
@Override
protected void run(@NotNull Result<Module> result) throws Throwable {
String moduleName;
ModifiableModuleModel moduleModel = ModuleManager.getInstance(project).getModifiableModel();
try {
moduleName = moduleModel.newModule(root.getPath() + "/" + name + ".iml", type.getId()).getName();
moduleModel.commit();
}
catch (Throwable t) {
moduleModel.dispose();
throw t;
}
Module dep = ModuleManager.getInstance(project).findModuleByName(moduleName);
assert dep != null : moduleName;
ModifiableRootModel model = ModuleRootManager.getInstance(dep).getModifiableModel();
try {
model.addContentEntry(root).addSourceFolder(root, false);
model.commit();
}
catch (Throwable t) {
model.dispose();
throw t;
}
result.setResult(dep);
}
}.execute().getResultObject();
}
public static void setCompilerOutputPath(Module module, String url, boolean forTests) {
ModuleRootModificationUtil.updateModel(module, model -> {
CompilerModuleExtension extension = model.getModuleExtension(CompilerModuleExtension.class);
extension.inheritCompilerOutputPath(false);
if (forTests) {
extension.setCompilerOutputPathForTests(url);
}
else {
extension.setCompilerOutputPath(url);
}
});
}
public static void setExcludeCompileOutput(Module module, boolean exclude) {
ModuleRootModificationUtil.updateModel(module, model -> model.getModuleExtension(CompilerModuleExtension.class).setExcludeOutput(exclude));
}
public static void setJavadocUrls(Module module, String... urls) {
ModuleRootModificationUtil.updateModel(module, model -> model.getModuleExtension(JavaModuleExternalPaths.class).setJavadocUrls(urls));
}
@NotNull
@Contract(pure=true)
public static Sdk addJdkAnnotations(@NotNull Sdk sdk) {
String path = FileUtil.toSystemIndependentName(PlatformTestUtil.getCommunityPath()) + "/java/jdkAnnotations";
VirtualFile root = LocalFileSystem.getInstance().findFileByPath(path);
return addRootsToJdk(sdk, AnnotationOrderRootType.getInstance(), root);
}
@NotNull
@Contract(pure=true)
public static Sdk addRootsToJdk(@NotNull Sdk sdk,
@NotNull OrderRootType rootType,
@NotNull VirtualFile... roots) {
Sdk clone;
try {
clone = (Sdk)sdk.clone();
}
catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
SdkModificator sdkModificator = clone.getSdkModificator();
for (VirtualFile root : roots) {
sdkModificator.addRoot(root, rootType);
}
sdkModificator.commitChanges();
return clone;
}
public static void checkStubsMatchText(@NotNull PsiFile file) {
Project project = file.getProject();
StubTree tree = getStubTree(file);
StubTree copyTree = getStubTree(
PsiFileFactory.getInstance(project).createFileFromText(file.getName(), file.getLanguage(), file.getText()));
if (tree == null || copyTree == null) return;
String fromText = DebugUtil.stubTreeToString(copyTree.getRoot());
String fromPsi = DebugUtil.stubTreeToString(tree.getRoot());
if (!fromText.equals(fromPsi)) {
Assert.assertEquals("Re-created from text:\n" + fromText, "Stubs from PSI structure:\n" + fromPsi);
}
Document document = file.getViewProvider().getDocument();
assert document != null;
if (!PsiDocumentManager.getInstance(project).isCommitted(document)) {
PsiDocumentManager.getInstance(project).commitDocument(document);
checkStubsMatchText(file);
}
}
@Nullable
private static StubTree getStubTree(PsiFile file) {
if (!(file instanceof PsiFileImpl)) return null;
if (((PsiFileImpl)file).getElementTypeForStubBuilder() == null) return null;
StubTree tree = ((PsiFileImpl)file).getStubTree();
return tree != null ? tree : ((PsiFileImpl)file).calcStubTree();
}
}
|
platform/testFramework/src/com/intellij/testFramework/PsiTestUtil.java
|
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testFramework;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.application.RunResult;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.module.ModifiableModuleModel;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.module.ModuleType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.projectRoots.SdkModificator;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.roots.impl.ContentEntryImpl;
import com.intellij.openapi.roots.impl.libraries.ProjectLibraryTable;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.roots.libraries.LibraryTable;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.*;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileFactory;
import com.intellij.psi.impl.DebugUtil;
import com.intellij.psi.impl.source.PsiFileImpl;
import com.intellij.psi.stubs.StubTree;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.model.JpsElement;
import org.jetbrains.jps.model.java.JavaSourceRootType;
import org.jetbrains.jps.model.module.JpsModuleSourceRootType;
import org.junit.Assert;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class PsiTestUtil {
public static VirtualFile createTestProjectStructure(Project project,
Module module,
String rootPath,
Collection<File> filesToDelete) throws Exception {
return createTestProjectStructure(project, module, rootPath, filesToDelete, true);
}
public static VirtualFile createTestProjectStructure(Project project, Module module, Collection<File> filesToDelete) throws IOException {
return createTestProjectStructure(project, module, null, filesToDelete, true);
}
public static VirtualFile createTestProjectStructure(Project project,
Module module,
String rootPath,
Collection<File> filesToDelete,
boolean addProjectRoots) throws IOException {
VirtualFile vDir = createTestProjectStructure(module, rootPath, filesToDelete, addProjectRoots);
PsiDocumentManager.getInstance(project).commitAllDocuments();
return vDir;
}
public static VirtualFile createTestProjectStructure(Module module,
String rootPath,
Collection<File> filesToDelete,
boolean addProjectRoots) throws IOException {
return createTestProjectStructure("unitTest", module, rootPath, filesToDelete, addProjectRoots);
}
public static VirtualFile createTestProjectStructure(String tempName,
Module module,
String rootPath,
Collection<File> filesToDelete,
boolean addProjectRoots) throws IOException {
File dir = FileUtil.createTempDirectory(tempName, null, false);
filesToDelete.add(dir);
VirtualFile vDir = LocalFileSystem.getInstance().refreshAndFindFileByPath(dir.getCanonicalPath().replace(File.separatorChar, '/'));
assert vDir != null && vDir.isDirectory() : dir;
PlatformTestCase.synchronizeTempDirVfs(vDir);
EdtTestUtil.runInEdtAndWait(() -> {
WriteAction.run(() -> {
if (rootPath != null) {
VirtualFile vDir1 = LocalFileSystem.getInstance().findFileByPath(rootPath.replace(File.separatorChar, '/'));
if (vDir1 == null) {
throw new Exception(rootPath + " not found");
}
VfsUtil.copyDirectory(null, vDir1, vDir, null);
}
if (addProjectRoots) {
addSourceContentToRoots(module, vDir);
}
});
});
return vDir;
}
public static void removeAllRoots(@NotNull Module module, Sdk jdk) {
ModuleRootModificationUtil.updateModel(module, model -> {
model.clear();
model.setSdk(jdk);
});
}
public static void addSourceContentToRoots(Module module, @NotNull VirtualFile vDir) {
addSourceContentToRoots(module, vDir, false);
}
public static void addSourceContentToRoots(Module module, @NotNull VirtualFile vDir, boolean testSource) {
ModuleRootModificationUtil.updateModel(module, model -> model.addContentEntry(vDir).addSourceFolder(vDir, testSource));
}
public static void addSourceRoot(Module module, VirtualFile vDir) {
addSourceRoot(module, vDir, false);
}
public static void addSourceRoot(Module module, VirtualFile vDir, boolean isTestSource) {
addSourceRoot(module, vDir, isTestSource ? JavaSourceRootType.TEST_SOURCE : JavaSourceRootType.SOURCE);
}
public static <P extends JpsElement> void addSourceRoot(Module module, VirtualFile vDir, @NotNull JpsModuleSourceRootType<P> rootType) {
addSourceRoot(module, vDir, rootType, rootType.createDefaultProperties());
}
public static <P extends JpsElement> void addSourceRoot(Module module,
VirtualFile vDir,
@NotNull JpsModuleSourceRootType<P> rootType,
P properties) {
ModuleRootModificationUtil.updateModel(module, model -> {
ContentEntry entry = findContentEntry(model, vDir);
if (entry == null) entry = model.addContentEntry(vDir);
entry.addSourceFolder(vDir, rootType, properties);
});
}
@Nullable
private static ContentEntry findContentEntry(ModuleRootModel rootModel, VirtualFile file) {
return ContainerUtil.find(rootModel.getContentEntries(), object -> {
VirtualFile entryRoot = object.getFile();
return entryRoot != null && VfsUtilCore.isAncestor(entryRoot, file, false);
});
}
public static ContentEntry addContentRoot(Module module, VirtualFile vDir) {
ModuleRootModificationUtil.updateModel(module, model -> model.addContentEntry(vDir));
for (ContentEntry entry : ModuleRootManager.getInstance(module).getContentEntries()) {
if (Comparing.equal(entry.getFile(), vDir)) {
Assert.assertFalse(((ContentEntryImpl)entry).isDisposed());
return entry;
}
}
return null;
}
public static void addExcludedRoot(Module module, VirtualFile dir) {
ModuleRootModificationUtil.updateModel(module, model -> ApplicationManager.getApplication().runReadAction(() -> {
findContentEntryWithAssertion(model, dir).addExcludeFolder(dir);
}));
}
@NotNull
private static ContentEntry findContentEntryWithAssertion(ModifiableRootModel model, VirtualFile dir) {
ContentEntry entry = findContentEntry(model, dir);
if (entry == null) {
throw new RuntimeException(dir + " is not under content roots: " + Arrays.toString(model.getContentRoots()));
}
return entry;
}
public static void removeContentEntry(Module module, VirtualFile contentRoot) {
ModuleRootModificationUtil.updateModel(module, model -> model.removeContentEntry(findContentEntryWithAssertion(model, contentRoot)));
}
public static void removeSourceRoot(Module module, VirtualFile root) {
ModuleRootModificationUtil.updateModel(module, model -> {
ContentEntry entry = findContentEntryWithAssertion(model, root);
for (SourceFolder sourceFolder : entry.getSourceFolders()) {
if (root.equals(sourceFolder.getFile())) {
entry.removeSourceFolder(sourceFolder);
break;
}
}
});
}
public static void removeExcludedRoot(Module module, VirtualFile root) {
ModuleRootModificationUtil.updateModel(module, model -> {
ContentEntry entry = findContentEntryWithAssertion(model, root);
entry.removeExcludeFolder(root.getUrl());
});
}
public static void checkFileStructure(PsiFile file) throws IncorrectOperationException {
String originalTree = DebugUtil.psiTreeToString(file, false);
PsiFile dummyFile = PsiFileFactory.getInstance(file.getProject()).createFileFromText(file.getName(), file.getFileType(), file.getText());
String reparsedTree = DebugUtil.psiTreeToString(dummyFile, false);
Assert.assertEquals(reparsedTree, originalTree);
}
public static void addLibrary(Module module, String libPath) {
File file = new File(libPath);
String libName = file.getName();
addLibrary(module, libName, file.getParent(), libName);
}
public static void addLibrary(Module module, String libName, String libPath, String... jarArr) {
ModuleRootModificationUtil.updateModel(module, model -> addLibrary(module, model, libName, libPath, jarArr));
}
public static void addProjectLibrary(Module module, String libName, VirtualFile... classesRoots) {
addProjectLibrary(module, libName, Arrays.asList(classesRoots), Collections.emptyList());
}
public static Library addProjectLibrary(Module module, String libName, List<VirtualFile> classesRoots, List<VirtualFile> sourceRoots) {
Ref<Library> result = Ref.create();
ModuleRootModificationUtil.updateModel(module, model -> result.set(addProjectLibrary(module, model, libName, classesRoots, sourceRoots)));
return result.get();
}
private static Library addProjectLibrary(Module module,
ModifiableRootModel model,
String libName,
List<VirtualFile> classesRoots,
List<VirtualFile> sourceRoots) {
LibraryTable libraryTable = ProjectLibraryTable.getInstance(module.getProject());
RunResult<Library> result = new WriteAction<Library>() {
@Override
protected void run(@NotNull Result<Library> result) throws Throwable {
Library library = libraryTable.createLibrary(libName);
Library.ModifiableModel libraryModel = library.getModifiableModel();
try {
for (VirtualFile root : classesRoots) {
libraryModel.addRoot(root, OrderRootType.CLASSES);
}
for (VirtualFile root : sourceRoots) {
libraryModel.addRoot(root, OrderRootType.SOURCES);
}
libraryModel.commit();
}
catch (Throwable t) {
//noinspection SSBasedInspection
libraryModel.dispose();
throw t;
}
model.addLibraryEntry(library);
OrderEntry[] orderEntries = model.getOrderEntries();
OrderEntry last = orderEntries[orderEntries.length - 1];
System.arraycopy(orderEntries, 0, orderEntries, 1, orderEntries.length - 1);
orderEntries[0] = last;
model.rearrangeOrderEntries(orderEntries);
result.setResult(library);
}
}.execute();
result.throwException();
return result.getResultObject();
}
public static void addLibrary(Module module,
ModifiableRootModel model,
String libName,
String libPath,
String... jarArr) {
List<VirtualFile> classesRoots = new ArrayList<>();
for (String jar : jarArr) {
if (!libPath.endsWith("/") && !jar.startsWith("/")) {
jar = "/" + jar;
}
String path = libPath + jar;
VirtualFile root;
if (path.endsWith(".jar")) {
root = JarFileSystem.getInstance().refreshAndFindFileByPath(path + "!/");
}
else {
root = LocalFileSystem.getInstance().refreshAndFindFileByPath(path);
}
assert root != null : "Library root folder not found: " + path + "!/";
classesRoots.add(root);
}
addProjectLibrary(module, model, libName, classesRoots, Collections.emptyList());
}
public static void addLibrary(Module module,
String libName, String libDir,
String[] classRoots,
String[] sourceRoots) {
String proto = (classRoots.length > 0 ? classRoots[0] : sourceRoots[0]).endsWith(".jar!/") ? JarFileSystem.PROTOCOL : LocalFileSystem.PROTOCOL;
String parentUrl = VirtualFileManager.constructUrl(proto, libDir);
List<String> classesUrls = new ArrayList<>();
List<String> sourceUrls = new ArrayList<>();
for (String classRoot : classRoots) {
classesUrls.add(parentUrl + classRoot);
}
for (String sourceRoot : sourceRoots) {
sourceUrls.add(parentUrl + sourceRoot);
}
ModuleRootModificationUtil.addModuleLibrary(module, libName, classesUrls, sourceUrls);
}
public static Module addModule(Project project, ModuleType type, String name, VirtualFile root) {
return new WriteCommandAction<Module>(project) {
@Override
protected void run(@NotNull Result<Module> result) throws Throwable {
String moduleName;
ModifiableModuleModel moduleModel = ModuleManager.getInstance(project).getModifiableModel();
try {
moduleName = moduleModel.newModule(root.getPath() + "/" + name + ".iml", type.getId()).getName();
moduleModel.commit();
}
catch (Throwable t) {
moduleModel.dispose();
throw t;
}
Module dep = ModuleManager.getInstance(project).findModuleByName(moduleName);
assert dep != null : moduleName;
ModifiableRootModel model = ModuleRootManager.getInstance(dep).getModifiableModel();
try {
model.addContentEntry(root).addSourceFolder(root, false);
model.commit();
}
catch (Throwable t) {
model.dispose();
throw t;
}
result.setResult(dep);
}
}.execute().getResultObject();
}
public static void setCompilerOutputPath(Module module, String url, boolean forTests) {
ModuleRootModificationUtil.updateModel(module, model -> {
CompilerModuleExtension extension = model.getModuleExtension(CompilerModuleExtension.class);
extension.inheritCompilerOutputPath(false);
if (forTests) {
extension.setCompilerOutputPathForTests(url);
}
else {
extension.setCompilerOutputPath(url);
}
});
}
public static void setExcludeCompileOutput(Module module, boolean exclude) {
ModuleRootModificationUtil.updateModel(module, model -> model.getModuleExtension(CompilerModuleExtension.class).setExcludeOutput(exclude));
}
public static void setJavadocUrls(Module module, String... urls) {
ModuleRootModificationUtil.updateModel(module, model -> model.getModuleExtension(JavaModuleExternalPaths.class).setJavadocUrls(urls));
}
@NotNull
@Contract(pure=true)
public static Sdk addJdkAnnotations(@NotNull Sdk sdk) {
String path = FileUtil.toSystemIndependentName(PlatformTestUtil.getCommunityPath()) + "/java/jdkAnnotations";
VirtualFile root = LocalFileSystem.getInstance().findFileByPath(path);
return addRootsToJdk(sdk, AnnotationOrderRootType.getInstance(), root);
}
@NotNull
@Contract(pure=true)
public static Sdk addRootsToJdk(@NotNull Sdk sdk,
@NotNull OrderRootType rootType,
@NotNull VirtualFile... roots) {
Sdk clone;
try {
clone = (Sdk)sdk.clone();
}
catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
SdkModificator sdkModificator = clone.getSdkModificator();
for (VirtualFile root : roots) {
sdkModificator.addRoot(root, rootType);
}
sdkModificator.commitChanges();
return clone;
}
public static void checkStubsMatchText(@NotNull PsiFile file) {
Project project = file.getProject();
StubTree tree = getStubTree(file);
StubTree copyTree = getStubTree(
PsiFileFactory.getInstance(project).createFileFromText(file.getName(), file.getLanguage(), file.getText()));
if (tree == null || copyTree == null) return;
String fromText = DebugUtil.stubTreeToString(copyTree.getRoot());
String fromPsi = DebugUtil.stubTreeToString(tree.getRoot());
if (!fromText.equals(fromPsi)) {
Assert.assertEquals("Re-created from text:\n" + fromText, "Stubs from PSI structure:\n" + fromPsi);
}
Document document = file.getViewProvider().getDocument();
assert document != null;
if (!PsiDocumentManager.getInstance(project).isCommitted(document)) {
PsiDocumentManager.getInstance(project).commitDocument(document);
checkStubsMatchText(file);
}
}
@Nullable
private static StubTree getStubTree(PsiFile file) {
if (!(file instanceof PsiFileImpl)) return null;
if (((PsiFileImpl)file).getElementTypeForStubBuilder() == null) return null;
StubTree tree = ((PsiFileImpl)file).getStubTree();
return tree != null ? tree : ((PsiFileImpl)file).calcStubTree();
}
}
|
add PsiTestUtil.checkPsiMatchesTextIgnoringWhitespace
|
platform/testFramework/src/com/intellij/testFramework/PsiTestUtil.java
|
add PsiTestUtil.checkPsiMatchesTextIgnoringWhitespace
|
<ide><path>latform/testFramework/src/com/intellij/testFramework/PsiTestUtil.java
<ide> Assert.assertEquals(reparsedTree, originalTree);
<ide> }
<ide>
<add> public static void checkPsiMatchesTextIgnoringWhitespace(PsiFile file) throws IncorrectOperationException {
<add> String originalTree = DebugUtil.psiTreeToString(file, true);
<add> PsiFile dummyFile = PsiFileFactory.getInstance(file.getProject()).createFileFromText(file.getName(), file.getFileType(), file.getText());
<add> String reparsedTree = DebugUtil.psiTreeToString(dummyFile, true);
<add> Assert.assertEquals(reparsedTree, originalTree);
<add>
<add> Document document = file.getViewProvider().getDocument();
<add> if (document != null && !PsiDocumentManager.getInstance(file.getProject()).isCommitted(document)) {
<add> PsiDocumentManager.getInstance(file.getProject()).commitDocument(document);
<add> checkPsiMatchesTextIgnoringWhitespace(file);
<add> }
<add> }
<add>
<ide> public static void addLibrary(Module module, String libPath) {
<ide> File file = new File(libPath);
<ide> String libName = file.getName();
|
|
Java
|
mit
|
75265b52331f0d1ff1660d0cc56701e8e7502f58
| 0 |
yzhnasa/TASSEL-iRods,yzhnasa/TASSEL-iRods,yzhnasa/TASSEL-iRods,yzhnasa/TASSEL-iRods
|
/*
* ExportUtils
*/
package net.maizegenetics.pal.alignment;
import ch.systemsx.cisd.base.mdarray.MDArray;
import ch.systemsx.cisd.hdf5.HDF5Factory;
import ch.systemsx.cisd.hdf5.HDF5IntStorageFeatures;
import ch.systemsx.cisd.hdf5.IHDF5Writer;
import ch.systemsx.cisd.hdf5.IHDF5WriterConfigurator;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.util.regex.Pattern;
import java.util.zip.GZIPOutputStream;
import net.maizegenetics.pal.io.FormattedOutput;
import net.maizegenetics.util.ExceptionUtils;
import net.maizegenetics.util.ProgressListener;
import net.maizegenetics.util.Utils;
import net.maizegenetics.util.VCFUtil;
import org.apache.log4j.Logger;
/**
* The class exports PAL alignment data types to various file formats.
*
* @author Jon, Terry, Ed
*/
public class ExportUtils {
private static final Logger myLogger = Logger.getLogger(ExportUtils.class);
private static FormattedOutput format = FormattedOutput.getInstance();
private ExportUtils() {
// Utility Class - do not instantiate.
}
public static String writeToHDF5(Alignment a, String newHDF5file) {
a = AlignmentUtils.optimizeForTaxaAndSites(a);
IHDF5Writer h5w = null;
try {
int numSites = a.getSiteCount();
int numTaxa = a.getSequenceCount();
newHDF5file = Utils.addSuffixIfNeeded(newHDF5file, ".hmp.h5");
File hdf5File = new File(newHDF5file);
if (hdf5File.exists()) {
throw new IllegalArgumentException("ExportUtils: writeToHDF5: File already exists: " + newHDF5file);
}
IHDF5WriterConfigurator config = HDF5Factory.configure(hdf5File);
myLogger.info("Writing HDF5 file: " + newHDF5file);
config.overwrite();
config.dontUseExtendableDataTypes();
h5w = config.writer();
h5w.setIntAttribute(HapMapHDF5Constants.DEFAULT_ATTRIBUTES_PATH, HapMapHDF5Constants.MAX_NUM_ALLELES, a.getMaxNumAlleles());
h5w.setBooleanAttribute(HapMapHDF5Constants.DEFAULT_ATTRIBUTES_PATH, HapMapHDF5Constants.RETAIN_RARE_ALLELES, a.retainsRareAlleles());
h5w.setIntAttribute(HapMapHDF5Constants.DEFAULT_ATTRIBUTES_PATH, HapMapHDF5Constants.NUM_TAXA, numTaxa);
int numSBitWords = a.getAllelePresenceForAllTaxa(0, 0).getNumWords();
h5w.setIntAttribute(HapMapHDF5Constants.DEFAULT_ATTRIBUTES_PATH, HapMapHDF5Constants.NUM_SBIT_WORDS, numSBitWords);
int numTBitWords = a.getAllelePresenceForAllSites(0, 0).getNumWords();
h5w.setIntAttribute(HapMapHDF5Constants.DEFAULT_ATTRIBUTES_PATH, HapMapHDF5Constants.NUM_TBIT_WORDS, numTBitWords);
String[][] aEncodings = a.getAlleleEncodings();
//myLogger.info(Arrays.deepToString(aEncodings));
int numEncodings = aEncodings.length;
int numStates = aEncodings[0].length;
MDArray<String> alleleEncodings = new MDArray<String>(String.class, new int[]{numEncodings, numStates});
for (int s = 0; s < numEncodings; s++) {
for (int x = 0; x < numStates; x++) {
alleleEncodings.set(aEncodings[s][x], s, x);
}
}
h5w.createStringMDArray(HapMapHDF5Constants.ALLELE_STATES, 100, new int[]{numEncodings, numStates});
h5w.writeStringMDArray(HapMapHDF5Constants.ALLELE_STATES, alleleEncodings);
MDArray<String> alleleEncodingReadAgain = h5w.readStringMDArray(HapMapHDF5Constants.ALLELE_STATES);
if (alleleEncodings.equals(alleleEncodingReadAgain) == false) {
throw new IllegalStateException("ExportUtils: writeToHDF5: Mismatch Allele States, expected '" + alleleEncodings + "', found '" + alleleEncodingReadAgain + "'!");
}
h5w.writeStringArray(HapMapHDF5Constants.SNP_IDS, a.getSNPIDs());
h5w.createGroup(HapMapHDF5Constants.SBIT);
h5w.setIntAttribute(HapMapHDF5Constants.DEFAULT_ATTRIBUTES_PATH, HapMapHDF5Constants.NUM_SITES, numSites);
String[] lociNames = new String[a.getNumLoci()];
Locus[] loci = a.getLoci();
for (int i = 0; i < a.getNumLoci(); i++) {
lociNames[i] = loci[i].getName();
}
h5w.createStringVariableLengthArray(HapMapHDF5Constants.LOCI, a.getNumLoci());
h5w.writeStringVariableLengthArray(HapMapHDF5Constants.LOCI, lociNames);
h5w.createIntArray(HapMapHDF5Constants.LOCUS_OFFSETS, a.getNumLoci());
h5w.writeIntArray(HapMapHDF5Constants.LOCUS_OFFSETS, a.getLociOffsets());
h5w.createIntArray(HapMapHDF5Constants.POSITIONS, numSites);
h5w.writeIntArray(HapMapHDF5Constants.POSITIONS, a.getPhysicalPositions());
h5w.createByteMatrix(HapMapHDF5Constants.ALLELES, a.getSiteCount(), a.getMaxNumAlleles());
byte[][] alleles = new byte[numSites][a.getMaxNumAlleles()];
for (int i = 0; i < numSites; i++) {
alleles[i] = a.getAlleles(i);
}
h5w.writeByteMatrix(HapMapHDF5Constants.ALLELES, alleles);
String[] tn = new String[numTaxa];
for (int i = 0; i < tn.length; i++) {
tn[i] = a.getFullTaxaName(i);
}
h5w.createStringVariableLengthArray(HapMapHDF5Constants.TAXA, numTaxa);
h5w.writeStringVariableLengthArray(HapMapHDF5Constants.TAXA, tn);
for (int aNum = 0; aNum < a.getTotalNumAlleles(); aNum++) {
String currentSBitPath = HapMapHDF5Constants.SBIT + "/" + aNum;
h5w.createLongMatrix(currentSBitPath, numSites, numSBitWords, 1, numSBitWords);
long[][] lgarray = new long[numSites][numSBitWords];
for (int i = 0; i < numSites; i++) {
lgarray[i] = a.getAllelePresenceForAllTaxa(i, aNum).getBits();
}
h5w.writeLongMatrix(currentSBitPath, lgarray);
String currentTBitPath = HapMapHDF5Constants.TBIT + "/" + aNum;
h5w.createLongMatrix(currentTBitPath, numTaxa, numTBitWords, 1, numTBitWords);
lgarray = new long[numTaxa][numTBitWords];
for (int i = 0; i < numTaxa; i++) {
lgarray[i] = a.getAllelePresenceForAllSites(i, aNum).getBits();
}
h5w.writeLongMatrix(currentTBitPath, lgarray);
}
return newHDF5file;
} finally {
try {
h5w.close();
} catch (Exception e) {
// do nothing
}
}
}
public static String writeToMutableHDF5(Alignment a, String newHDF5file, boolean includeGenotypes) {
IHDF5Writer h5w = null;
try {
int numSites = a.getSiteCount();
int numTaxa = a.getSequenceCount();
newHDF5file = Utils.addSuffixIfNeeded(newHDF5file, "mutable.hmp.h5");
File hdf5File = new File(newHDF5file);
if (hdf5File.exists()) {
throw new IllegalArgumentException("ExportUtils: writeToMutableHDF5: File already exists: " + newHDF5file);
}
IHDF5WriterConfigurator config = HDF5Factory.configure(hdf5File);
myLogger.info("Writing Mutable HDF5 file: " + newHDF5file);
config.overwrite();
config.dontUseExtendableDataTypes();
h5w = config.writer();
h5w.setIntAttribute(HapMapHDF5Constants.DEFAULT_ATTRIBUTES_PATH, HapMapHDF5Constants.MAX_NUM_ALLELES, a.getMaxNumAlleles());
h5w.setBooleanAttribute(HapMapHDF5Constants.DEFAULT_ATTRIBUTES_PATH, HapMapHDF5Constants.RETAIN_RARE_ALLELES, a.retainsRareAlleles());
h5w.setIntAttribute(HapMapHDF5Constants.DEFAULT_ATTRIBUTES_PATH, HapMapHDF5Constants.NUM_TAXA, numTaxa);
String[][] aEncodings = a.getAlleleEncodings();
int numEncodings = aEncodings.length;
int numStates = aEncodings[0].length;
MDArray<String> alleleEncodings = new MDArray<String>(String.class, new int[]{numEncodings, numStates});
for (int s = 0; s < numEncodings; s++) {
for (int x = 0; x < numStates; x++) {
alleleEncodings.set(aEncodings[s][x], s, x);
}
}
h5w.createStringMDArray(HapMapHDF5Constants.ALLELE_STATES, 100, new int[]{numEncodings, numStates});
h5w.writeStringMDArray(HapMapHDF5Constants.ALLELE_STATES, alleleEncodings);
MDArray<String> alleleEncodingReadAgain = h5w.readStringMDArray(HapMapHDF5Constants.ALLELE_STATES);
if (alleleEncodings.equals(alleleEncodingReadAgain) == false) {
throw new IllegalStateException("ExportUtils: writeToMutableHDF5: Mismatch Allele States, expected '" + alleleEncodings + "', found '" + alleleEncodingReadAgain + "'!");
}
h5w.writeStringArray(HapMapHDF5Constants.SNP_IDS, a.getSNPIDs());
h5w.setIntAttribute(HapMapHDF5Constants.DEFAULT_ATTRIBUTES_PATH, HapMapHDF5Constants.NUM_SITES, numSites);
String[] lociNames = new String[a.getNumLoci()];
Locus[] loci = a.getLoci();
for (int i = 0; i < a.getNumLoci(); i++) {
lociNames[i] = loci[i].getName();
}
h5w.createStringVariableLengthArray(HapMapHDF5Constants.LOCI, a.getNumLoci());
h5w.writeStringVariableLengthArray(HapMapHDF5Constants.LOCI, lociNames);
h5w.createIntArray(HapMapHDF5Constants.LOCUS_OFFSETS, a.getNumLoci());
h5w.writeIntArray(HapMapHDF5Constants.LOCUS_OFFSETS, a.getLociOffsets());
h5w.createIntArray(HapMapHDF5Constants.POSITIONS, numSites);
h5w.writeIntArray(HapMapHDF5Constants.POSITIONS, a.getPhysicalPositions());
h5w.createByteMatrix(HapMapHDF5Constants.ALLELES, a.getSiteCount(), a.getMaxNumAlleles());
byte[][] alleles = new byte[numSites][a.getMaxNumAlleles()];
for (int i = 0; i < numSites; i++) {
alleles[i] = a.getAlleles(i);
}
h5w.writeByteMatrix(HapMapHDF5Constants.ALLELES, alleles);
// Write Bases
HDF5IntStorageFeatures features = HDF5IntStorageFeatures.createDeflation(HDF5IntStorageFeatures.MAX_DEFLATION_LEVEL);
HDF5IntStorageFeatures.createDeflationDelete(HDF5IntStorageFeatures.MAX_DEFLATION_LEVEL);
if(includeGenotypes) {
for (int t = 0; t < numTaxa; t++) {
String basesPath = HapMapHDF5Constants.GENOTYPES + "/" + a.getFullTaxaName(t);
h5w.createByteArray(basesPath, numSites, features);
byte[] bases = a.getBaseRow(t);
h5w.writeByteArray(basesPath, bases, features);
}
}
return newHDF5file;
} finally {
try {
h5w.close();
} catch (Exception e) {
// do nothing
}
}
}
/**
* Writes multiple alignments to single Hapmap file. Currently no error
* checking
*
* @param alignment array of alignments
* @param diploid
* @param filename
* @param delimChar
*/
public static String writeToHapmap(Alignment alignment, boolean diploid, String filename, char delimChar, ProgressListener listener) {
if (delimChar != ' ' && delimChar != '\t') {
throw new IllegalArgumentException("Delimiter charater must be either a blank space or a tab.");
}
BufferedWriter bw = null;
try {
String fullFileName = Utils.addSuffixIfNeeded(filename, ".hmp.txt", new String[]{".hmp.txt", ".hmp.txt.gz"});
bw = Utils.getBufferedWriter(fullFileName);
bw.write("rs#");
bw.write(delimChar);
bw.write("alleles");
bw.write(delimChar);
bw.write("chrom");
bw.write(delimChar);
bw.write("pos");
bw.write(delimChar);
bw.write("strand");
bw.write(delimChar);
bw.write("assembly#");
bw.write(delimChar);
bw.write("center");
bw.write(delimChar);
bw.write("protLSID");
bw.write(delimChar);
bw.write("assayLSID");
bw.write(delimChar);
bw.write("panelLSID");
bw.write(delimChar);
bw.write("QCcode");
bw.write(delimChar);
int numTaxa = alignment.getSequenceCount();
for (int taxa = 0; taxa < numTaxa; taxa++) {
//finish filling out first row
//not completely sure this does what I want, I need to access the
//accession name from every alleleBLOB in bytes [52-201] but there
//doesn't seem to be a method to access that in Alignment
String sequenceID = alignment.getIdGroup().getIdentifier(taxa).getFullName().trim();
bw.write(sequenceID);
if (taxa != numTaxa - 1) {
bw.write(delimChar);
}
}
bw.write("\n");
int numSites = alignment.getSiteCount();
for (int site = 0; site < numSites; site++) {
bw.write(alignment.getSNPID(site));
bw.write(delimChar);
// byte[] alleles = alignment.getAlleles(site); // doesn't work right for MutableVCFAlignment (always returns 3 alleles, even if no data)
// int numAlleles = alleles.length;
int[][] sortedAlleles = alignment.getAllelesSortedByFrequency(site); // which alleles are actually present among the genotypes
int numAlleles = sortedAlleles[0].length;
if (numAlleles == 0) {
bw.write("NA"); //if data does not exist
} else if (numAlleles == 1) {
bw.write(alignment.getBaseAsString(site, (byte) sortedAlleles[0][0]));
} else {
bw.write(alignment.getBaseAsString(site, (byte) sortedAlleles[0][0]));
for (int allele = 1; allele < sortedAlleles[0].length; allele++) {
if (sortedAlleles[0][allele] != Alignment.UNKNOWN_ALLELE) {
bw.write('/');
bw.write(alignment.getBaseAsString(site, (byte) sortedAlleles[0][allele])); // will write out a third allele if it exists
}
}
}
bw.write(delimChar);
bw.write(alignment.getLocusName(site));
bw.write(delimChar);
bw.write(String.valueOf(alignment.getPositionInLocus(site)));
bw.write(delimChar);
bw.write("+"); //strand
bw.write(delimChar);
bw.write("NA"); //assembly# not supported
bw.write(delimChar);
bw.write("NA"); //center unavailable
bw.write(delimChar);
bw.write("NA"); //protLSID unavailable
bw.write(delimChar);
bw.write("NA"); //assayLSID unavailable
bw.write(delimChar);
bw.write("NA"); //panelLSID unavailable
bw.write(delimChar);
bw.write("NA"); //QCcode unavailable
bw.write(delimChar);
for (int taxa = 0; taxa < numTaxa; taxa++) {
if (diploid == false) {
String baseIUPAC = null;
try {
baseIUPAC = alignment.getBaseAsString(taxa, site);
} catch (Exception e) {
String[] b = alignment.getBaseAsStringArray(taxa, site);
throw new IllegalArgumentException("There is no String representation for diploid values: " + b[0] + ":" + b[1] + " getBase(): 0x" + Integer.toHexString(alignment.getBase(taxa, site)) + "\nTry Exporting as Diploid Values.");
}
if ((baseIUPAC == null) || baseIUPAC.equals("?")) {
String[] b = alignment.getBaseAsStringArray(taxa, site);
throw new IllegalArgumentException("There is no String representation for diploid values: " + b[0] + ":" + b[1] + " getBase(): 0x" + Integer.toHexString(alignment.getBase(taxa, site)) + "\nTry Exporting as Diploid Values.");
}
bw.write(baseIUPAC);
} else {
String[] b = alignment.getBaseAsStringArray(taxa, site);
if (b.length == 1) {
bw.write(b[0]);
bw.write(b[0]);
} else {
bw.write(b[0]);
bw.write(b[1]);
}
}
if (taxa != (numTaxa - 1)) {
bw.write(delimChar);
}
}
bw.write("\n");
if (listener != null) {
listener.progress((int) (((double) (site + 1) / (double) numSites) * 100.0), null);
}
}
return fullFileName;
} catch (Exception e) {
e.printStackTrace();
throw new IllegalArgumentException("Error writing Hapmap file: " + filename + ": " + ExceptionUtils.getExceptionCauses(e));
} finally {
try {
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Writes multiple alignments to single Hapmap file. Currently no error
* checking
*
* @param alignment array of alignments
* @param diploid
* @param filename
* @param delimChar
*/
public static String writeToHapmap(Alignment alignment, AlignmentMask mask, boolean diploid, String filename, char delimChar, ProgressListener listener) {
if (delimChar != ' ' && delimChar != '\t') {
throw new IllegalArgumentException("Delimiter charater must be either a blank space or a tab.");
}
BufferedWriter bw = null;
try {
String fullFileName = Utils.addSuffixIfNeeded(filename, ".hmp.txt", new String[]{".hmp.txt", ".hmp.txt.gz"});
bw = Utils.getBufferedWriter(fullFileName);
bw.write("rs#");
bw.write(delimChar);
bw.write("alleles");
bw.write(delimChar);
bw.write("chrom");
bw.write(delimChar);
bw.write("pos");
bw.write(delimChar);
bw.write("strand");
bw.write(delimChar);
bw.write("assembly#");
bw.write(delimChar);
bw.write("center");
bw.write(delimChar);
bw.write("protLSID");
bw.write(delimChar);
bw.write("assayLSID");
bw.write(delimChar);
bw.write("panelLSID");
bw.write(delimChar);
bw.write("QCcode");
bw.write(delimChar);
int numTaxa = alignment.getSequenceCount();
for (int taxa = 0; taxa < numTaxa; taxa++) {
//finish filling out first row
//not completely sure this does what I want, I need to access the
//accession name from every alleleBLOB in bytes [52-201] but there
//doesn't seem to be a method to access that in Alignment
String sequenceID = alignment.getIdGroup().getIdentifier(taxa).getFullName().trim();
bw.write(sequenceID);
if (taxa != numTaxa - 1) {
bw.write(delimChar);
}
}
bw.write("\n");
int numSites = alignment.getSiteCount();
for (int site = 0; site < numSites; site++) {
bw.write(alignment.getSNPID(site));
bw.write(delimChar);
// byte[] alleles = alignment.getAlleles(site); // doesn't work right for MutableVCFAlignment (always returns 3 alleles, even if no data)
// int numAlleles = alleles.length;
int[][] sortedAlleles = alignment.getAllelesSortedByFrequency(site); // which alleles are actually present among the genotypes
int numAlleles = sortedAlleles[0].length;
if (numAlleles == 0) {
bw.write("NA"); //if data does not exist
} else if (numAlleles == 1) {
bw.write(alignment.getBaseAsString(site, (byte) sortedAlleles[0][0]));
} else {
bw.write(alignment.getBaseAsString(site, (byte) sortedAlleles[0][0]));
for (int allele = 1; allele < sortedAlleles[0].length; allele++) {
if (sortedAlleles[0][allele] != Alignment.UNKNOWN_ALLELE) {
bw.write('/');
bw.write(alignment.getBaseAsString(site, (byte) sortedAlleles[0][allele])); // will write out a third allele if it exists
}
}
}
bw.write(delimChar);
bw.write(alignment.getLocusName(site));
bw.write(delimChar);
bw.write(String.valueOf(alignment.getPositionInLocus(site)));
bw.write(delimChar);
bw.write("+"); //strand
bw.write(delimChar);
bw.write("NA"); //assembly# not supported
bw.write(delimChar);
bw.write("NA"); //center unavailable
bw.write(delimChar);
bw.write("NA"); //protLSID unavailable
bw.write(delimChar);
bw.write("NA"); //assayLSID unavailable
bw.write(delimChar);
bw.write("NA"); //panelLSID unavailable
bw.write(delimChar);
bw.write("NA"); //QCcode unavailable
bw.write(delimChar);
for (int taxa = 0; taxa < numTaxa; taxa++) {
if (diploid == false) {
String baseIUPAC = alignment.getBaseAsString(taxa, site);
if (mask.getMask(taxa, site) == 0x0) {
bw.write(baseIUPAC);
} else if (mask.getMask(taxa, site) == 0x1) {
bw.write(baseIUPAC.toLowerCase());
}
} else {
String[] b = alignment.getBaseAsStringArray(taxa, site);
if (b.length == 1) {
if (mask.getMask(taxa, site) == 0x0) {
bw.write(b[0]);
bw.write(b[0]);
} else if (mask.getMask(taxa, site) == 0x1) {
bw.write(b[0].toLowerCase());
bw.write(b[0].toLowerCase());
}
} else {
if (mask.getMask(taxa, site) == 0x0) {
bw.write(b[0]);
bw.write(b[1]);
} else if (mask.getMask(taxa, site) == 0x1) {
bw.write(b[0].toLowerCase());
bw.write(b[1].toLowerCase());
}
}
}
if (taxa != (numTaxa - 1)) {
bw.write(delimChar);
}
}
bw.write("\n");
if (listener != null) {
listener.progress((int) (((double) (site + 1) / (double) numSites) * 100.0), null);
}
}
return fullFileName;
} catch (Exception e) {
e.printStackTrace();
throw new IllegalArgumentException("Error writing Hapmap file: " + filename + ": " + ExceptionUtils.getExceptionCauses(e));
} finally {
try {
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Writes given alignment to a VCF file
*
* @param alignment
* @param filename
* @return
*/
public static String writeToVCF(Alignment alignment, String filename, char delimChar) {
try {
filename = Utils.addSuffixIfNeeded(filename, ".vcf", new String[]{".vcf", ".vcf.gz"});
BufferedWriter bw = Utils.getBufferedWriter(filename);
bw.write("##fileformat=VCFv4.0");
bw.newLine();
if (alignment.getReferenceAllele(0) == Alignment.UNKNOWN_DIPLOID_ALLELE) {
bw.write("##Reference allele is not known. The major allele was used as reference allele.");
bw.newLine();
}
bw.write("##FORMAT=<ID=GT,Number=1,Type=String,Description=\"Genotype\">");
bw.newLine();
bw.write("##FORMAT=<ID=AD,Number=.,Type=Integer,Description=\"Allelic depths for the reference and alternate alleles in the order listed\">");
bw.newLine();
bw.write("##FORMAT=<ID=DP,Number=1,Type=Integer,Description=\"Read Depth (only filtered reads used for calling)\">");
bw.newLine();
bw.write("##FORMAT=<ID=GQ,Number=1,Type=Float,Description=\"Genotype Quality\">");
bw.newLine();
bw.write("####FORMAT=<ID=PL,Number=3,Type=Float,Description=\"Normalized, Phred-scaled likelihoods for AA,AB,BB genotypes where A=ref and B=alt; not applicable if site is not biallelic\">");
bw.newLine();
bw.write("##INFO=<ID=NS,Number=1,Type=Integer,Description=\"Number of Samples With Data\">");
bw.newLine();
bw.write("##INFO=<ID=DP,Number=1,Type=Integer,Description=\"Total Depth\">");
bw.newLine();
bw.write("##INFO=<ID=AF,Number=.,Type=Float,Description=\"Allele Frequency\">");
bw.newLine();
bw.write("#CHROM" + delimChar + "POS" + delimChar + "ID" + delimChar + "REF" + delimChar + "ALT" + delimChar + "QUAL" + delimChar + "FILTER" + delimChar + "INFO" + delimChar + "FORMAT");
boolean refTaxon = false;
for (int taxa = 0; taxa < alignment.getSequenceCount(); taxa++) {
String taxonName = alignment.getIdGroup().getIdentifier(taxa).getFullName().trim();
if (taxa == 0 && taxonName.contentEquals("REFERENCE_GENOME")) {
refTaxon = true;
} else {
bw.write(delimChar + taxonName);;
}
}
bw.newLine();
for (int site = 0; site < alignment.getSiteCount(); site++) {
int[][] sortedAlleles = alignment.getAllelesSortedByFrequency(site); // which alleles are actually present among the genotypes
int nAlleles = sortedAlleles[0].length;
if (nAlleles == 0) { //used to be ==0
System.out.println("no alleles at: " + site + " " + alignment.getPositionInLocus(site));
continue;
}
byte refGeno = alignment.getReferenceAllele(site);
if (refGeno == Alignment.UNKNOWN_DIPLOID_ALLELE) {
String myMajorAllele = NucleotideAlignmentConstants.NUCLEOTIDE_ALLELES[0][sortedAlleles[0][0]];
String MajorGenotype = myMajorAllele + myMajorAllele;
refGeno = NucleotideAlignmentConstants.getNucleotideDiploidByte(MajorGenotype);
}
byte refAllele = (byte) (refGeno & 0xF); // converts from diploid to haploid allele (2nd allele)
//System.out.println(alignment.getPositionInLocus(site) + " " + refAllele);
byte[] alleleValues = null;
if (alignment instanceof MutableVCFAlignment) {
alleleValues = alignment.getAllelesByScope(Alignment.ALLELE_SCOPE_TYPE.Depth, site); // storage order of the alleles in the alignment (myCommonAlleles & myAlleleDepth) (length always 3, EVEN IF THERE ARE ONLY 2 in the genos)
} else {
alleleValues = alignment.getAllelesByScope(Alignment.ALLELE_SCOPE_TYPE.Frequency, site);
if (nAlleles > alignment.getMaxNumAlleles()) {
nAlleles = alignment.getMaxNumAlleles();
}
}
int[] alleleRedirect = new int[nAlleles]; // holds the indices of alleleValues in ref, alt1, [alt2] order (max 3 alleles)
String refAlleleStr;
int refUnknownOffset = 0;
if (refGeno == Alignment.UNKNOWN_DIPLOID_ALLELE) { // reference allele unknown - report the alleles in maj, min1, [min2] order
refUnknownOffset = 1;
refAlleleStr = ".";
int aRedirectIndex = 0;
for (int sortedAIndex = 0; sortedAIndex < nAlleles; sortedAIndex++) {
for (int aValuesIndex = 0; aValuesIndex < alleleValues.length; aValuesIndex++) {
if (alleleValues[aValuesIndex] == sortedAlleles[0][sortedAIndex]) {
alleleRedirect[aRedirectIndex] = aValuesIndex;
++aRedirectIndex;
break;
}
}
}
} else { // refAllele known
refAlleleStr = NucleotideAlignmentConstants.NUCLEOTIDE_IUPAC_HASH.get(refGeno);
//refAlleleStr = String.valueOf(refGeno);
// check if the reference allele is found among the genotypes
boolean refAlleleAmongGenos = false;
boolean refAlleleInAllelValues = false;
for (int sortedAIndex = 0; sortedAIndex < nAlleles; sortedAIndex++) {
if (sortedAlleles[0][sortedAIndex] == refAllele) {
refAlleleAmongGenos = true;
for (int aValuesIndex = 0; aValuesIndex < alleleValues.length; aValuesIndex++) {
if (alleleValues[aValuesIndex] == refAllele) {
refAlleleInAllelValues = true;
break;
}
}
break;
}
}
if (refAlleleInAllelValues) {
// the refAllele index in alleleValues should be stored in alleleRedirect[0], and the remaining in desc order of freq
int aRedirectIndex = 1;
for (int sortedAIndex = 0; sortedAIndex < nAlleles; sortedAIndex++) {
for (int aValuesIndex = 0; aValuesIndex < alleleValues.length; aValuesIndex++) {
if (alleleValues[aValuesIndex] == sortedAlleles[0][sortedAIndex]) {
if (alleleValues[aValuesIndex] == refAllele) {
alleleRedirect[0] = aValuesIndex;
} else {
alleleRedirect[aRedirectIndex] = aValuesIndex;
++aRedirectIndex;
}
break;
}
}
}
} else {
// alleleRedirect[0] set to -1, the remaining in desc order of freq: maj, min1, [min2]
if (!refAlleleAmongGenos) {
alleleRedirect = new int[alleleRedirect.length + 1];
}
alleleRedirect[0] = -1;
int aRedirectIndex = 1;
for (int sortedAIndex = 0; sortedAIndex < nAlleles; sortedAIndex++) {
for (int aValuesIndex = 0; aValuesIndex < alleleValues.length; aValuesIndex++) {
if (alleleValues[aValuesIndex] == sortedAlleles[0][sortedAIndex]) {
alleleRedirect[aRedirectIndex] = aValuesIndex;
++aRedirectIndex;
break;
}
}
}
}
}
bw.write(alignment.getLocusName(site)); // chromosome
bw.write(delimChar);
bw.write(alignment.getPositionInLocus(site) + ""); // position
bw.write(delimChar);
bw.write(alignment.getSNPID(site)); // site name
bw.write(delimChar);
bw.write(refAlleleStr); // ref allele
bw.write(delimChar);
StringBuilder altAllelesBuilder = new StringBuilder("");
int firstAltAllele = (refAlleleStr == ".") ? 0 : 1; // if ref allele is unknown, ALL alleles are alt
for (int i = firstAltAllele; i < alleleRedirect.length; i++) {
if (i != firstAltAllele) {
altAllelesBuilder.append(",");
}
byte diploidByte = (byte) ((alleleValues[alleleRedirect[i]] << 4) | alleleValues[alleleRedirect[i]]);
String AlleleStr = NucleotideAlignmentConstants.NUCLEOTIDE_IUPAC_HASH.get(diploidByte);
if (AlleleStr == null) {
altAllelesBuilder.append(".");
} else {
altAllelesBuilder.append(AlleleStr);
}
}
String altAlleles = altAllelesBuilder.toString();
altAlleles = (altAlleles.equals("")) ? "." : altAlleles;
bw.write(altAlleles); // alt alleles
bw.write(delimChar);
bw.write("."); // qual score
bw.write(delimChar);
bw.write("PASS"); // filter
bw.write(delimChar);
if (alignment instanceof MutableVCFAlignment) {
int totalDepth = 0;
for (int i = 0; i < alignment.getSequenceCount(); i++) {
byte[] depth = alignment.getDepthForAlleles(i, site);
for (int k = 0; k < depth.length; k++) {
if (depth[k] != -1) {
totalDepth += depth[k];
}
}
}
bw.write("DP=" + totalDepth); // DP
} else {
bw.write("."); // DP
}
bw.write(delimChar);
if (alignment instanceof MutableVCFAlignment) {
bw.write("GT:AD:DP:GQ:PL");
} else {
bw.write("GT");
}
for (int taxa = 0; taxa < alignment.getSequenceCount(); taxa++) {
if (taxa == 0 && refTaxon) {
continue; // don't include REFERENCE_GENOME in vcf output
}
bw.write(delimChar);
// GT = genotype
String GTstr = "";
byte[] values = alignment.getBaseArray(taxa, site);
boolean genoOne = false;
if (values[0] == Alignment.UNKNOWN_ALLELE) {
GTstr += "./";
genoOne = true;
} else {
for (int i = 0; i < alleleRedirect.length; i++) { // alleleRedirect stores the alleles in ref/alt1/[alt2] order (if no alt2,length=2)
if (i == 0 && alleleRedirect[i] == -1) { // refAllele known but either not among genos or not in alleleValues
if (values[0] == refAllele) {
GTstr += (i + refUnknownOffset) + "/";
genoOne = true;
break;
}
} else if (values[0] == alleleValues[alleleRedirect[i]]) {
GTstr += (i + refUnknownOffset) + "/";
genoOne = true;
break;
}
}
}
// if (!genoOne) {
//bw.write("./.");
// if (values[0] == NucleotideAlignmentConstants.A_ALLELE) {
// bw.write("A/");
// } else if (values[0] == NucleotideAlignmentConstants.C_ALLELE) {
// bw.write("C/");
// } else if (values[0] == NucleotideAlignmentConstants.G_ALLELE) {
// bw.write("G/");
// } else if (values[0] == NucleotideAlignmentConstants.T_ALLELE) {
// bw.write("T/");
// } else if (values[0] == NucleotideAlignmentConstants.GAP_ALLELE) {
// bw.write("-/");
// } else {
// bw.write(values[0] + "/");
// // throw new IllegalArgumentException("Unknown allele value: " + alleleValues[i]);
// }
// }
boolean genoTwo = false;
if (values[1] == Alignment.UNKNOWN_ALLELE) {
GTstr += ".";
genoTwo = true;
} else {
for (int i = 0; i < alleleRedirect.length; i++) { // alleleRedirect stores the alleles in ref/alt1/alt2 order (if no alt2,length=2)
if (i == 0 && alleleRedirect[i] == -1) { // refAllele known but either not among genos or not in alleleValues
if (values[1] == refAllele) {
GTstr += (i + refUnknownOffset) + "";
genoTwo = true;
break;
}
} else if (values[1] == alleleValues[alleleRedirect[i]]) {
GTstr += (i + refUnknownOffset) + "";
genoTwo = true;
break;
}
}
}
// if (!genoTwo) {
// if (values[1] == NucleotideAlignmentConstants.A_ALLELE) {
// bw.write("A");
// } else if (values[1] == NucleotideAlignmentConstants.C_ALLELE) {
// bw.write("C");
// } else if (values[1] == NucleotideAlignmentConstants.G_ALLELE) {
// bw.write("G");
// } else if (values[1] == NucleotideAlignmentConstants.T_ALLELE) {
// bw.write("T");
// } else if (values[1] == NucleotideAlignmentConstants.GAP_ALLELE) {
// bw.write("-");
// } else {
// bw.write(values[1] + "");
// // throw new IllegalArgumentException("Unknown allele value: " + alleleValues[i]);
// }
// }
if (genoOne && genoTwo) {
bw.write(GTstr);
} else {
bw.write("./.");
}
if (!(alignment instanceof MutableVCFAlignment)) {
continue;
}
bw.write(":");
// AD
byte[] siteAlleleDepths = alignment.getDepthForAlleles(taxa, site);
int siteTotalDepth = 0;
if (siteAlleleDepths.length != 0) {
for (int a = 0; a < alleleRedirect.length; a++) {
if (a == 0 && alleleRedirect[a] == -1) { // refAllele known but is not among the genotypes
bw.write("0");
continue;
}
if (a != 0) {
bw.write(",");
}
bw.write(((int) (siteAlleleDepths[alleleRedirect[a]])) + "");
siteTotalDepth += siteAlleleDepths[alleleRedirect[a]];
}
} else {
bw.write(".,.,.");
}
bw.write(":");
// DP
bw.write(siteTotalDepth + "");
bw.write(":");
if (siteAlleleDepths.length != 0) {
int[] scores;
if (siteAlleleDepths.length == 1) {
int dep1 = siteAlleleDepths[alleleRedirect[0]] > 127 ? 127 : siteAlleleDepths[alleleRedirect[0]];
scores = VCFUtil.getScore(dep1, 0);
} else {
if (alleleRedirect[0] == -1) {
int dep1 = 0;
int dep2 = 0;
if (alleleRedirect.length > 2) {
dep1 = siteAlleleDepths[alleleRedirect[1]] > 127 ? 127 : siteAlleleDepths[alleleRedirect[1]];
dep2 = siteAlleleDepths[alleleRedirect[2]] > 127 ? 127 : siteAlleleDepths[alleleRedirect[2]];
} else if (alleleRedirect.length == 2) {
dep1 = 0;
dep2 = siteAlleleDepths[alleleRedirect[1]] > 127 ? 127 : siteAlleleDepths[alleleRedirect[1]];
}
scores = VCFUtil.getScore(dep1, dep2);
} else {
int dep1 = siteAlleleDepths[alleleRedirect[0]] > 127 ? 127 : siteAlleleDepths[alleleRedirect[0]];
int dep2 = 0;
if (alleleRedirect.length > 1) {
dep2 = siteAlleleDepths[alleleRedirect[1]] > 127 ? 127 : siteAlleleDepths[alleleRedirect[1]];
}
scores = VCFUtil.getScore(dep1, dep2);
}
}
// GQ
if (scores == null) {
scores = new int[]{-1, -1, -1, -1};
}
bw.write(scores[3] + "");
bw.write(":");
// PL
bw.write(scores[0] + "," + scores[1] + "," + scores[2]);
} else {
bw.write(".:.,.");
}
}
bw.newLine();
}
bw.flush();
bw.close();
} catch (Exception e) {
e.printStackTrace();;
throw new IllegalArgumentException("Error writing VCF file: " + filename + ": " + ExceptionUtils.getExceptionCauses(e));
}
return filename;
}
/**
* Writes given set of alignments to a set of Plink files
*
* @param alignment
* @param filename
* @param delimChar
*/
public static String writeToPlink(Alignment alignment, String filename, char delimChar) {
if (delimChar != ' ' && delimChar != '\t') {
throw new IllegalArgumentException("Delimiter charater must be either a blank space or a tab.");
}
BufferedWriter MAPbw = null;
BufferedWriter PEDbw = null;
String mapFileName = Utils.addSuffixIfNeeded(filename, ".plk.map");
String pedFileName = Utils.addSuffixIfNeeded(filename, ".plk.ped");
try {
MAPbw = new BufferedWriter(new FileWriter(mapFileName), 1000000);
int numSites = alignment.getSiteCount();
for (int site = 0; site < numSites; site++) {
MAPbw.write(alignment.getLocusName(site)); // chromosome name
MAPbw.write(delimChar);
MAPbw.write(alignment.getSNPID(site)); // rs#
MAPbw.write(delimChar);
MAPbw.write("-9"); // genetic distance unavailable
MAPbw.write(delimChar);
MAPbw.write(Integer.toString(alignment.getPositionInLocus(site))); // position
MAPbw.write("\n");
}
MAPbw.close();
PEDbw = new BufferedWriter(new FileWriter(pedFileName), 1000000);
// Compiled : Pattern
Pattern splitter = Pattern.compile(":");
int numTaxa = alignment.getSequenceCount();
for (int taxa = 0; taxa < numTaxa; taxa++) {
String[] name = splitter.split(alignment.getIdGroup().getIdentifier(taxa).getFullName().trim());
if (name.length != 1) {
PEDbw.write(name[1]); // namelvl 1 if is available
} else {
PEDbw.write("-9");
}
PEDbw.write(delimChar);
PEDbw.write(alignment.getIdGroup().getIdentifier(taxa).getFullName().trim()); // namelvl 0
PEDbw.write(delimChar);
PEDbw.write("-9"); // paternal ID unavailable
PEDbw.write(delimChar);
PEDbw.write("-9"); // maternal ID unavailable
PEDbw.write(delimChar);
PEDbw.write("-9"); // gender is both
PEDbw.write(delimChar);
PEDbw.write("-9"); // phenotype unavailable, might have to change to "-9" for missing affection status
PEDbw.write(delimChar);
for (int site = 0; site < numSites; site++) {
String[] b = getSNPValueForPlink(alignment.getBaseAsStringArray(taxa, site));
PEDbw.write(b[0]);
PEDbw.write(delimChar);
PEDbw.write(b[b.length - 1]);
if (site != numSites - 1) {
PEDbw.write(delimChar);
}
}
PEDbw.write("\n");
}
PEDbw.close();
return mapFileName + " and " + pedFileName;
} catch (Exception e) {
myLogger.error("Error writing Plink files: " + mapFileName + " and " + pedFileName + ": " + ExceptionUtils.getExceptionCauses(e));
throw new IllegalArgumentException("Error writing Plink files: " + mapFileName + " and " + pedFileName + ": " + ExceptionUtils.getExceptionCauses(e));
} finally {
try {
PEDbw.close();
} catch (Exception e) {
// do nothing
}
try {
MAPbw.close();
} catch (Exception e) {
// do nothing
}
}
}
private static String[] getSNPValueForPlink(String[] base) {
for (int i = 0; i < base.length; i++) {
if (base[i].equals("N")) {
base[i] = "0";
} else if (base[i].equals("0")) {
base[i] = "D";
}
}
return base;
}
/**
* Writes given set of alignments to a set of Flapjack files
*
* @param alignment
* @param filename
* @param delimChar
*/
public static String writeToFlapjack(Alignment alignment, String filename, char delimChar) {
if (delimChar != ' ' && delimChar != '\t') {
throw new IllegalArgumentException("Delimiter charater must be either a blank space or a tab.");
}
String mapFileName = Utils.addSuffixIfNeeded(filename, ".flpjk.map");
String genoFileName = Utils.addSuffixIfNeeded(filename, ".flpjk.geno");
try {
BufferedWriter MAPbw = new BufferedWriter(new FileWriter(mapFileName), 1000000);
BufferedWriter DATbw = new BufferedWriter(new FileWriter(genoFileName), 1000000);
int numSites = alignment.getSiteCount();
for (int site = 0; site < numSites; site++) {
MAPbw.write(alignment.getSNPID(site)); // rs#
MAPbw.write(delimChar);
MAPbw.write(alignment.getLocusName(site)); // chromosome name
MAPbw.write(delimChar);
MAPbw.write(Integer.toString(alignment.getPositionInLocus(site))); // position
MAPbw.write("\n");
DATbw.write(delimChar);
DATbw.write(alignment.getSNPID(site));
}
MAPbw.close();
DATbw.write("\n");
int numTaxa = alignment.getSequenceCount();
for (int taxa = 0; taxa < numTaxa; taxa++) {
DATbw.write(alignment.getIdGroup().getIdentifier(taxa).getFullName().trim());
DATbw.write(delimChar);
for (int site = 0; site < numSites; site++) {
String[] b = alignment.getBaseAsStringArray(taxa, site);
b = getSNPValueForFlapJack(b);
if (b.length == 1) {
DATbw.write(b[0]);
} else if (b.length == 2) {
DATbw.write(b[0]);
DATbw.write('/');
DATbw.write(b[1]);
} else if (b.length > 2) {
DATbw.write(b[0]);
DATbw.write('/');
DATbw.write(b[1]);
DATbw.write('/');
DATbw.write(b[2]);
}
if (site != numSites - 1) {
DATbw.write(delimChar);
}
}
DATbw.write("\n");
}
DATbw.close();
return mapFileName + " and " + genoFileName;
} catch (Exception e) {
myLogger.error("Error writing Flapjack files: " + mapFileName + " and " + genoFileName + ": " + ExceptionUtils.getExceptionCauses(e));
throw new IllegalArgumentException("Error writing Flapjack files: " + mapFileName + " and " + genoFileName + ": " + ExceptionUtils.getExceptionCauses(e));
}
}
private static String[] getSNPValueForFlapJack(String[] base) {
for (int i = 0; i < base.length; i++) {
if (base[i].equals("N")) {
base[i] = "-";
}
}
return base;
}
public static String saveDelimitedAlignment(Alignment theAlignment, String delimit, String saveFile) {
if ((saveFile == null) || (saveFile.length() == 0)) {
return null;
}
saveFile = Utils.addSuffixIfNeeded(saveFile, ".txt");
FileWriter fw = null;
BufferedWriter bw = null;
try {
fw = new FileWriter(new File(saveFile));
bw = new BufferedWriter(fw);
bw.write("Taxa");
int numSites = theAlignment.getSiteCount();
for (int j = 0; j < numSites; j++) {
bw.write(delimit);
bw.write(String.valueOf(theAlignment.getPositionInLocus(j)));
}
bw.write("\n");
for (int r = 0, n = theAlignment.getSequenceCount(); r < n; r++) {
bw.write(theAlignment.getIdGroup().getIdentifier(r).getFullName());
for (int i = 0; i < numSites; i++) {
bw.write(delimit);
bw.write(theAlignment.getBaseAsString(r, i));
}
bw.write("\n");
}
return saveFile;
} catch (Exception e) {
myLogger.error("Error writing Delimited Alignment: " + saveFile + ": " + ExceptionUtils.getExceptionCauses(e));
throw new IllegalArgumentException("Error writing Delimited Alignment: " + saveFile + ": " + ExceptionUtils.getExceptionCauses(e));
} finally {
try {
bw.close();
fw.close();
} catch (Exception e) {
// do nothing
}
}
}
/**
* print alignment (in PHYLIP SEQUENTIAL format)
*/
public static void printSequential(Alignment a, PrintWriter out) {
// PHYLIP header line
out.println(" " + a.getSequenceCount() + " " + a.getSiteCount() + " S");
// Print sequences
for (int s = 0; s < a.getSequenceCount(); s++) {
int n = 0;
while (n < a.getSiteCount()) {
if (n == 0) {
format.displayLabel(out, a.getIdGroup().getIdentifier(s).getName(), 10);
out.print(" ");
} else {
out.print(" ");
}
printNextSites(a, out, false, s, n, 50);
out.println();
n += 50;
}
}
}
/**
* print alignment (in PHYLIP 3.4 INTERLEAVED format)
*/
public static void printInterleaved(Alignment a, PrintWriter out) {
int n = 0;
// PHYLIP header line
out.println(" " + a.getSequenceCount() + " " + a.getSiteCount());
// Print sequences
while (n < a.getSiteCount()) {
for (int s = 0; s < a.getSequenceCount(); s++) {
if (n == 0) {
format.displayLabel(out, a.getIdGroup().getIdentifier(s).getName(), 10);
out.print(" ");
} else {
out.print(" ");
}
printNextSites(a, out, true, s, n, 50);
out.println();
}
out.println();
n += 50;
}
}
/**
* Print alignment (in CLUSTAL W format)
*/
public static void printCLUSTALW(Alignment a, PrintWriter out) {
int n = 0;
// CLUSTAL W header line
out.println("CLUSTAL W multiple sequence alignment");
out.println();
// Print sequences
while (n < a.getSiteCount()) {
out.println();
for (int s = 0; s < a.getSequenceCount(); s++) {
format.displayLabel(out, a.getIdGroup().getIdentifier(s).getName(), 10);
out.print(" ");
printNextSites(a, out, false, s, n, 50);
out.println();
}
// Blanks in status line are necessary for some parsers)
out.println(" ");
n += 50;
}
}
private static void printNextSites(Alignment a, PrintWriter out, boolean chunked, int seq, int start, int num) {
// Print next num characters
for (int i = 0; (i < num) && (start + i < a.getSiteCount()); i++) {
// Chunks of 10 characters
if (i % 10 == 0 && i != 0 && chunked) {
out.print(' ');
}
out.print(a.getBaseAsString(seq, start + i));
}
}
public static String writeAlignmentToSerialGZ(Alignment sba, String outFile) {
long time = System.currentTimeMillis();
File theFile = null;
FileOutputStream fos = null;
GZIPOutputStream gz = null;
ObjectOutputStream oos = null;
try {
theFile = new File(Utils.addSuffixIfNeeded(outFile, ".serial.gz"));
fos = new FileOutputStream(theFile);
gz = new GZIPOutputStream(fos);
oos = new ObjectOutputStream(gz);
oos.writeObject(sba);
return theFile.getName();
} catch (Exception e) {
e.printStackTrace();
myLogger.error("Error writing Serial GZ: " + theFile.getName() + ": " + ExceptionUtils.getExceptionCauses(e));
throw new IllegalArgumentException("Error writing Serial GZ: " + theFile.getName() + ": " + ExceptionUtils.getExceptionCauses(e));
} finally {
try {
oos.flush();
oos.close();
gz.close();
fos.close();
} catch (Exception e) {
// do nothing
}
myLogger.info("writeAlignmentToSerialGZ: " + theFile.toString() + " Time: " + (System.currentTimeMillis() - time));
}
}
}
|
src/net/maizegenetics/pal/alignment/ExportUtils.java
|
/*
* ExportUtils
*/
package net.maizegenetics.pal.alignment;
import ch.systemsx.cisd.base.mdarray.MDArray;
import ch.systemsx.cisd.hdf5.HDF5Factory;
import ch.systemsx.cisd.hdf5.HDF5IntStorageFeatures;
import ch.systemsx.cisd.hdf5.IHDF5Writer;
import ch.systemsx.cisd.hdf5.IHDF5WriterConfigurator;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.util.regex.Pattern;
import java.util.zip.GZIPOutputStream;
import net.maizegenetics.pal.io.FormattedOutput;
import net.maizegenetics.util.ExceptionUtils;
import net.maizegenetics.util.ProgressListener;
import net.maizegenetics.util.Utils;
import net.maizegenetics.util.VCFUtil;
import org.apache.log4j.Logger;
/**
* The class exports PAL alignment data types to various file formats.
*
* @author Jon, Terry, Ed
*/
public class ExportUtils {
private static final Logger myLogger = Logger.getLogger(ExportUtils.class);
private static FormattedOutput format = FormattedOutput.getInstance();
private ExportUtils() {
// Utility Class - do not instantiate.
}
public static String writeToHDF5(Alignment a, String newHDF5file) {
a = AlignmentUtils.optimizeForTaxaAndSites(a);
IHDF5Writer h5w = null;
try {
int numSites = a.getSiteCount();
int numTaxa = a.getSequenceCount();
newHDF5file = Utils.addSuffixIfNeeded(newHDF5file, ".hmp.h5");
File hdf5File = new File(newHDF5file);
if (hdf5File.exists()) {
throw new IllegalArgumentException("ExportUtils: writeToHDF5: File already exists: " + newHDF5file);
}
IHDF5WriterConfigurator config = HDF5Factory.configure(hdf5File);
myLogger.info("Writing HDF5 file: " + newHDF5file);
config.overwrite();
config.dontUseExtendableDataTypes();
h5w = config.writer();
h5w.setIntAttribute(HapMapHDF5Constants.DEFAULT_ATTRIBUTES_PATH, HapMapHDF5Constants.MAX_NUM_ALLELES, a.getMaxNumAlleles());
h5w.setBooleanAttribute(HapMapHDF5Constants.DEFAULT_ATTRIBUTES_PATH, HapMapHDF5Constants.RETAIN_RARE_ALLELES, a.retainsRareAlleles());
h5w.setIntAttribute(HapMapHDF5Constants.DEFAULT_ATTRIBUTES_PATH, HapMapHDF5Constants.NUM_TAXA, numTaxa);
int numSBitWords = a.getAllelePresenceForAllTaxa(0, 0).getNumWords();
h5w.setIntAttribute(HapMapHDF5Constants.DEFAULT_ATTRIBUTES_PATH, HapMapHDF5Constants.NUM_SBIT_WORDS, numSBitWords);
int numTBitWords = a.getAllelePresenceForAllSites(0, 0).getNumWords();
h5w.setIntAttribute(HapMapHDF5Constants.DEFAULT_ATTRIBUTES_PATH, HapMapHDF5Constants.NUM_TBIT_WORDS, numTBitWords);
String[][] aEncodings = a.getAlleleEncodings();
//myLogger.info(Arrays.deepToString(aEncodings));
int numEncodings = aEncodings.length;
int numStates = aEncodings[0].length;
MDArray<String> alleleEncodings = new MDArray<String>(String.class, new int[]{numEncodings, numStates});
for (int s = 0; s < numEncodings; s++) {
for (int x = 0; x < numStates; x++) {
alleleEncodings.set(aEncodings[s][x], s, x);
}
}
h5w.createStringMDArray(HapMapHDF5Constants.ALLELE_STATES, 100, new int[]{numEncodings, numStates});
h5w.writeStringMDArray(HapMapHDF5Constants.ALLELE_STATES, alleleEncodings);
MDArray<String> alleleEncodingReadAgain = h5w.readStringMDArray(HapMapHDF5Constants.ALLELE_STATES);
if (alleleEncodings.equals(alleleEncodingReadAgain) == false) {
throw new IllegalStateException("ExportUtils: writeToHDF5: Mismatch Allele States, expected '" + alleleEncodings + "', found '" + alleleEncodingReadAgain + "'!");
}
h5w.writeStringArray(HapMapHDF5Constants.SNP_IDS, a.getSNPIDs());
h5w.createGroup(HapMapHDF5Constants.SBIT);
h5w.setIntAttribute(HapMapHDF5Constants.DEFAULT_ATTRIBUTES_PATH, HapMapHDF5Constants.NUM_SITES, numSites);
String[] lociNames = new String[a.getNumLoci()];
Locus[] loci = a.getLoci();
for (int i = 0; i < a.getNumLoci(); i++) {
lociNames[i] = loci[i].getName();
}
h5w.createStringVariableLengthArray(HapMapHDF5Constants.LOCI, a.getNumLoci());
h5w.writeStringVariableLengthArray(HapMapHDF5Constants.LOCI, lociNames);
h5w.createIntArray(HapMapHDF5Constants.LOCUS_OFFSETS, a.getNumLoci());
h5w.writeIntArray(HapMapHDF5Constants.LOCUS_OFFSETS, a.getLociOffsets());
h5w.createIntArray(HapMapHDF5Constants.POSITIONS, numSites);
h5w.writeIntArray(HapMapHDF5Constants.POSITIONS, a.getPhysicalPositions());
h5w.createByteMatrix(HapMapHDF5Constants.ALLELES, a.getSiteCount(), a.getMaxNumAlleles());
byte[][] alleles = new byte[numSites][a.getMaxNumAlleles()];
for (int i = 0; i < numSites; i++) {
alleles[i] = a.getAlleles(i);
}
h5w.writeByteMatrix(HapMapHDF5Constants.ALLELES, alleles);
String[] tn = new String[numTaxa];
for (int i = 0; i < tn.length; i++) {
tn[i] = a.getFullTaxaName(i);
}
h5w.createStringVariableLengthArray(HapMapHDF5Constants.TAXA, numTaxa);
h5w.writeStringVariableLengthArray(HapMapHDF5Constants.TAXA, tn);
for (int aNum = 0; aNum < a.getTotalNumAlleles(); aNum++) {
String currentSBitPath = HapMapHDF5Constants.SBIT + "/" + aNum;
h5w.createLongMatrix(currentSBitPath, numSites, numSBitWords, 1, numSBitWords);
long[][] lgarray = new long[numSites][numSBitWords];
for (int i = 0; i < numSites; i++) {
lgarray[i] = a.getAllelePresenceForAllTaxa(i, aNum).getBits();
}
h5w.writeLongMatrix(currentSBitPath, lgarray);
String currentTBitPath = HapMapHDF5Constants.TBIT + "/" + aNum;
h5w.createLongMatrix(currentTBitPath, numTaxa, numTBitWords, 1, numTBitWords);
lgarray = new long[numTaxa][numTBitWords];
for (int i = 0; i < numTaxa; i++) {
lgarray[i] = a.getAllelePresenceForAllSites(i, aNum).getBits();
}
h5w.writeLongMatrix(currentTBitPath, lgarray);
}
return newHDF5file;
} finally {
try {
h5w.close();
} catch (Exception e) {
// do nothing
}
}
}
public static String writeToMutableHDF5(Alignment a, String newHDF5file) {
IHDF5Writer h5w = null;
try {
int numSites = a.getSiteCount();
int numTaxa = a.getSequenceCount();
newHDF5file = Utils.addSuffixIfNeeded(newHDF5file, "mutable.hmp.h5");
File hdf5File = new File(newHDF5file);
if (hdf5File.exists()) {
throw new IllegalArgumentException("ExportUtils: writeToMutableHDF5: File already exists: " + newHDF5file);
}
IHDF5WriterConfigurator config = HDF5Factory.configure(hdf5File);
myLogger.info("Writing Mutable HDF5 file: " + newHDF5file);
config.overwrite();
config.dontUseExtendableDataTypes();
h5w = config.writer();
h5w.setIntAttribute(HapMapHDF5Constants.DEFAULT_ATTRIBUTES_PATH, HapMapHDF5Constants.MAX_NUM_ALLELES, a.getMaxNumAlleles());
h5w.setBooleanAttribute(HapMapHDF5Constants.DEFAULT_ATTRIBUTES_PATH, HapMapHDF5Constants.RETAIN_RARE_ALLELES, a.retainsRareAlleles());
h5w.setIntAttribute(HapMapHDF5Constants.DEFAULT_ATTRIBUTES_PATH, HapMapHDF5Constants.NUM_TAXA, numTaxa);
String[][] aEncodings = a.getAlleleEncodings();
int numEncodings = aEncodings.length;
int numStates = aEncodings[0].length;
MDArray<String> alleleEncodings = new MDArray<String>(String.class, new int[]{numEncodings, numStates});
for (int s = 0; s < numEncodings; s++) {
for (int x = 0; x < numStates; x++) {
alleleEncodings.set(aEncodings[s][x], s, x);
}
}
h5w.createStringMDArray(HapMapHDF5Constants.ALLELE_STATES, 100, new int[]{numEncodings, numStates});
h5w.writeStringMDArray(HapMapHDF5Constants.ALLELE_STATES, alleleEncodings);
MDArray<String> alleleEncodingReadAgain = h5w.readStringMDArray(HapMapHDF5Constants.ALLELE_STATES);
if (alleleEncodings.equals(alleleEncodingReadAgain) == false) {
throw new IllegalStateException("ExportUtils: writeToMutableHDF5: Mismatch Allele States, expected '" + alleleEncodings + "', found '" + alleleEncodingReadAgain + "'!");
}
h5w.writeStringArray(HapMapHDF5Constants.SNP_IDS, a.getSNPIDs());
h5w.setIntAttribute(HapMapHDF5Constants.DEFAULT_ATTRIBUTES_PATH, HapMapHDF5Constants.NUM_SITES, numSites);
String[] lociNames = new String[a.getNumLoci()];
Locus[] loci = a.getLoci();
for (int i = 0; i < a.getNumLoci(); i++) {
lociNames[i] = loci[i].getName();
}
h5w.createStringVariableLengthArray(HapMapHDF5Constants.LOCI, a.getNumLoci());
h5w.writeStringVariableLengthArray(HapMapHDF5Constants.LOCI, lociNames);
h5w.createIntArray(HapMapHDF5Constants.LOCUS_OFFSETS, a.getNumLoci());
h5w.writeIntArray(HapMapHDF5Constants.LOCUS_OFFSETS, a.getLociOffsets());
h5w.createIntArray(HapMapHDF5Constants.POSITIONS, numSites);
h5w.writeIntArray(HapMapHDF5Constants.POSITIONS, a.getPhysicalPositions());
h5w.createByteMatrix(HapMapHDF5Constants.ALLELES, a.getSiteCount(), a.getMaxNumAlleles());
byte[][] alleles = new byte[numSites][a.getMaxNumAlleles()];
for (int i = 0; i < numSites; i++) {
alleles[i] = a.getAlleles(i);
}
h5w.writeByteMatrix(HapMapHDF5Constants.ALLELES, alleles);
// Write Bases
HDF5IntStorageFeatures features = HDF5IntStorageFeatures.createDeflation(HDF5IntStorageFeatures.MAX_DEFLATION_LEVEL);
HDF5IntStorageFeatures.createDeflationDelete(HDF5IntStorageFeatures.MAX_DEFLATION_LEVEL);
for (int t = 0; t < numTaxa; t++) {
String basesPath = HapMapHDF5Constants.GENOTYPES + "/" + a.getFullTaxaName(t);
h5w.createByteArray(basesPath, numSites, features);
byte[] bases = a.getBaseRow(t);
h5w.writeByteArray(basesPath, bases, features);
}
return newHDF5file;
} finally {
try {
h5w.close();
} catch (Exception e) {
// do nothing
}
}
}
/**
* Writes multiple alignments to single Hapmap file. Currently no error
* checking
*
* @param alignment array of alignments
* @param diploid
* @param filename
* @param delimChar
*/
public static String writeToHapmap(Alignment alignment, boolean diploid, String filename, char delimChar, ProgressListener listener) {
if (delimChar != ' ' && delimChar != '\t') {
throw new IllegalArgumentException("Delimiter charater must be either a blank space or a tab.");
}
BufferedWriter bw = null;
try {
String fullFileName = Utils.addSuffixIfNeeded(filename, ".hmp.txt", new String[]{".hmp.txt", ".hmp.txt.gz"});
bw = Utils.getBufferedWriter(fullFileName);
bw.write("rs#");
bw.write(delimChar);
bw.write("alleles");
bw.write(delimChar);
bw.write("chrom");
bw.write(delimChar);
bw.write("pos");
bw.write(delimChar);
bw.write("strand");
bw.write(delimChar);
bw.write("assembly#");
bw.write(delimChar);
bw.write("center");
bw.write(delimChar);
bw.write("protLSID");
bw.write(delimChar);
bw.write("assayLSID");
bw.write(delimChar);
bw.write("panelLSID");
bw.write(delimChar);
bw.write("QCcode");
bw.write(delimChar);
int numTaxa = alignment.getSequenceCount();
for (int taxa = 0; taxa < numTaxa; taxa++) {
//finish filling out first row
//not completely sure this does what I want, I need to access the
//accession name from every alleleBLOB in bytes [52-201] but there
//doesn't seem to be a method to access that in Alignment
String sequenceID = alignment.getIdGroup().getIdentifier(taxa).getFullName().trim();
bw.write(sequenceID);
if (taxa != numTaxa - 1) {
bw.write(delimChar);
}
}
bw.write("\n");
int numSites = alignment.getSiteCount();
for (int site = 0; site < numSites; site++) {
bw.write(alignment.getSNPID(site));
bw.write(delimChar);
// byte[] alleles = alignment.getAlleles(site); // doesn't work right for MutableVCFAlignment (always returns 3 alleles, even if no data)
// int numAlleles = alleles.length;
int[][] sortedAlleles = alignment.getAllelesSortedByFrequency(site); // which alleles are actually present among the genotypes
int numAlleles = sortedAlleles[0].length;
if (numAlleles == 0) {
bw.write("NA"); //if data does not exist
} else if (numAlleles == 1) {
bw.write(alignment.getBaseAsString(site, (byte) sortedAlleles[0][0]));
} else {
bw.write(alignment.getBaseAsString(site, (byte) sortedAlleles[0][0]));
for (int allele = 1; allele < sortedAlleles[0].length; allele++) {
if (sortedAlleles[0][allele] != Alignment.UNKNOWN_ALLELE) {
bw.write('/');
bw.write(alignment.getBaseAsString(site, (byte) sortedAlleles[0][allele])); // will write out a third allele if it exists
}
}
}
bw.write(delimChar);
bw.write(alignment.getLocusName(site));
bw.write(delimChar);
bw.write(String.valueOf(alignment.getPositionInLocus(site)));
bw.write(delimChar);
bw.write("+"); //strand
bw.write(delimChar);
bw.write("NA"); //assembly# not supported
bw.write(delimChar);
bw.write("NA"); //center unavailable
bw.write(delimChar);
bw.write("NA"); //protLSID unavailable
bw.write(delimChar);
bw.write("NA"); //assayLSID unavailable
bw.write(delimChar);
bw.write("NA"); //panelLSID unavailable
bw.write(delimChar);
bw.write("NA"); //QCcode unavailable
bw.write(delimChar);
for (int taxa = 0; taxa < numTaxa; taxa++) {
if (diploid == false) {
String baseIUPAC = null;
try {
baseIUPAC = alignment.getBaseAsString(taxa, site);
} catch (Exception e) {
String[] b = alignment.getBaseAsStringArray(taxa, site);
throw new IllegalArgumentException("There is no String representation for diploid values: " + b[0] + ":" + b[1] + " getBase(): 0x" + Integer.toHexString(alignment.getBase(taxa, site)) + "\nTry Exporting as Diploid Values.");
}
if ((baseIUPAC == null) || baseIUPAC.equals("?")) {
String[] b = alignment.getBaseAsStringArray(taxa, site);
throw new IllegalArgumentException("There is no String representation for diploid values: " + b[0] + ":" + b[1] + " getBase(): 0x" + Integer.toHexString(alignment.getBase(taxa, site)) + "\nTry Exporting as Diploid Values.");
}
bw.write(baseIUPAC);
} else {
String[] b = alignment.getBaseAsStringArray(taxa, site);
if (b.length == 1) {
bw.write(b[0]);
bw.write(b[0]);
} else {
bw.write(b[0]);
bw.write(b[1]);
}
}
if (taxa != (numTaxa - 1)) {
bw.write(delimChar);
}
}
bw.write("\n");
if (listener != null) {
listener.progress((int) (((double) (site + 1) / (double) numSites) * 100.0), null);
}
}
return fullFileName;
} catch (Exception e) {
e.printStackTrace();
throw new IllegalArgumentException("Error writing Hapmap file: " + filename + ": " + ExceptionUtils.getExceptionCauses(e));
} finally {
try {
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Writes multiple alignments to single Hapmap file. Currently no error
* checking
*
* @param alignment array of alignments
* @param diploid
* @param filename
* @param delimChar
*/
public static String writeToHapmap(Alignment alignment, AlignmentMask mask, boolean diploid, String filename, char delimChar, ProgressListener listener) {
if (delimChar != ' ' && delimChar != '\t') {
throw new IllegalArgumentException("Delimiter charater must be either a blank space or a tab.");
}
BufferedWriter bw = null;
try {
String fullFileName = Utils.addSuffixIfNeeded(filename, ".hmp.txt", new String[]{".hmp.txt", ".hmp.txt.gz"});
bw = Utils.getBufferedWriter(fullFileName);
bw.write("rs#");
bw.write(delimChar);
bw.write("alleles");
bw.write(delimChar);
bw.write("chrom");
bw.write(delimChar);
bw.write("pos");
bw.write(delimChar);
bw.write("strand");
bw.write(delimChar);
bw.write("assembly#");
bw.write(delimChar);
bw.write("center");
bw.write(delimChar);
bw.write("protLSID");
bw.write(delimChar);
bw.write("assayLSID");
bw.write(delimChar);
bw.write("panelLSID");
bw.write(delimChar);
bw.write("QCcode");
bw.write(delimChar);
int numTaxa = alignment.getSequenceCount();
for (int taxa = 0; taxa < numTaxa; taxa++) {
//finish filling out first row
//not completely sure this does what I want, I need to access the
//accession name from every alleleBLOB in bytes [52-201] but there
//doesn't seem to be a method to access that in Alignment
String sequenceID = alignment.getIdGroup().getIdentifier(taxa).getFullName().trim();
bw.write(sequenceID);
if (taxa != numTaxa - 1) {
bw.write(delimChar);
}
}
bw.write("\n");
int numSites = alignment.getSiteCount();
for (int site = 0; site < numSites; site++) {
bw.write(alignment.getSNPID(site));
bw.write(delimChar);
// byte[] alleles = alignment.getAlleles(site); // doesn't work right for MutableVCFAlignment (always returns 3 alleles, even if no data)
// int numAlleles = alleles.length;
int[][] sortedAlleles = alignment.getAllelesSortedByFrequency(site); // which alleles are actually present among the genotypes
int numAlleles = sortedAlleles[0].length;
if (numAlleles == 0) {
bw.write("NA"); //if data does not exist
} else if (numAlleles == 1) {
bw.write(alignment.getBaseAsString(site, (byte) sortedAlleles[0][0]));
} else {
bw.write(alignment.getBaseAsString(site, (byte) sortedAlleles[0][0]));
for (int allele = 1; allele < sortedAlleles[0].length; allele++) {
if (sortedAlleles[0][allele] != Alignment.UNKNOWN_ALLELE) {
bw.write('/');
bw.write(alignment.getBaseAsString(site, (byte) sortedAlleles[0][allele])); // will write out a third allele if it exists
}
}
}
bw.write(delimChar);
bw.write(alignment.getLocusName(site));
bw.write(delimChar);
bw.write(String.valueOf(alignment.getPositionInLocus(site)));
bw.write(delimChar);
bw.write("+"); //strand
bw.write(delimChar);
bw.write("NA"); //assembly# not supported
bw.write(delimChar);
bw.write("NA"); //center unavailable
bw.write(delimChar);
bw.write("NA"); //protLSID unavailable
bw.write(delimChar);
bw.write("NA"); //assayLSID unavailable
bw.write(delimChar);
bw.write("NA"); //panelLSID unavailable
bw.write(delimChar);
bw.write("NA"); //QCcode unavailable
bw.write(delimChar);
for (int taxa = 0; taxa < numTaxa; taxa++) {
if (diploid == false) {
String baseIUPAC = alignment.getBaseAsString(taxa, site);
if (mask.getMask(taxa, site) == 0x0) {
bw.write(baseIUPAC);
} else if (mask.getMask(taxa, site) == 0x1) {
bw.write(baseIUPAC.toLowerCase());
}
} else {
String[] b = alignment.getBaseAsStringArray(taxa, site);
if (b.length == 1) {
if (mask.getMask(taxa, site) == 0x0) {
bw.write(b[0]);
bw.write(b[0]);
} else if (mask.getMask(taxa, site) == 0x1) {
bw.write(b[0].toLowerCase());
bw.write(b[0].toLowerCase());
}
} else {
if (mask.getMask(taxa, site) == 0x0) {
bw.write(b[0]);
bw.write(b[1]);
} else if (mask.getMask(taxa, site) == 0x1) {
bw.write(b[0].toLowerCase());
bw.write(b[1].toLowerCase());
}
}
}
if (taxa != (numTaxa - 1)) {
bw.write(delimChar);
}
}
bw.write("\n");
if (listener != null) {
listener.progress((int) (((double) (site + 1) / (double) numSites) * 100.0), null);
}
}
return fullFileName;
} catch (Exception e) {
e.printStackTrace();
throw new IllegalArgumentException("Error writing Hapmap file: " + filename + ": " + ExceptionUtils.getExceptionCauses(e));
} finally {
try {
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Writes given alignment to a VCF file
*
* @param alignment
* @param filename
* @return
*/
public static String writeToVCF(Alignment alignment, String filename, char delimChar) {
try {
filename = Utils.addSuffixIfNeeded(filename, ".vcf", new String[]{".vcf", ".vcf.gz"});
BufferedWriter bw = Utils.getBufferedWriter(filename);
bw.write("##fileformat=VCFv4.0");
bw.newLine();
if (alignment.getReferenceAllele(0) == Alignment.UNKNOWN_DIPLOID_ALLELE) {
bw.write("##Reference allele is not known. The major allele was used as reference allele.");
bw.newLine();
}
bw.write("##FORMAT=<ID=GT,Number=1,Type=String,Description=\"Genotype\">");
bw.newLine();
bw.write("##FORMAT=<ID=AD,Number=.,Type=Integer,Description=\"Allelic depths for the reference and alternate alleles in the order listed\">");
bw.newLine();
bw.write("##FORMAT=<ID=DP,Number=1,Type=Integer,Description=\"Read Depth (only filtered reads used for calling)\">");
bw.newLine();
bw.write("##FORMAT=<ID=GQ,Number=1,Type=Float,Description=\"Genotype Quality\">");
bw.newLine();
bw.write("####FORMAT=<ID=PL,Number=3,Type=Float,Description=\"Normalized, Phred-scaled likelihoods for AA,AB,BB genotypes where A=ref and B=alt; not applicable if site is not biallelic\">");
bw.newLine();
bw.write("##INFO=<ID=NS,Number=1,Type=Integer,Description=\"Number of Samples With Data\">");
bw.newLine();
bw.write("##INFO=<ID=DP,Number=1,Type=Integer,Description=\"Total Depth\">");
bw.newLine();
bw.write("##INFO=<ID=AF,Number=.,Type=Float,Description=\"Allele Frequency\">");
bw.newLine();
bw.write("#CHROM" + delimChar + "POS" + delimChar + "ID" + delimChar + "REF" + delimChar + "ALT" + delimChar + "QUAL" + delimChar + "FILTER" + delimChar + "INFO" + delimChar + "FORMAT");
boolean refTaxon = false;
for (int taxa = 0; taxa < alignment.getSequenceCount(); taxa++) {
String taxonName = alignment.getIdGroup().getIdentifier(taxa).getFullName().trim();
if (taxa == 0 && taxonName.contentEquals("REFERENCE_GENOME")) {
refTaxon = true;
} else {
bw.write(delimChar + taxonName);;
}
}
bw.newLine();
for (int site = 0; site < alignment.getSiteCount(); site++) {
int[][] sortedAlleles = alignment.getAllelesSortedByFrequency(site); // which alleles are actually present among the genotypes
int nAlleles = sortedAlleles[0].length;
if (nAlleles == 0) { //used to be ==0
System.out.println("no alleles at: " + site + " " + alignment.getPositionInLocus(site));
continue;
}
byte refGeno = alignment.getReferenceAllele(site);
if (refGeno == Alignment.UNKNOWN_DIPLOID_ALLELE) {
String myMajorAllele = NucleotideAlignmentConstants.NUCLEOTIDE_ALLELES[0][sortedAlleles[0][0]];
String MajorGenotype = myMajorAllele + myMajorAllele;
refGeno = NucleotideAlignmentConstants.getNucleotideDiploidByte(MajorGenotype);
}
byte refAllele = (byte) (refGeno & 0xF); // converts from diploid to haploid allele (2nd allele)
//System.out.println(alignment.getPositionInLocus(site) + " " + refAllele);
byte[] alleleValues = null;
if (alignment instanceof MutableVCFAlignment) {
alleleValues = alignment.getAllelesByScope(Alignment.ALLELE_SCOPE_TYPE.Depth, site); // storage order of the alleles in the alignment (myCommonAlleles & myAlleleDepth) (length always 3, EVEN IF THERE ARE ONLY 2 in the genos)
} else {
alleleValues = alignment.getAllelesByScope(Alignment.ALLELE_SCOPE_TYPE.Frequency, site);
if (nAlleles > alignment.getMaxNumAlleles()) {
nAlleles = alignment.getMaxNumAlleles();
}
}
int[] alleleRedirect = new int[nAlleles]; // holds the indices of alleleValues in ref, alt1, [alt2] order (max 3 alleles)
String refAlleleStr;
int refUnknownOffset = 0;
if (refGeno == Alignment.UNKNOWN_DIPLOID_ALLELE) { // reference allele unknown - report the alleles in maj, min1, [min2] order
refUnknownOffset = 1;
refAlleleStr = ".";
int aRedirectIndex = 0;
for (int sortedAIndex = 0; sortedAIndex < nAlleles; sortedAIndex++) {
for (int aValuesIndex = 0; aValuesIndex < alleleValues.length; aValuesIndex++) {
if (alleleValues[aValuesIndex] == sortedAlleles[0][sortedAIndex]) {
alleleRedirect[aRedirectIndex] = aValuesIndex;
++aRedirectIndex;
break;
}
}
}
} else { // refAllele known
refAlleleStr = NucleotideAlignmentConstants.NUCLEOTIDE_IUPAC_HASH.get(refGeno);
//refAlleleStr = String.valueOf(refGeno);
// check if the reference allele is found among the genotypes
boolean refAlleleAmongGenos = false;
boolean refAlleleInAllelValues = false;
for (int sortedAIndex = 0; sortedAIndex < nAlleles; sortedAIndex++) {
if (sortedAlleles[0][sortedAIndex] == refAllele) {
refAlleleAmongGenos = true;
for (int aValuesIndex = 0; aValuesIndex < alleleValues.length; aValuesIndex++) {
if (alleleValues[aValuesIndex] == refAllele) {
refAlleleInAllelValues = true;
break;
}
}
break;
}
}
if (refAlleleInAllelValues) {
// the refAllele index in alleleValues should be stored in alleleRedirect[0], and the remaining in desc order of freq
int aRedirectIndex = 1;
for (int sortedAIndex = 0; sortedAIndex < nAlleles; sortedAIndex++) {
for (int aValuesIndex = 0; aValuesIndex < alleleValues.length; aValuesIndex++) {
if (alleleValues[aValuesIndex] == sortedAlleles[0][sortedAIndex]) {
if (alleleValues[aValuesIndex] == refAllele) {
alleleRedirect[0] = aValuesIndex;
} else {
alleleRedirect[aRedirectIndex] = aValuesIndex;
++aRedirectIndex;
}
break;
}
}
}
} else {
// alleleRedirect[0] set to -1, the remaining in desc order of freq: maj, min1, [min2]
if (!refAlleleAmongGenos) {
alleleRedirect = new int[alleleRedirect.length + 1];
}
alleleRedirect[0] = -1;
int aRedirectIndex = 1;
for (int sortedAIndex = 0; sortedAIndex < nAlleles; sortedAIndex++) {
for (int aValuesIndex = 0; aValuesIndex < alleleValues.length; aValuesIndex++) {
if (alleleValues[aValuesIndex] == sortedAlleles[0][sortedAIndex]) {
alleleRedirect[aRedirectIndex] = aValuesIndex;
++aRedirectIndex;
break;
}
}
}
}
}
bw.write(alignment.getLocusName(site)); // chromosome
bw.write(delimChar);
bw.write(alignment.getPositionInLocus(site) + ""); // position
bw.write(delimChar);
bw.write(alignment.getSNPID(site)); // site name
bw.write(delimChar);
bw.write(refAlleleStr); // ref allele
bw.write(delimChar);
StringBuilder altAllelesBuilder = new StringBuilder("");
int firstAltAllele = (refAlleleStr == ".") ? 0 : 1; // if ref allele is unknown, ALL alleles are alt
for (int i = firstAltAllele; i < alleleRedirect.length; i++) {
if (i != firstAltAllele) {
altAllelesBuilder.append(",");
}
byte diploidByte = (byte) ((alleleValues[alleleRedirect[i]] << 4) | alleleValues[alleleRedirect[i]]);
String AlleleStr = NucleotideAlignmentConstants.NUCLEOTIDE_IUPAC_HASH.get(diploidByte);
if (AlleleStr == null) {
altAllelesBuilder.append(".");
} else {
altAllelesBuilder.append(AlleleStr);
}
}
String altAlleles = altAllelesBuilder.toString();
altAlleles = (altAlleles.equals("")) ? "." : altAlleles;
bw.write(altAlleles); // alt alleles
bw.write(delimChar);
bw.write("."); // qual score
bw.write(delimChar);
bw.write("PASS"); // filter
bw.write(delimChar);
if (alignment instanceof MutableVCFAlignment) {
int totalDepth = 0;
for (int i = 0; i < alignment.getSequenceCount(); i++) {
byte[] depth = alignment.getDepthForAlleles(i, site);
for (int k = 0; k < depth.length; k++) {
if (depth[k] != -1) {
totalDepth += depth[k];
}
}
}
bw.write("DP=" + totalDepth); // DP
} else {
bw.write("."); // DP
}
bw.write(delimChar);
if (alignment instanceof MutableVCFAlignment) {
bw.write("GT:AD:DP:GQ:PL");
} else {
bw.write("GT");
}
for (int taxa = 0; taxa < alignment.getSequenceCount(); taxa++) {
if (taxa == 0 && refTaxon) {
continue; // don't include REFERENCE_GENOME in vcf output
}
bw.write(delimChar);
// GT = genotype
String GTstr = "";
byte[] values = alignment.getBaseArray(taxa, site);
boolean genoOne = false;
if (values[0] == Alignment.UNKNOWN_ALLELE) {
GTstr += "./";
genoOne = true;
} else {
for (int i = 0; i < alleleRedirect.length; i++) { // alleleRedirect stores the alleles in ref/alt1/[alt2] order (if no alt2,length=2)
if (i == 0 && alleleRedirect[i] == -1) { // refAllele known but either not among genos or not in alleleValues
if (values[0] == refAllele) {
GTstr += (i + refUnknownOffset) + "/";
genoOne = true;
break;
}
} else if (values[0] == alleleValues[alleleRedirect[i]]) {
GTstr += (i + refUnknownOffset) + "/";
genoOne = true;
break;
}
}
}
// if (!genoOne) {
//bw.write("./.");
// if (values[0] == NucleotideAlignmentConstants.A_ALLELE) {
// bw.write("A/");
// } else if (values[0] == NucleotideAlignmentConstants.C_ALLELE) {
// bw.write("C/");
// } else if (values[0] == NucleotideAlignmentConstants.G_ALLELE) {
// bw.write("G/");
// } else if (values[0] == NucleotideAlignmentConstants.T_ALLELE) {
// bw.write("T/");
// } else if (values[0] == NucleotideAlignmentConstants.GAP_ALLELE) {
// bw.write("-/");
// } else {
// bw.write(values[0] + "/");
// // throw new IllegalArgumentException("Unknown allele value: " + alleleValues[i]);
// }
// }
boolean genoTwo = false;
if (values[1] == Alignment.UNKNOWN_ALLELE) {
GTstr += ".";
genoTwo = true;
} else {
for (int i = 0; i < alleleRedirect.length; i++) { // alleleRedirect stores the alleles in ref/alt1/alt2 order (if no alt2,length=2)
if (i == 0 && alleleRedirect[i] == -1) { // refAllele known but either not among genos or not in alleleValues
if (values[1] == refAllele) {
GTstr += (i + refUnknownOffset) + "";
genoTwo = true;
break;
}
} else if (values[1] == alleleValues[alleleRedirect[i]]) {
GTstr += (i + refUnknownOffset) + "";
genoTwo = true;
break;
}
}
}
// if (!genoTwo) {
// if (values[1] == NucleotideAlignmentConstants.A_ALLELE) {
// bw.write("A");
// } else if (values[1] == NucleotideAlignmentConstants.C_ALLELE) {
// bw.write("C");
// } else if (values[1] == NucleotideAlignmentConstants.G_ALLELE) {
// bw.write("G");
// } else if (values[1] == NucleotideAlignmentConstants.T_ALLELE) {
// bw.write("T");
// } else if (values[1] == NucleotideAlignmentConstants.GAP_ALLELE) {
// bw.write("-");
// } else {
// bw.write(values[1] + "");
// // throw new IllegalArgumentException("Unknown allele value: " + alleleValues[i]);
// }
// }
if (genoOne && genoTwo) {
bw.write(GTstr);
} else {
bw.write("./.");
}
if (!(alignment instanceof MutableVCFAlignment)) {
continue;
}
bw.write(":");
// AD
byte[] siteAlleleDepths = alignment.getDepthForAlleles(taxa, site);
int siteTotalDepth = 0;
if (siteAlleleDepths.length != 0) {
for (int a = 0; a < alleleRedirect.length; a++) {
if (a == 0 && alleleRedirect[a] == -1) { // refAllele known but is not among the genotypes
bw.write("0");
continue;
}
if (a != 0) {
bw.write(",");
}
bw.write(((int) (siteAlleleDepths[alleleRedirect[a]])) + "");
siteTotalDepth += siteAlleleDepths[alleleRedirect[a]];
}
} else {
bw.write(".,.,.");
}
bw.write(":");
// DP
bw.write(siteTotalDepth + "");
bw.write(":");
if (siteAlleleDepths.length != 0) {
int[] scores;
if (siteAlleleDepths.length == 1) {
int dep1 = siteAlleleDepths[alleleRedirect[0]] > 127 ? 127 : siteAlleleDepths[alleleRedirect[0]];
scores = VCFUtil.getScore(dep1, 0);
} else {
if (alleleRedirect[0] == -1) {
int dep1 = 0;
int dep2 = 0;
if (alleleRedirect.length > 2) {
dep1 = siteAlleleDepths[alleleRedirect[1]] > 127 ? 127 : siteAlleleDepths[alleleRedirect[1]];
dep2 = siteAlleleDepths[alleleRedirect[2]] > 127 ? 127 : siteAlleleDepths[alleleRedirect[2]];
} else if (alleleRedirect.length == 2) {
dep1 = 0;
dep2 = siteAlleleDepths[alleleRedirect[1]] > 127 ? 127 : siteAlleleDepths[alleleRedirect[1]];
}
scores = VCFUtil.getScore(dep1, dep2);
} else {
int dep1 = siteAlleleDepths[alleleRedirect[0]] > 127 ? 127 : siteAlleleDepths[alleleRedirect[0]];
int dep2 = 0;
if (alleleRedirect.length > 1) {
dep2 = siteAlleleDepths[alleleRedirect[1]] > 127 ? 127 : siteAlleleDepths[alleleRedirect[1]];
}
scores = VCFUtil.getScore(dep1, dep2);
}
}
// GQ
if (scores == null) {
scores = new int[]{-1, -1, -1, -1};
}
bw.write(scores[3] + "");
bw.write(":");
// PL
bw.write(scores[0] + "," + scores[1] + "," + scores[2]);
} else {
bw.write(".:.,.");
}
}
bw.newLine();
}
bw.flush();
bw.close();
} catch (Exception e) {
e.printStackTrace();;
throw new IllegalArgumentException("Error writing VCF file: " + filename + ": " + ExceptionUtils.getExceptionCauses(e));
}
return filename;
}
/**
* Writes given set of alignments to a set of Plink files
*
* @param alignment
* @param filename
* @param delimChar
*/
public static String writeToPlink(Alignment alignment, String filename, char delimChar) {
if (delimChar != ' ' && delimChar != '\t') {
throw new IllegalArgumentException("Delimiter charater must be either a blank space or a tab.");
}
BufferedWriter MAPbw = null;
BufferedWriter PEDbw = null;
String mapFileName = Utils.addSuffixIfNeeded(filename, ".plk.map");
String pedFileName = Utils.addSuffixIfNeeded(filename, ".plk.ped");
try {
MAPbw = new BufferedWriter(new FileWriter(mapFileName), 1000000);
int numSites = alignment.getSiteCount();
for (int site = 0; site < numSites; site++) {
MAPbw.write(alignment.getLocusName(site)); // chromosome name
MAPbw.write(delimChar);
MAPbw.write(alignment.getSNPID(site)); // rs#
MAPbw.write(delimChar);
MAPbw.write("-9"); // genetic distance unavailable
MAPbw.write(delimChar);
MAPbw.write(Integer.toString(alignment.getPositionInLocus(site))); // position
MAPbw.write("\n");
}
MAPbw.close();
PEDbw = new BufferedWriter(new FileWriter(pedFileName), 1000000);
// Compiled : Pattern
Pattern splitter = Pattern.compile(":");
int numTaxa = alignment.getSequenceCount();
for (int taxa = 0; taxa < numTaxa; taxa++) {
String[] name = splitter.split(alignment.getIdGroup().getIdentifier(taxa).getFullName().trim());
if (name.length != 1) {
PEDbw.write(name[1]); // namelvl 1 if is available
} else {
PEDbw.write("-9");
}
PEDbw.write(delimChar);
PEDbw.write(alignment.getIdGroup().getIdentifier(taxa).getFullName().trim()); // namelvl 0
PEDbw.write(delimChar);
PEDbw.write("-9"); // paternal ID unavailable
PEDbw.write(delimChar);
PEDbw.write("-9"); // maternal ID unavailable
PEDbw.write(delimChar);
PEDbw.write("-9"); // gender is both
PEDbw.write(delimChar);
PEDbw.write("-9"); // phenotype unavailable, might have to change to "-9" for missing affection status
PEDbw.write(delimChar);
for (int site = 0; site < numSites; site++) {
String[] b = getSNPValueForPlink(alignment.getBaseAsStringArray(taxa, site));
PEDbw.write(b[0]);
PEDbw.write(delimChar);
PEDbw.write(b[b.length - 1]);
if (site != numSites - 1) {
PEDbw.write(delimChar);
}
}
PEDbw.write("\n");
}
PEDbw.close();
return mapFileName + " and " + pedFileName;
} catch (Exception e) {
myLogger.error("Error writing Plink files: " + mapFileName + " and " + pedFileName + ": " + ExceptionUtils.getExceptionCauses(e));
throw new IllegalArgumentException("Error writing Plink files: " + mapFileName + " and " + pedFileName + ": " + ExceptionUtils.getExceptionCauses(e));
} finally {
try {
PEDbw.close();
} catch (Exception e) {
// do nothing
}
try {
MAPbw.close();
} catch (Exception e) {
// do nothing
}
}
}
private static String[] getSNPValueForPlink(String[] base) {
for (int i = 0; i < base.length; i++) {
if (base[i].equals("N")) {
base[i] = "0";
} else if (base[i].equals("0")) {
base[i] = "D";
}
}
return base;
}
/**
* Writes given set of alignments to a set of Flapjack files
*
* @param alignment
* @param filename
* @param delimChar
*/
public static String writeToFlapjack(Alignment alignment, String filename, char delimChar) {
if (delimChar != ' ' && delimChar != '\t') {
throw new IllegalArgumentException("Delimiter charater must be either a blank space or a tab.");
}
String mapFileName = Utils.addSuffixIfNeeded(filename, ".flpjk.map");
String genoFileName = Utils.addSuffixIfNeeded(filename, ".flpjk.geno");
try {
BufferedWriter MAPbw = new BufferedWriter(new FileWriter(mapFileName), 1000000);
BufferedWriter DATbw = new BufferedWriter(new FileWriter(genoFileName), 1000000);
int numSites = alignment.getSiteCount();
for (int site = 0; site < numSites; site++) {
MAPbw.write(alignment.getSNPID(site)); // rs#
MAPbw.write(delimChar);
MAPbw.write(alignment.getLocusName(site)); // chromosome name
MAPbw.write(delimChar);
MAPbw.write(Integer.toString(alignment.getPositionInLocus(site))); // position
MAPbw.write("\n");
DATbw.write(delimChar);
DATbw.write(alignment.getSNPID(site));
}
MAPbw.close();
DATbw.write("\n");
int numTaxa = alignment.getSequenceCount();
for (int taxa = 0; taxa < numTaxa; taxa++) {
DATbw.write(alignment.getIdGroup().getIdentifier(taxa).getFullName().trim());
DATbw.write(delimChar);
for (int site = 0; site < numSites; site++) {
String[] b = alignment.getBaseAsStringArray(taxa, site);
b = getSNPValueForFlapJack(b);
if (b.length == 1) {
DATbw.write(b[0]);
} else if (b.length == 2) {
DATbw.write(b[0]);
DATbw.write('/');
DATbw.write(b[1]);
} else if (b.length > 2) {
DATbw.write(b[0]);
DATbw.write('/');
DATbw.write(b[1]);
DATbw.write('/');
DATbw.write(b[2]);
}
if (site != numSites - 1) {
DATbw.write(delimChar);
}
}
DATbw.write("\n");
}
DATbw.close();
return mapFileName + " and " + genoFileName;
} catch (Exception e) {
myLogger.error("Error writing Flapjack files: " + mapFileName + " and " + genoFileName + ": " + ExceptionUtils.getExceptionCauses(e));
throw new IllegalArgumentException("Error writing Flapjack files: " + mapFileName + " and " + genoFileName + ": " + ExceptionUtils.getExceptionCauses(e));
}
}
private static String[] getSNPValueForFlapJack(String[] base) {
for (int i = 0; i < base.length; i++) {
if (base[i].equals("N")) {
base[i] = "-";
}
}
return base;
}
public static String saveDelimitedAlignment(Alignment theAlignment, String delimit, String saveFile) {
if ((saveFile == null) || (saveFile.length() == 0)) {
return null;
}
saveFile = Utils.addSuffixIfNeeded(saveFile, ".txt");
FileWriter fw = null;
BufferedWriter bw = null;
try {
fw = new FileWriter(new File(saveFile));
bw = new BufferedWriter(fw);
bw.write("Taxa");
int numSites = theAlignment.getSiteCount();
for (int j = 0; j < numSites; j++) {
bw.write(delimit);
bw.write(String.valueOf(theAlignment.getPositionInLocus(j)));
}
bw.write("\n");
for (int r = 0, n = theAlignment.getSequenceCount(); r < n; r++) {
bw.write(theAlignment.getIdGroup().getIdentifier(r).getFullName());
for (int i = 0; i < numSites; i++) {
bw.write(delimit);
bw.write(theAlignment.getBaseAsString(r, i));
}
bw.write("\n");
}
return saveFile;
} catch (Exception e) {
myLogger.error("Error writing Delimited Alignment: " + saveFile + ": " + ExceptionUtils.getExceptionCauses(e));
throw new IllegalArgumentException("Error writing Delimited Alignment: " + saveFile + ": " + ExceptionUtils.getExceptionCauses(e));
} finally {
try {
bw.close();
fw.close();
} catch (Exception e) {
// do nothing
}
}
}
/**
* print alignment (in PHYLIP SEQUENTIAL format)
*/
public static void printSequential(Alignment a, PrintWriter out) {
// PHYLIP header line
out.println(" " + a.getSequenceCount() + " " + a.getSiteCount() + " S");
// Print sequences
for (int s = 0; s < a.getSequenceCount(); s++) {
int n = 0;
while (n < a.getSiteCount()) {
if (n == 0) {
format.displayLabel(out, a.getIdGroup().getIdentifier(s).getName(), 10);
out.print(" ");
} else {
out.print(" ");
}
printNextSites(a, out, false, s, n, 50);
out.println();
n += 50;
}
}
}
/**
* print alignment (in PHYLIP 3.4 INTERLEAVED format)
*/
public static void printInterleaved(Alignment a, PrintWriter out) {
int n = 0;
// PHYLIP header line
out.println(" " + a.getSequenceCount() + " " + a.getSiteCount());
// Print sequences
while (n < a.getSiteCount()) {
for (int s = 0; s < a.getSequenceCount(); s++) {
if (n == 0) {
format.displayLabel(out, a.getIdGroup().getIdentifier(s).getName(), 10);
out.print(" ");
} else {
out.print(" ");
}
printNextSites(a, out, true, s, n, 50);
out.println();
}
out.println();
n += 50;
}
}
/**
* Print alignment (in CLUSTAL W format)
*/
public static void printCLUSTALW(Alignment a, PrintWriter out) {
int n = 0;
// CLUSTAL W header line
out.println("CLUSTAL W multiple sequence alignment");
out.println();
// Print sequences
while (n < a.getSiteCount()) {
out.println();
for (int s = 0; s < a.getSequenceCount(); s++) {
format.displayLabel(out, a.getIdGroup().getIdentifier(s).getName(), 10);
out.print(" ");
printNextSites(a, out, false, s, n, 50);
out.println();
}
// Blanks in status line are necessary for some parsers)
out.println(" ");
n += 50;
}
}
private static void printNextSites(Alignment a, PrintWriter out, boolean chunked, int seq, int start, int num) {
// Print next num characters
for (int i = 0; (i < num) && (start + i < a.getSiteCount()); i++) {
// Chunks of 10 characters
if (i % 10 == 0 && i != 0 && chunked) {
out.print(' ');
}
out.print(a.getBaseAsString(seq, start + i));
}
}
public static String writeAlignmentToSerialGZ(Alignment sba, String outFile) {
long time = System.currentTimeMillis();
File theFile = null;
FileOutputStream fos = null;
GZIPOutputStream gz = null;
ObjectOutputStream oos = null;
try {
theFile = new File(Utils.addSuffixIfNeeded(outFile, ".serial.gz"));
fos = new FileOutputStream(theFile);
gz = new GZIPOutputStream(fos);
oos = new ObjectOutputStream(gz);
oos.writeObject(sba);
return theFile.getName();
} catch (Exception e) {
e.printStackTrace();
myLogger.error("Error writing Serial GZ: " + theFile.getName() + ": " + ExceptionUtils.getExceptionCauses(e));
throw new IllegalArgumentException("Error writing Serial GZ: " + theFile.getName() + ": " + ExceptionUtils.getExceptionCauses(e));
} finally {
try {
oos.flush();
oos.close();
gz.close();
fos.close();
} catch (Exception e) {
// do nothing
}
myLogger.info("writeAlignmentToSerialGZ: " + theFile.toString() + " Time: " + (System.currentTimeMillis() - time));
}
}
}
|
PRIVATE: Control of whether or not to export genotypes
|
src/net/maizegenetics/pal/alignment/ExportUtils.java
|
PRIVATE: Control of whether or not to export genotypes
|
<ide><path>rc/net/maizegenetics/pal/alignment/ExportUtils.java
<ide> }
<ide> }
<ide>
<del> public static String writeToMutableHDF5(Alignment a, String newHDF5file) {
<del>
<add> public static String writeToMutableHDF5(Alignment a, String newHDF5file, boolean includeGenotypes) {
<ide> IHDF5Writer h5w = null;
<ide> try {
<del>
<ide> int numSites = a.getSiteCount();
<ide> int numTaxa = a.getSequenceCount();
<del>
<ide> newHDF5file = Utils.addSuffixIfNeeded(newHDF5file, "mutable.hmp.h5");
<ide> File hdf5File = new File(newHDF5file);
<ide> if (hdf5File.exists()) {
<ide> alleleEncodings.set(aEncodings[s][x], s, x);
<ide> }
<ide> }
<del>
<ide> h5w.createStringMDArray(HapMapHDF5Constants.ALLELE_STATES, 100, new int[]{numEncodings, numStates});
<ide> h5w.writeStringMDArray(HapMapHDF5Constants.ALLELE_STATES, alleleEncodings);
<ide> MDArray<String> alleleEncodingReadAgain = h5w.readStringMDArray(HapMapHDF5Constants.ALLELE_STATES);
<ide> if (alleleEncodings.equals(alleleEncodingReadAgain) == false) {
<ide> throw new IllegalStateException("ExportUtils: writeToMutableHDF5: Mismatch Allele States, expected '" + alleleEncodings + "', found '" + alleleEncodingReadAgain + "'!");
<ide> }
<del>
<ide> h5w.writeStringArray(HapMapHDF5Constants.SNP_IDS, a.getSNPIDs());
<ide>
<ide> h5w.setIntAttribute(HapMapHDF5Constants.DEFAULT_ATTRIBUTES_PATH, HapMapHDF5Constants.NUM_SITES, numSites);
<ide> // Write Bases
<ide> HDF5IntStorageFeatures features = HDF5IntStorageFeatures.createDeflation(HDF5IntStorageFeatures.MAX_DEFLATION_LEVEL);
<ide> HDF5IntStorageFeatures.createDeflationDelete(HDF5IntStorageFeatures.MAX_DEFLATION_LEVEL);
<del> for (int t = 0; t < numTaxa; t++) {
<del> String basesPath = HapMapHDF5Constants.GENOTYPES + "/" + a.getFullTaxaName(t);
<del> h5w.createByteArray(basesPath, numSites, features);
<del> byte[] bases = a.getBaseRow(t);
<del> h5w.writeByteArray(basesPath, bases, features);
<del> }
<del>
<add> if(includeGenotypes) {
<add> for (int t = 0; t < numTaxa; t++) {
<add> String basesPath = HapMapHDF5Constants.GENOTYPES + "/" + a.getFullTaxaName(t);
<add> h5w.createByteArray(basesPath, numSites, features);
<add> byte[] bases = a.getBaseRow(t);
<add> h5w.writeByteArray(basesPath, bases, features);
<add> }
<add> }
<ide> return newHDF5file;
<ide>
<ide> } finally {
|
|
Java
|
mit
|
38b93ce16d0a42cb62a451cc3b11526edea3ab79
| 0 |
taoneill/war,grinning/war-tommybranch
|
package com.tommytony.war;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import bukkit.tommytony.war.War;
import com.tommytony.war.utils.SignHelper;
import com.tommytony.war.volumes.BlockInfo;
import com.tommytony.war.volumes.Volume;
/**
*
* @author tommytony, Tim Düsterhus
* @package com.tommytony.war
*/
public class WarHub {
private final War war;
private Location location;
private Volume volume;
private Map<String, Block> zoneGateBlocks = new HashMap<String, Block>();
private BlockFace orientation;
public WarHub(War war, Location location, String hubOrientation) {
this.war = war;
this.location = location;
this.volume = new Volume("warhub", war, location.getWorld());
if (hubOrientation.equals("south")) {
this.setOrientation(BlockFace.SOUTH);
} else if (hubOrientation.equals("north")) {
this.setOrientation(BlockFace.SOUTH);
} else if (hubOrientation.equals("east")) {
this.setOrientation(BlockFace.EAST);
} else {
this.setOrientation(BlockFace.WEST);
}
}
// Use when creating from player location (with yaw)
public WarHub(War war, Location location) {
this.war = war;
this.location = location;
this.volume = new Volume("warhub", war, location.getWorld());
setLocation(location);
}
public Volume getVolume() {
return this.volume;
}
public void setLocation(Location loc) {
this.location = loc;
// Lobby orientation
int yaw = 0;
if (location.getYaw() >= 0) {
yaw = (int) (location.getYaw() % 360);
} else {
yaw = (int) (360 + (location.getYaw() % 360));
}
BlockFace facing = null;
if ((yaw >= 0 && yaw < 45) || (yaw >= 315 && yaw <= 360)) {
facing = BlockFace.WEST;
} else if (yaw >= 45 && yaw < 135) {
facing = BlockFace.NORTH;
} else if (yaw >= 135 && yaw < 225) {
facing = BlockFace.EAST;
} else if (yaw >= 225 && yaw < 315) {
facing = BlockFace.SOUTH;
}
this.setOrientation(facing);
}
public Location getLocation() {
return this.location;
}
public Warzone getDestinationWarzoneForLocation(Location playerLocation) {
Warzone zone = null;
for (String zoneName : this.zoneGateBlocks.keySet()) {
Block gate = this.zoneGateBlocks.get(zoneName);
if (gate.getX() == playerLocation.getBlockX() && gate.getY() == playerLocation.getBlockY() && gate.getZ() == playerLocation.getBlockZ()) {
zone = this.war.findWarzone(zoneName);
}
}
return zone;
}
public void initialize() {
// for now, draw the wall of gates to the west
this.zoneGateBlocks.clear();
int disabled = 0;
for (Warzone zone : this.war.getWarzones()) {
if (zone.isDisabled()) {
disabled++;
}
}
int noOfWarzones = this.war.getWarzones().size() - disabled;
if (noOfWarzones > 0) {
int hubWidth = noOfWarzones * 4 + 2;
int halfHubWidth = hubWidth / 2;
int hubDepth = 6;
int hubHeigth = 4;
BlockFace left;
BlockFace right;
BlockFace front = this.getOrientation();
BlockFace back;
byte data;
if (this.getOrientation() == BlockFace.SOUTH) {
data = (byte) 4;
left = BlockFace.EAST;
right = BlockFace.WEST;
back = BlockFace.NORTH;
} else if (this.getOrientation() == BlockFace.NORTH) {
data = (byte) 12;
left = BlockFace.WEST;
right = BlockFace.EAST;
back = BlockFace.SOUTH;
} else if (this.getOrientation() == BlockFace.EAST) {
data = (byte) 0;
left = BlockFace.NORTH;
right = BlockFace.SOUTH;
back = BlockFace.WEST;
} else {
data = (byte) 8;
left = BlockFace.SOUTH;
right = BlockFace.NORTH;
back = BlockFace.EAST;
}
Block locationBlock = this.location.getWorld().getBlockAt(this.location.getBlockX(), this.location.getBlockY(), this.location.getBlockZ());
this.volume.setCornerOne(locationBlock.getFace(back).getFace(left, halfHubWidth).getFace(BlockFace.DOWN));
this.volume.setCornerTwo(locationBlock.getFace(right, halfHubWidth).getFace(front, hubDepth).getFace(BlockFace.UP, hubHeigth));
this.volume.saveBlocks();
// glass floor
this.volume.clearBlocksThatDontFloat();
this.volume.setToMaterial(Material.AIR);
this.volume.setFaceMaterial(BlockFace.DOWN, Material.GLASS);
// draw gates
Block currentGateBlock = BlockInfo.getBlock(this.location.getWorld(), this.volume.getCornerOne()).getFace(BlockFace.UP).getFace(front, hubDepth).getFace(right, 2);
for (Warzone zone : this.war.getWarzones()) { // gonna use the index to find it again
if (!zone.isDisabled()) {
this.zoneGateBlocks.put(zone.getName(), currentGateBlock);
currentGateBlock.getFace(BlockFace.DOWN).setType(Material.GLOWSTONE);
currentGateBlock.setType(Material.PORTAL);
currentGateBlock.getFace(BlockFace.UP).setType(Material.PORTAL);
currentGateBlock.getFace(left).setType(Material.OBSIDIAN);
currentGateBlock.getFace(right).getFace(BlockFace.UP).setType(Material.OBSIDIAN);
currentGateBlock.getFace(left).getFace(BlockFace.UP).getFace(BlockFace.UP).setType(Material.OBSIDIAN);
currentGateBlock.getFace(right).setType(Material.OBSIDIAN);
currentGateBlock.getFace(left).getFace(BlockFace.UP).setType(Material.OBSIDIAN);
currentGateBlock.getFace(right).getFace(BlockFace.UP).getFace(BlockFace.UP).setType(Material.OBSIDIAN);
currentGateBlock.getFace(BlockFace.UP).getFace(BlockFace.UP).setType(Material.OBSIDIAN);
currentGateBlock = currentGateBlock.getFace(right, 4);
}
}
// War hub sign
Block signBlock = locationBlock.getFace(front);
String[] lines = new String[4];
lines[0] = "War hub";
lines[1] = "(/warhub)";
lines[2] = "Pick your";
lines[3] = "battle!";
SignHelper.setToSign(this.war, signBlock, data, lines);
// Warzone signs
for (Warzone zone : this.war.getWarzones()) {
if (!zone.isDisabled() && zone.ready()) {
this.resetZoneSign(zone);
}
}
}
}
public void resetZoneSign(Warzone zone) {
BlockFace left;
BlockFace back;
byte data;
if (this.getOrientation() == BlockFace.SOUTH) {
data = (byte) 4;
left = BlockFace.EAST;
back = BlockFace.NORTH;
} else if (this.getOrientation() == BlockFace.NORTH) {
data = (byte) 12;
left = BlockFace.WEST;
back = BlockFace.SOUTH;
} else if (this.getOrientation() == BlockFace.EAST) {
data = (byte) 0;
left = BlockFace.NORTH;
back = BlockFace.WEST;
} else {
data = (byte) 8;
left = BlockFace.SOUTH;
back = BlockFace.EAST;
}
Block zoneGate = this.zoneGateBlocks.get(zone.getName());
Block block = zoneGate.getFace(left).getFace(back, 1);
if (block.getType() != Material.SIGN_POST) {
block.setType(Material.SIGN_POST);
}
block.setData(data);
int zoneCap = 0;
int zonePlayers = 0;
for (Team t : zone.getTeams()) {
zonePlayers += t.getPlayers().size();
zoneCap += zone.getTeamCap();
}
String[] lines = new String[4];
lines[0] = "Warzone";
lines[1] = zone.getName();
lines[2] = zonePlayers + "/" + zoneCap + " players";
lines[3] = zone.getTeams().size() + " teams";
SignHelper.setToSign(this.war, block, data, lines);
}
public void setVolume(Volume vol) {
this.volume = vol;
}
public void setOrientation(BlockFace orientation) {
this.orientation = orientation;
}
public BlockFace getOrientation() {
return orientation;
}
}
|
war/src/main/java/com/tommytony/war/WarHub.java
|
package com.tommytony.war;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import bukkit.tommytony.war.War;
import com.tommytony.war.utils.SignHelper;
import com.tommytony.war.volumes.BlockInfo;
import com.tommytony.war.volumes.Volume;
/**
*
* @author tommytony
*
*/
public class WarHub {
private final War war;
private Location location;
private Volume volume;
private Map<String, Block> zoneGateBlocks = new HashMap<String, Block>();
private BlockFace orientation;
public WarHub(War war, Location location, String hubOrientation) {
this.war = war;
this.location = location;
this.volume = new Volume("warhub", war, location.getWorld());
if (hubOrientation.equals("south")) {
this.setOrientation(BlockFace.SOUTH);
} else if (hubOrientation.equals("north")) {
this.setOrientation(BlockFace.SOUTH);
} else if (hubOrientation.equals("east")) {
this.setOrientation(BlockFace.EAST);
} else {
this.setOrientation(BlockFace.WEST);
}
}
// Use when creating from player location (with yaw)
public WarHub(War war, Location location) {
this.war = war;
this.location = location;
this.volume = new Volume("warhub", war, location.getWorld());
setLocation(location);
}
public Volume getVolume() {
return this.volume;
}
public void setLocation(Location loc) {
this.location = loc;
// Lobby orientation
int yaw = 0;
if (location.getYaw() >= 0) {
yaw = (int) (location.getYaw() % 360);
} else {
yaw = (int) (360 + (location.getYaw() % 360));
}
BlockFace facing = null;
BlockFace opposite = null;
if ((yaw >= 0 && yaw < 45) || (yaw >= 315 && yaw <= 360)) {
facing = BlockFace.WEST;
opposite = BlockFace.EAST;
} else if (yaw >= 45 && yaw < 135) {
facing = BlockFace.NORTH;
opposite = BlockFace.SOUTH;
} else if (yaw >= 135 && yaw < 225) {
facing = BlockFace.EAST;
opposite = BlockFace.WEST;
} else if (yaw >= 225 && yaw < 315) {
facing = BlockFace.SOUTH;
opposite = BlockFace.NORTH;
}
this.setOrientation(facing);
}
public Location getLocation() {
return this.location;
}
public Warzone getDestinationWarzoneForLocation(Location playerLocation) {
Warzone zone = null;
for (String zoneName : this.zoneGateBlocks.keySet()) {
Block gate = this.zoneGateBlocks.get(zoneName);
if (gate.getX() == playerLocation.getBlockX() && gate.getY() == playerLocation.getBlockY() && gate.getZ() == playerLocation.getBlockZ()) {
zone = this.war.findWarzone(zoneName);
}
}
return zone;
}
public void initialize() {
// for now, draw the wall of gates to the west
this.zoneGateBlocks.clear();
int disabled = 0;
for (Warzone zone : this.war.getWarzones()) {
if (zone.isDisabled()) {
disabled++;
}
}
int noOfWarzones = this.war.getWarzones().size() - disabled;
if (noOfWarzones > 0) {
int hubWidth = noOfWarzones * 4 + 2;
int halfHubWidth = hubWidth / 2;
int hubDepth = 6;
int hubHeigth = 4;
BlockFace left;
BlockFace right;
BlockFace front = this.getOrientation();
BlockFace back;
byte data;
if (this.getOrientation() == BlockFace.SOUTH) {
data = (byte) 4;
left = BlockFace.EAST;
right = BlockFace.WEST;
back = BlockFace.NORTH;
} else if (this.getOrientation() == BlockFace.NORTH) {
data = (byte) 12;
left = BlockFace.WEST;
right = BlockFace.EAST;
back = BlockFace.SOUTH;
} else if (this.getOrientation() == BlockFace.EAST) {
data = (byte) 0;
left = BlockFace.NORTH;
right = BlockFace.SOUTH;
back = BlockFace.WEST;
} else {
data = (byte) 8;
left = BlockFace.SOUTH;
right = BlockFace.NORTH;
back = BlockFace.EAST;
}
Block locationBlock = this.location.getWorld().getBlockAt(this.location.getBlockX(), this.location.getBlockY(), this.location.getBlockZ());
this.volume.setCornerOne(locationBlock.getFace(back).getFace(left, halfHubWidth).getFace(BlockFace.DOWN));
this.volume.setCornerTwo(locationBlock.getFace(right, halfHubWidth).getFace(front, hubDepth).getFace(BlockFace.UP, hubHeigth));
this.volume.saveBlocks();
// glass floor
this.volume.clearBlocksThatDontFloat();
this.volume.setToMaterial(Material.AIR);
this.volume.setFaceMaterial(BlockFace.DOWN, Material.GLASS);
// draw gates
Block currentGateBlock = BlockInfo.getBlock(this.location.getWorld(), this.volume.getCornerOne()).getFace(BlockFace.UP).getFace(front, hubDepth).getFace(right, 2);
for (Warzone zone : this.war.getWarzones()) { // gonna use the index to find it again
if (!zone.isDisabled()) {
this.zoneGateBlocks.put(zone.getName(), currentGateBlock);
currentGateBlock.getFace(BlockFace.DOWN).setType(Material.GLOWSTONE);
currentGateBlock.setType(Material.PORTAL);
currentGateBlock.getFace(BlockFace.UP).setType(Material.PORTAL);
currentGateBlock.getFace(left).setType(Material.OBSIDIAN);
currentGateBlock.getFace(right).getFace(BlockFace.UP).setType(Material.OBSIDIAN);
currentGateBlock.getFace(left).getFace(BlockFace.UP).getFace(BlockFace.UP).setType(Material.OBSIDIAN);
currentGateBlock.getFace(right).setType(Material.OBSIDIAN);
currentGateBlock.getFace(left).getFace(BlockFace.UP).setType(Material.OBSIDIAN);
currentGateBlock.getFace(right).getFace(BlockFace.UP).getFace(BlockFace.UP).setType(Material.OBSIDIAN);
currentGateBlock.getFace(BlockFace.UP).getFace(BlockFace.UP).setType(Material.OBSIDIAN);
currentGateBlock = currentGateBlock.getFace(right, 4);
}
}
// War hub sign
Block signBlock = locationBlock.getFace(front);
String[] lines = new String[4];
lines[0] = "War hub";
lines[1] = "(/warhub)";
lines[2] = "Pick your";
lines[3] = "battle!";
SignHelper.setToSign(this.war, signBlock, data, lines);
// Warzone signs
for (Warzone zone : this.war.getWarzones()) {
if (!zone.isDisabled() && zone.ready()) {
this.resetZoneSign(zone);
}
}
}
}
public void resetZoneSign(Warzone zone) {
BlockFace left;
BlockFace right;
BlockFace front = this.getOrientation();
BlockFace back;
byte data;
if (this.getOrientation() == BlockFace.SOUTH) {
data = (byte) 4;
left = BlockFace.EAST;
right = BlockFace.WEST;
back = BlockFace.NORTH;
} else if (this.getOrientation() == BlockFace.NORTH) {
data = (byte) 12;
left = BlockFace.WEST;
right = BlockFace.EAST;
back = BlockFace.SOUTH;
} else if (this.getOrientation() == BlockFace.EAST) {
data = (byte) 0;
left = BlockFace.NORTH;
right = BlockFace.SOUTH;
back = BlockFace.WEST;
} else {
data = (byte) 8;
left = BlockFace.SOUTH;
right = BlockFace.NORTH;
back = BlockFace.EAST;
}
Block zoneGate = this.zoneGateBlocks.get(zone.getName());
Block block = zoneGate.getFace(left).getFace(back, 1);
if (block.getType() != Material.SIGN_POST) {
block.setType(Material.SIGN_POST);
}
block.setData(data);
int zoneCap = 0;
int zonePlayers = 0;
for (Team t : zone.getTeams()) {
zonePlayers += t.getPlayers().size();
zoneCap += zone.getTeamCap();
}
String[] lines = new String[4];
lines[0] = "Warzone";
lines[1] = zone.getName();
lines[2] = zonePlayers + "/" + zoneCap + " players";
lines[3] = zone.getTeams().size() + " teams";
SignHelper.setToSign(this.war, block, data, lines);
}
public void setVolume(Volume vol) {
this.volume = vol;
}
public void setOrientation(BlockFace orientation) {
this.orientation = orientation;
}
public BlockFace getOrientation() {
return orientation;
}
}
|
Removing unused wars
|
war/src/main/java/com/tommytony/war/WarHub.java
|
Removing unused wars
|
<ide><path>ar/src/main/java/com/tommytony/war/WarHub.java
<ide> import com.tommytony.war.volumes.Volume;
<ide>
<ide> /**
<del> *
<del> * @author tommytony
<del> *
<add> *
<add> * @author tommytony, Tim Düsterhus
<add> * @package com.tommytony.war
<ide> */
<ide> public class WarHub {
<ide> private final War war;
<ide> this.location = location;
<ide> this.volume = new Volume("warhub", war, location.getWorld());
<ide> if (hubOrientation.equals("south")) {
<del> this.setOrientation(BlockFace.SOUTH);
<add> this.setOrientation(BlockFace.SOUTH);
<ide> } else if (hubOrientation.equals("north")) {
<ide> this.setOrientation(BlockFace.SOUTH);
<ide> } else if (hubOrientation.equals("east")) {
<ide> } else {
<ide> this.setOrientation(BlockFace.WEST);
<ide> }
<del>
<add>
<ide> }
<ide>
<ide> // Use when creating from player location (with yaw)
<ide> this.war = war;
<ide> this.location = location;
<ide> this.volume = new Volume("warhub", war, location.getWorld());
<del>
<add>
<ide> setLocation(location);
<ide> }
<ide>
<ide> } else {
<ide> yaw = (int) (360 + (location.getYaw() % 360));
<ide> }
<add>
<ide> BlockFace facing = null;
<del> BlockFace opposite = null;
<ide> if ((yaw >= 0 && yaw < 45) || (yaw >= 315 && yaw <= 360)) {
<ide> facing = BlockFace.WEST;
<del> opposite = BlockFace.EAST;
<ide> } else if (yaw >= 45 && yaw < 135) {
<ide> facing = BlockFace.NORTH;
<del> opposite = BlockFace.SOUTH;
<ide> } else if (yaw >= 135 && yaw < 225) {
<ide> facing = BlockFace.EAST;
<del> opposite = BlockFace.WEST;
<ide> } else if (yaw >= 225 && yaw < 315) {
<ide> facing = BlockFace.SOUTH;
<del> opposite = BlockFace.NORTH;
<ide> }
<ide> this.setOrientation(facing);
<ide> }
<ide> int halfHubWidth = hubWidth / 2;
<ide> int hubDepth = 6;
<ide> int hubHeigth = 4;
<del>
<add>
<ide> BlockFace left;
<ide> BlockFace right;
<ide> BlockFace front = this.getOrientation();
<ide> public void resetZoneSign(Warzone zone) {
<ide>
<ide> BlockFace left;
<del> BlockFace right;
<del> BlockFace front = this.getOrientation();
<ide> BlockFace back;
<ide> byte data;
<ide> if (this.getOrientation() == BlockFace.SOUTH) {
<ide> data = (byte) 4;
<ide> left = BlockFace.EAST;
<del> right = BlockFace.WEST;
<ide> back = BlockFace.NORTH;
<ide> } else if (this.getOrientation() == BlockFace.NORTH) {
<ide> data = (byte) 12;
<ide> left = BlockFace.WEST;
<del> right = BlockFace.EAST;
<ide> back = BlockFace.SOUTH;
<ide> } else if (this.getOrientation() == BlockFace.EAST) {
<ide> data = (byte) 0;
<ide> left = BlockFace.NORTH;
<del> right = BlockFace.SOUTH;
<ide> back = BlockFace.WEST;
<ide> } else {
<ide> data = (byte) 8;
<ide> left = BlockFace.SOUTH;
<del> right = BlockFace.NORTH;
<ide> back = BlockFace.EAST;
<ide> }
<del>
<add>
<ide> Block zoneGate = this.zoneGateBlocks.get(zone.getName());
<ide> Block block = zoneGate.getFace(left).getFace(back, 1);
<ide> if (block.getType() != Material.SIGN_POST) {
|
|
Java
|
apache-2.0
|
abc48ac9befdaf4eeed2a0484e9a584b8706dbdf
| 0 |
mtransitapps/ca-gtha-go-transit-train-parser
|
package org.mtransit.parser.ca_gtha_go_transit_train;
import java.util.HashSet;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.mtransit.parser.CleanUtils;
import org.mtransit.parser.DefaultAgencyTools;
import org.mtransit.parser.Utils;
import org.mtransit.parser.gtfs.data.GCalendar;
import org.mtransit.parser.gtfs.data.GCalendarDate;
import org.mtransit.parser.gtfs.data.GRoute;
import org.mtransit.parser.gtfs.data.GSpec;
import org.mtransit.parser.gtfs.data.GStop;
import org.mtransit.parser.gtfs.data.GTrip;
import org.mtransit.parser.mt.data.MAgency;
import org.mtransit.parser.mt.data.MRoute;
import org.mtransit.parser.mt.data.MTrip;
// http://www.gotransit.com/publicroot/en/schedules/DeveloperResources.aspx
// http://www.gotransit.com/timetables/fr/schedules/DeveloperResources.aspx
// http://www.gotransit.com/publicroot/en/schedules/GTFSdownload.aspx
// http://www.gotransit.com/publicroot/gtfs/google_transit.zip
public class GTHAGOTransitTrainAgencyTools extends DefaultAgencyTools {
public static void main(String[] args) {
if (args == null || args.length == 0) {
args = new String[3];
args[0] = "input/gtfs.zip";
args[1] = "../../mtransitapps/ca-gtha-go-transit-train-android/res/raw/";
args[2] = ""; // files-prefix
}
new GTHAGOTransitTrainAgencyTools().start(args);
}
private HashSet<String> serviceIds;
@Override
public void start(String[] args) {
System.out.printf("\nGenerating GO Transit train data...");
long start = System.currentTimeMillis();
this.serviceIds = extractUsefulServiceIds(args, this, true);
super.start(args);
System.out.printf("\nGenerating GO Transit train data... DONE in %s.\n", Utils.getPrettyDuration(System.currentTimeMillis() - start));
}
@Override
public boolean excludeCalendar(GCalendar gCalendar) {
if (this.serviceIds != null) {
return excludeUselessCalendar(gCalendar, this.serviceIds);
}
return super.excludeCalendar(gCalendar);
}
@Override
public boolean excludeCalendarDate(GCalendarDate gCalendarDates) {
if (this.serviceIds != null) {
return excludeUselessCalendarDate(gCalendarDates, this.serviceIds);
}
return super.excludeCalendarDate(gCalendarDates);
}
@Override
public boolean excludeTrip(GTrip gTrip) {
if (this.serviceIds != null) {
return excludeUselessTrip(gTrip, this.serviceIds);
}
return super.excludeTrip(gTrip);
}
@Override
public Integer getAgencyRouteType() {
return MAgency.ROUTE_TYPE_TRAIN;
}
private static final long LW_RID = 1l; // Lakeshore West
private static final long MI_RID = 2l; // Milton
private static final long KI_RID = 3l; // Kitchener
private static final long BR_RID = 5l; // Barrie
private static final long RH_RID = 6l; // Richmond Hill
private static final long ST_RID = 7l; // Stouffville
private static final long LE_RID = 9l; // Lakeshore East
@Override
public long getRouteId(GRoute gRoute) {
if (ST_RSN.equals(gRoute.getRouteShortName())) {
return ST_RID;
} else if (RH_RSN.equals(gRoute.getRouteShortName())) {
return RH_RID;
} else if (MI_RSN.equals(gRoute.getRouteShortName())) {
return MI_RID;
} else if (LW_RSN.equals(gRoute.getRouteShortName())) {
return LW_RID;
} else if (LE_RSN.equals(gRoute.getRouteShortName())) {
return LE_RID;
} else if (KI_RSN.equals(gRoute.getRouteShortName()) //
|| GT_RSN.equals(gRoute.getRouteShortName())) {
return KI_RID;
} else if (BR_RSN.equals(gRoute.getRouteShortName())) {
return BR_RID;
}
if (gRoute.getRouteId().endsWith(ST_RSN)) {
return ST_RID;
} else if (gRoute.getRouteId().endsWith(RH_RSN)) {
return RH_RID;
} else if (gRoute.getRouteId().endsWith(MI_RSN)) {
return MI_RID;
} else if (gRoute.getRouteId().endsWith(LW_RSN)) {
return LW_RID;
} else if (gRoute.getRouteId().endsWith(LE_RSN)) {
return LE_RID;
} else if (gRoute.getRouteId().endsWith(KI_RSN) //
|| gRoute.getRouteId().endsWith(GT_RSN)) {
return KI_RID;
} else if (gRoute.getRouteId().endsWith(BR_RSN)) {
return BR_RID;
}
System.out.printf("\nUnexpected route ID for %s!\n", gRoute);
System.exit(-1);
return -1l;
}
@Override
public String getRouteLongName(GRoute gRoute) {
String routeLongName = gRoute.getRouteLongName();
routeLongName = CleanUtils.cleanStreetTypes(routeLongName);
return CleanUtils.cleanLabel(routeLongName);
}
private static final String ST_RSN = "ST"; // Stouffville
private static final String RH_RSN = "RH"; // Richmond Hill
private static final String MI_RSN = "MI"; // Milton
private static final String LW_RSN = "LW"; // Lakeshore West
private static final String LE_RSN = "LE"; // Lakeshore East
private static final String KI_RSN = "KI"; // Kitchener
private static final String GT_RSN = "GT"; // Kitchener
private static final String BR_RSN = "BR"; // Barrie
@Override
public String getRouteShortName(GRoute gRoute) {
if (StringUtils.isEmpty(gRoute.getRouteShortName())) {
if (gRoute.getRouteId().endsWith(ST_RSN)) {
return ST_RSN;
} else if (gRoute.getRouteId().endsWith(RH_RSN)) {
return RH_RSN;
} else if (gRoute.getRouteId().endsWith(MI_RSN)) {
return MI_RSN;
} else if (gRoute.getRouteId().endsWith(LW_RSN)) {
return LW_RSN;
} else if (gRoute.getRouteId().endsWith(LE_RSN)) {
return LE_RSN;
} else if (gRoute.getRouteId().endsWith(KI_RSN) //
|| gRoute.getRouteId().endsWith(GT_RSN)) {
return GT_RSN;
} else if (gRoute.getRouteId().endsWith(BR_RSN)) {
return BR_RSN;
}
System.out.printf("\nUnexpected route short name for %s!\n", gRoute);
System.exit(-1);
return null;
}
return super.getRouteShortName(gRoute);
}
private static final String AGENCY_COLOR = "387C2B"; // GREEN (AGENCY WEB SITE CSS)
@Override
public String getAgencyColor() {
return AGENCY_COLOR;
}
private static final String COLOR_BC6277 = "BC6277";
private static final String COLOR_F46F1A = "F46F1A";
private static final String COLOR_098137 = "098137";
private static final String COLOR_0B335E = "0B335E";
private static final String COLOR_0098C9 = "0098C9";
private static final String COLOR_794500 = "794500";
private static final String COLOR_96092B = "96092B";
private static final String COLOR_EE3124 = "EE3124";
@Override
public String getRouteColor(GRoute gRoute) {
if (StringUtils.isEmpty(gRoute.getRouteColor())) {
int routeId = (int) getRouteId(gRoute);
switch (routeId) {
// @formatter:off
case 1: return COLOR_96092B; // Lakeshore West
case 2: return COLOR_F46F1A; // Milton
case 3: return COLOR_098137; // Kitchener
case 5: return COLOR_0B335E; // Barrie
case 6: return COLOR_0098C9; // Richmond Hill
case 7: return COLOR_794500; // Stouffville
case 8: return COLOR_BC6277; // Niagara Falls
case 9: return COLOR_EE3124; // Lakeshore East
// @formatter:on
}
System.out.printf("Unexpected route color '%s'!\n", gRoute);
System.exit(-1);
return null;
}
return super.getRouteColor(gRoute);
}
private static final String ALLANDALE_WATERFRONT = "Allandale Waterfront";
private static final String GORMLEY = "Gormley";
private static final String LINCOLNVILLE = "Lincolnville";
private static final String OSHAWA = "Oshawa";
private static final String KITCHENER = "Kitchener";
private static final String HAMILTON = "Hamilton";
@Override
public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip, GSpec gtfs) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), gTrip.getDirectionId());
}
@Override
public boolean mergeHeadsign(MTrip mTrip, MTrip mTripToMerge) {
if (mTrip.getRouteId() == LW_RID) { // Lakeshore West
if (mTrip.getHeadsignId() == 0) {
mTrip.setHeadsignString(HAMILTON, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == MI_RID) { // Milton
} else if (mTrip.getRouteId() == KI_RID) { // Kitchener
if (mTrip.getHeadsignId() == 0) {
mTrip.setHeadsignString(KITCHENER, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == BR_RID) { // Barrie
if (mTrip.getHeadsignId() == 0) {
mTrip.setHeadsignString(ALLANDALE_WATERFRONT, mTrip.getHeadsignId()); // Barrie
return true;
}
} else if (mTrip.getRouteId() == RH_RID) { // Richmond Hill
if (mTrip.getHeadsignId() == 0) {
mTrip.setHeadsignString(GORMLEY, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == ST_RID) { // Stouffville
if (mTrip.getHeadsignId() == 0) {
mTrip.setHeadsignString(LINCOLNVILLE, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == LE_RID) { // Lakeshore East
if (mTrip.getHeadsignId() == 0) {
mTrip.setHeadsignString(OSHAWA, mTrip.getHeadsignId());
return true;
}
}
System.out.printf("\nUnexpected trips to merge %s & %s!\n", mTrip, mTripToMerge);
return false;
}
private static final Pattern START_WITH_RSN = Pattern.compile("(^[A-Z]{2}\\-)", Pattern.CASE_INSENSITIVE);
private static final Pattern FIRST_STATION_TIME_LAST_STATION_TIME = Pattern.compile("" //
+ "(" //
+ "([\\w\\s]*)" //
+ "[\\s]+" //
+ "([\\d]{2}\\:[\\d]{2})" //
+ "[\\s]+" //
+ "\\-" //
+ "[\\s]+" //
+ "([\\w\\s]*)" //
+ "[\\s]+" //
+ "([\\d]{2}\\:[\\d]{2})" //
+ ")", Pattern.CASE_INSENSITIVE);
private static final String FIRST_STATION_TIME_LAST_STATION_TIME_REPLACEMENT = "$4";
private static final Pattern CENTER = Pattern.compile("((^|\\W){1}(center|centre|ctr)(\\W|$){1})", Pattern.CASE_INSENSITIVE);
private static final String CENTER_REPLACEMENT = " ";
@Override
public String cleanTripHeadsign(String tripHeadsign) {
tripHeadsign = START_WITH_RSN.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY);
tripHeadsign = FIRST_STATION_TIME_LAST_STATION_TIME.matcher(tripHeadsign).replaceAll(FIRST_STATION_TIME_LAST_STATION_TIME_REPLACEMENT);
tripHeadsign = GO.matcher(tripHeadsign).replaceAll(GO_REPLACEMENT);
tripHeadsign = CENTER.matcher(tripHeadsign).replaceAll(CENTER_REPLACEMENT);
tripHeadsign = STATION.matcher(tripHeadsign).replaceAll(STATION_REPLACEMENT);
tripHeadsign = CleanUtils.cleanStreetTypes(tripHeadsign);
return CleanUtils.cleanLabel(tripHeadsign);
}
private static final Pattern GO = Pattern.compile("(^|\\s){1}(go)($|\\s){1}", Pattern.CASE_INSENSITIVE);
private static final String GO_REPLACEMENT = " ";
private static final Pattern VIA = Pattern.compile("(^|\\s){1}(via)($|\\s){1}", Pattern.CASE_INSENSITIVE);
private static final String VIA_REPLACEMENT = " ";
private static final Pattern RAIL = Pattern.compile("(^|\\s){1}(rail)($|\\s){1}", Pattern.CASE_INSENSITIVE);
private static final String RAIL_REPLACEMENT = " ";
private static final Pattern STATION = Pattern.compile("(^|\\s){1}(station)($|\\s){1}", Pattern.CASE_INSENSITIVE);
private static final String STATION_REPLACEMENT = " ";
@Override
public String cleanStopName(String gStopName) {
gStopName = CleanUtils.CLEAN_AT.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AT_REPLACEMENT);
gStopName = VIA.matcher(gStopName).replaceAll(VIA_REPLACEMENT);
gStopName = GO.matcher(gStopName).replaceAll(GO_REPLACEMENT);
gStopName = RAIL.matcher(gStopName).replaceAll(RAIL_REPLACEMENT);
gStopName = STATION.matcher(gStopName).replaceAll(STATION_REPLACEMENT);
gStopName = CleanUtils.cleanNumbers(gStopName);
gStopName = CleanUtils.cleanStreetTypes(gStopName);
return CleanUtils.cleanLabel(gStopName);
}
private static final String SID_UN = "UN";
private static final int UN_SID = 9021;
private static final String SID_EX = "EX";
private static final int EX_SID = 9022;
private static final String SID_MI = "MI";
private static final int MI_SID = 9031;
private static final String SID_LO = "LO";
private static final int LO_SID = 9033;
private static final String SID_DA = "DA";
private static final int DA_SID = 9061;
private static final String SID_SC = "SC";
private static final int SC_SID = 9062;
private static final String SID_EG = "EG";
private static final int EG_SID = 9063;
private static final String SID_GU = "GU";
private static final int GU_SID = 9081;
private static final String SID_RO = "RO";
private static final int RO_SID = 9091;
private static final String SID_PO = "PO";
private static final int PO_SID = 9111;
private static final String SID_CL = "CL";
private static final int CL_SID = 9121;
private static final String SID_OA = "OA";
private static final int OA_SID = 9131;
private static final String SID_BO = "BO";
private static final int BO_SID = 9141;
private static final String SID_AP = "AP";
private static final int AP_SID = 9151;
private static final String SID_BU = "BU";
private static final int BU_SID = 9161;
private static final String SID_AL = "AL";
private static final int AL_SID = 9171;
private static final String SID_PIN = "PIN";
private static final int PIN_SID = 9911;
private static final String SID_AJ = "AJ";
private static final int AJ_SID = 9921;
private static final String SID_WH = "WH";
private static final int WH_SID = 9939;
private static final String SID_OS = "OS";
private static final int OS_SID = 9941;
private static final String SID_BL = "BL";
private static final int BL_SID = 9023;
private static final String SID_KP = "KP";
private static final int KP_SID = 9032;
private static final String SID_WE = "WE";
private static final int WE_SID = 9041;
private static final String SID_ET = "ET";
private static final int ET_SID = 9042;
private static final String SID_OR = "OR";
private static final int OR_SID = 9051;
private static final String SID_OL = "OL";
private static final int OL_SID = 9052;
private static final String SID_AG = "AG";
private static final int AG_SID = 9071;
private static final String SID_DI = "DI";
private static final int DI_SID = 9113;
private static final String SID_CO = "CO";
private static final int CO_SID = 9114;
private static final String SID_ER = "ER";
private static final int ER_SID = 9123;
private static final String SID_HA = "HA";
private static final int HA_SID = 9181;
private static final String SID_YO = "YO";
private static final int YO_SID = 9191;
private static final String SID_SR = "SR";
private static final int SR_SID = 9211;
private static final String SID_ME = "ME";
private static final int ME_SID = 9221;
private static final String SID_LS = "LS";
private static final int LS_SID = 9231;
private static final String SID_ML = "ML";
private static final int ML_SID = 9241;
private static final String SID_KI = "KI";
private static final int KI_SID = 9271;
private static final String SID_MA = "MA";
private static final int MA_SID = 9311;
private static final String SID_BE = "BE";
private static final int BE_SID = 9321;
private static final String SID_BR = "BR";
private static final int BR_SID = 9331;
private static final String SID_MO = "MO";
private static final int MO_SID = 9341;
private static final String SID_GE = "GE";
private static final int GE_SID = 9351;
private static final String SID_GO = "GO";
private static final int GO_SID = 2629;
private static final String SID_AC = "AC";
private static final int AC_SID = 9371;
private static final String SID_GL = "GL";
private static final int GL_SID = 9391;
private static final String SID_EA = "EA";
private static final int EA_SID = 9441;
private static final String SID_LA = "LA";
private static final int LA_SID = 9601;
private static final String SID_RI = "RI";
private static final int RI_SID = 9612;
private static final String SID_MP = "MP";
private static final int MP_SID = 9613;
private static final String SID_RU = "RU";
private static final int RU_SID = 9614;
private static final String SID_KC = "KC";
private static final int KC_SID = 9621;
private static final String SID_AU = "AU";
private static final int AU_SID = 9631;
private static final String SID_NE = "NE";
private static final int NE_SID = 9641;
private static final String SID_BD = "BD";
private static final int BD_SID = 9651;
private static final String SID_BA = "BA";
private static final int BA_SID = 9681;
private static final String SID_AD = "AD";
private static final int AD_SID = 9691;
private static final String SID_MK = "MK";
private static final int MK_SID = 9701;
private static final String SID_UI = "UI";
private static final int UI_SID = 9712;
private static final String SID_MR = "MR";
private static final int MR_SID = 9721;
private static final String SID_CE = "CE";
private static final int CE_SID = 9722;
private static final String SID_MJ = "MJ";
private static final int MJ_SID = 9731;
private static final String SID_ST = "ST";
private static final int ST_SID = 9741;
private static final String SID_LI = "LI";
private static final int LI_SID = 9742;
private static final String SID_KE = "KE";
private static final int KE_SID = 9771;
private static final String SID_WR = "WR";
private static final int WR_SID = 100001;
private static final String SID_USBT = "USBT";
private static final int USBT_SID = 100002;
private static final String SID_NI = "NI";
private static final int NI_SID = 100003;
private static final String SID_PA = "PA";
private static final int PA_SID = 100004;
private static final String SID_SCTH = "SCTH";
private static final int SCTH_SID = 100005;
@Override
public int getStopId(GStop gStop) {
if (!Utils.isDigitsOnly(gStop.getStopId())) {
if (SID_UN.equals(gStop.getStopId())) {
return UN_SID;
} else if (SID_EX.equals(gStop.getStopId())) {
return EX_SID;
} else if (SID_MI.equals(gStop.getStopId())) {
return MI_SID;
} else if (SID_LO.equals(gStop.getStopId())) {
return LO_SID;
} else if (SID_DA.equals(gStop.getStopId())) {
return DA_SID;
} else if (SID_SC.equals(gStop.getStopId())) {
return SC_SID;
} else if (SID_EG.equals(gStop.getStopId())) {
return EG_SID;
} else if (SID_GU.equals(gStop.getStopId())) {
return GU_SID;
} else if (SID_RO.equals(gStop.getStopId())) {
return RO_SID;
} else if (SID_PO.equals(gStop.getStopId())) {
return PO_SID;
} else if (SID_CL.equals(gStop.getStopId())) {
return CL_SID;
} else if (SID_OA.equals(gStop.getStopId())) {
return OA_SID;
} else if (SID_BO.equals(gStop.getStopId())) {
return BO_SID;
} else if (SID_AP.equals(gStop.getStopId())) {
return AP_SID;
} else if (SID_BU.equals(gStop.getStopId())) {
return BU_SID;
} else if (SID_AL.equals(gStop.getStopId())) {
return AL_SID;
} else if (SID_PIN.equals(gStop.getStopId())) {
return PIN_SID;
} else if (SID_AJ.equals(gStop.getStopId())) {
return AJ_SID;
} else if (SID_WH.equals(gStop.getStopId())) {
return WH_SID;
} else if (SID_OS.equals(gStop.getStopId())) {
return OS_SID;
} else if (SID_BL.equals(gStop.getStopId())) {
return BL_SID;
} else if (SID_KP.equals(gStop.getStopId())) {
return KP_SID;
} else if (SID_WE.equals(gStop.getStopId())) {
return WE_SID;
} else if (SID_ET.equals(gStop.getStopId())) {
return ET_SID;
} else if (SID_OR.equals(gStop.getStopId())) {
return OR_SID;
} else if (SID_OL.equals(gStop.getStopId())) {
return OL_SID;
} else if (SID_AG.equals(gStop.getStopId())) {
return AG_SID;
} else if (SID_DI.equals(gStop.getStopId())) {
return DI_SID;
} else if (SID_CO.equals(gStop.getStopId())) {
return CO_SID;
} else if (SID_ER.equals(gStop.getStopId())) {
return ER_SID;
} else if (SID_HA.equals(gStop.getStopId())) {
return HA_SID;
} else if (SID_YO.equals(gStop.getStopId())) {
return YO_SID;
} else if (SID_SR.equals(gStop.getStopId())) {
return SR_SID;
} else if (SID_ME.equals(gStop.getStopId())) {
return ME_SID;
} else if (SID_LS.equals(gStop.getStopId())) {
return LS_SID;
} else if (SID_ML.equals(gStop.getStopId())) {
return ML_SID;
} else if (SID_KI.equals(gStop.getStopId())) {
return KI_SID;
} else if (SID_MA.equals(gStop.getStopId())) {
return MA_SID;
} else if (SID_BE.equals(gStop.getStopId())) {
return BE_SID;
} else if (SID_BR.equals(gStop.getStopId())) {
return BR_SID;
} else if (SID_MO.equals(gStop.getStopId())) {
return MO_SID;
} else if (SID_GE.equals(gStop.getStopId())) {
return GE_SID;
} else if (SID_GO.equals(gStop.getStopId())) {
return GO_SID;
} else if (SID_AC.equals(gStop.getStopId())) {
return AC_SID;
} else if (SID_GL.equals(gStop.getStopId())) {
return GL_SID;
} else if (SID_EA.equals(gStop.getStopId())) {
return EA_SID;
} else if (SID_LA.equals(gStop.getStopId())) {
return LA_SID;
} else if (SID_RI.equals(gStop.getStopId())) {
return RI_SID;
} else if (SID_MP.equals(gStop.getStopId())) {
return MP_SID;
} else if (SID_RU.equals(gStop.getStopId())) {
return RU_SID;
} else if (SID_KC.equals(gStop.getStopId())) {
return KC_SID;
} else if (SID_AU.equals(gStop.getStopId())) {
return AU_SID;
} else if (SID_NE.equals(gStop.getStopId())) {
return NE_SID;
} else if (SID_BD.equals(gStop.getStopId())) {
return BD_SID;
} else if (SID_BA.equals(gStop.getStopId())) {
return BA_SID;
} else if (SID_AD.equals(gStop.getStopId())) {
return AD_SID;
} else if (SID_MK.equals(gStop.getStopId())) {
return MK_SID;
} else if (SID_UI.equals(gStop.getStopId())) {
return UI_SID;
} else if (SID_MR.equals(gStop.getStopId())) {
return MR_SID;
} else if (SID_CE.equals(gStop.getStopId())) {
return CE_SID;
} else if (SID_MJ.equals(gStop.getStopId())) {
return MJ_SID;
} else if (SID_ST.equals(gStop.getStopId())) {
return ST_SID;
} else if (SID_LI.equals(gStop.getStopId())) {
return LI_SID;
} else if (SID_KE.equals(gStop.getStopId())) {
return KE_SID;
} else if (SID_WR.equals(gStop.getStopId())) {
return WR_SID;
} else if (SID_USBT.equals(gStop.getStopId())) {
return USBT_SID;
} else if (SID_NI.equals(gStop.getStopId())) {
return NI_SID;
} else if (SID_PA.equals(gStop.getStopId())) {
return PA_SID;
} else if (SID_SCTH.equals(gStop.getStopId())) {
return SCTH_SID;
} else {
System.out.printf("\nUnexpected stop ID %s.\n", gStop);
System.exit(-1);
return -1;
}
}
return super.getStopId(gStop);
}
}
|
src/org/mtransit/parser/ca_gtha_go_transit_train/GTHAGOTransitTrainAgencyTools.java
|
package org.mtransit.parser.ca_gtha_go_transit_train;
import java.util.HashSet;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.mtransit.parser.CleanUtils;
import org.mtransit.parser.DefaultAgencyTools;
import org.mtransit.parser.Utils;
import org.mtransit.parser.gtfs.data.GCalendar;
import org.mtransit.parser.gtfs.data.GCalendarDate;
import org.mtransit.parser.gtfs.data.GRoute;
import org.mtransit.parser.gtfs.data.GSpec;
import org.mtransit.parser.gtfs.data.GStop;
import org.mtransit.parser.gtfs.data.GTrip;
import org.mtransit.parser.mt.data.MAgency;
import org.mtransit.parser.mt.data.MRoute;
import org.mtransit.parser.mt.data.MTrip;
// http://www.gotransit.com/publicroot/en/schedules/DeveloperResources.aspx
// http://www.gotransit.com/timetables/fr/schedules/DeveloperResources.aspx
// http://www.gotransit.com/publicroot/en/schedules/GTFSdownload.aspx
// http://www.gotransit.com/publicroot/gtfs/google_transit.zip
public class GTHAGOTransitTrainAgencyTools extends DefaultAgencyTools {
public static void main(String[] args) {
if (args == null || args.length == 0) {
args = new String[3];
args[0] = "input/gtfs.zip";
args[1] = "../../mtransitapps/ca-gtha-go-transit-train-android/res/raw/";
args[2] = ""; // files-prefix
}
new GTHAGOTransitTrainAgencyTools().start(args);
}
private HashSet<String> serviceIds;
@Override
public void start(String[] args) {
System.out.printf("\nGenerating GO Transit train data...");
long start = System.currentTimeMillis();
this.serviceIds = extractUsefulServiceIds(args, this, true);
super.start(args);
System.out.printf("\nGenerating GO Transit train data... DONE in %s.\n", Utils.getPrettyDuration(System.currentTimeMillis() - start));
}
@Override
public boolean excludeCalendar(GCalendar gCalendar) {
if (this.serviceIds != null) {
return excludeUselessCalendar(gCalendar, this.serviceIds);
}
return super.excludeCalendar(gCalendar);
}
@Override
public boolean excludeCalendarDate(GCalendarDate gCalendarDates) {
if (this.serviceIds != null) {
return excludeUselessCalendarDate(gCalendarDates, this.serviceIds);
}
return super.excludeCalendarDate(gCalendarDates);
}
@Override
public boolean excludeTrip(GTrip gTrip) {
if (this.serviceIds != null) {
return excludeUselessTrip(gTrip, this.serviceIds);
}
return super.excludeTrip(gTrip);
}
@Override
public Integer getAgencyRouteType() {
return MAgency.ROUTE_TYPE_TRAIN;
}
private static final long LW_RID = 1l; // Lakeshore West
private static final long MI_RID = 2l; // Milton
private static final long KI_RID = 3l; // Kitchener
private static final long BR_RID = 5l; // Barrie
private static final long RH_RID = 6l; // Richmond Hill
private static final long ST_RID = 7l; // Stouffville
private static final long LE_RID = 9l; // Lakeshore East
@Override
public long getRouteId(GRoute gRoute) {
if (ST_RSN.equals(gRoute.getRouteShortName())) {
return ST_RID;
} else if (RH_RSN.equals(gRoute.getRouteShortName())) {
return RH_RID;
} else if (MI_RSN.equals(gRoute.getRouteShortName())) {
return MI_RID;
} else if (LW_RSN.equals(gRoute.getRouteShortName())) {
return LW_RID;
} else if (LE_RSN.equals(gRoute.getRouteShortName())) {
return LE_RID;
} else if (KI_RSN.equals(gRoute.getRouteShortName()) //
|| GT_RSN.equals(gRoute.getRouteShortName())) {
return KI_RID;
} else if (BR_RSN.equals(gRoute.getRouteShortName())) {
return BR_RID;
} else {
System.out.printf("\nUnexpected route ID for %s!\n", gRoute);
System.exit(-1);
return -1l;
}
}
@Override
public String getRouteLongName(GRoute gRoute) {
String routeLongName = gRoute.getRouteLongName();
routeLongName = CleanUtils.cleanStreetTypes(routeLongName);
return CleanUtils.cleanLabel(routeLongName);
}
private static final String ST_RSN = "ST"; // Stouffville
private static final String RH_RSN = "RH"; // Richmond Hill
private static final String MI_RSN = "MI"; // Milton
private static final String LW_RSN = "LW"; // Lakeshore West
private static final String LE_RSN = "LE"; // Lakeshore East
private static final String KI_RSN = "KI"; // Kitchener
private static final String GT_RSN = "GT"; // Kitchener
private static final String BR_RSN = "BR"; // Barrie
private static final String AGENCY_COLOR = "387C2B"; // GREEN (AGENCY WEB SITE CSS)
@Override
public String getAgencyColor() {
return AGENCY_COLOR;
}
private static final String COLOR_BC6277 = "BC6277";
private static final String COLOR_F46F1A = "F46F1A";
private static final String COLOR_098137 = "098137";
private static final String COLOR_0B335E = "0B335E";
private static final String COLOR_0098C9 = "0098C9";
private static final String COLOR_794500 = "794500";
private static final String COLOR_96092B = "96092B";
private static final String COLOR_EE3124 = "EE3124";
@Override
public String getRouteColor(GRoute gRoute) {
if (StringUtils.isEmpty(gRoute.getRouteColor())) {
int routeId = (int) getRouteId(gRoute);
switch (routeId) {
// @formatter:off
case 1: return COLOR_96092B; // Lakeshore West
case 2: return COLOR_F46F1A; // Milton
case 3: return COLOR_098137; // Kitchener
case 5: return COLOR_0B335E; // Barrie
case 6: return COLOR_0098C9; // Richmond Hill
case 7: return COLOR_794500; // Stouffville
case 8: return COLOR_BC6277; // Niagara Falls
case 9: return COLOR_EE3124; // Lakeshore East
// @formatter:on
}
System.out.printf("Unexpected route color '%s'!\n", gRoute);
System.exit(-1);
return null;
}
return super.getRouteColor(gRoute);
}
private static final String ALLANDALE_WATERFRONT = "Allandale Waterfront";
private static final String GORMLEY = "Gormley";
private static final String LINCOLNVILLE = "Lincolnville";
private static final String OSHAWA = "Oshawa";
private static final String KITCHENER = "Kitchener";
private static final String HAMILTON = "Hamilton";
@Override
public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip, GSpec gtfs) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), gTrip.getDirectionId());
}
@Override
public boolean mergeHeadsign(MTrip mTrip, MTrip mTripToMerge) {
if (mTrip.getRouteId() == LW_RID) { // Lakeshore West
if (mTrip.getHeadsignId() == 0) {
mTrip.setHeadsignString(HAMILTON, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == MI_RID) { // Milton
} else if (mTrip.getRouteId() == KI_RID) { // Kitchener
if (mTrip.getHeadsignId() == 0) {
mTrip.setHeadsignString(KITCHENER, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == BR_RID) { // Barrie
if (mTrip.getHeadsignId() == 0) {
mTrip.setHeadsignString(ALLANDALE_WATERFRONT, mTrip.getHeadsignId()); // Barrie
return true;
}
} else if (mTrip.getRouteId() == RH_RID) { // Richmond Hill
if (mTrip.getHeadsignId() == 0) {
mTrip.setHeadsignString(GORMLEY, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == ST_RID) { // Stouffville
if (mTrip.getHeadsignId() == 0) {
mTrip.setHeadsignString(LINCOLNVILLE, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == LE_RID) { // Lakeshore East
if (mTrip.getHeadsignId() == 0) {
mTrip.setHeadsignString(OSHAWA, mTrip.getHeadsignId());
return true;
}
}
System.out.printf("\nUnexpected trips to merge %s & %s!\n", mTrip, mTripToMerge);
return false;
}
private static final Pattern START_WITH_RSN = Pattern.compile("(^[A-Z]{2}\\-)", Pattern.CASE_INSENSITIVE);
private static final Pattern FIRST_STATION_TIME_LAST_STATION_TIME = Pattern.compile("" //
+ "(" //
+ "([\\w\\s]*)" //
+ "[\\s]+" //
+ "([\\d]{2}\\:[\\d]{2})" //
+ "[\\s]+" //
+ "\\-" //
+ "[\\s]+" //
+ "([\\w\\s]*)" //
+ "[\\s]+" //
+ "([\\d]{2}\\:[\\d]{2})" //
+ ")", Pattern.CASE_INSENSITIVE);
private static final String FIRST_STATION_TIME_LAST_STATION_TIME_REPLACEMENT = "$4";
private static final Pattern CENTER = Pattern.compile("((^|\\W){1}(center|centre|ctr)(\\W|$){1})", Pattern.CASE_INSENSITIVE);
private static final String CENTER_REPLACEMENT = " ";
@Override
public String cleanTripHeadsign(String tripHeadsign) {
tripHeadsign = START_WITH_RSN.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY);
tripHeadsign = FIRST_STATION_TIME_LAST_STATION_TIME.matcher(tripHeadsign).replaceAll(FIRST_STATION_TIME_LAST_STATION_TIME_REPLACEMENT);
tripHeadsign = GO.matcher(tripHeadsign).replaceAll(GO_REPLACEMENT);
tripHeadsign = CENTER.matcher(tripHeadsign).replaceAll(CENTER_REPLACEMENT);
tripHeadsign = STATION.matcher(tripHeadsign).replaceAll(STATION_REPLACEMENT);
tripHeadsign = CleanUtils.cleanStreetTypes(tripHeadsign);
return CleanUtils.cleanLabel(tripHeadsign);
}
private static final Pattern GO = Pattern.compile("(^|\\s){1}(go)($|\\s){1}", Pattern.CASE_INSENSITIVE);
private static final String GO_REPLACEMENT = " ";
private static final Pattern VIA = Pattern.compile("(^|\\s){1}(via)($|\\s){1}", Pattern.CASE_INSENSITIVE);
private static final String VIA_REPLACEMENT = " ";
private static final Pattern RAIL = Pattern.compile("(^|\\s){1}(rail)($|\\s){1}", Pattern.CASE_INSENSITIVE);
private static final String RAIL_REPLACEMENT = " ";
private static final Pattern STATION = Pattern.compile("(^|\\s){1}(station)($|\\s){1}", Pattern.CASE_INSENSITIVE);
private static final String STATION_REPLACEMENT = " ";
@Override
public String cleanStopName(String gStopName) {
gStopName = CleanUtils.CLEAN_AT.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AT_REPLACEMENT);
gStopName = VIA.matcher(gStopName).replaceAll(VIA_REPLACEMENT);
gStopName = GO.matcher(gStopName).replaceAll(GO_REPLACEMENT);
gStopName = RAIL.matcher(gStopName).replaceAll(RAIL_REPLACEMENT);
gStopName = STATION.matcher(gStopName).replaceAll(STATION_REPLACEMENT);
gStopName = CleanUtils.cleanNumbers(gStopName);
gStopName = CleanUtils.cleanStreetTypes(gStopName);
return CleanUtils.cleanLabel(gStopName);
}
private static final String SID_UN = "UN";
private static final int UN_SID = 9021;
private static final String SID_EX = "EX";
private static final int EX_SID = 9022;
private static final String SID_MI = "MI";
private static final int MI_SID = 9031;
private static final String SID_LO = "LO";
private static final int LO_SID = 9033;
private static final String SID_DA = "DA";
private static final int DA_SID = 9061;
private static final String SID_SC = "SC";
private static final int SC_SID = 9062;
private static final String SID_EG = "EG";
private static final int EG_SID = 9063;
private static final String SID_GU = "GU";
private static final int GU_SID = 9081;
private static final String SID_RO = "RO";
private static final int RO_SID = 9091;
private static final String SID_PO = "PO";
private static final int PO_SID = 9111;
private static final String SID_CL = "CL";
private static final int CL_SID = 9121;
private static final String SID_OA = "OA";
private static final int OA_SID = 9131;
private static final String SID_BO = "BO";
private static final int BO_SID = 9141;
private static final String SID_AP = "AP";
private static final int AP_SID = 9151;
private static final String SID_BU = "BU";
private static final int BU_SID = 9161;
private static final String SID_AL = "AL";
private static final int AL_SID = 9171;
private static final String SID_PIN = "PIN";
private static final int PIN_SID = 9911;
private static final String SID_AJ = "AJ";
private static final int AJ_SID = 9921;
private static final String SID_WH = "WH";
private static final int WH_SID = 9939;
private static final String SID_OS = "OS";
private static final int OS_SID = 9941;
private static final String SID_BL = "BL";
private static final int BL_SID = 9023;
private static final String SID_KP = "KP";
private static final int KP_SID = 9032;
private static final String SID_WE = "WE";
private static final int WE_SID = 9041;
private static final String SID_ET = "ET";
private static final int ET_SID = 9042;
private static final String SID_OR = "OR";
private static final int OR_SID = 9051;
private static final String SID_OL = "OL";
private static final int OL_SID = 9052;
private static final String SID_AG = "AG";
private static final int AG_SID = 9071;
private static final String SID_DI = "DI";
private static final int DI_SID = 9113;
private static final String SID_CO = "CO";
private static final int CO_SID = 9114;
private static final String SID_ER = "ER";
private static final int ER_SID = 9123;
private static final String SID_HA = "HA";
private static final int HA_SID = 9181;
private static final String SID_YO = "YO";
private static final int YO_SID = 9191;
private static final String SID_SR = "SR";
private static final int SR_SID = 9211;
private static final String SID_ME = "ME";
private static final int ME_SID = 9221;
private static final String SID_LS = "LS";
private static final int LS_SID = 9231;
private static final String SID_ML = "ML";
private static final int ML_SID = 9241;
private static final String SID_KI = "KI";
private static final int KI_SID = 9271;
private static final String SID_MA = "MA";
private static final int MA_SID = 9311;
private static final String SID_BE = "BE";
private static final int BE_SID = 9321;
private static final String SID_BR = "BR";
private static final int BR_SID = 9331;
private static final String SID_MO = "MO";
private static final int MO_SID = 9341;
private static final String SID_GE = "GE";
private static final int GE_SID = 9351;
private static final String SID_GO = "GO";
private static final int GO_SID = 2629;
private static final String SID_AC = "AC";
private static final int AC_SID = 9371;
private static final String SID_GL = "GL";
private static final int GL_SID = 9391;
private static final String SID_EA = "EA";
private static final int EA_SID = 9441;
private static final String SID_LA = "LA";
private static final int LA_SID = 9601;
private static final String SID_RI = "RI";
private static final int RI_SID = 9612;
private static final String SID_MP = "MP";
private static final int MP_SID = 9613;
private static final String SID_RU = "RU";
private static final int RU_SID = 9614;
private static final String SID_KC = "KC";
private static final int KC_SID = 9621;
private static final String SID_AU = "AU";
private static final int AU_SID = 9631;
private static final String SID_NE = "NE";
private static final int NE_SID = 9641;
private static final String SID_BD = "BD";
private static final int BD_SID = 9651;
private static final String SID_BA = "BA";
private static final int BA_SID = 9681;
private static final String SID_AD = "AD";
private static final int AD_SID = 9691;
private static final String SID_MK = "MK";
private static final int MK_SID = 9701;
private static final String SID_UI = "UI";
private static final int UI_SID = 9712;
private static final String SID_MR = "MR";
private static final int MR_SID = 9721;
private static final String SID_CE = "CE";
private static final int CE_SID = 9722;
private static final String SID_MJ = "MJ";
private static final int MJ_SID = 9731;
private static final String SID_ST = "ST";
private static final int ST_SID = 9741;
private static final String SID_LI = "LI";
private static final int LI_SID = 9742;
private static final String SID_KE = "KE";
private static final int KE_SID = 9771;
private static final String SID_WR = "WR";
private static final int WR_SID = 100001;
private static final String SID_USBT = "USBT";
private static final int USBT_SID = 100002;
private static final String SID_NI = "NI";
private static final int NI_SID = 100003;
private static final String SID_PA = "PA";
private static final int PA_SID = 100004;
private static final String SID_SCTH = "SCTH";
private static final int SCTH_SID = 100005;
@Override
public int getStopId(GStop gStop) {
if (!Utils.isDigitsOnly(gStop.getStopId())) {
if (SID_UN.equals(gStop.getStopId())) {
return UN_SID;
} else if (SID_EX.equals(gStop.getStopId())) {
return EX_SID;
} else if (SID_MI.equals(gStop.getStopId())) {
return MI_SID;
} else if (SID_LO.equals(gStop.getStopId())) {
return LO_SID;
} else if (SID_DA.equals(gStop.getStopId())) {
return DA_SID;
} else if (SID_SC.equals(gStop.getStopId())) {
return SC_SID;
} else if (SID_EG.equals(gStop.getStopId())) {
return EG_SID;
} else if (SID_GU.equals(gStop.getStopId())) {
return GU_SID;
} else if (SID_RO.equals(gStop.getStopId())) {
return RO_SID;
} else if (SID_PO.equals(gStop.getStopId())) {
return PO_SID;
} else if (SID_CL.equals(gStop.getStopId())) {
return CL_SID;
} else if (SID_OA.equals(gStop.getStopId())) {
return OA_SID;
} else if (SID_BO.equals(gStop.getStopId())) {
return BO_SID;
} else if (SID_AP.equals(gStop.getStopId())) {
return AP_SID;
} else if (SID_BU.equals(gStop.getStopId())) {
return BU_SID;
} else if (SID_AL.equals(gStop.getStopId())) {
return AL_SID;
} else if (SID_PIN.equals(gStop.getStopId())) {
return PIN_SID;
} else if (SID_AJ.equals(gStop.getStopId())) {
return AJ_SID;
} else if (SID_WH.equals(gStop.getStopId())) {
return WH_SID;
} else if (SID_OS.equals(gStop.getStopId())) {
return OS_SID;
} else if (SID_BL.equals(gStop.getStopId())) {
return BL_SID;
} else if (SID_KP.equals(gStop.getStopId())) {
return KP_SID;
} else if (SID_WE.equals(gStop.getStopId())) {
return WE_SID;
} else if (SID_ET.equals(gStop.getStopId())) {
return ET_SID;
} else if (SID_OR.equals(gStop.getStopId())) {
return OR_SID;
} else if (SID_OL.equals(gStop.getStopId())) {
return OL_SID;
} else if (SID_AG.equals(gStop.getStopId())) {
return AG_SID;
} else if (SID_DI.equals(gStop.getStopId())) {
return DI_SID;
} else if (SID_CO.equals(gStop.getStopId())) {
return CO_SID;
} else if (SID_ER.equals(gStop.getStopId())) {
return ER_SID;
} else if (SID_HA.equals(gStop.getStopId())) {
return HA_SID;
} else if (SID_YO.equals(gStop.getStopId())) {
return YO_SID;
} else if (SID_SR.equals(gStop.getStopId())) {
return SR_SID;
} else if (SID_ME.equals(gStop.getStopId())) {
return ME_SID;
} else if (SID_LS.equals(gStop.getStopId())) {
return LS_SID;
} else if (SID_ML.equals(gStop.getStopId())) {
return ML_SID;
} else if (SID_KI.equals(gStop.getStopId())) {
return KI_SID;
} else if (SID_MA.equals(gStop.getStopId())) {
return MA_SID;
} else if (SID_BE.equals(gStop.getStopId())) {
return BE_SID;
} else if (SID_BR.equals(gStop.getStopId())) {
return BR_SID;
} else if (SID_MO.equals(gStop.getStopId())) {
return MO_SID;
} else if (SID_GE.equals(gStop.getStopId())) {
return GE_SID;
} else if (SID_GO.equals(gStop.getStopId())) {
return GO_SID;
} else if (SID_AC.equals(gStop.getStopId())) {
return AC_SID;
} else if (SID_GL.equals(gStop.getStopId())) {
return GL_SID;
} else if (SID_EA.equals(gStop.getStopId())) {
return EA_SID;
} else if (SID_LA.equals(gStop.getStopId())) {
return LA_SID;
} else if (SID_RI.equals(gStop.getStopId())) {
return RI_SID;
} else if (SID_MP.equals(gStop.getStopId())) {
return MP_SID;
} else if (SID_RU.equals(gStop.getStopId())) {
return RU_SID;
} else if (SID_KC.equals(gStop.getStopId())) {
return KC_SID;
} else if (SID_AU.equals(gStop.getStopId())) {
return AU_SID;
} else if (SID_NE.equals(gStop.getStopId())) {
return NE_SID;
} else if (SID_BD.equals(gStop.getStopId())) {
return BD_SID;
} else if (SID_BA.equals(gStop.getStopId())) {
return BA_SID;
} else if (SID_AD.equals(gStop.getStopId())) {
return AD_SID;
} else if (SID_MK.equals(gStop.getStopId())) {
return MK_SID;
} else if (SID_UI.equals(gStop.getStopId())) {
return UI_SID;
} else if (SID_MR.equals(gStop.getStopId())) {
return MR_SID;
} else if (SID_CE.equals(gStop.getStopId())) {
return CE_SID;
} else if (SID_MJ.equals(gStop.getStopId())) {
return MJ_SID;
} else if (SID_ST.equals(gStop.getStopId())) {
return ST_SID;
} else if (SID_LI.equals(gStop.getStopId())) {
return LI_SID;
} else if (SID_KE.equals(gStop.getStopId())) {
return KE_SID;
} else if (SID_WR.equals(gStop.getStopId())) {
return WR_SID;
} else if (SID_USBT.equals(gStop.getStopId())) {
return USBT_SID;
} else if (SID_NI.equals(gStop.getStopId())) {
return NI_SID;
} else if (SID_PA.equals(gStop.getStopId())) {
return PA_SID;
} else if (SID_SCTH.equals(gStop.getStopId())) {
return SCTH_SID;
} else {
System.out.printf("\nUnexpected stop ID %s.\n", gStop);
System.exit(-1);
return -1;
}
}
return super.getStopId(gStop);
}
}
|
Compatibility with latest update.
|
src/org/mtransit/parser/ca_gtha_go_transit_train/GTHAGOTransitTrainAgencyTools.java
|
Compatibility with latest update.
|
<ide><path>rc/org/mtransit/parser/ca_gtha_go_transit_train/GTHAGOTransitTrainAgencyTools.java
<ide> return KI_RID;
<ide> } else if (BR_RSN.equals(gRoute.getRouteShortName())) {
<ide> return BR_RID;
<del> } else {
<del> System.out.printf("\nUnexpected route ID for %s!\n", gRoute);
<del> System.exit(-1);
<del> return -1l;
<del> }
<add> }
<add> if (gRoute.getRouteId().endsWith(ST_RSN)) {
<add> return ST_RID;
<add> } else if (gRoute.getRouteId().endsWith(RH_RSN)) {
<add> return RH_RID;
<add> } else if (gRoute.getRouteId().endsWith(MI_RSN)) {
<add> return MI_RID;
<add> } else if (gRoute.getRouteId().endsWith(LW_RSN)) {
<add> return LW_RID;
<add> } else if (gRoute.getRouteId().endsWith(LE_RSN)) {
<add> return LE_RID;
<add> } else if (gRoute.getRouteId().endsWith(KI_RSN) //
<add> || gRoute.getRouteId().endsWith(GT_RSN)) {
<add> return KI_RID;
<add> } else if (gRoute.getRouteId().endsWith(BR_RSN)) {
<add> return BR_RID;
<add> }
<add> System.out.printf("\nUnexpected route ID for %s!\n", gRoute);
<add> System.exit(-1);
<add> return -1l;
<ide> }
<ide>
<ide> @Override
<ide> private static final String KI_RSN = "KI"; // Kitchener
<ide> private static final String GT_RSN = "GT"; // Kitchener
<ide> private static final String BR_RSN = "BR"; // Barrie
<add>
<add> @Override
<add> public String getRouteShortName(GRoute gRoute) {
<add> if (StringUtils.isEmpty(gRoute.getRouteShortName())) {
<add> if (gRoute.getRouteId().endsWith(ST_RSN)) {
<add> return ST_RSN;
<add> } else if (gRoute.getRouteId().endsWith(RH_RSN)) {
<add> return RH_RSN;
<add> } else if (gRoute.getRouteId().endsWith(MI_RSN)) {
<add> return MI_RSN;
<add> } else if (gRoute.getRouteId().endsWith(LW_RSN)) {
<add> return LW_RSN;
<add> } else if (gRoute.getRouteId().endsWith(LE_RSN)) {
<add> return LE_RSN;
<add> } else if (gRoute.getRouteId().endsWith(KI_RSN) //
<add> || gRoute.getRouteId().endsWith(GT_RSN)) {
<add> return GT_RSN;
<add> } else if (gRoute.getRouteId().endsWith(BR_RSN)) {
<add> return BR_RSN;
<add> }
<add> System.out.printf("\nUnexpected route short name for %s!\n", gRoute);
<add> System.exit(-1);
<add> return null;
<add> }
<add> return super.getRouteShortName(gRoute);
<add> }
<ide>
<ide> private static final String AGENCY_COLOR = "387C2B"; // GREEN (AGENCY WEB SITE CSS)
<ide>
|
|
Java
|
apache-2.0
|
fec14b9dcede399b37f4d62d8bc4179344716f90
| 0 |
shadabkhaniet/greenhouse,StetsiukRoman/greenhouse,abisare/greenhouse,spring-projects/greenhouse,aliasnash/z-greenhouse,mqprichard/spring-greenhouse-clickstart,shadabkhaniet/greenhouse,rajacsp/greenhouse,gienini/GreenHouseItteria,patidarjitu/networking-project-details1,spring-projects/greenhouse
|
package com.springsource.greenhouse.connect;
import java.util.HashMap;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
import org.springframework.security.core.Authentication;
import org.springframework.social.twitter.DuplicateTweetException;
import org.springframework.social.twitter.TwitterOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.flash.FlashMap;
import com.springsource.greenhouse.account.Account;
@Controller
@RequestMapping("/connect/twitter")
public class TwitterConnectController {
private static final String OAUTH_TOKEN_ATTRIBUTE = "oauthToken";
private AccountProvider<TwitterOperations> accountProvider;
@Inject
public TwitterConnectController(@Named("twitterAccountProvider") AccountProvider<TwitterOperations> accountProvider) {
this.accountProvider = accountProvider;
}
@RequestMapping(method = RequestMethod.GET)
public String twitterConnect(Account account) {
if (accountProvider.isConnected(account.getId())) {
return "connect/twitterConnected";
} else {
return "connect/twitterConnect";
}
}
@RequestMapping(method=RequestMethod.POST)
public String connect(@RequestParam(required=false, defaultValue="false") boolean postTweet, WebRequest request) {
OAuthToken requestToken = accountProvider.getRequestToken();
request.setAttribute(OAUTH_TOKEN_ATTRIBUTE, requestTokenHolder(requestToken, postTweet), WebRequest.SCOPE_SESSION);
return "redirect:" + accountProvider.getAuthorizeUrl(requestToken.getValue());
}
@RequestMapping(method=RequestMethod.GET, params="oauth_token")
public String authorizeCallback(@RequestParam("oauth_token") String token, @RequestParam("oauth_verifier") String verifier, Account account, WebRequest request) {
@SuppressWarnings("unchecked")
Map<String, Object> requestTokenHolder = (Map<String, Object>) request.getAttribute(OAUTH_TOKEN_ATTRIBUTE, WebRequest.SCOPE_SESSION);
if (requestTokenHolder == null) {
return "connect/twitterConnect";
}
request.removeAttribute(OAUTH_TOKEN_ATTRIBUTE, WebRequest.SCOPE_SESSION);
OAuthToken requestToken = (OAuthToken) requestTokenHolder.get("value");
TwitterOperations twitter = accountProvider.connect(account.getId(), requestToken, verifier);
accountProvider.updateProviderAccountId(account.getId(), twitter.getScreenName());
if (requestTokenHolder.containsKey("postTweet")) {
try {
twitter.tweet("Join me at the Greenhouse! " + account.getProfileUrl());
} catch (DuplicateTweetException doesntMatter) {
// In this case, it doesn't matter if there's a duplicate tweet.
// It's unlikely to happen unless the user repeatedly
// connects/disconnects to/from Twitter. And even then, it's no
// big deal.
}
}
FlashMap.setSuccessMessage("Your Greenhouse account is now connected to your Twitter account!");
return "redirect:/connect/twitter";
}
@RequestMapping(method = RequestMethod.DELETE)
public String disconnectTwitter(Account account, HttpServletRequest request, Authentication authentication) {
accountProvider.disconnect(account.getId());
return "redirect:/connect/twitter";
}
// internal helpers
private Map<String, Object> requestTokenHolder(OAuthToken requestToken, boolean postTweet) {
Map<String, Object> holder = new HashMap<String, Object>(2, 1);
holder.put("value", requestToken);
if (postTweet) {
holder.put("postTweet", Boolean.TRUE);
}
return holder;
}
}
|
src/main/java/com/springsource/greenhouse/connect/TwitterConnectController.java
|
package com.springsource.greenhouse.connect;
import java.util.HashMap;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
import org.springframework.security.core.Authentication;
import org.springframework.social.twitter.TwitterOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.flash.FlashMap;
import com.springsource.greenhouse.account.Account;
@Controller
@RequestMapping("/connect/twitter")
public class TwitterConnectController {
private static final String OAUTH_TOKEN_ATTRIBUTE = "oauthToken";
private AccountProvider<TwitterOperations> accountProvider;
@Inject
public TwitterConnectController(@Named("twitterAccountProvider") AccountProvider<TwitterOperations> accountProvider) {
this.accountProvider = accountProvider;
}
@RequestMapping(method = RequestMethod.GET)
public String twitterConnect(Account account) {
if (accountProvider.isConnected(account.getId())) {
return "connect/twitterConnected";
} else {
return "connect/twitterConnect";
}
}
@RequestMapping(method=RequestMethod.POST)
public String connect(@RequestParam(required=false, defaultValue="false") boolean postTweet, WebRequest request) {
OAuthToken requestToken = accountProvider.getRequestToken();
request.setAttribute(OAUTH_TOKEN_ATTRIBUTE, requestTokenHolder(requestToken, postTweet), WebRequest.SCOPE_SESSION);
return "redirect:" + accountProvider.getAuthorizeUrl(requestToken.getValue());
}
@RequestMapping(method=RequestMethod.GET, params="oauth_token")
public String authorizeCallback(@RequestParam("oauth_token") String token, @RequestParam("oauth_verifier") String verifier, Account account, WebRequest request) {
@SuppressWarnings("unchecked")
Map<String, Object> requestTokenHolder = (Map<String, Object>) request.getAttribute(OAUTH_TOKEN_ATTRIBUTE, WebRequest.SCOPE_SESSION);
if (requestTokenHolder == null) {
return "connect/twitterConnect";
}
request.removeAttribute(OAUTH_TOKEN_ATTRIBUTE, WebRequest.SCOPE_SESSION);
OAuthToken requestToken = (OAuthToken) requestTokenHolder.get("value");
TwitterOperations twitter = accountProvider.connect(account.getId(), requestToken, verifier);
accountProvider.updateProviderAccountId(account.getId(), twitter.getScreenName());
if (requestTokenHolder.containsKey("postTweet")) {
twitter.tweet("Join me at the Greenhouse! " + account.getProfileUrl());
}
FlashMap.setSuccessMessage("Your Greenhouse account is now connected to your Twitter account!");
return "redirect:/connect/twitter";
}
@RequestMapping(method = RequestMethod.DELETE)
public String disconnectTwitter(Account account, HttpServletRequest request, Authentication authentication) {
accountProvider.disconnect(account.getId());
return "redirect:/connect/twitter";
}
// internal helpers
private Map<String, Object> requestTokenHolder(OAuthToken requestToken, boolean postTweet) {
Map<String, Object> holder = new HashMap<String, Object>(2, 1);
holder.put("value", requestToken);
if (postTweet) {
holder.put("postTweet", Boolean.TRUE);
}
return holder;
}
}
|
Ignore duplicate tweet exceptions thrown when connecting to Twitter. At that point, they're not likely to happen and cause no harm if they do.
|
src/main/java/com/springsource/greenhouse/connect/TwitterConnectController.java
|
Ignore duplicate tweet exceptions thrown when connecting to Twitter. At that point, they're not likely to happen and cause no harm if they do.
|
<ide><path>rc/main/java/com/springsource/greenhouse/connect/TwitterConnectController.java
<ide> import javax.servlet.http.HttpServletRequest;
<ide>
<ide> import org.springframework.security.core.Authentication;
<add>import org.springframework.social.twitter.DuplicateTweetException;
<ide> import org.springframework.social.twitter.TwitterOperations;
<ide> import org.springframework.stereotype.Controller;
<ide> import org.springframework.web.bind.annotation.RequestMapping;
<ide> TwitterOperations twitter = accountProvider.connect(account.getId(), requestToken, verifier);
<ide> accountProvider.updateProviderAccountId(account.getId(), twitter.getScreenName());
<ide> if (requestTokenHolder.containsKey("postTweet")) {
<del> twitter.tweet("Join me at the Greenhouse! " + account.getProfileUrl());
<add> try {
<add> twitter.tweet("Join me at the Greenhouse! " + account.getProfileUrl());
<add> } catch (DuplicateTweetException doesntMatter) {
<add> // In this case, it doesn't matter if there's a duplicate tweet.
<add> // It's unlikely to happen unless the user repeatedly
<add> // connects/disconnects to/from Twitter. And even then, it's no
<add> // big deal.
<add> }
<ide> }
<ide> FlashMap.setSuccessMessage("Your Greenhouse account is now connected to your Twitter account!");
<ide> return "redirect:/connect/twitter";
|
|
Java
|
mit
|
error: pathspec 'drawee/src/main/java/com/facebook/drawee/drawable/LightBitmapDrawable.java' did not match any file(s) known to git
|
6220436277a4f16581ee1852943a26dfbf85f4de
| 1 |
desmond1121/fresco,HKMOpen/fresco,pandavickey/fresco,xjy2061/NovaImageLoader,pandavickey/fresco,MaTriXy/fresco,s1rius/fresco,s1rius/fresco,0mok/fresco,desmond1121/fresco,xjy2061/NovaImageLoader,pandavickey/fresco,facebook/fresco,wstczlt/fresco,HKMOpen/fresco,facebook/fresco,0mok/fresco,s1rius/fresco,0mok/fresco,s1rius/fresco,pandavickey/fresco,xjy2061/NovaImageLoader,wstczlt/fresco,wstczlt/fresco,pandavickey/fresco,wstczlt/fresco,xjy2061/NovaImageLoader,MaTriXy/fresco,facebook/fresco,desmond1121/fresco,0mok/fresco,desmond1121/fresco,facebook/fresco,MaTriXy/fresco,HKMOpen/fresco,xjy2061/NovaImageLoader,facebook/fresco,wstczlt/fresco,0mok/fresco,MaTriXy/fresco,desmond1121/fresco,facebook/fresco,MaTriXy/fresco,HKMOpen/fresco
|
/*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.drawee.drawable;
import javax.annotation.Nullable;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.util.DisplayMetrics;
/**
* Light implementation of a BitmapDrawable
*/
public class LightBitmapDrawable extends Drawable {
@Nullable private Bitmap mBitmap = null;
private int mTargetDensity = DisplayMetrics.DENSITY_DEFAULT;
private static final int DEFAULT_PAINT_FLAGS =
Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG;
// These are scaled to match the target density.
private int mBitmapWidth;
private int mBitmapHeight;
private final Paint mPaint = new Paint(DEFAULT_PAINT_FLAGS);
/**
* Create drawable from a bitmap, setting initial target density based on the display metrics of
* the resources.
*/
public LightBitmapDrawable(Resources res, Bitmap bitmap) {
mBitmap = bitmap;
mTargetDensity = res.getDisplayMetrics().densityDpi;
computeBitmapSize();
}
/**
* Returns the paint used to render this drawable.
*/
public final Paint getPaint() {
return mPaint;
}
/**
* Returns the bitmap used by this drawable to render. May be null.
*/
@Nullable public final Bitmap getBitmap() {
return mBitmap;
}
private void computeBitmapSize() {
if (mBitmap != null) {
mBitmapWidth = mBitmap.getScaledWidth(mTargetDensity);
mBitmapHeight = mBitmap.getScaledHeight(mTargetDensity);
} else {
mBitmapWidth = mBitmapHeight = -1;
}
}
public void setBitmap(Bitmap bitmap) {
if (mBitmap != bitmap) {
mBitmap = bitmap;
computeBitmapSize();
invalidateSelf();
}
}
/**
* Enables or disables anti-aliasing for this drawable. Anti-aliasing affects the edges of the
* bitmap only so it applies only when the drawable is rotated.
*
* @param antiAlias True if the bitmap should be anti-aliased, false otherwise.
* @see #hasAntiAlias()
*/
public void setAntiAlias(boolean antiAlias) {
mPaint.setAntiAlias(antiAlias);
invalidateSelf();
}
/**
* Indicates whether anti-aliasing is enabled for this drawable.
*
* @return True if anti-aliasing is enabled, false otherwise.
* @see #setAntiAlias(boolean)
*/
public boolean hasAntiAlias() {
return mPaint.isAntiAlias();
}
@Override
public void setFilterBitmap(boolean filter) {
mPaint.setFilterBitmap(filter);
invalidateSelf();
}
@Override
public void setDither(boolean dither) {
mPaint.setDither(dither);
invalidateSelf();
}
@Override
public void draw(Canvas canvas) {
if (mBitmap == null) {
return;
}
canvas.drawBitmap(mBitmap, null, getBounds(), mPaint);
}
@Override
public void setAlpha(int alpha) {
if (alpha != mPaint.getAlpha()) {
mPaint.setAlpha(alpha);
invalidateSelf();
}
}
public int getAlpha() {
return mPaint.getAlpha();
}
@Override
public void setColorFilter(ColorFilter cf) {
mPaint.setColorFilter(cf);
invalidateSelf();
}
public ColorFilter getColorFilter() {
return mPaint.getColorFilter();
}
@Override
public int getIntrinsicWidth() {
return mBitmapWidth;
}
@Override
public int getIntrinsicHeight() {
return mBitmapHeight;
}
@Override
public int getOpacity() {
return (mBitmap == null || mBitmap.hasAlpha() || mPaint.getAlpha() < 255) ?
PixelFormat.TRANSLUCENT : PixelFormat.OPAQUE;
}
}
|
drawee/src/main/java/com/facebook/drawee/drawable/LightBitmapDrawable.java
|
Implemented a light version of BitmapDrawable
Reviewed By: plamenko
Differential Revision: D3052858
fb-gh-sync-id: e5d53028361c1ad8e58e15d3855c8260fa00570d
fbshipit-source-id: e5d53028361c1ad8e58e15d3855c8260fa00570d
|
drawee/src/main/java/com/facebook/drawee/drawable/LightBitmapDrawable.java
|
Implemented a light version of BitmapDrawable
|
<ide><path>rawee/src/main/java/com/facebook/drawee/drawable/LightBitmapDrawable.java
<add>/*
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>
<add>package com.facebook.drawee.drawable;
<add>
<add>import javax.annotation.Nullable;
<add>
<add>import android.content.res.Resources;
<add>import android.graphics.Bitmap;
<add>import android.graphics.Canvas;
<add>import android.graphics.ColorFilter;
<add>import android.graphics.Paint;
<add>import android.graphics.PixelFormat;
<add>import android.graphics.drawable.Drawable;
<add>import android.util.DisplayMetrics;
<add>
<add>/**
<add> * Light implementation of a BitmapDrawable
<add> */
<add>public class LightBitmapDrawable extends Drawable {
<add>
<add> @Nullable private Bitmap mBitmap = null;
<add>
<add> private int mTargetDensity = DisplayMetrics.DENSITY_DEFAULT;
<add>
<add> private static final int DEFAULT_PAINT_FLAGS =
<add> Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG;
<add>
<add> // These are scaled to match the target density.
<add> private int mBitmapWidth;
<add> private int mBitmapHeight;
<add>
<add> private final Paint mPaint = new Paint(DEFAULT_PAINT_FLAGS);
<add>
<add> /**
<add> * Create drawable from a bitmap, setting initial target density based on the display metrics of
<add> * the resources.
<add> */
<add> public LightBitmapDrawable(Resources res, Bitmap bitmap) {
<add> mBitmap = bitmap;
<add> mTargetDensity = res.getDisplayMetrics().densityDpi;
<add> computeBitmapSize();
<add> }
<add>
<add> /**
<add> * Returns the paint used to render this drawable.
<add> */
<add> public final Paint getPaint() {
<add> return mPaint;
<add> }
<add>
<add> /**
<add> * Returns the bitmap used by this drawable to render. May be null.
<add> */
<add> @Nullable public final Bitmap getBitmap() {
<add> return mBitmap;
<add> }
<add>
<add> private void computeBitmapSize() {
<add> if (mBitmap != null) {
<add> mBitmapWidth = mBitmap.getScaledWidth(mTargetDensity);
<add> mBitmapHeight = mBitmap.getScaledHeight(mTargetDensity);
<add> } else {
<add> mBitmapWidth = mBitmapHeight = -1;
<add> }
<add> }
<add>
<add> public void setBitmap(Bitmap bitmap) {
<add> if (mBitmap != bitmap) {
<add> mBitmap = bitmap;
<add> computeBitmapSize();
<add> invalidateSelf();
<add> }
<add> }
<add>
<add> /**
<add> * Enables or disables anti-aliasing for this drawable. Anti-aliasing affects the edges of the
<add> * bitmap only so it applies only when the drawable is rotated.
<add> *
<add> * @param antiAlias True if the bitmap should be anti-aliased, false otherwise.
<add> * @see #hasAntiAlias()
<add> */
<add> public void setAntiAlias(boolean antiAlias) {
<add> mPaint.setAntiAlias(antiAlias);
<add> invalidateSelf();
<add> }
<add>
<add> /**
<add> * Indicates whether anti-aliasing is enabled for this drawable.
<add> *
<add> * @return True if anti-aliasing is enabled, false otherwise.
<add> * @see #setAntiAlias(boolean)
<add> */
<add> public boolean hasAntiAlias() {
<add> return mPaint.isAntiAlias();
<add> }
<add>
<add> @Override
<add> public void setFilterBitmap(boolean filter) {
<add> mPaint.setFilterBitmap(filter);
<add> invalidateSelf();
<add> }
<add>
<add> @Override
<add> public void setDither(boolean dither) {
<add> mPaint.setDither(dither);
<add> invalidateSelf();
<add> }
<add>
<add> @Override
<add> public void draw(Canvas canvas) {
<add> if (mBitmap == null) {
<add> return;
<add> }
<add> canvas.drawBitmap(mBitmap, null, getBounds(), mPaint);
<add> }
<add>
<add> @Override
<add> public void setAlpha(int alpha) {
<add> if (alpha != mPaint.getAlpha()) {
<add> mPaint.setAlpha(alpha);
<add> invalidateSelf();
<add> }
<add> }
<add>
<add> public int getAlpha() {
<add> return mPaint.getAlpha();
<add> }
<add>
<add> @Override
<add> public void setColorFilter(ColorFilter cf) {
<add> mPaint.setColorFilter(cf);
<add> invalidateSelf();
<add> }
<add>
<add> public ColorFilter getColorFilter() {
<add> return mPaint.getColorFilter();
<add> }
<add>
<add> @Override
<add> public int getIntrinsicWidth() {
<add> return mBitmapWidth;
<add> }
<add>
<add> @Override
<add> public int getIntrinsicHeight() {
<add> return mBitmapHeight;
<add> }
<add>
<add> @Override
<add> public int getOpacity() {
<add> return (mBitmap == null || mBitmap.hasAlpha() || mPaint.getAlpha() < 255) ?
<add> PixelFormat.TRANSLUCENT : PixelFormat.OPAQUE;
<add> }
<add>}
|
|
Java
|
apache-2.0
|
error: pathspec 'src/test/java/us/jts/fortress/rbac/apacheds/FortressJUnitApachedsTest.java' did not match any file(s) known to git
|
e85b6592a582efd3acee7916588bf08f644eb25d
| 1 |
PennState/directory-fortress-core-1,PennState/directory-fortress-core-1,PennState/directory-fortress-core-1
|
package us.jts.fortress.rbac.apacheds;
import org.apache.directory.server.annotations.CreateLdapServer;
import org.apache.directory.server.annotations.CreateTransport;
import org.apache.directory.server.core.annotations.ApplyLdifFiles;
import org.apache.directory.server.core.annotations.CreateDS;
import org.apache.directory.server.core.annotations.CreatePartition;
import org.apache.directory.server.core.integ.AbstractLdapTestUnit;
import org.apache.directory.server.core.integ.FrameworkRunner;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import us.jts.fortress.SecurityException;
import us.jts.fortress.rbac.AccessMgrImplTest;
import us.jts.fortress.rbac.AdminMgrImplTest;
import us.jts.fortress.rbac.AdminRoleTestData;
import us.jts.fortress.rbac.DelegatedMgrImplTest;
import us.jts.fortress.rbac.DelegatedMgrImplTest.ASSIGN_OP;
import us.jts.fortress.rbac.DelegatedMgrImplTest.GRANT_OP;
import us.jts.fortress.rbac.FortressJUnitTest;
import us.jts.fortress.rbac.OrgUnit;
import us.jts.fortress.rbac.OrgUnitTestData;
import us.jts.fortress.rbac.PRATestData;
import us.jts.fortress.rbac.PermTestData;
import us.jts.fortress.rbac.ReviewMgrImplTest;
import us.jts.fortress.rbac.RoleTestData;
import us.jts.fortress.rbac.Session;
import us.jts.fortress.rbac.TestUtils;
import us.jts.fortress.rbac.URATestData;
import us.jts.fortress.rbac.UserTestData;
import us.jts.fortress.util.cache.CacheMgr;
@RunWith(FrameworkRunner.class)
@CreateDS(name = "classDS", partitions =
{ @CreatePartition(name = "example", suffix = "dc=example,dc=com") })
@CreateLdapServer(
transports =
{
@CreateTransport(protocol = "LDAP", port = 10389)
})
@ApplyLdifFiles(
{ "fortress-schema.ldif", "init-ldap.ldif"/*, "test-data.ldif"*/})
public class FortressJUnitApachedsTest extends AbstractLdapTestUnit
{
private static final String CLS_NM = DelegatedMgrImplTest.class.getName();
final private static Logger log = Logger.getLogger( CLS_NM );
private static Session adminSess = null;
@Before
public void init()
{
CacheMgr.getInstance().clearAll();
}
/***********************************************************/
/* 2. Build Up */
/***********************************************************/
// DelegatedAdminMgrImplTest ARBAC Buildup APIs:
@Test
public void testAddAdminUser()
{
DelegatedMgrImplTest.addOrgUnit( "ADD ORG_PRM_APP0", OrgUnitTestData.ORGS_PRM_APP0[0] );
DelegatedMgrImplTest.addOrgUnit( "ADD ORG_USR_DEV0", OrgUnitTestData.ORGS_USR_DEV0[0] );
DelegatedMgrImplTest.addAdminRoles( "ADD-ARLS SUPER", AdminRoleTestData.AROLES_SUPER, false );
AdminMgrImplTest.addPermObjs( "ADD-OBS PSWDMGR_OBJ", PermTestData.PSWDMGR_OBJ, false, false );
AdminMgrImplTest.addPermObjs( "ADD-OBS ADMINMGR_OBJ", PermTestData.ADMINMGR_OBJ, false, false );
AdminMgrImplTest.addPermObjs( "ADD-OBS DELEGATEDMGR_OBJ", PermTestData.DELEGATEDMGR_OBJ, false, false );
AdminMgrImplTest.addPermObjs( "ADD-OBS DELEGATEDREVIEWMGR_OBJ", PermTestData.DELEGATEDREVIEWMGR_OBJ, false,
false );
AdminMgrImplTest.addPermObjs( "ADD-OBS REVIEWMGR_OBJ", PermTestData.REVIEWMGR_OBJ, false, false );
AdminMgrImplTest.addPermOps( "ADD-OPS PSWDMGR_OBJ PSWDMGR_OPS", PermTestData.PSWDMGR_OBJ,
PermTestData.PSWDMGR_OPS, false, false );
AdminMgrImplTest.addPermOps( "ADD-OPS ADMINMGR_OBJ ADMINMGR_OPS", PermTestData.ADMINMGR_OBJ,
PermTestData.ADMINMGR_OPS, false, false );
AdminMgrImplTest.addPermOps( "ADD-OPS DELEGATEDMGR_OBJ DELEGATEDMGR_OPS", PermTestData.DELEGATEDMGR_OBJ,
PermTestData.DELEGATEDMGR_OPS, false, false );
AdminMgrImplTest.addPermOps( "ADD-OPS DELEGATEDREVIEWMGR_OBJ DELEGATEDREVIEWMGR_OPS",
PermTestData.DELEGATEDREVIEWMGR_OBJ, PermTestData.DELEGATEDREVIEWMGR_OPS, false, false );
AdminMgrImplTest.addPermOps( "ADD-OPS REVIEWMGR_OBJ REVIEWMGR_OPS", PermTestData.REVIEWMGR_OBJ,
PermTestData.REVIEWMGR_OPS, false, false );
AdminMgrImplTest.addRoleGrants( "GRNT-APRMS SUPER PSWDMGR_OBJ PSWDMGR_OPS", AdminRoleTestData.AROLES_SUPER,
PermTestData.PSWDMGR_OBJ, PermTestData.PSWDMGR_OPS, false, false );
AdminMgrImplTest.addRoleGrants( "GRNT-APRMS SUPER ADMINMGR_OBJ ADMINMGR_OPS", AdminRoleTestData.AROLES_SUPER,
PermTestData.ADMINMGR_OBJ, PermTestData.ADMINMGR_OPS, false, false );
AdminMgrImplTest.addRoleGrants( "GRNT-APRMS SUPER DELEGATEDMGR_OBJ DELEGATEDMGR_OPS",
AdminRoleTestData.AROLES_SUPER, PermTestData.DELEGATEDMGR_OBJ, PermTestData.DELEGATEDMGR_OPS, false, false );
AdminMgrImplTest.addRoleGrants( "GRNT-APRMS SUPER DELEGATEDREVIEWMGR_OBJ DELEGATEDREVIEWMGR_OPS",
AdminRoleTestData.AROLES_SUPER, PermTestData.DELEGATEDREVIEWMGR_OBJ, PermTestData.DELEGATEDREVIEWMGR_OPS,
false, false );
AdminMgrImplTest.addRoleGrants( "GRNT-APRMS SUPER REVIEWMGR_OBJ REVIEWMGR_OPS", AdminRoleTestData.AROLES_SUPER,
PermTestData.REVIEWMGR_OBJ, PermTestData.REVIEWMGR_OPS, false, false );
AdminMgrImplTest.addUsers( "ADD-USRS TU0", UserTestData.USERS_TU0, false );
DelegatedMgrImplTest.assignAdminUsers( "ASGN-USRS TU0 SUPER", UserTestData.USERS_TU0,
AdminRoleTestData.AROLES_SUPER, false );
// do these last - may have already been added via demoUsers:
AdminMgrImplTest.addPermObjs( "ADD-OBS AUDITMGR_OBJ", PermTestData.AUDITMGR_OBJ, false, true );
AdminMgrImplTest.addPermOps( "ADD-OPS AUDITMGR_OBJ AUDITMGR_OPS", PermTestData.AUDITMGR_OBJ,
PermTestData.AUDITMGR_OPS, false, true );
AdminMgrImplTest.addRoleGrants( "GRNT-APRMS SUPER AUDITMGR_OBJ AUDITMGR_OPS", AdminRoleTestData.AROLES_SUPER,
PermTestData.AUDITMGR_OBJ, PermTestData.AUDITMGR_OPS, false, true );
}
@Test
public void testAddOrgUnit()
{
//addOrgUnits("ADD ORGS_USR_DEV0", OrgUnitTestData.ORGS_USR_DEV0);
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_TO1", OrgUnitTestData.ORGS_TO1 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO2", OrgUnitTestData.ORGS_USR_TO2 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_ORGS_PRM_TO3", OrgUnitTestData.ORGS_PRM_TO3 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO4", OrgUnitTestData.ORGS_PRM_TO4 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO5", OrgUnitTestData.ORGS_USR_TO5 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO5", OrgUnitTestData.ORGS_PRM_TO5 );
// The DEV1 OU is not removed during cleanup phase because the test system users belong to it:
if ( FortressJUnitTest.isFirstRun() )
{
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
}
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
}
@Test
public void testUpdateOrgUnit()
{
// Inject the needed data for the test
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_TO1", OrgUnitTestData.ORGS_TO1 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_ORGS_PRM_TO3", OrgUnitTestData.ORGS_PRM_TO3 );
// The test itself
DelegatedMgrImplTest.updateOrgUnits( "UPD ORGS_TO1", OrgUnitTestData.ORGS_TO1 );
DelegatedMgrImplTest.updateOrgUnits( "UPD ORGS_PRM_TO3", OrgUnitTestData.ORGS_PRM_TO3 );
}
@Test
public void testAddOrgInheritance()
{
// Inject the needed data for the test
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO2", OrgUnitTestData.ORGS_USR_TO2 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO4", OrgUnitTestData.ORGS_PRM_TO4 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO5", OrgUnitTestData.ORGS_USR_TO5 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO5", OrgUnitTestData.ORGS_PRM_TO5 );
// The test itself
DelegatedMgrImplTest.addInheritedOrgUnits( "ADD-INHERIT ORGS_USR_TO2", OrgUnitTestData.ORGS_USR_TO2 );
DelegatedMgrImplTest.addInheritedOrgUnits( "ADD-INHERIT ORGS_PRM_TO4", OrgUnitTestData.ORGS_PRM_TO4 );
DelegatedMgrImplTest.addInheritedOrgUnits( "ADD-INHERIT ORGS_USR_TO5", OrgUnitTestData.ORGS_USR_TO5 );
DelegatedMgrImplTest.addInheritedOrgUnits( "ADD-INHERIT ORGS_PRM_TO5", OrgUnitTestData.ORGS_PRM_TO5 );
}
@Test
public void testAddOrgUnitDescendant()
{
DelegatedMgrImplTest.addOrgUnitDescendant( "ADD ORGS-USR-TO6-DESC", OrgUnitTestData.ORGS_USR_TO6_DSC,
OrgUnit.Type.USER );
DelegatedMgrImplTest.addOrgUnitDescendant( "ADD ORGS-PRM-TO6-DESC", OrgUnitTestData.ORGS_PRM_TO6_DSC,
OrgUnit.Type.PERM );
}
@Test
public void testAddOrgUnitAscendants()
{
DelegatedMgrImplTest.addOrgUnitAscendant( "ADD-ORGS-USR-TR7-ASC", OrgUnitTestData.ORGS_USR_TO7_ASC,
OrgUnit.Type.USER );
DelegatedMgrImplTest.addOrgUnitAscendant( "ADD-ORGS-PRM-TR7-ASC", OrgUnitTestData.ORGS_PRM_TO7_ASC,
OrgUnit.Type.PERM );
}
@Test
public void testAddRole()
{
// Add the needed data for this test
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO2", OrgUnitTestData.ORGS_USR_TO2 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_TO1", OrgUnitTestData.ORGS_TO1 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_ORGS_PRM_TO3", OrgUnitTestData.ORGS_PRM_TO3 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO4", OrgUnitTestData.ORGS_PRM_TO4 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO5", OrgUnitTestData.ORGS_USR_TO5 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO5", OrgUnitTestData.ORGS_PRM_TO5 );
// The test itself
// public Role setRole(Role role)
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR14_ARBAC", RoleTestData.ROLES_TR14_ARBAC );
AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR14_ARBAC", RoleTestData.ROLES_TR14_ARBAC );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR1", AdminRoleTestData.AROLES_TR1, true );
DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR2", AdminRoleTestData.AROLES_TR2, true );
DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR3", AdminRoleTestData.AROLES_TR3, true );
DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR6", AdminRoleTestData.AROLES_TR6_HIER, true );
}
@Test
public void testUpdateAdminRole()
{
// Add the needed data for this test
DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR3", AdminRoleTestData.AROLES_TR3, true );
// The test itself
// public Role updateRole(Role role)
DelegatedMgrImplTest.updateAdminRoles( "UPD-ADMRLS TR3_UPD", AdminRoleTestData.AROLES_TR3_UPD, true );
}
@Test
public void testAddAdminRoleDescendant()
{
DelegatedMgrImplTest.addAdminRoleDescendant( "ADD-ARLS-TR5-DESC", AdminRoleTestData.AROLES_TR5_DSC );
}
@Test
public void testAddAdminRoleAscendants()
{
DelegatedMgrImplTest.addAdminRoleAscendant( "ADD-ARLS-TR4-ASC", AdminRoleTestData.AROLES_TR4_ASC );
}
@Test
public void testAddAdminRoleInheritance()
{
// Add the needed data for this test
DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR6", AdminRoleTestData.AROLES_TR6_HIER, true );
// The test itself
DelegatedMgrImplTest.addInheritedAdminRoles( "ADD-ARLS-TR6-HIER", AdminRoleTestData.AROLES_TR6_HIER );
}
@Test
public void testAddUser()
{
// Add the needed data for this test
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_TO1", OrgUnitTestData.ORGS_TO1 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO5", OrgUnitTestData.ORGS_USR_TO5 );
// The test itself
// public User addUser(User user)
// the admin user must be added before the "addUsers" can be called:
//AdminMgrImplTest.addAdminUser("ADD-USRS TU0", UserTestData.USERS_TU0[0]);
AdminMgrImplTest.addUsers( "ADD-USRS TU16_ARBAC", UserTestData.USERS_TU16_ARBAC, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU16B_ARBAC", UserTestData.USERS_TU16B_ARBAC, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU16A_ARBAC", UserTestData.USERS_TU17A_ARBAC, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU16U_ARBAC", UserTestData.USERS_TU17U_ARBAC, true );
}
@Test
public void testAddPermission()
{
// Add the needed data for this test
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO5", OrgUnitTestData.ORGS_PRM_TO5 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
// The test itself
// public Permission addPermObj(Permission pOp)
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB5", PermTestData.OBJS_TOB5, true, false );
AdminMgrImplTest.addPermObjs( "ADD-OBS ARBAC1", PermTestData.ARBAC_OBJS_1, true, false );
AdminMgrImplTest
.addPermOps( "ADD-OPS ARBAC1", PermTestData.ARBAC_OBJS_1, PermTestData.ARBAC_OPS_1, true, false );
AdminMgrImplTest.addPermObjs( "ADD-OBS ARBAC2", PermTestData.ARBAC_OBJ2, true, false );
AdminMgrImplTest.addPermOps( "ADD-OPS ARBAC2", PermTestData.ARBAC_OBJ2, PermTestData.ARBAC_OPS_2, true, false );
}
@Test
public void testAssignAdminUser()
{
// Add the needed data for this test
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO2", OrgUnitTestData.ORGS_USR_TO2 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_TO1", OrgUnitTestData.ORGS_TO1 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_ORGS_PRM_TO3", OrgUnitTestData.ORGS_PRM_TO3 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO4", OrgUnitTestData.ORGS_PRM_TO4 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO5", OrgUnitTestData.ORGS_USR_TO5 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO5", OrgUnitTestData.ORGS_PRM_TO5 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR14_ARBAC", RoleTestData.ROLES_TR14_ARBAC );
AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR14_ARBAC", RoleTestData.ROLES_TR14_ARBAC );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR1", AdminRoleTestData.AROLES_TR1, true );
DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR2", AdminRoleTestData.AROLES_TR2, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU16_ARBAC", UserTestData.USERS_TU16_ARBAC, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU16A_ARBAC", UserTestData.USERS_TU17A_ARBAC, true );
// The test itself
// public void assignUser(User user, Role role)
DelegatedMgrImplTest.assignAdminUsers( "ASGN-USRS TU16 TR1", UserTestData.USERS_TU16_ARBAC,
AdminRoleTestData.AROLES_TR1, true );
DelegatedMgrImplTest.assignAdminUserRole( "ASGN-USR TU17A TR2", UserTestData.USERS_TU17A_ARBAC,
AdminRoleTestData.AROLES_TR2, true );
}
@Test
public void testGrantPermissionRole()
{
// Add the needed data for this test
// From testAddUser
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_TO1", OrgUnitTestData.ORGS_TO1 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO5", OrgUnitTestData.ORGS_USR_TO5 );
AdminMgrImplTest.addUsers( "ADD-USRS TU16_ARBAC", UserTestData.USERS_TU16_ARBAC, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU16B_ARBAC", UserTestData.USERS_TU16B_ARBAC, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU16A_ARBAC", UserTestData.USERS_TU17A_ARBAC, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU16U_ARBAC", UserTestData.USERS_TU17U_ARBAC, true );
// From testAddPermission
// Add the needed data for this test
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO5", OrgUnitTestData.ORGS_PRM_TO5 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
// public Permission addPermObj(Permission pOp)
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB5", PermTestData.OBJS_TOB5, true, false );
AdminMgrImplTest.addPermObjs( "ADD-OBS ARBAC1", PermTestData.ARBAC_OBJS_1, true, false );
AdminMgrImplTest
.addPermOps( "ADD-OPS ARBAC1", PermTestData.ARBAC_OBJS_1, PermTestData.ARBAC_OPS_1, true, false );
AdminMgrImplTest.addPermObjs( "ADD-OBS ARBAC2", PermTestData.ARBAC_OBJ2, true, false );
AdminMgrImplTest.addPermOps( "ADD-OPS ARBAC2", PermTestData.ARBAC_OBJ2, PermTestData.ARBAC_OPS_2, true, false );
// From testAssignAdminUser
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO2", OrgUnitTestData.ORGS_USR_TO2 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_ORGS_PRM_TO3", OrgUnitTestData.ORGS_PRM_TO3 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO4", OrgUnitTestData.ORGS_PRM_TO4 );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR14_ARBAC", RoleTestData.ROLES_TR14_ARBAC );
AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR14_ARBAC", RoleTestData.ROLES_TR14_ARBAC );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR1", AdminRoleTestData.AROLES_TR1, true );
DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR2", AdminRoleTestData.AROLES_TR2, true );
// The test itself
// public void grantPermission(Permission pOp, Role role)
AdminMgrImplTest.addRoleGrants( "GRNT-APRMS ARTR2 AROBJ1 AROPS1", AdminRoleTestData.AROLES_TR2,
PermTestData.ARBAC_OBJS_1, PermTestData.ARBAC_OPS_1, true, false );
}
// AdminMgr RBAC APIs:
@Test
public void testAdminMgrAddRole()
{
// public Role addRole(Role role)
AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
AdminMgrImplTest.addRoles( "ADD-RLS TR4", RoleTestData.ROLES_TR4 );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR5_HIER", RoleTestData.ROLES_TR5_HIER );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR5B", RoleTestData.ROLES_TR5B );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR8_SSD", RoleTestData.ROLES_TR8_SSD );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR9_SSD", RoleTestData.ROLES_TR9_SSD );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR10_SSD", RoleTestData.ROLES_TR10_SSD );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR8_DSD", RoleTestData.ROLES_TR8_DSD );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR9_DSD", RoleTestData.ROLES_TR9_DSD );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR10_DSD", RoleTestData.ROLES_TR10_DSD );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR16_SD", RoleTestData.ROLES_TR16_SD );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR17_DSD_BRUNO", RoleTestData.ROLES_TR17_DSD_BRUNO );
}
@Test
public void testAdminMgrAddRoleInheritance()
{
// Add the needed data for this test
AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
AdminMgrImplTest.addRoles( "ADD-RLS TR4", RoleTestData.ROLES_TR4 );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR5_HIER", RoleTestData.ROLES_TR5_HIER );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR5B", RoleTestData.ROLES_TR5B );
// The test itself
//TODO: Test goes here...
// public void addInheritance(Role parentRole, Role childRole)
AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR5_HIER", RoleTestData.ROLES_TR5_HIER );
AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR5B", RoleTestData.ROLES_TR5B );
}
@Test
public void testAdminMgrddRoleDescendant()
{
//TODO: Test goes here...
// public void addDescendant(Role parentRole, Role childRole)
AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR6-DESC", RoleTestData.ROLES_TR6_DESC );
AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR11-DESC-SSD", RoleTestData.ROLES_TR11_DESC_SSD );
AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR12-DESC-SSD", RoleTestData.ROLES_TR12_DESC_SSD );
AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR13-DESC-SSD", RoleTestData.ROLES_TR13_DESC_SSD );
AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR11-DESC-DSD", RoleTestData.ROLES_TR11_DESC_DSD );
AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR12-DESC-DSD", RoleTestData.ROLES_TR12_DESC_DSD );
AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR13-DESC-DSD", RoleTestData.ROLES_TR13_DESC_DSD );
}
@Test
public void testAdminMgrAddRoleAscendants()
{
//TODO: Test goes here...
// public void addDescendant(Role parentRole, Role childRole)
AdminMgrImplTest.addRoleAscendant( "ADD-RLS-TR7-ASC", RoleTestData.ROLES_TR7_ASC );
}
@Test
public void testAdminMgrCreateSsdSet()
{
// Add the needed data for this test
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR8_SSD", RoleTestData.ROLES_TR8_SSD );
AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR11-DESC-SSD", RoleTestData.ROLES_TR11_DESC_SSD );
AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR12-DESC-SSD", RoleTestData.ROLES_TR12_DESC_SSD );
AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR13-DESC-SSD", RoleTestData.ROLES_TR13_DESC_SSD );
// The test itself
// public SDSet createSsdSet(SDSet ssdSet)
AdminMgrImplTest.createSsdSet( "ADD-SSD T1", RoleTestData.SSD_T1 );
AdminMgrImplTest.createSsdSet( "ADD-SSD T4", RoleTestData.SSD_T4 );
AdminMgrImplTest.createSsdSet( "ADD-SSD T5", RoleTestData.SSD_T5 );
AdminMgrImplTest.createSsdSet( "ADD-SSD T6", RoleTestData.SSD_T6 );
}
@Test
public void testAdminMgrCreateDsdSet()
{
// Add the needed data for this test
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR8_DSD", RoleTestData.ROLES_TR8_DSD );
AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR11-DESC-DSD", RoleTestData.ROLES_TR11_DESC_DSD );
AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR12-DESC-DSD", RoleTestData.ROLES_TR12_DESC_DSD );
AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR13-DESC-DSD", RoleTestData.ROLES_TR13_DESC_DSD );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR17_DSD_BRUNO", RoleTestData.ROLES_TR17_DSD_BRUNO );
// The test itself
// public SDSet createDsdSet(SDSet dsdSet)
AdminMgrImplTest.createDsdSet( "ADD-DSD T1", RoleTestData.DSD_T1 );
AdminMgrImplTest.createDsdSet( "ADD-DSD T4", RoleTestData.DSD_T4 );
AdminMgrImplTest.createDsdSet( "ADD-DSD T5", RoleTestData.DSD_T5 );
AdminMgrImplTest.createDsdSet( "ADD-DSD T6", RoleTestData.DSD_T6 );
AdminMgrImplTest.createDsdSet( "ADD-DSD T8 BRUNO", RoleTestData.DSD_T8_BRUNO );
}
@Test
public void testAdminMgrAddSsdRoleMember()
{
// Add the needed data for this test
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR9_SSD", RoleTestData.ROLES_TR9_SSD );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR10_SSD", RoleTestData.ROLES_TR10_SSD );
// The test itself
// public SDSet addSsdRoleMember(SDSet ssdSet, Role role)
AdminMgrImplTest.addSsdRoleMember( "ADD-MEM-SSD T2 TR9", RoleTestData.SSD_T2, RoleTestData.ROLES_TR9_SSD );
AdminMgrImplTest.addSsdRoleMember( "ADD-MEM-SSD T3 TR10", RoleTestData.SSD_T3, RoleTestData.ROLES_TR10_SSD );
}
@Test
public void testAdminMgrAddDsdRoleMember()
{
// Add the needed data for this test
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR9_DSD", RoleTestData.ROLES_TR9_DSD );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR10_DSD", RoleTestData.ROLES_TR10_DSD );
// The test itself
// public SDSet addDsdRoleMember(SDSet dsdSet, Role role)
AdminMgrImplTest.addDsdRoleMember( "ADD-MEM-DSD T2 TR9", RoleTestData.DSD_T2, RoleTestData.ROLES_TR9_DSD );
AdminMgrImplTest.addDsdRoleMember( "ADD-MEM-DSD T3 TR10", RoleTestData.DSD_T3, RoleTestData.ROLES_TR10_DSD );
}
@Test
public void testAdminMgrSsdCardinality()
{
// Add the needed data for this test
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR16_SD", RoleTestData.ROLES_TR16_SD );
// The test itself
AdminMgrImplTest.setSsdCardinality( "CARD-SSD T7 TR16", RoleTestData.SSD_T7, RoleTestData.ROLES_TR16_SD );
}
@Test
public void testAdminMgrDsdCardinality()
{
// Add the needed data for this test
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR16_SD", RoleTestData.ROLES_TR16_SD );
// The test itself
AdminMgrImplTest.setDsdCardinality( "CARD-DSD T7 TR16", RoleTestData.DSD_T7, RoleTestData.ROLES_TR16_SD );
}
@Test
public void testAdminMgrUpdateRole()
{
// Add the needed data for this test
AdminMgrImplTest.addRoles( "ADD-RLS TR4", RoleTestData.ROLES_TR4 );
// The test itself
// public Role updateRole(Role role)
AdminMgrImplTest.updateRoles( "UPD-RLS TR4_UPD", RoleTestData.ROLES_TR4_UPD );
}
@Test
public void testAdminMgrAddUser()
{
// Add the needed data for this test
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR6-DESC", RoleTestData.ROLES_TR6_DESC );
AdminMgrImplTest.addRoleAscendant( "ADD-RLS-TR7-ASC", RoleTestData.ROLES_TR7_ASC );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR17_DSD_BRUNO", RoleTestData.ROLES_TR17_DSD_BRUNO );
// The test itself
// public User addUser(User user)
AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU2", UserTestData.USERS_TU2, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU5", UserTestData.USERS_TU5, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU6", UserTestData.USERS_TU6, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU7_HIER", UserTestData.USERS_TU7_HIER, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU8_SSD", UserTestData.USERS_TU8_SSD, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU9_SSD_HIER", UserTestData.USERS_TU9_SSD_HIER, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU10_SSD_HIER", UserTestData.USERS_TU10_SSD_HIER, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU11_SSD_HIER", UserTestData.USERS_TU11_SSD_HIER, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU12_DSD", UserTestData.USERS_TU12_DSD, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU13_DSD_HIER", UserTestData.USERS_TU13_DSD_HIER, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU14_DSD_HIER", UserTestData.USERS_TU14_DSD_HIER, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU15_DSD_HIER", UserTestData.USERS_TU15_DSD_HIER, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU18 TR6_DESC", UserTestData.USERS_TU18U_TR6_DESC, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU19 TR7_ASC", UserTestData.USERS_TU19U_TR7_ASC, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU20 TR5_HIER", UserTestData.USERS_TU20U_TR5B, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU21 DSD_BRUNO", UserTestData.USERS_TU21_DSD_BRUNO, true );
}
@Test
public void testAdminMgrUpdateUser()
{
// Add the needed data for this test
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
// The test itself
// public User updateUser(User user)
AdminMgrImplTest.updateUsers( "UPD USERS TU1_UPD", UserTestData.USERS_TU1_UPD );
}
@Test
public void testAdminMgrAssignUser()
{
// Add the needed data for this test
// From testAddOrgUnit
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_TO1", OrgUnitTestData.ORGS_TO1 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO2", OrgUnitTestData.ORGS_USR_TO2 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_ORGS_PRM_TO3", OrgUnitTestData.ORGS_PRM_TO3 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO4", OrgUnitTestData.ORGS_PRM_TO4 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO5", OrgUnitTestData.ORGS_USR_TO5 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO5", OrgUnitTestData.ORGS_PRM_TO5 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
// From testAddRole Delegated
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR14_ARBAC", RoleTestData.ROLES_TR14_ARBAC );
AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR14_ARBAC", RoleTestData.ROLES_TR14_ARBAC );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR1", AdminRoleTestData.AROLES_TR1, true );
DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR2", AdminRoleTestData.AROLES_TR2, true );
DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR3", AdminRoleTestData.AROLES_TR3, true );
DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR6", AdminRoleTestData.AROLES_TR6_HIER, true );
// From testAddUser
AdminMgrImplTest.addUsers( "ADD-USRS TU16_ARBAC", UserTestData.USERS_TU16_ARBAC, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU16B_ARBAC", UserTestData.USERS_TU16B_ARBAC, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU16A_ARBAC", UserTestData.USERS_TU17A_ARBAC, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU16U_ARBAC", UserTestData.USERS_TU17U_ARBAC, true );
// From testAddRole Admin
AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
AdminMgrImplTest.addRoles( "ADD-RLS TR4", RoleTestData.ROLES_TR4 );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR5_HIER", RoleTestData.ROLES_TR5_HIER );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR5B", RoleTestData.ROLES_TR5B );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR8_SSD", RoleTestData.ROLES_TR8_SSD );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR9_SSD", RoleTestData.ROLES_TR9_SSD );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR10_SSD", RoleTestData.ROLES_TR10_SSD );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR8_DSD", RoleTestData.ROLES_TR8_DSD );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR9_DSD", RoleTestData.ROLES_TR9_DSD );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR10_DSD", RoleTestData.ROLES_TR10_DSD );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR16_SD", RoleTestData.ROLES_TR16_SD );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR17_DSD_BRUNO", RoleTestData.ROLES_TR17_DSD_BRUNO );
// From testAddRoleDescendant
AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR6-DESC", RoleTestData.ROLES_TR6_DESC );
AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR11-DESC-SSD", RoleTestData.ROLES_TR11_DESC_SSD );
AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR12-DESC-SSD", RoleTestData.ROLES_TR12_DESC_SSD );
AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR13-DESC-SSD", RoleTestData.ROLES_TR13_DESC_SSD );
AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR11-DESC-DSD", RoleTestData.ROLES_TR11_DESC_DSD );
AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR12-DESC-DSD", RoleTestData.ROLES_TR12_DESC_DSD );
AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR13-DESC-DSD", RoleTestData.ROLES_TR13_DESC_DSD );
// From testCreateSsdSet
AdminMgrImplTest.createSsdSet( "ADD-SSD T1", RoleTestData.SSD_T1 );
AdminMgrImplTest.createSsdSet( "ADD-SSD T4", RoleTestData.SSD_T4 );
AdminMgrImplTest.createSsdSet( "ADD-SSD T5", RoleTestData.SSD_T5 );
AdminMgrImplTest.createSsdSet( "ADD-SSD T6", RoleTestData.SSD_T6 );
// From testAddUser (Admin)
AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU2", UserTestData.USERS_TU2, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU7_HIER", UserTestData.USERS_TU7_HIER, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU8_SSD", UserTestData.USERS_TU8_SSD, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU9_SSD_HIER", UserTestData.USERS_TU9_SSD_HIER, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU10_SSD_HIER", UserTestData.USERS_TU10_SSD_HIER, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU11_SSD_HIER", UserTestData.USERS_TU11_SSD_HIER, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU12_DSD", UserTestData.USERS_TU12_DSD, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU13_DSD_HIER", UserTestData.USERS_TU13_DSD_HIER, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU14_DSD_HIER", UserTestData.USERS_TU14_DSD_HIER, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU15_DSD_HIER", UserTestData.USERS_TU15_DSD_HIER, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU20 TR5_HIER", UserTestData.USERS_TU20U_TR5B, true );
// The test itself
// public void assignUser(User user, Role role)
AdminMgrImplTest.assignUsers( "ASGN-USRS TU1 TR1", UserTestData.USERS_TU1, RoleTestData.ROLES_TR1, false );
AdminMgrImplTest.assignUsers( "ASGN-USRS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2, true );
AdminMgrImplTest.assignUsers( "ASGN-USRS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3, true );
AdminMgrImplTest.assignUsersH( "ASGN-USRS_H TU7 HIER TR5 HIER", UserTestData.USERS_TU7_HIER,
RoleTestData.ROLES_TR5_HIER, true );
AdminMgrImplTest.assignUsersH( "ASGN-USRS_H TU20 TR5B HIER", UserTestData.USERS_TU20U_TR5B,
RoleTestData.ROLES_TR5B, true );
AdminMgrImplTest.assignUsersSSD( "ASGN-USRS_SSDT1 TU8 SSD_T1", UserTestData.USERS_TU8_SSD, RoleTestData.SSD_T1 );
AdminMgrImplTest.assignUsersSSD( "ASGN-USRS_SSDT4B TU9 SSD_T4_B", UserTestData.USERS_TU9_SSD_HIER,
RoleTestData.SSD_T4_B );
AdminMgrImplTest.assignUsersSSD( "ASGN-USRS_SSDT5B TU10 SSD_T5_B", UserTestData.USERS_TU10_SSD_HIER,
RoleTestData.SSD_T5_B );
AdminMgrImplTest.assignUsersSSD( "ASGN-USRS_SSDT6B TU11 SSD_T6_B", UserTestData.USERS_TU11_SSD_HIER,
RoleTestData.SSD_T6_B );
AdminMgrImplTest.assignUsersDSD( "ASGN-USRS_DSDT1 TU8 DSD_T1", UserTestData.USERS_TU8_SSD, RoleTestData.DSD_T1 );
AdminMgrImplTest.assignUsersDSD( "ASGN-USRS_DSDT4B TU9 DSD_T4_B", UserTestData.USERS_TU9_SSD_HIER,
RoleTestData.DSD_T4_B );
AdminMgrImplTest.assignUsersDSD( "ASGN-USRS_DSDT5B TU10 DSD_T5_B", UserTestData.USERS_TU10_SSD_HIER,
RoleTestData.DSD_T5_B );
AdminMgrImplTest.assignUsersDSD( "ASGN-USRS_DSDT6B TU11 DSD_T6_B", UserTestData.USERS_TU11_SSD_HIER,
RoleTestData.DSD_T6_B );
AdminMgrImplTest.assignUsersDSD( "ASGN-USRS_DSDT1 TU12 DSD_T1", UserTestData.USERS_TU12_DSD,
RoleTestData.DSD_T1 );
AdminMgrImplTest.assignUsersDSD( "ASGN-USRS_DSDT4B TU13 DSD_T4_B", UserTestData.USERS_TU13_DSD_HIER,
RoleTestData.DSD_T4_B );
AdminMgrImplTest.assignUsersDSD( "ASGN-USRS_DSDT5B TU14 DSD_T5_B", UserTestData.USERS_TU14_DSD_HIER,
RoleTestData.DSD_T5_B );
AdminMgrImplTest.assignUsersDSD( "ASGN-USRS_DSDT6B TU15 DSD_T6_B", UserTestData.USERS_TU15_DSD_HIER,
RoleTestData.DSD_T6_B );
}
@Test
public void testAdminMgrAddPermissionObj() throws SecurityException
{
// Add the needed data for this test
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
// The test itself
// public Permission addPermObj(Permission pOp)
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB1", PermTestData.OBJS_TOB1, true, false );
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB2", PermTestData.OBJS_TOB2, true, false );
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB3", PermTestData.OBJS_TOB3, true, false );
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB4", PermTestData.OBJS_TOB4, true, false );
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB6", PermTestData.OBJS_TOB6, true, false );
}
@Test
public void testAdminMgrUpdatePermissionObj() throws SecurityException
{
// Add the needed data for this test
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB4", PermTestData.OBJS_TOB4, true, false );
// The test itself
AdminMgrImplTest.updatePermObjs( "UPD-OBS TOB4_UPD", PermTestData.OBJS_TOB4_UPD, true );
}
@Test
public void testAdminMgrAddPermissionOp()
{
// Add the needed data for this test
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB1", PermTestData.OBJS_TOB1, true, false );
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB2", PermTestData.OBJS_TOB2, true, false );
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB3", PermTestData.OBJS_TOB3, true, false );
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB4", PermTestData.OBJS_TOB4, true, false );
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB6", PermTestData.OBJS_TOB6, true, false );
// The test itself
// public PermObj addPermObj(PermObj pObj)
AdminMgrImplTest.addPermOps( "ADD-OPS TOB1 TOP1", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1, true, false );
AdminMgrImplTest.addPermOps( "ADD-OPS TOB2 TOP2", PermTestData.OBJS_TOB2, PermTestData.OPS_TOP2, true, false );
AdminMgrImplTest.addPermOps( "ADD-OPS TOB3 TOP3", PermTestData.OBJS_TOB3, PermTestData.OPS_TOP3, true, false );
AdminMgrImplTest.addPermOps( "ADD-OPS TOB4 TOP4", PermTestData.OBJS_TOB4, PermTestData.OPS_TOP4, true, false );
AdminMgrImplTest.addPermOps( "ADD-OPS TOB6 TOP5", PermTestData.OBJS_TOB6, PermTestData.OPS_TOP5, true, false );
}
@Test
public void testAdminMgrUpdatePermissionOp()
{
// Add the needed data for this test
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB1", PermTestData.OBJS_TOB1, true, false );
AdminMgrImplTest.addPermOps( "ADD-OPS TOB1 TOP1", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1, true, false );
// The test itself
AdminMgrImplTest.updatePermOps( "UPD-OPS TOB1 TOP1_UPD", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1_UPD,
true );
}
/**
* AMT24
*
* @throws SecurityException
*/
@Test
public void testAdminMgrGrantPermissionRole()
{
// Add the needed data for this test
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB1", PermTestData.OBJS_TOB1, true, false );
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB2", PermTestData.OBJS_TOB2, true, false );
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB3", PermTestData.OBJS_TOB3, true, false );
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB4", PermTestData.OBJS_TOB4, true, false );
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB6", PermTestData.OBJS_TOB6, true, false );
AdminMgrImplTest.addPermOps( "ADD-OPS TOB1 TOP1", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1, true, false );
AdminMgrImplTest.addPermOps( "ADD-OPS TOB2 TOP2", PermTestData.OBJS_TOB2, PermTestData.OPS_TOP2, true, false );
AdminMgrImplTest.addPermOps( "ADD-OPS TOB3 TOP3", PermTestData.OBJS_TOB3, PermTestData.OPS_TOP3, true, false );
AdminMgrImplTest.addPermOps( "ADD-OPS TOB4 TOP4", PermTestData.OBJS_TOB4, PermTestData.OPS_TOP4, true, false );
AdminMgrImplTest.addPermOps( "ADD-OPS TOB6 TOP5", PermTestData.OBJS_TOB6, PermTestData.OPS_TOP5, true, false );
AdminMgrImplTest.updatePermOps( "UPD-OPS TOB1 TOP1_UPD", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1_UPD,
true );
AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR5_HIER", RoleTestData.ROLES_TR5_HIER );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR5B", RoleTestData.ROLES_TR5B );
AdminMgrImplTest.addUsers( "ADD-USRS TU20 TR5_HIER", UserTestData.USERS_TU20U_TR5B, true );
// The test itself
// public void grantPermission(Permission pOp, Role role)
AdminMgrImplTest.addRoleGrants( "GRNT-PRMS TR1 TOB1 TOP1", RoleTestData.ROLES_TR1, PermTestData.OBJS_TOB1,
PermTestData.OPS_TOP1, true, false );
AdminMgrImplTest.addRoleGrants( "GRNT-PRMS TR2 TOB2 TOP2", RoleTestData.ROLES_TR2, PermTestData.OBJS_TOB2,
PermTestData.OPS_TOP2, true, false );
AdminMgrImplTest.addRoleGrants( "GRNT-PRMS TR3 TOB3 TOP3", RoleTestData.ROLES_TR3, PermTestData.OBJS_TOB3,
PermTestData.OPS_TOP3, true, false );
AdminMgrImplTest.addRoleGrantsH( "GRNT-PRMS_H ROLES_TR5_HIER TOB4 TOP4", RoleTestData.ROLES_TR5_HIER,
PermTestData.OBJS_TOB4,
PermTestData.OPS_TOP4 );
AdminMgrImplTest.addRoleGrantsHB( "GRNT-PRMS_HB USERS TU20 ROLES_TR5B TOB6 TOP5",
UserTestData.USERS_TU20U_TR5B,
RoleTestData.ROLES_TR5B, PermTestData.OBJS_TOB6, PermTestData.OPS_TOP5 );
}
@Test
public void testAdminMgrGrantPermissionUser()
{
// Add the needed data for this test
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB1", PermTestData.OBJS_TOB1, true, false );
AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
AdminMgrImplTest.addPermOps( "ADD-OPS TOB1 TOP1", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1, true, false );
// The test itself
// public void grantPermission(Permission pOp, User user)
AdminMgrImplTest.addUserGrants( "GRNT-PRMS TU1 TOB1 TOP1", UserTestData.USERS_TU1, PermTestData.OBJS_TOB1,
PermTestData.OPS_TOP1 );
}
/***********************************************************/
/* 3. Interrogation */
/***********************************************************/
// DelReviewMgr ARBAC:
@Test
public void testReadOrgUnit()
{
// Add the needed data for this test
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_TO1", OrgUnitTestData.ORGS_TO1 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_ORGS_PRM_TO3", OrgUnitTestData.ORGS_PRM_TO3 );
// The test itself
// public Role readRole(Role role)
DelegatedMgrImplTest.readOrgUnits( "RD ORGS_TO1", OrgUnitTestData.ORGS_TO1 );
DelegatedMgrImplTest.readOrgUnits( "RD ORGS_PRM_TO3", OrgUnitTestData.ORGS_PRM_TO3 );
}
@Test
public void testSearchOrgUnits()
{
// Add the needed data for this test
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_TO1", OrgUnitTestData.ORGS_TO1 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_ORGS_PRM_TO3", OrgUnitTestData.ORGS_PRM_TO3 );
// The test itself
DelegatedMgrImplTest.searchOrgUnits( "SRCH ORGS_TO1",
TestUtils.getSrchValue( OrgUnitTestData.getName( OrgUnitTestData.ORGS_TO1[0] ) ), OrgUnitTestData.ORGS_TO1 );
DelegatedMgrImplTest.searchOrgUnits( "SRCH ORGS_PRM_TO3",
TestUtils.getSrchValue( OrgUnitTestData.getName( OrgUnitTestData.ORGS_PRM_TO3[0] ) ),
OrgUnitTestData.ORGS_PRM_TO3 );
}
@Test
public void testReadAdminRole()
{
// Add the needed data for this test
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO2", OrgUnitTestData.ORGS_USR_TO2 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_TO1", OrgUnitTestData.ORGS_TO1 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_ORGS_PRM_TO3", OrgUnitTestData.ORGS_PRM_TO3 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO4", OrgUnitTestData.ORGS_PRM_TO4 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO5", OrgUnitTestData.ORGS_USR_TO5 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO5", OrgUnitTestData.ORGS_PRM_TO5 );
// public Role setRole(Role role)
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR14_ARBAC", RoleTestData.ROLES_TR14_ARBAC );
AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR14_ARBAC", RoleTestData.ROLES_TR14_ARBAC );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR1", AdminRoleTestData.AROLES_TR1, true );
DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR2", AdminRoleTestData.AROLES_TR2, true );
DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR3", AdminRoleTestData.AROLES_TR3, true );
DelegatedMgrImplTest.updateAdminRoles( "UPD-ADMRLS TR3_UPD", AdminRoleTestData.AROLES_TR3_UPD, true );
// The test itself
// public Role readRole(Role role)
DelegatedMgrImplTest.readAdminRoles( "RD-ADMRLS TR1", AdminRoleTestData.AROLES_TR1 );
DelegatedMgrImplTest.readAdminRoles( "RD-ADMRLS TR2", AdminRoleTestData.AROLES_TR2 );
DelegatedMgrImplTest.readAdminRoles( "RD-ADMRLS TR3_UPD", AdminRoleTestData.AROLES_TR3_UPD );
}
@Test
public void testSearchAdminRole()
{
// Add the needed data for this test
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO2", OrgUnitTestData.ORGS_USR_TO2 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_TO1", OrgUnitTestData.ORGS_TO1 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_ORGS_PRM_TO3", OrgUnitTestData.ORGS_PRM_TO3 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO4", OrgUnitTestData.ORGS_PRM_TO4 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO5", OrgUnitTestData.ORGS_USR_TO5 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO5", OrgUnitTestData.ORGS_PRM_TO5 );
// public Role setRole(Role role)
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR14_ARBAC", RoleTestData.ROLES_TR14_ARBAC );
AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR14_ARBAC", RoleTestData.ROLES_TR14_ARBAC );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR1", AdminRoleTestData.AROLES_TR1, true );
DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR2", AdminRoleTestData.AROLES_TR2, true );
DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR3", AdminRoleTestData.AROLES_TR3, true );
DelegatedMgrImplTest.updateAdminRoles( "UPD-ADMRLS TR3_UPD", AdminRoleTestData.AROLES_TR3_UPD, true );
// The test itself
DelegatedMgrImplTest.searchAdminRoles( "SRCH-ADMRLS TR1",
TestUtils.getSrchValue( RoleTestData.getName( AdminRoleTestData.AROLES_TR1[0] ) ),
AdminRoleTestData.AROLES_TR1 );
DelegatedMgrImplTest.searchAdminRoles( "SRCH-ADMRLS TR2",
TestUtils.getSrchValue( RoleTestData.getName( AdminRoleTestData.AROLES_TR2[0] ) ),
AdminRoleTestData.AROLES_TR2 );
DelegatedMgrImplTest.searchAdminRoles( "SRCH-ADMRLS TR3",
TestUtils.getSrchValue( RoleTestData.getName( AdminRoleTestData.AROLES_TR3_UPD[0] ) ),
AdminRoleTestData.AROLES_TR3_UPD );
}
// ReviewMgr RBAC:
@Test
public void testReadRole()
{
// Add the needed data for this test
AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
AdminMgrImplTest.addRoles( "ADD-RLS TR4", RoleTestData.ROLES_TR4 );
AdminMgrImplTest.updateRoles( "UPD-RLS TR4_UPD", RoleTestData.ROLES_TR4_UPD );
// The test itself
// public Role readRole(Role role)
ReviewMgrImplTest.readRoles( "RD-RLS TR1", RoleTestData.ROLES_TR1 );
ReviewMgrImplTest.readRoles( "RD-RLS TR2", RoleTestData.ROLES_TR2 );
ReviewMgrImplTest.readRoles( "RD-RLS TR3", RoleTestData.ROLES_TR3 );
ReviewMgrImplTest.readRoles( "RD-RLS TR4_UPD", RoleTestData.ROLES_TR4_UPD );
}
/**
* RMT06
*
* @throws us.jts.fortress.SecurityException
*/
@Test
public void testFindRoles()
{
// Add the needed data for this test
AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
AdminMgrImplTest.addRoles( "ADD-RLS TR4", RoleTestData.ROLES_TR4 );
AdminMgrImplTest.updateRoles( "UPD-RLS TR4_UPD", RoleTestData.ROLES_TR4_UPD );
// The test itself
// public List<Role> findRoles(String searchVal)
ReviewMgrImplTest.searchRoles( "SRCH-RLS TR1",
TestUtils.getSrchValue( RoleTestData.getName( RoleTestData.ROLES_TR1[0] ) ),
RoleTestData.ROLES_TR1 );
ReviewMgrImplTest.searchRoles( "SRCH-RLS TR2",
TestUtils.getSrchValue( RoleTestData.getName( RoleTestData.ROLES_TR2[0] ) ),
RoleTestData.ROLES_TR2 );
ReviewMgrImplTest.searchRoles( "SRCH-RLS TR3",
TestUtils.getSrchValue( RoleTestData.getName( RoleTestData.ROLES_TR3[0] ) ),
RoleTestData.ROLES_TR3 );
ReviewMgrImplTest.searchRoles( "SRCH-RLS TR4_UPD",
TestUtils.getSrchValue( RoleTestData.getName( RoleTestData.ROLES_TR4[0] ) ),
RoleTestData.ROLES_TR4_UPD );
}
@Test
public void testFindRoleNms()
{
// Add the needed data for this test
AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
AdminMgrImplTest.addRoles( "ADD-RLS TR4", RoleTestData.ROLES_TR4 );
AdminMgrImplTest.updateRoles( "UPD-RLS TR4_UPD", RoleTestData.ROLES_TR4_UPD );
// The test itself
// public List<String> findRoles(String searchVal, int limit)
ReviewMgrImplTest.searchRolesNms( "SRCH-RLNMS TR1",
TestUtils.getSrchValue( RoleTestData.getName( RoleTestData.ROLES_TR1[0] ) ),
RoleTestData.ROLES_TR1 );
ReviewMgrImplTest.searchRolesNms( "SRCH-RLNMS TR2",
TestUtils.getSrchValue( RoleTestData.getName( RoleTestData.ROLES_TR2[0] ) ),
RoleTestData.ROLES_TR2 );
ReviewMgrImplTest.searchRolesNms( "SRCH-RLNMS TR3",
TestUtils.getSrchValue( RoleTestData.getName( RoleTestData.ROLES_TR3[0] ) ),
RoleTestData.ROLES_TR3 );
ReviewMgrImplTest.searchRolesNms( "SRCH-RLNMS TR4_UPD",
TestUtils.getSrchValue( RoleTestData.getName( RoleTestData.ROLES_TR4[0] ) ), RoleTestData.ROLES_TR4_UPD );
}
@Test
public void testReadUser()
{
// Add the needed data for this test
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
AdminMgrImplTest.updateUsers( "UPD USERS TU1_UPD", UserTestData.USERS_TU1_UPD );
AdminMgrImplTest.addUsers( "ADD-USRS TU2", UserTestData.USERS_TU2, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU5", UserTestData.USERS_TU5, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU8_SSD", UserTestData.USERS_TU8_SSD, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU9_SSD_HIER", UserTestData.USERS_TU9_SSD_HIER, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU10_SSD_HIER", UserTestData.USERS_TU10_SSD_HIER, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU11_SSD_HIER", UserTestData.USERS_TU11_SSD_HIER, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU12_DSD", UserTestData.USERS_TU12_DSD, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU13_DSD_HIER", UserTestData.USERS_TU13_DSD_HIER, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU14_DSD_HIER", UserTestData.USERS_TU14_DSD_HIER, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU15_DSD_HIER", UserTestData.USERS_TU15_DSD_HIER, true );
// The test itself
// public User readUser(User user)
ReviewMgrImplTest.readUsers( "READ-USRS TU1_UPD", UserTestData.USERS_TU1_UPD );
ReviewMgrImplTest.readUsers( "READ-USRS TU3", UserTestData.USERS_TU3 );
ReviewMgrImplTest.readUsers( "READ-USRS TU4", UserTestData.USERS_TU4 );
ReviewMgrImplTest.readUsers( "READ-USRS TU5", UserTestData.USERS_TU5 );
ReviewMgrImplTest.readUsers( "READ-USRS TU8", UserTestData.USERS_TU8_SSD );
ReviewMgrImplTest.readUsers( "READ-USRS TU9", UserTestData.USERS_TU9_SSD_HIER );
ReviewMgrImplTest.readUsers( "READ-USRS TU10", UserTestData.USERS_TU10_SSD_HIER );
ReviewMgrImplTest.readUsers( "READ-USRS TU11", UserTestData.USERS_TU11_SSD_HIER );
ReviewMgrImplTest.readUsers( "READ-USRS TU12", UserTestData.USERS_TU12_DSD );
ReviewMgrImplTest.readUsers( "READ-USRS TU13", UserTestData.USERS_TU13_DSD_HIER );
ReviewMgrImplTest.readUsers( "READ-USRS TU14", UserTestData.USERS_TU14_DSD_HIER );
ReviewMgrImplTest.readUsers( "READ-USRS TU15", UserTestData.USERS_TU15_DSD_HIER );
}
@Test
public void testFindUsers()
{
// Add the needed data for this test
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
AdminMgrImplTest.updateUsers( "UPD USERS TU1_UPD", UserTestData.USERS_TU1_UPD );
AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU5", UserTestData.USERS_TU5, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU8_SSD", UserTestData.USERS_TU8_SSD, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU9_SSD_HIER", UserTestData.USERS_TU9_SSD_HIER, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU10_SSD_HIER", UserTestData.USERS_TU10_SSD_HIER, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU11_SSD_HIER", UserTestData.USERS_TU11_SSD_HIER, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU12_DSD", UserTestData.USERS_TU12_DSD, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU13_DSD_HIER", UserTestData.USERS_TU13_DSD_HIER, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU14_DSD_HIER", UserTestData.USERS_TU14_DSD_HIER, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU15_DSD_HIER", UserTestData.USERS_TU15_DSD_HIER, true );
// The test itself
// public List<User> findUsers(User user)
ReviewMgrImplTest.searchUsers( "SRCH-USRS TU1_UPD",
TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU1[0] ) ), UserTestData.USERS_TU1_UPD );
ReviewMgrImplTest.searchUsers( "SRCH-USRS TU3",
TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU3[0] ) ),
UserTestData.USERS_TU3 );
ReviewMgrImplTest.searchUsers( "SRCH-USRS TU4",
TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU4[0] ) ),
UserTestData.USERS_TU4 );
ReviewMgrImplTest.searchUsers( "SRCH-USRS TU5",
TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU5[0] ) ),
UserTestData.USERS_TU5 );
ReviewMgrImplTest.searchUsers( "SRCH-USRS TU8",
TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU8_SSD[0] ) ),
UserTestData.USERS_TU8_SSD );
ReviewMgrImplTest.searchUsers( "SRCH-USRS TU9",
TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU9_SSD_HIER[0] ) ),
UserTestData.USERS_TU9_SSD_HIER );
ReviewMgrImplTest.searchUsers( "SRCH-USRS TU10",
TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU10_SSD_HIER[0] ) ),
UserTestData.USERS_TU10_SSD_HIER );
ReviewMgrImplTest.searchUsers( "SRCH-USRS TU11",
TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU11_SSD_HIER[0] ) ),
UserTestData.USERS_TU11_SSD_HIER );
ReviewMgrImplTest.searchUsers( "SRCH-USRS TU12",
TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU12_DSD[0] ) ),
UserTestData.USERS_TU12_DSD );
ReviewMgrImplTest.searchUsers( "SRCH-USRS TU13",
TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU13_DSD_HIER[0] ) ),
UserTestData.USERS_TU13_DSD_HIER );
ReviewMgrImplTest.searchUsers( "SRCH-USRS TU14",
TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU14_DSD_HIER[0] ) ),
UserTestData.USERS_TU14_DSD_HIER );
ReviewMgrImplTest.searchUsers( "SRCH-USRS TU15",
TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU15_DSD_HIER[0] ) ),
UserTestData.USERS_TU15_DSD_HIER );
}
@Test
public void testFindUserIds()
{
// Add the needed data for this test
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
AdminMgrImplTest.updateUsers( "UPD USERS TU1_UPD", UserTestData.USERS_TU1_UPD );
AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
// The test itself
// public List<String> findUsers(User user, int limit)
ReviewMgrImplTest.searchUserIds( "SRCH-USRIDS TU1_UPD",
TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU1[0] ) ), UserTestData.USERS_TU1_UPD );
ReviewMgrImplTest.searchUserIds( "SRCH-USRIDS TU3",
TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU3[0] ) ), UserTestData.USERS_TU3 );
ReviewMgrImplTest.searchUserIds( "SRCH-USRIDS TU4",
TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU4[0] ) ), UserTestData.USERS_TU4 );
}
@Test
public void testAssignedRoles()
{
// Add the needed data for this test
// from testAddOrgUnit
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
// from testAddRole
AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
// from testAdminMgrAddUser
AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
// from testAssignUser
AdminMgrImplTest.assignUsers( "ASGN-USRS TU1 TR1", UserTestData.USERS_TU1, RoleTestData.ROLES_TR1, false );
AdminMgrImplTest.assignUsers( "ASGN-USRS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2, true );
AdminMgrImplTest.assignUsers( "ASGN-USRS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3, true );
// from testAddPermissionObj
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB1", PermTestData.OBJS_TOB1, true, false );
// from testAddPermissionOp
AdminMgrImplTest.addPermOps( "ADD-OPS TOB1 TOP1", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1, true, false );
// from testGrantPermissionUser
AdminMgrImplTest.addUserGrants( "GRNT-PRMS TU1 TOB1 TOP1", UserTestData.USERS_TU1, PermTestData.OBJS_TOB1,
PermTestData.OPS_TOP1 );
// The test itself
// public List<UserRole> assignedRoles(User userId)
ReviewMgrImplTest.assignedRoles( "ASGN-RLS TU1_UPD TR1", UserTestData.USERS_TU1_UPD, RoleTestData.ROLES_TR1 );
//assignedRoles("ASGN-RLS TU3 TR2", UserTestData.USERS_TU3, RoleTestData.ROLES_TR2);
ReviewMgrImplTest.assignedRoles( "ASGN-RLS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2 );
ReviewMgrImplTest.assignedRoles( "ASGN-RLS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3 );
}
@Test
public void testAssignedRoleNms()
{
// Add the needed data for this test
// from testAddOrgUnit
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
// from testAddRole
AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
// from testAdminMgrAddUser
AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
// from testAssignUser
AdminMgrImplTest.assignUsers( "ASGN-USRS TU1 TR1", UserTestData.USERS_TU1, RoleTestData.ROLES_TR1, false );
AdminMgrImplTest.assignUsers( "ASGN-USRS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2, true );
AdminMgrImplTest.assignUsers( "ASGN-USRS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3, true );
// The test itself
// public List<String> assignedRoles(String userId)
ReviewMgrImplTest.assignedRoleNms( "ASGN-RLS TU1_UPD TR1", UserTestData.USERS_TU1_UPD, RoleTestData.ROLES_TR1 );
//assignedRoles("ASGN-RLS TU3 TR2", UserTestData.USERS_TU3, RoleTestData.ROLES_TR2);
ReviewMgrImplTest.assignedRoleNms( "ASGN-RLS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2 );
ReviewMgrImplTest.assignedRoleNms( "ASGN-RLS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3 );
}
@Test
public void testAuthorizedRoles()
{
// Add the needed data for this test
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR6-DESC", RoleTestData.ROLES_TR6_DESC );
AdminMgrImplTest.addRoleAscendant( "ADD-RLS-TR7-ASC", RoleTestData.ROLES_TR7_ASC );
AdminMgrImplTest.addUsers( "ADD-USRS TU18 TR6_DESC", UserTestData.USERS_TU18U_TR6_DESC, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU19 TR7_ASC", UserTestData.USERS_TU19U_TR7_ASC, true );
// The test itself
// public Set<String> authorizedRoles(User user)
ReviewMgrImplTest.authorizedRoles( "AUTHZ-RLS TU18 TR6 DESC", UserTestData.USERS_TU18U_TR6_DESC );
ReviewMgrImplTest.authorizedRoles( "AUTHZ-RLS TU19 TR7 ASC", UserTestData.USERS_TU19U_TR7_ASC );
}
@Test
public void testAuthorizedUsers()
{
// Add the needed data for this test
// from testAddOrgUnit
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
// from testAddRole
AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
// from testAdminMgrAddUser
AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
// from testAdminMgrUpdateUser
AdminMgrImplTest.updateUsers( "UPD USERS TU1_UPD", UserTestData.USERS_TU1_UPD );
// from testAssignUser
AdminMgrImplTest.assignUsers( "ASGN-USRS TU1 TR1", UserTestData.USERS_TU1, RoleTestData.ROLES_TR1, false );
AdminMgrImplTest.assignUsers( "ASGN-USRS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2, true );
AdminMgrImplTest.assignUsers( "ASGN-USRS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3, true );
// The test itself
// public List<User> authorizedUsers(Role role)
ReviewMgrImplTest.authorizedUsers( "ATHZ-USRS TR1 TU1_UPD", RoleTestData.ROLES_TR1, UserTestData.USERS_TU1_UPD );
ReviewMgrImplTest.authorizedUsers( "ATHZ-USRS TR2 TU4", RoleTestData.ROLES_TR2, UserTestData.USERS_TU4 );
ReviewMgrImplTest.authorizedUsers( "ATHZ-USRS TR3 TU3", RoleTestData.ROLES_TR3, UserTestData.USERS_TU3 );
}
@Test
public void testAuthorizedUserIds()
{
// Add the needed data for this test
// from testAddOrgUnit
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
// from testAddRole
AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
// from testAdminMgrAddUser
AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
// from testAdminMgrUpdateUser
AdminMgrImplTest.updateUsers( "UPD USERS TU1_UPD", UserTestData.USERS_TU1_UPD );
// from testAssignUser
AdminMgrImplTest.assignUsers( "ASGN-USRS TU1 TR1", UserTestData.USERS_TU1, RoleTestData.ROLES_TR1, false );
AdminMgrImplTest.assignUsers( "ASGN-USRS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2, true );
AdminMgrImplTest.assignUsers( "ASGN-USRS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3, true );
// The test itself
// public List<String> authorizedUsers(Role role, int limit)
ReviewMgrImplTest.assignedUserIds( "ATHZ-USRS TR1 TU1_UPD", RoleTestData.ROLES_TR1, UserTestData.USERS_TU1_UPD );
ReviewMgrImplTest.assignedUserIds( "ATHZ-USRS TR2 TU4", RoleTestData.ROLES_TR2, UserTestData.USERS_TU4 );
ReviewMgrImplTest.assignedUserIds( "ATHZ-USRS TR3 TU3", RoleTestData.ROLES_TR3, UserTestData.USERS_TU3 );
}
@Test
public void testAuthorizedUsersHier()
{
// Add the needed data for this test
// from testAddOrgUnit
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
// from testAdminMgrAddRoleDescendant
AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR6-DESC", RoleTestData.ROLES_TR6_DESC );
// from testAdminMgrAddRoleAscendants
AdminMgrImplTest.addRoleAscendant( "ADD-RLS-TR7-ASC", RoleTestData.ROLES_TR7_ASC );
// from testAdminMgrAddUser
AdminMgrImplTest.addUsers( "ADD-USRS TU18 TR6_DESC", UserTestData.USERS_TU18U_TR6_DESC, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU19 TR7_ASC", UserTestData.USERS_TU19U_TR7_ASC, true );
// The test itself
// public List<User> authorizedUsers(Role role)
ReviewMgrImplTest.authorizedUsersHier( "ATHZ-USRS-HIER TR6 TU18", RoleTestData.TR6_AUTHORIZED_USERS );
ReviewMgrImplTest.authorizedUsersHier( "ATHZ-USRS-HIER TR7 TU19", RoleTestData.TR7_AUTHORIZED_USERS );
}
@Test
public void testReadPermissionObj()
{
// Add the needed data for this test
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
// The test itself
// public Permission addPermObj(Permission pOp)
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB1", PermTestData.OBJS_TOB1, true, false );
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB2", PermTestData.OBJS_TOB2, true, false );
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB3", PermTestData.OBJS_TOB3, true, false );
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB4", PermTestData.OBJS_TOB4, true, false );
AdminMgrImplTest.updatePermObjs( "UPD-OBS TOB4_UPD", PermTestData.OBJS_TOB4_UPD, true );
// The test itself
// public Permission readPermission(Permission permOp)
ReviewMgrImplTest.readPermissionObjs( "RD-PRM-OBJS TOB1", PermTestData.OBJS_TOB1 );
ReviewMgrImplTest.readPermissionObjs( "RD-PRM-OBJS TOB2", PermTestData.OBJS_TOB2 );
ReviewMgrImplTest.readPermissionObjs( "RD-PRM-OBJS TOB3", PermTestData.OBJS_TOB3 );
ReviewMgrImplTest.readPermissionObjs( "RD-PRM-OBJS TOB4_UPD", PermTestData.OBJS_TOB4_UPD );
}
@Test
public void testFindPermissionObjs()
{
// Add the needed data for this test
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
// The test itself
// public Permission addPermObj(Permission pOp)
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB1", PermTestData.OBJS_TOB1, true, false );
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB2", PermTestData.OBJS_TOB2, true, false );
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB3", PermTestData.OBJS_TOB3, true, false );
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB4", PermTestData.OBJS_TOB4, true, false );
AdminMgrImplTest.updatePermObjs( "UPD-OBS TOB4_UPD", PermTestData.OBJS_TOB4_UPD, true );
// The test itself
// public List<Permission> findPermissions(Permission permOp)
ReviewMgrImplTest.searchPermissionObjs( "FND-PRM-OBJS TOB1",
TestUtils.getSrchValue( PermTestData.getName( PermTestData.OBJS_TOB1[0] ) ), PermTestData.OBJS_TOB1 );
ReviewMgrImplTest.searchPermissionObjs( "FND-PRM-OBJS TOB2",
TestUtils.getSrchValue( PermTestData.getName( PermTestData.OBJS_TOB2[0] ) ), PermTestData.OBJS_TOB2 );
ReviewMgrImplTest.searchPermissionObjs( "FND-PRM-OBJS TOB3",
TestUtils.getSrchValue( PermTestData.getName( PermTestData.OBJS_TOB3[0] ) ), PermTestData.OBJS_TOB3 );
ReviewMgrImplTest
.searchPermissionObjs( "FND-PRM-OBJS TOB4_UPD",
TestUtils.getSrchValue( PermTestData.getName( PermTestData.OBJS_TOB4_UPD[0] ) ),
PermTestData.OBJS_TOB4_UPD );
}
@Test
public void testReadPermissionOp()
{
// Add the needed data for this test
// from testAddOrgUnit
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
// from testAddPermissionObj
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB1", PermTestData.OBJS_TOB1, true, false );
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB2", PermTestData.OBJS_TOB2, true, false );
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB3", PermTestData.OBJS_TOB3, true, false );
// from testAddPermissionOp
AdminMgrImplTest.addPermOps( "ADD-OPS TOB1 TOP1", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1, true, false );
AdminMgrImplTest.addPermOps( "ADD-OPS TOB2 TOP2", PermTestData.OBJS_TOB2, PermTestData.OPS_TOP2, true, false );
AdminMgrImplTest.addPermOps( "ADD-OPS TOB3 TOP3", PermTestData.OBJS_TOB3, PermTestData.OPS_TOP3, true, false );
// from testUpdatePermissionOp
AdminMgrImplTest.updatePermOps( "UPD-OPS TOB1 TOP1_UPD", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1_UPD,
true );
// The test itself
// public Permission readPermission(Permission permOp)
ReviewMgrImplTest.readPermissionOps( "RD-PRM-OPS TOB1 OPS_TOP1_UPD", PermTestData.OBJS_TOB1,
PermTestData.OPS_TOP1_UPD );
ReviewMgrImplTest.readPermissionOps( "RD-PRM-OPS TOB1 TOP2", PermTestData.OBJS_TOB2, PermTestData.OPS_TOP2 );
ReviewMgrImplTest.readPermissionOps( "RD-PRM-OPS TOB1 TOP3", PermTestData.OBJS_TOB3, PermTestData.OPS_TOP3 );
}
@Test
public void testFindPermissionOps()
{
// Add the needed data for this test
// from testAddOrgUnit
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
// from testAddPermissionObj
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB1", PermTestData.OBJS_TOB1, true, false );
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB2", PermTestData.OBJS_TOB2, true, false );
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB3", PermTestData.OBJS_TOB3, true, false );
// from testAddPermissionOp
AdminMgrImplTest.addPermOps( "ADD-OPS TOB1 TOP1", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1, true, false );
AdminMgrImplTest.addPermOps( "ADD-OPS TOB2 TOP2", PermTestData.OBJS_TOB2, PermTestData.OPS_TOP2, true, false );
AdminMgrImplTest.addPermOps( "ADD-OPS TOB3 TOP3", PermTestData.OBJS_TOB3, PermTestData.OPS_TOP3, true, false );
// from testUpdatePermissionOp
AdminMgrImplTest.updatePermOps( "UPD-OPS TOB1 TOP1_UPD", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1_UPD,
true );
// The test itself
// public List<Permission> findPermissions(Permission permOp)
ReviewMgrImplTest.searchPermissionOps( "FND-PRM-OPS TOB1 OPS_TOP1_UPD",
TestUtils.getSrchValue( PermTestData.getName( PermTestData.OPS_TOP1_UPD[0] ) ), PermTestData.OBJS_TOB1,
PermTestData.OPS_TOP1_UPD );
ReviewMgrImplTest.searchPermissionOps( "FND-PRM-OPS TOB2 TOP2",
TestUtils.getSrchValue( PermTestData.getName( PermTestData.OPS_TOP2[0] ) ), PermTestData.OBJS_TOB2,
PermTestData.OPS_TOP2 );
ReviewMgrImplTest.searchPermissionOps( "FND-PRM-OPS TOB3 TOP3",
TestUtils.getSrchValue( PermTestData.getName( PermTestData.OPS_TOP3[0] ) ), PermTestData.OBJS_TOB3,
PermTestData.OPS_TOP3 );
}
@Test
public void testRolePermissions()
{
// Add the needed data for this test
// from testAddOrgUnit
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
// from testAddRole
AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
// from testAddPermissionObj
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB1", PermTestData.OBJS_TOB1, true, false );
// from testAddPermissionOp
AdminMgrImplTest.addPermOps( "ADD-OPS TOB1 TOP1", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1, true, false );
// from testUpdatePermissionOp
AdminMgrImplTest.updatePermOps( "UPD-OPS TOB1 TOP1_UPD", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1_UPD,
true );
// from testGrantPermissionRole
AdminMgrImplTest.addRoleGrants( "GRNT-PRMS TR1 TOB1 TOP1", RoleTestData.ROLES_TR1, PermTestData.OBJS_TOB1,
PermTestData.OPS_TOP1, true, false );
// The test itself
// public List<Permission> rolePermissions(Role role)
ReviewMgrImplTest.rolePermissions( "ATHRZ-RLE-PRMS TR1 TOB1 TOP1_UPD", RoleTestData.ROLES_TR1,
PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1_UPD );
}
@Test
public void testPermissionRoles()
{
// Add the needed data for this test
// from testAddOrgUnit
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
// from testAddRole
AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
// from testAddPermissionObj
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB1", PermTestData.OBJS_TOB1, true, false );
// from testAddPermissionOp
AdminMgrImplTest.addPermOps( "ADD-OPS TOB1 TOP1", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1, true, false );
// from testGrantPermissionRole
AdminMgrImplTest.addRoleGrants( "GRNT-PRMS TR1 TOB1 TOP1", RoleTestData.ROLES_TR1, PermTestData.OBJS_TOB1,
PermTestData.OPS_TOP1, true, false );
// The test itself
// public List<Role> permissionRoles(Permission perm)
ReviewMgrImplTest.permissionRoles( "PRM-RLS TOB1 TOP1 TR1", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1,
RoleTestData.ROLES_TR1 );
}
@Test
public void testAuthorizedPermissionRoles()
{
// Add the needed data for this test
// from testAddOrgUnit
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
// from testAddRole
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR5B", RoleTestData.ROLES_TR5B );
// from testAdminMgrAddRoleInheritance
AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR5B", RoleTestData.ROLES_TR5B );
// from testAdminMgrAddUser
AdminMgrImplTest.addUsers( "ADD-USRS TU20 TR5_HIER", UserTestData.USERS_TU20U_TR5B, true );
// from testAddPermissionObj
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB6", PermTestData.OBJS_TOB6, true, false );
// from testAddPermissionOp
AdminMgrImplTest.addPermOps( "ADD-OPS TOB6 TOP5", PermTestData.OBJS_TOB6, PermTestData.OPS_TOP5, true, false );
// from testGrantPermissionRole
AdminMgrImplTest.addRoleGrantsHB( "GRNT-PRMS_HB USERS TU20 ROLES_TR5B TOB6 TOP5",
UserTestData.USERS_TU20U_TR5B,
RoleTestData.ROLES_TR5B, PermTestData.OBJS_TOB6, PermTestData.OPS_TOP5 );
// The test itself
// public Set<String> authorizedPermissionRoles(Permission perm)
ReviewMgrImplTest.authorizedPermissionRoles( "AUTHZ PRM-RLES TOB6 TOP5 TR5B", PermTestData.OBJS_TOB6,
PermTestData.OPS_TOP5,
RoleTestData.ROLES_TR5B );
}
@Test
public void testPermissionUsers()
{
// Add the needed data for this test
// from testAddOrgUnit
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
// from testAddRole
AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
// from testAdminMgrAddUser
AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
// from testAdminMgrUpdateUser
AdminMgrImplTest.updateUsers( "UPD USERS TU1_UPD", UserTestData.USERS_TU1_UPD );
// from testAssignUser
AdminMgrImplTest.assignUsers( "ASGN-USRS TU1 TR1", UserTestData.USERS_TU1, RoleTestData.ROLES_TR1, false );
// from testAddPermissionObj
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB1", PermTestData.OBJS_TOB1, true, false );
// from testAddPermissionOp
AdminMgrImplTest.addPermOps( "ADD-OPS TOB1 TOP1", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1, true, false );
//
// from testGrantPermissionUser
AdminMgrImplTest.addUserGrants( "GRNT-PRMS TU1 TOB1 TOP1", UserTestData.USERS_TU1, PermTestData.OBJS_TOB1,
PermTestData.OPS_TOP1 );
// The test itself
// public List<User> permissionUsers(Permission perm)
ReviewMgrImplTest.permissionUsers( "PRM-USRS TOB1 TOP1 TU1_UPD", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1,
UserTestData.USERS_TU1_UPD );
}
@Test
public void testAuthorizedPermissionUsers()
{
// Add the needed data for this test
// from testAddOrgUnit
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
// from testAddRole
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR5_HIER", RoleTestData.ROLES_TR5_HIER );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR5B", RoleTestData.ROLES_TR5B );
// from testAdminMgrAddRoleInheritance
AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR5_HIER", RoleTestData.ROLES_TR5_HIER );
AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR5B", RoleTestData.ROLES_TR5B );
// from testAdminMgrAddUser
AdminMgrImplTest.addUsers( "ADD-USRS TU20 TR5_HIER", UserTestData.USERS_TU20U_TR5B, true );
// from testAssignUser
AdminMgrImplTest.assignUsersH( "ASGN-USRS_H TU20 TR5B HIER", UserTestData.USERS_TU20U_TR5B,
RoleTestData.ROLES_TR5B, true );
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB6", PermTestData.OBJS_TOB6, true, false );
// from testAddPermissionOp
AdminMgrImplTest.addPermOps( "ADD-OPS TOB6 TOP5", PermTestData.OBJS_TOB6, PermTestData.OPS_TOP5, true, false );
// from testGrantPermissionRole
AdminMgrImplTest.addRoleGrantsHB( "GRNT-PRMS_HB USERS TU20 ROLES_TR5B TOB6 TOP5",
UserTestData.USERS_TU20U_TR5B,
RoleTestData.ROLES_TR5B, PermTestData.OBJS_TOB6, PermTestData.OPS_TOP5 );
// The test itself
// public Set<String> authorizedPermissionUsers(Permission perm)
ReviewMgrImplTest.authorizedPermissionUsers( "AUTHZ PRM-USRS TOB6 TOP5 TU20", PermTestData.OBJS_TOB6,
PermTestData.OPS_TOP5,
UserTestData.USERS_TU20U_TR5B );
}
@Test
public void testUserPermissions()
{
// Add the needed data for this test
// from testAddOrgUnit
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
// from testAddRole
AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR5_HIER", RoleTestData.ROLES_TR5_HIER );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR5B", RoleTestData.ROLES_TR5B );
// from testAdminMgrAddRoleInheritance
AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR5_HIER", RoleTestData.ROLES_TR5_HIER );
// from testAdminMgrAddUser
AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU2", UserTestData.USERS_TU2, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
// from testAssignUser
AdminMgrImplTest.assignUsers( "ASGN-USRS TU1 TR1", UserTestData.USERS_TU1, RoleTestData.ROLES_TR1, false );
AdminMgrImplTest.assignUsers( "ASGN-USRS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2, true );
AdminMgrImplTest.assignUsers( "ASGN-USRS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3, true );
// from testAddPermissionObj
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB1", PermTestData.OBJS_TOB1, true, false );
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB2", PermTestData.OBJS_TOB2, true, false );
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB3", PermTestData.OBJS_TOB3, true, false );
// from testAddPermissionOp
AdminMgrImplTest.addPermOps( "ADD-OPS TOB1 TOP1", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1, true, false );
AdminMgrImplTest.addPermOps( "ADD-OPS TOB2 TOP2", PermTestData.OBJS_TOB2, PermTestData.OPS_TOP2, true, false );
AdminMgrImplTest.addPermOps( "ADD-OPS TOB3 TOP3", PermTestData.OBJS_TOB3, PermTestData.OPS_TOP3, true, false );
// from testUpdatePermissionOp
AdminMgrImplTest.updatePermOps( "UPD-OPS TOB1 TOP1_UPD", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1_UPD,
true );
// from testGrantPermissionRole
AdminMgrImplTest.addRoleGrants( "GRNT-PRMS TR1 TOB1 TOP1", RoleTestData.ROLES_TR1, PermTestData.OBJS_TOB1,
PermTestData.OPS_TOP1, true, false );
AdminMgrImplTest.addRoleGrants( "GRNT-PRMS TR2 TOB2 TOP2", RoleTestData.ROLES_TR2, PermTestData.OBJS_TOB2,
PermTestData.OPS_TOP2, true, false );
AdminMgrImplTest.addRoleGrants( "GRNT-PRMS TR3 TOB3 TOP3", RoleTestData.ROLES_TR3, PermTestData.OBJS_TOB3,
PermTestData.OPS_TOP3, true, false );
// from testGrantPermissionUser
AdminMgrImplTest.addUserGrants( "GRNT-PRMS TU1 TOB1 TOP1", UserTestData.USERS_TU1, PermTestData.OBJS_TOB1,
PermTestData.OPS_TOP1 );
// The test itself
// public List <Permission> userPermissions(User user)
ReviewMgrImplTest.userPermissions( "USR-PRMS TU1_UPD TOB1 TOP1_UPD", UserTestData.USERS_TU1_UPD,
PermTestData.OBJS_TOB1,
PermTestData.OPS_TOP1_UPD );
ReviewMgrImplTest.userPermissions( "USR-PRMS TU3 TOB3 TOP3", UserTestData.USERS_TU3, PermTestData.OBJS_TOB3,
PermTestData.OPS_TOP3 );
ReviewMgrImplTest.userPermissions( "USR-PRMS TU4 TOB2 TOP2", UserTestData.USERS_TU4, PermTestData.OBJS_TOB2,
PermTestData.OPS_TOP2 );
}
/***********************************************************/
/* 4. Security Checks */
/***********************************************************/
// DelAccessMgr ARABC:
@Test
public void testCheckAccess()
{
// Add the needed data for this test
// from testAddOrgUnit
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO5", OrgUnitTestData.ORGS_USR_TO5 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO5", OrgUnitTestData.ORGS_PRM_TO5 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
// from testAddRole
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR2", AdminRoleTestData.AROLES_TR2, true );
// from testAddUser
AdminMgrImplTest.addUsers( "ADD-USRS TU16A_ARBAC", UserTestData.USERS_TU17A_ARBAC, true );
// from testAddPermission
AdminMgrImplTest.addPermObjs( "ADD-OBS ARBAC1", PermTestData.ARBAC_OBJS_1, true, false );
AdminMgrImplTest
.addPermOps( "ADD-OPS ARBAC1", PermTestData.ARBAC_OBJS_1, PermTestData.ARBAC_OPS_1, true, false );
// from testAssignAdminUser
DelegatedMgrImplTest.assignAdminUserRole( "ASGN-USR TU17A TR2", UserTestData.USERS_TU17A_ARBAC,
AdminRoleTestData.AROLES_TR2, true );
// from testGrantPermissionRole
AdminMgrImplTest.addRoleGrants( "GRNT-APRMS ARTR2 AROBJ1 AROPS1", AdminRoleTestData.AROLES_TR2,
PermTestData.ARBAC_OBJS_1, PermTestData.ARBAC_OPS_1, true, false );
// from testAdminMgrAddRoleAscendants
AdminMgrImplTest.addRoleAscendant( "ADD-RLS-TR7-ASC", RoleTestData.ROLES_TR7_ASC );
// The test itself
// public boolean checkAccess(String object, String operation, Session session)
DelegatedMgrImplTest.checkAccess( "CHCK-ACS TU1_UPD TO1 TOP1 ", UserTestData.USERS_TU17A_ARBAC,
PermTestData.ARBAC_OBJS_1,
PermTestData.ARBAC_OPS_1, PermTestData.ARBAC_OBJ2, PermTestData.ARBAC_OPS_2 );
}
@Test
public void testCanAssignUser()
{
// Add the needed data for this test
// from testAddOrgUnit
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO5", OrgUnitTestData.ORGS_USR_TO5 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO5", OrgUnitTestData.ORGS_PRM_TO5 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
// DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
// from testAddOrgInheritance
DelegatedMgrImplTest.addInheritedOrgUnits( "ADD-INHERIT ORGS_USR_TO5", OrgUnitTestData.ORGS_USR_TO5 );
// from testAddRole
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR2", AdminRoleTestData.AROLES_TR2, true );
// from testAddUser
AdminMgrImplTest.addUsers( "ADD-USRS TU16A_ARBAC", UserTestData.USERS_TU17A_ARBAC, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU16U_ARBAC", UserTestData.USERS_TU17U_ARBAC, true );
// from testAssignAdminUser
DelegatedMgrImplTest.assignAdminUserRole( "ASGN-USR TU17A TR2", UserTestData.USERS_TU17A_ARBAC,
AdminRoleTestData.AROLES_TR2, true );
// The test itself
//canAssignUsers("CAN-ASGN-USRS TU1 TR1", UserTestData.USERS_TU16_ARBAC, UserTestData.USERS_TU16B_ARBAC, RoleTestData.ROLES_TR14_ARBAC);
DelegatedMgrImplTest.canAssignUsers( "CAN-ASGN-USRS URA_T1 TU17A TU17U TR15", ASSIGN_OP.ASSIGN,
URATestData.URA_T1,
UserTestData.USERS_TU17A_ARBAC, UserTestData.USERS_TU17U_ARBAC, RoleTestData.ROLES_TR15_ARBAC );
}
@Test
public void testCanDeassignUser()
{
// Add the needed data for this test
// from testAddOrgUnit
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO5", OrgUnitTestData.ORGS_USR_TO5 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO5", OrgUnitTestData.ORGS_PRM_TO5 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
// DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
// from testAddOrgInheritance
DelegatedMgrImplTest.addInheritedOrgUnits( "ADD-INHERIT ORGS_USR_TO5", OrgUnitTestData.ORGS_USR_TO5 );
// from testAddRole
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR2", AdminRoleTestData.AROLES_TR2, true );
// from testAddUser
AdminMgrImplTest.addUsers( "ADD-USRS TU16A_ARBAC", UserTestData.USERS_TU17A_ARBAC, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU16U_ARBAC", UserTestData.USERS_TU17U_ARBAC, true );
// from testAssignAdminUser
DelegatedMgrImplTest.assignAdminUserRole( "ASGN-USR TU17A TR2", UserTestData.USERS_TU17A_ARBAC,
AdminRoleTestData.AROLES_TR2, true );
// The test itself
DelegatedMgrImplTest.canAssignUsers( "CAN-DEASGN-USRS URA_T1 TU17A TU17U TR15", ASSIGN_OP.DEASSIGN,
URATestData.URA_T1,
UserTestData.USERS_TU17A_ARBAC, UserTestData.USERS_TU17U_ARBAC, RoleTestData.ROLES_TR15_ARBAC );
}
@Test
public void testCanGrantPerm()
{
// Add the needed data for this test
// from testAddOrgUnit
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO5", OrgUnitTestData.ORGS_USR_TO5 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO5", OrgUnitTestData.ORGS_PRM_TO5 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
// from testAddOrgInheritance
DelegatedMgrImplTest.addInheritedOrgUnits( "ADD-INHERIT ORGS_PRM_TO5", OrgUnitTestData.ORGS_PRM_TO5 );
// from testAddRole
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR2", AdminRoleTestData.AROLES_TR2, true );
// from testAddUser
AdminMgrImplTest.addUsers( "ADD-USRS TU16A_ARBAC", UserTestData.USERS_TU17A_ARBAC, true );
// from testAddPermission
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB5", PermTestData.OBJS_TOB5, true, false );
// from testAssignAdminUser
DelegatedMgrImplTest.assignAdminUserRole( "ASGN-USR TU17A TR2", UserTestData.USERS_TU17A_ARBAC,
AdminRoleTestData.AROLES_TR2, true );
// The test itself
DelegatedMgrImplTest.canGrantPerms( "CAN-GRNT-PRMS PRA_T1 TU17A TOB5 TR15", GRANT_OP.GRANT, PRATestData.PRA_T1,
UserTestData.USERS_TU17A_ARBAC, PermTestData.OBJS_TOB5, RoleTestData.ROLES_TR15_ARBAC );
}
@Test
public void testCanRevokePerm()
{
// Add the needed data for this test
// from testAddOrgUnit
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO5", OrgUnitTestData.ORGS_USR_TO5 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO5", OrgUnitTestData.ORGS_PRM_TO5 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
// from testAddOrgInheritance
DelegatedMgrImplTest.addInheritedOrgUnits( "ADD-INHERIT ORGS_PRM_TO5", OrgUnitTestData.ORGS_PRM_TO5 );
// from testAddRole
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR2", AdminRoleTestData.AROLES_TR2, true );
// from testAddUser
AdminMgrImplTest.addUsers( "ADD-USRS TU16A_ARBAC", UserTestData.USERS_TU17A_ARBAC, true );
// from testAddPermission
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB5", PermTestData.OBJS_TOB5, true, false );
// from testAssignAdminUser
DelegatedMgrImplTest.assignAdminUserRole( "ASGN-USR TU17A TR2", UserTestData.USERS_TU17A_ARBAC,
AdminRoleTestData.AROLES_TR2, true );
// The test itself
DelegatedMgrImplTest.canGrantPerms( "CAN-RVKE-PRMS PRA_T1 TU17A TOB5 TR15", GRANT_OP.REVOKE,
PRATestData.PRA_T1,
UserTestData.USERS_TU17A_ARBAC, PermTestData.OBJS_TOB5, RoleTestData.ROLES_TR15_ARBAC );
}
// AccessMgr RBAC:
@Test
public void testGetUserId()
{
// Add the needed data for this test
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
AdminMgrImplTest.updateUsers( "UPD USERS TU1_UPD", UserTestData.USERS_TU1_UPD );
AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
// The test itself
// public String getUserId(Session, session)
AccessMgrImplTest.getUsers( "GET-USRIDS TU1_UPD", UserTestData.USERS_TU1_UPD );
AccessMgrImplTest.getUsers( "GET-USRIDS TU3", UserTestData.USERS_TU3 );
AccessMgrImplTest.getUsers( "GET-USRIDS TU4", UserTestData.USERS_TU4 );
}
@Test
public void testGetUser()
{
// Add the needed data for this test
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
AdminMgrImplTest.updateUsers( "UPD USERS TU1_UPD", UserTestData.USERS_TU1_UPD );
AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
// The test itself
// public User getUser(Session, session)
AccessMgrImplTest.getUsers( "GET-USRS TU1_UPD", UserTestData.USERS_TU1_UPD );
AccessMgrImplTest.getUsers( "GET-USRS TU3", UserTestData.USERS_TU3 );
AccessMgrImplTest.getUsers( "GET-USRS TU4", UserTestData.USERS_TU4 );
}
/**
*
*/
@Test
public void testCreateSession()
{
// Add the needed data for this test
AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
AdminMgrImplTest.updateUsers( "UPD USERS TU1_UPD", UserTestData.USERS_TU1_UPD );
AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
AdminMgrImplTest.assignUsers( "ASGN-USRS TU1 TR1", UserTestData.USERS_TU1, RoleTestData.ROLES_TR1, false );
AdminMgrImplTest.assignUsers( "ASGN-USRS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2, true );
AdminMgrImplTest.assignUsers( "ASGN-USRS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3, true );
// The test itself
// public Session createSession(User user, boolean isTrusted)
AccessMgrImplTest
.createSessions( "CREATE-SESS TU1_UPD TR1", UserTestData.USERS_TU1_UPD, RoleTestData.ROLES_TR1 );
AccessMgrImplTest.createSessions( "CREATE-SESS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3 );
AccessMgrImplTest.createSessions( "CREATE-SESS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2 );
}
/**
*
*/
@Test
public void testCreateSessionTrusted()
{
// Add the needed data for this test
AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
AdminMgrImplTest.updateUsers( "UPD USERS TU1_UPD", UserTestData.USERS_TU1_UPD );
AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
AdminMgrImplTest.assignUsers( "ASGN-USRS TU1 TR1", UserTestData.USERS_TU1, RoleTestData.ROLES_TR1, false );
AdminMgrImplTest.assignUsers( "ASGN-USRS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2, true );
AdminMgrImplTest.assignUsers( "ASGN-USRS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3, true );
// The test itself
// public Session createSession(User user, boolean isTrusted)
AccessMgrImplTest.createSessionsTrusted( "CR-SESS-TRST TU1_UPD TR1", UserTestData.USERS_TU1_UPD,
RoleTestData.ROLES_TR1 );
AccessMgrImplTest
.createSessionsTrusted( "CR-SESS-TRST TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3 );
AccessMgrImplTest
.createSessionsTrusted( "CR-SESS-TRST TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2 );
}
/**
*
*/
@Test
public void testCreateSessionHier()
{
// Add the needed data for this test
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR6-DESC", RoleTestData.ROLES_TR6_DESC );
AdminMgrImplTest.addRoleAscendant( "ADD-RLS-TR7-ASC", RoleTestData.ROLES_TR7_ASC );
AdminMgrImplTest.addUsers( "ADD-USRS TU18 TR6_DESC", UserTestData.USERS_TU18U_TR6_DESC, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU19 TR7_ASC", UserTestData.USERS_TU19U_TR7_ASC, true );
// The test itself
// public Session createSession(User user, boolean isTrusted)
AccessMgrImplTest.createSessionsHier( "CREATE-SESS-HIER TU18 TR6 DESC", UserTestData.USERS_TU18U_TR6_DESC );
AccessMgrImplTest.createSessionsHier( "CREATE-SESS-HIER TU19U TR7 ASC", UserTestData.USERS_TU19U_TR7_ASC );
}
@Test
public void testCreateSessionsDSD()
{
// from testAddOrgUnit
// DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_TO1", OrgUnitTestData.ORGS_TO1 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
// from testAddRole
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR8_DSD", RoleTestData.ROLES_TR8_DSD );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR9_DSD", RoleTestData.ROLES_TR9_DSD );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR17_DSD_BRUNO", RoleTestData.ROLES_TR17_DSD_BRUNO );
// from testAdminMgrAddRoleDescendant
AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR11-DESC-DSD", RoleTestData.ROLES_TR11_DESC_DSD );
AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR12-DESC-DSD", RoleTestData.ROLES_TR12_DESC_DSD );
AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR13-DESC-DSD", RoleTestData.ROLES_TR13_DESC_DSD );
// from testAdminMgrCreateDsdSet
AdminMgrImplTest.createDsdSet( "ADD-DSD T1", RoleTestData.DSD_T1 );
AdminMgrImplTest.createDsdSet( "ADD-DSD T4", RoleTestData.DSD_T4 );
AdminMgrImplTest.createDsdSet( "ADD-DSD T5", RoleTestData.DSD_T5 );
AdminMgrImplTest.createDsdSet( "ADD-DSD T6", RoleTestData.DSD_T6 );
AdminMgrImplTest.createDsdSet( "ADD-DSD T8 BRUNO", RoleTestData.DSD_T8_BRUNO );
// from testAdminMgrAddUser
AdminMgrImplTest.addUsers( "ADD-USRS TU12_DSD", UserTestData.USERS_TU12_DSD, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU13_DSD_HIER", UserTestData.USERS_TU13_DSD_HIER, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU14_DSD_HIER", UserTestData.USERS_TU14_DSD_HIER, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU15_DSD_HIER", UserTestData.USERS_TU15_DSD_HIER, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU21 DSD_BRUNO", UserTestData.USERS_TU21_DSD_BRUNO, true );
// from testAssignUser
AdminMgrImplTest.assignUsersDSD( "ASGN-USRS_DSDT1 TU12 DSD_T1", UserTestData.USERS_TU12_DSD,
RoleTestData.DSD_T1 );
AdminMgrImplTest.assignUsersDSD( "ASGN-USRS_DSDT4B TU13 DSD_T4_B", UserTestData.USERS_TU13_DSD_HIER,
RoleTestData.DSD_T4_B );
AdminMgrImplTest.assignUsersDSD( "ASGN-USRS_DSDT5B TU14 DSD_T5_B", UserTestData.USERS_TU14_DSD_HIER,
RoleTestData.DSD_T5_B );
AdminMgrImplTest.assignUsersDSD( "ASGN-USRS_DSDT6B TU15 DSD_T6_B", UserTestData.USERS_TU15_DSD_HIER,
RoleTestData.DSD_T6_B );
// The test itself
// public Session createSession(User user, boolean isTrusted)
AccessMgrImplTest.createSessionsDSD( "CR-SESS-DSD TU12 DSD_T1", UserTestData.USERS_TU12_DSD,
RoleTestData.DSD_T1 );
AccessMgrImplTest.createSessionsDSD( "CR-SESS-DSD TU13 DSD_T4_B", UserTestData.USERS_TU13_DSD_HIER,
RoleTestData.DSD_T4_B );
AccessMgrImplTest.createSessionsDSD( "CR-SESS-DSD TU14 DSD_T5_B", UserTestData.USERS_TU14_DSD_HIER,
RoleTestData.DSD_T5_B );
AccessMgrImplTest.createSessionsDSD( "CR-SESS-DSD TU15 DSD_T6_C", UserTestData.USERS_TU15_DSD_HIER,
RoleTestData.DSD_T6_C );
AccessMgrImplTest.createSessionsDSD( "CR-SESS-DSD TU21 DSD_T8_BRUNO", UserTestData.USERS_TU21_DSD_BRUNO,
RoleTestData.DSD_T8_BRUNO );
// Running it again to make sure the caching is working good:
AccessMgrImplTest.createSessionsDSD( "CR-SESS-DSD TU12 DSD_T1", UserTestData.USERS_TU12_DSD,
RoleTestData.DSD_T1 );
AccessMgrImplTest.createSessionsDSD( "CR-SESS-DSD TU13 DSD_T4_B", UserTestData.USERS_TU13_DSD_HIER,
RoleTestData.DSD_T4_B );
AccessMgrImplTest.createSessionsDSD( "CR-SESS-DSD TU14 DSD_T5_B", UserTestData.USERS_TU14_DSD_HIER,
RoleTestData.DSD_T5_B );
AccessMgrImplTest.createSessionsDSD( "CR-SESS-DSD TU15 DSD_T6_C", UserTestData.USERS_TU15_DSD_HIER,
RoleTestData.DSD_T6_C );
AccessMgrImplTest.createSessionsDSD( "CR-SESS-DSD TU21 DSD_T8_BRUNO", UserTestData.USERS_TU21_DSD_BRUNO,
RoleTestData.DSD_T8_BRUNO );
}
/**
*
*/
@Test
public void testSessionRole()
{
// Add the needed data for this test
// from testAddOrgUnit
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
// from testAddRole
AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
// from testAdminMgrAddUser
AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
// from testAdminMgrUpdateUser
AdminMgrImplTest.updateUsers( "UPD USERS TU1_UPD", UserTestData.USERS_TU1_UPD );
// from testAssignUser
AdminMgrImplTest.assignUsers( "ASGN-USRS TU1 TR1", UserTestData.USERS_TU1, RoleTestData.ROLES_TR1, false );
AdminMgrImplTest.assignUsers( "ASGN-USRS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2, true );
AdminMgrImplTest.assignUsers( "ASGN-USRS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3, true );
// The test itself
// public List<UserRole> sessionRoles(Session session)
AccessMgrImplTest.sessionRoles( "SESS-RLS TU1_UPD TR1", UserTestData.USERS_TU1_UPD, RoleTestData.ROLES_TR1 );
AccessMgrImplTest.sessionRoles( "SESS-RLS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3 );
AccessMgrImplTest.sessionRoles( "SESS-RLS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2 );
}
/**
*
*/
@Test
public void testAccessMgrCheckAccess()
{
// Add the needed data for this test
// from testAddOrgUnit
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
// from testAddRole
AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
// from testAdminMgrAddUser
AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
// from testAdminMgrUpdateUser
AdminMgrImplTest.updateUsers( "UPD USERS TU1_UPD", UserTestData.USERS_TU1_UPD );
// from testAssignUser
AdminMgrImplTest.assignUsers( "ASGN-USRS TU1 TR1", UserTestData.USERS_TU1, RoleTestData.ROLES_TR1, false );
AdminMgrImplTest.assignUsers( "ASGN-USRS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2, true );
AdminMgrImplTest.assignUsers( "ASGN-USRS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3, true );
// from testAddPermissionObj
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB1", PermTestData.OBJS_TOB1, true, false );
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB2", PermTestData.OBJS_TOB2, true, false );
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB3", PermTestData.OBJS_TOB3, true, false );
// from testAddPermissionOp
AdminMgrImplTest.addPermOps( "ADD-OPS TOB1 TOP1", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1, true, false );
AdminMgrImplTest.addPermOps( "ADD-OPS TOB2 TOP2", PermTestData.OBJS_TOB2, PermTestData.OPS_TOP2, true, false );
AdminMgrImplTest.addPermOps( "ADD-OPS TOB3 TOP3", PermTestData.OBJS_TOB3, PermTestData.OPS_TOP3, true, false );
// from testGrantPermissionRole
AdminMgrImplTest.addRoleGrants( "GRNT-PRMS TR1 TOB1 TOP1", RoleTestData.ROLES_TR1, PermTestData.OBJS_TOB1,
PermTestData.OPS_TOP1, true, false );
AdminMgrImplTest.addRoleGrants( "GRNT-PRMS TR2 TOB2 TOP2", RoleTestData.ROLES_TR2, PermTestData.OBJS_TOB2,
PermTestData.OPS_TOP2, true, false );
AdminMgrImplTest.addRoleGrants( "GRNT-PRMS TR3 TOB3 TOP3", RoleTestData.ROLES_TR3, PermTestData.OBJS_TOB3,
PermTestData.OPS_TOP3, true, false );
// The test itself
// public boolean checkAccess(String object, String operation, Session session)
AccessMgrImplTest.checkAccess( "CHCK-ACS TU1_UPD TO1 TOP1 ", UserTestData.USERS_TU1_UPD,
PermTestData.OBJS_TOB1,
PermTestData.OPS_TOP1, PermTestData.OBJS_TOB3, PermTestData.OPS_TOP3 );
AccessMgrImplTest.checkAccess( "CHCK-ACS TU3 TO3 TOP1 ", UserTestData.USERS_TU3, PermTestData.OBJS_TOB3,
PermTestData.OPS_TOP3,
PermTestData.OBJS_TOB2, PermTestData.OPS_TOP1 );
AccessMgrImplTest.checkAccess( "CHCK-ACS TU4 TO4 TOP1 ", UserTestData.USERS_TU4, PermTestData.OBJS_TOB2,
PermTestData.OPS_TOP2,
PermTestData.OBJS_TOB2, PermTestData.OPS_TOP1 );
}
@Test
public void testAddActiveRole()
{
// Add the needed data for this test
// from testAddOrgUnit
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
// from testAddRole
AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR8_DSD", RoleTestData.ROLES_TR8_DSD );
// from testAdminMgrAddRoleDescendant
AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR11-DESC-DSD", RoleTestData.ROLES_TR11_DESC_DSD );
AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR12-DESC-DSD", RoleTestData.ROLES_TR12_DESC_DSD );
AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR13-DESC-DSD", RoleTestData.ROLES_TR13_DESC_DSD );
// from testAdminMgrCreateDsdSet
AdminMgrImplTest.createDsdSet( "ADD-DSD T1", RoleTestData.DSD_T1 );
AdminMgrImplTest.createDsdSet( "ADD-DSD T4", RoleTestData.DSD_T4 );
AdminMgrImplTest.createDsdSet( "ADD-DSD T5", RoleTestData.DSD_T5 );
AdminMgrImplTest.createDsdSet( "ADD-DSD T6", RoleTestData.DSD_T6 );
// from testAdminMgrAddUser
AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU8_SSD", UserTestData.USERS_TU8_SSD, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU9_SSD_HIER", UserTestData.USERS_TU9_SSD_HIER, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU10_SSD_HIER", UserTestData.USERS_TU10_SSD_HIER, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU11_SSD_HIER", UserTestData.USERS_TU11_SSD_HIER, true );
// from testAdminMgrUpdateUser
AdminMgrImplTest.updateUsers( "UPD USERS TU1_UPD", UserTestData.USERS_TU1_UPD );
// from testAssignUser
AdminMgrImplTest.assignUsers( "ASGN-USRS TU1 TR1", UserTestData.USERS_TU1, RoleTestData.ROLES_TR1, false );
AdminMgrImplTest.assignUsers( "ASGN-USRS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2, true );
AdminMgrImplTest.assignUsers( "ASGN-USRS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3, true );
AdminMgrImplTest.assignUsersDSD( "ASGN-USRS_DSDT1 TU8 DSD_T1", UserTestData.USERS_TU8_SSD, RoleTestData.DSD_T1 );
AdminMgrImplTest.assignUsersDSD( "ASGN-USRS_DSDT4B TU9 DSD_T4_B", UserTestData.USERS_TU9_SSD_HIER,
RoleTestData.DSD_T4_B );
AdminMgrImplTest.assignUsersDSD( "ASGN-USRS_DSDT5B TU10 DSD_T5_B", UserTestData.USERS_TU10_SSD_HIER,
RoleTestData.DSD_T5_B );
AdminMgrImplTest.assignUsersDSD( "ASGN-USRS_DSDT6B TU11 DSD_T6_B", UserTestData.USERS_TU11_SSD_HIER,
RoleTestData.DSD_T6_B );
// The test itself
// public void addActiveRole(Session session, String role)
AccessMgrImplTest.addActiveRoles( "ADD-ACT-RLS TU1_UPD TR1 bad:TR2", UserTestData.USERS_TU1_UPD,
RoleTestData.ROLES_TR1,
RoleTestData.ROLES_TR2 );
AccessMgrImplTest.addActiveRoles( "ADD-ACT-RLS TU3 TR3 bad:TR1:", UserTestData.USERS_TU3,
RoleTestData.ROLES_TR3,
RoleTestData.ROLES_TR1 );
AccessMgrImplTest.addActiveRoles( "ADD-ACT-RLS TU4 TR2 bad:TR1", UserTestData.USERS_TU4,
RoleTestData.ROLES_TR2,
RoleTestData.ROLES_TR1 );
AccessMgrImplTest.addActiveRolesDSD( "ADD-ACT-RLS-USRS_DSDT1 TU8 DSD_T1", UserTestData.USERS_TU8_SSD,
RoleTestData.DSD_T1 );
AccessMgrImplTest.addActiveRolesDSD( "ADD-ACT-RLS-USRS_DSDT4B TU9 DSD_T4_B", UserTestData.USERS_TU9_SSD_HIER,
RoleTestData.DSD_T4_B );
AccessMgrImplTest.addActiveRolesDSD( "ADD-ACT-RLS-USRS_DSDT5B TU10 DSD_T5_B", UserTestData.USERS_TU10_SSD_HIER,
RoleTestData.DSD_T5_B );
AccessMgrImplTest.addActiveRolesDSD( "ADD-ACT-RLS-USRS_DSDT6B TU11 DSD_T6_B", UserTestData.USERS_TU11_SSD_HIER,
RoleTestData.DSD_T6_B );
}
@Test
public void testDropActiveRole()
{
// Add the needed data for this test
// from testAddOrgUnit
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
// from testAddRole
AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR8_DSD", RoleTestData.ROLES_TR8_DSD );
// from testAdminMgrAddRoleDescendant
AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR11-DESC-DSD", RoleTestData.ROLES_TR11_DESC_DSD );
AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR12-DESC-DSD", RoleTestData.ROLES_TR12_DESC_DSD );
AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR13-DESC-DSD", RoleTestData.ROLES_TR13_DESC_DSD );
// from testAdminMgrCreateDsdSet
AdminMgrImplTest.createDsdSet( "ADD-DSD T1", RoleTestData.DSD_T1 );
AdminMgrImplTest.createDsdSet( "ADD-DSD T4", RoleTestData.DSD_T4 );
AdminMgrImplTest.createDsdSet( "ADD-DSD T5", RoleTestData.DSD_T5 );
AdminMgrImplTest.createDsdSet( "ADD-DSD T6", RoleTestData.DSD_T6 );
// from testAdminMgrAddUser
AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU8_SSD", UserTestData.USERS_TU8_SSD, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU9_SSD_HIER", UserTestData.USERS_TU9_SSD_HIER, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU10_SSD_HIER", UserTestData.USERS_TU10_SSD_HIER, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU11_SSD_HIER", UserTestData.USERS_TU11_SSD_HIER, true );
// from testAdminMgrUpdateUser
AdminMgrImplTest.updateUsers( "UPD USERS TU1_UPD", UserTestData.USERS_TU1_UPD );
// from testAssignUser
AdminMgrImplTest.assignUsers( "ASGN-USRS TU1 TR1", UserTestData.USERS_TU1, RoleTestData.ROLES_TR1, false );
AdminMgrImplTest.assignUsers( "ASGN-USRS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2, true );
AdminMgrImplTest.assignUsers( "ASGN-USRS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3, true );
AdminMgrImplTest.assignUsersDSD( "ASGN-USRS_DSDT1 TU8 DSD_T1", UserTestData.USERS_TU8_SSD, RoleTestData.DSD_T1 );
AdminMgrImplTest.assignUsersDSD( "ASGN-USRS_DSDT4B TU9 DSD_T4_B", UserTestData.USERS_TU9_SSD_HIER,
RoleTestData.DSD_T4_B );
// The test itself
// public void dropActiveRole(Session session, String role)
AccessMgrImplTest.dropActiveRoles( "DRP-ACT-RLS TU1_UPD TR1 bad:TR2", UserTestData.USERS_TU1_UPD,
RoleTestData.ROLES_TR1 );
AccessMgrImplTest.dropActiveRoles( "DRP-ACT-RLS TU3 TR3 bad:TR1", UserTestData.USERS_TU3,
RoleTestData.ROLES_TR3 );
AccessMgrImplTest.dropActiveRoles( "DRP-ACT-RLS TU4 TR2 bad:TR1", UserTestData.USERS_TU4,
RoleTestData.ROLES_TR2 );
}
@Test
public void testSessionPermission()
{
// Add the needed data for this test
// from testAddOrgUnit
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
// from testAddRole
AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR5_HIER", RoleTestData.ROLES_TR5_HIER );
// from testAdminMgrAddRoleInheritance
AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR5_HIER", RoleTestData.ROLES_TR5_HIER );
// from testAdminMgrAddUser
AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU7_HIER", UserTestData.USERS_TU7_HIER, true );
// from testAdminMgrUpdateUser
AdminMgrImplTest.updateUsers( "UPD USERS TU1_UPD", UserTestData.USERS_TU1_UPD );
// from testAssignUser
AdminMgrImplTest.assignUsers( "ASGN-USRS TU1 TR1", UserTestData.USERS_TU1, RoleTestData.ROLES_TR1, false );
AdminMgrImplTest.assignUsersH( "ASGN-USRS_H TU7 HIER TR5 HIER", UserTestData.USERS_TU7_HIER,
RoleTestData.ROLES_TR5_HIER, true );
// from testAddPermissionObj
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB1", PermTestData.OBJS_TOB1, true, false );
AdminMgrImplTest.addPermObjs( "ADD-OBS TOB4", PermTestData.OBJS_TOB4, true, false );
// from testAddPermissionOp
AdminMgrImplTest.addPermOps( "ADD-OPS TOB1 TOP1", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1, true, false );
AdminMgrImplTest.addPermOps( "ADD-OPS TOB4 TOP4", PermTestData.OBJS_TOB4, PermTestData.OPS_TOP4, true, false );
// from testGrantPermissionRole
AdminMgrImplTest.addRoleGrants( "GRNT-PRMS TR1 TOB1 TOP1", RoleTestData.ROLES_TR1, PermTestData.OBJS_TOB1,
PermTestData.OPS_TOP1, true, false );
AdminMgrImplTest.addRoleGrantsH( "GRNT-PRMS_H ROLES_TR5_HIER TOB4 TOP4", RoleTestData.ROLES_TR5_HIER,
PermTestData.OBJS_TOB4,
PermTestData.OPS_TOP4 );
// The test itself
// public List<Permission> sessionPermissions(Session session)
// public static void sessionPermissions(String msg, String[][] uArray, String[][] oArray, String[][] opArray)
AccessMgrImplTest.sessionPermissions( "SESS-PRMS TU1_UPD TO1 TOP1 ", UserTestData.USERS_TU1_UPD,
PermTestData.OBJS_TOB1,
PermTestData.OPS_TOP1 );
AccessMgrImplTest.sessionPermissionsH( "SESS-PRMS_H USERS_TU7_HIER OBJS_TOB4 OPS_TOP4 ",
UserTestData.USERS_TU7_HIER,
PermTestData.OBJS_TOB4, PermTestData.OPS_TOP4 );
}
@Test
public void testCreateSessionWithRole()
{
// Add the needed data for this test
// from testAddOrgUnit
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
// from testAddRole
AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
// from testAdminMgrAddUser
AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
// from testAdminMgrUpdateUser
AdminMgrImplTest.updateUsers( "UPD USERS TU1_UPD", UserTestData.USERS_TU1_UPD );
// from testAssignUser
AdminMgrImplTest.assignUsers( "ASGN-USRS TU1 TR1", UserTestData.USERS_TU1, RoleTestData.ROLES_TR1, false );
AdminMgrImplTest.assignUsers( "ASGN-USRS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2, true );
AdminMgrImplTest.assignUsers( "ASGN-USRS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3, true );
// The test itself
// public Session createSession(User user, boolean isTrusted)
AccessMgrImplTest.createSessionsWithRoles( "CR-SESS-WRLS TU1_UPD TR1", UserTestData.USERS_TU1_UPD,
RoleTestData.ROLES_TR1 );
AccessMgrImplTest.createSessionsWithRoles( "CR-SESS-WRLS TU3 TR3", UserTestData.USERS_TU3,
RoleTestData.ROLES_TR3 );
AccessMgrImplTest.createSessionsWithRoles( "CR-SESS-WRLS TU4 TR2", UserTestData.USERS_TU4,
RoleTestData.ROLES_TR2 );
}
@Test
public void testCreateSessionWithRolesTrusted()
{
// Add the needed data for this test
// from testAddOrgUnit
DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
// from testAddRole
AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
// from testAdminMgrAddUser
AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
// from testAdminMgrUpdateUser
AdminMgrImplTest.updateUsers( "UPD USERS TU1_UPD", UserTestData.USERS_TU1_UPD );
// from testAssignUser
AdminMgrImplTest.assignUsers( "ASGN-USRS TU1 TR1", UserTestData.USERS_TU1, RoleTestData.ROLES_TR1, false );
AdminMgrImplTest.assignUsers( "ASGN-USRS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2, true );
AdminMgrImplTest.assignUsers( "ASGN-USRS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3, true );
// The test itself
// public Session createSession(User user, boolean isTrusted)
AccessMgrImplTest.createSessionsWithRolesTrusted( "CR-SESS-WRLS-TRST TU1_UPD TR1", UserTestData.USERS_TU1_UPD,
RoleTestData.ROLES_TR1 );
AccessMgrImplTest.createSessionsWithRolesTrusted( "CR-SESS-WRLS-TRST TU3 TR3", UserTestData.USERS_TU3,
RoleTestData.ROLES_TR3 );
AccessMgrImplTest.createSessionsWithRolesTrusted( "CR-SESS-WRLS-TRST TU4 TR2", UserTestData.USERS_TU4,
RoleTestData.ROLES_TR2 );
}
}
|
src/test/java/us/jts/fortress/rbac/apacheds/FortressJUnitApachedsTest.java
|
Ported the Fortress Openldap tests to ApacheDS
|
src/test/java/us/jts/fortress/rbac/apacheds/FortressJUnitApachedsTest.java
|
Ported the Fortress Openldap tests to ApacheDS
|
<ide><path>rc/test/java/us/jts/fortress/rbac/apacheds/FortressJUnitApachedsTest.java
<add>package us.jts.fortress.rbac.apacheds;
<add>
<add>
<add>import org.apache.directory.server.annotations.CreateLdapServer;
<add>import org.apache.directory.server.annotations.CreateTransport;
<add>import org.apache.directory.server.core.annotations.ApplyLdifFiles;
<add>import org.apache.directory.server.core.annotations.CreateDS;
<add>import org.apache.directory.server.core.annotations.CreatePartition;
<add>import org.apache.directory.server.core.integ.AbstractLdapTestUnit;
<add>import org.apache.directory.server.core.integ.FrameworkRunner;
<add>import org.apache.log4j.Logger;
<add>import org.junit.Before;
<add>import org.junit.Test;
<add>import org.junit.runner.RunWith;
<add>
<add>import us.jts.fortress.SecurityException;
<add>import us.jts.fortress.rbac.AccessMgrImplTest;
<add>import us.jts.fortress.rbac.AdminMgrImplTest;
<add>import us.jts.fortress.rbac.AdminRoleTestData;
<add>import us.jts.fortress.rbac.DelegatedMgrImplTest;
<add>import us.jts.fortress.rbac.DelegatedMgrImplTest.ASSIGN_OP;
<add>import us.jts.fortress.rbac.DelegatedMgrImplTest.GRANT_OP;
<add>import us.jts.fortress.rbac.FortressJUnitTest;
<add>import us.jts.fortress.rbac.OrgUnit;
<add>import us.jts.fortress.rbac.OrgUnitTestData;
<add>import us.jts.fortress.rbac.PRATestData;
<add>import us.jts.fortress.rbac.PermTestData;
<add>import us.jts.fortress.rbac.ReviewMgrImplTest;
<add>import us.jts.fortress.rbac.RoleTestData;
<add>import us.jts.fortress.rbac.Session;
<add>import us.jts.fortress.rbac.TestUtils;
<add>import us.jts.fortress.rbac.URATestData;
<add>import us.jts.fortress.rbac.UserTestData;
<add>import us.jts.fortress.util.cache.CacheMgr;
<add>
<add>
<add>@RunWith(FrameworkRunner.class)
<add>@CreateDS(name = "classDS", partitions =
<add> { @CreatePartition(name = "example", suffix = "dc=example,dc=com") })
<add>@CreateLdapServer(
<add> transports =
<add> {
<add> @CreateTransport(protocol = "LDAP", port = 10389)
<add> })
<add>@ApplyLdifFiles(
<add> { "fortress-schema.ldif", "init-ldap.ldif"/*, "test-data.ldif"*/})
<add>public class FortressJUnitApachedsTest extends AbstractLdapTestUnit
<add>{
<add> private static final String CLS_NM = DelegatedMgrImplTest.class.getName();
<add> final private static Logger log = Logger.getLogger( CLS_NM );
<add> private static Session adminSess = null;
<add>
<add>
<add> @Before
<add> public void init()
<add> {
<add> CacheMgr.getInstance().clearAll();
<add> }
<add>
<add>
<add> /***********************************************************/
<add> /* 2. Build Up */
<add> /***********************************************************/
<add> // DelegatedAdminMgrImplTest ARBAC Buildup APIs:
<add> @Test
<add> public void testAddAdminUser()
<add> {
<add> DelegatedMgrImplTest.addOrgUnit( "ADD ORG_PRM_APP0", OrgUnitTestData.ORGS_PRM_APP0[0] );
<add> DelegatedMgrImplTest.addOrgUnit( "ADD ORG_USR_DEV0", OrgUnitTestData.ORGS_USR_DEV0[0] );
<add> DelegatedMgrImplTest.addAdminRoles( "ADD-ARLS SUPER", AdminRoleTestData.AROLES_SUPER, false );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS PSWDMGR_OBJ", PermTestData.PSWDMGR_OBJ, false, false );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS ADMINMGR_OBJ", PermTestData.ADMINMGR_OBJ, false, false );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS DELEGATEDMGR_OBJ", PermTestData.DELEGATEDMGR_OBJ, false, false );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS DELEGATEDREVIEWMGR_OBJ", PermTestData.DELEGATEDREVIEWMGR_OBJ, false,
<add> false );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS REVIEWMGR_OBJ", PermTestData.REVIEWMGR_OBJ, false, false );
<add> AdminMgrImplTest.addPermOps( "ADD-OPS PSWDMGR_OBJ PSWDMGR_OPS", PermTestData.PSWDMGR_OBJ,
<add> PermTestData.PSWDMGR_OPS, false, false );
<add> AdminMgrImplTest.addPermOps( "ADD-OPS ADMINMGR_OBJ ADMINMGR_OPS", PermTestData.ADMINMGR_OBJ,
<add> PermTestData.ADMINMGR_OPS, false, false );
<add> AdminMgrImplTest.addPermOps( "ADD-OPS DELEGATEDMGR_OBJ DELEGATEDMGR_OPS", PermTestData.DELEGATEDMGR_OBJ,
<add> PermTestData.DELEGATEDMGR_OPS, false, false );
<add> AdminMgrImplTest.addPermOps( "ADD-OPS DELEGATEDREVIEWMGR_OBJ DELEGATEDREVIEWMGR_OPS",
<add> PermTestData.DELEGATEDREVIEWMGR_OBJ, PermTestData.DELEGATEDREVIEWMGR_OPS, false, false );
<add> AdminMgrImplTest.addPermOps( "ADD-OPS REVIEWMGR_OBJ REVIEWMGR_OPS", PermTestData.REVIEWMGR_OBJ,
<add> PermTestData.REVIEWMGR_OPS, false, false );
<add> AdminMgrImplTest.addRoleGrants( "GRNT-APRMS SUPER PSWDMGR_OBJ PSWDMGR_OPS", AdminRoleTestData.AROLES_SUPER,
<add> PermTestData.PSWDMGR_OBJ, PermTestData.PSWDMGR_OPS, false, false );
<add> AdminMgrImplTest.addRoleGrants( "GRNT-APRMS SUPER ADMINMGR_OBJ ADMINMGR_OPS", AdminRoleTestData.AROLES_SUPER,
<add> PermTestData.ADMINMGR_OBJ, PermTestData.ADMINMGR_OPS, false, false );
<add> AdminMgrImplTest.addRoleGrants( "GRNT-APRMS SUPER DELEGATEDMGR_OBJ DELEGATEDMGR_OPS",
<add> AdminRoleTestData.AROLES_SUPER, PermTestData.DELEGATEDMGR_OBJ, PermTestData.DELEGATEDMGR_OPS, false, false );
<add> AdminMgrImplTest.addRoleGrants( "GRNT-APRMS SUPER DELEGATEDREVIEWMGR_OBJ DELEGATEDREVIEWMGR_OPS",
<add> AdminRoleTestData.AROLES_SUPER, PermTestData.DELEGATEDREVIEWMGR_OBJ, PermTestData.DELEGATEDREVIEWMGR_OPS,
<add> false, false );
<add> AdminMgrImplTest.addRoleGrants( "GRNT-APRMS SUPER REVIEWMGR_OBJ REVIEWMGR_OPS", AdminRoleTestData.AROLES_SUPER,
<add> PermTestData.REVIEWMGR_OBJ, PermTestData.REVIEWMGR_OPS, false, false );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU0", UserTestData.USERS_TU0, false );
<add> DelegatedMgrImplTest.assignAdminUsers( "ASGN-USRS TU0 SUPER", UserTestData.USERS_TU0,
<add> AdminRoleTestData.AROLES_SUPER, false );
<add>
<add> // do these last - may have already been added via demoUsers:
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS AUDITMGR_OBJ", PermTestData.AUDITMGR_OBJ, false, true );
<add> AdminMgrImplTest.addPermOps( "ADD-OPS AUDITMGR_OBJ AUDITMGR_OPS", PermTestData.AUDITMGR_OBJ,
<add> PermTestData.AUDITMGR_OPS, false, true );
<add> AdminMgrImplTest.addRoleGrants( "GRNT-APRMS SUPER AUDITMGR_OBJ AUDITMGR_OPS", AdminRoleTestData.AROLES_SUPER,
<add> PermTestData.AUDITMGR_OBJ, PermTestData.AUDITMGR_OPS, false, true );
<add> }
<add>
<add>
<add> @Test
<add> public void testAddOrgUnit()
<add> {
<add> //addOrgUnits("ADD ORGS_USR_DEV0", OrgUnitTestData.ORGS_USR_DEV0);
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_TO1", OrgUnitTestData.ORGS_TO1 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO2", OrgUnitTestData.ORGS_USR_TO2 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_ORGS_PRM_TO3", OrgUnitTestData.ORGS_PRM_TO3 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO4", OrgUnitTestData.ORGS_PRM_TO4 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO5", OrgUnitTestData.ORGS_USR_TO5 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO5", OrgUnitTestData.ORGS_PRM_TO5 );
<add>
<add> // The DEV1 OU is not removed during cleanup phase because the test system users belong to it:
<add> if ( FortressJUnitTest.isFirstRun() )
<add> {
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add> }
<add>
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
<add> }
<add>
<add>
<add> @Test
<add> public void testUpdateOrgUnit()
<add> {
<add> // Inject the needed data for the test
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_TO1", OrgUnitTestData.ORGS_TO1 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_ORGS_PRM_TO3", OrgUnitTestData.ORGS_PRM_TO3 );
<add>
<add> // The test itself
<add> DelegatedMgrImplTest.updateOrgUnits( "UPD ORGS_TO1", OrgUnitTestData.ORGS_TO1 );
<add> DelegatedMgrImplTest.updateOrgUnits( "UPD ORGS_PRM_TO3", OrgUnitTestData.ORGS_PRM_TO3 );
<add> }
<add>
<add>
<add> @Test
<add> public void testAddOrgInheritance()
<add> {
<add> // Inject the needed data for the test
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO2", OrgUnitTestData.ORGS_USR_TO2 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO4", OrgUnitTestData.ORGS_PRM_TO4 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO5", OrgUnitTestData.ORGS_USR_TO5 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO5", OrgUnitTestData.ORGS_PRM_TO5 );
<add>
<add> // The test itself
<add> DelegatedMgrImplTest.addInheritedOrgUnits( "ADD-INHERIT ORGS_USR_TO2", OrgUnitTestData.ORGS_USR_TO2 );
<add> DelegatedMgrImplTest.addInheritedOrgUnits( "ADD-INHERIT ORGS_PRM_TO4", OrgUnitTestData.ORGS_PRM_TO4 );
<add> DelegatedMgrImplTest.addInheritedOrgUnits( "ADD-INHERIT ORGS_USR_TO5", OrgUnitTestData.ORGS_USR_TO5 );
<add> DelegatedMgrImplTest.addInheritedOrgUnits( "ADD-INHERIT ORGS_PRM_TO5", OrgUnitTestData.ORGS_PRM_TO5 );
<add> }
<add>
<add>
<add> @Test
<add> public void testAddOrgUnitDescendant()
<add> {
<add> DelegatedMgrImplTest.addOrgUnitDescendant( "ADD ORGS-USR-TO6-DESC", OrgUnitTestData.ORGS_USR_TO6_DSC,
<add> OrgUnit.Type.USER );
<add> DelegatedMgrImplTest.addOrgUnitDescendant( "ADD ORGS-PRM-TO6-DESC", OrgUnitTestData.ORGS_PRM_TO6_DSC,
<add> OrgUnit.Type.PERM );
<add> }
<add>
<add>
<add> @Test
<add> public void testAddOrgUnitAscendants()
<add> {
<add> DelegatedMgrImplTest.addOrgUnitAscendant( "ADD-ORGS-USR-TR7-ASC", OrgUnitTestData.ORGS_USR_TO7_ASC,
<add> OrgUnit.Type.USER );
<add> DelegatedMgrImplTest.addOrgUnitAscendant( "ADD-ORGS-PRM-TR7-ASC", OrgUnitTestData.ORGS_PRM_TO7_ASC,
<add> OrgUnit.Type.PERM );
<add> }
<add>
<add>
<add> @Test
<add> public void testAddRole()
<add> {
<add> // Add the needed data for this test
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO2", OrgUnitTestData.ORGS_USR_TO2 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_TO1", OrgUnitTestData.ORGS_TO1 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_ORGS_PRM_TO3", OrgUnitTestData.ORGS_PRM_TO3 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO4", OrgUnitTestData.ORGS_PRM_TO4 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO5", OrgUnitTestData.ORGS_USR_TO5 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO5", OrgUnitTestData.ORGS_PRM_TO5 );
<add>
<add> // The test itself
<add> // public Role setRole(Role role)
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR14_ARBAC", RoleTestData.ROLES_TR14_ARBAC );
<add> AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR14_ARBAC", RoleTestData.ROLES_TR14_ARBAC );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
<add> AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
<add>
<add> DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR1", AdminRoleTestData.AROLES_TR1, true );
<add> DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR2", AdminRoleTestData.AROLES_TR2, true );
<add> DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR3", AdminRoleTestData.AROLES_TR3, true );
<add> DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR6", AdminRoleTestData.AROLES_TR6_HIER, true );
<add> }
<add>
<add>
<add> @Test
<add> public void testUpdateAdminRole()
<add> {
<add> // Add the needed data for this test
<add> DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR3", AdminRoleTestData.AROLES_TR3, true );
<add>
<add> // The test itself
<add> // public Role updateRole(Role role)
<add> DelegatedMgrImplTest.updateAdminRoles( "UPD-ADMRLS TR3_UPD", AdminRoleTestData.AROLES_TR3_UPD, true );
<add> }
<add>
<add>
<add> @Test
<add> public void testAddAdminRoleDescendant()
<add> {
<add> DelegatedMgrImplTest.addAdminRoleDescendant( "ADD-ARLS-TR5-DESC", AdminRoleTestData.AROLES_TR5_DSC );
<add> }
<add>
<add>
<add> @Test
<add> public void testAddAdminRoleAscendants()
<add> {
<add> DelegatedMgrImplTest.addAdminRoleAscendant( "ADD-ARLS-TR4-ASC", AdminRoleTestData.AROLES_TR4_ASC );
<add> }
<add>
<add>
<add> @Test
<add> public void testAddAdminRoleInheritance()
<add> {
<add> // Add the needed data for this test
<add> DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR6", AdminRoleTestData.AROLES_TR6_HIER, true );
<add>
<add> // The test itself
<add> DelegatedMgrImplTest.addInheritedAdminRoles( "ADD-ARLS-TR6-HIER", AdminRoleTestData.AROLES_TR6_HIER );
<add> }
<add>
<add>
<add> @Test
<add> public void testAddUser()
<add> {
<add> // Add the needed data for this test
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_TO1", OrgUnitTestData.ORGS_TO1 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO5", OrgUnitTestData.ORGS_USR_TO5 );
<add>
<add> // The test itself
<add> // public User addUser(User user)
<add> // the admin user must be added before the "addUsers" can be called:
<add> //AdminMgrImplTest.addAdminUser("ADD-USRS TU0", UserTestData.USERS_TU0[0]);
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU16_ARBAC", UserTestData.USERS_TU16_ARBAC, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU16B_ARBAC", UserTestData.USERS_TU16B_ARBAC, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU16A_ARBAC", UserTestData.USERS_TU17A_ARBAC, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU16U_ARBAC", UserTestData.USERS_TU17U_ARBAC, true );
<add> }
<add>
<add>
<add> @Test
<add> public void testAddPermission()
<add> {
<add> // Add the needed data for this test
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO5", OrgUnitTestData.ORGS_PRM_TO5 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
<add>
<add> // The test itself
<add> // public Permission addPermObj(Permission pOp)
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB5", PermTestData.OBJS_TOB5, true, false );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS ARBAC1", PermTestData.ARBAC_OBJS_1, true, false );
<add> AdminMgrImplTest
<add> .addPermOps( "ADD-OPS ARBAC1", PermTestData.ARBAC_OBJS_1, PermTestData.ARBAC_OPS_1, true, false );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS ARBAC2", PermTestData.ARBAC_OBJ2, true, false );
<add> AdminMgrImplTest.addPermOps( "ADD-OPS ARBAC2", PermTestData.ARBAC_OBJ2, PermTestData.ARBAC_OPS_2, true, false );
<add> }
<add>
<add>
<add> @Test
<add> public void testAssignAdminUser()
<add> {
<add> // Add the needed data for this test
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO2", OrgUnitTestData.ORGS_USR_TO2 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_TO1", OrgUnitTestData.ORGS_TO1 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_ORGS_PRM_TO3", OrgUnitTestData.ORGS_PRM_TO3 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO4", OrgUnitTestData.ORGS_PRM_TO4 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO5", OrgUnitTestData.ORGS_USR_TO5 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO5", OrgUnitTestData.ORGS_PRM_TO5 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR14_ARBAC", RoleTestData.ROLES_TR14_ARBAC );
<add> AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR14_ARBAC", RoleTestData.ROLES_TR14_ARBAC );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
<add> AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
<add> DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR1", AdminRoleTestData.AROLES_TR1, true );
<add> DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR2", AdminRoleTestData.AROLES_TR2, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU16_ARBAC", UserTestData.USERS_TU16_ARBAC, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU16A_ARBAC", UserTestData.USERS_TU17A_ARBAC, true );
<add>
<add> // The test itself
<add> // public void assignUser(User user, Role role)
<add> DelegatedMgrImplTest.assignAdminUsers( "ASGN-USRS TU16 TR1", UserTestData.USERS_TU16_ARBAC,
<add> AdminRoleTestData.AROLES_TR1, true );
<add> DelegatedMgrImplTest.assignAdminUserRole( "ASGN-USR TU17A TR2", UserTestData.USERS_TU17A_ARBAC,
<add> AdminRoleTestData.AROLES_TR2, true );
<add> }
<add>
<add>
<add> @Test
<add> public void testGrantPermissionRole()
<add> {
<add> // Add the needed data for this test
<add> // From testAddUser
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_TO1", OrgUnitTestData.ORGS_TO1 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO5", OrgUnitTestData.ORGS_USR_TO5 );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU16_ARBAC", UserTestData.USERS_TU16_ARBAC, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU16B_ARBAC", UserTestData.USERS_TU16B_ARBAC, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU16A_ARBAC", UserTestData.USERS_TU17A_ARBAC, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU16U_ARBAC", UserTestData.USERS_TU17U_ARBAC, true );
<add>
<add> // From testAddPermission
<add> // Add the needed data for this test
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO5", OrgUnitTestData.ORGS_PRM_TO5 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
<add>
<add> // public Permission addPermObj(Permission pOp)
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB5", PermTestData.OBJS_TOB5, true, false );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS ARBAC1", PermTestData.ARBAC_OBJS_1, true, false );
<add> AdminMgrImplTest
<add> .addPermOps( "ADD-OPS ARBAC1", PermTestData.ARBAC_OBJS_1, PermTestData.ARBAC_OPS_1, true, false );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS ARBAC2", PermTestData.ARBAC_OBJ2, true, false );
<add> AdminMgrImplTest.addPermOps( "ADD-OPS ARBAC2", PermTestData.ARBAC_OBJ2, PermTestData.ARBAC_OPS_2, true, false );
<add>
<add> // From testAssignAdminUser
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO2", OrgUnitTestData.ORGS_USR_TO2 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_ORGS_PRM_TO3", OrgUnitTestData.ORGS_PRM_TO3 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO4", OrgUnitTestData.ORGS_PRM_TO4 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR14_ARBAC", RoleTestData.ROLES_TR14_ARBAC );
<add> AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR14_ARBAC", RoleTestData.ROLES_TR14_ARBAC );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
<add> AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
<add> DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR1", AdminRoleTestData.AROLES_TR1, true );
<add> DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR2", AdminRoleTestData.AROLES_TR2, true );
<add>
<add> // The test itself
<add> // public void grantPermission(Permission pOp, Role role)
<add> AdminMgrImplTest.addRoleGrants( "GRNT-APRMS ARTR2 AROBJ1 AROPS1", AdminRoleTestData.AROLES_TR2,
<add> PermTestData.ARBAC_OBJS_1, PermTestData.ARBAC_OPS_1, true, false );
<add> }
<add>
<add>
<add> // AdminMgr RBAC APIs:
<add> @Test
<add> public void testAdminMgrAddRole()
<add> {
<add> // public Role addRole(Role role)
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR4", RoleTestData.ROLES_TR4 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR5_HIER", RoleTestData.ROLES_TR5_HIER );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR5B", RoleTestData.ROLES_TR5B );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR8_SSD", RoleTestData.ROLES_TR8_SSD );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR9_SSD", RoleTestData.ROLES_TR9_SSD );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR10_SSD", RoleTestData.ROLES_TR10_SSD );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR8_DSD", RoleTestData.ROLES_TR8_DSD );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR9_DSD", RoleTestData.ROLES_TR9_DSD );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR10_DSD", RoleTestData.ROLES_TR10_DSD );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR16_SD", RoleTestData.ROLES_TR16_SD );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR17_DSD_BRUNO", RoleTestData.ROLES_TR17_DSD_BRUNO );
<add> }
<add>
<add>
<add> @Test
<add> public void testAdminMgrAddRoleInheritance()
<add> {
<add> // Add the needed data for this test
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR4", RoleTestData.ROLES_TR4 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR5_HIER", RoleTestData.ROLES_TR5_HIER );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR5B", RoleTestData.ROLES_TR5B );
<add>
<add> // The test itself
<add> //TODO: Test goes here...
<add> // public void addInheritance(Role parentRole, Role childRole)
<add> AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR5_HIER", RoleTestData.ROLES_TR5_HIER );
<add> AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR5B", RoleTestData.ROLES_TR5B );
<add> }
<add>
<add>
<add> @Test
<add> public void testAdminMgrddRoleDescendant()
<add> {
<add> //TODO: Test goes here...
<add> // public void addDescendant(Role parentRole, Role childRole)
<add> AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR6-DESC", RoleTestData.ROLES_TR6_DESC );
<add> AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR11-DESC-SSD", RoleTestData.ROLES_TR11_DESC_SSD );
<add> AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR12-DESC-SSD", RoleTestData.ROLES_TR12_DESC_SSD );
<add> AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR13-DESC-SSD", RoleTestData.ROLES_TR13_DESC_SSD );
<add> AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR11-DESC-DSD", RoleTestData.ROLES_TR11_DESC_DSD );
<add> AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR12-DESC-DSD", RoleTestData.ROLES_TR12_DESC_DSD );
<add> AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR13-DESC-DSD", RoleTestData.ROLES_TR13_DESC_DSD );
<add> }
<add>
<add>
<add> @Test
<add> public void testAdminMgrAddRoleAscendants()
<add> {
<add> //TODO: Test goes here...
<add> // public void addDescendant(Role parentRole, Role childRole)
<add> AdminMgrImplTest.addRoleAscendant( "ADD-RLS-TR7-ASC", RoleTestData.ROLES_TR7_ASC );
<add> }
<add>
<add>
<add> @Test
<add> public void testAdminMgrCreateSsdSet()
<add> {
<add> // Add the needed data for this test
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR8_SSD", RoleTestData.ROLES_TR8_SSD );
<add> AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR11-DESC-SSD", RoleTestData.ROLES_TR11_DESC_SSD );
<add> AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR12-DESC-SSD", RoleTestData.ROLES_TR12_DESC_SSD );
<add> AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR13-DESC-SSD", RoleTestData.ROLES_TR13_DESC_SSD );
<add>
<add> // The test itself
<add> // public SDSet createSsdSet(SDSet ssdSet)
<add> AdminMgrImplTest.createSsdSet( "ADD-SSD T1", RoleTestData.SSD_T1 );
<add> AdminMgrImplTest.createSsdSet( "ADD-SSD T4", RoleTestData.SSD_T4 );
<add> AdminMgrImplTest.createSsdSet( "ADD-SSD T5", RoleTestData.SSD_T5 );
<add> AdminMgrImplTest.createSsdSet( "ADD-SSD T6", RoleTestData.SSD_T6 );
<add> }
<add>
<add>
<add> @Test
<add> public void testAdminMgrCreateDsdSet()
<add> {
<add> // Add the needed data for this test
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR8_DSD", RoleTestData.ROLES_TR8_DSD );
<add> AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR11-DESC-DSD", RoleTestData.ROLES_TR11_DESC_DSD );
<add> AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR12-DESC-DSD", RoleTestData.ROLES_TR12_DESC_DSD );
<add> AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR13-DESC-DSD", RoleTestData.ROLES_TR13_DESC_DSD );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR17_DSD_BRUNO", RoleTestData.ROLES_TR17_DSD_BRUNO );
<add>
<add> // The test itself
<add> // public SDSet createDsdSet(SDSet dsdSet)
<add> AdminMgrImplTest.createDsdSet( "ADD-DSD T1", RoleTestData.DSD_T1 );
<add> AdminMgrImplTest.createDsdSet( "ADD-DSD T4", RoleTestData.DSD_T4 );
<add> AdminMgrImplTest.createDsdSet( "ADD-DSD T5", RoleTestData.DSD_T5 );
<add> AdminMgrImplTest.createDsdSet( "ADD-DSD T6", RoleTestData.DSD_T6 );
<add> AdminMgrImplTest.createDsdSet( "ADD-DSD T8 BRUNO", RoleTestData.DSD_T8_BRUNO );
<add> }
<add>
<add>
<add> @Test
<add> public void testAdminMgrAddSsdRoleMember()
<add> {
<add> // Add the needed data for this test
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR9_SSD", RoleTestData.ROLES_TR9_SSD );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR10_SSD", RoleTestData.ROLES_TR10_SSD );
<add>
<add> // The test itself
<add> // public SDSet addSsdRoleMember(SDSet ssdSet, Role role)
<add> AdminMgrImplTest.addSsdRoleMember( "ADD-MEM-SSD T2 TR9", RoleTestData.SSD_T2, RoleTestData.ROLES_TR9_SSD );
<add> AdminMgrImplTest.addSsdRoleMember( "ADD-MEM-SSD T3 TR10", RoleTestData.SSD_T3, RoleTestData.ROLES_TR10_SSD );
<add> }
<add>
<add>
<add> @Test
<add> public void testAdminMgrAddDsdRoleMember()
<add> {
<add> // Add the needed data for this test
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR9_DSD", RoleTestData.ROLES_TR9_DSD );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR10_DSD", RoleTestData.ROLES_TR10_DSD );
<add>
<add> // The test itself
<add> // public SDSet addDsdRoleMember(SDSet dsdSet, Role role)
<add> AdminMgrImplTest.addDsdRoleMember( "ADD-MEM-DSD T2 TR9", RoleTestData.DSD_T2, RoleTestData.ROLES_TR9_DSD );
<add> AdminMgrImplTest.addDsdRoleMember( "ADD-MEM-DSD T3 TR10", RoleTestData.DSD_T3, RoleTestData.ROLES_TR10_DSD );
<add>
<add> }
<add>
<add>
<add> @Test
<add> public void testAdminMgrSsdCardinality()
<add> {
<add> // Add the needed data for this test
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR16_SD", RoleTestData.ROLES_TR16_SD );
<add>
<add> // The test itself
<add> AdminMgrImplTest.setSsdCardinality( "CARD-SSD T7 TR16", RoleTestData.SSD_T7, RoleTestData.ROLES_TR16_SD );
<add> }
<add>
<add>
<add> @Test
<add> public void testAdminMgrDsdCardinality()
<add> {
<add> // Add the needed data for this test
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR16_SD", RoleTestData.ROLES_TR16_SD );
<add>
<add> // The test itself
<add> AdminMgrImplTest.setDsdCardinality( "CARD-DSD T7 TR16", RoleTestData.DSD_T7, RoleTestData.ROLES_TR16_SD );
<add> }
<add>
<add>
<add> @Test
<add> public void testAdminMgrUpdateRole()
<add> {
<add> // Add the needed data for this test
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR4", RoleTestData.ROLES_TR4 );
<add>
<add> // The test itself
<add> // public Role updateRole(Role role)
<add> AdminMgrImplTest.updateRoles( "UPD-RLS TR4_UPD", RoleTestData.ROLES_TR4_UPD );
<add> }
<add>
<add>
<add> @Test
<add> public void testAdminMgrAddUser()
<add> {
<add> // Add the needed data for this test
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add> AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR6-DESC", RoleTestData.ROLES_TR6_DESC );
<add> AdminMgrImplTest.addRoleAscendant( "ADD-RLS-TR7-ASC", RoleTestData.ROLES_TR7_ASC );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR17_DSD_BRUNO", RoleTestData.ROLES_TR17_DSD_BRUNO );
<add>
<add> // The test itself
<add> // public User addUser(User user)
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU2", UserTestData.USERS_TU2, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU5", UserTestData.USERS_TU5, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU6", UserTestData.USERS_TU6, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU7_HIER", UserTestData.USERS_TU7_HIER, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU8_SSD", UserTestData.USERS_TU8_SSD, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU9_SSD_HIER", UserTestData.USERS_TU9_SSD_HIER, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU10_SSD_HIER", UserTestData.USERS_TU10_SSD_HIER, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU11_SSD_HIER", UserTestData.USERS_TU11_SSD_HIER, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU12_DSD", UserTestData.USERS_TU12_DSD, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU13_DSD_HIER", UserTestData.USERS_TU13_DSD_HIER, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU14_DSD_HIER", UserTestData.USERS_TU14_DSD_HIER, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU15_DSD_HIER", UserTestData.USERS_TU15_DSD_HIER, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU18 TR6_DESC", UserTestData.USERS_TU18U_TR6_DESC, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU19 TR7_ASC", UserTestData.USERS_TU19U_TR7_ASC, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU20 TR5_HIER", UserTestData.USERS_TU20U_TR5B, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU21 DSD_BRUNO", UserTestData.USERS_TU21_DSD_BRUNO, true );
<add> }
<add>
<add>
<add> @Test
<add> public void testAdminMgrUpdateUser()
<add> {
<add> // Add the needed data for this test
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
<add>
<add> // The test itself
<add> // public User updateUser(User user)
<add> AdminMgrImplTest.updateUsers( "UPD USERS TU1_UPD", UserTestData.USERS_TU1_UPD );
<add> }
<add>
<add>
<add> @Test
<add> public void testAdminMgrAssignUser()
<add> {
<add> // Add the needed data for this test
<add> // From testAddOrgUnit
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_TO1", OrgUnitTestData.ORGS_TO1 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO2", OrgUnitTestData.ORGS_USR_TO2 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_ORGS_PRM_TO3", OrgUnitTestData.ORGS_PRM_TO3 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO4", OrgUnitTestData.ORGS_PRM_TO4 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO5", OrgUnitTestData.ORGS_USR_TO5 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO5", OrgUnitTestData.ORGS_PRM_TO5 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
<add>
<add> // From testAddRole Delegated
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR14_ARBAC", RoleTestData.ROLES_TR14_ARBAC );
<add> AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR14_ARBAC", RoleTestData.ROLES_TR14_ARBAC );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
<add> AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
<add> DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR1", AdminRoleTestData.AROLES_TR1, true );
<add> DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR2", AdminRoleTestData.AROLES_TR2, true );
<add> DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR3", AdminRoleTestData.AROLES_TR3, true );
<add> DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR6", AdminRoleTestData.AROLES_TR6_HIER, true );
<add>
<add> // From testAddUser
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU16_ARBAC", UserTestData.USERS_TU16_ARBAC, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU16B_ARBAC", UserTestData.USERS_TU16B_ARBAC, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU16A_ARBAC", UserTestData.USERS_TU17A_ARBAC, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU16U_ARBAC", UserTestData.USERS_TU17U_ARBAC, true );
<add>
<add> // From testAddRole Admin
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR4", RoleTestData.ROLES_TR4 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR5_HIER", RoleTestData.ROLES_TR5_HIER );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR5B", RoleTestData.ROLES_TR5B );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR8_SSD", RoleTestData.ROLES_TR8_SSD );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR9_SSD", RoleTestData.ROLES_TR9_SSD );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR10_SSD", RoleTestData.ROLES_TR10_SSD );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR8_DSD", RoleTestData.ROLES_TR8_DSD );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR9_DSD", RoleTestData.ROLES_TR9_DSD );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR10_DSD", RoleTestData.ROLES_TR10_DSD );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR16_SD", RoleTestData.ROLES_TR16_SD );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR17_DSD_BRUNO", RoleTestData.ROLES_TR17_DSD_BRUNO );
<add>
<add> // From testAddRoleDescendant
<add> AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR6-DESC", RoleTestData.ROLES_TR6_DESC );
<add> AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR11-DESC-SSD", RoleTestData.ROLES_TR11_DESC_SSD );
<add> AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR12-DESC-SSD", RoleTestData.ROLES_TR12_DESC_SSD );
<add> AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR13-DESC-SSD", RoleTestData.ROLES_TR13_DESC_SSD );
<add> AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR11-DESC-DSD", RoleTestData.ROLES_TR11_DESC_DSD );
<add> AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR12-DESC-DSD", RoleTestData.ROLES_TR12_DESC_DSD );
<add> AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR13-DESC-DSD", RoleTestData.ROLES_TR13_DESC_DSD );
<add>
<add> // From testCreateSsdSet
<add> AdminMgrImplTest.createSsdSet( "ADD-SSD T1", RoleTestData.SSD_T1 );
<add> AdminMgrImplTest.createSsdSet( "ADD-SSD T4", RoleTestData.SSD_T4 );
<add> AdminMgrImplTest.createSsdSet( "ADD-SSD T5", RoleTestData.SSD_T5 );
<add> AdminMgrImplTest.createSsdSet( "ADD-SSD T6", RoleTestData.SSD_T6 );
<add>
<add> // From testAddUser (Admin)
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU2", UserTestData.USERS_TU2, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
<add>
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU7_HIER", UserTestData.USERS_TU7_HIER, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU8_SSD", UserTestData.USERS_TU8_SSD, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU9_SSD_HIER", UserTestData.USERS_TU9_SSD_HIER, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU10_SSD_HIER", UserTestData.USERS_TU10_SSD_HIER, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU11_SSD_HIER", UserTestData.USERS_TU11_SSD_HIER, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU12_DSD", UserTestData.USERS_TU12_DSD, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU13_DSD_HIER", UserTestData.USERS_TU13_DSD_HIER, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU14_DSD_HIER", UserTestData.USERS_TU14_DSD_HIER, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU15_DSD_HIER", UserTestData.USERS_TU15_DSD_HIER, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU20 TR5_HIER", UserTestData.USERS_TU20U_TR5B, true );
<add>
<add> // The test itself
<add> // public void assignUser(User user, Role role)
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU1 TR1", UserTestData.USERS_TU1, RoleTestData.ROLES_TR1, false );
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2, true );
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3, true );
<add> AdminMgrImplTest.assignUsersH( "ASGN-USRS_H TU7 HIER TR5 HIER", UserTestData.USERS_TU7_HIER,
<add> RoleTestData.ROLES_TR5_HIER, true );
<add> AdminMgrImplTest.assignUsersH( "ASGN-USRS_H TU20 TR5B HIER", UserTestData.USERS_TU20U_TR5B,
<add> RoleTestData.ROLES_TR5B, true );
<add> AdminMgrImplTest.assignUsersSSD( "ASGN-USRS_SSDT1 TU8 SSD_T1", UserTestData.USERS_TU8_SSD, RoleTestData.SSD_T1 );
<add> AdminMgrImplTest.assignUsersSSD( "ASGN-USRS_SSDT4B TU9 SSD_T4_B", UserTestData.USERS_TU9_SSD_HIER,
<add> RoleTestData.SSD_T4_B );
<add> AdminMgrImplTest.assignUsersSSD( "ASGN-USRS_SSDT5B TU10 SSD_T5_B", UserTestData.USERS_TU10_SSD_HIER,
<add> RoleTestData.SSD_T5_B );
<add> AdminMgrImplTest.assignUsersSSD( "ASGN-USRS_SSDT6B TU11 SSD_T6_B", UserTestData.USERS_TU11_SSD_HIER,
<add> RoleTestData.SSD_T6_B );
<add> AdminMgrImplTest.assignUsersDSD( "ASGN-USRS_DSDT1 TU8 DSD_T1", UserTestData.USERS_TU8_SSD, RoleTestData.DSD_T1 );
<add> AdminMgrImplTest.assignUsersDSD( "ASGN-USRS_DSDT4B TU9 DSD_T4_B", UserTestData.USERS_TU9_SSD_HIER,
<add> RoleTestData.DSD_T4_B );
<add> AdminMgrImplTest.assignUsersDSD( "ASGN-USRS_DSDT5B TU10 DSD_T5_B", UserTestData.USERS_TU10_SSD_HIER,
<add> RoleTestData.DSD_T5_B );
<add> AdminMgrImplTest.assignUsersDSD( "ASGN-USRS_DSDT6B TU11 DSD_T6_B", UserTestData.USERS_TU11_SSD_HIER,
<add> RoleTestData.DSD_T6_B );
<add> AdminMgrImplTest.assignUsersDSD( "ASGN-USRS_DSDT1 TU12 DSD_T1", UserTestData.USERS_TU12_DSD,
<add> RoleTestData.DSD_T1 );
<add> AdminMgrImplTest.assignUsersDSD( "ASGN-USRS_DSDT4B TU13 DSD_T4_B", UserTestData.USERS_TU13_DSD_HIER,
<add> RoleTestData.DSD_T4_B );
<add> AdminMgrImplTest.assignUsersDSD( "ASGN-USRS_DSDT5B TU14 DSD_T5_B", UserTestData.USERS_TU14_DSD_HIER,
<add> RoleTestData.DSD_T5_B );
<add> AdminMgrImplTest.assignUsersDSD( "ASGN-USRS_DSDT6B TU15 DSD_T6_B", UserTestData.USERS_TU15_DSD_HIER,
<add> RoleTestData.DSD_T6_B );
<add> }
<add>
<add>
<add> @Test
<add> public void testAdminMgrAddPermissionObj() throws SecurityException
<add> {
<add> // Add the needed data for this test
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
<add>
<add> // The test itself
<add> // public Permission addPermObj(Permission pOp)
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB1", PermTestData.OBJS_TOB1, true, false );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB2", PermTestData.OBJS_TOB2, true, false );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB3", PermTestData.OBJS_TOB3, true, false );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB4", PermTestData.OBJS_TOB4, true, false );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB6", PermTestData.OBJS_TOB6, true, false );
<add> }
<add>
<add>
<add> @Test
<add> public void testAdminMgrUpdatePermissionObj() throws SecurityException
<add> {
<add> // Add the needed data for this test
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB4", PermTestData.OBJS_TOB4, true, false );
<add>
<add> // The test itself
<add> AdminMgrImplTest.updatePermObjs( "UPD-OBS TOB4_UPD", PermTestData.OBJS_TOB4_UPD, true );
<add> }
<add>
<add>
<add> @Test
<add> public void testAdminMgrAddPermissionOp()
<add> {
<add> // Add the needed data for this test
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB1", PermTestData.OBJS_TOB1, true, false );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB2", PermTestData.OBJS_TOB2, true, false );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB3", PermTestData.OBJS_TOB3, true, false );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB4", PermTestData.OBJS_TOB4, true, false );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB6", PermTestData.OBJS_TOB6, true, false );
<add>
<add> // The test itself
<add> // public PermObj addPermObj(PermObj pObj)
<add> AdminMgrImplTest.addPermOps( "ADD-OPS TOB1 TOP1", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1, true, false );
<add> AdminMgrImplTest.addPermOps( "ADD-OPS TOB2 TOP2", PermTestData.OBJS_TOB2, PermTestData.OPS_TOP2, true, false );
<add> AdminMgrImplTest.addPermOps( "ADD-OPS TOB3 TOP3", PermTestData.OBJS_TOB3, PermTestData.OPS_TOP3, true, false );
<add> AdminMgrImplTest.addPermOps( "ADD-OPS TOB4 TOP4", PermTestData.OBJS_TOB4, PermTestData.OPS_TOP4, true, false );
<add> AdminMgrImplTest.addPermOps( "ADD-OPS TOB6 TOP5", PermTestData.OBJS_TOB6, PermTestData.OPS_TOP5, true, false );
<add> }
<add>
<add>
<add> @Test
<add> public void testAdminMgrUpdatePermissionOp()
<add> {
<add> // Add the needed data for this test
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB1", PermTestData.OBJS_TOB1, true, false );
<add> AdminMgrImplTest.addPermOps( "ADD-OPS TOB1 TOP1", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1, true, false );
<add>
<add> // The test itself
<add> AdminMgrImplTest.updatePermOps( "UPD-OPS TOB1 TOP1_UPD", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1_UPD,
<add> true );
<add> }
<add>
<add>
<add> /**
<add> * AMT24
<add> *
<add> * @throws SecurityException
<add> */
<add> @Test
<add> public void testAdminMgrGrantPermissionRole()
<add> {
<add> // Add the needed data for this test
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB1", PermTestData.OBJS_TOB1, true, false );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB2", PermTestData.OBJS_TOB2, true, false );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB3", PermTestData.OBJS_TOB3, true, false );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB4", PermTestData.OBJS_TOB4, true, false );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB6", PermTestData.OBJS_TOB6, true, false );
<add> AdminMgrImplTest.addPermOps( "ADD-OPS TOB1 TOP1", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1, true, false );
<add> AdminMgrImplTest.addPermOps( "ADD-OPS TOB2 TOP2", PermTestData.OBJS_TOB2, PermTestData.OPS_TOP2, true, false );
<add> AdminMgrImplTest.addPermOps( "ADD-OPS TOB3 TOP3", PermTestData.OBJS_TOB3, PermTestData.OPS_TOP3, true, false );
<add> AdminMgrImplTest.addPermOps( "ADD-OPS TOB4 TOP4", PermTestData.OBJS_TOB4, PermTestData.OPS_TOP4, true, false );
<add> AdminMgrImplTest.addPermOps( "ADD-OPS TOB6 TOP5", PermTestData.OBJS_TOB6, PermTestData.OPS_TOP5, true, false );
<add> AdminMgrImplTest.updatePermOps( "UPD-OPS TOB1 TOP1_UPD", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1_UPD,
<add> true );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR5_HIER", RoleTestData.ROLES_TR5_HIER );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR5B", RoleTestData.ROLES_TR5B );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU20 TR5_HIER", UserTestData.USERS_TU20U_TR5B, true );
<add>
<add> // The test itself
<add> // public void grantPermission(Permission pOp, Role role)
<add> AdminMgrImplTest.addRoleGrants( "GRNT-PRMS TR1 TOB1 TOP1", RoleTestData.ROLES_TR1, PermTestData.OBJS_TOB1,
<add> PermTestData.OPS_TOP1, true, false );
<add> AdminMgrImplTest.addRoleGrants( "GRNT-PRMS TR2 TOB2 TOP2", RoleTestData.ROLES_TR2, PermTestData.OBJS_TOB2,
<add> PermTestData.OPS_TOP2, true, false );
<add> AdminMgrImplTest.addRoleGrants( "GRNT-PRMS TR3 TOB3 TOP3", RoleTestData.ROLES_TR3, PermTestData.OBJS_TOB3,
<add> PermTestData.OPS_TOP3, true, false );
<add> AdminMgrImplTest.addRoleGrantsH( "GRNT-PRMS_H ROLES_TR5_HIER TOB4 TOP4", RoleTestData.ROLES_TR5_HIER,
<add> PermTestData.OBJS_TOB4,
<add> PermTestData.OPS_TOP4 );
<add> AdminMgrImplTest.addRoleGrantsHB( "GRNT-PRMS_HB USERS TU20 ROLES_TR5B TOB6 TOP5",
<add> UserTestData.USERS_TU20U_TR5B,
<add> RoleTestData.ROLES_TR5B, PermTestData.OBJS_TOB6, PermTestData.OPS_TOP5 );
<add> }
<add>
<add>
<add> @Test
<add> public void testAdminMgrGrantPermissionUser()
<add> {
<add> // Add the needed data for this test
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB1", PermTestData.OBJS_TOB1, true, false );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
<add> AdminMgrImplTest.addPermOps( "ADD-OPS TOB1 TOP1", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1, true, false );
<add>
<add> // The test itself
<add> // public void grantPermission(Permission pOp, User user)
<add> AdminMgrImplTest.addUserGrants( "GRNT-PRMS TU1 TOB1 TOP1", UserTestData.USERS_TU1, PermTestData.OBJS_TOB1,
<add> PermTestData.OPS_TOP1 );
<add> }
<add>
<add>
<add> /***********************************************************/
<add> /* 3. Interrogation */
<add> /***********************************************************/
<add> // DelReviewMgr ARBAC:
<add> @Test
<add> public void testReadOrgUnit()
<add> {
<add> // Add the needed data for this test
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_TO1", OrgUnitTestData.ORGS_TO1 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_ORGS_PRM_TO3", OrgUnitTestData.ORGS_PRM_TO3 );
<add>
<add> // The test itself
<add> // public Role readRole(Role role)
<add> DelegatedMgrImplTest.readOrgUnits( "RD ORGS_TO1", OrgUnitTestData.ORGS_TO1 );
<add> DelegatedMgrImplTest.readOrgUnits( "RD ORGS_PRM_TO3", OrgUnitTestData.ORGS_PRM_TO3 );
<add> }
<add>
<add>
<add> @Test
<add> public void testSearchOrgUnits()
<add> {
<add> // Add the needed data for this test
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_TO1", OrgUnitTestData.ORGS_TO1 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_ORGS_PRM_TO3", OrgUnitTestData.ORGS_PRM_TO3 );
<add>
<add> // The test itself
<add> DelegatedMgrImplTest.searchOrgUnits( "SRCH ORGS_TO1",
<add> TestUtils.getSrchValue( OrgUnitTestData.getName( OrgUnitTestData.ORGS_TO1[0] ) ), OrgUnitTestData.ORGS_TO1 );
<add> DelegatedMgrImplTest.searchOrgUnits( "SRCH ORGS_PRM_TO3",
<add> TestUtils.getSrchValue( OrgUnitTestData.getName( OrgUnitTestData.ORGS_PRM_TO3[0] ) ),
<add> OrgUnitTestData.ORGS_PRM_TO3 );
<add> }
<add>
<add>
<add> @Test
<add> public void testReadAdminRole()
<add> {
<add> // Add the needed data for this test
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO2", OrgUnitTestData.ORGS_USR_TO2 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_TO1", OrgUnitTestData.ORGS_TO1 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_ORGS_PRM_TO3", OrgUnitTestData.ORGS_PRM_TO3 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO4", OrgUnitTestData.ORGS_PRM_TO4 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO5", OrgUnitTestData.ORGS_USR_TO5 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO5", OrgUnitTestData.ORGS_PRM_TO5 );
<add>
<add> // public Role setRole(Role role)
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR14_ARBAC", RoleTestData.ROLES_TR14_ARBAC );
<add> AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR14_ARBAC", RoleTestData.ROLES_TR14_ARBAC );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
<add> AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
<add>
<add> DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR1", AdminRoleTestData.AROLES_TR1, true );
<add> DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR2", AdminRoleTestData.AROLES_TR2, true );
<add> DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR3", AdminRoleTestData.AROLES_TR3, true );
<add> DelegatedMgrImplTest.updateAdminRoles( "UPD-ADMRLS TR3_UPD", AdminRoleTestData.AROLES_TR3_UPD, true );
<add>
<add> // The test itself
<add> // public Role readRole(Role role)
<add> DelegatedMgrImplTest.readAdminRoles( "RD-ADMRLS TR1", AdminRoleTestData.AROLES_TR1 );
<add> DelegatedMgrImplTest.readAdminRoles( "RD-ADMRLS TR2", AdminRoleTestData.AROLES_TR2 );
<add> DelegatedMgrImplTest.readAdminRoles( "RD-ADMRLS TR3_UPD", AdminRoleTestData.AROLES_TR3_UPD );
<add> }
<add>
<add>
<add> @Test
<add> public void testSearchAdminRole()
<add> {
<add> // Add the needed data for this test
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO2", OrgUnitTestData.ORGS_USR_TO2 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_TO1", OrgUnitTestData.ORGS_TO1 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_ORGS_PRM_TO3", OrgUnitTestData.ORGS_PRM_TO3 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO4", OrgUnitTestData.ORGS_PRM_TO4 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO5", OrgUnitTestData.ORGS_USR_TO5 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO5", OrgUnitTestData.ORGS_PRM_TO5 );
<add>
<add> // public Role setRole(Role role)
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR14_ARBAC", RoleTestData.ROLES_TR14_ARBAC );
<add> AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR14_ARBAC", RoleTestData.ROLES_TR14_ARBAC );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
<add> AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
<add>
<add> DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR1", AdminRoleTestData.AROLES_TR1, true );
<add> DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR2", AdminRoleTestData.AROLES_TR2, true );
<add> DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR3", AdminRoleTestData.AROLES_TR3, true );
<add> DelegatedMgrImplTest.updateAdminRoles( "UPD-ADMRLS TR3_UPD", AdminRoleTestData.AROLES_TR3_UPD, true );
<add>
<add> // The test itself
<add> DelegatedMgrImplTest.searchAdminRoles( "SRCH-ADMRLS TR1",
<add> TestUtils.getSrchValue( RoleTestData.getName( AdminRoleTestData.AROLES_TR1[0] ) ),
<add> AdminRoleTestData.AROLES_TR1 );
<add> DelegatedMgrImplTest.searchAdminRoles( "SRCH-ADMRLS TR2",
<add> TestUtils.getSrchValue( RoleTestData.getName( AdminRoleTestData.AROLES_TR2[0] ) ),
<add> AdminRoleTestData.AROLES_TR2 );
<add> DelegatedMgrImplTest.searchAdminRoles( "SRCH-ADMRLS TR3",
<add> TestUtils.getSrchValue( RoleTestData.getName( AdminRoleTestData.AROLES_TR3_UPD[0] ) ),
<add> AdminRoleTestData.AROLES_TR3_UPD );
<add> }
<add>
<add>
<add> // ReviewMgr RBAC:
<add> @Test
<add> public void testReadRole()
<add> {
<add> // Add the needed data for this test
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR4", RoleTestData.ROLES_TR4 );
<add> AdminMgrImplTest.updateRoles( "UPD-RLS TR4_UPD", RoleTestData.ROLES_TR4_UPD );
<add>
<add> // The test itself
<add> // public Role readRole(Role role)
<add> ReviewMgrImplTest.readRoles( "RD-RLS TR1", RoleTestData.ROLES_TR1 );
<add> ReviewMgrImplTest.readRoles( "RD-RLS TR2", RoleTestData.ROLES_TR2 );
<add> ReviewMgrImplTest.readRoles( "RD-RLS TR3", RoleTestData.ROLES_TR3 );
<add> ReviewMgrImplTest.readRoles( "RD-RLS TR4_UPD", RoleTestData.ROLES_TR4_UPD );
<add> }
<add>
<add>
<add> /**
<add> * RMT06
<add> *
<add> * @throws us.jts.fortress.SecurityException
<add> */
<add> @Test
<add> public void testFindRoles()
<add> {
<add> // Add the needed data for this test
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR4", RoleTestData.ROLES_TR4 );
<add> AdminMgrImplTest.updateRoles( "UPD-RLS TR4_UPD", RoleTestData.ROLES_TR4_UPD );
<add>
<add> // The test itself
<add> // public List<Role> findRoles(String searchVal)
<add> ReviewMgrImplTest.searchRoles( "SRCH-RLS TR1",
<add> TestUtils.getSrchValue( RoleTestData.getName( RoleTestData.ROLES_TR1[0] ) ),
<add> RoleTestData.ROLES_TR1 );
<add> ReviewMgrImplTest.searchRoles( "SRCH-RLS TR2",
<add> TestUtils.getSrchValue( RoleTestData.getName( RoleTestData.ROLES_TR2[0] ) ),
<add> RoleTestData.ROLES_TR2 );
<add> ReviewMgrImplTest.searchRoles( "SRCH-RLS TR3",
<add> TestUtils.getSrchValue( RoleTestData.getName( RoleTestData.ROLES_TR3[0] ) ),
<add> RoleTestData.ROLES_TR3 );
<add> ReviewMgrImplTest.searchRoles( "SRCH-RLS TR4_UPD",
<add> TestUtils.getSrchValue( RoleTestData.getName( RoleTestData.ROLES_TR4[0] ) ),
<add> RoleTestData.ROLES_TR4_UPD );
<add> }
<add>
<add>
<add> @Test
<add> public void testFindRoleNms()
<add> {
<add> // Add the needed data for this test
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR4", RoleTestData.ROLES_TR4 );
<add> AdminMgrImplTest.updateRoles( "UPD-RLS TR4_UPD", RoleTestData.ROLES_TR4_UPD );
<add>
<add> // The test itself
<add> // public List<String> findRoles(String searchVal, int limit)
<add> ReviewMgrImplTest.searchRolesNms( "SRCH-RLNMS TR1",
<add> TestUtils.getSrchValue( RoleTestData.getName( RoleTestData.ROLES_TR1[0] ) ),
<add> RoleTestData.ROLES_TR1 );
<add> ReviewMgrImplTest.searchRolesNms( "SRCH-RLNMS TR2",
<add> TestUtils.getSrchValue( RoleTestData.getName( RoleTestData.ROLES_TR2[0] ) ),
<add> RoleTestData.ROLES_TR2 );
<add> ReviewMgrImplTest.searchRolesNms( "SRCH-RLNMS TR3",
<add> TestUtils.getSrchValue( RoleTestData.getName( RoleTestData.ROLES_TR3[0] ) ),
<add> RoleTestData.ROLES_TR3 );
<add> ReviewMgrImplTest.searchRolesNms( "SRCH-RLNMS TR4_UPD",
<add> TestUtils.getSrchValue( RoleTestData.getName( RoleTestData.ROLES_TR4[0] ) ), RoleTestData.ROLES_TR4_UPD );
<add> }
<add>
<add>
<add> @Test
<add> public void testReadUser()
<add> {
<add> // Add the needed data for this test
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
<add> AdminMgrImplTest.updateUsers( "UPD USERS TU1_UPD", UserTestData.USERS_TU1_UPD );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU2", UserTestData.USERS_TU2, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU5", UserTestData.USERS_TU5, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU8_SSD", UserTestData.USERS_TU8_SSD, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU9_SSD_HIER", UserTestData.USERS_TU9_SSD_HIER, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU10_SSD_HIER", UserTestData.USERS_TU10_SSD_HIER, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU11_SSD_HIER", UserTestData.USERS_TU11_SSD_HIER, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU12_DSD", UserTestData.USERS_TU12_DSD, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU13_DSD_HIER", UserTestData.USERS_TU13_DSD_HIER, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU14_DSD_HIER", UserTestData.USERS_TU14_DSD_HIER, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU15_DSD_HIER", UserTestData.USERS_TU15_DSD_HIER, true );
<add>
<add> // The test itself
<add> // public User readUser(User user)
<add> ReviewMgrImplTest.readUsers( "READ-USRS TU1_UPD", UserTestData.USERS_TU1_UPD );
<add> ReviewMgrImplTest.readUsers( "READ-USRS TU3", UserTestData.USERS_TU3 );
<add> ReviewMgrImplTest.readUsers( "READ-USRS TU4", UserTestData.USERS_TU4 );
<add> ReviewMgrImplTest.readUsers( "READ-USRS TU5", UserTestData.USERS_TU5 );
<add> ReviewMgrImplTest.readUsers( "READ-USRS TU8", UserTestData.USERS_TU8_SSD );
<add> ReviewMgrImplTest.readUsers( "READ-USRS TU9", UserTestData.USERS_TU9_SSD_HIER );
<add> ReviewMgrImplTest.readUsers( "READ-USRS TU10", UserTestData.USERS_TU10_SSD_HIER );
<add> ReviewMgrImplTest.readUsers( "READ-USRS TU11", UserTestData.USERS_TU11_SSD_HIER );
<add> ReviewMgrImplTest.readUsers( "READ-USRS TU12", UserTestData.USERS_TU12_DSD );
<add> ReviewMgrImplTest.readUsers( "READ-USRS TU13", UserTestData.USERS_TU13_DSD_HIER );
<add> ReviewMgrImplTest.readUsers( "READ-USRS TU14", UserTestData.USERS_TU14_DSD_HIER );
<add> ReviewMgrImplTest.readUsers( "READ-USRS TU15", UserTestData.USERS_TU15_DSD_HIER );
<add> }
<add>
<add>
<add> @Test
<add> public void testFindUsers()
<add> {
<add> // Add the needed data for this test
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
<add> AdminMgrImplTest.updateUsers( "UPD USERS TU1_UPD", UserTestData.USERS_TU1_UPD );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU5", UserTestData.USERS_TU5, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU8_SSD", UserTestData.USERS_TU8_SSD, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU9_SSD_HIER", UserTestData.USERS_TU9_SSD_HIER, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU10_SSD_HIER", UserTestData.USERS_TU10_SSD_HIER, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU11_SSD_HIER", UserTestData.USERS_TU11_SSD_HIER, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU12_DSD", UserTestData.USERS_TU12_DSD, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU13_DSD_HIER", UserTestData.USERS_TU13_DSD_HIER, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU14_DSD_HIER", UserTestData.USERS_TU14_DSD_HIER, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU15_DSD_HIER", UserTestData.USERS_TU15_DSD_HIER, true );
<add>
<add> // The test itself
<add> // public List<User> findUsers(User user)
<add> ReviewMgrImplTest.searchUsers( "SRCH-USRS TU1_UPD",
<add> TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU1[0] ) ), UserTestData.USERS_TU1_UPD );
<add> ReviewMgrImplTest.searchUsers( "SRCH-USRS TU3",
<add> TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU3[0] ) ),
<add> UserTestData.USERS_TU3 );
<add> ReviewMgrImplTest.searchUsers( "SRCH-USRS TU4",
<add> TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU4[0] ) ),
<add> UserTestData.USERS_TU4 );
<add> ReviewMgrImplTest.searchUsers( "SRCH-USRS TU5",
<add> TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU5[0] ) ),
<add> UserTestData.USERS_TU5 );
<add> ReviewMgrImplTest.searchUsers( "SRCH-USRS TU8",
<add> TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU8_SSD[0] ) ),
<add> UserTestData.USERS_TU8_SSD );
<add> ReviewMgrImplTest.searchUsers( "SRCH-USRS TU9",
<add> TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU9_SSD_HIER[0] ) ),
<add> UserTestData.USERS_TU9_SSD_HIER );
<add> ReviewMgrImplTest.searchUsers( "SRCH-USRS TU10",
<add> TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU10_SSD_HIER[0] ) ),
<add> UserTestData.USERS_TU10_SSD_HIER );
<add> ReviewMgrImplTest.searchUsers( "SRCH-USRS TU11",
<add> TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU11_SSD_HIER[0] ) ),
<add> UserTestData.USERS_TU11_SSD_HIER );
<add> ReviewMgrImplTest.searchUsers( "SRCH-USRS TU12",
<add> TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU12_DSD[0] ) ),
<add> UserTestData.USERS_TU12_DSD );
<add> ReviewMgrImplTest.searchUsers( "SRCH-USRS TU13",
<add> TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU13_DSD_HIER[0] ) ),
<add> UserTestData.USERS_TU13_DSD_HIER );
<add> ReviewMgrImplTest.searchUsers( "SRCH-USRS TU14",
<add> TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU14_DSD_HIER[0] ) ),
<add> UserTestData.USERS_TU14_DSD_HIER );
<add> ReviewMgrImplTest.searchUsers( "SRCH-USRS TU15",
<add> TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU15_DSD_HIER[0] ) ),
<add> UserTestData.USERS_TU15_DSD_HIER );
<add> }
<add>
<add>
<add> @Test
<add> public void testFindUserIds()
<add> {
<add> // Add the needed data for this test
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
<add> AdminMgrImplTest.updateUsers( "UPD USERS TU1_UPD", UserTestData.USERS_TU1_UPD );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
<add>
<add> // The test itself
<add> // public List<String> findUsers(User user, int limit)
<add> ReviewMgrImplTest.searchUserIds( "SRCH-USRIDS TU1_UPD",
<add> TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU1[0] ) ), UserTestData.USERS_TU1_UPD );
<add> ReviewMgrImplTest.searchUserIds( "SRCH-USRIDS TU3",
<add> TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU3[0] ) ), UserTestData.USERS_TU3 );
<add> ReviewMgrImplTest.searchUserIds( "SRCH-USRIDS TU4",
<add> TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU4[0] ) ), UserTestData.USERS_TU4 );
<add> }
<add>
<add>
<add> @Test
<add> public void testAssignedRoles()
<add> {
<add> // Add the needed data for this test
<add> // from testAddOrgUnit
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
<add>
<add> // from testAddRole
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
<add>
<add> // from testAdminMgrAddUser
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
<add>
<add> // from testAssignUser
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU1 TR1", UserTestData.USERS_TU1, RoleTestData.ROLES_TR1, false );
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2, true );
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3, true );
<add>
<add> // from testAddPermissionObj
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB1", PermTestData.OBJS_TOB1, true, false );
<add>
<add> // from testAddPermissionOp
<add> AdminMgrImplTest.addPermOps( "ADD-OPS TOB1 TOP1", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1, true, false );
<add>
<add> // from testGrantPermissionUser
<add> AdminMgrImplTest.addUserGrants( "GRNT-PRMS TU1 TOB1 TOP1", UserTestData.USERS_TU1, PermTestData.OBJS_TOB1,
<add> PermTestData.OPS_TOP1 );
<add>
<add> // The test itself
<add> // public List<UserRole> assignedRoles(User userId)
<add> ReviewMgrImplTest.assignedRoles( "ASGN-RLS TU1_UPD TR1", UserTestData.USERS_TU1_UPD, RoleTestData.ROLES_TR1 );
<add> //assignedRoles("ASGN-RLS TU3 TR2", UserTestData.USERS_TU3, RoleTestData.ROLES_TR2);
<add> ReviewMgrImplTest.assignedRoles( "ASGN-RLS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2 );
<add> ReviewMgrImplTest.assignedRoles( "ASGN-RLS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3 );
<add> }
<add>
<add>
<add> @Test
<add> public void testAssignedRoleNms()
<add> {
<add> // Add the needed data for this test
<add> // from testAddOrgUnit
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add>
<add> // from testAddRole
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
<add>
<add> // from testAdminMgrAddUser
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
<add>
<add> // from testAssignUser
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU1 TR1", UserTestData.USERS_TU1, RoleTestData.ROLES_TR1, false );
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2, true );
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3, true );
<add>
<add> // The test itself
<add> // public List<String> assignedRoles(String userId)
<add> ReviewMgrImplTest.assignedRoleNms( "ASGN-RLS TU1_UPD TR1", UserTestData.USERS_TU1_UPD, RoleTestData.ROLES_TR1 );
<add> //assignedRoles("ASGN-RLS TU3 TR2", UserTestData.USERS_TU3, RoleTestData.ROLES_TR2);
<add> ReviewMgrImplTest.assignedRoleNms( "ASGN-RLS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2 );
<add> ReviewMgrImplTest.assignedRoleNms( "ASGN-RLS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3 );
<add> }
<add>
<add>
<add> @Test
<add> public void testAuthorizedRoles()
<add> {
<add> // Add the needed data for this test
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add> AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR6-DESC", RoleTestData.ROLES_TR6_DESC );
<add> AdminMgrImplTest.addRoleAscendant( "ADD-RLS-TR7-ASC", RoleTestData.ROLES_TR7_ASC );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU18 TR6_DESC", UserTestData.USERS_TU18U_TR6_DESC, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU19 TR7_ASC", UserTestData.USERS_TU19U_TR7_ASC, true );
<add>
<add> // The test itself
<add> // public Set<String> authorizedRoles(User user)
<add> ReviewMgrImplTest.authorizedRoles( "AUTHZ-RLS TU18 TR6 DESC", UserTestData.USERS_TU18U_TR6_DESC );
<add> ReviewMgrImplTest.authorizedRoles( "AUTHZ-RLS TU19 TR7 ASC", UserTestData.USERS_TU19U_TR7_ASC );
<add> }
<add>
<add>
<add> @Test
<add> public void testAuthorizedUsers()
<add> {
<add> // Add the needed data for this test
<add> // from testAddOrgUnit
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
<add>
<add> // from testAddRole
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
<add>
<add> // from testAdminMgrAddUser
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
<add>
<add> // from testAdminMgrUpdateUser
<add> AdminMgrImplTest.updateUsers( "UPD USERS TU1_UPD", UserTestData.USERS_TU1_UPD );
<add>
<add> // from testAssignUser
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU1 TR1", UserTestData.USERS_TU1, RoleTestData.ROLES_TR1, false );
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2, true );
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3, true );
<add>
<add> // The test itself
<add> // public List<User> authorizedUsers(Role role)
<add> ReviewMgrImplTest.authorizedUsers( "ATHZ-USRS TR1 TU1_UPD", RoleTestData.ROLES_TR1, UserTestData.USERS_TU1_UPD );
<add> ReviewMgrImplTest.authorizedUsers( "ATHZ-USRS TR2 TU4", RoleTestData.ROLES_TR2, UserTestData.USERS_TU4 );
<add> ReviewMgrImplTest.authorizedUsers( "ATHZ-USRS TR3 TU3", RoleTestData.ROLES_TR3, UserTestData.USERS_TU3 );
<add> }
<add>
<add>
<add> @Test
<add> public void testAuthorizedUserIds()
<add> {
<add> // Add the needed data for this test
<add> // from testAddOrgUnit
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
<add>
<add> // from testAddRole
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
<add>
<add> // from testAdminMgrAddUser
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
<add>
<add> // from testAdminMgrUpdateUser
<add> AdminMgrImplTest.updateUsers( "UPD USERS TU1_UPD", UserTestData.USERS_TU1_UPD );
<add>
<add> // from testAssignUser
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU1 TR1", UserTestData.USERS_TU1, RoleTestData.ROLES_TR1, false );
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2, true );
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3, true );
<add>
<add> // The test itself
<add> // public List<String> authorizedUsers(Role role, int limit)
<add> ReviewMgrImplTest.assignedUserIds( "ATHZ-USRS TR1 TU1_UPD", RoleTestData.ROLES_TR1, UserTestData.USERS_TU1_UPD );
<add> ReviewMgrImplTest.assignedUserIds( "ATHZ-USRS TR2 TU4", RoleTestData.ROLES_TR2, UserTestData.USERS_TU4 );
<add> ReviewMgrImplTest.assignedUserIds( "ATHZ-USRS TR3 TU3", RoleTestData.ROLES_TR3, UserTestData.USERS_TU3 );
<add> }
<add>
<add>
<add> @Test
<add> public void testAuthorizedUsersHier()
<add> {
<add> // Add the needed data for this test
<add> // from testAddOrgUnit
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add>
<add> // from testAdminMgrAddRoleDescendant
<add> AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR6-DESC", RoleTestData.ROLES_TR6_DESC );
<add>
<add> // from testAdminMgrAddRoleAscendants
<add> AdminMgrImplTest.addRoleAscendant( "ADD-RLS-TR7-ASC", RoleTestData.ROLES_TR7_ASC );
<add>
<add> // from testAdminMgrAddUser
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU18 TR6_DESC", UserTestData.USERS_TU18U_TR6_DESC, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU19 TR7_ASC", UserTestData.USERS_TU19U_TR7_ASC, true );
<add>
<add> // The test itself
<add> // public List<User> authorizedUsers(Role role)
<add> ReviewMgrImplTest.authorizedUsersHier( "ATHZ-USRS-HIER TR6 TU18", RoleTestData.TR6_AUTHORIZED_USERS );
<add> ReviewMgrImplTest.authorizedUsersHier( "ATHZ-USRS-HIER TR7 TU19", RoleTestData.TR7_AUTHORIZED_USERS );
<add> }
<add>
<add>
<add> @Test
<add> public void testReadPermissionObj()
<add> {
<add> // Add the needed data for this test
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
<add>
<add> // The test itself
<add> // public Permission addPermObj(Permission pOp)
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB1", PermTestData.OBJS_TOB1, true, false );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB2", PermTestData.OBJS_TOB2, true, false );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB3", PermTestData.OBJS_TOB3, true, false );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB4", PermTestData.OBJS_TOB4, true, false );
<add> AdminMgrImplTest.updatePermObjs( "UPD-OBS TOB4_UPD", PermTestData.OBJS_TOB4_UPD, true );
<add>
<add> // The test itself
<add> // public Permission readPermission(Permission permOp)
<add> ReviewMgrImplTest.readPermissionObjs( "RD-PRM-OBJS TOB1", PermTestData.OBJS_TOB1 );
<add> ReviewMgrImplTest.readPermissionObjs( "RD-PRM-OBJS TOB2", PermTestData.OBJS_TOB2 );
<add> ReviewMgrImplTest.readPermissionObjs( "RD-PRM-OBJS TOB3", PermTestData.OBJS_TOB3 );
<add> ReviewMgrImplTest.readPermissionObjs( "RD-PRM-OBJS TOB4_UPD", PermTestData.OBJS_TOB4_UPD );
<add> }
<add>
<add>
<add> @Test
<add> public void testFindPermissionObjs()
<add> {
<add> // Add the needed data for this test
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
<add>
<add> // The test itself
<add> // public Permission addPermObj(Permission pOp)
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB1", PermTestData.OBJS_TOB1, true, false );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB2", PermTestData.OBJS_TOB2, true, false );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB3", PermTestData.OBJS_TOB3, true, false );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB4", PermTestData.OBJS_TOB4, true, false );
<add> AdminMgrImplTest.updatePermObjs( "UPD-OBS TOB4_UPD", PermTestData.OBJS_TOB4_UPD, true );
<add>
<add> // The test itself
<add> // public List<Permission> findPermissions(Permission permOp)
<add> ReviewMgrImplTest.searchPermissionObjs( "FND-PRM-OBJS TOB1",
<add> TestUtils.getSrchValue( PermTestData.getName( PermTestData.OBJS_TOB1[0] ) ), PermTestData.OBJS_TOB1 );
<add> ReviewMgrImplTest.searchPermissionObjs( "FND-PRM-OBJS TOB2",
<add> TestUtils.getSrchValue( PermTestData.getName( PermTestData.OBJS_TOB2[0] ) ), PermTestData.OBJS_TOB2 );
<add> ReviewMgrImplTest.searchPermissionObjs( "FND-PRM-OBJS TOB3",
<add> TestUtils.getSrchValue( PermTestData.getName( PermTestData.OBJS_TOB3[0] ) ), PermTestData.OBJS_TOB3 );
<add> ReviewMgrImplTest
<add> .searchPermissionObjs( "FND-PRM-OBJS TOB4_UPD",
<add> TestUtils.getSrchValue( PermTestData.getName( PermTestData.OBJS_TOB4_UPD[0] ) ),
<add> PermTestData.OBJS_TOB4_UPD );
<add> }
<add>
<add>
<add> @Test
<add> public void testReadPermissionOp()
<add> {
<add> // Add the needed data for this test
<add> // from testAddOrgUnit
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
<add>
<add> // from testAddPermissionObj
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB1", PermTestData.OBJS_TOB1, true, false );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB2", PermTestData.OBJS_TOB2, true, false );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB3", PermTestData.OBJS_TOB3, true, false );
<add>
<add> // from testAddPermissionOp
<add> AdminMgrImplTest.addPermOps( "ADD-OPS TOB1 TOP1", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1, true, false );
<add> AdminMgrImplTest.addPermOps( "ADD-OPS TOB2 TOP2", PermTestData.OBJS_TOB2, PermTestData.OPS_TOP2, true, false );
<add> AdminMgrImplTest.addPermOps( "ADD-OPS TOB3 TOP3", PermTestData.OBJS_TOB3, PermTestData.OPS_TOP3, true, false );
<add>
<add> // from testUpdatePermissionOp
<add> AdminMgrImplTest.updatePermOps( "UPD-OPS TOB1 TOP1_UPD", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1_UPD,
<add> true );
<add>
<add> // The test itself
<add> // public Permission readPermission(Permission permOp)
<add> ReviewMgrImplTest.readPermissionOps( "RD-PRM-OPS TOB1 OPS_TOP1_UPD", PermTestData.OBJS_TOB1,
<add> PermTestData.OPS_TOP1_UPD );
<add> ReviewMgrImplTest.readPermissionOps( "RD-PRM-OPS TOB1 TOP2", PermTestData.OBJS_TOB2, PermTestData.OPS_TOP2 );
<add> ReviewMgrImplTest.readPermissionOps( "RD-PRM-OPS TOB1 TOP3", PermTestData.OBJS_TOB3, PermTestData.OPS_TOP3 );
<add> }
<add>
<add>
<add> @Test
<add> public void testFindPermissionOps()
<add> {
<add> // Add the needed data for this test
<add> // from testAddOrgUnit
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
<add>
<add> // from testAddPermissionObj
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB1", PermTestData.OBJS_TOB1, true, false );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB2", PermTestData.OBJS_TOB2, true, false );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB3", PermTestData.OBJS_TOB3, true, false );
<add>
<add> // from testAddPermissionOp
<add> AdminMgrImplTest.addPermOps( "ADD-OPS TOB1 TOP1", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1, true, false );
<add> AdminMgrImplTest.addPermOps( "ADD-OPS TOB2 TOP2", PermTestData.OBJS_TOB2, PermTestData.OPS_TOP2, true, false );
<add> AdminMgrImplTest.addPermOps( "ADD-OPS TOB3 TOP3", PermTestData.OBJS_TOB3, PermTestData.OPS_TOP3, true, false );
<add>
<add> // from testUpdatePermissionOp
<add> AdminMgrImplTest.updatePermOps( "UPD-OPS TOB1 TOP1_UPD", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1_UPD,
<add> true );
<add>
<add> // The test itself
<add> // public List<Permission> findPermissions(Permission permOp)
<add> ReviewMgrImplTest.searchPermissionOps( "FND-PRM-OPS TOB1 OPS_TOP1_UPD",
<add> TestUtils.getSrchValue( PermTestData.getName( PermTestData.OPS_TOP1_UPD[0] ) ), PermTestData.OBJS_TOB1,
<add> PermTestData.OPS_TOP1_UPD );
<add> ReviewMgrImplTest.searchPermissionOps( "FND-PRM-OPS TOB2 TOP2",
<add> TestUtils.getSrchValue( PermTestData.getName( PermTestData.OPS_TOP2[0] ) ), PermTestData.OBJS_TOB2,
<add> PermTestData.OPS_TOP2 );
<add> ReviewMgrImplTest.searchPermissionOps( "FND-PRM-OPS TOB3 TOP3",
<add> TestUtils.getSrchValue( PermTestData.getName( PermTestData.OPS_TOP3[0] ) ), PermTestData.OBJS_TOB3,
<add> PermTestData.OPS_TOP3 );
<add> }
<add>
<add>
<add> @Test
<add> public void testRolePermissions()
<add> {
<add> // Add the needed data for this test
<add> // from testAddOrgUnit
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
<add>
<add> // from testAddRole
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
<add>
<add> // from testAddPermissionObj
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB1", PermTestData.OBJS_TOB1, true, false );
<add>
<add> // from testAddPermissionOp
<add> AdminMgrImplTest.addPermOps( "ADD-OPS TOB1 TOP1", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1, true, false );
<add>
<add> // from testUpdatePermissionOp
<add> AdminMgrImplTest.updatePermOps( "UPD-OPS TOB1 TOP1_UPD", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1_UPD,
<add> true );
<add>
<add> // from testGrantPermissionRole
<add> AdminMgrImplTest.addRoleGrants( "GRNT-PRMS TR1 TOB1 TOP1", RoleTestData.ROLES_TR1, PermTestData.OBJS_TOB1,
<add> PermTestData.OPS_TOP1, true, false );
<add>
<add> // The test itself
<add> // public List<Permission> rolePermissions(Role role)
<add> ReviewMgrImplTest.rolePermissions( "ATHRZ-RLE-PRMS TR1 TOB1 TOP1_UPD", RoleTestData.ROLES_TR1,
<add> PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1_UPD );
<add> }
<add>
<add>
<add> @Test
<add> public void testPermissionRoles()
<add> {
<add> // Add the needed data for this test
<add> // from testAddOrgUnit
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
<add>
<add> // from testAddRole
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
<add>
<add> // from testAddPermissionObj
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB1", PermTestData.OBJS_TOB1, true, false );
<add>
<add> // from testAddPermissionOp
<add> AdminMgrImplTest.addPermOps( "ADD-OPS TOB1 TOP1", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1, true, false );
<add>
<add> // from testGrantPermissionRole
<add> AdminMgrImplTest.addRoleGrants( "GRNT-PRMS TR1 TOB1 TOP1", RoleTestData.ROLES_TR1, PermTestData.OBJS_TOB1,
<add> PermTestData.OPS_TOP1, true, false );
<add>
<add> // The test itself
<add> // public List<Role> permissionRoles(Permission perm)
<add> ReviewMgrImplTest.permissionRoles( "PRM-RLS TOB1 TOP1 TR1", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1,
<add> RoleTestData.ROLES_TR1 );
<add> }
<add>
<add>
<add> @Test
<add> public void testAuthorizedPermissionRoles()
<add> {
<add> // Add the needed data for this test
<add> // from testAddOrgUnit
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
<add>
<add> // from testAddRole
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR5B", RoleTestData.ROLES_TR5B );
<add>
<add> // from testAdminMgrAddRoleInheritance
<add> AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR5B", RoleTestData.ROLES_TR5B );
<add>
<add> // from testAdminMgrAddUser
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU20 TR5_HIER", UserTestData.USERS_TU20U_TR5B, true );
<add>
<add> // from testAddPermissionObj
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB6", PermTestData.OBJS_TOB6, true, false );
<add>
<add> // from testAddPermissionOp
<add> AdminMgrImplTest.addPermOps( "ADD-OPS TOB6 TOP5", PermTestData.OBJS_TOB6, PermTestData.OPS_TOP5, true, false );
<add>
<add> // from testGrantPermissionRole
<add> AdminMgrImplTest.addRoleGrantsHB( "GRNT-PRMS_HB USERS TU20 ROLES_TR5B TOB6 TOP5",
<add> UserTestData.USERS_TU20U_TR5B,
<add> RoleTestData.ROLES_TR5B, PermTestData.OBJS_TOB6, PermTestData.OPS_TOP5 );
<add>
<add> // The test itself
<add> // public Set<String> authorizedPermissionRoles(Permission perm)
<add> ReviewMgrImplTest.authorizedPermissionRoles( "AUTHZ PRM-RLES TOB6 TOP5 TR5B", PermTestData.OBJS_TOB6,
<add> PermTestData.OPS_TOP5,
<add> RoleTestData.ROLES_TR5B );
<add> }
<add>
<add>
<add> @Test
<add> public void testPermissionUsers()
<add> {
<add> // Add the needed data for this test
<add> // from testAddOrgUnit
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
<add>
<add> // from testAddRole
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
<add>
<add> // from testAdminMgrAddUser
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
<add>
<add> // from testAdminMgrUpdateUser
<add> AdminMgrImplTest.updateUsers( "UPD USERS TU1_UPD", UserTestData.USERS_TU1_UPD );
<add>
<add> // from testAssignUser
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU1 TR1", UserTestData.USERS_TU1, RoleTestData.ROLES_TR1, false );
<add>
<add> // from testAddPermissionObj
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB1", PermTestData.OBJS_TOB1, true, false );
<add>
<add> // from testAddPermissionOp
<add> AdminMgrImplTest.addPermOps( "ADD-OPS TOB1 TOP1", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1, true, false );
<add> //
<add> // from testGrantPermissionUser
<add> AdminMgrImplTest.addUserGrants( "GRNT-PRMS TU1 TOB1 TOP1", UserTestData.USERS_TU1, PermTestData.OBJS_TOB1,
<add> PermTestData.OPS_TOP1 );
<add>
<add> // The test itself
<add> // public List<User> permissionUsers(Permission perm)
<add> ReviewMgrImplTest.permissionUsers( "PRM-USRS TOB1 TOP1 TU1_UPD", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1,
<add> UserTestData.USERS_TU1_UPD );
<add> }
<add>
<add>
<add> @Test
<add> public void testAuthorizedPermissionUsers()
<add> {
<add> // Add the needed data for this test
<add> // from testAddOrgUnit
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
<add>
<add> // from testAddRole
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR5_HIER", RoleTestData.ROLES_TR5_HIER );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR5B", RoleTestData.ROLES_TR5B );
<add>
<add> // from testAdminMgrAddRoleInheritance
<add> AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR5_HIER", RoleTestData.ROLES_TR5_HIER );
<add> AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR5B", RoleTestData.ROLES_TR5B );
<add>
<add> // from testAdminMgrAddUser
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU20 TR5_HIER", UserTestData.USERS_TU20U_TR5B, true );
<add>
<add> // from testAssignUser
<add> AdminMgrImplTest.assignUsersH( "ASGN-USRS_H TU20 TR5B HIER", UserTestData.USERS_TU20U_TR5B,
<add> RoleTestData.ROLES_TR5B, true );
<add>
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB6", PermTestData.OBJS_TOB6, true, false );
<add>
<add> // from testAddPermissionOp
<add> AdminMgrImplTest.addPermOps( "ADD-OPS TOB6 TOP5", PermTestData.OBJS_TOB6, PermTestData.OPS_TOP5, true, false );
<add>
<add> // from testGrantPermissionRole
<add> AdminMgrImplTest.addRoleGrantsHB( "GRNT-PRMS_HB USERS TU20 ROLES_TR5B TOB6 TOP5",
<add> UserTestData.USERS_TU20U_TR5B,
<add> RoleTestData.ROLES_TR5B, PermTestData.OBJS_TOB6, PermTestData.OPS_TOP5 );
<add>
<add> // The test itself
<add> // public Set<String> authorizedPermissionUsers(Permission perm)
<add> ReviewMgrImplTest.authorizedPermissionUsers( "AUTHZ PRM-USRS TOB6 TOP5 TU20", PermTestData.OBJS_TOB6,
<add> PermTestData.OPS_TOP5,
<add> UserTestData.USERS_TU20U_TR5B );
<add> }
<add>
<add>
<add> @Test
<add> public void testUserPermissions()
<add> {
<add> // Add the needed data for this test
<add> // from testAddOrgUnit
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
<add>
<add> // from testAddRole
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR5_HIER", RoleTestData.ROLES_TR5_HIER );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR5B", RoleTestData.ROLES_TR5B );
<add>
<add> // from testAdminMgrAddRoleInheritance
<add> AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR5_HIER", RoleTestData.ROLES_TR5_HIER );
<add>
<add> // from testAdminMgrAddUser
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU2", UserTestData.USERS_TU2, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
<add>
<add> // from testAssignUser
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU1 TR1", UserTestData.USERS_TU1, RoleTestData.ROLES_TR1, false );
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2, true );
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3, true );
<add>
<add> // from testAddPermissionObj
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB1", PermTestData.OBJS_TOB1, true, false );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB2", PermTestData.OBJS_TOB2, true, false );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB3", PermTestData.OBJS_TOB3, true, false );
<add>
<add> // from testAddPermissionOp
<add> AdminMgrImplTest.addPermOps( "ADD-OPS TOB1 TOP1", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1, true, false );
<add> AdminMgrImplTest.addPermOps( "ADD-OPS TOB2 TOP2", PermTestData.OBJS_TOB2, PermTestData.OPS_TOP2, true, false );
<add> AdminMgrImplTest.addPermOps( "ADD-OPS TOB3 TOP3", PermTestData.OBJS_TOB3, PermTestData.OPS_TOP3, true, false );
<add>
<add> // from testUpdatePermissionOp
<add> AdminMgrImplTest.updatePermOps( "UPD-OPS TOB1 TOP1_UPD", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1_UPD,
<add> true );
<add>
<add> // from testGrantPermissionRole
<add> AdminMgrImplTest.addRoleGrants( "GRNT-PRMS TR1 TOB1 TOP1", RoleTestData.ROLES_TR1, PermTestData.OBJS_TOB1,
<add> PermTestData.OPS_TOP1, true, false );
<add> AdminMgrImplTest.addRoleGrants( "GRNT-PRMS TR2 TOB2 TOP2", RoleTestData.ROLES_TR2, PermTestData.OBJS_TOB2,
<add> PermTestData.OPS_TOP2, true, false );
<add> AdminMgrImplTest.addRoleGrants( "GRNT-PRMS TR3 TOB3 TOP3", RoleTestData.ROLES_TR3, PermTestData.OBJS_TOB3,
<add> PermTestData.OPS_TOP3, true, false );
<add>
<add> // from testGrantPermissionUser
<add> AdminMgrImplTest.addUserGrants( "GRNT-PRMS TU1 TOB1 TOP1", UserTestData.USERS_TU1, PermTestData.OBJS_TOB1,
<add> PermTestData.OPS_TOP1 );
<add>
<add> // The test itself
<add> // public List <Permission> userPermissions(User user)
<add> ReviewMgrImplTest.userPermissions( "USR-PRMS TU1_UPD TOB1 TOP1_UPD", UserTestData.USERS_TU1_UPD,
<add> PermTestData.OBJS_TOB1,
<add> PermTestData.OPS_TOP1_UPD );
<add> ReviewMgrImplTest.userPermissions( "USR-PRMS TU3 TOB3 TOP3", UserTestData.USERS_TU3, PermTestData.OBJS_TOB3,
<add> PermTestData.OPS_TOP3 );
<add> ReviewMgrImplTest.userPermissions( "USR-PRMS TU4 TOB2 TOP2", UserTestData.USERS_TU4, PermTestData.OBJS_TOB2,
<add> PermTestData.OPS_TOP2 );
<add> }
<add>
<add>
<add> /***********************************************************/
<add> /* 4. Security Checks */
<add> /***********************************************************/
<add> // DelAccessMgr ARABC:
<add> @Test
<add> public void testCheckAccess()
<add> {
<add> // Add the needed data for this test
<add> // from testAddOrgUnit
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO5", OrgUnitTestData.ORGS_USR_TO5 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO5", OrgUnitTestData.ORGS_PRM_TO5 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
<add>
<add> // from testAddRole
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
<add> AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
<add> DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR2", AdminRoleTestData.AROLES_TR2, true );
<add>
<add> // from testAddUser
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU16A_ARBAC", UserTestData.USERS_TU17A_ARBAC, true );
<add>
<add> // from testAddPermission
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS ARBAC1", PermTestData.ARBAC_OBJS_1, true, false );
<add> AdminMgrImplTest
<add> .addPermOps( "ADD-OPS ARBAC1", PermTestData.ARBAC_OBJS_1, PermTestData.ARBAC_OPS_1, true, false );
<add>
<add> // from testAssignAdminUser
<add> DelegatedMgrImplTest.assignAdminUserRole( "ASGN-USR TU17A TR2", UserTestData.USERS_TU17A_ARBAC,
<add> AdminRoleTestData.AROLES_TR2, true );
<add>
<add> // from testGrantPermissionRole
<add> AdminMgrImplTest.addRoleGrants( "GRNT-APRMS ARTR2 AROBJ1 AROPS1", AdminRoleTestData.AROLES_TR2,
<add> PermTestData.ARBAC_OBJS_1, PermTestData.ARBAC_OPS_1, true, false );
<add>
<add> // from testAdminMgrAddRoleAscendants
<add> AdminMgrImplTest.addRoleAscendant( "ADD-RLS-TR7-ASC", RoleTestData.ROLES_TR7_ASC );
<add>
<add> // The test itself
<add> // public boolean checkAccess(String object, String operation, Session session)
<add> DelegatedMgrImplTest.checkAccess( "CHCK-ACS TU1_UPD TO1 TOP1 ", UserTestData.USERS_TU17A_ARBAC,
<add> PermTestData.ARBAC_OBJS_1,
<add> PermTestData.ARBAC_OPS_1, PermTestData.ARBAC_OBJ2, PermTestData.ARBAC_OPS_2 );
<add> }
<add>
<add>
<add> @Test
<add> public void testCanAssignUser()
<add> {
<add> // Add the needed data for this test
<add> // from testAddOrgUnit
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO5", OrgUnitTestData.ORGS_USR_TO5 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO5", OrgUnitTestData.ORGS_PRM_TO5 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add> // DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
<add>
<add> // from testAddOrgInheritance
<add> DelegatedMgrImplTest.addInheritedOrgUnits( "ADD-INHERIT ORGS_USR_TO5", OrgUnitTestData.ORGS_USR_TO5 );
<add>
<add> // from testAddRole
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
<add> AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
<add> DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR2", AdminRoleTestData.AROLES_TR2, true );
<add>
<add> // from testAddUser
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU16A_ARBAC", UserTestData.USERS_TU17A_ARBAC, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU16U_ARBAC", UserTestData.USERS_TU17U_ARBAC, true );
<add>
<add> // from testAssignAdminUser
<add> DelegatedMgrImplTest.assignAdminUserRole( "ASGN-USR TU17A TR2", UserTestData.USERS_TU17A_ARBAC,
<add> AdminRoleTestData.AROLES_TR2, true );
<add>
<add> // The test itself
<add> //canAssignUsers("CAN-ASGN-USRS TU1 TR1", UserTestData.USERS_TU16_ARBAC, UserTestData.USERS_TU16B_ARBAC, RoleTestData.ROLES_TR14_ARBAC);
<add> DelegatedMgrImplTest.canAssignUsers( "CAN-ASGN-USRS URA_T1 TU17A TU17U TR15", ASSIGN_OP.ASSIGN,
<add> URATestData.URA_T1,
<add> UserTestData.USERS_TU17A_ARBAC, UserTestData.USERS_TU17U_ARBAC, RoleTestData.ROLES_TR15_ARBAC );
<add> }
<add>
<add>
<add> @Test
<add> public void testCanDeassignUser()
<add> {
<add> // Add the needed data for this test
<add> // from testAddOrgUnit
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO5", OrgUnitTestData.ORGS_USR_TO5 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO5", OrgUnitTestData.ORGS_PRM_TO5 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add> // DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
<add>
<add> // from testAddOrgInheritance
<add> DelegatedMgrImplTest.addInheritedOrgUnits( "ADD-INHERIT ORGS_USR_TO5", OrgUnitTestData.ORGS_USR_TO5 );
<add>
<add> // from testAddRole
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
<add> AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
<add> DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR2", AdminRoleTestData.AROLES_TR2, true );
<add>
<add> // from testAddUser
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU16A_ARBAC", UserTestData.USERS_TU17A_ARBAC, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU16U_ARBAC", UserTestData.USERS_TU17U_ARBAC, true );
<add>
<add> // from testAssignAdminUser
<add> DelegatedMgrImplTest.assignAdminUserRole( "ASGN-USR TU17A TR2", UserTestData.USERS_TU17A_ARBAC,
<add> AdminRoleTestData.AROLES_TR2, true );
<add>
<add> // The test itself
<add> DelegatedMgrImplTest.canAssignUsers( "CAN-DEASGN-USRS URA_T1 TU17A TU17U TR15", ASSIGN_OP.DEASSIGN,
<add> URATestData.URA_T1,
<add> UserTestData.USERS_TU17A_ARBAC, UserTestData.USERS_TU17U_ARBAC, RoleTestData.ROLES_TR15_ARBAC );
<add> }
<add>
<add>
<add> @Test
<add> public void testCanGrantPerm()
<add> {
<add> // Add the needed data for this test
<add> // from testAddOrgUnit
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO5", OrgUnitTestData.ORGS_USR_TO5 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO5", OrgUnitTestData.ORGS_PRM_TO5 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add>
<add> // from testAddOrgInheritance
<add> DelegatedMgrImplTest.addInheritedOrgUnits( "ADD-INHERIT ORGS_PRM_TO5", OrgUnitTestData.ORGS_PRM_TO5 );
<add>
<add> // from testAddRole
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
<add> AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
<add> DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR2", AdminRoleTestData.AROLES_TR2, true );
<add>
<add> // from testAddUser
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU16A_ARBAC", UserTestData.USERS_TU17A_ARBAC, true );
<add>
<add> // from testAddPermission
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB5", PermTestData.OBJS_TOB5, true, false );
<add>
<add> // from testAssignAdminUser
<add> DelegatedMgrImplTest.assignAdminUserRole( "ASGN-USR TU17A TR2", UserTestData.USERS_TU17A_ARBAC,
<add> AdminRoleTestData.AROLES_TR2, true );
<add>
<add> // The test itself
<add> DelegatedMgrImplTest.canGrantPerms( "CAN-GRNT-PRMS PRA_T1 TU17A TOB5 TR15", GRANT_OP.GRANT, PRATestData.PRA_T1,
<add> UserTestData.USERS_TU17A_ARBAC, PermTestData.OBJS_TOB5, RoleTestData.ROLES_TR15_ARBAC );
<add> }
<add>
<add>
<add> @Test
<add> public void testCanRevokePerm()
<add> {
<add> // Add the needed data for this test
<add> // from testAddOrgUnit
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_USR_TO5", OrgUnitTestData.ORGS_USR_TO5 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_PRM_TO5", OrgUnitTestData.ORGS_PRM_TO5 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add>
<add> // from testAddOrgInheritance
<add> DelegatedMgrImplTest.addInheritedOrgUnits( "ADD-INHERIT ORGS_PRM_TO5", OrgUnitTestData.ORGS_PRM_TO5 );
<add>
<add> // from testAddRole
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
<add> AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR15_ARBAC", RoleTestData.ROLES_TR15_ARBAC );
<add> DelegatedMgrImplTest.addAdminRoles( "ADD-ADMRLS TR2", AdminRoleTestData.AROLES_TR2, true );
<add>
<add> // from testAddUser
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU16A_ARBAC", UserTestData.USERS_TU17A_ARBAC, true );
<add>
<add> // from testAddPermission
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB5", PermTestData.OBJS_TOB5, true, false );
<add>
<add> // from testAssignAdminUser
<add> DelegatedMgrImplTest.assignAdminUserRole( "ASGN-USR TU17A TR2", UserTestData.USERS_TU17A_ARBAC,
<add> AdminRoleTestData.AROLES_TR2, true );
<add>
<add> // The test itself
<add> DelegatedMgrImplTest.canGrantPerms( "CAN-RVKE-PRMS PRA_T1 TU17A TOB5 TR15", GRANT_OP.REVOKE,
<add> PRATestData.PRA_T1,
<add> UserTestData.USERS_TU17A_ARBAC, PermTestData.OBJS_TOB5, RoleTestData.ROLES_TR15_ARBAC );
<add> }
<add>
<add>
<add> // AccessMgr RBAC:
<add> @Test
<add> public void testGetUserId()
<add> {
<add> // Add the needed data for this test
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
<add> AdminMgrImplTest.updateUsers( "UPD USERS TU1_UPD", UserTestData.USERS_TU1_UPD );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
<add>
<add> // The test itself
<add> // public String getUserId(Session, session)
<add> AccessMgrImplTest.getUsers( "GET-USRIDS TU1_UPD", UserTestData.USERS_TU1_UPD );
<add> AccessMgrImplTest.getUsers( "GET-USRIDS TU3", UserTestData.USERS_TU3 );
<add> AccessMgrImplTest.getUsers( "GET-USRIDS TU4", UserTestData.USERS_TU4 );
<add> }
<add>
<add>
<add> @Test
<add> public void testGetUser()
<add> {
<add> // Add the needed data for this test
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
<add> AdminMgrImplTest.updateUsers( "UPD USERS TU1_UPD", UserTestData.USERS_TU1_UPD );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
<add>
<add> // The test itself
<add> // public User getUser(Session, session)
<add> AccessMgrImplTest.getUsers( "GET-USRS TU1_UPD", UserTestData.USERS_TU1_UPD );
<add> AccessMgrImplTest.getUsers( "GET-USRS TU3", UserTestData.USERS_TU3 );
<add> AccessMgrImplTest.getUsers( "GET-USRS TU4", UserTestData.USERS_TU4 );
<add> }
<add>
<add>
<add> /**
<add> *
<add> */
<add> @Test
<add> public void testCreateSession()
<add> {
<add> // Add the needed data for this test
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
<add> AdminMgrImplTest.updateUsers( "UPD USERS TU1_UPD", UserTestData.USERS_TU1_UPD );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU1 TR1", UserTestData.USERS_TU1, RoleTestData.ROLES_TR1, false );
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2, true );
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3, true );
<add>
<add> // The test itself
<add> // public Session createSession(User user, boolean isTrusted)
<add> AccessMgrImplTest
<add> .createSessions( "CREATE-SESS TU1_UPD TR1", UserTestData.USERS_TU1_UPD, RoleTestData.ROLES_TR1 );
<add> AccessMgrImplTest.createSessions( "CREATE-SESS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3 );
<add> AccessMgrImplTest.createSessions( "CREATE-SESS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2 );
<add> }
<add>
<add>
<add> /**
<add> *
<add> */
<add> @Test
<add> public void testCreateSessionTrusted()
<add> {
<add> // Add the needed data for this test
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
<add> AdminMgrImplTest.updateUsers( "UPD USERS TU1_UPD", UserTestData.USERS_TU1_UPD );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU1 TR1", UserTestData.USERS_TU1, RoleTestData.ROLES_TR1, false );
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2, true );
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3, true );
<add>
<add> // The test itself
<add> // public Session createSession(User user, boolean isTrusted)
<add> AccessMgrImplTest.createSessionsTrusted( "CR-SESS-TRST TU1_UPD TR1", UserTestData.USERS_TU1_UPD,
<add> RoleTestData.ROLES_TR1 );
<add> AccessMgrImplTest
<add> .createSessionsTrusted( "CR-SESS-TRST TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3 );
<add> AccessMgrImplTest
<add> .createSessionsTrusted( "CR-SESS-TRST TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2 );
<add> }
<add>
<add>
<add> /**
<add> *
<add> */
<add> @Test
<add> public void testCreateSessionHier()
<add> {
<add> // Add the needed data for this test
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add> AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR6-DESC", RoleTestData.ROLES_TR6_DESC );
<add> AdminMgrImplTest.addRoleAscendant( "ADD-RLS-TR7-ASC", RoleTestData.ROLES_TR7_ASC );
<add>
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU18 TR6_DESC", UserTestData.USERS_TU18U_TR6_DESC, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU19 TR7_ASC", UserTestData.USERS_TU19U_TR7_ASC, true );
<add>
<add> // The test itself
<add> // public Session createSession(User user, boolean isTrusted)
<add> AccessMgrImplTest.createSessionsHier( "CREATE-SESS-HIER TU18 TR6 DESC", UserTestData.USERS_TU18U_TR6_DESC );
<add> AccessMgrImplTest.createSessionsHier( "CREATE-SESS-HIER TU19U TR7 ASC", UserTestData.USERS_TU19U_TR7_ASC );
<add> }
<add>
<add>
<add> @Test
<add> public void testCreateSessionsDSD()
<add> {
<add> // from testAddOrgUnit
<add> // DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_TO1", OrgUnitTestData.ORGS_TO1 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add>
<add> // from testAddRole
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR8_DSD", RoleTestData.ROLES_TR8_DSD );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR9_DSD", RoleTestData.ROLES_TR9_DSD );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR17_DSD_BRUNO", RoleTestData.ROLES_TR17_DSD_BRUNO );
<add>
<add> // from testAdminMgrAddRoleDescendant
<add> AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR11-DESC-DSD", RoleTestData.ROLES_TR11_DESC_DSD );
<add> AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR12-DESC-DSD", RoleTestData.ROLES_TR12_DESC_DSD );
<add> AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR13-DESC-DSD", RoleTestData.ROLES_TR13_DESC_DSD );
<add>
<add> // from testAdminMgrCreateDsdSet
<add> AdminMgrImplTest.createDsdSet( "ADD-DSD T1", RoleTestData.DSD_T1 );
<add> AdminMgrImplTest.createDsdSet( "ADD-DSD T4", RoleTestData.DSD_T4 );
<add> AdminMgrImplTest.createDsdSet( "ADD-DSD T5", RoleTestData.DSD_T5 );
<add> AdminMgrImplTest.createDsdSet( "ADD-DSD T6", RoleTestData.DSD_T6 );
<add> AdminMgrImplTest.createDsdSet( "ADD-DSD T8 BRUNO", RoleTestData.DSD_T8_BRUNO );
<add>
<add> // from testAdminMgrAddUser
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU12_DSD", UserTestData.USERS_TU12_DSD, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU13_DSD_HIER", UserTestData.USERS_TU13_DSD_HIER, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU14_DSD_HIER", UserTestData.USERS_TU14_DSD_HIER, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU15_DSD_HIER", UserTestData.USERS_TU15_DSD_HIER, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU21 DSD_BRUNO", UserTestData.USERS_TU21_DSD_BRUNO, true );
<add>
<add> // from testAssignUser
<add> AdminMgrImplTest.assignUsersDSD( "ASGN-USRS_DSDT1 TU12 DSD_T1", UserTestData.USERS_TU12_DSD,
<add> RoleTestData.DSD_T1 );
<add> AdminMgrImplTest.assignUsersDSD( "ASGN-USRS_DSDT4B TU13 DSD_T4_B", UserTestData.USERS_TU13_DSD_HIER,
<add> RoleTestData.DSD_T4_B );
<add> AdminMgrImplTest.assignUsersDSD( "ASGN-USRS_DSDT5B TU14 DSD_T5_B", UserTestData.USERS_TU14_DSD_HIER,
<add> RoleTestData.DSD_T5_B );
<add> AdminMgrImplTest.assignUsersDSD( "ASGN-USRS_DSDT6B TU15 DSD_T6_B", UserTestData.USERS_TU15_DSD_HIER,
<add> RoleTestData.DSD_T6_B );
<add>
<add> // The test itself
<add> // public Session createSession(User user, boolean isTrusted)
<add> AccessMgrImplTest.createSessionsDSD( "CR-SESS-DSD TU12 DSD_T1", UserTestData.USERS_TU12_DSD,
<add> RoleTestData.DSD_T1 );
<add> AccessMgrImplTest.createSessionsDSD( "CR-SESS-DSD TU13 DSD_T4_B", UserTestData.USERS_TU13_DSD_HIER,
<add> RoleTestData.DSD_T4_B );
<add> AccessMgrImplTest.createSessionsDSD( "CR-SESS-DSD TU14 DSD_T5_B", UserTestData.USERS_TU14_DSD_HIER,
<add> RoleTestData.DSD_T5_B );
<add> AccessMgrImplTest.createSessionsDSD( "CR-SESS-DSD TU15 DSD_T6_C", UserTestData.USERS_TU15_DSD_HIER,
<add> RoleTestData.DSD_T6_C );
<add> AccessMgrImplTest.createSessionsDSD( "CR-SESS-DSD TU21 DSD_T8_BRUNO", UserTestData.USERS_TU21_DSD_BRUNO,
<add> RoleTestData.DSD_T8_BRUNO );
<add>
<add> // Running it again to make sure the caching is working good:
<add> AccessMgrImplTest.createSessionsDSD( "CR-SESS-DSD TU12 DSD_T1", UserTestData.USERS_TU12_DSD,
<add> RoleTestData.DSD_T1 );
<add> AccessMgrImplTest.createSessionsDSD( "CR-SESS-DSD TU13 DSD_T4_B", UserTestData.USERS_TU13_DSD_HIER,
<add> RoleTestData.DSD_T4_B );
<add> AccessMgrImplTest.createSessionsDSD( "CR-SESS-DSD TU14 DSD_T5_B", UserTestData.USERS_TU14_DSD_HIER,
<add> RoleTestData.DSD_T5_B );
<add> AccessMgrImplTest.createSessionsDSD( "CR-SESS-DSD TU15 DSD_T6_C", UserTestData.USERS_TU15_DSD_HIER,
<add> RoleTestData.DSD_T6_C );
<add> AccessMgrImplTest.createSessionsDSD( "CR-SESS-DSD TU21 DSD_T8_BRUNO", UserTestData.USERS_TU21_DSD_BRUNO,
<add> RoleTestData.DSD_T8_BRUNO );
<add> }
<add>
<add>
<add> /**
<add> *
<add> */
<add> @Test
<add> public void testSessionRole()
<add> {
<add> // Add the needed data for this test
<add> // from testAddOrgUnit
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add>
<add> // from testAddRole
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
<add>
<add> // from testAdminMgrAddUser
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
<add>
<add> // from testAdminMgrUpdateUser
<add> AdminMgrImplTest.updateUsers( "UPD USERS TU1_UPD", UserTestData.USERS_TU1_UPD );
<add>
<add> // from testAssignUser
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU1 TR1", UserTestData.USERS_TU1, RoleTestData.ROLES_TR1, false );
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2, true );
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3, true );
<add>
<add> // The test itself
<add> // public List<UserRole> sessionRoles(Session session)
<add> AccessMgrImplTest.sessionRoles( "SESS-RLS TU1_UPD TR1", UserTestData.USERS_TU1_UPD, RoleTestData.ROLES_TR1 );
<add> AccessMgrImplTest.sessionRoles( "SESS-RLS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3 );
<add> AccessMgrImplTest.sessionRoles( "SESS-RLS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2 );
<add> }
<add>
<add>
<add> /**
<add> *
<add> */
<add> @Test
<add> public void testAccessMgrCheckAccess()
<add> {
<add> // Add the needed data for this test
<add> // from testAddOrgUnit
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
<add>
<add> // from testAddRole
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
<add>
<add> // from testAdminMgrAddUser
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
<add>
<add> // from testAdminMgrUpdateUser
<add> AdminMgrImplTest.updateUsers( "UPD USERS TU1_UPD", UserTestData.USERS_TU1_UPD );
<add>
<add> // from testAssignUser
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU1 TR1", UserTestData.USERS_TU1, RoleTestData.ROLES_TR1, false );
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2, true );
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3, true );
<add>
<add> // from testAddPermissionObj
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB1", PermTestData.OBJS_TOB1, true, false );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB2", PermTestData.OBJS_TOB2, true, false );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB3", PermTestData.OBJS_TOB3, true, false );
<add>
<add> // from testAddPermissionOp
<add> AdminMgrImplTest.addPermOps( "ADD-OPS TOB1 TOP1", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1, true, false );
<add> AdminMgrImplTest.addPermOps( "ADD-OPS TOB2 TOP2", PermTestData.OBJS_TOB2, PermTestData.OPS_TOP2, true, false );
<add> AdminMgrImplTest.addPermOps( "ADD-OPS TOB3 TOP3", PermTestData.OBJS_TOB3, PermTestData.OPS_TOP3, true, false );
<add>
<add> // from testGrantPermissionRole
<add> AdminMgrImplTest.addRoleGrants( "GRNT-PRMS TR1 TOB1 TOP1", RoleTestData.ROLES_TR1, PermTestData.OBJS_TOB1,
<add> PermTestData.OPS_TOP1, true, false );
<add> AdminMgrImplTest.addRoleGrants( "GRNT-PRMS TR2 TOB2 TOP2", RoleTestData.ROLES_TR2, PermTestData.OBJS_TOB2,
<add> PermTestData.OPS_TOP2, true, false );
<add> AdminMgrImplTest.addRoleGrants( "GRNT-PRMS TR3 TOB3 TOP3", RoleTestData.ROLES_TR3, PermTestData.OBJS_TOB3,
<add> PermTestData.OPS_TOP3, true, false );
<add>
<add> // The test itself
<add> // public boolean checkAccess(String object, String operation, Session session)
<add> AccessMgrImplTest.checkAccess( "CHCK-ACS TU1_UPD TO1 TOP1 ", UserTestData.USERS_TU1_UPD,
<add> PermTestData.OBJS_TOB1,
<add> PermTestData.OPS_TOP1, PermTestData.OBJS_TOB3, PermTestData.OPS_TOP3 );
<add> AccessMgrImplTest.checkAccess( "CHCK-ACS TU3 TO3 TOP1 ", UserTestData.USERS_TU3, PermTestData.OBJS_TOB3,
<add> PermTestData.OPS_TOP3,
<add> PermTestData.OBJS_TOB2, PermTestData.OPS_TOP1 );
<add> AccessMgrImplTest.checkAccess( "CHCK-ACS TU4 TO4 TOP1 ", UserTestData.USERS_TU4, PermTestData.OBJS_TOB2,
<add> PermTestData.OPS_TOP2,
<add> PermTestData.OBJS_TOB2, PermTestData.OPS_TOP1 );
<add> }
<add>
<add>
<add> @Test
<add> public void testAddActiveRole()
<add> {
<add> // Add the needed data for this test
<add> // from testAddOrgUnit
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add>
<add> // from testAddRole
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR8_DSD", RoleTestData.ROLES_TR8_DSD );
<add>
<add> // from testAdminMgrAddRoleDescendant
<add> AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR11-DESC-DSD", RoleTestData.ROLES_TR11_DESC_DSD );
<add> AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR12-DESC-DSD", RoleTestData.ROLES_TR12_DESC_DSD );
<add> AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR13-DESC-DSD", RoleTestData.ROLES_TR13_DESC_DSD );
<add>
<add> // from testAdminMgrCreateDsdSet
<add> AdminMgrImplTest.createDsdSet( "ADD-DSD T1", RoleTestData.DSD_T1 );
<add> AdminMgrImplTest.createDsdSet( "ADD-DSD T4", RoleTestData.DSD_T4 );
<add> AdminMgrImplTest.createDsdSet( "ADD-DSD T5", RoleTestData.DSD_T5 );
<add> AdminMgrImplTest.createDsdSet( "ADD-DSD T6", RoleTestData.DSD_T6 );
<add>
<add> // from testAdminMgrAddUser
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU8_SSD", UserTestData.USERS_TU8_SSD, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU9_SSD_HIER", UserTestData.USERS_TU9_SSD_HIER, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU10_SSD_HIER", UserTestData.USERS_TU10_SSD_HIER, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU11_SSD_HIER", UserTestData.USERS_TU11_SSD_HIER, true );
<add>
<add> // from testAdminMgrUpdateUser
<add> AdminMgrImplTest.updateUsers( "UPD USERS TU1_UPD", UserTestData.USERS_TU1_UPD );
<add>
<add> // from testAssignUser
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU1 TR1", UserTestData.USERS_TU1, RoleTestData.ROLES_TR1, false );
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2, true );
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3, true );
<add> AdminMgrImplTest.assignUsersDSD( "ASGN-USRS_DSDT1 TU8 DSD_T1", UserTestData.USERS_TU8_SSD, RoleTestData.DSD_T1 );
<add> AdminMgrImplTest.assignUsersDSD( "ASGN-USRS_DSDT4B TU9 DSD_T4_B", UserTestData.USERS_TU9_SSD_HIER,
<add> RoleTestData.DSD_T4_B );
<add> AdminMgrImplTest.assignUsersDSD( "ASGN-USRS_DSDT5B TU10 DSD_T5_B", UserTestData.USERS_TU10_SSD_HIER,
<add> RoleTestData.DSD_T5_B );
<add> AdminMgrImplTest.assignUsersDSD( "ASGN-USRS_DSDT6B TU11 DSD_T6_B", UserTestData.USERS_TU11_SSD_HIER,
<add> RoleTestData.DSD_T6_B );
<add>
<add> // The test itself
<add> // public void addActiveRole(Session session, String role)
<add> AccessMgrImplTest.addActiveRoles( "ADD-ACT-RLS TU1_UPD TR1 bad:TR2", UserTestData.USERS_TU1_UPD,
<add> RoleTestData.ROLES_TR1,
<add> RoleTestData.ROLES_TR2 );
<add> AccessMgrImplTest.addActiveRoles( "ADD-ACT-RLS TU3 TR3 bad:TR1:", UserTestData.USERS_TU3,
<add> RoleTestData.ROLES_TR3,
<add> RoleTestData.ROLES_TR1 );
<add> AccessMgrImplTest.addActiveRoles( "ADD-ACT-RLS TU4 TR2 bad:TR1", UserTestData.USERS_TU4,
<add> RoleTestData.ROLES_TR2,
<add> RoleTestData.ROLES_TR1 );
<add> AccessMgrImplTest.addActiveRolesDSD( "ADD-ACT-RLS-USRS_DSDT1 TU8 DSD_T1", UserTestData.USERS_TU8_SSD,
<add> RoleTestData.DSD_T1 );
<add> AccessMgrImplTest.addActiveRolesDSD( "ADD-ACT-RLS-USRS_DSDT4B TU9 DSD_T4_B", UserTestData.USERS_TU9_SSD_HIER,
<add> RoleTestData.DSD_T4_B );
<add> AccessMgrImplTest.addActiveRolesDSD( "ADD-ACT-RLS-USRS_DSDT5B TU10 DSD_T5_B", UserTestData.USERS_TU10_SSD_HIER,
<add> RoleTestData.DSD_T5_B );
<add> AccessMgrImplTest.addActiveRolesDSD( "ADD-ACT-RLS-USRS_DSDT6B TU11 DSD_T6_B", UserTestData.USERS_TU11_SSD_HIER,
<add> RoleTestData.DSD_T6_B );
<add> }
<add>
<add>
<add> @Test
<add> public void testDropActiveRole()
<add> {
<add> // Add the needed data for this test
<add> // from testAddOrgUnit
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add>
<add> // from testAddRole
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR8_DSD", RoleTestData.ROLES_TR8_DSD );
<add>
<add> // from testAdminMgrAddRoleDescendant
<add> AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR11-DESC-DSD", RoleTestData.ROLES_TR11_DESC_DSD );
<add> AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR12-DESC-DSD", RoleTestData.ROLES_TR12_DESC_DSD );
<add> AdminMgrImplTest.addRoleDescendant( "ADD-RLS-TR13-DESC-DSD", RoleTestData.ROLES_TR13_DESC_DSD );
<add>
<add> // from testAdminMgrCreateDsdSet
<add> AdminMgrImplTest.createDsdSet( "ADD-DSD T1", RoleTestData.DSD_T1 );
<add> AdminMgrImplTest.createDsdSet( "ADD-DSD T4", RoleTestData.DSD_T4 );
<add> AdminMgrImplTest.createDsdSet( "ADD-DSD T5", RoleTestData.DSD_T5 );
<add> AdminMgrImplTest.createDsdSet( "ADD-DSD T6", RoleTestData.DSD_T6 );
<add>
<add> // from testAdminMgrAddUser
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU8_SSD", UserTestData.USERS_TU8_SSD, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU9_SSD_HIER", UserTestData.USERS_TU9_SSD_HIER, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU10_SSD_HIER", UserTestData.USERS_TU10_SSD_HIER, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU11_SSD_HIER", UserTestData.USERS_TU11_SSD_HIER, true );
<add>
<add> // from testAdminMgrUpdateUser
<add> AdminMgrImplTest.updateUsers( "UPD USERS TU1_UPD", UserTestData.USERS_TU1_UPD );
<add>
<add> // from testAssignUser
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU1 TR1", UserTestData.USERS_TU1, RoleTestData.ROLES_TR1, false );
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2, true );
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3, true );
<add> AdminMgrImplTest.assignUsersDSD( "ASGN-USRS_DSDT1 TU8 DSD_T1", UserTestData.USERS_TU8_SSD, RoleTestData.DSD_T1 );
<add> AdminMgrImplTest.assignUsersDSD( "ASGN-USRS_DSDT4B TU9 DSD_T4_B", UserTestData.USERS_TU9_SSD_HIER,
<add> RoleTestData.DSD_T4_B );
<add>
<add> // The test itself
<add> // public void dropActiveRole(Session session, String role)
<add> AccessMgrImplTest.dropActiveRoles( "DRP-ACT-RLS TU1_UPD TR1 bad:TR2", UserTestData.USERS_TU1_UPD,
<add> RoleTestData.ROLES_TR1 );
<add> AccessMgrImplTest.dropActiveRoles( "DRP-ACT-RLS TU3 TR3 bad:TR1", UserTestData.USERS_TU3,
<add> RoleTestData.ROLES_TR3 );
<add> AccessMgrImplTest.dropActiveRoles( "DRP-ACT-RLS TU4 TR2 bad:TR1", UserTestData.USERS_TU4,
<add> RoleTestData.ROLES_TR2 );
<add> }
<add>
<add>
<add> @Test
<add> public void testSessionPermission()
<add> {
<add> // Add the needed data for this test
<add> // from testAddOrgUnit
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_APP1", OrgUnitTestData.ORGS_APP1 );
<add>
<add> // from testAddRole
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS ROLES_TR5_HIER", RoleTestData.ROLES_TR5_HIER );
<add>
<add> // from testAdminMgrAddRoleInheritance
<add> AdminMgrImplTest.addInheritedRoles( "ADD-INHERIT-RLS ROLES_TR5_HIER", RoleTestData.ROLES_TR5_HIER );
<add>
<add> // from testAdminMgrAddUser
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU7_HIER", UserTestData.USERS_TU7_HIER, true );
<add>
<add> // from testAdminMgrUpdateUser
<add> AdminMgrImplTest.updateUsers( "UPD USERS TU1_UPD", UserTestData.USERS_TU1_UPD );
<add>
<add> // from testAssignUser
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU1 TR1", UserTestData.USERS_TU1, RoleTestData.ROLES_TR1, false );
<add> AdminMgrImplTest.assignUsersH( "ASGN-USRS_H TU7 HIER TR5 HIER", UserTestData.USERS_TU7_HIER,
<add> RoleTestData.ROLES_TR5_HIER, true );
<add>
<add> // from testAddPermissionObj
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB1", PermTestData.OBJS_TOB1, true, false );
<add> AdminMgrImplTest.addPermObjs( "ADD-OBS TOB4", PermTestData.OBJS_TOB4, true, false );
<add>
<add> // from testAddPermissionOp
<add> AdminMgrImplTest.addPermOps( "ADD-OPS TOB1 TOP1", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1, true, false );
<add> AdminMgrImplTest.addPermOps( "ADD-OPS TOB4 TOP4", PermTestData.OBJS_TOB4, PermTestData.OPS_TOP4, true, false );
<add>
<add> // from testGrantPermissionRole
<add> AdminMgrImplTest.addRoleGrants( "GRNT-PRMS TR1 TOB1 TOP1", RoleTestData.ROLES_TR1, PermTestData.OBJS_TOB1,
<add> PermTestData.OPS_TOP1, true, false );
<add> AdminMgrImplTest.addRoleGrantsH( "GRNT-PRMS_H ROLES_TR5_HIER TOB4 TOP4", RoleTestData.ROLES_TR5_HIER,
<add> PermTestData.OBJS_TOB4,
<add> PermTestData.OPS_TOP4 );
<add>
<add> // The test itself
<add> // public List<Permission> sessionPermissions(Session session)
<add> // public static void sessionPermissions(String msg, String[][] uArray, String[][] oArray, String[][] opArray)
<add> AccessMgrImplTest.sessionPermissions( "SESS-PRMS TU1_UPD TO1 TOP1 ", UserTestData.USERS_TU1_UPD,
<add> PermTestData.OBJS_TOB1,
<add> PermTestData.OPS_TOP1 );
<add> AccessMgrImplTest.sessionPermissionsH( "SESS-PRMS_H USERS_TU7_HIER OBJS_TOB4 OPS_TOP4 ",
<add> UserTestData.USERS_TU7_HIER,
<add> PermTestData.OBJS_TOB4, PermTestData.OPS_TOP4 );
<add> }
<add>
<add>
<add> @Test
<add> public void testCreateSessionWithRole()
<add> {
<add> // Add the needed data for this test
<add> // from testAddOrgUnit
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add>
<add> // from testAddRole
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
<add>
<add> // from testAdminMgrAddUser
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
<add>
<add> // from testAdminMgrUpdateUser
<add> AdminMgrImplTest.updateUsers( "UPD USERS TU1_UPD", UserTestData.USERS_TU1_UPD );
<add>
<add> // from testAssignUser
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU1 TR1", UserTestData.USERS_TU1, RoleTestData.ROLES_TR1, false );
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2, true );
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3, true );
<add>
<add> // The test itself
<add> // public Session createSession(User user, boolean isTrusted)
<add> AccessMgrImplTest.createSessionsWithRoles( "CR-SESS-WRLS TU1_UPD TR1", UserTestData.USERS_TU1_UPD,
<add> RoleTestData.ROLES_TR1 );
<add> AccessMgrImplTest.createSessionsWithRoles( "CR-SESS-WRLS TU3 TR3", UserTestData.USERS_TU3,
<add> RoleTestData.ROLES_TR3 );
<add> AccessMgrImplTest.createSessionsWithRoles( "CR-SESS-WRLS TU4 TR2", UserTestData.USERS_TU4,
<add> RoleTestData.ROLES_TR2 );
<add> }
<add>
<add>
<add> @Test
<add> public void testCreateSessionWithRolesTrusted()
<add> {
<add> // Add the needed data for this test
<add> // from testAddOrgUnit
<add> DelegatedMgrImplTest.addOrgUnits( "ADD ORGS_DEV1", OrgUnitTestData.ORGS_DEV1 );
<add>
<add> // from testAddRole
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR1", RoleTestData.ROLES_TR1 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR2", RoleTestData.ROLES_TR2 );
<add> AdminMgrImplTest.addRoles( "ADD-RLS TR3", RoleTestData.ROLES_TR3 );
<add>
<add> // from testAdminMgrAddUser
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU1", UserTestData.USERS_TU1, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU3", UserTestData.USERS_TU3, true );
<add> AdminMgrImplTest.addUsers( "ADD-USRS TU4", UserTestData.USERS_TU4, true );
<add>
<add> // from testAdminMgrUpdateUser
<add> AdminMgrImplTest.updateUsers( "UPD USERS TU1_UPD", UserTestData.USERS_TU1_UPD );
<add>
<add> // from testAssignUser
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU1 TR1", UserTestData.USERS_TU1, RoleTestData.ROLES_TR1, false );
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2, true );
<add> AdminMgrImplTest.assignUsers( "ASGN-USRS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3, true );
<add>
<add> // The test itself
<add> // public Session createSession(User user, boolean isTrusted)
<add> AccessMgrImplTest.createSessionsWithRolesTrusted( "CR-SESS-WRLS-TRST TU1_UPD TR1", UserTestData.USERS_TU1_UPD,
<add> RoleTestData.ROLES_TR1 );
<add> AccessMgrImplTest.createSessionsWithRolesTrusted( "CR-SESS-WRLS-TRST TU3 TR3", UserTestData.USERS_TU3,
<add> RoleTestData.ROLES_TR3 );
<add> AccessMgrImplTest.createSessionsWithRolesTrusted( "CR-SESS-WRLS-TRST TU4 TR2", UserTestData.USERS_TU4,
<add> RoleTestData.ROLES_TR2 );
<add> }
<add>}
|
|
Java
|
apache-2.0
|
1dc1149207b67ee1e2adf1ad07d12aa93a8052c7
| 0 |
jwillia/kc-rice1,UniversityOfHawaiiORS/rice,geothomasp/kualico-rice-kc,sonamuthu/rice-1,gathreya/rice-kc,bhutchinson/rice,cniesen/rice,ewestfal/rice,rojlarge/rice-kc,UniversityOfHawaiiORS/rice,rojlarge/rice-kc,bhutchinson/rice,bhutchinson/rice,ewestfal/rice,bhutchinson/rice,geothomasp/kualico-rice-kc,ewestfal/rice-svn2git-test,geothomasp/kualico-rice-kc,smith750/rice,jwillia/kc-rice1,gathreya/rice-kc,cniesen/rice,ewestfal/rice-svn2git-test,sonamuthu/rice-1,smith750/rice,gathreya/rice-kc,bsmith83/rice-1,smith750/rice,cniesen/rice,ewestfal/rice-svn2git-test,UniversityOfHawaiiORS/rice,bsmith83/rice-1,shahess/rice,cniesen/rice,kuali/kc-rice,ewestfal/rice,gathreya/rice-kc,gathreya/rice-kc,cniesen/rice,bhutchinson/rice,geothomasp/kualico-rice-kc,kuali/kc-rice,kuali/kc-rice,smith750/rice,ewestfal/rice,sonamuthu/rice-1,ewestfal/rice,rojlarge/rice-kc,UniversityOfHawaiiORS/rice,bsmith83/rice-1,geothomasp/kualico-rice-kc,kuali/kc-rice,UniversityOfHawaiiORS/rice,ewestfal/rice-svn2git-test,jwillia/kc-rice1,shahess/rice,shahess/rice,shahess/rice,smith750/rice,shahess/rice,sonamuthu/rice-1,jwillia/kc-rice1,jwillia/kc-rice1,rojlarge/rice-kc,bsmith83/rice-1,kuali/kc-rice,rojlarge/rice-kc
|
/**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.krad.demo.uif.library.controls;
import org.junit.Test;
import org.kuali.rice.testtools.selenium.WebDriverLegacyITBase;
/**
* @author Kuali Rice Team ([email protected])
*/
public class DemoControlSelectAft extends WebDriverLegacyITBase {
/**
* /kr-krad/kradsampleapp?viewId=Demo-SelectControlView&methodToCall=start
*/
public static final String BOOKMARK_URL = "/kr-krad/kradsampleapp?viewId=Demo-SelectControlView&methodToCall=start";
@Override
protected String getBookmarkUrl() {
return BOOKMARK_URL;
}
@Override
protected void navigate() throws Exception {
waitAndClickById("Demo-LibraryLink", "");
waitAndClickByLinkText("Controls");
waitAndClickByLinkText("Select");
}
protected void testLibraryControlSelectDefault() throws Exception {
assertElementPresentByXpath("//select[@name='inputField1']");
selectByName("inputField1","Option 1");
}
protected void testLibraryControlSelectMultiSelect() throws Exception {
waitAndClickByLinkText("MultiSelect");
assertElementPresentByXpath("//select[@name='inputField2' and @multiple='multiple']");
selectByName("inputField2","Select 1");
selectByName("inputField2","Select 2");
selectByName("inputField2","Select 3");
}
protected void testLibraryControlSelectDisabled() throws Exception {
waitAndClickByLinkText("Disabled");
assertElementPresentByXpath("//select[@name='inputField1' and @disabled='disabled']");
}
protected void testLibraryControlSelectNavigation() throws Exception {
waitAndClickByXpath("//li[@data-tabfor='Demo-SelectControl-Example4']/a");
assertElementPresentByXpath("//div[@data-parent='Demo-SelectControl-Example4']/select/option[@data-location='http://www.kuali.org']");
selectByXpath("//div[@data-parent='Demo-SelectControl-Example4']/select","Kuali.org");
//After this step it might throw some Javascript error on console as browser may invoke popup with "Stay on page" or "Leave Page" option.
}
@Test
public void testControlSelectBookmark() throws Exception {
testLibraryControlSelectDefault();
testLibraryControlSelectMultiSelect();
testLibraryControlSelectDisabled();
testLibraryControlSelectNavigation();
passed();
}
@Test
public void testControlSelectNav() throws Exception {
testLibraryControlSelectDefault();
testLibraryControlSelectMultiSelect();
testLibraryControlSelectDisabled();
testLibraryControlSelectNavigation();
passed();
}
}
|
rice-framework/krad-sampleapp/web/src/it/java/org/kuali/rice/krad/demo/uif/library/controls/DemoControlSelectAft.java
|
/**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.krad.demo.uif.library.controls;
import org.junit.Test;
import org.kuali.rice.testtools.selenium.WebDriverLegacyITBase;
/**
* @author Kuali Rice Team ([email protected])
*/
public class DemoControlSelectAft extends WebDriverLegacyITBase {
/**
* /kr-krad/kradsampleapp?viewId=Demo-SelectControlView&methodToCall=start
*/
public static final String BOOKMARK_URL = "/kr-krad/kradsampleapp?viewId=Demo-SelectControlView&methodToCall=start";
@Override
protected String getBookmarkUrl() {
return BOOKMARK_URL;
}
@Override
protected void navigate() throws Exception {
waitAndClickById("Demo-LibraryLink", "");
waitAndClickByLinkText("Controls");
waitAndClickByLinkText("Select");
}
protected void testLibraryControlSelectDefault() throws Exception {
assertElementPresentByXpath("//select[@name='inputField1']");
}
protected void testLibraryControlSelectMultiSelect() throws Exception {
waitAndClickByLinkText("MultiSelect");
assertElementPresentByXpath("//select[@name='inputField2' and @multiple='multiple']");
}
protected void testLibraryControlSelectDisabled() throws Exception {
waitAndClickByLinkText("Disabled");
assertElementPresentByXpath("//select[@name='inputField1' and @disabled='disabled']");
}
protected void testLibraryControlSelectNavigation() throws Exception {
waitAndClickByXpath("//li[@data-tabfor='Demo-SelectControl-Example4']/a");
assertElementPresentByXpath("//div[@data-parent='Demo-SelectControl-Example4']/select/option[@data-location='http://www.kuali.org']");
}
@Test
public void testControlSelectBookmark() throws Exception {
testLibraryControlSelectDefault();
testLibraryControlSelectMultiSelect();
testLibraryControlSelectDisabled();
testLibraryControlSelectNavigation();
passed();
}
@Test
public void testControlSelectNav() throws Exception {
testLibraryControlSelectDefault();
testLibraryControlSelectMultiSelect();
testLibraryControlSelectDisabled();
testLibraryControlSelectNavigation();
passed();
}
}
|
RICEQA-331 : Fill AFT per-screen item gap: KRAD Library: Controls: Select
|
rice-framework/krad-sampleapp/web/src/it/java/org/kuali/rice/krad/demo/uif/library/controls/DemoControlSelectAft.java
|
RICEQA-331 : Fill AFT per-screen item gap: KRAD Library: Controls: Select
|
<ide><path>ice-framework/krad-sampleapp/web/src/it/java/org/kuali/rice/krad/demo/uif/library/controls/DemoControlSelectAft.java
<ide>
<ide> protected void testLibraryControlSelectDefault() throws Exception {
<ide> assertElementPresentByXpath("//select[@name='inputField1']");
<add> selectByName("inputField1","Option 1");
<ide> }
<ide>
<ide> protected void testLibraryControlSelectMultiSelect() throws Exception {
<ide> waitAndClickByLinkText("MultiSelect");
<ide> assertElementPresentByXpath("//select[@name='inputField2' and @multiple='multiple']");
<add> selectByName("inputField2","Select 1");
<add> selectByName("inputField2","Select 2");
<add> selectByName("inputField2","Select 3");
<ide> }
<ide>
<ide> protected void testLibraryControlSelectDisabled() throws Exception {
<ide> protected void testLibraryControlSelectNavigation() throws Exception {
<ide> waitAndClickByXpath("//li[@data-tabfor='Demo-SelectControl-Example4']/a");
<ide> assertElementPresentByXpath("//div[@data-parent='Demo-SelectControl-Example4']/select/option[@data-location='http://www.kuali.org']");
<add> selectByXpath("//div[@data-parent='Demo-SelectControl-Example4']/select","Kuali.org");
<add> //After this step it might throw some Javascript error on console as browser may invoke popup with "Stay on page" or "Leave Page" option.
<ide> }
<ide>
<ide> @Test
|
|
Java
|
apache-2.0
|
e45607a493dd60e40e4c405d5dd7f94ba074c666
| 0 |
machristie/airavata,machristie/airavata,apache/airavata,apache/airavata,jjj117/airavata,gouravshenoy/airavata,anujbhan/airavata,anujbhan/airavata,glahiru/airavata,anujbhan/airavata,gouravshenoy/airavata,apache/airavata,anujbhan/airavata,machristie/airavata,dogless/airavata,anujbhan/airavata,hasinitg/airavata,dogless/airavata,hasinitg/airavata,machristie/airavata,apache/airavata,hasinitg/airavata,gouravshenoy/airavata,jjj117/airavata,glahiru/airavata,hasinitg/airavata,anujbhan/airavata,glahiru/airavata,hasinitg/airavata,apache/airavata,glahiru/airavata,jjj117/airavata,anujbhan/airavata,hasinitg/airavata,jjj117/airavata,jjj117/airavata,dogless/airavata,dogless/airavata,machristie/airavata,dogless/airavata,gouravshenoy/airavata,gouravshenoy/airavata,machristie/airavata,glahiru/airavata,machristie/airavata,apache/airavata,apache/airavata,gouravshenoy/airavata,gouravshenoy/airavata,apache/airavata,jjj117/airavata,dogless/airavata
|
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.airavata.gfac.monitor.impl.pull.qstat;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.AiravataZKUtils;
import org.apache.airavata.common.utils.Constants;
import org.apache.airavata.common.utils.MonitorPublisher;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.commons.gfac.type.HostDescription;
import org.apache.airavata.gfac.GFacException;
import org.apache.airavata.gfac.core.cpi.GFac;
import org.apache.airavata.gfac.core.monitor.MonitorID;
import org.apache.airavata.gfac.core.monitor.TaskIdentity;
import org.apache.airavata.gfac.core.monitor.state.JobStatusChangeRequest;
import org.apache.airavata.gfac.core.monitor.state.TaskStatusChangeRequest;
import org.apache.airavata.gfac.monitor.HostMonitorData;
import org.apache.airavata.gfac.monitor.UserMonitorData;
import org.apache.airavata.gfac.monitor.core.PullMonitor;
import org.apache.airavata.gfac.monitor.exception.AiravataMonitorException;
import org.apache.airavata.gfac.monitor.impl.push.amqp.SimpleJobFinishConsumer;
import org.apache.airavata.gfac.monitor.util.CommonUtils;
import org.apache.airavata.gsi.ssh.api.SSHApiException;
import org.apache.airavata.gsi.ssh.api.authentication.AuthenticationInfo;
import org.apache.airavata.model.workspace.experiment.JobState;
import org.apache.airavata.model.workspace.experiment.TaskState;
import org.apache.airavata.schemas.gfac.GsisshHostType;
import org.apache.airavata.schemas.gfac.SSHHostType;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.eventbus.EventBus;
/**
* This monitor is based on qstat command which can be run
* in grid resources and retrieve the job status.
*/
public class HPCPullMonitor extends PullMonitor {
private final static Logger logger = LoggerFactory.getLogger(HPCPullMonitor.class);
public static final int FAILED_COUNT = 5;
// I think this should use DelayedBlocking Queue to do the monitoring*/
private BlockingQueue<UserMonitorData> queue;
private boolean startPulling = false;
private Map<String, ResourceConnection> connections;
private MonitorPublisher publisher;
private LinkedBlockingQueue<String> cancelJobList;
private List<String> completedJobsFromPush;
private GFac gfac;
private AuthenticationInfo authenticationInfo;
public HPCPullMonitor() {
connections = new HashMap<String, ResourceConnection>();
queue = new LinkedBlockingDeque<UserMonitorData>();
publisher = new MonitorPublisher(new EventBus());
cancelJobList = new LinkedBlockingQueue<String>();
completedJobsFromPush = new ArrayList<String>();
(new SimpleJobFinishConsumer(this.completedJobsFromPush)).listen();
}
public HPCPullMonitor(MonitorPublisher monitorPublisher, AuthenticationInfo authInfo) {
connections = new HashMap<String, ResourceConnection>();
queue = new LinkedBlockingDeque<UserMonitorData>();
publisher = monitorPublisher;
authenticationInfo = authInfo;
cancelJobList = new LinkedBlockingQueue<String>();
this.completedJobsFromPush = new ArrayList<String>();
(new SimpleJobFinishConsumer(this.completedJobsFromPush)).listen();
}
public HPCPullMonitor(BlockingQueue<UserMonitorData> queue, MonitorPublisher publisher) {
this.queue = queue;
this.publisher = publisher;
connections = new HashMap<String, ResourceConnection>();
cancelJobList = new LinkedBlockingQueue<String>();
this.completedJobsFromPush = new ArrayList<String>();
(new SimpleJobFinishConsumer(this.completedJobsFromPush)).listen();
}
public void run() {
/* implement a logic to pick each monitorID object from the queue and do the
monitoring
*/
this.startPulling = true;
while (this.startPulling && !ServerSettings.isStopAllThreads()) {
try {
startPulling();
// After finishing one iteration of the full queue this thread sleeps 1 second
Thread.sleep(10000);
} catch (Exception e) {
// we catch all the exceptions here because no matter what happens we do not stop running this
// thread, but ideally we should report proper error messages, but this is handled in startPulling
// method, incase something happen in Thread.sleep we handle it with this catch block.
e.printStackTrace();
logger.error(e.getMessage());
}
}
// thread is going to return so we close all the connections
Iterator<String> iterator = connections.keySet().iterator();
while (iterator.hasNext()) {
String next = iterator.next();
ResourceConnection resourceConnection = connections.get(next);
try {
resourceConnection.getCluster().disconnect();
} catch (SSHApiException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
/**
* This method will can invoke when PullMonitor needs to start
* and it has to invoke in the frequency specified below,
*
* @return if the start process is successful return true else false
*/
synchronized public boolean startPulling() throws AiravataMonitorException {
// take the top element in the queue and pull the data and put that element
// at the tail of the queue
//todo this polling will not work with multiple usernames but with single user
// and multiple hosts, currently monitoring will work
UserMonitorData take = null;
JobStatusChangeRequest jobStatus = new JobStatusChangeRequest();
MonitorID currentMonitorID = null;
HostDescription currentHostDescription = null;
try {
take = this.queue.take();
List<MonitorID> completedJobs = new ArrayList<MonitorID>();
List<HostMonitorData> hostMonitorData = take.getHostMonitorData();
for (HostMonitorData iHostMonitorData : hostMonitorData) {
if (iHostMonitorData.getHost().getType() instanceof GsisshHostType
|| iHostMonitorData.getHost().getType() instanceof SSHHostType) {
currentHostDescription = iHostMonitorData.getHost();
String hostName = iHostMonitorData.getHost().getType().getHostAddress();
ResourceConnection connection = null;
if (connections.containsKey(hostName)) {
if(!connections.get(hostName).isConnected()){
connection = new ResourceConnection(iHostMonitorData,getAuthenticationInfo());
connections.put(hostName, connection);
}else{
logger.debug("We already have this connection so not going to create one");
connection = connections.get(hostName);
}
} else {
connection = new ResourceConnection(iHostMonitorData,getAuthenticationInfo());
connections.put(hostName, connection);
}
// before we get the statuses, we check the cancel job list and remove them permanently
List<MonitorID> monitorID = iHostMonitorData.getMonitorIDs();
Iterator<String> iterator1 = cancelJobList.iterator();
for(MonitorID iMonitorID:monitorID){
while(iterator1.hasNext()) {
String cancelMId = iterator1.next();
if (cancelMId.equals(iMonitorID.getExperimentID() + "+" + iMonitorID.getTaskID())) {
logger.info("Found a match in monitoring Queue, so marking this job to remove from monitor queue " + cancelMId);
logger.info("ExperimentID: " + cancelMId.split("\\+")[0] + ",TaskID: " + cancelMId.split("\\+")[1] + "JobID" + iMonitorID.getJobID());
completedJobs.add(iMonitorID);
iMonitorID.setStatus(JobState.CANCELED);
iterator1.remove();
}
}
}
Iterator<String> iterator = completedJobsFromPush.iterator();
for(MonitorID iMonitorID:monitorID){
while(iterator.hasNext()) {
String cancelMId = iterator.next();
if (cancelMId.equals(iMonitorID.getUserName() + "," + iMonitorID.getJobName())) {
logger.info("This job is finished because push notification came with <username,jobName> " + cancelMId);
completedJobs.add(iMonitorID);
iterator.remove();
iMonitorID.setStatus(JobState.COMPLETE);
}
}
}
Map<String, JobState> jobStatuses = connection.getJobStatuses(monitorID);
for (MonitorID iMonitorID : monitorID) {
currentMonitorID = iMonitorID;
if (!JobState.CANCELED.equals(iMonitorID.getStatus())&&
!JobState.COMPLETE.equals(iMonitorID.getStatus())) {
iMonitorID.setStatus(jobStatuses.get(iMonitorID.getJobID() + "," + iMonitorID.getJobName())); //IMPORTANT this is NOT a simple setter we have a logic
}
jobStatus = new JobStatusChangeRequest(iMonitorID);
// we have this JobStatus class to handle amqp monitoring
publisher.publish(jobStatus);
// if the job is completed we do not have to put the job to the queue again
iMonitorID.setLastMonitored(new Timestamp((new Date()).getTime()));
// After successful monitoring perform follow ing actions to cleanup the queue, if necessary
if (jobStatus.getState().equals(JobState.COMPLETE)) {
completedJobs.add(iMonitorID);
try {
gfac.invokeOutFlowHandlers(iMonitorID.getJobExecutionContext());
} catch (GFacException e) {
publisher.publish(new TaskStatusChangeRequest(new TaskIdentity(iMonitorID.getExperimentID(), iMonitorID.getWorkflowNodeID(),
iMonitorID.getTaskID()), TaskState.FAILED));
//FIXME this is a case where the output retrieving fails even if the job execution was a success. Thus updating the task status
//should be done understanding whole workflow of job submission and data transfer
// publisher.publish(new ExperimentStatusChangedEvent(new ExperimentIdentity(iMonitorID.getExperimentID()),
// ExperimentState.FAILED));
logger.info(e.getLocalizedMessage(), e);
}
} else if (iMonitorID.getFailedCount() > FAILED_COUNT) {
logger.error("Tried to monitor the job with ID " + iMonitorID.getJobID() + " But failed 3 times, so skip this Job from Monitor");
iMonitorID.setLastMonitored(new Timestamp((new Date()).getTime()));
completedJobs.add(iMonitorID);
try {
logger.error("Launching outflow handlers to check output are genereated or not");
gfac.invokeOutFlowHandlers(iMonitorID.getJobExecutionContext());
} catch (GFacException e) {
publisher.publish(new TaskStatusChangeRequest(new TaskIdentity(iMonitorID.getExperimentID(), iMonitorID.getWorkflowNodeID(),
iMonitorID.getTaskID()), TaskState.FAILED));
logger.info(e.getLocalizedMessage(), e);
}
} else {
// Evey
iMonitorID.setLastMonitored(new Timestamp((new Date()).getTime()));
// if the job is complete we remove it from the Map, if any of these maps
// get empty this userMonitorData will get delete from the queue
}
}
} else {
logger.debug("Qstat Monitor doesn't handle non-gsissh hosts");
}
}
// We have finished all the HostMonitorData object in userMonitorData, now we need to put it back
// now the userMonitorData goes back to the tail of the queue
queue.put(take);
// cleaning up the completed jobs, this method will remove some of the userMonitorData from the queue if
// they become empty
for (MonitorID completedJob : completedJobs) {
CommonUtils.removeMonitorFromQueue(queue, completedJob);
}
// updateZkWithJobCount(take , completedJobs);
} catch (InterruptedException e) {
if (!this.queue.contains(take)) {
try {
this.queue.put(take);
} catch (InterruptedException e1) {
e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
logger.error("Error handling the job with Job ID:" + currentMonitorID.getJobID());
throw new AiravataMonitorException(e);
} catch (SSHApiException e) {
logger.error(e.getMessage());
if (e.getMessage().contains("Unknown Job Id Error")) {
// in this case job is finished or may be the given job ID is wrong
jobStatus.setState(JobState.UNKNOWN);
publisher.publish(jobStatus);
} else if (e.getMessage().contains("illegally formed job identifier")) {
logger.error("Wrong job ID is given so dropping the job from monitoring system");
} else if (!this.queue.contains(take)) { // we put the job back to the queue only if its state is not unknown
if (currentMonitorID == null) {
logger.error("Monitoring the jobs failed, for user: " + take.getUserName()
+ " in Host: " + currentHostDescription.getType().getHostAddress());
} else {
if (currentMonitorID != null) {
if (currentMonitorID.getFailedCount() < 2) {
try {
currentMonitorID.setFailedCount(currentMonitorID.getFailedCount() + 1);
this.queue.put(take);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
} else {
logger.error(e.getMessage());
logger.error("Tried to monitor the job 3 times, so dropping of the the Job with ID: " + currentMonitorID.getJobID());
}
}
}
}
throw new AiravataMonitorException("Error retrieving the job status", e);
} catch (Exception e) {
if (currentMonitorID != null) {
if (currentMonitorID.getFailedCount() < 3) {
try {
currentMonitorID.setFailedCount(currentMonitorID.getFailedCount() + 1);
this.queue.put(take);
// if we get a wrong status we wait for a while and request again
Thread.sleep(10000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
} else {
logger.error(e.getMessage());
logger.error("Tryied to monitor the job 3 times, so dropping of the the Job with ID: " + currentMonitorID.getJobID());
}
}
throw new AiravataMonitorException("Error retrieving the job status", e);
}
return true;
}
/**
* Build the /stat/{username}/{hostAddress}/job znode path and store job count
*
* @param userMonitorData
* @param completedJobs
* @throws ApplicationSettingsException
* @throws IOException
* @throws KeeperException
* @throws InterruptedException
*/
private void updateZkWithJobCount(UserMonitorData userMonitorData, List<MonitorID> completedJobs) {
try {
final CountDownLatch latch = new CountDownLatch(1);
ZooKeeper zk = new ZooKeeper(AiravataZKUtils.getZKhostPort(), 6000, new Watcher() {
@Override
public void process(WatchedEvent event) {
if (event.getState() == Event.KeeperState.SyncConnected) {
latch.countDown();
}
}
});
latch.await();
try {
List<String> updatedPathList = new ArrayList<String>();
String pathToUserName = new StringBuilder("/").append(Constants.STAT)
.append("/").append(userMonitorData.getUserName()).toString();
StringBuilder jobPathBuilder;
for (HostMonitorData hostData : userMonitorData.getHostMonitorData()) {
jobPathBuilder = new StringBuilder(pathToUserName).append("/")
.append(hostData.getHost().getType().getHostAddress()).append("/").append(Constants.JOB);
checkAndCreateZNode(zk, jobPathBuilder.toString());
int jobCount = 0;
String jobCountStr = new String(zk.getData(jobPathBuilder.toString(), null, null));
try {
jobCount = Integer.parseInt(jobCountStr);
} catch (NumberFormatException e) {
// do nothing , keep jobCount 0
}
List<MonitorID> idList = hostData.getMonitorIDs();
boolean updatePath = true;
if (idList != null) {
if (jobCount == idList.size()) {
updatePath = false;
} else {
jobCount = idList.size();
}
// removed already updated jobs from complete jobs
for (MonitorID monitorID : idList) {
if (completedJobs.contains(monitorID)) {
completedJobs.remove(monitorID);
}
}
}
if (updatePath) {
zk.setData(jobPathBuilder.toString(), String.valueOf(jobCount).getBytes(), -1);
updatedPathList.add(jobPathBuilder.toString());
}
}
//handle completed jobs
/* If all jobs are completed in a host then monitor queue remove such hosts from monitoring ,but we need
to update those host's stat with JobCount 0 */
for (MonitorID monitorID : completedJobs) {
jobPathBuilder = new StringBuilder(pathToUserName).append("/")
.append(monitorID.getHost().getType().getHostAddress()).append("/").append(Constants.JOB);
zk.setData(jobPathBuilder.toString(), "0".getBytes(), -1);
updatedPathList.add(jobPathBuilder.toString());
}
// trigger orchestrator watcher by saving the updated list to zookeeper
if (updatedPathList.size() > 0) {
StringBuilder strBuilder = new StringBuilder();
for (String updatedPath : updatedPathList) {
strBuilder.append(updatedPath).append(":");
}
strBuilder.deleteCharAt(strBuilder.length() - 1);
zk.setData(("/" + Constants.STAT), strBuilder.toString().getBytes(), -1);
}
zk.close();
} catch (KeeperException e) {
logger.error("Error while storing job count to zookeeper", e);
} catch (InterruptedException e) {
logger.error("Error while storing job count to zookeeper", e);
}
} catch (IOException e) {
logger.error("Error while connecting to the zookeeper server", e);
} catch (ApplicationSettingsException e) {
logger.error("Error while getting zookeeper hostport property", e);
} catch (InterruptedException e) {
logger.error("Error while waiting for SyncConnected message", e);
}
}
/**
* Check whether znode is exist in given path if not create a new znode
* @param zk - zookeeper instance
* @param path - path to check znode
* @throws KeeperException
* @throws InterruptedException
*/
private void checkAndCreateZNode(ZooKeeper zk , String path) throws KeeperException, InterruptedException {
if (zk.exists(path, null) == null) { // if znode doesn't exist
if (path.lastIndexOf("/") > 1) { // recursively traverse to parent znode and check parent exist
checkAndCreateZNode(zk, (path.substring(0, path.lastIndexOf("/"))));
}
zk.create(path, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);// create a znode
}
}
/**
* This is the method to stop the polling process
*
* @return if the stopping process is successful return true else false
*/
public boolean stopPulling() {
this.startPulling = false;
return true;
}
public MonitorPublisher getPublisher() {
return publisher;
}
public void setPublisher(MonitorPublisher publisher) {
this.publisher = publisher;
}
public BlockingQueue<UserMonitorData> getQueue() {
return queue;
}
public void setQueue(BlockingQueue<UserMonitorData> queue) {
this.queue = queue;
}
public boolean authenticate() {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
public Map<String, ResourceConnection> getConnections() {
return connections;
}
public boolean isStartPulling() {
return startPulling;
}
public void setConnections(Map<String, ResourceConnection> connections) {
this.connections = connections;
}
public void setStartPulling(boolean startPulling) {
this.startPulling = startPulling;
}
public GFac getGfac() {
return gfac;
}
public void setGfac(GFac gfac) {
this.gfac = gfac;
}
public AuthenticationInfo getAuthenticationInfo() {
return authenticationInfo;
}
public void setAuthenticationInfo(AuthenticationInfo authenticationInfo) {
this.authenticationInfo = authenticationInfo;
}
public LinkedBlockingQueue<String> getCancelJobList() {
return cancelJobList;
}
public void setCancelJobList(LinkedBlockingQueue<String> cancelJobList) {
this.cancelJobList = cancelJobList;
}
}
|
modules/gfac/gfac-monitor/src/main/java/org/apache/airavata/gfac/monitor/impl/pull/qstat/HPCPullMonitor.java
|
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.airavata.gfac.monitor.impl.pull.qstat;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.AiravataZKUtils;
import org.apache.airavata.common.utils.Constants;
import org.apache.airavata.common.utils.MonitorPublisher;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.commons.gfac.type.HostDescription;
import org.apache.airavata.gfac.GFacException;
import org.apache.airavata.gfac.core.cpi.GFac;
import org.apache.airavata.gfac.core.monitor.MonitorID;
import org.apache.airavata.gfac.core.monitor.TaskIdentity;
import org.apache.airavata.gfac.core.monitor.state.JobStatusChangeRequest;
import org.apache.airavata.gfac.core.monitor.state.TaskStatusChangeRequest;
import org.apache.airavata.gfac.monitor.HostMonitorData;
import org.apache.airavata.gfac.monitor.UserMonitorData;
import org.apache.airavata.gfac.monitor.core.PullMonitor;
import org.apache.airavata.gfac.monitor.exception.AiravataMonitorException;
import org.apache.airavata.gfac.monitor.impl.push.amqp.SimpleJobFinishConsumer;
import org.apache.airavata.gfac.monitor.util.CommonUtils;
import org.apache.airavata.gsi.ssh.api.SSHApiException;
import org.apache.airavata.gsi.ssh.api.authentication.AuthenticationInfo;
import org.apache.airavata.model.workspace.experiment.JobState;
import org.apache.airavata.model.workspace.experiment.TaskState;
import org.apache.airavata.schemas.gfac.GsisshHostType;
import org.apache.airavata.schemas.gfac.SSHHostType;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.eventbus.EventBus;
/**
* This monitor is based on qstat command which can be run
* in grid resources and retrieve the job status.
*/
public class HPCPullMonitor extends PullMonitor {
private final static Logger logger = LoggerFactory.getLogger(HPCPullMonitor.class);
public static final int FAILED_COUNT = 5;
// I think this should use DelayedBlocking Queue to do the monitoring*/
private BlockingQueue<UserMonitorData> queue;
private boolean startPulling = false;
private Map<String, ResourceConnection> connections;
private MonitorPublisher publisher;
private LinkedBlockingQueue<String> cancelJobList;
private List<String> completedJobsFromPush;
private GFac gfac;
private AuthenticationInfo authenticationInfo;
public HPCPullMonitor() {
connections = new HashMap<String, ResourceConnection>();
queue = new LinkedBlockingDeque<UserMonitorData>();
publisher = new MonitorPublisher(new EventBus());
cancelJobList = new LinkedBlockingQueue<String>();
completedJobsFromPush = new ArrayList<String>();
(new SimpleJobFinishConsumer(this.completedJobsFromPush)).listen();
}
public HPCPullMonitor(MonitorPublisher monitorPublisher, AuthenticationInfo authInfo) {
connections = new HashMap<String, ResourceConnection>();
queue = new LinkedBlockingDeque<UserMonitorData>();
publisher = monitorPublisher;
authenticationInfo = authInfo;
cancelJobList = new LinkedBlockingQueue<String>();
this.completedJobsFromPush = new ArrayList<String>();
(new SimpleJobFinishConsumer(this.completedJobsFromPush)).listen();
}
public HPCPullMonitor(BlockingQueue<UserMonitorData> queue, MonitorPublisher publisher) {
this.queue = queue;
this.publisher = publisher;
connections = new HashMap<String, ResourceConnection>();
cancelJobList = new LinkedBlockingQueue<String>();
this.completedJobsFromPush = new ArrayList<String>();
(new SimpleJobFinishConsumer(this.completedJobsFromPush)).listen();
}
public void run() {
/* implement a logic to pick each monitorID object from the queue and do the
monitoring
*/
this.startPulling = true;
while (this.startPulling && !ServerSettings.isStopAllThreads()) {
try {
startPulling();
// After finishing one iteration of the full queue this thread sleeps 1 second
Thread.sleep(10000);
} catch (Exception e) {
// we catch all the exceptions here because no matter what happens we do not stop running this
// thread, but ideally we should report proper error messages, but this is handled in startPulling
// method, incase something happen in Thread.sleep we handle it with this catch block.
e.printStackTrace();
logger.error(e.getMessage());
}
}
// thread is going to return so we close all the connections
Iterator<String> iterator = connections.keySet().iterator();
while (iterator.hasNext()) {
String next = iterator.next();
ResourceConnection resourceConnection = connections.get(next);
try {
resourceConnection.getCluster().disconnect();
} catch (SSHApiException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
/**
* This method will can invoke when PullMonitor needs to start
* and it has to invoke in the frequency specified below,
*
* @return if the start process is successful return true else false
*/
synchronized public boolean startPulling() throws AiravataMonitorException {
// take the top element in the queue and pull the data and put that element
// at the tail of the queue
//todo this polling will not work with multiple usernames but with single user
// and multiple hosts, currently monitoring will work
UserMonitorData take = null;
JobStatusChangeRequest jobStatus = new JobStatusChangeRequest();
MonitorID currentMonitorID = null;
HostDescription currentHostDescription = null;
try {
take = this.queue.take();
List<MonitorID> completedJobs = new ArrayList<MonitorID>();
List<HostMonitorData> hostMonitorData = take.getHostMonitorData();
for (HostMonitorData iHostMonitorData : hostMonitorData) {
if (iHostMonitorData.getHost().getType() instanceof GsisshHostType
|| iHostMonitorData.getHost().getType() instanceof SSHHostType) {
currentHostDescription = iHostMonitorData.getHost();
String hostName = iHostMonitorData.getHost().getType().getHostAddress();
ResourceConnection connection = null;
if (connections.containsKey(hostName)) {
if(!connections.get(hostName).isConnected()){
connection = new ResourceConnection(iHostMonitorData,getAuthenticationInfo());
connections.put(hostName, connection);
}else{
logger.debug("We already have this connection so not going to create one");
connection = connections.get(hostName);
}
} else {
connection = new ResourceConnection(iHostMonitorData,getAuthenticationInfo());
connections.put(hostName, connection);
}
// before we get the statuses, we check the cancel job list and remove them permanently
List<MonitorID> monitorID = iHostMonitorData.getMonitorIDs();
Iterator<String> iterator1 = cancelJobList.iterator();
for(MonitorID iMonitorID:monitorID){
while(iterator1.hasNext()) {
String cancelMId = iterator1.next();
if (cancelMId.equals(iMonitorID.getExperimentID() + "+" + iMonitorID.getTaskID())) {
logger.info("Found a match in monitoring Queue, so marking this job to remove from monitor queue " + cancelMId);
logger.info("ExperimentID: " + cancelMId.split("\\+")[0] + ",TaskID: " + cancelMId.split("\\+")[1] + "JobID" + iMonitorID.getJobID());
completedJobs.add(iMonitorID);
iMonitorID.setStatus(JobState.CANCELED);
iterator1.remove();
}
}
}
Iterator<String> iterator = completedJobsFromPush.iterator();
for(MonitorID iMonitorID:monitorID){
while(iterator.hasNext()) {
String cancelMId = iterator.next();
if (cancelMId.equals(iMonitorID.getUserName() + "," + iMonitorID.getJobName())) {
logger.info("This job is finished because push notification came with <username,jobName> " + cancelMId);
completedJobs.add(iMonitorID);
iterator.remove();
iMonitorID.setStatus(JobState.COMPLETE);
}
}
}
Map<String, JobState> jobStatuses = connection.getJobStatuses(monitorID);
for (MonitorID iMonitorID : monitorID) {
currentMonitorID = iMonitorID;
if (!JobState.CANCELED.equals(iMonitorID.getStatus())&&
!JobState.COMPLETE.equals(iMonitorID.getStatus())) {
iMonitorID.setStatus(jobStatuses.get(iMonitorID.getJobID() + "," + iMonitorID.getJobName())); //IMPORTANT this is NOT a simple setter we have a logic
}
jobStatus = new JobStatusChangeRequest(iMonitorID);
// we have this JobStatus class to handle amqp monitoring
publisher.publish(jobStatus);
// if the job is completed we do not have to put the job to the queue again
iMonitorID.setLastMonitored(new Timestamp((new Date()).getTime()));
// After successful monitoring perform follow ing actions to cleanup the queue, if necessary
if (jobStatus.getState().equals(JobState.COMPLETE)) {
completedJobs.add(iMonitorID);
try {
gfac.invokeOutFlowHandlers(iMonitorID.getJobExecutionContext());
} catch (GFacException e) {
publisher.publish(new TaskStatusChangeRequest(new TaskIdentity(iMonitorID.getExperimentID(), iMonitorID.getWorkflowNodeID(),
iMonitorID.getTaskID()), TaskState.FAILED));
//FIXME this is a case where the output retrieving fails even if the job execution was a success. Thus updating the task status
//should be done understanding whole workflow of job submission and data transfer
// publisher.publish(new ExperimentStatusChangedEvent(new ExperimentIdentity(iMonitorID.getExperimentID()),
// ExperimentState.FAILED));
logger.info(e.getLocalizedMessage(), e);
}
} else if (iMonitorID.getFailedCount() > FAILED_COUNT) {
logger.error("Tried to monitor the job with ID " + iMonitorID.getJobID() + " But failed 3 times, so skip this Job from Monitor");
iMonitorID.setLastMonitored(new Timestamp((new Date()).getTime()));
completedJobs.add(iMonitorID);
try {
logger.error("Launching outflow handlers to check output are genereated or not");
gfac.invokeOutFlowHandlers(iMonitorID.getJobExecutionContext());
} catch (GFacException e) {
publisher.publish(new TaskStatusChangeRequest(new TaskIdentity(iMonitorID.getExperimentID(), iMonitorID.getWorkflowNodeID(),
iMonitorID.getTaskID()), TaskState.FAILED));
logger.info(e.getLocalizedMessage(), e);
}
} else {
// Evey
iMonitorID.setLastMonitored(new Timestamp((new Date()).getTime()));
// if the job is complete we remove it from the Map, if any of these maps
// get empty this userMonitorData will get delete from the queue
}
}
} else {
logger.debug("Qstat Monitor doesn't handle non-gsissh hosts");
}
}
// We have finished all the HostMonitorData object in userMonitorData, now we need to put it back
// now the userMonitorData goes back to the tail of the queue
queue.put(take);
// cleaning up the completed jobs, this method will remove some of the userMonitorData from the queue if
// they become empty
for (MonitorID completedJob : completedJobs) {
CommonUtils.removeMonitorFromQueue(queue, completedJob);
}
updateZkWithJobCount(take , completedJobs);
} catch (InterruptedException e) {
if (!this.queue.contains(take)) {
try {
this.queue.put(take);
} catch (InterruptedException e1) {
e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
logger.error("Error handling the job with Job ID:" + currentMonitorID.getJobID());
throw new AiravataMonitorException(e);
} catch (SSHApiException e) {
logger.error(e.getMessage());
if (e.getMessage().contains("Unknown Job Id Error")) {
// in this case job is finished or may be the given job ID is wrong
jobStatus.setState(JobState.UNKNOWN);
publisher.publish(jobStatus);
} else if (e.getMessage().contains("illegally formed job identifier")) {
logger.error("Wrong job ID is given so dropping the job from monitoring system");
} else if (!this.queue.contains(take)) { // we put the job back to the queue only if its state is not unknown
if (currentMonitorID == null) {
logger.error("Monitoring the jobs failed, for user: " + take.getUserName()
+ " in Host: " + currentHostDescription.getType().getHostAddress());
} else {
if (currentMonitorID != null) {
if (currentMonitorID.getFailedCount() < 2) {
try {
currentMonitorID.setFailedCount(currentMonitorID.getFailedCount() + 1);
this.queue.put(take);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
} else {
logger.error(e.getMessage());
logger.error("Tried to monitor the job 3 times, so dropping of the the Job with ID: " + currentMonitorID.getJobID());
}
}
}
}
throw new AiravataMonitorException("Error retrieving the job status", e);
} catch (Exception e) {
if (currentMonitorID != null) {
if (currentMonitorID.getFailedCount() < 3) {
try {
currentMonitorID.setFailedCount(currentMonitorID.getFailedCount() + 1);
this.queue.put(take);
// if we get a wrong status we wait for a while and request again
Thread.sleep(10000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
} else {
logger.error(e.getMessage());
logger.error("Tryied to monitor the job 3 times, so dropping of the the Job with ID: " + currentMonitorID.getJobID());
}
}
throw new AiravataMonitorException("Error retrieving the job status", e);
}
return true;
}
/**
* Build the /stat/{username}/{hostAddress}/job znode path and store job count
*
* @param userMonitorData
* @param completedJobs
* @throws ApplicationSettingsException
* @throws IOException
* @throws KeeperException
* @throws InterruptedException
*/
private void updateZkWithJobCount(UserMonitorData userMonitorData, List<MonitorID> completedJobs) {
try {
final CountDownLatch latch = new CountDownLatch(1);
ZooKeeper zk = new ZooKeeper(AiravataZKUtils.getZKhostPort(), 6000, new Watcher() {
@Override
public void process(WatchedEvent event) {
if (event.getState() == Event.KeeperState.SyncConnected) {
latch.countDown();
}
}
});
latch.await();
try {
List<String> updatedPathList = new ArrayList<String>();
String pathToUserName = new StringBuilder("/").append(Constants.STAT)
.append("/").append(userMonitorData.getUserName()).toString();
StringBuilder jobPathBuilder;
for (HostMonitorData hostData : userMonitorData.getHostMonitorData()) {
jobPathBuilder = new StringBuilder(pathToUserName).append("/")
.append(hostData.getHost().getType().getHostAddress()).append("/").append(Constants.JOB);
checkAndCreateZNode(zk, jobPathBuilder.toString());
int jobCount = 0;
String jobCountStr = new String(zk.getData(jobPathBuilder.toString(), null, null));
try {
jobCount = Integer.parseInt(jobCountStr);
} catch (NumberFormatException e) {
// do nothing , keep jobCount 0
}
List<MonitorID> idList = hostData.getMonitorIDs();
boolean updatePath = true;
if (idList != null) {
if (jobCount == idList.size()) {
updatePath = false;
} else {
jobCount = idList.size();
}
// removed already updated jobs from complete jobs
for (MonitorID monitorID : idList) {
if (completedJobs.contains(monitorID)) {
completedJobs.remove(monitorID);
}
}
}
if (updatePath) {
zk.setData(jobPathBuilder.toString(), String.valueOf(jobCount).getBytes(), -1);
updatedPathList.add(jobPathBuilder.toString());
}
}
//handle completed jobs
/* If all jobs are completed in a host then monitor queue remove such hosts from monitoring ,but we need
to update those host's stat with JobCount 0 */
for (MonitorID monitorID : completedJobs) {
jobPathBuilder = new StringBuilder(pathToUserName).append("/")
.append(monitorID.getHost().getType().getHostAddress()).append("/").append(Constants.JOB);
zk.setData(jobPathBuilder.toString(), "0".getBytes(), -1);
updatedPathList.add(jobPathBuilder.toString());
}
// trigger orchestrator watcher by saving the updated list to zookeeper
if (updatedPathList.size() > 0) {
StringBuilder strBuilder = new StringBuilder();
for (String updatedPath : updatedPathList) {
strBuilder.append(updatedPath).append(":");
}
strBuilder.deleteCharAt(strBuilder.length() - 1);
zk.setData(("/" + Constants.STAT), strBuilder.toString().getBytes(), -1);
}
zk.close();
} catch (KeeperException e) {
logger.error("Error while storing job count to zookeeper", e);
} catch (InterruptedException e) {
logger.error("Error while storing job count to zookeeper", e);
}
} catch (IOException e) {
logger.error("Error while connecting to the zookeeper server", e);
} catch (ApplicationSettingsException e) {
logger.error("Error while getting zookeeper hostport property", e);
} catch (InterruptedException e) {
logger.error("Error while waiting for SyncConnected message", e);
}
}
/**
* Check whether znode is exist in given path if not create a new znode
* @param zk - zookeeper instance
* @param path - path to check znode
* @throws KeeperException
* @throws InterruptedException
*/
private void checkAndCreateZNode(ZooKeeper zk , String path) throws KeeperException, InterruptedException {
if (zk.exists(path, null) == null) { // if znode doesn't exist
if (path.lastIndexOf("/") > 1) { // recursively traverse to parent znode and check parent exist
checkAndCreateZNode(zk, (path.substring(0, path.lastIndexOf("/"))));
}
zk.create(path, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);// create a znode
}
}
/**
* This is the method to stop the polling process
*
* @return if the stopping process is successful return true else false
*/
public boolean stopPulling() {
this.startPulling = false;
return true;
}
public MonitorPublisher getPublisher() {
return publisher;
}
public void setPublisher(MonitorPublisher publisher) {
this.publisher = publisher;
}
public BlockingQueue<UserMonitorData> getQueue() {
return queue;
}
public void setQueue(BlockingQueue<UserMonitorData> queue) {
this.queue = queue;
}
public boolean authenticate() {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
public Map<String, ResourceConnection> getConnections() {
return connections;
}
public boolean isStartPulling() {
return startPulling;
}
public void setConnections(Map<String, ResourceConnection> connections) {
this.connections = connections;
}
public void setStartPulling(boolean startPulling) {
this.startPulling = startPulling;
}
public GFac getGfac() {
return gfac;
}
public void setGfac(GFac gfac) {
this.gfac = gfac;
}
public AuthenticationInfo getAuthenticationInfo() {
return authenticationInfo;
}
public void setAuthenticationInfo(AuthenticationInfo authenticationInfo) {
this.authenticationInfo = authenticationInfo;
}
public LinkedBlockingQueue<String> getCancelJobList() {
return cancelJobList;
}
public void setCancelJobList(LinkedBlockingQueue<String> cancelJobList) {
this.cancelJobList = cancelJobList;
}
}
|
removing temporarilly
|
modules/gfac/gfac-monitor/src/main/java/org/apache/airavata/gfac/monitor/impl/pull/qstat/HPCPullMonitor.java
|
removing temporarilly
|
<ide><path>odules/gfac/gfac-monitor/src/main/java/org/apache/airavata/gfac/monitor/impl/pull/qstat/HPCPullMonitor.java
<ide> for (MonitorID completedJob : completedJobs) {
<ide> CommonUtils.removeMonitorFromQueue(queue, completedJob);
<ide> }
<del> updateZkWithJobCount(take , completedJobs);
<add>// updateZkWithJobCount(take , completedJobs);
<ide> } catch (InterruptedException e) {
<ide> if (!this.queue.contains(take)) {
<ide> try {
|
|
Java
|
apache-2.0
|
8bee0779e2e01c125ecc42bc19d455d7cd931662
| 0 |
samwgoldman/torquebox,torquebox/torquebox,samwgoldman/torquebox,ksw2599/torquebox,ksw2599/torquebox,torquebox/torquebox-release,torquebox/torquebox-release,torquebox/torquebox-release,mje113/torquebox,torquebox/torquebox-release,mje113/torquebox,ksw2599/torquebox,vaskoz/torquebox,samwgoldman/torquebox,torquebox/torquebox,vaskoz/torquebox,ksw2599/torquebox,mje113/torquebox,torquebox/torquebox,torquebox/torquebox,samwgoldman/torquebox,vaskoz/torquebox,vaskoz/torquebox,mje113/torquebox
|
integration-tests/src/test/java/org/jboss/arquillian/impl/RSpecArchiveGenerator.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2009, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.arquillian.impl;
import java.net.URL;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.arquillian.spi.ApplicationArchiveGenerator;
import org.jboss.arquillian.spi.TestClass;
import org.jruby.Ruby;
import org.jruby.RubyObject;
import org.jruby.RubyClass;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.javasupport.JavaEmbedUtils;
/**
* Use this class by naming it in src/test/resources/META-INF/services/org.jboss.arquillian.spi.ApplicationArchiveGenerator
*/
public class RSpecArchiveGenerator implements ApplicationArchiveGenerator {
public Archive<?> generateApplicationArchive(TestClass testCase) {
System.out.println("JC: generateApplicationArchive for "+testCase.getName());
Validate.notNull(testCase, "TestCase must be specified");
return createDeployment("rack/1.1.0/basic-rack.yml");
}
public JavaArchive createDeployment(String name) {
System.out.println("JC: createDeployment");
String tail = name.substring( name.lastIndexOf( '/' ) + 1 );
String base = tail.substring(0, tail.lastIndexOf( '.' ) );
JavaArchive archive = ShrinkWrap.create( JavaArchive.class, base + ".jar" );
ClassLoader classLoader = getClass().getClassLoader();
URL deploymentDescriptorUrl = classLoader.getResource( name );
archive.addResource( deploymentDescriptorUrl, "/META-INF/" + tail );
return archive;
}
private ApplicationArchiveGenerator delegate = new DeploymentAnnotationArchiveGenerator();
}
|
This thing's presences seems to confuse arquillian when errors occur.
|
integration-tests/src/test/java/org/jboss/arquillian/impl/RSpecArchiveGenerator.java
|
This thing's presences seems to confuse arquillian when errors occur.
|
<ide><path>ntegration-tests/src/test/java/org/jboss/arquillian/impl/RSpecArchiveGenerator.java
<del>/*
<del> * JBoss, Home of Professional Open Source
<del> * Copyright 2009, Red Hat Middleware LLC, and individual contributors
<del> * by the @authors tag. See the copyright.txt in the distribution for a
<del> * full listing of individual contributors.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>package org.jboss.arquillian.impl;
<del>
<del>import java.net.URL;
<del>
<del>import org.jboss.shrinkwrap.api.ShrinkWrap;
<del>import org.jboss.shrinkwrap.api.Archive;
<del>import org.jboss.shrinkwrap.api.spec.JavaArchive;
<del>
<del>import org.jboss.arquillian.spi.ApplicationArchiveGenerator;
<del>import org.jboss.arquillian.spi.TestClass;
<del>
<del>import org.jruby.Ruby;
<del>import org.jruby.RubyObject;
<del>import org.jruby.RubyClass;
<del>import org.jruby.runtime.builtin.IRubyObject;
<del>import org.jruby.javasupport.JavaEmbedUtils;
<del>
<del>/**
<del> * Use this class by naming it in src/test/resources/META-INF/services/org.jboss.arquillian.spi.ApplicationArchiveGenerator
<del> */
<del>public class RSpecArchiveGenerator implements ApplicationArchiveGenerator {
<del>
<del> public Archive<?> generateApplicationArchive(TestClass testCase) {
<del> System.out.println("JC: generateApplicationArchive for "+testCase.getName());
<del> Validate.notNull(testCase, "TestCase must be specified");
<del> return createDeployment("rack/1.1.0/basic-rack.yml");
<del> }
<del>
<del> public JavaArchive createDeployment(String name) {
<del> System.out.println("JC: createDeployment");
<del> String tail = name.substring( name.lastIndexOf( '/' ) + 1 );
<del> String base = tail.substring(0, tail.lastIndexOf( '.' ) );
<del>
<del> JavaArchive archive = ShrinkWrap.create( JavaArchive.class, base + ".jar" );
<del> ClassLoader classLoader = getClass().getClassLoader();
<del> URL deploymentDescriptorUrl = classLoader.getResource( name );
<del> archive.addResource( deploymentDescriptorUrl, "/META-INF/" + tail );
<del> return archive;
<del> }
<del>
<del> private ApplicationArchiveGenerator delegate = new DeploymentAnnotationArchiveGenerator();
<del>}
|
||
Java
|
apache-2.0
|
01b5804c50480e354fdf28a869f04a117d97befd
| 0 |
sakai-mirror/k2,sakai-mirror/k2,sakai-mirror/k2
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.sakaiproject.kernel.rest.test;
import static org.easymock.EasyMock.anyObject;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.junit.Assert.assertTrue;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.sakaiproject.kernel.api.ComponentActivatorException;
import org.sakaiproject.kernel.api.KernelManager;
import org.sakaiproject.kernel.api.Registry;
import org.sakaiproject.kernel.api.RegistryService;
import org.sakaiproject.kernel.api.authz.AuthzResolverService;
import org.sakaiproject.kernel.api.jcr.JCRService;
import org.sakaiproject.kernel.api.jcr.support.JCRNodeFactoryService;
import org.sakaiproject.kernel.api.jcr.support.JCRNodeFactoryServiceException;
import org.sakaiproject.kernel.api.memory.CacheManagerService;
import org.sakaiproject.kernel.api.memory.CacheScope;
import org.sakaiproject.kernel.api.rest.RestProvider;
import org.sakaiproject.kernel.api.session.SessionManagerService;
import org.sakaiproject.kernel.api.user.UserResolverService;
import org.sakaiproject.kernel.jcr.jackrabbit.sakai.SakaiJCRCredentials;
import org.sakaiproject.kernel.rest.RestMeProvider;
import org.sakaiproject.kernel.test.AuthZServiceKernelUnitT;
import org.sakaiproject.kernel.test.KernelIntegrationBase;
import org.sakaiproject.kernel.util.PathUtils;
import org.sakaiproject.kernel.util.ResourceLoader;
import org.sakaiproject.kernel.webapp.SakaiServletRequest;
import org.sakaiproject.kernel.webapp.test.InternalUser;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import javax.jcr.LoginException;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
*/
public class RestMeProviderKernelUnitT extends KernelIntegrationBase {
private static final Log LOG = LogFactory
.getLog(AuthZServiceKernelUnitT.class);
private static final String[] USERS = { "admin", "ib236" };
private static final String TEST_USERENV = "res://org/sakaiproject/kernel/test/sampleuserenv/";
private static boolean shutdown;
@BeforeClass
public static void beforeThisClass() throws ComponentActivatorException {
shutdown = KernelIntegrationBase.beforeClass();
}
@AfterClass
public static void afterThisClass() {
KernelIntegrationBase.afterClass(shutdown);
}
@Test
public void testAnonGet() throws ServletException, IOException {
KernelManager km = new KernelManager();
SessionManagerService sessionManagerService = km
.getService(SessionManagerService.class);
CacheManagerService cacheManagerService = km
.getService(CacheManagerService.class);
UserResolverService userResolverService = km
.getService(UserResolverService.class);
RegistryService registryService = km.getService(RegistryService.class);
Registry<String, RestProvider> registry = registryService
.getRegistry(RestProvider.REST_REGISTRY);
RestMeProvider rmp = (RestMeProvider) registry.getMap().get("me");
HttpServletRequest request = createMock(HttpServletRequest.class);
HttpServletResponse response = createMock(HttpServletResponse.class);
HttpSession session = createMock(HttpSession.class);
expect(request.getRequestedSessionId()).andReturn("SESSIONID-123").anyTimes();
expect(session.getId()).andReturn("SESSIONID-123").anyTimes();
Cookie cookie = new Cookie("SAKAIID","SESSIONID-123");
expect(request.getCookies()).andReturn(new Cookie[]{cookie}).anyTimes();
expect(request.getAttribute("_no_session")).andReturn(null).anyTimes();
expect(request.getSession(true)).andReturn(session).anyTimes();
expect(request.getAttribute("_uuid")).andReturn(null).anyTimes();
expect(session.getAttribute("_u")).andReturn(null).anyTimes();
expect(session.getAttribute("_uu")).andReturn(null).anyTimes();
expect(request.getLocale()).andReturn(new Locale("en", "US")).anyTimes();
expect(session.getAttribute("sakai.locale.")).andReturn(null).anyTimes();
response.setContentType(RestProvider.CONTENT_TYPE);
expectLastCall().atLeastOnce();
response.addCookie((Cookie) anyObject());
expectLastCall().anyTimes();
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
expect(response.getOutputStream()).andReturn(new ServletOutputStream() {
@Override
public void write(int b) throws IOException {
baos.write(b);
}
});
expectLastCall().atLeastOnce();
replay(request, response, session);
SakaiServletRequest sakaiServletRequest = new SakaiServletRequest(request,
response, userResolverService, sessionManagerService);
sessionManagerService.bindRequest(sakaiServletRequest);
rmp.dispatch(new String[] { "me", "garbage" }, request, response);
String responseString = new String(baos.toByteArray(), "UTF-8");
System.err.println("Response Was " + responseString);
assertTrue(responseString.indexOf("uuid : null") > 0);
cacheManagerService.unbind(CacheScope.REQUEST);
verify(request, response, session);
}
@Test
public void testUserNoEnv() throws ServletException, IOException {
KernelManager km = new KernelManager();
SessionManagerService sessionManagerService = km
.getService(SessionManagerService.class);
CacheManagerService cacheManagerService = km
.getService(CacheManagerService.class);
UserResolverService userResolverService = km
.getService(UserResolverService.class);
RegistryService registryService = km.getService(RegistryService.class);
Registry<String, RestProvider> registry = registryService
.getRegistry(RestProvider.REST_REGISTRY);
RestMeProvider rmp = (RestMeProvider) registry.getMap().get("me");
HttpServletRequest request = createMock(HttpServletRequest.class);
HttpServletResponse response = createMock(HttpServletResponse.class);
HttpSession session = createMock(HttpSession.class);
expect(request.getRequestedSessionId()).andReturn(null).anyTimes();
expect(session.getId()).andReturn("SESSIONID-123-5").anyTimes();
expect(request.getCookies()).andReturn(null).anyTimes();
expect(request.getAttribute("_no_session")).andReturn(null).anyTimes();
expect(request.getSession(true)).andReturn(session).anyTimes();
expect(request.getAttribute("_uuid")).andReturn(null).anyTimes();
expect(session.getAttribute("_u")).andReturn(new InternalUser("ib236"))
.anyTimes();
expect(session.getAttribute("_uu")).andReturn(null).anyTimes();
expect(request.getLocale()).andReturn(new Locale("en", "US")).anyTimes();
expect(session.getAttribute("sakai.locale.")).andReturn(null).anyTimes();
response.addCookie((Cookie) anyObject());
expectLastCall().anyTimes();
response.setContentType(RestProvider.CONTENT_TYPE);
expectLastCall().atLeastOnce();
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
expect(response.getOutputStream()).andReturn(new ServletOutputStream() {
@Override
public void write(int b) throws IOException {
baos.write(b);
}
});
expectLastCall().atLeastOnce();
replay(request, response, session);
SakaiServletRequest sakaiServletRequest = new SakaiServletRequest(request,
response, userResolverService, sessionManagerService);
sessionManagerService.bindRequest(sakaiServletRequest);
rmp.dispatch(new String[] { "me", "garbage" }, request, response);
String responseString = new String(baos.toByteArray(), "UTF-8");
System.err.println("Response Was " + responseString);
assertTrue(responseString.indexOf("\"ib236\"") > 0);
cacheManagerService.unbind(CacheScope.REQUEST);
verify(request, response, session);
}
@Test
public void testUserWithEnv() throws ServletException, IOException,
JCRNodeFactoryServiceException, LoginException, RepositoryException {
KernelManager km = new KernelManager();
SessionManagerService sessionManagerService = km
.getService(SessionManagerService.class);
CacheManagerService cacheManagerService = km
.getService(CacheManagerService.class);
UserResolverService userResolverService = km
.getService(UserResolverService.class);
AuthzResolverService authzResolverService = km
.getService(AuthzResolverService.class);
JCRService jcrService = km.getService(JCRService.class);
JCRNodeFactoryService jcrNodeFactoryService = km
.getService(JCRNodeFactoryService.class);
// bypass security
authzResolverService.setRequestGrant("Populating Test JSON");
// login to the repo with super admin
SakaiJCRCredentials credentials = new SakaiJCRCredentials();
Session jsession = jcrService.getRepository().login(credentials);
jcrService.setSession(jsession);
// setup the user environment for the admin user.
for (String userName : USERS) {
String prefix = PathUtils.getUserPrefix(userName);
String userEnvironmentPath = "/userenv" + prefix + "userenv";
LOG.info("Saving " + userEnvironmentPath);
jcrNodeFactoryService.createFile(userEnvironmentPath);
InputStream in = ResourceLoader.openResource(TEST_USERENV + userName
+ ".json", AuthZServiceKernelUnitT.class.getClassLoader());
jcrNodeFactoryService.setInputStream(userEnvironmentPath, in);
jsession.save();
in.close();
}
RegistryService registryService = km.getService(RegistryService.class);
Registry<String, RestProvider> registry = registryService
.getRegistry(RestProvider.REST_REGISTRY);
RestMeProvider rmp = (RestMeProvider) registry.getMap().get("me");
HttpServletRequest request = createMock(HttpServletRequest.class);
HttpServletResponse response = createMock(HttpServletResponse.class);
HttpSession session = createMock(HttpSession.class);
expect(request.getRequestedSessionId()).andReturn("SESSIONID-123A").anyTimes();
expect(session.getId()).andReturn("SESSIONID-123A").anyTimes();
expect(request.getCookies()).andReturn(null).anyTimes();
expect(request.getAttribute("_no_session")).andReturn(null).anyTimes();
expect(request.getSession(true)).andReturn(session).anyTimes();
expect(request.getAttribute("_uuid")).andReturn(null).anyTimes();
expect(session.getAttribute("_u")).andReturn(new InternalUser("ib236"))
.anyTimes();
expect(session.getAttribute("_uu")).andReturn(null).anyTimes();
expect(request.getLocale()).andReturn(new Locale("en", "US")).anyTimes();
expect(session.getAttribute("sakai.locale.")).andReturn(null).anyTimes();
response.addCookie((Cookie) anyObject());
expectLastCall().anyTimes();
response.setContentType(RestProvider.CONTENT_TYPE);
expectLastCall().atLeastOnce();
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
expect(response.getOutputStream()).andReturn(new ServletOutputStream() {
@Override
public void write(int b) throws IOException {
baos.write(b);
}
});
expectLastCall().atLeastOnce();
replay(request, response, session);
SakaiServletRequest sakaiServletRequest = new SakaiServletRequest(request,
response, userResolverService, sessionManagerService);
sessionManagerService.bindRequest(sakaiServletRequest);
rmp.dispatch(new String[] { "me", "garbage" }, request, response);
System.err.println("=====================================FAILING HERE ");
String responseString = new String(baos.toByteArray(), "UTF-8");
System.err.println("Response Was " + responseString);
assertTrue(responseString.indexOf("\"ib236\"") > 0);
System.err.println("=====================================FAILING HERE PASED ");
cacheManagerService.unbind(CacheScope.REQUEST);
verify(request, response, session);
}
}
|
kernel/src/test/java/org/sakaiproject/kernel/rest/test/RestMeProviderKernelUnitT.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.sakaiproject.kernel.rest.test;
import static org.easymock.EasyMock.anyObject;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.junit.Assert.assertTrue;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.sakaiproject.kernel.api.ComponentActivatorException;
import org.sakaiproject.kernel.api.KernelManager;
import org.sakaiproject.kernel.api.Registry;
import org.sakaiproject.kernel.api.RegistryService;
import org.sakaiproject.kernel.api.authz.AuthzResolverService;
import org.sakaiproject.kernel.api.jcr.JCRService;
import org.sakaiproject.kernel.api.jcr.support.JCRNodeFactoryService;
import org.sakaiproject.kernel.api.jcr.support.JCRNodeFactoryServiceException;
import org.sakaiproject.kernel.api.memory.CacheManagerService;
import org.sakaiproject.kernel.api.memory.CacheScope;
import org.sakaiproject.kernel.api.rest.RestProvider;
import org.sakaiproject.kernel.api.session.SessionManagerService;
import org.sakaiproject.kernel.api.user.UserResolverService;
import org.sakaiproject.kernel.jcr.jackrabbit.sakai.SakaiJCRCredentials;
import org.sakaiproject.kernel.rest.RestMeProvider;
import org.sakaiproject.kernel.test.AuthZServiceKernelUnitT;
import org.sakaiproject.kernel.test.KernelIntegrationBase;
import org.sakaiproject.kernel.util.PathUtils;
import org.sakaiproject.kernel.util.ResourceLoader;
import org.sakaiproject.kernel.webapp.SakaiServletRequest;
import org.sakaiproject.kernel.webapp.test.InternalUser;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import javax.jcr.LoginException;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
*/
public class RestMeProviderKernelUnitT extends KernelIntegrationBase {
private static final Log LOG = LogFactory
.getLog(AuthZServiceKernelUnitT.class);
private static final String[] USERS = { "admin", "ib236" };
private static final String TEST_USERENV = "res://org/sakaiproject/kernel/test/sampleuserenv/";
private static boolean shutdown;
@BeforeClass
public static void beforeThisClass() throws ComponentActivatorException {
shutdown = KernelIntegrationBase.beforeClass();
}
@AfterClass
public static void afterThisClass() {
KernelIntegrationBase.afterClass(shutdown);
}
@Test
public void testAnonGet() throws ServletException, IOException {
KernelManager km = new KernelManager();
SessionManagerService sessionManagerService = km
.getService(SessionManagerService.class);
CacheManagerService cacheManagerService = km
.getService(CacheManagerService.class);
UserResolverService userResolverService = km
.getService(UserResolverService.class);
RegistryService registryService = km.getService(RegistryService.class);
Registry<String, RestProvider> registry = registryService
.getRegistry(RestProvider.REST_REGISTRY);
RestMeProvider rmp = (RestMeProvider) registry.getMap().get("me");
HttpServletRequest request = createMock(HttpServletRequest.class);
HttpServletResponse response = createMock(HttpServletResponse.class);
HttpSession session = createMock(HttpSession.class);
expect(request.getRequestedSessionId()).andReturn("SESSIONID-123").anyTimes();
expect(session.getId()).andReturn("SESSIONID-123").anyTimes();
Cookie cookie = new Cookie("SAKAIID","SESSIONID-123");
expect(request.getCookies()).andReturn(new Cookie[]{cookie}).anyTimes();
expect(request.getAttribute("_no_session")).andReturn(null).anyTimes();
expect(request.getSession(true)).andReturn(session).anyTimes();
expect(request.getAttribute("_uuid")).andReturn(null).anyTimes();
expect(session.getAttribute("_u")).andReturn(null).anyTimes();
expect(session.getAttribute("_uu")).andReturn(null).anyTimes();
expect(request.getLocale()).andReturn(new Locale("en", "US")).anyTimes();
expect(session.getAttribute("sakai.locale.")).andReturn(null).anyTimes();
response.setContentType(RestProvider.CONTENT_TYPE);
expectLastCall().atLeastOnce();
response.addCookie((Cookie) anyObject());
expectLastCall().anyTimes();
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
expect(response.getOutputStream()).andReturn(new ServletOutputStream() {
@Override
public void write(int b) throws IOException {
baos.write(b);
}
});
expectLastCall().atLeastOnce();
replay(request, response, session);
SakaiServletRequest sakaiServletRequest = new SakaiServletRequest(request,
response, userResolverService, sessionManagerService);
sessionManagerService.bindRequest(sakaiServletRequest);
rmp.dispatch(new String[] { "me", "garbage" }, request, response);
String responseString = new String(baos.toByteArray(), "UTF-8");
System.err.println("Response Was " + responseString);
assertTrue(responseString.indexOf("uuid : null") > 0);
cacheManagerService.unbind(CacheScope.REQUEST);
verify(request, response, session);
}
@Test
public void testUserNoEnv() throws ServletException, IOException {
KernelManager km = new KernelManager();
SessionManagerService sessionManagerService = km
.getService(SessionManagerService.class);
CacheManagerService cacheManagerService = km
.getService(CacheManagerService.class);
UserResolverService userResolverService = km
.getService(UserResolverService.class);
RegistryService registryService = km.getService(RegistryService.class);
Registry<String, RestProvider> registry = registryService
.getRegistry(RestProvider.REST_REGISTRY);
RestMeProvider rmp = (RestMeProvider) registry.getMap().get("me");
HttpServletRequest request = createMock(HttpServletRequest.class);
HttpServletResponse response = createMock(HttpServletResponse.class);
HttpSession session = createMock(HttpSession.class);
expect(request.getRequestedSessionId()).andReturn(null).anyTimes();
expect(session.getId()).andReturn("SESSIONID-123-5").anyTimes();
expect(request.getCookies()).andReturn(null).anyTimes();
expect(request.getAttribute("_no_session")).andReturn(null).anyTimes();
expect(request.getSession(true)).andReturn(session).anyTimes();
expect(request.getAttribute("_uuid")).andReturn(null).anyTimes();
expect(session.getAttribute("_u")).andReturn(new InternalUser("ib236"))
.anyTimes();
expect(session.getAttribute("_uu")).andReturn(null).anyTimes();
expect(request.getLocale()).andReturn(new Locale("en", "US")).anyTimes();
expect(session.getAttribute("sakai.locale.")).andReturn(null).anyTimes();
response.addCookie((Cookie) anyObject());
expectLastCall().anyTimes();
response.setContentType(RestProvider.CONTENT_TYPE);
expectLastCall().atLeastOnce();
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
expect(response.getOutputStream()).andReturn(new ServletOutputStream() {
@Override
public void write(int b) throws IOException {
baos.write(b);
}
});
expectLastCall().atLeastOnce();
replay(request, response, session);
SakaiServletRequest sakaiServletRequest = new SakaiServletRequest(request,
response, userResolverService, sessionManagerService);
sessionManagerService.bindRequest(sakaiServletRequest);
rmp.dispatch(new String[] { "me", "garbage" }, request, response);
String responseString = new String(baos.toByteArray(), "UTF-8");
System.err.println("Response Was " + responseString);
assertTrue(responseString.indexOf("\"ib236\"") > 0);
cacheManagerService.unbind(CacheScope.REQUEST);
verify(request, response, session);
}
@Test
public void testUserWithEnv() throws ServletException, IOException,
JCRNodeFactoryServiceException, LoginException, RepositoryException {
KernelManager km = new KernelManager();
SessionManagerService sessionManagerService = km
.getService(SessionManagerService.class);
CacheManagerService cacheManagerService = km
.getService(CacheManagerService.class);
UserResolverService userResolverService = km
.getService(UserResolverService.class);
AuthzResolverService authzResolverService = km
.getService(AuthzResolverService.class);
JCRService jcrService = km.getService(JCRService.class);
JCRNodeFactoryService jcrNodeFactoryService = km
.getService(JCRNodeFactoryService.class);
// bypass security
authzResolverService.setRequestGrant("Populating Test JSON");
// login to the repo with super admin
SakaiJCRCredentials credentials = new SakaiJCRCredentials();
Session jsession = jcrService.getRepository().login(credentials);
jcrService.setSession(jsession);
// setup the user environment for the admin user.
for (String userName : USERS) {
String prefix = PathUtils.getUserPrefix(userName);
String userEnvironmentPath = "/userenv" + prefix + "userenv";
LOG.info("Saving " + userEnvironmentPath);
jcrNodeFactoryService.createFile(userEnvironmentPath);
InputStream in = ResourceLoader.openResource(TEST_USERENV + userName
+ ".json", AuthZServiceKernelUnitT.class.getClassLoader());
jcrNodeFactoryService.setInputStream(userEnvironmentPath, in);
jsession.save();
in.close();
}
RegistryService registryService = km.getService(RegistryService.class);
Registry<String, RestProvider> registry = registryService
.getRegistry(RestProvider.REST_REGISTRY);
RestMeProvider rmp = (RestMeProvider) registry.getMap().get("me");
HttpServletRequest request = createMock(HttpServletRequest.class);
HttpServletResponse response = createMock(HttpServletResponse.class);
HttpSession session = createMock(HttpSession.class);
expect(request.getRequestedSessionId()).andReturn("SESSIONID-123").anyTimes();
expect(session.getId()).andReturn("SESSIONID-123").anyTimes();
expect(request.getCookies()).andReturn(null).anyTimes();
expect(request.getAttribute("_no_session")).andReturn(null).anyTimes();
expect(request.getSession(true)).andReturn(session).anyTimes();
expect(request.getAttribute("_uuid")).andReturn(null).anyTimes();
expect(session.getAttribute("_u")).andReturn(new InternalUser("ib236"))
.anyTimes();
expect(session.getAttribute("_uu")).andReturn(null).anyTimes();
expect(request.getLocale()).andReturn(new Locale("en", "US")).anyTimes();
expect(session.getAttribute("sakai.locale.")).andReturn(null).anyTimes();
response.addCookie((Cookie) anyObject());
expectLastCall().anyTimes();
response.setContentType(RestProvider.CONTENT_TYPE);
expectLastCall().atLeastOnce();
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
expect(response.getOutputStream()).andReturn(new ServletOutputStream() {
@Override
public void write(int b) throws IOException {
baos.write(b);
}
});
expectLastCall().atLeastOnce();
replay(request, response, session);
SakaiServletRequest sakaiServletRequest = new SakaiServletRequest(request,
response, userResolverService, sessionManagerService);
sessionManagerService.bindRequest(sakaiServletRequest);
rmp.dispatch(new String[] { "me", "garbage" }, request, response);
String responseString = new String(baos.toByteArray(), "UTF-8");
System.err.println("Response Was " + responseString);
assertTrue(responseString.indexOf("\"ib236\"") > 0);
cacheManagerService.unbind(CacheScope.REQUEST);
verify(request, response, session);
}
}
|
Fixed a brokent test in the RestMeProvider.
git-svn-id: 81ed41d7d168891742cba5e65a82c2d517ef9008@57171 fdecad78-55fc-0310-b1b2-d7d25cf747c9
|
kernel/src/test/java/org/sakaiproject/kernel/rest/test/RestMeProviderKernelUnitT.java
|
Fixed a brokent test in the RestMeProvider.
|
<ide><path>ernel/src/test/java/org/sakaiproject/kernel/rest/test/RestMeProviderKernelUnitT.java
<ide> HttpServletResponse response = createMock(HttpServletResponse.class);
<ide> HttpSession session = createMock(HttpSession.class);
<ide>
<del> expect(request.getRequestedSessionId()).andReturn("SESSIONID-123").anyTimes();
<del> expect(session.getId()).andReturn("SESSIONID-123").anyTimes();
<add> expect(request.getRequestedSessionId()).andReturn("SESSIONID-123A").anyTimes();
<add> expect(session.getId()).andReturn("SESSIONID-123A").anyTimes();
<ide> expect(request.getCookies()).andReturn(null).anyTimes();
<ide> expect(request.getAttribute("_no_session")).andReturn(null).anyTimes();
<ide> expect(request.getSession(true)).andReturn(session).anyTimes();
<ide>
<ide> rmp.dispatch(new String[] { "me", "garbage" }, request, response);
<ide>
<add> System.err.println("=====================================FAILING HERE ");
<ide> String responseString = new String(baos.toByteArray(), "UTF-8");
<ide> System.err.println("Response Was " + responseString);
<ide> assertTrue(responseString.indexOf("\"ib236\"") > 0);
<add> System.err.println("=====================================FAILING HERE PASED ");
<ide>
<ide> cacheManagerService.unbind(CacheScope.REQUEST);
<ide> verify(request, response, session);
|
|
Java
|
apache-2.0
|
ff53ea327b3c2f3cbbc0fd1f21645ada40e6a951
| 0 |
CIRDLES/Topsoil,CIRDLES/Topsoil
|
package org.cirdles.topsoil.app.control.data;
import com.sun.javafx.scene.control.skin.TreeTableViewSkin;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.control.cell.CheckBoxTreeTableCell;
import javafx.scene.control.cell.TextFieldTreeTableCell;
import javafx.scene.layout.Region;
import javafx.scene.text.TextAlignment;
import javafx.util.StringConverter;
import javafx.util.converter.DefaultStringConverter;
import org.cirdles.topsoil.app.control.undo.UndoAction;
import org.cirdles.topsoil.app.data.FXDataColumn;
import org.cirdles.topsoil.app.data.FXDataRow;
import org.cirdles.topsoil.app.data.FXDataTable;
import org.cirdles.topsoil.app.data.NumberColumnStringConverter;
import org.cirdles.topsoil.data.DataColumn;
import org.cirdles.topsoil.data.DataTable;
import org.cirdles.topsoil.data.TableUtils;
import org.cirdles.topsoil.javafx.SingleChildRegion;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
/**
* A customized {@code TreeTableView} that displays the data contained in a {@link DataTable}.
*
* @author marottajb
*/
public class FXDataTableViewer extends SingleChildRegion<TreeTableView<FXDataRow>> {
private static final double LABEL_COL_WIDTH = 150.0;
private static final double SELECTED_COL_WIDTH = 70.0;
private static final double DATA_COL_WIDTH = 145.0;
private FXDataTable table;
private TreeTableView<FXDataRow> treeTableView;
private Map<DataColumn<?>, StringConverter<?>> converterMap = new HashMap<>();
//**********************************************//
// CONSTRUCTORS //
//**********************************************//
/**
* Constructs a new tree table view for the given data table.
*
* @param table DataTable
*/
public FXDataTableViewer(FXDataTable table) {
super(new TreeTableView<>());
this.table = table;
treeTableView = getChild();
treeTableView.setEditable(true);
treeTableView.setShowRoot(false);
treeTableView.setSkin(new CustomTreeTableViewSkin(treeTableView));
// Create root item
CheckBoxTreeItem<FXDataRow> rootItem = new CheckBoxTreeItem<>();
// Add TreeItems for data
for (FXDataRow row : table.getRows()) {
rootItem.getChildren().add(treeItemForDataRow(row));
}
treeTableView.setRoot(rootItem);
// Create converters for leaf columns
int maxFractionDigits;
for (DataColumn<?> column : table.getLeafColumns()) {
if (column.getType() == Number.class) {
NumberColumnStringConverter converter = new NumberColumnStringConverter();
maxFractionDigits = TableUtils.maxFractionDigitsForColumn(
table.getRows(),
(DataColumn<Number>) column,
table.isScientificNotation()
);
if (table.getMaxFractionDigits() >= 0) {
maxFractionDigits = Math.min(maxFractionDigits, table.getMaxFractionDigits());
}
converter.setNumFractionDigits(maxFractionDigits);
converterMap.put(column, converter);
} else {
converterMap.put(column, new DefaultStringConverter());
}
}
// Add tree table columns
treeTableView.getColumns().add(labelColumn());
treeTableView.getColumns().add(checkBoxColumn());
for (FXDataColumn<?> column : table.getColumns()) {
treeTableView.getColumns().add(treeColumnForDataColumn(column));
}
// Refresh cells on fraction digit changes
table.maxFractionDigitsProperty().addListener(c -> {
updateFractionDigitsForLeafColumns();
refreshCells();
});
table.scientificNotationProperty().addListener(c -> {
updateFractionDigitsForLeafColumns();
refreshCells();
});
}
//**********************************************//
// PRIVATE METHODS //
//**********************************************//
/**
* Returns the column of {@code String} labels for rows/segments.
*
* @return new TreeTableColumn
*/
private TreeTableColumn<FXDataRow, String> labelColumn() {
MultilineHeaderTreeTableColumn<FXDataRow, String> column = new MultilineHeaderTreeTableColumn<>("Label");
column.setCellFactory(param -> {
TextFieldTreeTableCell<FXDataRow, String> cell = new TextFieldTreeTableCell<>();
cell.setTextAlignment(TextAlignment.LEFT);
cell.setEditable(false);
return cell;
});
column.setCellValueFactory(param -> {
FXDataRow row = param.getValue().getValue();
return row.titleProperty();
});
column.setPrefWidth(LABEL_COL_WIDTH);
return column;
}
/**
* Returns the column of {@link javafx.scene.control.CheckBox}es for row/segment selection.
*
* @return new TreeTableColumn
*/
private TreeTableColumn<FXDataRow, Boolean> checkBoxColumn() {
MultilineHeaderTreeTableColumn<FXDataRow, Boolean> column = new MultilineHeaderTreeTableColumn<>("Selected");
column.setCellFactory(param -> {
CheckBoxTreeTableCell<FXDataRow, Boolean> cell = new CheckBoxTreeTableCell<>();
cell.setAlignment(Pos.CENTER);
cell.setEditable(true);
return cell;
});
column.setCellValueFactory(param -> {
FXDataRow row = param.getValue().getValue();
return row.selectedProperty();
});
column.setEditable(true);
column.setPrefWidth(SELECTED_COL_WIDTH);
return column;
}
private <T> TreeTableColumn<FXDataRow, T> treeColumnForDataColumn(FXDataColumn<T> column) {
DataTreeTableColumn<FXDataRow, T> treeTableColumn = new DataTreeTableColumn<>(column);
if (column.getChildren().size() == 0) {
treeTableColumn.setCellFactory(param -> {
TreeTableCell<FXDataRow, T> cell = new FXDataTreeTableCell<>(column, (StringConverter<T>) converterMap.get(column));
if (column.getType() == Number.class) {
cell.setAlignment(Pos.CENTER_RIGHT);
} else {
cell.setAlignment(Pos.CENTER_LEFT);
}
return cell;
});
treeTableColumn.setCellValueFactory(param -> {
FXDataRow row = param.getValue().getValue();
if (row.getChildren().size() == 0) {
return new SimpleObjectProperty<>(row.getValueForColumn(column));
}
return null;
});
treeTableColumn.setOnEditCommit(event -> {
UndoAction editAction = new CellEditUndoAction<>(
column,
event
);
editAction.execute();
this.table.addUndo(editAction);
});
treeTableColumn.visibleProperty().bindBidirectional(column.selectedProperty());
treeTableColumn.setPrefWidth(DATA_COL_WIDTH);
} else {
for (FXDataColumn<?> child : column.getChildren()) {
treeTableColumn.getColumns().add(treeColumnForDataColumn(child));
}
}
return treeTableColumn;
}
/**
* Returns a new {@code CheckBoxTreeItem} for the provided {@code DataRow}.
*
* @param row DataRow
* @return CheckBoxTreeItem;
*/
private CheckBoxTreeItem<FXDataRow> treeItemForDataRow(FXDataRow row) {
CheckBoxTreeItem<FXDataRow> treeItem = new CheckBoxTreeItem<>(row);
for (FXDataRow child : row.getChildren()) {
treeItem.getChildren().add(treeItemForDataRow(child));
}
treeItem.selectedProperty().bindBidirectional(row.selectedProperty());
return treeItem;
}
private void updateFractionDigitsForLeafColumns() {
int tableSetting = table.getMaxFractionDigits();
int maxFractionDigits;
for (Map.Entry<DataColumn<?>, StringConverter<?>> entry : converterMap.entrySet()) {
if (entry.getValue() instanceof NumberColumnStringConverter) {
NumberColumnStringConverter converter = (NumberColumnStringConverter) entry.getValue();
if (tableSetting > -1) {
maxFractionDigits = Math.min(tableSetting, TableUtils.maxFractionDigitsForColumn(
table.getRows(),
(DataColumn<Number>) entry.getKey(),
table.isScientificNotation()
));
} else {
maxFractionDigits = TableUtils.maxFractionDigitsForColumn(
table.getRows(),
(DataColumn<Number>) entry.getKey(),
table.isScientificNotation()
);
}
converter.setNumFractionDigits(maxFractionDigits);
converter.setScientificNotation(table.isScientificNotation());
}
}
}
private void refreshCells() {
((CustomTreeTableViewSkin) treeTableView.getSkin()).refreshCells();
}
private class CustomTreeTableViewSkin extends TreeTableViewSkin<FXDataRow> {
CustomTreeTableViewSkin(TreeTableView<FXDataRow> treeTableView) {
super(treeTableView);
}
public void refreshCells() {
super.flow.recreateCells();
}
}
}
|
topsoilApp/src/main/java/org/cirdles/topsoil/app/control/data/FXDataTableViewer.java
|
package org.cirdles.topsoil.app.control.data;
import com.sun.javafx.scene.control.skin.TreeTableViewSkin;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.control.cell.CheckBoxTreeTableCell;
import javafx.scene.control.cell.TextFieldTreeTableCell;
import javafx.scene.layout.Region;
import javafx.scene.text.TextAlignment;
import javafx.util.StringConverter;
import javafx.util.converter.DefaultStringConverter;
import org.cirdles.topsoil.app.control.undo.UndoAction;
import org.cirdles.topsoil.app.data.FXDataColumn;
import org.cirdles.topsoil.app.data.FXDataRow;
import org.cirdles.topsoil.app.data.FXDataTable;
import org.cirdles.topsoil.app.data.NumberColumnStringConverter;
import org.cirdles.topsoil.data.DataColumn;
import org.cirdles.topsoil.data.DataTable;
import org.cirdles.topsoil.data.TableUtils;
import org.cirdles.topsoil.javafx.SingleChildRegion;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
/**
* A customized {@code TreeTableView} that displays the data contained in a {@link DataTable}.
*
* @author marottajb
*/
public class FXDataTableViewer extends SingleChildRegion<TreeTableView<FXDataRow>> {
private static final double LABEL_COL_WIDTH = 150.0;
private static final double SELECTED_COL_WIDTH = 65.0;
private static final double DATA_COL_WIDTH = 145.0;
private FXDataTable table;
private TreeTableView<FXDataRow> treeTableView;
private Map<DataColumn<?>, StringConverter<?>> converterMap = new HashMap<>();
//**********************************************//
// CONSTRUCTORS //
//**********************************************//
/**
* Constructs a new tree table view for the given data table.
*
* @param table DataTable
*/
public FXDataTableViewer(FXDataTable table) {
super(new TreeTableView<>());
this.table = table;
treeTableView = getChild();
treeTableView.setEditable(true);
treeTableView.setShowRoot(false);
treeTableView.setSkin(new CustomTreeTableViewSkin(treeTableView));
// Create root item
CheckBoxTreeItem<FXDataRow> rootItem = new CheckBoxTreeItem<>();
// Add TreeItems for data
for (FXDataRow row : table.getRows()) {
rootItem.getChildren().add(treeItemForDataRow(row));
}
treeTableView.setRoot(rootItem);
// Create converters for leaf columns
int maxFractionDigits;
for (DataColumn<?> column : table.getLeafColumns()) {
if (column.getType() == Number.class) {
NumberColumnStringConverter converter = new NumberColumnStringConverter();
maxFractionDigits = TableUtils.maxFractionDigitsForColumn(
table.getRows(),
(DataColumn<Number>) column,
table.isScientificNotation()
);
if (table.getMaxFractionDigits() >= 0) {
maxFractionDigits = Math.min(maxFractionDigits, table.getMaxFractionDigits());
}
converter.setNumFractionDigits(maxFractionDigits);
converterMap.put(column, converter);
} else {
converterMap.put(column, new DefaultStringConverter());
}
}
// Add tree table columns
treeTableView.getColumns().add(labelColumn());
treeTableView.getColumns().add(checkBoxColumn());
for (FXDataColumn<?> column : table.getColumns()) {
treeTableView.getColumns().add(treeColumnForDataColumn(column));
}
// Refresh cells on fraction digit changes
table.maxFractionDigitsProperty().addListener(c -> {
updateFractionDigitsForLeafColumns();
refreshCells();
});
table.scientificNotationProperty().addListener(c -> {
updateFractionDigitsForLeafColumns();
refreshCells();
});
}
//**********************************************//
// PRIVATE METHODS //
//**********************************************//
/**
* Returns the column of {@code String} labels for rows/segments.
*
* @return new TreeTableColumn
*/
private TreeTableColumn<FXDataRow, String> labelColumn() {
MultilineHeaderTreeTableColumn<FXDataRow, String> column = new MultilineHeaderTreeTableColumn<>("Label");
column.setCellFactory(param -> {
TextFieldTreeTableCell<FXDataRow, String> cell = new TextFieldTreeTableCell<>();
cell.setTextAlignment(TextAlignment.LEFT);
cell.setEditable(false);
return cell;
});
column.setCellValueFactory(param -> {
FXDataRow row = param.getValue().getValue();
return row.titleProperty();
});
column.setPrefWidth(LABEL_COL_WIDTH);
return column;
}
/**
* Returns the column of {@link javafx.scene.control.CheckBox}es for row/segment selection.
*
* @return new TreeTableColumn
*/
private TreeTableColumn<FXDataRow, Boolean> checkBoxColumn() {
MultilineHeaderTreeTableColumn<FXDataRow, Boolean> column = new MultilineHeaderTreeTableColumn<>("Selected");
column.setCellFactory(param -> {
CheckBoxTreeTableCell<FXDataRow, Boolean> cell = new CheckBoxTreeTableCell<>();
cell.setAlignment(Pos.CENTER);
cell.setEditable(true);
return cell;
});
column.setCellValueFactory(param -> {
FXDataRow row = param.getValue().getValue();
return row.selectedProperty();
});
column.setEditable(true);
column.setPrefWidth(SELECTED_COL_WIDTH);
return column;
}
private <T> TreeTableColumn<FXDataRow, T> treeColumnForDataColumn(FXDataColumn<T> column) {
DataTreeTableColumn<FXDataRow, T> treeTableColumn = new DataTreeTableColumn<>(column);
if (column.getChildren().size() == 0) {
treeTableColumn.setCellFactory(param -> {
TreeTableCell<FXDataRow, T> cell = new FXDataTreeTableCell<>(column, (StringConverter<T>) converterMap.get(column));
if (column.getType() == Number.class) {
cell.setAlignment(Pos.CENTER_RIGHT);
} else {
cell.setAlignment(Pos.CENTER_LEFT);
}
return cell;
});
treeTableColumn.setCellValueFactory(param -> {
FXDataRow row = param.getValue().getValue();
if (row.getChildren().size() == 0) {
return new SimpleObjectProperty<>(row.getValueForColumn(column));
}
return null;
});
treeTableColumn.setOnEditCommit(event -> {
UndoAction editAction = new CellEditUndoAction<>(
column,
event
);
editAction.execute();
this.table.addUndo(editAction);
});
treeTableColumn.visibleProperty().bindBidirectional(column.selectedProperty());
treeTableColumn.setPrefWidth(DATA_COL_WIDTH);
} else {
for (FXDataColumn<?> child : column.getChildren()) {
treeTableColumn.getColumns().add(treeColumnForDataColumn(child));
}
}
return treeTableColumn;
}
/**
* Returns a new {@code CheckBoxTreeItem} for the provided {@code DataRow}.
*
* @param row DataRow
* @return CheckBoxTreeItem;
*/
private CheckBoxTreeItem<FXDataRow> treeItemForDataRow(FXDataRow row) {
CheckBoxTreeItem<FXDataRow> treeItem = new CheckBoxTreeItem<>(row);
for (FXDataRow child : row.getChildren()) {
treeItem.getChildren().add(treeItemForDataRow(child));
}
treeItem.selectedProperty().bindBidirectional(row.selectedProperty());
return treeItem;
}
private void updateFractionDigitsForLeafColumns() {
int tableSetting = table.getMaxFractionDigits();
int maxFractionDigits;
for (Map.Entry<DataColumn<?>, StringConverter<?>> entry : converterMap.entrySet()) {
if (entry.getValue() instanceof NumberColumnStringConverter) {
NumberColumnStringConverter converter = (NumberColumnStringConverter) entry.getValue();
if (tableSetting > -1) {
maxFractionDigits = Math.min(tableSetting, TableUtils.maxFractionDigitsForColumn(
table.getRows(),
(DataColumn<Number>) entry.getKey(),
table.isScientificNotation()
));
} else {
maxFractionDigits = TableUtils.maxFractionDigitsForColumn(
table.getRows(),
(DataColumn<Number>) entry.getKey(),
table.isScientificNotation()
);
}
converter.setNumFractionDigits(maxFractionDigits);
converter.setScientificNotation(table.isScientificNotation());
}
}
}
private void refreshCells() {
((CustomTreeTableViewSkin) treeTableView.getSkin()).refreshCells();
}
private class CustomTreeTableViewSkin extends TreeTableViewSkin<FXDataRow> {
CustomTreeTableViewSkin(TreeTableView<FXDataRow> treeTableView) {
super(treeTableView);
}
public void refreshCells() {
super.flow.recreateCells();
}
}
}
|
increased Selected column width to 70.0 px
|
topsoilApp/src/main/java/org/cirdles/topsoil/app/control/data/FXDataTableViewer.java
|
increased Selected column width to 70.0 px
|
<ide><path>opsoilApp/src/main/java/org/cirdles/topsoil/app/control/data/FXDataTableViewer.java
<ide> public class FXDataTableViewer extends SingleChildRegion<TreeTableView<FXDataRow>> {
<ide>
<ide> private static final double LABEL_COL_WIDTH = 150.0;
<del> private static final double SELECTED_COL_WIDTH = 65.0;
<add> private static final double SELECTED_COL_WIDTH = 70.0;
<ide> private static final double DATA_COL_WIDTH = 145.0;
<ide>
<ide> private FXDataTable table;
|
|
Java
|
bsd-3-clause
|
5178f6c662eb656d9da17968e795bd442262804c
| 0 |
NCIP/cananolab,NCIP/cananolab,NCIP/cananolab
|
package gov.nih.nci.cananolab.ui.sample;
import gov.nih.nci.cananolab.domain.characterization.physical.PhysicoChemicalCharacterization;
import gov.nih.nci.cananolab.domain.particle.Characterization;
import gov.nih.nci.cananolab.domain.particle.Sample;
import gov.nih.nci.cananolab.dto.common.ExperimentConfigBean;
import gov.nih.nci.cananolab.dto.common.FileBean;
import gov.nih.nci.cananolab.dto.common.FindingBean;
import gov.nih.nci.cananolab.dto.common.UserBean;
import gov.nih.nci.cananolab.dto.particle.SampleBean;
import gov.nih.nci.cananolab.dto.particle.characterization.CharacterizationBean;
import gov.nih.nci.cananolab.dto.particle.characterization.CharacterizationSummaryViewBean;
import gov.nih.nci.cananolab.service.common.FileService;
import gov.nih.nci.cananolab.service.common.impl.FileServiceLocalImpl;
import gov.nih.nci.cananolab.service.sample.CharacterizationResultService;
import gov.nih.nci.cananolab.service.sample.CharacterizationService;
import gov.nih.nci.cananolab.service.sample.ExperimentConfigService;
import gov.nih.nci.cananolab.service.sample.SampleService;
import gov.nih.nci.cananolab.service.sample.impl.CharacterizationResultServiceLocalImpl;
import gov.nih.nci.cananolab.service.sample.impl.CharacterizationServiceLocalImpl;
import gov.nih.nci.cananolab.service.sample.impl.ExperimentConfigServiceLocalImpl;
import gov.nih.nci.cananolab.service.sample.impl.SampleServiceLocalImpl;
import gov.nih.nci.cananolab.service.security.AuthorizationService;
import gov.nih.nci.cananolab.ui.core.BaseAnnotationAction;
import gov.nih.nci.cananolab.ui.core.InitSetup;
import gov.nih.nci.cananolab.ui.protocol.InitProtocolSetup;
import gov.nih.nci.cananolab.util.Constants;
import gov.nih.nci.cananolab.util.StringUtils;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedSet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.validator.DynaValidatorForm;
import org.directwebremoting.WebContextFactory;
/**
* Base action for characterization actions
*
* @author pansu
*
*/
public class CharacterizationAction extends BaseAnnotationAction {
/**
* Add or update the data to database
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward create(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
CharacterizationBean charBean = (CharacterizationBean) theForm
.get("achar");
InitCharacterizationSetup.getInstance()
.persistCharacterizationDropdowns(request, charBean);
// TODO::
// if (!validateDerivedDatum(request, charBean)) {
// return mapping.getInputForward();
// }
saveCharacterization(request, theForm, charBean);
ActionMessages msgs = new ActionMessages();
// validate number by javascript filterFloatingNumber
// validateNumber(request, charBean, msgs);
ActionMessage msg = new ActionMessage("message.addCharacterization",
charBean.getCharacterizationName());
msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
saveMessages(request, msgs);
return summaryEdit(mapping, form, request, response);
}
/**
* Set up the input form for adding new characterization
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward setupNew(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
setupInputForm(request, theForm);
// reset characterizationBean
CharacterizationBean charBean = new CharacterizationBean();
theForm.set("achar", charBean);
String charType = request.getParameter("charType");
if (charType != null) {
charBean.setCharacterizationType(charType);
SortedSet<String> charNames = InitCharacterizationSetup
.getInstance().getCharNamesByCharType(request,
charBean.getCharacterizationType());
request.getSession().setAttribute("charTypeChars", charNames);
}
return mapping.getInputForward();
}
/**
* Set up drop-downs need for the input form
*
* @param request
* @param theForm
* @throws Exception
*/
private void setupInputForm(HttpServletRequest request,
DynaValidatorForm theForm) throws Exception {
String sampleId = request.getParameter("sampleId");
String charType = request.getParameter("charType");
InitSampleSetup.getInstance().setSharedDropdowns(request);
InitCharacterizationSetup.getInstance().setCharactierizationDropDowns(
request, sampleId);
InitExperimentConfigSetup.getInstance().setExperimentConfigDropDowns(
request);
if (charType != null)
InitProtocolSetup.getInstance().getProtocolsByChar(request,
charType);
InitCharacterizationSetup.getInstance().setCharacterizationDropdowns(
request);
// String detailPage = setupDetailPage(charBean);
// request.getSession().setAttribute("characterizationDetailPage",
// detailPage);
// set up other samples with the same primary point of contact
InitSampleSetup.getInstance().getOtherSampleNames(request, sampleId);
}
/**
* Set up the input form for editing existing characterization
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward setupUpdate(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
String charId = request.getParameter("charId");
String charClass = request.getParameter("charClassName");
CharacterizationService charService = new CharacterizationServiceLocalImpl();
Characterization chara = charService.findCharacterizationById(charId,
charClass);
CharacterizationBean charBean = new CharacterizationBean(chara);
// setup correct display for characterization name and characterization
// type
InitCharacterizationSetup.getInstance().setCharacterizationName(
request, charBean);
InitCharacterizationSetup.getInstance().setCharacterizationType(
request, charBean);
// setup dropdown for existing characterization
InitCharacterizationSetup.getInstance().getCharNamesByCharType(request,
charBean.getCharacterizationType());
InitCharacterizationSetup.getInstance().getAssayTypesByCharName(
request, charBean.getCharacterizationName());
InitCharacterizationSetup.getInstance().getDatumNamesByCharName(
request, charBean.getCharacterizationName());
request.setAttribute("achar", charBean);
theForm.set("achar", charBean);
setupInputForm(request, theForm);
String detailPage = null;
if (charBean.isWithProperties()) {
detailPage = setupDetailPage(charBean);
}
request.setAttribute("characterizationDetailPage", detailPage);
return mapping.getInputForward();
}
private String setupDetailPage(CharacterizationBean charBean) {
String includePage = null;
if (charBean.getClassName().equals("PhysicalState")
|| charBean.getClassName().equals("Shape")
|| charBean.getClassName().equals("Solubility")
|| charBean.getClassName().equals("Surface")) {
includePage = "physical/body" + charBean.getClassName()
+ "Info.jsp";
} else if (charBean.getClassName().equals("Cytotoxicity")) {
includePage = "invitro/body" + charBean.getClassName() + "Info.jsp";
} else if (charBean.getClassName().equals("EnzymeInduction")) {
includePage = "invitro/body" + charBean.getClassName() + "Info.jsp";
}
return includePage;
}
private void saveToOtherSamples(HttpServletRequest request,
Characterization copy, UserBean user, String sampleName,
Sample[] otherSamples) throws Exception {
FileService fileService = new FileServiceLocalImpl();
CharacterizationService charService = new CharacterizationServiceLocalImpl();
for (Sample sample : otherSamples) {
charService.saveCharacterization(sample, copy);
// update copied filename and save content and set visibility
// TODO
// if (copy.getDerivedBioAssayDataCollection() != null) {
// for (DerivedBioAssayData bioassay : copy
// .getDerivedBioAssayDataCollection()) {
// if (bioassay.getFile() != null) {
// fileService.saveCopiedFileAndSetVisibility(bioassay
// .getFile(), user, sampleName, sample
// .getName());
// }
// }
// }
}
}
private void setupDomainChar(HttpServletRequest request,
DynaValidatorForm theForm, CharacterizationBean charBean)
throws Exception {
// setup domainFile for fileBeans
SampleBean sampleBean = setupSample(theForm, request, "local");
UserBean user = (UserBean) request.getSession().getAttribute("user");
// setup domainFile uri for fileBeans
String internalUriPath = Constants.FOLDER_PARTICLE
+ "/"
+ sampleBean.getDomain().getName()
+ "/"
+ StringUtils.getOneWordLowerCaseFirstLetter(InitSetup
.getInstance().getDisplayName(charBean.getClassName(),
request.getSession().getServletContext()));
if (charBean.getClassName() == null) {
String className = InitSetup.getInstance().getClassName(
charBean.getCharacterizationName(),
request.getSession().getServletContext());
charBean.setClassName(className);
}
charBean.setupDomain(user.getLoginName(), internalUriPath);
}
// TODO for datum and condition
// protected boolean validateDerivedDatum(HttpServletRequest request,
// CharacterizationBean charBean) throws Exception {
//
// ActionMessages msgs = new ActionMessages();
// boolean noErrors = true;
// for (DerivedBioAssayDataBean derivedBioassayDataBean : charBean
// .getDerivedBioAssayDataList()) {
//
// List<DerivedDatumBean> datumList = derivedBioassayDataBean
// .getDatumList();
// FileBean lfBean = derivedBioassayDataBean.getFileBean();
//
// // error, if no data input from either the lab file or derived datum
// boolean noFileError = true;
// if (datumList == null || datumList.size() == 0) {
// noFileError = validateFileBean(request, msgs, lfBean);
// if (!noFileError) {
// ActionMessage msg = new ActionMessage("errors.required",
// "If no derived datum entered, the file data");
// msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
// this.saveErrors(request, msgs);
// noErrors = false;
// }
// }
//
// for (DerivedDatumBean datum : datumList) {
// // if value field is populated, so does the name field.
// if (datum.getDomainDerivedDatum().getName().length() == 0) {
// ActionMessage msg = new ActionMessage("errors.required",
// "Derived data name");
// msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
// this.saveErrors(request, msgs);
// noErrors = false;
// }
// try {
// Float value = new Float(datum.getValueStr());
// // for boolean type, the value must be 0/1
// if (datum.getDomainDerivedDatum().getValueType()
// .equalsIgnoreCase("boolean")
// && value != 0.0 && value != 1.0) {
// ActionMessage msg = new ActionMessage(
// "error.booleanValue", "Derived data value");
// msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
// saveErrors(request, msgs);
// noErrors = false;
// }
// } catch (NumberFormatException e) {
// // for boolean type, the value must be true/false
// if (datum.getDomainDerivedDatum().getValueType()
// .equalsIgnoreCase("boolean")
// && !datum.getValueStr().equalsIgnoreCase("true")
// && !datum.getValueStr().equalsIgnoreCase("false")) {
// ActionMessage msg = new ActionMessage(
// "error.booleanValue", "Derived data value");
// msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
// saveErrors(request, msgs);
// noErrors = false;
// } else if (!datum.getDomainDerivedDatum().getValueType()
// .equalsIgnoreCase("boolean")) {
// ActionMessage msg = new ActionMessage(
// "error.derivedDatumValue", "Derived data value");
// msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
// saveErrors(request, msgs);
// noErrors = false;
// }
// }
// }
// }
// return noErrors;
// }
private void saveCharacterization(HttpServletRequest request,
DynaValidatorForm theForm, CharacterizationBean charBean)
throws Exception {
// setup domainFile for fileBeans
SampleBean sampleBean = setupSample(theForm, request, "local");
UserBean user = (UserBean) request.getSession().getAttribute("user");
// setup domainFile uri for fileBeans
setupDomainChar(request, theForm, charBean);
CharacterizationService charService = new CharacterizationServiceLocalImpl();
charService.saveCharacterization(sampleBean.getDomain(), charBean
.getDomainChar());
// set public visibility
AuthorizationService authService = new AuthorizationService(
Constants.CSM_APP_NAME);
List<String> accessibleGroups = authService.getAccessibleGroups(
sampleBean.getDomain().getName(), Constants.CSM_READ_PRIVILEGE);
if (accessibleGroups != null
&& accessibleGroups.contains(Constants.CSM_PUBLIC_GROUP)) {
charService.assignPublicVisibility(authService, charBean
.getDomainChar());
}
// save file data to file system and set visibility
List<FileBean> files = new ArrayList<FileBean>();
// TODO::
// for (DerivedBioAssayDataBean bioassay : charBean
// .getDerivedBioAssayDataList()) {
// if (bioassay.getFileBean() != null) {
// files.add(bioassay.getFileBean());
// }
// }
saveFilesToFileSystem(files);
// save to other samples
Sample[] otherSamples = prepareCopy(request, theForm);
if (otherSamples != null) {
Boolean copyData = (Boolean) theForm.get("copyData");
Characterization copy = charBean.getDomainCopy(copyData);
saveToOtherSamples(request, copy, user, sampleBean.getDomain()
.getName(), otherSamples);
}
sampleBean = setupSample(theForm, request, "local");
}
private void deleteCharacterization(HttpServletRequest request,
DynaValidatorForm theForm, CharacterizationBean charBean,
String createdBy) throws Exception {
SampleBean sampleBean = setupSample(theForm, request, "local");
// setup domainFile uri for fileBeans
String internalUriPath = Constants.FOLDER_PARTICLE
+ "/"
+ sampleBean.getDomain().getName()
+ "/"
+ StringUtils.getOneWordLowerCaseFirstLetter(InitSetup
.getInstance().getDisplayName(charBean.getClassName(),
request.getSession().getServletContext()));
charBean.setupDomain(createdBy, internalUriPath);
CharacterizationService charService = new CharacterizationServiceLocalImpl();
charService.deleteCharacterization(charBean.getDomainChar());
}
public ActionForward delete(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
CharacterizationBean charBean = (CharacterizationBean) theForm
.get("achar");
UserBean user = (UserBean) request.getSession().getAttribute("user");
deleteCharacterization(request, theForm, charBean, user.getLoginName());
ActionMessages msgs = new ActionMessages();
ActionMessage msg = new ActionMessage("message.deleteCharacterization");
msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
saveMessages(request, msgs);
ActionForward forward = mapping.findForward("success");
request.setAttribute("updateDataTree", "true");
String sampleId = theForm.getString("sampleId");
SampleService sampleService = new SampleServiceLocalImpl();
SampleBean sampleBean = sampleService.findSampleById(sampleId);
InitSampleSetup.getInstance().getDataTree(sampleBean, request);
return forward;
}
public void validateNumber(HttpServletRequest request,
CharacterizationBean charBean, ActionMessages msgs)
throws Exception {
if (charBean.getSolubility().getCriticalConcentration() == 0.0) {
ActionMessage msg = new ActionMessage("message.invalidNumber");
msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
}
}
private void setCharacterizationFileFullPath(HttpServletRequest request,
CharacterizationBean charBean, String location) throws Exception {
if (location.equals("local")) {
// TODO::
// set file full path
// for (DerivedBioAssayDataBean bioassayBean : charBean
// .getDerivedBioAssayDataList()) {
// if (bioassayBean.getFileBean() != null) {
// FileBean fileBean = bioassayBean.getFileBean();
// if (!fileBean.getDomainFile().getUriExternal()) {
// String fileRoot = PropertyReader.getProperty(
// Constants.FILEUPLOAD_PROPERTY,
// "fileRepositoryDir");
// fileBean.setFullPath(fileRoot + File.separator
// + fileBean.getDomainFile().getUri());
// } else {
// fileBean.setFullPath(fileBean.getDomainFile().getUri());
// }
// }
// }
} else {
String serviceUrl = InitSetup.getInstance().getGridServiceUrl(
request, location);
URL localURL = new URL(request.getRequestURL().toString());
String actionPath = localURL.getPath();
URL remoteUrl = new URL(serviceUrl);
String remoteServerHostUrl = remoteUrl.getProtocol() + "://"
+ remoteUrl.getHost() + ":" + remoteUrl.getPort();
String remoteDownloadUrlBase = remoteServerHostUrl + actionPath
+ "?dispatch=download&location=local&fileId=";
// TODO::
// for (DerivedBioAssayDataBean bioassayBean : charBean
// .getDerivedBioAssayDataList()) {
// if (bioassayBean.getFileBean() != null) {
// FileBean fileBean = bioassayBean.getFileBean();
// String remoteDownloadUrl = remoteDownloadUrlBase
// + fileBean.getDomainFile().getId().toString();
// fileBean.setFullPath(remoteDownloadUrl);
// }
// }
}
}
public ActionForward summaryView(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String sampleId = request.getParameter("sampleId");
String location = request.getParameter("location");
CharacterizationService service = null;
if (location.equals("local")) {
service = new CharacterizationServiceLocalImpl();
} else {
String serviceUrl = InitSetup.getInstance().getGridServiceUrl(
request, location);
// TODO model change
// service = new CharacterizationServiceRemoteImpl(
// serviceUrl);
}
List<CharacterizationBean> charBeans = service
.findCharsBySampleId(sampleId);
// set characterization types
for (CharacterizationBean charBean : charBeans) {
InitCharacterizationSetup.getInstance().setCharacterizationType(
request, charBean);
InitCharacterizationSetup.getInstance().setCharacterizationName(
request, charBean);
}
CharacterizationSummaryViewBean summaryView = new CharacterizationSummaryViewBean(
charBeans);
request.setAttribute("characterizationSummaryView", summaryView);
// keep submitted characterization types in the correct display order
List<String> allCharacterizationTypes = new ArrayList<String>(
(List<? extends String>) request.getSession().getAttribute(
"characterizationTypes"));
List<String> characterizationTypes = new ArrayList<String>();
for (String type : allCharacterizationTypes) {
if (summaryView.getCharacterizationTypes().contains(type)
&& !characterizationTypes.contains(type)) {
characterizationTypes.add(type);
}
}
request.setAttribute("characterizationTypes", characterizationTypes);
return mapping.findForward("summaryView");
}
public ActionForward summaryEdit(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String sampleId = request.getParameter("sampleId");
CharacterizationService service = new CharacterizationServiceLocalImpl();
List<CharacterizationBean> charBeans = service
.findCharsBySampleId(sampleId);
// set characterization types
for (CharacterizationBean charBean : charBeans) {
InitCharacterizationSetup.getInstance().setCharacterizationType(
request, charBean);
InitCharacterizationSetup.getInstance().setCharacterizationName(
request, charBean);
}
CharacterizationSummaryViewBean summaryView = new CharacterizationSummaryViewBean(
charBeans);
request.setAttribute("characterizationSummaryView", summaryView);
return mapping.findForward("summaryEdit");
}
public ActionForward saveExperimentConfig(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
CharacterizationBean achar = (CharacterizationBean) theForm
.get("achar");
ExperimentConfigBean configBean = achar.getTheExperimentConfig();
UserBean user = (UserBean) request.getSession().getAttribute("user");
configBean.setupDomain(user.getLoginName());
ExperimentConfigService service = new ExperimentConfigServiceLocalImpl();
service.saveExperimentConfig(configBean.getDomain());
achar.addExperimentConfig(configBean);
InitCharacterizationSetup.getInstance()
.persistCharacterizationDropdowns(request, achar);
InitExperimentConfigSetup.getInstance()
.persistExperimentConfigDropdowns(request, configBean);
// also save characterization
saveCharacterization(request, theForm, achar);
return mapping.getInputForward();
}
public ActionForward saveFinding(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
CharacterizationBean achar = (CharacterizationBean) theForm
.get("achar");
FindingBean findingBean = achar.getTheFinding();
String theFindingId = (String) theForm.get("theFindingId");
if (theFindingId != null && !theFindingId.equals("null")
&& theFindingId.trim().length() > 0) {
findingBean.getDomain().setId(new Long(theFindingId));
}
UserBean user = (UserBean) request.getSession().getAttribute("user");
findingBean.setupDomain(user.getLoginName());
CharacterizationResultService service = new CharacterizationResultServiceLocalImpl();
service.saveFinding(findingBean.getDomain());
achar.addFinding(findingBean);
InitCharacterizationSetup.getInstance()
.persistCharacterizationDropdowns(request, achar);
// also save characterization
saveCharacterization(request, theForm, achar);
return mapping.getInputForward();
}
public ActionForward addFile(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
SampleBean sampleBean = setupSample(theForm, request, "local");
CharacterizationBean achar = (CharacterizationBean) theForm
.get("achar");
FindingBean findingBean = achar.getTheFinding();
FileBean theFile = findingBean.getTheFile();
String internalUriPath = Constants.FOLDER_PARTICLE
+ "/"
+ sampleBean.getDomain().getName()
+ "/"
+ StringUtils.getOneWordLowerCaseFirstLetter(InitSetup
.getInstance().getDisplayName(achar.getClassName(),
request.getSession().getServletContext()));
UserBean user = (UserBean) request.getSession().getAttribute("user");
theFile.setupDomainFile(internalUriPath, user.getLoginName(), 0);
findingBean.addFile(theFile);
return mapping.getInputForward();
}
public ActionForward deleteFinding(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
CharacterizationBean achar = (CharacterizationBean) theForm
.get("achar");
FindingBean dataSetBean = achar.getTheFinding();
CharacterizationResultService service = new CharacterizationResultServiceLocalImpl();
service.deleteFinding(dataSetBean.getDomain());
achar.removeFinding(dataSetBean);
InitCharacterizationSetup.getInstance()
.persistCharacterizationDropdowns(request, achar);
return mapping.getInputForward();
}
public ActionForward deleteExperimentConfig(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
CharacterizationBean achar = (CharacterizationBean) theForm
.get("achar");
ExperimentConfigBean configBean = achar.getTheExperimentConfig();
ExperimentConfigService service = new ExperimentConfigServiceLocalImpl();
service.deleteExperimentConfig(configBean.getDomain());
achar.removeExperimentConfig(configBean);
InitCharacterizationSetup.getInstance()
.persistCharacterizationDropdowns(request, achar);
InitExperimentConfigSetup.getInstance()
.persistExperimentConfigDropdowns(request, configBean);
// also save characterization
saveCharacterization(request, theForm, achar);
return mapping.getInputForward();
}
}
|
src/gov/nih/nci/cananolab/ui/sample/CharacterizationAction.java
|
package gov.nih.nci.cananolab.ui.sample;
import gov.nih.nci.cananolab.domain.particle.Characterization;
import gov.nih.nci.cananolab.domain.particle.Sample;
import gov.nih.nci.cananolab.dto.common.ExperimentConfigBean;
import gov.nih.nci.cananolab.dto.common.FileBean;
import gov.nih.nci.cananolab.dto.common.FindingBean;
import gov.nih.nci.cananolab.dto.common.UserBean;
import gov.nih.nci.cananolab.dto.particle.SampleBean;
import gov.nih.nci.cananolab.dto.particle.characterization.CharacterizationBean;
import gov.nih.nci.cananolab.dto.particle.characterization.CharacterizationSummaryViewBean;
import gov.nih.nci.cananolab.service.common.FileService;
import gov.nih.nci.cananolab.service.common.impl.FileServiceLocalImpl;
import gov.nih.nci.cananolab.service.sample.CharacterizationResultService;
import gov.nih.nci.cananolab.service.sample.CharacterizationService;
import gov.nih.nci.cananolab.service.sample.ExperimentConfigService;
import gov.nih.nci.cananolab.service.sample.SampleService;
import gov.nih.nci.cananolab.service.sample.impl.CharacterizationResultServiceLocalImpl;
import gov.nih.nci.cananolab.service.sample.impl.CharacterizationServiceLocalImpl;
import gov.nih.nci.cananolab.service.sample.impl.ExperimentConfigServiceLocalImpl;
import gov.nih.nci.cananolab.service.sample.impl.SampleServiceLocalImpl;
import gov.nih.nci.cananolab.service.security.AuthorizationService;
import gov.nih.nci.cananolab.ui.core.BaseAnnotationAction;
import gov.nih.nci.cananolab.ui.core.InitSetup;
import gov.nih.nci.cananolab.ui.protocol.InitProtocolSetup;
import gov.nih.nci.cananolab.util.Constants;
import gov.nih.nci.cananolab.util.StringUtils;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.validator.DynaValidatorForm;
/**
* Base action for characterization actions
*
* @author pansu
*
*/
public class CharacterizationAction extends BaseAnnotationAction {
/**
* Add or update the data to database
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward create(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
CharacterizationBean charBean = (CharacterizationBean) theForm
.get("achar");
InitCharacterizationSetup.getInstance()
.persistCharacterizationDropdowns(request, charBean);
// TODO::
// if (!validateDerivedDatum(request, charBean)) {
// return mapping.getInputForward();
// }
saveCharacterization(request, theForm, charBean);
ActionMessages msgs = new ActionMessages();
// validate number by javascript filterFloatingNumber
// validateNumber(request, charBean, msgs);
ActionMessage msg = new ActionMessage("message.addCharacterization",
charBean.getCharacterizationName());
msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
saveMessages(request, msgs);
return summaryEdit(mapping, form, request, response);
}
/**
* Set up the input form for adding new characterization
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward setupNew(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
setupInputForm(request, theForm);
// reset characterizationBean
CharacterizationBean charBean = new CharacterizationBean();
theForm.set("achar", charBean);
String charType = request.getParameter("charType");
if (charType != null) {
charBean.setCharacterizationType(charType);
SortedSet<String> charNames = InitCharacterizationSetup
.getInstance().getCharNamesByCharType(request,
charBean.getCharacterizationType());
request.getSession().setAttribute("charTypeChars", charNames);
}
return mapping.getInputForward();
}
/**
* Set up drop-downs need for the input form
*
* @param request
* @param theForm
* @throws Exception
*/
private void setupInputForm(HttpServletRequest request,
DynaValidatorForm theForm) throws Exception {
String sampleId = request.getParameter("sampleId");
String charType = request.getParameter("charType");
InitSampleSetup.getInstance().setSharedDropdowns(request);
InitCharacterizationSetup.getInstance().setCharactierizationDropDowns(
request, sampleId);
InitExperimentConfigSetup.getInstance().setExperimentConfigDropDowns(
request);
if (charType != null)
InitProtocolSetup.getInstance().getProtocolsByChar(request,
charType);
InitCharacterizationSetup.getInstance().setCharacterizationDropdowns(
request);
// String detailPage = setupDetailPage(charBean);
// request.getSession().setAttribute("characterizationDetailPage",
// detailPage);
// set up other samples with the same primary point of contact
InitSampleSetup.getInstance().getOtherSampleNames(request, sampleId);
}
/**
* Set up the input form for editing existing characterization
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward setupUpdate(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
String charId = request.getParameter("charId");
String charClass = request.getParameter("charClassName");
CharacterizationService charService = new CharacterizationServiceLocalImpl();
Characterization chara = charService.findCharacterizationById(charId,
charClass);
CharacterizationBean charBean = new CharacterizationBean(chara);
// setup correct display for characterization name and characterization
// type
InitCharacterizationSetup.getInstance().setCharacterizationName(
request, charBean);
InitCharacterizationSetup.getInstance().setCharacterizationType(
request, charBean);
// setup dropdown for existing characterization
InitCharacterizationSetup.getInstance().getCharNamesByCharType(request,
charBean.getCharacterizationType());
InitCharacterizationSetup.getInstance().getAssayTypesByCharName(
request, charBean.getCharacterizationName());
InitCharacterizationSetup.getInstance().getDatumNamesByCharName(
request, charBean.getCharacterizationName());
request.setAttribute("achar", charBean);
theForm.set("achar", charBean);
setupInputForm(request, theForm);
String detailPage = null;
if (charBean.isWithProperties()) {
detailPage = setupDetailPage(charBean);
}
request.setAttribute("characterizationDetailPage", detailPage);
return mapping.getInputForward();
}
private String setupDetailPage(CharacterizationBean charBean) {
String includePage = null;
if (charBean.getClassName().equals("PhysicalState")
|| charBean.getClassName().equals("Shape")
|| charBean.getClassName().equals("Solubility")
|| charBean.getClassName().equals("Surface")) {
includePage = "physical/body" + charBean.getClassName()
+ "Info.jsp";
} else if (charBean.getClassName().equals("Cytotoxicity")) {
includePage = "invitro/body" + charBean.getClassName() + "Info.jsp";
} else if (charBean.getClassName().equals("EnzymeInduction")) {
includePage = "invitro/body" + charBean.getClassName() + "Info.jsp";
}
return includePage;
}
private void saveToOtherSamples(HttpServletRequest request,
Characterization copy, UserBean user, String sampleName,
Sample[] otherSamples) throws Exception {
FileService fileService = new FileServiceLocalImpl();
CharacterizationService charService = new CharacterizationServiceLocalImpl();
for (Sample sample : otherSamples) {
charService.saveCharacterization(sample, copy);
// update copied filename and save content and set visibility
// TODO
// if (copy.getDerivedBioAssayDataCollection() != null) {
// for (DerivedBioAssayData bioassay : copy
// .getDerivedBioAssayDataCollection()) {
// if (bioassay.getFile() != null) {
// fileService.saveCopiedFileAndSetVisibility(bioassay
// .getFile(), user, sampleName, sample
// .getName());
// }
// }
// }
}
}
private void setupDomainChar(HttpServletRequest request,
DynaValidatorForm theForm, CharacterizationBean charBean)
throws Exception {
// setup domainFile for fileBeans
SampleBean sampleBean = setupSample(theForm, request, "local");
UserBean user = (UserBean) request.getSession().getAttribute("user");
// setup domainFile uri for fileBeans
String internalUriPath = Constants.FOLDER_PARTICLE
+ "/"
+ sampleBean.getDomain().getName()
+ "/"
+ StringUtils.getOneWordLowerCaseFirstLetter(InitSetup
.getInstance().getDisplayName(charBean.getClassName(),
request.getSession().getServletContext()));
if (charBean.getClassName() == null) {
String className = InitSetup.getInstance().getClassName(
charBean.getCharacterizationName(),
request.getSession().getServletContext());
charBean.setClassName(className);
}
charBean.setupDomain(user.getLoginName(), internalUriPath);
}
// TODO for datum and condition
// protected boolean validateDerivedDatum(HttpServletRequest request,
// CharacterizationBean charBean) throws Exception {
//
// ActionMessages msgs = new ActionMessages();
// boolean noErrors = true;
// for (DerivedBioAssayDataBean derivedBioassayDataBean : charBean
// .getDerivedBioAssayDataList()) {
//
// List<DerivedDatumBean> datumList = derivedBioassayDataBean
// .getDatumList();
// FileBean lfBean = derivedBioassayDataBean.getFileBean();
//
// // error, if no data input from either the lab file or derived datum
// boolean noFileError = true;
// if (datumList == null || datumList.size() == 0) {
// noFileError = validateFileBean(request, msgs, lfBean);
// if (!noFileError) {
// ActionMessage msg = new ActionMessage("errors.required",
// "If no derived datum entered, the file data");
// msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
// this.saveErrors(request, msgs);
// noErrors = false;
// }
// }
//
// for (DerivedDatumBean datum : datumList) {
// // if value field is populated, so does the name field.
// if (datum.getDomainDerivedDatum().getName().length() == 0) {
// ActionMessage msg = new ActionMessage("errors.required",
// "Derived data name");
// msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
// this.saveErrors(request, msgs);
// noErrors = false;
// }
// try {
// Float value = new Float(datum.getValueStr());
// // for boolean type, the value must be 0/1
// if (datum.getDomainDerivedDatum().getValueType()
// .equalsIgnoreCase("boolean")
// && value != 0.0 && value != 1.0) {
// ActionMessage msg = new ActionMessage(
// "error.booleanValue", "Derived data value");
// msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
// saveErrors(request, msgs);
// noErrors = false;
// }
// } catch (NumberFormatException e) {
// // for boolean type, the value must be true/false
// if (datum.getDomainDerivedDatum().getValueType()
// .equalsIgnoreCase("boolean")
// && !datum.getValueStr().equalsIgnoreCase("true")
// && !datum.getValueStr().equalsIgnoreCase("false")) {
// ActionMessage msg = new ActionMessage(
// "error.booleanValue", "Derived data value");
// msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
// saveErrors(request, msgs);
// noErrors = false;
// } else if (!datum.getDomainDerivedDatum().getValueType()
// .equalsIgnoreCase("boolean")) {
// ActionMessage msg = new ActionMessage(
// "error.derivedDatumValue", "Derived data value");
// msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
// saveErrors(request, msgs);
// noErrors = false;
// }
// }
// }
// }
// return noErrors;
// }
private void saveCharacterization(HttpServletRequest request,
DynaValidatorForm theForm, CharacterizationBean charBean)
throws Exception {
// setup domainFile for fileBeans
SampleBean sampleBean = setupSample(theForm, request, "local");
UserBean user = (UserBean) request.getSession().getAttribute("user");
// setup domainFile uri for fileBeans
setupDomainChar(request, theForm, charBean);
CharacterizationService charService = new CharacterizationServiceLocalImpl();
charService.saveCharacterization(sampleBean.getDomain(), charBean
.getDomainChar());
// set public visibility
AuthorizationService authService = new AuthorizationService(
Constants.CSM_APP_NAME);
List<String> accessibleGroups = authService.getAccessibleGroups(
sampleBean.getDomain().getName(), Constants.CSM_READ_PRIVILEGE);
if (accessibleGroups != null
&& accessibleGroups.contains(Constants.CSM_PUBLIC_GROUP)) {
charService.assignPublicVisibility(authService, charBean
.getDomainChar());
}
// save file data to file system and set visibility
List<FileBean> files = new ArrayList<FileBean>();
// TODO::
// for (DerivedBioAssayDataBean bioassay : charBean
// .getDerivedBioAssayDataList()) {
// if (bioassay.getFileBean() != null) {
// files.add(bioassay.getFileBean());
// }
// }
saveFilesToFileSystem(files);
// save to other samples
Sample[] otherSamples = prepareCopy(request, theForm);
if (otherSamples != null) {
Boolean copyData = (Boolean) theForm.get("copyData");
Characterization copy = charBean.getDomainCopy(copyData);
saveToOtherSamples(request, copy, user, sampleBean.getDomain()
.getName(), otherSamples);
}
sampleBean = setupSample(theForm, request, "local");
}
private void deleteCharacterization(HttpServletRequest request,
DynaValidatorForm theForm, CharacterizationBean charBean,
String createdBy) throws Exception {
SampleBean sampleBean = setupSample(theForm, request, "local");
// setup domainFile uri for fileBeans
String internalUriPath = Constants.FOLDER_PARTICLE
+ "/"
+ sampleBean.getDomain().getName()
+ "/"
+ StringUtils.getOneWordLowerCaseFirstLetter(InitSetup
.getInstance().getDisplayName(charBean.getClassName(),
request.getSession().getServletContext()));
charBean.setupDomain(createdBy, internalUriPath);
CharacterizationService charService = new CharacterizationServiceLocalImpl();
charService.deleteCharacterization(charBean.getDomainChar());
}
public ActionForward delete(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
CharacterizationBean charBean = (CharacterizationBean) theForm
.get("achar");
UserBean user = (UserBean) request.getSession().getAttribute("user");
deleteCharacterization(request, theForm, charBean, user.getLoginName());
ActionMessages msgs = new ActionMessages();
ActionMessage msg = new ActionMessage("message.deleteCharacterization");
msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
saveMessages(request, msgs);
ActionForward forward = mapping.findForward("success");
request.setAttribute("updateDataTree", "true");
String sampleId = theForm.getString("sampleId");
SampleService sampleService = new SampleServiceLocalImpl();
SampleBean sampleBean = sampleService.findSampleById(sampleId);
InitSampleSetup.getInstance().getDataTree(sampleBean, request);
return forward;
}
public void validateNumber(HttpServletRequest request,
CharacterizationBean charBean, ActionMessages msgs)
throws Exception {
if (charBean.getSolubility().getCriticalConcentration() == 0.0) {
ActionMessage msg = new ActionMessage("message.invalidNumber");
msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
}
}
private void setCharacterizationFileFullPath(HttpServletRequest request,
CharacterizationBean charBean, String location) throws Exception {
if (location.equals("local")) {
// TODO::
// set file full path
// for (DerivedBioAssayDataBean bioassayBean : charBean
// .getDerivedBioAssayDataList()) {
// if (bioassayBean.getFileBean() != null) {
// FileBean fileBean = bioassayBean.getFileBean();
// if (!fileBean.getDomainFile().getUriExternal()) {
// String fileRoot = PropertyReader.getProperty(
// Constants.FILEUPLOAD_PROPERTY,
// "fileRepositoryDir");
// fileBean.setFullPath(fileRoot + File.separator
// + fileBean.getDomainFile().getUri());
// } else {
// fileBean.setFullPath(fileBean.getDomainFile().getUri());
// }
// }
// }
} else {
String serviceUrl = InitSetup.getInstance().getGridServiceUrl(
request, location);
URL localURL = new URL(request.getRequestURL().toString());
String actionPath = localURL.getPath();
URL remoteUrl = new URL(serviceUrl);
String remoteServerHostUrl = remoteUrl.getProtocol() + "://"
+ remoteUrl.getHost() + ":" + remoteUrl.getPort();
String remoteDownloadUrlBase = remoteServerHostUrl + actionPath
+ "?dispatch=download&location=local&fileId=";
// TODO::
// for (DerivedBioAssayDataBean bioassayBean : charBean
// .getDerivedBioAssayDataList()) {
// if (bioassayBean.getFileBean() != null) {
// FileBean fileBean = bioassayBean.getFileBean();
// String remoteDownloadUrl = remoteDownloadUrlBase
// + fileBean.getDomainFile().getId().toString();
// fileBean.setFullPath(remoteDownloadUrl);
// }
// }
}
}
public ActionForward summaryView(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String sampleId = request.getParameter("sampleId");
String location = request.getParameter("location");
CharacterizationService service = null;
if (location.equals("local")) {
service = new CharacterizationServiceLocalImpl();
} else {
String serviceUrl = InitSetup.getInstance().getGridServiceUrl(
request, location);
// TODO model change
// service = new CharacterizationServiceRemoteImpl(
// serviceUrl);
}
List<CharacterizationBean> charBeans = service
.findCharsBySampleId(sampleId);
// set characterization types
for (CharacterizationBean charBean : charBeans) {
InitCharacterizationSetup.getInstance().setCharacterizationType(
request, charBean);
InitCharacterizationSetup.getInstance().setCharacterizationName(
request, charBean);
}
CharacterizationSummaryViewBean summaryView = new CharacterizationSummaryViewBean(
charBeans);
request.setAttribute("characterizationSummaryView", summaryView);
//keep submitted characterization types in the correct display order
List<String> allCharacterizationTypes = new ArrayList<String>(
(List<? extends String>) request.getSession().getAttribute(
"characterizationTypes"));
List<String> characterizationTypes = new ArrayList<String>();
for (String type : allCharacterizationTypes) {
if (summaryView.getCharacterizationTypes().contains(type)
&& !characterizationTypes.contains(type)) {
characterizationTypes.add(type);
}
}
request.setAttribute("characterizationTypes",
characterizationTypes);
return mapping.findForward("summaryView");
}
public ActionForward summaryEdit(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String sampleId = request.getParameter("sampleId");
CharacterizationService service = new CharacterizationServiceLocalImpl();
List<CharacterizationBean> charBeans = service
.findCharsBySampleId(sampleId);
// set characterization types
for (CharacterizationBean charBean : charBeans) {
InitCharacterizationSetup.getInstance().setCharacterizationType(
request, charBean);
InitCharacterizationSetup.getInstance().setCharacterizationName(
request, charBean);
}
CharacterizationSummaryViewBean summaryView = new CharacterizationSummaryViewBean(
charBeans);
request.setAttribute("characterizationSummaryView", summaryView);
return mapping.findForward("summaryEdit");
}
public ActionForward saveExperimentConfig(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
CharacterizationBean achar = (CharacterizationBean) theForm
.get("achar");
ExperimentConfigBean configBean = achar.getTheExperimentConfig();
UserBean user = (UserBean) request.getSession().getAttribute("user");
configBean.setupDomain(user.getLoginName());
ExperimentConfigService service = new ExperimentConfigServiceLocalImpl();
service.saveExperimentConfig(configBean.getDomain());
achar.addExperimentConfig(configBean);
InitCharacterizationSetup.getInstance()
.persistCharacterizationDropdowns(request, achar);
InitExperimentConfigSetup.getInstance()
.persistExperimentConfigDropdowns(request, configBean);
// also save characterization
saveCharacterization(request, theForm, achar);
return mapping.getInputForward();
}
public ActionForward saveFinding(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
CharacterizationBean achar = (CharacterizationBean) theForm
.get("achar");
FindingBean dataSetBean = achar.getTheFinding();
String theFindingId = (String) theForm.get("theFindingId");
if (theFindingId != null && !theFindingId.equals("null")
&& theFindingId.trim().length() > 0) {
dataSetBean.getDomain().setId(new Long(theFindingId));
}
UserBean user = (UserBean) request.getSession().getAttribute("user");
dataSetBean.setupDomain(user.getLoginName());
CharacterizationResultService service = new CharacterizationResultServiceLocalImpl();
service.saveFinding(dataSetBean.getDomain());
achar.addFinding(dataSetBean);
InitCharacterizationSetup.getInstance()
.persistCharacterizationDropdowns(request, achar);
// also save characterization
saveCharacterization(request, theForm, achar);
return mapping.getInputForward();
}
public ActionForward deleteFinding(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
CharacterizationBean achar = (CharacterizationBean) theForm
.get("achar");
FindingBean dataSetBean = achar.getTheFinding();
CharacterizationResultService service = new CharacterizationResultServiceLocalImpl();
service.deleteFinding(dataSetBean.getDomain());
achar.removeFinding(dataSetBean);
InitCharacterizationSetup.getInstance()
.persistCharacterizationDropdowns(request, achar);
return mapping.getInputForward();
}
public ActionForward deleteExperimentConfig(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
CharacterizationBean achar = (CharacterizationBean) theForm
.get("achar");
ExperimentConfigBean configBean = achar.getTheExperimentConfig();
ExperimentConfigService service = new ExperimentConfigServiceLocalImpl();
service.deleteExperimentConfig(configBean.getDomain());
achar.removeExperimentConfig(configBean);
InitCharacterizationSetup.getInstance()
.persistCharacterizationDropdowns(request, achar);
InitExperimentConfigSetup.getInstance()
.persistExperimentConfigDropdowns(request, configBean);
// also save characterization
saveCharacterization(request, theForm, achar);
return mapping.getInputForward();
}
}
|
added addFile
SVN-Revision: 14969
|
src/gov/nih/nci/cananolab/ui/sample/CharacterizationAction.java
|
added addFile
|
<ide><path>rc/gov/nih/nci/cananolab/ui/sample/CharacterizationAction.java
<ide> package gov.nih.nci.cananolab.ui.sample;
<ide>
<add>import gov.nih.nci.cananolab.domain.characterization.physical.PhysicoChemicalCharacterization;
<ide> import gov.nih.nci.cananolab.domain.particle.Characterization;
<ide> import gov.nih.nci.cananolab.domain.particle.Sample;
<ide> import gov.nih.nci.cananolab.dto.common.ExperimentConfigBean;
<ide> import java.util.ArrayList;
<ide> import java.util.List;
<ide> import java.util.SortedSet;
<del>import java.util.TreeSet;
<ide>
<ide> import javax.servlet.http.HttpServletRequest;
<ide> import javax.servlet.http.HttpServletResponse;
<ide> import org.apache.struts.action.ActionMessage;
<ide> import org.apache.struts.action.ActionMessages;
<ide> import org.apache.struts.validator.DynaValidatorForm;
<add>import org.directwebremoting.WebContextFactory;
<ide>
<ide> /**
<ide> * Base action for characterization actions
<ide> detailPage = setupDetailPage(charBean);
<ide> }
<ide> request.setAttribute("characterizationDetailPage", detailPage);
<add>
<ide> return mapping.getInputForward();
<ide> }
<ide>
<ide> CharacterizationSummaryViewBean summaryView = new CharacterizationSummaryViewBean(
<ide> charBeans);
<ide> request.setAttribute("characterizationSummaryView", summaryView);
<del> //keep submitted characterization types in the correct display order
<add> // keep submitted characterization types in the correct display order
<ide> List<String> allCharacterizationTypes = new ArrayList<String>(
<ide> (List<? extends String>) request.getSession().getAttribute(
<ide> "characterizationTypes"));
<ide> characterizationTypes.add(type);
<ide> }
<ide> }
<del> request.setAttribute("characterizationTypes",
<del> characterizationTypes);
<add> request.setAttribute("characterizationTypes", characterizationTypes);
<ide> return mapping.findForward("summaryView");
<ide> }
<ide>
<ide> DynaValidatorForm theForm = (DynaValidatorForm) form;
<ide> CharacterizationBean achar = (CharacterizationBean) theForm
<ide> .get("achar");
<del> FindingBean dataSetBean = achar.getTheFinding();
<add> FindingBean findingBean = achar.getTheFinding();
<ide> String theFindingId = (String) theForm.get("theFindingId");
<ide> if (theFindingId != null && !theFindingId.equals("null")
<ide> && theFindingId.trim().length() > 0) {
<del> dataSetBean.getDomain().setId(new Long(theFindingId));
<add> findingBean.getDomain().setId(new Long(theFindingId));
<ide> }
<ide> UserBean user = (UserBean) request.getSession().getAttribute("user");
<del> dataSetBean.setupDomain(user.getLoginName());
<add> findingBean.setupDomain(user.getLoginName());
<ide> CharacterizationResultService service = new CharacterizationResultServiceLocalImpl();
<del> service.saveFinding(dataSetBean.getDomain());
<del> achar.addFinding(dataSetBean);
<add> service.saveFinding(findingBean.getDomain());
<add> achar.addFinding(findingBean);
<ide> InitCharacterizationSetup.getInstance()
<ide> .persistCharacterizationDropdowns(request, achar);
<ide> // also save characterization
<ide> saveCharacterization(request, theForm, achar);
<add> return mapping.getInputForward();
<add> }
<add>
<add> public ActionForward addFile(ActionMapping mapping, ActionForm form,
<add> HttpServletRequest request, HttpServletResponse response)
<add> throws Exception {
<add> DynaValidatorForm theForm = (DynaValidatorForm) form;
<add> SampleBean sampleBean = setupSample(theForm, request, "local");
<add> CharacterizationBean achar = (CharacterizationBean) theForm
<add> .get("achar");
<add> FindingBean findingBean = achar.getTheFinding();
<add> FileBean theFile = findingBean.getTheFile();
<add> String internalUriPath = Constants.FOLDER_PARTICLE
<add> + "/"
<add> + sampleBean.getDomain().getName()
<add> + "/"
<add> + StringUtils.getOneWordLowerCaseFirstLetter(InitSetup
<add> .getInstance().getDisplayName(achar.getClassName(),
<add> request.getSession().getServletContext()));
<add> UserBean user = (UserBean) request.getSession().getAttribute("user");
<add> theFile.setupDomainFile(internalUriPath, user.getLoginName(), 0);
<add> findingBean.addFile(theFile);
<ide> return mapping.getInputForward();
<ide> }
<ide>
|
|
Java
|
lgpl-2.1
|
60e12514010c7dc33f37e898509540856b349468
| 0 |
konradkwisniewski/abixen-platform,abixen/abixen-platform,asteriskbimal/abixen-platform,konradkwisniewski/abixen-platform,cloudowski/abixen-platform,rajsingh8220/abixen-platform,asteriskbimal/abixen-platform,asteriskbimal/abixen-platform,abixen/abixen-platform,rajsingh8220/abixen-platform,rajsingh8220/abixen-platform,rajsingh8220/abixen-platform,cloudowski/abixen-platform,abixen/abixen-platform,konradkwisniewski/abixen-platform,rbharath26/abixen-platform,cloudowski/abixen-platform,abixen/abixen-platform,cloudowski/abixen-platform,konradkwisniewski/abixen-platform,rbharath26/abixen-platform,rbharath26/abixen-platform,rbharath26/abixen-platform,asteriskbimal/abixen-platform
|
/**
* Copyright (c) 2010-present Abixen Systems. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.abixen.platform.core.service.impl;
import com.abixen.platform.core.configuration.properties.AbstractPlatformMailConfigurationProperties;
import com.abixen.platform.core.service.MailService;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.context.ServletContextAware;
import javax.mail.Message;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.servlet.ServletContext;
import java.io.File;
import java.util.Map;
@Slf4j
@Service
public class MailServiceImpl implements MailService, ServletContextAware {
@Autowired
private JavaMailSender mailSender;
private ServletContext servletContext;
@Autowired
private AbstractPlatformMailConfigurationProperties platformMailConfigurationProperties;
@Override
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
@Async
@Override
public void sendMail(String to, Map<String, String> parameters, String template, String subject) {
log.debug("sendMail() - to: " + to);
MimeMessage message = mailSender.createMimeMessage();
try {
//String context = servletContext.getRealPath("../resources/templates/freemarker");
String stringDir = MailServiceImpl.class.getResource("/templates/freemarker").getPath();
//context.replaceAll("\\\\", "/");
Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
cfg.setDefaultEncoding("UTF-8");
File dir = new File(stringDir);
cfg.setDirectoryForTemplateLoading(dir);
cfg.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_22));
StringBuffer content = new StringBuffer();
Template temp = cfg.getTemplate(template);
content.append(FreeMarkerTemplateUtils.processTemplateIntoString(temp, parameters));
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(content.toString(), "text/html;charset=\"UTF-8\"");
MimeMultipart multipart = new MimeMultipart("related");
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
message.setFrom(new InternetAddress(platformMailConfigurationProperties.getUser().getUsername(), platformMailConfigurationProperties.getUser().getName()));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
mailSender.send(message);
log.info("Message has been sent to: " + to);
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
abixen-platform-core/src/main/java/com/abixen/platform/core/service/impl/MailServiceImpl.java
|
/**
* Copyright (c) 2010-present Abixen Systems. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.abixen.platform.core.service.impl;
import com.abixen.platform.core.configuration.properties.AbstractPlatformMailConfigurationProperties;
import com.abixen.platform.core.service.MailService;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.context.ServletContextAware;
import javax.mail.Message;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.servlet.ServletContext;
import java.io.File;
import java.util.Map;
@Slf4j
@Service
public class MailServiceImpl implements MailService, ServletContextAware {
@Autowired
private JavaMailSender mailSender;
private ServletContext servletContext;
@Autowired
private AbstractPlatformMailConfigurationProperties platformMailConfigurationProperties;
@Override
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
@Override
public void sendMail(String to, Map<String, String> parameters, String template, String subject) {
log.debug("sendMail() - to: " + to);
MimeMessage message = mailSender.createMimeMessage();
try {
//String context = servletContext.getRealPath("../resources/templates/freemarker");
String stringDir = MailServiceImpl.class.getResource("/templates/freemarker").getPath();
//context.replaceAll("\\\\", "/");
Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
cfg.setDefaultEncoding("UTF-8");
File dir = new File(stringDir);
cfg.setDirectoryForTemplateLoading(dir);
cfg.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_22));
StringBuffer content = new StringBuffer();
Template temp = cfg.getTemplate(template);
content.append(FreeMarkerTemplateUtils.processTemplateIntoString(temp, parameters));
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(content.toString(), "text/html;charset=\"UTF-8\"");
MimeMultipart multipart = new MimeMultipart("related");
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
message.setFrom(new InternetAddress(platformMailConfigurationProperties.getUser().getUsername(), platformMailConfigurationProperties.getUser().getName()));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
mailSender.send(message);
log.info("Message has been sent to: " + to);
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
Made the send email method as an async.
|
abixen-platform-core/src/main/java/com/abixen/platform/core/service/impl/MailServiceImpl.java
|
Made the send email method as an async.
|
<ide><path>bixen-platform-core/src/main/java/com/abixen/platform/core/service/impl/MailServiceImpl.java
<ide> import lombok.extern.slf4j.Slf4j;
<ide> import org.springframework.beans.factory.annotation.Autowired;
<ide> import org.springframework.mail.javamail.JavaMailSender;
<add>import org.springframework.scheduling.annotation.Async;
<ide> import org.springframework.stereotype.Service;
<ide> import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
<ide> import org.springframework.web.context.ServletContextAware;
<ide> this.servletContext = servletContext;
<ide> }
<ide>
<add> @Async
<ide> @Override
<ide> public void sendMail(String to, Map<String, String> parameters, String template, String subject) {
<ide> log.debug("sendMail() - to: " + to);
|
|
Java
|
bsd-2-clause
|
0abb849f8ffbc7b78349afa548347fdc8f5a1407
| 0 |
scenerygraphics/SciView,scenerygraphics/SciView
|
/*-
* #%L
* Scenery-backed 3D visualization package for ImageJ.
* %%
* Copyright (C) 2016 - 2018 SciView developers.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package sc.iview.commands.demo;
import bdv.util.Bdv;
import bdv.util.BdvSource;
import cleargl.GLVector;
import graphics.scenery.Material;
import graphics.scenery.Node;
import graphics.scenery.PointLight;
import graphics.scenery.volumes.TransferFunction;
import graphics.scenery.volumes.bdv.BDVVolume;
import net.imagej.Dataset;
import net.imagej.mesh.Mesh;
import net.imagej.ops.OpService;
import net.imagej.ops.geom.geom3d.mesh.BitTypeVertexInterpolator;
import net.imglib2.Cursor;
import net.imglib2.IterableInterval;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.algorithm.labeling.ConnectedComponents;
import net.imglib2.algorithm.morphology.StructuringElements;
import net.imglib2.img.Img;
import net.imglib2.img.array.ArrayImgs;
import net.imglib2.roi.labeling.ImgLabeling;
import net.imglib2.type.logic.BitType;
import net.imglib2.type.numeric.integer.IntType;
import net.imglib2.type.numeric.integer.LongType;
import net.imglib2.type.numeric.integer.UnsignedByteType;
import net.imglib2.type.numeric.integer.UnsignedShortType;
import net.imglib2.type.volatiles.VolatileUnsignedShortType;
import net.imglib2.util.Intervals;
import net.imglib2.view.IntervalView;
import net.imglib2.view.Views;
import org.apache.commons.io.FileUtils;
import org.scijava.command.Command;
import org.scijava.command.CommandService;
import org.scijava.io.IOService;
import org.scijava.log.LogService;
import org.scijava.plugin.Menu;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.ui.UIService;
import org.scijava.util.ColorRGB;
import sc.iview.SciView;
import sc.iview.Utils;
import sc.iview.process.MeshConverter;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Random;
import java.util.concurrent.atomic.AtomicReference;
import static sc.iview.commands.MenuWeights.*;
/**
* A demo rendering an embryo volume with meshes for nuclei.
*
* @author Kyle Harrington
*/
@Plugin(type = Command.class, label = "Embryo Demo", menuRoot = "SciView", //
menu = { @Menu(label = "Demo", weight = DEMO), //
@Menu(label = "Embryo", weight = DEMO_EMBRYO) })
public class EmbryoDemo implements Command {
@Parameter
private IOService io;
@Parameter
private LogService log;
@Parameter
private SciView sciView;
@Parameter
private CommandService commandService;
@Parameter
private OpService opService;
@Parameter
private UIService uiService;
@Parameter
private IOService ioService;
private String localDirectory = System.getProperty("user.home") + File.separator + "Desktop";
private BDVVolume v;
@Override
public void run() {
fetchEmbryoImage(localDirectory);
v = (BDVVolume) sciView.addBDVVolume(localDirectory + File.separator + "drosophila_filtered.xml");
v.setName( "Embryo Demo" );
v.setPixelToWorldRatio(0.1f);
v.setNeedsUpdate(true);
v.setDirty(true);
// Set the initial volume transfer function
/* TODO: TransferFunction behaviour is not yet implemeneted for BDVVolumes
AtomicReference<Float> rampMax = new AtomicReference<>(0.007f);
float rampStep = 0.01f;
AtomicReference<Double> dRampSign = new AtomicReference<>(1.);
if( rampMax.get() < 0 ) {
dRampSign.updateAndGet(v1 -> v1 * -1);
}
if( rampMax.get() > 0.3 ) {
dRampSign.updateAndGet(v1 -> v1 * -1);
}
rampMax.updateAndGet(v1 -> (float) (v1 + dRampSign.get() * rampStep));
//System.out.println("RampMax: " + rampMax.get());
v.setTransferFunction(TransferFunction.ramp(0.0f, rampMax.get()));
v.setNeedsUpdate(true);
v.setDirty(true);
*/
// use ConverterSetups instead:
v.getConverterSetups().forEach( s -> s.setDisplayRange( 500.0, 1500.0 ) );
sciView.centerOnNode( sciView.getActiveNode() );
System.out.println("Meshing nuclei");
Img<UnsignedByteType> filtered = null;
try {
filtered = (Img<UnsignedByteType> ) ioService.open("/home/kharrington/Data/Tobi/drosophila_filtered_8bit_v2.tif");
} catch (IOException e) {
e.printStackTrace();
}
// RandomAccessibleInterval<VolatileUnsignedShortType> volRAI = (RandomAccessibleInterval<VolatileUnsignedShortType>) v.getStack(0, 0, false).resolutions().get(0).getImage();
// IterableInterval<VolatileUnsignedShortType> volII = Views.iterable(volRAI);
//
// int isoLevel = 6;
//
// //Img<UnsignedByteType> volImg = opService.create().img(new long[]{volII.dimension(0), volII.dimension(1), volII.dimension(2)},new UnsignedByteType());
// Img<UnsignedByteType> volImg = opService.create().img(Intervals.createMinMax(0,0,0,volII.dimension(0), volII.dimension(1), volII.dimension(2)), new UnsignedByteType());
//
// System.out.println("Populating img: " + volImg);
//
// Cursor<VolatileUnsignedShortType> c0 = volII.cursor();
// Cursor<UnsignedByteType> c1 = volImg.cursor();
// while(c0.hasNext()) {
// c0.next();
// c1.next();
// c1.get().set(c0.get().get().get());
// }
Img<UnsignedByteType> volImg = filtered;
int isoLevel = 75;
uiService.show(volImg);
Img<BitType> bitImg = ( Img<BitType> ) opService.threshold().apply( volImg, new UnsignedByteType( isoLevel ) );
System.out.println("Thresholding done");
//ImgLabeling<Object, IntType> labels = opService.labeling().cca(bitImg, ConnectedComponents.StructuringElement.FOUR_CONNECTED);
int start = 1;
final Iterator< Integer > names = new Iterator< Integer >()
{
private int i = start;
@Override
public boolean hasNext()
{
return true;
}
@Override
public Integer next()
{
return i++;
}
@Override
public void remove()
{}
};
final long[] dimensions = new long[] { bitImg.dimension(0), bitImg.dimension(1), bitImg.dimension(2) };
final Img< LongType > indexImg = ArrayImgs.longs( dimensions );
final ImgLabeling< Integer, LongType > labeling = new ImgLabeling<>(indexImg);
ConnectedComponents.labelAllConnectedComponents( bitImg, labeling, names, ConnectedComponents.StructuringElement.FOUR_CONNECTED );
uiService.show(bitImg);
uiService.show(indexImg);
Node[] lights = sciView.getSceneNodes(n -> n instanceof PointLight);
float y = 0;
GLVector c = new GLVector(0,0,0);
float r = 500;
for( int k = 0; k < lights.length; k++ ) {
PointLight light = (PointLight) lights[k];
float x = (float) (c.x() + r * Math.cos( k == 0 ? 0 : Math.PI * 2 * ((float)k / (float)lights.length) ));
float z = (float) (c.y() + r * Math.sin( k == 0 ? 0 : Math.PI * 2 * ((float)k / (float)lights.length) ));
light.setLightRadius( 2 * r );
light.setPosition( new GLVector( x, y, z ) );
}
showMeshes(labeling);
// Mesh m = opService.geom().marchingCubes( bitImg, isoLevel, new BitTypeVertexInterpolator() );
// System.out.println("Marching cubes done");
//
// graphics.scenery.Mesh isoSurfaceMesh = MeshConverter.toScenery(m,true);
// Node scMesh = sciView.addMesh(isoSurfaceMesh);
//
// isoSurfaceMesh.setName( "Volume Render Demo Isosurface" );
// isoSurfaceMesh.setScale(new GLVector(v.getPixelToWorldRatio(),
// v.getPixelToWorldRatio(),
// v.getPixelToWorldRatio()));
//sciView.addSphere();
}
public void showMeshes( ImgLabeling<Integer, LongType> labeling ) {
RandomAccessibleInterval<LongType> labelRAI = labeling.getIndexImg();
IterableInterval<LongType> labelII = Views.iterable(labelRAI);
HashSet<Long> labelSet = new HashSet<>();
Cursor<LongType> cur = labelII.cursor();
while( cur.hasNext() ) {
cur.next();
labelSet.add((long) cur.get().get());
}
// Create label list and colors
ArrayList<LongType> labelList = new ArrayList<>();
ArrayList<ColorRGB> labelColors = new ArrayList<>();
for( Long l : labelSet ) {
labelList.add( new LongType(Math.toIntExact(l)) );
labelColors.add( new ColorRGB((int) (Math.random()*255), (int) (Math.random()*255), (int) (Math.random()*255) ) );
}
int numRegions = labelList.size();
// GLVector vOffset = new GLVector(v.getSizeX() * v.getVoxelSizeX() * v.getPixelToWorldRatio() * 0.5f,
// v.getSizeY() * v.getVoxelSizeY() * v.getPixelToWorldRatio() * 0.5f,
// v.getSizeZ() * v.getVoxelSizeZ() * v.getPixelToWorldRatio() * 0.5f);
GLVector vHalf = new GLVector(v.getSizeX() * v.getVoxelSizeX() * v.getPixelToWorldRatio() * 0.5f,
v.getSizeY() * v.getVoxelSizeY() * v.getPixelToWorldRatio() * 0.5f,
v.getSizeZ() * v.getVoxelSizeZ() * v.getPixelToWorldRatio() * 0.5f);
GLVector vOffset = new GLVector(0,0,0);
System.out.println("Found " + numRegions + " regions");
System.out.println("Voxel size: " + v.getVoxelSizeX() + " , " + v.getVoxelSizeY() + " " + v.getVoxelSizeZ() + " voxtoworld: " + v.getPixelToWorldRatio());
Random rng = new Random();
// Create label images and segmentations
//for( LabelRegion labelRegion : labelRegions ) {
for( int k = 0; k < numRegions; k++ ) {
System.out.println("Starting to process region " + k );
long id = labelList.get(k).getIntegerLong();
if( id > 1 ) { // Ignore background
// get labelColor using ID
//ColorRGB labelColor = labelColors.get(k);
//ColorRGB labelColor = colorFromID(id);
//ColorRGB labelColor = new ColorRGB(255,255,255);
ColorRGB labelColor = new ColorRGB(rng.nextInt(255),rng.nextInt(255), rng.nextInt(255));
Img<BitType> labelRegion = opService.create().img(labelII, new BitType());
cur = labelII.cursor();
LongType thisLabel = labelList.get(k);
Cursor<BitType> rCur = labelRegion.cursor();
long sum = 0;
while (cur.hasNext()) {
cur.next();
rCur.next();
if (cur.get().valueEquals(thisLabel)) {
rCur.get().set(true);
sum++;
} else {
rCur.get().set(false);
}
}
System.out.println("Label " + k + " has sum voxels = " + sum);
// FIXME: hack to skip large meshes
if ( sum > 10 && sum < 10000) {
// Find the smallest bounding box
int xmin=Integer.MAX_VALUE, ymin=Integer.MAX_VALUE, zmin=Integer.MAX_VALUE;
int xmax=Integer.MIN_VALUE, ymax=Integer.MIN_VALUE, zmax=Integer.MIN_VALUE;
int x,y,z;
rCur = labelRegion.cursor();
while(rCur.hasNext()) {
rCur.next();
if( rCur.get().get() ) {
x = rCur.getIntPosition(0);
y = rCur.getIntPosition(1);
z = rCur.getIntPosition(2);
xmin = Math.min(xmin,x);
ymin = Math.min(ymin,y);
zmin = Math.min(zmin,z);
xmax = Math.max(xmax,x);
ymax = Math.max(ymax,y);
zmax = Math.max(zmax,z);
}
}
IntervalView<BitType> cropLabelRegion = Views.interval(labelRegion, new long[]{xmin, ymin, zmin}, new long[]{xmax, ymax, zmax});
Mesh m = opService.geom().marchingCubes(cropLabelRegion, 1, new BitTypeVertexInterpolator());
graphics.scenery.Mesh isoSurfaceMesh = MeshConverter.toScenery(m, false);
isoSurfaceMesh.recalculateNormals();
Node scMesh = sciView.addMesh(isoSurfaceMesh);
scMesh.setPosition(scMesh.getPosition().minus(vOffset).plus(new GLVector( -vHalf.x() + xmin* v.getVoxelSizeX() * v.getPixelToWorldRatio() * 0.5f,
ymin* v.getVoxelSizeX() * v.getPixelToWorldRatio() * 0.5f,
zmin* v.getVoxelSizeX() * v.getPixelToWorldRatio() * 0.5f)));
scMesh.setScale(new GLVector(v.getPixelToWorldRatio(),
v.getPixelToWorldRatio(),
v.getPixelToWorldRatio()));
scMesh.getMaterial().setAmbient(Utils.convertToGLVector(labelColor));
scMesh.getMaterial().setDiffuse(Utils.convertToGLVector(labelColor));
scMesh.setName("region_" + k);
scMesh.setNeedsUpdate(true);
scMesh.setDirty(true);
scMesh.getMetadata().put("mesh_ID", id);
}
}
//scMesh.setName( "region_" + labelRegion.getLabel() );
}
sciView.takeScreenshot();
// Remove all other old meshes
// for( Node n : previousMeshes ) {
// sciView.deleteNode( n );
// }
// Color code meshes and overlay in volume
}
public static ColorRGB colorFromID( Long id ) {
// Hash to get label colors so they are unique by id
Random rng = new Random(id);
return new ColorRGB( rng.nextInt(256), rng.nextInt(256), rng.nextInt(256) );
}
public void fetchEmbryoImage(String localDestination) {
String remoteLocation = "https://fly.mpi-cbg.de/~pietzsch/bdv-examples/";
String xmlFilename = "drosophila_filtered.xml";
String h5Filename = "drosophila_filtered.h5";
if( !(new File(localDirectory + File.separator + xmlFilename).exists()) ) {
// File doesnt exist, so fetch
System.out.println("Fetching data. This may take a moment...");
try {
FileUtils.copyURLToFile(new URL(remoteLocation + "/" + xmlFilename),
new File(localDestination + File.separator + xmlFilename));
FileUtils.copyURLToFile(new URL(remoteLocation + "/" + h5Filename),
new File(localDestination + File.separator + h5Filename));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
|
src/main/java/sc/iview/commands/demo/EmbryoDemo.java
|
/*-
* #%L
* Scenery-backed 3D visualization package for ImageJ.
* %%
* Copyright (C) 2016 - 2018 SciView developers.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package sc.iview.commands.demo;
import cleargl.GLVector;
import graphics.scenery.Material;
import graphics.scenery.Node;
import graphics.scenery.volumes.TransferFunction;
import graphics.scenery.volumes.bdv.BDVVolume;
import net.imagej.mesh.Mesh;
import org.apache.commons.io.FileUtils;
import org.scijava.command.Command;
import org.scijava.command.CommandService;
import org.scijava.io.IOService;
import org.scijava.log.LogService;
import org.scijava.plugin.Menu;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import sc.iview.SciView;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.atomic.AtomicReference;
import static sc.iview.commands.MenuWeights.*;
/**
* A demo rendering an embryo volume with meshes for nuclei.
*
* @author Kyle Harrington
*/
@Plugin(type = Command.class, label = "Embryo Demo", menuRoot = "SciView", //
menu = { @Menu(label = "Demo", weight = DEMO), //
@Menu(label = "Embryo", weight = DEMO_EMBRYO) })
public class EmbryoDemo implements Command {
@Parameter
private IOService io;
@Parameter
private LogService log;
@Parameter
private SciView sciView;
@Parameter
private CommandService commandService;
private String localDirectory = System.getProperty("user.home") + File.separator + "Desktop";
@Override
public void run() {
fetchEmbryoImage(localDirectory);
BDVVolume v = (BDVVolume) sciView.addBDVVolume(localDirectory + File.separator + "drosophila.xml");
v.setName( "Embryo Demo" );
v.setPixelToWorldRatio(0.1f);
v.setNeedsUpdate(true);
v.setDirty(true);
// Set the initial volume transfer function
/* TODO: TransferFunction behaviour is not yet implemeneted for BDVVolumes
AtomicReference<Float> rampMax = new AtomicReference<>(0.007f);
float rampStep = 0.01f;
AtomicReference<Double> dRampSign = new AtomicReference<>(1.);
if( rampMax.get() < 0 ) {
dRampSign.updateAndGet(v1 -> v1 * -1);
}
if( rampMax.get() > 0.3 ) {
dRampSign.updateAndGet(v1 -> v1 * -1);
}
rampMax.updateAndGet(v1 -> (float) (v1 + dRampSign.get() * rampStep));
//System.out.println("RampMax: " + rampMax.get());
v.setTransferFunction(TransferFunction.ramp(0.0f, rampMax.get()));
v.setNeedsUpdate(true);
v.setDirty(true);
*/
// use ConverterSetups instead:
v.getConverterSetups().forEach( s -> s.setDisplayRange( 500.0, 1500.0 ) );
sciView.centerOnNode( sciView.getActiveNode() );
//sciView.addSphere();
}
public void fetchEmbryoImage(String localDestination) {
String remoteLocation = "https://fly.mpi-cbg.de/~pietzsch/bdv-examples/";
String xmlFilename = "drosophila.xml";
String h5Filename = "drosophila.h5";
if( !(new File(localDirectory + File.separator + xmlFilename).exists()) ) {
// File doesnt exist, so fetch
System.out.println("Fetching data. This may take a moment...");
try {
FileUtils.copyURLToFile(new URL(remoteLocation + "/" + xmlFilename),
new File(localDestination + File.separator + xmlFilename));
FileUtils.copyURLToFile(new URL(remoteLocation + "/" + h5Filename),
new File(localDestination + File.separator + h5Filename));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
|
Nuclei being meshed, but misplaced
|
src/main/java/sc/iview/commands/demo/EmbryoDemo.java
|
Nuclei being meshed, but misplaced
|
<ide><path>rc/main/java/sc/iview/commands/demo/EmbryoDemo.java
<ide> */
<ide> package sc.iview.commands.demo;
<ide>
<add>import bdv.util.Bdv;
<add>import bdv.util.BdvSource;
<ide> import cleargl.GLVector;
<ide> import graphics.scenery.Material;
<ide> import graphics.scenery.Node;
<add>import graphics.scenery.PointLight;
<ide> import graphics.scenery.volumes.TransferFunction;
<ide> import graphics.scenery.volumes.bdv.BDVVolume;
<add>import net.imagej.Dataset;
<ide> import net.imagej.mesh.Mesh;
<add>import net.imagej.ops.OpService;
<add>import net.imagej.ops.geom.geom3d.mesh.BitTypeVertexInterpolator;
<add>import net.imglib2.Cursor;
<add>import net.imglib2.IterableInterval;
<add>import net.imglib2.RandomAccessibleInterval;
<add>import net.imglib2.algorithm.labeling.ConnectedComponents;
<add>import net.imglib2.algorithm.morphology.StructuringElements;
<add>import net.imglib2.img.Img;
<add>import net.imglib2.img.array.ArrayImgs;
<add>import net.imglib2.roi.labeling.ImgLabeling;
<add>import net.imglib2.type.logic.BitType;
<add>import net.imglib2.type.numeric.integer.IntType;
<add>import net.imglib2.type.numeric.integer.LongType;
<add>import net.imglib2.type.numeric.integer.UnsignedByteType;
<add>import net.imglib2.type.numeric.integer.UnsignedShortType;
<add>import net.imglib2.type.volatiles.VolatileUnsignedShortType;
<add>import net.imglib2.util.Intervals;
<add>import net.imglib2.view.IntervalView;
<add>import net.imglib2.view.Views;
<ide> import org.apache.commons.io.FileUtils;
<ide> import org.scijava.command.Command;
<ide> import org.scijava.command.CommandService;
<ide> import org.scijava.plugin.Menu;
<ide> import org.scijava.plugin.Parameter;
<ide> import org.scijava.plugin.Plugin;
<add>import org.scijava.ui.UIService;
<add>import org.scijava.util.ColorRGB;
<ide> import sc.iview.SciView;
<add>import sc.iview.Utils;
<add>import sc.iview.process.MeshConverter;
<ide>
<ide> import java.io.File;
<ide> import java.io.IOException;
<ide> import java.net.URL;
<add>import java.util.ArrayList;
<add>import java.util.HashSet;
<add>import java.util.Iterator;
<add>import java.util.Random;
<ide> import java.util.concurrent.atomic.AtomicReference;
<ide>
<ide> import static sc.iview.commands.MenuWeights.*;
<ide> @Parameter
<ide> private CommandService commandService;
<ide>
<add> @Parameter
<add> private OpService opService;
<add>
<add> @Parameter
<add> private UIService uiService;
<add>
<add> @Parameter
<add> private IOService ioService;
<add>
<ide> private String localDirectory = System.getProperty("user.home") + File.separator + "Desktop";
<add> private BDVVolume v;
<ide>
<ide> @Override
<ide> public void run() {
<ide> fetchEmbryoImage(localDirectory);
<ide>
<del> BDVVolume v = (BDVVolume) sciView.addBDVVolume(localDirectory + File.separator + "drosophila.xml");
<add> v = (BDVVolume) sciView.addBDVVolume(localDirectory + File.separator + "drosophila_filtered.xml");
<ide> v.setName( "Embryo Demo" );
<ide> v.setPixelToWorldRatio(0.1f);
<ide> v.setNeedsUpdate(true);
<ide>
<ide> sciView.centerOnNode( sciView.getActiveNode() );
<ide>
<add> System.out.println("Meshing nuclei");
<add>
<add> Img<UnsignedByteType> filtered = null;
<add> try {
<add> filtered = (Img<UnsignedByteType> ) ioService.open("/home/kharrington/Data/Tobi/drosophila_filtered_8bit_v2.tif");
<add> } catch (IOException e) {
<add> e.printStackTrace();
<add> }
<add>
<add>// RandomAccessibleInterval<VolatileUnsignedShortType> volRAI = (RandomAccessibleInterval<VolatileUnsignedShortType>) v.getStack(0, 0, false).resolutions().get(0).getImage();
<add>// IterableInterval<VolatileUnsignedShortType> volII = Views.iterable(volRAI);
<add>//
<add>// int isoLevel = 6;
<add>//
<add>// //Img<UnsignedByteType> volImg = opService.create().img(new long[]{volII.dimension(0), volII.dimension(1), volII.dimension(2)},new UnsignedByteType());
<add>// Img<UnsignedByteType> volImg = opService.create().img(Intervals.createMinMax(0,0,0,volII.dimension(0), volII.dimension(1), volII.dimension(2)), new UnsignedByteType());
<add>//
<add>// System.out.println("Populating img: " + volImg);
<add>//
<add>// Cursor<VolatileUnsignedShortType> c0 = volII.cursor();
<add>// Cursor<UnsignedByteType> c1 = volImg.cursor();
<add>// while(c0.hasNext()) {
<add>// c0.next();
<add>// c1.next();
<add>// c1.get().set(c0.get().get().get());
<add>// }
<add>
<add> Img<UnsignedByteType> volImg = filtered;
<add>
<add> int isoLevel = 75;
<add> uiService.show(volImg);
<add>
<add> Img<BitType> bitImg = ( Img<BitType> ) opService.threshold().apply( volImg, new UnsignedByteType( isoLevel ) );
<add> System.out.println("Thresholding done");
<add>
<add> //ImgLabeling<Object, IntType> labels = opService.labeling().cca(bitImg, ConnectedComponents.StructuringElement.FOUR_CONNECTED);
<add>
<add> int start = 1;
<add> final Iterator< Integer > names = new Iterator< Integer >()
<add> {
<add> private int i = start;
<add>
<add> @Override
<add> public boolean hasNext()
<add> {
<add> return true;
<add> }
<add>
<add> @Override
<add> public Integer next()
<add> {
<add> return i++;
<add> }
<add>
<add> @Override
<add> public void remove()
<add> {}
<add> };
<add> final long[] dimensions = new long[] { bitImg.dimension(0), bitImg.dimension(1), bitImg.dimension(2) };
<add> final Img< LongType > indexImg = ArrayImgs.longs( dimensions );
<add> final ImgLabeling< Integer, LongType > labeling = new ImgLabeling<>(indexImg);
<add> ConnectedComponents.labelAllConnectedComponents( bitImg, labeling, names, ConnectedComponents.StructuringElement.FOUR_CONNECTED );
<add>
<add> uiService.show(bitImg);
<add> uiService.show(indexImg);
<add>
<add> Node[] lights = sciView.getSceneNodes(n -> n instanceof PointLight);
<add> float y = 0;
<add> GLVector c = new GLVector(0,0,0);
<add> float r = 500;
<add> for( int k = 0; k < lights.length; k++ ) {
<add> PointLight light = (PointLight) lights[k];
<add> float x = (float) (c.x() + r * Math.cos( k == 0 ? 0 : Math.PI * 2 * ((float)k / (float)lights.length) ));
<add> float z = (float) (c.y() + r * Math.sin( k == 0 ? 0 : Math.PI * 2 * ((float)k / (float)lights.length) ));
<add> light.setLightRadius( 2 * r );
<add> light.setPosition( new GLVector( x, y, z ) );
<add> }
<add>
<add> showMeshes(labeling);
<add>
<add>// Mesh m = opService.geom().marchingCubes( bitImg, isoLevel, new BitTypeVertexInterpolator() );
<add>// System.out.println("Marching cubes done");
<add>//
<add>// graphics.scenery.Mesh isoSurfaceMesh = MeshConverter.toScenery(m,true);
<add>// Node scMesh = sciView.addMesh(isoSurfaceMesh);
<add>//
<add>// isoSurfaceMesh.setName( "Volume Render Demo Isosurface" );
<add>// isoSurfaceMesh.setScale(new GLVector(v.getPixelToWorldRatio(),
<add>// v.getPixelToWorldRatio(),
<add>// v.getPixelToWorldRatio()));
<add>
<ide> //sciView.addSphere();
<ide> }
<ide>
<add> public void showMeshes( ImgLabeling<Integer, LongType> labeling ) {
<add>
<add> RandomAccessibleInterval<LongType> labelRAI = labeling.getIndexImg();
<add> IterableInterval<LongType> labelII = Views.iterable(labelRAI);
<add> HashSet<Long> labelSet = new HashSet<>();
<add> Cursor<LongType> cur = labelII.cursor();
<add> while( cur.hasNext() ) {
<add> cur.next();
<add> labelSet.add((long) cur.get().get());
<add> }
<add>
<add> // Create label list and colors
<add> ArrayList<LongType> labelList = new ArrayList<>();
<add> ArrayList<ColorRGB> labelColors = new ArrayList<>();
<add> for( Long l : labelSet ) {
<add> labelList.add( new LongType(Math.toIntExact(l)) );
<add> labelColors.add( new ColorRGB((int) (Math.random()*255), (int) (Math.random()*255), (int) (Math.random()*255) ) );
<add> }
<add>
<add> int numRegions = labelList.size();
<add>
<add>// GLVector vOffset = new GLVector(v.getSizeX() * v.getVoxelSizeX() * v.getPixelToWorldRatio() * 0.5f,
<add>// v.getSizeY() * v.getVoxelSizeY() * v.getPixelToWorldRatio() * 0.5f,
<add>// v.getSizeZ() * v.getVoxelSizeZ() * v.getPixelToWorldRatio() * 0.5f);
<add>
<add> GLVector vHalf = new GLVector(v.getSizeX() * v.getVoxelSizeX() * v.getPixelToWorldRatio() * 0.5f,
<add> v.getSizeY() * v.getVoxelSizeY() * v.getPixelToWorldRatio() * 0.5f,
<add> v.getSizeZ() * v.getVoxelSizeZ() * v.getPixelToWorldRatio() * 0.5f);
<add>
<add> GLVector vOffset = new GLVector(0,0,0);
<add>
<add>
<add> System.out.println("Found " + numRegions + " regions");
<add> System.out.println("Voxel size: " + v.getVoxelSizeX() + " , " + v.getVoxelSizeY() + " " + v.getVoxelSizeZ() + " voxtoworld: " + v.getPixelToWorldRatio());
<add>
<add> Random rng = new Random();
<add>
<add> // Create label images and segmentations
<add> //for( LabelRegion labelRegion : labelRegions ) {
<add> for( int k = 0; k < numRegions; k++ ) {
<add> System.out.println("Starting to process region " + k );
<add> long id = labelList.get(k).getIntegerLong();
<add>
<add> if( id > 1 ) { // Ignore background
<add>
<add> // get labelColor using ID
<add> //ColorRGB labelColor = labelColors.get(k);
<add> //ColorRGB labelColor = colorFromID(id);
<add> //ColorRGB labelColor = new ColorRGB(255,255,255);
<add> ColorRGB labelColor = new ColorRGB(rng.nextInt(255),rng.nextInt(255), rng.nextInt(255));
<add>
<add> Img<BitType> labelRegion = opService.create().img(labelII, new BitType());
<add> cur = labelII.cursor();
<add> LongType thisLabel = labelList.get(k);
<add> Cursor<BitType> rCur = labelRegion.cursor();
<add> long sum = 0;
<add> while (cur.hasNext()) {
<add> cur.next();
<add> rCur.next();
<add> if (cur.get().valueEquals(thisLabel)) {
<add> rCur.get().set(true);
<add> sum++;
<add> } else {
<add> rCur.get().set(false);
<add> }
<add> }
<add> System.out.println("Label " + k + " has sum voxels = " + sum);
<add>
<add> // FIXME: hack to skip large meshes
<add> if ( sum > 10 && sum < 10000) {
<add>
<add> // Find the smallest bounding box
<add> int xmin=Integer.MAX_VALUE, ymin=Integer.MAX_VALUE, zmin=Integer.MAX_VALUE;
<add> int xmax=Integer.MIN_VALUE, ymax=Integer.MIN_VALUE, zmax=Integer.MIN_VALUE;
<add> int x,y,z;
<add> rCur = labelRegion.cursor();
<add> while(rCur.hasNext()) {
<add> rCur.next();
<add> if( rCur.get().get() ) {
<add> x = rCur.getIntPosition(0);
<add> y = rCur.getIntPosition(1);
<add> z = rCur.getIntPosition(2);
<add> xmin = Math.min(xmin,x);
<add> ymin = Math.min(ymin,y);
<add> zmin = Math.min(zmin,z);
<add> xmax = Math.max(xmax,x);
<add> ymax = Math.max(ymax,y);
<add> zmax = Math.max(zmax,z);
<add> }
<add> }
<add>
<add> IntervalView<BitType> cropLabelRegion = Views.interval(labelRegion, new long[]{xmin, ymin, zmin}, new long[]{xmax, ymax, zmax});
<add>
<add> Mesh m = opService.geom().marchingCubes(cropLabelRegion, 1, new BitTypeVertexInterpolator());
<add>
<add> graphics.scenery.Mesh isoSurfaceMesh = MeshConverter.toScenery(m, false);
<add> isoSurfaceMesh.recalculateNormals();
<add>
<add> Node scMesh = sciView.addMesh(isoSurfaceMesh);
<add> scMesh.setPosition(scMesh.getPosition().minus(vOffset).plus(new GLVector( -vHalf.x() + xmin* v.getVoxelSizeX() * v.getPixelToWorldRatio() * 0.5f,
<add> ymin* v.getVoxelSizeX() * v.getPixelToWorldRatio() * 0.5f,
<add> zmin* v.getVoxelSizeX() * v.getPixelToWorldRatio() * 0.5f)));
<add> scMesh.setScale(new GLVector(v.getPixelToWorldRatio(),
<add> v.getPixelToWorldRatio(),
<add> v.getPixelToWorldRatio()));
<add> scMesh.getMaterial().setAmbient(Utils.convertToGLVector(labelColor));
<add> scMesh.getMaterial().setDiffuse(Utils.convertToGLVector(labelColor));
<add> scMesh.setName("region_" + k);
<add> scMesh.setNeedsUpdate(true);
<add> scMesh.setDirty(true);
<add> scMesh.getMetadata().put("mesh_ID", id);
<add>
<add> }
<add> }
<add> //scMesh.setName( "region_" + labelRegion.getLabel() );
<add> }
<add> sciView.takeScreenshot();
<add>
<add> // Remove all other old meshes
<add>// for( Node n : previousMeshes ) {
<add>// sciView.deleteNode( n );
<add>// }
<add>
<add> // Color code meshes and overlay in volume
<add> }
<add>
<add> public static ColorRGB colorFromID( Long id ) {
<add> // Hash to get label colors so they are unique by id
<add> Random rng = new Random(id);
<add> return new ColorRGB( rng.nextInt(256), rng.nextInt(256), rng.nextInt(256) );
<add> }
<add>
<ide> public void fetchEmbryoImage(String localDestination) {
<ide> String remoteLocation = "https://fly.mpi-cbg.de/~pietzsch/bdv-examples/";
<del> String xmlFilename = "drosophila.xml";
<del> String h5Filename = "drosophila.h5";
<add> String xmlFilename = "drosophila_filtered.xml";
<add> String h5Filename = "drosophila_filtered.h5";
<ide>
<ide> if( !(new File(localDirectory + File.separator + xmlFilename).exists()) ) {
<ide> // File doesnt exist, so fetch
|
|
JavaScript
|
mit
|
7a4c0bb330e7dbf0bcb88a9a4d4d2c93c6dd0b81
| 0 |
zubairq/gosharedata,zubairq/yazz,zubairq/gosharedata,zubairq/AppShare,zubairq/yazz,zubairq/AppShare,zubairq/AppShare,zubairq/AppShare
|
function showHelp() {
$('#myModal').modal();
}
|
resources/public/coilshelpers.js
|
showHelp = function() {
$('#myModal').modal();
}
updateScrollSpy = function() {
//$('#bs-sidebar').on('activate.bs.scrollspy', function () {
$('[data-spy="scroll"]').each(function () {
var $spy = $(this).scrollspy('refresh')
});
//});
}
|
Investigating IE8 bug
|
resources/public/coilshelpers.js
|
Investigating IE8 bug
|
<ide><path>esources/public/coilshelpers.js
<del>showHelp = function() {
<add>function showHelp() {
<ide> $('#myModal').modal();
<ide> }
<del>
<del>updateScrollSpy = function() {
<del> //$('#bs-sidebar').on('activate.bs.scrollspy', function () {
<del>
<del>
<del> $('[data-spy="scroll"]').each(function () {
<del> var $spy = $(this).scrollspy('refresh')
<del> });
<del>
<del> //});
<del>
<del>}
|
|
Java
|
apache-2.0
|
7cf11a79f9fc626607df02ec58b320c2c5bb0ce1
| 0 |
mariamKh/robovm-ios-bindings,dzungpv/robovm-ios-bindings,BlueRiverInteractive/robovm-ios-bindings,BlueRiverInteractive/robovm-ios-bindings,BlueRiverInteractive/robovm-ios-bindings,mariamKh/robovm-ios-bindings,mariamKh/robovm-ios-bindings,TomGrill/robovm-ios-bindings,BlueRiverInteractive/robovm-ios-bindings,mariamKh/robovm-ios-bindings,Roncon93/robovm-ios-bindings,Roncon93/robovm-ios-bindings,TomGrill/robovm-ios-bindings,mariamKh/robovm-ios-bindings,TomGrill/robovm-ios-bindings,dzungpv/robovm-ios-bindings,Roncon93/robovm-ios-bindings,dzungpv/robovm-ios-bindings,TomGrill/robovm-ios-bindings,BlueRiverInteractive/robovm-ios-bindings,dzungpv/robovm-ios-bindings,Roncon93/robovm-ios-bindings,TomGrill/robovm-ios-bindings,dzungpv/robovm-ios-bindings,Roncon93/robovm-ios-bindings,TomGrill/robovm-ios-bindings,Roncon93/robovm-ios-bindings,BlueRiverInteractive/robovm-ios-bindings,dzungpv/robovm-ios-bindings
|
package org.robovm.bindings.mopub;
import org.robovm.cocoatouch.coregraphics.CGRect;
import org.robovm.cocoatouch.foundation.NSAutoreleasePool;
import org.robovm.cocoatouch.uikit.UIApplication;
import org.robovm.cocoatouch.uikit.UIApplicationDelegate;
import org.robovm.cocoatouch.uikit.UIColor;
import org.robovm.cocoatouch.uikit.UIScreen;
import org.robovm.cocoatouch.uikit.UIViewController;
import org.robovm.cocoatouch.uikit.UIWindow;
/**
* Basic usage of banners and interstitials.
*/
public class Sample extends UIApplicationDelegate.Adapter {
private UIViewController interstitialViewController;
@Override
public void didFinishLaunching(UIApplication application) {
// We need a view controller to see ads.
interstitialViewController = new UIViewController();
// Create an interstitial.
MPInterstitialAdController interstitial = MPInterstitialAdController.getAdController("YOUR_AD_UNIT_ID");
// The delegate for an interstitial is optional.
MPInterstitialAdControllerDelegate delegate = new MPInterstitialAdControllerDelegate.Adapter() {
@Override
public void didExpire(MPInterstitialAdController interstitial) {
// If the ad did expire, load a new ad.
interstitial.loadAd();
}
@Override
public void didLoadAd(MPInterstitialAdController interstitial) {
// If the ad is ready, show it.
// It's best to call these methods manually and not in didLoadAd().
if (interstitial.isReady())
interstitial.show(interstitialViewController);
}
@Override
public void didFailToLoadAd(MPInterstitialAdController interstitial) {
// If the ad did fail to load, load a new ad. Check the debug log to see why it didn't load.
interstitial.loadAd();
}
};
interstitial.setDelegate(delegate);
// Load an interstitial ad.
interstitial.loadAd();
// Create a MoPub ad. In this case a banner, but you can make it any size you want.
MPAdView banner = new MPAdView("YOUR_AD_UNIT_ID", MPConstants.MOPUB_BANNER_SIZE);
// Let's calculate our banner size. We need to do this because the resolution of a retina and normal device is different.
float bannerWidth = UIScreen.getMainScreen().getApplicationFrame().size().width();
float bannerHeight = bannerWidth / MPConstants.MOPUB_BANNER_SIZE.width() * MPConstants.MOPUB_BANNER_SIZE.height();
// Let's set the frame (boundings) of our banner view. Remember on iOS view coordinates have their origin top-left.
// Position banner on the top.
// banner.setFrame(new CGRect(0, 0, bannerWidth, bannerHeight));
// Position banner on the bottom.
banner.setFrame(new CGRect(0, UIScreen.getMainScreen().getApplicationFrame().size().height() - bannerHeight, bannerWidth, bannerHeight));
// Let's color the background for testing, so we can see if it is positioned correctly, even if no ad is loaded yet.
banner.setBackgroundColor(new UIColor(1, 0, 0, 1)); // Remove this after testing.
// The delegate for the banner. It is required to override getViewController() to get ads.
MPAdViewDelegate bannerDelegate = new MPAdViewDelegate.Adapter() {
@Override
public UIViewController getViewController() {
return interstitialViewController;
}
};
banner.setDelegate(bannerDelegate);
// Add banner to our view controller.
interstitialViewController.getView().addSubview(banner);
// Finally load a banner ad. This ad gets refreshed automatically, although you can refresh it at any time via refreshAd().
banner.loadAd();
// Create a standard UIWindow at screen size, add the view controller and show it.
UIWindow window = new UIWindow(UIScreen.getMainScreen().getBounds());
window.setRootViewController(interstitialViewController);
window.makeKeyAndVisible();
// If you are already using a UIWindow, you can do the following (f.e. LibGDX):
// UIView interstitialView = new UIView(UIScreen.getMainScreen().getBounds());
// interstitialView.setUserInteractionEnabled(false);
// interstitialViewController.setView(interstitialView);
// application.getKeyWindow().addSubview(interstitialViewController.getView());
}
public static void main(String[] argv) {
NSAutoreleasePool pool = new NSAutoreleasePool();
UIApplication.main(argv, null, Sample.class);
pool.drain();
}
}
|
mopub/src/org/robovm/bindings/mopub/Sample.java
|
package org.robovm.bindings.mopub;
import org.robovm.cocoatouch.coregraphics.CGRect;
import org.robovm.cocoatouch.foundation.NSAutoreleasePool;
import org.robovm.cocoatouch.uikit.UIApplication;
import org.robovm.cocoatouch.uikit.UIApplicationDelegate;
import org.robovm.cocoatouch.uikit.UIColor;
import org.robovm.cocoatouch.uikit.UIScreen;
import org.robovm.cocoatouch.uikit.UIViewController;
import org.robovm.cocoatouch.uikit.UIWindow;
/**
* Basic usage of banners and interstitials.
*/
public class Sample extends UIApplicationDelegate.Adapter {
private UIViewController interstitialViewController;
@Override
public void didFinishLaunching(UIApplication application) {
// We need a view controller to see ads.
interstitialViewController = new UIViewController();
// Create an interstitial.
MPInterstitialAdController interstitial = MPInterstitialAdController.getAdController("YOUR_AD_UNIT_ID");
// The delegate for an interstitial is optional.
MPInterstitialAdControllerDelegate delegate = new MPInterstitialAdControllerDelegate.Adapter() {
@Override
public void didExpire(MPInterstitialAdController interstitial) {
// If the ad did expire, load a new ad.
interstitial.loadAd();
}
@Override
public void didLoadAd(MPInterstitialAdController interstitial) {
// If the ad is ready, show it.
// It's best to call these methods manually and not in didLoadAd().
if (interstitial.isReady())
interstitial.show(interstitialViewController);
}
@Override
public void didFailToLoadAd(MPInterstitialAdController interstitial) {
// If the ad did fail to load, load a new ad. Check the debug log to see why it didn't load.
interstitial.loadAd();
}
};
interstitial.setDelegate(delegate);
// Load an interstitial ad.
interstitial.loadAd();
// Create a MoPub ad. In this case a banner, but you can make it any size you want.
MPAdView banner = new MPAdView("YOUR_AD_UNIT_ID", MPConstants.MOPUB_BANNER_SIZE);
// Let's calculate our banner size. We need to do this because the resolution of a retina and normal device is different.
float bannerWidth = UIScreen.getMainScreen().getApplicationFrame().size().width();
float bannerHeight = bannerWidth / MPConstants.MOPUB_BANNER_SIZE.width() * MPConstants.MOPUB_BANNER_SIZE.height();
// Let's set the frame (boundings) of our banner view. Remember on iOS view coordinates have their origin top-left.
// Position banner on the top.
// banner.setFrame(new CGRect(0, 0, bannerWidth, bannerHeight));
// Position banner on the bottom.
banner.setFrame(new CGRect(0, UIScreen.getMainScreen().getApplicationFrame().size().height() - bannerHeight, bannerWidth, bannerHeight));
// Let's color the background for testing, so we can see if it is positioned correctly, even if no ad is loaded yet.
banner.setBackgroundColor(new UIColor(1, 0, 0, 1)); // Remove this after testing.
// The delegate for the banner. It is required to override getViewController() to get ads.
MPAdViewDelegate bannerDelegate = new MPAdViewDelegate.Adapter() {
@Override
public UIViewController getViewController() {
return interstitialViewController;
}
};
banner.setDelegate(bannerDelegate);
// Add banner to our view controller.
interstitialViewController.getView().addSubview(banner);
// Finally load a banner ad. This ad gets refreshed automatically, although you can refresh it at any time via refreshAd().
banner.loadAd();
// Create a standard UIWindow at screen size, add the view controller and show it.
UIWindow window = new UIWindow(UIScreen.getMainScreen().getBounds());
window.setRootViewController(interstitialViewController);
window.makeKeyAndVisible();
// If you are already using a UIWindow, you can do the following (f.e. LibGDX):
// UIView interstitialView = new UIView(UIScreen.getMainScreen().getBounds());
// interstitialView.setUserInteractionEnabled(false);
// mainViewController.setView(interstitialView);
// application.getKeyWindow().addSubview(mainViewController.getView());
}
public static void main(String[] argv) {
NSAutoreleasePool pool = new NSAutoreleasePool();
UIApplication.main(argv, null, Sample.class);
pool.drain();
}
}
|
Small fixes
|
mopub/src/org/robovm/bindings/mopub/Sample.java
|
Small fixes
|
<ide><path>opub/src/org/robovm/bindings/mopub/Sample.java
<ide> // If you are already using a UIWindow, you can do the following (f.e. LibGDX):
<ide> // UIView interstitialView = new UIView(UIScreen.getMainScreen().getBounds());
<ide> // interstitialView.setUserInteractionEnabled(false);
<del> // mainViewController.setView(interstitialView);
<del> // application.getKeyWindow().addSubview(mainViewController.getView());
<add> // interstitialViewController.setView(interstitialView);
<add> // application.getKeyWindow().addSubview(interstitialViewController.getView());
<ide> }
<ide>
<ide> public static void main(String[] argv) {
|
|
Java
|
mit
|
1e51c0f8737280bf6f9d73228866c04075cf3661
| 0 |
hovsepm/azure-sdk-for-java,navalev/azure-sdk-for-java,jmspring/azure-sdk-for-java,pomortaz/azure-sdk-for-java,oaastest/azure-sdk-for-java,anudeepsharma/azure-sdk-for-java,martinsawicki/azure-sdk-for-java,anudeepsharma/azure-sdk-for-java,anudeepsharma/azure-sdk-for-java,ljhljh235/azure-sdk-for-java,jmspring/azure-sdk-for-java,southworkscom/azure-sdk-for-java,oaastest/azure-sdk-for-java,southworkscom/azure-sdk-for-java,devigned/azure-sdk-for-java,Azure/azure-sdk-for-java,ljhljh235/azure-sdk-for-java,pomortaz/azure-sdk-for-java,devigned/azure-sdk-for-java,selvasingh/azure-sdk-for-java,herveyw/azure-sdk-for-java,hovsepm/azure-sdk-for-java,Azure/azure-sdk-for-java,hovsepm/azure-sdk-for-java,martinsawicki/azure-sdk-for-java,manikandan-palaniappan/azure-sdk-for-java,anudeepsharma/azure-sdk-for-java,navalev/azure-sdk-for-java,avranju/azure-sdk-for-java,manikandan-palaniappan/azure-sdk-for-java,jianghaolu/azure-sdk-for-java,Azure/azure-sdk-for-java,Azure/azure-sdk-for-java,jalves94/azure-sdk-for-java,ElliottMiller/azure-sdk-for-java,pomortaz/azure-sdk-for-java,anudeepsharma/azure-sdk-for-java,navalev/azure-sdk-for-java,jianghaolu/azure-sdk-for-java,herveyw/azure-sdk-for-java,selvasingh/azure-sdk-for-java,jingleheimerschmidt/azure-sdk-for-java,jianghaolu/azure-sdk-for-java,Azure/azure-sdk-for-java,jalves94/azure-sdk-for-java,ElliottMiller/azure-sdk-for-java,jalves94/azure-sdk-for-java,jingleheimerschmidt/azure-sdk-for-java,hovsepm/azure-sdk-for-java,jalves94/azure-sdk-for-java,navalev/azure-sdk-for-java,flydream2046/azure-sdk-for-java,martinsawicki/azure-sdk-for-java,avranju/azure-sdk-for-java,navalev/azure-sdk-for-java,flydream2046/azure-sdk-for-java,herveyw/azure-sdk-for-java,selvasingh/azure-sdk-for-java,pomortaz/azure-sdk-for-java,hovsepm/azure-sdk-for-java,herveyw/azure-sdk-for-java
|
/**
* Copyright 2012 Microsoft Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.windowsazure.services.media;
import static org.junit.Assert.*;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
import java.util.EnumSet;
import java.util.List;
import javax.ws.rs.core.MultivaluedMap;
import org.junit.Test;
import com.microsoft.windowsazure.services.core.ServiceException;
import com.microsoft.windowsazure.services.media.models.AccessPolicy;
import com.microsoft.windowsazure.services.media.models.AccessPolicyInfo;
import com.microsoft.windowsazure.services.media.models.AccessPolicyPermission;
import com.microsoft.windowsazure.services.media.models.Asset;
import com.microsoft.windowsazure.services.media.models.AssetFile;
import com.microsoft.windowsazure.services.media.models.AssetInfo;
import com.microsoft.windowsazure.services.media.models.Job;
import com.microsoft.windowsazure.services.media.models.JobInfo;
import com.microsoft.windowsazure.services.media.models.JobState;
import com.microsoft.windowsazure.services.media.models.ListResult;
import com.microsoft.windowsazure.services.media.models.Locator;
import com.microsoft.windowsazure.services.media.models.LocatorInfo;
import com.microsoft.windowsazure.services.media.models.LocatorType;
import com.microsoft.windowsazure.services.media.models.Task;
import com.sun.jersey.core.util.MultivaluedMapImpl;
public class JobIntegrationTest extends IntegrationTestBase {
private final String testJobPrefix = "testJobPrefix";
private final byte[] testBlobData = new byte[] { 0, 1, 2 };
private final String taskBody = "<?xml version=\"1.0\" encoding=\"utf-8\"?><taskBody>"
+ "<inputAsset>JobInputAsset(0)</inputAsset><outputAsset>JobOutputAsset(0)</outputAsset>" + "</taskBody>";
private void verifyJobInfoEqual(String message, JobInfo expected, JobInfo actual) {
verifyJobProperties(message, expected.getName(), expected.getPriority(), expected.getRunningDuration(),
expected.getState(), expected.getTemplateId(), expected.getInputMediaAssets(),
expected.getOutputMediaAssets(), actual);
}
private AccessPolicyInfo createWritableAccessPolicy(String name, int durationInMinutes) throws ServiceException {
return service.create(AccessPolicy.create(testPolicyPrefix + name, durationInMinutes,
EnumSet.of(AccessPolicyPermission.WRITE)));
}
private void createAndUploadBlob(WritableBlobContainerContract blobWriter, String blobName, byte[] blobData)
throws ServiceException {
InputStream blobContent = new ByteArrayInputStream(blobData);
blobWriter.createBlockBlob(blobName, blobContent);
}
private String createFileAsset(String name) throws ServiceException {
String testBlobName = "test" + name + ".bin";
AssetInfo assetInfo = service.create(Asset.create().setName(name));
AccessPolicyInfo accessPolicyInfo = createWritableAccessPolicy(name, 10);
LocatorInfo locator = createLocator(accessPolicyInfo, assetInfo, 5, 10);
WritableBlobContainerContract blobWriter = MediaService.createBlobWriter(locator);
createAndUploadBlob(blobWriter, testBlobName, testBlobData);
service.create(AssetFile.create(assetInfo.getId(), testBlobName).setIsPrimary(true).setIsEncrypted(false)
.setContentFileSize(new Long(testBlobData.length)));
service.action(AssetFile.createFileInfos(assetInfo.getId()));
return assetInfo.getId();
}
private LocatorInfo createLocator(AccessPolicyInfo accessPolicy, AssetInfo asset, int startDeltaMinutes,
int expirationDeltaMinutes) throws ServiceException {
Date now = new Date();
Date start = new Date(now.getTime() - (startDeltaMinutes * 60 * 1000));
Date expire = new Date(now.getTime() + (expirationDeltaMinutes * 60 * 1000));
return service.create(Locator.create(accessPolicy.getId(), asset.getId(), LocatorType.SAS)
.setStartDateTime(start).setExpirationDateTime(expire));
}
private void verifyJobProperties(String message, String testName, Integer priority, Double runningDuration,
JobState state, String templateId, List<String> inputMediaAssets, List<String> outputMediaAssets,
JobInfo actualJob) {
assertNotNull(message, actualJob);
assertEquals(message + " Name", testName, actualJob.getName());
// comment out due to issue 464
// assertEquals(message + " Priority", priority, actualJob.getPriority());
assertEquals(message + " RunningDuration", runningDuration, actualJob.getRunningDuration());
assertEquals(message + " State", state, actualJob.getState());
// commented out due to issue 463
// assertEquals(message + " TemplateId", templateId, actualJob.getTemplateId());
assertEquals(message + " InputMediaAssets", inputMediaAssets, actualJob.getInputMediaAssets());
assertEquals(message + " OutputMediaAssets", outputMediaAssets, actualJob.getOutputMediaAssets());
}
private JobInfo createJob(String name) throws ServiceException {
String assetId = createFileAsset(name);
URI serviceUri = service.getRestServiceUri();
return service.create(Job
.create(serviceUri)
.setName("My Encoding Job")
.setPriority(3)
.addInputMediaAsset(assetId)
.addTaskCreator(
Task.create().setConfiguration("H.264 256k DSL CBR")
.setMediaProcessorId("nb:mpid:UUID:2f381738-c504-4e4a-a38e-d199e207fcd5")
.setName("My encoding Task").setTaskBody(taskBody)));
}
@Test
public void createJobSuccess() throws Exception {
// Arrange
AssetInfo assetInfo = service.create(Asset.create());
JobInfo expectedJob = new JobInfo();
expectedJob.setName("My Encoding Job");
expectedJob.setPriority(3);
expectedJob.setRunningDuration(0.0);
expectedJob.setState(JobState.Queued);
AccessPolicyInfo accessPolicyInfo = createWritableAccessPolicy("createJobSuccess", 10);
LocatorInfo locator = createLocator(accessPolicyInfo, assetInfo, 5, 10);
WritableBlobContainerContract blobWriter = MediaService.createBlobWriter(locator);
createAndUploadBlob(blobWriter, "blob1.bin", testBlobData);
service.create(AssetFile.create(assetInfo.getId(), "blob1.bin").setIsPrimary(true).setIsEncrypted(false)
.setContentFileSize(new Long(testBlobData.length)));
service.action(AssetFile.createFileInfos(assetInfo.getId()));
URI serviceURI = service.getRestServiceUri();
// Act
JobInfo actualJob = service.create(Job
.create(serviceURI)
.setName("My Encoding Job")
.setPriority(3)
.addInputMediaAsset(assetInfo.getId())
.addTaskCreator(
Task.create().setConfiguration("H.264 256k DSL CBR")
.setMediaProcessorId("nb:mpid:UUID:2f381738-c504-4e4a-a38e-d199e207fcd5")
.setName("My encoding Task").setTaskBody(taskBody)));
// Assert
verifyJobInfoEqual("actualJob", expectedJob, actualJob);
}
@Test
public void getJobSuccess() throws Exception {
// Arrange
JobInfo expectedJob = new JobInfo();
expectedJob.setName("My Encoding Job");
expectedJob.setPriority(3);
expectedJob.setRunningDuration(0.0);
expectedJob.setState(JobState.Queued);
String jobId = createJob("getJobSuccess").getId();
// Act
JobInfo actualJob = service.get(Job.get(jobId));
// Assert
verifyJobInfoEqual("actualJob", expectedJob, actualJob);
}
@Test
public void getJobInvalidIdFailed() throws ServiceException {
expectedException.expect(ServiceException.class);
expectedException.expect(new ServiceExceptionMatcher(400));
service.get(Job.get(invalidId));
}
@Test
public void listJobSuccess() throws ServiceException {
// Arrange
JobInfo jobInfo = createJob("listJobSuccess");
List<JobInfo> jobInfos = new ArrayList<JobInfo>();
jobInfos.add(jobInfo);
ListResult<JobInfo> expectedListJobsResult = new ListResult<JobInfo>(jobInfos);
// Act
ListResult<JobInfo> actualListJobResult = service.list(Job.list());
// Assert
verifyListResultContains("listJobs", expectedListJobsResult, actualListJobResult, new ComponentDelegate() {
@Override
public void verifyEquals(String message, Object expected, Object actual) {
verifyJobInfoEqual(message, (JobInfo) expected, (JobInfo) actual);
}
});
}
@Test
public void canListJobsWithOptions() throws ServiceException {
String[] assetNames = new String[] { testJobPrefix + "assetListOptionsA", testJobPrefix + "assetListOptionsB",
testJobPrefix + "assetListOptionsC", testJobPrefix + "assetListOptionsD" };
List<JobInfo> expectedJobs = new ArrayList<JobInfo>();
for (int i = 0; i < assetNames.length; i++) {
String name = assetNames[i];
JobInfo jobInfo = createJob(name);
expectedJobs.add(jobInfo);
}
MultivaluedMap<String, String> queryParameters = new MultivaluedMapImpl();
queryParameters.add("$top", "2");
ListResult<JobInfo> listJobsResult = service.list(Job.list(queryParameters));
// Assert
assertEquals(2, listJobsResult.size());
}
@Test
public void cancelJobSuccess() throws Exception {
// Arrange
JobInfo jobInfo = createJob("cancelJobSuccess");
// Act
service.action(Job.cancel(jobInfo.getId()));
// Assert
JobInfo canceledJob = service.get(Job.get(jobInfo.getId()));
assertEquals(JobState.Canceling, canceledJob.getState());
}
@Test
public void cancelJobFailedWithInvalidId() throws ServiceException {
// Arrange
expectedException.expect(ServiceException.class);
expectedException.expect(new ServiceExceptionMatcher(400));
// Act
service.action(Job.cancel(invalidId));
// Assert
}
@Test
public void deleteJobSuccess() throws ServiceException {
// Arrange
JobInfo jobInfo = createJob("deleteJobSuccess");
service.action(Job.cancel(jobInfo.getId()));
JobInfo cancellingJobInfo = service.get(Job.get(jobInfo.getId()));
while (cancellingJobInfo.getState() == JobState.Canceling) {
cancellingJobInfo = service.get(Job.get(jobInfo.getId()));
}
// Act
service.delete(Job.delete(jobInfo.getId()));
// Assert
expectedException.expect(ServiceException.class);
service.get(Job.get(jobInfo.getId()));
}
@Test
public void deleteJobIvalidIdFail() throws ServiceException {
// Arrange
expectedException.expect(ServiceException.class);
expectedException.expect(new ServiceExceptionMatcher(400));
// Act
service.delete(Job.delete(invalidId));
// Assert
}
}
|
microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/JobIntegrationTest.java
|
/**
* Copyright 2012 Microsoft Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.windowsazure.services.media;
import static org.junit.Assert.*;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
import java.util.EnumSet;
import java.util.List;
import javax.ws.rs.core.MultivaluedMap;
import org.junit.Test;
import com.microsoft.windowsazure.services.core.ServiceException;
import com.microsoft.windowsazure.services.media.models.AccessPolicy;
import com.microsoft.windowsazure.services.media.models.AccessPolicyInfo;
import com.microsoft.windowsazure.services.media.models.AccessPolicyPermission;
import com.microsoft.windowsazure.services.media.models.Asset;
import com.microsoft.windowsazure.services.media.models.AssetFile;
import com.microsoft.windowsazure.services.media.models.AssetInfo;
import com.microsoft.windowsazure.services.media.models.Job;
import com.microsoft.windowsazure.services.media.models.JobInfo;
import com.microsoft.windowsazure.services.media.models.JobState;
import com.microsoft.windowsazure.services.media.models.ListResult;
import com.microsoft.windowsazure.services.media.models.Locator;
import com.microsoft.windowsazure.services.media.models.LocatorInfo;
import com.microsoft.windowsazure.services.media.models.LocatorType;
import com.microsoft.windowsazure.services.media.models.Task;
import com.sun.jersey.core.util.MultivaluedMapImpl;
public class JobIntegrationTest extends IntegrationTestBase {
private final String testJobPrefix = "testJobPrefix";
private final byte[] testBlobData = new byte[] { 0, 1, 2 };
private final String taskBody = "<?xml version=\"1.0\" encoding=\"utf-8\"?><taskBody>"
+ "<inputAsset>JobInputAsset(0)</inputAsset><outputAsset>JobOutputAsset(0)</outputAsset>" + "</taskBody>";
private void verifyJobInfoEqual(String message, JobInfo expected, JobInfo actual) {
verifyJobProperties(message, expected.getName(), expected.getPriority(), expected.getRunningDuration(),
expected.getState(), expected.getTemplateId(), expected.getInputMediaAssets(),
expected.getOutputMediaAssets(), actual);
}
private AccessPolicyInfo createWritableAccessPolicy(String name, int durationInMinutes) throws ServiceException {
return service.create(AccessPolicy.create(testPolicyPrefix + name, durationInMinutes,
EnumSet.of(AccessPolicyPermission.WRITE)));
}
private void createAndUploadBlob(WritableBlobContainerContract blobWriter, String blobName, byte[] blobData)
throws ServiceException {
InputStream blobContent = new ByteArrayInputStream(blobData);
blobWriter.createBlockBlob(blobName, blobContent);
}
private String createFileAsset(String name) throws ServiceException {
String testBlobName = "test" + name + ".bin";
AssetInfo assetInfo = service.create(Asset.create().setName(name));
AccessPolicyInfo accessPolicyInfo = createWritableAccessPolicy(name, 10);
LocatorInfo locator = createLocator(accessPolicyInfo, assetInfo, 5, 10);
WritableBlobContainerContract blobWriter = MediaService.createBlobWriter(locator);
createAndUploadBlob(blobWriter, testBlobName, testBlobData);
service.create(AssetFile.create(assetInfo.getId(), testBlobName).setIsPrimary(true).setIsEncrypted(false)
.setContentFileSize(new Long(testBlobData.length)));
service.action(AssetFile.createFileInfos(assetInfo.getId()));
return assetInfo.getId();
}
private LocatorInfo createLocator(AccessPolicyInfo accessPolicy, AssetInfo asset, int startDeltaMinutes,
int expirationDeltaMinutes) throws ServiceException {
Date now = new Date();
Date start = new Date(now.getTime() - (startDeltaMinutes * 60 * 1000));
Date expire = new Date(now.getTime() + (expirationDeltaMinutes * 60 * 1000));
return service.create(Locator.create(accessPolicy.getId(), asset.getId(), LocatorType.SAS)
.setStartDateTime(start).setExpirationDateTime(expire));
}
private void verifyJobProperties(String message, String testName, Integer priority, Double runningDuration,
JobState state, String templateId, List<String> inputMediaAssets, List<String> outputMediaAssets,
JobInfo actualJob) {
assertNotNull(message, actualJob);
assertEquals(message + " Name", testName, actualJob.getName());
// comment out due to issue 464
// assertEquals(message + " Priority", priority, actualJob.getPriority());
assertEquals(message + " RunningDuration", runningDuration, actualJob.getRunningDuration());
assertEquals(message + " State", state, actualJob.getState());
// commented out due to issue 463
// assertEquals(message + " TemplateId", templateId, actualJob.getTemplateId());
assertEquals(message + " InputMediaAssets", inputMediaAssets, actualJob.getInputMediaAssets());
assertEquals(message + " OutputMediaAssets", outputMediaAssets, actualJob.getOutputMediaAssets());
}
private JobInfo createJob(String name) throws ServiceException {
String assetId = createFileAsset(name);
URI serviceUri = service.getRestServiceUri();
return service.create(Job
.create(serviceUri)
.setName("My Encoding Job")
.setPriority(3)
.addInputMediaAsset(assetId)
.addTaskCreator(
Task.create().setConfiguration("H.264 256k DSL CBR")
.setMediaProcessorId("nb:mpid:UUID:2f381738-c504-4e4a-a38e-d199e207fcd5")
.setName("My encoding Task").setTaskBody(taskBody)));
}
@Test
public void createJobSuccess() throws Exception {
// Arrange
AssetInfo assetInfo = service.create(Asset.create());
JobInfo expectedJob = new JobInfo();
expectedJob.setName("My Encoding Job");
expectedJob.setPriority(3);
expectedJob.setRunningDuration(0.0);
expectedJob.setState(JobState.Queued);
AccessPolicyInfo accessPolicyInfo = createWritableAccessPolicy("createJobSuccess", 10);
LocatorInfo locator = createLocator(accessPolicyInfo, assetInfo, 5, 10);
WritableBlobContainerContract blobWriter = MediaService.createBlobWriter(locator);
createAndUploadBlob(blobWriter, "blob1.bin", testBlobData);
service.create(AssetFile.create(assetInfo.getId(), "blob1.bin").setIsPrimary(true).setIsEncrypted(false)
.setContentFileSize(new Long(testBlobData.length)));
service.action(AssetFile.createFileInfos(assetInfo.getId()));
URI serviceURI = service.getRestServiceUri();
// Act
JobInfo actualJob = service.create(Job
.create(serviceURI)
.setName("My Encoding Job")
.setPriority(3)
.addInputMediaAsset(assetInfo.getId())
.addTaskCreator(
Task.create().setConfiguration("H.264 256k DSL CBR")
.setMediaProcessorId("nb:mpid:UUID:2f381738-c504-4e4a-a38e-d199e207fcd5")
.setName("My encoding Task").setTaskBody(taskBody)));
// Assert
verifyJobInfoEqual("actualJob", expectedJob, actualJob);
}
@Test
public void getJobSuccess() throws Exception {
// Arrange
JobInfo expectedJob = new JobInfo();
expectedJob.setName("My Encoding Job");
expectedJob.setPriority(3);
expectedJob.setRunningDuration(0.0);
expectedJob.setState(JobState.Queued);
String jobId = createJob("getJobSuccess").getId();
// Act
JobInfo actualJob = service.get(Job.get(jobId));
// Assert
verifyJobInfoEqual("actualJob", expectedJob, actualJob);
}
@Test
public void getJobInvalidIdFailed() throws ServiceException {
expectedException.expect(ServiceException.class);
expectedException.expect(new ServiceExceptionMatcher(400));
service.get(Job.get(invalidId));
}
@Test
public void listJobSuccess() throws ServiceException {
// Arrange
JobInfo jobInfo = createJob("listJobSuccess");
List<JobInfo> jobInfos = new ArrayList<JobInfo>();
jobInfos.add(jobInfo);
ListResult<JobInfo> expectedListJobsResult = new ListResult<JobInfo>(jobInfos);
// Act
ListResult<JobInfo> actualListJobResult = service.list(Job.list());
// Assert
verifyListResultContains("listJobs", expectedListJobsResult, actualListJobResult, new ComponentDelegate() {
@Override
public void verifyEquals(String message, Object expected, Object actual) {
verifyJobInfoEqual(message, (JobInfo) expected, (JobInfo) actual);
}
});
}
@Test
public void canListJobsWithOptions() throws ServiceException {
String[] assetNames = new String[] { testJobPrefix + "assetListOptionsA", testJobPrefix + "assetListOptionsB",
testJobPrefix + "assetListOptionsC", testJobPrefix + "assetListOptionsD" };
List<JobInfo> expectedJobs = new ArrayList<JobInfo>();
for (int i = 0; i < assetNames.length; i++) {
String name = assetNames[i];
JobInfo jobInfo = createJob(name);
expectedJobs.add(jobInfo);
}
MultivaluedMap<String, String> queryParameters = new MultivaluedMapImpl();
queryParameters.add("$top", "2");
ListResult<JobInfo> listJobsResult = service.list(Job.list(queryParameters));
// Assert
assertEquals(2, listJobsResult.size());
}
@Test
public void cancelJobSuccess() throws Exception {
// Arrange
JobInfo jobInfo = createJob("cancelJobSuccess");
// Act
service.action(Job.cancel(jobInfo.getId()));
// Assert
JobInfo canceledJob = service.get(Job.get(jobInfo.getId()));
assertEquals(6, canceledJob.getState());
}
@Test
public void cancelJobFailedWithInvalidId() throws ServiceException {
// Arrange
expectedException.expect(ServiceException.class);
expectedException.expect(new ServiceExceptionMatcher(400));
// Act
service.action(Job.cancel(invalidId));
// Assert
}
@Test
public void deleteJobSuccess() throws ServiceException {
// Arrange
JobInfo jobInfo = createJob("deleteJobSuccess");
service.action(Job.cancel(jobInfo.getId()));
JobInfo cancellingJobInfo = service.get(Job.get(jobInfo.getId()));
while (cancellingJobInfo.getState() == JobState.Canceling) {
cancellingJobInfo = service.get(Job.get(jobInfo.getId()));
}
// Act
service.delete(Job.delete(jobInfo.getId()));
// Assert
expectedException.expect(ServiceException.class);
service.get(Job.get(jobInfo.getId()));
}
@Test
public void deleteJobIvalidIdFail() throws ServiceException {
// Arrange
expectedException.expect(ServiceException.class);
expectedException.expect(new ServiceExceptionMatcher(400));
// Act
service.delete(Job.delete(invalidId));
// Assert
}
}
|
Updated test to check enum value, not integer
|
microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/JobIntegrationTest.java
|
Updated test to check enum value, not integer
|
<ide><path>icrosoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/JobIntegrationTest.java
<ide>
<ide> // Assert
<ide> JobInfo canceledJob = service.get(Job.get(jobInfo.getId()));
<del> assertEquals(6, canceledJob.getState());
<add> assertEquals(JobState.Canceling, canceledJob.getState());
<ide>
<ide> }
<ide>
|
|
Java
|
apache-2.0
|
6bcf062621a6b456926a08dbe11a3e3570bd012e
| 0 |
CMPUT301W15T02/TeamTo
|
/* User class which consists a user's list of claims and personalized tags.
*
* Copyright 2015 Michael Stensby, Christine Shaffer, Kyle Carlstrom, Mitchell Messerschmidt, Raman Dhatt, Adam Rankin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.CMPUT301W15T02.teamtoapp;
import java.util.ArrayList;
public class User {
private String name;
private boolean type; // true for claimant, false for approver?
private ArrayList<Tag> tags;
public User(String string) {
this.name = string;
tags = new ArrayList<Tag>();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean getType() {
return type;
}
public void setType(boolean type) {
this.type = type;
}
public ArrayList<Tag> getTags() {
return tags;
}
public void setTags(ArrayList<Tag> tags) {
this.tags = tags;
}
public void addTag(Tag tag) {
tags.add(tag);
}
public void removeTag(Tag tag) {
tags.remove(tag);
}
}
|
TeamToApp/src/com/CMPUT301W15T02/teamtoapp/User.java
|
/* User class which consists a user's list of claims and personalized tags.
*
* Copyright 2015 Michael Stensby, Christine Shaffer, Kyle Carlstrom, Mitchell Messerschmidt, Raman Dhatt, Adam Rankin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.CMPUT301W15T02.teamtoapp;
import java.util.ArrayList;
public class User {
private String name;
private boolean type; // true for claimant, false for approver?
private ArrayList<Tag> tags;
public User(String string) {
this.name = string;
tags = new ArrayList<Tag>();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean getType() {
return type;
}
public void setType(boolean type) {
this.type = type;
}
public ArrayList<Tag> getTags() {
return tags;
}
public void setTags(ArrayList<Tag> tags) {
this.tags = tags;
}
public void addTag(Tag tag) {
tags.add(tag);
}
public void removeTag(Tag tag) {
tags.remove(tag);
}
public void editTag(Tag prev_tag, Tag new_tag) {
if (tags.contains(prev_tag)) {
int index = tags.indexOf(prev_tag);
// Replace tag with new tag at original index
tags.set(index, new_tag);
}
}
public Claim getClaim(Claim claim) {
// TODO Auto-generated method stub
return null;
}
public void addClaim(Claim claim) {
// TODO Auto-generated method stub
}
public Tag getATag(Object object) {
// TODO Auto-generated method stub
return null;
}
public String getClaimsWithTags(String string) {
// TODO Auto-generated method stub
return null;
}
public void submitClaim(Claim claim) {
// TODO Auto-generated method stub
}
public void returnClaim(Claim claim) {
// TODO Auto-generated method stub
}
public void approveClaim(Claim claim) {
// TODO Auto-generated method stub
}
public Object getClaimPos(int i) {
// TODO Auto-generated method stub
return null;
}
public void saveToCloud() {
// TODO Auto-generated method stub
}
public Object loadFromCloud() {
// TODO Auto-generated method stub
return null;
}
}
|
Updated user object
|
TeamToApp/src/com/CMPUT301W15T02/teamtoapp/User.java
|
Updated user object
|
<ide><path>eamToApp/src/com/CMPUT301W15T02/teamtoapp/User.java
<ide> public void removeTag(Tag tag) {
<ide> tags.remove(tag);
<ide> }
<del>
<del>
<del>
<del> public void editTag(Tag prev_tag, Tag new_tag) {
<del> if (tags.contains(prev_tag)) {
<del> int index = tags.indexOf(prev_tag);
<del> // Replace tag with new tag at original index
<del> tags.set(index, new_tag);
<del> }
<del> }
<del>
<del>
<del>
<del> public Claim getClaim(Claim claim) {
<del> // TODO Auto-generated method stub
<del> return null;
<del> }
<del>
<del>
<del>
<del> public void addClaim(Claim claim) {
<del> // TODO Auto-generated method stub
<del>
<del> }
<del>
<del>
<del>
<del> public Tag getATag(Object object) {
<del> // TODO Auto-generated method stub
<del> return null;
<del> }
<del>
<del>
<del>
<del> public String getClaimsWithTags(String string) {
<del> // TODO Auto-generated method stub
<del> return null;
<del> }
<del>
<del>
<del>
<del> public void submitClaim(Claim claim) {
<del> // TODO Auto-generated method stub
<del>
<del> }
<del>
<del>
<del>
<del> public void returnClaim(Claim claim) {
<del> // TODO Auto-generated method stub
<del>
<del> }
<del>
<del>
<del>
<del> public void approveClaim(Claim claim) {
<del> // TODO Auto-generated method stub
<del>
<del> }
<del>
<del>
<del>
<del> public Object getClaimPos(int i) {
<del> // TODO Auto-generated method stub
<del> return null;
<del> }
<del>
<del>
<del>
<del> public void saveToCloud() {
<del> // TODO Auto-generated method stub
<del>
<del> }
<del>
<del>
<del>
<del> public Object loadFromCloud() {
<del> // TODO Auto-generated method stub
<del> return null;
<del> }
<del>
<del>
<del>
<ide>
<ide>
<ide> }
|
|
Java
|
mit
|
c03c1e3e4be48d0a2e8d7d68ee30db4b14991a4d
| 0 |
zmaster587/AdvancedRocketry,zmaster587/AdvancedRocketry
|
package zmaster587.advancedRocketry.entity;
import io.netty.buffer.ByteBuf;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import javax.annotation.Nullable;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GLAllocation;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityList;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.network.datasync.DataParameter;
import net.minecraft.network.datasync.DataSerializers;
import net.minecraft.network.datasync.EntityDataManager;
import net.minecraft.network.play.server.SPacketRespawn;
import net.minecraft.server.MinecraftServer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.world.Teleporter;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fluids.FluidContainerRegistry;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.IFluidContainerItem;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import zmaster587.advancedRocketry.AdvancedRocketry;
import zmaster587.advancedRocketry.achievements.ARAchivements;
import zmaster587.advancedRocketry.api.AdvancedRocketryItems;
import zmaster587.advancedRocketry.api.Configuration;
import zmaster587.advancedRocketry.api.EntityRocketBase;
import zmaster587.advancedRocketry.api.IInfrastructure;
import zmaster587.advancedRocketry.api.RocketEvent;
import zmaster587.advancedRocketry.api.RocketEvent.RocketLaunchEvent;
import zmaster587.advancedRocketry.api.RocketEvent.RocketPreLaunchEvent;
import zmaster587.advancedRocketry.api.SatelliteRegistry;
import zmaster587.advancedRocketry.api.StatsRocket;
import zmaster587.advancedRocketry.api.fuel.FuelRegistry;
import zmaster587.advancedRocketry.api.fuel.FuelRegistry.FuelType;
import zmaster587.advancedRocketry.api.satellite.SatelliteBase;
import zmaster587.advancedRocketry.api.stations.ISpaceObject;
import zmaster587.advancedRocketry.atmosphere.AtmosphereHandler;
import zmaster587.advancedRocketry.client.SoundRocketEngine;
import zmaster587.advancedRocketry.dimension.DimensionManager;
import zmaster587.advancedRocketry.dimension.DimensionProperties;
import zmaster587.advancedRocketry.event.PlanetEventHandler;
import zmaster587.advancedRocketry.inventory.TextureResources;
import zmaster587.advancedRocketry.inventory.modules.ModulePlanetSelector;
import zmaster587.advancedRocketry.item.ItemAsteroidChip;
import zmaster587.advancedRocketry.item.ItemPackedStructure;
import zmaster587.advancedRocketry.item.ItemPlanetIdentificationChip;
import zmaster587.advancedRocketry.item.ItemStationChip;
import zmaster587.advancedRocketry.mission.MissionOreMining;
import zmaster587.advancedRocketry.network.PacketSatellite;
import zmaster587.advancedRocketry.stations.SpaceObject;
import zmaster587.advancedRocketry.stations.SpaceObjectManager;
import zmaster587.advancedRocketry.tile.TileGuidanceComputer;
import zmaster587.advancedRocketry.tile.hatch.TileSatelliteHatch;
import zmaster587.advancedRocketry.util.AudioRegistry;
import zmaster587.advancedRocketry.util.RocketInventoryHelper;
import zmaster587.advancedRocketry.util.StorageChunk;
import zmaster587.advancedRocketry.util.TransitionEntity;
import zmaster587.advancedRocketry.world.util.TeleporterNoPortal;
import zmaster587.libVulpes.LibVulpes;
import zmaster587.libVulpes.client.util.ProgressBarImage;
import zmaster587.libVulpes.gui.CommonResources;
import zmaster587.libVulpes.interfaces.INetworkEntity;
import zmaster587.libVulpes.inventory.GuiHandler;
import zmaster587.libVulpes.inventory.modules.IButtonInventory;
import zmaster587.libVulpes.inventory.modules.IModularInventory;
import zmaster587.libVulpes.inventory.modules.IProgressBar;
import zmaster587.libVulpes.inventory.modules.ISelectionNotify;
import zmaster587.libVulpes.inventory.modules.ModuleBase;
import zmaster587.libVulpes.inventory.modules.ModuleButton;
import zmaster587.libVulpes.inventory.modules.ModuleImage;
import zmaster587.libVulpes.inventory.modules.ModuleProgress;
import zmaster587.libVulpes.inventory.modules.ModuleSlotButton;
import zmaster587.libVulpes.items.ItemLinker;
import zmaster587.libVulpes.network.PacketEntity;
import zmaster587.libVulpes.network.PacketHandler;
import zmaster587.libVulpes.util.HashedBlockPosition;
import zmaster587.libVulpes.util.IconResource;
import zmaster587.libVulpes.util.Vector3F;
public class EntityRocket extends EntityRocketBase implements INetworkEntity, IModularInventory, IProgressBar, IButtonInventory, ISelectionNotify {
//true if the rocket is on decent
private boolean isInOrbit;
//True if the rocket isn't on the ground
private boolean isInFlight;
//used in the rare case a player goes to a non-existant space station
private int lastDimensionFrom = 0;
public StorageChunk storage;
private String errorStr;
private long lastErrorTime = Long.MIN_VALUE;
private static long ERROR_DISPLAY_TIME = 100;
protected long lastWorldTickTicked;
private SatelliteBase satallite;
protected int destinationDimId;
//Offset for buttons linking to the tileEntityGrid
private int tilebuttonOffset = 3;
private WeakReference<Entity>[] mountedEntities;
protected ModulePlanetSelector container;
boolean acceptedPacket = false;
public static enum PacketType {
RECIEVENBT,
SENDINTERACT,
REQUESTNBT,
FORCEMOUNT,
LAUNCH,
DECONSTRUCT,
OPENGUI,
CHANGEWORLD,
REVERTWORLD,
OPENPLANETSELECTION,
SENDPLANETDATA,
DISCONNECTINFRASTRUCTURE,
CONNECTINFRASTRUCTURE,
ROCKETLANDEVENT,
MENU_CHANGE,
UPDATE_ATM,
UPDATE_ORBIT,
UPDATE_FLIGHT,
DISMOUNTCLIENT
}
private static final DataParameter<Integer> fuelLevel = EntityDataManager.<Integer>createKey(EntityRocket.class, DataSerializers.VARINT);
private static final DataParameter<Boolean> INFLIGHT = EntityDataManager.<Boolean>createKey(EntityRocket.class, DataSerializers.BOOLEAN);
private static final DataParameter<Boolean> INORBIT = EntityDataManager.<Boolean>createKey(EntityRocket.class, DataSerializers.BOOLEAN);
public EntityRocket(World p_i1582_1_) {
super(p_i1582_1_);
isInOrbit = false;
stats = new StatsRocket();
isInFlight = false;
connectedInfrastructure = new LinkedList<IInfrastructure>();
infrastructureCoords = new LinkedList<HashedBlockPosition>();
mountedEntities = new WeakReference[stats.getNumPassengerSeats()];
lastWorldTickTicked = p_i1582_1_.getTotalWorldTime();
}
public EntityRocket(World world, StorageChunk storage, StatsRocket stats, double x, double y, double z) {
this(world);
this.stats = stats;
this.setPosition(x, y, z);
this.storage = storage;
this.storage.setEntity(this);
initFromBounds();
isInFlight = false;
mountedEntities = new WeakReference[stats.getNumPassengerSeats()];
lastWorldTickTicked = world.getTotalWorldTime();
}
@Override
public AxisAlignedBB getEntityBoundingBox() {
if(storage != null) {
return super.getEntityBoundingBox();//.offset(0, -storage.getSizeY(), 0);
}
return new AxisAlignedBB(0,0,0,1,1,1);
}
@Override
public void setEntityBoundingBox(AxisAlignedBB bb) {
//if(storage != null)
// super.setEntityBoundingBox(bb.offset(0, storage.getSizeY(),0));
//else
super.setEntityBoundingBox(bb);
}
@Override
public AxisAlignedBB getCollisionBoundingBox() {
// TODO Auto-generated method stub
return getEntityBoundingBox();
}
/**
* @return the amount of fuel stored in the rocket
*/
public int getFuelAmount() {
int amount = dataManager.get(fuelLevel);
stats.setFuelAmount(FuelType.LIQUID,amount);
return amount;
}
/**
* Adds fuel and updates the datawatcher
* @param amount amount of fuel to add
* @return the amount of fuel added
*/
public int addFuelAmount(int amount) {
int ret = stats.addFuelAmount(FuelType.LIQUID, amount);
setFuelAmount(stats.getFuelAmount(FuelType.LIQUID));
return ret;
}
public void disconnectInfrastructure(IInfrastructure infrastructure){
infrastructure.unlinkRocket();
infrastructureCoords.remove(new HashedBlockPosition(((TileEntity)infrastructure).getPos()));
if(!worldObj.isRemote) {
int pos[] = {((TileEntity)infrastructure).getPos().getX(), ((TileEntity)infrastructure).getPos().getY(), ((TileEntity)infrastructure).getPos().getZ()};
NBTTagCompound nbt = new NBTTagCompound();
nbt.setIntArray("pos", pos);
//PacketHandler.sendToPlayersTrackingEntity(new PacketEntity(this, (byte)PacketType.DISCONNECTINFRASTRUCTURE.ordinal(), nbt), this);
}
}
@Override
public String getTextOverlay() {
if(this.worldObj.getTotalWorldTime() < this.lastErrorTime + ERROR_DISPLAY_TIME)
return errorStr;
//Get destination string
String displayStr = "N/A";
if(storage != null) {
int dimid = storage.getDestinationDimId(this.worldObj.provider.getDimension(), (int)posX, (int)posZ);
if(dimid == Configuration.spaceDimId) {
Vector3F<Float> vec = storage.getDestinationCoordinates(dimid, false);
if(vec != null) {
ISpaceObject obj = SpaceObjectManager.getSpaceManager().getSpaceStationFromBlockCoords(new BlockPos(vec.x,vec.y,vec.z));
if(obj != null) {
displayStr = "Station " + obj.getId();
}
}
}
else if(dimid != -1 && dimid != SpaceObjectManager.WARPDIMID) {
displayStr = DimensionManager.getInstance().getDimensionProperties(dimid).getName();
}
}
if(isInOrbit() && !isInFlight())
return "Press Space to descend!";
else if(!isInFlight())
return "Press Space to take off!\nDest: " + displayStr;
return super.getTextOverlay();
}
private void setError(String error) {
this.errorStr = error;
this.lastErrorTime = this.worldObj.getTotalWorldTime();
}
@Override
public void setPosition(double x, double y,
double z) {
super.setPosition(x, y, z);
if(storage != null) {
float sizeX = storage.getSizeX()/2.0f;
float sizeY = storage.getSizeY();
float sizeZ = storage.getSizeZ()/2.0f;
//setEntityBoundingBox(new AxisAlignedBB(x - sizeX, y - (double)this.getYOffset() + this.height, z - sizeZ, x + sizeX, y + sizeY - (double)this.getYOffset() + this.height, z + sizeZ));
}
}
/**
* Updates the data option
* @param amt sets the amount of fuel in the rocket
*/
public void setFuelAmount(int amt) {
dataManager.set(fuelLevel, amt);
dataManager.setDirty(fuelLevel);
}
/**
* @return gets the fuel capacity of the rocket
*/
public int getFuelCapacity() {
return stats.getFuelCapacity(FuelType.LIQUID);
}
@Override
public void setEntityId(int id){
super.setEntityId(id);
//Ask server for nbt data
if(worldObj.isRemote) {
PacketHandler.sendToServer(new PacketEntity(this, (byte)PacketType.REQUESTNBT.ordinal()));
}
}
@Override
public boolean canBeCollidedWith() {
return true;
}
/**
* If the rocket is in flight, ie the rocket has taken off and has not touched the ground
* @return true if in flight
*/
public boolean isInFlight() {
if(!worldObj.isRemote) {
return isInFlight;
}
return this.dataManager.get(INFLIGHT);
}
/**
* Sets the the status of flight of the rocket and updates the datawatcher
* @param inflight status of flight
*/
public void setInOrbit(boolean inOrbit) {
this.isInOrbit = inOrbit;
this.dataManager.set(INORBIT, inOrbit);
this.dataManager.setDirty(INORBIT);
}
/**
* If the rocket is in flight, ie the rocket has taken off and has not touched the ground
* @return true if in flight
*/
public boolean isInOrbit() {
if(!worldObj.isRemote) {
return isInOrbit;
}
return this.dataManager.get(INORBIT);
}
/**
* Sets the the status of flight of the rocket and updates the datawatcher
* @param inflight status of flight
*/
public void setInFlight(boolean inflight) {
this.isInFlight = inflight;
this.dataManager.set(INFLIGHT, inflight);
this.dataManager.setDirty(INFLIGHT);
}
@Override
protected void entityInit() {
this.dataManager.register(INFLIGHT, false);
this.dataManager.register(fuelLevel, 0);
this.dataManager.register(INORBIT, false);
}
//Set the size and position of the rocket from storage
public void initFromBounds() {
if(storage != null) {
this.setSize(Math.max(storage.getSizeX(), storage.getSizeZ()), storage.getSizeY());
this.setPosition(this.posX, this.posY, this.posZ);
}
}
protected boolean interact(EntityPlayer player) {
//Actual interact code needs to be moved to a packet receive on the server
ItemStack heldItem = player.getHeldItem(EnumHand.MAIN_HAND);
//Handle linkers and right-click with fuel
if(heldItem != null) {
float fuelMult;
FluidStack fluidStack;
if(heldItem.getItem() instanceof ItemLinker) {
if(ItemLinker.isSet(heldItem)) {
TileEntity tile = this.worldObj.getTileEntity(ItemLinker.getMasterCoords(heldItem));
if(tile instanceof IInfrastructure) {
IInfrastructure infrastructure = (IInfrastructure)tile;
if(this.getDistance(ItemLinker.getMasterX(heldItem), this.posY, ItemLinker.getMasterZ(heldItem)) < infrastructure.getMaxLinkDistance() + Math.max(storage.getSizeX(), storage.getSizeZ())) {
if(!connectedInfrastructure.contains(tile)) {
linkInfrastructure(infrastructure);
if(!worldObj.isRemote) {
player.addChatMessage(new TextComponentString("Linked Sucessfully"));
}
ItemLinker.resetPosition(heldItem);
return true;
}
else if(!worldObj.isRemote)
player.addChatMessage(new TextComponentString("Already linked!"));
}
else if(!worldObj.isRemote)
player.addChatMessage(new TextComponentString("The object you are trying to link is too far away"));
}
else if(!worldObj.isRemote)
player.addChatMessage(new TextComponentString("This cannot be linked to a rocket!"));
}
else if(!worldObj.isRemote)
player.addChatMessage(new TextComponentString("Nothing to be linked"));
return false;
}
else if((FluidContainerRegistry.isFilledContainer(heldItem) && (fuelMult = FuelRegistry.instance.getMultiplier(FuelType.LIQUID, (fluidStack = FluidContainerRegistry.getFluidForFilledItem(heldItem)).getFluid()) ) > 0 )
|| ( heldItem.getItem() instanceof IFluidContainerItem && ((IFluidContainerItem) heldItem.getItem()).getFluid(heldItem) != null &&
((IFluidContainerItem) heldItem.getItem()).getFluid(heldItem).amount >= FluidContainerRegistry.BUCKET_VOLUME
&& (fuelMult = FuelRegistry.instance.getMultiplier(FuelType.LIQUID, (fluidStack = ((IFluidContainerItem) heldItem.getItem()).getFluid(heldItem)).getFluid())) > 0 )) {
int amountToAdd = (int) (fuelMult*fluidStack.amount);
this.addFuelAmount(amountToAdd);
//if the player is not in creative then try to use the fluid container
if(!player.capabilities.isCreativeMode) {
if(heldItem.getItem() instanceof IFluidContainerItem) {
((IFluidContainerItem) heldItem.getItem()).drain(heldItem, FluidContainerRegistry.BUCKET_VOLUME, true);
}
else {
ItemStack emptyStack = FluidContainerRegistry.drainFluidContainer(player.getHeldItem(EnumHand.MAIN_HAND));
if(player.inventory.addItemStackToInventory(emptyStack)) {
player.getHeldItem(EnumHand.MAIN_HAND).splitStack(1);
if(player.getHeldItem(EnumHand.MAIN_HAND).stackSize == 0)
player.inventory.setInventorySlotContents(player.inventory.currentItem, null);
}
}
}
return true;
}
}
//If player is holding shift open GUI
if(player.isSneaking()) {
openGui(player);
}
else if(stats.hasSeat()) { //If pilot seat is open mount entity there
if(stats.hasSeat() && this.getPassengers().isEmpty()) {
if(!worldObj.isRemote)
player.startRiding(this);
}
/*else if(stats.getNumPassengerSeats() > 0) { //If a passenger seat exists and one is empty, mount the player to it
for(int i = 0; i < stats.getNumPassengerSeats(); i++) {
if(this.mountedEntities[i] == null || this.mountedEntities[i].get() == null) {
player.ridingEntity = this;
this.mountedEntities[i] = new WeakReference<Entity>(player);
break;
}
}
}*/
}
return true;
}
public void openGui(EntityPlayer player) {
player.openGui(LibVulpes.instance, GuiHandler.guiId.MODULAR.ordinal(), player.worldObj, this.getEntityId(), -1,0);
//Only handle the bypass on the server
if(!worldObj.isRemote)
RocketInventoryHelper.addPlayerToInventoryBypass(player);
}
@Override
public boolean processInitialInteract(EntityPlayer player, @Nullable ItemStack stack, EnumHand hand){
if(worldObj.isRemote) {
//Due to forge's rigid handling of entities (NetHanlderPlayServer:866) needs to be handled differently for large rockets
PacketHandler.sendToServer(new PacketEntity(this, (byte)PacketType.SENDINTERACT.ordinal()));
return interact(player);
}
return true;
}
public boolean isBurningFuel() {
return (getFuelAmount() > 0 || !Configuration.rocketRequireFuel) && ((!this.getPassengers().isEmpty() && getPassengerMovingForward() > 0) || !isInOrbit());
}
public float getPassengerMovingForward() {
for(Entity entity : this.getPassengers()) {
if(entity instanceof EntityPlayer) {
return ((EntityPlayer) entity).moveForward;
}
}
return 0f;
}
private boolean hasHumanPassenger() {
for(Entity entity : this.getPassengers()) {
if(entity instanceof EntityPlayer) {
return true;
}
}
return false;
}
public boolean isDescentPhase() {
return Configuration.automaticRetroRockets && isInOrbit() && this.posY < 300 && (this.motionY < -0.4f || worldObj.isRemote);
}
public boolean areEnginesRunning() {
return (this.motionY > 0 || isDescentPhase() || (getPassengerMovingForward() > 0));
}
@Override
public void onUpdate() {
super.onUpdate();
long deltaTime = worldObj.getTotalWorldTime() - lastWorldTickTicked;
lastWorldTickTicked = worldObj.getTotalWorldTime();
if(this.ticksExisted == 20) {
//problems with loading on other world then where the infrastructure was set?
ListIterator<HashedBlockPosition> itr = infrastructureCoords.listIterator();
while(itr.hasNext()) {
HashedBlockPosition temp = itr.next();
TileEntity tile = this.worldObj.getTileEntity(new BlockPos(temp.x, temp.y, temp.z));
if(tile instanceof IInfrastructure) {
this.linkInfrastructure((IInfrastructure)tile);
itr.remove();
}
}
if(worldObj.isRemote)
LibVulpes.proxy.playSound(new SoundRocketEngine( AudioRegistry.combustionRocket, SoundCategory.NEUTRAL,this));
}
//Hackish crap to make clients mount entities immediately after server transfer and fire events
//Known race condition... screw me...
if(!worldObj.isRemote && (this.isInFlight() || this.isInOrbit()) && this.ticksExisted == 20) {
//Deorbiting
MinecraftForge.EVENT_BUS.post(new RocketEvent.RocketDeOrbitingEvent(this));
PacketHandler.sendToNearby(new PacketEntity(this, (byte)PacketType.ROCKETLANDEVENT.ordinal()), worldObj.provider.getDimension(), (int)posX, (int)posY, (int)posZ, 64);
for(Entity riddenByEntity : getPassengers()) {
if(riddenByEntity instanceof EntityPlayer) {
EntityPlayer player = (EntityPlayer)riddenByEntity;
if(player instanceof EntityPlayer)
PacketHandler.sendToPlayer(new PacketEntity((INetworkEntity)this,(byte)PacketType.FORCEMOUNT.ordinal()), player);
}
}
}
if(isInFlight()) {
boolean burningFuel = isBurningFuel();
boolean descentPhase = isDescentPhase();
if(burningFuel || descentPhase) {
//Burn the rocket fuel
if(!worldObj.isRemote && !descentPhase)
setFuelAmount(getFuelAmount() - stats.getFuelRate(FuelType.LIQUID));
//Spawn in the particle effects for the engines
int engineNum = 0;
if(worldObj.isRemote && Minecraft.getMinecraft().gameSettings.particleSetting < 2 && areEnginesRunning()) {
for(Vector3F<Float> vec : stats.getEngineLocations()) {
AtmosphereHandler handler;
if(Minecraft.getMinecraft().gameSettings.particleSetting < 1 && worldObj.getTotalWorldTime() % 10 == 0 && (engineNum < 8 || ((worldObj.getTotalWorldTime()/10) % Math.max((stats.getEngineLocations().size()/8),1)) == (engineNum/8)) && ( (handler = AtmosphereHandler.getOxygenHandler(worldObj.provider.getDimension())) == null || (handler.getAtmosphereType(this) != null && handler.getAtmosphereType(this).allowsCombustion())) )
AdvancedRocketry.proxy.spawnParticle("rocketSmoke", worldObj, this.posX + vec.x, this.posY + vec.y - 0.75, this.posZ +vec.z,0,0,0);
for(int i = 0; i < 4; i++) {
AdvancedRocketry.proxy.spawnParticle("rocketFlame", worldObj, this.posX + vec.x, this.posY + vec.y - 0.75, this.posZ +vec.z,(this.rand.nextFloat() - 0.5f)/8f,-.75 ,(this.rand.nextFloat() - 0.5f)/8f);
}
}
}
}
if(!this.getPassengers().isEmpty()) {
for(Entity entity : this.getPassengers()) {
entity.fallDistance = 0;
this.fallDistance = 0;
}
//if the player holds the forward key then decelerate
if(isInOrbit() && (burningFuel || descentPhase)) {
float vel = descentPhase ? 1f : getPassengerMovingForward();
this.motionY -= this.motionY*vel/50f;
}
this.velocityChanged = true;
}
else if(isInOrbit() && descentPhase) { //For unmanned rockets
this.motionY -= this.motionY/50f;
this.velocityChanged = true;
}
if(!worldObj.isRemote) {
//If out of fuel or descending then accelerate downwards
if(isInOrbit() || !burningFuel) {
this.motionY = Math.min(this.motionY - 0.001, 1);
} else
//this.motionY = Math.min(this.motionY + 0.001, 1);
this.motionY += stats.getAcceleration() * deltaTime;
double lastPosY = this.posY;
double prevMotion = this.motionY;
this.moveEntity(0, prevMotion*deltaTime, 0);
//Check to see if it's landed
if((isInOrbit() || !burningFuel) && isInFlight() && lastPosY + prevMotion != this.posY && this.posY < 256) {
MinecraftForge.EVENT_BUS.post(new RocketEvent.RocketLandedEvent(this));
//PacketHandler.sendToPlayersTrackingEntity(new PacketEntity(this, (byte)PacketType.ROCKETLANDEVENT.ordinal()), this);
this.setInFlight(false);
this.setInOrbit(false);
}
if(!isInOrbit() && (this.posY > Configuration.orbit)) {
onOrbitReached();
}
//If the rocket falls out of the world while in orbit either fall back to earth or die
if(this.posY < 0) {
int dimId = worldObj.provider.getDimension();
if(dimId == Configuration.spaceDimId) {
ISpaceObject obj = SpaceObjectManager.getSpaceManager().getSpaceStationFromBlockCoords(getPosition());
if(obj != null) {
int targetDimID = obj.getOrbitingPlanetId();
Vector3F<Float> pos = storage.getDestinationCoordinates(targetDimID, true);
if(pos != null) {
setInOrbit(true);
setInFlight(false);
this.changeDimension(targetDimID, pos.x, Configuration.orbit, pos.z);
}
else
this.setDead();
}
else {
Vector3F<Float> pos = storage.getDestinationCoordinates(0, true);
if(pos != null) {
setInOrbit(true);
setInFlight(false);
this.changeDimension(lastDimensionFrom, pos.x, Configuration.orbit, pos.z);
}
else
this.setDead();
}
}
else
this.setDead();
}
}
else {
this.moveEntity(0, this.motionY, 0);
}
}
}
/**
* @return a list of satellites stores in this rocket
*/
public List<SatelliteBase> getSatellites() {
List<SatelliteBase> satellites = new ArrayList<SatelliteBase>();
for(TileSatelliteHatch tile : storage.getSatelliteHatches()) {
SatelliteBase satellite = tile.getSatellite();
if(satellite != null)
satellites.add(satellite);
}
return satellites;
}
/**
* Called when the rocket reaches orbit
*/
public void onOrbitReached() {
super.onOrbitReached();
//TODO: support multiple riders and rider/satellite combo
if(!stats.hasSeat()) {
TileGuidanceComputer computer = storage.getGuidanceComputer();
if(computer != null && computer.getStackInSlot(0) != null &&
computer.getStackInSlot(0).getItem() instanceof ItemAsteroidChip) {
//make it 30 minutes with one drill
float drillingPower = stats.getDrillingPower();
MissionOreMining miningMission = new MissionOreMining((long)(drillingPower == 0f ? 36000 : 360/stats.getDrillingPower()), this, connectedInfrastructure);
DimensionProperties properties = DimensionManager.getInstance().getDimensionProperties(worldObj.provider.getDimension());
properties.addSatallite(miningMission, worldObj);
if(!worldObj.isRemote)
PacketHandler.sendToAll(new PacketSatellite(miningMission));
for(IInfrastructure i : connectedInfrastructure) {
i.linkMission(miningMission);
}
this.setDead();
//TODO: Move tracking stations over to the mission handler
}
else {
unpackSatellites();
}
destinationDimId = storage.getDestinationDimId(this.worldObj.provider.getDimension(), (int)this.posX, (int)this.posZ);
if(DimensionManager.getInstance().canTravelTo(destinationDimId)) {
Vector3F<Float> pos = storage.getDestinationCoordinates(destinationDimId, true);
storage.setDestinationCoordinates(new Vector3F<Float>((float)this.posX, (float)this.posY, (float)this.posZ), this.worldObj.provider.getDimension());
if(pos != null) {
this.setInOrbit(true);
this.motionY = -this.motionY;
this.changeDimension(destinationDimId, pos.x, Configuration.orbit, pos.z);
return;
}
}
else
this.setDead();
//TODO: satellite event?
}
else {
unpackSatellites();
//TODO: maybe add orbit dimension
this.motionY = -this.motionY;
setInOrbit(true);
//If going to a station or something make sure to set coords accordingly
//If in space land on the planet, if on the planet go to space
if(destinationDimId == Configuration.spaceDimId || this.worldObj.provider.getDimension() == Configuration.spaceDimId) {
Vector3F<Float> pos = storage.getDestinationCoordinates(destinationDimId, true);
storage.setDestinationCoordinates(new Vector3F<Float>((float)this.posX, (float)this.posY, (float)this.posZ), this.worldObj.provider.getDimension());
if(pos != null) {
//Make player confirm deorbit if a player is riding the rocket
if(hasHumanPassenger()) {
setInFlight(false);
pos.y = (float) Configuration.orbit;
}
this.changeDimension(destinationDimId, pos.x, pos.y, pos.z);
return;
}
}
//Make player confirm deorbit if a player is riding the rocket
if(hasHumanPassenger()) {
setInFlight(false);
if(DimensionManager.getInstance().getDimensionProperties(destinationDimId).getName().equals("Luna")) {
for(Entity player : this.getPassengers()) {
if(player instanceof EntityPlayer) {
((EntityPlayer)player).addStat(ARAchivements.moonLanding);
if(!DimensionManager.hasReachedMoon)
((EntityPlayer)player).addStat(ARAchivements.oneSmallStep);
}
}
DimensionManager.hasReachedMoon = true;
}
}
else
setPosition(posX, Configuration.orbit, posZ);
if(destinationDimId != this.worldObj.provider.getDimension())
this.changeDimension(this.worldObj.provider.getDimension() == destinationDimId ? 0 : destinationDimId);
}
}
private void unpackSatellites() {
List<TileSatelliteHatch> satelliteHatches = storage.getSatelliteHatches();
for(TileSatelliteHatch tile : satelliteHatches) {
SatelliteBase satellite = tile.getSatellite();
if(satellite == null) {
ItemStack stack = tile.getStackInSlot(0);
if(stack != null && stack.getItem() == AdvancedRocketryItems.itemSpaceStation) {
StorageChunk storage = ((ItemPackedStructure)stack.getItem()).getStructure(stack);
ISpaceObject object = SpaceObjectManager.getSpaceManager().getSpaceStation((int)ItemStationChip.getUUID(stack));
SpaceObjectManager.getSpaceManager().moveStationToBody(object, this.worldObj.provider.getDimension());
//Vector3F<Integer> spawn = object.getSpawnLocation();
object.onModuleUnpack(storage);
tile.setInventorySlotContents(0, null);
}
}
else {
satellite.setDimensionId(worldObj);
DimensionProperties properties = DimensionManager.getInstance().getDimensionProperties(this.worldObj.provider.getDimension());
properties.addSatallite(satellite, this.worldObj);
}
}
}
@Override
/**
* Called immediately before launch
*/
public void prepareLaunch() {
RocketPreLaunchEvent event = new RocketEvent.RocketPreLaunchEvent(this);
MinecraftForge.EVENT_BUS.post(event);
if(!event.isCanceled()) {
if(worldObj.isRemote)
PacketHandler.sendToServer(new PacketEntity(this, (byte)EntityRocket.PacketType.LAUNCH.ordinal()));
launch();
}
}
@Override
public void launch() {
if(isInFlight())
return;
if(isInOrbit()) {
setInFlight(true);
return;
}
//Get destination dimid and lock the computer
//TODO: lock the computer
destinationDimId = storage.getDestinationDimId(worldObj.provider.getDimension(), (int)this.posX, (int)this.posZ);
//TODO: make sure this doesn't break asteriod mining
if(!(DimensionManager.getInstance().canTravelTo(destinationDimId) || (destinationDimId == -1 && storage.getSatelliteHatches().size() != 0))) {
setError(LibVulpes.proxy.getLocalizedString("error.rocket.cannotGetThere"));
return;
}
int finalDest = destinationDimId;
if(destinationDimId == Configuration.spaceDimId) {
ISpaceObject obj = null;
Vector3F<Float> vec = storage.getDestinationCoordinates(destinationDimId,false);
if(vec != null)
obj = SpaceObjectManager.getSpaceManager().getSpaceStationFromBlockCoords(new BlockPos(vec.x, vec.y, vec.z));
if( obj != null)
finalDest = obj.getOrbitingPlanetId();
else {
setError(LibVulpes.proxy.getLocalizedString("error.rocket.destinationNotExist"));
return;
}
}
int thisDimId = this.worldObj.provider.getDimension();
if(this.worldObj.provider.getDimension() == Configuration.spaceDimId) {
ISpaceObject object = SpaceObjectManager.getSpaceManager().getSpaceStationFromBlockCoords(this.getPosition());
if(object != null)
thisDimId = object.getProperties().getParentProperties().getId();
}
if(finalDest != -1 && !DimensionManager.getInstance().areDimensionsInSamePlanetMoonSystem(finalDest, thisDimId)) {
setError(LibVulpes.proxy.getLocalizedString("error.rocket.notSameSystem"));
return;
}
//TODO: Clean this logic a bit?
if(!stats.hasSeat() || ((DimensionManager.getInstance().isDimensionCreated(destinationDimId)) || destinationDimId == Configuration.spaceDimId || destinationDimId == 0) ) { //Abort if destination is invalid
setInFlight(true);
Iterator<IInfrastructure> connectedTiles = connectedInfrastructure.iterator();
MinecraftForge.EVENT_BUS.post(new RocketLaunchEvent(this));
//Disconnect things linked to the rocket on liftoff
while(connectedTiles.hasNext()) {
IInfrastructure i = connectedTiles.next();
if(i.disconnectOnLiftOff()) {
disconnectInfrastructure(i);
connectedTiles.remove();
}
}
}
}
/**
* Called when the rocket is to be deconstructed
*/
@Override
public void deconstructRocket() {
super.deconstructRocket();
for(IInfrastructure infrastructure : connectedInfrastructure) {
infrastructure.unlinkRocket();
}
//paste the rocket into the world as blocks
storage.pasteInWorld(this.worldObj, (int)(this.posX - storage.getSizeX()/2f), (int)this.posY, (int)(this.posZ - storage.getSizeZ()/2f));
this.setDead();
}
@Override
public void setDead() {
super.setDead();
if(storage != null && storage.world.displayListIndex != -1)
GLAllocation.deleteDisplayLists(storage.world.displayListIndex);
//unlink any connected tiles
Iterator<IInfrastructure> connectedTiles = connectedInfrastructure.iterator();
while(connectedTiles.hasNext()) {
connectedTiles.next().unlinkRocket();
connectedTiles.remove();
}
}
public void setOverriddenCoords(int dimId, float x, float y, float z) {
TileGuidanceComputer tile = storage.getGuidanceComputer();
if(tile != null) {
tile.setFallbackDestination(dimId, new Vector3F<Float>(x, y, z));
}
}
@Override
public Entity changeDimension(int newDimId) {
return changeDimension(newDimId, this.posX, (double)Configuration.orbit, this.posZ);
}
@Nullable
public Entity changeDimension(int dimensionIn, double posX, double y, double posZ)
{
if (!this.worldObj.isRemote && !this.isDead)
{
if(!DimensionManager.getInstance().canTravelTo(dimensionIn)) {
AdvancedRocketry.logger.warning("Rocket trying to travel from Dim" + this.worldObj.provider.getDimension() + " to Dim " + dimensionIn + ". target not accessible by rocket from launch dim");
return null;
}
lastDimensionFrom = this.worldObj.provider.getDimension();
List<Entity> passengers = getPassengers();
if (!net.minecraftforge.common.ForgeHooks.onTravelToDimension(this, dimensionIn)) return null;
this.worldObj.theProfiler.startSection("changeDimension");
MinecraftServer minecraftserver = this.getServer();
int i = this.dimension;
WorldServer worldserver = minecraftserver.worldServerForDimension(i);
WorldServer worldserver1 = minecraftserver.worldServerForDimension(dimensionIn);
this.dimension = dimensionIn;
if (i == 1 && dimensionIn == 1)
{
worldserver1 = minecraftserver.worldServerForDimension(0);
this.dimension = 0;
}
this.worldObj.removeEntity(this);
this.isDead = false;
this.worldObj.theProfiler.startSection("reposition");
BlockPos blockpos;
double d0 = this.posX;
double d1 = this.posZ;
double d2 = 8.0D;
d0 = MathHelper.clamp_double(d0 * 8.0D, worldserver1.getWorldBorder().minX() + 16.0D, worldserver1.getWorldBorder().maxX() - 16.0D);
d1 = MathHelper.clamp_double(d1 * 8.0D, worldserver1.getWorldBorder().minZ() + 16.0D, worldserver1.getWorldBorder().maxZ() - 16.0D);
d0 = (double)MathHelper.clamp_int((int)d0, -29999872, 29999872);
d1 = (double)MathHelper.clamp_int((int)d1, -29999872, 29999872);
float f = this.rotationYaw;
this.setLocationAndAngles(d0, this.posY, d1, 90.0F, 0.0F);
Teleporter teleporter = new TeleporterNoPortal(worldserver1);
teleporter.placeInExistingPortal(this, f);
worldserver.updateEntityWithOptionalForce(this, false);
this.worldObj.theProfiler.endStartSection("reloading");
Entity entity = EntityList.createEntityByName(EntityList.getEntityString(this), worldserver1);
if (entity != null)
{
this.moveToBlockPosAndAngles(new BlockPos(posX, y, posZ), entity.rotationYaw, entity.rotationPitch);
((EntityRocket)entity).copyDataFromOld(this);
entity.forceSpawn = true;
worldserver1.spawnEntityInWorld(entity);
worldserver1.updateEntityWithOptionalForce(entity, true);
int timeOffset = 1;
for(Entity e : passengers) {
//Fix that darn random crash?
worldserver.resetUpdateEntityTick();
worldserver1.resetUpdateEntityTick();
//Transfer the player if applicable
//Need to handle our own removal to avoid race condition where player is mounted on client on the old entity but is already mounted to the new one on server
//PacketHandler.sendToPlayer(new PacketEntity(this, (byte)PacketType.DISMOUNTCLIENT.ordinal()), (EntityPlayer) e);
PlanetEventHandler.addDelayedTransition(worldserver.getTotalWorldTime(), new TransitionEntity(worldserver.getTotalWorldTime(), e, dimensionIn, new BlockPos(posX + 16, y, posZ), entity));
//minecraftserver.getPlayerList().transferPlayerToDimension((EntityPlayerMP)e, dimensionIn, teleporter);
//e.setLocationAndAngles(posX, Configuration.orbit, posZ, this.rotationYaw, this.rotationPitch);
//e.startRiding(entity);
//e.playerNetServerHandler.sendPacket(new SPacketRespawn(e.dimension, e.worldObj.getDifficulty(), worldserver1.getWorldInfo().getTerrainType(), ((EntityPlayerMP)e).interactionManager.getGameType()));
//((WorldServer)startWorld).getPlayerManager().removePlayer(player);
}
}
this.isDead = true;
this.worldObj.theProfiler.endSection();
worldserver.resetUpdateEntityTick();
worldserver1.resetUpdateEntityTick();
this.worldObj.theProfiler.endSection();
return entity;
}
else
{
return null;
}
}
/**
* Prepares this entity in new dimension by copying NBT data from entity in old dimension
*/
public void copyDataFromOld(Entity entityIn)
{
NBTTagCompound nbttagcompound = entityIn.writeToNBT(new NBTTagCompound());
nbttagcompound.removeTag("Dimension");
nbttagcompound.removeTag("Passengers");
this.readFromNBT(nbttagcompound);
this.timeUntilPortal = entityIn.timeUntilPortal;
}
protected void readNetworkableNBT(NBTTagCompound nbt) {
//Normal function checks for the existance of the data anyway
readEntityFromNBT(nbt);
}
@Override
protected void readEntityFromNBT(NBTTagCompound nbt) {
setInOrbit(isInOrbit = nbt.getBoolean("orbit"));
stats.readFromNBT(nbt);
mountedEntities = new WeakReference[stats.getNumPassengerSeats()];
setFuelAmount(stats.getFuelAmount(FuelType.LIQUID));
setInFlight(isInFlight = nbt.getBoolean("flight"));
readMissionPersistantNBT(nbt);
if(nbt.hasKey("data"))
{
if(storage == null)
storage = new StorageChunk();
storage.readFromNBT(nbt.getCompoundTag("data"));
storage.setEntity(this);
this.setSize(Math.max(storage.getSizeX(), storage.getSizeZ()), storage.getSizeY());
}
NBTTagList tagList = nbt.getTagList("infrastructure", 10);
for (int i = 0; i < tagList.tagCount(); i++) {
int coords[] = tagList.getCompoundTagAt(i).getIntArray("loc");
//If called on server causes recursive loop, use hackish workaround with tempcoords and onChunkLoad if on server
if(worldObj.isRemote) {
TileEntity tile = this.worldObj.getTileEntity(new BlockPos(coords[0], coords[1], coords[2]));
if(tile instanceof IInfrastructure)
this.linkInfrastructure((IInfrastructure)tile);
}
else
infrastructureCoords.add(new HashedBlockPosition(coords[0], coords[1], coords[2]));
}
destinationDimId = nbt.getInteger("destinationDimId");
lastDimensionFrom = nbt.getInteger("lastDimensionFrom");
//Satallite
if(nbt.hasKey("satallite")) {
NBTTagCompound satalliteNbt = nbt.getCompoundTag("satallite");
satallite = SatelliteRegistry.createFromNBT(satalliteNbt);
}
}
protected void writeNetworkableNBT(NBTTagCompound nbt) {
writeMissionPersistantNBT(nbt);
nbt.setBoolean("orbit", isInOrbit());
nbt.setBoolean("flight", isInFlight());
stats.writeToNBT(nbt);
NBTTagList itemList = new NBTTagList();
for(int i = 0; i < connectedInfrastructure.size(); i++)
{
IInfrastructure inf = connectedInfrastructure.get(i);
if(inf instanceof TileEntity) {
TileEntity ent = (TileEntity)inf;
NBTTagCompound tag = new NBTTagCompound();
tag.setIntArray("loc", new int[] {ent.getPos().getX(), ent.getPos().getY(), ent.getPos().getZ()});
itemList.appendTag(tag);
}
}
nbt.setTag("infrastructure", itemList);
nbt.setInteger("destinationDimId", destinationDimId);
//Satallite
if(satallite != null) {
NBTTagCompound satalliteNbt = new NBTTagCompound();
satallite.writeToNBT(satalliteNbt);
satalliteNbt.setString("DataType",SatelliteRegistry.getKey(satallite.getClass()));
nbt.setTag("satallite", satalliteNbt);
}
}
public void writeMissionPersistantNBT(NBTTagCompound nbt) {
}
public void readMissionPersistantNBT(NBTTagCompound nbt) {
}
@Override
protected void writeEntityToNBT(NBTTagCompound nbt) {
writeNetworkableNBT(nbt);
if(storage != null) {
NBTTagCompound blocks = new NBTTagCompound();
storage.writeToNBT(blocks);
nbt.setTag("data", blocks);
}
//TODO handle non tile Infrastructure
nbt.setInteger("lastDimensionFrom", lastDimensionFrom);
}
@Override
public void readDataFromNetwork(ByteBuf in, byte packetId,
NBTTagCompound nbt) {
if(packetId == PacketType.RECIEVENBT.ordinal()) {
storage = new StorageChunk();
storage.setEntity(this);
storage.readFromNetwork(in);
}
else if(packetId == PacketType.SENDPLANETDATA.ordinal()) {
nbt.setInteger("selection", in.readInt());
}
}
@Override
public void writeDataToNetwork(ByteBuf out, byte id) {
if(id == PacketType.RECIEVENBT.ordinal()) {
storage.writeToNetwork(out);
}
else if(id == PacketType.SENDPLANETDATA.ordinal()) {
if(worldObj.isRemote)
out.writeInt(container.getSelectedSystem());
else {
if(storage.getGuidanceComputer() != null) {
ItemStack stack = storage.getGuidanceComputer().getStackInSlot(0);
if(stack != null && stack.getItem() == AdvancedRocketryItems.itemPlanetIdChip) {
out.writeInt(((ItemPlanetIdentificationChip)AdvancedRocketryItems.itemPlanetIdChip).getDimensionId(stack));
}
}
}
}
}
@Override
public void useNetworkData(EntityPlayer player, Side side, byte id,
NBTTagCompound nbt) {
if(id == PacketType.RECIEVENBT.ordinal()) {
this.readEntityFromNBT(nbt);
initFromBounds();
}
else if(id == PacketType.DECONSTRUCT.ordinal()) {
deconstructRocket();
}
else if(id == PacketType.SENDINTERACT.ordinal()) {
interact(player);
}
else if(id == PacketType.OPENGUI.ordinal()) { //Used in key handler
if(player.getRidingEntity() == this) //Prevent cheating
openGui(player);
}
else if(id == PacketType.REQUESTNBT.ordinal()) {
if(storage != null) {
NBTTagCompound nbtdata = new NBTTagCompound();
this.writeNetworkableNBT(nbtdata);
PacketHandler.sendToPlayer(new PacketEntity((INetworkEntity)this, (byte)PacketType.RECIEVENBT.ordinal(), nbtdata), player);
}
}
else if(id == PacketType.FORCEMOUNT.ordinal()) { //Used for pesky dimension transfers
//When dimensions are transferred make sure to remount the player on the client
if(!acceptedPacket) {
acceptedPacket = true;
player.setPositionAndRotation(this.posX, this.posY, this.posZ, player.rotationYaw, player.rotationPitch);
player.startRiding(this);
MinecraftForge.EVENT_BUS.post(new RocketEvent.RocketDeOrbitingEvent(this));
}
}
else if(id == PacketType.LAUNCH.ordinal()) {
if(this.getPassengers().contains(player))
this.prepareLaunch();
}
else if(id == PacketType.CHANGEWORLD.ordinal()) {
AdvancedRocketry.proxy.changeClientPlayerWorld(storage.world);
}
else if(id == PacketType.REVERTWORLD.ordinal()) {
AdvancedRocketry.proxy.changeClientPlayerWorld(this.worldObj);
}
else if(id == PacketType.OPENPLANETSELECTION.ordinal()) {
player.openGui(LibVulpes.instance, GuiHandler.guiId.MODULARFULLSCREEN.ordinal(), player.worldObj, this.getEntityId(), -1,0);
}
else if(id == PacketType.SENDPLANETDATA.ordinal()) {
ItemStack stack = storage.getGuidanceComputer().getStackInSlot(0);
if(stack != null && stack.getItem() == AdvancedRocketryItems.itemPlanetIdChip) {
((ItemPlanetIdentificationChip)AdvancedRocketryItems.itemPlanetIdChip).setDimensionId(stack, nbt.getInteger("selection"));
//Send data back to sync destination dims
if(!worldObj.isRemote) {
PacketHandler.sendToPlayersTrackingEntity(new PacketEntity(this, (byte)PacketType.SENDPLANETDATA.ordinal()), this);
}
}
}
else if(id == PacketType.DISCONNECTINFRASTRUCTURE.ordinal()) {
int pos[] = nbt.getIntArray("pos");
connectedInfrastructure.remove(new HashedBlockPosition(pos[0], pos[1], pos[2]));
TileEntity tile = worldObj.getTileEntity(new BlockPos(pos[0], pos[1], pos[2]));
if(tile instanceof IInfrastructure) {
((IInfrastructure)tile).unlinkRocket();
connectedInfrastructure.remove(tile);
}
}
else if(id == PacketType.ROCKETLANDEVENT.ordinal() && worldObj.isRemote) {
MinecraftForge.EVENT_BUS.post(new RocketEvent.RocketLandedEvent(this));
}
else if(id == PacketType.DISMOUNTCLIENT.ordinal() && worldObj.isRemote) {
player.dismountRidingEntity();
//this.removePassenger(player);
}
else if(id > 100) {
TileEntity tile = storage.getGUItiles().get(id - 100 - tilebuttonOffset);
//Welcome to super hack time with packets
//Due to the fact the client uses the player's current world to open the gui, we have to move the client between worlds for a bit
PacketHandler.sendToPlayer(new PacketEntity(this, (byte)PacketType.CHANGEWORLD.ordinal()), player);
storage.getBlockState(tile.getPos()).getBlock().onBlockActivated(storage.world, tile.getPos(), storage.getBlockState(tile.getPos()), player, EnumHand.MAIN_HAND, null, EnumFacing.DOWN, 0, 0, 0);
PacketHandler.sendToPlayer(new PacketEntity(this, (byte)PacketType.REVERTWORLD.ordinal()), player);
}
}
@Override
public void updatePassenger(Entity entity)
{
if (entity != null )
{
//Bind player to the seat
if(this.storage != null) {
//Conditional b/c for some reason client/server positions do not match
float xOffset = this.storage.getSizeX() % 2 == 0 ? 0.5f : 0f;
float zOffset = this.storage.getSizeZ() % 2 == 0 ? 0.5f : 0f;
entity.setPosition(this.posX + stats.getSeatX() + xOffset, this.posY + stats.getSeatY() - 0.5f, this.posZ + stats.getSeatZ() + zOffset );
}
else
entity.setPosition(this.posX , this.posY , this.posZ );
}
for(int i = 0; i < this.stats.getNumPassengerSeats(); i++) {
HashedBlockPosition pos = this.stats.getPassengerSeat(i);
if(mountedEntities[i] != null && mountedEntities[i].get() != null) {
mountedEntities[i].get().setPosition(this.posX + pos.x, this.posY + pos.y, this.posZ + pos.z);
System.out.println("Additional: " + mountedEntities[i].get());
}
}
}
@Override
public List<ModuleBase> getModules(int ID, EntityPlayer player) {
List<ModuleBase> modules;
//If the rocket is flight don't load the interface
modules = new LinkedList<ModuleBase>();
if(ID == GuiHandler.guiId.MODULAR.ordinal()) {
//Backgrounds
if(worldObj.isRemote) {
modules.add(new ModuleImage(173, 0, new IconResource(128, 0, 48, 86, CommonResources.genericBackground)));
modules.add(new ModuleImage(173, 86, new IconResource(98, 0, 78, 83, CommonResources.genericBackground)));
modules.add(new ModuleImage(173, 168, new IconResource(98, 168, 78, 3, CommonResources.genericBackground)));
}
//Fuel
modules.add(new ModuleProgress(192, 7, 0, new ProgressBarImage(2, 173, 12, 71, 17, 6, 3, 69, 1, 1, EnumFacing.UP, TextureResources.rocketHud), this));
//TODO DEBUG tiles!
List<TileEntity> tiles = storage.getGUItiles();
for(int i = 0; i < tiles.size(); i++) {
TileEntity tile = tiles.get(i);
IBlockState state = storage.getBlockState(tile.getPos());
try {
modules.add(new ModuleSlotButton(8 + 18* (i % 9), 17 + 18*(i/9), i + tilebuttonOffset, this, new ItemStack(state.getBlock(), 1, state.getBlock().getMetaFromState(state)), worldObj));
} catch (NullPointerException e) {
}
}
//Add buttons
modules.add(new ModuleButton(180, 140, 0, "Dissassemble", this, zmaster587.libVulpes.inventory.TextureResources.buttonBuild, 64, 20));
//modules.add(new ModuleButton(180, 95, 1, "", this, TextureResources.buttonLeft, 10, 16));
//modules.add(new ModuleButton(202, 95, 2, "", this, TextureResources.buttonRight, 10, 16));
modules.add(new ModuleButton(180, 114, 1, "Select Dst", this, zmaster587.libVulpes.inventory.TextureResources.buttonBuild, 64,20));
//modules.add(new ModuleText(180, 114, "Inventories", 0x404040));
}
else {
DimensionProperties properties = DimensionManager.getEffectiveDimId(worldObj, this.getPosition());
while(properties.getParentProperties() != null) properties = properties.getParentProperties();
container = new ModulePlanetSelector(properties.getId(), zmaster587.libVulpes.inventory.TextureResources.starryBG, this, false);
container.setOffset(1000, 1000);
modules.add(container);
}
return modules;
}
@Override
public String getModularInventoryName() {
return "Rocket";
}
@Override
public float getNormallizedProgress(int id) {
if(id == 0)
return getFuelAmount()/(float)getFuelCapacity();
return 0;
}
@Override
public void setProgress(int id, int progress) {
}
@Override
public int getProgress(int id) {
return 0;
}
@Override
public int getTotalProgress(int id) {
return 0;
}
@Override
public void setTotalProgress(int id, int progress) {}
@Override
public boolean startRiding(Entity entityIn, boolean force) {
// TODO Auto-generated method stub
return super.startRiding(entityIn, force);
}
@Override
public boolean startRiding(Entity entityIn) {
// TODO Auto-generated method stub
return super.startRiding(entityIn);
}
@Override
@SideOnly(Side.CLIENT)
public void onInventoryButtonPressed(int buttonId) {
switch(buttonId) {
case 0:
PacketHandler.sendToServer(new PacketEntity(this, (byte)EntityRocket.PacketType.DECONSTRUCT.ordinal()));
break;
case 1:
PacketHandler.sendToServer(new PacketEntity(this, (byte)EntityRocket.PacketType.OPENPLANETSELECTION.ordinal()));
break;
default:
PacketHandler.sendToServer(new PacketEntity(this, (byte)(buttonId + 100)));
//Minecraft.getMinecraft().thePlayer.closeScreen();
TileEntity tile = storage.getGUItiles().get(buttonId - tilebuttonOffset);
storage.getBlockState(tile.getPos()).getBlock().onBlockActivated(storage.world, tile.getPos(), storage.getBlockState(tile.getPos()), Minecraft.getMinecraft().thePlayer, EnumHand.MAIN_HAND, null, EnumFacing.DOWN, 0, 0, 0);
}
}
@Override
public boolean canInteractWithContainer(EntityPlayer entity) {
boolean ret = !this.isDead && this.getDistanceToEntity(entity) < 64;
if(!ret)
RocketInventoryHelper.removePlayerFromInventoryBypass(entity);
RocketInventoryHelper.updateTime(entity, worldObj.getWorldTime());
return ret;
}
@Override
public StatsRocket getRocketStats() {
return stats;
}
@Override
public void onSelected(Object sender) {
}
@Override
public void onSelectionConfirmed(Object sender) {
PacketHandler.sendToServer(new PacketEntity(this, (byte)PacketType.SENDPLANETDATA.ordinal()));
}
@Override
public void onSystemFocusChanged(Object sender) {
// TODO Auto-generated method stub
}
public LinkedList<IInfrastructure> getConnectedInfrastructure() {
return connectedInfrastructure;
}
}
|
src/main/java/zmaster587/advancedRocketry/entity/EntityRocket.java
|
package zmaster587.advancedRocketry.entity;
import io.netty.buffer.ByteBuf;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import javax.annotation.Nullable;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GLAllocation;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityList;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.network.datasync.DataParameter;
import net.minecraft.network.datasync.DataSerializers;
import net.minecraft.network.datasync.EntityDataManager;
import net.minecraft.network.play.server.SPacketRespawn;
import net.minecraft.server.MinecraftServer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.world.Teleporter;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fluids.FluidContainerRegistry;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.IFluidContainerItem;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import zmaster587.advancedRocketry.AdvancedRocketry;
import zmaster587.advancedRocketry.achievements.ARAchivements;
import zmaster587.advancedRocketry.api.AdvancedRocketryItems;
import zmaster587.advancedRocketry.api.Configuration;
import zmaster587.advancedRocketry.api.EntityRocketBase;
import zmaster587.advancedRocketry.api.IInfrastructure;
import zmaster587.advancedRocketry.api.RocketEvent;
import zmaster587.advancedRocketry.api.RocketEvent.RocketLaunchEvent;
import zmaster587.advancedRocketry.api.RocketEvent.RocketPreLaunchEvent;
import zmaster587.advancedRocketry.api.SatelliteRegistry;
import zmaster587.advancedRocketry.api.StatsRocket;
import zmaster587.advancedRocketry.api.fuel.FuelRegistry;
import zmaster587.advancedRocketry.api.fuel.FuelRegistry.FuelType;
import zmaster587.advancedRocketry.api.satellite.SatelliteBase;
import zmaster587.advancedRocketry.api.stations.ISpaceObject;
import zmaster587.advancedRocketry.atmosphere.AtmosphereHandler;
import zmaster587.advancedRocketry.client.SoundRocketEngine;
import zmaster587.advancedRocketry.dimension.DimensionManager;
import zmaster587.advancedRocketry.dimension.DimensionProperties;
import zmaster587.advancedRocketry.event.PlanetEventHandler;
import zmaster587.advancedRocketry.inventory.TextureResources;
import zmaster587.advancedRocketry.inventory.modules.ModulePlanetSelector;
import zmaster587.advancedRocketry.item.ItemAsteroidChip;
import zmaster587.advancedRocketry.item.ItemPackedStructure;
import zmaster587.advancedRocketry.item.ItemPlanetIdentificationChip;
import zmaster587.advancedRocketry.item.ItemStationChip;
import zmaster587.advancedRocketry.mission.MissionOreMining;
import zmaster587.advancedRocketry.network.PacketSatellite;
import zmaster587.advancedRocketry.stations.SpaceObject;
import zmaster587.advancedRocketry.stations.SpaceObjectManager;
import zmaster587.advancedRocketry.tile.TileGuidanceComputer;
import zmaster587.advancedRocketry.tile.hatch.TileSatelliteHatch;
import zmaster587.advancedRocketry.util.AudioRegistry;
import zmaster587.advancedRocketry.util.RocketInventoryHelper;
import zmaster587.advancedRocketry.util.StorageChunk;
import zmaster587.advancedRocketry.util.TransitionEntity;
import zmaster587.advancedRocketry.world.util.TeleporterNoPortal;
import zmaster587.libVulpes.LibVulpes;
import zmaster587.libVulpes.client.util.ProgressBarImage;
import zmaster587.libVulpes.gui.CommonResources;
import zmaster587.libVulpes.interfaces.INetworkEntity;
import zmaster587.libVulpes.inventory.GuiHandler;
import zmaster587.libVulpes.inventory.modules.IButtonInventory;
import zmaster587.libVulpes.inventory.modules.IModularInventory;
import zmaster587.libVulpes.inventory.modules.IProgressBar;
import zmaster587.libVulpes.inventory.modules.ISelectionNotify;
import zmaster587.libVulpes.inventory.modules.ModuleBase;
import zmaster587.libVulpes.inventory.modules.ModuleButton;
import zmaster587.libVulpes.inventory.modules.ModuleImage;
import zmaster587.libVulpes.inventory.modules.ModuleProgress;
import zmaster587.libVulpes.inventory.modules.ModuleSlotButton;
import zmaster587.libVulpes.items.ItemLinker;
import zmaster587.libVulpes.network.PacketEntity;
import zmaster587.libVulpes.network.PacketHandler;
import zmaster587.libVulpes.util.HashedBlockPosition;
import zmaster587.libVulpes.util.IconResource;
import zmaster587.libVulpes.util.Vector3F;
public class EntityRocket extends EntityRocketBase implements INetworkEntity, IModularInventory, IProgressBar, IButtonInventory, ISelectionNotify {
//true if the rocket is on decent
private boolean isInOrbit;
//True if the rocket isn't on the ground
private boolean isInFlight;
public StorageChunk storage;
private String errorStr;
private long lastErrorTime = Long.MIN_VALUE;
private static long ERROR_DISPLAY_TIME = 100;
protected long lastWorldTickTicked;
private SatelliteBase satallite;
protected int destinationDimId;
//Offset for buttons linking to the tileEntityGrid
private int tilebuttonOffset = 3;
private WeakReference<Entity>[] mountedEntities;
protected ModulePlanetSelector container;
boolean acceptedPacket = false;
public static enum PacketType {
RECIEVENBT,
SENDINTERACT,
REQUESTNBT,
FORCEMOUNT,
LAUNCH,
DECONSTRUCT,
OPENGUI,
CHANGEWORLD,
REVERTWORLD,
OPENPLANETSELECTION,
SENDPLANETDATA,
DISCONNECTINFRASTRUCTURE,
CONNECTINFRASTRUCTURE,
ROCKETLANDEVENT,
MENU_CHANGE,
UPDATE_ATM,
UPDATE_ORBIT,
UPDATE_FLIGHT,
DISMOUNTCLIENT
}
private static final DataParameter<Integer> fuelLevel = EntityDataManager.<Integer>createKey(EntityRocket.class, DataSerializers.VARINT);
private static final DataParameter<Boolean> INFLIGHT = EntityDataManager.<Boolean>createKey(EntityRocket.class, DataSerializers.BOOLEAN);
private static final DataParameter<Boolean> INORBIT = EntityDataManager.<Boolean>createKey(EntityRocket.class, DataSerializers.BOOLEAN);
public EntityRocket(World p_i1582_1_) {
super(p_i1582_1_);
isInOrbit = false;
stats = new StatsRocket();
isInFlight = false;
connectedInfrastructure = new LinkedList<IInfrastructure>();
infrastructureCoords = new LinkedList<HashedBlockPosition>();
mountedEntities = new WeakReference[stats.getNumPassengerSeats()];
lastWorldTickTicked = p_i1582_1_.getTotalWorldTime();
}
public EntityRocket(World world, StorageChunk storage, StatsRocket stats, double x, double y, double z) {
this(world);
this.stats = stats;
this.setPosition(x, y, z);
this.storage = storage;
this.storage.setEntity(this);
initFromBounds();
isInFlight = false;
mountedEntities = new WeakReference[stats.getNumPassengerSeats()];
lastWorldTickTicked = world.getTotalWorldTime();
}
@Override
public AxisAlignedBB getEntityBoundingBox() {
if(storage != null) {
return super.getEntityBoundingBox();//.offset(0, -storage.getSizeY(), 0);
}
return new AxisAlignedBB(0,0,0,1,1,1);
}
@Override
public void setEntityBoundingBox(AxisAlignedBB bb) {
//if(storage != null)
// super.setEntityBoundingBox(bb.offset(0, storage.getSizeY(),0));
//else
super.setEntityBoundingBox(bb);
}
@Override
public AxisAlignedBB getCollisionBoundingBox() {
// TODO Auto-generated method stub
return getEntityBoundingBox();
}
/**
* @return the amount of fuel stored in the rocket
*/
public int getFuelAmount() {
int amount = dataManager.get(fuelLevel);
stats.setFuelAmount(FuelType.LIQUID,amount);
return amount;
}
/**
* Adds fuel and updates the datawatcher
* @param amount amount of fuel to add
* @return the amount of fuel added
*/
public int addFuelAmount(int amount) {
int ret = stats.addFuelAmount(FuelType.LIQUID, amount);
setFuelAmount(stats.getFuelAmount(FuelType.LIQUID));
return ret;
}
public void disconnectInfrastructure(IInfrastructure infrastructure){
infrastructure.unlinkRocket();
infrastructureCoords.remove(new HashedBlockPosition(((TileEntity)infrastructure).getPos()));
if(!worldObj.isRemote) {
int pos[] = {((TileEntity)infrastructure).getPos().getX(), ((TileEntity)infrastructure).getPos().getY(), ((TileEntity)infrastructure).getPos().getZ()};
NBTTagCompound nbt = new NBTTagCompound();
nbt.setIntArray("pos", pos);
//PacketHandler.sendToPlayersTrackingEntity(new PacketEntity(this, (byte)PacketType.DISCONNECTINFRASTRUCTURE.ordinal(), nbt), this);
}
}
@Override
public String getTextOverlay() {
if(this.worldObj.getTotalWorldTime() < this.lastErrorTime + ERROR_DISPLAY_TIME)
return errorStr;
//Get destination string
String displayStr = "N/A";
if(storage != null) {
int dimid = storage.getDestinationDimId(this.worldObj.provider.getDimension(), (int)posX, (int)posZ);
if(dimid == Configuration.spaceDimId) {
Vector3F<Float> vec = storage.getDestinationCoordinates(dimid, false);
if(vec != null) {
ISpaceObject obj = SpaceObjectManager.getSpaceManager().getSpaceStationFromBlockCoords(new BlockPos(vec.x,vec.y,vec.z));
if(obj != null) {
displayStr = "Station " + obj.getId();
}
}
}
else if(dimid != -1 && dimid != SpaceObjectManager.WARPDIMID) {
displayStr = DimensionManager.getInstance().getDimensionProperties(dimid).getName();
}
}
if(isInOrbit() && !isInFlight())
return "Press Space to descend!";
else if(!isInFlight())
return "Press Space to take off!\nDest: " + displayStr;
return super.getTextOverlay();
}
private void setError(String error) {
this.errorStr = error;
this.lastErrorTime = this.worldObj.getTotalWorldTime();
}
@Override
public void setPosition(double x, double y,
double z) {
super.setPosition(x, y, z);
if(storage != null) {
float sizeX = storage.getSizeX()/2.0f;
float sizeY = storage.getSizeY();
float sizeZ = storage.getSizeZ()/2.0f;
//setEntityBoundingBox(new AxisAlignedBB(x - sizeX, y - (double)this.getYOffset() + this.height, z - sizeZ, x + sizeX, y + sizeY - (double)this.getYOffset() + this.height, z + sizeZ));
}
}
/**
* Updates the data option
* @param amt sets the amount of fuel in the rocket
*/
public void setFuelAmount(int amt) {
dataManager.set(fuelLevel, amt);
dataManager.setDirty(fuelLevel);
}
/**
* @return gets the fuel capacity of the rocket
*/
public int getFuelCapacity() {
return stats.getFuelCapacity(FuelType.LIQUID);
}
@Override
public void setEntityId(int id){
super.setEntityId(id);
//Ask server for nbt data
if(worldObj.isRemote) {
PacketHandler.sendToServer(new PacketEntity(this, (byte)PacketType.REQUESTNBT.ordinal()));
}
}
@Override
public boolean canBeCollidedWith() {
return true;
}
/**
* If the rocket is in flight, ie the rocket has taken off and has not touched the ground
* @return true if in flight
*/
public boolean isInFlight() {
if(!worldObj.isRemote) {
return isInFlight;
}
return this.dataManager.get(INFLIGHT);
}
/**
* Sets the the status of flight of the rocket and updates the datawatcher
* @param inflight status of flight
*/
public void setInOrbit(boolean inOrbit) {
this.isInOrbit = inOrbit;
this.dataManager.set(INORBIT, inOrbit);
this.dataManager.setDirty(INORBIT);
}
/**
* If the rocket is in flight, ie the rocket has taken off and has not touched the ground
* @return true if in flight
*/
public boolean isInOrbit() {
if(!worldObj.isRemote) {
return isInOrbit;
}
return this.dataManager.get(INORBIT);
}
/**
* Sets the the status of flight of the rocket and updates the datawatcher
* @param inflight status of flight
*/
public void setInFlight(boolean inflight) {
this.isInFlight = inflight;
this.dataManager.set(INFLIGHT, inflight);
this.dataManager.setDirty(INFLIGHT);
}
@Override
protected void entityInit() {
this.dataManager.register(INFLIGHT, false);
this.dataManager.register(fuelLevel, 0);
this.dataManager.register(INORBIT, false);
}
//Set the size and position of the rocket from storage
public void initFromBounds() {
if(storage != null) {
this.setSize(Math.max(storage.getSizeX(), storage.getSizeZ()), storage.getSizeY());
this.setPosition(this.posX, this.posY, this.posZ);
}
}
protected boolean interact(EntityPlayer player) {
//Actual interact code needs to be moved to a packet receive on the server
ItemStack heldItem = player.getHeldItem(EnumHand.MAIN_HAND);
//Handle linkers and right-click with fuel
if(heldItem != null) {
float fuelMult;
FluidStack fluidStack;
if(heldItem.getItem() instanceof ItemLinker) {
if(ItemLinker.isSet(heldItem)) {
TileEntity tile = this.worldObj.getTileEntity(ItemLinker.getMasterCoords(heldItem));
if(tile instanceof IInfrastructure) {
IInfrastructure infrastructure = (IInfrastructure)tile;
if(this.getDistance(ItemLinker.getMasterX(heldItem), this.posY, ItemLinker.getMasterZ(heldItem)) < infrastructure.getMaxLinkDistance() + Math.max(storage.getSizeX(), storage.getSizeZ())) {
if(!connectedInfrastructure.contains(tile)) {
linkInfrastructure(infrastructure);
if(!worldObj.isRemote) {
player.addChatMessage(new TextComponentString("Linked Sucessfully"));
}
ItemLinker.resetPosition(heldItem);
return true;
}
else if(!worldObj.isRemote)
player.addChatMessage(new TextComponentString("Already linked!"));
}
else if(!worldObj.isRemote)
player.addChatMessage(new TextComponentString("The object you are trying to link is too far away"));
}
else if(!worldObj.isRemote)
player.addChatMessage(new TextComponentString("This cannot be linked to a rocket!"));
}
else if(!worldObj.isRemote)
player.addChatMessage(new TextComponentString("Nothing to be linked"));
return false;
}
else if((FluidContainerRegistry.isFilledContainer(heldItem) && (fuelMult = FuelRegistry.instance.getMultiplier(FuelType.LIQUID, (fluidStack = FluidContainerRegistry.getFluidForFilledItem(heldItem)).getFluid()) ) > 0 )
|| ( heldItem.getItem() instanceof IFluidContainerItem && ((IFluidContainerItem) heldItem.getItem()).getFluid(heldItem) != null &&
((IFluidContainerItem) heldItem.getItem()).getFluid(heldItem).amount >= FluidContainerRegistry.BUCKET_VOLUME
&& (fuelMult = FuelRegistry.instance.getMultiplier(FuelType.LIQUID, (fluidStack = ((IFluidContainerItem) heldItem.getItem()).getFluid(heldItem)).getFluid())) > 0 )) {
int amountToAdd = (int) (fuelMult*fluidStack.amount);
this.addFuelAmount(amountToAdd);
//if the player is not in creative then try to use the fluid container
if(!player.capabilities.isCreativeMode) {
if(heldItem.getItem() instanceof IFluidContainerItem) {
((IFluidContainerItem) heldItem.getItem()).drain(heldItem, FluidContainerRegistry.BUCKET_VOLUME, true);
}
else {
ItemStack emptyStack = FluidContainerRegistry.drainFluidContainer(player.getHeldItem(EnumHand.MAIN_HAND));
if(player.inventory.addItemStackToInventory(emptyStack)) {
player.getHeldItem(EnumHand.MAIN_HAND).splitStack(1);
if(player.getHeldItem(EnumHand.MAIN_HAND).stackSize == 0)
player.inventory.setInventorySlotContents(player.inventory.currentItem, null);
}
}
}
return true;
}
}
//If player is holding shift open GUI
if(player.isSneaking()) {
openGui(player);
}
else if(stats.hasSeat()) { //If pilot seat is open mount entity there
if(stats.hasSeat() && this.getPassengers().isEmpty()) {
if(!worldObj.isRemote)
player.startRiding(this);
}
/*else if(stats.getNumPassengerSeats() > 0) { //If a passenger seat exists and one is empty, mount the player to it
for(int i = 0; i < stats.getNumPassengerSeats(); i++) {
if(this.mountedEntities[i] == null || this.mountedEntities[i].get() == null) {
player.ridingEntity = this;
this.mountedEntities[i] = new WeakReference<Entity>(player);
break;
}
}
}*/
}
return true;
}
public void openGui(EntityPlayer player) {
player.openGui(LibVulpes.instance, GuiHandler.guiId.MODULAR.ordinal(), player.worldObj, this.getEntityId(), -1,0);
//Only handle the bypass on the server
if(!worldObj.isRemote)
RocketInventoryHelper.addPlayerToInventoryBypass(player);
}
@Override
public boolean processInitialInteract(EntityPlayer player, @Nullable ItemStack stack, EnumHand hand){
if(worldObj.isRemote) {
//Due to forge's rigid handling of entities (NetHanlderPlayServer:866) needs to be handled differently for large rockets
PacketHandler.sendToServer(new PacketEntity(this, (byte)PacketType.SENDINTERACT.ordinal()));
return interact(player);
}
return true;
}
public boolean isBurningFuel() {
return (getFuelAmount() > 0 || !Configuration.rocketRequireFuel) && ((!this.getPassengers().isEmpty() && getPassengerMovingForward() > 0) || !isInOrbit());
}
public float getPassengerMovingForward() {
for(Entity entity : this.getPassengers()) {
if(entity instanceof EntityPlayer) {
return ((EntityPlayer) entity).moveForward;
}
}
return 0f;
}
private boolean hasHumanPassenger() {
for(Entity entity : this.getPassengers()) {
if(entity instanceof EntityPlayer) {
return true;
}
}
return false;
}
public boolean isDescentPhase() {
return Configuration.automaticRetroRockets && isInOrbit() && this.posY < 300 && (this.motionY < -0.4f || worldObj.isRemote);
}
public boolean areEnginesRunning() {
return (this.motionY > 0 || isDescentPhase() || (getPassengerMovingForward() > 0));
}
@Override
public void onUpdate() {
super.onUpdate();
long deltaTime = worldObj.getTotalWorldTime() - lastWorldTickTicked;
lastWorldTickTicked = worldObj.getTotalWorldTime();
if(this.ticksExisted == 20) {
//problems with loading on other world then where the infrastructure was set?
ListIterator<HashedBlockPosition> itr = infrastructureCoords.listIterator();
while(itr.hasNext()) {
HashedBlockPosition temp = itr.next();
TileEntity tile = this.worldObj.getTileEntity(new BlockPos(temp.x, temp.y, temp.z));
if(tile instanceof IInfrastructure) {
this.linkInfrastructure((IInfrastructure)tile);
itr.remove();
}
}
if(worldObj.isRemote)
LibVulpes.proxy.playSound(new SoundRocketEngine( AudioRegistry.combustionRocket, SoundCategory.NEUTRAL,this));
}
//Hackish crap to make clients mount entities immediately after server transfer and fire events
//Known race condition... screw me...
if(!worldObj.isRemote && (this.isInFlight() || this.isInOrbit()) && this.ticksExisted == 20) {
//Deorbiting
MinecraftForge.EVENT_BUS.post(new RocketEvent.RocketDeOrbitingEvent(this));
PacketHandler.sendToNearby(new PacketEntity(this, (byte)PacketType.ROCKETLANDEVENT.ordinal()), worldObj.provider.getDimension(), (int)posX, (int)posY, (int)posZ, 64);
for(Entity riddenByEntity : getPassengers()) {
if(riddenByEntity instanceof EntityPlayer) {
EntityPlayer player = (EntityPlayer)riddenByEntity;
if(player instanceof EntityPlayer)
PacketHandler.sendToPlayer(new PacketEntity((INetworkEntity)this,(byte)PacketType.FORCEMOUNT.ordinal()), player);
}
}
}
if(isInFlight()) {
boolean burningFuel = isBurningFuel();
boolean descentPhase = isDescentPhase();
if(burningFuel || descentPhase) {
//Burn the rocket fuel
if(!worldObj.isRemote && !descentPhase)
setFuelAmount(getFuelAmount() - stats.getFuelRate(FuelType.LIQUID));
//Spawn in the particle effects for the engines
int engineNum = 0;
if(worldObj.isRemote && Minecraft.getMinecraft().gameSettings.particleSetting < 2 && areEnginesRunning()) {
for(Vector3F<Float> vec : stats.getEngineLocations()) {
AtmosphereHandler handler;
if(Minecraft.getMinecraft().gameSettings.particleSetting < 1 && worldObj.getTotalWorldTime() % 10 == 0 && (engineNum < 8 || ((worldObj.getTotalWorldTime()/10) % Math.max((stats.getEngineLocations().size()/8),1)) == (engineNum/8)) && ( (handler = AtmosphereHandler.getOxygenHandler(worldObj.provider.getDimension())) == null || (handler.getAtmosphereType(this) != null && handler.getAtmosphereType(this).allowsCombustion())) )
AdvancedRocketry.proxy.spawnParticle("rocketSmoke", worldObj, this.posX + vec.x, this.posY + vec.y - 0.75, this.posZ +vec.z,0,0,0);
for(int i = 0; i < 4; i++) {
AdvancedRocketry.proxy.spawnParticle("rocketFlame", worldObj, this.posX + vec.x, this.posY + vec.y - 0.75, this.posZ +vec.z,(this.rand.nextFloat() - 0.5f)/8f,-.75 ,(this.rand.nextFloat() - 0.5f)/8f);
}
}
}
}
if(!this.getPassengers().isEmpty()) {
for(Entity entity : this.getPassengers()) {
entity.fallDistance = 0;
this.fallDistance = 0;
}
//if the player holds the forward key then decelerate
if(isInOrbit() && (burningFuel || descentPhase)) {
float vel = descentPhase ? 1f : getPassengerMovingForward();
this.motionY -= this.motionY*vel/50f;
}
this.velocityChanged = true;
}
else if(isInOrbit() && descentPhase) { //For unmanned rockets
this.motionY -= this.motionY/50f;
this.velocityChanged = true;
}
if(!worldObj.isRemote) {
//If out of fuel or descending then accelerate downwards
if(isInOrbit() || !burningFuel) {
this.motionY = Math.min(this.motionY - 0.001, 1);
} else
//this.motionY = Math.min(this.motionY + 0.001, 1);
this.motionY += stats.getAcceleration() * deltaTime;
double lastPosY = this.posY;
double prevMotion = this.motionY;
this.moveEntity(0, prevMotion*deltaTime, 0);
//Check to see if it's landed
if((isInOrbit() || !burningFuel) && isInFlight() && lastPosY + prevMotion != this.posY && this.posY < 256) {
MinecraftForge.EVENT_BUS.post(new RocketEvent.RocketLandedEvent(this));
//PacketHandler.sendToPlayersTrackingEntity(new PacketEntity(this, (byte)PacketType.ROCKETLANDEVENT.ordinal()), this);
this.setInFlight(false);
this.setInOrbit(false);
}
if(!isInOrbit() && (this.posY > Configuration.orbit)) {
onOrbitReached();
}
//If the rocket falls out of the world while in orbit either fall back to earth or die
if(this.posY < 0) {
int dimId = worldObj.provider.getDimension();
if(dimId == Configuration.spaceDimId) {
ISpaceObject obj = SpaceObjectManager.getSpaceManager().getSpaceStationFromBlockCoords(getPosition());
if(obj != null) {
int targetDimID = obj.getOrbitingPlanetId();
Vector3F<Float> pos = storage.getDestinationCoordinates(targetDimID, true);
if(pos != null) {
this.changeDimension(destinationDimId, pos.x, Configuration.orbit, pos.z);
}
else
this.setDead();
}
else {
Vector3F<Float> pos = storage.getDestinationCoordinates(0, true);
if(pos != null) {
this.changeDimension(destinationDimId, pos.x, Configuration.orbit, pos.z);
}
else
this.setDead();
}
}
else
this.setDead();
}
}
else {
this.moveEntity(0, this.motionY, 0);
}
}
}
/**
* @return a list of satellites stores in this rocket
*/
public List<SatelliteBase> getSatellites() {
List<SatelliteBase> satellites = new ArrayList<SatelliteBase>();
for(TileSatelliteHatch tile : storage.getSatelliteHatches()) {
SatelliteBase satellite = tile.getSatellite();
if(satellite != null)
satellites.add(satellite);
}
return satellites;
}
/**
* Called when the rocket reaches orbit
*/
public void onOrbitReached() {
super.onOrbitReached();
//TODO: support multiple riders and rider/satellite combo
if(!stats.hasSeat()) {
TileGuidanceComputer computer = storage.getGuidanceComputer();
if(computer != null && computer.getStackInSlot(0) != null &&
computer.getStackInSlot(0).getItem() instanceof ItemAsteroidChip) {
//make it 30 minutes with one drill
float drillingPower = stats.getDrillingPower();
MissionOreMining miningMission = new MissionOreMining((long)(drillingPower == 0f ? 36000 : 360/stats.getDrillingPower()), this, connectedInfrastructure);
DimensionProperties properties = DimensionManager.getInstance().getDimensionProperties(worldObj.provider.getDimension());
properties.addSatallite(miningMission, worldObj);
if(!worldObj.isRemote)
PacketHandler.sendToAll(new PacketSatellite(miningMission));
for(IInfrastructure i : connectedInfrastructure) {
i.linkMission(miningMission);
}
this.setDead();
//TODO: Move tracking stations over to the mission handler
}
else {
unpackSatellites();
}
destinationDimId = storage.getDestinationDimId(this.worldObj.provider.getDimension(), (int)this.posX, (int)this.posZ);
if(DimensionManager.getInstance().canTravelTo(destinationDimId)) {
Vector3F<Float> pos = storage.getDestinationCoordinates(destinationDimId, true);
storage.setDestinationCoordinates(new Vector3F<Float>((float)this.posX, (float)this.posY, (float)this.posZ), this.worldObj.provider.getDimension());
if(pos != null) {
this.setInOrbit(true);
this.motionY = -this.motionY;
this.changeDimension(destinationDimId, pos.x, Configuration.orbit, pos.z);
return;
}
}
else
this.setDead();
//TODO: satellite event?
}
else {
unpackSatellites();
//TODO: maybe add orbit dimension
this.motionY = -this.motionY;
setInOrbit(true);
//If going to a station or something make sure to set coords accordingly
//If in space land on the planet, if on the planet go to space
if(destinationDimId == Configuration.spaceDimId || this.worldObj.provider.getDimension() == Configuration.spaceDimId) {
Vector3F<Float> pos = storage.getDestinationCoordinates(destinationDimId, true);
storage.setDestinationCoordinates(new Vector3F<Float>((float)this.posX, (float)this.posY, (float)this.posZ), this.worldObj.provider.getDimension());
if(pos != null) {
//Make player confirm deorbit if a player is riding the rocket
if(hasHumanPassenger()) {
setInFlight(false);
pos.y = (float) Configuration.orbit;
}
this.changeDimension(destinationDimId, pos.x, pos.y, pos.z);
return;
}
}
//Make player confirm deorbit if a player is riding the rocket
if(hasHumanPassenger()) {
setInFlight(false);
if(DimensionManager.getInstance().getDimensionProperties(destinationDimId).getName().equals("Luna")) {
for(Entity player : this.getPassengers()) {
if(player instanceof EntityPlayer) {
((EntityPlayer)player).addStat(ARAchivements.moonLanding);
if(!DimensionManager.hasReachedMoon)
((EntityPlayer)player).addStat(ARAchivements.oneSmallStep);
}
}
DimensionManager.hasReachedMoon = true;
}
}
else
setPosition(posX, Configuration.orbit, posZ);
if(destinationDimId != this.worldObj.provider.getDimension())
this.changeDimension(this.worldObj.provider.getDimension() == destinationDimId ? 0 : destinationDimId);
}
}
private void unpackSatellites() {
List<TileSatelliteHatch> satelliteHatches = storage.getSatelliteHatches();
for(TileSatelliteHatch tile : satelliteHatches) {
SatelliteBase satellite = tile.getSatellite();
if(satellite == null) {
ItemStack stack = tile.getStackInSlot(0);
if(stack != null && stack.getItem() == AdvancedRocketryItems.itemSpaceStation) {
StorageChunk storage = ((ItemPackedStructure)stack.getItem()).getStructure(stack);
ISpaceObject object = SpaceObjectManager.getSpaceManager().getSpaceStation((int)ItemStationChip.getUUID(stack));
SpaceObjectManager.getSpaceManager().moveStationToBody(object, this.worldObj.provider.getDimension());
//Vector3F<Integer> spawn = object.getSpawnLocation();
object.onModuleUnpack(storage);
tile.setInventorySlotContents(0, null);
}
}
else {
satellite.setDimensionId(worldObj);
DimensionProperties properties = DimensionManager.getInstance().getDimensionProperties(this.worldObj.provider.getDimension());
properties.addSatallite(satellite, this.worldObj);
}
}
}
@Override
/**
* Called immediately before launch
*/
public void prepareLaunch() {
RocketPreLaunchEvent event = new RocketEvent.RocketPreLaunchEvent(this);
MinecraftForge.EVENT_BUS.post(event);
if(!event.isCanceled()) {
if(worldObj.isRemote)
PacketHandler.sendToServer(new PacketEntity(this, (byte)EntityRocket.PacketType.LAUNCH.ordinal()));
launch();
}
}
@Override
public void launch() {
if(isInFlight())
return;
if(isInOrbit()) {
setInFlight(true);
return;
}
//Get destination dimid and lock the computer
//TODO: lock the computer
destinationDimId = storage.getDestinationDimId(worldObj.provider.getDimension(), (int)this.posX, (int)this.posZ);
//TODO: make sure this doesn't break asteriod mining
if(!(DimensionManager.getInstance().canTravelTo(destinationDimId) || (destinationDimId == -1 && storage.getSatelliteHatches().size() != 0))) {
setError(LibVulpes.proxy.getLocalizedString("error.rocket.cannotGetThere"));
return;
}
int finalDest = destinationDimId;
if(destinationDimId == Configuration.spaceDimId) {
ISpaceObject obj = null;
Vector3F<Float> vec = storage.getDestinationCoordinates(destinationDimId,false);
if(vec != null)
obj = SpaceObjectManager.getSpaceManager().getSpaceStationFromBlockCoords(new BlockPos(vec.x, vec.y, vec.z));
if( obj != null)
finalDest = obj.getOrbitingPlanetId();
else {
setError(LibVulpes.proxy.getLocalizedString("error.rocket.destinationNotExist"));
return;
}
}
int thisDimId = this.worldObj.provider.getDimension();
if(this.worldObj.provider.getDimension() == Configuration.spaceDimId) {
ISpaceObject object = SpaceObjectManager.getSpaceManager().getSpaceStationFromBlockCoords(this.getPosition());
if(object != null)
thisDimId = object.getProperties().getParentProperties().getId();
}
if(finalDest != -1 && !DimensionManager.getInstance().areDimensionsInSamePlanetMoonSystem(finalDest, thisDimId)) {
setError(LibVulpes.proxy.getLocalizedString("error.rocket.notSameSystem"));
return;
}
//TODO: Clean this logic a bit?
if(!stats.hasSeat() || ((DimensionManager.getInstance().isDimensionCreated(destinationDimId)) || destinationDimId == Configuration.spaceDimId || destinationDimId == 0) ) { //Abort if destination is invalid
setInFlight(true);
Iterator<IInfrastructure> connectedTiles = connectedInfrastructure.iterator();
MinecraftForge.EVENT_BUS.post(new RocketLaunchEvent(this));
//Disconnect things linked to the rocket on liftoff
while(connectedTiles.hasNext()) {
IInfrastructure i = connectedTiles.next();
if(i.disconnectOnLiftOff()) {
disconnectInfrastructure(i);
connectedTiles.remove();
}
}
}
}
/**
* Called when the rocket is to be deconstructed
*/
@Override
public void deconstructRocket() {
super.deconstructRocket();
for(IInfrastructure infrastructure : connectedInfrastructure) {
infrastructure.unlinkRocket();
}
//paste the rocket into the world as blocks
storage.pasteInWorld(this.worldObj, (int)(this.posX - storage.getSizeX()/2f), (int)this.posY, (int)(this.posZ - storage.getSizeZ()/2f));
this.setDead();
}
@Override
public void setDead() {
super.setDead();
if(storage != null && storage.world.displayListIndex != -1)
GLAllocation.deleteDisplayLists(storage.world.displayListIndex);
//unlink any connected tiles
Iterator<IInfrastructure> connectedTiles = connectedInfrastructure.iterator();
while(connectedTiles.hasNext()) {
connectedTiles.next().unlinkRocket();
connectedTiles.remove();
}
}
public void setOverriddenCoords(int dimId, float x, float y, float z) {
TileGuidanceComputer tile = storage.getGuidanceComputer();
if(tile != null) {
tile.setFallbackDestination(dimId, new Vector3F<Float>(x, y, z));
}
}
@Override
public Entity changeDimension(int newDimId) {
return changeDimension(newDimId, this.posX, (double)Configuration.orbit, this.posZ);
}
@Nullable
public Entity changeDimension(int dimensionIn, double posX, double y, double posZ)
{
if (!this.worldObj.isRemote && !this.isDead)
{
List<Entity> passengers = getPassengers();
if (!net.minecraftforge.common.ForgeHooks.onTravelToDimension(this, dimensionIn)) return null;
this.worldObj.theProfiler.startSection("changeDimension");
MinecraftServer minecraftserver = this.getServer();
int i = this.dimension;
WorldServer worldserver = minecraftserver.worldServerForDimension(i);
WorldServer worldserver1 = minecraftserver.worldServerForDimension(dimensionIn);
this.dimension = dimensionIn;
if (i == 1 && dimensionIn == 1)
{
worldserver1 = minecraftserver.worldServerForDimension(0);
this.dimension = 0;
}
this.worldObj.removeEntity(this);
this.isDead = false;
this.worldObj.theProfiler.startSection("reposition");
BlockPos blockpos;
double d0 = this.posX;
double d1 = this.posZ;
double d2 = 8.0D;
d0 = MathHelper.clamp_double(d0 * 8.0D, worldserver1.getWorldBorder().minX() + 16.0D, worldserver1.getWorldBorder().maxX() - 16.0D);
d1 = MathHelper.clamp_double(d1 * 8.0D, worldserver1.getWorldBorder().minZ() + 16.0D, worldserver1.getWorldBorder().maxZ() - 16.0D);
d0 = (double)MathHelper.clamp_int((int)d0, -29999872, 29999872);
d1 = (double)MathHelper.clamp_int((int)d1, -29999872, 29999872);
float f = this.rotationYaw;
this.setLocationAndAngles(d0, this.posY, d1, 90.0F, 0.0F);
Teleporter teleporter = new TeleporterNoPortal(worldserver1);
teleporter.placeInExistingPortal(this, f);
worldserver.updateEntityWithOptionalForce(this, false);
this.worldObj.theProfiler.endStartSection("reloading");
Entity entity = EntityList.createEntityByName(EntityList.getEntityString(this), worldserver1);
if (entity != null)
{
this.moveToBlockPosAndAngles(new BlockPos(posX, y, posZ), entity.rotationYaw, entity.rotationPitch);
((EntityRocket)entity).copyDataFromOld(this);
entity.forceSpawn = true;
worldserver1.spawnEntityInWorld(entity);
worldserver1.updateEntityWithOptionalForce(entity, true);
int timeOffset = 1;
for(Entity e : passengers) {
//Fix that darn random crash?
worldserver.resetUpdateEntityTick();
worldserver1.resetUpdateEntityTick();
//Transfer the player if applicable
//Need to handle our own removal to avoid race condition where player is mounted on client on the old entity but is already mounted to the new one on server
//PacketHandler.sendToPlayer(new PacketEntity(this, (byte)PacketType.DISMOUNTCLIENT.ordinal()), (EntityPlayer) e);
PlanetEventHandler.addDelayedTransition(worldserver.getTotalWorldTime(), new TransitionEntity(worldserver.getTotalWorldTime(), e, dimensionIn, new BlockPos(posX + 16, y, posZ), entity));
//minecraftserver.getPlayerList().transferPlayerToDimension((EntityPlayerMP)e, dimensionIn, teleporter);
//e.setLocationAndAngles(posX, Configuration.orbit, posZ, this.rotationYaw, this.rotationPitch);
//e.startRiding(entity);
//e.playerNetServerHandler.sendPacket(new SPacketRespawn(e.dimension, e.worldObj.getDifficulty(), worldserver1.getWorldInfo().getTerrainType(), ((EntityPlayerMP)e).interactionManager.getGameType()));
//((WorldServer)startWorld).getPlayerManager().removePlayer(player);
}
}
this.isDead = true;
this.worldObj.theProfiler.endSection();
worldserver.resetUpdateEntityTick();
worldserver1.resetUpdateEntityTick();
this.worldObj.theProfiler.endSection();
return entity;
}
else
{
return null;
}
}
/**
* Prepares this entity in new dimension by copying NBT data from entity in old dimension
*/
public void copyDataFromOld(Entity entityIn)
{
NBTTagCompound nbttagcompound = entityIn.writeToNBT(new NBTTagCompound());
nbttagcompound.removeTag("Dimension");
nbttagcompound.removeTag("Passengers");
this.readFromNBT(nbttagcompound);
this.timeUntilPortal = entityIn.timeUntilPortal;
}
protected void readNetworkableNBT(NBTTagCompound nbt) {
//Normal function checks for the existance of the data anyway
readEntityFromNBT(nbt);
}
@Override
protected void readEntityFromNBT(NBTTagCompound nbt) {
setInOrbit(isInOrbit = nbt.getBoolean("orbit"));
stats.readFromNBT(nbt);
mountedEntities = new WeakReference[stats.getNumPassengerSeats()];
setFuelAmount(stats.getFuelAmount(FuelType.LIQUID));
setInFlight(isInFlight = nbt.getBoolean("flight"));
readMissionPersistantNBT(nbt);
if(nbt.hasKey("data"))
{
if(storage == null)
storage = new StorageChunk();
storage.readFromNBT(nbt.getCompoundTag("data"));
storage.setEntity(this);
this.setSize(Math.max(storage.getSizeX(), storage.getSizeZ()), storage.getSizeY());
}
NBTTagList tagList = nbt.getTagList("infrastructure", 10);
for (int i = 0; i < tagList.tagCount(); i++) {
int coords[] = tagList.getCompoundTagAt(i).getIntArray("loc");
//If called on server causes recursive loop, use hackish workaround with tempcoords and onChunkLoad if on server
if(worldObj.isRemote) {
TileEntity tile = this.worldObj.getTileEntity(new BlockPos(coords[0], coords[1], coords[2]));
if(tile instanceof IInfrastructure)
this.linkInfrastructure((IInfrastructure)tile);
}
else
infrastructureCoords.add(new HashedBlockPosition(coords[0], coords[1], coords[2]));
}
destinationDimId = nbt.getInteger("destinationDimId");
//Satallite
if(nbt.hasKey("satallite")) {
NBTTagCompound satalliteNbt = nbt.getCompoundTag("satallite");
satallite = SatelliteRegistry.createFromNBT(satalliteNbt);
}
}
protected void writeNetworkableNBT(NBTTagCompound nbt) {
writeMissionPersistantNBT(nbt);
nbt.setBoolean("orbit", isInOrbit());
nbt.setBoolean("flight", isInFlight());
stats.writeToNBT(nbt);
NBTTagList itemList = new NBTTagList();
for(int i = 0; i < connectedInfrastructure.size(); i++)
{
IInfrastructure inf = connectedInfrastructure.get(i);
if(inf instanceof TileEntity) {
TileEntity ent = (TileEntity)inf;
NBTTagCompound tag = new NBTTagCompound();
tag.setIntArray("loc", new int[] {ent.getPos().getX(), ent.getPos().getY(), ent.getPos().getZ()});
itemList.appendTag(tag);
}
}
nbt.setTag("infrastructure", itemList);
nbt.setInteger("destinationDimId", destinationDimId);
//Satallite
if(satallite != null) {
NBTTagCompound satalliteNbt = new NBTTagCompound();
satallite.writeToNBT(satalliteNbt);
satalliteNbt.setString("DataType",SatelliteRegistry.getKey(satallite.getClass()));
nbt.setTag("satallite", satalliteNbt);
}
}
public void writeMissionPersistantNBT(NBTTagCompound nbt) {
}
public void readMissionPersistantNBT(NBTTagCompound nbt) {
}
@Override
protected void writeEntityToNBT(NBTTagCompound nbt) {
writeNetworkableNBT(nbt);
if(storage != null) {
NBTTagCompound blocks = new NBTTagCompound();
storage.writeToNBT(blocks);
nbt.setTag("data", blocks);
}
//TODO handle non tile Infrastructure
}
@Override
public void readDataFromNetwork(ByteBuf in, byte packetId,
NBTTagCompound nbt) {
if(packetId == PacketType.RECIEVENBT.ordinal()) {
storage = new StorageChunk();
storage.setEntity(this);
storage.readFromNetwork(in);
}
else if(packetId == PacketType.SENDPLANETDATA.ordinal()) {
nbt.setInteger("selection", in.readInt());
}
}
@Override
public void writeDataToNetwork(ByteBuf out, byte id) {
if(id == PacketType.RECIEVENBT.ordinal()) {
storage.writeToNetwork(out);
}
else if(id == PacketType.SENDPLANETDATA.ordinal()) {
if(worldObj.isRemote)
out.writeInt(container.getSelectedSystem());
else {
if(storage.getGuidanceComputer() != null) {
ItemStack stack = storage.getGuidanceComputer().getStackInSlot(0);
if(stack != null && stack.getItem() == AdvancedRocketryItems.itemPlanetIdChip) {
out.writeInt(((ItemPlanetIdentificationChip)AdvancedRocketryItems.itemPlanetIdChip).getDimensionId(stack));
}
}
}
}
}
@Override
public void useNetworkData(EntityPlayer player, Side side, byte id,
NBTTagCompound nbt) {
if(id == PacketType.RECIEVENBT.ordinal()) {
this.readEntityFromNBT(nbt);
initFromBounds();
}
else if(id == PacketType.DECONSTRUCT.ordinal()) {
deconstructRocket();
}
else if(id == PacketType.SENDINTERACT.ordinal()) {
interact(player);
}
else if(id == PacketType.OPENGUI.ordinal()) { //Used in key handler
if(player.getRidingEntity() == this) //Prevent cheating
openGui(player);
}
else if(id == PacketType.REQUESTNBT.ordinal()) {
if(storage != null) {
NBTTagCompound nbtdata = new NBTTagCompound();
this.writeNetworkableNBT(nbtdata);
PacketHandler.sendToPlayer(new PacketEntity((INetworkEntity)this, (byte)PacketType.RECIEVENBT.ordinal(), nbtdata), player);
}
}
else if(id == PacketType.FORCEMOUNT.ordinal()) { //Used for pesky dimension transfers
//When dimensions are transferred make sure to remount the player on the client
if(!acceptedPacket) {
acceptedPacket = true;
player.setPositionAndRotation(this.posX, this.posY, this.posZ, player.rotationYaw, player.rotationPitch);
player.startRiding(this);
MinecraftForge.EVENT_BUS.post(new RocketEvent.RocketDeOrbitingEvent(this));
}
}
else if(id == PacketType.LAUNCH.ordinal()) {
if(this.getPassengers().contains(player))
this.prepareLaunch();
}
else if(id == PacketType.CHANGEWORLD.ordinal()) {
AdvancedRocketry.proxy.changeClientPlayerWorld(storage.world);
}
else if(id == PacketType.REVERTWORLD.ordinal()) {
AdvancedRocketry.proxy.changeClientPlayerWorld(this.worldObj);
}
else if(id == PacketType.OPENPLANETSELECTION.ordinal()) {
player.openGui(LibVulpes.instance, GuiHandler.guiId.MODULARFULLSCREEN.ordinal(), player.worldObj, this.getEntityId(), -1,0);
}
else if(id == PacketType.SENDPLANETDATA.ordinal()) {
ItemStack stack = storage.getGuidanceComputer().getStackInSlot(0);
if(stack != null && stack.getItem() == AdvancedRocketryItems.itemPlanetIdChip) {
((ItemPlanetIdentificationChip)AdvancedRocketryItems.itemPlanetIdChip).setDimensionId(stack, nbt.getInteger("selection"));
//Send data back to sync destination dims
if(!worldObj.isRemote) {
PacketHandler.sendToPlayersTrackingEntity(new PacketEntity(this, (byte)PacketType.SENDPLANETDATA.ordinal()), this);
}
}
}
else if(id == PacketType.DISCONNECTINFRASTRUCTURE.ordinal()) {
int pos[] = nbt.getIntArray("pos");
connectedInfrastructure.remove(new HashedBlockPosition(pos[0], pos[1], pos[2]));
TileEntity tile = worldObj.getTileEntity(new BlockPos(pos[0], pos[1], pos[2]));
if(tile instanceof IInfrastructure) {
((IInfrastructure)tile).unlinkRocket();
connectedInfrastructure.remove(tile);
}
}
else if(id == PacketType.ROCKETLANDEVENT.ordinal() && worldObj.isRemote) {
MinecraftForge.EVENT_BUS.post(new RocketEvent.RocketLandedEvent(this));
}
else if(id == PacketType.DISMOUNTCLIENT.ordinal() && worldObj.isRemote) {
player.dismountRidingEntity();
//this.removePassenger(player);
}
else if(id > 100) {
TileEntity tile = storage.getGUItiles().get(id - 100 - tilebuttonOffset);
//Welcome to super hack time with packets
//Due to the fact the client uses the player's current world to open the gui, we have to move the client between worlds for a bit
PacketHandler.sendToPlayer(new PacketEntity(this, (byte)PacketType.CHANGEWORLD.ordinal()), player);
storage.getBlockState(tile.getPos()).getBlock().onBlockActivated(storage.world, tile.getPos(), storage.getBlockState(tile.getPos()), player, EnumHand.MAIN_HAND, null, EnumFacing.DOWN, 0, 0, 0);
PacketHandler.sendToPlayer(new PacketEntity(this, (byte)PacketType.REVERTWORLD.ordinal()), player);
}
}
@Override
public void updatePassenger(Entity entity)
{
if (entity != null )
{
//Bind player to the seat
if(this.storage != null) {
//Conditional b/c for some reason client/server positions do not match
float xOffset = this.storage.getSizeX() % 2 == 0 ? 0.5f : 0f;
float zOffset = this.storage.getSizeZ() % 2 == 0 ? 0.5f : 0f;
entity.setPosition(this.posX + stats.getSeatX() + xOffset, this.posY + stats.getSeatY() - 0.5f, this.posZ + stats.getSeatZ() + zOffset );
}
else
entity.setPosition(this.posX , this.posY , this.posZ );
}
for(int i = 0; i < this.stats.getNumPassengerSeats(); i++) {
HashedBlockPosition pos = this.stats.getPassengerSeat(i);
if(mountedEntities[i] != null && mountedEntities[i].get() != null) {
mountedEntities[i].get().setPosition(this.posX + pos.x, this.posY + pos.y, this.posZ + pos.z);
System.out.println("Additional: " + mountedEntities[i].get());
}
}
}
@Override
public List<ModuleBase> getModules(int ID, EntityPlayer player) {
List<ModuleBase> modules;
//If the rocket is flight don't load the interface
modules = new LinkedList<ModuleBase>();
if(ID == GuiHandler.guiId.MODULAR.ordinal()) {
//Backgrounds
if(worldObj.isRemote) {
modules.add(new ModuleImage(173, 0, new IconResource(128, 0, 48, 86, CommonResources.genericBackground)));
modules.add(new ModuleImage(173, 86, new IconResource(98, 0, 78, 83, CommonResources.genericBackground)));
modules.add(new ModuleImage(173, 168, new IconResource(98, 168, 78, 3, CommonResources.genericBackground)));
}
//Fuel
modules.add(new ModuleProgress(192, 7, 0, new ProgressBarImage(2, 173, 12, 71, 17, 6, 3, 69, 1, 1, EnumFacing.UP, TextureResources.rocketHud), this));
//TODO DEBUG tiles!
List<TileEntity> tiles = storage.getGUItiles();
for(int i = 0; i < tiles.size(); i++) {
TileEntity tile = tiles.get(i);
IBlockState state = storage.getBlockState(tile.getPos());
try {
modules.add(new ModuleSlotButton(8 + 18* (i % 9), 17 + 18*(i/9), i + tilebuttonOffset, this, new ItemStack(state.getBlock(), 1, state.getBlock().getMetaFromState(state)), worldObj));
} catch (NullPointerException e) {
}
}
//Add buttons
modules.add(new ModuleButton(180, 140, 0, "Dissassemble", this, zmaster587.libVulpes.inventory.TextureResources.buttonBuild, 64, 20));
//modules.add(new ModuleButton(180, 95, 1, "", this, TextureResources.buttonLeft, 10, 16));
//modules.add(new ModuleButton(202, 95, 2, "", this, TextureResources.buttonRight, 10, 16));
modules.add(new ModuleButton(180, 114, 1, "Select Dst", this, zmaster587.libVulpes.inventory.TextureResources.buttonBuild, 64,20));
//modules.add(new ModuleText(180, 114, "Inventories", 0x404040));
}
else {
DimensionProperties properties = DimensionManager.getEffectiveDimId(worldObj, this.getPosition());
while(properties.getParentProperties() != null) properties = properties.getParentProperties();
container = new ModulePlanetSelector(properties.getId(), zmaster587.libVulpes.inventory.TextureResources.starryBG, this, false);
container.setOffset(1000, 1000);
modules.add(container);
}
return modules;
}
@Override
public String getModularInventoryName() {
return "Rocket";
}
@Override
public float getNormallizedProgress(int id) {
if(id == 0)
return getFuelAmount()/(float)getFuelCapacity();
return 0;
}
@Override
public void setProgress(int id, int progress) {
}
@Override
public int getProgress(int id) {
return 0;
}
@Override
public int getTotalProgress(int id) {
return 0;
}
@Override
public void setTotalProgress(int id, int progress) {}
@Override
public boolean startRiding(Entity entityIn, boolean force) {
// TODO Auto-generated method stub
return super.startRiding(entityIn, force);
}
@Override
public boolean startRiding(Entity entityIn) {
// TODO Auto-generated method stub
return super.startRiding(entityIn);
}
@Override
@SideOnly(Side.CLIENT)
public void onInventoryButtonPressed(int buttonId) {
switch(buttonId) {
case 0:
PacketHandler.sendToServer(new PacketEntity(this, (byte)EntityRocket.PacketType.DECONSTRUCT.ordinal()));
break;
case 1:
PacketHandler.sendToServer(new PacketEntity(this, (byte)EntityRocket.PacketType.OPENPLANETSELECTION.ordinal()));
break;
default:
PacketHandler.sendToServer(new PacketEntity(this, (byte)(buttonId + 100)));
//Minecraft.getMinecraft().thePlayer.closeScreen();
TileEntity tile = storage.getGUItiles().get(buttonId - tilebuttonOffset);
storage.getBlockState(tile.getPos()).getBlock().onBlockActivated(storage.world, tile.getPos(), storage.getBlockState(tile.getPos()), Minecraft.getMinecraft().thePlayer, EnumHand.MAIN_HAND, null, EnumFacing.DOWN, 0, 0, 0);
}
}
@Override
public boolean canInteractWithContainer(EntityPlayer entity) {
boolean ret = !this.isDead && this.getDistanceToEntity(entity) < 64;
if(!ret)
RocketInventoryHelper.removePlayerFromInventoryBypass(entity);
RocketInventoryHelper.updateTime(entity, worldObj.getWorldTime());
return ret;
}
@Override
public StatsRocket getRocketStats() {
return stats;
}
@Override
public void onSelected(Object sender) {
}
@Override
public void onSelectionConfirmed(Object sender) {
PacketHandler.sendToServer(new PacketEntity(this, (byte)PacketType.SENDPLANETDATA.ordinal()));
}
@Override
public void onSystemFocusChanged(Object sender) {
// TODO Auto-generated method stub
}
public LinkedList<IInfrastructure> getConnectedInfrastructure() {
return connectedInfrastructure;
}
}
|
fix rocket not falling back to planet if station missed
|
src/main/java/zmaster587/advancedRocketry/entity/EntityRocket.java
|
fix rocket not falling back to planet if station missed
|
<ide><path>rc/main/java/zmaster587/advancedRocketry/entity/EntityRocket.java
<ide> private boolean isInOrbit;
<ide> //True if the rocket isn't on the ground
<ide> private boolean isInFlight;
<add> //used in the rare case a player goes to a non-existant space station
<add> private int lastDimensionFrom = 0;
<ide> public StorageChunk storage;
<ide> private String errorStr;
<ide> private long lastErrorTime = Long.MIN_VALUE;
<ide>
<ide> Vector3F<Float> pos = storage.getDestinationCoordinates(targetDimID, true);
<ide> if(pos != null) {
<del> this.changeDimension(destinationDimId, pos.x, Configuration.orbit, pos.z);
<add> setInOrbit(true);
<add> setInFlight(false);
<add> this.changeDimension(targetDimID, pos.x, Configuration.orbit, pos.z);
<ide> }
<ide> else
<ide> this.setDead();
<ide> else {
<ide> Vector3F<Float> pos = storage.getDestinationCoordinates(0, true);
<ide> if(pos != null) {
<del> this.changeDimension(destinationDimId, pos.x, Configuration.orbit, pos.z);
<add> setInOrbit(true);
<add> setInFlight(false);
<add> this.changeDimension(lastDimensionFrom, pos.x, Configuration.orbit, pos.z);
<ide> }
<ide> else
<ide> this.setDead();
<ide> {
<ide> if (!this.worldObj.isRemote && !this.isDead)
<ide> {
<add>
<add> if(!DimensionManager.getInstance().canTravelTo(dimensionIn)) {
<add> AdvancedRocketry.logger.warning("Rocket trying to travel from Dim" + this.worldObj.provider.getDimension() + " to Dim " + dimensionIn + ". target not accessible by rocket from launch dim");
<add> return null;
<add> }
<add>
<add> lastDimensionFrom = this.worldObj.provider.getDimension();
<add>
<ide> List<Entity> passengers = getPassengers();
<ide>
<ide> if (!net.minecraftforge.common.ForgeHooks.onTravelToDimension(this, dimensionIn)) return null;
<ide>
<ide> destinationDimId = nbt.getInteger("destinationDimId");
<ide>
<add> lastDimensionFrom = nbt.getInteger("lastDimensionFrom");
<add>
<ide> //Satallite
<ide> if(nbt.hasKey("satallite")) {
<ide> NBTTagCompound satalliteNbt = nbt.getCompoundTag("satallite");
<ide>
<ide> //TODO handle non tile Infrastructure
<ide>
<add>
<add> nbt.setInteger("lastDimensionFrom", lastDimensionFrom);
<ide> }
<ide>
<ide> @Override
|
|
JavaScript
|
mit
|
15ecebea48f8f27f44fb5380b7ce50e71ae92299
| 0 |
partridgejiang/Kekule.js,partridgejiang/Kekule.js,partridgejiang/Kekule.js,partridgejiang/Kekule.js,partridgejiang/Kekule.js,partridgejiang/Kekule.js
|
/**
* @fileoverview
* Operations need to implement an editor.
* @author Partridge Jiang
*/
/*
* requires /lan/classes.js
* requires /utils/kekule.utils.js
* requires /widgets/operation/kekule.operations.js
* requires /core/kekule.structures.js
* requires /widgets/chem/editor/kekule.chemEditor.baseEditors.js
* requires /localization/
*/
(function(){
"use strict";
/**
* A namespace for operation about normal ChemObject instance.
* @namespace
*/
Kekule.ChemObjOperation = {};
/**
* Base operation for ChemObject instance.
* @class
* @augments Kekule.Operation
*
* @param {Kekule.ChemObject} chemObject Target chem object.
*
* @property {Kekule.ChemObject} target Target chem object.
* @property {Bool} allowCoordBorrow Whether allow borrowing between 2D and 3D when manipulating coords.
*/
Kekule.ChemObjOperation.Base = Class.create(Kekule.Operation,
/** @lends Kekule.ChemObjOperation.Base# */
{
/** @private */
CLASS_NAME: 'Kekule.ChemObjOperation.Base',
/** @constructs */
initialize: function($super, chemObj)
{
$super();
this.setTarget(chemObj);
},
/** @private */
initProperties: function()
{
this.defineProp('target', {'dataType': 'Kekule.ChemObject', 'serializable': false});
this.defineProp('allowCoordBorrow', {'dataType': DataType.BOOL});
}
});
/**
* Operation of changing a chemObject's properties.
* @class
* @augments Kekule.ChemObjOperation.Base
*
* @param {Kekule.ChemObject} chemObject Target chem object.
* @param {Hash} newPropValues A hash of new prop-value map.
*
* @property {Hash} newPropValues A hash of new prop-value map.
*/
Kekule.ChemObjOperation.Modify = Class.create(Kekule.ChemObjOperation.Base,
/** @lends Kekule.ChemObjOperation.Modify# */
{
/** @private */
CLASS_NAME: 'Kekule.ChemObjOperation.Modify',
/** @constructs */
initialize: function($super, chemObj, newPropValues)
{
$super(chemObj);
if (newPropValues)
this.setNewPropValues(newPropValues);
},
/** @private */
initProperties: function()
{
this.defineProp('newPropValues', {'dataType': DataType.HASH});
this.defineProp('oldPropValues', {'dataType': DataType.HASH}); // private
},
/** @private */
doExecute: function()
{
var oldValues = {};
var map = this.getNewPropValues();
var obj = this.getTarget();
for (var prop in map)
{
var value = map[prop];
// store old value first
oldValues[prop] = obj.getPropValue(prop);
// set new value
obj.setPropValue(prop, value);
}
this.setOldPropValues(oldValues);
},
/** @private */
doReverse: function()
{
var map = this.getOldPropValues();
var obj = this.getTarget();
for (var prop in map)
{
var value = map[prop];
// restore old value
obj.setPropValue(prop, value);
}
}
});
/**
* Operation of changing a chemObject's coord.
* @class
* @augments Kekule.ChemObjOperation.Base
*
* @param {Kekule.ChemObject} chemObject Target chem object.
* @param {Hash} newCoord
* @param {Int} coordMode
* @param {Bool} useAbsCoord
*
* @property {Hash} newCoord
* @property {Hash} oldCoord If old coord is not set, this property will be automatically calculated when execute the operation.
* @property {Int} coordMode
* @property {Bool} useAbsCoord
*/
Kekule.ChemObjOperation.MoveTo = Class.create(Kekule.ChemObjOperation.Base,
/** @lends Kekule.ChemObjOperation.MoveTo# */
{
/** @private */
CLASS_NAME: 'Kekule.ChemObjOperation.MoveTo',
/** @constructs */
initialize: function($super, chemObj, newCoord, coordMode, useAbsCoord)
{
$super(chemObj);
if (newCoord)
this.setNewCoord(newCoord);
this.setCoordMode(coordMode || Kekule.CoordMode.COORD2D);
this.setUseAbsCoord(!!useAbsCoord);
},
/** @private */
initProperties: function()
{
this.defineProp('newCoord', {'dataType': DataType.HASH});
this.defineProp('oldCoord', {'dataType': DataType.HASH});
this.defineProp('coordMode', {'dataType': DataType.INT});
this.defineProp('useAbsCoord', {'dataType': DataType.BOOL});
},
/** @private */
setObjCoord: function(obj, coord, coordMode)
{
if (obj && coord && coordMode)
{
var success = false;
if (this.getUseAbsCoord())
{
if (obj.setAbsCoordOfMode)
{
obj.setAbsCoordOfMode(coord, coordMode);
success = true;
}
}
else
{
if (obj.setCoordOfMode)
{
obj.setCoordOfMode(coord, coordMode);
success = true;
}
}
if (!success)
{
var className = obj.getClassName? obj.getClassName(): (typeof obj);
Kekule.warn(/*Kekule.ErrorMsg.CAN_NOT_SET_COORD_OF_CLASS*/Kekule.$L('ErrorMsg.CAN_NOT_SET_COORD_OF_CLASS').format(className));
}
}
},
/** @private */
getObjCoord: function(obj, coordMode)
{
if (this.getUseAbsCoord())
{
if (obj.getAbsCoordOfMode)
return obj.getAbsCoordOfMode(coordMode, this.getAllowCoordBorrow());
}
else
{
if (obj.getCoordOfMode)
return obj.getCoordOfMode(coordMode, this.getAllowCoordBorrow());
}
return null;
},
/** @private */
doExecute: function()
{
var obj = this.getTarget();
if (!this.getOldCoord())
this.setOldCoord(this.getObjCoord(obj, this.getCoordMode()));
if (this.getNewCoord())
this.setObjCoord(this.getTarget(), this.getNewCoord(), this.getCoordMode());
},
/** @private */
doReverse: function()
{
if (this.getOldCoord())
{
this.setObjCoord(this.getTarget(), this.getOldCoord(), this.getCoordMode());
}
}
});
/**
* Operation of changing a chem object's size and coord.
* @class
* @augments Kekule.ChemObjOperation.MoveTo
*
* @param {Kekule.ChemObject} chemObject Target chem object.
* @param {Hash} newDimension {width, height}
* @param {Hash} newCoord
* @param {Int} coordMode
* @param {Bool} useAbsCoord
*
* @property {Hash} newDimension
* @property {Hash} oldDimension If old dimension is not set, this property will be automatically calculated when execute the operation.
*/
Kekule.ChemObjOperation.MoveAndResize = Class.create(Kekule.ChemObjOperation.MoveTo,
/** @lends Kekule.ChemObjOperation.MoveAndResize# */
{
/** @private */
CLASS_NAME: 'Kekule.ChemObjOperation.MoveAndResize',
/** @constructs */
initialize: function($super, chemObj, newDimension, newCoord, coordMode, useAbsCoord)
{
$super(chemObj, newCoord, coordMode, useAbsCoord);
},
/** @private */
initProperties: function()
{
this.defineProp('newDimension', {'dataType': DataType.HASH});
this.defineProp('oldDimension', {'dataType': DataType.HASH});
},
/** @private */
setObjSize: function(obj, dimension, coordMode)
{
if (obj && dimension)
{
if (obj.setSizeOfMode)
{
obj.setSizeOfMode(dimension, coordMode);
}
else
{
var className = obj.getClassName? obj.getClassName(): (typeof obj);
Kekule.warn(/*Kekule.ErrorMsg.CAN_NOT_SET_DIMENSION_OF_CLASS*/Kekule.$L('ErrorMsg.CAN_NOT_SET_DIMENSION_OF_CLASS').format(className));
}
}
},
/** @private */
getObjSize: function(obj, coordMode)
{
if (obj.getSizeOfMode)
return obj.getSizeOfMode(coordMode, this.getAllowCoordBorrow());
else
return null;
},
/** @private */
doExecute: function($super)
{
$super();
var obj = this.getTarget();
if (!this.getOldDimension())
this.setOldDimension(this.getObjSize(obj, this.getCoordMode()));
if (this.getNewDimension())
this.setObjSize(this.getTarget(), this.getNewDimension(), this.getCoordMode());
},
/** @private */
doReverse: function($super)
{
if (this.getOldDimension())
this.setObjSize(this.getTarget(), this.getOldDimension(), this.getCoordMode());
$super();
}
});
/**
* Operation of adding a chem object to parent.
* @class
* @augments Kekule.ChemObjOperation.Base
*
* @param {Kekule.ChemObject} chemObject Target chem object.
* @param {Kekule.ChemObject} parentObj Object should be added to.
* @param {Kekule.ChemObject} refSibling If this property is set, chem object will be inserted before this sibling.
*
* @property {Kekule.ChemObject} parentObj Object should be added to.
* @property {Kekule.ChemObject} refSibling If this property is set, chem object will be inserted before this sibling.
*/
Kekule.ChemObjOperation.Add = Class.create(Kekule.ChemObjOperation.Base,
/** @lends Kekule.ChemObjOperation.Add# */
{
/** @private */
CLASS_NAME: 'Kekule.ChemObjOperation.Add',
/** @constructs */
initialize: function($super, chemObj, parentObj, refSibling)
{
$super(chemObj);
this.setParentObj(parentObj);
this.setRefSibling(refSibling);
},
/** @private */
initProperties: function()
{
this.defineProp('parentObj', {'dataType': 'Kekule.ChemObject', 'serializable': false});
this.defineProp('refSibling', {'dataType': 'Kekule.ChemObject', 'serializable': false});
},
/** @private */
doExecute: function()
{
var parent = this.getParentObj();
var obj = this.getTarget();
if (parent && obj)
{
var sibling = this.getRefSibling() || null;
parent.insertBefore(obj, sibling);
}
},
/** @private */
doReverse: function()
{
var obj = this.getTarget();
/*
var parent = obj.getParent? obj.getParent(): null;
if (!parent)
parent = this.getParentObj();
if (parent !== this.getParentObj())
console.log('[abnormal!!!!!!!]', parent.getId(), this.getParentObj().getId());
*/
var parent = this.getParentObj();
if (parent && obj)
{
var sibling = this.getRefSibling();
if (!sibling) // auto calc
{
sibling = obj.getNextSibling();
this.setRefSibling(sibling);
}
parent.removeChild(obj);
}
}
});
/**
* Operation of removing a chem object from its parent.
* @class
* @augments Kekule.ChemObjOperation.Base
*
* @param {Kekule.ChemObject} chemObject Target chem object.
* @param {Kekule.ChemObject} parentObj Object should be added to.
* @param {Kekule.ChemObject} refSibling Sibling after target object before removing.
*
* @property {Kekule.ChemObject} parentObj Object should be added to.
* @property {Kekule.ChemObject} refSibling Sibling after target object before removing.
* This property is used in reversing the operation. If not set, it will be calculated automatically in execution.
*/
Kekule.ChemObjOperation.Remove = Class.create(Kekule.ChemObjOperation.Base,
/** @lends Kekule.ChemObjOperation.Remove# */
{
/** @private */
CLASS_NAME: 'Kekule.ChemObjOperation.Remove',
/** @constructs */
initialize: function($super, chemObj, parentObj, refSibling)
{
$super(chemObj);
this.setParentObj(parentObj);
this.setRefSibling(refSibling);
},
/** @private */
initProperties: function()
{
this.defineProp('parentObj', {'dataType': 'Kekule.ChemObject', 'serializable': false});
this.defineProp('ownerObj', {'dataType': 'Kekule.ChemObject', 'serializable': false});
this.defineProp('refSibling', {'dataType': 'Kekule.ChemObject', 'serializable': false});
},
/** @private */
doExecute: function()
{
var obj = this.getTarget();
var parent = this.getParentObj();
var owner = this.getOwnerObj();
if (!parent && obj.getParent)
{
parent = obj.getParent();
this.setParentObj(parent);
}
if (!owner && obj.getOwner)
{
owner = obj.getOwner();
this.setOwnerObj(owner);
}
if (parent && obj)
{
if (!this.getRefSibling())
{
var sibling = obj.getNextSibling? obj.getNextSibling(): null;
this.setRefSibling(sibling);
}
//console.log('remove child', parent.getClassName(), obj.getClassName());
parent.removeChild(obj)
}
},
/** @private */
doReverse: function()
{
var parent = this.getParentObj();
var owner = this.getOwnerObj();
var obj = this.getTarget();
if (parent && obj)
{
var sibling = this.getRefSibling();
if (owner)
obj.setOwner(owner);
parent.insertBefore(obj, sibling);
}
}
});
/**
* A namespace for operation about Chem Structure instance.
* @namespace
*/
Kekule.ChemStructOperation = {};
/**
* Operation of adding a chem node to a structure fragment / molecule.
* @class
* @augments Kekule.ChemObjOperation.Add
*/
Kekule.ChemStructOperation.AddNode = Class.create(Kekule.ChemObjOperation.Add,
/** @lends Kekule.ChemStructOperation.AddNode# */
{
/** @private */
CLASS_NAME: 'Kekule.ChemStructOperation.AddNode'
});
/**
* Operation of removing a chem node from a structure fragment / molecule.
* @class
* @augments Kekule.ChemObjOperation.Remove
*
* @property {Array} linkedConnectors
*/
Kekule.ChemStructOperation.RemoveNode = Class.create(Kekule.ChemObjOperation.Remove,
/** @lends Kekule.ChemStructOperation.RemoveNode# */
{
/** @private */
CLASS_NAME: 'Kekule.ChemStructOperation.RemoveNode',
/** @private */
initProperties: function()
{
this.defineProp('linkedConnectors', {'dataType': DataType.ARRAY, 'serializable': false});
},
/** @private */
doExecute: function($super)
{
if (!this.getLinkedConnectors())
{
this.setLinkedConnectors(Kekule.ArrayUtils.clone(this.getTarget().getLinkedConnectors()));
}
$super()
},
/** @private */
doReverse: function($super)
{
$super();
var linkedConnectors = this.getLinkedConnectors();
//console.log('reverse node', this.getTarget().getId());
if (linkedConnectors && linkedConnectors.length)
{
//this.getTarget().setLinkedConnectors(linkedConnectors);
var target = this.getTarget();
//console.log('reverse append connector', linkedConnectors.length);
for (var i = 0, l = linkedConnectors.length; i < l; ++i)
{
//linkedConnectors[i].appendConnectedObj(target);
target.appendLinkedConnector(linkedConnectors[i]);
}
}
}
});
/**
* Operation of replace a chem node with another one.
* @class
* @augments Kekule.Operation
*/
Kekule.ChemStructOperation.ReplaceNode = Class.create(Kekule.Operation,
/** @lends Kekule.ChemStructOperation.ReplaceNode# */
{
/** @private */
CLASS_NAME: 'Kekule.ChemStructOperation.ReplaceNode',
/** @constructs */
initialize: function($super, oldNode, newNode, parentObj)
{
$super();
this.setOldNode(oldNode);
this.setNewNode(newNode);
this.setParentObj(parentObj);
},
/** @private */
initProperties: function()
{
this.defineProp('oldNode', {'dataType': 'Kekule.ChemStructureNode', 'serializable': false});
this.defineProp('newNode', {'dataType': 'Kekule.ChemStructureNode', 'serializable': false});
this.defineProp('parentObj', {'dataType': 'Kekule.ChemStructureFragment', 'serializable': false});
},
/** @private */
doExecute: function()
{
var oldNode = this.getOldNode();
var newNode = this.getNewNode();
if (oldNode && newNode)
{
var parent = this.getParentObj();
if (!parent)
{
parent = oldNode.getParent();
this.setParentObj(parent);
}
if (parent.replaceNode)
parent.replaceNode(oldNode, newNode);
}
},
/** @private */
doReverse: function()
{
var oldNode = this.getOldNode();
var newNode = this.getNewNode();
if (oldNode && newNode)
{
var parent = this.getParentObj() || newNode.getParent();
if (parent.replaceNode)
{
//console.log('reverse!');
parent.replaceNode(newNode, oldNode);
}
}
}
});
/**
* Operation of adding a chem connector to a structure fragment / molecule.
* @class
* @augments Kekule.ChemObjOperation.Add
*
* @param {Kekule.ChemObject} chemObject Target chem object.
* @param {Kekule.ChemObject} parentObj Object should be added to.
* @param {Kekule.ChemObject} refSibling If this property is set, chem object will be inserted before this sibling.
* @param {Array} connectedObjs Objects that connected by this connector.
*
* @property {Array} connectedObjs Objects that connected by this connector.
*/
Kekule.ChemStructOperation.AddConnector = Class.create(Kekule.ChemObjOperation.Add,
/** @lends Kekule.ChemStructOperation.AddConnector# */
{
/** @private */
CLASS_NAME: 'Kekule.ChemStructOperation.AddConnector',
/** @constructs */
initialize: function($super, chemObj, parentObj, refSibling, connectedObjs)
{
$super(chemObj);
this.setParentObj(parentObj);
this.setRefSibling(refSibling);
this.setConnectedObjs(connectedObjs);
},
/** @private */
initProperties: function()
{
this.defineProp('connectedObjs', {'dataType': DataType.ARRAY, 'serializable': false});
},
/** @private */
doExecute: function($super)
{
$super();
var connObjs = Kekule.ArrayUtils.clone(this.getConnectedObjs());
if (connObjs && connObjs.length)
{
this.getTarget().setConnectedObjs(connObjs);
}
},
/** @private */
doReverse: function($super)
{
$super();
}
});
/**
* Operation of removing a chem connector from a structure fragment / molecule.
* @class
* @augments Kekule.ChemObjOperation.Remove
*
* @property {Array} connectedObjs Objects that connected by this connector.
* This property is used in operation reversing. If not set, value will be automatically calculated in operation executing.
*/
Kekule.ChemStructOperation.RemoveConnector = Class.create(Kekule.ChemObjOperation.Remove,
/** @lends Kekule.ChemStructOperation.RemoveConnector# */
{
/** @private */
CLASS_NAME: 'Kekule.ChemStructOperation.RemoveConnector',
/** @private */
initProperties: function()
{
this.defineProp('connectedObjs', {'dataType': DataType.ARRAY, 'serializable': false});
},
/** @private */
doExecute: function($super)
{
if (!this.getConnectedObjs())
{
this.setConnectedObjs(Kekule.ArrayUtils.clone(this.getTarget().getConnectedObjs()));
}
$super()
},
/** @private */
doReverse: function($super)
{
$super();
var connObjs = this.getConnectedObjs();
if (connObjs && connObjs.length)
{
this.getTarget().setConnectedObjs(connObjs);
}
}
});
/**
* Operation of merging two nodes as one.
* @class
* @augments Kekule.ChemObjOperation.Base
*
* @param {Kekule.ChemStructureNode} target Source node, all connectors to this node will be connected to toNode.
* @param {Kekule.ChemStructureNode} dest Destination node.
* @param {Bool} enableStructFragmentMerge If true, molecule will be also merged when merging nodes between different molecule.
*
* @property {Kekule.ChemStructureNode} target Source node, all connectors to this node will be connected to toNode.
* @property {Kekule.ChemStructureNode} dest Destination node.
* @property {Array} changedConnectors Connectors modified during merge.
* @property {Array} removedConnectors Connectors removed during merge.
* @property {Bool} enableStructFragmentMerge If true, molecule will be also merged when merging nodes between different molecule.
*/
Kekule.ChemStructOperation.MergeNodes = Class.create(Kekule.ChemObjOperation.Base,
/** @lends Kekule.ChemStructOperation.MergeNodes# */
{
/** @private */
CLASS_NAME: 'Kekule.ChemStructOperation.MergeNodes',
/** @constructs */
initialize: function($super, target, dest, enableStructFragmentMerge)
{
$super(target);
this.setDest(dest);
this.setEnableStructFragmentMerge(enableStructFragmentMerge || false);
this._refSibling = null;
this._nodeParent = null;
this._structFragmentMergeOperation = null;
this._removeConnectorOperations = [];
},
/** @private */
initProperties: function()
{
this.defineProp('dest', {'dataType': 'Kekule.ChemStructureNode', 'serializable': false});
this.defineProp('changedConnectors', {'dataType': DataType.ARRAY, 'serializable': false});
this.defineProp('removedConnectors', {'dataType': DataType.ARRAY, 'serializable': false});
this.defineProp('enableStructFragmentMerge', {'dataType': DataType.BOOL});
},
/**
* Returns nodes connected with both node1 and node2.
* @param {Kekule.ChemStructureNode} node1
* @param {Kekule.ChemStructureNode} node2
* @returns {Array}
*/
getCommonSiblings: function(node1, node2)
{
var siblings1 = node1.getLinkedObjs();
var siblings2 = node2.getLinkedObjs();
return Kekule.ArrayUtils.intersect(siblings1, siblings2);
},
/** @private */
doExecute: function()
{
var fromNode = this.getTarget();
var toNode = this.getDest();
var structFragment = fromNode.getParent();
var destFragment = toNode.getParent();
if (structFragment !== destFragment) // from different molecule
{
//console.log('need merge mol');
if (this.getEnableStructFragmentMerge())
{
this._structFragmentMergeOperation = new Kekule.ChemStructOperation.MergeStructFragment(structFragment, destFragment);
//this._structFragmentMergeOperation = new Kekule.ChemStructOperation.MergeStructFragment(destFragment, structFragment);
this._structFragmentMergeOperation.execute();
structFragment = destFragment;
}
else
return null;
}
this._nodeParent = structFragment;
var removedConnectors = this.getRemovedConnectors();
if (!removedConnectors) // auto calc
{
var commonSiblings = this.getCommonSiblings(fromNode, toNode);
var removedConnectors = [];
if (commonSiblings.length) // has common sibling between from/toNode, bypass bond between fromNode and sibling
{
for (var i = 0, l = commonSiblings.length; i < l; ++i)
{
var sibling = commonSiblings[i];
var connector = fromNode.getConnectorTo(sibling);
if (connector && (connector.getConnectedObjCount() == 2))
removedConnectors.push(connector);
}
}
var directConnector = fromNode.getConnectorTo(toNode);
if (directConnector)
removedConnectors.push(directConnector);
this.setRemovedConnectors(removedConnectors);
}
var connectors = this.getChangedConnectors();
if (!connectors) // auto calc
{
var connectors = Kekule.ArrayUtils.clone(fromNode.getLinkedConnectors()) || [];
connectors = Kekule.ArrayUtils.exclude(connectors, removedConnectors);
this.setChangedConnectors(connectors);
}
// save fromNode's information
this._refSibling = fromNode.getNextSibling();
for (var i = 0, l = connectors.length; i < l; ++i)
{
var connector = connectors[i];
var index = connector.indexOfConnectedObj(fromNode);
connector.removeConnectedObj(fromNode);
connector.insertConnectedObjAt(toNode, index); // keep the index is important, wedge bond direction is related with node sequence
}
this._removeConnectorOperations = [];
for (var i = 0, l = removedConnectors.length; i < l; ++i)
{
var connector = removedConnectors[i];
var oper = new Kekule.ChemStructOperation.RemoveConnector(connector);
oper.execute();
this._removeConnectorOperations.push(oper);
}
structFragment.removeNode(fromNode);
},
/** @private */
doReverse: function()
{
var fromNode = this.getTarget();
var toNode = this.getDest();
//var structFragment = fromNode.getParent();
//var structFragment = toNode.getParent();
var structFragment = this._nodeParent;
/*
console.log(fromNode.getParent(), fromNode.getParent() === structFragment,
toNode.getParent(), toNode.getParent() === structFragment);
*/
structFragment.insertBefore(fromNode, this._refSibling);
if (this._removeConnectorOperations.length)
{
for (var i = this._removeConnectorOperations.length - 1; i >= 0; --i)
{
var oper = this._removeConnectorOperations[i];
oper.reverse();
}
}
this._removeConnectorOperations = [];
var connectors = this.getChangedConnectors();
//console.log('reverse node merge2', toNode, toNode.getParent());
for (var i = 0, l = connectors.length; i < l; ++i)
{
var connector = connectors[i];
var index = connector.indexOfConnectedObj(toNode);
connector.removeConnectedObj(toNode);
connector.insertConnectedObjAt(fromNode, index);
}
//console.log('reverse node merge', toNode, toNode.getParent());
if (this._structFragmentMergeOperation)
{
this._structFragmentMergeOperation.reverse();
}
}
});
/**
* A class method to check if two connectors can be merged
* @param {Kekule.ChemStructureNode} target
* @param {Kekule.ChemStructureNode} dest
* @param {Bool} canMergeStructFragment
* @returns {Bool}
*/
Kekule.ChemStructOperation.MergeNodes.canMerge = function(target, dest, canMergeStructFragment, canMergeNeighborNodes)
{
// never allow merge to another molecule point (e.g. formula molecule) or subgroup
if ((target instanceof Kekule.StructureFragment) || (dest instanceof Kekule.StructureFragment))
return false;
var targetFragment = target.getParent();
var destFragment = dest.getParent();
var result = (targetFragment === destFragment) || canMergeStructFragment;
if (!canMergeNeighborNodes)
result = result && (!target.getConnectorTo(dest));
return result;
};
/**
* Operation of merging two connectors as one.
* @class
* @augments Kekule.ChemObjOperation.Base
*
* @param {Kekule.ChemStructureConnector} target Source connector.
* @param {Kekule.ChemStructureConnector} dest Destination connector.
* @param {Int} coordMode Coord mode of current editor.
* @param {Bool} enableStructFragmentMerge If true, molecule will be also merged when merging connectors between different molecule.
*
* @property {Kekule.ChemStructureConnector} target Source connector.
* @property {Kekule.ChemStructureConnector} dest Destination connector.
* @property {Int} coordMode Coord mode of current editor.
* @property {Bool} enableStructFragmentMerge If true, molecule will be also merged when merging connectors between different molecule.
*/
Kekule.ChemStructOperation.MergeConnectors = Class.create(Kekule.ChemObjOperation.Base,
/** @lends Kekule.ChemStructOperation.MergeConnectors# */
{
/** @private */
CLASS_NAME: 'Kekule.ChemStructOperation.MergeConnectors',
/** @constructs */
initialize: function($super, target, dest, coordMode, enableStructFragmentMerge)
{
$super(target);
this.setDest(dest);
this.setCoordMode(coordMode || Kekule.CoordMode.COORD2D);
this.setEnableStructFragmentMerge(enableStructFragmentMerge || false);
this._refSibling = null;
this._nodeParent = null;
//this._structFragmentMergeOperation = null;
this._nodeMergeOperations = [];
},
/** @private */
initProperties: function()
{
this.defineProp('dest', {'dataType': 'Kekule.ChemStructureConnector', 'serializable': false});
this.defineProp('enableStructFragmentMerge', {'dataType': DataType.BOOL});
this.defineProp('coordMode', {'dataType': DataType.INT});
},
/** @private */
doExecute: function()
{
var canMerge = Kekule.ChemStructOperation.MergeConnectors.canMerge(this.getTarget(), this.getDest(), this.getEnableStructFragmentMerge());
/*
if (this.getTarget().isConnectingConnector() || this.getDest().isConnectingConnector())
{
Kekule.error(Kekule.ErrorMsg.CAN_NOT_MERGE_CONNECTOR_CONNECTED_WITH_CONNECTOR);
return;
}
var targetNodes = this.getTarget().getConnectedExposedObjs();
var destNodes = this.getDest().getConnectedObjs();
if (targetNodes.length !== destNodes.length)
{
Kekule.error(Kekule.ErrorMsg.CAN_NOT_MERGE_CONNECTOR_WITH_DIFF_NODECOUNT);
return;
}
if (targetNodes.length !== 2) // currently can only handle connector with 2 connected objects
{
Kekule.error(Kekule.ErrorMsg.CAN_NOT_MERGE_CONNECTOR_WITH_NODECOUNT_NOT_TWO);
return;
}
*/
if (!canMerge)
Kekule.error(/*Kekule.ErrorMsg.CAN_NOT_MERGE_CONNECTORS*/Kekule.$L('ErrorMsg.CAN_NOT_MERGE_CONNECTORS'));
// sort targetNodes and destNodes via coord
var coordMode = this.getCoordMode();
var connectors = [this.getTarget(), this.getDest()];
var AU = Kekule.ArrayUtils;
var targetNodes = AU.clone(this.getTarget().getConnectedObjs());
var destNodes = AU.clone(this.getDest().getConnectedObjs());
var allowCoordBorrow = this.getAllowCoordBorrow();
for (var i = 0, l = connectors.length; i < l; ++i)
{
var connector = connectors[i];
var coord1 = connector.getConnectedObjAt(0).getAbsCoordOfMode(coordMode, allowCoordBorrow);
var coord2 = connector.getConnectedObjAt(1).getAbsCoordOfMode(coordMode, allowCoordBorrow);
var coordDelta = Kekule.CoordUtils.substract(coord1, coord2);
var dominateDirection = Math.abs(coordDelta.x) > Math.abs(coordDelta.y)? 'x': 'y';
if (Kekule.ObjUtils.notUnset(coord1.z))
{
if (Math.abs(coordDelta.z) > Math.abs(coordDelta.x))
dominateDirection = 'z';
}
var nodes = (i === 0)? targetNodes: destNodes;
nodes.sort(function(a, b)
{
var coord1 = a.getAbsCoordOfMode(coordMode, allowCoordBorrow);
var coord2 = b.getAbsCoordOfMode(coordMode, allowCoordBorrow);
return (coord1[dominateDirection] - coord2[dominateDirection]) || 0;
}
);
}
var commonNodes = AU.intersect(targetNodes, destNodes);
targetNodes = AU.exclude(targetNodes, commonNodes);
destNodes = AU.exclude(destNodes, commonNodes);
this._nodeMergeOperations = [];
for (var i = 0, l = targetNodes.length; i < l; ++i)
{
if (targetNodes[i] !== destNodes[i])
{
var oper = new Kekule.ChemStructOperation.MergeNodes(targetNodes[i], destNodes[i], this.getEnableStructFragmentMerge());
oper.execute();
}
this._nodeMergeOperations.push(oper);
}
},
/** @private */
doReverse: function()
{
for (var i = this._nodeMergeOperations.length - 1; i >= 0; --i)
{
var oper = this._nodeMergeOperations[i];
oper.reverse();
}
this._nodeMergeOperations = [];
}
});
/**
* A class method to check if two connectors can be merged
* @param {Kekule.ChemStructureConnector} target
* @param {Kekule.ChemStructureConnector} dest
* @param {Bool} canMergeStructFragment
* @returns {Bool}
*/
Kekule.ChemStructOperation.MergeConnectors.canMerge = function(target, dest, canMergeStructFragment)
{
if (!canMergeStructFragment && (target.getParent() !== dest.getParent()))
return false;
if (target.isConnectingConnector() || dest.isConnectingConnector())
{
return false;
}
var targetNodes = target.getConnectedExposedObjs();
var destNodes = dest.getConnectedObjs();
if (targetNodes.length !== destNodes.length)
{
return false;
}
if (targetNodes.length !== 2) // currently can only handle connector with 2 connected objects
{
return false;
}
if (Kekule.ArrayUtils.intersect(targetNodes, destNodes).length >= 1)
{
return false;
}
return true;
};
/**
* Operation of merging two structure fragment as one.
* @class
* @augments Kekule.ChemObjOperation.Base
*
* @param {Kekule.StructureFragment} target Source fragment.
* @param {Kekule.StructureFragment} dest Destination fragment.
*
* @property {Kekule.StructureFragment} target Source fragment, all connectors and nodes will be moved to dest fragment.
* @property {Kekule.StructureFragment} dest Destination fragment.
* @property {Array} mergedNodes Nodes moved from target to dest during merging.
* @property {Array} mergedConnectors Connectors moved from target to dest during merging.
*/
Kekule.ChemStructOperation.MergeStructFragment = Class.create(Kekule.ChemObjOperation.Base,
/** @lends Kekule.ChemStructOperation.MergeStructFragment# */
{
/** @private */
CLASS_NAME: 'Kekule.ChemStructOperation.MergeStructFragment',
/** @constructs */
initialize: function($super, target, dest)
{
$super(target);
this.setDest(dest);
this._removeOperation = null;
},
/** @private */
initProperties: function()
{
this.defineProp('dest', {'dataType': 'Kekule.StructureFragment', 'serializable': false});
this.defineProp('mergedNodes', {'dataType': DataType.ARRAY, 'serializable': false});
this.defineProp('mergedConnectors', {'dataType': DataType.ARRAY, 'serializable': false});
},
/** @private */
moveChildBetweenStructFragment: function(target, dest, nodes, connectors)
{
Kekule.ChemStructureUtils.moveChildBetweenStructFragment(target, dest, nodes, connectors);
},
/** @private */
doExecute: function()
{
var target = this.getTarget();
var dest = this.getDest();
if (target && dest)
{
var nodes = Kekule.ArrayUtils.clone(target.getNodes());
this.setMergedNodes(nodes);
var connectors = Kekule.ArrayUtils.clone(target.getConnectors());
this.setMergedConnectors(connectors);
this.moveChildBetweenStructFragment(target, dest, nodes, connectors);
var parent = target.getParent();
if (parent) // remove target from parent
{
this._removeOperation = new Kekule.ChemObjOperation.Remove(target, parent);
this._removeOperation.execute();
}
}
},
/** @private */
doReverse: function()
{
var target = this.getTarget();
var dest = this.getDest();
if (target && dest)
{
if (this._removeOperation)
{
this._removeOperation.reverse();
this._removeOperation = null;
}
var nodes = this.getMergedNodes();
var connectors = this.getMergedConnectors();
/*
console.log('before mol merge reverse dest', dest.getNodeCount(), dest.getConnectorCount());
console.log('before mol merge reverse target', target.getNodeCount(), target.getConnectorCount());
console.log('reverse mol merge', nodes.length, connectors.length);
*/
this.moveChildBetweenStructFragment(dest, target, nodes, connectors);
/*
console.log('after mol merge reverse dest', dest.getNodeCount(), dest.getConnectorCount());
console.log('after mol merge reverse target', target.getNodeCount(), target.getConnectorCount());
*/
}
}
});
/**
* Operation of split one unconnected structure fragment into multiple connected ones.
* @class
* @augments Kekule.ChemObjOperation.Base
*
* @param {Kekule.StructureFragment} target.
*
* @property {Kekule.StructureFragment} target Source fragment, all connectors and nodes will be moved to dest fragment.
* @property {Array} splittedFragments Fragment splitted, this property will be automatically calculated in execution of operation.
*/
Kekule.ChemStructOperation.SplitStructFragment = Class.create(Kekule.ChemObjOperation.Base,
/** @lends Kekule.ChemStructOperation.SplitStructFragment# */
{
/** @private */
CLASS_NAME: 'Kekule.ChemStructOperation.SplitStructFragment',
/** @constructs */
initialize: function($super, target)
{
$super(target);
},
/** @private */
initProperties: function()
{
this.defineProp('splittedFragments', {'dataType': DataType.ARRAY, 'serializable': false, 'setter': null});
},
/** @private */
doExecute: function()
{
var splitted = Kekule.ChemStructureUtils.splitStructFragment(this.getTarget());
if (splitted.length > 1) // do really split
{
this.setPropStoreFieldValue('splittedFragments', splitted);
var parent = this.getTarget().getParent();
var ref = this.getTarget().getNextSibling();
parent.beginUpdate();
try
{
if (parent) // insert newly splitted fragments
{
for (var i = 1, l = splitted.length; i < l; ++i)
{
var frag = splitted[i];
parent.insertBefore(frag, ref);
}
}
}
finally
{
parent.endUpdate();
}
}
else // no real split actions done
{
this.setPropStoreFieldValue('splittedFragments', null);
}
},
/** @private */
doReverse: function()
{
var fragments = this.getSplittedFragments();
if (fragments && fragments.length)
{
var target = this.getTarget();
for (var i = 0, l = fragments.length; i < l; ++i)
{
var frag = fragments[i];
if (frag !== target)
{
Kekule.ChemStructureUtils.moveChildBetweenStructFragment(frag, target, Kekule.ArrayUtils.clone(frag.getNodes()), Kekule.ArrayUtils.clone(frag.getConnectors()));
var p = frag.getParent();
if (p)
p.removeChild(frag);
frag.finalize();
}
}
}
//console.log('split reverse done', target.getNodeCount(), target.getConnectorCount());
}
});
/**
* Split one unconnected structure fragment into multiple connected ones, or remove the fragment
* if the fragment contains no node.
* @class
* @augments Kekule.ChemObjOperation.Base
*
* @param {Kekule.StructureFragment} target.
*
* @property {Kekule.StructureFragment} target Source fragment.
* @property {Bool} enableRemove Whether allow remove empty structure fragment. Default is true.
* @property {Bool} enableSplit Whether allow splitting structure fragment. Default is true.
*/
Kekule.ChemStructOperation.StandardizeStructFragment = Class.create(Kekule.ChemObjOperation.Base,
/** @lends Kekule.ChemStructOperation.StandardizeStructFragment# */
{
/** @private */
CLASS_NAME: 'Kekule.ChemStructOperation.StandardizeStructFragment',
/** @constructs */
initialize: function($super, target)
{
$super(target);
this.setEnableSplit(true);
this.setEnableRemove(true);
this._concreteOper = null; // private
},
/** @private */
initProperties: function()
{
this.defineProp('enableRemove', {'dataType': DataType.BOOL});
this.defineProp('enableSplit', {'dataType': DataType.BOOL});
},
/** @private */
doExecute: function()
{
var target = this.getTarget();
var nodeCount = target.getNodeCount();
this._concreteOper = null;
if (nodeCount <= 0)
{
if (this.getEnableRemove())
this._concreteOper = new Kekule.ChemObjOperation.Remove(target);
}
else
{
if (this.getEnableSplit())
this._concreteOper = new Kekule.ChemStructOperation.SplitStructFragment(target);
}
if (this._concreteOper)
return this._concreteOper.execute();
else
return null;
},
/** @private */
doReverse: function()
{
return this._concreteOper? this._concreteOper.reverse(): null;
}
});
})();
|
src/widgets/chem/editor/kekule.chemEditor.operations.js
|
/**
* @fileoverview
* Operations need to implement an editor.
* @author Partridge Jiang
*/
/*
* requires /lan/classes.js
* requires /utils/kekule.utils.js
* requires /widgets/operation/kekule.operations.js
* requires /core/kekule.structures.js
* requires /widgets/chem/editor/kekule.chemEditor.baseEditors.js
* requires /localization/
*/
(function(){
"use strict";
/**
* A namespace for operation about normal ChemObject instance.
* @namespace
*/
Kekule.ChemObjOperation = {};
/**
* Base operation for ChemObject instance.
* @class
* @augments Kekule.Operation
*
* @param {Kekule.ChemObject} chemObject Target chem object.
*
* @property {Kekule.ChemObject} target Target chem object.
* @property {Bool} allowCoordBorrow Whether allow borrowing between 2D and 3D when manipulating coords.
*/
Kekule.ChemObjOperation.Base = Class.create(Kekule.Operation,
/** @lends Kekule.ChemObjOperation.Base# */
{
/** @private */
CLASS_NAME: 'Kekule.ChemObjOperation.Base',
/** @constructs */
initialize: function($super, chemObj)
{
$super();
this.setTarget(chemObj);
},
/** @private */
initProperties: function()
{
this.defineProp('target', {'dataType': 'Kekule.ChemObject', 'serializable': false});
this.defineProp('allowCoordBorrow', {'dataType': DataType.BOOL});
}
});
/**
* Operation of changing a chemObject's properties.
* @class
* @augments Kekule.ChemObjOperation.Base
*
* @param {Kekule.ChemObject} chemObject Target chem object.
* @param {Hash} newPropValues A hash of new prop-value map.
*
* @property {Hash} newPropValues A hash of new prop-value map.
*/
Kekule.ChemObjOperation.Modify = Class.create(Kekule.ChemObjOperation.Base,
/** @lends Kekule.ChemObjOperation.Modify# */
{
/** @private */
CLASS_NAME: 'Kekule.ChemObjOperation.Modify',
/** @constructs */
initialize: function($super, chemObj, newPropValues)
{
$super(chemObj);
if (newPropValues)
this.setNewPropValues(newPropValues);
},
/** @private */
initProperties: function()
{
this.defineProp('newPropValues', {'dataType': DataType.HASH});
this.defineProp('oldPropValues', {'dataType': DataType.HASH}); // private
},
/** @private */
doExecute: function()
{
var oldValues = {};
var map = this.getNewPropValues();
var obj = this.getTarget();
for (var prop in map)
{
var value = map[prop];
// store old value first
oldValues[prop] = obj.getPropValue(prop);
// set new value
obj.setPropValue(prop, value);
}
this.setOldPropValues(oldValues);
},
/** @private */
doReverse: function()
{
var map = this.getOldPropValues();
var obj = this.getTarget();
for (var prop in map)
{
var value = map[prop];
// restore old value
obj.setPropValue(prop, value);
}
}
});
/**
* Operation of changing a chemObject's coord.
* @class
* @augments Kekule.ChemObjOperation.Base
*
* @param {Kekule.ChemObject} chemObject Target chem object.
* @param {Hash} newCoord
* @param {Int} coordMode
* @param {Bool} useAbsCoord
*
* @property {Hash} newCoord
* @property {Hash} oldCoord If old coord is not set, this property will be automatically calculated when execute the operation.
* @property {Int} coordMode
* @property {Bool} useAbsCoord
*/
Kekule.ChemObjOperation.MoveTo = Class.create(Kekule.ChemObjOperation.Base,
/** @lends Kekule.ChemObjOperation.MoveTo# */
{
/** @private */
CLASS_NAME: 'Kekule.ChemObjOperation.MoveTo',
/** @constructs */
initialize: function($super, chemObj, newCoord, coordMode, useAbsCoord)
{
$super(chemObj);
if (newCoord)
this.setNewCoord(newCoord);
this.setCoordMode(coordMode || Kekule.CoordMode.COORD2D);
this.setUseAbsCoord(!!useAbsCoord);
},
/** @private */
initProperties: function()
{
this.defineProp('newCoord', {'dataType': DataType.HASH});
this.defineProp('oldCoord', {'dataType': DataType.HASH});
this.defineProp('coordMode', {'dataType': DataType.INT});
this.defineProp('useAbsCoord', {'dataType': DataType.BOOL});
},
/** @private */
setObjCoord: function(obj, coord, coordMode)
{
if (obj && coord && coordMode)
{
var success = false;
if (this.getUseAbsCoord())
{
if (obj.setAbsCoordOfMode)
{
obj.setAbsCoordOfMode(coord, coordMode);
success = true;
}
}
else
{
if (obj.setCoordOfMode)
{
obj.setCoordOfMode(coord, coordMode);
success = true;
}
}
if (!success)
{
var className = obj.getClassName? obj.getClassName(): (typeof obj);
Kekule.warn(/*Kekule.ErrorMsg.CAN_NOT_SET_COORD_OF_CLASS*/Kekule.$L('ErrorMsg.CAN_NOT_SET_COORD_OF_CLASS').format(className));
}
}
},
/** @private */
getObjCoord: function(obj, coordMode)
{
if (this.getUseAbsCoord())
{
if (obj.getAbsCoordOfMode)
return obj.getAbsCoordOfMode(coordMode, this.getAllowCoordBorrow());
}
else
{
if (obj.getCoordOfMode)
return obj.getCoordOfMode(coordMode, this.getAllowCoordBorrow());
}
return null;
},
/** @private */
doExecute: function()
{
var obj = this.getTarget();
if (!this.getOldCoord())
this.setOldCoord(this.getObjCoord(obj, this.getCoordMode()));
if (this.getNewCoord())
this.setObjCoord(this.getTarget(), this.getNewCoord(), this.getCoordMode());
},
/** @private */
doReverse: function()
{
if (this.getOldCoord())
{
this.setObjCoord(this.getTarget(), this.getOldCoord(), this.getCoordMode());
}
}
});
/**
* Operation of changing a chem object's size and coord.
* @class
* @augments Kekule.ChemObjOperation.MoveTo
*
* @param {Kekule.ChemObject} chemObject Target chem object.
* @param {Hash} newDimension {width, height}
* @param {Hash} newCoord
* @param {Int} coordMode
* @param {Bool} useAbsCoord
*
* @property {Hash} newDimension
* @property {Hash} oldDimension If old dimension is not set, this property will be automatically calculated when execute the operation.
*/
Kekule.ChemObjOperation.MoveAndResize = Class.create(Kekule.ChemObjOperation.MoveTo,
/** @lends Kekule.ChemObjOperation.MoveAndResize# */
{
/** @private */
CLASS_NAME: 'Kekule.ChemObjOperation.MoveAndResize',
/** @constructs */
initialize: function($super, chemObj, newDimension, newCoord, coordMode, useAbsCoord)
{
$super(chemObj, newCoord, coordMode, useAbsCoord);
},
/** @private */
initProperties: function()
{
this.defineProp('newDimension', {'dataType': DataType.HASH});
this.defineProp('oldDimension', {'dataType': DataType.HASH});
},
/** @private */
setObjSize: function(obj, dimension, coordMode)
{
if (obj && dimension)
{
if (obj.setSizeOfMode)
{
obj.setSizeOfMode(dimension, coordMode);
}
else
{
var className = obj.getClassName? obj.getClassName(): (typeof obj);
Kekule.warn(/*Kekule.ErrorMsg.CAN_NOT_SET_DIMENSION_OF_CLASS*/Kekule.$L('ErrorMsg.CAN_NOT_SET_DIMENSION_OF_CLASS').format(className));
}
}
},
/** @private */
getObjSize: function(obj, coordMode)
{
if (obj.getSizeOfMode)
return obj.getSizeOfMode(coordMode, this.getAllowCoordBorrow());
else
return null;
},
/** @private */
doExecute: function($super)
{
$super();
var obj = this.getTarget();
if (!this.getOldDimension())
this.setOldDimension(this.getObjSize(obj, this.getCoordMode()));
if (this.getNewDimension())
this.setObjSize(this.getTarget(), this.getNewDimension(), this.getCoordMode());
},
/** @private */
doReverse: function($super)
{
if (this.getOldDimension())
this.setObjSize(this.getTarget(), this.getOldDimension(), this.getCoordMode());
$super();
}
});
/**
* Operation of adding a chem object to parent.
* @class
* @augments Kekule.ChemObjOperation.Base
*
* @param {Kekule.ChemObject} chemObject Target chem object.
* @param {Kekule.ChemObject} parentObj Object should be added to.
* @param {Kekule.ChemObject} refSibling If this property is set, chem object will be inserted before this sibling.
*
* @property {Kekule.ChemObject} parentObj Object should be added to.
* @property {Kekule.ChemObject} refSibling If this property is set, chem object will be inserted before this sibling.
*/
Kekule.ChemObjOperation.Add = Class.create(Kekule.ChemObjOperation.Base,
/** @lends Kekule.ChemObjOperation.Add# */
{
/** @private */
CLASS_NAME: 'Kekule.ChemObjOperation.Add',
/** @constructs */
initialize: function($super, chemObj, parentObj, refSibling)
{
$super(chemObj);
this.setParentObj(parentObj);
this.setRefSibling(refSibling);
},
/** @private */
initProperties: function()
{
this.defineProp('parentObj', {'dataType': 'Kekule.ChemObject', 'serializable': false});
this.defineProp('refSibling', {'dataType': 'Kekule.ChemObject', 'serializable': false});
},
/** @private */
doExecute: function()
{
var parent = this.getParentObj();
var obj = this.getTarget();
if (parent && obj)
{
var sibling = this.getRefSibling() || null;
parent.insertBefore(obj, sibling);
}
},
/** @private */
doReverse: function()
{
var obj = this.getTarget();
/*
var parent = obj.getParent? obj.getParent(): null;
if (!parent)
parent = this.getParentObj();
if (parent !== this.getParentObj())
console.log('[abnormal!!!!!!!]', parent.getId(), this.getParentObj().getId());
*/
var parent = this.getParentObj();
if (parent && obj)
{
var sibling = this.getRefSibling();
if (!sibling) // auto calc
{
sibling = obj.getNextSibling();
this.setRefSibling(sibling);
}
parent.removeChild(obj);
}
}
});
/**
* Operation of removing a chem object from its parent.
* @class
* @augments Kekule.ChemObjOperation.Base
*
* @param {Kekule.ChemObject} chemObject Target chem object.
* @param {Kekule.ChemObject} parentObj Object should be added to.
* @param {Kekule.ChemObject} refSibling Sibling after target object before removing.
*
* @property {Kekule.ChemObject} parentObj Object should be added to.
* @property {Kekule.ChemObject} refSibling Sibling after target object before removing.
* This property is used in reversing the operation. If not set, it will be calculated automatically in execution.
*/
Kekule.ChemObjOperation.Remove = Class.create(Kekule.ChemObjOperation.Base,
/** @lends Kekule.ChemObjOperation.Remove# */
{
/** @private */
CLASS_NAME: 'Kekule.ChemObjOperation.Remove',
/** @constructs */
initialize: function($super, chemObj, parentObj, refSibling)
{
$super(chemObj);
this.setParentObj(parentObj);
this.setRefSibling(refSibling);
},
/** @private */
initProperties: function()
{
this.defineProp('parentObj', {'dataType': 'Kekule.ChemObject', 'serializable': false});
this.defineProp('ownerObj', {'dataType': 'Kekule.ChemObject', 'serializable': false});
this.defineProp('refSibling', {'dataType': 'Kekule.ChemObject', 'serializable': false});
},
/** @private */
doExecute: function()
{
var obj = this.getTarget();
var parent = this.getParentObj();
var owner = this.getOwnerObj();
if (!parent && obj.getParent)
{
parent = obj.getParent();
this.setParentObj(parent);
}
if (!owner && obj.getOwner)
{
owner = obj.getOwner();
this.setOwnerObj(owner);
}
if (parent && obj)
{
if (!this.getRefSibling())
{
var sibling = obj.getNextSibling? obj.getNextSibling(): null;
this.setRefSibling(sibling);
}
//console.log('remove child', parent.getClassName(), obj.getClassName());
parent.removeChild(obj)
}
},
/** @private */
doReverse: function()
{
var parent = this.getParentObj();
var owner = this.getOwnerObj();
var obj = this.getTarget();
if (parent && obj)
{
var sibling = this.getRefSibling();
if (owner)
obj.setOwner(owner);
parent.insertBefore(obj, sibling);
}
}
});
/**
* A namespace for operation about Chem Structure instance.
* @namespace
*/
Kekule.ChemStructOperation = {};
/**
* Operation of adding a chem node to a structure fragment / molecule.
* @class
* @augments Kekule.ChemObjOperation.Add
*/
Kekule.ChemStructOperation.AddNode = Class.create(Kekule.ChemObjOperation.Add,
/** @lends Kekule.ChemStructOperation.AddNode# */
{
/** @private */
CLASS_NAME: 'Kekule.ChemStructOperation.AddNode'
});
/**
* Operation of removing a chem node from a structure fragment / molecule.
* @class
* @augments Kekule.ChemObjOperation.Remove
*
* @property {Array} linkedConnectors
*/
Kekule.ChemStructOperation.RemoveNode = Class.create(Kekule.ChemObjOperation.Remove,
/** @lends Kekule.ChemStructOperation.RemoveNode# */
{
/** @private */
CLASS_NAME: 'Kekule.ChemStructOperation.RemoveNode',
/** @private */
initProperties: function()
{
this.defineProp('linkedConnectors', {'dataType': DataType.ARRAY, 'serializable': false});
},
/** @private */
doExecute: function($super)
{
if (!this.getLinkedConnectors())
{
this.setLinkedConnectors(Kekule.ArrayUtils.clone(this.getTarget().getLinkedConnectors()));
}
$super()
},
/** @private */
doReverse: function($super)
{
$super();
var linkedConnectors = this.getLinkedConnectors();
//console.log('reverse node', this.getTarget().getId());
if (linkedConnectors && linkedConnectors.length)
{
//this.getTarget().setLinkedConnectors(linkedConnectors);
var target = this.getTarget();
//console.log('reverse append connector', linkedConnectors.length);
for (var i = 0, l = linkedConnectors.length; i < l; ++i)
{
//linkedConnectors[i].appendConnectedObj(target);
target.appendLinkedConnector(linkedConnectors[i]);
}
}
}
});
/**
* Operation of replace a chem node with another one.
* @class
* @augments Kekule.Operation
*/
Kekule.ChemStructOperation.ReplaceNode = Class.create(Kekule.Operation,
/** @lends Kekule.ChemStructOperation.ReplaceNode# */
{
/** @private */
CLASS_NAME: 'Kekule.ChemStructOperation.ReplaceNode',
/** @constructs */
initialize: function($super, oldNode, newNode, parentObj)
{
$super();
this.setOldNode(oldNode);
this.setNewNode(newNode);
this.setParentObj(parentObj);
},
/** @private */
initProperties: function()
{
this.defineProp('oldNode', {'dataType': 'Kekule.ChemStructureNode', 'serializable': false});
this.defineProp('newNode', {'dataType': 'Kekule.ChemStructureNode', 'serializable': false});
this.defineProp('parentObj', {'dataType': 'Kekule.ChemStructureFragment', 'serializable': false});
},
/** @private */
doExecute: function()
{
var oldNode = this.getOldNode();
var newNode = this.getNewNode();
if (oldNode && newNode)
{
var parent = this.getParentObj();
if (!parent)
{
parent = oldNode.getParent();
this.setParentObj(parent);
}
if (parent.replaceNode)
parent.replaceNode(oldNode, newNode);
}
},
/** @private */
doReverse: function()
{
var oldNode = this.getOldNode();
var newNode = this.getNewNode();
if (oldNode && newNode)
{
var parent = this.getParentObj() || newNode.getParent();
if (parent.replaceNode)
{
//console.log('reverse!');
parent.replaceNode(newNode, oldNode);
}
}
}
});
/**
* Operation of adding a chem connector to a structure fragment / molecule.
* @class
* @augments Kekule.ChemObjOperation.Add
*
* @param {Kekule.ChemObject} chemObject Target chem object.
* @param {Kekule.ChemObject} parentObj Object should be added to.
* @param {Kekule.ChemObject} refSibling If this property is set, chem object will be inserted before this sibling.
* @param {Array} connectedObjs Objects that connected by this connector.
*
* @property {Array} connectedObjs Objects that connected by this connector.
*/
Kekule.ChemStructOperation.AddConnector = Class.create(Kekule.ChemObjOperation.Add,
/** @lends Kekule.ChemStructOperation.AddConnector# */
{
/** @private */
CLASS_NAME: 'Kekule.ChemStructOperation.AddConnector',
/** @constructs */
initialize: function($super, chemObj, parentObj, refSibling, connectedObjs)
{
$super(chemObj);
this.setParentObj(parentObj);
this.setRefSibling(refSibling);
this.setConnectedObjs(connectedObjs);
},
/** @private */
initProperties: function()
{
this.defineProp('connectedObjs', {'dataType': DataType.ARRAY, 'serializable': false});
},
/** @private */
doExecute: function($super)
{
$super();
var connObjs = Kekule.ArrayUtils.clone(this.getConnectedObjs());
if (connObjs && connObjs.length)
{
this.getTarget().setConnectedObjs(connObjs);
}
},
/** @private */
doReverse: function($super)
{
$super();
}
});
/**
* Operation of removing a chem connector from a structure fragment / molecule.
* @class
* @augments Kekule.ChemObjOperation.Remove
*
* @property {Array} connectedObjs Objects that connected by this connector.
* This property is used in operation reversing. If not set, value will be automatically calculated in operation executing.
*/
Kekule.ChemStructOperation.RemoveConnector = Class.create(Kekule.ChemObjOperation.Remove,
/** @lends Kekule.ChemStructOperation.RemoveConnector# */
{
/** @private */
CLASS_NAME: 'Kekule.ChemStructOperation.RemoveConnector',
/** @private */
initProperties: function()
{
this.defineProp('connectedObjs', {'dataType': DataType.ARRAY, 'serializable': false});
},
/** @private */
doExecute: function($super)
{
if (!this.getConnectedObjs())
{
this.setConnectedObjs(Kekule.ArrayUtils.clone(this.getTarget().getConnectedObjs()));
}
$super()
},
/** @private */
doReverse: function($super)
{
$super();
var connObjs = this.getConnectedObjs();
if (connObjs && connObjs.length)
{
this.getTarget().setConnectedObjs(connObjs);
}
}
});
/**
* Operation of merging two nodes as one.
* @class
* @augments Kekule.ChemObjOperation.Base
*
* @param {Kekule.ChemStructureNode} target Source node, all connectors to this node will be connected to toNode.
* @param {Kekule.ChemStructureNode} dest Destination node.
* @param {Bool} enableStructFragmentMerge If true, molecule will be also merged when merging nodes between different molecule.
*
* @property {Kekule.ChemStructureNode} target Source node, all connectors to this node will be connected to toNode.
* @property {Kekule.ChemStructureNode} dest Destination node.
* @property {Array} changedConnectors Connectors modified during merge.
* @property {Array} removedConnectors Connectors removed during merge.
* @property {Bool} enableStructFragmentMerge If true, molecule will be also merged when merging nodes between different molecule.
*/
Kekule.ChemStructOperation.MergeNodes = Class.create(Kekule.ChemObjOperation.Base,
/** @lends Kekule.ChemStructOperation.MergeNodes# */
{
/** @private */
CLASS_NAME: 'Kekule.ChemStructOperation.MergeNodes',
/** @constructs */
initialize: function($super, target, dest, enableStructFragmentMerge)
{
$super(target);
this.setDest(dest);
this.setEnableStructFragmentMerge(enableStructFragmentMerge || false);
this._refSibling = null;
this._nodeParent = null;
this._structFragmentMergeOperation = null;
this._removeConnectorOperations = [];
},
/** @private */
initProperties: function()
{
this.defineProp('dest', {'dataType': 'Kekule.ChemStructureNode', 'serializable': false});
this.defineProp('changedConnectors', {'dataType': DataType.ARRAY, 'serializable': false});
this.defineProp('removedConnectors', {'dataType': DataType.ARRAY, 'serializable': false});
this.defineProp('enableStructFragmentMerge', {'dataType': DataType.BOOL});
},
/**
* Returns nodes connected with both node1 and node2.
* @param {Kekule.ChemStructureNode} node1
* @param {Kekule.ChemStructureNode} node2
* @returns {Array}
*/
getCommonSiblings: function(node1, node2)
{
var siblings1 = node1.getLinkedObjs();
var siblings2 = node2.getLinkedObjs();
return Kekule.ArrayUtils.intersect(siblings1, siblings2);
},
/** @private */
doExecute: function()
{
var fromNode = this.getTarget();
var toNode = this.getDest();
var structFragment = fromNode.getParent();
var destFragment = toNode.getParent();
if (structFragment !== destFragment) // from different molecule
{
//console.log('need merge mol');
if (this.getEnableStructFragmentMerge())
{
this._structFragmentMergeOperation = new Kekule.ChemStructOperation.MergeStructFragment(structFragment, destFragment);
//this._structFragmentMergeOperation = new Kekule.ChemStructOperation.MergeStructFragment(destFragment, structFragment);
this._structFragmentMergeOperation.execute();
structFragment = destFragment;
}
else
return null;
}
this._nodeParent = structFragment;
var removedConnectors = this.getRemovedConnectors();
if (!removedConnectors) // auto calc
{
var commonSiblings = this.getCommonSiblings(fromNode, toNode);
var removedConnectors = [];
if (commonSiblings.length) // has common sibling between from/toNode, bypass bond between fromNode and sibling
{
for (var i = 0, l = commonSiblings.length; i < l; ++i)
{
var sibling = commonSiblings[i];
var connector = fromNode.getConnectorTo(sibling);
if (connector && (connector.getConnectedObjCount() == 2))
removedConnectors.push(connector);
}
}
var directConnector = fromNode.getConnectorTo(toNode);
if (directConnector)
removedConnectors.push(directConnector);
this.setRemovedConnectors(removedConnectors);
}
var connectors = this.getChangedConnectors();
if (!connectors) // auto calc
{
var connectors = Kekule.ArrayUtils.clone(fromNode.getLinkedConnectors()) || [];
connectors = Kekule.ArrayUtils.exclude(connectors, removedConnectors);
this.setChangedConnectors(connectors);
}
// save fromNode's information
this._refSibling = fromNode.getNextSibling();
for (var i = 0, l = connectors.length; i < l; ++i)
{
var connector = connectors[i];
var index = connector.indexOfConnectedObj(fromNode);
connector.removeConnectedObj(fromNode);
connector.insertConnectedObjAt(toNode, index); // keep the index is important, wedge bond direction is related with node sequence
}
this._removeConnectorOperations = [];
for (var i = 0, l = removedConnectors.length; i < l; ++i)
{
var connector = removedConnectors[i];
var oper = new Kekule.ChemStructOperation.RemoveConnector(connector);
oper.execute();
this._removeConnectorOperations.push(oper);
}
structFragment.removeNode(fromNode);
},
/** @private */
doReverse: function()
{
var fromNode = this.getTarget();
var toNode = this.getDest();
//var structFragment = fromNode.getParent();
//var structFragment = toNode.getParent();
var structFragment = this._nodeParent;
/*
console.log(fromNode.getParent(), fromNode.getParent() === structFragment,
toNode.getParent(), toNode.getParent() === structFragment);
*/
structFragment.insertBefore(fromNode, this._refSibling);
if (this._removeConnectorOperations.length)
{
for (var i = this._removeConnectorOperations.length - 1; i >= 0; --i)
{
var oper = this._removeConnectorOperations[i];
oper.reverse();
}
}
this._removeConnectorOperations = [];
var connectors = this.getChangedConnectors();
//console.log('reverse node merge2', toNode, toNode.getParent());
for (var i = 0, l = connectors.length; i < l; ++i)
{
var connector = connectors[i];
var index = connector.indexOfConnectedObj(toNode);
connector.removeConnectedObj(toNode);
connector.insertConnectedObjAt(fromNode, index);
}
//console.log('reverse node merge', toNode, toNode.getParent());
if (this._structFragmentMergeOperation)
{
this._structFragmentMergeOperation.reverse();
}
}
});
/**
* A class method to check if two connectors can be merged
* @param {Kekule.ChemStructureNode} target
* @param {Kekule.ChemStructureNode} dest
* @param {Bool} canMergeStructFragment
* @returns {Bool}
*/
Kekule.ChemStructOperation.MergeNodes.canMerge = function(target, dest, canMergeStructFragment, canMergeNeighborNodes)
{
var targetFragment = target.getParent();
var destFragment = dest.getParent();
var result = (targetFragment === destFragment) || canMergeStructFragment;
if (!canMergeNeighborNodes)
result = result && (!target.getConnectorTo(dest))
return result;
};
/**
* Operation of merging two connectors as one.
* @class
* @augments Kekule.ChemObjOperation.Base
*
* @param {Kekule.ChemStructureConnector} target Source connector.
* @param {Kekule.ChemStructureConnector} dest Destination connector.
* @param {Int} coordMode Coord mode of current editor.
* @param {Bool} enableStructFragmentMerge If true, molecule will be also merged when merging connectors between different molecule.
*
* @property {Kekule.ChemStructureConnector} target Source connector.
* @property {Kekule.ChemStructureConnector} dest Destination connector.
* @property {Int} coordMode Coord mode of current editor.
* @property {Bool} enableStructFragmentMerge If true, molecule will be also merged when merging connectors between different molecule.
*/
Kekule.ChemStructOperation.MergeConnectors = Class.create(Kekule.ChemObjOperation.Base,
/** @lends Kekule.ChemStructOperation.MergeConnectors# */
{
/** @private */
CLASS_NAME: 'Kekule.ChemStructOperation.MergeConnectors',
/** @constructs */
initialize: function($super, target, dest, coordMode, enableStructFragmentMerge)
{
$super(target);
this.setDest(dest);
this.setCoordMode(coordMode || Kekule.CoordMode.COORD2D);
this.setEnableStructFragmentMerge(enableStructFragmentMerge || false);
this._refSibling = null;
this._nodeParent = null;
//this._structFragmentMergeOperation = null;
this._nodeMergeOperations = [];
},
/** @private */
initProperties: function()
{
this.defineProp('dest', {'dataType': 'Kekule.ChemStructureConnector', 'serializable': false});
this.defineProp('enableStructFragmentMerge', {'dataType': DataType.BOOL});
this.defineProp('coordMode', {'dataType': DataType.INT});
},
/** @private */
doExecute: function()
{
var canMerge = Kekule.ChemStructOperation.MergeConnectors.canMerge(this.getTarget(), this.getDest(), this.getEnableStructFragmentMerge());
/*
if (this.getTarget().isConnectingConnector() || this.getDest().isConnectingConnector())
{
Kekule.error(Kekule.ErrorMsg.CAN_NOT_MERGE_CONNECTOR_CONNECTED_WITH_CONNECTOR);
return;
}
var targetNodes = this.getTarget().getConnectedExposedObjs();
var destNodes = this.getDest().getConnectedObjs();
if (targetNodes.length !== destNodes.length)
{
Kekule.error(Kekule.ErrorMsg.CAN_NOT_MERGE_CONNECTOR_WITH_DIFF_NODECOUNT);
return;
}
if (targetNodes.length !== 2) // currently can only handle connector with 2 connected objects
{
Kekule.error(Kekule.ErrorMsg.CAN_NOT_MERGE_CONNECTOR_WITH_NODECOUNT_NOT_TWO);
return;
}
*/
if (!canMerge)
Kekule.error(/*Kekule.ErrorMsg.CAN_NOT_MERGE_CONNECTORS*/Kekule.$L('ErrorMsg.CAN_NOT_MERGE_CONNECTORS'));
// sort targetNodes and destNodes via coord
var coordMode = this.getCoordMode();
var connectors = [this.getTarget(), this.getDest()];
var AU = Kekule.ArrayUtils;
var targetNodes = AU.clone(this.getTarget().getConnectedObjs());
var destNodes = AU.clone(this.getDest().getConnectedObjs());
var allowCoordBorrow = this.getAllowCoordBorrow();
for (var i = 0, l = connectors.length; i < l; ++i)
{
var connector = connectors[i];
var coord1 = connector.getConnectedObjAt(0).getAbsCoordOfMode(coordMode, allowCoordBorrow);
var coord2 = connector.getConnectedObjAt(1).getAbsCoordOfMode(coordMode, allowCoordBorrow);
var coordDelta = Kekule.CoordUtils.substract(coord1, coord2);
var dominateDirection = Math.abs(coordDelta.x) > Math.abs(coordDelta.y)? 'x': 'y';
if (Kekule.ObjUtils.notUnset(coord1.z))
{
if (Math.abs(coordDelta.z) > Math.abs(coordDelta.x))
dominateDirection = 'z';
}
var nodes = (i === 0)? targetNodes: destNodes;
nodes.sort(function(a, b)
{
var coord1 = a.getAbsCoordOfMode(coordMode, allowCoordBorrow);
var coord2 = b.getAbsCoordOfMode(coordMode, allowCoordBorrow);
return (coord1[dominateDirection] - coord2[dominateDirection]) || 0;
}
);
}
var commonNodes = AU.intersect(targetNodes, destNodes);
targetNodes = AU.exclude(targetNodes, commonNodes);
destNodes = AU.exclude(destNodes, commonNodes);
this._nodeMergeOperations = [];
for (var i = 0, l = targetNodes.length; i < l; ++i)
{
if (targetNodes[i] !== destNodes[i])
{
var oper = new Kekule.ChemStructOperation.MergeNodes(targetNodes[i], destNodes[i], this.getEnableStructFragmentMerge());
oper.execute();
}
this._nodeMergeOperations.push(oper);
}
},
/** @private */
doReverse: function()
{
for (var i = this._nodeMergeOperations.length - 1; i >= 0; --i)
{
var oper = this._nodeMergeOperations[i];
oper.reverse();
}
this._nodeMergeOperations = [];
}
});
/**
* A class method to check if two connectors can be merged
* @param {Kekule.ChemStructureConnector} target
* @param {Kekule.ChemStructureConnector} dest
* @param {Bool} canMergeStructFragment
* @returns {Bool}
*/
Kekule.ChemStructOperation.MergeConnectors.canMerge = function(target, dest, canMergeStructFragment)
{
if (!canMergeStructFragment && (target.getParent() !== dest.getParent()))
return false;
if (target.isConnectingConnector() || dest.isConnectingConnector())
{
return false;
}
var targetNodes = target.getConnectedExposedObjs();
var destNodes = dest.getConnectedObjs();
if (targetNodes.length !== destNodes.length)
{
return false;
}
if (targetNodes.length !== 2) // currently can only handle connector with 2 connected objects
{
return false;
}
if (Kekule.ArrayUtils.intersect(targetNodes, destNodes).length >= 1)
{
return false;
}
return true;
};
/**
* Operation of merging two structure fragment as one.
* @class
* @augments Kekule.ChemObjOperation.Base
*
* @param {Kekule.StructureFragment} target Source fragment.
* @param {Kekule.StructureFragment} dest Destination fragment.
*
* @property {Kekule.StructureFragment} target Source fragment, all connectors and nodes will be moved to dest fragment.
* @property {Kekule.StructureFragment} dest Destination fragment.
* @property {Array} mergedNodes Nodes moved from target to dest during merging.
* @property {Array} mergedConnectors Connectors moved from target to dest during merging.
*/
Kekule.ChemStructOperation.MergeStructFragment = Class.create(Kekule.ChemObjOperation.Base,
/** @lends Kekule.ChemStructOperation.MergeStructFragment# */
{
/** @private */
CLASS_NAME: 'Kekule.ChemStructOperation.MergeStructFragment',
/** @constructs */
initialize: function($super, target, dest)
{
$super(target);
this.setDest(dest);
this._removeOperation = null;
},
/** @private */
initProperties: function()
{
this.defineProp('dest', {'dataType': 'Kekule.StructureFragment', 'serializable': false});
this.defineProp('mergedNodes', {'dataType': DataType.ARRAY, 'serializable': false});
this.defineProp('mergedConnectors', {'dataType': DataType.ARRAY, 'serializable': false});
},
/** @private */
moveChildBetweenStructFragment: function(target, dest, nodes, connectors)
{
Kekule.ChemStructureUtils.moveChildBetweenStructFragment(target, dest, nodes, connectors);
},
/** @private */
doExecute: function()
{
var target = this.getTarget();
var dest = this.getDest();
if (target && dest)
{
var nodes = Kekule.ArrayUtils.clone(target.getNodes());
this.setMergedNodes(nodes);
var connectors = Kekule.ArrayUtils.clone(target.getConnectors());
this.setMergedConnectors(connectors);
this.moveChildBetweenStructFragment(target, dest, nodes, connectors);
var parent = target.getParent();
if (parent) // remove target from parent
{
this._removeOperation = new Kekule.ChemObjOperation.Remove(target, parent);
this._removeOperation.execute();
}
}
},
/** @private */
doReverse: function()
{
var target = this.getTarget();
var dest = this.getDest();
if (target && dest)
{
if (this._removeOperation)
{
this._removeOperation.reverse();
this._removeOperation = null;
}
var nodes = this.getMergedNodes();
var connectors = this.getMergedConnectors();
/*
console.log('before mol merge reverse dest', dest.getNodeCount(), dest.getConnectorCount());
console.log('before mol merge reverse target', target.getNodeCount(), target.getConnectorCount());
console.log('reverse mol merge', nodes.length, connectors.length);
*/
this.moveChildBetweenStructFragment(dest, target, nodes, connectors);
/*
console.log('after mol merge reverse dest', dest.getNodeCount(), dest.getConnectorCount());
console.log('after mol merge reverse target', target.getNodeCount(), target.getConnectorCount());
*/
}
}
});
/**
* Operation of split one unconnected structure fragment into multiple connected ones.
* @class
* @augments Kekule.ChemObjOperation.Base
*
* @param {Kekule.StructureFragment} target.
*
* @property {Kekule.StructureFragment} target Source fragment, all connectors and nodes will be moved to dest fragment.
* @property {Array} splittedFragments Fragment splitted, this property will be automatically calculated in execution of operation.
*/
Kekule.ChemStructOperation.SplitStructFragment = Class.create(Kekule.ChemObjOperation.Base,
/** @lends Kekule.ChemStructOperation.SplitStructFragment# */
{
/** @private */
CLASS_NAME: 'Kekule.ChemStructOperation.SplitStructFragment',
/** @constructs */
initialize: function($super, target)
{
$super(target);
},
/** @private */
initProperties: function()
{
this.defineProp('splittedFragments', {'dataType': DataType.ARRAY, 'serializable': false, 'setter': null});
},
/** @private */
doExecute: function()
{
var splitted = Kekule.ChemStructureUtils.splitStructFragment(this.getTarget());
if (splitted.length > 1) // do really split
{
this.setPropStoreFieldValue('splittedFragments', splitted);
var parent = this.getTarget().getParent();
var ref = this.getTarget().getNextSibling();
parent.beginUpdate();
try
{
if (parent) // insert newly splitted fragments
{
for (var i = 1, l = splitted.length; i < l; ++i)
{
var frag = splitted[i];
parent.insertBefore(frag, ref);
}
}
}
finally
{
parent.endUpdate();
}
}
else // no real split actions done
{
this.setPropStoreFieldValue('splittedFragments', null);
}
},
/** @private */
doReverse: function()
{
var fragments = this.getSplittedFragments();
if (fragments && fragments.length)
{
var target = this.getTarget();
for (var i = 0, l = fragments.length; i < l; ++i)
{
var frag = fragments[i];
if (frag !== target)
{
Kekule.ChemStructureUtils.moveChildBetweenStructFragment(frag, target, Kekule.ArrayUtils.clone(frag.getNodes()), Kekule.ArrayUtils.clone(frag.getConnectors()));
var p = frag.getParent();
if (p)
p.removeChild(frag);
frag.finalize();
}
}
}
//console.log('split reverse done', target.getNodeCount(), target.getConnectorCount());
}
});
/**
* Split one unconnected structure fragment into multiple connected ones, or remove the fragment
* if the fragment contains no node.
* @class
* @augments Kekule.ChemObjOperation.Base
*
* @param {Kekule.StructureFragment} target.
*
* @property {Kekule.StructureFragment} target Source fragment.
* @property {Bool} enableRemove Whether allow remove empty structure fragment. Default is true.
* @property {Bool} enableSplit Whether allow splitting structure fragment. Default is true.
*/
Kekule.ChemStructOperation.StandardizeStructFragment = Class.create(Kekule.ChemObjOperation.Base,
/** @lends Kekule.ChemStructOperation.StandardizeStructFragment# */
{
/** @private */
CLASS_NAME: 'Kekule.ChemStructOperation.StandardizeStructFragment',
/** @constructs */
initialize: function($super, target)
{
$super(target);
this.setEnableSplit(true);
this.setEnableRemove(true);
this._concreteOper = null; // private
},
/** @private */
initProperties: function()
{
this.defineProp('enableRemove', {'dataType': DataType.BOOL});
this.defineProp('enableSplit', {'dataType': DataType.BOOL});
},
/** @private */
doExecute: function()
{
var target = this.getTarget();
var nodeCount = target.getNodeCount();
this._concreteOper = null;
if (nodeCount <= 0)
{
if (this.getEnableRemove())
this._concreteOper = new Kekule.ChemObjOperation.Remove(target);
}
else
{
if (this.getEnableSplit())
this._concreteOper = new Kekule.ChemStructOperation.SplitStructFragment(target);
}
if (this._concreteOper)
return this._concreteOper.execute();
else
return null;
},
/** @private */
doReverse: function()
{
return this._concreteOper? this._concreteOper.reverse(): null;
}
});
})();
|
Fix a bug in editor, now forumla or subgroup are not regarded as node merge destination
|
src/widgets/chem/editor/kekule.chemEditor.operations.js
|
Fix a bug in editor, now forumla or subgroup are not regarded as node merge destination
|
<ide><path>rc/widgets/chem/editor/kekule.chemEditor.operations.js
<ide> */
<ide> Kekule.ChemStructOperation.MergeNodes.canMerge = function(target, dest, canMergeStructFragment, canMergeNeighborNodes)
<ide> {
<add> // never allow merge to another molecule point (e.g. formula molecule) or subgroup
<add> if ((target instanceof Kekule.StructureFragment) || (dest instanceof Kekule.StructureFragment))
<add> return false;
<ide> var targetFragment = target.getParent();
<ide> var destFragment = dest.getParent();
<ide> var result = (targetFragment === destFragment) || canMergeStructFragment;
<ide> if (!canMergeNeighborNodes)
<del> result = result && (!target.getConnectorTo(dest))
<add> result = result && (!target.getConnectorTo(dest));
<ide> return result;
<ide> };
<ide>
|
|
Java
|
mit
|
0e720399874790280bc4c1cbe0ffdac56dda757e
| 0 |
nls-oskari/oskari-server,nls-oskari/oskari-server,nls-oskari/oskari-server
|
package fi.nls.oskari.map.view;
import com.ibatis.sqlmap.client.SqlMapSession;
import fi.nls.oskari.domain.Role;
import fi.nls.oskari.domain.User;
import fi.nls.oskari.domain.map.view.Bundle;
import fi.nls.oskari.domain.map.view.View;
import fi.nls.oskari.domain.map.view.ViewTypes;
import fi.nls.oskari.log.LogFactory;
import fi.nls.oskari.log.Logger;
import fi.nls.oskari.service.ServiceException;
import fi.nls.oskari.service.db.BaseIbatisService;
import fi.nls.oskari.util.ConversionHelper;
import fi.nls.oskari.util.PropertyUtil;
import java.sql.SQLException;
import java.util.*;
public class ViewServiceIbatisImpl extends BaseIbatisService<Object> implements
ViewService {
private static final Logger LOG = LogFactory.getLogger(ViewServiceIbatisImpl.class);
private static final String PROP_VIEW_DEFAULT = "view.default";
private static final String PROP_VIEW_DEFAULT_ROLES = "view.default.roles";
private final Map<String, Long> roleToDefaultViewId;
private final String[] defaultViewRoles;
private final long defaultViewId;
public ViewServiceIbatisImpl() {
// roles in preferred order which we use to resolve default view
// view.default.roles=Admin, User, Guest
defaultViewRoles = PropertyUtil.getCommaSeparatedList(PROP_VIEW_DEFAULT_ROLES);
roleToDefaultViewId = initDefaultViewsByRole(defaultViewRoles);
defaultViewId = initDefaultViewId();
}
private Map<String, Long> initDefaultViewsByRole(String[] roles) {
if (roles.length == 0) {
return Collections.emptyMap();
}
Map<String, Long> roleToDefaultViewId = new HashMap<>();
for (String role : roles) {
String roleViewIdStr = PropertyUtil.get(PROP_VIEW_DEFAULT + "." + role);
long roleViewId = ConversionHelper.getLong(roleViewIdStr, -1);
if (roleViewId != -1) {
roleToDefaultViewId.put(role, roleViewId);
LOG.debug("Added default view", roleViewId, "for role", role);
} else {
LOG.info("Failed to set default view id for role", role,
"property missing or value invalid");
}
}
return roleToDefaultViewId;
}
private long initDefaultViewId() {
long property = ConversionHelper.getLong(PropertyUtil.get(PROP_VIEW_DEFAULT), -1);
if (property != -1) {
LOG.debug("Global default view id from properties:" , property);
return property;
}
// use one from db if property doesn't exist or is invalid
Long database = ((Long) queryForObject("View.get-default-view-id", ViewTypes.DEFAULT));
LOG.debug("Global default view id from database:" , database);
return database;
}
@Override
protected String getNameSpace() {
return "View";
}
public boolean hasPermissionToAlterView(final View view, final User user) {
// uuids are much longer than 10 actually but check for atleast 10
if(user.getUuid() == null || user.getUuid().length() < 10) {
LOG.debug("Users uuid is missing or invalid: ", user.getUuid());
// user doesn't have an uuid, he shouldn't have any published maps
return false;
}
if(view == null) {
LOG.debug("View is null");
// view with id not found
return false;
}
if(user.isGuest()) {
LOG.debug("User is default/guest user");
return false;
}
if(view.getCreator() != user.getId()) {
// check current user id against view creator (is it the same user)
LOG.debug("Users id:", user.getId(), "didn't match view creator:", view.getCreator());
return false;
}
return true;
}
public List<View> getViews(int page, int pagesize) {
final Map<String, Object> params = new HashMap<String, Object>();
params.put("limit", pagesize);
params.put("offset", (page -1) * pagesize);
List<View> views = queryForList("View.paged-views", params);
return views;
}
public View getViewWithConf(long viewId) {
if (viewId < 1)
return null;
View view = queryForObject("View.view-with-conf-by-view-id", viewId);
return view;
}
public View getViewWithConfByUuId(String uuId) {
if (uuId == null)
return null;
LOG.debug("uuid != null --> view-with-conf-by-uuid");
View view = (View) queryForObject("View.view-with-conf-by-uuid", uuId);
setBundlesForView(view);
return view;
}
public View getViewWithConfByOldId(long oldId) {
if (oldId < 1)
return null;
View view = queryForObject("View.view-with-conf-by-old-id", oldId);
return view;
}
public View getViewWithConf(String viewName) {
View view = (View) queryForObject("View.view-with-conf-by-view-name",
viewName);
return view;
}
public List<View> getViewsForUser(long userId) {
List<View> views = queryForList("View.views-with-conf-by-user-id",
userId);
LOG.debug("Found", views.size(), "views for user", userId);
return views;
}
private void setBundlesForView(View view) {
if (view == null) {
return;
}
long id = view.getId();
List<Bundle> bundles = queryForList("View.bundle-by-view-id", id);
view.setBundles(bundles);
}
public long addView(View view) throws ViewException {
SqlMapSession session = openSession();
try {
view.setUuid(UUID.randomUUID().toString());
session.startTransaction();
Object ret = queryForObject("View.add-view", view);
long id = ((Long) ret).longValue();
LOG.info("Inserted view with id", id);
view.setId(id);
for (Bundle bundle : view.getBundles()) {
addBundleForView(view.getId(), bundle);
}
session.commitTransaction();
return id;
} catch (Exception e) {
throw new ViewException("Error adding a view ", e);
} finally {
endSession(session);
}
}
public void updateAccessFlag(View view) {
update("View.update-access", view);
}
public void deleteViewById(final long id) throws DeleteViewException {
View view = queryForObject("View.view-with-conf-by-view-id", id);
if(view == null) {
throw new DeleteViewException("Couldn't find a view with id:" + id);
}
SqlMapSession session = openSession();
try {
session.startTransaction();
session.delete("View.delete-bundle-by-view", id);
session.delete("View.delete-view", id);
session.commitTransaction();
} catch (Exception e) {
throw new DeleteViewException("Error deleting a view with id:" + id, e);
} finally {
endSession(session);
}
}
public void deleteViewByUserId(long userId) throws DeleteViewException {
SqlMapSession session = openSession();
try {
session.startTransaction();
delete("View.delete-view-by-user", userId);
session.commitTransaction();
} catch (Exception e) {
throw new DeleteViewException("Error deleting a view with user id:" + userId, e);
} finally {
endSession(session);
}
}
public void resetUsersDefaultViews(long userId) {
update("View.resetUsersDefaultViews", userId);
}
public void updateView(View view) {
update("View.update", view);
}
public void updateViewUsage(View view) {
update("View.updateUsage", view);
}
public void updatePublishedView(final View view) throws ViewException {
SqlMapSession session = openSession();
long id = view.getId();
try {
session.startTransaction();
updateView(view);
delete("View.delete-bundle-by-view", id);
for (Bundle bundle : view.getBundles()) {
addBundleForView(view.getId(), bundle);
}
session.commitTransaction();
} catch (Exception e) {
throw new ViewException("Error updating a view with id:" + id, e);
} finally {
endSession(session);
}
}
public void addBundleForView(final long viewId, final Bundle bundle) throws SQLException {
// TODO: maybe setup sequencenumber to last if not set?
bundle.setViewId(viewId);
queryForObject("View.add-bundle", bundle);
LOG.debug("Added bundle to view", bundle.getName());
}
public void updateBundleSettingsForView(final long viewId, final Bundle bundle) throws ViewException {
final Map<String, Object> params = new HashMap<String, Object>();
params.put("view_id", viewId);
params.put("bundle_id", bundle.getBundleId());
params.put("seqno", bundle.getSeqNo());
params.put("startup", bundle.getStartup());
params.put("config", bundle.getConfig());
params.put("state", bundle.getState());
params.put("bundleinstance", bundle.getBundleinstance());
try {
final int numUpdated = getSqlMapClient().update("View.update-bundle-settings-in-view", params);
if(numUpdated == 0) {
// not updated, bundle not found
throw new ViewException("Failed to update - bundle not found in view?");
}
} catch (Exception e) {
throw new ViewException("Failed to update", e);
}
}
public long getDefaultViewId() {
return defaultViewId;
}
/**
* Returns default view id for the user, based on user roles. Configured by properties:
*
* view.default=[global default view id that is used if role-based default view is not found]
* view.default.roles=[comma-separated list of role names in descending order f.ex. Admin, User, Guest]
* view.default.[role name]=[default view id for the role]
*
* If properties are not found, defaults to #getDefaultViewId()
* @param user to get default view for
* @return view id based on users roles
*/
public long getDefaultViewId(final User user) {
if(user == null) {
LOG.debug("Tried to get default view for <null> user");
return getDefaultViewId();
}
else {
final long personalizedId = getPersonalizedDefaultViewId(user);
if(personalizedId != -1) {
return personalizedId;
}
return getSystemDefaultViewId(user.getRoles());
}
}
public long getSystemDefaultViewId(Collection<Role> roles) {
if (roles == null) {
LOG.debug("Tried to get default view for <null> roles");
} else {
// Check the roles in given order and return the first match
for (String defaultViewRole : defaultViewRoles) {
if (Role.hasRoleWithName(roles, defaultViewRole)) {
Long rolesDefaultViewId = roleToDefaultViewId.get(defaultViewRole);
if (rolesDefaultViewId != null) {
LOG.debug("Default view found for role", defaultViewRole, ":", rolesDefaultViewId);
return rolesDefaultViewId;
}
}
}
}
LOG.debug("No role based default views matched user roles:", roles, ". Defaulting to global default.");
return getDefaultViewId();
}
@SuppressWarnings("unchecked")
@Override
public List<Long> getSystemDefaultViewIds() throws ServiceException {
try {
return (List<Long>) getSqlMapClient().queryForList("View.get-default-view-ids");
} catch (SQLException e) {
throw new ServiceException(e.getMessage(), e);
}
}
public boolean isSystemDefaultView(final long id) {
return roleToDefaultViewId.containsValue(id) || getDefaultViewId() == id;
}
/**
* Returns the saved default view id for the user, if one exists
*
* @param user to get default view for
* @return view id of a saved default view
*/
private long getPersonalizedDefaultViewId(final User user) {
if (!user.isGuest() && user.getId() != -1) {
Object queryResult = queryForObject("View.get-default-view-id-by-user-id", user.getId());
if (queryResult != null) {
return (Long) queryResult;
}
}
return -1;
}
/**
* Returns default view id for given role name
* @param roleName
* @return
*/
public long getDefaultViewIdForRole(final String roleName) {
Long rolesDefaultViewId = roleToDefaultViewId.get(roleName);
return rolesDefaultViewId != null ? rolesDefaultViewId : defaultViewId;
}
}
|
service-map/src/main/java/fi/nls/oskari/map/view/ViewServiceIbatisImpl.java
|
package fi.nls.oskari.map.view;
import com.ibatis.sqlmap.client.SqlMapSession;
import fi.nls.oskari.domain.Role;
import fi.nls.oskari.domain.User;
import fi.nls.oskari.domain.map.view.Bundle;
import fi.nls.oskari.domain.map.view.View;
import fi.nls.oskari.domain.map.view.ViewTypes;
import fi.nls.oskari.log.LogFactory;
import fi.nls.oskari.log.Logger;
import fi.nls.oskari.service.ServiceException;
import fi.nls.oskari.service.db.BaseIbatisService;
import fi.nls.oskari.util.ConversionHelper;
import fi.nls.oskari.util.PropertyUtil;
import java.sql.SQLException;
import java.util.*;
public class ViewServiceIbatisImpl extends BaseIbatisService<Object> implements
ViewService {
private static final Logger LOG = LogFactory.getLogger(ViewServiceIbatisImpl.class);
private static final String PROP_VIEW_DEFAULT = "view.default";
private static final String PROP_VIEW_DEFAULT_ROLES = "view.default.roles";
private final Map<String, Long> roleToDefaultViewId;
private final String[] defaultViewRoles;
private final long defaultViewId;
public ViewServiceIbatisImpl() {
// roles in preferred order which we use to resolve default view
// view.default.roles=Admin, User, Guest
defaultViewRoles = PropertyUtil.getCommaSeparatedList(PROP_VIEW_DEFAULT_ROLES);
roleToDefaultViewId = initDefaultViewsByRole(defaultViewRoles);
defaultViewId = initDefaultViewId();
}
private Map<String, Long> initDefaultViewsByRole(String[] roles) {
if (roles.length == 0) {
return Collections.emptyMap();
}
Map<String, Long> roleToDefaultViewId = new HashMap<>();
for (String role : roles) {
String roleViewIdStr = PropertyUtil.get(PROP_VIEW_DEFAULT + "." + role);
long roleViewId = ConversionHelper.getLong(roleViewIdStr, -1);
if (roleViewId != -1) {
roleToDefaultViewId.put(role, roleViewId);
LOG.debug("Added default view", roleViewId, "for role", role);
} else {
LOG.info("Failed to set default view id for role", role,
"property missing or value invalid");
}
}
return roleToDefaultViewId;
}
private long initDefaultViewId() {
long property = ConversionHelper.getLong(PropertyUtil.get(PROP_VIEW_DEFAULT), -1);
if (property != -1) {
LOG.debug("Global default view id from properties:" , property);
return property;
}
// use one from db if property doesn't exist or is invalid
Long database = ((Long) queryForObject("View.get-default-view-id", ViewTypes.DEFAULT));
LOG.debug("Global default view id from database:" , database);
return database;
}
@Override
protected String getNameSpace() {
return "View";
}
public boolean hasPermissionToAlterView(final View view, final User user) {
// uuids are much longer than 10 actually but check for atleast 10
if(user.getUuid() == null || user.getUuid().length() < 10) {
LOG.debug("Users uuid is missing or invalid: ", user.getUuid());
// user doesn't have an uuid, he shouldn't have any published maps
return false;
}
if(view == null) {
LOG.debug("View is null");
// view with id not found
return false;
}
if(user.isGuest()) {
LOG.debug("User is default/guest user");
return false;
}
if(view.getCreator() != user.getId()) {
// check current user id against view creator (is it the same user)
LOG.debug("Users id:", user.getId(), "didn't match view creator:", view.getCreator());
return false;
}
return true;
}
public List<View> getViews(int page, int pagesize) {
final Map<String, Object> params = new HashMap<String, Object>();
params.put("limit", pagesize);
params.put("offset", (page -1) * pagesize);
List<View> views = queryForList("View.paged-views", params);
return views;
}
public View getViewWithConf(long viewId) {
if (viewId < 1)
return null;
View view = queryForObject("View.view-with-conf-by-view-id", viewId);
return view;
}
public View getViewWithConfByUuId(String uuId) {
if (uuId == null)
return null;
LOG.debug("uuid != null --> view-with-conf-by-uuid");
View view = (View) queryForObject("View.view-with-conf-by-uuid", uuId);
setBundlesForView(view);
return view;
}
public View getViewWithConfByOldId(long oldId) {
if (oldId < 1)
return null;
View view = queryForObject("View.view-with-conf-by-old-id", oldId);
return view;
}
public View getViewWithConf(String viewName) {
View view = (View) queryForObject("View.view-with-conf-by-view-name",
viewName);
return view;
}
public List<View> getViewsForUser(long userId) {
List<View> views = queryForList("View.views-with-conf-by-user-id",
userId);
LOG.debug("Found", views.size(), "views for user", userId);
return views;
}
private void setBundlesForView(View view) {
if (view == null) {
return;
}
long id = view.getId();
List<Bundle> bundles = queryForList("View.bundle-by-view-id", id);
view.setBundles(bundles);
}
public long addView(View view) throws ViewException {
SqlMapSession session = openSession();
try {
view.setUuid(UUID.randomUUID().toString());
session.startTransaction();
Object ret = queryForObject("View.add-view", view);
long id = ((Long) ret).longValue();
LOG.info("Inserted view with id", id);
view.setId(id);
for (Bundle bundle : view.getBundles()) {
addBundleForView(view.getId(), bundle);
}
session.commitTransaction();
return id;
} catch (Exception e) {
throw new ViewException("Error adding a view ", e);
} finally {
endSession(session);
}
}
public void updateAccessFlag(View view) {
update("View.update-access", view);
}
public void deleteViewById(final long id) throws DeleteViewException {
View view = queryForObject("View.view-with-conf-by-view-id", id);
if(view == null) {
throw new DeleteViewException("Couldn't find a view with id:" + id);
}
SqlMapSession session = openSession();
try {
session.startTransaction();
session.delete("View.delete-bundle-by-view", id);
session.delete("View.delete-view", id);
session.commitTransaction();
} catch (Exception e) {
throw new DeleteViewException("Error deleting a view with id:" + id, e);
} finally {
endSession(session);
}
}
public void deleteViewByUserId(long userId) throws DeleteViewException {
SqlMapSession session = openSession();
try {
session.startTransaction();
delete("View.delete-view-by-user", userId);
session.commitTransaction();
} catch (Exception e) {
throw new DeleteViewException("Error deleting a view with user id:" + userId, e);
} finally {
endSession(session);
}
}
public void resetUsersDefaultViews(long userId) {
update("View.resetUsersDefaultViews", userId);
}
public void updateView(View view) {
update("View.update", view);
}
public void updateViewUsage(View view) {
update("View.updateUsage", view);
}
public void updatePublishedView(final View view) throws ViewException {
SqlMapSession session = openSession();
long id = view.getId();
try {
session.startTransaction();
updateView(view);
delete("View.delete-bundle-by-view", id);
for (Bundle bundle : view.getBundles()) {
addBundleForView(view.getId(), bundle);
}
session.commitTransaction();
} catch (Exception e) {
throw new ViewException("Error updating a view with id:" + id, e);
} finally {
endSession(session);
}
}
public void addBundleForView(final long viewId, final Bundle bundle) throws SQLException {
// TODO: maybe setup sequencenumber to last if not set?
bundle.setViewId(viewId);
queryForObject("View.add-bundle", bundle);
LOG.debug("Added bundle to view", bundle.getName());
}
public void updateBundleSettingsForView(final long viewId, final Bundle bundle) throws ViewException {
final Map<String, Object> params = new HashMap<String, Object>();
params.put("view_id", viewId);
params.put("bundle_id", bundle.getBundleId());
params.put("seqno", bundle.getSeqNo());
params.put("startup", bundle.getStartup());
params.put("config", bundle.getConfig());
params.put("state", bundle.getState());
params.put("bundleinstance", bundle.getBundleinstance());
try {
final int numUpdated = getSqlMapClient().update("View.update-bundle-settings-in-view", params);
if(numUpdated == 0) {
// not updated, bundle not found
throw new ViewException("Failed to update - bundle not found in view?");
}
} catch (Exception e) {
throw new ViewException("Failed to update", e);
}
}
public long getDefaultViewId() {
return defaultViewId;
}
/**
* Returns default view id for the user, based on user roles. Configured by properties:
*
* view.default=[global default view id that is used if role-based default view is not found]
* view.default.roles=[comma-separated list of role names in descending order f.ex. Admin, User, Guest]
* view.default.[role name]=[default view id for the role]
*
* If properties are not found, defaults to #getDefaultViewId()
* @param user to get default view for
* @return view id based on users roles
*/
public long getDefaultViewId(final User user) {
if(user == null) {
LOG.debug("Tried to get default view for <null> user");
return getDefaultViewId();
}
else {
final long personalizedId = getPersonalizedDefaultViewId(user);
if(personalizedId != -1) {
return personalizedId;
}
return getSystemDefaultViewId(user.getRoles());
}
}
public long getSystemDefaultViewId(Collection<Role> roles) {
if (roles == null) {
LOG.debug("Tried to get default view for <null> roles");
} else {
// Check the roles in given order and return the first match
for (String defaultViewRole : defaultViewRoles) {
if (Role.hasRoleWithName(roles, defaultViewRole)) {
Long rolesDefaultViewId = roleToDefaultViewId.get(defaultViewRole);
if (rolesDefaultViewId != null) {
LOG.debug("Default view found for role", defaultViewRole, ":", rolesDefaultViewId);
return rolesDefaultViewId;
}
}
}
}
LOG.debug("No role based default views matched user roles:", roles, ". Defaulting to global default.");
return getDefaultViewId();
}
@SuppressWarnings("unchecked")
@Override
public List<Long> getSystemDefaultViewIds() throws ServiceException {
try {
return (List<Long>) getSqlMapClient().queryForList("View.get-default-view-ids");
} catch (SQLException e) {
throw new ServiceException(e.getMessage(), e);
}
}
/**
* Returns the saved default view id for the user, if one exists
*
* @param user to get default view for
* @return view id of a saved default view
*/
private long getPersonalizedDefaultViewId(final User user) {
if (!user.isGuest() && user.getId() != -1) {
Object queryResult = queryForObject("View.get-default-view-id-by-user-id", user.getId());
if (queryResult != null) {
return (Long) queryResult;
}
}
return -1;
}
public boolean isSystemDefaultView(final long id) {
return getDefaultViewId() == id || roleToDefaultViewId.containsValue(id);
}
/**
* Returns default view id for given role name
* @param roleName
* @return
*/
public long getDefaultViewIdForRole(final String roleName) {
Long rolesDefaultViewId = roleToDefaultViewId.get(roleName);
return rolesDefaultViewId != null ? rolesDefaultViewId : defaultViewId;
}
}
|
More of this
|
service-map/src/main/java/fi/nls/oskari/map/view/ViewServiceIbatisImpl.java
|
More of this
|
<ide><path>ervice-map/src/main/java/fi/nls/oskari/map/view/ViewServiceIbatisImpl.java
<ide> }
<ide> }
<ide>
<add> public boolean isSystemDefaultView(final long id) {
<add> return roleToDefaultViewId.containsValue(id) || getDefaultViewId() == id;
<add> }
<add>
<ide> /**
<ide> * Returns the saved default view id for the user, if one exists
<ide> *
<ide> return -1;
<ide> }
<ide>
<del> public boolean isSystemDefaultView(final long id) {
<del> return getDefaultViewId() == id || roleToDefaultViewId.containsValue(id);
<del> }
<del>
<ide> /**
<ide> * Returns default view id for given role name
<ide> * @param roleName
|
|
Java
|
mit
|
e6e82ba56140fdff4b41925bcc5543f2b38a28b0
| 0 |
fredyw/leetcode,fredyw/leetcode,fredyw/leetcode,fredyw/leetcode
|
package leetcode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
/**
* https://leetcode.com/problems/average-of-levels-in-binary-tree/
*/
public class Problem637 {
public static class TreeNode {
long val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public List<Double> averageOfLevels(TreeNode root) {
Map<Integer, ValueCount> map = new HashMap<>();
Queue<LevelNode> queue = new LinkedList<>();
queue.add(new LevelNode(1, root));
while (!queue.isEmpty()) {
LevelNode current = queue.remove();
if (!map.containsKey(current.level)) {
map.put(current.level, new ValueCount(current.node.val, 1));
} else {
ValueCount valueCount = map.get(current.level);
valueCount.count++;
valueCount.value += current.node.val;
}
if (current.node.left != null) {
queue.add(new LevelNode(current.level + 1, current.node.left));
}
if (current.node.right != null) {
queue.add(new LevelNode(current.level + 1, current.node.right));
}
}
List<Double> result = new ArrayList<>();
for (int i = 1; i <= map.size(); i++) {
ValueCount valueCount = map.get(i);
result.add((double) valueCount.value / (double) valueCount.count);
}
return result;
}
private static class ValueCount {
private long value;
private int count;
public ValueCount(long value, int count) {
this.value = value;
this.count = count;
}
}
private static class LevelNode {
private final int level;
private final TreeNode node;
public LevelNode(int level, TreeNode node) {
this.level = level;
this.node = node;
}
}
public static void main(String[] args) {
Problem637 prob = new Problem637();
TreeNode root = new TreeNode(3);
root.left = new TreeNode(9);
root.right = new TreeNode(20);
root.right.left = new TreeNode(15);
root.right.right = new TreeNode(7);
System.out.println(prob.averageOfLevels(root)); // [3, 14.5, 11]
}
}
|
src/main/java/leetcode/Problem637.java
|
package leetcode;
import java.util.ArrayList;
import java.util.List;
/**
* https://leetcode.com/problems/average-of-levels-in-binary-tree/
*/
public class Problem637 {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public List<Double> averageOfLevels(TreeNode root) {
// TODO
return new ArrayList<>();
}
public static void main(String[] args) {
Problem637 prob = new Problem637();
TreeNode root = new TreeNode(3);
root.left = new TreeNode(9);
root.right = new TreeNode(20);
root.right.left = new TreeNode(15);
root.right.right = new TreeNode(7);
System.out.println(prob.averageOfLevels(root)); // [3, 14.5, 11]
}
}
|
Solve problem 637
|
src/main/java/leetcode/Problem637.java
|
Solve problem 637
|
<ide><path>rc/main/java/leetcode/Problem637.java
<ide> package leetcode;
<ide>
<ide> import java.util.ArrayList;
<add>import java.util.HashMap;
<add>import java.util.LinkedList;
<ide> import java.util.List;
<add>import java.util.Map;
<add>import java.util.Queue;
<ide>
<ide> /**
<ide> * https://leetcode.com/problems/average-of-levels-in-binary-tree/
<ide> */
<ide> public class Problem637 {
<ide> public static class TreeNode {
<del> int val;
<add> long val;
<ide> TreeNode left;
<ide> TreeNode right;
<ide>
<ide> }
<ide>
<ide> public List<Double> averageOfLevels(TreeNode root) {
<del> // TODO
<del> return new ArrayList<>();
<add> Map<Integer, ValueCount> map = new HashMap<>();
<add> Queue<LevelNode> queue = new LinkedList<>();
<add> queue.add(new LevelNode(1, root));
<add> while (!queue.isEmpty()) {
<add> LevelNode current = queue.remove();
<add> if (!map.containsKey(current.level)) {
<add> map.put(current.level, new ValueCount(current.node.val, 1));
<add> } else {
<add> ValueCount valueCount = map.get(current.level);
<add> valueCount.count++;
<add> valueCount.value += current.node.val;
<add> }
<add> if (current.node.left != null) {
<add> queue.add(new LevelNode(current.level + 1, current.node.left));
<add> }
<add> if (current.node.right != null) {
<add> queue.add(new LevelNode(current.level + 1, current.node.right));
<add> }
<add> }
<add> List<Double> result = new ArrayList<>();
<add> for (int i = 1; i <= map.size(); i++) {
<add> ValueCount valueCount = map.get(i);
<add> result.add((double) valueCount.value / (double) valueCount.count);
<add> }
<add> return result;
<add> }
<add>
<add> private static class ValueCount {
<add> private long value;
<add> private int count;
<add>
<add> public ValueCount(long value, int count) {
<add> this.value = value;
<add> this.count = count;
<add> }
<add> }
<add>
<add> private static class LevelNode {
<add> private final int level;
<add> private final TreeNode node;
<add>
<add> public LevelNode(int level, TreeNode node) {
<add> this.level = level;
<add> this.node = node;
<add> }
<ide> }
<ide>
<ide> public static void main(String[] args) {
|
|
Java
|
apache-2.0
|
9a9f703a9fd7dd23f12f8b83da477d3f13916dc7
| 0 |
dalaro/incubator-tinkerpop,artem-aliev/tinkerpop,jorgebay/tinkerpop,gdelafosse/incubator-tinkerpop,jorgebay/tinkerpop,edgarRd/incubator-tinkerpop,robertdale/tinkerpop,mpollmeier/tinkerpop3,BrynCooke/incubator-tinkerpop,gdelafosse/incubator-tinkerpop,vtslab/incubator-tinkerpop,apache/tinkerpop,PommeVerte/incubator-tinkerpop,krlohnes/tinkerpop,artem-aliev/tinkerpop,gdelafosse/incubator-tinkerpop,artem-aliev/tinkerpop,apache/tinkerpop,pluradj/incubator-tinkerpop,robertdale/tinkerpop,rmagen/incubator-tinkerpop,velo/incubator-tinkerpop,robertdale/tinkerpop,newkek/incubator-tinkerpop,n-tran/incubator-tinkerpop,vtslab/incubator-tinkerpop,mike-tr-adamson/incubator-tinkerpop,apache/tinkerpop,newkek/incubator-tinkerpop,RedSeal-co/incubator-tinkerpop,samiunn/incubator-tinkerpop,Lab41/tinkerpop3,apache/incubator-tinkerpop,krlohnes/tinkerpop,mpollmeier/tinkerpop3,apache/tinkerpop,RedSeal-co/incubator-tinkerpop,artem-aliev/tinkerpop,RedSeal-co/incubator-tinkerpop,BrynCooke/incubator-tinkerpop,dalaro/incubator-tinkerpop,samiunn/incubator-tinkerpop,n-tran/incubator-tinkerpop,apache/tinkerpop,krlohnes/tinkerpop,PommeVerte/incubator-tinkerpop,robertdale/tinkerpop,apache/incubator-tinkerpop,n-tran/incubator-tinkerpop,vtslab/incubator-tinkerpop,jorgebay/tinkerpop,samiunn/incubator-tinkerpop,pluradj/incubator-tinkerpop,jorgebay/tinkerpop,dalaro/incubator-tinkerpop,krlohnes/tinkerpop,RussellSpitzer/incubator-tinkerpop,apache/incubator-tinkerpop,BrynCooke/incubator-tinkerpop,Lab41/tinkerpop3,edgarRd/incubator-tinkerpop,velo/incubator-tinkerpop,newkek/incubator-tinkerpop,apache/tinkerpop,RussellSpitzer/incubator-tinkerpop,pluradj/incubator-tinkerpop,PommeVerte/incubator-tinkerpop,krlohnes/tinkerpop,rmagen/incubator-tinkerpop,artem-aliev/tinkerpop,rmagen/incubator-tinkerpop,RussellSpitzer/incubator-tinkerpop,velo/incubator-tinkerpop,edgarRd/incubator-tinkerpop,mike-tr-adamson/incubator-tinkerpop,robertdale/tinkerpop,mike-tr-adamson/incubator-tinkerpop,apache/tinkerpop
|
package com.tinkerpop.gremlin.structure.strategy;
import com.tinkerpop.gremlin.process.graph.GraphTraversal;
import com.tinkerpop.gremlin.structure.Direction;
import com.tinkerpop.gremlin.structure.Edge;
import com.tinkerpop.gremlin.structure.Element;
import com.tinkerpop.gremlin.structure.Graph;
import com.tinkerpop.gremlin.structure.Vertex;
import com.tinkerpop.gremlin.structure.util.ElementHelper;
import com.tinkerpop.gremlin.structure.util.StringFactory;
import com.tinkerpop.gremlin.util.StreamFactory;
import java.util.Iterator;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
/**
* A GraphStrategy which creates a logical subgraph to selectively include vertices and edges of a Graph according to
* provided criteria. A vertex is in the subgraph if it meets the specified {@link #vertexPredicate}. An edge
* is in the subgraph if it meets the specified {@link #edgePredicate} and its associated vertices meet the
* specified {@link #vertexPredicate}.
*
* @author Joshua Shinavier (http://fortytwo.net)
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
public class SubgraphStrategy implements GraphStrategy {
protected Predicate<Vertex> vertexPredicate;
protected Predicate<Edge> edgePredicate;
// TODO protected Predicate<VertexProperty> vertexPropertyPredicate;
public SubgraphStrategy(final Predicate<Vertex> vertexPredicate, final Predicate<Edge> edgePredicate) {
this.vertexPredicate = vertexPredicate;
this.edgePredicate = edgePredicate;
}
@Override
public UnaryOperator<Function<Object, Vertex>> getGraphvStrategy(final Strategy.Context<StrategyWrappedGraph> ctx) {
return (f) -> (id) -> {
final Vertex v = f.apply(id);
if (!this.testVertex(v)) {
throw Graph.Exceptions.elementNotFound(Vertex.class, id);
}
return v;
};
}
@Override
public UnaryOperator<Function<Object, Edge>> getGrapheStrategy(final Strategy.Context<StrategyWrappedGraph> ctx) {
return (f) -> (id) -> {
final Edge e = f.apply(id);
if (!this.testEdge(e)) {
throw Graph.Exceptions.elementNotFound(Edge.class, id);
}
return e;
};
}
@Override
public UnaryOperator<BiFunction<Direction, String[], Iterator<Vertex>>> getVertexIteratorsVerticesStrategy(final Strategy.Context<StrategyWrappedVertex> ctx) {
return (f) -> (direction, labels) -> StreamFactory
.stream(ctx.getCurrent().edgeIterator(direction, labels))
.filter(this::testEdge)
.map(edge -> otherVertex(direction, ctx.getCurrent(), edge))
.filter(this::testVertex)
.map(v -> ((StrategyWrappedVertex) v).getBaseVertex()).iterator();
// TODO: why do we have to unwrap? Note that we are not doing f.apply() like the other methods. Is this bad?
}
@Override
public UnaryOperator<BiFunction<Direction, String[], Iterator<Edge>>> getVertexIteratorsEdgesStrategy(final Strategy.Context<StrategyWrappedVertex> ctx) {
return (f) -> (direction, labels) -> StreamFactory.stream(f.apply(direction, labels)).filter(this::testEdge).iterator();
}
@Override
public UnaryOperator<Function<Direction, Iterator<Vertex>>> getEdgeIteratorsVerticesStrategy(final Strategy.Context<StrategyWrappedEdge> ctx) {
return (f) -> direction -> StreamFactory.stream(f.apply(direction)).filter(this::testVertex).iterator();
}
@Override
public UnaryOperator<Supplier<GraphTraversal<Vertex, Vertex>>> getGraphVStrategy(final Strategy.Context<StrategyWrappedGraph> ctx) {
return (f) -> () -> f.get().filter(t -> this.testVertex(t.get())); // TODO: we should make sure index hits go first.
}
@Override
public UnaryOperator<Supplier<GraphTraversal<Edge, Edge>>> getGraphEStrategy(final Strategy.Context<StrategyWrappedGraph> ctx) {
return (f) -> () -> f.get().filter(t -> this.testEdge(t.get())); // TODO: we should make sure index hits go first.
}
// TODO: make this work for DSL -- we need Element predicate
/*public UnaryOperator<Supplier<GraphTraversal>> getGraphOfStrategy(final Strategy.Context<StrategyWrappedGraph> ctx) {
return (f) -> () -> f.get().filter(el);
}*/
private boolean testVertex(final Vertex vertex) {
return vertexPredicate.test(vertex);
}
private boolean testEdge(final Edge edge) {
// the edge must pass the edge predicate, and both of its incident vertices must also pass the vertex predicate
// inV() and/or outV() will be empty if they do not. it is sometimes the case that an edge is unwrapped
// in which case it may not be filtered. in such cases, the vertices on such edges should be tested.
return edgePredicate.test(edge)
&& (edge instanceof StrategyWrapped ? edge.inV().hasNext() && edge.outV().hasNext()
: testVertex(edge.inV().next()) && testVertex(edge.outV().next()));
}
private boolean testElement(final Element element) {
return element instanceof Vertex ? testVertex((Vertex) element) : testEdge((Edge) element);
}
private static final Vertex otherVertex(final Direction direction, final Vertex start, final Edge edge) {
if (direction.equals(Direction.BOTH)) {
final Vertex inVertex = edge.iterators().vertexIterator(Direction.IN).next();
return ElementHelper.areEqual(start, inVertex) ?
edge.iterators().vertexIterator(Direction.OUT).next() :
inVertex;
} else {
return edge.iterators().vertexIterator(direction.opposite()).next();
}
}
@Override
public String toString() {
return StringFactory.graphStrategyString(this);
}
}
|
gremlin-core/src/main/java/com/tinkerpop/gremlin/structure/strategy/SubgraphStrategy.java
|
package com.tinkerpop.gremlin.structure.strategy;
import com.tinkerpop.gremlin.process.graph.GraphTraversal;
import com.tinkerpop.gremlin.structure.Direction;
import com.tinkerpop.gremlin.structure.Edge;
import com.tinkerpop.gremlin.structure.Element;
import com.tinkerpop.gremlin.structure.Graph;
import com.tinkerpop.gremlin.structure.Vertex;
import com.tinkerpop.gremlin.structure.util.ElementHelper;
import com.tinkerpop.gremlin.structure.util.StringFactory;
import com.tinkerpop.gremlin.util.StreamFactory;
import java.util.Iterator;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
/**
* A GraphStrategy which creates a logical subgraph to selectively include vertices and edges of a Graph according to
* provided criteria. A vertex is in the subgraph if it meets the specified {@link #vertexPredicate}. An edge
* is in the subgraph if it meets the specified {@link #edgePredicate} and its associated vertices meet the
* specified {@link #vertexPredicate}.
*
* @author Joshua Shinavier (http://fortytwo.net)
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
public class SubgraphStrategy implements GraphStrategy {
protected Predicate<Vertex> vertexPredicate;
protected Predicate<Edge> edgePredicate;
// TODO protected Predicate<VertexProperty> vertexPropertyPredicate;
public SubgraphStrategy(final Predicate<Vertex> vertexPredicate, final Predicate<Edge> edgePredicate) {
this.vertexPredicate = vertexPredicate;
this.edgePredicate = edgePredicate;
}
@Override
public UnaryOperator<Function<Object, Vertex>> getGraphvStrategy(final Strategy.Context<StrategyWrappedGraph> ctx) {
return (f) -> (id) -> {
final Vertex v = f.apply(id);
if (!this.testVertex(v)) {
throw Graph.Exceptions.elementNotFound(Vertex.class, id);
}
return v;
};
}
@Override
public UnaryOperator<Function<Object, Edge>> getGrapheStrategy(final Strategy.Context<StrategyWrappedGraph> ctx) {
return (f) -> (id) -> {
final Edge e = f.apply(id);
if (!this.testEdge(e)) {
throw Graph.Exceptions.elementNotFound(Edge.class, id);
}
return e;
};
}
public UnaryOperator<BiFunction<Direction, String[], Iterator<Vertex>>> getVertexIteratorsVerticesStrategy(final Strategy.Context<StrategyWrappedVertex> ctx) {
return (f) -> (direction, labels) -> StreamFactory
.stream(ctx.getCurrent().edgeIterator(direction, labels))
.filter(this::testEdge)
.map(edge -> otherVertex(direction, ctx.getCurrent(), edge))
.filter(this::testVertex)
.map(v -> ((StrategyWrappedVertex) v).getBaseVertex()).iterator();
// TODO: why do we have to unwrap? Note that we are not doing f.apply() like the other methods. Is this bad?
}
public UnaryOperator<BiFunction<Direction, String[], Iterator<Edge>>> getVertexIteratorsEdgesStrategy(final Strategy.Context<StrategyWrappedVertex> ctx) {
return (f) -> (direction, labels) -> StreamFactory.stream(f.apply(direction, labels)).filter(this::testEdge).iterator();
}
public UnaryOperator<Function<Direction, Iterator<Vertex>>> getEdgeIteratorsVerticesStrategy(final Strategy.Context<StrategyWrappedEdge> ctx) {
return (f) -> direction -> StreamFactory.stream(f.apply(direction)).filter(this::testVertex).iterator();
}
public UnaryOperator<Supplier<GraphTraversal<Vertex, Vertex>>> getGraphVStrategy(final Strategy.Context<StrategyWrappedGraph> ctx) {
return (f) -> () -> f.get().filter(t -> this.testVertex(t.get())); // TODO: we should make sure index hits go first.
}
public UnaryOperator<Supplier<GraphTraversal<Edge, Edge>>> getGraphEStrategy(final Strategy.Context<StrategyWrappedGraph> ctx) {
return (f) -> () -> f.get().filter(t -> this.testEdge(t.get())); // TODO: we should make sure index hits go first.
}
// TODO: make this work for DSL -- we need Element predicate
/*public UnaryOperator<Supplier<GraphTraversal>> getGraphOfStrategy(final Strategy.Context<StrategyWrappedGraph> ctx) {
return (f) -> () -> f.get().filter(el);
}*/
private boolean testVertex(final Vertex vertex) {
return vertexPredicate.test(vertex);
}
private boolean testEdge(final Edge edge) {
// the edge must pass the edge predicate, and both of its incident vertices must also pass the vertex predicate
// inV() and/or outV() will be empty if they do not. it is sometimes the case that an edge is unwrapped
// in which case it may not be filtered. in such cases, the vertices on such edges should be tested.
return edgePredicate.test(edge)
&& (edge instanceof StrategyWrapped ? edge.inV().hasNext() && edge.outV().hasNext()
: testVertex(edge.inV().next()) && testVertex(edge.outV().next()));
}
private boolean testElement(final Element element) {
return element instanceof Vertex ? testVertex((Vertex) element) : testEdge((Edge) element);
}
private static final Vertex otherVertex(final Direction direction, final Vertex start, final Edge edge) {
if (direction.equals(Direction.BOTH)) {
final Vertex inVertex = edge.iterators().vertexIterator(Direction.IN).next();
return ElementHelper.areEqual(start, inVertex) ?
edge.iterators().vertexIterator(Direction.OUT).next() :
inVertex;
} else {
return edge.iterators().vertexIterator(direction.opposite()).next();
}
}
@Override
public String toString() {
return StringFactory.graphStrategyString(this);
}
}
|
added @Overrides to SubgraphStrategy.
|
gremlin-core/src/main/java/com/tinkerpop/gremlin/structure/strategy/SubgraphStrategy.java
|
added @Overrides to SubgraphStrategy.
|
<ide><path>remlin-core/src/main/java/com/tinkerpop/gremlin/structure/strategy/SubgraphStrategy.java
<ide> };
<ide> }
<ide>
<add> @Override
<ide> public UnaryOperator<BiFunction<Direction, String[], Iterator<Vertex>>> getVertexIteratorsVerticesStrategy(final Strategy.Context<StrategyWrappedVertex> ctx) {
<ide> return (f) -> (direction, labels) -> StreamFactory
<ide> .stream(ctx.getCurrent().edgeIterator(direction, labels))
<ide> // TODO: why do we have to unwrap? Note that we are not doing f.apply() like the other methods. Is this bad?
<ide> }
<ide>
<add> @Override
<ide> public UnaryOperator<BiFunction<Direction, String[], Iterator<Edge>>> getVertexIteratorsEdgesStrategy(final Strategy.Context<StrategyWrappedVertex> ctx) {
<ide> return (f) -> (direction, labels) -> StreamFactory.stream(f.apply(direction, labels)).filter(this::testEdge).iterator();
<ide> }
<ide>
<add> @Override
<ide> public UnaryOperator<Function<Direction, Iterator<Vertex>>> getEdgeIteratorsVerticesStrategy(final Strategy.Context<StrategyWrappedEdge> ctx) {
<ide> return (f) -> direction -> StreamFactory.stream(f.apply(direction)).filter(this::testVertex).iterator();
<ide> }
<ide>
<add> @Override
<ide> public UnaryOperator<Supplier<GraphTraversal<Vertex, Vertex>>> getGraphVStrategy(final Strategy.Context<StrategyWrappedGraph> ctx) {
<ide> return (f) -> () -> f.get().filter(t -> this.testVertex(t.get())); // TODO: we should make sure index hits go first.
<ide> }
<ide>
<add> @Override
<ide> public UnaryOperator<Supplier<GraphTraversal<Edge, Edge>>> getGraphEStrategy(final Strategy.Context<StrategyWrappedGraph> ctx) {
<ide> return (f) -> () -> f.get().filter(t -> this.testEdge(t.get())); // TODO: we should make sure index hits go first.
<ide> }
|
|
Java
|
apache-2.0
|
8801699b19c15ee9985bd4f845160d80c27617f2
| 0 |
tltv/gantt
|
/*
* Copyright 2014 Tomi Virtanen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.tltv.gantt.client;
import static org.tltv.gantt.client.shared.GanttUtil.getBoundingClientRectWidth;
import static org.tltv.gantt.client.shared.GanttUtil.getMarginByComputedStyle;
import static org.tltv.gantt.client.shared.GanttUtil.getTouchOrMouseClientX;
import static org.tltv.gantt.client.shared.GanttUtil.getTouchOrMouseClientY;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.tltv.gantt.client.shared.GanttUtil;
import org.tltv.gantt.client.shared.Resolution;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.dom.client.Style.Cursor;
import com.google.gwt.dom.client.Style.Display;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ContextMenuEvent;
import com.google.gwt.event.dom.client.ContextMenuHandler;
import com.google.gwt.event.dom.client.MouseDownEvent;
import com.google.gwt.event.dom.client.MouseDownHandler;
import com.google.gwt.event.dom.client.MouseMoveEvent;
import com.google.gwt.event.dom.client.MouseMoveHandler;
import com.google.gwt.event.dom.client.MouseUpEvent;
import com.google.gwt.event.dom.client.MouseUpHandler;
import com.google.gwt.event.dom.client.ScrollEvent;
import com.google.gwt.event.dom.client.ScrollHandler;
import com.google.gwt.event.dom.client.TouchCancelEvent;
import com.google.gwt.event.dom.client.TouchCancelHandler;
import com.google.gwt.event.dom.client.TouchEndEvent;
import com.google.gwt.event.dom.client.TouchEndHandler;
import com.google.gwt.event.dom.client.TouchMoveEvent;
import com.google.gwt.event.dom.client.TouchMoveHandler;
import com.google.gwt.event.dom.client.TouchStartEvent;
import com.google.gwt.event.dom.client.TouchStartHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.touch.client.Point;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.AbstractNativeScrollbar;
import com.google.gwt.user.client.ui.ComplexPanel;
import com.google.gwt.user.client.ui.HasEnabled;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.WidgetCollection;
import com.vaadin.client.event.PointerCancelEvent;
import com.vaadin.client.event.PointerCancelHandler;
import com.vaadin.client.event.PointerDownEvent;
import com.vaadin.client.event.PointerDownHandler;
import com.vaadin.client.event.PointerMoveEvent;
import com.vaadin.client.event.PointerMoveHandler;
import com.vaadin.client.event.PointerUpEvent;
import com.vaadin.client.event.PointerUpHandler;
/**
* GWT Gantt chart widget. Includes {@link TimelineWidget} to show timeline, and
* below the timeline, shows content of the Gantt. Content is freely (position:
* absolute) positioned steps aligned vertically on top of each others.
* <p>
* These steps can be moved and resized freely in the space available, limited
* only by the timeline's borders.
* <p>
* All events are handled via {@link GanttRpc}.
* <p>
* Timeline's localization is handled via {@link LocaleDataProvider}.
* <p>
* Here are few steps that need to be notified when taking this widget in use. <br>
* First of all, after constructing this widget, you need to initialize it by
* {@link #initWidget(GanttRpc, LocaleDataProvider)} method. But before doing
* that, make sure to call
* {@link #setBrowserInfo(boolean, boolean, boolean, boolean, int)} to let this
* widget know some details of the browser. And if client supports touch events,
* let this widget know that by calling {@link #setTouchSupported(boolean)}
* method before initWidget.
* <p>
* Sample code snippet:
*
* <pre>
* GanttWidget widget = new GanttWidget();
* widget.setBrowserInfo(isIe(), isChrome(), isSafari(), isWebkit(),
* getMajorBrowserVersion());
* widget.setTouchSupportted(isTouchDevice());
* widget.initWidget(ganttRpc, localeDataProvider);
* </pre>
* <p>
* After initializing, widget is ready to go. But to let this widget know when
* it should re-calculate content widths/heights, call either
* {@link #notifyHeightChanged(int)} or {@link #notifyWidthChanged(int)} methods
* to do that. This needs to be done explicitly for example when widget's width
* is 100%, and the parent's width changes due to browser window's resize event.
*
* @author Tltv
*
*/
public class GanttWidget extends ComplexPanel implements HasEnabled, HasWidgets {
private static final int RESIZE_WIDTH = 10;
private static final int BAR_MIN_WIDTH = RESIZE_WIDTH;
private static final int CLICK_INTERVAL = 250;
private static final int POINTER_TOUCH_DETECTION_INTERVAL = 100;
private static final String STYLE_GANTT = "gantt";
private static final String STYLE_GANTT_CONTAINER = "gantt-container";
private static final String STYLE_GANTT_CONTENT = "gantt-content";
private static final String STYLE_MOVING = "moving";
private static final String STYLE_RESIZING = "resizing";
private static final String STYLE_MOVE_ELEMENT = "mv-el";
private HandlerRegistration msPointerDownHandlerRegistration;
private HandlerRegistration msPointerUpHandlerRegistration;
private HandlerRegistration msPointerMoveHandlerRegistration;
private HandlerRegistration msPointerCancelHandlerRegistration;
private HandlerRegistration touchStartHandlerRegistration;
private HandlerRegistration touchEndHandlerRegistration;
private HandlerRegistration touchMoveHandlerRegistration;
private HandlerRegistration touchCancelHandlerRegistration;
private HandlerRegistration scrollHandlerRegistration;
private HandlerRegistration mouseMoveHandlerRegistration;
private HandlerRegistration mouseDownHandlerHandlerRegistration;
private HandlerRegistration mouseUpHandlerHandlerRegistration;
private HandlerRegistration contextMenuHandlerRegistration;
private WidgetCollection children = new WidgetCollection(this);
private boolean enabled = true;
private boolean touchSupported = false;
private boolean movableSteps;
private boolean movableStepsBetweenLines;
private boolean resizableSteps;
private boolean backgroundGridEnabled;
private boolean defaultContextMenuEnabled = false;
private GanttRpc ganttRpc;
private LocaleDataProvider localeDataProvider;
private String locale;
private Resolution resolution;
private int firstDayOfRange;
private int firstHourOfRange;
private long startDate;
private long endDate;
private int minWidth;
protected double contentHeight;
protected boolean wasTimelineOverflowingHorizontally = false;
protected boolean wasContentOverflowingVertically = false;
protected TimelineWidget timeline;
protected DivElement container;
protected DivElement content;
protected DivElement scrollbarSpacer;
protected BgGridElement bgGrid;
/* Extra elements inside the content. */
protected Set<Widget> extraContentElements = new HashSet<Widget>();
protected boolean clickOnNextMouseUp = true;
protected boolean secondaryClickOnNextMouseUp = true;
protected Point movePoint;
protected boolean resizing = false;
protected boolean resizingFromLeft = false;
protected boolean resizingInProgress = false;
protected boolean moveInProgress = false;
protected int currentPointerEventId;
// following variables are set during mouse down event over a bar element,
// or over it's children element.
protected Point capturePoint;
protected String capturePointLeftPercentage;
protected String capturePointWidthPercentage;
protected double capturePointLeftPx;
protected double capturePointTopPx;
protected double capturePointWidthPx;
protected String capturePointBgColor;
protected Element targetBarElement;
// these variables are used to memorize the Y and Y origin to scroll the
// container (with touchStart/touchEnd/touchMove events).
protected int containerScrollStartPosY = -1;
protected int containerScrollStartPosX = -1;
// additional element that appears when moving or resizing
protected DivElement moveElement = DivElement.as(DOM.createDiv());
// click is actually detected by 'mouseup'/'mousedown' events, not with
// 'onclick'. click event is not used. disallowClickTimer helps to detect
// click during a short interval. And disallowing it after a short interval.
private Timer disallowClickTimer = new Timer() {
@Override
public void run() {
disableClickOnNextMouseUp();
if (isMovableSteps() && !isResizingInProgress()) {
addMovingStyles(targetBarElement);
}
}
};
private NativeEvent pendingPointerDownEvent;
private Timer pointerTouchStartedTimer = new Timer() {
@Override
public void run() {
GanttWidget.this.onTouchOrMouseDown(pendingPointerDownEvent);
pendingPointerDownEvent = null;
}
};
private ScrollHandler scrollHandler = new ScrollHandler() {
@Override
public void onScroll(ScrollEvent event) {
Element element = event.getNativeEvent().getEventTarget().cast();
if (element != container) {
return;
}
timeline.setScrollLeft(container.getScrollLeft());
}
};
private MouseDownHandler mouseDownHandler = new MouseDownHandler() {
@Override
public void onMouseDown(MouseDownEvent event) {
GWT.log("onMouseDown(MouseDownEvent)");
if (event.getNativeButton() == NativeEvent.BUTTON_LEFT) {
GanttWidget.this.onTouchOrMouseDown(event.getNativeEvent());
} else {
secondaryClickOnNextMouseUp = true;
new Timer() {
@Override
public void run() {
secondaryClickOnNextMouseUp = false;
}
}.schedule(CLICK_INTERVAL);
event.stopPropagation();
}
}
};
private MouseUpHandler mouseUpHandler = new MouseUpHandler() {
@Override
public void onMouseUp(MouseUpEvent event) {
if (event.getNativeButton() == NativeEvent.BUTTON_LEFT) {
GanttWidget.this.onTouchOrMouseUp(event.getNativeEvent());
} else {
if (secondaryClickOnNextMouseUp) {
Element bar = getBar(event.getNativeEvent());
if (bar != null && isEnabled()) {
getRpc().stepClicked(getStepUid(bar),
event.getNativeEvent(), bar);
}
}
secondaryClickOnNextMouseUp = true;
}
}
};
private ContextMenuHandler contextMenuHandler = new ContextMenuHandler() {
@Override
public void onContextMenu(ContextMenuEvent event) {
if (!defaultContextMenuEnabled) {
event.preventDefault();
}
}
};
private MouseMoveHandler mouseMoveHandler = new MouseMoveHandler() {
@Override
public void onMouseMove(MouseMoveEvent event) {
GanttWidget.this.onTouchOrMouseMove(event.getNativeEvent());
event.preventDefault();
}
};
private PointerDownHandler msPointerDownHandler = new PointerDownHandler() {
@Override
public void onPointerDown(PointerDownEvent event) {
GWT.log("onPointerDown(PointerDownEvent)");
if (currentPointerEventId == -1) {
currentPointerEventId = event.getPointerId();
} else {
event.preventDefault();
return; // multi-touch not supported
}
pendingPointerDownEvent = event.getNativeEvent();
capturePoint = new Point(
getTouchOrMouseClientX(event.getNativeEvent()),
getTouchOrMouseClientY(event.getNativeEvent()));
pointerTouchStartedTimer.schedule(POINTER_TOUCH_DETECTION_INTERVAL);
event.preventDefault();
}
};
private PointerUpHandler msPointerUpHandler = new PointerUpHandler() {
@Override
public void onPointerUp(PointerUpEvent event) {
currentPointerEventId = -1;
pointerTouchStartedTimer.cancel();
pendingPointerDownEvent = null;
GanttWidget.this.onTouchOrMouseUp(event.getNativeEvent());
event.preventDefault();
}
};
private PointerMoveHandler msPointerMoveHandler = new PointerMoveHandler() {
@Override
public void onPointerMove(PointerMoveEvent event) {
if (capturePoint == null) {
return;
}
movePoint = new Point(
getTouchOrMouseClientX(event.getNativeEvent()),
getTouchOrMouseClientY(event.getNativeEvent()));
// do nothing, if touch position has not changed
if (!(capturePoint.getX() == movePoint.getX() && capturePoint
.getY() == movePoint.getY())) {
GanttWidget.this.onTouchOrMouseMove(event.getNativeEvent());
}
}
};
private PointerCancelHandler msPointerCancelHandler = new PointerCancelHandler() {
@Override
public void onPointerCancel(PointerCancelEvent event) {
currentPointerEventId = -1;
pointerTouchStartedTimer.cancel();
pendingPointerDownEvent = null;
onCancelTouch(event.getNativeEvent());
}
};
private TouchStartHandler touchStartHandler = new TouchStartHandler() {
@Override
public void onTouchStart(TouchStartEvent event) {
if (event.getTargetTouches().length() == 1) {
JavaScriptObject target = event.getNativeEvent()
.getEventTarget().cast();
containerScrollStartPosY = -1;
containerScrollStartPosX = -1;
if (target == container || target == content
|| (!isMovableSteps())) {
boolean preventDefaultAndReturn = false;
// store x,y position for 'manual' vertical scrolling
if (isContentOverflowingVertically()) {
containerScrollStartPosY = container.getScrollTop()
+ event.getTouches().get(0).getPageY();
preventDefaultAndReturn = true;
}
if (isContentOverflowingHorizontally()) {
containerScrollStartPosX = container.getScrollLeft()
+ event.getTouches().get(0).getPageX();
preventDefaultAndReturn = true;
}
if (preventDefaultAndReturn) {
event.preventDefault();
return;
}
}
GanttWidget.this.onTouchOrMouseDown(event.getNativeEvent());
}
event.preventDefault();
}
};
private TouchEndHandler touchEndHandler = new TouchEndHandler() {
@Override
public void onTouchEnd(TouchEndEvent event) {
containerScrollStartPosY = -1;
containerScrollStartPosX = -1;
GanttWidget.this.onTouchOrMouseUp(event.getNativeEvent());
event.preventDefault();
}
};
private TouchMoveHandler touchMoveHandler = new TouchMoveHandler() {
@Override
public void onTouchMove(TouchMoveEvent event) {
if (event.getChangedTouches().length() == 1) {
boolean preventDefaultAndReturn = false;
// did we intend to scroll the container?
// apply 'manual' vertical scrolling
if (containerScrollStartPosY != -1) {
container.setScrollTop(containerScrollStartPosY
- event.getChangedTouches().get(0).getPageY());
preventDefaultAndReturn = true;
}
if (containerScrollStartPosX != -1) {
container.setScrollLeft(containerScrollStartPosX
- event.getChangedTouches().get(0).getPageX());
preventDefaultAndReturn = true;
}
if (preventDefaultAndReturn) {
event.preventDefault();
return;
}
if (GanttWidget.this.onTouchOrMouseMove(event.getNativeEvent())) {
event.preventDefault();
}
}
}
};
private TouchCancelHandler touchCancelHandler = new TouchCancelHandler() {
@Override
public void onTouchCancel(TouchCancelEvent event) {
containerScrollStartPosY = -1;
containerScrollStartPosX = -1;
onCancelTouch(event.getNativeEvent());
}
};
private boolean ie, ie8, chrome, safari, webkit;
public GanttWidget() {
setElement(DivElement.as(DOM.createDiv()));
setStyleName(STYLE_GANTT);
moveElement.setClassName(STYLE_MOVE_ELEMENT);
// not visible by default
moveElement.getStyle().setDisplay(Display.NONE);
timeline = GWT.create(TimelineWidget.class);
container = DivElement.as(DOM.createDiv());
container.setClassName(STYLE_GANTT_CONTAINER);
content = DivElement.as(DOM.createDiv());
content.setClassName(STYLE_GANTT_CONTENT);
container.appendChild(content);
content.appendChild(moveElement);
scrollbarSpacer = DivElement.as(DOM.createDiv());
scrollbarSpacer.getStyle().setHeight(
AbstractNativeScrollbar.getNativeScrollbarHeight(), Unit.PX);
scrollbarSpacer.getStyle().setDisplay(Display.NONE);
getElement().appendChild(timeline.getElement());
getElement().appendChild(container);
getElement().appendChild(scrollbarSpacer);
}
public void initWidget(GanttRpc ganttRpc,
LocaleDataProvider localeDataProvider) {
setRpc(ganttRpc);
setLocaleDataProvider(localeDataProvider);
resetListeners();
}
/**
* Add new StepWidget into content area.
*
* @param stepIndex
* Index of step (0 based) (not element index in container)
* @param widget
*/
public void addStep(int stepIndex, Widget widget) {
DivElement bar = DivElement.as(widget.getElement());
insert(stepIndex + getAdditonalContentElementCount(), widget);
int widgetsInContainer = getChildren().size();
int indexInWidgetContainer = stepIndex + extraContentElements.size();
// bar height should be defined in css
int height = getElementHeightWithMargin(bar);
int lineIndex = -1;
if (widget instanceof StepWidget) {
lineIndex = ((StepWidget)widget).getStep().getLineIndex();
}
if (lineIndex >= 0) {
double top = height * lineIndex;
bar.getStyle().setTop(top, Unit.PX);
if( contentHeight < (top + height) ) {
contentHeight = top + height;
}
} else if ( (stepIndex + 1) < (widgetsInContainer - extraContentElements.size()) ) {
// not the first step, update contentHeight by the previous step
int prevIndex = indexInWidgetContainer - 1;
Widget w = getWidget(prevIndex);
if (w instanceof StepWidget) {
double top = parseSize(w.getElement().getStyle().getTop(), "px");
top += getElementHeightWithMargin(w.getElement());
bar.getStyle().setTop(top, Unit.PX);
updateTopForAllStepsBelow(indexInWidgetContainer + 1, height);
}
contentHeight += height;
} else {
bar.getStyle().setTop(contentHeight, Unit.PX);
contentHeight += height;
}
registerBarEventListener(bar);
}
/**
* Remove Widget from the content area.
*
* @param widget
*/
public void removeStep(Widget widget) {
remove(widget);
}
/**
* Update Gantt chart's timeline and content for the given steps. This won't
* add any steps, but will update the content widths and heights.
*
* @param steps
*/
public void update(List<StepWidget> steps) {
if (startDate < 0 || endDate < 0 || startDate >= endDate) {
GWT.log("Invalid start and end dates. Gantt chart can't be rendered. Start: "
+ startDate + ", End: " + endDate);
return;
}
content.getStyle().setHeight(contentHeight, Unit.PX);
GWT.log("GanttWidget's active TimeZone: "
+ getLocaleDataProvider().getTimeZone().getID()
+ " (raw offset: "
+ getLocaleDataProvider().getTimeZone().getStandardOffset()
+ ")");
// tell timeline to notice vertical scrollbar before updating it
timeline.setNoticeVerticalScrollbarWidth(isContentOverflowingVertically());
timeline.update(resolution, startDate, endDate, firstDayOfRange,
firstHourOfRange, localeDataProvider);
setContentMinWidth(timeline.getMinWidth());
updateContainerStyle();
updateContentWidth();
updateStepWidths(steps);
wasTimelineOverflowingHorizontally = timeline
.isTimelineOverflowingHorizontally();
}
/**
* Set minimum width for the content element.
*
* @param minWidth
* Minimum width in pixels.
*/
public void setContentMinWidth(int minWidth) {
this.minWidth = minWidth;
content.getStyle().setProperty("minWidth", this.minWidth + "px");
}
/**
* Return minimal width of the content.
*
* @return Minimum width in pixels.
*/
public int getMinWidth() {
return minWidth;
}
/**
* Get current currently active timeline {@link Resolution}.
*
* @return resolution enum
*/
public Resolution getResolution() {
return resolution;
}
/**
* Set Gantt's timeline resolution.
*
* @param resolution
* New timeline resolution.
*/
public void setResolution(Resolution resolution) {
this.resolution = resolution;
}
/**
* Get timeline's start date. Date value should follow specification in
* {@link Date#getTime()}.
*
* @return Start date in milliseconds.
*/
public long getStartDate() {
return startDate;
}
/**
* Set timeline's start date. Date value should follow specification in
* {@link Date#getTime()}.
*
* @param startDate
* New start date in milliseconds.
*/
public void setStartDate(Long startDate) {
this.startDate = (startDate != null) ? startDate : 0;
}
/**
* Get timeline's end date. Date value should follow specification in
* {@link Date#getTime()}.
*
* @return End date in milliseconds.
*/
public long getEndDate() {
return endDate;
}
/**
* Set timeline's end date. Date value should follow specification in
* {@link Date#getTime()}.
*
* @param endDate
* New end date in milliseconds.
*/
public void setEndDate(Long endDate) {
this.endDate = (endDate != null) ? endDate : 0;
}
/**
* Set first day of timeline's date range. Value is between 1-7, where 1 is
* SUNDAY.
*
* @param firstDayOfRange
* Value between 1-7.
*/
public void setFirstDayOfRange(int firstDayOfRange) {
this.firstDayOfRange = firstDayOfRange;
}
public void setFirstHourOfRange(int firstHourOfRange) {
this.firstHourOfRange = firstHourOfRange;
}
/**
* Notify Gantt widget that height has changed. Delegates necessary changes
* to child elements.
*
* @param height
* New height in pixels
*/
public void notifyHeightChanged(int height) {
if (container != null && timeline != null) {
container.getStyle().setHeight(
height - getTimelineHeight()
- getHorizontalScrollbarSpacerHeight(), Unit.PX);
boolean overflow = isContentOverflowingVertically();
if (wasContentOverflowingVertically != overflow) {
wasContentOverflowingVertically = overflow;
timeline.setNoticeVerticalScrollbarWidth(overflow);
// width has changed due to vertical scrollbar
// appearing/disappearing
internalHandleWidthChange();
}
}
}
/**
* Get Timeline widget height.
*
* @return
*/
public int getTimelineHeight() {
if (timeline != null) {
return timeline.getElement().getClientHeight();
}
return 0;
}
/**
* Notify Gantt widget that width has changed. Delegates necessary changes
* to child elements.
*
* @param width
* New width in pixels
*/
public void notifyWidthChanged(int width) {
if (timeline != null) {
boolean overflow = timeline.checkTimelineOverflowingHorizontally();
if (timeline.isAlwaysCalculatePixelWidths()
|| wasTimelineOverflowingHorizontally != overflow) {
// scrollbar has just appeared/disappeared
wasTimelineOverflowingHorizontally = overflow;
if (!wasTimelineOverflowingHorizontally) {
timeline.setScrollLeft(0);
}
}
internalHandleWidthChange();
}
}
protected void internalHandleWidthChange() {
timeline.updateWidths();
updateContainerStyle();
updateContentWidth();
}
/**
* Set RPC implementation that is used to communicate with the server.
*
* @param ganttRpc
* GanttRpc
*/
public void setRpc(GanttRpc ganttRpc) {
this.ganttRpc = ganttRpc;
}
/**
* Get RPC implementation that is used to communicate with the server.
*
* @return GanttRpc
*/
public GanttRpc getRpc() {
return ganttRpc;
}
/**
* Reset listeners.
*/
public void resetListeners() {
Event.sinkEvents(container, Event.ONSCROLL);
Event.sinkEvents(container, Event.ONCONTEXTMENU);
if (contextMenuHandlerRegistration == null) {
contextMenuHandlerRegistration = addDomHandler(contextMenuHandler,
ContextMenuEvent.getType());
}
if (scrollHandlerRegistration == null) {
scrollHandlerRegistration = addHandler(scrollHandler,
ScrollEvent.getType());
}
if (isMsTouchSupported()) {
// IE10 pointer events (ms-prefixed events)
if (msPointerDownHandlerRegistration == null) {
msPointerDownHandlerRegistration = addDomHandler(
msPointerDownHandler, PointerDownEvent.getType());
}
if (msPointerUpHandlerRegistration == null) {
msPointerUpHandlerRegistration = addDomHandler(
msPointerUpHandler, PointerUpEvent.getType());
}
if (msPointerMoveHandlerRegistration == null) {
msPointerMoveHandlerRegistration = addDomHandler(
msPointerMoveHandler, PointerMoveEvent.getType());
}
if (msPointerCancelHandlerRegistration == null) {
msPointerCancelHandlerRegistration = addHandler(
msPointerCancelHandler, PointerCancelEvent.getType());
}
} else if (touchSupported) {
// touch events replaces mouse events
if (touchStartHandlerRegistration == null) {
touchStartHandlerRegistration = addDomHandler(
touchStartHandler, TouchStartEvent.getType());
}
if (touchEndHandlerRegistration == null) {
touchEndHandlerRegistration = addDomHandler(touchEndHandler,
TouchEndEvent.getType());
}
if (touchMoveHandlerRegistration == null) {
touchMoveHandlerRegistration = addDomHandler(touchMoveHandler,
TouchMoveEvent.getType());
}
if (touchCancelHandlerRegistration == null) {
touchCancelHandlerRegistration = addHandler(touchCancelHandler,
TouchCancelEvent.getType());
}
} else {
if (mouseDownHandlerHandlerRegistration == null) {
mouseDownHandlerHandlerRegistration = addDomHandler(
mouseDownHandler, MouseDownEvent.getType());
}
if (mouseUpHandlerHandlerRegistration == null) {
mouseUpHandlerHandlerRegistration = addDomHandler(
mouseUpHandler, MouseUpEvent.getType());
}
if (isMovableSteps() || isResizableSteps()) {
if (mouseMoveHandlerRegistration == null) {
mouseMoveHandlerRegistration = addDomHandler(
mouseMoveHandler, MouseMoveEvent.getType());
}
} else if (mouseMoveHandlerRegistration != null) {
mouseMoveHandlerRegistration.removeHandler();
mouseMoveHandlerRegistration = null;
}
}
}
/**
* Return true if background grid is enabled.
*
* @return True if background grid is enabled.
*/
public boolean isBackgroundGridEnabled() {
return backgroundGridEnabled;
}
/**
* Set background grid enabled. Next time the widget is painted, the grid is
* shown on the background of the container.
*
* @param backgroundGridEnabled
* True sets background grid enabled.
*/
public void setBackgroundGridEnabled(boolean backgroundGridEnabled) {
this.backgroundGridEnabled = backgroundGridEnabled;
}
/**
* Enable or disable touch support.
*
* @param touchSupported
* True enables touch support.
*/
public void setTouchSupported(boolean touchSupported) {
this.touchSupported = touchSupported;
}
/**
* Are touch events supported.
*
* @return True if touch events are supported.
*/
public boolean isTouchSupported() {
return touchSupported;
}
/**
* Enable or disable resizable steps.
*
* @param resizableSteps
* True enables step resizing.
*/
public void setResizableSteps(boolean resizableSteps) {
this.resizableSteps = resizableSteps;
}
/**
* Returns true if widget is enabled and steps are resizable.
*
* @return
*/
public boolean isResizableSteps() {
return isEnabled() && resizableSteps;
}
/**
* Enable or disable movable step's -feature.
*
* @param movableSteps
* True makes steps movable.
*/
public void setMovableSteps(boolean movableSteps) {
this.movableSteps = movableSteps;
}
/**
* Returns true if widget is enabled and steps are movable.
*
* @return
*/
public boolean isMovableSteps() {
return isEnabled() && movableSteps;
}
/**
* Returns true if the widget is enabled the steps are movable and the steps are movable between lines
* @return
*/
public boolean isMovableStepsBetweenLines() {
return isMovableSteps() && movableStepsBetweenLines;
}
/**
* Returns true if the the bar is not a sub bar and
* the widget is enabled the steps are movable and the steps are movable between lines
* @return
*/
public boolean isMovableStepsBetweenLines(Element bar) {
return isMovableStepsBetweenLines() && movableStepsBetweenLines && !isSubBar(bar);
}
/**
* Enable or disable movable steps between lines feature
*
* @param movableStepsBetweenLines True makes steps movable between lines
*/
public void setMovableStepsBetweenLines(boolean movableStepsBetweenLines) {
this.movableStepsBetweenLines = movableStepsBetweenLines;
}
public boolean isMonthRowVisible() {
return timeline.isMonthRowVisible();
}
public void setMonthRowVisible(boolean monthRowVisible) {
timeline.setMonthRowVisible(monthRowVisible);
}
public boolean isYearRowVisible() {
return timeline.isYearRowVisible();
}
public void setYearRowVisible(boolean yearRowVisible) {
timeline.setYearRowVisible(yearRowVisible);
}
public String getMonthFormat() {
return timeline.getMonthFormat();
}
public void setMonthFormat(String monthFormat) {
timeline.setMonthFormat(monthFormat);
}
public void setYearFormat(String yearFormat) {
timeline.setYearFormat(yearFormat);
}
public String getYearFormat() {
return timeline.getYearFormat();
}
public void setWeekFormat(String weekFormat) {
timeline.setWeekFormat(weekFormat);
}
public void setDayFormat(String dayFormat) {
timeline.setDayFormat(dayFormat);
}
public boolean isDefaultContextMenuEnabled() {
return defaultContextMenuEnabled;
}
public void setDefaultContextMenuEnabled(boolean defaultContextMenuEnabled) {
this.defaultContextMenuEnabled = defaultContextMenuEnabled;
}
/**
* Set LocaleDataProvider that is used to provide translations of months and
* weekdays.
*
* @param localeDataProvider
*/
public void setLocaleDataProvider(LocaleDataProvider localeDataProvider) {
this.localeDataProvider = localeDataProvider;
}
public LocaleDataProvider getLocaleDataProvider() {
return localeDataProvider;
}
/**
* Notify which browser this widget should optimize to. Usually just one
* argument is true.
*
* @param ie
* @param chrome
* @param safari
* @param webkit
* @param majorVersion
*/
public void setBrowserInfo(boolean ie, boolean chrome, boolean safari,
boolean webkit, int majorVersion) {
this.ie = ie;
ie8 = ie && majorVersion == 8;
this.chrome = chrome;
this.safari = safari;
this.webkit = webkit;
timeline.setBrowserInfo(ie, ie8, majorVersion);
}
/**
* @see TimelineWidget#setAlwaysCalculatePixelWidths(boolean)
* @param calcPx
*/
public void setAlwaysCalculatePixelWidths(boolean calcPx) {
timeline.setAlwaysCalculatePixelWidths(calcPx);
}
/**
* Sets timeline's force update flag up. Next
* {@link TimelineWidget#update(Resolution, long, long, int, int, LocaleDataProvider)}
* call knows then to update everything.
*/
public void setForceUpdateTimeline() {
if (timeline == null) {
return;
}
timeline.setForceUpdate();
}
@Override
public boolean isEnabled() {
return enabled;
}
@Override
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Element getScrollContainer() {
return container;
}
/**
* Get height of the scroll container. Includes the horizontal scrollbar
* spacer.
*
* @return
*/
public int getScrollContainerHeight() {
if (scrollbarSpacer.getStyle().getDisplay().isEmpty()) {
return getScrollContainer().getClientHeight()
+ scrollbarSpacer.getClientHeight();
}
return getScrollContainer().getClientHeight();
}
/**
* Return true, if content is overflowing vertically. This means also that
* vertical scroll bar is visible.
*
* @return
*/
public boolean isContentOverflowingVertically() {
if (content == null || container == null) {
return false;
}
return content.getClientHeight() > container.getClientHeight();
}
/**
* Return true, if content is overflowing horizontally. This means also that
* horizontal scroll bar is visible.
*
* @return
*/
public boolean isContentOverflowingHorizontally() {
// state of horizontal overflow is handled by timeline widget
if (content == null || container == null || timeline == null) {
return false;
}
return timeline.isTimelineOverflowingHorizontally();
}
/**
* Show empty spacing in horizontal scrollbar's position.
*/
public void showHorizontalScrollbarSpacer() {
if (!scrollbarSpacer.getStyle().getDisplay().isEmpty()) {
scrollbarSpacer.getStyle().clearDisplay();
notifyHeightChanged(getOffsetHeight());
}
}
/**
* Hide empty spacing in horizontal scrollbar's position.
*/
public void hideHorizontalScrollbarSpacer() {
if (scrollbarSpacer.getStyle().getDisplay().isEmpty()) {
scrollbarSpacer.getStyle().setDisplay(Display.NONE);
notifyHeightChanged(getOffsetHeight());
}
}
public void updateBarPercentagePosition(long startDate, long endDate,
long ownerStartDate, long ownerEndDate, Element bar) {
double ownerStepWidth = GanttUtil.getBoundingClientRectWidth(bar
.getParentElement());
String sLeft = timeline.getLeftPositionPercentageStringForDate(
startDate, ownerStepWidth, ownerStartDate, ownerEndDate);
bar.getStyle().setProperty("left", sLeft);
double range = ownerEndDate - ownerStartDate;
String sWidth = timeline.getWidthPercentageStringForDateInterval(
endDate - startDate, range);
bar.getStyle().setProperty("width", sWidth);
}
public void updateBarPercentagePosition(long startDate, long endDate,
Element bar) {
String sLeft = timeline.getLeftPositionPercentageStringForDate(
startDate, getContentWidth());
bar.getStyle().setProperty("left", sLeft);
String sWidth = timeline
.getWidthPercentageStringForDateInterval(endDate - startDate);
bar.getStyle().setProperty("width", sWidth);
}
/**
* Register and add Widget inside the content.
*/
public void registerContentElement(Widget widget) {
if (extraContentElements.add(widget)) {
insertFirst(widget);
}
}
/**
* Unregister and remove element from the content.
*/
public void unregisterContentElement(Widget widget) {
if (widget != null) {
extraContentElements.remove(widget);
widget.removeFromParent();
}
}
public native boolean isMsTouchSupported()
/*-{
return !!navigator.msMaxTouchPoints;
}-*/;
@Override
public void add(Widget w) {
super.add(w, content);
}
@Override
protected void insert(Widget child, Element container, int beforeIndex,
boolean domInsert) {
// Validate index; adjust if the widget is already a child of this
// panel.
int adjustedBeforeIndex = adjustIndex(child, beforeIndex
- getAdditionalNonWidgetContentElementCount());
// Detach new child.
child.removeFromParent();
// Logical attach.
getChildren().insert(child, adjustedBeforeIndex);
// Physical attach.
if (domInsert) {
DOM.insertChild(container, child.getElement(), beforeIndex);
} else {
DOM.appendChild(container, child.getElement());
}
// Adopt.
adopt(child);
}
public void insert(int beforeIndex, Widget w) {
insert(w, content, beforeIndex, true);
}
public void insertFirst(Widget child) {
// Detach new child.
child.removeFromParent();
// Logical attach.
getChildren().insert(child, 0);
// Physical attach.
content.insertFirst(child.getElement());
// Adopt.
adopt(child);
}
@Override
public boolean remove(Widget w) {
if (!(w instanceof StepWidget)) {
return super.remove(w);
} else {
StepWidget stepWidget = (StepWidget) w;
if( stepWidget.getStep().getLineIndex() >= 0 ) {
return super.remove(stepWidget);
} else {
int startIndex = getWidgetIndex(w);
int height = getElementHeightWithMargin(w.getElement());
contentHeight -= height;
if ((startIndex = removeAndReturnIndex(w)) >= 0) {
updateTopForAllStepsBelow(startIndex, -height);
// update content height
content.getStyle().setHeight(contentHeight, Unit.PX);
return true;
}
return false;
}
}
}
public int removeAndReturnIndex(Widget w) {
int index = -1;
// Validate.
if (w.getParent() != this) {
return index;
}
// Orphan.
try {
orphan(w);
} finally {
index = getWidgetIndex(w);
// Physical detach.
Element elem = w.getElement();
content.removeChild(elem);
// Logical detach.
getChildren().remove(w);
}
return index;
}
/**
* Update step widths based on the timeline. Timeline's width have to be
* final at this point.
*
* @param steps
*/
protected void updateStepWidths(Collection<StepWidget> steps) {
for (StepWidget step : steps) {
step.updateWidth();
}
}
protected Element getBar(NativeEvent event) {
Element element = event.getEventTarget().cast();
if (element == null || isSvg(element)) {
return null;
}
Element parent = element;
while (parent.getParentElement() != null
&& parent.getParentElement() != content && !isBar(parent)) {
parent = parent.getParentElement();
}
if (isBar(parent)) {
return parent;
}
return null;
}
protected boolean isBgElement(Element target) {
return bgGrid != null && bgGrid.equals(target);
}
private boolean isSvg(Element element) {
// safety check to avoid calling non existing functions
if (!isPartOfSvg(element)) {
return element.hasTagName("svg");
}
return true;
}
private static native boolean isPartOfSvg(Element element)
/*-{
if(element.ownerSVGElement) {
return true;
}
return false;
}-*/;
protected boolean isBar(Element element) {
if (isSvg(element)) {
return false;
}
return element.hasClassName(AbstractStepWidget.STYLE_BAR);
}
protected boolean isSubBar(Element element) {
if (isSvg(element)) {
return false;
}
return element.hasClassName(SubStepWidget.STYLE_SUB_BAR);
}
protected boolean hasSubBars(Element element) {
if (isSvg(element)) {
return false;
}
return element.hasClassName(StepWidget.STYLE_HAS_SUB_STEPS);
}
/**
* This is called when target bar element is moved successfully. Element's
* CSS attributes 'left' and 'width' are updated (unit in pixels).
*
* @param bar
* Moved Bar element
* @param y
*/
protected void moveCompleted(Element bar, int y) {
double deltay = y - capturePoint.getY();
GWT.log("Position delta y: " + deltay + "px");
Element newPosition;
if( isMovableStepsBetweenLines(bar) ) {
newPosition = bar; //if movement between lines are enabled findStepElement may give wrong result
} else {
newPosition = findStepElement(bar, y, deltay);
}
internalMoveOrResizeCompleted(bar, newPosition, true);
}
/**
* This is called when target bar is resized successfully. Element's CSS
* attributes 'left' and 'width' are updated (unit in pixels).
*
* @param bar
* Resized Bar element
*/
protected void resizingCompleted(Element bar) {
internalMoveOrResizeCompleted(bar, null, false);
}
protected void onTouchOrMouseDown(NativeEvent event) {
Element bar = getBar(event);
if (bar == null) {
return;
}
targetBarElement = bar;
capturePoint = new Point(getTouchOrMouseClientX(event),
getTouchOrMouseClientY(event));
movePoint = new Point(getTouchOrMouseClientX(event),
getTouchOrMouseClientY(event));
capturePointLeftPercentage = bar.getStyle().getProperty("left");
capturePointWidthPercentage = bar.getStyle().getProperty("width");
capturePointLeftPx = bar.getOffsetLeft();
capturePointTopPx = bar.getOffsetTop();
capturePointWidthPx = bar.getClientWidth();
capturePointBgColor = bar.getStyle().getBackgroundColor();
if (detectResizing(bar)) {
resizing = true;
resizingFromLeft = isResizingLeft(bar);
} else {
resizing = false;
}
disallowClickTimer.schedule(CLICK_INTERVAL);
event.stopPropagation();
}
protected void onTouchOrMouseUp(NativeEvent event) {
if (targetBarElement == null) {
return;
}
Element bar = getBar(event);
disallowClickTimer.cancel();
if (bar == targetBarElement && isClickOnNextMouseup()) {
clickOnNextMouseUp = true;
if (isEnabled()) {
getRpc().stepClicked(getStepUid(bar), event, bar);
}
} else {
clickOnNextMouseUp = true;
bar = targetBarElement;
if (resizing) {
removeResizingStyles(bar);
if (resizingInProgress) {
resizingCompleted(bar);
} else {
resetBarPosition(bar);
}
} else if (isMovableSteps()) {
// moving in progress
removeMovingStyles(bar);
if (moveInProgress) {
moveCompleted(bar, getTouchOrMouseClientY(event));
} else {
resetBarPosition(bar);
}
}
bar.getStyle().setBackgroundColor(capturePointBgColor);
}
stopDrag(event);
}
protected void stopDrag(NativeEvent event) {
hideMoveElement();
targetBarElement = null;
capturePoint = null;
resizing = false;
resizingInProgress = false;
moveInProgress = false;
event.stopPropagation();
}
protected void onCancelTouch(NativeEvent event) {
if (targetBarElement == null) {
return;
}
resetBarPosition(targetBarElement);
stopDrag(event);
}
/**
* Handle step's move event.
*
* @param event
* NativeEvent
* @return True, if this event was handled and had effect on step.
*/
protected boolean onTouchOrMouseMove(NativeEvent event) {
Element bar = getBar(event);
if (bar != null) {
movePoint = new Point(getTouchOrMouseClientX(event),
getTouchOrMouseClientY(event));
showResizingPointer(bar, detectResizing(bar));
}
if (targetBarElement == null) {
return false;
}
bar = targetBarElement;
disallowClickTimer.cancel();
clickOnNextMouseUp = false;
// calculate delta x and y by original position and the current one.
double deltax = getTouchOrMouseClientX(event) - capturePoint.getX();
double deltay = getTouchOrMouseClientY(event) - capturePoint.getY();
GWT.log("Position delta x: " + deltax + "px");
if (resizing) {
resizingInProgress = deltax != 0.0;
if (resizingFromLeft) {
updateBarResizingLeft(bar, deltax);
} else {
updateBarResizingRight(bar, deltax);
}
addResizingStyles(bar);
bar.getStyle().clearBackgroundColor();
} else if (isMovableSteps()) {
updateMoveInProgressFlag(bar, deltax, deltay);
updateBarMovingPosition(bar, deltax);
addMovingStyles(bar);
bar.getStyle().clearBackgroundColor();
if( isMovableStepsBetweenLines(bar) ) {
updateBarYPosition(bar, deltay);
}
}
// event.stopPropagation();
return true;
}
protected void updateMoveInProgressFlag(Element bar, double deltax, double deltay) {
moveInProgress = deltax != 0.0 && (!isMovableStepsBetweenLines(bar) || deltay != 0.0 ) ;
}
/**
* Helper method to find Step element by given starting point and y-position
* and delta-y. Starting point is there to optimize performance a bit as
* there's no need to iterate through every single step element.
*
* @param startFromBar
* Starting point element
* @param y
* target y-axis position
* @param deltay
* delta-y relative to starting point element.
* @return Step element at y-axis position. May be same element as given
* startFromBar element.
*/
protected Element findStepElement(Element startFromBar, int y, double deltay) {
if (isSubBar(startFromBar)) {
startFromBar = startFromBar.getParentElement();
}
if (isBetween(y, startFromBar.getAbsoluteTop(),
startFromBar.getAbsoluteBottom())) {
return startFromBar;
}
int startIndex = getChildIndex(content, startFromBar);
Element barCanditate;
int i = startIndex;
if (deltay > 0) {
i++;
for (; i < content.getChildCount(); i++) {
barCanditate = Element.as(content.getChild(i));
if (isBetween(y, barCanditate.getAbsoluteTop(),
barCanditate.getAbsoluteBottom())) {
return barCanditate;
}
}
} else if (deltay < 0) {
i--;
for (; i >= getAdditonalContentElementCount(); i--) {
barCanditate = Element.as(content.getChild(i));
if (isBetween(y, barCanditate.getAbsoluteTop(),
barCanditate.getAbsoluteBottom())) {
return barCanditate;
}
}
}
return startFromBar;
}
/**
* Get UID for the given Step element. Or null if StepWidget for the element
* doesn't exist in container.
*/
protected String getStepUid(Element stepElement) {
if (isSubBar(stepElement)) {
return getSubStepUid(stepElement);
}
// get widget by index known by this ComplexPanel.
StepWidget widget = getStepWidget(stepElement);
if (widget != null) {
return widget.getStep().getUid();
}
return null;
}
protected String getSubStepUid(Element subStepElement) {
Element stepElement = subStepElement.getParentElement();
StepWidget widget = getStepWidget(stepElement);
if (widget != null) {
return widget.getStepUidBySubStepElement(subStepElement);
}
return null;
}
protected SubStepWidget getSubStepWidget(Element subStepElement) {
Element stepElement = subStepElement.getParentElement();
StepWidget widget = getStepWidget(stepElement);
if (widget != null) {
return widget.getSubStepWidgetByElement(subStepElement);
}
return null;
}
protected StepWidget getStepWidget(Element stepElement) {
Widget widget = getWidget(getChildIndex(content, stepElement)
- getAdditionalNonWidgetContentElementCount());
if (widget instanceof StepWidget) {
return (StepWidget) widget;
}
return null;
}
protected AbstractStepWidget getAbstractStepWidget(Element stepElement) {
if (isSubBar(stepElement)) {
return getSubStepWidget(stepElement);
}
return getStepWidget(stepElement);
}
protected BgGridElement createBackgroundGrid() {
// implementation may be overridden via deferred binding. There is
// BgGridSvgElement alternative available and also used by Chrome.
BgGridElement grid = GWT.create(BgGridCssElement.class);
grid.init(container, content);
return grid;
}
private void updateTopForAllStepsBelow(int startIndex, int delta) {
// update top for all elements below
Element elementBelow;
for (int i = startIndex; i < getChildren().size(); i++) {
elementBelow = getWidget(i).getElement();
double top = parseSize(elementBelow.getStyle().getTop(), "px");
elementBelow.getStyle().setTop(top + delta, Unit.PX);
}
}
private double calculateBackgroundGridWidth() {
return timeline.calculateTimelineWidth();
}
private void updateContainerStyle() {
if (bgGrid == null) {
bgGrid = createBackgroundGrid();
}
if (!isBackgroundGridEnabled()) {
bgGrid.hide();
return;
}
// Container element has a background image that is positioned, sized
// and repeated to fill the whole container with a nice grid background.
// Update 'background-size' in container element to match the background
// grid's cell width and height to match with the timeline and rows.
// Update also 'background-position' in container to match the first
// resolution element width in the timeline, IF it's not same as all
// other resolution element widths.
int resDivElementCount = timeline.getResolutionDiv().getChildCount();
if (resDivElementCount == 0) {
return;
}
Element secondResolutionBlock = null;
Double firstResolutionBlockWidth = timeline
.getFirstResolutionElementWidth();
if (firstResolutionBlockWidth == null) {
return;
}
Double secondResolutionBlockWidth = null;
if (resDivElementCount > 2) {
secondResolutionBlock = Element.as(timeline.getResolutionDiv()
.getChild(1));
secondResolutionBlockWidth = getBoundingClientRectWidth(secondResolutionBlock);
}
boolean contentOverflowingHorizontally = isContentOverflowingHorizontally();
boolean adjustBgPosition = secondResolutionBlockWidth != null
&& !firstResolutionBlockWidth
.equals(secondResolutionBlockWidth);
double gridBlockWidthPx = 0.0;
if (!adjustBgPosition) {
gridBlockWidthPx = firstResolutionBlockWidth;
} else {
gridBlockWidthPx = secondResolutionBlockWidth;
}
updateContainerBackgroundSize(contentOverflowingHorizontally,
gridBlockWidthPx);
updateContainerBackgroundPosition(firstResolutionBlockWidth,
contentOverflowingHorizontally, gridBlockWidthPx,
adjustBgPosition);
}
private void updateContainerBackgroundSize(
boolean contentOverflowingHorizontally, double gridBlockWidthPx) {
String gridBlockWidth = null;
if (contentOverflowingHorizontally || useAlwaysPxSizeInBackground()) {
gridBlockWidth = timeline.toCssCalcOrNumberString(gridBlockWidthPx,
"px");
} else {
double contentWidth = getBoundingClientRectWidth(content);
gridBlockWidth = timeline.toCssCalcOrNumberString(
(100.0 / contentWidth) * gridBlockWidthPx, "%");
}
int gridBlockHeightPx = getBgGridCellHeight();
bgGrid.setBackgroundSize(gridBlockWidth, gridBlockWidthPx,
gridBlockHeightPx);
}
private void updateContainerBackgroundPosition(
double firstResolutionBlockWidth,
boolean contentOverflowingHorizontally, double gridBlockWidthPx,
boolean adjustBgPosition) {
if (adjustBgPosition) {
double realBgPosXPx = firstResolutionBlockWidth - 1.0;
if (useAlwaysPxSizeInBackground() || contentOverflowingHorizontally) {
bgGrid.setBackgroundPosition(
timeline.toCssCalcOrNumberString(realBgPosXPx, "px"),
"0px", realBgPosXPx, 0);
} else {
double timelineWidth = calculateBackgroundGridWidth();
double relativeBgAreaWidth = timelineWidth - gridBlockWidthPx;
double bgPosX = (100.0 / relativeBgAreaWidth) * realBgPosXPx;
bgGrid.setBackgroundPosition(
timeline.toCssCalcOrNumberString(bgPosX, "%"), "0px",
realBgPosXPx, 0);
}
} else {
bgGrid.setBackgroundPosition("-1px", "0", -1, 0);
}
}
private boolean useAlwaysPxSizeInBackground() {
return ie || chrome || safari || webkit;
}
private int getBgGridCellHeight() {
int gridBlockHeightPx = 0;
int firstStepIndex = getAdditonalContentElementCount();
if (firstStepIndex < content.getChildCount()) {
Element firstBar = Element.as(content.getChild(firstStepIndex));
gridBlockHeightPx = getElementHeightWithMargin(firstBar);
if ((contentHeight % gridBlockHeightPx) != 0) {
// height is not divided evenly for each bar.
// Can't use background grid with background-size trick.
gridBlockHeightPx = 0;
}
}
return gridBlockHeightPx;
}
private void updateContentWidth() {
if (timeline.isAlwaysCalculatePixelWidths()) {
content.getStyle().setWidth(timeline.getResolutionWidth(), Unit.PX);
}
}
private int getElementHeightWithMargin(Element div) {
int height = div.getClientHeight();
double marginHeight = 0;
if (!ie8) {
marginHeight = getMarginByComputedStyle(div);
}
return height + (int) Math.round(marginHeight);
}
private boolean isBetween(int v, int min, int max) {
return v >= min && v <= max;
}
private void updateMoveElementFor(Element target) {
if (target == null) {
moveElement.getStyle().setDisplay(Display.NONE);
}
moveElement.getStyle().clearDisplay();
String styleLeft = target.getStyle().getLeft();
// user capturePointLeftPx as default
double left = capturePointLeftPx;
if (styleLeft != null && styleLeft.length() > 2
&& styleLeft.endsWith("px")) {
// if target's 'left' is pixel value like '123px', use that.
// When target is already moved, then it's using pixel values. If
// it's not moved yet, it may use percentage value.
left = parseSize(styleLeft, "px");
}
if (isSubBar(target)) {
left += target.getParentElement().getOffsetLeft();
}
moveElement.getStyle().setProperty("left", left + "px");
moveElement.getStyle().setProperty("width",
target.getClientWidth() + "px");
}
private void hideMoveElement() {
moveElement.getStyle().setDisplay(Display.NONE);
}
private void internalMoveOrResizeCompleted(Element bar,
Element newPosition, boolean move) {
String stepUid = getStepUid(bar);
String newStepUid = stepUid;
if (newPosition != null && bar != newPosition) {
newStepUid = getStepUid(newPosition);
}
boolean subBar = isSubBar(bar);
long ownerStartDate = 0;
long ownerEndDate = 0;
double left = parseSize(bar.getStyle().getLeft(), "px");
int lineIndex = -1;
if (subBar) {
double ownerLeft = bar.getParentElement().getOffsetLeft();
left += ownerLeft;
ownerStartDate = timeline.getDateForLeftPosition(ownerLeft);
ownerLeft += GanttUtil.getBoundingClientRectWidth(bar
.getParentElement());
ownerEndDate = timeline.getDateForLeftPosition(ownerLeft);
}
long startDate = timeline.getDateForLeftPosition(left);
left += GanttUtil.getBoundingClientRectWidth(bar);
long endDate = timeline.getDateForLeftPosition(left);
// update left-position to percentage (so that it scales again)
if (subBar) {
updateBarPercentagePosition(startDate, endDate, ownerStartDate,
ownerEndDate, bar);
} else {
updateBarPercentagePosition(startDate, endDate, bar);
}
if (move) {
if( isMovableStepsBetweenLines(bar) ) {
lineIndex = getLineIndexByPosition(bar);
}
getRpc().onMove(stepUid, newStepUid, lineIndex, startDate, endDate);
} else {
getRpc().onResize(stepUid, startDate, endDate);
}
}
private int getLineIndexByPosition(Element bar) {
double top = parseSize(bar.getStyle().getTop(), "px");
double height = getElementHeightWithMargin(bar);
return (int) (top / height);
}
private void registerBarEventListener(final DivElement bar) {
Event.sinkEvents(bar, Event.ONSCROLL | Event.MOUSEEVENTS
| Event.TOUCHEVENTS);
}
private boolean isBar(NativeEvent event) {
Element element = getBar(event);
return element != null;
}
private double parseSize(String size, String suffix) {
if (size == null || size.length() == 0 || "0".equals(size)
|| "0.0".equals(size)) {
return 0;
}
return Double.parseDouble(size.substring(0,
size.length() - suffix.length()));
}
private int getStepIndex(Element parent, Element child) {
// return child index minus additional elements in the content
return getChildIndex(parent, child) - getAdditonalContentElementCount();
}
private int getAdditonalContentElementCount() {
// moveElement and background element inside the content is noticed.
// extraContentElements are also noticed.
return getAdditionalNonWidgetContentElementCount()
+ extraContentElements.size();
}
private int isMoveElementAttached() {
return moveElement.hasParentElement() ? 1 : 0;
}
private int getAdditionalNonWidgetContentElementCount() {
return isMoveElementAttached() + isBgGridAttached();
}
/**
* Return the number of background grid related elements in the content. May
* return 0...n, depending on which browser is used.
*/
private int isBgGridAttached() {
return (bgGrid != null && bgGrid.isAttached()) ? 1 : 0;
}
private int getChildIndex(Element parent, Element child) {
return DOM.getChildIndex(com.google.gwt.dom.client.Element.as(parent),
com.google.gwt.dom.client.Element.as(child));
}
private boolean detectResizing(Element bar) {
return isResizableStep(bar) && !hasSubBars(bar)
&& (isResizingLeft(bar) || isResizingRight(bar));
}
private boolean isResizableStep(Element bar) {
if (!isResizableSteps()) {
return false;
}
AbstractStepWidget step = getAbstractStepWidget(bar);
return step != null && step.getStep() != null
&& step.getStep().isResizable();
}
private boolean isResizingLeft(Element bar) {
if (movePoint.getX() <= (bar.getAbsoluteLeft() + RESIZE_WIDTH)) {
return true;
}
return false;
}
private boolean isResizingRight(Element bar) {
if (movePoint.getX() >= (bar.getAbsoluteRight() + -RESIZE_WIDTH)) {
return true;
}
return false;
}
private void addResizingStyles(Element bar) {
bar.addClassName(STYLE_RESIZING);
updateMoveElementFor(bar);
}
private void removeResizingStyles(Element bar) {
bar.removeClassName(STYLE_RESIZING);
}
private void showResizingPointer(Element bar, boolean showPointer) {
if (showPointer) {
bar.getStyle().setCursor(Cursor.E_RESIZE);
} else {
bar.getStyle().clearCursor();
}
}
private void addMovingStyles(Element bar) {
if (bar == null) {
return;
}
bar.addClassName(STYLE_MOVING);
updateMoveElementFor(bar);
}
private void removeMovingStyles(Element bar) {
bar.removeClassName(STYLE_MOVING);
}
private void updateBarResizingRight(Element bar, double deltax) {
double newWidth = capturePointWidthPx + deltax;
if (newWidth >= BAR_MIN_WIDTH) {
bar.getStyle().setLeft(capturePointLeftPx, Unit.PX);
bar.getStyle().setWidth(newWidth, Unit.PX);
}
}
private void updateBarResizingLeft(Element bar, double deltax) {
double newLeft = capturePointLeftPx + deltax;
double newWidth = capturePointWidthPx - deltax;
if (newWidth >= BAR_MIN_WIDTH) {
bar.getStyle().setLeft(newLeft, Unit.PX);
bar.getStyle().setWidth(newWidth, Unit.PX);
}
}
private void updateBarMovingPosition(Element bar, double deltax) {
bar.getStyle().setLeft(capturePointLeftPx + deltax, Unit.PX);
}
private void updateBarYPosition(Element bar, double deltay) {
int barHeight = getElementHeightWithMargin(bar);
double barTop = parseSize(bar.getStyle().getTop(), "px");
double movementFromTop = capturePointTopPx + deltay;
double deltaTop = movementFromTop - barTop;
if( deltaTop <= -1 * barHeight / 2 ) {
//move up
if( (barTop - barHeight) >= 0 ) {
bar.getStyle().setTop(barTop - barHeight, Unit.PX);
}
} else if( deltaTop >= barHeight / 2 ) {
//move down
bar.getStyle().setTop(barTop+barHeight, Unit.PX);
}
}
private void resetBarPosition(Element bar) {
bar.getStyle().setProperty("left", capturePointLeftPercentage);
bar.getStyle().setProperty("width", capturePointWidthPercentage);
}
private void disableClickOnNextMouseUp() {
clickOnNextMouseUp = false;
}
private boolean isClickOnNextMouseup() {
return clickOnNextMouseUp;
}
private boolean isResizingInProgress() {
return resizingInProgress;
}
private int getHorizontalScrollbarSpacerHeight() {
if (scrollbarSpacer.getStyle().getDisplay().isEmpty()) {
return scrollbarSpacer.getClientHeight();
}
return 0;
}
private double getContentWidth() {
if (!ie8) {
return getBoundingClientRectWidth(content);
}
return content.getClientWidth();
}
}
|
gantt-addon/src/main/java/org/tltv/gantt/client/GanttWidget.java
|
/*
* Copyright 2014 Tomi Virtanen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.tltv.gantt.client;
import static org.tltv.gantt.client.shared.GanttUtil.getBoundingClientRectWidth;
import static org.tltv.gantt.client.shared.GanttUtil.getMarginByComputedStyle;
import static org.tltv.gantt.client.shared.GanttUtil.getTouchOrMouseClientX;
import static org.tltv.gantt.client.shared.GanttUtil.getTouchOrMouseClientY;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.tltv.gantt.client.shared.GanttUtil;
import org.tltv.gantt.client.shared.Resolution;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.dom.client.Style.Cursor;
import com.google.gwt.dom.client.Style.Display;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ContextMenuEvent;
import com.google.gwt.event.dom.client.ContextMenuHandler;
import com.google.gwt.event.dom.client.MouseDownEvent;
import com.google.gwt.event.dom.client.MouseDownHandler;
import com.google.gwt.event.dom.client.MouseMoveEvent;
import com.google.gwt.event.dom.client.MouseMoveHandler;
import com.google.gwt.event.dom.client.MouseUpEvent;
import com.google.gwt.event.dom.client.MouseUpHandler;
import com.google.gwt.event.dom.client.ScrollEvent;
import com.google.gwt.event.dom.client.ScrollHandler;
import com.google.gwt.event.dom.client.TouchCancelEvent;
import com.google.gwt.event.dom.client.TouchCancelHandler;
import com.google.gwt.event.dom.client.TouchEndEvent;
import com.google.gwt.event.dom.client.TouchEndHandler;
import com.google.gwt.event.dom.client.TouchMoveEvent;
import com.google.gwt.event.dom.client.TouchMoveHandler;
import com.google.gwt.event.dom.client.TouchStartEvent;
import com.google.gwt.event.dom.client.TouchStartHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.touch.client.Point;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.AbstractNativeScrollbar;
import com.google.gwt.user.client.ui.ComplexPanel;
import com.google.gwt.user.client.ui.HasEnabled;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.WidgetCollection;
import com.vaadin.client.event.PointerCancelEvent;
import com.vaadin.client.event.PointerCancelHandler;
import com.vaadin.client.event.PointerDownEvent;
import com.vaadin.client.event.PointerDownHandler;
import com.vaadin.client.event.PointerMoveEvent;
import com.vaadin.client.event.PointerMoveHandler;
import com.vaadin.client.event.PointerUpEvent;
import com.vaadin.client.event.PointerUpHandler;
/**
* GWT Gantt chart widget. Includes {@link TimelineWidget} to show timeline, and
* below the timeline, shows content of the Gantt. Content is freely (position:
* absolute) positioned steps aligned vertically on top of each others.
* <p>
* These steps can be moved and resized freely in the space available, limited
* only by the timeline's borders.
* <p>
* All events are handled via {@link GanttRpc}.
* <p>
* Timeline's localization is handled via {@link LocaleDataProvider}.
* <p>
* Here are few steps that need to be notified when taking this widget in use. <br>
* First of all, after constructing this widget, you need to initialize it by
* {@link #initWidget(GanttRpc, LocaleDataProvider)} method. But before doing
* that, make sure to call
* {@link #setBrowserInfo(boolean, boolean, boolean, boolean, int)} to let this
* widget know some details of the browser. And if client supports touch events,
* let this widget know that by calling {@link #setTouchSupported(boolean)}
* method before initWidget.
* <p>
* Sample code snippet:
*
* <pre>
* GanttWidget widget = new GanttWidget();
* widget.setBrowserInfo(isIe(), isChrome(), isSafari(), isWebkit(),
* getMajorBrowserVersion());
* widget.setTouchSupportted(isTouchDevice());
* widget.initWidget(ganttRpc, localeDataProvider);
* </pre>
* <p>
* After initializing, widget is ready to go. But to let this widget know when
* it should re-calculate content widths/heights, call either
* {@link #notifyHeightChanged(int)} or {@link #notifyWidthChanged(int)} methods
* to do that. This needs to be done explicitly for example when widget's width
* is 100%, and the parent's width changes due to browser window's resize event.
*
* @author Tltv
*
*/
public class GanttWidget extends ComplexPanel implements HasEnabled, HasWidgets {
private static final int RESIZE_WIDTH = 10;
private static final int BAR_MIN_WIDTH = RESIZE_WIDTH;
private static final int CLICK_INTERVAL = 250;
private static final int POINTER_TOUCH_DETECTION_INTERVAL = 100;
private static final String STYLE_GANTT = "gantt";
private static final String STYLE_GANTT_CONTAINER = "gantt-container";
private static final String STYLE_GANTT_CONTENT = "gantt-content";
private static final String STYLE_MOVING = "moving";
private static final String STYLE_RESIZING = "resizing";
private static final String STYLE_MOVE_ELEMENT = "mv-el";
private HandlerRegistration msPointerDownHandlerRegistration;
private HandlerRegistration msPointerUpHandlerRegistration;
private HandlerRegistration msPointerMoveHandlerRegistration;
private HandlerRegistration msPointerCancelHandlerRegistration;
private HandlerRegistration touchStartHandlerRegistration;
private HandlerRegistration touchEndHandlerRegistration;
private HandlerRegistration touchMoveHandlerRegistration;
private HandlerRegistration touchCancelHandlerRegistration;
private HandlerRegistration scrollHandlerRegistration;
private HandlerRegistration mouseMoveHandlerRegistration;
private HandlerRegistration mouseDownHandlerHandlerRegistration;
private HandlerRegistration mouseUpHandlerHandlerRegistration;
private HandlerRegistration contextMenuHandlerRegistration;
private WidgetCollection children = new WidgetCollection(this);
private boolean enabled = true;
private boolean touchSupported = false;
private boolean movableSteps;
private boolean movableStepsBetweenLines;
private boolean resizableSteps;
private boolean backgroundGridEnabled;
private boolean defaultContextMenuEnabled = false;
private GanttRpc ganttRpc;
private LocaleDataProvider localeDataProvider;
private String locale;
private Resolution resolution;
private int firstDayOfRange;
private int firstHourOfRange;
private long startDate;
private long endDate;
private int minWidth;
protected double contentHeight;
protected boolean wasTimelineOverflowingHorizontally = false;
protected boolean wasContentOverflowingVertically = false;
protected TimelineWidget timeline;
protected DivElement container;
protected DivElement content;
protected DivElement scrollbarSpacer;
protected BgGridElement bgGrid;
/* Extra elements inside the content. */
protected Set<Widget> extraContentElements = new HashSet<Widget>();
protected boolean clickOnNextMouseUp = true;
protected boolean secondaryClickOnNextMouseUp = true;
protected Point movePoint;
protected boolean resizing = false;
protected boolean resizingFromLeft = false;
protected boolean resizingInProgress = false;
protected boolean moveInProgress = false;
protected int currentPointerEventId;
// following variables are set during mouse down event over a bar element,
// or over it's children element.
protected Point capturePoint;
protected String capturePointLeftPercentage;
protected String capturePointWidthPercentage;
protected double capturePointLeftPx;
protected double capturePointTopPx;
protected double capturePointWidthPx;
protected String capturePointBgColor;
protected Element targetBarElement;
// these variables are used to memorize the Y and Y origin to scroll the
// container (with touchStart/touchEnd/touchMove events).
protected int containerScrollStartPosY = -1;
protected int containerScrollStartPosX = -1;
// additional element that appears when moving or resizing
protected DivElement moveElement = DivElement.as(DOM.createDiv());
// click is actually detected by 'mouseup'/'mousedown' events, not with
// 'onclick'. click event is not used. disallowClickTimer helps to detect
// click during a short interval. And disallowing it after a short interval.
private Timer disallowClickTimer = new Timer() {
@Override
public void run() {
disableClickOnNextMouseUp();
if (isMovableSteps() && !isResizingInProgress()) {
addMovingStyles(targetBarElement);
}
}
};
private NativeEvent pendingPointerDownEvent;
private Timer pointerTouchStartedTimer = new Timer() {
@Override
public void run() {
GanttWidget.this.onTouchOrMouseDown(pendingPointerDownEvent);
pendingPointerDownEvent = null;
}
};
private ScrollHandler scrollHandler = new ScrollHandler() {
@Override
public void onScroll(ScrollEvent event) {
Element element = event.getNativeEvent().getEventTarget().cast();
if (element != container) {
return;
}
timeline.setScrollLeft(container.getScrollLeft());
}
};
private MouseDownHandler mouseDownHandler = new MouseDownHandler() {
@Override
public void onMouseDown(MouseDownEvent event) {
GWT.log("onMouseDown(MouseDownEvent)");
if (event.getNativeButton() == NativeEvent.BUTTON_LEFT) {
GanttWidget.this.onTouchOrMouseDown(event.getNativeEvent());
} else {
secondaryClickOnNextMouseUp = true;
new Timer() {
@Override
public void run() {
secondaryClickOnNextMouseUp = false;
}
}.schedule(CLICK_INTERVAL);
event.stopPropagation();
}
}
};
private MouseUpHandler mouseUpHandler = new MouseUpHandler() {
@Override
public void onMouseUp(MouseUpEvent event) {
if (event.getNativeButton() == NativeEvent.BUTTON_LEFT) {
GanttWidget.this.onTouchOrMouseUp(event.getNativeEvent());
} else {
if (secondaryClickOnNextMouseUp) {
Element bar = getBar(event.getNativeEvent());
if (bar != null && isEnabled()) {
getRpc().stepClicked(getStepUid(bar),
event.getNativeEvent(), bar);
}
}
secondaryClickOnNextMouseUp = true;
}
}
};
private ContextMenuHandler contextMenuHandler = new ContextMenuHandler() {
@Override
public void onContextMenu(ContextMenuEvent event) {
if (!defaultContextMenuEnabled) {
event.preventDefault();
}
}
};
private MouseMoveHandler mouseMoveHandler = new MouseMoveHandler() {
@Override
public void onMouseMove(MouseMoveEvent event) {
GanttWidget.this.onTouchOrMouseMove(event.getNativeEvent());
event.preventDefault();
}
};
private PointerDownHandler msPointerDownHandler = new PointerDownHandler() {
@Override
public void onPointerDown(PointerDownEvent event) {
GWT.log("onPointerDown(PointerDownEvent)");
if (currentPointerEventId == -1) {
currentPointerEventId = event.getPointerId();
} else {
event.preventDefault();
return; // multi-touch not supported
}
pendingPointerDownEvent = event.getNativeEvent();
capturePoint = new Point(
getTouchOrMouseClientX(event.getNativeEvent()),
getTouchOrMouseClientY(event.getNativeEvent()));
pointerTouchStartedTimer.schedule(POINTER_TOUCH_DETECTION_INTERVAL);
event.preventDefault();
}
};
private PointerUpHandler msPointerUpHandler = new PointerUpHandler() {
@Override
public void onPointerUp(PointerUpEvent event) {
currentPointerEventId = -1;
pointerTouchStartedTimer.cancel();
pendingPointerDownEvent = null;
GanttWidget.this.onTouchOrMouseUp(event.getNativeEvent());
event.preventDefault();
}
};
private PointerMoveHandler msPointerMoveHandler = new PointerMoveHandler() {
@Override
public void onPointerMove(PointerMoveEvent event) {
if (capturePoint == null) {
return;
}
movePoint = new Point(
getTouchOrMouseClientX(event.getNativeEvent()),
getTouchOrMouseClientY(event.getNativeEvent()));
// do nothing, if touch position has not changed
if (!(capturePoint.getX() == movePoint.getX() && capturePoint
.getY() == movePoint.getY())) {
GanttWidget.this.onTouchOrMouseMove(event.getNativeEvent());
}
}
};
private PointerCancelHandler msPointerCancelHandler = new PointerCancelHandler() {
@Override
public void onPointerCancel(PointerCancelEvent event) {
currentPointerEventId = -1;
pointerTouchStartedTimer.cancel();
pendingPointerDownEvent = null;
onCancelTouch(event.getNativeEvent());
}
};
private TouchStartHandler touchStartHandler = new TouchStartHandler() {
@Override
public void onTouchStart(TouchStartEvent event) {
if (event.getTargetTouches().length() == 1) {
JavaScriptObject target = event.getNativeEvent()
.getEventTarget().cast();
containerScrollStartPosY = -1;
containerScrollStartPosX = -1;
if (target == container || target == content
|| (!isMovableSteps())) {
boolean preventDefaultAndReturn = false;
// store x,y position for 'manual' vertical scrolling
if (isContentOverflowingVertically()) {
containerScrollStartPosY = container.getScrollTop()
+ event.getTouches().get(0).getPageY();
preventDefaultAndReturn = true;
}
if (isContentOverflowingHorizontally()) {
containerScrollStartPosX = container.getScrollLeft()
+ event.getTouches().get(0).getPageX();
preventDefaultAndReturn = true;
}
if (preventDefaultAndReturn) {
event.preventDefault();
return;
}
}
GanttWidget.this.onTouchOrMouseDown(event.getNativeEvent());
}
event.preventDefault();
}
};
private TouchEndHandler touchEndHandler = new TouchEndHandler() {
@Override
public void onTouchEnd(TouchEndEvent event) {
containerScrollStartPosY = -1;
containerScrollStartPosX = -1;
GanttWidget.this.onTouchOrMouseUp(event.getNativeEvent());
event.preventDefault();
}
};
private TouchMoveHandler touchMoveHandler = new TouchMoveHandler() {
@Override
public void onTouchMove(TouchMoveEvent event) {
if (event.getChangedTouches().length() == 1) {
boolean preventDefaultAndReturn = false;
// did we intend to scroll the container?
// apply 'manual' vertical scrolling
if (containerScrollStartPosY != -1) {
container.setScrollTop(containerScrollStartPosY
- event.getChangedTouches().get(0).getPageY());
preventDefaultAndReturn = true;
}
if (containerScrollStartPosX != -1) {
container.setScrollLeft(containerScrollStartPosX
- event.getChangedTouches().get(0).getPageX());
preventDefaultAndReturn = true;
}
if (preventDefaultAndReturn) {
event.preventDefault();
return;
}
if (GanttWidget.this.onTouchOrMouseMove(event.getNativeEvent())) {
event.preventDefault();
}
}
}
};
private TouchCancelHandler touchCancelHandler = new TouchCancelHandler() {
@Override
public void onTouchCancel(TouchCancelEvent event) {
containerScrollStartPosY = -1;
containerScrollStartPosX = -1;
onCancelTouch(event.getNativeEvent());
}
};
private boolean ie, ie8, chrome, safari, webkit;
public GanttWidget() {
setElement(DivElement.as(DOM.createDiv()));
setStyleName(STYLE_GANTT);
moveElement.setClassName(STYLE_MOVE_ELEMENT);
// not visible by default
moveElement.getStyle().setDisplay(Display.NONE);
timeline = GWT.create(TimelineWidget.class);
container = DivElement.as(DOM.createDiv());
container.setClassName(STYLE_GANTT_CONTAINER);
content = DivElement.as(DOM.createDiv());
content.setClassName(STYLE_GANTT_CONTENT);
container.appendChild(content);
content.appendChild(moveElement);
scrollbarSpacer = DivElement.as(DOM.createDiv());
scrollbarSpacer.getStyle().setHeight(
AbstractNativeScrollbar.getNativeScrollbarHeight(), Unit.PX);
scrollbarSpacer.getStyle().setDisplay(Display.NONE);
getElement().appendChild(timeline.getElement());
getElement().appendChild(container);
getElement().appendChild(scrollbarSpacer);
}
public void initWidget(GanttRpc ganttRpc,
LocaleDataProvider localeDataProvider) {
setRpc(ganttRpc);
setLocaleDataProvider(localeDataProvider);
resetListeners();
}
/**
* Add new StepWidget into content area.
*
* @param stepIndex
* Index of step (0 based) (not element index in container)
* @param widget
*/
public void addStep(int stepIndex, Widget widget) {
DivElement bar = DivElement.as(widget.getElement());
insert(stepIndex + getAdditonalContentElementCount(), widget);
int widgetsInContainer = getChildren().size();
int indexInWidgetContainer = stepIndex + extraContentElements.size();
// bar height should be defined in css
int height = getElementHeightWithMargin(bar);
int lineIndex = -1;
if (widget instanceof StepWidget) {
lineIndex = ((StepWidget)widget).getStep().getLineIndex();
}
if ( (stepIndex + 1) < (widgetsInContainer - extraContentElements.size()) ) {
// not the first step, update contentHeight by the previous step
int prevIndex = indexInWidgetContainer - 1;
Widget w = getWidget(prevIndex);
if (w instanceof StepWidget) {
double top = parseSize(w.getElement().getStyle().getTop(), "px");
top += getElementHeightWithMargin(w.getElement());
bar.getStyle().setTop(top, Unit.PX);
updateTopForAllStepsBelow(indexInWidgetContainer + 1, height);
}
contentHeight += height;
} else if (lineIndex >= 0) {
double top = height * lineIndex;
bar.getStyle().setTop(top, Unit.PX);
if( contentHeight < (top + height) ) {
contentHeight = top + height;
}
} else {
bar.getStyle().setTop(contentHeight, Unit.PX);
contentHeight += height;
}
registerBarEventListener(bar);
}
/**
* Remove Widget from the content area.
*
* @param widget
*/
public void removeStep(Widget widget) {
remove(widget);
}
/**
* Update Gantt chart's timeline and content for the given steps. This won't
* add any steps, but will update the content widths and heights.
*
* @param steps
*/
public void update(List<StepWidget> steps) {
if (startDate < 0 || endDate < 0 || startDate >= endDate) {
GWT.log("Invalid start and end dates. Gantt chart can't be rendered. Start: "
+ startDate + ", End: " + endDate);
return;
}
content.getStyle().setHeight(contentHeight, Unit.PX);
GWT.log("GanttWidget's active TimeZone: "
+ getLocaleDataProvider().getTimeZone().getID()
+ " (raw offset: "
+ getLocaleDataProvider().getTimeZone().getStandardOffset()
+ ")");
// tell timeline to notice vertical scrollbar before updating it
timeline.setNoticeVerticalScrollbarWidth(isContentOverflowingVertically());
timeline.update(resolution, startDate, endDate, firstDayOfRange,
firstHourOfRange, localeDataProvider);
setContentMinWidth(timeline.getMinWidth());
updateContainerStyle();
updateContentWidth();
updateStepWidths(steps);
wasTimelineOverflowingHorizontally = timeline
.isTimelineOverflowingHorizontally();
}
/**
* Set minimum width for the content element.
*
* @param minWidth
* Minimum width in pixels.
*/
public void setContentMinWidth(int minWidth) {
this.minWidth = minWidth;
content.getStyle().setProperty("minWidth", this.minWidth + "px");
}
/**
* Return minimal width of the content.
*
* @return Minimum width in pixels.
*/
public int getMinWidth() {
return minWidth;
}
/**
* Get current currently active timeline {@link Resolution}.
*
* @return resolution enum
*/
public Resolution getResolution() {
return resolution;
}
/**
* Set Gantt's timeline resolution.
*
* @param resolution
* New timeline resolution.
*/
public void setResolution(Resolution resolution) {
this.resolution = resolution;
}
/**
* Get timeline's start date. Date value should follow specification in
* {@link Date#getTime()}.
*
* @return Start date in milliseconds.
*/
public long getStartDate() {
return startDate;
}
/**
* Set timeline's start date. Date value should follow specification in
* {@link Date#getTime()}.
*
* @param startDate
* New start date in milliseconds.
*/
public void setStartDate(Long startDate) {
this.startDate = (startDate != null) ? startDate : 0;
}
/**
* Get timeline's end date. Date value should follow specification in
* {@link Date#getTime()}.
*
* @return End date in milliseconds.
*/
public long getEndDate() {
return endDate;
}
/**
* Set timeline's end date. Date value should follow specification in
* {@link Date#getTime()}.
*
* @param endDate
* New end date in milliseconds.
*/
public void setEndDate(Long endDate) {
this.endDate = (endDate != null) ? endDate : 0;
}
/**
* Set first day of timeline's date range. Value is between 1-7, where 1 is
* SUNDAY.
*
* @param firstDayOfRange
* Value between 1-7.
*/
public void setFirstDayOfRange(int firstDayOfRange) {
this.firstDayOfRange = firstDayOfRange;
}
public void setFirstHourOfRange(int firstHourOfRange) {
this.firstHourOfRange = firstHourOfRange;
}
/**
* Notify Gantt widget that height has changed. Delegates necessary changes
* to child elements.
*
* @param height
* New height in pixels
*/
public void notifyHeightChanged(int height) {
if (container != null && timeline != null) {
container.getStyle().setHeight(
height - getTimelineHeight()
- getHorizontalScrollbarSpacerHeight(), Unit.PX);
boolean overflow = isContentOverflowingVertically();
if (wasContentOverflowingVertically != overflow) {
wasContentOverflowingVertically = overflow;
timeline.setNoticeVerticalScrollbarWidth(overflow);
// width has changed due to vertical scrollbar
// appearing/disappearing
internalHandleWidthChange();
}
}
}
/**
* Get Timeline widget height.
*
* @return
*/
public int getTimelineHeight() {
if (timeline != null) {
return timeline.getElement().getClientHeight();
}
return 0;
}
/**
* Notify Gantt widget that width has changed. Delegates necessary changes
* to child elements.
*
* @param width
* New width in pixels
*/
public void notifyWidthChanged(int width) {
if (timeline != null) {
boolean overflow = timeline.checkTimelineOverflowingHorizontally();
if (timeline.isAlwaysCalculatePixelWidths()
|| wasTimelineOverflowingHorizontally != overflow) {
// scrollbar has just appeared/disappeared
wasTimelineOverflowingHorizontally = overflow;
if (!wasTimelineOverflowingHorizontally) {
timeline.setScrollLeft(0);
}
}
internalHandleWidthChange();
}
}
protected void internalHandleWidthChange() {
timeline.updateWidths();
updateContainerStyle();
updateContentWidth();
}
/**
* Set RPC implementation that is used to communicate with the server.
*
* @param ganttRpc
* GanttRpc
*/
public void setRpc(GanttRpc ganttRpc) {
this.ganttRpc = ganttRpc;
}
/**
* Get RPC implementation that is used to communicate with the server.
*
* @return GanttRpc
*/
public GanttRpc getRpc() {
return ganttRpc;
}
/**
* Reset listeners.
*/
public void resetListeners() {
Event.sinkEvents(container, Event.ONSCROLL);
Event.sinkEvents(container, Event.ONCONTEXTMENU);
if (contextMenuHandlerRegistration == null) {
contextMenuHandlerRegistration = addDomHandler(contextMenuHandler,
ContextMenuEvent.getType());
}
if (scrollHandlerRegistration == null) {
scrollHandlerRegistration = addHandler(scrollHandler,
ScrollEvent.getType());
}
if (isMsTouchSupported()) {
// IE10 pointer events (ms-prefixed events)
if (msPointerDownHandlerRegistration == null) {
msPointerDownHandlerRegistration = addDomHandler(
msPointerDownHandler, PointerDownEvent.getType());
}
if (msPointerUpHandlerRegistration == null) {
msPointerUpHandlerRegistration = addDomHandler(
msPointerUpHandler, PointerUpEvent.getType());
}
if (msPointerMoveHandlerRegistration == null) {
msPointerMoveHandlerRegistration = addDomHandler(
msPointerMoveHandler, PointerMoveEvent.getType());
}
if (msPointerCancelHandlerRegistration == null) {
msPointerCancelHandlerRegistration = addHandler(
msPointerCancelHandler, PointerCancelEvent.getType());
}
} else if (touchSupported) {
// touch events replaces mouse events
if (touchStartHandlerRegistration == null) {
touchStartHandlerRegistration = addDomHandler(
touchStartHandler, TouchStartEvent.getType());
}
if (touchEndHandlerRegistration == null) {
touchEndHandlerRegistration = addDomHandler(touchEndHandler,
TouchEndEvent.getType());
}
if (touchMoveHandlerRegistration == null) {
touchMoveHandlerRegistration = addDomHandler(touchMoveHandler,
TouchMoveEvent.getType());
}
if (touchCancelHandlerRegistration == null) {
touchCancelHandlerRegistration = addHandler(touchCancelHandler,
TouchCancelEvent.getType());
}
} else {
if (mouseDownHandlerHandlerRegistration == null) {
mouseDownHandlerHandlerRegistration = addDomHandler(
mouseDownHandler, MouseDownEvent.getType());
}
if (mouseUpHandlerHandlerRegistration == null) {
mouseUpHandlerHandlerRegistration = addDomHandler(
mouseUpHandler, MouseUpEvent.getType());
}
if (isMovableSteps() || isResizableSteps()) {
if (mouseMoveHandlerRegistration == null) {
mouseMoveHandlerRegistration = addDomHandler(
mouseMoveHandler, MouseMoveEvent.getType());
}
} else if (mouseMoveHandlerRegistration != null) {
mouseMoveHandlerRegistration.removeHandler();
mouseMoveHandlerRegistration = null;
}
}
}
/**
* Return true if background grid is enabled.
*
* @return True if background grid is enabled.
*/
public boolean isBackgroundGridEnabled() {
return backgroundGridEnabled;
}
/**
* Set background grid enabled. Next time the widget is painted, the grid is
* shown on the background of the container.
*
* @param backgroundGridEnabled
* True sets background grid enabled.
*/
public void setBackgroundGridEnabled(boolean backgroundGridEnabled) {
this.backgroundGridEnabled = backgroundGridEnabled;
}
/**
* Enable or disable touch support.
*
* @param touchSupported
* True enables touch support.
*/
public void setTouchSupported(boolean touchSupported) {
this.touchSupported = touchSupported;
}
/**
* Are touch events supported.
*
* @return True if touch events are supported.
*/
public boolean isTouchSupported() {
return touchSupported;
}
/**
* Enable or disable resizable steps.
*
* @param resizableSteps
* True enables step resizing.
*/
public void setResizableSteps(boolean resizableSteps) {
this.resizableSteps = resizableSteps;
}
/**
* Returns true if widget is enabled and steps are resizable.
*
* @return
*/
public boolean isResizableSteps() {
return isEnabled() && resizableSteps;
}
/**
* Enable or disable movable step's -feature.
*
* @param movableSteps
* True makes steps movable.
*/
public void setMovableSteps(boolean movableSteps) {
this.movableSteps = movableSteps;
}
/**
* Returns true if widget is enabled and steps are movable.
*
* @return
*/
public boolean isMovableSteps() {
return isEnabled() && movableSteps;
}
/**
* Returns true if the widget is enabled the steps are movable and the steps are movable between lines
* @return
*/
public boolean isMovableStepsBetweenLines() {
return isMovableSteps() && movableStepsBetweenLines;
}
/**
* Returns true if the the bar is not a sub bar and
* the widget is enabled the steps are movable and the steps are movable between lines
* @return
*/
public boolean isMovableStepsBetweenLines(Element bar) {
return isMovableStepsBetweenLines() && movableStepsBetweenLines && !isSubBar(bar);
}
/**
* Enable or disable movable steps between lines feature
*
* @param movableStepsBetweenLines True makes steps movable between lines
*/
public void setMovableStepsBetweenLines(boolean movableStepsBetweenLines) {
this.movableStepsBetweenLines = movableStepsBetweenLines;
}
public boolean isMonthRowVisible() {
return timeline.isMonthRowVisible();
}
public void setMonthRowVisible(boolean monthRowVisible) {
timeline.setMonthRowVisible(monthRowVisible);
}
public boolean isYearRowVisible() {
return timeline.isYearRowVisible();
}
public void setYearRowVisible(boolean yearRowVisible) {
timeline.setYearRowVisible(yearRowVisible);
}
public String getMonthFormat() {
return timeline.getMonthFormat();
}
public void setMonthFormat(String monthFormat) {
timeline.setMonthFormat(monthFormat);
}
public void setYearFormat(String yearFormat) {
timeline.setYearFormat(yearFormat);
}
public String getYearFormat() {
return timeline.getYearFormat();
}
public void setWeekFormat(String weekFormat) {
timeline.setWeekFormat(weekFormat);
}
public void setDayFormat(String dayFormat) {
timeline.setDayFormat(dayFormat);
}
public boolean isDefaultContextMenuEnabled() {
return defaultContextMenuEnabled;
}
public void setDefaultContextMenuEnabled(boolean defaultContextMenuEnabled) {
this.defaultContextMenuEnabled = defaultContextMenuEnabled;
}
/**
* Set LocaleDataProvider that is used to provide translations of months and
* weekdays.
*
* @param localeDataProvider
*/
public void setLocaleDataProvider(LocaleDataProvider localeDataProvider) {
this.localeDataProvider = localeDataProvider;
}
public LocaleDataProvider getLocaleDataProvider() {
return localeDataProvider;
}
/**
* Notify which browser this widget should optimize to. Usually just one
* argument is true.
*
* @param ie
* @param chrome
* @param safari
* @param webkit
* @param majorVersion
*/
public void setBrowserInfo(boolean ie, boolean chrome, boolean safari,
boolean webkit, int majorVersion) {
this.ie = ie;
ie8 = ie && majorVersion == 8;
this.chrome = chrome;
this.safari = safari;
this.webkit = webkit;
timeline.setBrowserInfo(ie, ie8, majorVersion);
}
/**
* @see TimelineWidget#setAlwaysCalculatePixelWidths(boolean)
* @param calcPx
*/
public void setAlwaysCalculatePixelWidths(boolean calcPx) {
timeline.setAlwaysCalculatePixelWidths(calcPx);
}
/**
* Sets timeline's force update flag up. Next
* {@link TimelineWidget#update(Resolution, long, long, int, int, LocaleDataProvider)}
* call knows then to update everything.
*/
public void setForceUpdateTimeline() {
if (timeline == null) {
return;
}
timeline.setForceUpdate();
}
@Override
public boolean isEnabled() {
return enabled;
}
@Override
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Element getScrollContainer() {
return container;
}
/**
* Get height of the scroll container. Includes the horizontal scrollbar
* spacer.
*
* @return
*/
public int getScrollContainerHeight() {
if (scrollbarSpacer.getStyle().getDisplay().isEmpty()) {
return getScrollContainer().getClientHeight()
+ scrollbarSpacer.getClientHeight();
}
return getScrollContainer().getClientHeight();
}
/**
* Return true, if content is overflowing vertically. This means also that
* vertical scroll bar is visible.
*
* @return
*/
public boolean isContentOverflowingVertically() {
if (content == null || container == null) {
return false;
}
return content.getClientHeight() > container.getClientHeight();
}
/**
* Return true, if content is overflowing horizontally. This means also that
* horizontal scroll bar is visible.
*
* @return
*/
public boolean isContentOverflowingHorizontally() {
// state of horizontal overflow is handled by timeline widget
if (content == null || container == null || timeline == null) {
return false;
}
return timeline.isTimelineOverflowingHorizontally();
}
/**
* Show empty spacing in horizontal scrollbar's position.
*/
public void showHorizontalScrollbarSpacer() {
if (!scrollbarSpacer.getStyle().getDisplay().isEmpty()) {
scrollbarSpacer.getStyle().clearDisplay();
notifyHeightChanged(getOffsetHeight());
}
}
/**
* Hide empty spacing in horizontal scrollbar's position.
*/
public void hideHorizontalScrollbarSpacer() {
if (scrollbarSpacer.getStyle().getDisplay().isEmpty()) {
scrollbarSpacer.getStyle().setDisplay(Display.NONE);
notifyHeightChanged(getOffsetHeight());
}
}
public void updateBarPercentagePosition(long startDate, long endDate,
long ownerStartDate, long ownerEndDate, Element bar) {
double ownerStepWidth = GanttUtil.getBoundingClientRectWidth(bar
.getParentElement());
String sLeft = timeline.getLeftPositionPercentageStringForDate(
startDate, ownerStepWidth, ownerStartDate, ownerEndDate);
bar.getStyle().setProperty("left", sLeft);
double range = ownerEndDate - ownerStartDate;
String sWidth = timeline.getWidthPercentageStringForDateInterval(
endDate - startDate, range);
bar.getStyle().setProperty("width", sWidth);
}
public void updateBarPercentagePosition(long startDate, long endDate,
Element bar) {
String sLeft = timeline.getLeftPositionPercentageStringForDate(
startDate, getContentWidth());
bar.getStyle().setProperty("left", sLeft);
String sWidth = timeline
.getWidthPercentageStringForDateInterval(endDate - startDate);
bar.getStyle().setProperty("width", sWidth);
}
/**
* Register and add Widget inside the content.
*/
public void registerContentElement(Widget widget) {
if (extraContentElements.add(widget)) {
insertFirst(widget);
}
}
/**
* Unregister and remove element from the content.
*/
public void unregisterContentElement(Widget widget) {
if (widget != null) {
extraContentElements.remove(widget);
widget.removeFromParent();
}
}
public native boolean isMsTouchSupported()
/*-{
return !!navigator.msMaxTouchPoints;
}-*/;
@Override
public void add(Widget w) {
super.add(w, content);
}
@Override
protected void insert(Widget child, Element container, int beforeIndex,
boolean domInsert) {
// Validate index; adjust if the widget is already a child of this
// panel.
int adjustedBeforeIndex = adjustIndex(child, beforeIndex
- getAdditionalNonWidgetContentElementCount());
// Detach new child.
child.removeFromParent();
// Logical attach.
getChildren().insert(child, adjustedBeforeIndex);
// Physical attach.
if (domInsert) {
DOM.insertChild(container, child.getElement(), beforeIndex);
} else {
DOM.appendChild(container, child.getElement());
}
// Adopt.
adopt(child);
}
public void insert(int beforeIndex, Widget w) {
insert(w, content, beforeIndex, true);
}
public void insertFirst(Widget child) {
// Detach new child.
child.removeFromParent();
// Logical attach.
getChildren().insert(child, 0);
// Physical attach.
content.insertFirst(child.getElement());
// Adopt.
adopt(child);
}
@Override
public boolean remove(Widget w) {
if (!(w instanceof StepWidget)) {
return super.remove(w);
}
int startIndex = getWidgetIndex(w);
int height = getElementHeightWithMargin(w.getElement());
contentHeight -= height;
if ((startIndex = removeAndReturnIndex(w)) >= 0) {
updateTopForAllStepsBelow(startIndex, -height);
// update content height
content.getStyle().setHeight(contentHeight, Unit.PX);
return true;
}
return false;
}
public int removeAndReturnIndex(Widget w) {
int index = -1;
// Validate.
if (w.getParent() != this) {
return index;
}
// Orphan.
try {
orphan(w);
} finally {
index = getWidgetIndex(w);
// Physical detach.
Element elem = w.getElement();
content.removeChild(elem);
// Logical detach.
getChildren().remove(w);
}
return index;
}
/**
* Update step widths based on the timeline. Timeline's width have to be
* final at this point.
*
* @param steps
*/
protected void updateStepWidths(Collection<StepWidget> steps) {
for (StepWidget step : steps) {
step.updateWidth();
}
}
protected Element getBar(NativeEvent event) {
Element element = event.getEventTarget().cast();
if (element == null || isSvg(element)) {
return null;
}
Element parent = element;
while (parent.getParentElement() != null
&& parent.getParentElement() != content && !isBar(parent)) {
parent = parent.getParentElement();
}
if (isBar(parent)) {
return parent;
}
return null;
}
protected boolean isBgElement(Element target) {
return bgGrid != null && bgGrid.equals(target);
}
private boolean isSvg(Element element) {
// safety check to avoid calling non existing functions
if (!isPartOfSvg(element)) {
return element.hasTagName("svg");
}
return true;
}
private static native boolean isPartOfSvg(Element element)
/*-{
if(element.ownerSVGElement) {
return true;
}
return false;
}-*/;
protected boolean isBar(Element element) {
if (isSvg(element)) {
return false;
}
return element.hasClassName(AbstractStepWidget.STYLE_BAR);
}
protected boolean isSubBar(Element element) {
if (isSvg(element)) {
return false;
}
return element.hasClassName(SubStepWidget.STYLE_SUB_BAR);
}
protected boolean hasSubBars(Element element) {
if (isSvg(element)) {
return false;
}
return element.hasClassName(StepWidget.STYLE_HAS_SUB_STEPS);
}
/**
* This is called when target bar element is moved successfully. Element's
* CSS attributes 'left' and 'width' are updated (unit in pixels).
*
* @param bar
* Moved Bar element
* @param y
*/
protected void moveCompleted(Element bar, int y) {
double deltay = y - capturePoint.getY();
GWT.log("Position delta y: " + deltay + "px");
Element newPosition;
if( isMovableStepsBetweenLines(bar) ) {
newPosition = bar; //if movement between lines are enabled findStepElement may give wrong result
} else {
newPosition = findStepElement(bar, y, deltay);
}
internalMoveOrResizeCompleted(bar, newPosition, true);
}
/**
* This is called when target bar is resized successfully. Element's CSS
* attributes 'left' and 'width' are updated (unit in pixels).
*
* @param bar
* Resized Bar element
*/
protected void resizingCompleted(Element bar) {
internalMoveOrResizeCompleted(bar, null, false);
}
protected void onTouchOrMouseDown(NativeEvent event) {
Element bar = getBar(event);
if (bar == null) {
return;
}
targetBarElement = bar;
capturePoint = new Point(getTouchOrMouseClientX(event),
getTouchOrMouseClientY(event));
movePoint = new Point(getTouchOrMouseClientX(event),
getTouchOrMouseClientY(event));
capturePointLeftPercentage = bar.getStyle().getProperty("left");
capturePointWidthPercentage = bar.getStyle().getProperty("width");
capturePointLeftPx = bar.getOffsetLeft();
capturePointTopPx = bar.getOffsetTop();
capturePointWidthPx = bar.getClientWidth();
capturePointBgColor = bar.getStyle().getBackgroundColor();
if (detectResizing(bar)) {
resizing = true;
resizingFromLeft = isResizingLeft(bar);
} else {
resizing = false;
}
disallowClickTimer.schedule(CLICK_INTERVAL);
event.stopPropagation();
}
protected void onTouchOrMouseUp(NativeEvent event) {
if (targetBarElement == null) {
return;
}
Element bar = getBar(event);
disallowClickTimer.cancel();
if (bar == targetBarElement && isClickOnNextMouseup()) {
clickOnNextMouseUp = true;
if (isEnabled()) {
getRpc().stepClicked(getStepUid(bar), event, bar);
}
} else {
clickOnNextMouseUp = true;
bar = targetBarElement;
if (resizing) {
removeResizingStyles(bar);
if (resizingInProgress) {
resizingCompleted(bar);
} else {
resetBarPosition(bar);
}
} else if (isMovableSteps()) {
// moving in progress
removeMovingStyles(bar);
if (moveInProgress) {
moveCompleted(bar, getTouchOrMouseClientY(event));
} else {
resetBarPosition(bar);
}
}
bar.getStyle().setBackgroundColor(capturePointBgColor);
}
stopDrag(event);
}
protected void stopDrag(NativeEvent event) {
hideMoveElement();
targetBarElement = null;
capturePoint = null;
resizing = false;
resizingInProgress = false;
moveInProgress = false;
event.stopPropagation();
}
protected void onCancelTouch(NativeEvent event) {
if (targetBarElement == null) {
return;
}
resetBarPosition(targetBarElement);
stopDrag(event);
}
/**
* Handle step's move event.
*
* @param event
* NativeEvent
* @return True, if this event was handled and had effect on step.
*/
protected boolean onTouchOrMouseMove(NativeEvent event) {
Element bar = getBar(event);
if (bar != null) {
movePoint = new Point(getTouchOrMouseClientX(event),
getTouchOrMouseClientY(event));
showResizingPointer(bar, detectResizing(bar));
}
if (targetBarElement == null) {
return false;
}
bar = targetBarElement;
disallowClickTimer.cancel();
clickOnNextMouseUp = false;
// calculate delta x and y by original position and the current one.
double deltax = getTouchOrMouseClientX(event) - capturePoint.getX();
double deltay = getTouchOrMouseClientY(event) - capturePoint.getY();
GWT.log("Position delta x: " + deltax + "px");
if (resizing) {
resizingInProgress = deltax != 0.0;
if (resizingFromLeft) {
updateBarResizingLeft(bar, deltax);
} else {
updateBarResizingRight(bar, deltax);
}
addResizingStyles(bar);
bar.getStyle().clearBackgroundColor();
} else if (isMovableSteps()) {
updateMoveInProgressFlag(bar, deltax, deltay);
updateBarMovingPosition(bar, deltax);
addMovingStyles(bar);
bar.getStyle().clearBackgroundColor();
if( isMovableStepsBetweenLines(bar) ) {
updateBarYPosition(bar, deltay);
}
}
// event.stopPropagation();
return true;
}
protected void updateMoveInProgressFlag(Element bar, double deltax, double deltay) {
moveInProgress = deltax != 0.0 && (!isMovableStepsBetweenLines(bar) || deltay != 0.0 ) ;
}
/**
* Helper method to find Step element by given starting point and y-position
* and delta-y. Starting point is there to optimize performance a bit as
* there's no need to iterate through every single step element.
*
* @param startFromBar
* Starting point element
* @param y
* target y-axis position
* @param deltay
* delta-y relative to starting point element.
* @return Step element at y-axis position. May be same element as given
* startFromBar element.
*/
protected Element findStepElement(Element startFromBar, int y, double deltay) {
if (isSubBar(startFromBar)) {
startFromBar = startFromBar.getParentElement();
}
if (isBetween(y, startFromBar.getAbsoluteTop(),
startFromBar.getAbsoluteBottom())) {
return startFromBar;
}
int startIndex = getChildIndex(content, startFromBar);
Element barCanditate;
int i = startIndex;
if (deltay > 0) {
i++;
for (; i < content.getChildCount(); i++) {
barCanditate = Element.as(content.getChild(i));
if (isBetween(y, barCanditate.getAbsoluteTop(),
barCanditate.getAbsoluteBottom())) {
return barCanditate;
}
}
} else if (deltay < 0) {
i--;
for (; i >= getAdditonalContentElementCount(); i--) {
barCanditate = Element.as(content.getChild(i));
if (isBetween(y, barCanditate.getAbsoluteTop(),
barCanditate.getAbsoluteBottom())) {
return barCanditate;
}
}
}
return startFromBar;
}
/**
* Get UID for the given Step element. Or null if StepWidget for the element
* doesn't exist in container.
*/
protected String getStepUid(Element stepElement) {
if (isSubBar(stepElement)) {
return getSubStepUid(stepElement);
}
// get widget by index known by this ComplexPanel.
StepWidget widget = getStepWidget(stepElement);
if (widget != null) {
return widget.getStep().getUid();
}
return null;
}
protected String getSubStepUid(Element subStepElement) {
Element stepElement = subStepElement.getParentElement();
StepWidget widget = getStepWidget(stepElement);
if (widget != null) {
return widget.getStepUidBySubStepElement(subStepElement);
}
return null;
}
protected SubStepWidget getSubStepWidget(Element subStepElement) {
Element stepElement = subStepElement.getParentElement();
StepWidget widget = getStepWidget(stepElement);
if (widget != null) {
return widget.getSubStepWidgetByElement(subStepElement);
}
return null;
}
protected StepWidget getStepWidget(Element stepElement) {
Widget widget = getWidget(getChildIndex(content, stepElement)
- getAdditionalNonWidgetContentElementCount());
if (widget instanceof StepWidget) {
return (StepWidget) widget;
}
return null;
}
protected AbstractStepWidget getAbstractStepWidget(Element stepElement) {
if (isSubBar(stepElement)) {
return getSubStepWidget(stepElement);
}
return getStepWidget(stepElement);
}
protected BgGridElement createBackgroundGrid() {
// implementation may be overridden via deferred binding. There is
// BgGridSvgElement alternative available and also used by Chrome.
BgGridElement grid = GWT.create(BgGridCssElement.class);
grid.init(container, content);
return grid;
}
private void updateTopForAllStepsBelow(int startIndex, int delta) {
// update top for all elements below
Element elementBelow;
for (int i = startIndex; i < getChildren().size(); i++) {
elementBelow = getWidget(i).getElement();
double top = parseSize(elementBelow.getStyle().getTop(), "px");
elementBelow.getStyle().setTop(top + delta, Unit.PX);
}
}
private double calculateBackgroundGridWidth() {
return timeline.calculateTimelineWidth();
}
private void updateContainerStyle() {
if (bgGrid == null) {
bgGrid = createBackgroundGrid();
}
if (!isBackgroundGridEnabled()) {
bgGrid.hide();
return;
}
// Container element has a background image that is positioned, sized
// and repeated to fill the whole container with a nice grid background.
// Update 'background-size' in container element to match the background
// grid's cell width and height to match with the timeline and rows.
// Update also 'background-position' in container to match the first
// resolution element width in the timeline, IF it's not same as all
// other resolution element widths.
int resDivElementCount = timeline.getResolutionDiv().getChildCount();
if (resDivElementCount == 0) {
return;
}
Element secondResolutionBlock = null;
Double firstResolutionBlockWidth = timeline
.getFirstResolutionElementWidth();
if (firstResolutionBlockWidth == null) {
return;
}
Double secondResolutionBlockWidth = null;
if (resDivElementCount > 2) {
secondResolutionBlock = Element.as(timeline.getResolutionDiv()
.getChild(1));
secondResolutionBlockWidth = getBoundingClientRectWidth(secondResolutionBlock);
}
boolean contentOverflowingHorizontally = isContentOverflowingHorizontally();
boolean adjustBgPosition = secondResolutionBlockWidth != null
&& !firstResolutionBlockWidth
.equals(secondResolutionBlockWidth);
double gridBlockWidthPx = 0.0;
if (!adjustBgPosition) {
gridBlockWidthPx = firstResolutionBlockWidth;
} else {
gridBlockWidthPx = secondResolutionBlockWidth;
}
updateContainerBackgroundSize(contentOverflowingHorizontally,
gridBlockWidthPx);
updateContainerBackgroundPosition(firstResolutionBlockWidth,
contentOverflowingHorizontally, gridBlockWidthPx,
adjustBgPosition);
}
private void updateContainerBackgroundSize(
boolean contentOverflowingHorizontally, double gridBlockWidthPx) {
String gridBlockWidth = null;
if (contentOverflowingHorizontally || useAlwaysPxSizeInBackground()) {
gridBlockWidth = timeline.toCssCalcOrNumberString(gridBlockWidthPx,
"px");
} else {
double contentWidth = getBoundingClientRectWidth(content);
gridBlockWidth = timeline.toCssCalcOrNumberString(
(100.0 / contentWidth) * gridBlockWidthPx, "%");
}
int gridBlockHeightPx = getBgGridCellHeight();
bgGrid.setBackgroundSize(gridBlockWidth, gridBlockWidthPx,
gridBlockHeightPx);
}
private void updateContainerBackgroundPosition(
double firstResolutionBlockWidth,
boolean contentOverflowingHorizontally, double gridBlockWidthPx,
boolean adjustBgPosition) {
if (adjustBgPosition) {
double realBgPosXPx = firstResolutionBlockWidth - 1.0;
if (useAlwaysPxSizeInBackground() || contentOverflowingHorizontally) {
bgGrid.setBackgroundPosition(
timeline.toCssCalcOrNumberString(realBgPosXPx, "px"),
"0px", realBgPosXPx, 0);
} else {
double timelineWidth = calculateBackgroundGridWidth();
double relativeBgAreaWidth = timelineWidth - gridBlockWidthPx;
double bgPosX = (100.0 / relativeBgAreaWidth) * realBgPosXPx;
bgGrid.setBackgroundPosition(
timeline.toCssCalcOrNumberString(bgPosX, "%"), "0px",
realBgPosXPx, 0);
}
} else {
bgGrid.setBackgroundPosition("-1px", "0", -1, 0);
}
}
private boolean useAlwaysPxSizeInBackground() {
return ie || chrome || safari || webkit;
}
private int getBgGridCellHeight() {
int gridBlockHeightPx = 0;
int firstStepIndex = getAdditonalContentElementCount();
if (firstStepIndex < content.getChildCount()) {
Element firstBar = Element.as(content.getChild(firstStepIndex));
gridBlockHeightPx = getElementHeightWithMargin(firstBar);
if ((contentHeight % gridBlockHeightPx) != 0) {
// height is not divided evenly for each bar.
// Can't use background grid with background-size trick.
gridBlockHeightPx = 0;
}
}
return gridBlockHeightPx;
}
private void updateContentWidth() {
if (timeline.isAlwaysCalculatePixelWidths()) {
content.getStyle().setWidth(timeline.getResolutionWidth(), Unit.PX);
}
}
private int getElementHeightWithMargin(Element div) {
int height = div.getClientHeight();
double marginHeight = 0;
if (!ie8) {
marginHeight = getMarginByComputedStyle(div);
}
return height + (int) Math.round(marginHeight);
}
private boolean isBetween(int v, int min, int max) {
return v >= min && v <= max;
}
private void updateMoveElementFor(Element target) {
if (target == null) {
moveElement.getStyle().setDisplay(Display.NONE);
}
moveElement.getStyle().clearDisplay();
String styleLeft = target.getStyle().getLeft();
// user capturePointLeftPx as default
double left = capturePointLeftPx;
if (styleLeft != null && styleLeft.length() > 2
&& styleLeft.endsWith("px")) {
// if target's 'left' is pixel value like '123px', use that.
// When target is already moved, then it's using pixel values. If
// it's not moved yet, it may use percentage value.
left = parseSize(styleLeft, "px");
}
if (isSubBar(target)) {
left += target.getParentElement().getOffsetLeft();
}
moveElement.getStyle().setProperty("left", left + "px");
moveElement.getStyle().setProperty("width",
target.getClientWidth() + "px");
}
private void hideMoveElement() {
moveElement.getStyle().setDisplay(Display.NONE);
}
private void internalMoveOrResizeCompleted(Element bar,
Element newPosition, boolean move) {
String stepUid = getStepUid(bar);
String newStepUid = stepUid;
if (newPosition != null && bar != newPosition) {
newStepUid = getStepUid(newPosition);
}
boolean subBar = isSubBar(bar);
long ownerStartDate = 0;
long ownerEndDate = 0;
double left = parseSize(bar.getStyle().getLeft(), "px");
int lineIndex = -1;
if (subBar) {
double ownerLeft = bar.getParentElement().getOffsetLeft();
left += ownerLeft;
ownerStartDate = timeline.getDateForLeftPosition(ownerLeft);
ownerLeft += GanttUtil.getBoundingClientRectWidth(bar
.getParentElement());
ownerEndDate = timeline.getDateForLeftPosition(ownerLeft);
}
long startDate = timeline.getDateForLeftPosition(left);
left += GanttUtil.getBoundingClientRectWidth(bar);
long endDate = timeline.getDateForLeftPosition(left);
// update left-position to percentage (so that it scales again)
if (subBar) {
updateBarPercentagePosition(startDate, endDate, ownerStartDate,
ownerEndDate, bar);
} else {
updateBarPercentagePosition(startDate, endDate, bar);
}
if (move) {
if( isMovableStepsBetweenLines(bar) ) {
lineIndex = getLineIndexByPosition(bar);
}
getRpc().onMove(stepUid, newStepUid, lineIndex, startDate, endDate);
} else {
getRpc().onResize(stepUid, startDate, endDate);
}
}
private int getLineIndexByPosition(Element bar) {
double top = parseSize(bar.getStyle().getTop(), "px");
double height = getElementHeightWithMargin(bar);
return (int) (top / height);
}
private void registerBarEventListener(final DivElement bar) {
Event.sinkEvents(bar, Event.ONSCROLL | Event.MOUSEEVENTS
| Event.TOUCHEVENTS);
}
private boolean isBar(NativeEvent event) {
Element element = getBar(event);
return element != null;
}
private double parseSize(String size, String suffix) {
if (size == null || size.length() == 0 || "0".equals(size)
|| "0.0".equals(size)) {
return 0;
}
return Double.parseDouble(size.substring(0,
size.length() - suffix.length()));
}
private int getStepIndex(Element parent, Element child) {
// return child index minus additional elements in the content
return getChildIndex(parent, child) - getAdditonalContentElementCount();
}
private int getAdditonalContentElementCount() {
// moveElement and background element inside the content is noticed.
// extraContentElements are also noticed.
return getAdditionalNonWidgetContentElementCount()
+ extraContentElements.size();
}
private int isMoveElementAttached() {
return moveElement.hasParentElement() ? 1 : 0;
}
private int getAdditionalNonWidgetContentElementCount() {
return isMoveElementAttached() + isBgGridAttached();
}
/**
* Return the number of background grid related elements in the content. May
* return 0...n, depending on which browser is used.
*/
private int isBgGridAttached() {
return (bgGrid != null && bgGrid.isAttached()) ? 1 : 0;
}
private int getChildIndex(Element parent, Element child) {
return DOM.getChildIndex(com.google.gwt.dom.client.Element.as(parent),
com.google.gwt.dom.client.Element.as(child));
}
private boolean detectResizing(Element bar) {
return isResizableStep(bar) && !hasSubBars(bar)
&& (isResizingLeft(bar) || isResizingRight(bar));
}
private boolean isResizableStep(Element bar) {
if (!isResizableSteps()) {
return false;
}
AbstractStepWidget step = getAbstractStepWidget(bar);
return step != null && step.getStep() != null
&& step.getStep().isResizable();
}
private boolean isResizingLeft(Element bar) {
if (movePoint.getX() <= (bar.getAbsoluteLeft() + RESIZE_WIDTH)) {
return true;
}
return false;
}
private boolean isResizingRight(Element bar) {
if (movePoint.getX() >= (bar.getAbsoluteRight() + -RESIZE_WIDTH)) {
return true;
}
return false;
}
private void addResizingStyles(Element bar) {
bar.addClassName(STYLE_RESIZING);
updateMoveElementFor(bar);
}
private void removeResizingStyles(Element bar) {
bar.removeClassName(STYLE_RESIZING);
}
private void showResizingPointer(Element bar, boolean showPointer) {
if (showPointer) {
bar.getStyle().setCursor(Cursor.E_RESIZE);
} else {
bar.getStyle().clearCursor();
}
}
private void addMovingStyles(Element bar) {
if (bar == null) {
return;
}
bar.addClassName(STYLE_MOVING);
updateMoveElementFor(bar);
}
private void removeMovingStyles(Element bar) {
bar.removeClassName(STYLE_MOVING);
}
private void updateBarResizingRight(Element bar, double deltax) {
double newWidth = capturePointWidthPx + deltax;
if (newWidth >= BAR_MIN_WIDTH) {
bar.getStyle().setLeft(capturePointLeftPx, Unit.PX);
bar.getStyle().setWidth(newWidth, Unit.PX);
}
}
private void updateBarResizingLeft(Element bar, double deltax) {
double newLeft = capturePointLeftPx + deltax;
double newWidth = capturePointWidthPx - deltax;
if (newWidth >= BAR_MIN_WIDTH) {
bar.getStyle().setLeft(newLeft, Unit.PX);
bar.getStyle().setWidth(newWidth, Unit.PX);
}
}
private void updateBarMovingPosition(Element bar, double deltax) {
bar.getStyle().setLeft(capturePointLeftPx + deltax, Unit.PX);
}
private void updateBarYPosition(Element bar, double deltay) {
int barHeight = getElementHeightWithMargin(bar);
double barTop = parseSize(bar.getStyle().getTop(), "px");
double movementFromTop = capturePointTopPx + deltay;
double deltaTop = movementFromTop - barTop;
if( deltaTop <= -1 * barHeight / 2 ) {
//move up
bar.getStyle().setTop(barTop-barHeight, Unit.PX);
} else if( deltaTop >= barHeight / 2 ) {
//move down
bar.getStyle().setTop(barTop+barHeight, Unit.PX);
}
}
private void resetBarPosition(Element bar) {
bar.getStyle().setProperty("left", capturePointLeftPercentage);
bar.getStyle().setProperty("width", capturePointWidthPercentage);
}
private void disableClickOnNextMouseUp() {
clickOnNextMouseUp = false;
}
private boolean isClickOnNextMouseup() {
return clickOnNextMouseUp;
}
private boolean isResizingInProgress() {
return resizingInProgress;
}
private int getHorizontalScrollbarSpacerHeight() {
if (scrollbarSpacer.getStyle().getDisplay().isEmpty()) {
return scrollbarSpacer.getClientHeight();
}
return 0;
}
private double getContentWidth() {
if (!ie8) {
return getBoundingClientRectWidth(content);
}
return content.getClientWidth();
}
}
|
#50 dnd between lines: remove step bugfix, drop to negative line index bugfix
|
gantt-addon/src/main/java/org/tltv/gantt/client/GanttWidget.java
|
#50 dnd between lines: remove step bugfix, drop to negative line index bugfix
|
<ide><path>antt-addon/src/main/java/org/tltv/gantt/client/GanttWidget.java
<ide> lineIndex = ((StepWidget)widget).getStep().getLineIndex();
<ide> }
<ide>
<del> if ( (stepIndex + 1) < (widgetsInContainer - extraContentElements.size()) ) {
<add> if (lineIndex >= 0) {
<add> double top = height * lineIndex;
<add> bar.getStyle().setTop(top, Unit.PX);
<add> if( contentHeight < (top + height) ) {
<add> contentHeight = top + height;
<add> }
<add> } else if ( (stepIndex + 1) < (widgetsInContainer - extraContentElements.size()) ) {
<ide> // not the first step, update contentHeight by the previous step
<ide> int prevIndex = indexInWidgetContainer - 1;
<ide> Widget w = getWidget(prevIndex);
<ide> updateTopForAllStepsBelow(indexInWidgetContainer + 1, height);
<ide> }
<ide> contentHeight += height;
<del> } else if (lineIndex >= 0) {
<del> double top = height * lineIndex;
<del> bar.getStyle().setTop(top, Unit.PX);
<del> if( contentHeight < (top + height) ) {
<del> contentHeight = top + height;
<del> }
<ide> } else {
<ide> bar.getStyle().setTop(contentHeight, Unit.PX);
<ide> contentHeight += height;
<ide> public boolean remove(Widget w) {
<ide> if (!(w instanceof StepWidget)) {
<ide> return super.remove(w);
<del> }
<del>
<del> int startIndex = getWidgetIndex(w);
<del> int height = getElementHeightWithMargin(w.getElement());
<del> contentHeight -= height;
<del>
<del> if ((startIndex = removeAndReturnIndex(w)) >= 0) {
<del> updateTopForAllStepsBelow(startIndex, -height);
<del>
<del> // update content height
<del> content.getStyle().setHeight(contentHeight, Unit.PX);
<del> return true;
<del> }
<del> return false;
<add> } else {
<add> StepWidget stepWidget = (StepWidget) w;
<add>
<add> if( stepWidget.getStep().getLineIndex() >= 0 ) {
<add> return super.remove(stepWidget);
<add> } else {
<add> int startIndex = getWidgetIndex(w);
<add> int height = getElementHeightWithMargin(w.getElement());
<add> contentHeight -= height;
<add>
<add> if ((startIndex = removeAndReturnIndex(w)) >= 0) {
<add> updateTopForAllStepsBelow(startIndex, -height);
<add>
<add> // update content height
<add> content.getStyle().setHeight(contentHeight, Unit.PX);
<add> return true;
<add> }
<add> return false;
<add> }
<add> }
<ide> }
<ide>
<ide> public int removeAndReturnIndex(Widget w) {
<ide>
<ide> if( deltaTop <= -1 * barHeight / 2 ) {
<ide> //move up
<del> bar.getStyle().setTop(barTop-barHeight, Unit.PX);
<add> if( (barTop - barHeight) >= 0 ) {
<add> bar.getStyle().setTop(barTop - barHeight, Unit.PX);
<add> }
<ide> } else if( deltaTop >= barHeight / 2 ) {
<ide> //move down
<ide> bar.getStyle().setTop(barTop+barHeight, Unit.PX);
|
|
JavaScript
|
mit
|
76c0bdeecfbe7e74a8971c0b374c6f76e7cb5821
| 0 |
JoshuaSCochrane/arrows,efritz/arrows
|
let annotationCache = {};
class LiftedArrow extends Arrow {
constructor(f) {
if (!(f instanceof Function)) {
throw new Error("Cannot lift non-function");
}
super(_construct(() => {
let start = window.performance.now();
let s = f.toString();
let i = s.indexOf("/*");
let j = s.indexOf("*/", i + 1);
let c = s.substring(i + 2, j);
let parsed = annotationCache[c];
if (annotationCache[c] === undefined) {
let comment;
try {
comment = c.match(/\@arrow :: (.*)\n?/)[1];
} catch (err) {
if (typecheck) {
console.warn("Function being lifted does not contain an @arrow annotation");
}
comment = "_ ~> _";
}
try {
// jison exports the parser name like this
parsed = parser.parse(comment);
} catch (err) {
throw new ComposeError(`Function being lifted does not contain a parseable @arrow annotation.\n${err.message}\n`);
}
annotationCache[c] = parsed;
}
let elapsed = window.performance.now() - start;
numannotations++;
annotationParseTime += elapsed;
let arg = parsed[0];
let out = parsed[1];
let ncs = new ConstraintSet([]).addAll(parsed[2][0]);
return new ArrowType(arg, out, ncs, parsed[2][1]).sanitize();
}));
this.f = f;
}
toString() {
return "lift :: " + this.type.toString();
}
call(x, p, k, h) {
try {
// If the function has more than one parameter and we have
// an array argument, spread the elements. Else, just call
// the function with a single argument.
if (x && x.constructor === Array && this.f.length > 1) {
let result = this.f.apply(null, x);
} else {
let result = this.f(x);
}
_check(this.type.out, result);
} catch (err) {
return h(err);
}
k(result);
}
equals(that) {
return that instanceof LiftedArrow && this.f === that.f;
}
}
class ElemArrow extends LiftedArrow {
constructor(selector) {
super(() => {
/* @arrow :: _ ~> Elem */
return $(selector);
});
this.selector = selector;
}
toString() {
return "elem :: " + this.type.toString();
}
equals(that) {
return that instanceof ElemArrow && this.selector === that.selector;
}
}
//
// Simple Asynchronous Arrow Implementation
//
class SimpleAsyncArrow extends Arrow {
isAsync() {
return true;
}
}
// Simple Asynchronous Arrow that takes in a config object
class SimpleConfigBasedAsyncArrow extends SimpleAsyncArrow {
constructor(f, errorType) {
if (!(f instanceof Function)) {
throw new Error("Cannot use non-function as configuration value");
}
super(_construct(() => {
let start = window.performance.now();
let s = f.toString();
let i = s.indexOf("/*");
let j = s.indexOf("*/", i + 1);
let c = s.substring(i + 2, j);
let ncs = new ConstraintSet([]);
let err = [new NamedType(errorType)];
if (annotationCache[c] !== undefined) {
let conf = annotationCache[c][0];
let resp = annotationCache[c][1];
} else {
try {
// jison exports the parser name like this
let conf = parser.parse(c.match(/\@conf :: (.*)\n?/)[1]);
ncs = ncs.addAll(conf[1][0]);
err = err.concat(conf[1][1]);
} catch (err) {
throw new ComposeError(`Config does not contain a parseable @conf annotation.\n${err.message}\n`);
}
try {
// jison exports the parser name like this
let resp = parser.parse(c.match(/\@resp :: (.*)\n?/)[1]);
ncs = ncs.addAll(resp[1][0]);
err = err.concat(resp[1][1]);
} catch (err) {
throw new ComposeError(`Config does not contain a parseable @resp annotation.\n${err.message}\n`);
}
annotationCache[c] = [conf, resp];
}
let elapsed = window.performance.now() - start;
numannotations++;
annotationParseTime += elapsed;
return new ArrowType(conf[0], resp[0], ncs, err).sanitize();
}));
this.c = f;
}
}
class AjaxArrow extends SimpleConfigBasedAsyncArrow {
constructor(f) {
super(f, "AjaxError");
}
toString() {
return "ajax :: " + this.type.toString();
}
call(x, p, k, h) {
// If the function has more than one parameter and we have
// an array argument, spread the elements. Else, just call
// the function with a single argument.
// TODO - wrap this in try
if (x && x.constructor === Array && this.c.length > 1) {
let conf = this.c.apply(null, x);
} else {
let conf = this.c(x);
}
let abort = false;
const cancel = () => {
abort = true;
};
const fail = h;
const succ = x => {
_check(this.type.out, x);
k(x);
};
$.ajax($.extend(conf, {
success: (x, status, xhr) => { if (!abort) { p.advance(cancelerId); succ(x); } },
error : (xhr, status, x) => { if (!abort) { p.advance(cancelerId); fail(x); } },
}));
let cancelerId = p.addCanceler(cancel);
}
equals(that) {
// TODO - deep comparison of objects
return that instanceof AjaxArrow && this.c === that.c;
}
}
class QueryArrow extends SimpleConfigBasedAsyncArrow {
constructor(f, db) {
super(f, "QueryError");
this.db = db;
}
toString() {
return "query :: " + this.type.toString();
}
call(x, p, k, h) {
if (x && x.constructor === Array && this.c.length > 1) {
let conf = this.c.apply(null, x);
} else {
let conf = this.c(x);
}
let abort = false;
const cancel = () => {
abort = true;
};
const fail = h;
const succ = x => {
_check(this.type.out, x);
k(x);
};
this.db.query(conf.query, conf.param, function (err, rows) {
if (err) {
if (!abort) {
p.advance(cancelerId);
fail(err);
}
} else {
if (!abort) {
p.advance(cancelerId);
succ(rows);
}
}
});
let cancelerId = p.addCanceler(cancel);
}
equals(that) {
// TODO - deep comparison of objects
return that instanceof QueryArrow && this.c === that.c;
}
}
class EventArrow extends SimpleAsyncArrow {
constructor(name) {
// Elem ~> Event
super(_construct(() => new ArrowType(new NamedType("Elem"), new NamedType("Event"))));
this.name = name;
}
toString() {
return "event(" + this.name + ") :: " + this.type.toString();
}
call(x, p, k, h) {
let abort = false;
const cancel = () => {
abort = true;
x.off(this.name, runner);
};
const runner = ev => {
if (!abort) {
cancel();
p.advance(cancelerId);
k(ev);
}
};
x.on(this.name, runner);
let cancelerId = p.addCanceler(cancel);
}
equals(that) {
return that instanceof EventArrow && this.name === that.name;
}
}
class DynamicDelayArrow extends SimpleAsyncArrow {
constructor() {
// Number ~> _
super(_construct(() => {
return new ArrowType(new NamedType("Number"), new TopType());
}));
}
toString() {
return "delay :: " + this.type.toString();
}
call(x, p, k, h) {
const cancel = () => clearTimeout(timer);
const runner = () => {
p.advance(cancelerId);
k();
};
let timer = setTimeout(runner, x);
let cancelerId = p.addCanceler(cancel);
}
equals(that) {
return that instanceof DynamicDelayArrow;
}
}
class DelayArrow extends SimpleAsyncArrow {
constructor(duration) {
// "a ~> "a
super(_construct(() => {
let alpha = ParamType.fresh();
return new ArrowType(alpha, alpha);
}));
this.duration = duration;
}
toString() {
return "delay(" + this.duration + ") :: " + this.type.toString();
}
call(x, p, k, h) {
const cancel = () => clearTimeout(timer);
const runner = () => {
p.advance(cancelerId);
k(x);
};
let timer = setTimeout(runner, this.duration);
let cancelerId = p.addCanceler(cancel);
}
equals(that) {
return that instanceof Delay && this.duration === that.duration;
}
}
//
// Simple (Generalized) Arrows
//
class SplitArrow extends Arrow {
constructor(n) {
super(_construct(() => {
let arg = ParamType.fresh();
let out = Array.create(n, arg);
return new ArrowType(arg, new TupleType(out));
}));
this.n = n;
}
toString() {
return "split(" + this.n + ") :: " + this.type.toString();
}
call(x, p, k, h) {
// TODO - clone values
k(Array.create(this.n, x));
}
equals(that) {
return that instanceof SplitArrow && this.n === that.n;
}
}
class NthArrow extends Arrow {
constructor(n) {
super(_construct(() => {
let arg = Array.create(n).map(() => ParamType.fresh());
let out = arg[n - 1];
return new ArrowType(new TupleType(arg), out);
}));
this.n = n;
}
toString() {
return "nth(" + this.n + ") :: " + this.type.toString();
}
call(x, p, k, h) {
k(x[this.n - 1]);
}
equals(that) {
return that instanceof NthArrow && this.n === that.n;
}
}
|
src/builtins.js
|
let annotationCache = {};
class LiftedArrow extends Arrow {
constructor(f) {
if (!(f instanceof Function)) {
throw new Error("Cannot lift non-function");
}
super(_construct(() => {
let start = window.performance.now();
let s = f.toString();
let i = s.indexOf("/*");
let j = s.indexOf("*/", i + 1);
let c = s.substring(i + 2, j);
if (annotationCache[c] !== undefined) {
let parsed = annotationCache[c];
} else {
let comment;
try {
comment = c.match(/\@arrow :: (.*)\n?/)[1];
} catch (err) {
if (typecheck) {
console.warn("Function being lifted does not contain an @arrow annotation");
}
comment = "_ ~> _";
}
try {
// jison exports the parser name like this
parsed = parser.parse(comment);
} catch (err) {
throw new ComposeError(`Function being lifted does not contain a parseable @arrow annotation.\n${err.message}\n`);
}
annotationCache[c] = parsed;
}
let elapsed = window.performance.now() - start;
numannotations++;
annotationParseTime += elapsed;
let arg = parsed[0];
let out = parsed[1];
let ncs = new ConstraintSet([]).addAll(parsed[2][0]);
return new ArrowType(arg, out, ncs, parsed[2][1]).sanitize();
}));
this.f = f;
}
toString() {
return "lift :: " + this.type.toString();
}
call(x, p, k, h) {
try {
// If the function has more than one parameter and we have
// an array argument, spread the elements. Else, just call
// the function with a single argument.
if (x && x.constructor === Array && this.f.length > 1) {
let result = this.f.apply(null, x);
} else {
let result = this.f(x);
}
_check(this.type.out, result);
} catch (err) {
return h(err);
}
k(result);
}
equals(that) {
return that instanceof LiftedArrow && this.f === that.f;
}
}
class ElemArrow extends LiftedArrow {
constructor(selector) {
super(() => {
/* @arrow :: _ ~> Elem */
return $(selector);
});
this.selector = selector;
}
toString() {
return "elem :: " + this.type.toString();
}
equals(that) {
return that instanceof ElemArrow && this.selector === that.selector;
}
}
//
// Simple Asynchronous Arrow Implementation
//
class SimpleAsyncArrow extends Arrow {
isAsync() {
return true;
}
}
// Simple Asynchronous Arrow that takes in a config object
class SimpleConfigBasedAsyncArrow extends SimpleAsyncArrow {
constructor(f, errorType) {
if (!(f instanceof Function)) {
throw new Error("Cannot use non-function as configuration value");
}
super(_construct(() => {
let start = window.performance.now();
let s = f.toString();
let i = s.indexOf("/*");
let j = s.indexOf("*/", i + 1);
let c = s.substring(i + 2, j);
let ncs = new ConstraintSet([]);
let err = [new NamedType(errorType)];
if (annotationCache[c] !== undefined) {
let conf = annotationCache[c][0];
let resp = annotationCache[c][1];
} else {
try {
// jison exports the parser name like this
let conf = parser.parse(c.match(/\@conf :: (.*)\n?/)[1]);
ncs = ncs.addAll(conf[1][0]);
err = err.concat(conf[1][1]);
} catch (err) {
throw new ComposeError(`Config does not contain a parseable @conf annotation.\n${err.message}\n`);
}
try {
// jison exports the parser name like this
let resp = parser.parse(c.match(/\@resp :: (.*)\n?/)[1]);
ncs = ncs.addAll(resp[1][0]);
err = err.concat(resp[1][1]);
} catch (err) {
throw new ComposeError(`Config does not contain a parseable @resp annotation.\n${err.message}\n`);
}
annotationCache[c] = [conf, resp];
}
let elapsed = window.performance.now() - start;
numannotations++;
annotationParseTime += elapsed;
return new ArrowType(conf[0], resp[0], ncs, err).sanitize();
}));
this.c = f;
}
}
class AjaxArrow extends SimpleConfigBasedAsyncArrow {
constructor(f) {
super(f, "AjaxError");
}
toString() {
return "ajax :: " + this.type.toString();
}
call(x, p, k, h) {
// If the function has more than one parameter and we have
// an array argument, spread the elements. Else, just call
// the function with a single argument.
// TODO - wrap this in try
if (x && x.constructor === Array && this.c.length > 1) {
let conf = this.c.apply(null, x);
} else {
let conf = this.c(x);
}
let abort = false;
const cancel = () => {
abort = true;
};
const fail = h;
const succ = x => {
_check(this.type.out, x);
k(x);
};
$.ajax($.extend(conf, {
success: (x, status, xhr) => { if (!abort) { p.advance(cancelerId); succ(x); } },
error : (xhr, status, x) => { if (!abort) { p.advance(cancelerId); fail(x); } },
}));
let cancelerId = p.addCanceler(cancel);
}
equals(that) {
// TODO - deep comparison of objects
return that instanceof AjaxArrow && this.c === that.c;
}
}
class QueryArrow extends SimpleConfigBasedAsyncArrow {
constructor(f, db) {
super(f, "QueryError");
this.db = db;
}
toString() {
return "query :: " + this.type.toString();
}
call(x, p, k, h) {
if (x && x.constructor === Array && this.c.length > 1) {
let conf = this.c.apply(null, x);
} else {
let conf = this.c(x);
}
let abort = false;
const cancel = () => {
abort = true;
};
const fail = h;
const succ = x => {
_check(this.type.out, x);
k(x);
};
this.db.query(conf.query, conf.param, function (err, rows) {
if (err) {
if (!abort) {
p.advance(cancelerId);
fail(err);
}
} else {
if (!abort) {
p.advance(cancelerId);
succ(rows);
}
}
});
let cancelerId = p.addCanceler(cancel);
}
equals(that) {
// TODO - deep comparison of objects
return that instanceof QueryArrow && this.c === that.c;
}
}
class EventArrow extends SimpleAsyncArrow {
constructor(name) {
// Elem ~> Event
super(_construct(() => new ArrowType(new NamedType("Elem"), new NamedType("Event"))));
this.name = name;
}
toString() {
return "event(" + this.name + ") :: " + this.type.toString();
}
call(x, p, k, h) {
let abort = false;
const cancel = () => {
abort = true;
x.off(this.name, runner);
};
const runner = ev => {
if (!abort) {
cancel();
p.advance(cancelerId);
k(ev);
}
};
x.on(this.name, runner);
let cancelerId = p.addCanceler(cancel);
}
equals(that) {
return that instanceof EventArrow && this.name === that.name;
}
}
class DynamicDelayArrow extends SimpleAsyncArrow {
constructor() {
// Number ~> _
super(_construct(() => {
return new ArrowType(new NamedType("Number"), new TopType());
}));
}
toString() {
return "delay :: " + this.type.toString();
}
call(x, p, k, h) {
const cancel = () => clearTimeout(timer);
const runner = () => {
p.advance(cancelerId);
k();
};
let timer = setTimeout(runner, x);
let cancelerId = p.addCanceler(cancel);
}
equals(that) {
return that instanceof DynamicDelayArrow;
}
}
class DelayArrow extends SimpleAsyncArrow {
constructor(duration) {
// "a ~> "a
super(_construct(() => {
let alpha = ParamType.fresh();
return new ArrowType(alpha, alpha);
}));
this.duration = duration;
}
toString() {
return "delay(" + this.duration + ") :: " + this.type.toString();
}
call(x, p, k, h) {
const cancel = () => clearTimeout(timer);
const runner = () => {
p.advance(cancelerId);
k(x);
};
let timer = setTimeout(runner, this.duration);
let cancelerId = p.addCanceler(cancel);
}
equals(that) {
return that instanceof Delay && this.duration === that.duration;
}
}
//
// Simple (Generalized) Arrows
//
class SplitArrow extends Arrow {
constructor(n) {
super(_construct(() => {
let arg = ParamType.fresh();
let out = Array.create(n, arg);
return new ArrowType(arg, new TupleType(out));
}));
this.n = n;
}
toString() {
return "split(" + this.n + ") :: " + this.type.toString();
}
call(x, p, k, h) {
// TODO - clone values
k(Array.create(this.n, x));
}
equals(that) {
return that instanceof SplitArrow && this.n === that.n;
}
}
class NthArrow extends Arrow {
constructor(n) {
super(_construct(() => {
let arg = Array.create(n).map(() => ParamType.fresh());
let out = arg[n - 1];
return new ArrowType(new TupleType(arg), out);
}));
this.n = n;
}
toString() {
return "nth(" + this.n + ") :: " + this.type.toString();
}
call(x, p, k, h) {
k(x[this.n - 1]);
}
equals(that) {
return that instanceof NthArrow && this.n === that.n;
}
}
|
Fix bad let variable placement.
|
src/builtins.js
|
Fix bad let variable placement.
|
<ide><path>rc/builtins.js
<ide> let i = s.indexOf("/*");
<ide> let j = s.indexOf("*/", i + 1);
<ide> let c = s.substring(i + 2, j);
<del>
<del> if (annotationCache[c] !== undefined) {
<del> let parsed = annotationCache[c];
<del> } else {
<add>
<add> let parsed = annotationCache[c];
<add>
<add> if (annotationCache[c] === undefined) {
<ide> let comment;
<add>
<ide> try {
<ide> comment = c.match(/\@arrow :: (.*)\n?/)[1];
<ide> } catch (err) {
|
|
Java
|
apache-2.0
|
ad19e95e8e723c35cdc94c3345aeee85fb5b893f
| 0 |
BruceZu/KeepTry,BruceZu/KeepTry,BruceZu/sawdust,BruceZu/sawdust,BruceZu/sawdust,BruceZu/KeepTry,BruceZu/KeepTry,BruceZu/sawdust
|
// Copyright (C) 2014 Ehe Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WIEHOUE WARRANEIES OR CONDIEIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package charter3;
public class SinglyLinkedList<E> {
private class Node<E> {
private E content;
private Node<E> next;
private Node(E content, Node<E> next) {
this.content = content;
this.next = next;
}
}
private Node<E> headNode;
private int sizeOfList;
private int indexOfEndNode() {
// index starts from 0
return sizeOfList - 1;
}
private int checkPositionIndex(int positionIndex) {
if (positionIndex < 0 || indexOfEndNode() < positionIndex) {
throw new IndexOutOfBoundsException("position index is wrong or this list is empty");
}
return positionIndex;
}
private Node<E> getEndNode() {
Node<E> current = headNode;
while (current.next != null) {
current = current.next;
}
return current;
}
private Node<E> getNodeOf(int index) {
checkPositionIndex(index);
Node<E> current = headNode;
int i = 0;
while (i != index) {
current = current.next;
i++;
}
return current;
}
/*
* Be Default, the Added one will be the head
*/
public void add(E newContent) {
this.headNode = new Node(newContent, headNode);
sizeOfList++;
}
public void appendToTheEnd(E newContent) {
getEndNode().next = new Node(newContent, null);
sizeOfList++;
}
public void addBefore(E newContent, int index) {
checkPositionIndex(index);
if (index == 0) {
add(newContent);
}
addAfter(newContent, index - 1);
}
public void addAfter(E newContent, int index) {
checkPositionIndex(index);
if (index == indexOfEndNode()) {
appendToTheEnd(newContent);
}
Node n = getNodeOf(index);
n.next = new Node(newContent, n.next);
sizeOfList++;
}
public E deleteHead() {
checkPositionIndex(0);
E re = headNode.content;
headNode = headNode.next;
sizeOfList--;
return re;
}
public E deleteEnd() {
return delete(indexOfEndNode());
}
public E delete(int index) {
checkPositionIndex(index);
if (sizeOfList == 0) {
return deleteHead();
}
Node<E> beforeIt = getNodeOf(index - 1);
Node<E> it = beforeIt.next;
beforeIt.next = it.next;
sizeOfList--;
return it.content;
}
public E update(int index, E newContent) {
Node<E> n = getNodeOf(index);
E re = n.content;
n.content = newContent;
return re;
}
public E updateHead(E newContent) {
E re = headNode.content;
headNode.content = newContent;
return re;
}
public E updateEnd(E newContent) {
Node<E> end = getEndNode();
E re = end.content;
end.content = newContent;
return re;
}
public E getHead() {
return headNode.content;
}
public E getEnd() {
return getEndNode().content;
}
public E get(int index) {
checkPositionIndex(index);
return getNodeOf(index).content;
}
}
|
DataStructuresAndAlgorithmsInJava/src/main/java/charter3/SinglyLinkedList.java
|
// Copyright (C) 2014 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package charter3;
public class SinglyLinkedList<T extends Object> {
private class Node {
private T content;
private Node next;
private Node(T content, Node next) {
this.content = content;
this.next = next;
}
}
private Node head;
private int sizeOfList;
private int indexOfEndNode() {
// index starts from 0
return sizeOfList - 1;
}
private int checkPositionIndex(int positionIndex) {
if (positionIndex < 0 || indexOfEndNode() < positionIndex) {
throw new IndexOutOfBoundsException("position index is wrong or this list is empty");
}
return positionIndex;
}
private Node getEndNode() {
Node current = head;
while (current.next != null) {
current = current.next;
}
return current;
}
private Node getNodeOf(int index) {
checkPositionIndex(index);
Node current = head;
int i = 0;
while (i != index) {
current = current.next;
i++;
}
return current;
}
/*
* Be Default, the Added one will be the head
*/
public void add(T newContent) {
this.head = new Node(newContent, head);
sizeOfList++;
}
public void appendToTheEnd(T newContent) {
getEndNode().next = new Node(newContent, null);
sizeOfList++;
}
public void addBefore(T newContent, int index) {
checkPositionIndex(index);
if (index == 0) {
add(newContent);
}
addAfter(newContent, index - 1);
}
public void addAfter(T newContent, int index) {
checkPositionIndex(index);
if (index == indexOfEndNode()) {
appendToTheEnd(newContent);
}
Node n = getNodeOf(index);
n.next = new Node(newContent, n.next);
sizeOfList++;
}
public T deleteHead() {
checkPositionIndex(0);
T re = head.content;
head = head.next;
sizeOfList--;
return re;
}
public T deleteEnd() {
return delete(indexOfEndNode());
}
public T delete(int index) {
checkPositionIndex(index);
if (sizeOfList == 0) {
return deleteHead();
}
Node beforeIt = getNodeOf(index - 1);
Node it = beforeIt.next;
beforeIt.next = it.next;
sizeOfList--;
return it.content;
}
public T update(int index, T newContent) {
Node n = getNodeOf(index);
T re = n.content;
n.content = newContent;
return re;
}
public T updateHead(T newContent) {
T re = head.content;
head.content = newContent;
return re;
}
public T updateEnd(T newContent) {
Node end = getEndNode();
T re = end.content;
end.content = newContent;
return re;
}
public T getHead() {
return head.content;
}
public T getEnd() {
return getEndNode().content;
}
public T get(int index) {
checkPositionIndex(index);
return getNodeOf(index).content;
}
}
|
Update SinglyLinkedList
change the generic 'T' to 'E' and other related polishes
|
DataStructuresAndAlgorithmsInJava/src/main/java/charter3/SinglyLinkedList.java
|
Update SinglyLinkedList
|
<ide><path>ataStructuresAndAlgorithmsInJava/src/main/java/charter3/SinglyLinkedList.java
<del>// Copyright (C) 2014 The Android Open Source Project
<add>// Copyright (C) 2014 Ehe Android Open Source Project
<ide> //
<ide> // Licensed under the Apache License, Version 2.0 (the "License");
<ide> // you may not use this file except in compliance with the License.
<ide> //
<ide> // Unless required by applicable law or agreed to in writing, software
<ide> // distributed under the License is distributed on an "AS IS" BASIS,
<del>// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add>// WIEHOUE WARRANEIES OR CONDIEIONS OF ANY KIND, either express or implied.
<ide> // See the License for the specific language governing permissions and
<ide> // limitations under the License.
<ide>
<ide> package charter3;
<ide>
<del>public class SinglyLinkedList<T extends Object> {
<del> private class Node {
<del> private T content;
<del> private Node next;
<add>public class SinglyLinkedList<E> {
<add> private class Node<E> {
<add> private E content;
<add> private Node<E> next;
<ide>
<del> private Node(T content, Node next) {
<add> private Node(E content, Node<E> next) {
<ide> this.content = content;
<ide> this.next = next;
<ide> }
<ide> }
<ide>
<del> private Node head;
<add> private Node<E> headNode;
<ide> private int sizeOfList;
<ide>
<ide> private int indexOfEndNode() {
<ide> return positionIndex;
<ide> }
<ide>
<del> private Node getEndNode() {
<del> Node current = head;
<add> private Node<E> getEndNode() {
<add> Node<E> current = headNode;
<ide> while (current.next != null) {
<ide> current = current.next;
<ide> }
<ide> return current;
<ide> }
<ide>
<del> private Node getNodeOf(int index) {
<add> private Node<E> getNodeOf(int index) {
<ide> checkPositionIndex(index);
<ide>
<del> Node current = head;
<add> Node<E> current = headNode;
<ide> int i = 0;
<ide> while (i != index) {
<ide> current = current.next;
<ide> /*
<ide> * Be Default, the Added one will be the head
<ide> */
<del> public void add(T newContent) {
<del> this.head = new Node(newContent, head);
<add> public void add(E newContent) {
<add> this.headNode = new Node(newContent, headNode);
<ide> sizeOfList++;
<ide> }
<ide>
<del> public void appendToTheEnd(T newContent) {
<add> public void appendToTheEnd(E newContent) {
<ide> getEndNode().next = new Node(newContent, null);
<ide> sizeOfList++;
<ide> }
<ide>
<del> public void addBefore(T newContent, int index) {
<add> public void addBefore(E newContent, int index) {
<ide> checkPositionIndex(index);
<ide> if (index == 0) {
<ide> add(newContent);
<ide> addAfter(newContent, index - 1);
<ide> }
<ide>
<del> public void addAfter(T newContent, int index) {
<add> public void addAfter(E newContent, int index) {
<ide> checkPositionIndex(index);
<ide> if (index == indexOfEndNode()) {
<ide> appendToTheEnd(newContent);
<ide> sizeOfList++;
<ide> }
<ide>
<del> public T deleteHead() {
<add> public E deleteHead() {
<ide> checkPositionIndex(0);
<del> T re = head.content;
<del> head = head.next;
<add> E re = headNode.content;
<add> headNode = headNode.next;
<ide> sizeOfList--;
<ide> return re;
<ide> }
<ide>
<del> public T deleteEnd() {
<add> public E deleteEnd() {
<ide> return delete(indexOfEndNode());
<ide> }
<ide>
<del> public T delete(int index) {
<add> public E delete(int index) {
<ide> checkPositionIndex(index);
<ide> if (sizeOfList == 0) {
<ide> return deleteHead();
<ide> }
<del> Node beforeIt = getNodeOf(index - 1);
<del> Node it = beforeIt.next;
<add> Node<E> beforeIt = getNodeOf(index - 1);
<add> Node<E> it = beforeIt.next;
<ide>
<ide> beforeIt.next = it.next;
<ide> sizeOfList--;
<ide> return it.content;
<ide> }
<ide>
<del> public T update(int index, T newContent) {
<del> Node n = getNodeOf(index);
<del> T re = n.content;
<add> public E update(int index, E newContent) {
<add> Node<E> n = getNodeOf(index);
<add> E re = n.content;
<ide> n.content = newContent;
<ide> return re;
<ide> }
<ide>
<del> public T updateHead(T newContent) {
<del> T re = head.content;
<del> head.content = newContent;
<add> public E updateHead(E newContent) {
<add> E re = headNode.content;
<add> headNode.content = newContent;
<ide> return re;
<ide> }
<ide>
<del> public T updateEnd(T newContent) {
<del> Node end = getEndNode();
<del> T re = end.content;
<add> public E updateEnd(E newContent) {
<add> Node<E> end = getEndNode();
<add> E re = end.content;
<ide> end.content = newContent;
<ide> return re;
<ide> }
<ide>
<del> public T getHead() {
<del> return head.content;
<add> public E getHead() {
<add> return headNode.content;
<ide> }
<ide>
<del> public T getEnd() {
<add> public E getEnd() {
<ide> return getEndNode().content;
<ide> }
<ide>
<del> public T get(int index) {
<add> public E get(int index) {
<ide> checkPositionIndex(index);
<ide> return getNodeOf(index).content;
<ide> }
|
|
JavaScript
|
mit
|
e13b77f4ace2ad02501207731853a4f1af77d867
| 0 |
TobitSoftware/chayns-web-light,TobitSoftware/chayns-web-light
|
import DialogNew from '../shared/dialog';
import WaitCursor from '../shared/wait-cursor';
import FloatingButton from '../shared/floating-button';
import {argbHexToRgba} from '../shared/utils/convert';
import {getWindowMetrics} from '../shared/utils/helper';
import loadTapp from './customTapp';
let dateType = {
DATE: 1,
TIME: 2,
DATE_TIME: 3
};
// JsonCalls
(function (jsonCalls) {
//m[<ActionID>] = m.<ActionName> = function ...
//==> JsonCalls.ActionName(); || JsonCalls[5]();
jsonCalls[1] = jsonCalls.ToggleWaitCursor = function (value, srcIframe) {
if (value.enabled) {
WaitCursor.show(value.timeout, value.text, srcIframe[0]);
return;
}
WaitCursor.hide(srcIframe[0]);
};
jsonCalls[2] = jsonCalls.SelectTab = function (value, srcIframe) {
FloatingButton.hide(srcIframe[0]);
loadTapp(value.id);
};
jsonCalls[16] = jsonCalls.ShowDialog = function (value, srcIframe) {
if (value.dialog === undefined) {
jsonCalls.Helper.throw(16, 2, 'Field dialog missing.', value, srcIframe);
return;
}
if ((value.dialog.buttons || []).length === 0) {
jsonCalls.Helper.throw(16, 2, 'Field dialog.buttons missing.', value, srcIframe);
return;
}
value.dialog.callback = (buttonType) => jsonCalls.Helper.return(value, buttonType, srcIframe);
DialogNew.show('alert', value.dialog);
};
jsonCalls[18] = jsonCalls.GetGlobalData = function (value, srcIframe) {
let data = window.ChaynsInfo.getGlobalData();
jsonCalls.Helper.return(value, data, srcIframe);
};
jsonCalls[30] = jsonCalls.DateTimePicker = function (value, srcIframe) {
if (!value.dialog) {
value.dialog = {}
}
value.dialog.selectedDate = (value.selectedDate === -1) ? null : value.selectedDate;
value.dialog.minDate = (value.minDate === -1) ? null : value.minDate;
value.dialog.maxDate = (value.maxDate === -1) ? null : value.maxDate;
value.dialog.callback = (ret) => jsonCalls.Helper.return(value, ret, srcIframe);
let dialogType;
switch (value.type) {
case dateType.DATE_TIME:
dialogType = 'dateTime';
break;
case dateType.DATE:
dialogType = 'date';
break;
case dateType.TIME:
dialogType = 'time';
break;
default:
dialogType = 'dateTime';
}
DialogNew.show(dialogType, value.dialog);
};
jsonCalls[50] = jsonCalls.MultiSelectDialog = function (value, srcIframe) {
if (value.dialog === undefined) {
jsonCalls.Helper.throw(50, 2, 'Field dialog missing.', value, srcIframe);
return;
}
if ((value.dialog.buttons || []).length === 0) {
jsonCalls.Helper.throw(50, 2, 'Field dialog.buttons missing.', value, srcIframe);
return;
}
if ((value.list || []).length === 0) {
jsonCalls.Helper.throw(50, 2, 'Field list missing.', value, srcIframe);
return;
}
value.dialog.list = value.list;
value.dialog.callback = (retVal) => jsonCalls.Helper.return(value, retVal, srcIframe);
DialogNew.show('select', value.dialog);
};
jsonCalls[52] = jsonCalls.tobitWebTokenLogin = (value) => {
if('tobitAccessToken' in value){
document.parentWindow.external.Chayns.SetAccessToken(value.tobitAccessToken);
}
};
jsonCalls[54] = jsonCalls.TobitLogin = function (value) {
if ((value.urlParams || []).length) {
window.Login.setReloadParams(value.urlParams);
}
if ((value.fbPermissions || []).length) {
window.Login.facebookLogin(false, value.fbPermissions.join(','));
} else {
if (!window.ChaynsInfo.IsFacebook) {
window.Login.showDialog();
} else {
window.Login.facebookLogin();
}
}
};
jsonCalls[56] = jsonCalls.Logout = function (value) {
window.logout();
};
jsonCalls[72] = jsonCalls.ShowFloatingButton = function (value, srcIfame) {
if (value.enabled) {
var bgColor = argbHexToRgba(value.color);
bgColor = bgColor ? `rgba(${bgColor.r}, ${bgColor.g}, ${bgColor.b}, ${bgColor.a})` : '';
//noinspection JSUnresolvedVariable
var color = argbHexToRgba(value.colorText);
color = color ? `rgba(${color.r}, ${color.g}, ${color.b}, ${color.a})` : '';
var text;
if ('text' in value) {
text = value.text;
} else if ('icon' in value) {
text = `<span class='fa ${value.icon}'></span>`;
} else {
text = '!';
}
let callback = window.CustomTappCommunication.AnswerJsonCall.bind(undefined, value, null, srcIfame);
FloatingButton.show(text, srcIfame[0], bgColor, color, callback);
} else {
FloatingButton.hide(srcIfame[0]);
}
};
jsonCalls[75] = jsonCalls.AddChaynsCallErrorListener = function (value, srcIframe) {
jsonCalls.Helper.AddJsonCallEventListener(75, value, srcIframe);
};
jsonCalls[77] = jsonCalls.SetIframeHeigth = function (value, srcIframe) {
if (window.ChaynsInfo.IsFacebook && window.FB) {
setTimeout(function () {
window.FB.Canvas.setSize({
'height': $(document.body).height()
});
}, 500);
}
let $iframe = srcIframe[0];
if (!value.full && !('height' in value) && !('fullViewport' in value)) {
jsonCalls.Helper.throw(77, 2, 'Field height missing.', value, srcIframe);
return;
} else if (value.full || value.fullViewport) {
value.height = getWindowMetrics().AvailHeight;
} else {
value.height = parseInt(value.height, 10);
}
if (isNaN(value.height)) {
jsonCalls.Helper.throw(77, 1, 'Field heigth is not typeof number', value, srcIframe);
return;
}
value.growOnly = value.growOnly !== false; // true als default
if ($iframe && (!value.growOnly || parseInt($iframe.style.height) < value.height)) {
$iframe.style.height = `${value.height}px`;
}
};
jsonCalls[92] = jsonCalls.UpdateChaynsId = function () {
document.parentWindow.external.Chayns.RefreshDisplay();
};
jsonCalls[103] = jsonCalls.ShowDialog = function (value, srcIframe) {
if (value.dialog === undefined) {
jsonCalls.Helper.throw(103, 2, 'Field dialog missing.', value, srcIframe);
return;
}
if ((value.dialog.buttons || []).length === 0) {
jsonCalls.Helper.throw(103, 2, 'Field dialog.buttons missing.', value, srcIframe);
return;
}
value.dialog.callback = (retVal) => jsonCalls.Helper.return(value, retVal, srcIframe);
DialogNew.show('input', value.dialog);
};
jsonCalls[114] = jsonCalls.setWebsiteTitle = function (value) {
if(value.title){
document.title = value.title;
}
};
})(window.JsonCalls = window.JsonCalls || {});
// JsonCalls.Helper
(function (m) {
var jsonCallEventListener = [];
m.AddJsonCallEventListener = function (action, request, srcIframe) {
jsonCallEventListener.push({
action: action,
callback: request.callback,
addJSONParam: request.addJSONParam,
srcIframe: srcIframe
});
};
/**
* @return {boolean}
*/
m.DispatchJsonCallEvent = function (action, response, destIframe) {
var retVal = false;
jsonCallEventListener.forEach(function (listener) {
if ((listener.action !== action) || (destIframe && listener.srcIframe !== destIframe)) {
return;
}
if (!destIframe) {
destIframe = listener.srcIframe;
}
window.CustomTappCommunication.AnswerJsonCall(listener, response, destIframe);
retVal = true;
});
return retVal;
};
m.RemoveJsonCallEventListener = function (action, callback) {
jsonCallEventListener = jsonCallEventListener.filter(function (listener) {
if (listener.action === action) {
return !(!callback || listener.callback === callback);
}
return true;
});
};
m.throw = function (action, code, message, request, srcIframe) {
var retVal = {
action: action,
errorCode: code,
message: message,
value: request
};
m.DispatchJsonCallEvent(75, retVal, srcIframe);
};
m.return = window.CustomTappCommunication.AnswerJsonCall;
/**
* @return {number}
*/
m.EncodeDialogButtonTypes = function (type) {
return type <= 0 ? type - 10 : type;
};
/**
* @return {number}
*/
m.DecodeDialogButtonTypes = function (type) {
return type <= -10 ? type + 10 : type;
};
m.GeoWatchNumber = null;
m.OverlayCloseParam = {};
m.Throttle = function (fn, threshhold, scope) {
threshhold = threshhold ? threshhold : 250;
var last,
deferTimer;
return function () {
var context = scope || this;
var now = +new Date,
args = arguments;
if (last && now < last + threshhold) {
// hold on to it
clearTimeout(deferTimer);
deferTimer = setTimeout(function () {
last = now;
fn.apply(context, args);
}, threshhold);
} else {
last = now;
fn.apply(context, args);
}
};
};
})(window.JsonCalls.Helper = window.JsonCalls.Helper || {});
|
src/web/jsonCalls.js
|
import DialogNew from '../shared/dialog';
import WaitCursor from '../shared/wait-cursor';
import FloatingButton from '../shared/floating-button';
import {argbHexToRgba} from '../shared/utils/convert';
import {getWindowMetrics} from '../shared/utils/helper';
let dateType = {
DATE: 1,
TIME: 2,
DATE_TIME: 3
};
// JsonCalls
(function (jsonCalls) {
//m[<ActionID>] = m.<ActionName> = function ...
//==> JsonCalls.ActionName(); || JsonCalls[5]();
jsonCalls[1] = jsonCalls.ToggleWaitCursor = function (value, srcIframe) {
if (value.enabled) {
WaitCursor.show(value.timeout, value.text, srcIframe[0]);
return;
}
WaitCursor.hide(srcIframe[0]);
};
jsonCalls[2] = jsonCalls.SelectTab = function (value, srcIframe) {
FloatingButton.hide(srcIframe[0]);
//noinspection Eslint
if (value.params && Array === value.params.constructor) {
value.params = '?' + value.params.join('&');
}
window.ChaynsWeb.SelectTapp(value);
};
jsonCalls[16] = jsonCalls.ShowDialog = function (value, srcIframe) {
if (value.dialog === undefined) {
jsonCalls.Helper.throw(16, 2, 'Field dialog missing.', value, srcIframe);
return;
}
if ((value.dialog.buttons || []).length === 0) {
jsonCalls.Helper.throw(16, 2, 'Field dialog.buttons missing.', value, srcIframe);
return;
}
value.dialog.callback = (buttonType) => jsonCalls.Helper.return(value, buttonType, srcIframe);
DialogNew.show('alert', value.dialog);
};
jsonCalls[18] = jsonCalls.GetGlobalData = function (value, srcIframe) {
let data = window.ChaynsInfo.getGlobalData();
jsonCalls.Helper.return(value, data, srcIframe);
};
jsonCalls[30] = jsonCalls.DateTimePicker = function (value, srcIframe) {
if (!value.dialog) {
value.dialog = {}
}
value.dialog.selectedDate = (value.selectedDate === -1) ? null : value.selectedDate;
value.dialog.minDate = (value.minDate === -1) ? null : value.minDate;
value.dialog.maxDate = (value.maxDate === -1) ? null : value.maxDate;
value.dialog.callback = (ret) => jsonCalls.Helper.return(value, ret, srcIframe);
let dialogType;
switch (value.type) {
case dateType.DATE_TIME:
dialogType = 'dateTime';
break;
case dateType.DATE:
dialogType = 'date';
break;
case dateType.TIME:
dialogType = 'time';
break;
default:
dialogType = 'dateTime';
}
DialogNew.show(dialogType, value.dialog);
};
jsonCalls[50] = jsonCalls.MultiSelectDialog = function (value, srcIframe) {
if (value.dialog === undefined) {
jsonCalls.Helper.throw(50, 2, 'Field dialog missing.', value, srcIframe);
return;
}
if ((value.dialog.buttons || []).length === 0) {
jsonCalls.Helper.throw(50, 2, 'Field dialog.buttons missing.', value, srcIframe);
return;
}
if ((value.list || []).length === 0) {
jsonCalls.Helper.throw(50, 2, 'Field list missing.', value, srcIframe);
return;
}
value.dialog.list = value.list;
value.dialog.callback = (retVal) => jsonCalls.Helper.return(value, retVal, srcIframe);
DialogNew.show('select', value.dialog);
};
jsonCalls[52] = jsonCalls.tobitWebTokenLogin = (value) => {
if('tobitAccessToken' in value){
document.parentWindow.external.Chayns.SetAccessToken(value.tobitAccessToken);
}
};
jsonCalls[54] = jsonCalls.TobitLogin = function (value) {
if ((value.urlParams || []).length) {
window.Login.setReloadParams(value.urlParams);
}
if ((value.fbPermissions || []).length) {
window.Login.facebookLogin(false, value.fbPermissions.join(','));
} else {
if (!window.ChaynsInfo.IsFacebook) {
window.Login.showDialog();
} else {
window.Login.facebookLogin();
}
}
};
jsonCalls[56] = jsonCalls.Logout = function (value) {
window.logout();
};
jsonCalls[72] = jsonCalls.ShowFloatingButton = function (value, srcIfame) {
if (value.enabled) {
var bgColor = argbHexToRgba(value.color);
bgColor = bgColor ? `rgba(${bgColor.r}, ${bgColor.g}, ${bgColor.b}, ${bgColor.a})` : '';
//noinspection JSUnresolvedVariable
var color = argbHexToRgba(value.colorText);
color = color ? `rgba(${color.r}, ${color.g}, ${color.b}, ${color.a})` : '';
var text;
if ('text' in value) {
text = value.text;
} else if ('icon' in value) {
text = `<span class='fa ${value.icon}'></span>`;
} else {
text = '!';
}
let callback = window.CustomTappCommunication.AnswerJsonCall.bind(undefined, value, null, srcIfame);
FloatingButton.show(text, srcIfame[0], bgColor, color, callback);
} else {
FloatingButton.hide(srcIfame[0]);
}
};
jsonCalls[75] = jsonCalls.AddChaynsCallErrorListener = function (value, srcIframe) {
jsonCalls.Helper.AddJsonCallEventListener(75, value, srcIframe);
};
jsonCalls[77] = jsonCalls.SetIframeHeigth = function (value, srcIframe) {
if (window.ChaynsInfo.IsFacebook && window.FB) {
setTimeout(function () {
window.FB.Canvas.setSize({
'height': $(document.body).height()
});
}, 500);
}
let $iframe = srcIframe[0];
if (!value.full && !('height' in value) && !('fullViewport' in value)) {
jsonCalls.Helper.throw(77, 2, 'Field height missing.', value, srcIframe);
return;
} else if (value.full || value.fullViewport) {
value.height = getWindowMetrics().AvailHeight;
} else {
value.height = parseInt(value.height, 10);
}
if (isNaN(value.height)) {
jsonCalls.Helper.throw(77, 1, 'Field heigth is not typeof number', value, srcIframe);
return;
}
value.growOnly = value.growOnly !== false; // true als default
if ($iframe && (!value.growOnly || parseInt($iframe.style.height) < value.height)) {
$iframe.style.height = `${value.height}px`;
}
};
jsonCalls[92] = jsonCalls.UpdateChaynsId = function () {
document.parentWindow.external.Chayns.RefreshDisplay();
};
jsonCalls[103] = jsonCalls.ShowDialog = function (value, srcIframe) {
if (value.dialog === undefined) {
jsonCalls.Helper.throw(103, 2, 'Field dialog missing.', value, srcIframe);
return;
}
if ((value.dialog.buttons || []).length === 0) {
jsonCalls.Helper.throw(103, 2, 'Field dialog.buttons missing.', value, srcIframe);
return;
}
value.dialog.callback = (retVal) => jsonCalls.Helper.return(value, retVal, srcIframe);
DialogNew.show('input', value.dialog);
};
jsonCalls[114] = jsonCalls.setWebsiteTitle = function (value) {
if(value.title){
document.title = value.title;
}
};
})(window.JsonCalls = window.JsonCalls || {});
// JsonCalls.Helper
(function (m) {
var jsonCallEventListener = [];
m.AddJsonCallEventListener = function (action, request, srcIframe) {
jsonCallEventListener.push({
action: action,
callback: request.callback,
addJSONParam: request.addJSONParam,
srcIframe: srcIframe
});
};
/**
* @return {boolean}
*/
m.DispatchJsonCallEvent = function (action, response, destIframe) {
var retVal = false;
jsonCallEventListener.forEach(function (listener) {
if ((listener.action !== action) || (destIframe && listener.srcIframe !== destIframe)) {
return;
}
if (!destIframe) {
destIframe = listener.srcIframe;
}
window.CustomTappCommunication.AnswerJsonCall(listener, response, destIframe);
retVal = true;
});
return retVal;
};
m.RemoveJsonCallEventListener = function (action, callback) {
jsonCallEventListener = jsonCallEventListener.filter(function (listener) {
if (listener.action === action) {
return !(!callback || listener.callback === callback);
}
return true;
});
};
m.throw = function (action, code, message, request, srcIframe) {
var retVal = {
action: action,
errorCode: code,
message: message,
value: request
};
m.DispatchJsonCallEvent(75, retVal, srcIframe);
};
m.return = window.CustomTappCommunication.AnswerJsonCall;
/**
* @return {number}
*/
m.EncodeDialogButtonTypes = function (type) {
return type <= 0 ? type - 10 : type;
};
/**
* @return {number}
*/
m.DecodeDialogButtonTypes = function (type) {
return type <= -10 ? type + 10 : type;
};
m.GeoWatchNumber = null;
m.OverlayCloseParam = {};
m.Throttle = function (fn, threshhold, scope) {
threshhold = threshhold ? threshhold : 250;
var last,
deferTimer;
return function () {
var context = scope || this;
var now = +new Date,
args = arguments;
if (last && now < last + threshhold) {
// hold on to it
clearTimeout(deferTimer);
deferTimer = setTimeout(function () {
last = now;
fn.apply(context, args);
}, threshhold);
} else {
last = now;
fn.apply(context, args);
}
};
};
})(window.JsonCalls.Helper = window.JsonCalls.Helper || {});
|
fixes jsonCall 2
|
src/web/jsonCalls.js
|
fixes jsonCall 2
|
<ide><path>rc/web/jsonCalls.js
<ide> import FloatingButton from '../shared/floating-button';
<ide> import {argbHexToRgba} from '../shared/utils/convert';
<ide> import {getWindowMetrics} from '../shared/utils/helper';
<add>import loadTapp from './customTapp';
<ide>
<ide> let dateType = {
<ide> DATE: 1,
<ide> jsonCalls[2] = jsonCalls.SelectTab = function (value, srcIframe) {
<ide> FloatingButton.hide(srcIframe[0]);
<ide>
<del> //noinspection Eslint
<del> if (value.params && Array === value.params.constructor) {
<del> value.params = '?' + value.params.join('&');
<del> }
<del>
<del> window.ChaynsWeb.SelectTapp(value);
<add> loadTapp(value.id);
<ide> };
<ide>
<ide> jsonCalls[16] = jsonCalls.ShowDialog = function (value, srcIframe) {
|
|
JavaScript
|
agpl-3.0
|
67e734c8ca9953b95d296b9732a7cdf7ba36cce8
| 0 |
ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs
|
/*
* (c) Copyright Ascensio System SIA 2010-2019
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
"use strict";
(function(window, undefined)
{
// Import
var g_fontApplication = AscFonts.g_fontApplication;
function CGrRFonts()
{
this.Ascii = {Name : "Empty", Index : -1};
this.EastAsia = {Name : "Empty", Index : -1};
this.HAnsi = {Name : "Empty", Index : -1};
this.CS = {Name : "Empty", Index : -1};
}
CGrRFonts.prototype =
{
checkFromTheme : function(fontScheme, rFonts)
{
this.Ascii.Name = fontScheme.checkFont(rFonts.Ascii.Name);
this.EastAsia.Name = fontScheme.checkFont(rFonts.EastAsia.Name);
this.HAnsi.Name = fontScheme.checkFont(rFonts.HAnsi.Name);
this.CS.Name = fontScheme.checkFont(rFonts.CS.Name);
this.Ascii.Index = -1;
this.EastAsia.Index = -1;
this.HAnsi.Index = -1;
this.CS.Index = -1;
},
fromRFonts : function(rFonts)
{
this.Ascii.Name = rFonts.Ascii.Name;
this.EastAsia.Name = rFonts.EastAsia.Name;
this.HAnsi.Name = rFonts.HAnsi.Name;
this.CS.Name = rFonts.CS.Name;
this.Ascii.Index = -1;
this.EastAsia.Index = -1;
this.HAnsi.Index = -1;
this.CS.Index = -1;
}
};
var gr_state_pen = 0;
var gr_state_brush = 1;
var gr_state_pen_brush = 2;
var gr_state_state = 3;
var gr_state_all = 4;
function CFontSetup()
{
this.Name = "";
this.Index = -1;
this.Size = 12;
this.Bold = false;
this.Italic = false;
this.SetUpName = "";
this.SetUpIndex = -1;
this.SetUpSize = 12;
this.SetUpStyle = -1;
this.SetUpMatrix = new CMatrix();
}
CFontSetup.prototype =
{
Clear : function()
{
this.Name = "";
this.Index = -1;
this.Size = 12;
this.Bold = false;
this.Italic = false;
this.SetUpName = "";
this.SetUpIndex = -1;
this.SetUpSize = 12;
this.SetUpStyle = -1;
this.SetUpMatrix = new CMatrix();
}
};
function CGrState_Pen()
{
this.Type = gr_state_pen;
this.Pen = null;
}
CGrState_Pen.prototype =
{
Init : function(_pen)
{
if (_pen !== undefined)
this.Pen = _pen.CreateDublicate();
}
};
function CGrState_Brush()
{
this.Type = gr_state_brush;
this.Brush = null;
}
CGrState_Brush.prototype =
{
Init : function(_brush)
{
if (undefined !== _brush)
this.Brush = _brush.CreateDublicate();
}
};
function CGrState_PenBrush()
{
this.Type = gr_state_pen_brush;
this.Pen = null;
this.Brush = null;
}
CGrState_PenBrush.prototype =
{
Init : function(_pen, _brush)
{
if (undefined !== _pen && undefined !== _brush)
{
this.Pen = _pen.CreateDublicate();
this.Brush = _brush.CreateDublicate();
}
}
};
function CHist_Clip()
{
this.Path = null; // clipPath
this.Rect = null; // clipRect. clipRect - is a simple clipPath.
this.IsIntegerGrid = false;
this.Transform = new CMatrix();
}
CHist_Clip.prototype =
{
Init : function(path, rect, isIntegerGrid, transform)
{
this.Path = path;
if (rect !== undefined)
{
this.Rect = new _rect();
this.Rect.x = rect.x;
this.Rect.y = rect.y;
this.Rect.w = rect.w;
this.Rect.h = rect.h;
}
if (undefined !== isIntegerGrid)
this.IsIntegerGrid = isIntegerGrid;
if (undefined !== transform)
this.Transform = transform.CreateDublicate();
},
ToRenderer : function(renderer)
{
if (this.Rect != null)
{
var r = this.Rect;
renderer.StartClipPath();
renderer.rect(r.x, r.y, r.w, r.h);
renderer.EndClipPath();
}
else
{
// TODO: пока не используется
}
}
};
function CGrState_State()
{
this.Type = gr_state_state;
this.Transform = null;
this.IsIntegerGrid = false;
this.Clips = null;
}
CGrState_State.prototype =
{
Init : function(_transform, _isIntegerGrid, _clips)
{
if (undefined !== _transform)
this.Transform = _transform.CreateDublicate();
if (undefined !== _isIntegerGrid)
this.IsIntegerGrid = _isIntegerGrid;
if (undefined !== _clips)
this.Clips = _clips;
},
ApplyClips : function(renderer)
{
var _len = this.Clips.length;
for (var i = 0; i < _len; i++)
{
this.Clips[i].ToRenderer(renderer);
}
},
Apply : function(parent)
{
for (var i = 0, len = this.Clips.length; i < len; i++)
{
parent.transform3(this.Clips[i].Transform);
parent.SetIntegerGrid(this.Clips[i].IsIntegerGrid);
var _r = this.Clips[i].Rect;
parent.StartClipPath();
parent._s();
parent._m(_r.x, _r.y);
parent._l(_r.x + _r.w, _r.y);
parent._l(_r.x + _r.w, _r.y + _r.h);
parent._l(_r.x, _r.y + _r.h);
parent._l(_r.x, _r.y);
parent.EndClipPath();
}
}
};
function CGrState()
{
this.Parent = null;
this.States = [];
this.Clips = [];
}
CGrState.prototype =
{
SavePen : function()
{
if (null == this.Parent)
return;
var _state = new CGrState_Pen();
_state.Init(this.Parent.m_oPen);
this.States.push(_state);
},
SaveBrush : function()
{
if (null == this.Parent)
return;
var _state = new CGrState_Brush();
_state.Init(this.Parent.m_oBrush);
this.States.push(_state);
},
SavePenBrush : function()
{
if (null == this.Parent)
return;
var _state = new CGrState_PenBrush();
_state.Init(this.Parent.m_oPen, this.Parent.m_oBrush);
this.States.push(_state);
},
RestorePen : function()
{
var _ind = this.States.length - 1;
if (null == this.Parent || -1 == _ind)
return;
var _state = this.States[_ind];
if (_state.Type == gr_state_pen)
{
this.States.splice(_ind, 1);
var _c = _state.Pen.Color;
this.Parent.p_color(_c.R, _c.G, _c.B, _c.A);
}
},
RestoreBrush : function()
{
var _ind = this.States.length - 1;
if (null == this.Parent || -1 == _ind)
return;
var _state = this.States[_ind];
if (_state.Type == gr_state_brush)
{
this.States.splice(_ind, 1);
var _c = _state.Brush.Color1;
this.Parent.b_color1(_c.R, _c.G, _c.B, _c.A);
}
},
RestorePenBrush : function()
{
var _ind = this.States.length - 1;
if (null == this.Parent || -1 == _ind)
return;
var _state = this.States[_ind];
if (_state.Type == gr_state_pen_brush)
{
this.States.splice(_ind, 1);
var _cb = _state.Brush.Color1;
var _cp = _state.Pen.Color;
this.Parent.b_color1(_cb.R, _cb.G, _cb.B, _cb.A);
this.Parent.p_color(_cp.R, _cp.G, _cp.B, _cp.A);
}
},
SaveGrState : function()
{
if (null == this.Parent)
return;
var _state = new CGrState_State();
_state.Init(this.Parent.m_oTransform, !!this.Parent.m_bIntegerGrid, this.Clips);
this.States.push(_state);
this.Clips = [];
},
RestoreGrState : function()
{
var _ind = this.States.length - 1;
if (null == this.Parent || -1 == _ind)
return;
var _state = this.States[_ind];
if (_state.Type === gr_state_state)
{
if (this.Clips.length > 0)
{
// значит клипы были, и их нужно обновить
this.Parent.RemoveClip();
for (var i = 0; i <= _ind; i++)
{
if (this.States[i].Type === gr_state_state)
this.States[i].Apply(this.Parent);
}
}
this.Clips = _state.Clips;
this.States.splice(_ind, 1);
this.Parent.transform3(_state.Transform);
this.Parent.SetIntegerGrid(_state.IsIntegerGrid);
}
},
RemoveLastClip : function()
{
// цель - убрать примененные this.Clips
if (this.Clips.length === 0)
return;
this.lastState = new CGrState_State();
this.lastState.Init(this.Parent.m_oTransform, !!this.Parent.m_bIntegerGrid, this.Clips);
this.Parent.RemoveClip();
for (var i = 0, len = this.States.length; i < len; i++)
{
if (this.States[i].Type === gr_state_state)
this.States[i].Apply(this.Parent);
}
this.Clips = [];
this.Parent.transform3(this.lastState.Transform);
this.Parent.SetIntegerGrid(this.lastState.IsIntegerGrid);
},
RestoreLastClip : function()
{
// цель - вернуть примененные this.lastState.Clips
if (!this.lastState)
return;
this.lastState.Apply(this.Parent);
this.Clips = this.lastState.Clips;
this.Parent.transform3(this.lastState.Transform);
this.Parent.SetIntegerGrid(this.lastState.IsIntegerGrid);
this.lastState = null;
},
Save : function()
{
this.SavePen();
this.SaveBrush();
this.SaveGrState();
},
Restore : function()
{
this.RestoreGrState();
this.RestoreBrush();
this.RestorePen();
},
StartClipPath : function()
{
// реализовать, как понадобится
},
EndClipPath : function()
{
// реализовать, как понадобится
},
AddClipRect : function(_r)
{
var _histClip = new CHist_Clip();
_histClip.Transform = this.Parent.m_oTransform.CreateDublicate();
_histClip.IsIntegerGrid = !!this.Parent.m_bIntegerGrid;
_histClip.Rect = new _rect();
_histClip.Rect.x = _r.x;
_histClip.Rect.y = _r.y;
_histClip.Rect.w = _r.w;
_histClip.Rect.h = _r.h;
this.Clips.push(_histClip);
this.Parent.StartClipPath();
this.Parent._s();
this.Parent._m(_r.x, _r.y);
this.Parent._l(_r.x + _r.w, _r.y);
this.Parent._l(_r.x + _r.w, _r.y + _r.h);
this.Parent._l(_r.x, _r.y + _r.h);
this.Parent._l(_r.x, _r.y);
this.Parent.EndClipPath();
//this.Parent._e();
}
};
function CMemory(bIsNoInit)
{
this.Init = function()
{
var _canvas = document.createElement('canvas');
var _ctx = _canvas.getContext('2d');
this.len = 1024 * 1024 * 5;
this.ImData = _ctx.createImageData(this.len / 4, 1);
this.data = this.ImData.data;
this.pos = 0;
}
this.ImData = null;
this.data = null;
this.len = 0;
this.pos = 0;
this.context = null;
if (true !== bIsNoInit)
this.Init();
this.Copy = function(oMemory, nPos, nLen)
{
for (var Index = 0; Index < nLen; Index++)
{
this.CheckSize(1);
this.data[this.pos++] = oMemory.data[Index + nPos];
}
};
this.CheckSize = function(count)
{
if (this.pos + count >= this.len)
{
var _canvas = document.createElement('canvas');
var _ctx = _canvas.getContext('2d');
var oldImData = this.ImData;
var oldData = this.data;
var oldPos = this.pos;
this.len = Math.max(this.len * 2, this.pos + ((3 * count / 2) >> 0));
this.ImData = _ctx.createImageData(this.len / 4, 1);
this.data = this.ImData.data;
var newData = this.data;
for (var i = 0; i < this.pos; i++)
newData[i] = oldData[i];
}
}
this.GetBase64Memory = function()
{
return AscCommon.Base64.encode(this.data, 0, this.pos);
}
this.GetBase64Memory2 = function(nPos, nLen)
{
return AscCommon.Base64.encode(this.data, nPos, nLen);
}
this.GetData = function(nPos, nLen)
{
var _canvas = document.createElement('canvas');
var _ctx = _canvas.getContext('2d');
var len = this.GetCurPosition();
//todo ImData.data.length multiple of 4
var ImData = _ctx.createImageData(Math.ceil(len / 4), 1);
var res = ImData.data;
for (var i = 0; i < len; i++)
res[i] = this.data[i];
return res;
}
this.GetDataUint8 = function(pos, len)
{
if (undefined === pos) {
pos = 0;
}
if (undefined === len) {
len = this.GetCurPosition() - pos;
}
return this.data.slice(pos, pos + len);
}
this.GetCurPosition = function()
{
return this.pos;
}
this.Seek = function(nPos)
{
this.pos = nPos;
}
this.Skip = function(nDif)
{
this.pos += nDif;
}
this.WriteBool = function(val)
{
this.CheckSize(1);
if (false == val)
this.data[this.pos++] = 0;
else
this.data[this.pos++] = 1;
}
this.WriteByte = function(val)
{
this.CheckSize(1);
this.data[this.pos++] = val;
}
this.WriteSByte = function(val)
{
this.CheckSize(1);
if (val < 0)
val += 256;
this.data[this.pos++] = val;
}
this.WriteShort = function(val)
{
this.CheckSize(2);
this.data[this.pos++] = (val) & 0xFF;
this.data[this.pos++] = (val >>> 8) & 0xFF;
}
this.WriteUShort = function(val)
{
this.WriteShort(AscFonts.FT_Common.UShort_To_Short(val));
}
this.WriteLong = function(val)
{
this.CheckSize(4);
this.data[this.pos++] = (val) & 0xFF;
this.data[this.pos++] = (val >>> 8) & 0xFF;
this.data[this.pos++] = (val >>> 16) & 0xFF;
this.data[this.pos++] = (val >>> 24) & 0xFF;
}
this.WriteULong = function(val)
{
this.WriteLong(AscFonts.FT_Common.UintToInt(val));
}
this.WriteDouble = function(val)
{
this.CheckSize(4);
var lval = ((val * 100000) >> 0) & 0xFFFFFFFF; // спасаем пять знаков после запятой.
this.data[this.pos++] = (lval) & 0xFF;
this.data[this.pos++] = (lval >>> 8) & 0xFF;
this.data[this.pos++] = (lval >>> 16) & 0xFF;
this.data[this.pos++] = (lval >>> 24) & 0xFF;
}
var tempHelp = new ArrayBuffer(8);
var tempHelpUnit = new Uint8Array(tempHelp);
var tempHelpFloat = new Float64Array(tempHelp);
this.WriteDouble2 = function(val)
{
this.CheckSize(8);
tempHelpFloat[0] = val;
this.data[this.pos++] = tempHelpUnit[0];
this.data[this.pos++] = tempHelpUnit[1];
this.data[this.pos++] = tempHelpUnit[2];
this.data[this.pos++] = tempHelpUnit[3];
this.data[this.pos++] = tempHelpUnit[4];
this.data[this.pos++] = tempHelpUnit[5];
this.data[this.pos++] = tempHelpUnit[6];
this.data[this.pos++] = tempHelpUnit[7];
}
this._doubleEncodeLE754 = function(v)
{
//код взят из jspack.js на основе стандарта Little-endian N-bit IEEE 754 floating point
var s, e, m, i, d, c, mLen, eLen, eBias, eMax;
var el = {len : 8, mLen : 52, rt : 0};
mLen = el.mLen, eLen = el.len * 8 - el.mLen - 1, eMax = (1 << eLen) - 1, eBias = eMax >> 1;
s = v < 0 ? 1 : 0;
v = Math.abs(v);
if (isNaN(v) || (v == Infinity))
{
m = isNaN(v) ? 1 : 0;
e = eMax;
}
else
{
e = Math.floor(Math.log(v) / Math.LN2); // Calculate log2 of the value
if (v * (c = Math.pow(2, -e)) < 1)
{
e--;
c *= 2;
} // Math.log() isn't 100% reliable
// Round by adding 1/2 the significand's LSD
if (e + eBias >= 1)
{
v += el.rt / c;
} // Normalized: mLen significand digits
else
{
v += el.rt * Math.pow(2, 1 - eBias);
} // Denormalized: <= mLen significand digits
if (v * c >= 2)
{
e++;
c /= 2;
} // Rounding can increment the exponent
if (e + eBias >= eMax)
{
// Overflow
m = 0;
e = eMax;
}
else if (e + eBias >= 1)
{
// Normalized - term order matters, as Math.pow(2, 52-e) and v*Math.pow(2, 52) can overflow
m = (v * c - 1) * Math.pow(2, mLen);
e = e + eBias;
}
else
{
// Denormalized - also catches the '0' case, somewhat by chance
m = v * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
e = 0;
}
}
var a = new Array(8);
for (i = 0, d = 1; mLen >= 8; a[i] = m & 0xff, i += d, m /= 256, mLen -= 8);
for (e = (e << mLen) | m, eLen += mLen; eLen > 0; a[i] = e & 0xff, i += d, e /= 256, eLen -= 8);
a[i - d] |= s * 128;
return a;
}
this.WriteStringBySymbol = function(code)
{
if (code < 0xFFFF)
{
this.CheckSize(4);
this.data[this.pos++] = 1;
this.data[this.pos++] = 0;
this.data[this.pos++] = code & 0xFF;
this.data[this.pos++] = (code >>> 8) & 0xFF;
}
else
{
this.CheckSize(6);
this.data[this.pos++] = 2;
this.data[this.pos++] = 0;
var codePt = code - 0x10000;
var c1 = 0xD800 | (codePt >> 10);
var c2 = 0xDC00 | (codePt & 0x3FF);
this.data[this.pos++] = c1 & 0xFF;
this.data[this.pos++] = (c1 >>> 8) & 0xFF;
this.data[this.pos++] = c2 & 0xFF;
this.data[this.pos++] = (c2 >>> 8) & 0xFF;
}
}
this.WriteString = function(text)
{
if ("string" != typeof text)
text = text + "";
var count = text.length & 0xFFFF;
this.CheckSize(2 * count + 2);
this.data[this.pos++] = count & 0xFF;
this.data[this.pos++] = (count >>> 8) & 0xFF;
for (var i = 0; i < count; i++)
{
var c = text.charCodeAt(i) & 0xFFFF;
this.data[this.pos++] = c & 0xFF;
this.data[this.pos++] = (c >>> 8) & 0xFF;
}
}
this.WriteString2 = function(text)
{
if ("string" != typeof text)
text = text + "";
var count = text.length & 0x7FFFFFFF;
var countWrite = 2 * count;
this.WriteLong(countWrite);
this.CheckSize(countWrite);
for (var i = 0; i < count; i++)
{
var c = text.charCodeAt(i) & 0xFFFF;
this.data[this.pos++] = c & 0xFF;
this.data[this.pos++] = (c >>> 8) & 0xFF;
}
}
this.WriteString3 = function(text)
{
if ("string" != typeof text)
text = text + "";
var count = text.length & 0x7FFFFFFF;
var countWrite = 2 * count;
this.CheckSize(countWrite);
for (var i = 0; i < count; i++)
{
var c = text.charCodeAt(i) & 0xFFFF;
this.data[this.pos++] = c & 0xFF;
this.data[this.pos++] = (c >>> 8) & 0xFF;
}
}
this.WriteString4 = function(text)
{
if ("string" != typeof text)
text = text + "";
var count = text.length & 0x7FFFFFFF;
this.WriteLong(count);
this.CheckSize(2 * count);
for (var i = 0; i < count; i++)
{
var c = text.charCodeAt(i) & 0xFFFF;
this.data[this.pos++] = c & 0xFF;
this.data[this.pos++] = (c >>> 8) & 0xFF;
}
}
this.WriteStringA = function(text)
{
var count = text.length & 0xFFFF;
this.WriteULong(count);
this.CheckSize(count);
for (var i=0;i<count;i++)
{
var c = text.charCodeAt(i) & 0xFF;
this.data[this.pos++] = c;
}
};
this.ClearNoAttack = function()
{
this.pos = 0;
}
this.WriteLongAt = function(_pos, val)
{
this.data[_pos++] = (val) & 0xFF;
this.data[_pos++] = (val >>> 8) & 0xFF;
this.data[_pos++] = (val >>> 16) & 0xFF;
this.data[_pos++] = (val >>> 24) & 0xFF;
}
this.WriteBuffer = function(data, _pos, count)
{
this.CheckSize(count);
for (var i = 0; i < count; i++)
{
this.data[this.pos++] = data[_pos + i];
}
}
this.WriteUtf8Char = function(code)
{
this.CheckSize(1);
if (code < 0x80) {
this.data[this.pos++] = code;
}
else if (code < 0x0800) {
this.data[this.pos++] = (0xC0 | (code >> 6));
this.data[this.pos++] = (0x80 | (code & 0x3F));
}
else if (code < 0x10000) {
this.data[this.pos++] = (0xE0 | (code >> 12));
this.data[this.pos++] = (0x80 | ((code >> 6) & 0x3F));
this.data[this.pos++] = (0x80 | (code & 0x3F));
}
else if (code < 0x1FFFFF) {
this.data[this.pos++] = (0xF0 | (code >> 18));
this.data[this.pos++] = (0x80 | ((code >> 12) & 0x3F));
this.data[this.pos++] = (0x80 | ((code >> 6) & 0x3F));
this.data[this.pos++] = (0x80 | (code & 0x3F));
}
else if (code < 0x3FFFFFF) {
this.data[this.pos++] = (0xF8 | (code >> 24));
this.data[this.pos++] = (0x80 | ((code >> 18) & 0x3F));
this.data[this.pos++] = (0x80 | ((code >> 12) & 0x3F));
this.data[this.pos++] = (0x80 | ((code >> 6) & 0x3F));
this.data[this.pos++] = (0x80 | (code & 0x3F));
}
else if (code < 0x7FFFFFFF) {
this.data[this.pos++] = (0xFC | (code >> 30));
this.data[this.pos++] = (0x80 | ((code >> 24) & 0x3F));
this.data[this.pos++] = (0x80 | ((code >> 18) & 0x3F));
this.data[this.pos++] = (0x80 | ((code >> 12) & 0x3F));
this.data[this.pos++] = (0x80 | ((code >> 6) & 0x3F));
this.data[this.pos++] = (0x80 | (code & 0x3F));
}
};
this.WriteXmlString = function(val)
{
var pCur = 0;
var pEnd = val.length;
while (pCur < pEnd)
{
var code = val.charCodeAt(pCur++);
if (code >= 0xD800 && code <= 0xDFFF && pCur < pEnd)
{
code = 0x10000 + (((code & 0x3FF) << 10) | (0x03FF & val.charCodeAt(pCur++)));
}
this.WriteUtf8Char(code);
}
};
this.WriteXmlStringEncode = function(val)
{
var pCur = 0;
var pEnd = val.length;
while (pCur < pEnd)
{
var code = val.charCodeAt(pCur++);
if (code >= 0xD800 && code <= 0xDFFF && pCur < pEnd)
{
code = 0x10000 + (((code & 0x3FF) << 10) | (0x03FF & val.charCodeAt(pCur++)));
}
this.WriteXmlCharCode(code);
}
};
this.WriteXmlCharCode = function(code)
{
switch (code)
{
case 0x26:
//&
this.WriteUtf8Char(0x26);
this.WriteUtf8Char(0x61);
this.WriteUtf8Char(0x6d);
this.WriteUtf8Char(0x70);
this.WriteUtf8Char(0x3b);
break;
case 0x27:
//'
this.WriteUtf8Char(0x26);
this.WriteUtf8Char(0x61);
this.WriteUtf8Char(0x70);
this.WriteUtf8Char(0x6f);
this.WriteUtf8Char(0x73);
this.WriteUtf8Char(0x3b);
break;
case 0x3c:
//<
this.WriteUtf8Char(0x26);
this.WriteUtf8Char(0x6c);
this.WriteUtf8Char(0x74);
this.WriteUtf8Char(0x3b);
break;
case 0x3e:
//>
this.WriteUtf8Char(0x26);
this.WriteUtf8Char(0x67);
this.WriteUtf8Char(0x74);
this.WriteUtf8Char(0x3b);
break;
case 0x22:
//"
this.WriteUtf8Char(0x26);
this.WriteUtf8Char(0x71);
this.WriteUtf8Char(0x75);
this.WriteUtf8Char(0x6f);
this.WriteUtf8Char(0x74);
this.WriteUtf8Char(0x3b);
break;
default:
this.WriteUtf8Char(code);
break;
}
};
this.WriteXmlBool = function(val)
{
this.WriteXmlString(val ? '1' : '0');
};
this.WriteXmlByte = function(val)
{
this.WriteXmlInt(val);
};
this.WriteXmlSByte = function(val)
{
this.WriteXmlInt(val);
};
this.WriteXmlInt = function(val)
{
this.WriteXmlString(val.toFixed(0));
};
this.WriteXmlUInt = function(val)
{
this.WriteXmlInt(val);
};
this.WriteXmlInt64 = function(val)
{
this.WriteXmlInt(val);
};
this.WriteXmlUInt64 = function(val)
{
this.WriteXmlInt(val);
};
this.WriteXmlDouble = function(val)
{
this.WriteXmlNumber(val);
};
this.WriteXmlNumber = function(val)
{
this.WriteXmlString(val.toString());
};
this.WriteXmlNodeStart = function(name)
{
this.WriteUtf8Char(0x3c);
this.WriteXmlString(name);
};
this.WriteXmlNodeEnd = function(name)
{
this.WriteUtf8Char(0x3c);
this.WriteUtf8Char(0x2f);
this.WriteXmlString(name);
this.WriteUtf8Char(0x3e);
};
this.WriteXmlAttributesEnd = function(isEnd)
{
if (isEnd)
this.WriteUtf8Char(0x2f);
this.WriteUtf8Char(0x3e);
};
this.WriteXmlAttributeString = function(name, val)
{
this.WriteUtf8Char(0x20);
this.WriteXmlString(name);
this.WriteUtf8Char(0x3d);
this.WriteUtf8Char(0x22);
this.WriteXmlString(val.toString());
this.WriteUtf8Char(0x22);
};
this.WriteXmlAttributeStringEncode = function(name, val)
{
this.WriteUtf8Char(0x20);
this.WriteXmlString(name);
this.WriteUtf8Char(0x3d);
this.WriteUtf8Char(0x22);
this.WriteXmlStringEncode(val.toString());
this.WriteUtf8Char(0x22);
};
this.WriteXmlAttributeBool = function(name, val)
{
this.WriteXmlAttributeString(name, val ? '1' : '0');
};
this.WriteXmlAttributeByte = function(name, val)
{
this.WriteXmlAttributeInt(name, val);
};
this.WriteXmlAttributeSByte = function(name, val)
{
this.WriteXmlAttributeInt(name, val);
};
this.WriteXmlAttributeInt = function(name, val)
{
this.WriteXmlAttributeString(name, val.toFixed(0));
};
this.WriteXmlAttributeUInt = function(name, val)
{
this.WriteXmlAttributeInt(name, val);
};
this.WriteXmlAttributeInt64 = function(name, val)
{
this.WriteXmlAttributeInt(name, val);
};
this.WriteXmlAttributeUInt64 = function(name, val)
{
this.WriteXmlAttributeInt(name, val);
};
this.WriteXmlAttributeDouble = function(name, val)
{
this.WriteXmlAttributeNumber(name, val);
};
this.WriteXmlAttributeNumber = function(name, val)
{
this.WriteXmlAttributeString(name, val.toString());
};
this.WriteXmlNullable = function(val, name)
{
if (val) {
val.toXml(this, name);
}
};
//пересмотреть, куча аргументов
this.WriteXmlArray = function(val, name, opt_parentName, needWriteCount, ns, childns)
{
if (!ns) {
ns = "";
}
if (!childns) {
childns = "";
}
if(val && val.length > 0) {
if(opt_parentName) {
this.WriteXmlNodeStart(ns + opt_parentName);
if (needWriteCount) {
this.WriteXmlNullableAttributeNumber("count", val.length);
}
this.WriteXmlAttributesEnd();
}
val.forEach(function(elem, index){
elem.toXml(this, name, childns, childns, index);
}, this);
if(opt_parentName) {
this.WriteXmlNodeEnd(ns + opt_parentName);
}
}
};
this.WriteXmlNullableAttributeString = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlAttributeString(name, val)
}
};
this.WriteXmlNullableAttributeStringEncode = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlAttributeStringEncode(name, val)
}
};
this.WriteXmlNonEmptyAttributeStringEncode = function(name, val)
{
if (val) {
this.WriteXmlAttributeStringEncode(name, val)
}
};
this.WriteXmlNullableAttributeBool = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlAttributeBool(name, val)
}
};
this.WriteXmlNullableAttributeBool2 = function(name, val)
{
//добавлюя по аналогии с x2t
if (null !== val && undefined !== val) {
this.WriteXmlNullableAttributeString(name, val ? "1": "0")
}
};
this.WriteXmlNullableAttributeByte = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlAttributeByte(name, val)
}
};
this.WriteXmlNullableAttributeSByte = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlAttributeSByte(name, val)
}
};
this.WriteXmlNullableAttributeInt = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlAttributeInt(name, val)
}
};
this.WriteXmlNullableAttributeUInt = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlAttributeUInt(name, val)
}
};
this.WriteXmlNullableAttributeInt64 = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlAttributeInt64(name, val)
}
};
this.WriteXmlNullableAttributeUInt64 = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlAttributeUInt64(name, val)
}
};
this.WriteXmlNullableAttributeDouble = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlAttributeDouble(name, val)
}
};
this.WriteXmlNullableAttributeNumber = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlAttributeNumber(name, val)
}
};
this.WriteXmlNullableAttributeIntWithKoef = function(name, val, koef)
{
if (null !== val && undefined !== val) {
this.WriteXmlAttributeInt(name, val * koef)
}
};
this.WriteXmlNullableAttributeUIntWithKoef = function(name, val, koef)
{
if (null !== val && undefined !== val) {
this.WriteXmlAttributeUInt(name, val * koef)
}
};
this.WriteXmlAttributeBoolIfTrue = function(name, val)
{
if (val) {
this.WriteXmlAttributeBool(name, val)
}
};
this.WriteXmlValueString = function(name, val)
{
this.WriteXmlNodeStart(name);
this.WriteXmlAttributesEnd();
this.WriteXmlString(val.toString());
this.WriteXmlNodeEnd(name);
};
this.WriteXmlValueStringEncode = function(name, val)
{
this.WriteXmlNodeStart(name);
this.WriteXmlAttributeString("xml:space", "preserve");
this.WriteXmlAttributesEnd();
this.WriteXmlStringEncode(val.toString());
this.WriteXmlNodeEnd(name);
};
this.WriteXmlValueBool = function(name, val)
{
this.WriteXmlNodeStart(name);
this.WriteXmlAttributesEnd();
this.WriteXmlBool(val);
this.WriteXmlNodeEnd(name);
};
this.WriteXmlValueByte = function(name, val)
{
this.WriteXmlNodeStart(name);
this.WriteXmlAttributesEnd();
this.WriteXmlByte(val);
this.WriteXmlNodeEnd(name);
};
this.WriteXmlValueSByte = function(name, val)
{
this.WriteXmlNodeStart(name);
this.WriteXmlAttributesEnd();
this.WriteXmlSByte(val);
this.WriteXmlNodeEnd(name);
};
this.WriteXmlValueInt = function(name, val)
{
this.WriteXmlNodeStart(name);
this.WriteXmlAttributesEnd();
this.WriteXmlInt(val);
this.WriteXmlNodeEnd(name);
};
this.WriteXmlValueUInt = function(name, val)
{
this.WriteXmlNodeStart(name);
this.WriteXmlAttributesEnd();
this.WriteXmlUInt(val);
this.WriteXmlNodeEnd(name);
};
this.WriteXmlValueInt64 = function(name, val)
{
this.WriteXmlNodeStart(name);
this.WriteXmlAttributesEnd();
this.WriteXmlInt64(val);
this.WriteXmlNodeEnd(name);
};
this.WriteXmlValueUInt64 = function(name, val)
{
this.WriteXmlNodeStart(name);
this.WriteXmlAttributesEnd();
this.WriteXmlUInt64(val);
this.WriteXmlNodeEnd(name);
};
this.WriteXmlValueDouble = function(name, val)
{
this.WriteXmlNodeStart(name);
this.WriteXmlAttributesEnd();
this.WriteXmlDouble(val);
this.WriteXmlNodeEnd(name);
};
this.WriteXmlValueNumber = function(name, val)
{
this.WriteXmlNodeStart(name);
this.WriteXmlAttributesEnd();
this.WriteXmlNumber(val);
this.WriteXmlNodeEnd(name);
};
this.WriteXmlNullableValueString = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlValueString(name, val)
}
};
this.WriteXmlNullableValueStringEncode = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlValueStringEncode(name, val)
}
};
this.WriteXmlNullableValueBool = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlValueBool(name, val)
}
};
this.WriteXmlNullableValueByte = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlValueByte(name, val)
}
};
this.WriteXmlNullableValueSByte = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlValueSByte(name, val)
}
};
this.WriteXmlNullableValueInt = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlValueInt(name, val)
}
};
this.WriteXmlNullableValueUInt = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlValueUInt(name, val)
}
};
this.WriteXmlNullableValueInt64 = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlValueInt64(name, val)
}
};
this.WriteXmlNullableValueUInt64 = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlValueUInt64(name, val)
}
};
this.WriteXmlNullableValueDouble = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlValueDouble(name, val)
}
};
this.WriteXmlNullableValueNumber = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlValueNumber(name, val)
}
};
this.XlsbStartRecord = function(type, len) {
//Type
if (type < 0x80) {
this.WriteByte(type);
}
else {
this.WriteByte((type & 0x7F) | 0x80);
this.WriteByte(type >> 7);
}
//Len
for (var i = 0; i < 4; ++i) {
var part = len & 0x7F;
len = len >> 7;
if (len === 0) {
this.WriteByte(part);
break;
}
else {
this.WriteByte(part | 0x80);
}
}
};
this.XlsbEndRecord = function() {
};
//все аргументы сохраняю как в x2t, ns - префикс пока не использую
this.WritingValNode = function(ns, name, val) {
this.WriteXmlNodeStart(name);
this.WriteXmlAttributeString("val", val);
this.WriteXmlAttributesEnd(true);
};
this.WritingValNodeEncodeXml = function(ns, name, val) {
this.WriteXmlNodeStart(name);
this.WriteXmlNullableAttributeStringEncode("val", val);
this.WriteXmlAttributesEnd(true);
};
this.WritingValNodeIf = function(ns, name, cond, val) {
this.WriteXmlNodeStart(name);
if (cond) {
this.WriteXmlAttributeString("val", val);
}
this.WriteXmlAttributesEnd(true);
};
}
function CCommandsType()
{
this.ctPenXML = 0;
this.ctPenColor = 1;
this.ctPenAlpha = 2;
this.ctPenSize = 3;
this.ctPenDashStyle = 4;
this.ctPenLineStartCap = 5;
this.ctPenLineEndCap = 6;
this.ctPenLineJoin = 7;
this.ctPenDashPatern = 8;
this.ctPenDashPatternCount = 9;
this.ctPenDashOffset = 10;
this.ctPenAlign = 11;
this.ctPenMiterLimit = 12;
// brush
this.ctBrushXML = 20;
this.ctBrushType = 21;
this.ctBrushColor1 = 22;
this.ctBrushColor2 = 23;
this.ctBrushAlpha1 = 24;
this.ctBrushAlpha2 = 25;
this.ctBrushTexturePath = 26;
this.ctBrushTextureAlpha = 27;
this.ctBrushTextureMode = 28;
this.ctBrushRectable = 29;
this.ctBrushRectableEnabled = 30;
this.ctBrushGradient = 31;
// font
this.ctFontXML = 40;
this.ctFontName = 41;
this.ctFontSize = 42;
this.ctFontStyle = 43;
this.ctFontPath = 44;
this.ctFontGID = 45;
this.ctFontCharSpace = 46;
// shadow
this.ctShadowXML = 50;
this.ctShadowVisible = 51;
this.ctShadowDistanceX = 52;
this.ctShadowDistanceY = 53;
this.ctShadowBlurSize = 54;
this.ctShadowColor = 55;
this.ctShadowAlpha = 56;
// edge
this.ctEdgeXML = 70;
this.ctEdgeVisible = 71;
this.ctEdgeDistance = 72;
this.ctEdgeColor = 73;
this.ctEdgeAlpha = 74;
// text
this.ctDrawText = 80;
this.ctDrawTextEx = 81;
this.ctDrawTextCode = 82;
this.ctDrawTextCodeGid = 83;
// pathcommands
this.ctPathCommandMoveTo = 91;
this.ctPathCommandLineTo = 92;
this.ctPathCommandLinesTo = 93;
this.ctPathCommandCurveTo = 94;
this.ctPathCommandCurvesTo = 95;
this.ctPathCommandArcTo = 96;
this.ctPathCommandClose = 97;
this.ctPathCommandEnd = 98;
this.ctDrawPath = 99;
this.ctPathCommandStart = 100;
this.ctPathCommandGetCurrentPoint = 101;
this.ctPathCommandText = 102;
this.ctPathCommandTextEx = 103;
// image
this.ctDrawImage = 110;
this.ctDrawImageFromFile = 111;
this.ctSetParams = 120;
this.ctBeginCommand = 121;
this.ctEndCommand = 122;
this.ctSetTransform = 130;
this.ctResetTransform = 131;
this.ctClipMode = 140;
this.ctCommandLong1 = 150;
this.ctCommandDouble1 = 151;
this.ctCommandString1 = 152;
this.ctCommandLong2 = 153;
this.ctCommandDouble2 = 154;
this.ctCommandString2 = 155;
this.ctHyperlink = 160;
this.ctLink = 161;
this.ctFormField = 162;
this.ctPageWidth = 200;
this.ctPageHeight = 201;
this.ctPageStart = 202;
this.ctPageEnd = 203;
this.ctError = 255;
}
var CommandType = new CCommandsType();
var MetaBrushType = {
Solid : 0,
Gradient : 1,
Texture : 2
};
// 0 - dash
// 1 - dashDot
// 2 - dot
// 3 - lgDash
// 4 - lgDashDot
// 5 - lgDashDotDot
// 6 - solid
// 7 - sysDash
// 8 - sysDashDot
// 9 - sysDashDotDot
// 10- sysDot
var DashPatternPresets = [
[4, 3],
[4, 3, 1, 3],
[1, 3],
[8, 3],
[8, 3, 1, 3],
[8, 3, 1, 3, 1, 3],
undefined,
[3, 1],
[3, 1, 1, 1],
[3, 1, 1, 1, 1, 1],
[1, 1]
];
function CMetafileFontPicker(manager)
{
this.Manager = manager; // в идеале - кэш измерятеля. тогда ни один шрифт не будет загружен заново
if (!this.Manager)
{
this.Manager = new AscFonts.CFontManager();
this.Manager.Initialize(false)
}
this.FontsInCache = {};
this.LastPickFont = null;
this.LastPickFontNameOrigin = "";
this.LastPickFontName = "";
this.Metafile = null; // класс, которому будет подменяться шрифт
this.SetFont = function(setFont)
{
var name = setFont.FontFamily.Name;
var size = setFont.FontSize;
var style = 0;
if (setFont.Italic == true)
style += 2;
if (setFont.Bold == true)
style += 1;
var name_check = name + "_" + style;
if (this.FontsInCache[name_check])
{
this.LastPickFont = this.FontsInCache[name_check];
}
else
{
var font = g_fontApplication.GetFontFileWeb(name, style);
var font_name_index = AscFonts.g_map_font_index[font.m_wsFontName];
var fontId = AscFonts.g_font_infos[font_name_index].GetFontID(AscCommon.g_font_loader, style);
var test_id = fontId.id + fontId.faceIndex + size;
var cache = this.Manager.m_oFontsCache;
this.LastPickFont = cache.Fonts[test_id];
if (!this.LastPickFont)
this.LastPickFont = cache.Fonts[test_id + "nbold"];
if (!this.LastPickFont)
this.LastPickFont = cache.Fonts[test_id + "nitalic"];
if (!this.LastPickFont)
this.LastPickFont = cache.Fonts[test_id + "nboldnitalic"];
if (!this.LastPickFont)
{
// такого при правильном кэше быть не должно
if (window["NATIVE_EDITOR_ENJINE"] && fontId.file.Status != 0)
{
fontId.file.LoadFontNative();
}
this.LastPickFont = cache.LockFont(fontId.file.stream_index, fontId.id, fontId.faceIndex, size, "", this.Manager);
}
this.FontsInCache[name_check] = this.LastPickFont;
}
this.LastPickFontNameOrigin = name;
this.LastPickFontName = name;
this.Metafile.SetFont(setFont, true);
};
this.FillTextCode = function(glyph)
{
if (this.LastPickFont && this.LastPickFont.GetGIDByUnicode(glyph))
{
if (this.LastPickFontName != this.LastPickFontNameOrigin)
{
this.LastPickFontName = this.LastPickFontNameOrigin;
this.Metafile.SetFontName(this.LastPickFontName);
}
}
else
{
var name = AscFonts.FontPickerByCharacter.getFontBySymbol(glyph);
if (name != this.LastPickFontName)
{
this.LastPickFontName = name;
this.Metafile.SetFontName(this.LastPickFontName);
}
}
};
}
function CMetafile(width, height)
{
this.Width = width;
this.Height = height;
this.m_oPen = new CPen();
this.m_oBrush = new CBrush();
this.m_oFont =
{
Name : "",
FontSize : -1,
Style : -1
};
// чтобы выставилось в первый раз
this.m_oPen.Color.R = -1;
this.m_oBrush.Color1.R = -1;
this.m_oBrush.Color2.R = -1;
this.m_oTransform = new CMatrix();
this.m_arrayCommands = [];
this.Memory = null;
this.VectorMemoryForPrint = null;
this.BrushType = MetaBrushType.Solid;
// RFonts
this.m_oTextPr = null;
this.m_oGrFonts = new CGrRFonts();
// просто чтобы не создавать каждый раз
this.m_oFontSlotFont = new CFontSetup();
this.LastFontOriginInfo = {Name : "", Replace : null};
this.m_oFontTmp = { FontFamily : { Name : "arial" }, Bold : false, Italic : false };
this.StartOffset = 0;
this.m_bIsPenDash = false;
this.FontPicker = null;
}
CMetafile.prototype =
{
// pen methods
p_color : function(r, g, b, a)
{
if (this.m_oPen.Color.R != r || this.m_oPen.Color.G != g || this.m_oPen.Color.B != b)
{
this.m_oPen.Color.R = r;
this.m_oPen.Color.G = g;
this.m_oPen.Color.B = b;
var value = b << 16 | g << 8 | r;
this.Memory.WriteByte(CommandType.ctPenColor);
this.Memory.WriteLong(value);
}
if (this.m_oPen.Color.A != a)
{
this.m_oPen.Color.A = a;
this.Memory.WriteByte(CommandType.ctPenAlpha);
this.Memory.WriteByte(a);
}
},
p_width : function(w)
{
var val = w / 1000;
if (this.m_oPen.Size != val)
{
this.m_oPen.Size = val;
this.Memory.WriteByte(CommandType.ctPenSize);
this.Memory.WriteDouble(val);
}
},
p_dash : function(params)
{
var bIsDash = (params && (params.length > 0)) ? true : false;
if (false == this.m_bIsPenDash && bIsDash == this.m_bIsPenDash)
return;
this.m_bIsPenDash = bIsDash;
if (!this.m_bIsPenDash)
{
this.Memory.WriteByte(CommandType.ctPenDashStyle);
this.Memory.WriteByte(0);
}
else
{
this.Memory.WriteByte(CommandType.ctPenDashStyle);
this.Memory.WriteByte(5);
this.Memory.WriteLong(params.length);
for (var i = 0; i < params.length; i++)
{
this.Memory.WriteDouble(params[i]);
}
}
},
// brush methods
b_color1 : function(r, g, b, a)
{
if (this.BrushType != MetaBrushType.Solid)
{
this.Memory.WriteByte(CommandType.ctBrushType);
this.Memory.WriteLong(1000);
this.BrushType = MetaBrushType.Solid;
}
if (this.m_oBrush.Color1.R != r || this.m_oBrush.Color1.G != g || this.m_oBrush.Color1.B != b)
{
this.m_oBrush.Color1.R = r;
this.m_oBrush.Color1.G = g;
this.m_oBrush.Color1.B = b;
var value = b << 16 | g << 8 | r;
this.Memory.WriteByte(CommandType.ctBrushColor1);
this.Memory.WriteLong(value);
}
if (this.m_oBrush.Color1.A != a)
{
this.m_oBrush.Color1.A = a;
this.Memory.WriteByte(CommandType.ctBrushAlpha1);
this.Memory.WriteByte(a);
}
},
b_color2 : function(r, g, b, a)
{
if (this.m_oBrush.Color2.R != r || this.m_oBrush.Color2.G != g || this.m_oBrush.Color2.B != b)
{
this.m_oBrush.Color2.R = r;
this.m_oBrush.Color2.G = g;
this.m_oBrush.Color2.B = b;
var value = b << 16 | g << 8 | r;
this.Memory.WriteByte(CommandType.ctBrushColor2);
this.Memory.WriteLong(value);
}
if (this.m_oBrush.Color2.A != a)
{
this.m_oBrush.Color2.A = a;
this.Memory.WriteByte(CommandType.ctBrushAlpha2);
this.Memory.WriteByte(a);
}
},
put_brushTexture : function(src, mode)
{
var isLocalUse = true;
if (window["AscDesktopEditor"] && window["AscDesktopEditor"]["IsLocalFile"] && window["AscDesktopEditor"]["IsFilePrinting"])
isLocalUse = ((!window["AscDesktopEditor"]["IsLocalFile"]()) && window["AscDesktopEditor"]["IsFilePrinting"]()) ? false : true;
if (window["AscDesktopEditor"] && !isLocalUse)
{
if ((undefined !== window["AscDesktopEditor"]["CryptoMode"]) && (0 < window["AscDesktopEditor"]["CryptoMode"]))
isLocalUse = true;
}
if (this.BrushType != MetaBrushType.Texture)
{
this.Memory.WriteByte(CommandType.ctBrushType);
this.Memory.WriteLong(3008);
this.BrushType = MetaBrushType.Texture;
}
this.m_oBrush.Color1.R = -1;
this.m_oBrush.Color1.G = -1;
this.m_oBrush.Color1.B = -1;
this.m_oBrush.Color1.A = -1;
this.Memory.WriteByte(CommandType.ctBrushTexturePath);
var _src = src;
var srcLocal = AscCommon.g_oDocumentUrls.getLocal(_src);
if (srcLocal && isLocalUse)
{
_src = srcLocal;
}
this.Memory.WriteString(_src);
this.Memory.WriteByte(CommandType.ctBrushTextureMode);
this.Memory.WriteByte(mode);
},
put_BrushTextureAlpha : function(alpha)
{
var write = alpha;
if (null == alpha || undefined == alpha)
write = 255;
this.Memory.WriteByte(CommandType.ctBrushTextureAlpha);
this.Memory.WriteByte(write);
},
put_BrushGradient : function(gradFill, points, transparent)
{
this.BrushType = MetaBrushType.Gradient;
this.Memory.WriteByte(CommandType.ctBrushGradient);
this.Memory.WriteByte(AscCommon.g_nodeAttributeStart);
if (gradFill.path != null && (gradFill.lin == null || gradFill.lin == undefined))
{
this.Memory.WriteByte(1);
this.Memory.WriteByte(gradFill.path);
this.Memory.WriteDouble(points.x0);
this.Memory.WriteDouble(points.y0);
this.Memory.WriteDouble(points.x1);
this.Memory.WriteDouble(points.y1);
this.Memory.WriteDouble(points.r0);
this.Memory.WriteDouble(points.r1);
}
else
{
this.Memory.WriteByte(0);
if (null == gradFill.lin)
{
this.Memory.WriteLong(90 * 60000);
this.Memory.WriteBool(false);
}
else
{
this.Memory.WriteLong(gradFill.lin.angle);
this.Memory.WriteBool(gradFill.lin.scale);
}
this.Memory.WriteDouble(points.x0);
this.Memory.WriteDouble(points.y0);
this.Memory.WriteDouble(points.x1);
this.Memory.WriteDouble(points.y1);
}
var _colors = gradFill.colors;
var firstColor = null;
var lastColor = null;
if (_colors.length > 0)
{
if (_colors[0].pos > 0)
{
firstColor = {
color : {
RGBA : {
R : _colors[0].color.RGBA.R,
G : _colors[0].color.RGBA.G,
B : _colors[0].color.RGBA.B,
A : _colors[0].color.RGBA.A
}
},
pos : 0
};
_colors.unshift(firstColor);
}
var posLast = _colors.length - 1;
if (_colors[posLast].pos < 100000)
{
lastColor = {
color : {
RGBA : {
R : _colors[posLast].color.RGBA.R,
G : _colors[posLast].color.RGBA.G,
B : _colors[posLast].color.RGBA.B,
A : _colors[posLast].color.RGBA.A
}
},
pos : 100000
};
_colors.push(lastColor);
}
}
this.Memory.WriteByte(2);
this.Memory.WriteLong(_colors.length);
for (var i = 0; i < _colors.length; i++)
{
this.Memory.WriteLong(_colors[i].pos);
this.Memory.WriteByte(_colors[i].color.RGBA.R);
this.Memory.WriteByte(_colors[i].color.RGBA.G);
this.Memory.WriteByte(_colors[i].color.RGBA.B);
if (null == transparent)
this.Memory.WriteByte(_colors[i].color.RGBA.A);
else
this.Memory.WriteByte(transparent);
}
if (firstColor)
_colors.shift();
if (lastColor)
_colors.pop();
this.Memory.WriteByte(AscCommon.g_nodeAttributeEnd);
},
transform : function(sx, shy, shx, sy, tx, ty)
{
if (this.m_oTransform.sx != sx || this.m_oTransform.shx != shx || this.m_oTransform.shy != shy ||
this.m_oTransform.sy != sy || this.m_oTransform.tx != tx || this.m_oTransform.ty != ty)
{
this.m_oTransform.sx = sx;
this.m_oTransform.shx = shx;
this.m_oTransform.shy = shy;
this.m_oTransform.sy = sy;
this.m_oTransform.tx = tx;
this.m_oTransform.ty = ty;
this.Memory.WriteByte(CommandType.ctSetTransform);
this.Memory.WriteDouble(sx);
this.Memory.WriteDouble(shy);
this.Memory.WriteDouble(shx);
this.Memory.WriteDouble(sy);
this.Memory.WriteDouble(tx);
this.Memory.WriteDouble(ty);
}
},
// path commands
_s : function()
{
if (this.VectorMemoryForPrint != null)
this.VectorMemoryForPrint.ClearNoAttack();
var _memory = (null == this.VectorMemoryForPrint) ? this.Memory : this.VectorMemoryForPrint;
_memory.WriteByte(CommandType.ctPathCommandStart);
},
_e : function()
{
// тут всегда напрямую в Memory
this.Memory.WriteByte(CommandType.ctPathCommandEnd);
},
_z : function()
{
var _memory = (null == this.VectorMemoryForPrint) ? this.Memory : this.VectorMemoryForPrint;
_memory.WriteByte(CommandType.ctPathCommandClose);
},
_m : function(x, y)
{
var _memory = (null == this.VectorMemoryForPrint) ? this.Memory : this.VectorMemoryForPrint;
_memory.WriteByte(CommandType.ctPathCommandMoveTo);
_memory.WriteDouble(x);
_memory.WriteDouble(y);
},
_l : function(x, y)
{
var _memory = (null == this.VectorMemoryForPrint) ? this.Memory : this.VectorMemoryForPrint;
_memory.WriteByte(CommandType.ctPathCommandLineTo);
_memory.WriteDouble(x);
_memory.WriteDouble(y);
},
_c : function(x1, y1, x2, y2, x3, y3)
{
var _memory = (null == this.VectorMemoryForPrint) ? this.Memory : this.VectorMemoryForPrint;
_memory.WriteByte(CommandType.ctPathCommandCurveTo);
_memory.WriteDouble(x1);
_memory.WriteDouble(y1);
_memory.WriteDouble(x2);
_memory.WriteDouble(y2);
_memory.WriteDouble(x3);
_memory.WriteDouble(y3);
},
_c2 : function(x1, y1, x2, y2)
{
var _memory = (null == this.VectorMemoryForPrint) ? this.Memory : this.VectorMemoryForPrint;
_memory.WriteByte(CommandType.ctPathCommandCurveTo);
_memory.WriteDouble(x1);
_memory.WriteDouble(y1);
_memory.WriteDouble(x1);
_memory.WriteDouble(y1);
_memory.WriteDouble(x2);
_memory.WriteDouble(y2);
},
ds : function()
{
if (null == this.VectorMemoryForPrint)
{
this.Memory.WriteByte(CommandType.ctDrawPath);
this.Memory.WriteLong(1);
}
else
{
this.Memory.Copy(this.VectorMemoryForPrint, 0, this.VectorMemoryForPrint.pos);
this.Memory.WriteByte(CommandType.ctDrawPath);
this.Memory.WriteLong(1);
}
},
df : function()
{
if (null == this.VectorMemoryForPrint)
{
this.Memory.WriteByte(CommandType.ctDrawPath);
this.Memory.WriteLong(256);
}
else
{
this.Memory.Copy(this.VectorMemoryForPrint, 0, this.VectorMemoryForPrint.pos);
this.Memory.WriteByte(CommandType.ctDrawPath);
this.Memory.WriteLong(256);
}
},
WriteVectorMemoryForPrint : function()
{
if (null != this.VectorMemoryForPrint)
{
this.Memory.Copy(this.VectorMemoryForPrint, 0, this.VectorMemoryForPrint.pos);
}
},
drawpath : function(type)
{
if (null == this.VectorMemoryForPrint)
{
this.Memory.WriteByte(CommandType.ctDrawPath);
this.Memory.WriteLong(type);
}
else
{
this.Memory.Copy(this.VectorMemoryForPrint, 0, this.VectorMemoryForPrint.pos);
this.Memory.WriteByte(CommandType.ctDrawPath);
this.Memory.WriteLong(type);
}
},
// canvas state
save : function()
{
},
restore : function()
{
},
clip : function()
{
},
// images
drawImage : function(img, x, y, w, h, isUseOriginUrl)
{
var isLocalUse = true;
if (window["AscDesktopEditor"] && window["AscDesktopEditor"]["IsLocalFile"] && window["AscDesktopEditor"]["IsFilePrinting"])
isLocalUse = ((!window["AscDesktopEditor"]["IsLocalFile"]()) && window["AscDesktopEditor"]["IsFilePrinting"]()) ? false : true;
if (window["AscDesktopEditor"] && !isLocalUse)
{
if ((undefined !== window["AscDesktopEditor"]["CryptoMode"]) && (0 < window["AscDesktopEditor"]["CryptoMode"]))
isLocalUse = true;
}
if (!window.editor)
{
// excel
this.Memory.WriteByte(CommandType.ctDrawImageFromFile);
var imgLocal = AscCommon.g_oDocumentUrls.getLocal(img);
if (imgLocal && isLocalUse && (true !== isUseOriginUrl))
{
this.Memory.WriteString2(imgLocal);
}
else
{
this.Memory.WriteString2(img);
}
this.Memory.WriteDouble(x);
this.Memory.WriteDouble(y);
this.Memory.WriteDouble(w);
this.Memory.WriteDouble(h);
return;
}
var _src = "";
if (!window["NATIVE_EDITOR_ENJINE"] && (true !== isUseOriginUrl))
{
var _img = window.editor.ImageLoader.map_image_index[img];
if (_img == undefined || _img.Image == null)
return;
_src = _img.src;
}
else
{
_src = img;
}
var srcLocal = AscCommon.g_oDocumentUrls.getLocal(_src);
if (srcLocal && isLocalUse)
{
_src = srcLocal;
}
this.Memory.WriteByte(CommandType.ctDrawImageFromFile);
this.Memory.WriteString2(_src);
this.Memory.WriteDouble(x);
this.Memory.WriteDouble(y);
this.Memory.WriteDouble(w);
this.Memory.WriteDouble(h);
},
SetFontName : function(name)
{
var fontinfo = g_fontApplication.GetFontInfo(name, 0, this.LastFontOriginInfo);
if (this.m_oFont.Name != fontinfo.Name)
{
this.m_oFont.Name = fontinfo.Name;
this.Memory.WriteByte(CommandType.ctFontName);
this.Memory.WriteString(this.m_oFont.Name);
}
},
SetFont : function(font, isFromPicker)
{
if (this.FontPicker && !isFromPicker)
return this.FontPicker.SetFont(font);
if (null == font)
return;
var style = 0;
if (font.Italic == true)
style += 2;
if (font.Bold == true)
style += 1;
var fontinfo = g_fontApplication.GetFontInfo(font.FontFamily.Name, style, this.LastFontOriginInfo);
//style = fontinfo.GetBaseStyle(style);
if (this.m_oFont.Name != fontinfo.Name)
{
this.m_oFont.Name = fontinfo.Name;
this.Memory.WriteByte(CommandType.ctFontName);
this.Memory.WriteString(this.m_oFont.Name);
}
if (this.m_oFont.FontSize != font.FontSize)
{
this.m_oFont.FontSize = font.FontSize;
this.Memory.WriteByte(CommandType.ctFontSize);
this.Memory.WriteDouble(this.m_oFont.FontSize);
}
if (this.m_oFont.Style != style)
{
this.m_oFont.Style = style;
this.Memory.WriteByte(CommandType.ctFontStyle);
this.Memory.WriteLong(style);
}
},
FillText : function(x, y, text)
{
if (1 == text.length)
return this.FillTextCode(x, y, text.charCodeAt(0));
this.Memory.WriteByte(CommandType.ctDrawText);
this.Memory.WriteString(text);
this.Memory.WriteDouble(x);
this.Memory.WriteDouble(y);
},
FillTextCode : function(x, y, code)
{
var _code = code;
if (null != this.LastFontOriginInfo.Replace)
_code = g_fontApplication.GetReplaceGlyph(_code, this.LastFontOriginInfo.Replace);
if (this.FontPicker)
this.FontPicker.FillTextCode(_code);
this.Memory.WriteByte(CommandType.ctDrawText);
this.Memory.WriteStringBySymbol(_code);
this.Memory.WriteDouble(x);
this.Memory.WriteDouble(y);
},
tg : function(gid, x, y, codepoints)
{
/*
var _old_pos = this.Memory.pos;
g_fontApplication.LoadFont(this.m_oFont.Name, AscCommon.g_font_loader, AscCommon.g_oTextMeasurer.m_oManager, this.m_oFont.FontSize, Math.max(this.m_oFont.Style, 0), 72, 72);
AscCommon.g_oTextMeasurer.m_oManager.LoadStringPathCode(gid, true, x, y, this);
// start (1) + draw(1) + typedraw(4) + end(1) = 7!
if ((this.Memory.pos - _old_pos) < 8)
this.Memory.pos = _old_pos;
*/
this.Memory.WriteByte(CommandType.ctDrawTextCodeGid);
this.Memory.WriteLong(gid);
this.Memory.WriteDouble(x);
this.Memory.WriteDouble(y);
var count = codepoints ? codepoints.length : 0;
this.Memory.WriteLong(count);
for (var i = 0; i < count; i++)
this.Memory.WriteLong(codepoints[i]);
},
charspace : function(space)
{
},
beginCommand : function(command)
{
this.Memory.WriteByte(CommandType.ctBeginCommand);
this.Memory.WriteLong(command);
},
endCommand : function(command)
{
if (32 == command)
{
if (null == this.VectorMemoryForPrint)
{
this.Memory.WriteByte(CommandType.ctEndCommand);
this.Memory.WriteLong(command);
}
else
{
this.Memory.Copy(this.VectorMemoryForPrint, 0, this.VectorMemoryForPrint.pos);
this.Memory.WriteByte(CommandType.ctEndCommand);
this.Memory.WriteLong(command);
}
return;
}
this.Memory.WriteByte(CommandType.ctEndCommand);
this.Memory.WriteLong(command);
},
put_PenLineJoin : function(_join)
{
this.Memory.WriteByte(CommandType.ctPenLineJoin);
this.Memory.WriteByte(_join & 0xFF);
},
put_TextureBounds : function(x, y, w, h)
{
this.Memory.WriteByte(CommandType.ctBrushRectable);
this.Memory.WriteDouble(x);
this.Memory.WriteDouble(y);
this.Memory.WriteDouble(w);
this.Memory.WriteDouble(h);
},
put_TextureBoundsEnabled : function(bIsEnabled)
{
this.Memory.WriteByte(CommandType.ctBrushRectableEnabled);
this.Memory.WriteBool(bIsEnabled);
},
SetFontInternal : function(name, size, style)
{
// TODO: remove m_oFontSlotFont
var _lastFont = this.m_oFontSlotFont;
_lastFont.Name = name;
_lastFont.Size = size;
_lastFont.Bold = (style & AscFonts.FontStyle.FontStyleBold) ? true : false;
_lastFont.Italic = (style & AscFonts.FontStyle.FontStyleItalic) ? true : false;
this.m_oFontTmp.FontFamily.Name = _lastFont.Name;
this.m_oFontTmp.Bold = _lastFont.Bold;
this.m_oFontTmp.Italic = _lastFont.Italic;
this.m_oFontTmp.FontSize = _lastFont.Size;
this.SetFont(this.m_oFontTmp);
},
SetFontSlot : function(slot, fontSizeKoef)
{
var _rfonts = this.m_oGrFonts;
var _lastFont = this.m_oFontSlotFont;
switch (slot)
{
case fontslot_ASCII:
{
_lastFont.Name = _rfonts.Ascii.Name;
_lastFont.Size = this.m_oTextPr.FontSize;
_lastFont.Bold = this.m_oTextPr.Bold;
_lastFont.Italic = this.m_oTextPr.Italic;
break;
}
case fontslot_CS:
{
_lastFont.Name = _rfonts.CS.Name;
_lastFont.Size = this.m_oTextPr.FontSizeCS;
_lastFont.Bold = this.m_oTextPr.BoldCS;
_lastFont.Italic = this.m_oTextPr.ItalicCS;
break;
}
case fontslot_EastAsia:
{
_lastFont.Name = _rfonts.EastAsia.Name;
_lastFont.Size = this.m_oTextPr.FontSize;
_lastFont.Bold = this.m_oTextPr.Bold;
_lastFont.Italic = this.m_oTextPr.Italic;
break;
}
case fontslot_HAnsi:
default:
{
_lastFont.Name = _rfonts.HAnsi.Name;
_lastFont.Size = this.m_oTextPr.FontSize;
_lastFont.Bold = this.m_oTextPr.Bold;
_lastFont.Italic = this.m_oTextPr.Italic;
break;
}
}
if (undefined !== fontSizeKoef)
_lastFont.Size *= fontSizeKoef;
this.m_oFontTmp.FontFamily.Name = _lastFont.Name;
this.m_oFontTmp.Bold = _lastFont.Bold;
this.m_oFontTmp.Italic = _lastFont.Italic;
this.m_oFontTmp.FontSize = _lastFont.Size;
this.SetFont(this.m_oFontTmp);
},
AddHyperlink : function(x, y, w, h, url, tooltip)
{
this.Memory.WriteByte(CommandType.ctHyperlink);
this.Memory.WriteDouble(x);
this.Memory.WriteDouble(y);
this.Memory.WriteDouble(w);
this.Memory.WriteDouble(h);
this.Memory.WriteString(url);
this.Memory.WriteString(tooltip);
},
AddLink : function(x, y, w, h, dx, dy, dPage)
{
this.Memory.WriteByte(CommandType.ctLink);
this.Memory.WriteDouble(x);
this.Memory.WriteDouble(y);
this.Memory.WriteDouble(w);
this.Memory.WriteDouble(h);
this.Memory.WriteDouble(dx);
this.Memory.WriteDouble(dy);
this.Memory.WriteLong(dPage);
},
AddFormField : function(nX, nY, nW, nH, nBaseLineOffset, oForm)
{
if (!oForm)
return;
this.Memory.WriteByte(CommandType.ctFormField);
var nStartPos = this.Memory.GetCurPosition();
this.Memory.Skip(4);
this.Memory.WriteDouble(nX);
this.Memory.WriteDouble(nY);
this.Memory.WriteDouble(nW);
this.Memory.WriteDouble(nH);
this.Memory.WriteDouble(nBaseLineOffset);
var nFlagPos = this.Memory.GetCurPosition();
this.Memory.Skip(4);
var nFlag = 0;
var oFormPr = oForm.GetFormPr();
var sFormKey = oFormPr.GetKey();
if (sFormKey)
{
nFlag |= 1;
this.Memory.WriteString(sFormKey);
}
var sHelpText = oFormPr.GetHelpText();
if (sHelpText)
{
nFlag |= (1 << 1);
this.Memory.WriteString(sHelpText);
}
if (oFormPr.GetRequired())
nFlag |= (1 << 2);
if (oForm.IsPlaceHolder())
nFlag |= (1 << 3);
// 7-ой и 8-ой биты зарезервированы для бордера
var oBorder = oFormPr.GetBorder();
if (oBorder && !oBorder.IsNone())
{
nFlag |= (1 << 6);
var oColor = oBorder.GetColor();
this.Memory.WriteLong(1);
this.Memory.WriteDouble(oBorder.GetWidth());
this.Memory.WriteByte(oColor.r);
this.Memory.WriteByte(oColor.g);
this.Memory.WriteByte(oColor.b);
this.Memory.WriteByte(0x255);
}
var oParagraph = oForm.GetParagraph();
var oShd = oFormPr.GetShd();
if (oParagraph && oShd && !oShd.IsNil())
{
nFlag |= (1 << 9);
var oColor = oShd.GetSimpleColor(oParagraph.GetTheme(), oParagraph.GetColorMap());
this.Memory.WriteByte(oColor.r);
this.Memory.WriteByte(oColor.g);
this.Memory.WriteByte(oColor.b);
this.Memory.WriteByte(0x255);
}
if (oParagraph && AscCommon.align_Left !== oParagraph.GetParagraphAlign())
{
nFlag |= (1 << 10);
this.Memory.WriteByte(oParagraph.GetParagraphAlign());
}
// 0 - Unknown
// 1 - Text
// 2 - ComboBox/DropDownList
// 3 - CheckBox/RadioButton
// 4 - Picture
if (oForm.IsTextForm())
{
this.Memory.WriteLong(1);
var oTextFormPr = oForm.GetTextFormPr();
if (oTextFormPr.Comb)
nFlag |= (1 << 20);
if (oTextFormPr.MaxCharacters > 0)
{
nFlag |= (1 << 21);
this.Memory.WriteLong(oTextFormPr.MaxCharacters);
}
var sValue = oForm.GetSelectedText(true);
if (sValue)
{
nFlag |= (1 << 22);
this.Memory.WriteString(sValue);
}
if (oTextFormPr.MultiLine && oForm.IsFixedForm())
nFlag |= (1 << 23);
if (oTextFormPr.AutoFit)
nFlag |= (1 << 24);
var sPlaceHolderText = oForm.GetPlaceholderText();
if (sPlaceHolderText)
{
nFlag |= (1 << 25);
this.Memory.WriteString(sPlaceHolderText);
}
}
else if (oForm.IsComboBox() || oForm.IsDropDownList())
{
this.Memory.WriteLong(2);
var isComboBox = oForm.IsComboBox();
var oFormPr = isComboBox ? oForm.GetComboBoxPr() : oForm.GetDropDownListPr();
if (isComboBox)
nFlag |= (1 << 20);
var sValue = oForm.GetSelectedText(true);
var nSelectedIndex = -1;
// Обработка "Choose an item"
var nItemsCount = oFormPr.GetItemsCount();
if (nItemsCount > 0 && AscCommon.translateManager.getValue("Choose an item") === oFormPr.GetItemDisplayText(0))
{
this.Memory.WriteLong(nItemsCount - 1);
for (var nIndex = 1; nIndex < nItemsCount; ++nIndex)
{
var sItemValue = oFormPr.GetItemDisplayText(nIndex);
if (sItemValue === sValue)
nSelectedIndex = nIndex;
this.Memory.WriteString(sItemValue);
}
}
else
{
this.Memory.WriteLong(nItemsCount);
for (var nIndex = 0; nIndex < nItemsCount; ++nIndex)
{
var sItemValue = oFormPr.GetItemDisplayText(nIndex);
if (sItemValue === sValue)
nSelectedIndex = nIndex;
this.Memory.WriteString(sItemValue);
}
}
this.Memory.WriteLong(nSelectedIndex);
if (sValue)
{
nFlag |= (1 << 22);
this.Memory.WriteString(sValue);
}
var sPlaceHolderText = oForm.GetPlaceholderText();
if (sPlaceHolderText)
{
nFlag |= (1 << 23);
this.Memory.WriteString(sPlaceHolderText);
}
}
else if (oForm.IsCheckBox())
{
this.Memory.WriteLong(3);
var oCheckBoxPr = oForm.GetCheckBoxPr();
if (oCheckBoxPr.GetChecked())
nFlag |= (1 << 20);
var nCheckedSymbol = oCheckBoxPr.GetCheckedSymbol();
var nUncheckedSymbol = oCheckBoxPr.GetUncheckedSymbol();
var nType = 0x0000;
if (0x2611 === nCheckedSymbol && 0x2610 === nUncheckedSymbol)
nType = 0x0001;
else if (0x25C9 === nCheckedSymbol && 0x25CB === nUncheckedSymbol)
nType = 0x0002;
var sCheckedFont = oCheckBoxPr.GetCheckedFont();
if (AscCommon.IsAscFontSupport(sCheckedFont, nCheckedSymbol))
sCheckedFont = "ASCW3";
var sUncheckedFont = oCheckBoxPr.GetUncheckedFont();
if (AscCommon.IsAscFontSupport(sUncheckedFont, nUncheckedSymbol))
sUncheckedFont = "ASCW3";
this.Memory.WriteLong(nType);
this.Memory.WriteLong(nCheckedSymbol);
this.Memory.WriteString(sCheckedFont);
this.Memory.WriteLong(nUncheckedSymbol);
this.Memory.WriteString(sUncheckedFont);
var sGroupName = oCheckBoxPr.GetGroupKey();
if (sGroupName)
{
nFlag |= (1 << 21);
this.Memory.WriteString(sGroupName);
}
}
else if (oForm.IsPicture())
{
this.Memory.WriteLong(4);
var oPicturePr = oForm.GetPictureFormPr();
if (oPicturePr.IsConstantProportions())
nFlag |= (1 << 20);
if (oPicturePr.IsRespectBorders())
nFlag |= (1 << 21);
nFlag |= ((oPicturePr.GetScaleFlag() & 0xF) << 24);
this.Memory.WriteLong(oPicturePr.GetShiftX() * 1000);
this.Memory.WriteLong(oPicturePr.GetShiftY() * 1000);
if (!oForm.IsPlaceHolder())
{
var arrDrawings = oForm.GetAllDrawingObjects();
if (arrDrawings.length > 0 && arrDrawings[0].IsPicture() && arrDrawings[0].GraphicObj.blipFill)
{
var isLocalUse = true;
if (window["AscDesktopEditor"] && window["AscDesktopEditor"]["IsLocalFile"] && window["AscDesktopEditor"]["IsFilePrinting"])
isLocalUse = ((!window["AscDesktopEditor"]["IsLocalFile"]()) && window["AscDesktopEditor"]["IsFilePrinting"]()) ? false : true;
if (window["AscDesktopEditor"] && !isLocalUse)
{
if ((undefined !== window["AscDesktopEditor"]["CryptoMode"]) && (0 < window["AscDesktopEditor"]["CryptoMode"]))
isLocalUse = true;
}
var src = AscCommon.getFullImageSrc2(arrDrawings[0].GraphicObj.blipFill.RasterImageId);
var srcLocal = AscCommon.g_oDocumentUrls.getLocal(src);
if (srcLocal && isLocalUse)
src = srcLocal;
nFlag |= (1 << 22);
this.Memory.WriteString(src);
}
}
}
else
{
this.Memory.WriteLong(0);
}
var nEndPos = this.Memory.GetCurPosition();
this.Memory.Seek(nFlagPos);
this.Memory.WriteLong(nFlag);
this.Memory.Seek(nStartPos);
this.Memory.WriteLong(nEndPos - nStartPos);
this.Memory.Seek(nEndPos);
}
};
function CDocumentRenderer()
{
this.m_arrayPages = [];
this.m_lPagesCount = 0;
//this.DocumentInfo = "";
this.Memory = new CMemory();
this.VectorMemoryForPrint = null;
this.ClipManager = new CClipManager();
this.ClipManager.BaseObject = this;
this.RENDERER_PDF_FLAG = true;
this.ArrayPoints = null;
this.GrState = new CGrState();
this.GrState.Parent = this;
this.m_oPen = null;
this.m_oBrush = null;
this.m_oTransform = null;
this._restoreDumpedVectors = null;
this.m_oBaseTransform = null;
this.UseOriginImageUrl = false;
this.FontPicker = null;
this.isPrintMode = false;
}
CDocumentRenderer.prototype =
{
InitPicker : function(_manager)
{
this.FontPicker = new CMetafileFontPicker(_manager);
},
SetBaseTransform : function(_matrix)
{
this.m_oBaseTransform = _matrix;
},
BeginPage : function(width, height)
{
this.m_arrayPages[this.m_arrayPages.length] = new CMetafile(width, height);
this.m_lPagesCount = this.m_arrayPages.length;
this.m_arrayPages[this.m_lPagesCount - 1].Memory = this.Memory;
this.m_arrayPages[this.m_lPagesCount - 1].StartOffset = this.Memory.pos;
this.m_arrayPages[this.m_lPagesCount - 1].VectorMemoryForPrint = this.VectorMemoryForPrint;
this.m_arrayPages[this.m_lPagesCount - 1].FontPicker = this.FontPicker;
if (this.FontPicker)
this.m_arrayPages[this.m_lPagesCount - 1].FontPicker.Metafile = this.m_arrayPages[this.m_lPagesCount - 1];
this.Memory.WriteByte(CommandType.ctPageStart);
this.Memory.WriteByte(CommandType.ctPageWidth);
this.Memory.WriteDouble(width);
this.Memory.WriteByte(CommandType.ctPageHeight);
this.Memory.WriteDouble(height);
var _page = this.m_arrayPages[this.m_lPagesCount - 1];
this.m_oPen = _page.m_oPen;
this.m_oBrush = _page.m_oBrush;
this.m_oTransform = _page.m_oTransform;
},
EndPage : function()
{
this.Memory.WriteByte(CommandType.ctPageEnd);
},
p_color : function(r, g, b, a)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].p_color(r, g, b, a);
},
p_width : function(w)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].p_width(w);
},
p_dash : function(params)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].p_dash(params);
},
// brush methods
b_color1 : function(r, g, b, a)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].b_color1(r, g, b, a);
},
b_color2 : function(r, g, b, a)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].b_color2(r, g, b, a);
},
transform : function(sx, shy, shx, sy, tx, ty)
{
if (0 != this.m_lPagesCount)
{
if (null == this.m_oBaseTransform)
this.m_arrayPages[this.m_lPagesCount - 1].transform(sx, shy, shx, sy, tx, ty);
else
{
var _transform = new CMatrix();
_transform.sx = sx;
_transform.shy = shy;
_transform.shx = shx;
_transform.sy = sy;
_transform.tx = tx;
_transform.ty = ty;
AscCommon.global_MatrixTransformer.MultiplyAppend(_transform, this.m_oBaseTransform);
this.m_arrayPages[this.m_lPagesCount - 1].transform(_transform.sx, _transform.shy, _transform.shx, _transform.sy, _transform.tx, _transform.ty);
}
}
},
transform3 : function(m)
{
this.transform(m.sx, m.shy, m.shx, m.sy, m.tx, m.ty);
},
reset : function()
{
this.transform(1, 0, 0, 1, 0, 0);
},
// path commands
_s : function()
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1]._s();
},
_e : function()
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1]._e();
},
_z : function()
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1]._z();
},
_m : function(x, y)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1]._m(x, y);
if (this.ArrayPoints != null)
this.ArrayPoints[this.ArrayPoints.length] = {x : x, y : y};
},
_l : function(x, y)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1]._l(x, y);
if (this.ArrayPoints != null)
this.ArrayPoints[this.ArrayPoints.length] = {x : x, y : y};
},
_c : function(x1, y1, x2, y2, x3, y3)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1]._c(x1, y1, x2, y2, x3, y3);
if (this.ArrayPoints != null)
{
this.ArrayPoints[this.ArrayPoints.length] = {x : x1, y : y1};
this.ArrayPoints[this.ArrayPoints.length] = {x : x2, y : y2};
this.ArrayPoints[this.ArrayPoints.length] = {x : x3, y : y3};
}
},
_c2 : function(x1, y1, x2, y2)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1]._c2(x1, y1, x2, y2);
if (this.ArrayPoints != null)
{
this.ArrayPoints[this.ArrayPoints.length] = {x : x1, y : y1};
this.ArrayPoints[this.ArrayPoints.length] = {x : x2, y : y2};
}
},
ds : function()
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].ds();
},
df : function()
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].df();
},
drawpath : function(type)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].drawpath(type);
},
// canvas state
save : function()
{
},
restore : function()
{
},
clip : function()
{
},
// images
drawImage : function(img, x, y, w, h, alpha, srcRect)
{
if (img == null || img == undefined || img == "")
return;
if (0 != this.m_lPagesCount)
{
if (!srcRect)
this.m_arrayPages[this.m_lPagesCount - 1].drawImage(img, x, y, w, h, this.UseOriginImageUrl);
else
{
/*
if (!window.editor)
{
this.m_arrayPages[this.m_lPagesCount - 1].drawImage(img,x,y,w,h);
return;
}
*/
/*
var _img = undefined;
if (window.editor)
_img = window.editor.ImageLoader.map_image_index[img];
else if (window["Asc"]["editor"])
_img = window["Asc"]["editor"].ImageLoader.map_image_index[img];
var w0 = 0;
var h0 = 0;
if (_img != undefined && _img.Image != null)
{
w0 = _img.Image.width;
h0 = _img.Image.height;
}
if (w0 == 0 || h0 == 0)
{
this.m_arrayPages[this.m_lPagesCount - 1].drawImage(img, x, y, w, h);
return;
}
*/
var bIsClip = false;
if (srcRect.l > 0 || srcRect.t > 0 || srcRect.r < 100 || srcRect.b < 100)
bIsClip = true;
if (bIsClip)
{
this.SaveGrState();
this.AddClipRect(x, y, w, h);
}
var __w = w;
var __h = h;
var _delW = Math.max(0, -srcRect.l) + Math.max(0, srcRect.r - 100) + 100;
var _delH = Math.max(0, -srcRect.t) + Math.max(0, srcRect.b - 100) + 100;
if (srcRect.l < 0)
{
var _off = ((-srcRect.l / _delW) * __w);
x += _off;
w -= _off;
}
if (srcRect.t < 0)
{
var _off = ((-srcRect.t / _delH) * __h);
y += _off;
h -= _off;
}
if (srcRect.r > 100)
{
var _off = ((srcRect.r - 100) / _delW) * __w;
w -= _off;
}
if (srcRect.b > 100)
{
var _off = ((srcRect.b - 100) / _delH) * __h;
h -= _off;
}
var _wk = 100;
if (srcRect.l > 0)
_wk -= srcRect.l;
if (srcRect.r < 100)
_wk -= (100 - srcRect.r);
_wk = 100 / _wk;
var _hk = 100;
if (srcRect.t > 0)
_hk -= srcRect.t;
if (srcRect.b < 100)
_hk -= (100 - srcRect.b);
_hk = 100 / _hk;
var _r = x + w;
var _b = y + h;
if (srcRect.l > 0)
{
x -= ((srcRect.l * _wk * w) / 100);
}
if (srcRect.t > 0)
{
y -= ((srcRect.t * _hk * h) / 100);
}
if (srcRect.r < 100)
{
_r += (((100 - srcRect.r) * _wk * w) / 100);
}
if (srcRect.b < 100)
{
_b += (((100 - srcRect.b) * _hk * h) / 100);
}
this.m_arrayPages[this.m_lPagesCount - 1].drawImage(img, x, y, _r - x, _b - y);
if (bIsClip)
{
this.RestoreGrState();
}
}
}
},
SetFont : function(font)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].SetFont(font);
},
FillText : function(x, y, text, cropX, cropW)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].FillText(x, y, text);
},
FillTextCode : function(x, y, text, cropX, cropW)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].FillTextCode(x, y, text);
},
tg : function(gid, x, y, codePoints)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].tg(gid, x, y, codePoints);
},
FillText2 : function(x, y, text)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].FillText(x, y, text);
},
charspace : function(space)
{
},
SetIntegerGrid : function(param)
{
},
GetIntegerGrid : function()
{
},
GetFont : function()
{
if (0 != this.m_lPagesCount)
return this.m_arrayPages[this.m_lPagesCount - 1].m_oFont;
return null;
},
put_GlobalAlpha : function(enable, alpha)
{
},
Start_GlobalAlpha : function()
{
},
End_GlobalAlpha : function()
{
},
DrawHeaderEdit : function(yPos)
{
},
DrawFooterEdit : function(yPos)
{
},
drawCollaborativeChanges : function(x, y, w, h)
{
},
drawSearchResult : function(x, y, w, h)
{
},
DrawEmptyTableLine : function(x1, y1, x2, y2)
{
// эта функция не для печати или сохранения вообще
},
DrawLockParagraph : function(lock_type, x, y1, y2)
{
// эта функция не для печати или сохранения вообще
},
DrawLockObjectRect : function(lock_type, x, y, w, h)
{
// эта функция не для печати или сохранения вообще
},
DrawSpellingLine : function(y0, x0, x1, w)
{
},
// smart methods for horizontal / vertical lines
drawHorLine : function(align, y, x, r, penW)
{
this.p_width(1000 * penW);
this._s();
var _y = y;
switch (align)
{
case 0:
{
_y = y + penW / 2;
break;
}
case 1:
{
break;
}
case 2:
{
_y = y - penW / 2;
}
}
this._m(x, y);
this._l(r, y);
this.ds();
this._e();
},
drawHorLine2 : function(align, y, x, r, penW)
{
this.p_width(1000 * penW);
var _y = y;
switch (align)
{
case 0:
{
_y = y + penW / 2;
break;
}
case 1:
{
break;
}
case 2:
{
_y = y - penW / 2;
break;
}
}
this._s();
this._m(x, (_y - penW));
this._l(r, (_y - penW));
this.ds();
this._s();
this._m(x, (_y + penW));
this._l(r, (_y + penW));
this.ds();
this._e();
},
drawVerLine : function(align, x, y, b, penW)
{
this.p_width(1000 * penW);
this._s();
var _x = x;
switch (align)
{
case 0:
{
_x = x + penW / 2;
break;
}
case 1:
{
break;
}
case 2:
{
_x = x - penW / 2;
}
}
this._m(_x, y);
this._l(_x, b);
this.ds();
},
// мега крутые функции для таблиц
drawHorLineExt : function(align, y, x, r, penW, leftMW, rightMW)
{
this.drawHorLine(align, y, x + leftMW, r + rightMW, penW);
},
rect : function(x, y, w, h)
{
var _x = x;
var _y = y;
var _r = (x + w);
var _b = (y + h);
this._s();
this._m(_x, _y);
this._l(_r, _y);
this._l(_r, _b);
this._l(_x, _b);
this._l(_x, _y);
},
TableRect : function(x, y, w, h)
{
this.rect(x, y, w, h);
this.df();
},
put_PenLineJoin : function(_join)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].put_PenLineJoin(_join);
},
put_TextureBounds : function(x, y, w, h)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].put_TextureBounds(x, y, w, h);
},
put_TextureBoundsEnabled : function(val)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].put_TextureBoundsEnabled(val);
},
put_brushTexture : function(src, mode)
{
if (src == null || src == undefined)
src = "";
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].put_brushTexture(src, mode);
},
put_BrushTextureAlpha : function(alpha)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].put_BrushTextureAlpha(alpha);
},
put_BrushGradient : function(gradFill, points, transparent)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].put_BrushGradient(gradFill, points, transparent);
},
// функции клиппирования
AddClipRect : function(x, y, w, h)
{
/*
this.b_color1(0, 0, 0, 255);
this.rect(x, y, w, h);
this.df();
return;
*/
var __rect = new _rect();
__rect.x = x;
__rect.y = y;
__rect.w = w;
__rect.h = h;
this.GrState.AddClipRect(__rect);
//this.ClipManager.AddRect(x, y, w, h);
},
RemoveClipRect : function()
{
//this.ClipManager.RemoveRect();
},
SetClip : function(r)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].beginCommand(32);
this.rect(r.x, r.y, r.w, r.h);
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].endCommand(32);
//this._s();
},
RemoveClip : function()
{
if (0 != this.m_lPagesCount)
{
this.m_arrayPages[this.m_lPagesCount - 1].beginCommand(64);
this.m_arrayPages[this.m_lPagesCount - 1].endCommand(64);
}
},
GetTransform : function()
{
if (0 != this.m_lPagesCount)
{
return this.m_arrayPages[this.m_lPagesCount - 1].m_oTransform;
}
return null;
},
GetLineWidth : function()
{
if (0 != this.m_lPagesCount)
{
return this.m_arrayPages[this.m_lPagesCount - 1].m_oPen.Size;
}
return 0;
},
GetPen : function()
{
if (0 != this.m_lPagesCount)
{
return this.m_arrayPages[this.m_lPagesCount - 1].m_oPen;
}
return 0;
},
GetBrush : function()
{
if (0 != this.m_lPagesCount)
{
return this.m_arrayPages[this.m_lPagesCount - 1].m_oBrush;
}
return 0;
},
drawFlowAnchor : function(x, y)
{
},
SavePen : function()
{
this.GrState.SavePen();
},
RestorePen : function()
{
this.GrState.RestorePen();
},
SaveBrush : function()
{
this.GrState.SaveBrush();
},
RestoreBrush : function()
{
this.GrState.RestoreBrush();
},
SavePenBrush : function()
{
this.GrState.SavePenBrush();
},
RestorePenBrush : function()
{
this.GrState.RestorePenBrush();
},
SaveGrState : function()
{
this.GrState.SaveGrState();
},
RestoreGrState : function()
{
var _t = this.m_oBaseTransform;
this.m_oBaseTransform = null;
this.GrState.RestoreGrState();
this.m_oBaseTransform = _t;
},
RemoveLastClip : function()
{
var _t = this.m_oBaseTransform;
this.m_oBaseTransform = null;
this.GrState.RemoveLastClip();
this.m_oBaseTransform = _t;
},
RestoreLastClip : function()
{
var _t = this.m_oBaseTransform;
this.m_oBaseTransform = null;
this.GrState.RestoreLastClip();
this.m_oBaseTransform = _t;
},
StartClipPath : function()
{
this.private_removeVectors();
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].beginCommand(32);
},
EndClipPath : function()
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].endCommand(32);
this.private_restoreVectors();
},
SetTextPr : function(textPr, theme)
{
if (0 != this.m_lPagesCount)
{
var _page = this.m_arrayPages[this.m_lPagesCount - 1];
if (theme && textPr && textPr.ReplaceThemeFonts)
textPr.ReplaceThemeFonts(theme.themeElements.fontScheme);
_page.m_oTextPr = textPr;
if (theme)
_page.m_oGrFonts.checkFromTheme(theme.themeElements.fontScheme, _page.m_oTextPr.RFonts);
else
_page.m_oGrFonts = _page.m_oTextPr.RFonts;
}
},
SetFontInternal : function(name, size, style)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].SetFontInternal(name, size, style);
},
SetFontSlot : function(slot, fontSizeKoef)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].SetFontSlot(slot, fontSizeKoef);
},
GetTextPr : function()
{
if (0 != this.m_lPagesCount)
return this.m_arrayPages[this.m_lPagesCount - 1].m_oTextPr;
return null;
},
DrawPresentationComment : function(type, x, y, w, h)
{
},
private_removeVectors : function()
{
this._restoreDumpedVectors = this.VectorMemoryForPrint;
if (this._restoreDumpedVectors != null)
{
this.VectorMemoryForPrint = null;
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].VectorMemoryForPrint = null;
}
},
private_restoreVectors : function()
{
if (null != this._restoreDumpedVectors)
{
this.VectorMemoryForPrint = this._restoreDumpedVectors;
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].VectorMemoryForPrint = this._restoreDumpedVectors;
}
this._restoreDumpedVectors = null;
},
AddHyperlink : function(x, y, w, h, url, tooltip)
{
if (0 !== this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].AddHyperlink(x, y, w, h, url, tooltip);
},
AddLink : function(x, y, w, h, dx, dy, dPage)
{
if (0 !== this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].AddLink(x, y, w, h, dx, dy, dPage);
},
AddFormField : function(nX, nY, nW, nH, nBaseLineOffset, oForm)
{
if (0 !== this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].AddFormField(nX, nY, nW, nH, nBaseLineOffset, oForm);
}
};
var MATRIX_ORDER_PREPEND = 0;
var MATRIX_ORDER_APPEND = 1;
function deg2rad(deg)
{
return deg * Math.PI / 180.0;
}
function rad2deg(rad)
{
return rad * 180.0 / Math.PI;
}
function CMatrix()
{
this.sx = 1.0;
this.shx = 0.0;
this.shy = 0.0;
this.sy = 1.0;
this.tx = 0.0;
this.ty = 0.0;
}
CMatrix.prototype =
{
Reset : function()
{
this.sx = 1.0;
this.shx = 0.0;
this.shy = 0.0;
this.sy = 1.0;
this.tx = 0.0;
this.ty = 0.0;
},
// трансформ
Multiply : function(matrix, order)
{
if (MATRIX_ORDER_PREPEND == order)
{
var m = new CMatrix();
m.sx = matrix.sx;
m.shx = matrix.shx;
m.shy = matrix.shy;
m.sy = matrix.sy;
m.tx = matrix.tx;
m.ty = matrix.ty;
m.Multiply(this, MATRIX_ORDER_APPEND);
this.sx = m.sx;
this.shx = m.shx;
this.shy = m.shy;
this.sy = m.sy;
this.tx = m.tx;
this.ty = m.ty;
}
else
{
var t0 = this.sx * matrix.sx + this.shy * matrix.shx;
var t2 = this.shx * matrix.sx + this.sy * matrix.shx;
var t4 = this.tx * matrix.sx + this.ty * matrix.shx + matrix.tx;
this.shy = this.sx * matrix.shy + this.shy * matrix.sy;
this.sy = this.shx * matrix.shy + this.sy * matrix.sy;
this.ty = this.tx * matrix.shy + this.ty * matrix.sy + matrix.ty;
this.sx = t0;
this.shx = t2;
this.tx = t4;
}
return this;
},
// а теперь частные случаи трансформа (для удобного пользования)
Translate : function(x, y, order)
{
var m = new CMatrix();
m.tx = x;
m.ty = y;
this.Multiply(m, order);
},
Scale : function(x, y, order)
{
var m = new CMatrix();
m.sx = x;
m.sy = y;
this.Multiply(m, order);
},
Rotate : function(a, order)
{
var m = new CMatrix();
var rad = deg2rad(a);
m.sx = Math.cos(rad);
m.shx = Math.sin(rad);
m.shy = -Math.sin(rad);
m.sy = Math.cos(rad);
this.Multiply(m, order);
},
RotateAt : function(a, x, y, order)
{
this.Translate(-x, -y, order);
this.Rotate(a, order);
this.Translate(x, y, order);
},
// determinant
Determinant : function()
{
return this.sx * this.sy - this.shy * this.shx;
},
// invert
Invert : function()
{
var det = this.Determinant();
if (0.0001 > Math.abs(det))
return;
var d = 1 / det;
var t0 = this.sy * d;
this.sy = this.sx * d;
this.shy = -this.shy * d;
this.shx = -this.shx * d;
var t4 = -this.tx * t0 - this.ty * this.shx;
this.ty = -this.tx * this.shy - this.ty * this.sy;
this.sx = t0;
this.tx = t4;
return this;
},
// transform point
TransformPointX : function(x, y)
{
return x * this.sx + y * this.shx + this.tx;
},
TransformPointY : function(x, y)
{
return x * this.shy + y * this.sy + this.ty;
},
// calculate rotate angle
GetRotation : function()
{
var x1 = 0.0;
var y1 = 0.0;
var x2 = 1.0;
var y2 = 0.0;
var _x1 = this.TransformPointX(x1, y1);
var _y1 = this.TransformPointY(x1, y1);
var _x2 = this.TransformPointX(x2, y2);
var _y2 = this.TransformPointY(x2, y2);
var _y = _y2 - _y1;
var _x = _x2 - _x1;
if (Math.abs(_y) < 0.001)
{
if (_x > 0)
return 0;
else
return 180;
}
if (Math.abs(_x) < 0.001)
{
if (_y > 0)
return 90;
else
return 270;
}
var a = Math.atan2(_y, _x);
a = rad2deg(a);
if (a < 0)
a += 360;
return a;
},
// сделать дубликата
CreateDublicate : function()
{
var m = new CMatrix();
m.sx = this.sx;
m.shx = this.shx;
m.shy = this.shy;
m.sy = this.sy;
m.tx = this.tx;
m.ty = this.ty;
return m;
},
IsIdentity : function()
{
if (this.sx == 1.0 &&
this.shx == 0.0 &&
this.shy == 0.0 &&
this.sy == 1.0 &&
this.tx == 0.0 &&
this.ty == 0.0)
{
return true;
}
return false;
},
IsIdentity2 : function()
{
if (this.sx == 1.0 &&
this.shx == 0.0 &&
this.shy == 0.0 &&
this.sy == 1.0)
{
return true;
}
return false;
},
GetScaleValue : function()
{
var x1 = this.TransformPointX(0, 0);
var y1 = this.TransformPointY(0, 0);
var x2 = this.TransformPointX(1, 1);
var y2 = this.TransformPointY(1, 1);
return Math.sqrt(((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1))/2);
}
};
function GradientGetAngleNoRotate(_angle, _transform)
{
var x1 = 0.0;
var y1 = 0.0;
var x2 = 1.0;
var y2 = 0.0;
var _matrixRotate = new CMatrix();
_matrixRotate.Rotate(-_angle / 60000);
var _x11 = _matrixRotate.TransformPointX(x1, y1);
var _y11 = _matrixRotate.TransformPointY(x1, y1);
var _x22 = _matrixRotate.TransformPointX(x2, y2);
var _y22 = _matrixRotate.TransformPointY(x2, y2);
_matrixRotate = global_MatrixTransformer.Invert(_transform);
var _x1 = _matrixRotate.TransformPointX(_x11, _y11);
var _y1 = _matrixRotate.TransformPointY(_x11, _y11);
var _x2 = _matrixRotate.TransformPointX(_x22, _y22);
var _y2 = _matrixRotate.TransformPointY(_x22, _y22);
var _y = _y2 - _y1;
var _x = _x2 - _x1;
var a = 0;
if (Math.abs(_y) < 0.001)
{
if (_x > 0)
a = 0;
else
a = 180;
}
else if (Math.abs(_x) < 0.001)
{
if (_y > 0)
a = 90;
else
a = 270;
}
else
{
a = Math.atan2(_y, _x);
a = rad2deg(a);
}
if (a < 0)
a += 360;
//console.log(a);
return a * 60000;
};
var CMatrixL = CMatrix;
function CGlobalMatrixTransformer()
{
this.TranslateAppend = function(m, _tx, _ty)
{
m.tx += _tx;
m.ty += _ty;
}
this.ScaleAppend = function(m, _sx, _sy)
{
m.sx *= _sx;
m.shx *= _sx;
m.shy *= _sy;
m.sy *= _sy;
m.tx *= _sx;
m.ty *= _sy;
}
this.RotateRadAppend = function(m, _rad)
{
var _sx = Math.cos(_rad);
var _shx = Math.sin(_rad);
var _shy = -Math.sin(_rad);
var _sy = Math.cos(_rad);
var t0 = m.sx * _sx + m.shy * _shx;
var t2 = m.shx * _sx + m.sy * _shx;
var t4 = m.tx * _sx + m.ty * _shx;
m.shy = m.sx * _shy + m.shy * _sy;
m.sy = m.shx * _shy + m.sy * _sy;
m.ty = m.tx * _shy + m.ty * _sy;
m.sx = t0;
m.shx = t2;
m.tx = t4;
}
this.MultiplyAppend = function(m1, m2)
{
var t0 = m1.sx * m2.sx + m1.shy * m2.shx;
var t2 = m1.shx * m2.sx + m1.sy * m2.shx;
var t4 = m1.tx * m2.sx + m1.ty * m2.shx + m2.tx;
m1.shy = m1.sx * m2.shy + m1.shy * m2.sy;
m1.sy = m1.shx * m2.shy + m1.sy * m2.sy;
m1.ty = m1.tx * m2.shy + m1.ty * m2.sy + m2.ty;
m1.sx = t0;
m1.shx = t2;
m1.tx = t4;
}
this.Invert = function(m)
{
var newM = m.CreateDublicate();
var det = newM.sx * newM.sy - newM.shy * newM.shx;
if (0.0001 > Math.abs(det))
return newM;
var d = 1 / det;
var t0 = newM.sy * d;
newM.sy = newM.sx * d;
newM.shy = -newM.shy * d;
newM.shx = -newM.shx * d;
var t4 = -newM.tx * t0 - newM.ty * newM.shx;
newM.ty = -newM.tx * newM.shy - newM.ty * newM.sy;
newM.sx = t0;
newM.tx = t4;
return newM;
}
this.MultiplyAppendInvert = function(m1, m2)
{
var m = this.Invert(m2);
this.MultiplyAppend(m1, m);
}
this.MultiplyPrepend = function(m1, m2)
{
var m = new CMatrixL();
m.sx = m2.sx;
m.shx = m2.shx;
m.shy = m2.shy;
m.sy = m2.sy;
m.tx = m2.tx;
m.ty = m2.ty;
this.MultiplyAppend(m, m1);
m1.sx = m.sx;
m1.shx = m.shx;
m1.shy = m.shy;
m1.sy = m.sy;
m1.tx = m.tx;
m1.ty = m.ty;
}
this.Reflect = function (matrix, isHorizontal, isVertical) {
var m = new CMatrixL();
m.shx = 0;
m.sy = 1;
m.tx = 0;
m.ty = 0;
m.sx = 1;
m.shy = 0;
if (isHorizontal && isVertical) {
m.sx = -1;
m.sy = -1;
} else if (isHorizontal) {
m.sx = -1;
} else if (isVertical) {
m.sy = -1;
} else {
return;
}
this.MultiplyAppend(matrix, m);
}
this.CreateDublicateM = function(matrix)
{
var m = new CMatrixL();
m.sx = matrix.sx;
m.shx = matrix.shx;
m.shy = matrix.shy;
m.sy = matrix.sy;
m.tx = matrix.tx;
m.ty = matrix.ty;
return m;
}
this.IsIdentity = function(m)
{
if (m.sx == 1.0 &&
m.shx == 0.0 &&
m.shy == 0.0 &&
m.sy == 1.0 &&
m.tx == 0.0 &&
m.ty == 0.0)
{
return true;
}
return false;
}
this.IsIdentity2 = function(m)
{
var eps = 0.00001;
if (Math.abs(m.sx - 1.0) < eps &&
Math.abs(m.shx) < eps &&
Math.abs(m.shy) < eps &&
Math.abs(m.sy - 1.0) < eps)
{
return true;
}
return false;
}
}
function CClipManager()
{
this.clipRects = [];
this.curRect = new _rect();
this.BaseObject = null;
this.AddRect = function(x, y, w, h)
{
var _count = this.clipRects.length;
if (0 == _count)
{
this.curRect.x = x;
this.curRect.y = y;
this.curRect.w = w;
this.curRect.h = h;
var _r = new _rect();
_r.x = x;
_r.y = y;
_r.w = w;
_r.h = h;
this.clipRects[_count] = _r;
this.BaseObject.SetClip(this.curRect);
}
else
{
this.BaseObject.RemoveClip();
var _r = new _rect();
_r.x = x;
_r.y = y;
_r.w = w;
_r.h = h;
this.clipRects[_count] = _r;
this.curRect = this.IntersectRect(this.curRect, _r);
this.BaseObject.SetClip(this.curRect);
}
}
this.RemoveRect = function()
{
var _count = this.clipRects.length;
if (0 != _count)
{
this.clipRects.splice(_count - 1, 1);
--_count;
this.BaseObject.RemoveClip();
if (0 != _count)
{
this.curRect.x = this.clipRects[0].x;
this.curRect.y = this.clipRects[0].y;
this.curRect.w = this.clipRects[0].w;
this.curRect.h = this.clipRects[0].h;
for (var i = 1; i < _count; i++)
this.curRect = this.IntersectRect(this.curRect, this.clipRects[i]);
this.BaseObject.SetClip(this.curRect);
}
}
}
this.IntersectRect = function(r1, r2)
{
var res = new _rect();
res.x = Math.max(r1.x, r2.x);
res.y = Math.max(r1.y, r2.y);
res.w = Math.min(r1.x + r1.w, r2.x + r2.w) - res.x;
res.h = Math.min(r1.y + r1.h, r2.y + r2.h) - res.y;
if (0 > res.w)
res.w = 0;
if (0 > res.h)
res.h = 0;
return res;
}
}
function CPen()
{
this.Color = {R : 255, G : 255, B : 255, A : 255};
this.Style = 0;
this.LineCap = 0;
this.LineJoin = 0;
this.LineWidth = 1;
}
function CBrush()
{
this.Color1 = {R : 255, G : 255, B : 255, A : 255};
this.Color2 = {R : 255, G : 255, B : 255, A : 255};
this.Type = 0;
}
function CTableMarkup(Table)
{
this.Internal =
{
RowIndex : 0,
CellIndex : 0,
PageNum : 0
};
this.Table = Table;
this.X = 0; // Смещение таблицы от начала страницы до первой колонки
this.Cols = []; // массив ширин колонок
this.Margins = []; // массив левых и правых маргинов
this.Rows = []; // массив позиций, высот строк(для данной страницы)
// Rows = [ { Y : , H : }, ... ]
this.CurCol = 0; // текущая колонка
this.CurRow = 0; // текущая строка
this.TransformX = 0;
this.TransformY = 0;
}
CTableMarkup.prototype =
{
CreateDublicate : function()
{
var obj = new CTableMarkup(this.Table);
obj.Internal = {RowIndex : this.Internal.RowIndex, CellIndex : this.Internal.CellIndex, PageNum : this.Internal.PageNum};
obj.X = this.X;
var len = this.Cols.length;
for (var i = 0; i < len; i++)
obj.Cols[i] = this.Cols[i];
len = this.Margins.length;
for (var i = 0; i < len; i++)
obj.Margins[i] = {Left : this.Margins[i].Left, Right : this.Margins[i].Right};
len = this.Rows.length;
for (var i = 0; i < len; i++)
obj.Rows[i] = {Y : this.Rows[i].Y, H : this.Rows[i].H};
obj.CurRow = this.CurRow;
obj.CurCol = this.CurCol;
return obj;
},
CorrectFrom : function()
{
this.X += this.TransformX;
var _len = this.Rows.length;
for (var i = 0; i < _len; i++)
{
this.Rows[i].Y += this.TransformY;
}
},
CorrectTo : function()
{
this.X -= this.TransformX;
var _len = this.Rows.length;
for (var i = 0; i < _len; i++)
{
this.Rows[i].Y -= this.TransformY;
}
},
Get_X : function()
{
return this.X;
},
Get_Y : function()
{
var _Y = 0;
if (this.Rows.length > 0)
{
_Y = this.Rows[0].Y;
}
return _Y;
}
};
function CTableOutline(Table, PageNum, X, Y, W, H)
{
this.Table = Table;
this.PageNum = PageNum;
this.X = X;
this.Y = Y;
this.W = W;
this.H = H;
}
var g_fontManager = new AscFonts.CFontManager();
g_fontManager.Initialize(true);
g_fontManager.SetHintsProps(true, true);
var g_dDpiX = 96.0;
var g_dDpiY = 96.0;
var g_dKoef_mm_to_pix = g_dDpiX / 25.4;
var g_dKoef_pix_to_mm = 25.4 / g_dDpiX;
function _rect()
{
this.x = 0;
this.y = 0;
this.w = 0;
this.h = 0;
}
//--------------------------------------------------------export----------------------------------------------------
window['AscCommon'] = window['AscCommon'] || {};
window['AscCommon'].CGrRFonts = CGrRFonts;
window['AscCommon'].CFontSetup = CFontSetup;
window['AscCommon'].CGrState = CGrState;
window['AscCommon'].CMemory = CMemory;
window['AscCommon'].CDocumentRenderer = CDocumentRenderer;
window['AscCommon'].MATRIX_ORDER_PREPEND = MATRIX_ORDER_PREPEND;
window['AscCommon'].MATRIX_ORDER_APPEND = MATRIX_ORDER_APPEND;
window['AscCommon'].deg2rad = deg2rad;
window['AscCommon'].rad2deg = rad2deg;
window['AscCommon'].CMatrix = CMatrix;
window['AscCommon'].CMatrixL = CMatrixL;
window['AscCommon'].CGlobalMatrixTransformer = CGlobalMatrixTransformer;
window['AscCommon'].CClipManager = CClipManager;
window['AscCommon'].CPen = CPen;
window['AscCommon'].CBrush = CBrush;
window['AscCommon'].CTableMarkup = CTableMarkup;
window['AscCommon'].CTableOutline = CTableOutline;
window['AscCommon']._rect = _rect;
window['AscCommon'].global_MatrixTransformer = new CGlobalMatrixTransformer();
window['AscCommon'].g_fontManager = g_fontManager;
window['AscCommon'].g_dDpiX = g_dDpiX;
window['AscCommon'].g_dKoef_mm_to_pix = g_dKoef_mm_to_pix;
window['AscCommon'].g_dKoef_pix_to_mm = g_dKoef_pix_to_mm;
window['AscCommon'].GradientGetAngleNoRotate = GradientGetAngleNoRotate;
window['AscCommon'].DashPatternPresets = DashPatternPresets;
window['AscCommon'].CommandType = CommandType;
})(window);
|
common/Drawings/Metafile.js
|
/*
* (c) Copyright Ascensio System SIA 2010-2019
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
"use strict";
(function(window, undefined)
{
// Import
var g_fontApplication = AscFonts.g_fontApplication;
function CGrRFonts()
{
this.Ascii = {Name : "Empty", Index : -1};
this.EastAsia = {Name : "Empty", Index : -1};
this.HAnsi = {Name : "Empty", Index : -1};
this.CS = {Name : "Empty", Index : -1};
}
CGrRFonts.prototype =
{
checkFromTheme : function(fontScheme, rFonts)
{
this.Ascii.Name = fontScheme.checkFont(rFonts.Ascii.Name);
this.EastAsia.Name = fontScheme.checkFont(rFonts.EastAsia.Name);
this.HAnsi.Name = fontScheme.checkFont(rFonts.HAnsi.Name);
this.CS.Name = fontScheme.checkFont(rFonts.CS.Name);
this.Ascii.Index = -1;
this.EastAsia.Index = -1;
this.HAnsi.Index = -1;
this.CS.Index = -1;
},
fromRFonts : function(rFonts)
{
this.Ascii.Name = rFonts.Ascii.Name;
this.EastAsia.Name = rFonts.EastAsia.Name;
this.HAnsi.Name = rFonts.HAnsi.Name;
this.CS.Name = rFonts.CS.Name;
this.Ascii.Index = -1;
this.EastAsia.Index = -1;
this.HAnsi.Index = -1;
this.CS.Index = -1;
}
};
var gr_state_pen = 0;
var gr_state_brush = 1;
var gr_state_pen_brush = 2;
var gr_state_state = 3;
var gr_state_all = 4;
function CFontSetup()
{
this.Name = "";
this.Index = -1;
this.Size = 12;
this.Bold = false;
this.Italic = false;
this.SetUpName = "";
this.SetUpIndex = -1;
this.SetUpSize = 12;
this.SetUpStyle = -1;
this.SetUpMatrix = new CMatrix();
}
CFontSetup.prototype =
{
Clear : function()
{
this.Name = "";
this.Index = -1;
this.Size = 12;
this.Bold = false;
this.Italic = false;
this.SetUpName = "";
this.SetUpIndex = -1;
this.SetUpSize = 12;
this.SetUpStyle = -1;
this.SetUpMatrix = new CMatrix();
}
};
function CGrState_Pen()
{
this.Type = gr_state_pen;
this.Pen = null;
}
CGrState_Pen.prototype =
{
Init : function(_pen)
{
if (_pen !== undefined)
this.Pen = _pen.CreateDublicate();
}
};
function CGrState_Brush()
{
this.Type = gr_state_brush;
this.Brush = null;
}
CGrState_Brush.prototype =
{
Init : function(_brush)
{
if (undefined !== _brush)
this.Brush = _brush.CreateDublicate();
}
};
function CGrState_PenBrush()
{
this.Type = gr_state_pen_brush;
this.Pen = null;
this.Brush = null;
}
CGrState_PenBrush.prototype =
{
Init : function(_pen, _brush)
{
if (undefined !== _pen && undefined !== _brush)
{
this.Pen = _pen.CreateDublicate();
this.Brush = _brush.CreateDublicate();
}
}
};
function CHist_Clip()
{
this.Path = null; // clipPath
this.Rect = null; // clipRect. clipRect - is a simple clipPath.
this.IsIntegerGrid = false;
this.Transform = new CMatrix();
}
CHist_Clip.prototype =
{
Init : function(path, rect, isIntegerGrid, transform)
{
this.Path = path;
if (rect !== undefined)
{
this.Rect = new _rect();
this.Rect.x = rect.x;
this.Rect.y = rect.y;
this.Rect.w = rect.w;
this.Rect.h = rect.h;
}
if (undefined !== isIntegerGrid)
this.IsIntegerGrid = isIntegerGrid;
if (undefined !== transform)
this.Transform = transform.CreateDublicate();
},
ToRenderer : function(renderer)
{
if (this.Rect != null)
{
var r = this.Rect;
renderer.StartClipPath();
renderer.rect(r.x, r.y, r.w, r.h);
renderer.EndClipPath();
}
else
{
// TODO: пока не используется
}
}
};
function CGrState_State()
{
this.Type = gr_state_state;
this.Transform = null;
this.IsIntegerGrid = false;
this.Clips = null;
}
CGrState_State.prototype =
{
Init : function(_transform, _isIntegerGrid, _clips)
{
if (undefined !== _transform)
this.Transform = _transform.CreateDublicate();
if (undefined !== _isIntegerGrid)
this.IsIntegerGrid = _isIntegerGrid;
if (undefined !== _clips)
this.Clips = _clips;
},
ApplyClips : function(renderer)
{
var _len = this.Clips.length;
for (var i = 0; i < _len; i++)
{
this.Clips[i].ToRenderer(renderer);
}
},
Apply : function(parent)
{
for (var i = 0, len = this.Clips.length; i < len; i++)
{
parent.transform3(this.Clips[i].Transform);
parent.SetIntegerGrid(this.Clips[i].IsIntegerGrid);
var _r = this.Clips[i].Rect;
parent.StartClipPath();
parent._s();
parent._m(_r.x, _r.y);
parent._l(_r.x + _r.w, _r.y);
parent._l(_r.x + _r.w, _r.y + _r.h);
parent._l(_r.x, _r.y + _r.h);
parent._l(_r.x, _r.y);
parent.EndClipPath();
}
}
};
function CGrState()
{
this.Parent = null;
this.States = [];
this.Clips = [];
}
CGrState.prototype =
{
SavePen : function()
{
if (null == this.Parent)
return;
var _state = new CGrState_Pen();
_state.Init(this.Parent.m_oPen);
this.States.push(_state);
},
SaveBrush : function()
{
if (null == this.Parent)
return;
var _state = new CGrState_Brush();
_state.Init(this.Parent.m_oBrush);
this.States.push(_state);
},
SavePenBrush : function()
{
if (null == this.Parent)
return;
var _state = new CGrState_PenBrush();
_state.Init(this.Parent.m_oPen, this.Parent.m_oBrush);
this.States.push(_state);
},
RestorePen : function()
{
var _ind = this.States.length - 1;
if (null == this.Parent || -1 == _ind)
return;
var _state = this.States[_ind];
if (_state.Type == gr_state_pen)
{
this.States.splice(_ind, 1);
var _c = _state.Pen.Color;
this.Parent.p_color(_c.R, _c.G, _c.B, _c.A);
}
},
RestoreBrush : function()
{
var _ind = this.States.length - 1;
if (null == this.Parent || -1 == _ind)
return;
var _state = this.States[_ind];
if (_state.Type == gr_state_brush)
{
this.States.splice(_ind, 1);
var _c = _state.Brush.Color1;
this.Parent.b_color1(_c.R, _c.G, _c.B, _c.A);
}
},
RestorePenBrush : function()
{
var _ind = this.States.length - 1;
if (null == this.Parent || -1 == _ind)
return;
var _state = this.States[_ind];
if (_state.Type == gr_state_pen_brush)
{
this.States.splice(_ind, 1);
var _cb = _state.Brush.Color1;
var _cp = _state.Pen.Color;
this.Parent.b_color1(_cb.R, _cb.G, _cb.B, _cb.A);
this.Parent.p_color(_cp.R, _cp.G, _cp.B, _cp.A);
}
},
SaveGrState : function()
{
if (null == this.Parent)
return;
var _state = new CGrState_State();
_state.Init(this.Parent.m_oTransform, !!this.Parent.m_bIntegerGrid, this.Clips);
this.States.push(_state);
this.Clips = [];
},
RestoreGrState : function()
{
var _ind = this.States.length - 1;
if (null == this.Parent || -1 == _ind)
return;
var _state = this.States[_ind];
if (_state.Type === gr_state_state)
{
if (this.Clips.length > 0)
{
// значит клипы были, и их нужно обновить
this.Parent.RemoveClip();
for (var i = 0; i <= _ind; i++)
{
if (this.States[i].Type === gr_state_state)
this.States[i].Apply(this.Parent);
}
}
this.Clips = _state.Clips;
this.States.splice(_ind, 1);
this.Parent.transform3(_state.Transform);
this.Parent.SetIntegerGrid(_state.IsIntegerGrid);
}
},
RemoveLastClip : function()
{
// цель - убрать примененные this.Clips
if (this.Clips.length === 0)
return;
this.lastState = new CGrState_State();
this.lastState.Init(this.Parent.m_oTransform, !!this.Parent.m_bIntegerGrid, this.Clips);
this.Parent.RemoveClip();
for (var i = 0, len = this.States.length; i < len; i++)
{
if (this.States[i].Type === gr_state_state)
this.States[i].Apply(this.Parent);
}
this.Clips = [];
this.Parent.transform3(this.lastState.Transform);
this.Parent.SetIntegerGrid(this.lastState.IsIntegerGrid);
},
RestoreLastClip : function()
{
// цель - вернуть примененные this.lastState.Clips
if (!this.lastState)
return;
this.lastState.Apply(this.Parent);
this.Clips = this.lastState.Clips;
this.Parent.transform3(this.lastState.Transform);
this.Parent.SetIntegerGrid(this.lastState.IsIntegerGrid);
this.lastState = null;
},
Save : function()
{
this.SavePen();
this.SaveBrush();
this.SaveGrState();
},
Restore : function()
{
this.RestoreGrState();
this.RestoreBrush();
this.RestorePen();
},
StartClipPath : function()
{
// реализовать, как понадобится
},
EndClipPath : function()
{
// реализовать, как понадобится
},
AddClipRect : function(_r)
{
var _histClip = new CHist_Clip();
_histClip.Transform = this.Parent.m_oTransform.CreateDublicate();
_histClip.IsIntegerGrid = !!this.Parent.m_bIntegerGrid;
_histClip.Rect = new _rect();
_histClip.Rect.x = _r.x;
_histClip.Rect.y = _r.y;
_histClip.Rect.w = _r.w;
_histClip.Rect.h = _r.h;
this.Clips.push(_histClip);
this.Parent.StartClipPath();
this.Parent._s();
this.Parent._m(_r.x, _r.y);
this.Parent._l(_r.x + _r.w, _r.y);
this.Parent._l(_r.x + _r.w, _r.y + _r.h);
this.Parent._l(_r.x, _r.y + _r.h);
this.Parent._l(_r.x, _r.y);
this.Parent.EndClipPath();
//this.Parent._e();
}
};
function CMemory(bIsNoInit)
{
this.Init = function()
{
var _canvas = document.createElement('canvas');
var _ctx = _canvas.getContext('2d');
this.len = 1024 * 1024 * 5;
this.ImData = _ctx.createImageData(this.len / 4, 1);
this.data = this.ImData.data;
this.pos = 0;
}
this.ImData = null;
this.data = null;
this.len = 0;
this.pos = 0;
this.context = null;
if (true !== bIsNoInit)
this.Init();
this.Copy = function(oMemory, nPos, nLen)
{
for (var Index = 0; Index < nLen; Index++)
{
this.CheckSize(1);
this.data[this.pos++] = oMemory.data[Index + nPos];
}
};
this.CheckSize = function(count)
{
if (this.pos + count >= this.len)
{
var _canvas = document.createElement('canvas');
var _ctx = _canvas.getContext('2d');
var oldImData = this.ImData;
var oldData = this.data;
var oldPos = this.pos;
this.len = Math.max(this.len * 2, this.pos + ((3 * count / 2) >> 0));
this.ImData = _ctx.createImageData(this.len / 4, 1);
this.data = this.ImData.data;
var newData = this.data;
for (var i = 0; i < this.pos; i++)
newData[i] = oldData[i];
}
}
this.GetBase64Memory = function()
{
return AscCommon.Base64.encode(this.data, 0, this.pos);
}
this.GetBase64Memory2 = function(nPos, nLen)
{
return AscCommon.Base64.encode(this.data, nPos, nLen);
}
this.GetData = function(nPos, nLen)
{
var _canvas = document.createElement('canvas');
var _ctx = _canvas.getContext('2d');
var len = this.GetCurPosition();
//todo ImData.data.length multiple of 4
var ImData = _ctx.createImageData(Math.ceil(len / 4), 1);
var res = ImData.data;
for (var i = 0; i < len; i++)
res[i] = this.data[i];
return res;
}
this.GetDataUint8 = function(pos, len)
{
if (undefined === pos) {
pos = 0;
}
if (undefined === len) {
len = this.GetCurPosition() - pos;
}
return this.data.slice(pos, pos + len);
}
this.GetCurPosition = function()
{
return this.pos;
}
this.Seek = function(nPos)
{
this.pos = nPos;
}
this.Skip = function(nDif)
{
this.pos += nDif;
}
this.WriteBool = function(val)
{
this.CheckSize(1);
if (false == val)
this.data[this.pos++] = 0;
else
this.data[this.pos++] = 1;
}
this.WriteByte = function(val)
{
this.CheckSize(1);
this.data[this.pos++] = val;
}
this.WriteSByte = function(val)
{
this.CheckSize(1);
if (val < 0)
val += 256;
this.data[this.pos++] = val;
}
this.WriteShort = function(val)
{
this.CheckSize(2);
this.data[this.pos++] = (val) & 0xFF;
this.data[this.pos++] = (val >>> 8) & 0xFF;
}
this.WriteUShort = function(val)
{
this.WriteShort(AscFonts.FT_Common.UShort_To_Short(val));
}
this.WriteLong = function(val)
{
this.CheckSize(4);
this.data[this.pos++] = (val) & 0xFF;
this.data[this.pos++] = (val >>> 8) & 0xFF;
this.data[this.pos++] = (val >>> 16) & 0xFF;
this.data[this.pos++] = (val >>> 24) & 0xFF;
}
this.WriteULong = function(val)
{
this.WriteLong(AscFonts.FT_Common.UintToInt(val));
}
this.WriteDouble = function(val)
{
this.CheckSize(4);
var lval = ((val * 100000) >> 0) & 0xFFFFFFFF; // спасаем пять знаков после запятой.
this.data[this.pos++] = (lval) & 0xFF;
this.data[this.pos++] = (lval >>> 8) & 0xFF;
this.data[this.pos++] = (lval >>> 16) & 0xFF;
this.data[this.pos++] = (lval >>> 24) & 0xFF;
}
var tempHelp = new ArrayBuffer(8);
var tempHelpUnit = new Uint8Array(tempHelp);
var tempHelpFloat = new Float64Array(tempHelp);
this.WriteDouble2 = function(val)
{
this.CheckSize(8);
tempHelpFloat[0] = val;
this.data[this.pos++] = tempHelpUnit[0];
this.data[this.pos++] = tempHelpUnit[1];
this.data[this.pos++] = tempHelpUnit[2];
this.data[this.pos++] = tempHelpUnit[3];
this.data[this.pos++] = tempHelpUnit[4];
this.data[this.pos++] = tempHelpUnit[5];
this.data[this.pos++] = tempHelpUnit[6];
this.data[this.pos++] = tempHelpUnit[7];
}
this._doubleEncodeLE754 = function(v)
{
//код взят из jspack.js на основе стандарта Little-endian N-bit IEEE 754 floating point
var s, e, m, i, d, c, mLen, eLen, eBias, eMax;
var el = {len : 8, mLen : 52, rt : 0};
mLen = el.mLen, eLen = el.len * 8 - el.mLen - 1, eMax = (1 << eLen) - 1, eBias = eMax >> 1;
s = v < 0 ? 1 : 0;
v = Math.abs(v);
if (isNaN(v) || (v == Infinity))
{
m = isNaN(v) ? 1 : 0;
e = eMax;
}
else
{
e = Math.floor(Math.log(v) / Math.LN2); // Calculate log2 of the value
if (v * (c = Math.pow(2, -e)) < 1)
{
e--;
c *= 2;
} // Math.log() isn't 100% reliable
// Round by adding 1/2 the significand's LSD
if (e + eBias >= 1)
{
v += el.rt / c;
} // Normalized: mLen significand digits
else
{
v += el.rt * Math.pow(2, 1 - eBias);
} // Denormalized: <= mLen significand digits
if (v * c >= 2)
{
e++;
c /= 2;
} // Rounding can increment the exponent
if (e + eBias >= eMax)
{
// Overflow
m = 0;
e = eMax;
}
else if (e + eBias >= 1)
{
// Normalized - term order matters, as Math.pow(2, 52-e) and v*Math.pow(2, 52) can overflow
m = (v * c - 1) * Math.pow(2, mLen);
e = e + eBias;
}
else
{
// Denormalized - also catches the '0' case, somewhat by chance
m = v * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
e = 0;
}
}
var a = new Array(8);
for (i = 0, d = 1; mLen >= 8; a[i] = m & 0xff, i += d, m /= 256, mLen -= 8);
for (e = (e << mLen) | m, eLen += mLen; eLen > 0; a[i] = e & 0xff, i += d, e /= 256, eLen -= 8);
a[i - d] |= s * 128;
return a;
}
this.WriteStringBySymbol = function(code)
{
if (code < 0xFFFF)
{
this.CheckSize(4);
this.data[this.pos++] = 1;
this.data[this.pos++] = 0;
this.data[this.pos++] = code & 0xFF;
this.data[this.pos++] = (code >>> 8) & 0xFF;
}
else
{
this.CheckSize(6);
this.data[this.pos++] = 2;
this.data[this.pos++] = 0;
var codePt = code - 0x10000;
var c1 = 0xD800 | (codePt >> 10);
var c2 = 0xDC00 | (codePt & 0x3FF);
this.data[this.pos++] = c1 & 0xFF;
this.data[this.pos++] = (c1 >>> 8) & 0xFF;
this.data[this.pos++] = c2 & 0xFF;
this.data[this.pos++] = (c2 >>> 8) & 0xFF;
}
}
this.WriteString = function(text)
{
if ("string" != typeof text)
text = text + "";
var count = text.length & 0xFFFF;
this.CheckSize(2 * count + 2);
this.data[this.pos++] = count & 0xFF;
this.data[this.pos++] = (count >>> 8) & 0xFF;
for (var i = 0; i < count; i++)
{
var c = text.charCodeAt(i) & 0xFFFF;
this.data[this.pos++] = c & 0xFF;
this.data[this.pos++] = (c >>> 8) & 0xFF;
}
}
this.WriteString2 = function(text)
{
if ("string" != typeof text)
text = text + "";
var count = text.length & 0x7FFFFFFF;
var countWrite = 2 * count;
this.WriteLong(countWrite);
this.CheckSize(countWrite);
for (var i = 0; i < count; i++)
{
var c = text.charCodeAt(i) & 0xFFFF;
this.data[this.pos++] = c & 0xFF;
this.data[this.pos++] = (c >>> 8) & 0xFF;
}
}
this.WriteString3 = function(text)
{
if ("string" != typeof text)
text = text + "";
var count = text.length & 0x7FFFFFFF;
var countWrite = 2 * count;
this.CheckSize(countWrite);
for (var i = 0; i < count; i++)
{
var c = text.charCodeAt(i) & 0xFFFF;
this.data[this.pos++] = c & 0xFF;
this.data[this.pos++] = (c >>> 8) & 0xFF;
}
}
this.WriteString4 = function(text)
{
if ("string" != typeof text)
text = text + "";
var count = text.length & 0x7FFFFFFF;
this.WriteLong(count);
this.CheckSize(2 * count);
for (var i = 0; i < count; i++)
{
var c = text.charCodeAt(i) & 0xFFFF;
this.data[this.pos++] = c & 0xFF;
this.data[this.pos++] = (c >>> 8) & 0xFF;
}
}
this.WriteStringA = function(text)
{
var count = text.length & 0xFFFF;
this.WriteULong(count);
this.CheckSize(count);
for (var i=0;i<count;i++)
{
var c = text.charCodeAt(i) & 0xFF;
this.data[this.pos++] = c;
}
};
this.ClearNoAttack = function()
{
this.pos = 0;
}
this.WriteLongAt = function(_pos, val)
{
this.data[_pos++] = (val) & 0xFF;
this.data[_pos++] = (val >>> 8) & 0xFF;
this.data[_pos++] = (val >>> 16) & 0xFF;
this.data[_pos++] = (val >>> 24) & 0xFF;
}
this.WriteBuffer = function(data, _pos, count)
{
this.CheckSize(count);
for (var i = 0; i < count; i++)
{
this.data[this.pos++] = data[_pos + i];
}
}
this.WriteUtf8Char = function(code)
{
this.CheckSize(1);
if (code < 0x80) {
this.data[this.pos++] = code;
}
else if (code < 0x0800) {
this.data[this.pos++] = (0xC0 | (code >> 6));
this.data[this.pos++] = (0x80 | (code & 0x3F));
}
else if (code < 0x10000) {
this.data[this.pos++] = (0xE0 | (code >> 12));
this.data[this.pos++] = (0x80 | ((code >> 6) & 0x3F));
this.data[this.pos++] = (0x80 | (code & 0x3F));
}
else if (code < 0x1FFFFF) {
this.data[this.pos++] = (0xF0 | (code >> 18));
this.data[this.pos++] = (0x80 | ((code >> 12) & 0x3F));
this.data[this.pos++] = (0x80 | ((code >> 6) & 0x3F));
this.data[this.pos++] = (0x80 | (code & 0x3F));
}
else if (code < 0x3FFFFFF) {
this.data[this.pos++] = (0xF8 | (code >> 24));
this.data[this.pos++] = (0x80 | ((code >> 18) & 0x3F));
this.data[this.pos++] = (0x80 | ((code >> 12) & 0x3F));
this.data[this.pos++] = (0x80 | ((code >> 6) & 0x3F));
this.data[this.pos++] = (0x80 | (code & 0x3F));
}
else if (code < 0x7FFFFFFF) {
this.data[this.pos++] = (0xFC | (code >> 30));
this.data[this.pos++] = (0x80 | ((code >> 24) & 0x3F));
this.data[this.pos++] = (0x80 | ((code >> 18) & 0x3F));
this.data[this.pos++] = (0x80 | ((code >> 12) & 0x3F));
this.data[this.pos++] = (0x80 | ((code >> 6) & 0x3F));
this.data[this.pos++] = (0x80 | (code & 0x3F));
}
};
this.WriteXmlString = function(val)
{
var pCur = 0;
var pEnd = val.length;
while (pCur < pEnd)
{
var code = val.charCodeAt(pCur++);
if (code >= 0xD800 && code <= 0xDFFF && pCur < pEnd)
{
code = 0x10000 + (((code & 0x3FF) << 10) | (0x03FF & val.charCodeAt(pCur++)));
}
this.WriteUtf8Char(code);
}
};
this.WriteXmlStringEncode = function(val)
{
var pCur = 0;
var pEnd = val.length;
while (pCur < pEnd)
{
var code = val.charCodeAt(pCur++);
if (code >= 0xD800 && code <= 0xDFFF && pCur < pEnd)
{
code = 0x10000 + (((code & 0x3FF) << 10) | (0x03FF & val.charCodeAt(pCur++)));
}
this.WriteXmlCharCode(code);
}
};
this.WriteXmlCharCode = function(code)
{
switch (code)
{
case 0x26:
//&
this.WriteUtf8Char(0x26);
this.WriteUtf8Char(0x61);
this.WriteUtf8Char(0x6d);
this.WriteUtf8Char(0x70);
this.WriteUtf8Char(0x3b);
break;
case 0x27:
//'
this.WriteUtf8Char(0x26);
this.WriteUtf8Char(0x61);
this.WriteUtf8Char(0x70);
this.WriteUtf8Char(0x6f);
this.WriteUtf8Char(0x73);
this.WriteUtf8Char(0x3b);
break;
case 0x3c:
//<
this.WriteUtf8Char(0x26);
this.WriteUtf8Char(0x6c);
this.WriteUtf8Char(0x74);
this.WriteUtf8Char(0x3b);
break;
case 0x3e:
//>
this.WriteUtf8Char(0x26);
this.WriteUtf8Char(0x67);
this.WriteUtf8Char(0x74);
this.WriteUtf8Char(0x3b);
break;
case 0x22:
//"
this.WriteUtf8Char(0x26);
this.WriteUtf8Char(0x71);
this.WriteUtf8Char(0x75);
this.WriteUtf8Char(0x6f);
this.WriteUtf8Char(0x74);
this.WriteUtf8Char(0x3b);
break;
default:
this.WriteUtf8Char(code);
break;
}
};
this.WriteXmlBool = function(val)
{
this.WriteXmlString(val ? '1' : '0');
};
this.WriteXmlByte = function(val)
{
this.WriteXmlInt(val);
};
this.WriteXmlSByte = function(val)
{
this.WriteXmlInt(val);
};
this.WriteXmlInt = function(val)
{
this.WriteXmlString(val.toFixed(0));
};
this.WriteXmlUInt = function(val)
{
this.WriteXmlInt(val);
};
this.WriteXmlInt64 = function(val)
{
this.WriteXmlInt(val);
};
this.WriteXmlUInt64 = function(val)
{
this.WriteXmlInt(val);
};
this.WriteXmlDouble = function(val)
{
this.WriteXmlNumber(val);
};
this.WriteXmlNumber = function(val)
{
this.WriteXmlString(val.toString());
};
this.WriteXmlNodeStart = function(name)
{
this.WriteUtf8Char(0x3c);
this.WriteXmlString(name);
};
this.WriteXmlNodeEnd = function(name)
{
this.WriteUtf8Char(0x3c);
this.WriteUtf8Char(0x2f);
this.WriteXmlString(name);
this.WriteUtf8Char(0x3e);
};
this.WriteXmlAttributesEnd = function(isEnd)
{
if (isEnd)
this.WriteUtf8Char(0x2f);
this.WriteUtf8Char(0x3e);
};
this.WriteXmlAttributeString = function(name, val)
{
this.WriteUtf8Char(0x20);
this.WriteXmlString(name);
this.WriteUtf8Char(0x3d);
this.WriteUtf8Char(0x22);
this.WriteXmlString(val.toString());
this.WriteUtf8Char(0x22);
};
this.WriteXmlAttributeStringEncode = function(name, val)
{
this.WriteUtf8Char(0x20);
this.WriteXmlString(name);
this.WriteUtf8Char(0x3d);
this.WriteUtf8Char(0x22);
this.WriteXmlStringEncode(val.toString());
this.WriteUtf8Char(0x22);
};
this.WriteXmlAttributeBool = function(name, val)
{
this.WriteXmlAttributeString(name, val ? '1' : '0');
};
this.WriteXmlAttributeByte = function(name, val)
{
this.WriteXmlAttributeInt(name, val);
};
this.WriteXmlAttributeSByte = function(name, val)
{
this.WriteXmlAttributeInt(name, val);
};
this.WriteXmlAttributeInt = function(name, val)
{
this.WriteXmlAttributeString(name, val.toFixed(0));
};
this.WriteXmlAttributeUInt = function(name, val)
{
this.WriteXmlAttributeInt(name, val);
};
this.WriteXmlAttributeInt64 = function(name, val)
{
this.WriteXmlAttributeInt(name, val);
};
this.WriteXmlAttributeUInt64 = function(name, val)
{
this.WriteXmlAttributeInt(name, val);
};
this.WriteXmlAttributeDouble = function(name, val)
{
this.WriteXmlAttributeNumber(name, val);
};
this.WriteXmlAttributeNumber = function(name, val)
{
this.WriteXmlAttributeString(name, val.toString());
};
this.WriteXmlNullable = function(val, name)
{
if (val) {
val.toXml(this, name);
}
};
//пересмотреть, куча аргументов
this.WriteXmlArray = function(val, name, opt_parentName, needWriteCount, ns, childns)
{
if (!ns) {
ns = "";
}
if (!childns) {
childns = "";
}
if(val && val.length > 0) {
if(opt_parentName) {
this.WriteXmlNodeStart(ns + opt_parentName);
if (needWriteCount) {
this.WriteXmlNullableAttributeNumber("count", val.length);
}
this.WriteXmlAttributesEnd();
}
val.forEach(function(elem, index){
elem.toXml(this, name, childns, childns, index);
}, this);
if(opt_parentName) {
this.WriteXmlNodeEnd(ns + opt_parentName);
}
}
};
this.WriteXmlNullableAttributeString = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlAttributeString(name, val)
}
};
this.WriteXmlNullableAttributeStringEncode = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlAttributeStringEncode(name, val)
}
};
this.WriteXmlNonEmptyAttributeStringEncode = function(name, val)
{
if (val) {
this.WriteXmlAttributeStringEncode(name, val)
}
};
this.WriteXmlNullableAttributeBool = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlAttributeBool(name, val)
}
};
this.WriteXmlNullableAttributeBool2 = function(name, val)
{
//добавлюя по аналогии с x2t
if (null !== val && undefined !== val) {
this.WriteXmlNullableAttributeString(name, val ? "1": "0")
}
};
this.WriteXmlNullableAttributeByte = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlAttributeByte(name, val)
}
};
this.WriteXmlNullableAttributeSByte = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlAttributeSByte(name, val)
}
};
this.WriteXmlNullableAttributeInt = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlAttributeInt(name, val)
}
};
this.WriteXmlNullableAttributeUInt = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlAttributeUInt(name, val)
}
};
this.WriteXmlNullableAttributeInt64 = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlAttributeInt64(name, val)
}
};
this.WriteXmlNullableAttributeUInt64 = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlAttributeUInt64(name, val)
}
};
this.WriteXmlNullableAttributeDouble = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlAttributeDouble(name, val)
}
};
this.WriteXmlNullableAttributeNumber = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlAttributeNumber(name, val)
}
};
this.WriteXmlNullableAttributeIntWithKoef = function(name, val, koef)
{
if (null !== val && undefined !== val) {
this.WriteXmlAttributeInt(name, val * koef)
}
};
this.WriteXmlNullableAttributeUIntWithKoef = function(name, val, koef)
{
if (null !== val && undefined !== val) {
this.WriteXmlAttributeUInt(name, val * koef)
}
};
this.WriteXmlAttributeBoolIfTrue = function(name, val)
{
if (val) {
this.WriteXmlAttributeBool(name, val)
}
};
this.WriteXmlValueString = function(name, val)
{
this.WriteXmlNodeStart(name);
this.WriteXmlAttributesEnd();
this.WriteXmlString(val.toString());
this.WriteXmlNodeEnd(name);
};
this.WriteXmlValueStringEncode = function(name, val)
{
this.WriteXmlNodeStart(name);
this.WriteXmlAttributeString("xml:space", "preserve");
this.WriteXmlAttributesEnd();
this.WriteXmlStringEncode(val.toString());
this.WriteXmlNodeEnd(name);
};
this.WriteXmlValueBool = function(name, val)
{
this.WriteXmlNodeStart(name);
this.WriteXmlAttributesEnd();
this.WriteXmlBool(val);
this.WriteXmlNodeEnd(name);
};
this.WriteXmlValueByte = function(name, val)
{
this.WriteXmlNodeStart(name);
this.WriteXmlAttributesEnd();
this.WriteXmlByte(val);
this.WriteXmlNodeEnd(name);
};
this.WriteXmlValueSByte = function(name, val)
{
this.WriteXmlNodeStart(name);
this.WriteXmlAttributesEnd();
this.WriteXmlSByte(val);
this.WriteXmlNodeEnd(name);
};
this.WriteXmlValueInt = function(name, val)
{
this.WriteXmlNodeStart(name);
this.WriteXmlAttributesEnd();
this.WriteXmlInt(val);
this.WriteXmlNodeEnd(name);
};
this.WriteXmlValueUInt = function(name, val)
{
this.WriteXmlNodeStart(name);
this.WriteXmlAttributesEnd();
this.WriteXmlUInt(val);
this.WriteXmlNodeEnd(name);
};
this.WriteXmlValueInt64 = function(name, val)
{
this.WriteXmlNodeStart(name);
this.WriteXmlAttributesEnd();
this.WriteXmlInt64(val);
this.WriteXmlNodeEnd(name);
};
this.WriteXmlValueUInt64 = function(name, val)
{
this.WriteXmlNodeStart(name);
this.WriteXmlAttributesEnd();
this.WriteXmlUInt64(val);
this.WriteXmlNodeEnd(name);
};
this.WriteXmlValueDouble = function(name, val)
{
this.WriteXmlNodeStart(name);
this.WriteXmlAttributesEnd();
this.WriteXmlDouble(val);
this.WriteXmlNodeEnd(name);
};
this.WriteXmlValueNumber = function(name, val)
{
this.WriteXmlNodeStart(name);
this.WriteXmlAttributesEnd();
this.WriteXmlNumber(val);
this.WriteXmlNodeEnd(name);
};
this.WriteXmlNullableValueString = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlValueString(name, val)
}
};
this.WriteXmlNullableValueStringEncode = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlValueStringEncode(name, val)
}
};
this.WriteXmlNullableValueBool = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlValueBool(name, val)
}
};
this.WriteXmlNullableValueByte = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlValueByte(name, val)
}
};
this.WriteXmlNullableValueSByte = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlValueSByte(name, val)
}
};
this.WriteXmlNullableValueInt = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlValueInt(name, val)
}
};
this.WriteXmlNullableValueUInt = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlValueUInt(name, val)
}
};
this.WriteXmlNullableValueInt64 = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlValueInt64(name, val)
}
};
this.WriteXmlNullableValueUInt64 = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlValueUInt64(name, val)
}
};
this.WriteXmlNullableValueDouble = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlValueDouble(name, val)
}
};
this.WriteXmlNullableValueNumber = function(name, val)
{
if (null !== val && undefined !== val) {
this.WriteXmlValueNumber(name, val)
}
};
this.XlsbStartRecord = function(type, len) {
//Type
if (type < 0x80) {
this.WriteByte(type);
}
else {
this.WriteByte((type & 0x7F) | 0x80);
this.WriteByte(type >> 7);
}
//Len
for (var i = 0; i < 4; ++i) {
var part = len & 0x7F;
len = len >> 7;
if (len === 0) {
this.WriteByte(part);
break;
}
else {
this.WriteByte(part | 0x80);
}
}
};
this.XlsbEndRecord = function() {
};
//все аргументы сохраняю как в x2t, ns - префикс пока не использую
this.WritingValNode = function(ns, name, val) {
this.WriteXmlNodeStart(name);
this.WriteXmlAttributeString("val", val);
this.WriteXmlAttributesEnd(true);
};
this.WritingValNodeEncodeXml = function(ns, name, val) {
this.WriteXmlNodeStart(name);
this.WriteXmlNullableAttributeStringEncode("val", val);
this.WriteXmlAttributesEnd(true);
};
this.WritingValNodeIf = function(ns, name, cond, val) {
this.WriteXmlNodeStart(name);
if (cond) {
this.WriteXmlAttributeString("val", val);
}
this.WriteXmlAttributesEnd(true);
};
}
function CCommandsType()
{
this.ctPenXML = 0;
this.ctPenColor = 1;
this.ctPenAlpha = 2;
this.ctPenSize = 3;
this.ctPenDashStyle = 4;
this.ctPenLineStartCap = 5;
this.ctPenLineEndCap = 6;
this.ctPenLineJoin = 7;
this.ctPenDashPatern = 8;
this.ctPenDashPatternCount = 9;
this.ctPenDashOffset = 10;
this.ctPenAlign = 11;
this.ctPenMiterLimit = 12;
// brush
this.ctBrushXML = 20;
this.ctBrushType = 21;
this.ctBrushColor1 = 22;
this.ctBrushColor2 = 23;
this.ctBrushAlpha1 = 24;
this.ctBrushAlpha2 = 25;
this.ctBrushTexturePath = 26;
this.ctBrushTextureAlpha = 27;
this.ctBrushTextureMode = 28;
this.ctBrushRectable = 29;
this.ctBrushRectableEnabled = 30;
this.ctBrushGradient = 31;
// font
this.ctFontXML = 40;
this.ctFontName = 41;
this.ctFontSize = 42;
this.ctFontStyle = 43;
this.ctFontPath = 44;
this.ctFontGID = 45;
this.ctFontCharSpace = 46;
// shadow
this.ctShadowXML = 50;
this.ctShadowVisible = 51;
this.ctShadowDistanceX = 52;
this.ctShadowDistanceY = 53;
this.ctShadowBlurSize = 54;
this.ctShadowColor = 55;
this.ctShadowAlpha = 56;
// edge
this.ctEdgeXML = 70;
this.ctEdgeVisible = 71;
this.ctEdgeDistance = 72;
this.ctEdgeColor = 73;
this.ctEdgeAlpha = 74;
// text
this.ctDrawText = 80;
this.ctDrawTextEx = 81;
this.ctDrawTextCode = 82;
this.ctDrawTextCodeGid = 83;
// pathcommands
this.ctPathCommandMoveTo = 91;
this.ctPathCommandLineTo = 92;
this.ctPathCommandLinesTo = 93;
this.ctPathCommandCurveTo = 94;
this.ctPathCommandCurvesTo = 95;
this.ctPathCommandArcTo = 96;
this.ctPathCommandClose = 97;
this.ctPathCommandEnd = 98;
this.ctDrawPath = 99;
this.ctPathCommandStart = 100;
this.ctPathCommandGetCurrentPoint = 101;
this.ctPathCommandText = 102;
this.ctPathCommandTextEx = 103;
// image
this.ctDrawImage = 110;
this.ctDrawImageFromFile = 111;
this.ctSetParams = 120;
this.ctBeginCommand = 121;
this.ctEndCommand = 122;
this.ctSetTransform = 130;
this.ctResetTransform = 131;
this.ctClipMode = 140;
this.ctCommandLong1 = 150;
this.ctCommandDouble1 = 151;
this.ctCommandString1 = 152;
this.ctCommandLong2 = 153;
this.ctCommandDouble2 = 154;
this.ctCommandString2 = 155;
this.ctHyperlink = 160;
this.ctLink = 161;
this.ctFormField = 162;
this.ctPageWidth = 200;
this.ctPageHeight = 201;
this.ctPageStart = 202;
this.ctPageEnd = 203;
this.ctError = 255;
}
var CommandType = new CCommandsType();
var MetaBrushType = {
Solid : 0,
Gradient : 1,
Texture : 2
};
// 0 - dash
// 1 - dashDot
// 2 - dot
// 3 - lgDash
// 4 - lgDashDot
// 5 - lgDashDotDot
// 6 - solid
// 7 - sysDash
// 8 - sysDashDot
// 9 - sysDashDotDot
// 10- sysDot
var DashPatternPresets = [
[4, 3],
[4, 3, 1, 3],
[1, 3],
[8, 3],
[8, 3, 1, 3],
[8, 3, 1, 3, 1, 3],
undefined,
[3, 1],
[3, 1, 1, 1],
[3, 1, 1, 1, 1, 1],
[1, 1]
];
function CMetafileFontPicker(manager)
{
this.Manager = manager; // в идеале - кэш измерятеля. тогда ни один шрифт не будет загружен заново
if (!this.Manager)
{
this.Manager = new AscFonts.CFontManager();
this.Manager.Initialize(false)
}
this.FontsInCache = {};
this.LastPickFont = null;
this.LastPickFontNameOrigin = "";
this.LastPickFontName = "";
this.Metafile = null; // класс, которому будет подменяться шрифт
this.SetFont = function(setFont)
{
var name = setFont.FontFamily.Name;
var size = setFont.FontSize;
var style = 0;
if (setFont.Italic == true)
style += 2;
if (setFont.Bold == true)
style += 1;
var name_check = name + "_" + style;
if (this.FontsInCache[name_check])
{
this.LastPickFont = this.FontsInCache[name_check];
}
else
{
var font = g_fontApplication.GetFontFileWeb(name, style);
var font_name_index = AscFonts.g_map_font_index[font.m_wsFontName];
var fontId = AscFonts.g_font_infos[font_name_index].GetFontID(AscCommon.g_font_loader, style);
var test_id = fontId.id + fontId.faceIndex + size;
var cache = this.Manager.m_oFontsCache;
this.LastPickFont = cache.Fonts[test_id];
if (!this.LastPickFont)
this.LastPickFont = cache.Fonts[test_id + "nbold"];
if (!this.LastPickFont)
this.LastPickFont = cache.Fonts[test_id + "nitalic"];
if (!this.LastPickFont)
this.LastPickFont = cache.Fonts[test_id + "nboldnitalic"];
if (!this.LastPickFont)
{
// такого при правильном кэше быть не должно
if (window["NATIVE_EDITOR_ENJINE"] && fontId.file.Status != 0)
{
fontId.file.LoadFontNative();
}
this.LastPickFont = cache.LockFont(fontId.file.stream_index, fontId.id, fontId.faceIndex, size, "", this.Manager);
}
this.FontsInCache[name_check] = this.LastPickFont;
}
this.LastPickFontNameOrigin = name;
this.LastPickFontName = name;
this.Metafile.SetFont(setFont, true);
};
this.FillTextCode = function(glyph)
{
if (this.LastPickFont && this.LastPickFont.GetGIDByUnicode(glyph))
{
if (this.LastPickFontName != this.LastPickFontNameOrigin)
{
this.LastPickFontName = this.LastPickFontNameOrigin;
this.Metafile.SetFontName(this.LastPickFontName);
}
}
else
{
var name = AscFonts.FontPickerByCharacter.getFontBySymbol(glyph);
if (name != this.LastPickFontName)
{
this.LastPickFontName = name;
this.Metafile.SetFontName(this.LastPickFontName);
}
}
};
}
function CMetafile(width, height)
{
this.Width = width;
this.Height = height;
this.m_oPen = new CPen();
this.m_oBrush = new CBrush();
this.m_oFont =
{
Name : "",
FontSize : -1,
Style : -1
};
// чтобы выставилось в первый раз
this.m_oPen.Color.R = -1;
this.m_oBrush.Color1.R = -1;
this.m_oBrush.Color2.R = -1;
this.m_oTransform = new CMatrix();
this.m_arrayCommands = [];
this.Memory = null;
this.VectorMemoryForPrint = null;
this.BrushType = MetaBrushType.Solid;
// RFonts
this.m_oTextPr = null;
this.m_oGrFonts = new CGrRFonts();
// просто чтобы не создавать каждый раз
this.m_oFontSlotFont = new CFontSetup();
this.LastFontOriginInfo = {Name : "", Replace : null};
this.m_oFontTmp = { FontFamily : { Name : "arial" }, Bold : false, Italic : false };
this.StartOffset = 0;
this.m_bIsPenDash = false;
this.FontPicker = null;
}
CMetafile.prototype =
{
// pen methods
p_color : function(r, g, b, a)
{
if (this.m_oPen.Color.R != r || this.m_oPen.Color.G != g || this.m_oPen.Color.B != b)
{
this.m_oPen.Color.R = r;
this.m_oPen.Color.G = g;
this.m_oPen.Color.B = b;
var value = b << 16 | g << 8 | r;
this.Memory.WriteByte(CommandType.ctPenColor);
this.Memory.WriteLong(value);
}
if (this.m_oPen.Color.A != a)
{
this.m_oPen.Color.A = a;
this.Memory.WriteByte(CommandType.ctPenAlpha);
this.Memory.WriteByte(a);
}
},
p_width : function(w)
{
var val = w / 1000;
if (this.m_oPen.Size != val)
{
this.m_oPen.Size = val;
this.Memory.WriteByte(CommandType.ctPenSize);
this.Memory.WriteDouble(val);
}
},
p_dash : function(params)
{
var bIsDash = (params && (params.length > 0)) ? true : false;
if (false == this.m_bIsPenDash && bIsDash == this.m_bIsPenDash)
return;
this.m_bIsPenDash = bIsDash;
if (!this.m_bIsPenDash)
{
this.Memory.WriteByte(CommandType.ctPenDashStyle);
this.Memory.WriteByte(0);
}
else
{
this.Memory.WriteByte(CommandType.ctPenDashStyle);
this.Memory.WriteByte(5);
this.Memory.WriteLong(params.length);
for (var i = 0; i < params.length; i++)
{
this.Memory.WriteDouble(params[i]);
}
}
},
// brush methods
b_color1 : function(r, g, b, a)
{
if (this.BrushType != MetaBrushType.Solid)
{
this.Memory.WriteByte(CommandType.ctBrushType);
this.Memory.WriteLong(1000);
this.BrushType = MetaBrushType.Solid;
}
if (this.m_oBrush.Color1.R != r || this.m_oBrush.Color1.G != g || this.m_oBrush.Color1.B != b)
{
this.m_oBrush.Color1.R = r;
this.m_oBrush.Color1.G = g;
this.m_oBrush.Color1.B = b;
var value = b << 16 | g << 8 | r;
this.Memory.WriteByte(CommandType.ctBrushColor1);
this.Memory.WriteLong(value);
}
if (this.m_oBrush.Color1.A != a)
{
this.m_oBrush.Color1.A = a;
this.Memory.WriteByte(CommandType.ctBrushAlpha1);
this.Memory.WriteByte(a);
}
},
b_color2 : function(r, g, b, a)
{
if (this.m_oBrush.Color2.R != r || this.m_oBrush.Color2.G != g || this.m_oBrush.Color2.B != b)
{
this.m_oBrush.Color2.R = r;
this.m_oBrush.Color2.G = g;
this.m_oBrush.Color2.B = b;
var value = b << 16 | g << 8 | r;
this.Memory.WriteByte(CommandType.ctBrushColor2);
this.Memory.WriteLong(value);
}
if (this.m_oBrush.Color2.A != a)
{
this.m_oBrush.Color2.A = a;
this.Memory.WriteByte(CommandType.ctBrushAlpha2);
this.Memory.WriteByte(a);
}
},
put_brushTexture : function(src, mode)
{
var isLocalUse = true;
if (window["AscDesktopEditor"] && window["AscDesktopEditor"]["IsLocalFile"] && window["AscDesktopEditor"]["IsFilePrinting"])
isLocalUse = ((!window["AscDesktopEditor"]["IsLocalFile"]()) && window["AscDesktopEditor"]["IsFilePrinting"]()) ? false : true;
if (window["AscDesktopEditor"] && !isLocalUse)
{
if ((undefined !== window["AscDesktopEditor"]["CryptoMode"]) && (0 < window["AscDesktopEditor"]["CryptoMode"]))
isLocalUse = true;
}
if (this.BrushType != MetaBrushType.Texture)
{
this.Memory.WriteByte(CommandType.ctBrushType);
this.Memory.WriteLong(3008);
this.BrushType = MetaBrushType.Texture;
}
this.m_oBrush.Color1.R = -1;
this.m_oBrush.Color1.G = -1;
this.m_oBrush.Color1.B = -1;
this.m_oBrush.Color1.A = -1;
this.Memory.WriteByte(CommandType.ctBrushTexturePath);
var _src = src;
var srcLocal = AscCommon.g_oDocumentUrls.getLocal(_src);
if (srcLocal && isLocalUse)
{
_src = srcLocal;
}
this.Memory.WriteString(_src);
this.Memory.WriteByte(CommandType.ctBrushTextureMode);
this.Memory.WriteByte(mode);
},
put_BrushTextureAlpha : function(alpha)
{
var write = alpha;
if (null == alpha || undefined == alpha)
write = 255;
this.Memory.WriteByte(CommandType.ctBrushTextureAlpha);
this.Memory.WriteByte(write);
},
put_BrushGradient : function(gradFill, points, transparent)
{
this.BrushType = MetaBrushType.Gradient;
this.Memory.WriteByte(CommandType.ctBrushGradient);
this.Memory.WriteByte(AscCommon.g_nodeAttributeStart);
if (gradFill.path != null && (gradFill.lin == null || gradFill.lin == undefined))
{
this.Memory.WriteByte(1);
this.Memory.WriteByte(gradFill.path);
this.Memory.WriteDouble(points.x0);
this.Memory.WriteDouble(points.y0);
this.Memory.WriteDouble(points.x1);
this.Memory.WriteDouble(points.y1);
this.Memory.WriteDouble(points.r0);
this.Memory.WriteDouble(points.r1);
}
else
{
this.Memory.WriteByte(0);
if (null == gradFill.lin)
{
this.Memory.WriteLong(90 * 60000);
this.Memory.WriteBool(false);
}
else
{
this.Memory.WriteLong(gradFill.lin.angle);
this.Memory.WriteBool(gradFill.lin.scale);
}
this.Memory.WriteDouble(points.x0);
this.Memory.WriteDouble(points.y0);
this.Memory.WriteDouble(points.x1);
this.Memory.WriteDouble(points.y1);
}
var _colors = gradFill.colors;
var firstColor = null;
var lastColor = null;
if (_colors.length > 0)
{
if (_colors[0].pos > 0)
{
firstColor = {
color : {
RGBA : {
R : _colors[0].color.RGBA.R,
G : _colors[0].color.RGBA.G,
B : _colors[0].color.RGBA.B,
A : _colors[0].color.RGBA.A
}
},
pos : 0
};
_colors.unshift(firstColor);
}
var posLast = _colors.length - 1;
if (_colors[posLast].pos < 100000)
{
lastColor = {
color : {
RGBA : {
R : _colors[posLast].color.RGBA.R,
G : _colors[posLast].color.RGBA.G,
B : _colors[posLast].color.RGBA.B,
A : _colors[posLast].color.RGBA.A
}
},
pos : 100000
};
_colors.push(lastColor);
}
}
this.Memory.WriteByte(2);
this.Memory.WriteLong(_colors.length);
for (var i = 0; i < _colors.length; i++)
{
this.Memory.WriteLong(_colors[i].pos);
this.Memory.WriteByte(_colors[i].color.RGBA.R);
this.Memory.WriteByte(_colors[i].color.RGBA.G);
this.Memory.WriteByte(_colors[i].color.RGBA.B);
if (null == transparent)
this.Memory.WriteByte(_colors[i].color.RGBA.A);
else
this.Memory.WriteByte(transparent);
}
if (firstColor)
_colors.shift();
if (lastColor)
_colors.pop();
this.Memory.WriteByte(AscCommon.g_nodeAttributeEnd);
},
transform : function(sx, shy, shx, sy, tx, ty)
{
if (this.m_oTransform.sx != sx || this.m_oTransform.shx != shx || this.m_oTransform.shy != shy ||
this.m_oTransform.sy != sy || this.m_oTransform.tx != tx || this.m_oTransform.ty != ty)
{
this.m_oTransform.sx = sx;
this.m_oTransform.shx = shx;
this.m_oTransform.shy = shy;
this.m_oTransform.sy = sy;
this.m_oTransform.tx = tx;
this.m_oTransform.ty = ty;
this.Memory.WriteByte(CommandType.ctSetTransform);
this.Memory.WriteDouble(sx);
this.Memory.WriteDouble(shy);
this.Memory.WriteDouble(shx);
this.Memory.WriteDouble(sy);
this.Memory.WriteDouble(tx);
this.Memory.WriteDouble(ty);
}
},
// path commands
_s : function()
{
if (this.VectorMemoryForPrint != null)
this.VectorMemoryForPrint.ClearNoAttack();
var _memory = (null == this.VectorMemoryForPrint) ? this.Memory : this.VectorMemoryForPrint;
_memory.WriteByte(CommandType.ctPathCommandStart);
},
_e : function()
{
// тут всегда напрямую в Memory
this.Memory.WriteByte(CommandType.ctPathCommandEnd);
},
_z : function()
{
var _memory = (null == this.VectorMemoryForPrint) ? this.Memory : this.VectorMemoryForPrint;
_memory.WriteByte(CommandType.ctPathCommandClose);
},
_m : function(x, y)
{
var _memory = (null == this.VectorMemoryForPrint) ? this.Memory : this.VectorMemoryForPrint;
_memory.WriteByte(CommandType.ctPathCommandMoveTo);
_memory.WriteDouble(x);
_memory.WriteDouble(y);
},
_l : function(x, y)
{
var _memory = (null == this.VectorMemoryForPrint) ? this.Memory : this.VectorMemoryForPrint;
_memory.WriteByte(CommandType.ctPathCommandLineTo);
_memory.WriteDouble(x);
_memory.WriteDouble(y);
},
_c : function(x1, y1, x2, y2, x3, y3)
{
var _memory = (null == this.VectorMemoryForPrint) ? this.Memory : this.VectorMemoryForPrint;
_memory.WriteByte(CommandType.ctPathCommandCurveTo);
_memory.WriteDouble(x1);
_memory.WriteDouble(y1);
_memory.WriteDouble(x2);
_memory.WriteDouble(y2);
_memory.WriteDouble(x3);
_memory.WriteDouble(y3);
},
_c2 : function(x1, y1, x2, y2)
{
var _memory = (null == this.VectorMemoryForPrint) ? this.Memory : this.VectorMemoryForPrint;
_memory.WriteByte(CommandType.ctPathCommandCurveTo);
_memory.WriteDouble(x1);
_memory.WriteDouble(y1);
_memory.WriteDouble(x1);
_memory.WriteDouble(y1);
_memory.WriteDouble(x2);
_memory.WriteDouble(y2);
},
ds : function()
{
if (null == this.VectorMemoryForPrint)
{
this.Memory.WriteByte(CommandType.ctDrawPath);
this.Memory.WriteLong(1);
}
else
{
this.Memory.Copy(this.VectorMemoryForPrint, 0, this.VectorMemoryForPrint.pos);
this.Memory.WriteByte(CommandType.ctDrawPath);
this.Memory.WriteLong(1);
}
},
df : function()
{
if (null == this.VectorMemoryForPrint)
{
this.Memory.WriteByte(CommandType.ctDrawPath);
this.Memory.WriteLong(256);
}
else
{
this.Memory.Copy(this.VectorMemoryForPrint, 0, this.VectorMemoryForPrint.pos);
this.Memory.WriteByte(CommandType.ctDrawPath);
this.Memory.WriteLong(256);
}
},
WriteVectorMemoryForPrint : function()
{
if (null != this.VectorMemoryForPrint)
{
this.Memory.Copy(this.VectorMemoryForPrint, 0, this.VectorMemoryForPrint.pos);
}
},
drawpath : function(type)
{
if (null == this.VectorMemoryForPrint)
{
this.Memory.WriteByte(CommandType.ctDrawPath);
this.Memory.WriteLong(type);
}
else
{
this.Memory.Copy(this.VectorMemoryForPrint, 0, this.VectorMemoryForPrint.pos);
this.Memory.WriteByte(CommandType.ctDrawPath);
this.Memory.WriteLong(type);
}
},
// canvas state
save : function()
{
},
restore : function()
{
},
clip : function()
{
},
// images
drawImage : function(img, x, y, w, h, isUseOriginUrl)
{
var isLocalUse = true;
if (window["AscDesktopEditor"] && window["AscDesktopEditor"]["IsLocalFile"] && window["AscDesktopEditor"]["IsFilePrinting"])
isLocalUse = ((!window["AscDesktopEditor"]["IsLocalFile"]()) && window["AscDesktopEditor"]["IsFilePrinting"]()) ? false : true;
if (window["AscDesktopEditor"] && !isLocalUse)
{
if ((undefined !== window["AscDesktopEditor"]["CryptoMode"]) && (0 < window["AscDesktopEditor"]["CryptoMode"]))
isLocalUse = true;
}
if (!window.editor)
{
// excel
this.Memory.WriteByte(CommandType.ctDrawImageFromFile);
var imgLocal = AscCommon.g_oDocumentUrls.getLocal(img);
if (imgLocal && isLocalUse && (true !== isUseOriginUrl))
{
this.Memory.WriteString2(imgLocal);
}
else
{
this.Memory.WriteString2(img);
}
this.Memory.WriteDouble(x);
this.Memory.WriteDouble(y);
this.Memory.WriteDouble(w);
this.Memory.WriteDouble(h);
return;
}
var _src = "";
if (!window["NATIVE_EDITOR_ENJINE"] && (true !== isUseOriginUrl))
{
var _img = window.editor.ImageLoader.map_image_index[img];
if (_img == undefined || _img.Image == null)
return;
_src = _img.src;
}
else
{
_src = img;
}
var srcLocal = AscCommon.g_oDocumentUrls.getLocal(_src);
if (srcLocal && isLocalUse)
{
_src = srcLocal;
}
this.Memory.WriteByte(CommandType.ctDrawImageFromFile);
this.Memory.WriteString2(_src);
this.Memory.WriteDouble(x);
this.Memory.WriteDouble(y);
this.Memory.WriteDouble(w);
this.Memory.WriteDouble(h);
},
SetFontName : function(name)
{
var fontinfo = g_fontApplication.GetFontInfo(name, 0, this.LastFontOriginInfo);
if (this.m_oFont.Name != fontinfo.Name)
{
this.m_oFont.Name = fontinfo.Name;
this.Memory.WriteByte(CommandType.ctFontName);
this.Memory.WriteString(this.m_oFont.Name);
}
},
SetFont : function(font, isFromPicker)
{
if (this.FontPicker && !isFromPicker)
return this.FontPicker.SetFont(font);
if (null == font)
return;
var style = 0;
if (font.Italic == true)
style += 2;
if (font.Bold == true)
style += 1;
var fontinfo = g_fontApplication.GetFontInfo(font.FontFamily.Name, style, this.LastFontOriginInfo);
//style = fontinfo.GetBaseStyle(style);
if (this.m_oFont.Name != fontinfo.Name)
{
this.m_oFont.Name = fontinfo.Name;
this.Memory.WriteByte(CommandType.ctFontName);
this.Memory.WriteString(this.m_oFont.Name);
}
if (this.m_oFont.FontSize != font.FontSize)
{
this.m_oFont.FontSize = font.FontSize;
this.Memory.WriteByte(CommandType.ctFontSize);
this.Memory.WriteDouble(this.m_oFont.FontSize);
}
if (this.m_oFont.Style != style)
{
this.m_oFont.Style = style;
this.Memory.WriteByte(CommandType.ctFontStyle);
this.Memory.WriteLong(style);
}
},
FillText : function(x, y, text)
{
if (1 == text.length)
return this.FillTextCode(x, y, text.charCodeAt(0));
this.Memory.WriteByte(CommandType.ctDrawText);
this.Memory.WriteString(text);
this.Memory.WriteDouble(x);
this.Memory.WriteDouble(y);
},
FillTextCode : function(x, y, code)
{
var _code = code;
if (null != this.LastFontOriginInfo.Replace)
_code = g_fontApplication.GetReplaceGlyph(_code, this.LastFontOriginInfo.Replace);
if (this.FontPicker)
this.FontPicker.FillTextCode(_code);
this.Memory.WriteByte(CommandType.ctDrawText);
this.Memory.WriteStringBySymbol(_code);
this.Memory.WriteDouble(x);
this.Memory.WriteDouble(y);
},
tg : function(gid, x, y, codepoints)
{
/*
var _old_pos = this.Memory.pos;
g_fontApplication.LoadFont(this.m_oFont.Name, AscCommon.g_font_loader, AscCommon.g_oTextMeasurer.m_oManager, this.m_oFont.FontSize, Math.max(this.m_oFont.Style, 0), 72, 72);
AscCommon.g_oTextMeasurer.m_oManager.LoadStringPathCode(gid, true, x, y, this);
// start (1) + draw(1) + typedraw(4) + end(1) = 7!
if ((this.Memory.pos - _old_pos) < 8)
this.Memory.pos = _old_pos;
*/
this.Memory.WriteByte(CommandType.ctDrawTextCodeGid);
this.Memory.WriteLong(gid);
this.Memory.WriteDouble(x);
this.Memory.WriteDouble(y);
var count = codepoints ? codepoints.length : 0;
this.Memory.WriteLong(count);
for (var i = 0; i < count; i++)
this.Memory.WriteLong(codepoints[i]);
},
charspace : function(space)
{
},
beginCommand : function(command)
{
this.Memory.WriteByte(CommandType.ctBeginCommand);
this.Memory.WriteLong(command);
},
endCommand : function(command)
{
if (32 == command)
{
if (null == this.VectorMemoryForPrint)
{
this.Memory.WriteByte(CommandType.ctEndCommand);
this.Memory.WriteLong(command);
}
else
{
this.Memory.Copy(this.VectorMemoryForPrint, 0, this.VectorMemoryForPrint.pos);
this.Memory.WriteByte(CommandType.ctEndCommand);
this.Memory.WriteLong(command);
}
return;
}
this.Memory.WriteByte(CommandType.ctEndCommand);
this.Memory.WriteLong(command);
},
put_PenLineJoin : function(_join)
{
this.Memory.WriteByte(CommandType.ctPenLineJoin);
this.Memory.WriteByte(_join & 0xFF);
},
put_TextureBounds : function(x, y, w, h)
{
this.Memory.WriteByte(CommandType.ctBrushRectable);
this.Memory.WriteDouble(x);
this.Memory.WriteDouble(y);
this.Memory.WriteDouble(w);
this.Memory.WriteDouble(h);
},
put_TextureBoundsEnabled : function(bIsEnabled)
{
this.Memory.WriteByte(CommandType.ctBrushRectableEnabled);
this.Memory.WriteBool(bIsEnabled);
},
SetFontInternal : function(name, size, style)
{
// TODO: remove m_oFontSlotFont
var _lastFont = this.m_oFontSlotFont;
_lastFont.Name = name;
_lastFont.Size = size;
_lastFont.Bold = (style & AscFonts.FontStyle.FontStyleBold) ? true : false;
_lastFont.Italic = (style & AscFonts.FontStyle.FontStyleItalic) ? true : false;
this.m_oFontTmp.FontFamily.Name = _lastFont.Name;
this.m_oFontTmp.Bold = _lastFont.Bold;
this.m_oFontTmp.Italic = _lastFont.Italic;
this.m_oFontTmp.FontSize = _lastFont.Size;
this.SetFont(this.m_oFontTmp);
},
SetFontSlot : function(slot, fontSizeKoef)
{
var _rfonts = this.m_oGrFonts;
var _lastFont = this.m_oFontSlotFont;
switch (slot)
{
case fontslot_ASCII:
{
_lastFont.Name = _rfonts.Ascii.Name;
_lastFont.Size = this.m_oTextPr.FontSize;
_lastFont.Bold = this.m_oTextPr.Bold;
_lastFont.Italic = this.m_oTextPr.Italic;
break;
}
case fontslot_CS:
{
_lastFont.Name = _rfonts.CS.Name;
_lastFont.Size = this.m_oTextPr.FontSizeCS;
_lastFont.Bold = this.m_oTextPr.BoldCS;
_lastFont.Italic = this.m_oTextPr.ItalicCS;
break;
}
case fontslot_EastAsia:
{
_lastFont.Name = _rfonts.EastAsia.Name;
_lastFont.Size = this.m_oTextPr.FontSize;
_lastFont.Bold = this.m_oTextPr.Bold;
_lastFont.Italic = this.m_oTextPr.Italic;
break;
}
case fontslot_HAnsi:
default:
{
_lastFont.Name = _rfonts.HAnsi.Name;
_lastFont.Size = this.m_oTextPr.FontSize;
_lastFont.Bold = this.m_oTextPr.Bold;
_lastFont.Italic = this.m_oTextPr.Italic;
break;
}
}
if (undefined !== fontSizeKoef)
_lastFont.Size *= fontSizeKoef;
this.m_oFontTmp.FontFamily.Name = _lastFont.Name;
this.m_oFontTmp.Bold = _lastFont.Bold;
this.m_oFontTmp.Italic = _lastFont.Italic;
this.m_oFontTmp.FontSize = _lastFont.Size;
this.SetFont(this.m_oFontTmp);
},
AddHyperlink : function(x, y, w, h, url, tooltip)
{
this.Memory.WriteByte(CommandType.ctHyperlink);
this.Memory.WriteDouble(x);
this.Memory.WriteDouble(y);
this.Memory.WriteDouble(w);
this.Memory.WriteDouble(h);
this.Memory.WriteString(url);
this.Memory.WriteString(tooltip);
},
AddLink : function(x, y, w, h, dx, dy, dPage)
{
this.Memory.WriteByte(CommandType.ctLink);
this.Memory.WriteDouble(x);
this.Memory.WriteDouble(y);
this.Memory.WriteDouble(w);
this.Memory.WriteDouble(h);
this.Memory.WriteDouble(dx);
this.Memory.WriteDouble(dy);
this.Memory.WriteLong(dPage);
},
AddFormField : function(nX, nY, nW, nH, nBaseLineOffset, oForm)
{
if (!oForm)
return;
this.Memory.WriteByte(CommandType.ctFormField);
var nStartPos = this.Memory.GetCurPosition();
this.Memory.Skip(4);
this.Memory.WriteDouble(nX);
this.Memory.WriteDouble(nY);
this.Memory.WriteDouble(nW);
this.Memory.WriteDouble(nH);
this.Memory.WriteDouble(nBaseLineOffset);
var nFlagPos = this.Memory.GetCurPosition();
this.Memory.Skip(4);
var nFlag = 0;
var oFormPr = oForm.GetFormPr();
var sFormKey = oFormPr.GetKey();
if (sFormKey)
{
nFlag |= 1;
this.Memory.WriteString(sFormKey);
}
var sHelpText = oFormPr.GetHelpText();
if (sHelpText)
{
nFlag |= (1 << 1);
this.Memory.WriteString(sHelpText);
}
if (oFormPr.GetRequired())
nFlag |= (1 << 2);
if (oForm.IsPlaceHolder())
nFlag |= (1 << 3);
// 7-ой и 8-ой биты зарезервированы для бордера
var oBorder = oFormPr.GetBorder();
if (oBorder && !oBorder.IsNone())
{
nFlag |= (1 << 6);
var oColor = oBorder.GetColor();
this.Memory.WriteLong(1);
this.Memory.WriteDouble(oBorder.GetWidth());
this.Memory.WriteByte(oColor.r);
this.Memory.WriteByte(oColor.g);
this.Memory.WriteByte(oColor.b);
this.Memory.WriteByte(0x255);
}
var oParagraph = oForm.GetParagraph();
var oShd = oFormPr.GetShd();
if (oParagraph && oShd && !oShd.IsNil())
{
nFlag |= (1 << 9);
var oColor = oShd.GetSimpleColor(oParagraph.GetTheme(), oParagraph.GetColorMap());
this.Memory.WriteByte(oColor.r);
this.Memory.WriteByte(oColor.g);
this.Memory.WriteByte(oColor.b);
this.Memory.WriteByte(0x255);
}
if (oParagraph && AscCommon.align_Left !== oParagraph.GetParagraphAlign())
{
nFlag |= (1 << 10);
this.Memory.WriteByte(oParagraph.GetParagraphAlign());
}
// 0 - Unknown
// 1 - Text
// 2 - ComboBox/DropDownList
// 3 - CheckBox/RadioButton
// 4 - Picture
if (oForm.IsTextForm())
{
this.Memory.WriteLong(1);
var oTextFormPr = oForm.GetTextFormPr();
if (oTextFormPr.Comb)
nFlag |= (1 << 20);
if (oTextFormPr.MaxCharacters > 0)
{
nFlag |= (1 << 21);
this.Memory.WriteLong(oTextFormPr.MaxCharacters);
}
var sValue = oForm.GetSelectedText(true);
if (sValue)
{
nFlag |= (1 << 22);
this.Memory.WriteString(sValue);
}
if (oTextFormPr.MultiLine && oForm.IsFixedForm())
nFlag |= (1 << 23);
if (oTextFormPr.AutoFit)
nFlag |= (1 << 24);
var sPlaceHolderText = oForm.GetPlaceholderText();
if (sPlaceHolderText)
{
nFlag |= (1 << 25);
this.Memory.WriteString(sPlaceHolderText);
}
}
else if (oForm.IsComboBox() || oForm.IsDropDownList())
{
this.Memory.WriteLong(2);
var isComboBox = oForm.IsComboBox();
var oFormPr = isComboBox ? oForm.GetComboBoxPr() : oForm.GetDropDownListPr();
if (isComboBox)
nFlag |= (1 << 20);
var sValue = oForm.GetSelectedText(true);
var nSelectedIndex = -1;
// Обработка "Choose an item"
var nItemsCount = oFormPr.GetItemsCount();
if (nItemsCount > 0 && AscCommon.translateManager.getValue("Choose an item") === oFormPr.GetItemDisplayText(0))
{
this.Memory.WriteLong(nItemsCount - 1);
for (var nIndex = 1; nIndex < nItemsCount; ++nIndex)
{
var sItemValue = oFormPr.GetItemDisplayText(nIndex);
if (sItemValue === sValue)
nSelectedIndex = nIndex;
this.Memory.WriteString(sItemValue);
}
}
else
{
this.Memory.WriteLong(nItemsCount);
for (var nIndex = 0; nIndex < nItemsCount; ++nIndex)
{
var sItemValue = oFormPr.GetItemDisplayText(nIndex);
if (sItemValue === sValue)
nSelectedIndex = nIndex;
this.Memory.WriteString(sItemValue);
}
}
this.Memory.WriteLong(nSelectedIndex);
if (sValue)
{
nFlag |= (1 << 22);
this.Memory.WriteString(sValue);
}
var sPlaceHolderText = oForm.GetPlaceholderText();
if (sPlaceHolderText)
{
nFlag |= (1 << 23);
this.Memory.WriteString(sPlaceHolderText);
}
}
else if (oForm.IsCheckBox())
{
this.Memory.WriteLong(3);
var oCheckBoxPr = oForm.GetCheckBoxPr();
if (oCheckBoxPr.GetChecked())
nFlag |= (1 << 20);
var nCheckedSymbol = oCheckBoxPr.GetCheckedSymbol();
var nUncheckedSymbol = oCheckBoxPr.GetUncheckedSymbol();
var nType = 0x0000;
if (0x2611 === nCheckedSymbol && 0x2610 === nUncheckedSymbol)
nType = 0x0001;
else if (0x25C9 === nCheckedSymbol && 0x25CB === nUncheckedSymbol)
nType = 0x0002;
var sCheckedFont = oCheckBoxPr.GetCheckedFont();
if (AscCommon.IsAscFontSupport(sCheckedFont, nCheckedSymbol))
sCheckedFont = "ASCW3";
var sUncheckedFont = oCheckBoxPr.GetUncheckedFont();
if (AscCommon.IsAscFontSupport(sUncheckedFont, nUncheckedSymbol))
sUncheckedFont = "ASCW3";
this.Memory.WriteLong(nType);
this.Memory.WriteLong(nCheckedSymbol);
this.Memory.WriteString(sCheckedFont);
this.Memory.WriteLong(nUncheckedSymbol);
this.Memory.WriteString(sUncheckedFont);
var sGroupName = oCheckBoxPr.GetGroupKey();
if (sGroupName)
{
nFlag |= (1 << 21);
this.Memory.WriteString(sGroupName);
}
}
else if (oForm.IsPicture())
{
this.Memory.WriteLong(4);
var oPicturePr = oForm.GetPictureFormPr();
if (oPicturePr.IsConstantProportions())
nFlag |= (1 << 20);
if (oPicturePr.IsRespectBorders())
nFlag |= (1 << 21);
nFlag |= ((oPicturePr.GetScaleFlag() & 0xF) << 24);
this.Memory.WriteLong(oPicturePr.GetShiftX() * 1000);
this.Memory.WriteLong(oPicturePr.GetShiftY() * 1000);
if (!oForm.IsPlaceHolder())
{
var arrDrawings = oForm.GetAllDrawingObjects();
if (arrDrawings.length > 0 && arrDrawings[0].IsPicture() && arrDrawings[0].GraphicObj.blipFill)
{
var isLocalUse = true;
if (window["AscDesktopEditor"] && window["AscDesktopEditor"]["IsLocalFile"] && window["AscDesktopEditor"]["IsFilePrinting"])
isLocalUse = ((!window["AscDesktopEditor"]["IsLocalFile"]()) && window["AscDesktopEditor"]["IsFilePrinting"]()) ? false : true;
if (window["AscDesktopEditor"] && !isLocalUse)
{
if ((undefined !== window["AscDesktopEditor"]["CryptoMode"]) && (0 < window["AscDesktopEditor"]["CryptoMode"]))
isLocalUse = true;
}
var src = AscCommon.getFullImageSrc2(arrDrawings[0].GraphicObj.blipFill.RasterImageId);
var srcLocal = AscCommon.g_oDocumentUrls.getLocal(src);
if (srcLocal && isLocalUse)
src = srcLocal;
nFlag |= (1 << 22);
this.Memory.WriteString(src);
}
}
}
else
{
this.Memory.WriteLong(0);
}
var nEndPos = this.Memory.GetCurPosition();
this.Memory.Seek(nFlagPos);
this.Memory.WriteLong(nFlag);
this.Memory.Seek(nStartPos);
this.Memory.WriteLong(nEndPos - nStartPos);
this.Memory.Seek(nEndPos);
}
};
function CDocumentRenderer()
{
this.m_arrayPages = [];
this.m_lPagesCount = 0;
//this.DocumentInfo = "";
this.Memory = new CMemory();
this.VectorMemoryForPrint = null;
this.ClipManager = new CClipManager();
this.ClipManager.BaseObject = this;
this.RENDERER_PDF_FLAG = true;
this.ArrayPoints = null;
this.GrState = new CGrState();
this.GrState.Parent = this;
this.m_oPen = null;
this.m_oBrush = null;
this.m_oTransform = null;
this._restoreDumpedVectors = null;
this.m_oBaseTransform = null;
this.UseOriginImageUrl = false;
this.FontPicker = null;
this.isPrintMode = false;
}
CDocumentRenderer.prototype =
{
InitPicker : function(_manager)
{
this.FontPicker = new CMetafileFontPicker(_manager);
},
SetBaseTransform : function(_matrix)
{
this.m_oBaseTransform = _matrix;
},
BeginPage : function(width, height)
{
this.m_arrayPages[this.m_arrayPages.length] = new CMetafile(width, height);
this.m_lPagesCount = this.m_arrayPages.length;
this.m_arrayPages[this.m_lPagesCount - 1].Memory = this.Memory;
this.m_arrayPages[this.m_lPagesCount - 1].StartOffset = this.Memory.pos;
this.m_arrayPages[this.m_lPagesCount - 1].VectorMemoryForPrint = this.VectorMemoryForPrint;
this.m_arrayPages[this.m_lPagesCount - 1].FontPicker = this.FontPicker;
if (this.FontPicker)
this.m_arrayPages[this.m_lPagesCount - 1].FontPicker.Metafile = this.m_arrayPages[this.m_lPagesCount - 1];
this.Memory.WriteByte(CommandType.ctPageStart);
this.Memory.WriteByte(CommandType.ctPageWidth);
this.Memory.WriteDouble(width);
this.Memory.WriteByte(CommandType.ctPageHeight);
this.Memory.WriteDouble(height);
var _page = this.m_arrayPages[this.m_lPagesCount - 1];
this.m_oPen = _page.m_oPen;
this.m_oBrush = _page.m_oBrush;
this.m_oTransform = _page.m_oTransform;
},
EndPage : function()
{
this.Memory.WriteByte(CommandType.ctPageEnd);
},
p_color : function(r, g, b, a)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].p_color(r, g, b, a);
},
p_width : function(w)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].p_width(w);
},
p_dash : function(params)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].p_dash(params);
},
// brush methods
b_color1 : function(r, g, b, a)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].b_color1(r, g, b, a);
},
b_color2 : function(r, g, b, a)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].b_color2(r, g, b, a);
},
transform : function(sx, shy, shx, sy, tx, ty)
{
if (0 != this.m_lPagesCount)
{
if (null == this.m_oBaseTransform)
this.m_arrayPages[this.m_lPagesCount - 1].transform(sx, shy, shx, sy, tx, ty);
else
{
var _transform = new CMatrix();
_transform.sx = sx;
_transform.shy = shy;
_transform.shx = shx;
_transform.sy = sy;
_transform.tx = tx;
_transform.ty = ty;
AscCommon.global_MatrixTransformer.MultiplyAppend(_transform, this.m_oBaseTransform);
this.m_arrayPages[this.m_lPagesCount - 1].transform(_transform.sx, _transform.shy, _transform.shx, _transform.sy, _transform.tx, _transform.ty);
}
}
},
transform3 : function(m)
{
this.transform(m.sx, m.shy, m.shx, m.sy, m.tx, m.ty);
},
reset : function()
{
this.transform(1, 0, 0, 1, 0, 0);
},
// path commands
_s : function()
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1]._s();
},
_e : function()
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1]._e();
},
_z : function()
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1]._z();
},
_m : function(x, y)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1]._m(x, y);
if (this.ArrayPoints != null)
this.ArrayPoints[this.ArrayPoints.length] = {x : x, y : y};
},
_l : function(x, y)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1]._l(x, y);
if (this.ArrayPoints != null)
this.ArrayPoints[this.ArrayPoints.length] = {x : x, y : y};
},
_c : function(x1, y1, x2, y2, x3, y3)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1]._c(x1, y1, x2, y2, x3, y3);
if (this.ArrayPoints != null)
{
this.ArrayPoints[this.ArrayPoints.length] = {x : x1, y : y1};
this.ArrayPoints[this.ArrayPoints.length] = {x : x2, y : y2};
this.ArrayPoints[this.ArrayPoints.length] = {x : x3, y : y3};
}
},
_c2 : function(x1, y1, x2, y2)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1]._c2(x1, y1, x2, y2);
if (this.ArrayPoints != null)
{
this.ArrayPoints[this.ArrayPoints.length] = {x : x1, y : y1};
this.ArrayPoints[this.ArrayPoints.length] = {x : x2, y : y2};
}
},
ds : function()
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].ds();
},
df : function()
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].df();
},
drawpath : function(type)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].drawpath(type);
},
// canvas state
save : function()
{
},
restore : function()
{
},
clip : function()
{
},
// images
drawImage : function(img, x, y, w, h, alpha, srcRect)
{
if (img == null || img == undefined || img == "")
return;
if (0 != this.m_lPagesCount)
{
if (!srcRect)
this.m_arrayPages[this.m_lPagesCount - 1].drawImage(img, x, y, w, h, this.UseOriginImageUrl);
else
{
/*
if (!window.editor)
{
this.m_arrayPages[this.m_lPagesCount - 1].drawImage(img,x,y,w,h);
return;
}
*/
/*
var _img = undefined;
if (window.editor)
_img = window.editor.ImageLoader.map_image_index[img];
else if (window["Asc"]["editor"])
_img = window["Asc"]["editor"].ImageLoader.map_image_index[img];
var w0 = 0;
var h0 = 0;
if (_img != undefined && _img.Image != null)
{
w0 = _img.Image.width;
h0 = _img.Image.height;
}
if (w0 == 0 || h0 == 0)
{
this.m_arrayPages[this.m_lPagesCount - 1].drawImage(img, x, y, w, h);
return;
}
*/
var bIsClip = false;
if (srcRect.l > 0 || srcRect.t > 0 || srcRect.r < 100 || srcRect.b < 100)
bIsClip = true;
if (bIsClip)
{
this.SaveGrState();
this.AddClipRect(x, y, w, h);
}
var __w = w;
var __h = h;
var _delW = Math.max(0, -srcRect.l) + Math.max(0, srcRect.r - 100) + 100;
var _delH = Math.max(0, -srcRect.t) + Math.max(0, srcRect.b - 100) + 100;
if (srcRect.l < 0)
{
var _off = ((-srcRect.l / _delW) * __w);
x += _off;
w -= _off;
}
if (srcRect.t < 0)
{
var _off = ((-srcRect.t / _delH) * __h);
y += _off;
h -= _off;
}
if (srcRect.r > 100)
{
var _off = ((srcRect.r - 100) / _delW) * __w;
w -= _off;
}
if (srcRect.b > 100)
{
var _off = ((srcRect.b - 100) / _delH) * __h;
h -= _off;
}
var _wk = 100;
if (srcRect.l > 0)
_wk -= srcRect.l;
if (srcRect.r < 100)
_wk -= (100 - srcRect.r);
_wk = 100 / _wk;
var _hk = 100;
if (srcRect.t > 0)
_hk -= srcRect.t;
if (srcRect.b < 100)
_hk -= (100 - srcRect.b);
_hk = 100 / _hk;
var _r = x + w;
var _b = y + h;
if (srcRect.l > 0)
{
x -= ((srcRect.l * _wk * w) / 100);
}
if (srcRect.t > 0)
{
y -= ((srcRect.t * _hk * h) / 100);
}
if (srcRect.r < 100)
{
_r += (((100 - srcRect.r) * _wk * w) / 100);
}
if (srcRect.b < 100)
{
_b += (((100 - srcRect.b) * _hk * h) / 100);
}
this.m_arrayPages[this.m_lPagesCount - 1].drawImage(img, x, y, _r - x, _b - y);
if (bIsClip)
{
this.RestoreGrState();
}
}
}
},
SetFont : function(font)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].SetFont(font);
},
FillText : function(x, y, text, cropX, cropW)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].FillText(x, y, text);
},
FillTextCode : function(x, y, text, cropX, cropW)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].FillTextCode(x, y, text);
},
tg : function(gid, x, y)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].tg(gid, x, y);
},
FillText2 : function(x, y, text)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].FillText(x, y, text);
},
charspace : function(space)
{
},
SetIntegerGrid : function(param)
{
},
GetIntegerGrid : function()
{
},
GetFont : function()
{
if (0 != this.m_lPagesCount)
return this.m_arrayPages[this.m_lPagesCount - 1].m_oFont;
return null;
},
put_GlobalAlpha : function(enable, alpha)
{
},
Start_GlobalAlpha : function()
{
},
End_GlobalAlpha : function()
{
},
DrawHeaderEdit : function(yPos)
{
},
DrawFooterEdit : function(yPos)
{
},
drawCollaborativeChanges : function(x, y, w, h)
{
},
drawSearchResult : function(x, y, w, h)
{
},
DrawEmptyTableLine : function(x1, y1, x2, y2)
{
// эта функция не для печати или сохранения вообще
},
DrawLockParagraph : function(lock_type, x, y1, y2)
{
// эта функция не для печати или сохранения вообще
},
DrawLockObjectRect : function(lock_type, x, y, w, h)
{
// эта функция не для печати или сохранения вообще
},
DrawSpellingLine : function(y0, x0, x1, w)
{
},
// smart methods for horizontal / vertical lines
drawHorLine : function(align, y, x, r, penW)
{
this.p_width(1000 * penW);
this._s();
var _y = y;
switch (align)
{
case 0:
{
_y = y + penW / 2;
break;
}
case 1:
{
break;
}
case 2:
{
_y = y - penW / 2;
}
}
this._m(x, y);
this._l(r, y);
this.ds();
this._e();
},
drawHorLine2 : function(align, y, x, r, penW)
{
this.p_width(1000 * penW);
var _y = y;
switch (align)
{
case 0:
{
_y = y + penW / 2;
break;
}
case 1:
{
break;
}
case 2:
{
_y = y - penW / 2;
break;
}
}
this._s();
this._m(x, (_y - penW));
this._l(r, (_y - penW));
this.ds();
this._s();
this._m(x, (_y + penW));
this._l(r, (_y + penW));
this.ds();
this._e();
},
drawVerLine : function(align, x, y, b, penW)
{
this.p_width(1000 * penW);
this._s();
var _x = x;
switch (align)
{
case 0:
{
_x = x + penW / 2;
break;
}
case 1:
{
break;
}
case 2:
{
_x = x - penW / 2;
}
}
this._m(_x, y);
this._l(_x, b);
this.ds();
},
// мега крутые функции для таблиц
drawHorLineExt : function(align, y, x, r, penW, leftMW, rightMW)
{
this.drawHorLine(align, y, x + leftMW, r + rightMW, penW);
},
rect : function(x, y, w, h)
{
var _x = x;
var _y = y;
var _r = (x + w);
var _b = (y + h);
this._s();
this._m(_x, _y);
this._l(_r, _y);
this._l(_r, _b);
this._l(_x, _b);
this._l(_x, _y);
},
TableRect : function(x, y, w, h)
{
this.rect(x, y, w, h);
this.df();
},
put_PenLineJoin : function(_join)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].put_PenLineJoin(_join);
},
put_TextureBounds : function(x, y, w, h)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].put_TextureBounds(x, y, w, h);
},
put_TextureBoundsEnabled : function(val)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].put_TextureBoundsEnabled(val);
},
put_brushTexture : function(src, mode)
{
if (src == null || src == undefined)
src = "";
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].put_brushTexture(src, mode);
},
put_BrushTextureAlpha : function(alpha)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].put_BrushTextureAlpha(alpha);
},
put_BrushGradient : function(gradFill, points, transparent)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].put_BrushGradient(gradFill, points, transparent);
},
// функции клиппирования
AddClipRect : function(x, y, w, h)
{
/*
this.b_color1(0, 0, 0, 255);
this.rect(x, y, w, h);
this.df();
return;
*/
var __rect = new _rect();
__rect.x = x;
__rect.y = y;
__rect.w = w;
__rect.h = h;
this.GrState.AddClipRect(__rect);
//this.ClipManager.AddRect(x, y, w, h);
},
RemoveClipRect : function()
{
//this.ClipManager.RemoveRect();
},
SetClip : function(r)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].beginCommand(32);
this.rect(r.x, r.y, r.w, r.h);
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].endCommand(32);
//this._s();
},
RemoveClip : function()
{
if (0 != this.m_lPagesCount)
{
this.m_arrayPages[this.m_lPagesCount - 1].beginCommand(64);
this.m_arrayPages[this.m_lPagesCount - 1].endCommand(64);
}
},
GetTransform : function()
{
if (0 != this.m_lPagesCount)
{
return this.m_arrayPages[this.m_lPagesCount - 1].m_oTransform;
}
return null;
},
GetLineWidth : function()
{
if (0 != this.m_lPagesCount)
{
return this.m_arrayPages[this.m_lPagesCount - 1].m_oPen.Size;
}
return 0;
},
GetPen : function()
{
if (0 != this.m_lPagesCount)
{
return this.m_arrayPages[this.m_lPagesCount - 1].m_oPen;
}
return 0;
},
GetBrush : function()
{
if (0 != this.m_lPagesCount)
{
return this.m_arrayPages[this.m_lPagesCount - 1].m_oBrush;
}
return 0;
},
drawFlowAnchor : function(x, y)
{
},
SavePen : function()
{
this.GrState.SavePen();
},
RestorePen : function()
{
this.GrState.RestorePen();
},
SaveBrush : function()
{
this.GrState.SaveBrush();
},
RestoreBrush : function()
{
this.GrState.RestoreBrush();
},
SavePenBrush : function()
{
this.GrState.SavePenBrush();
},
RestorePenBrush : function()
{
this.GrState.RestorePenBrush();
},
SaveGrState : function()
{
this.GrState.SaveGrState();
},
RestoreGrState : function()
{
var _t = this.m_oBaseTransform;
this.m_oBaseTransform = null;
this.GrState.RestoreGrState();
this.m_oBaseTransform = _t;
},
RemoveLastClip : function()
{
var _t = this.m_oBaseTransform;
this.m_oBaseTransform = null;
this.GrState.RemoveLastClip();
this.m_oBaseTransform = _t;
},
RestoreLastClip : function()
{
var _t = this.m_oBaseTransform;
this.m_oBaseTransform = null;
this.GrState.RestoreLastClip();
this.m_oBaseTransform = _t;
},
StartClipPath : function()
{
this.private_removeVectors();
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].beginCommand(32);
},
EndClipPath : function()
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].endCommand(32);
this.private_restoreVectors();
},
SetTextPr : function(textPr, theme)
{
if (0 != this.m_lPagesCount)
{
var _page = this.m_arrayPages[this.m_lPagesCount - 1];
if (theme && textPr && textPr.ReplaceThemeFonts)
textPr.ReplaceThemeFonts(theme.themeElements.fontScheme);
_page.m_oTextPr = textPr;
if (theme)
_page.m_oGrFonts.checkFromTheme(theme.themeElements.fontScheme, _page.m_oTextPr.RFonts);
else
_page.m_oGrFonts = _page.m_oTextPr.RFonts;
}
},
SetFontInternal : function(name, size, style)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].SetFontInternal(name, size, style);
},
SetFontSlot : function(slot, fontSizeKoef)
{
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].SetFontSlot(slot, fontSizeKoef);
},
GetTextPr : function()
{
if (0 != this.m_lPagesCount)
return this.m_arrayPages[this.m_lPagesCount - 1].m_oTextPr;
return null;
},
DrawPresentationComment : function(type, x, y, w, h)
{
},
private_removeVectors : function()
{
this._restoreDumpedVectors = this.VectorMemoryForPrint;
if (this._restoreDumpedVectors != null)
{
this.VectorMemoryForPrint = null;
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].VectorMemoryForPrint = null;
}
},
private_restoreVectors : function()
{
if (null != this._restoreDumpedVectors)
{
this.VectorMemoryForPrint = this._restoreDumpedVectors;
if (0 != this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].VectorMemoryForPrint = this._restoreDumpedVectors;
}
this._restoreDumpedVectors = null;
},
AddHyperlink : function(x, y, w, h, url, tooltip)
{
if (0 !== this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].AddHyperlink(x, y, w, h, url, tooltip);
},
AddLink : function(x, y, w, h, dx, dy, dPage)
{
if (0 !== this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].AddLink(x, y, w, h, dx, dy, dPage);
},
AddFormField : function(nX, nY, nW, nH, nBaseLineOffset, oForm)
{
if (0 !== this.m_lPagesCount)
this.m_arrayPages[this.m_lPagesCount - 1].AddFormField(nX, nY, nW, nH, nBaseLineOffset, oForm);
}
};
var MATRIX_ORDER_PREPEND = 0;
var MATRIX_ORDER_APPEND = 1;
function deg2rad(deg)
{
return deg * Math.PI / 180.0;
}
function rad2deg(rad)
{
return rad * 180.0 / Math.PI;
}
function CMatrix()
{
this.sx = 1.0;
this.shx = 0.0;
this.shy = 0.0;
this.sy = 1.0;
this.tx = 0.0;
this.ty = 0.0;
}
CMatrix.prototype =
{
Reset : function()
{
this.sx = 1.0;
this.shx = 0.0;
this.shy = 0.0;
this.sy = 1.0;
this.tx = 0.0;
this.ty = 0.0;
},
// трансформ
Multiply : function(matrix, order)
{
if (MATRIX_ORDER_PREPEND == order)
{
var m = new CMatrix();
m.sx = matrix.sx;
m.shx = matrix.shx;
m.shy = matrix.shy;
m.sy = matrix.sy;
m.tx = matrix.tx;
m.ty = matrix.ty;
m.Multiply(this, MATRIX_ORDER_APPEND);
this.sx = m.sx;
this.shx = m.shx;
this.shy = m.shy;
this.sy = m.sy;
this.tx = m.tx;
this.ty = m.ty;
}
else
{
var t0 = this.sx * matrix.sx + this.shy * matrix.shx;
var t2 = this.shx * matrix.sx + this.sy * matrix.shx;
var t4 = this.tx * matrix.sx + this.ty * matrix.shx + matrix.tx;
this.shy = this.sx * matrix.shy + this.shy * matrix.sy;
this.sy = this.shx * matrix.shy + this.sy * matrix.sy;
this.ty = this.tx * matrix.shy + this.ty * matrix.sy + matrix.ty;
this.sx = t0;
this.shx = t2;
this.tx = t4;
}
return this;
},
// а теперь частные случаи трансформа (для удобного пользования)
Translate : function(x, y, order)
{
var m = new CMatrix();
m.tx = x;
m.ty = y;
this.Multiply(m, order);
},
Scale : function(x, y, order)
{
var m = new CMatrix();
m.sx = x;
m.sy = y;
this.Multiply(m, order);
},
Rotate : function(a, order)
{
var m = new CMatrix();
var rad = deg2rad(a);
m.sx = Math.cos(rad);
m.shx = Math.sin(rad);
m.shy = -Math.sin(rad);
m.sy = Math.cos(rad);
this.Multiply(m, order);
},
RotateAt : function(a, x, y, order)
{
this.Translate(-x, -y, order);
this.Rotate(a, order);
this.Translate(x, y, order);
},
// determinant
Determinant : function()
{
return this.sx * this.sy - this.shy * this.shx;
},
// invert
Invert : function()
{
var det = this.Determinant();
if (0.0001 > Math.abs(det))
return;
var d = 1 / det;
var t0 = this.sy * d;
this.sy = this.sx * d;
this.shy = -this.shy * d;
this.shx = -this.shx * d;
var t4 = -this.tx * t0 - this.ty * this.shx;
this.ty = -this.tx * this.shy - this.ty * this.sy;
this.sx = t0;
this.tx = t4;
return this;
},
// transform point
TransformPointX : function(x, y)
{
return x * this.sx + y * this.shx + this.tx;
},
TransformPointY : function(x, y)
{
return x * this.shy + y * this.sy + this.ty;
},
// calculate rotate angle
GetRotation : function()
{
var x1 = 0.0;
var y1 = 0.0;
var x2 = 1.0;
var y2 = 0.0;
var _x1 = this.TransformPointX(x1, y1);
var _y1 = this.TransformPointY(x1, y1);
var _x2 = this.TransformPointX(x2, y2);
var _y2 = this.TransformPointY(x2, y2);
var _y = _y2 - _y1;
var _x = _x2 - _x1;
if (Math.abs(_y) < 0.001)
{
if (_x > 0)
return 0;
else
return 180;
}
if (Math.abs(_x) < 0.001)
{
if (_y > 0)
return 90;
else
return 270;
}
var a = Math.atan2(_y, _x);
a = rad2deg(a);
if (a < 0)
a += 360;
return a;
},
// сделать дубликата
CreateDublicate : function()
{
var m = new CMatrix();
m.sx = this.sx;
m.shx = this.shx;
m.shy = this.shy;
m.sy = this.sy;
m.tx = this.tx;
m.ty = this.ty;
return m;
},
IsIdentity : function()
{
if (this.sx == 1.0 &&
this.shx == 0.0 &&
this.shy == 0.0 &&
this.sy == 1.0 &&
this.tx == 0.0 &&
this.ty == 0.0)
{
return true;
}
return false;
},
IsIdentity2 : function()
{
if (this.sx == 1.0 &&
this.shx == 0.0 &&
this.shy == 0.0 &&
this.sy == 1.0)
{
return true;
}
return false;
},
GetScaleValue : function()
{
var x1 = this.TransformPointX(0, 0);
var y1 = this.TransformPointY(0, 0);
var x2 = this.TransformPointX(1, 1);
var y2 = this.TransformPointY(1, 1);
return Math.sqrt(((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1))/2);
}
};
function GradientGetAngleNoRotate(_angle, _transform)
{
var x1 = 0.0;
var y1 = 0.0;
var x2 = 1.0;
var y2 = 0.0;
var _matrixRotate = new CMatrix();
_matrixRotate.Rotate(-_angle / 60000);
var _x11 = _matrixRotate.TransformPointX(x1, y1);
var _y11 = _matrixRotate.TransformPointY(x1, y1);
var _x22 = _matrixRotate.TransformPointX(x2, y2);
var _y22 = _matrixRotate.TransformPointY(x2, y2);
_matrixRotate = global_MatrixTransformer.Invert(_transform);
var _x1 = _matrixRotate.TransformPointX(_x11, _y11);
var _y1 = _matrixRotate.TransformPointY(_x11, _y11);
var _x2 = _matrixRotate.TransformPointX(_x22, _y22);
var _y2 = _matrixRotate.TransformPointY(_x22, _y22);
var _y = _y2 - _y1;
var _x = _x2 - _x1;
var a = 0;
if (Math.abs(_y) < 0.001)
{
if (_x > 0)
a = 0;
else
a = 180;
}
else if (Math.abs(_x) < 0.001)
{
if (_y > 0)
a = 90;
else
a = 270;
}
else
{
a = Math.atan2(_y, _x);
a = rad2deg(a);
}
if (a < 0)
a += 360;
//console.log(a);
return a * 60000;
};
var CMatrixL = CMatrix;
function CGlobalMatrixTransformer()
{
this.TranslateAppend = function(m, _tx, _ty)
{
m.tx += _tx;
m.ty += _ty;
}
this.ScaleAppend = function(m, _sx, _sy)
{
m.sx *= _sx;
m.shx *= _sx;
m.shy *= _sy;
m.sy *= _sy;
m.tx *= _sx;
m.ty *= _sy;
}
this.RotateRadAppend = function(m, _rad)
{
var _sx = Math.cos(_rad);
var _shx = Math.sin(_rad);
var _shy = -Math.sin(_rad);
var _sy = Math.cos(_rad);
var t0 = m.sx * _sx + m.shy * _shx;
var t2 = m.shx * _sx + m.sy * _shx;
var t4 = m.tx * _sx + m.ty * _shx;
m.shy = m.sx * _shy + m.shy * _sy;
m.sy = m.shx * _shy + m.sy * _sy;
m.ty = m.tx * _shy + m.ty * _sy;
m.sx = t0;
m.shx = t2;
m.tx = t4;
}
this.MultiplyAppend = function(m1, m2)
{
var t0 = m1.sx * m2.sx + m1.shy * m2.shx;
var t2 = m1.shx * m2.sx + m1.sy * m2.shx;
var t4 = m1.tx * m2.sx + m1.ty * m2.shx + m2.tx;
m1.shy = m1.sx * m2.shy + m1.shy * m2.sy;
m1.sy = m1.shx * m2.shy + m1.sy * m2.sy;
m1.ty = m1.tx * m2.shy + m1.ty * m2.sy + m2.ty;
m1.sx = t0;
m1.shx = t2;
m1.tx = t4;
}
this.Invert = function(m)
{
var newM = m.CreateDublicate();
var det = newM.sx * newM.sy - newM.shy * newM.shx;
if (0.0001 > Math.abs(det))
return newM;
var d = 1 / det;
var t0 = newM.sy * d;
newM.sy = newM.sx * d;
newM.shy = -newM.shy * d;
newM.shx = -newM.shx * d;
var t4 = -newM.tx * t0 - newM.ty * newM.shx;
newM.ty = -newM.tx * newM.shy - newM.ty * newM.sy;
newM.sx = t0;
newM.tx = t4;
return newM;
}
this.MultiplyAppendInvert = function(m1, m2)
{
var m = this.Invert(m2);
this.MultiplyAppend(m1, m);
}
this.MultiplyPrepend = function(m1, m2)
{
var m = new CMatrixL();
m.sx = m2.sx;
m.shx = m2.shx;
m.shy = m2.shy;
m.sy = m2.sy;
m.tx = m2.tx;
m.ty = m2.ty;
this.MultiplyAppend(m, m1);
m1.sx = m.sx;
m1.shx = m.shx;
m1.shy = m.shy;
m1.sy = m.sy;
m1.tx = m.tx;
m1.ty = m.ty;
}
this.Reflect = function (matrix, isHorizontal, isVertical) {
var m = new CMatrixL();
m.shx = 0;
m.sy = 1;
m.tx = 0;
m.ty = 0;
m.sx = 1;
m.shy = 0;
if (isHorizontal && isVertical) {
m.sx = -1;
m.sy = -1;
} else if (isHorizontal) {
m.sx = -1;
} else if (isVertical) {
m.sy = -1;
} else {
return;
}
this.MultiplyAppend(matrix, m);
}
this.CreateDublicateM = function(matrix)
{
var m = new CMatrixL();
m.sx = matrix.sx;
m.shx = matrix.shx;
m.shy = matrix.shy;
m.sy = matrix.sy;
m.tx = matrix.tx;
m.ty = matrix.ty;
return m;
}
this.IsIdentity = function(m)
{
if (m.sx == 1.0 &&
m.shx == 0.0 &&
m.shy == 0.0 &&
m.sy == 1.0 &&
m.tx == 0.0 &&
m.ty == 0.0)
{
return true;
}
return false;
}
this.IsIdentity2 = function(m)
{
var eps = 0.00001;
if (Math.abs(m.sx - 1.0) < eps &&
Math.abs(m.shx) < eps &&
Math.abs(m.shy) < eps &&
Math.abs(m.sy - 1.0) < eps)
{
return true;
}
return false;
}
}
function CClipManager()
{
this.clipRects = [];
this.curRect = new _rect();
this.BaseObject = null;
this.AddRect = function(x, y, w, h)
{
var _count = this.clipRects.length;
if (0 == _count)
{
this.curRect.x = x;
this.curRect.y = y;
this.curRect.w = w;
this.curRect.h = h;
var _r = new _rect();
_r.x = x;
_r.y = y;
_r.w = w;
_r.h = h;
this.clipRects[_count] = _r;
this.BaseObject.SetClip(this.curRect);
}
else
{
this.BaseObject.RemoveClip();
var _r = new _rect();
_r.x = x;
_r.y = y;
_r.w = w;
_r.h = h;
this.clipRects[_count] = _r;
this.curRect = this.IntersectRect(this.curRect, _r);
this.BaseObject.SetClip(this.curRect);
}
}
this.RemoveRect = function()
{
var _count = this.clipRects.length;
if (0 != _count)
{
this.clipRects.splice(_count - 1, 1);
--_count;
this.BaseObject.RemoveClip();
if (0 != _count)
{
this.curRect.x = this.clipRects[0].x;
this.curRect.y = this.clipRects[0].y;
this.curRect.w = this.clipRects[0].w;
this.curRect.h = this.clipRects[0].h;
for (var i = 1; i < _count; i++)
this.curRect = this.IntersectRect(this.curRect, this.clipRects[i]);
this.BaseObject.SetClip(this.curRect);
}
}
}
this.IntersectRect = function(r1, r2)
{
var res = new _rect();
res.x = Math.max(r1.x, r2.x);
res.y = Math.max(r1.y, r2.y);
res.w = Math.min(r1.x + r1.w, r2.x + r2.w) - res.x;
res.h = Math.min(r1.y + r1.h, r2.y + r2.h) - res.y;
if (0 > res.w)
res.w = 0;
if (0 > res.h)
res.h = 0;
return res;
}
}
function CPen()
{
this.Color = {R : 255, G : 255, B : 255, A : 255};
this.Style = 0;
this.LineCap = 0;
this.LineJoin = 0;
this.LineWidth = 1;
}
function CBrush()
{
this.Color1 = {R : 255, G : 255, B : 255, A : 255};
this.Color2 = {R : 255, G : 255, B : 255, A : 255};
this.Type = 0;
}
function CTableMarkup(Table)
{
this.Internal =
{
RowIndex : 0,
CellIndex : 0,
PageNum : 0
};
this.Table = Table;
this.X = 0; // Смещение таблицы от начала страницы до первой колонки
this.Cols = []; // массив ширин колонок
this.Margins = []; // массив левых и правых маргинов
this.Rows = []; // массив позиций, высот строк(для данной страницы)
// Rows = [ { Y : , H : }, ... ]
this.CurCol = 0; // текущая колонка
this.CurRow = 0; // текущая строка
this.TransformX = 0;
this.TransformY = 0;
}
CTableMarkup.prototype =
{
CreateDublicate : function()
{
var obj = new CTableMarkup(this.Table);
obj.Internal = {RowIndex : this.Internal.RowIndex, CellIndex : this.Internal.CellIndex, PageNum : this.Internal.PageNum};
obj.X = this.X;
var len = this.Cols.length;
for (var i = 0; i < len; i++)
obj.Cols[i] = this.Cols[i];
len = this.Margins.length;
for (var i = 0; i < len; i++)
obj.Margins[i] = {Left : this.Margins[i].Left, Right : this.Margins[i].Right};
len = this.Rows.length;
for (var i = 0; i < len; i++)
obj.Rows[i] = {Y : this.Rows[i].Y, H : this.Rows[i].H};
obj.CurRow = this.CurRow;
obj.CurCol = this.CurCol;
return obj;
},
CorrectFrom : function()
{
this.X += this.TransformX;
var _len = this.Rows.length;
for (var i = 0; i < _len; i++)
{
this.Rows[i].Y += this.TransformY;
}
},
CorrectTo : function()
{
this.X -= this.TransformX;
var _len = this.Rows.length;
for (var i = 0; i < _len; i++)
{
this.Rows[i].Y -= this.TransformY;
}
},
Get_X : function()
{
return this.X;
},
Get_Y : function()
{
var _Y = 0;
if (this.Rows.length > 0)
{
_Y = this.Rows[0].Y;
}
return _Y;
}
};
function CTableOutline(Table, PageNum, X, Y, W, H)
{
this.Table = Table;
this.PageNum = PageNum;
this.X = X;
this.Y = Y;
this.W = W;
this.H = H;
}
var g_fontManager = new AscFonts.CFontManager();
g_fontManager.Initialize(true);
g_fontManager.SetHintsProps(true, true);
var g_dDpiX = 96.0;
var g_dDpiY = 96.0;
var g_dKoef_mm_to_pix = g_dDpiX / 25.4;
var g_dKoef_pix_to_mm = 25.4 / g_dDpiX;
function _rect()
{
this.x = 0;
this.y = 0;
this.w = 0;
this.h = 0;
}
//--------------------------------------------------------export----------------------------------------------------
window['AscCommon'] = window['AscCommon'] || {};
window['AscCommon'].CGrRFonts = CGrRFonts;
window['AscCommon'].CFontSetup = CFontSetup;
window['AscCommon'].CGrState = CGrState;
window['AscCommon'].CMemory = CMemory;
window['AscCommon'].CDocumentRenderer = CDocumentRenderer;
window['AscCommon'].MATRIX_ORDER_PREPEND = MATRIX_ORDER_PREPEND;
window['AscCommon'].MATRIX_ORDER_APPEND = MATRIX_ORDER_APPEND;
window['AscCommon'].deg2rad = deg2rad;
window['AscCommon'].rad2deg = rad2deg;
window['AscCommon'].CMatrix = CMatrix;
window['AscCommon'].CMatrixL = CMatrixL;
window['AscCommon'].CGlobalMatrixTransformer = CGlobalMatrixTransformer;
window['AscCommon'].CClipManager = CClipManager;
window['AscCommon'].CPen = CPen;
window['AscCommon'].CBrush = CBrush;
window['AscCommon'].CTableMarkup = CTableMarkup;
window['AscCommon'].CTableOutline = CTableOutline;
window['AscCommon']._rect = _rect;
window['AscCommon'].global_MatrixTransformer = new CGlobalMatrixTransformer();
window['AscCommon'].g_fontManager = g_fontManager;
window['AscCommon'].g_dDpiX = g_dDpiX;
window['AscCommon'].g_dKoef_mm_to_pix = g_dKoef_mm_to_pix;
window['AscCommon'].g_dKoef_pix_to_mm = g_dKoef_pix_to_mm;
window['AscCommon'].GradientGetAngleNoRotate = GradientGetAngleNoRotate;
window['AscCommon'].DashPatternPresets = DashPatternPresets;
window['AscCommon'].CommandType = CommandType;
})(window);
|
Write code points array to PDF
|
common/Drawings/Metafile.js
|
Write code points array to PDF
|
<ide><path>ommon/Drawings/Metafile.js
<ide> if (0 != this.m_lPagesCount)
<ide> this.m_arrayPages[this.m_lPagesCount - 1].FillTextCode(x, y, text);
<ide> },
<del> tg : function(gid, x, y)
<del> {
<del> if (0 != this.m_lPagesCount)
<del> this.m_arrayPages[this.m_lPagesCount - 1].tg(gid, x, y);
<add> tg : function(gid, x, y, codePoints)
<add> {
<add> if (0 != this.m_lPagesCount)
<add> this.m_arrayPages[this.m_lPagesCount - 1].tg(gid, x, y, codePoints);
<ide> },
<ide> FillText2 : function(x, y, text)
<ide> {
|
|
Java
|
mit
|
cc27f6eb915fdf7bd0f11c1a7770c07706965940
| 0 |
topone37/GLESDemo,topone37/GLESDemo
|
package com.tp.gl.demo002;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.GLUtils;
import android.opengl.Matrix;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.util.Log;
import com.tp.gl.R;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
/**
* Created by root on 17-10-10.
* 加载图片作为纹理
*/
public class Demo012GLSurfaceView extends GLSurfaceView implements GLSurfaceView.Renderer {
private static final String VERREXT_SOURECE = "" +
"attribute vec4 aPosition;" +
"attribute vec2 aCoordinate;" +
"varying vec2 vCoordinate;" +
"uniform mat4 uMatrix;" +
"varying mat4 vMatrix;" +
"void main() {" +
" gl_Position = uMatrix * aPosition ;" +
" vCoordinate = aCoordinate ;" +
" vMatrix = uMatrix;" +
"}";
private static final String FRAGMENT_SOURCE = " precision mediump float;\n" +
" uniform sampler2D vTexture;\n" +
" varying vec2 vCoordinate;\n" +
" varying mat4 vMatrix;" +
" void main(){\n" +
// " gl_FragColor = texture2D(vTexture,(vMatrix * vec4(vCoordinate - vec2(0.5), 0.0, 1.0)).xy + vec2(0.5)); " +
// " gl_FragColor=texture2D(vTexture,vCoordinate);\n" +
" gl_FragColor=vec4(1.0,1.0,0.0,1.0);\n" +
" }";
private final float[] sPos = {
// /************左上角************/
// -1.0f, 1.0f,
// -1.0f, 0.0f,
// 0.0f, 1.0f,
// 0.0f, 0.0f,
// /************右上角************/
// 0.0f, 1.0f,
// 0.0f, 0.0f,
// 1.0f, 1.0f,
// 1.0f, 0.0f,
// /************左下角************/
// -1.0f, 0.0f,
// -1.0f, -1.0f,
// 0.0f, 0.0f,
// 0.0f, -1.0f,
// /************右下角************/
// 0.0f, 0.0f,
// 0.0f, -1.0f,
// 1.0f, 0.0f,
// 1.0f, -1.0f,
-1.0f, 1.0f,
-1.0f, -1.0f,
1.0f, 1.0f,
1.0f, -1.0f
};
private final float[] sCoord = {
0.0f, 0.0f,
0.0f, 1.0f,
1.0f, 0.0f,
1.0f, 1.0f,
0.0f, 0.0f,
0.0f, 1.0f,
1.0f, 0.0f,
1.0f, 1.0f,
0.0f, 0.0f,
0.0f, 1.0f,
1.0f, 0.0f,
1.0f, 1.0f,
0.0f, 0.0f,
0.0f, 1.0f,
1.0f, 0.0f,
1.0f, 1.0f,
};
private final int[] index = {
0, 1, 2,
2, 1, 3,
4, 5, 6,
6, 5, 7,
8, 9, 10,
10, 9, 11,
12, 13, 14,
14, 13, 15
};
private Bitmap mBitmap;
private float mProjectMatrix[] = new float[16];
float[] mViewMatrix = new float[16];
float[] mMVPMatrix = new float[16];
private int textureId;
private int mProgram;
private FloatBuffer mVertexBuff;
private FloatBuffer mColorBuff;
private IntBuffer mIndexBuff;
public Demo012GLSurfaceView(Context context) {
this(context, null);
}
public Demo012GLSurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
setEGLContextClientVersion(2);
setEGLConfigChooser(8, 8, 8, 8, 8, 0);
setRenderer(this);
setRenderMode(RENDERMODE_CONTINUOUSLY);
}
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
GLES20.glClearColor(0.5f, 0.5f, 0.5f, 1.0f);//设置清屏颜色,只有你调用 GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);起作用
ByteBuffer bb = ByteBuffer.allocateDirect(sPos.length * 4);//分配
bb.order(ByteOrder.nativeOrder());//一定要用native的字节序 (大小端字节问题)
mVertexBuff = bb.asFloatBuffer();
mVertexBuff.put(sPos);/*讲数据填入*/
mVertexBuff.position(0);/*读/写的数据的索引*/
ByteBuffer bc = ByteBuffer.allocateDirect(sCoord.length * 4);
bc.order(ByteOrder.nativeOrder());
mColorBuff = bc.asFloatBuffer();
mColorBuff.put(sCoord);
mColorBuff.position(0);
ByteBuffer bi = ByteBuffer.allocateDirect(index.length * 4);
bi.order(ByteOrder.nativeOrder());
mIndexBuff = bi.asIntBuffer();
mIndexBuff.put(index);
mIndexBuff.position(0);
int vertex_shader = GLES20.glCreateShader(GLES20.GL_VERTEX_SHADER);/**创建一个Shader对象*/
if (vertex_shader != 0) {
GLES20.glShaderSource(vertex_shader, VERREXT_SOURECE);/**绑定源码*/
GLES20.glCompileShader(vertex_shader);/**编译*/
int[] complied = new int[1];
GLES20.glGetShaderiv(vertex_shader, GLES20.GL_COMPILE_STATUS, complied, 0);
if (complied[0] == 0) {
Log.e("GLES", "GL_VERTEX_SHADER Error!!!!" + GLES20.glGetShaderInfoLog(vertex_shader));
GLES20.glDeleteShader(vertex_shader);
vertex_shader = 0;
}
}
int fragment_shader = GLES20.glCreateShader(GLES20.GL_FRAGMENT_SHADER);
if (fragment_shader != 0) {
GLES20.glShaderSource(fragment_shader, FRAGMENT_SOURCE);
GLES20.glCompileShader(fragment_shader);
int[] complied = new int[1];
GLES20.glGetShaderiv(fragment_shader, GLES20.GL_COMPILE_STATUS, complied, 0);
if (complied[0] == 0) {
Log.e("GLES", "GL_FRAGMENT_SHADER Error!!!!");
GLES20.glDeleteShader(fragment_shader);
fragment_shader = 0;
}
}
mProgram = GLES20.glCreateProgram();
if (mProgram != 0) {
GLES20.glAttachShader(mProgram, vertex_shader);
GLES20.glAttachShader(mProgram, fragment_shader);
GLES20.glLinkProgram(mProgram);
int linked[] = new int[1];
GLES20.glGetProgramiv(mProgram, GLES20.GL_LINK_STATUS, linked, 0);
if (linked[0] == 0) {
Log.e("GLES", "linked Error!!!!");
GLES20.glDeleteProgram(mProgram);
mProgram = 0;
}
}
}
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
GLES20.glViewport(0, 0, width, height);
mBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.test);
int w = mBitmap.getWidth();
int h = mBitmap.getHeight();
float sWH = w / (float) h;
float sWidthHeight = width / (float) height;
if (width > height) {
if (sWH > sWidthHeight) {
Matrix.orthoM(mProjectMatrix, 0, -sWidthHeight * sWH, sWidthHeight * sWH, -1, 1, 3, 7);
} else {
Matrix.orthoM(mProjectMatrix, 0, -sWidthHeight / sWH, sWidthHeight / sWH, -1, 1, 3, 7);
}
} else {
if (sWH > sWidthHeight) {
Matrix.orthoM(mProjectMatrix, 0, -1, 1, -1 / sWidthHeight * sWH, 1 / sWidthHeight * sWH, 3, 7);
} else {
Matrix.orthoM(mProjectMatrix, 0, -1, 1, -sWH / sWidthHeight, sWH / sWidthHeight, 3, 7);
}
}
//设置相机位置
Matrix.setLookAtM(mViewMatrix, 0, 0, 0, 7.0f, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
//计算变换矩阵
Matrix.multiplyMM(mMVPMatrix, 0, mProjectMatrix, 0, mViewMatrix, 0);
requestRender();
}
/**
* 旋转变形( Matrix.multiplyMM 该方法来整合最初的 矩阵 以及投影矩阵)
* @param gl
*/
@Override
public void onDrawFrame(GL10 gl) {
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
GLES20.glUseProgram(mProgram);
int glHMatrix = GLES20.glGetUniformLocation(mProgram, "uMatrix");
long time = SystemClock.uptimeMillis() % 4000L;
float angle = 0.090f * ((int) time);
float[] mRotationMatrix = new float[16];
Matrix.setRotateM(mRotationMatrix, 0, angle, 0, 0, -1.0f);
float[] result = new float[16];
Matrix.multiplyMM(result, 0, mMVPMatrix, 0, mRotationMatrix, 0);
GLES20.glUniformMatrix4fv(glHMatrix, 1, false, result, 0);
int glHPosition = GLES20.glGetAttribLocation(mProgram, "aPosition");
int glHCoordinate = GLES20.glGetAttribLocation(mProgram, "aCoordinate");
GLES20.glEnableVertexAttribArray(glHPosition);
GLES20.glEnableVertexAttribArray(glHCoordinate);
int glHTexture = GLES20.glGetUniformLocation(mProgram, "vTexture");
GLES20.glVertexAttribPointer(glHPosition, 2, GLES20.GL_FLOAT, false, 0, mVertexBuff);
//传入纹理坐标
GLES20.glVertexAttribPointer(glHCoordinate, 2, GLES20.GL_FLOAT, false, 0, mColorBuff);
createTexture(R.mipmap.test, 0);
GLES20.glUniform1i(glHTexture, 0);
//传入顶点坐标
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
// Matrix.setIdentityM(mMVPMatrix, 0);
// Matrix.setRotateM(mMVPMatrix, 0, 30, 0.5f, 0.5f, 0);
// GLES20.glUniformMatrix4fv(glHMatrix, 1, false, mMVPMatrix, 0);
// createTexture(R.mipmap.moto, 1);
// GLES20.glUniform1i(glHTexture, 1);
// GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 1 * 4, 4);
// Matrix.setIdentityM(mMVPMatrix, 0);
// Matrix.setRotateM(mMVPMatrix, 0, 30, 0.5f, 0.5f, 0);
// GLES20.glUniformMatrix4fv(glHMatrix, 1, false, mMVPMatrix, 0);
// createTexture(R.mipmap.moto, 2);
// GLES20.glUniform1i(glHTexture, 2);
// GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 2 * 4, 4);
// Matrix.setIdentityM(mMVPMatrix, 0);
// Matrix.setRotateM(mMVPMatrix, 0, 30, 0.5f, 0.5f, 0);
// GLES20.glUniformMatrix4fv(glHMatrix, 1, false, mMVPMatrix, 0);
// createTexture(R.mipmap.test, 3);
// GLES20.glUniform1i(glHTexture, 3);
// GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 3 * 4, 4);
}
private void createTexture(int resId, int i) {
int[] texture = new int[1];
mBitmap = BitmapFactory.decodeResource(getResources(), resId);
if (mBitmap != null && !mBitmap.isRecycled()) {
//生成纹理
GLES20.glGenTextures(1, texture, 0);
GLES20.glActiveTexture(GLES20.GL_TEXTURE0 + i);
//生成纹理
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texture[0]);
//设置缩小过滤为使用纹理中坐标最接近的一个像素的颜色作为需要绘制的像素颜色
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST);
//设置放大过滤为使用纹理中坐标最接近的若干个颜色,通过加权平均算法得到需要绘制的像素颜色
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
//设置环绕方向S,截取纹理坐标到[1/2n,1-1/2n]。将导致永远不会与border融合
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
//设置环绕方向T,截取纹理坐标到[1/2n,1-1/2n]。将导致永远不会与border融合
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);
//根据以上指定的参数,生成一个2D纹理
GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, mBitmap, 0);
}
}
}
|
app/src/main/java/com/tp/gl/demo002/Demo012GLSurfaceView.java
|
package com.tp.gl.demo002;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.GLUtils;
import android.opengl.Matrix;
import android.util.AttributeSet;
import android.util.Log;
import com.tp.gl.R;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
/**
* Created by root on 17-10-10.
* 加载图片作为纹理
*/
public class Demo012GLSurfaceView extends GLSurfaceView implements GLSurfaceView.Renderer {
private static final String VERREXT_SOURECE = "" +
"attribute vec4 aPosition;" +
"attribute vec2 aCoordinate;" +
"varying vec2 vCoordinate;" +
"uniform mat4 uMatrix;" +
"void main() {" +
" gl_Position = uMatrix * aPosition ;" +
" vCoordinate = aCoordinate ;" +
"}";
private static final String FRAGMENT_SOURCE = " precision mediump float;\n" +
" uniform sampler2D vTexture;\n" +
" varying vec2 vCoordinate;\n" +
" void main(){\n" +
" gl_FragColor=texture2D(vTexture,vCoordinate);\n" +
" }";
private final float[] sPos = {
/************左上角************/
-1.0f, 1.0f,
-1.0f, 0.0f,
0.0f, 1.0f,
0.0f, 0.0f,
/************右上角************/
0.0f, 1.0f,
0.0f, 0.0f,
1.0f, 1.0f,
1.0f, 0.0f,
/************左下角************/
-1.0f, 0.0f,
-1.0f, -1.0f,
0.0f, 0.0f,
0.0f, -1.0f,
/************右下角************/
0.0f, 0.0f,
0.0f, -1.0f,
1.0f, 0.0f,
1.0f, -1.0f,
};
private final float[] sCoord = {
0.0f, 0.0f,
0.0f, 1.0f,
1.0f, 0.0f,
1.0f, 1.0f,
0.0f, 0.0f,
0.0f, 1.0f,
1.0f, 0.0f,
1.0f, 1.0f,
0.0f, 0.0f,
0.0f, 1.0f,
1.0f, 0.0f,
1.0f, 1.0f,
0.0f, 0.0f,
0.0f, 1.0f,
1.0f, 0.0f,
1.0f, 1.0f,
};
private final int[] index = {
0, 1, 2,
2, 1, 3,
4, 5, 6,
6, 5, 7,
8, 9, 10,
10, 9, 11,
12, 13, 14,
14, 13, 15
};
private Bitmap mBitmap;
private float mProjectMatrix[] = new float[16];
float[] mViewMatrix = new float[16];
float[] mMVPMatrix = new float[16];
private int textureId;
private int mProgram;
private FloatBuffer mVertexBuff;
private FloatBuffer mColorBuff;
private IntBuffer mIndexBuff;
public Demo012GLSurfaceView(Context context) {
this(context, null);
}
public Demo012GLSurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
setEGLContextClientVersion(2);
setEGLConfigChooser(8, 8, 8, 8, 8, 0);
setRenderer(this);
setRenderMode(RENDERMODE_WHEN_DIRTY);
}
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
GLES20.glClearColor(0.5f, 0.5f, 0.5f, 1.0f);//设置清屏颜色,只有你调用 GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);起作用
ByteBuffer bb = ByteBuffer.allocateDirect(sPos.length * 4);//分配
bb.order(ByteOrder.nativeOrder());//一定要用native的字节序 (大小端字节问题)
mVertexBuff = bb.asFloatBuffer();
mVertexBuff.put(sPos);/*讲数据填入*/
mVertexBuff.position(0);/*读/写的数据的索引*/
ByteBuffer bc = ByteBuffer.allocateDirect(sCoord.length * 4);
bc.order(ByteOrder.nativeOrder());
mColorBuff = bc.asFloatBuffer();
mColorBuff.put(sCoord);
mColorBuff.position(0);
ByteBuffer bi = ByteBuffer.allocateDirect(index.length * 4);
bi.order(ByteOrder.nativeOrder());
mIndexBuff = bi.asIntBuffer();
mIndexBuff.put(index);
mIndexBuff.position(0);
int vertex_shader = GLES20.glCreateShader(GLES20.GL_VERTEX_SHADER);/**创建一个Shader对象*/
if (vertex_shader != 0) {
GLES20.glShaderSource(vertex_shader, VERREXT_SOURECE);/**绑定源码*/
GLES20.glCompileShader(vertex_shader);/**编译*/
int[] complied = new int[1];
GLES20.glGetShaderiv(vertex_shader, GLES20.GL_COMPILE_STATUS, complied, 0);
if (complied[0] == 0) {
Log.e("GLES", "GL_VERTEX_SHADER Error!!!!" + GLES20.glGetShaderInfoLog(vertex_shader));
GLES20.glDeleteShader(vertex_shader);
vertex_shader = 0;
}
}
int fragment_shader = GLES20.glCreateShader(GLES20.GL_FRAGMENT_SHADER);
if (fragment_shader != 0) {
GLES20.glShaderSource(fragment_shader, FRAGMENT_SOURCE);
GLES20.glCompileShader(fragment_shader);
int[] complied = new int[1];
GLES20.glGetShaderiv(fragment_shader, GLES20.GL_COMPILE_STATUS, complied, 0);
if (complied[0] == 0) {
Log.e("GLES", "GL_FRAGMENT_SHADER Error!!!!");
GLES20.glDeleteShader(fragment_shader);
fragment_shader = 0;
}
}
mProgram = GLES20.glCreateProgram();
if (mProgram != 0) {
GLES20.glAttachShader(mProgram, vertex_shader);
GLES20.glAttachShader(mProgram, fragment_shader);
GLES20.glLinkProgram(mProgram);
int linked[] = new int[1];
GLES20.glGetProgramiv(mProgram, GLES20.GL_LINK_STATUS, linked, 0);
if (linked[0] == 0) {
Log.e("GLES", "linked Error!!!!");
GLES20.glDeleteProgram(mProgram);
mProgram = 0;
}
}
}
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
GLES20.glViewport(0, 0, width, height);
mBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.test);
int w = mBitmap.getWidth();
int h = mBitmap.getHeight();
float sWH = w / (float) h;
float sWidthHeight = width / (float) height;
if (width > height) {
if (sWH > sWidthHeight) {
Matrix.orthoM(mProjectMatrix, 0, -sWidthHeight * sWH, sWidthHeight * sWH, -1, 1, 3, 7);
} else {
Matrix.orthoM(mProjectMatrix, 0, -sWidthHeight / sWH, sWidthHeight / sWH, -1, 1, 3, 7);
}
} else {
if (sWH > sWidthHeight) {
Matrix.orthoM(mProjectMatrix, 0, -1, 1, -1 / sWidthHeight * sWH, 1 / sWidthHeight * sWH, 3, 7);
} else {
Matrix.orthoM(mProjectMatrix, 0, -1, 1, -sWH / sWidthHeight, sWH / sWidthHeight, 3, 7);
}
}
//设置相机位置
Matrix.setLookAtM(mViewMatrix, 0, 0, 0, 7.0f, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
//计算变换矩阵
Matrix.multiplyMM(mMVPMatrix, 0, mProjectMatrix, 0, mViewMatrix, 0);
requestRender();
}
@Override
public void onDrawFrame(GL10 gl) {
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
GLES20.glUseProgram(mProgram);
int glHMatrix = GLES20.glGetUniformLocation(mProgram, "uMatrix");
GLES20.glUniformMatrix4fv(glHMatrix, 1, false, mMVPMatrix, 0);
int glHPosition = GLES20.glGetAttribLocation(mProgram, "aPosition");
int glHCoordinate = GLES20.glGetAttribLocation(mProgram, "aCoordinate");
GLES20.glEnableVertexAttribArray(glHPosition);
GLES20.glEnableVertexAttribArray(glHCoordinate);
int glHTexture = GLES20.glGetUniformLocation(mProgram, "vTexture");
GLES20.glVertexAttribPointer(glHPosition, 2, GLES20.GL_FLOAT, false, 0, mVertexBuff);
//传入纹理坐标
GLES20.glVertexAttribPointer(glHCoordinate, 2, GLES20.GL_FLOAT, false, 0, mColorBuff);
createTexture(R.mipmap.test, 0);
GLES20.glUniform1i(glHTexture, 0);
//传入顶点坐标
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
createTexture(R.mipmap.moto, 1);
GLES20.glUniform1i(glHTexture, 1);
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 1 * 4, 4);
createTexture(R.mipmap.moto, 2);
GLES20.glUniform1i(glHTexture, 2);
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 2 * 4, 4);
createTexture(R.mipmap.test, 3);
GLES20.glUniform1i(glHTexture, 3);
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 3 * 4, 4);
}
private void createTexture(int resId, int i) {
int[] texture = new int[1];
mBitmap = BitmapFactory.decodeResource(getResources(), resId);
if (mBitmap != null && !mBitmap.isRecycled()) {
//生成纹理
GLES20.glGenTextures(1, texture, 0);
GLES20.glActiveTexture(GLES20.GL_TEXTURE0 + i);
//生成纹理
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texture[0]);
//设置缩小过滤为使用纹理中坐标最接近的一个像素的颜色作为需要绘制的像素颜色
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST);
//设置放大过滤为使用纹理中坐标最接近的若干个颜色,通过加权平均算法得到需要绘制的像素颜色
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
//设置环绕方向S,截取纹理坐标到[1/2n,1-1/2n]。将导致永远不会与border融合
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
//设置环绕方向T,截取纹理坐标到[1/2n,1-1/2n]。将导致永远不会与border融合
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);
//根据以上指定的参数,生成一个2D纹理
GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, mBitmap, 0);
}
}
}
|
**旋转变形的问题
|
app/src/main/java/com/tp/gl/demo002/Demo012GLSurfaceView.java
|
**旋转变形的问题
|
<ide><path>pp/src/main/java/com/tp/gl/demo002/Demo012GLSurfaceView.java
<ide> import android.opengl.GLSurfaceView;
<ide> import android.opengl.GLUtils;
<ide> import android.opengl.Matrix;
<add>import android.os.SystemClock;
<ide> import android.util.AttributeSet;
<ide> import android.util.Log;
<ide>
<ide> "attribute vec2 aCoordinate;" +
<ide> "varying vec2 vCoordinate;" +
<ide> "uniform mat4 uMatrix;" +
<add> "varying mat4 vMatrix;" +
<ide> "void main() {" +
<ide> " gl_Position = uMatrix * aPosition ;" +
<ide> " vCoordinate = aCoordinate ;" +
<add> " vMatrix = uMatrix;" +
<ide> "}";
<ide> private static final String FRAGMENT_SOURCE = " precision mediump float;\n" +
<ide> " uniform sampler2D vTexture;\n" +
<ide> " varying vec2 vCoordinate;\n" +
<add> " varying mat4 vMatrix;" +
<ide> " void main(){\n" +
<del> " gl_FragColor=texture2D(vTexture,vCoordinate);\n" +
<add>// " gl_FragColor = texture2D(vTexture,(vMatrix * vec4(vCoordinate - vec2(0.5), 0.0, 1.0)).xy + vec2(0.5)); " +
<add>// " gl_FragColor=texture2D(vTexture,vCoordinate);\n" +
<add> " gl_FragColor=vec4(1.0,1.0,0.0,1.0);\n" +
<ide> " }";
<ide> private final float[] sPos = {
<del> /************左上角************/
<add>// /************左上角************/
<add>// -1.0f, 1.0f,
<add>// -1.0f, 0.0f,
<add>// 0.0f, 1.0f,
<add>// 0.0f, 0.0f,
<add>// /************右上角************/
<add>// 0.0f, 1.0f,
<add>// 0.0f, 0.0f,
<add>// 1.0f, 1.0f,
<add>// 1.0f, 0.0f,
<add>// /************左下角************/
<add>// -1.0f, 0.0f,
<add>// -1.0f, -1.0f,
<add>// 0.0f, 0.0f,
<add>// 0.0f, -1.0f,
<add>// /************右下角************/
<add>// 0.0f, 0.0f,
<add>// 0.0f, -1.0f,
<add>// 1.0f, 0.0f,
<add>// 1.0f, -1.0f,
<ide> -1.0f, 1.0f,
<del> -1.0f, 0.0f,
<del> 0.0f, 1.0f,
<del> 0.0f, 0.0f,
<del> /************右上角************/
<del> 0.0f, 1.0f,
<del> 0.0f, 0.0f,
<del> 1.0f, 1.0f,
<del> 1.0f, 0.0f,
<del> /************左下角************/
<del> -1.0f, 0.0f,
<ide> -1.0f, -1.0f,
<del> 0.0f, 0.0f,
<del> 0.0f, -1.0f,
<del> /************右下角************/
<del> 0.0f, 0.0f,
<del> 0.0f, -1.0f,
<del> 1.0f, 0.0f,
<del> 1.0f, -1.0f,
<add> 1.0f, 1.0f,
<add> 1.0f, -1.0f
<ide>
<ide>
<ide> };
<ide> setEGLContextClientVersion(2);
<ide> setEGLConfigChooser(8, 8, 8, 8, 8, 0);
<ide> setRenderer(this);
<del> setRenderMode(RENDERMODE_WHEN_DIRTY);
<add> setRenderMode(RENDERMODE_CONTINUOUSLY);
<ide> }
<ide>
<ide> @Override
<ide> requestRender();
<ide> }
<ide>
<add> /**
<add> * 旋转变形( Matrix.multiplyMM 该方法来整合最初的 矩阵 以及投影矩阵)
<add> * @param gl
<add> */
<ide> @Override
<ide> public void onDrawFrame(GL10 gl) {
<ide> GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
<ide> GLES20.glUseProgram(mProgram);
<ide> int glHMatrix = GLES20.glGetUniformLocation(mProgram, "uMatrix");
<del> GLES20.glUniformMatrix4fv(glHMatrix, 1, false, mMVPMatrix, 0);
<add> long time = SystemClock.uptimeMillis() % 4000L;
<add> float angle = 0.090f * ((int) time);
<add> float[] mRotationMatrix = new float[16];
<add> Matrix.setRotateM(mRotationMatrix, 0, angle, 0, 0, -1.0f);
<add>
<add> float[] result = new float[16];
<add> Matrix.multiplyMM(result, 0, mMVPMatrix, 0, mRotationMatrix, 0);
<add> GLES20.glUniformMatrix4fv(glHMatrix, 1, false, result, 0);
<ide> int glHPosition = GLES20.glGetAttribLocation(mProgram, "aPosition");
<ide> int glHCoordinate = GLES20.glGetAttribLocation(mProgram, "aCoordinate");
<ide> GLES20.glEnableVertexAttribArray(glHPosition);
<ide> GLES20.glUniform1i(glHTexture, 0);
<ide> //传入顶点坐标
<ide> GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
<del>
<del> createTexture(R.mipmap.moto, 1);
<del> GLES20.glUniform1i(glHTexture, 1);
<del> GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 1 * 4, 4);
<del> createTexture(R.mipmap.moto, 2);
<del> GLES20.glUniform1i(glHTexture, 2);
<del> GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 2 * 4, 4);
<del> createTexture(R.mipmap.test, 3);
<del> GLES20.glUniform1i(glHTexture, 3);
<del> GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 3 * 4, 4);
<add>// Matrix.setIdentityM(mMVPMatrix, 0);
<add>// Matrix.setRotateM(mMVPMatrix, 0, 30, 0.5f, 0.5f, 0);
<add>// GLES20.glUniformMatrix4fv(glHMatrix, 1, false, mMVPMatrix, 0);
<add>// createTexture(R.mipmap.moto, 1);
<add>// GLES20.glUniform1i(glHTexture, 1);
<add>// GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 1 * 4, 4);
<add>// Matrix.setIdentityM(mMVPMatrix, 0);
<add>// Matrix.setRotateM(mMVPMatrix, 0, 30, 0.5f, 0.5f, 0);
<add>// GLES20.glUniformMatrix4fv(glHMatrix, 1, false, mMVPMatrix, 0);
<add>// createTexture(R.mipmap.moto, 2);
<add>// GLES20.glUniform1i(glHTexture, 2);
<add>// GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 2 * 4, 4);
<add>// Matrix.setIdentityM(mMVPMatrix, 0);
<add>// Matrix.setRotateM(mMVPMatrix, 0, 30, 0.5f, 0.5f, 0);
<add>// GLES20.glUniformMatrix4fv(glHMatrix, 1, false, mMVPMatrix, 0);
<add>// createTexture(R.mipmap.test, 3);
<add>// GLES20.glUniform1i(glHTexture, 3);
<add>// GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 3 * 4, 4);
<ide> }
<ide>
<ide> private void createTexture(int resId, int i) {
|
|
JavaScript
|
mit
|
1a5ed5b574ff706eb0e609f21dd731ca965af730
| 0 |
mnutt/hid.im-firefox,mnutt/hid.im-firefox
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is hid.im.
*
* The Initial Developer of the Original Code is
* Michael Nutt.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
var hidim = {
onLoad: function() {
// initialization code
this.initialized = true;
this.strings = document.getElementById("hidim-strings");
document.getElementById("contentAreaContextMenu")
.addEventListener("popupshowing", function(e) { hidim.showContextMenu(e); }, false);
},
showContextMenu: function(event) {
// show or hide the menuitem based on what the context menu is on
// see http://kb.mozillazine.org/Adding_items_to_menus
document.getElementById("context-hidim").hidden = !gContextMenu.onImage;
},
onMenuItemCommand: function(e) {
var torrent = PngReader.readPng(gContextMenu.target);
if(!torrent) {
alert("The image is either not a torrent or corrupted.");
return false;
}
// Check to make sure stated sha1 matches computed sha1
if(torrent.file.sha1 != torrent.sha1) {
alert("The torrent seems to be corrupted.");
return false;
}
const nsIFilePicker = Components.interfaces.nsIFilePicker;
var fp = Components.classes["@mozilla.org/filepicker;1"]
.createInstance(Components.interfaces.nsIFilePicker);
fp.init(window, "Save Torrent As...", nsIFilePicker.modeSave);
fp.appendFilter("Torrents", "*.torrent");
fp.appendFilters(0x01);
// Make sure it gets saved as a .torrent, no cheating...
if(!torrent.fileName.match(/\.torrent$/)) {
torrent.fileName = torrent.fileName + ".torrent";
}
fp.defaultString = torrent.fileName;
var rv = fp.show();
if (rv == nsIFilePicker.returnOK || rv == nsIFilePicker.returnReplace) {
var aFile = Components.classes["@mozilla.org/file/local;1"]
.createInstance(Components.interfaces.nsILocalFile);
aFile.initWithPath(fp.file.path);
aFile.createUnique( Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0600);
var stream = Components.classes["@mozilla.org/network/safe-file-output-stream;1"].
createInstance(Components.interfaces.nsIFileOutputStream);
stream.init(aFile, 0x02 | 0x08 | 0x20, 0600, 0); // write, create, truncate
stream.write(torrent.file.data, torrent.file.data.length);
if (stream instanceof Components.interfaces.nsISafeOutputStream) {
stream.finish();
} else {
stream.close();
}
}
}
};
window.addEventListener("load", function(e) { hidim.onLoad(e); }, false);
|
content/overlay.js
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is hid.im.
*
* The Initial Developer of the Original Code is
* Michael Nutt.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
var hidim = {
onLoad: function() {
// initialization code
this.initialized = true;
this.strings = document.getElementById("hidim-strings");
document.getElementById("contentAreaContextMenu")
.addEventListener("popupshowing", function(e) { hidim.showContextMenu(e); }, false);
},
showContextMenu: function(event) {
// show or hide the menuitem based on what the context menu is on
// see http://kb.mozillazine.org/Adding_items_to_menus
document.getElementById("context-hidim").hidden = !gContextMenu.onImage;
},
onMenuItemCommand: function(e) {
var torrent = PngReader.readPng(gContextMenu.target);
if(!torrent) {
alert("The image is either not a torrent or corrupted.");
return false;
}
// Check to make sure stated sha1 matches computed sha1
if(torrent.file.sha1 != torrent.sha1) {
alert("The torrent seems to be corrupted.");
return false;
}
const nsIFilePicker = Components.interfaces.nsIFilePicker;
var fp = Components.classes["@mozilla.org/filepicker;1"]
.createInstance(Components.interfaces.nsIFilePicker);
fp.init(window, "Save Torrent As...", nsIFilePicker.modeSave);
fp.appendFilter("Torrents", "*.torrent");
fp.appendFilters(0x01);
// Make sure it gets saved as a .torrent, no cheating...
if(!torrent.fileName.match(/\.torrent$/)) {
torrent.fileName = torrent.fileName + ".torrent";
}
fp.defaultString = torrent.fileName;
var rv = fp.show();
if (rv == nsIFilePicker.returnOK || rv == nsIFilePicker.returnReplace) {
var aFile = Components.classes["@mozilla.org/file/local;1"]
.createInstance(Components.interfaces.nsILocalFile);
aFile.initWithPath(fp.file.path);
aFile.createUnique( Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 600);
var stream = Components.classes["@mozilla.org/network/safe-file-output-stream;1"].
createInstance(Components.interfaces.nsIFileOutputStream);
stream.init(aFile, 0x02 | 0x08 | 0x20, 0600, 0); // write, create, truncate
stream.write(torrent.file.data, torrent.file.data.length);
if (stream instanceof Components.interfaces.nsISafeOutputStream) {
stream.finish();
} else {
stream.close();
}
}
}
};
window.addEventListener("load", function(e) { hidim.onLoad(e); }, false);
|
Fix permissions issue where generated torrent was unreadable
|
content/overlay.js
|
Fix permissions issue where generated torrent was unreadable
|
<ide><path>ontent/overlay.js
<ide> var aFile = Components.classes["@mozilla.org/file/local;1"]
<ide> .createInstance(Components.interfaces.nsILocalFile);
<ide> aFile.initWithPath(fp.file.path);
<del> aFile.createUnique( Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 600);
<add> aFile.createUnique( Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0600);
<ide>
<ide> var stream = Components.classes["@mozilla.org/network/safe-file-output-stream;1"].
<ide> createInstance(Components.interfaces.nsIFileOutputStream);
|
|
Java
|
apache-2.0
|
efabc3c28549209ab060bed785ca6541b2e35474
| 0 |
blademainer/netty,lukw00/netty,Alwayswithme/netty,zzcclp/netty,normanmaurer/netty,netty/netty,mosoft521/netty,Spikhalskiy/netty,satishsaley/netty,imangry/netty-zh,dongjiaqiang/netty,drowning/netty,DavidAlphaFox/netty,ioanbsu/netty,blucas/netty,wuyinxian124/netty,Techcable/netty,balaprasanna/netty,ajaysarda/netty,DavidAlphaFox/netty,SinaTadayon/netty,orika/netty,caoyanwei/netty,Scottmitch/netty,cnoldtree/netty,jongyeol/netty,nat2013/netty,carl-mastrangelo/netty,WangJunTYTL/netty,nadeeshaan/netty,idelpivnitskiy/netty,zhujingling/netty,chrisprobst/netty,eonezhang/netty,netty/netty,golovnin/netty,mway08/netty,yawkat/netty,buchgr/netty,Alwayswithme/netty,johnou/netty,huuthang1993/netty,artgon/netty,NiteshKant/netty,windie/netty,netty/netty,wuxiaowei907/netty,artgon/netty,carl-mastrangelo/netty,sammychen105/netty,hyangtack/netty,gerdriesselmann/netty,mikkokar/netty,ninja-/netty,Apache9/netty,orika/netty,xingguang2013/netty,eonezhang/netty,tbrooks8/netty,unei66/netty,Kingson4Wu/netty,slandelle/netty,x1957/netty,nayato/netty,fengjiachun/netty,menacher/netty,chrisprobst/netty,Spikhalskiy/netty,timboudreau/netty,chinayin/netty,tempbottle/netty,MediumOne/netty,codevelop/netty,golovnin/netty,zer0se7en/netty,SinaTadayon/netty,wangyikai/netty,mway08/netty,purplefox/netty-4.0.2.8-hacked,woshilaiceshide/netty,alkemist/netty,serioussam/netty,zzcclp/netty,nadeeshaan/netty,mubarak/netty,blademainer/netty,moyiguket/netty,ichaki5748/netty,johnou/netty,tbrooks8/netty,skyao/netty,mosoft521/netty,danbev/netty,ijuma/netty,netty/netty,afredlyj/learn-netty,wuxiaowei907/netty,gerdriesselmann/netty,fenik17/netty,bigheary/netty,drowning/netty,jdivy/netty,unei66/netty,carl-mastrangelo/netty,Squarespace/netty,castomer/netty,ejona86/netty,sverkera/netty,maliqq/netty,carl-mastrangelo/netty,lightsocks/netty,chinayin/netty,andsel/netty,dongjiaqiang/netty,liuciuse/netty,bob329/netty,exinguu/netty,qingsong-xu/netty,jovezhougang/netty,xiongzheng/netty,andsel/netty,ngocdaothanh/netty,fenik17/netty,gigold/netty,buchgr/netty,hgl888/netty,pengzj/netty,altihou/netty,sunbeansoft/netty,hepin1989/netty,luyiisme/netty,silvaran/netty,orika/netty,nayato/netty,rovarga/netty,zhujingling/netty,JungMinu/netty,xiexingguang/netty,xiexingguang/netty,Kalvar/netty,brennangaunce/netty,woshilaiceshide/netty,imangry/netty-zh,jchambers/netty,carlbai/netty,altihou/netty,kiril-me/netty,qingsong-xu/netty,slandelle/netty,DolphinZhao/netty,afds/netty,olupotd/netty,liyang1025/netty,sverkera/netty,imangry/netty-zh,alkemist/netty,DolphinZhao/netty,IBYoung/netty,phlizik/netty,chinayin/netty,bob329/netty,lukw00/netty,olupotd/netty,hepin1989/netty,DavidAlphaFox/netty,zxhfirefox/netty,smayoorans/netty,firebase/netty,Kingson4Wu/netty,mx657649013/netty,moyiguket/netty,maliqq/netty,shuangqiuan/netty,chanakaudaya/netty,nkhuyu/netty,serioussam/netty,KatsuraKKKK/netty,junjiemars/netty,wangyikai/netty,blucas/netty,shenguoquan/netty,hyangtack/netty,jchambers/netty,lukehutch/netty,SinaTadayon/netty,ngocdaothanh/netty,normanmaurer/netty,mx657649013/netty,Squarespace/netty,unei66/netty,Kingson4Wu/netty,silvaran/netty,satishsaley/netty,SinaTadayon/netty,phlizik/netty,xingguang2013/netty,ichaki5748/netty,wuyinxian124/netty,lugt/netty,IBYoung/netty,DolphinZhao/netty,afds/netty,castomer/netty,johnou/netty,eonezhang/netty,niuxinghua/netty,blademainer/netty,zzcclp/netty,ngocdaothanh/netty,serioussam/netty,mcanthony/netty,altihou/netty,s-gheldd/netty,seetharamireddy540/netty,AchinthaReemal/netty,tbrooks8/netty,unei66/netty,lukehutch/netty,bigheary/netty,huuthang1993/netty,yonglehou/netty-1,yawkat/netty,timboudreau/netty,hyangtack/netty,zhoffice/netty,fenik17/netty,liuciuse/netty,exinguu/netty,satishsaley/netty,KatsuraKKKK/netty,jenskordowski/netty,clebertsuconic/netty,gigold/netty,nmittler/netty,maliqq/netty,f7753/netty,junjiemars/netty,blucas/netty,maliqq/netty,sja/netty,lugt/netty,lukw00/netty,duqiao/netty,KatsuraKKKK/netty,BrunoColin/netty,Squarespace/netty,lukehutch/netty,Techcable/netty,louiscryan/netty,WangJunTYTL/netty,silvaran/netty,kvr000/netty,louxiu/netty,lugt/netty,BrunoColin/netty,clebertsuconic/netty,huanyi0723/netty,louxiu/netty,jenskordowski/netty,liuciuse/netty,yrcourage/netty,ninja-/netty,Alwayswithme/netty,brennangaunce/netty,lugt/netty,silvaran/netty,doom369/netty,bigheary/netty,rovarga/netty,seetharamireddy540/netty,JungMinu/netty,duqiao/netty,hyangtack/netty,Mounika-Chirukuri/netty,sunbeansoft/netty,yipen9/netty,huanyi0723/netty,Spikhalskiy/netty,x1957/netty,fengshao0907/netty,hepin1989/netty,shuangqiuan/netty,mcobrien/netty,rovarga/netty,fantayeneh/netty,Kalvar/netty,shelsonjava/netty,djchen/netty,zzcclp/netty,jdivy/netty,danny200309/netty,AnselQiao/netty,altihou/netty,alkemist/netty,windie/netty,codevelop/netty,caoyanwei/netty,kvr000/netty,ninja-/netty,purplefox/netty-4.0.2.8-hacked,Techcable/netty,lznhust/netty,clebertsuconic/netty,sameira/netty,nat2013/netty,zhoffice/netty,louiscryan/netty,moyiguket/netty,huuthang1993/netty,louiscryan/netty,jdivy/netty,caoyanwei/netty,rovarga/netty,AchinthaReemal/netty,eincs/netty,f7753/netty,liyang1025/netty,AchinthaReemal/netty,purplefox/netty-4.0.2.8-hacked,jenskordowski/netty,afds/netty,balaprasanna/netty,smayoorans/netty,windie/netty,kiril-me/netty,s-gheldd/netty,f7753/netty,junjiemars/netty,f7753/netty,Alwayswithme/netty,youprofit/netty,jdivy/netty,chrisprobst/netty,exinguu/netty,hgl888/netty,skyao/netty,timboudreau/netty,serioussam/netty,dongjiaqiang/netty,brennangaunce/netty,zhoffice/netty,MediumOne/netty,jovezhougang/netty,satishsaley/netty,NiteshKant/netty,lznhust/netty,imangry/netty-zh,AnselQiao/netty,youprofit/netty,ifesdjeen/netty,exinguu/netty,cnoldtree/netty,netty/netty,ioanbsu/netty,AnselQiao/netty,blademainer/netty,mx657649013/netty,golovnin/netty,eincs/netty,niuxinghua/netty,WangJunTYTL/netty,hepin1989/netty,fenik17/netty,yrcourage/netty,wuxiaowei907/netty,kvr000/netty,IBYoung/netty,chanakaudaya/netty,jovezhougang/netty,louxiu/netty,danbev/netty,jroper/netty,joansmith/netty,hgl888/netty,Mounika-Chirukuri/netty,kjniemi/netty,slandelle/netty,mubarak/netty,fenik17/netty,qingsong-xu/netty,s-gheldd/netty,mikkokar/netty,daschl/netty,lukw00/netty,firebase/netty,Spikhalskiy/netty,golovnin/netty,blucas/netty,fantayeneh/netty,sammychen105/netty,ijuma/netty,ijuma/netty,mcanthony/netty,bryce-anderson/netty,Kalvar/netty,mway08/netty,djchen/netty,sja/netty,nayato/netty,xingguang2013/netty,develar/netty,mx657649013/netty,qingsong-xu/netty,shenguoquan/netty,zhujingling/netty,mcobrien/netty,duqiao/netty,codevelop/netty,LuminateWireless/netty,sverkera/netty,AnselQiao/netty,Kalvar/netty,windie/netty,wangyikai/netty,fantayeneh/netty,junjiemars/netty,phlizik/netty,drowning/netty,johnou/netty,gigold/netty,danny200309/netty,youprofit/netty,niuxinghua/netty,sammychen105/netty,pengzj/netty,zxhfirefox/netty,sunbeansoft/netty,clebertsuconic/netty,luyiisme/netty,pengzj/netty,ioanbsu/netty,BrunoColin/netty,lznhust/netty,woshilaiceshide/netty,moyiguket/netty,codevelop/netty,alkemist/netty,jongyeol/netty,imangry/netty-zh,jdivy/netty,artgon/netty,artgon/netty,cnoldtree/netty,lightsocks/netty,tempbottle/netty,carlbai/netty,kiril-me/netty,ejona86/netty,buchgr/netty,eonezhang/netty,orika/netty,gerdriesselmann/netty,lznhust/netty,nayato/netty,serioussam/netty,ejona86/netty,doom369/netty,ajaysarda/netty,bob329/netty,gerdriesselmann/netty,nayato/netty,shelsonjava/netty,louiscryan/netty,LuminateWireless/netty,fantayeneh/netty,skyao/netty,eincs/netty,nkhuyu/netty,CodingFabian/netty,Scottmitch/netty,yrcourage/netty,yonglehou/netty-1,drowning/netty,fengjiachun/netty,seetharamireddy540/netty,niuxinghua/netty,carlbai/netty,danbev/netty,fengjiachun/netty,BrunoColin/netty,lugt/netty,WangJunTYTL/netty,yipen9/netty,IBYoung/netty,lightsocks/netty,qingsong-xu/netty,lukehutch/netty,louxiu/netty,x1957/netty,kyle-liu/netty4study,normanmaurer/netty,JungMinu/netty,sja/netty,Scottmitch/netty,alkemist/netty,balaprasanna/netty,lightsocks/netty,DavidAlphaFox/netty,jovezhougang/netty,ichaki5748/netty,unei66/netty,kyle-liu/netty4study,sverkera/netty,eonezhang/netty,bigheary/netty,firebase/netty,zzcclp/netty,artgon/netty,danny200309/netty,SinaTadayon/netty,wangyikai/netty,orika/netty,nat2013/netty,skyao/netty,smayoorans/netty,ninja-/netty,shelsonjava/netty,huuthang1993/netty,chrisprobst/netty,yrcourage/netty,zer0se7en/netty,JungMinu/netty,djchen/netty,danbev/netty,mcanthony/netty,x1957/netty,MediumOne/netty,ngocdaothanh/netty,ifesdjeen/netty,duqiao/netty,nadeeshaan/netty,develar/netty,bryce-anderson/netty,Techcable/netty,kiril-me/netty,Squarespace/netty,kiril-me/netty,wuxiaowei907/netty,mubarak/netty,cnoldtree/netty,chinayin/netty,Alwayswithme/netty,moyiguket/netty,mway08/netty,hgl888/netty,zer0se7en/netty,shelsonjava/netty,chanakaudaya/netty,shenguoquan/netty,shism/netty,Spikhalskiy/netty,doom369/netty,kjniemi/netty,mosoft521/netty,seetharamireddy540/netty,louiscryan/netty,jchambers/netty,nadeeshaan/netty,shism/netty,nkhuyu/netty,yipen9/netty,Kingson4Wu/netty,Techcable/netty,sameira/netty,ejona86/netty,NiteshKant/netty,mcanthony/netty,huanyi0723/netty,bryce-anderson/netty,kjniemi/netty,tempbottle/netty,mway08/netty,zhoffice/netty,nkhuyu/netty,junjiemars/netty,carlbai/netty,yrcourage/netty,mikkokar/netty,tempbottle/netty,shism/netty,sameira/netty,Mounika-Chirukuri/netty,shuangqiuan/netty,liyang1025/netty,nkhuyu/netty,joansmith/netty,nmittler/netty,mubarak/netty,LuminateWireless/netty,balaprasanna/netty,kvr000/netty,bigheary/netty,seetharamireddy540/netty,shism/netty,chanakaudaya/netty,balaprasanna/netty,skyao/netty,idelpivnitskiy/netty,djchen/netty,cnoldtree/netty,zhujingling/netty,duqiao/netty,woshilaiceshide/netty,sja/netty,castomer/netty,IBYoung/netty,zhujingling/netty,yonglehou/netty-1,nadeeshaan/netty,ijuma/netty,mcobrien/netty,blucas/netty,louxiu/netty,luyiisme/netty,ninja-/netty,zer0se7en/netty,Apache9/netty,windie/netty,shenguoquan/netty,eincs/netty,ajaysarda/netty,bryce-anderson/netty,ioanbsu/netty,gigold/netty,mosoft521/netty,afredlyj/learn-netty,yonglehou/netty-1,AchinthaReemal/netty,lightsocks/netty,wuyinxian124/netty,MediumOne/netty,brennangaunce/netty,fengshao0907/netty,chanakaudaya/netty,carl-mastrangelo/netty,Apache9/netty,tbrooks8/netty,liyang1025/netty,mcanthony/netty,xiongzheng/netty,woshilaiceshide/netty,KatsuraKKKK/netty,LuminateWireless/netty,xiongzheng/netty,luyiisme/netty,huanyi0723/netty,LuminateWireless/netty,brennangaunce/netty,afds/netty,daschl/netty,purplefox/netty-4.0.2.8-hacked,caoyanwei/netty,bob329/netty,s-gheldd/netty,ioanbsu/netty,hgl888/netty,jongyeol/netty,xiongzheng/netty,sameira/netty,jovezhougang/netty,sja/netty,carlbai/netty,f7753/netty,silvaran/netty,Squarespace/netty,nmittler/netty,yawkat/netty,ichaki5748/netty,AnselQiao/netty,xiongzheng/netty,shelsonjava/netty,smayoorans/netty,danny200309/netty,niuxinghua/netty,timboudreau/netty,shuangqiuan/netty,Scottmitch/netty,caoyanwei/netty,satishsaley/netty,xiexingguang/netty,yawkat/netty,mcobrien/netty,wangyikai/netty,sunbeansoft/netty,zxhfirefox/netty,mikkokar/netty,andsel/netty,mx657649013/netty,mosoft521/netty,liuciuse/netty,jongyeol/netty,johnou/netty,kjniemi/netty,xingguang2013/netty,KatsuraKKKK/netty,dongjiaqiang/netty,luyiisme/netty,yawkat/netty,normanmaurer/netty,phlizik/netty,MediumOne/netty,golovnin/netty,BrunoColin/netty,sameira/netty,doom369/netty,chinayin/netty,firebase/netty,fantayeneh/netty,ijuma/netty,bob329/netty,normanmaurer/netty,slandelle/netty,olupotd/netty,lukw00/netty,maliqq/netty,danbev/netty,mubarak/netty,jenskordowski/netty,Apache9/netty,mcobrien/netty,CodingFabian/netty,Mounika-Chirukuri/netty,Scottmitch/netty,fengjiachun/netty,CodingFabian/netty,jongyeol/netty,ngocdaothanh/netty,andsel/netty,castomer/netty,castomer/netty,xiexingguang/netty,wuxiaowei907/netty,mikkokar/netty,sverkera/netty,huanyi0723/netty,huuthang1993/netty,DolphinZhao/netty,yonglehou/netty-1,chrisprobst/netty,smayoorans/netty,gerdriesselmann/netty,fengjiachun/netty,zxhfirefox/netty,shenguoquan/netty,daschl/netty,NiteshKant/netty,liyang1025/netty,NiteshKant/netty,tbrooks8/netty,xingguang2013/netty,bryce-anderson/netty,Apache9/netty,afds/netty,fengshao0907/netty,buchgr/netty,zer0se7en/netty,x1957/netty,liuciuse/netty,gigold/netty,joansmith/netty,sunbeansoft/netty,djchen/netty,kjniemi/netty,ichaki5748/netty,danny200309/netty,CodingFabian/netty,timboudreau/netty,xiexingguang/netty,menacher/netty,idelpivnitskiy/netty,WangJunTYTL/netty,altihou/netty,AchinthaReemal/netty,idelpivnitskiy/netty,dongjiaqiang/netty,olupotd/netty,shuangqiuan/netty,ejona86/netty,Kalvar/netty,lukehutch/netty,DolphinZhao/netty,andsel/netty,youprofit/netty,afredlyj/learn-netty,jchambers/netty,zxhfirefox/netty,zhoffice/netty,jenskordowski/netty,doom369/netty,pengzj/netty,shism/netty,wuyinxian124/netty,ajaysarda/netty,youprofit/netty,CodingFabian/netty,s-gheldd/netty,jchambers/netty,yipen9/netty,exinguu/netty,joansmith/netty,clebertsuconic/netty,eincs/netty,olupotd/netty,Mounika-Chirukuri/netty,joansmith/netty,Kingson4Wu/netty,tempbottle/netty,ajaysarda/netty,lznhust/netty,blademainer/netty,idelpivnitskiy/netty,kvr000/netty
|
/*
* Copyright 2011 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly([email protected]) and Mark Adler([email protected])
* and contributors of zlib.
*/
package io.netty.util.internal.jzlib;
import io.netty.logging.InternalLogger;
import io.netty.logging.InternalLoggerFactory;
import io.netty.util.internal.jzlib.JZlib.WrapperType;
public final class ZStream {
private static final InternalLogger logger =
InternalLoggerFactory.getInstance(ZStream.class);
public byte[] next_in; // next input byte
public int next_in_index;
public int avail_in; // number of bytes available at next_in
public long total_in; // total nb of input bytes read so far
public byte[] next_out; // next output byte should be put there
public int next_out_index;
public int avail_out; // remaining free space at next_out
public long total_out; // total nb of bytes output so far
public String msg;
Deflate dstate;
Inflate istate;
long adler;
int crc32;
public int inflateInit() {
return inflateInit(JZlib.DEF_WBITS);
}
public int inflateInit(Enum<?> wrapperType) {
return inflateInit(JZlib.DEF_WBITS, wrapperType);
}
public int inflateInit(int w) {
return inflateInit(w, WrapperType.ZLIB);
}
public int inflateInit(int w, @SuppressWarnings("rawtypes") Enum wrapperType) {
istate = new Inflate();
return istate.inflateInit(this, w, (WrapperType) wrapperType);
}
public int inflate(int f) {
if (istate == null) {
return JZlib.Z_STREAM_ERROR;
}
return istate.inflate(this, f);
}
public int inflateEnd() {
if (istate == null) {
return JZlib.Z_STREAM_ERROR;
}
int ret = istate.inflateEnd(this);
istate = null;
return ret;
}
public int inflateSync() {
if (istate == null) {
return JZlib.Z_STREAM_ERROR;
}
return istate.inflateSync(this);
}
public int inflateSetDictionary(byte[] dictionary, int dictLength) {
if (istate == null) {
return JZlib.Z_STREAM_ERROR;
}
return istate.inflateSetDictionary(this, dictionary, dictLength);
}
public int deflateInit(int level) {
return deflateInit(level, JZlib.MAX_WBITS);
}
public int deflateInit(int level, Enum<?> wrapperType) {
return deflateInit(level, JZlib.MAX_WBITS, wrapperType);
}
public int deflateInit(int level, int bits) {
return deflateInit(level, bits, WrapperType.ZLIB);
}
public int deflateInit(int level, int bits, Enum<?> wrapperType) {
return deflateInit(level, bits, JZlib.DEF_MEM_LEVEL, wrapperType);
}
public int deflateInit(int level, int bits, int memLevel, @SuppressWarnings("rawtypes") Enum wrapperType) {
dstate = new Deflate();
return dstate.deflateInit(this, level, bits, memLevel, (WrapperType) wrapperType);
}
public int deflate(int flush) {
if (dstate == null) {
return JZlib.Z_STREAM_ERROR;
}
return dstate.deflate(this, flush);
}
public int deflateEnd() {
if (dstate == null) {
return JZlib.Z_STREAM_ERROR;
}
int ret = dstate.deflateEnd();
dstate = null;
return ret;
}
public int deflateParams(int level, int strategy) {
if (dstate == null) {
return JZlib.Z_STREAM_ERROR;
}
return dstate.deflateParams(this, level, strategy);
}
public int deflateSetDictionary(byte[] dictionary, int dictLength) {
if (dstate == null) {
return JZlib.Z_STREAM_ERROR;
}
return dstate.deflateSetDictionary(this, dictionary, dictLength);
}
// Flush as much pending output as possible. All deflate() output goes
// through this function so some applications may wish to modify it
// to avoid allocating a large strm->next_out buffer and copying into it.
// (See also read_buf()).
void flush_pending() {
int len = dstate.pending;
if (len > avail_out) {
len = avail_out;
}
if (len == 0) {
return;
}
if (dstate.pending_buf.length <= dstate.pending_out ||
next_out.length <= next_out_index ||
dstate.pending_buf.length < dstate.pending_out + len ||
next_out.length < next_out_index + len) {
logger.info(dstate.pending_buf.length + ", " +
dstate.pending_out + ", " + next_out.length + ", " +
next_out_index + ", " + len);
logger.info("avail_out=" + avail_out);
}
System.arraycopy(dstate.pending_buf, dstate.pending_out, next_out,
next_out_index, len);
next_out_index += len;
dstate.pending_out += len;
total_out += len;
avail_out -= len;
dstate.pending -= len;
if (dstate.pending == 0) {
dstate.pending_out = 0;
}
}
// Read a new buffer from the current input stream, update the adler32
// and total number of bytes read. All deflate() input goes through
// this function so some applications may wish to modify it to avoid
// allocating a large strm->next_in buffer and copying from it.
// (See also flush_pending()).
int read_buf(byte[] buf, int start, int size) {
int len = avail_in;
if (len > size) {
len = size;
}
if (len == 0) {
return 0;
}
avail_in -= len;
switch (dstate.wrapperType) {
case ZLIB:
adler = Adler32.adler32(adler, next_in, next_in_index, len);
break;
case GZIP:
crc32 = CRC32.crc32(crc32, next_in, next_in_index, len);
break;
}
System.arraycopy(next_in, next_in_index, buf, start, len);
next_in_index += len;
total_in += len;
return len;
}
public void free() {
next_in = null;
next_out = null;
msg = null;
}
}
|
common/src/main/java/io/netty/util/internal/jzlib/ZStream.java
|
/*
* Copyright 2011 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly([email protected]) and Mark Adler([email protected])
* and contributors of zlib.
*/
package io.netty.util.internal.jzlib;
import io.netty.util.internal.jzlib.JZlib.WrapperType;
public final class ZStream {
public byte[] next_in; // next input byte
public int next_in_index;
public int avail_in; // number of bytes available at next_in
public long total_in; // total nb of input bytes read so far
public byte[] next_out; // next output byte should be put there
public int next_out_index;
public int avail_out; // remaining free space at next_out
public long total_out; // total nb of bytes output so far
public String msg;
Deflate dstate;
Inflate istate;
long adler;
int crc32;
public int inflateInit() {
return inflateInit(JZlib.DEF_WBITS);
}
public int inflateInit(Enum<?> wrapperType) {
return inflateInit(JZlib.DEF_WBITS, wrapperType);
}
public int inflateInit(int w) {
return inflateInit(w, WrapperType.ZLIB);
}
public int inflateInit(int w, @SuppressWarnings("rawtypes") Enum wrapperType) {
istate = new Inflate();
return istate.inflateInit(this, w, (WrapperType) wrapperType);
}
public int inflate(int f) {
if (istate == null) {
return JZlib.Z_STREAM_ERROR;
}
return istate.inflate(this, f);
}
public int inflateEnd() {
if (istate == null) {
return JZlib.Z_STREAM_ERROR;
}
int ret = istate.inflateEnd(this);
istate = null;
return ret;
}
public int inflateSync() {
if (istate == null) {
return JZlib.Z_STREAM_ERROR;
}
return istate.inflateSync(this);
}
public int inflateSetDictionary(byte[] dictionary, int dictLength) {
if (istate == null) {
return JZlib.Z_STREAM_ERROR;
}
return istate.inflateSetDictionary(this, dictionary, dictLength);
}
public int deflateInit(int level) {
return deflateInit(level, JZlib.MAX_WBITS);
}
public int deflateInit(int level, Enum<?> wrapperType) {
return deflateInit(level, JZlib.MAX_WBITS, wrapperType);
}
public int deflateInit(int level, int bits) {
return deflateInit(level, bits, WrapperType.ZLIB);
}
public int deflateInit(int level, int bits, Enum<?> wrapperType) {
return deflateInit(level, bits, JZlib.DEF_MEM_LEVEL, wrapperType);
}
public int deflateInit(int level, int bits, int memLevel, @SuppressWarnings("rawtypes") Enum wrapperType) {
dstate = new Deflate();
return dstate.deflateInit(this, level, bits, memLevel, (WrapperType) wrapperType);
}
public int deflate(int flush) {
if (dstate == null) {
return JZlib.Z_STREAM_ERROR;
}
return dstate.deflate(this, flush);
}
public int deflateEnd() {
if (dstate == null) {
return JZlib.Z_STREAM_ERROR;
}
int ret = dstate.deflateEnd();
dstate = null;
return ret;
}
public int deflateParams(int level, int strategy) {
if (dstate == null) {
return JZlib.Z_STREAM_ERROR;
}
return dstate.deflateParams(this, level, strategy);
}
public int deflateSetDictionary(byte[] dictionary, int dictLength) {
if (dstate == null) {
return JZlib.Z_STREAM_ERROR;
}
return dstate.deflateSetDictionary(this, dictionary, dictLength);
}
// Flush as much pending output as possible. All deflate() output goes
// through this function so some applications may wish to modify it
// to avoid allocating a large strm->next_out buffer and copying into it.
// (See also read_buf()).
void flush_pending() {
int len = dstate.pending;
if (len > avail_out) {
len = avail_out;
}
if (len == 0) {
return;
}
if (dstate.pending_buf.length <= dstate.pending_out ||
next_out.length <= next_out_index ||
dstate.pending_buf.length < dstate.pending_out + len ||
next_out.length < next_out_index + len) {
System.out.println(dstate.pending_buf.length + ", " +
dstate.pending_out + ", " + next_out.length + ", " +
next_out_index + ", " + len);
System.out.println("avail_out=" + avail_out);
}
System.arraycopy(dstate.pending_buf, dstate.pending_out, next_out,
next_out_index, len);
next_out_index += len;
dstate.pending_out += len;
total_out += len;
avail_out -= len;
dstate.pending -= len;
if (dstate.pending == 0) {
dstate.pending_out = 0;
}
}
// Read a new buffer from the current input stream, update the adler32
// and total number of bytes read. All deflate() input goes through
// this function so some applications may wish to modify it to avoid
// allocating a large strm->next_in buffer and copying from it.
// (See also flush_pending()).
int read_buf(byte[] buf, int start, int size) {
int len = avail_in;
if (len > size) {
len = size;
}
if (len == 0) {
return 0;
}
avail_in -= len;
switch (dstate.wrapperType) {
case ZLIB:
adler = Adler32.adler32(adler, next_in, next_in_index, len);
break;
case GZIP:
crc32 = CRC32.crc32(crc32, next_in, next_in_index, len);
break;
}
System.arraycopy(next_in, next_in_index, buf, start, len);
next_in_index += len;
total_in += len;
return len;
}
public void free() {
next_in = null;
next_out = null;
msg = null;
}
}
|
Use a logger in ZStream
|
common/src/main/java/io/netty/util/internal/jzlib/ZStream.java
|
Use a logger in ZStream
|
<ide><path>ommon/src/main/java/io/netty/util/internal/jzlib/ZStream.java
<ide> */
<ide> package io.netty.util.internal.jzlib;
<ide>
<add>import io.netty.logging.InternalLogger;
<add>import io.netty.logging.InternalLoggerFactory;
<ide> import io.netty.util.internal.jzlib.JZlib.WrapperType;
<ide>
<ide> public final class ZStream {
<add>
<add> private static final InternalLogger logger =
<add> InternalLoggerFactory.getInstance(ZStream.class);
<ide>
<ide> public byte[] next_in; // next input byte
<ide> public int next_in_index;
<ide> next_out.length <= next_out_index ||
<ide> dstate.pending_buf.length < dstate.pending_out + len ||
<ide> next_out.length < next_out_index + len) {
<del> System.out.println(dstate.pending_buf.length + ", " +
<add> logger.info(dstate.pending_buf.length + ", " +
<ide> dstate.pending_out + ", " + next_out.length + ", " +
<ide> next_out_index + ", " + len);
<del> System.out.println("avail_out=" + avail_out);
<add> logger.info("avail_out=" + avail_out);
<ide> }
<ide>
<ide> System.arraycopy(dstate.pending_buf, dstate.pending_out, next_out,
|
|
Java
|
apache-2.0
|
a52439647562f842ec2dd8a70427bd8af6e30e87
| 0 |
liuciuse/netty,Mounika-Chirukuri/netty,golovnin/netty,mcobrien/netty,unei66/netty,skyao/netty,blademainer/netty,gerdriesselmann/netty,jenskordowski/netty,luyiisme/netty,blucas/netty,DolphinZhao/netty,Apache9/netty,maliqq/netty,f7753/netty,jenskordowski/netty,seetharamireddy540/netty,carl-mastrangelo/netty,djchen/netty,fenik17/netty,wangyikai/netty,BrunoColin/netty,xiongzheng/netty,exinguu/netty,LuminateWireless/netty,idelpivnitskiy/netty,zhujingling/netty,jdivy/netty,bryce-anderson/netty,afredlyj/learn-netty,liuciuse/netty,olupotd/netty,golovnin/netty,carlbai/netty,joansmith/netty,windie/netty,olupotd/netty,yonglehou/netty-1,zxhfirefox/netty,fantayeneh/netty,Apache9/netty,wuyinxian124/netty,netty/netty,unei66/netty,lightsocks/netty,zhoffice/netty,silvaran/netty,lukehutch/netty,yipen9/netty,sja/netty,yawkat/netty,zxhfirefox/netty,cnoldtree/netty,eincs/netty,carlbai/netty,skyao/netty,nkhuyu/netty,lightsocks/netty,Squarespace/netty,niuxinghua/netty,JungMinu/netty,mikkokar/netty,jchambers/netty,sammychen105/netty,danny200309/netty,caoyanwei/netty,jchambers/netty,caoyanwei/netty,ninja-/netty,mikkokar/netty,djchen/netty,Kalvar/netty,lznhust/netty,carlbai/netty,shelsonjava/netty,huanyi0723/netty,wuxiaowei907/netty,chinayin/netty,andsel/netty,Alwayswithme/netty,jroper/netty,yipen9/netty,blucas/netty,kjniemi/netty,chrisprobst/netty,fenik17/netty,chanakaudaya/netty,maliqq/netty,mubarak/netty,zer0se7en/netty,castomer/netty,sameira/netty,maliqq/netty,carlbai/netty,lugt/netty,bigheary/netty,WangJunTYTL/netty,artgon/netty,mikkokar/netty,kyle-liu/netty4study,chinayin/netty,liyang1025/netty,balaprasanna/netty,windie/netty,nkhuyu/netty,huuthang1993/netty,xiongzheng/netty,afds/netty,fengshao0907/netty,Alwayswithme/netty,kvr000/netty,MediumOne/netty,eonezhang/netty,ajaysarda/netty,afds/netty,nkhuyu/netty,mubarak/netty,orika/netty,hepin1989/netty,xiexingguang/netty,zzcclp/netty,shenguoquan/netty,andsel/netty,liyang1025/netty,balaprasanna/netty,danny200309/netty,cnoldtree/netty,ninja-/netty,yonglehou/netty-1,chanakaudaya/netty,rovarga/netty,shism/netty,chrisprobst/netty,ioanbsu/netty,danbev/netty,moyiguket/netty,unei66/netty,jdivy/netty,NiteshKant/netty,normanmaurer/netty,Scottmitch/netty,LuminateWireless/netty,louiscryan/netty,bryce-anderson/netty,Alwayswithme/netty,junjiemars/netty,AnselQiao/netty,moyiguket/netty,alkemist/netty,hgl888/netty,ejona86/netty,f7753/netty,carl-mastrangelo/netty,eonezhang/netty,skyao/netty,SinaTadayon/netty,fengjiachun/netty,afredlyj/learn-netty,netty/netty,sameira/netty,skyao/netty,gigold/netty,xingguang2013/netty,mx657649013/netty,satishsaley/netty,youprofit/netty,fengjiachun/netty,nadeeshaan/netty,jchambers/netty,junjiemars/netty,maliqq/netty,tbrooks8/netty,unei66/netty,zhujingling/netty,sja/netty,artgon/netty,AchinthaReemal/netty,CodingFabian/netty,huanyi0723/netty,silvaran/netty,Kalvar/netty,ajaysarda/netty,lightsocks/netty,fantayeneh/netty,liuciuse/netty,lugt/netty,AchinthaReemal/netty,tbrooks8/netty,huanyi0723/netty,jongyeol/netty,wangyikai/netty,lukehutch/netty,shelsonjava/netty,AnselQiao/netty,hyangtack/netty,windie/netty,slandelle/netty,nkhuyu/netty,serioussam/netty,wuxiaowei907/netty,qingsong-xu/netty,hgl888/netty,afds/netty,hyangtack/netty,artgon/netty,Spikhalskiy/netty,nadeeshaan/netty,ngocdaothanh/netty,woshilaiceshide/netty,fenik17/netty,pengzj/netty,chrisprobst/netty,timboudreau/netty,zhoffice/netty,liyang1025/netty,junjiemars/netty,joansmith/netty,xiexingguang/netty,luyiisme/netty,s-gheldd/netty,youprofit/netty,luyiisme/netty,ejona86/netty,x1957/netty,Alwayswithme/netty,DavidAlphaFox/netty,mosoft521/netty,smayoorans/netty,BrunoColin/netty,kjniemi/netty,Squarespace/netty,louxiu/netty,phlizik/netty,Kingson4Wu/netty,yrcourage/netty,jdivy/netty,Kingson4Wu/netty,MediumOne/netty,artgon/netty,wuyinxian124/netty,pengzj/netty,liyang1025/netty,menacher/netty,moyiguket/netty,bob329/netty,phlizik/netty,AchinthaReemal/netty,johnou/netty,mway08/netty,jovezhougang/netty,louxiu/netty,lznhust/netty,buchgr/netty,Scottmitch/netty,zhujingling/netty,smayoorans/netty,s-gheldd/netty,f7753/netty,SinaTadayon/netty,orika/netty,purplefox/netty-4.0.2.8-hacked,nayato/netty,duqiao/netty,normanmaurer/netty,lukw00/netty,tempbottle/netty,golovnin/netty,duqiao/netty,xingguang2013/netty,mcanthony/netty,mway08/netty,jovezhougang/netty,bigheary/netty,yrcourage/netty,fengjiachun/netty,lukw00/netty,daschl/netty,IBYoung/netty,Techcable/netty,alkemist/netty,qingsong-xu/netty,mx657649013/netty,nadeeshaan/netty,johnou/netty,Mounika-Chirukuri/netty,huuthang1993/netty,ioanbsu/netty,imangry/netty-zh,silvaran/netty,balaprasanna/netty,ajaysarda/netty,mubarak/netty,fengshao0907/netty,IBYoung/netty,daschl/netty,gigold/netty,artgon/netty,blademainer/netty,normanmaurer/netty,x1957/netty,chinayin/netty,exinguu/netty,NiteshKant/netty,AchinthaReemal/netty,mosoft521/netty,duqiao/netty,mcobrien/netty,silvaran/netty,mubarak/netty,slandelle/netty,idelpivnitskiy/netty,Apache9/netty,windie/netty,danny200309/netty,phlizik/netty,hgl888/netty,danny200309/netty,ioanbsu/netty,sverkera/netty,imangry/netty-zh,AnselQiao/netty,WangJunTYTL/netty,alkemist/netty,Kingson4Wu/netty,kvr000/netty,louiscryan/netty,zzcclp/netty,clebertsuconic/netty,jchambers/netty,ejona86/netty,Alwayswithme/netty,Kingson4Wu/netty,LuminateWireless/netty,liuciuse/netty,lukehutch/netty,andsel/netty,serioussam/netty,tempbottle/netty,idelpivnitskiy/netty,IBYoung/netty,shuangqiuan/netty,lukehutch/netty,Spikhalskiy/netty,fengjiachun/netty,yrcourage/netty,ijuma/netty,shism/netty,sunbeansoft/netty,sameira/netty,johnou/netty,mikkokar/netty,fantayeneh/netty,zer0se7en/netty,doom369/netty,Kalvar/netty,zhoffice/netty,lukw00/netty,jovezhougang/netty,fenik17/netty,sverkera/netty,firebase/netty,louxiu/netty,xingguang2013/netty,doom369/netty,moyiguket/netty,f7753/netty,KatsuraKKKK/netty,alkemist/netty,afds/netty,sameira/netty,gerdriesselmann/netty,gerdriesselmann/netty,gigold/netty,golovnin/netty,WangJunTYTL/netty,x1957/netty,altihou/netty,junjiemars/netty,satishsaley/netty,SinaTadayon/netty,brennangaunce/netty,shism/netty,kiril-me/netty,ngocdaothanh/netty,wangyikai/netty,xiongzheng/netty,olupotd/netty,orika/netty,zzcclp/netty,yawkat/netty,serioussam/netty,zhujingling/netty,tempbottle/netty,blademainer/netty,fengshao0907/netty,shelsonjava/netty,kiril-me/netty,clebertsuconic/netty,Mounika-Chirukuri/netty,tbrooks8/netty,zhoffice/netty,Kalvar/netty,andsel/netty,kjniemi/netty,nat2013/netty,xiexingguang/netty,mosoft521/netty,timboudreau/netty,JungMinu/netty,DavidAlphaFox/netty,shenguoquan/netty,balaprasanna/netty,wuxiaowei907/netty,timboudreau/netty,hyangtack/netty,Scottmitch/netty,satishsaley/netty,tempbottle/netty,mcanthony/netty,mway08/netty,zxhfirefox/netty,kiril-me/netty,shuangqiuan/netty,satishsaley/netty,seetharamireddy540/netty,altihou/netty,x1957/netty,purplefox/netty-4.0.2.8-hacked,Spikhalskiy/netty,huanyi0723/netty,ifesdjeen/netty,qingsong-xu/netty,danbev/netty,caoyanwei/netty,mosoft521/netty,nat2013/netty,cnoldtree/netty,louiscryan/netty,gigold/netty,kjniemi/netty,develar/netty,purplefox/netty-4.0.2.8-hacked,clebertsuconic/netty,ioanbsu/netty,ajaysarda/netty,louxiu/netty,shuangqiuan/netty,seetharamireddy540/netty,smayoorans/netty,serioussam/netty,hepin1989/netty,danbev/netty,junjiemars/netty,ioanbsu/netty,drowning/netty,ichaki5748/netty,chinayin/netty,mway08/netty,exinguu/netty,lukw00/netty,buchgr/netty,danbev/netty,caoyanwei/netty,NiteshKant/netty,blucas/netty,MediumOne/netty,smayoorans/netty,mubarak/netty,nayato/netty,doom369/netty,nmittler/netty,bryce-anderson/netty,BrunoColin/netty,eincs/netty,sammychen105/netty,brennangaunce/netty,youprofit/netty,jdivy/netty,drowning/netty,carl-mastrangelo/netty,chrisprobst/netty,ijuma/netty,hepin1989/netty,louiscryan/netty,ichaki5748/netty,DolphinZhao/netty,kiril-me/netty,silvaran/netty,Kalvar/netty,shism/netty,fengjiachun/netty,NiteshKant/netty,jongyeol/netty,joansmith/netty,sunbeansoft/netty,Kingson4Wu/netty,altihou/netty,blucas/netty,huuthang1993/netty,s-gheldd/netty,normanmaurer/netty,chrisprobst/netty,louxiu/netty,huuthang1993/netty,jongyeol/netty,xiexingguang/netty,kyle-liu/netty4study,andsel/netty,Apache9/netty,djchen/netty,yrcourage/netty,yawkat/netty,jongyeol/netty,SinaTadayon/netty,altihou/netty,fenik17/netty,sverkera/netty,duqiao/netty,slandelle/netty,mikkokar/netty,KatsuraKKKK/netty,mcanthony/netty,zer0se7en/netty,mcobrien/netty,yrcourage/netty,castomer/netty,tbrooks8/netty,zer0se7en/netty,ichaki5748/netty,gerdriesselmann/netty,huanyi0723/netty,jovezhougang/netty,moyiguket/netty,purplefox/netty-4.0.2.8-hacked,liyang1025/netty,ijuma/netty,ninja-/netty,sameira/netty,djchen/netty,joansmith/netty,johnou/netty,yonglehou/netty-1,s-gheldd/netty,hgl888/netty,liuciuse/netty,fantayeneh/netty,bigheary/netty,serioussam/netty,IBYoung/netty,gigold/netty,caoyanwei/netty,dongjiaqiang/netty,ejona86/netty,Apache9/netty,lukw00/netty,mcanthony/netty,shenguoquan/netty,chinayin/netty,ijuma/netty,fantayeneh/netty,hgl888/netty,gerdriesselmann/netty,CodingFabian/netty,pengzj/netty,mx657649013/netty,hepin1989/netty,windie/netty,tbrooks8/netty,develar/netty,lugt/netty,mx657649013/netty,CodingFabian/netty,nadeeshaan/netty,hyangtack/netty,AchinthaReemal/netty,firebase/netty,DolphinZhao/netty,bigheary/netty,wuxiaowei907/netty,s-gheldd/netty,woshilaiceshide/netty,altihou/netty,xiexingguang/netty,lznhust/netty,shenguoquan/netty,eincs/netty,bob329/netty,KatsuraKKKK/netty,niuxinghua/netty,ngocdaothanh/netty,xiongzheng/netty,Scottmitch/netty,blademainer/netty,wangyikai/netty,carl-mastrangelo/netty,duqiao/netty,shism/netty,nayato/netty,unei66/netty,codevelop/netty,Spikhalskiy/netty,zzcclp/netty,bob329/netty,bob329/netty,jchambers/netty,brennangaunce/netty,skyao/netty,MediumOne/netty,wuxiaowei907/netty,nkhuyu/netty,DavidAlphaFox/netty,sammychen105/netty,Techcable/netty,luyiisme/netty,qingsong-xu/netty,sunbeansoft/netty,olupotd/netty,ninja-/netty,pengzj/netty,Techcable/netty,exinguu/netty,nayato/netty,codevelop/netty,codevelop/netty,ichaki5748/netty,jenskordowski/netty,tempbottle/netty,xingguang2013/netty,nmittler/netty,nat2013/netty,AnselQiao/netty,joansmith/netty,DolphinZhao/netty,x1957/netty,woshilaiceshide/netty,ngocdaothanh/netty,ninja-/netty,bryce-anderson/netty,WangJunTYTL/netty,afredlyj/learn-netty,alkemist/netty,mcobrien/netty,netty/netty,shelsonjava/netty,imangry/netty-zh,clebertsuconic/netty,kiril-me/netty,wangyikai/netty,bigheary/netty,buchgr/netty,lugt/netty,AnselQiao/netty,ajaysarda/netty,Squarespace/netty,zhoffice/netty,eonezhang/netty,idelpivnitskiy/netty,imangry/netty-zh,rovarga/netty,danbev/netty,jenskordowski/netty,brennangaunce/netty,Mounika-Chirukuri/netty,nadeeshaan/netty,jenskordowski/netty,dongjiaqiang/netty,doom369/netty,ichaki5748/netty,idelpivnitskiy/netty,castomer/netty,olupotd/netty,chanakaudaya/netty,carl-mastrangelo/netty,imangry/netty-zh,normanmaurer/netty,jdivy/netty,BrunoColin/netty,clebertsuconic/netty,Mounika-Chirukuri/netty,zxhfirefox/netty,BrunoColin/netty,sja/netty,smayoorans/netty,jovezhougang/netty,eonezhang/netty,exinguu/netty,dongjiaqiang/netty,Squarespace/netty,lugt/netty,daschl/netty,balaprasanna/netty,sverkera/netty,danny200309/netty,netty/netty,timboudreau/netty,slandelle/netty,nayato/netty,Spikhalskiy/netty,blucas/netty,eincs/netty,kvr000/netty,drowning/netty,castomer/netty,Scottmitch/netty,dongjiaqiang/netty,rovarga/netty,KatsuraKKKK/netty,drowning/netty,lznhust/netty,seetharamireddy540/netty,louiscryan/netty,sja/netty,KatsuraKKKK/netty,huuthang1993/netty,IBYoung/netty,seetharamireddy540/netty,Techcable/netty,SinaTadayon/netty,sverkera/netty,buchgr/netty,xingguang2013/netty,kjniemi/netty,zhujingling/netty,yonglehou/netty-1,doom369/netty,golovnin/netty,wuyinxian124/netty,cnoldtree/netty,firebase/netty,yipen9/netty,DolphinZhao/netty,shenguoquan/netty,CodingFabian/netty,rovarga/netty,blademainer/netty,niuxinghua/netty,mway08/netty,WangJunTYTL/netty,youprofit/netty,CodingFabian/netty,yawkat/netty,timboudreau/netty,mosoft521/netty,netty/netty,LuminateWireless/netty,johnou/netty,f7753/netty,qingsong-xu/netty,zer0se7en/netty,castomer/netty,jongyeol/netty,satishsaley/netty,kvr000/netty,youprofit/netty,lightsocks/netty,sja/netty,djchen/netty,niuxinghua/netty,ijuma/netty,DavidAlphaFox/netty,Techcable/netty,menacher/netty,orika/netty,zzcclp/netty,brennangaunce/netty,bob329/netty,eincs/netty,chanakaudaya/netty,JungMinu/netty,cnoldtree/netty,ejona86/netty,NiteshKant/netty,mcobrien/netty,phlizik/netty,afds/netty,luyiisme/netty,zxhfirefox/netty,wuyinxian124/netty,ngocdaothanh/netty,carlbai/netty,maliqq/netty,JungMinu/netty,ifesdjeen/netty,yipen9/netty,chanakaudaya/netty,shuangqiuan/netty,lznhust/netty,Squarespace/netty,LuminateWireless/netty,eonezhang/netty,sunbeansoft/netty,bryce-anderson/netty,MediumOne/netty,xiongzheng/netty,mx657649013/netty,yonglehou/netty-1,mcanthony/netty,shuangqiuan/netty,orika/netty,lightsocks/netty,nmittler/netty,lukehutch/netty,yawkat/netty,niuxinghua/netty,woshilaiceshide/netty,sunbeansoft/netty,dongjiaqiang/netty,shelsonjava/netty,kvr000/netty,codevelop/netty,woshilaiceshide/netty,firebase/netty
|
/*
* Copyright 2011 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.http;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import io.netty.buffer.ChannelBuffer;
import io.netty.buffer.ChannelBuffers;
import org.jboss.netty.handler.codec.http2.HttpPostBodyUtil.SeekAheadNoBackArray;
import org.jboss.netty.handler.codec.http2.HttpPostBodyUtil.SeekAheadOptimize;
import io.netty.handler.codec.http.HttpPostBodyUtil.TransferEncodingMechanism;
/**
* This decoder will decode Body and can handle POST BODY.
*/
public class HttpPostRequestDecoder {
/**
* Factory used to create InterfaceHttpData
*/
private final HttpDataFactory factory;
/**
* Request to decode
*/
private final HttpRequest request;
/**
* Default charset to use
*/
private final Charset charset;
/**
* Does request have a body to decode
*/
private boolean bodyToDecode;
/**
* Does the last chunk already received
*/
private boolean isLastChunk;
/**
* HttpDatas from Body
*/
private final List<InterfaceHttpData> bodyListHttpData = new ArrayList<InterfaceHttpData>();
/**
* HttpDatas as Map from Body
*/
private final Map<String, List<InterfaceHttpData>> bodyMapHttpData = new TreeMap<String, List<InterfaceHttpData>>(
CaseIgnoringComparator.INSTANCE);
/**
* The current channelBuffer
*/
private ChannelBuffer undecodedChunk;
/**
* Does this request is a Multipart request
*/
private boolean isMultipart;
/**
* Body HttpDatas current position
*/
private int bodyListHttpDataRank;
/**
* If multipart, this is the boundary for the flobal multipart
*/
private String multipartDataBoundary;
/**
* If multipart, there could be internal multiparts (mixed) to the global multipart.
* Only one level is allowed.
*/
private String multipartMixedBoundary;
/**
* Current status
*/
private MultiPartStatus currentStatus = MultiPartStatus.NOTSTARTED;
/**
* Used in Multipart
*/
private Map<String, Attribute> currentFieldAttributes;
/**
* The current FileUpload that is currently in decode process
*/
private FileUpload currentFileUpload;
/**
* The current Attribute that is currently in decode process
*/
private Attribute currentAttribute;
/**
*
* @param request the request to decode
* @throws NullPointerException for request
* @throws IncompatibleDataDecoderException if the request has no body to decode
* @throws ErrorDataDecoderException if the default charset was wrong when decoding or other errors
*/
public HttpPostRequestDecoder(HttpRequest request)
throws ErrorDataDecoderException, IncompatibleDataDecoderException {
this(new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE),
request, HttpCodecUtil.DEFAULT_CHARSET);
}
/**
*
* @param factory the factory used to create InterfaceHttpData
* @param request the request to decode
* @throws NullPointerException for request or factory
* @throws IncompatibleDataDecoderException if the request has no body to decode
* @throws ErrorDataDecoderException if the default charset was wrong when decoding or other errors
*/
public HttpPostRequestDecoder(HttpDataFactory factory, HttpRequest request)
throws ErrorDataDecoderException, IncompatibleDataDecoderException {
this(factory, request, HttpCodecUtil.DEFAULT_CHARSET);
}
/**
*
* @param factory the factory used to create InterfaceHttpData
* @param request the request to decode
* @param charset the charset to use as default
* @throws NullPointerException for request or charset or factory
* @throws IncompatibleDataDecoderException if the request has no body to decode
* @throws ErrorDataDecoderException if the default charset was wrong when decoding or other errors
*/
public HttpPostRequestDecoder(HttpDataFactory factory, HttpRequest request,
Charset charset) throws ErrorDataDecoderException,
IncompatibleDataDecoderException {
if (factory == null) {
throw new NullPointerException("factory");
}
if (request == null) {
throw new NullPointerException("request");
}
if (charset == null) {
throw new NullPointerException("charset");
}
this.request = request;
HttpMethod method = request.getMethod();
if (method.equals(HttpMethod.POST) || method.equals(HttpMethod.PUT) || method.equals(HttpMethod.PATCH)) {
bodyToDecode = true;
}
this.charset = charset;
this.factory = factory;
// Fill default values
if (this.request.containsHeader(HttpHeaders.Names.CONTENT_TYPE)) {
checkMultipart(this.request.getHeader(HttpHeaders.Names.CONTENT_TYPE));
} else {
isMultipart = false;
}
if (!bodyToDecode) {
throw new IncompatibleDataDecoderException("No Body to decode");
}
if (!this.request.isChunked()) {
undecodedChunk = this.request.getContent();
isLastChunk = true;
parseBody();
}
}
/**
* states follow
* NOTSTARTED PREAMBLE (
* (HEADERDELIMITER DISPOSITION (FIELD | FILEUPLOAD))*
* (HEADERDELIMITER DISPOSITION MIXEDPREAMBLE
* (MIXEDDELIMITER MIXEDDISPOSITION MIXEDFILEUPLOAD)+
* MIXEDCLOSEDELIMITER)*
* CLOSEDELIMITER)+ EPILOGUE
*
* First status is: NOSTARTED
Content-type: multipart/form-data, boundary=AaB03x => PREAMBLE in Header
--AaB03x => HEADERDELIMITER
content-disposition: form-data; name="field1" => DISPOSITION
Joe Blow => FIELD
--AaB03x => HEADERDELIMITER
content-disposition: form-data; name="pics" => DISPOSITION
Content-type: multipart/mixed, boundary=BbC04y
--BbC04y => MIXEDDELIMITER
Content-disposition: attachment; filename="file1.txt" => MIXEDDISPOSITION
Content-Type: text/plain
... contents of file1.txt ... => MIXEDFILEUPLOAD
--BbC04y => MIXEDDELIMITER
Content-disposition: file; filename="file2.gif" => MIXEDDISPOSITION
Content-type: image/gif
Content-Transfer-Encoding: binary
...contents of file2.gif... => MIXEDFILEUPLOAD
--BbC04y-- => MIXEDCLOSEDELIMITER
--AaB03x-- => CLOSEDELIMITER
Once CLOSEDELIMITER is found, last status is EPILOGUE
*/
private enum MultiPartStatus {
NOTSTARTED,
PREAMBLE,
HEADERDELIMITER,
DISPOSITION,
FIELD,
FILEUPLOAD,
MIXEDPREAMBLE,
MIXEDDELIMITER,
MIXEDDISPOSITION,
MIXEDFILEUPLOAD,
MIXEDCLOSEDELIMITER,
CLOSEDELIMITER,
PREEPILOGUE,
EPILOGUE
}
/**
* Check from the request ContentType if this request is a Multipart request.
* @param contentType
* @throws ErrorDataDecoderException
*/
private void checkMultipart(String contentType)
throws ErrorDataDecoderException {
// Check if Post using "multipart/form-data; boundary=--89421926422648"
String[] headerContentType = splitHeaderContentType(contentType);
if (headerContentType[0].toLowerCase().startsWith(
HttpHeaders.Values.MULTIPART_FORM_DATA) &&
headerContentType[1].toLowerCase().startsWith(
HttpHeaders.Values.BOUNDARY)) {
String[] boundary = headerContentType[1].split("=");
if (boundary.length != 2) {
throw new ErrorDataDecoderException("Needs a boundary value");
}
multipartDataBoundary = "--" + boundary[1];
isMultipart = true;
currentStatus = MultiPartStatus.HEADERDELIMITER;
} else {
isMultipart = false;
}
}
/**
* True if this request is a Multipart request
* @return True if this request is a Multipart request
*/
public boolean isMultipart() {
return isMultipart;
}
/**
* This method returns a List of all HttpDatas from body.<br>
*
* If chunked, all chunks must have been offered using offer() method.
* If not, NotEnoughDataDecoderException will be raised.
*
* @return the list of HttpDatas from Body part for POST method
* @throws NotEnoughDataDecoderException Need more chunks
*/
public List<InterfaceHttpData> getBodyHttpDatas()
throws NotEnoughDataDecoderException {
if (!isLastChunk) {
throw new NotEnoughDataDecoderException();
}
return bodyListHttpData;
}
/**
* This method returns a List of all HttpDatas with the given name from body.<br>
*
* If chunked, all chunks must have been offered using offer() method.
* If not, NotEnoughDataDecoderException will be raised.
* @param name
* @return All Body HttpDatas with the given name (ignore case)
* @throws NotEnoughDataDecoderException need more chunks
*/
public List<InterfaceHttpData> getBodyHttpDatas(String name)
throws NotEnoughDataDecoderException {
if (!isLastChunk) {
throw new NotEnoughDataDecoderException();
}
return bodyMapHttpData.get(name);
}
/**
* This method returns the first InterfaceHttpData with the given name from body.<br>
*
* If chunked, all chunks must have been offered using offer() method.
* If not, NotEnoughDataDecoderException will be raised.
*
* @param name
* @return The first Body InterfaceHttpData with the given name (ignore case)
* @throws NotEnoughDataDecoderException need more chunks
*/
public InterfaceHttpData getBodyHttpData(String name)
throws NotEnoughDataDecoderException {
if (!isLastChunk) {
throw new NotEnoughDataDecoderException();
}
List<InterfaceHttpData> list = bodyMapHttpData.get(name);
if (list != null) {
return list.get(0);
}
return null;
}
/**
* Initialized the internals from a new chunk
* @param chunk the new received chunk
* @throws ErrorDataDecoderException if there is a problem with the charset decoding or
* other errors
*/
public void offer(HttpChunk chunk) throws ErrorDataDecoderException {
ChannelBuffer chunked = chunk.getContent();
if (undecodedChunk == null) {
undecodedChunk = chunked;
} else {
//undecodedChunk = ChannelBuffers.wrappedBuffer(undecodedChunk, chunk.getContent());
// less memory usage
undecodedChunk = ChannelBuffers.wrappedBuffer(
undecodedChunk, chunked);
}
if (chunk.isLast()) {
isLastChunk = true;
}
parseBody();
}
/**
* True if at current status, there is an available decoded InterfaceHttpData from the Body.
*
* This method works for chunked and not chunked request.
*
* @return True if at current status, there is a decoded InterfaceHttpData
* @throws EndOfDataDecoderException No more data will be available
*/
public boolean hasNext() throws EndOfDataDecoderException {
if (currentStatus == MultiPartStatus.EPILOGUE) {
// OK except if end of list
if (bodyListHttpDataRank >= bodyListHttpData.size()) {
throw new EndOfDataDecoderException();
}
}
return bodyListHttpData.size() > 0 &&
bodyListHttpDataRank < bodyListHttpData.size();
}
/**
* Returns the next available InterfaceHttpData or null if, at the time it is called, there is no more
* available InterfaceHttpData. A subsequent call to offer(httpChunk) could enable more data.
*
* @return the next available InterfaceHttpData or null if none
* @throws EndOfDataDecoderException No more data will be available
*/
public InterfaceHttpData next() throws EndOfDataDecoderException {
if (hasNext()) {
return bodyListHttpData.get(bodyListHttpDataRank++);
}
return null;
}
/**
* This method will parse as much as possible data and fill the list and map
* @throws ErrorDataDecoderException if there is a problem with the charset decoding or
* other errors
*/
private void parseBody() throws ErrorDataDecoderException {
if (currentStatus == MultiPartStatus.PREEPILOGUE ||
currentStatus == MultiPartStatus.EPILOGUE) {
if (isLastChunk) {
currentStatus = MultiPartStatus.EPILOGUE;
}
return;
}
if (isMultipart) {
parseBodyMultipart();
} else {
parseBodyAttributes();
}
}
/**
* Utility function to add a new decoded data
* @param data
*/
private void addHttpData(InterfaceHttpData data) {
if (data == null) {
return;
}
List<InterfaceHttpData> datas = bodyMapHttpData.get(data.getName());
if (datas == null) {
datas = new ArrayList<InterfaceHttpData>(1);
bodyMapHttpData.put(data.getName(), datas);
}
datas.add(data);
bodyListHttpData.add(data);
}
/**
* This method fill the map and list with as much Attribute as possible from Body in
* not Multipart mode.
*
* @throws ErrorDataDecoderException if there is a problem with the charset decoding or
* other errors
*/
private void parseBodyAttributesStandard() throws ErrorDataDecoderException {
int firstpos = undecodedChunk.readerIndex();
int currentpos = firstpos;
int equalpos = firstpos;
int ampersandpos = firstpos;
if (currentStatus == MultiPartStatus.NOTSTARTED) {
currentStatus = MultiPartStatus.DISPOSITION;
}
boolean contRead = true;
try {
while (undecodedChunk.readable() && contRead) {
char read = (char) undecodedChunk.readUnsignedByte();
currentpos++;
switch (currentStatus) {
case DISPOSITION:// search '='
if (read == '=') {
currentStatus = MultiPartStatus.FIELD;
equalpos = currentpos - 1;
String key = decodeAttribute(
undecodedChunk.toString(firstpos, equalpos - firstpos, charset),
charset);
currentAttribute = factory.createAttribute(request, key);
firstpos = currentpos;
} else if (read == '&') { // special empty FIELD
currentStatus = MultiPartStatus.DISPOSITION;
ampersandpos = currentpos - 1;
String key = decodeAttribute(undecodedChunk.toString(firstpos, ampersandpos - firstpos, charset), charset);
currentAttribute = factory.createAttribute(request, key);
currentAttribute.setValue(""); // empty
addHttpData(currentAttribute);
currentAttribute = null;
firstpos = currentpos;
contRead = true;
}
break;
case FIELD:// search '&' or end of line
if (read == '&') {
currentStatus = MultiPartStatus.DISPOSITION;
ampersandpos = currentpos - 1;
setFinalBuffer(undecodedChunk.slice(firstpos, ampersandpos - firstpos));
firstpos = currentpos;
contRead = true;
} else if (read == HttpCodecUtil.CR) {
if (undecodedChunk.readable()) {
read = (char) undecodedChunk.readUnsignedByte();
currentpos++;
if (read == HttpCodecUtil.LF) {
currentStatus = MultiPartStatus.PREEPILOGUE;
ampersandpos = currentpos - 2;
setFinalBuffer(
undecodedChunk.slice(firstpos, ampersandpos - firstpos));
firstpos = currentpos;
contRead = false;
} else {
// Error
contRead = false;
throw new ErrorDataDecoderException("Bad end of line");
}
} else {
currentpos--;
}
} else if (read == HttpCodecUtil.LF) {
currentStatus = MultiPartStatus.PREEPILOGUE;
ampersandpos = currentpos - 1;
setFinalBuffer(
undecodedChunk.slice(firstpos, ampersandpos - firstpos));
firstpos = currentpos;
contRead = false;
}
break;
default:
// just stop
contRead = false;
}
}
if (isLastChunk && currentAttribute != null) {
// special case
ampersandpos = currentpos;
if (ampersandpos > firstpos) {
setFinalBuffer(
undecodedChunk.slice(firstpos, ampersandpos - firstpos));
} else if (! currentAttribute.isCompleted()) {
setFinalBuffer(ChannelBuffers.EMPTY_BUFFER);
}
firstpos = currentpos;
currentStatus = MultiPartStatus.EPILOGUE;
return;
}
if (contRead && currentAttribute != null) {
// reset index except if to continue in case of FIELD status
if (currentStatus == MultiPartStatus.FIELD) {
currentAttribute.addContent(
undecodedChunk.slice(firstpos, currentpos - firstpos),
false);
firstpos = currentpos;
}
undecodedChunk.readerIndex(firstpos);
} else {
// end of line so keep index
}
} catch (ErrorDataDecoderException e) {
// error while decoding
undecodedChunk.readerIndex(firstpos);
throw e;
} catch (IOException e) {
// error while decoding
undecodedChunk.readerIndex(firstpos);
throw new ErrorDataDecoderException(e);
}
}
/**
* This method fill the map and list with as much Attribute as possible from Body in
* not Multipart mode.
*
* @throws ErrorDataDecoderException if there is a problem with the charset decoding or
* other errors
*/
private void parseBodyAttributes() throws ErrorDataDecoderException {
SeekAheadOptimize sao = null;
try {
sao = new SeekAheadOptimize(undecodedChunk);
} catch (SeekAheadNoBackArray e1) {
parseBodyAttributesStandard();
return;
}
int firstpos = undecodedChunk.readerIndex();
int currentpos = firstpos;
int equalpos = firstpos;
int ampersandpos = firstpos;
if (currentStatus == MultiPartStatus.NOTSTARTED) {
currentStatus = MultiPartStatus.DISPOSITION;
}
boolean contRead = true;
try {
loop:
while (sao.pos < sao.limit) {
char read = (char) (sao.bytes[sao.pos ++] & 0xFF);
currentpos ++;
switch (currentStatus) {
case DISPOSITION:// search '='
if (read == '=') {
currentStatus = MultiPartStatus.FIELD;
equalpos = currentpos - 1;
String key = decodeAttribute(
undecodedChunk.toString(firstpos, equalpos - firstpos, charset),
charset);
currentAttribute = factory.createAttribute(request, key);
firstpos = currentpos;
} else if (read == '&') { // special empty FIELD
currentStatus = MultiPartStatus.DISPOSITION;
ampersandpos = currentpos - 1;
String key = decodeAttribute(undecodedChunk.toString(firstpos, ampersandpos - firstpos, charset), charset);
currentAttribute = factory.createAttribute(request, key);
currentAttribute.setValue(""); // empty
addHttpData(currentAttribute);
currentAttribute = null;
firstpos = currentpos;
contRead = true;
}
break;
case FIELD:// search '&' or end of line
if (read == '&') {
currentStatus = MultiPartStatus.DISPOSITION;
ampersandpos = currentpos - 1;
setFinalBuffer(undecodedChunk.slice(firstpos, ampersandpos - firstpos));
firstpos = currentpos;
contRead = true;
} else if (read == HttpCodecUtil.CR) {
if (sao.pos < sao.limit) {
read = (char) (sao.bytes[sao.pos ++] & 0xFF);
currentpos++;
if (read == HttpCodecUtil.LF) {
currentStatus = MultiPartStatus.PREEPILOGUE;
ampersandpos = currentpos - 2;
sao.setReadPosition(0);
setFinalBuffer(
undecodedChunk.slice(firstpos, ampersandpos - firstpos));
firstpos = currentpos;
contRead = false;
break loop;
} else {
// Error
sao.setReadPosition(0);
contRead = false;
throw new ErrorDataDecoderException("Bad end of line");
}
} else {
if (sao.limit > 0) {
currentpos --;
}
}
} else if (read == HttpCodecUtil.LF) {
currentStatus = MultiPartStatus.PREEPILOGUE;
ampersandpos = currentpos - 1;
sao.setReadPosition(0);
setFinalBuffer(
undecodedChunk.slice(firstpos, ampersandpos - firstpos));
firstpos = currentpos;
contRead = false;
break loop;
}
break;
default:
// just stop
sao.setReadPosition(0);
contRead = false;
break loop;
}
}
if (isLastChunk && currentAttribute != null) {
// special case
ampersandpos = currentpos;
if (ampersandpos > firstpos) {
setFinalBuffer(
undecodedChunk.slice(firstpos, ampersandpos - firstpos));
} else if (! currentAttribute.isCompleted()) {
setFinalBuffer(ChannelBuffers.EMPTY_BUFFER);
}
firstpos = currentpos;
currentStatus = MultiPartStatus.EPILOGUE;
return;
}
if (contRead && currentAttribute != null) {
// reset index except if to continue in case of FIELD status
if (currentStatus == MultiPartStatus.FIELD) {
currentAttribute.addContent(
undecodedChunk.slice(firstpos, currentpos - firstpos),
false);
firstpos = currentpos;
}
undecodedChunk.readerIndex(firstpos);
} else {
// end of line so keep index
}
} catch (ErrorDataDecoderException e) {
// error while decoding
undecodedChunk.readerIndex(firstpos);
throw e;
} catch (IOException e) {
// error while decoding
undecodedChunk.readerIndex(firstpos);
throw new ErrorDataDecoderException(e);
}
}
private void setFinalBuffer(ChannelBuffer buffer) throws ErrorDataDecoderException, IOException {
currentAttribute.addContent(buffer, true);
String value = decodeAttribute(
currentAttribute.getChannelBuffer().toString(charset),
charset);
currentAttribute.setValue(value);
addHttpData(currentAttribute);
currentAttribute = null;
}
/**
* Decode component
* @param s
* @param charset
* @return the decoded component
* @throws ErrorDataDecoderException
*/
private static String decodeAttribute(String s, Charset charset)
throws ErrorDataDecoderException {
if (s == null) {
return "";
}
try {
return URLDecoder.decode(s, charset.name());
} catch (UnsupportedEncodingException e) {
throw new ErrorDataDecoderException(charset.toString(), e);
}
}
/**
* Parse the Body for multipart
*
* @throws ErrorDataDecoderException if there is a problem with the charset decoding or other errors
*/
private void parseBodyMultipart() throws ErrorDataDecoderException {
if (undecodedChunk == null || undecodedChunk.readableBytes() == 0) {
// nothing to decode
return;
}
InterfaceHttpData data = decodeMultipart(currentStatus);
while (data != null) {
addHttpData(data);
if (currentStatus == MultiPartStatus.PREEPILOGUE ||
currentStatus == MultiPartStatus.EPILOGUE) {
break;
}
data = decodeMultipart(currentStatus);
}
}
/**
* Decode a multipart request by pieces<br>
* <br>
* NOTSTARTED PREAMBLE (<br>
* (HEADERDELIMITER DISPOSITION (FIELD | FILEUPLOAD))*<br>
* (HEADERDELIMITER DISPOSITION MIXEDPREAMBLE<br>
* (MIXEDDELIMITER MIXEDDISPOSITION MIXEDFILEUPLOAD)+<br>
* MIXEDCLOSEDELIMITER)*<br>
* CLOSEDELIMITER)+ EPILOGUE<br>
*
* Inspired from HttpMessageDecoder
*
* @param state
* @return the next decoded InterfaceHttpData or null if none until now.
* @throws ErrorDataDecoderException if an error occurs
*/
private InterfaceHttpData decodeMultipart(MultiPartStatus state)
throws ErrorDataDecoderException {
switch (state) {
case NOTSTARTED:
throw new ErrorDataDecoderException(
"Should not be called with the current status");
case PREAMBLE:
// Content-type: multipart/form-data, boundary=AaB03x
throw new ErrorDataDecoderException(
"Should not be called with the current status");
case HEADERDELIMITER: {
// --AaB03x or --AaB03x--
return findMultipartDelimiter(multipartDataBoundary,
MultiPartStatus.DISPOSITION, MultiPartStatus.PREEPILOGUE);
}
case DISPOSITION: {
// content-disposition: form-data; name="field1"
// content-disposition: form-data; name="pics"; filename="file1.txt"
// and other immediate values like
// Content-type: image/gif
// Content-Type: text/plain
// Content-Type: text/plain; charset=ISO-8859-1
// Content-Transfer-Encoding: binary
// The following line implies a change of mode (mixed mode)
// Content-type: multipart/mixed, boundary=BbC04y
return findMultipartDisposition();
}
case FIELD: {
// Now get value according to Content-Type and Charset
Charset localCharset = null;
Attribute charsetAttribute = currentFieldAttributes
.get(HttpHeaders.Values.CHARSET);
if (charsetAttribute != null) {
try {
localCharset = Charset.forName(charsetAttribute.getValue());
} catch (IOException e) {
throw new ErrorDataDecoderException(e);
}
}
Attribute nameAttribute = currentFieldAttributes
.get(HttpPostBodyUtil.NAME);
if (currentAttribute == null) {
try {
currentAttribute = factory.createAttribute(request, nameAttribute
.getValue());
} catch (NullPointerException e) {
throw new ErrorDataDecoderException(e);
} catch (IllegalArgumentException e) {
throw new ErrorDataDecoderException(e);
} catch (IOException e) {
throw new ErrorDataDecoderException(e);
}
if (localCharset != null) {
currentAttribute.setCharset(localCharset);
}
}
// load data
try {
loadFieldMultipart(multipartDataBoundary);
} catch (NotEnoughDataDecoderException e) {
return null;
}
Attribute finalAttribute = currentAttribute;
currentAttribute = null;
currentFieldAttributes = null;
// ready to load the next one
currentStatus = MultiPartStatus.HEADERDELIMITER;
return finalAttribute;
}
case FILEUPLOAD: {
// eventually restart from existing FileUpload
return getFileUpload(multipartDataBoundary);
}
case MIXEDDELIMITER: {
// --AaB03x or --AaB03x--
// Note that currentFieldAttributes exists
return findMultipartDelimiter(multipartMixedBoundary,
MultiPartStatus.MIXEDDISPOSITION,
MultiPartStatus.HEADERDELIMITER);
}
case MIXEDDISPOSITION: {
return findMultipartDisposition();
}
case MIXEDFILEUPLOAD: {
// eventually restart from existing FileUpload
return getFileUpload(multipartMixedBoundary);
}
case PREEPILOGUE:
return null;
case EPILOGUE:
return null;
default:
throw new ErrorDataDecoderException("Shouldn't reach here.");
}
}
/**
* Skip control Characters
*/
void skipControlCharacters() {
SeekAheadOptimize sao = null;
try {
sao = new SeekAheadOptimize(undecodedChunk);
} catch (SeekAheadNoBackArray e) {
skipControlCharactersStandard(undecodedChunk);
return;
}
while (sao.pos < sao.limit) {
char c = (char) sao.bytes[sao.pos ++];
if (!Character.isISOControl(c) && !Character.isWhitespace(c)) {
sao.setReadPosition(1);
return;
}
}
sao.setReadPosition(0);
}
static void skipControlCharactersStandard(ChannelBuffer buffer) {
for (;;) {
char c = (char) buffer.readUnsignedByte();
if (!Character.isISOControl(c) && !Character.isWhitespace(c)) {
buffer.readerIndex(buffer.readerIndex() - 1);
break;
}
}
}
/**
* Find the next Multipart Delimiter
* @param delimiter delimiter to find
* @param dispositionStatus the next status if the delimiter is a start
* @param closeDelimiterStatus the next status if the delimiter is a close delimiter
* @return the next InterfaceHttpData if any
* @throws ErrorDataDecoderException
*/
private InterfaceHttpData findMultipartDelimiter(String delimiter,
MultiPartStatus dispositionStatus,
MultiPartStatus closeDelimiterStatus)
throws ErrorDataDecoderException {
// --AaB03x or --AaB03x--
int readerIndex = undecodedChunk.readerIndex();
skipControlCharacters(undecodedChunk);
skipOneLine();
String newline;
try {
newline = readLine();
} catch (NotEnoughDataDecoderException e) {
undecodedChunk.readerIndex(readerIndex);
return null;
}
if (newline.equals(delimiter)) {
currentStatus = dispositionStatus;
return decodeMultipart(dispositionStatus);
} else if (newline.equals(delimiter + "--")) {
// CLOSEDELIMITER or MIXED CLOSEDELIMITER found
currentStatus = closeDelimiterStatus;
if (currentStatus == MultiPartStatus.HEADERDELIMITER) {
// MIXEDCLOSEDELIMITER
// end of the Mixed part
currentFieldAttributes = null;
return decodeMultipart(MultiPartStatus.HEADERDELIMITER);
}
return null;
}
undecodedChunk.readerIndex(readerIndex);
throw new ErrorDataDecoderException("No Multipart delimiter found");
}
/**
* Find the next Disposition
* @return the next InterfaceHttpData if any
* @throws ErrorDataDecoderException
*/
private InterfaceHttpData findMultipartDisposition()
throws ErrorDataDecoderException {
int readerIndex = undecodedChunk.readerIndex();
if (currentStatus == MultiPartStatus.DISPOSITION) {
currentFieldAttributes = new TreeMap<String, Attribute>(
CaseIgnoringComparator.INSTANCE);
}
// read many lines until empty line with newline found! Store all data
while (!skipOneLine()) {
skipControlCharacters(undecodedChunk);
String newline;
try {
newline = readLine();
} catch (NotEnoughDataDecoderException e) {
undecodedChunk.readerIndex(readerIndex);
return null;
}
String[] contents = splitMultipartHeader(newline);
if (contents[0].equalsIgnoreCase(HttpPostBodyUtil.CONTENT_DISPOSITION)) {
boolean checkSecondArg = false;
if (currentStatus == MultiPartStatus.DISPOSITION) {
checkSecondArg = contents[1]
.equalsIgnoreCase(HttpPostBodyUtil.FORM_DATA);
} else {
checkSecondArg = contents[1]
.equalsIgnoreCase(HttpPostBodyUtil.ATTACHMENT) ||
contents[1]
.equalsIgnoreCase(HttpPostBodyUtil.FILE);
}
if (checkSecondArg) {
// read next values and store them in the map as Attribute
for (int i = 2; i < contents.length; i ++) {
String[] values = contents[i].split("=");
Attribute attribute;
try {
attribute = factory.createAttribute(request, values[0].trim(),
decodeAttribute(cleanString(values[1]), charset));
} catch (NullPointerException e) {
throw new ErrorDataDecoderException(e);
} catch (IllegalArgumentException e) {
throw new ErrorDataDecoderException(e);
}
currentFieldAttributes.put(attribute.getName(),
attribute);
}
}
} else if (contents[0]
.equalsIgnoreCase(HttpHeaders.Names.CONTENT_TRANSFER_ENCODING)) {
Attribute attribute;
try {
attribute = factory.createAttribute(request,
HttpHeaders.Names.CONTENT_TRANSFER_ENCODING,
cleanString(contents[1]));
} catch (NullPointerException e) {
throw new ErrorDataDecoderException(e);
} catch (IllegalArgumentException e) {
throw new ErrorDataDecoderException(e);
}
currentFieldAttributes.put(
HttpHeaders.Names.CONTENT_TRANSFER_ENCODING, attribute);
} else if (contents[0]
.equalsIgnoreCase(HttpHeaders.Names.CONTENT_LENGTH)) {
Attribute attribute;
try {
attribute = factory.createAttribute(request,
HttpHeaders.Names.CONTENT_LENGTH,
cleanString(contents[1]));
} catch (NullPointerException e) {
throw new ErrorDataDecoderException(e);
} catch (IllegalArgumentException e) {
throw new ErrorDataDecoderException(e);
}
currentFieldAttributes.put(HttpHeaders.Names.CONTENT_LENGTH,
attribute);
} else if (contents[0].equalsIgnoreCase(HttpHeaders.Names.CONTENT_TYPE)) {
// Take care of possible "multipart/mixed"
if (contents[1].equalsIgnoreCase(HttpPostBodyUtil.MULTIPART_MIXED)) {
if (currentStatus == MultiPartStatus.DISPOSITION) {
String[] values = contents[2].split("=");
multipartMixedBoundary = "--" + values[1];
currentStatus = MultiPartStatus.MIXEDDELIMITER;
return decodeMultipart(MultiPartStatus.MIXEDDELIMITER);
} else {
throw new ErrorDataDecoderException(
"Mixed Multipart found in a previous Mixed Multipart");
}
} else {
for (int i = 1; i < contents.length; i ++) {
if (contents[i].toLowerCase().startsWith(
HttpHeaders.Values.CHARSET)) {
String[] values = contents[i].split("=");
Attribute attribute;
try {
attribute = factory.createAttribute(request,
HttpHeaders.Values.CHARSET,
cleanString(values[1]));
} catch (NullPointerException e) {
throw new ErrorDataDecoderException(e);
} catch (IllegalArgumentException e) {
throw new ErrorDataDecoderException(e);
}
currentFieldAttributes.put(HttpHeaders.Values.CHARSET,
attribute);
} else {
Attribute attribute;
try {
attribute = factory.createAttribute(request,
contents[0].trim(),
decodeAttribute(cleanString(contents[i]), charset));
} catch (NullPointerException e) {
throw new ErrorDataDecoderException(e);
} catch (IllegalArgumentException e) {
throw new ErrorDataDecoderException(e);
}
currentFieldAttributes.put(attribute.getName(),
attribute);
}
}
}
} else {
throw new ErrorDataDecoderException("Unknown Params: " +
newline);
}
}
// Is it a FileUpload
Attribute filenameAttribute = currentFieldAttributes
.get(HttpPostBodyUtil.FILENAME);
if (currentStatus == MultiPartStatus.DISPOSITION) {
if (filenameAttribute != null) {
// FileUpload
currentStatus = MultiPartStatus.FILEUPLOAD;
// do not change the buffer position
return decodeMultipart(MultiPartStatus.FILEUPLOAD);
} else {
// Field
currentStatus = MultiPartStatus.FIELD;
// do not change the buffer position
return decodeMultipart(MultiPartStatus.FIELD);
}
} else {
if (filenameAttribute != null) {
// FileUpload
currentStatus = MultiPartStatus.MIXEDFILEUPLOAD;
// do not change the buffer position
return decodeMultipart(MultiPartStatus.MIXEDFILEUPLOAD);
} else {
// Field is not supported in MIXED mode
throw new ErrorDataDecoderException("Filename not found");
}
}
}
/**
* Get the FileUpload (new one or current one)
* @param delimiter the delimiter to use
* @return the InterfaceHttpData if any
* @throws ErrorDataDecoderException
*/
private InterfaceHttpData getFileUpload(String delimiter)
throws ErrorDataDecoderException {
// eventually restart from existing FileUpload
// Now get value according to Content-Type and Charset
Attribute encoding = currentFieldAttributes
.get(HttpHeaders.Names.CONTENT_TRANSFER_ENCODING);
Charset localCharset = charset;
// Default
TransferEncodingMechanism mechanism = TransferEncodingMechanism.BIT7;
if (encoding != null) {
String code;
try {
code = encoding.getValue().toLowerCase();
} catch (IOException e) {
throw new ErrorDataDecoderException(e);
}
if (code.equals(HttpPostBodyUtil.TransferEncodingMechanism.BIT7.value)) {
localCharset = HttpPostBodyUtil.US_ASCII;
} else if (code.equals(HttpPostBodyUtil.TransferEncodingMechanism.BIT8.value)) {
localCharset = HttpPostBodyUtil.ISO_8859_1;
mechanism = TransferEncodingMechanism.BIT8;
} else if (code
.equals(HttpPostBodyUtil.TransferEncodingMechanism.BINARY.value)) {
// no real charset, so let the default
mechanism = TransferEncodingMechanism.BINARY;
} else {
throw new ErrorDataDecoderException(
"TransferEncoding Unknown: " + code);
}
}
Attribute charsetAttribute = currentFieldAttributes
.get(HttpHeaders.Values.CHARSET);
if (charsetAttribute != null) {
try {
localCharset = Charset.forName(charsetAttribute.getValue());
} catch (IOException e) {
throw new ErrorDataDecoderException(e);
}
}
if (currentFileUpload == null) {
Attribute filenameAttribute = currentFieldAttributes
.get(HttpPostBodyUtil.FILENAME);
Attribute nameAttribute = currentFieldAttributes
.get(HttpPostBodyUtil.NAME);
Attribute contentTypeAttribute = currentFieldAttributes
.get(HttpHeaders.Names.CONTENT_TYPE);
if (contentTypeAttribute == null) {
throw new ErrorDataDecoderException(
"Content-Type is absent but required");
}
Attribute lengthAttribute = currentFieldAttributes
.get(HttpHeaders.Names.CONTENT_LENGTH);
long size;
try {
size = lengthAttribute != null? Long.parseLong(lengthAttribute
.getValue()) : 0L;
} catch (IOException e) {
throw new ErrorDataDecoderException(e);
} catch (NumberFormatException e) {
size = 0;
}
try {
currentFileUpload = factory.createFileUpload(
request,
nameAttribute.getValue(), filenameAttribute.getValue(),
contentTypeAttribute.getValue(), mechanism.value,
localCharset, size);
} catch (NullPointerException e) {
throw new ErrorDataDecoderException(e);
} catch (IllegalArgumentException e) {
throw new ErrorDataDecoderException(e);
} catch (IOException e) {
throw new ErrorDataDecoderException(e);
}
}
// load data as much as possible
try {
readFileUploadByteMultipart(delimiter);
} catch (NotEnoughDataDecoderException e) {
// do not change the buffer position
// since some can be already saved into FileUpload
// So do not change the currentStatus
return null;
}
if (currentFileUpload.isCompleted()) {
// ready to load the next one
if (currentStatus == MultiPartStatus.FILEUPLOAD) {
currentStatus = MultiPartStatus.HEADERDELIMITER;
currentFieldAttributes = null;
} else {
currentStatus = MultiPartStatus.MIXEDDELIMITER;
cleanMixedAttributes();
}
FileUpload fileUpload = currentFileUpload;
currentFileUpload = null;
return fileUpload;
}
// do not change the buffer position
// since some can be already saved into FileUpload
// So do not change the currentStatus
return null;
}
/**
* Clean all HttpDatas (on Disk) for the current request.
*/
public void cleanFiles() {
factory.cleanRequestHttpDatas(request);
}
/**
* Remove the given FileUpload from the list of FileUploads to clean
*/
public void removeHttpDataFromClean(InterfaceHttpData data) {
factory.removeHttpDataFromClean(request, data);
}
/**
* Remove all Attributes that should be cleaned between two FileUpload in Mixed mode
*/
private void cleanMixedAttributes() {
currentFieldAttributes.remove(HttpHeaders.Values.CHARSET);
currentFieldAttributes.remove(HttpHeaders.Names.CONTENT_LENGTH);
currentFieldAttributes.remove(HttpHeaders.Names.CONTENT_TRANSFER_ENCODING);
currentFieldAttributes.remove(HttpHeaders.Names.CONTENT_TYPE);
currentFieldAttributes.remove(HttpPostBodyUtil.FILENAME);
}
/**
* Read one line up to the CRLF or LF
* @return the String from one line
* @throws NotEnoughDataDecoderException Need more chunks and
* reset the readerInder to the previous value
*/
private String readLineStandard() throws NotEnoughDataDecoderException {
int readerIndex = undecodedChunk.readerIndex();
try {
StringBuilder sb = new StringBuilder(64);
while (undecodedChunk.readable()) {
byte nextByte = undecodedChunk.readByte();
if (nextByte == HttpCodecUtil.CR) {
nextByte = undecodedChunk.readByte();
if (nextByte == HttpCodecUtil.LF) {
return sb.toString();
}
} else if (nextByte == HttpCodecUtil.LF) {
return sb.toString();
} else {
sb.append((char) nextByte);
}
}
} catch (IndexOutOfBoundsException e) {
undecodedChunk.readerIndex(readerIndex);
throw new NotEnoughDataDecoderException(e);
}
undecodedChunk.readerIndex(readerIndex);
throw new NotEnoughDataDecoderException();
}
/**
* Read one line up to the CRLF or LF
* @return the String from one line
* @throws NotEnoughDataDecoderException Need more chunks and
* reset the readerInder to the previous value
*/
private String readLine() throws NotEnoughDataDecoderException {
SeekAheadOptimize sao = null;
try {
sao = new SeekAheadOptimize(undecodedChunk);
} catch (SeekAheadNoBackArray e1) {
return readLineStandard();
}
int readerIndex = undecodedChunk.readerIndex();
try {
StringBuilder sb = new StringBuilder(64);
while (sao.pos < sao.limit) {
byte nextByte = sao.bytes[sao.pos ++];
if (nextByte == HttpCodecUtil.CR) {
if (sao.pos < sao.limit) {
nextByte = sao.bytes[sao.pos ++];
if (nextByte == HttpCodecUtil.LF) {
sao.setReadPosition(0);
return sb.toString();
}
} else {
sb.append((char) nextByte);
}
} else if (nextByte == HttpCodecUtil.LF) {
sao.setReadPosition(0);
return sb.toString();
} else {
sb.append((char) nextByte);
}
}
} catch (IndexOutOfBoundsException e) {
undecodedChunk.readerIndex(readerIndex);
throw new NotEnoughDataDecoderException(e);
}
undecodedChunk.readerIndex(readerIndex);
throw new NotEnoughDataDecoderException();
}
/**
* Read a FileUpload data as Byte (Binary) and add the bytes directly to the
* FileUpload. If the delimiter is found, the FileUpload is completed.
* @param delimiter
* @throws NotEnoughDataDecoderException Need more chunks but
* do not reset the readerInder since some values will be already added to the FileOutput
* @throws ErrorDataDecoderException write IO error occurs with the FileUpload
*/
private void readFileUploadByteMultipartStandard(String delimiter)
throws NotEnoughDataDecoderException, ErrorDataDecoderException {
int readerIndex = undecodedChunk.readerIndex();
// found the decoder limit
boolean newLine = true;
int index = 0;
int lastPosition = undecodedChunk.readerIndex();
boolean found = false;
while (undecodedChunk.readable()) {
byte nextByte = undecodedChunk.readByte();
if (newLine) {
// Check the delimiter
if (nextByte == delimiter.codePointAt(index)) {
index ++;
if (delimiter.length() == index) {
found = true;
break;
}
continue;
} else {
newLine = false;
index = 0;
// continue until end of line
if (nextByte == HttpCodecUtil.CR) {
if (undecodedChunk.readable()) {
nextByte = undecodedChunk.readByte();
if (nextByte == HttpCodecUtil.LF) {
newLine = true;
index = 0;
lastPosition = undecodedChunk.readerIndex() - 2;
}
}
} else if (nextByte == HttpCodecUtil.LF) {
newLine = true;
index = 0;
lastPosition = undecodedChunk.readerIndex() - 1;
} else {
// save last valid position
lastPosition = undecodedChunk.readerIndex();
}
}
} else {
// continue until end of line
if (nextByte == HttpCodecUtil.CR) {
if (undecodedChunk.readable()) {
nextByte = undecodedChunk.readByte();
if (nextByte == HttpCodecUtil.LF) {
newLine = true;
index = 0;
lastPosition = undecodedChunk.readerIndex() - 2;
}
}
} else if (nextByte == HttpCodecUtil.LF) {
newLine = true;
index = 0;
lastPosition = undecodedChunk.readerIndex() - 1;
} else {
// save last valid position
lastPosition = undecodedChunk.readerIndex();
}
}
}
ChannelBuffer buffer = undecodedChunk.slice(readerIndex, lastPosition -
readerIndex);
if (found) {
// found so lastPosition is correct and final
try {
currentFileUpload.addContent(buffer, true);
// just before the CRLF and delimiter
undecodedChunk.readerIndex(lastPosition);
} catch (IOException e) {
throw new ErrorDataDecoderException(e);
}
} else {
// possibly the delimiter is partially found but still the last position is OK
try {
currentFileUpload.addContent(buffer, false);
// last valid char (not CR, not LF, not beginning of delimiter)
undecodedChunk.readerIndex(lastPosition);
throw new NotEnoughDataDecoderException();
} catch (IOException e) {
throw new ErrorDataDecoderException(e);
}
}
}
/**
* Read a FileUpload data as Byte (Binary) and add the bytes directly to the
* FileUpload. If the delimiter is found, the FileUpload is completed.
* @param delimiter
* @throws NotEnoughDataDecoderException Need more chunks but
* do not reset the readerInder since some values will be already added to the FileOutput
* @throws ErrorDataDecoderException write IO error occurs with the FileUpload
*/
private void readFileUploadByteMultipart(String delimiter)
throws NotEnoughDataDecoderException, ErrorDataDecoderException {
SeekAheadOptimize sao = null;
try {
sao = new SeekAheadOptimize(undecodedChunk);
} catch (SeekAheadNoBackArray e1) {
readFileUploadByteMultipartStandard(delimiter);
return;
}
int readerIndex = undecodedChunk.readerIndex();
// found the decoder limit
boolean newLine = true;
int index = 0;
int lastPosition = undecodedChunk.readerIndex();
boolean found = false;
while (sao.pos < sao.limit) {
byte nextByte = sao.bytes[sao.pos ++];
if (newLine) {
// Check the delimiter
if (nextByte == delimiter.codePointAt(index)) {
index ++;
if (delimiter.length() == index) {
found = true;
sao.setReadPosition(0);
break;
}
continue;
} else {
newLine = false;
index = 0;
// continue until end of line
if (nextByte == HttpCodecUtil.CR) {
if (sao.pos < sao.limit) {
nextByte = sao.bytes[sao.pos ++];
if (nextByte == HttpCodecUtil.LF) {
newLine = true;
index = 0;
sao.setReadPosition(0);
lastPosition = undecodedChunk.readerIndex() - 2;
}
} else {
// save last valid position
sao.setReadPosition(0);
lastPosition = undecodedChunk.readerIndex();
}
} else if (nextByte == HttpCodecUtil.LF) {
newLine = true;
index = 0;
sao.setReadPosition(0);
lastPosition = undecodedChunk.readerIndex() - 1;
} else {
// save last valid position
sao.setReadPosition(0);
lastPosition = undecodedChunk.readerIndex();
}
}
} else {
// continue until end of line
if (nextByte == HttpCodecUtil.CR) {
if (sao.pos < sao.limit) {
nextByte = sao.bytes[sao.pos ++];
if (nextByte == HttpCodecUtil.LF) {
newLine = true;
index = 0;
sao.setReadPosition(0);
lastPosition = undecodedChunk.readerIndex() - 2;
}
} else {
// save last valid position
sao.setReadPosition(0);
lastPosition = undecodedChunk.readerIndex();
}
} else if (nextByte == HttpCodecUtil.LF) {
newLine = true;
index = 0;
sao.setReadPosition(0);
lastPosition = undecodedChunk.readerIndex() - 1;
} else {
// save last valid position
sao.setReadPosition(0);
lastPosition = undecodedChunk.readerIndex();
}
}
}
ChannelBuffer buffer = undecodedChunk.slice(readerIndex, lastPosition - readerIndex);
if (found) {
// found so lastPosition is correct and final
try {
currentFileUpload.addContent(buffer, true);
// just before the CRLF and delimiter
undecodedChunk.readerIndex(lastPosition);
} catch (IOException e) {
throw new ErrorDataDecoderException(e);
}
} else {
// possibly the delimiter is partially found but still the last position is OK
try {
currentFileUpload.addContent(buffer, false);
// last valid char (not CR, not LF, not beginning of delimiter)
undecodedChunk.readerIndex(lastPosition);
throw new NotEnoughDataDecoderException();
} catch (IOException e) {
throw new ErrorDataDecoderException(e);
}
}
}
/**
* Load the field value from a Multipart request
* @throws NotEnoughDataDecoderException Need more chunks
* @throws ErrorDataDecoderException
*/
private void loadFieldMultipartStandard(String delimiter)
throws NotEnoughDataDecoderException, ErrorDataDecoderException {
int readerIndex = undecodedChunk.readerIndex();
try {
// found the decoder limit
boolean newLine = true;
int index = 0;
int lastPosition = undecodedChunk.readerIndex();
boolean found = false;
while (undecodedChunk.readable()) {
byte nextByte = undecodedChunk.readByte();
if (newLine) {
// Check the delimiter
if (nextByte == delimiter.codePointAt(index)) {
index ++;
if (delimiter.length() == index) {
found = true;
break;
}
continue;
} else {
newLine = false;
index = 0;
// continue until end of line
if (nextByte == HttpCodecUtil.CR) {
if (undecodedChunk.readable()) {
nextByte = undecodedChunk.readByte();
if (nextByte == HttpCodecUtil.LF) {
newLine = true;
index = 0;
lastPosition = undecodedChunk.readerIndex() - 2;
}
}
} else if (nextByte == HttpCodecUtil.LF) {
newLine = true;
index = 0;
lastPosition = undecodedChunk.readerIndex() - 1;
} else {
lastPosition = undecodedChunk.readerIndex();
}
}
} else {
// continue until end of line
if (nextByte == HttpCodecUtil.CR) {
if (undecodedChunk.readable()) {
nextByte = undecodedChunk.readByte();
if (nextByte == HttpCodecUtil.LF) {
newLine = true;
index = 0;
lastPosition = undecodedChunk.readerIndex() - 2;
}
}
} else if (nextByte == HttpCodecUtil.LF) {
newLine = true;
index = 0;
lastPosition = undecodedChunk.readerIndex() - 1;
} else {
lastPosition = undecodedChunk.readerIndex();
}
}
}
if (found) {
// found so lastPosition is correct
// but position is just after the delimiter (either close delimiter or simple one)
// so go back of delimiter size
try {
currentAttribute.addContent(
undecodedChunk.slice(readerIndex, lastPosition - readerIndex),
true);
} catch (IOException e) {
throw new ErrorDataDecoderException(e);
}
undecodedChunk.readerIndex(lastPosition);
} else {
try {
currentAttribute.addContent(
undecodedChunk.slice(readerIndex, lastPosition - readerIndex),
false);
} catch (IOException e) {
throw new ErrorDataDecoderException(e);
}
undecodedChunk.readerIndex(lastPosition);
throw new NotEnoughDataDecoderException();
}
} catch (IndexOutOfBoundsException e) {
undecodedChunk.readerIndex(readerIndex);
throw new NotEnoughDataDecoderException(e);
}
}
/**
* Load the field value from a Multipart request
* @throws NotEnoughDataDecoderException Need more chunks
* @throws ErrorDataDecoderException
*/
private void loadFieldMultipart(String delimiter)
throws NotEnoughDataDecoderException, ErrorDataDecoderException {
SeekAheadOptimize sao = null;
try {
sao = new SeekAheadOptimize(undecodedChunk);
} catch (SeekAheadNoBackArray e1) {
loadFieldMultipartStandard(delimiter);
return;
}
int readerIndex = undecodedChunk.readerIndex();
try {
// found the decoder limit
boolean newLine = true;
int index = 0;
int lastPosition = undecodedChunk.readerIndex();
boolean found = false;
while (sao.pos < sao.limit) {
byte nextByte = sao.bytes[sao.pos ++];
if (newLine) {
// Check the delimiter
if (nextByte == delimiter.codePointAt(index)) {
index ++;
if (delimiter.length() == index) {
found = true;
sao.setReadPosition(0);
break;
}
continue;
} else {
newLine = false;
index = 0;
// continue until end of line
if (nextByte == HttpCodecUtil.CR) {
if (sao.pos < sao.limit) {
nextByte = sao.bytes[sao.pos ++];
if (nextByte == HttpCodecUtil.LF) {
newLine = true;
index = 0;
sao.setReadPosition(0);
lastPosition = undecodedChunk.readerIndex() - 2;
}
} else {
sao.setReadPosition(0);
lastPosition = undecodedChunk.readerIndex();
}
} else if (nextByte == HttpCodecUtil.LF) {
newLine = true;
index = 0;
sao.setReadPosition(0);
lastPosition = undecodedChunk.readerIndex() - 1;
} else {
sao.setReadPosition(0);
lastPosition = undecodedChunk.readerIndex();
}
}
} else {
// continue until end of line
if (nextByte == HttpCodecUtil.CR) {
if (sao.pos < sao.limit) {
nextByte = sao.bytes[sao.pos ++];
if (nextByte == HttpCodecUtil.LF) {
newLine = true;
index = 0;
sao.setReadPosition(0);
lastPosition = undecodedChunk.readerIndex() - 2;
}
} else {
sao.setReadPosition(0);
lastPosition = undecodedChunk.readerIndex();
}
} else if (nextByte == HttpCodecUtil.LF) {
newLine = true;
index = 0;
sao.setReadPosition(0);
lastPosition = undecodedChunk.readerIndex() - 1;
} else {
sao.setReadPosition(0);
lastPosition = undecodedChunk.readerIndex();
}
}
}
if (found) {
// found so lastPosition is correct
// but position is just after the delimiter (either close delimiter or simple one)
// so go back of delimiter size
try {
currentAttribute.addContent(
undecodedChunk.slice(readerIndex, lastPosition - readerIndex), true);
} catch (IOException e) {
throw new ErrorDataDecoderException(e);
}
undecodedChunk.readerIndex(lastPosition);
} else {
try {
currentAttribute.addContent(
undecodedChunk.slice(readerIndex, lastPosition - readerIndex), false);
} catch (IOException e) {
throw new ErrorDataDecoderException(e);
}
undecodedChunk.readerIndex(lastPosition);
throw new NotEnoughDataDecoderException();
}
} catch (IndexOutOfBoundsException e) {
undecodedChunk.readerIndex(readerIndex);
throw new NotEnoughDataDecoderException(e);
}
}
/**
* Clean the String from any unallowed character
* @return the cleaned String
*/
private String cleanString(String field) {
StringBuilder sb = new StringBuilder(field.length());
int i = 0;
for (i = 0; i < field.length(); i ++) {
char nextChar = field.charAt(i);
if (nextChar == HttpCodecUtil.COLON) {
sb.append(HttpCodecUtil.SP);
} else if (nextChar == HttpCodecUtil.COMMA) {
sb.append(HttpCodecUtil.SP);
} else if (nextChar == HttpCodecUtil.EQUALS) {
sb.append(HttpCodecUtil.SP);
} else if (nextChar == HttpCodecUtil.SEMICOLON) {
sb.append(HttpCodecUtil.SP);
} else if (nextChar == HttpCodecUtil.HT) {
sb.append(HttpCodecUtil.SP);
} else if (nextChar == HttpCodecUtil.DOUBLE_QUOTE) {
// nothing added, just removes it
} else {
sb.append(nextChar);
}
}
return sb.toString().trim();
}
/**
* Skip one empty line
* @return True if one empty line was skipped
*/
private boolean skipOneLine() {
if (!undecodedChunk.readable()) {
return false;
}
byte nextByte = undecodedChunk.readByte();
if (nextByte == HttpCodecUtil.CR) {
if (!undecodedChunk.readable()) {
undecodedChunk.readerIndex(undecodedChunk.readerIndex() - 1);
return false;
}
nextByte = undecodedChunk.readByte();
if (nextByte == HttpCodecUtil.LF) {
return true;
}
undecodedChunk.readerIndex(undecodedChunk.readerIndex() - 2);
return false;
} else if (nextByte == HttpCodecUtil.LF) {
return true;
}
undecodedChunk.readerIndex(undecodedChunk.readerIndex() - 1);
return false;
}
/**
* Split the very first line (Content-Type value) in 2 Strings
* @param sb
* @return the array of 2 Strings
*/
private String[] splitHeaderContentType(String sb) {
int size = sb.length();
int aStart;
int aEnd;
int bStart;
int bEnd;
aStart = HttpPostBodyUtil.findNonWhitespace(sb, 0);
aEnd = HttpPostBodyUtil.findWhitespace(sb, aStart);
if (aEnd >= size) {
return new String[] { sb, "" };
}
if (sb.charAt(aEnd) == ';') {
aEnd --;
}
bStart = HttpPostBodyUtil.findNonWhitespace(sb, aEnd);
bEnd = HttpPostBodyUtil.findEndOfString(sb);
return new String[] { sb.substring(aStart, aEnd),
sb.substring(bStart, bEnd) };
}
/**
* Split one header in Multipart
* @param sb
* @return an array of String where rank 0 is the name of the header, follows by several
* values that were separated by ';' or ','
*/
private String[] splitMultipartHeader(String sb) {
ArrayList<String> headers = new ArrayList<String>(1);
int nameStart;
int nameEnd;
int colonEnd;
int valueStart;
int valueEnd;
nameStart = HttpPostBodyUtil.findNonWhitespace(sb, 0);
for (nameEnd = nameStart; nameEnd < sb.length(); nameEnd ++) {
char ch = sb.charAt(nameEnd);
if (ch == ':' || Character.isWhitespace(ch)) {
break;
}
}
for (colonEnd = nameEnd; colonEnd < sb.length(); colonEnd ++) {
if (sb.charAt(colonEnd) == ':') {
colonEnd ++;
break;
}
}
valueStart = HttpPostBodyUtil.findNonWhitespace(sb, colonEnd);
valueEnd = HttpPostBodyUtil.findEndOfString(sb);
headers.add(sb.substring(nameStart, nameEnd));
String svalue = sb.substring(valueStart, valueEnd);
String[] values = null;
if (svalue.indexOf(";") >= 0) {
values = svalue.split(";");
} else {
values = svalue.split(",");
}
for (String value: values) {
headers.add(value.trim());
}
String[] array = new String[headers.size()];
for (int i = 0; i < headers.size(); i ++) {
array[i] = headers.get(i);
}
return array;
}
/**
* Exception when try reading data from request in chunked format, and not enough
* data are available (need more chunks)
*/
public static class NotEnoughDataDecoderException extends Exception {
/**
*/
private static final long serialVersionUID = -7846841864603865638L;
/**
*/
public NotEnoughDataDecoderException() {
}
/**
* @param arg0
*/
public NotEnoughDataDecoderException(String arg0) {
super(arg0);
}
/**
* @param arg0
*/
public NotEnoughDataDecoderException(Throwable arg0) {
super(arg0);
}
/**
* @param arg0
* @param arg1
*/
public NotEnoughDataDecoderException(String arg0, Throwable arg1) {
super(arg0, arg1);
}
}
/**
* Exception when the body is fully decoded, even if there is still data
*/
public static class EndOfDataDecoderException extends Exception {
/**
*/
private static final long serialVersionUID = 1336267941020800769L;
}
/**
* Exception when an error occurs while decoding
*/
public static class ErrorDataDecoderException extends Exception {
/**
*/
private static final long serialVersionUID = 5020247425493164465L;
/**
*/
public ErrorDataDecoderException() {
}
/**
* @param arg0
*/
public ErrorDataDecoderException(String arg0) {
super(arg0);
}
/**
* @param arg0
*/
public ErrorDataDecoderException(Throwable arg0) {
super(arg0);
}
/**
* @param arg0
* @param arg1
*/
public ErrorDataDecoderException(String arg0, Throwable arg1) {
super(arg0, arg1);
}
}
/**
* Exception when an unappropriated method was called on a request
*/
public static class IncompatibleDataDecoderException extends Exception {
/**
*/
private static final long serialVersionUID = -953268047926250267L;
/**
*/
public IncompatibleDataDecoderException() {
}
/**
* @param arg0
*/
public IncompatibleDataDecoderException(String arg0) {
super(arg0);
}
/**
* @param arg0
*/
public IncompatibleDataDecoderException(Throwable arg0) {
super(arg0);
}
/**
* @param arg0
* @param arg1
*/
public IncompatibleDataDecoderException(String arg0, Throwable arg1) {
super(arg0, arg1);
}
}
}
|
codec-http/src/main/java/io/netty/handler/codec/http/HttpPostRequestDecoder.java
|
/*
* Copyright 2011 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.http;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import io.netty.buffer.ChannelBuffer;
import io.netty.buffer.ChannelBuffers;
import io.netty.handler.codec.http.HttpPostBodyUtil.TransferEncodingMechanism;
/**
* This decoder will decode Body and can handle POST BODY.
*/
public class HttpPostRequestDecoder {
/**
* Factory used to create InterfaceHttpData
*/
private final HttpDataFactory factory;
/**
* Request to decode
*/
private final HttpRequest request;
/**
* Default charset to use
*/
private final Charset charset;
/**
* Does request have a body to decode
*/
private boolean bodyToDecode;
/**
* Does the last chunk already received
*/
private boolean isLastChunk;
/**
* HttpDatas from Body
*/
private final List<InterfaceHttpData> bodyListHttpData = new ArrayList<InterfaceHttpData>();
/**
* HttpDatas as Map from Body
*/
private final Map<String, List<InterfaceHttpData>> bodyMapHttpData = new TreeMap<String, List<InterfaceHttpData>>(
CaseIgnoringComparator.INSTANCE);
/**
* The current channelBuffer
*/
private ChannelBuffer undecodedChunk;
/**
* Does this request is a Multipart request
*/
private boolean isMultipart;
/**
* Body HttpDatas current position
*/
private int bodyListHttpDataRank;
/**
* If multipart, this is the boundary for the flobal multipart
*/
private String multipartDataBoundary;
/**
* If multipart, there could be internal multiparts (mixed) to the global multipart.
* Only one level is allowed.
*/
private String multipartMixedBoundary;
/**
* Current status
*/
private MultiPartStatus currentStatus = MultiPartStatus.NOTSTARTED;
/**
* Used in Multipart
*/
private Map<String, Attribute> currentFieldAttributes;
/**
* The current FileUpload that is currently in decode process
*/
private FileUpload currentFileUpload;
/**
* The current Attribute that is currently in decode process
*/
private Attribute currentAttribute;
/**
*
* @param request the request to decode
* @throws NullPointerException for request
* @throws IncompatibleDataDecoderException if the request has no body to decode
* @throws ErrorDataDecoderException if the default charset was wrong when decoding or other errors
*/
public HttpPostRequestDecoder(HttpRequest request)
throws ErrorDataDecoderException, IncompatibleDataDecoderException {
this(new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE),
request, HttpCodecUtil.DEFAULT_CHARSET);
}
/**
*
* @param factory the factory used to create InterfaceHttpData
* @param request the request to decode
* @throws NullPointerException for request or factory
* @throws IncompatibleDataDecoderException if the request has no body to decode
* @throws ErrorDataDecoderException if the default charset was wrong when decoding or other errors
*/
public HttpPostRequestDecoder(HttpDataFactory factory, HttpRequest request)
throws ErrorDataDecoderException, IncompatibleDataDecoderException {
this(factory, request, HttpCodecUtil.DEFAULT_CHARSET);
}
/**
*
* @param factory the factory used to create InterfaceHttpData
* @param request the request to decode
* @param charset the charset to use as default
* @throws NullPointerException for request or charset or factory
* @throws IncompatibleDataDecoderException if the request has no body to decode
* @throws ErrorDataDecoderException if the default charset was wrong when decoding or other errors
*/
public HttpPostRequestDecoder(HttpDataFactory factory, HttpRequest request,
Charset charset) throws ErrorDataDecoderException,
IncompatibleDataDecoderException {
if (factory == null) {
throw new NullPointerException("factory");
}
if (request == null) {
throw new NullPointerException("request");
}
if (charset == null) {
throw new NullPointerException("charset");
}
this.request = request;
HttpMethod method = request.getMethod();
if (method.equals(HttpMethod.POST) || method.equals(HttpMethod.PUT) || method.equals(HttpMethod.PATCH)) {
bodyToDecode = true;
}
this.charset = charset;
this.factory = factory;
// Fill default values
if (this.request.containsHeader(HttpHeaders.Names.CONTENT_TYPE)) {
checkMultipart(this.request.getHeader(HttpHeaders.Names.CONTENT_TYPE));
} else {
isMultipart = false;
}
if (!bodyToDecode) {
throw new IncompatibleDataDecoderException("No Body to decode");
}
if (!this.request.isChunked()) {
undecodedChunk = this.request.getContent();
isLastChunk = true;
parseBody();
}
}
/**
* states follow
* NOTSTARTED PREAMBLE (
* (HEADERDELIMITER DISPOSITION (FIELD | FILEUPLOAD))*
* (HEADERDELIMITER DISPOSITION MIXEDPREAMBLE
* (MIXEDDELIMITER MIXEDDISPOSITION MIXEDFILEUPLOAD)+
* MIXEDCLOSEDELIMITER)*
* CLOSEDELIMITER)+ EPILOGUE
*
* First status is: NOSTARTED
Content-type: multipart/form-data, boundary=AaB03x => PREAMBLE in Header
--AaB03x => HEADERDELIMITER
content-disposition: form-data; name="field1" => DISPOSITION
Joe Blow => FIELD
--AaB03x => HEADERDELIMITER
content-disposition: form-data; name="pics" => DISPOSITION
Content-type: multipart/mixed, boundary=BbC04y
--BbC04y => MIXEDDELIMITER
Content-disposition: attachment; filename="file1.txt" => MIXEDDISPOSITION
Content-Type: text/plain
... contents of file1.txt ... => MIXEDFILEUPLOAD
--BbC04y => MIXEDDELIMITER
Content-disposition: file; filename="file2.gif" => MIXEDDISPOSITION
Content-type: image/gif
Content-Transfer-Encoding: binary
...contents of file2.gif... => MIXEDFILEUPLOAD
--BbC04y-- => MIXEDCLOSEDELIMITER
--AaB03x-- => CLOSEDELIMITER
Once CLOSEDELIMITER is found, last status is EPILOGUE
*/
private enum MultiPartStatus {
NOTSTARTED,
PREAMBLE,
HEADERDELIMITER,
DISPOSITION,
FIELD,
FILEUPLOAD,
MIXEDPREAMBLE,
MIXEDDELIMITER,
MIXEDDISPOSITION,
MIXEDFILEUPLOAD,
MIXEDCLOSEDELIMITER,
CLOSEDELIMITER,
PREEPILOGUE,
EPILOGUE
}
/**
* Check from the request ContentType if this request is a Multipart request.
* @param contentType
* @throws ErrorDataDecoderException
*/
private void checkMultipart(String contentType)
throws ErrorDataDecoderException {
// Check if Post using "multipart/form-data; boundary=--89421926422648"
String[] headerContentType = splitHeaderContentType(contentType);
if (headerContentType[0].toLowerCase().startsWith(
HttpHeaders.Values.MULTIPART_FORM_DATA) &&
headerContentType[1].toLowerCase().startsWith(
HttpHeaders.Values.BOUNDARY)) {
String[] boundary = headerContentType[1].split("=");
if (boundary.length != 2) {
throw new ErrorDataDecoderException("Needs a boundary value");
}
multipartDataBoundary = "--" + boundary[1];
isMultipart = true;
currentStatus = MultiPartStatus.HEADERDELIMITER;
} else {
isMultipart = false;
}
}
/**
* True if this request is a Multipart request
* @return True if this request is a Multipart request
*/
public boolean isMultipart() {
return isMultipart;
}
/**
* This method returns a List of all HttpDatas from body.<br>
*
* If chunked, all chunks must have been offered using offer() method.
* If not, NotEnoughDataDecoderException will be raised.
*
* @return the list of HttpDatas from Body part for POST method
* @throws NotEnoughDataDecoderException Need more chunks
*/
public List<InterfaceHttpData> getBodyHttpDatas()
throws NotEnoughDataDecoderException {
if (!isLastChunk) {
throw new NotEnoughDataDecoderException();
}
return bodyListHttpData;
}
/**
* This method returns a List of all HttpDatas with the given name from body.<br>
*
* If chunked, all chunks must have been offered using offer() method.
* If not, NotEnoughDataDecoderException will be raised.
* @param name
* @return All Body HttpDatas with the given name (ignore case)
* @throws NotEnoughDataDecoderException need more chunks
*/
public List<InterfaceHttpData> getBodyHttpDatas(String name)
throws NotEnoughDataDecoderException {
if (!isLastChunk) {
throw new NotEnoughDataDecoderException();
}
return bodyMapHttpData.get(name);
}
/**
* This method returns the first InterfaceHttpData with the given name from body.<br>
*
* If chunked, all chunks must have been offered using offer() method.
* If not, NotEnoughDataDecoderException will be raised.
*
* @param name
* @return The first Body InterfaceHttpData with the given name (ignore case)
* @throws NotEnoughDataDecoderException need more chunks
*/
public InterfaceHttpData getBodyHttpData(String name)
throws NotEnoughDataDecoderException {
if (!isLastChunk) {
throw new NotEnoughDataDecoderException();
}
List<InterfaceHttpData> list = bodyMapHttpData.get(name);
if (list != null) {
return list.get(0);
}
return null;
}
/**
* Initialized the internals from a new chunk
* @param chunk the new received chunk
* @throws ErrorDataDecoderException if there is a problem with the charset decoding or
* other errors
*/
public void offer(HttpChunk chunk) throws ErrorDataDecoderException {
ChannelBuffer chunked = chunk.getContent();
if (undecodedChunk == null) {
undecodedChunk = chunked;
} else {
//undecodedChunk = ChannelBuffers.wrappedBuffer(undecodedChunk, chunk.getContent());
// less memory usage
undecodedChunk = ChannelBuffers.wrappedBuffer(
undecodedChunk, chunked);
}
if (chunk.isLast()) {
isLastChunk = true;
}
parseBody();
}
/**
* True if at current status, there is an available decoded InterfaceHttpData from the Body.
*
* This method works for chunked and not chunked request.
*
* @return True if at current status, there is a decoded InterfaceHttpData
* @throws EndOfDataDecoderException No more data will be available
*/
public boolean hasNext() throws EndOfDataDecoderException {
if (currentStatus == MultiPartStatus.EPILOGUE) {
// OK except if end of list
if (bodyListHttpDataRank >= bodyListHttpData.size()) {
throw new EndOfDataDecoderException();
}
}
return bodyListHttpData.size() > 0 &&
bodyListHttpDataRank < bodyListHttpData.size();
}
/**
* Returns the next available InterfaceHttpData or null if, at the time it is called, there is no more
* available InterfaceHttpData. A subsequent call to offer(httpChunk) could enable more data.
*
* @return the next available InterfaceHttpData or null if none
* @throws EndOfDataDecoderException No more data will be available
*/
public InterfaceHttpData next() throws EndOfDataDecoderException {
if (hasNext()) {
return bodyListHttpData.get(bodyListHttpDataRank++);
}
return null;
}
/**
* This method will parse as much as possible data and fill the list and map
* @throws ErrorDataDecoderException if there is a problem with the charset decoding or
* other errors
*/
private void parseBody() throws ErrorDataDecoderException {
if (currentStatus == MultiPartStatus.PREEPILOGUE ||
currentStatus == MultiPartStatus.EPILOGUE) {
if (isLastChunk) {
currentStatus = MultiPartStatus.EPILOGUE;
}
return;
}
if (isMultipart) {
parseBodyMultipart();
} else {
parseBodyAttributes();
}
}
/**
* Utility function to add a new decoded data
* @param data
*/
private void addHttpData(InterfaceHttpData data) {
if (data == null) {
return;
}
List<InterfaceHttpData> datas = bodyMapHttpData.get(data.getName());
if (datas == null) {
datas = new ArrayList<InterfaceHttpData>(1);
bodyMapHttpData.put(data.getName(), datas);
}
datas.add(data);
bodyListHttpData.add(data);
}
/**
* This method fill the map and list with as much Attribute as possible from Body in
* not Multipart mode.
*
* @throws ErrorDataDecoderException if there is a problem with the charset decoding or
* other errors
*/
private void parseBodyAttributes() throws ErrorDataDecoderException {
int firstpos = undecodedChunk.readerIndex();
int currentpos = firstpos;
int equalpos = firstpos;
int ampersandpos = firstpos;
if (currentStatus == MultiPartStatus.NOTSTARTED) {
currentStatus = MultiPartStatus.DISPOSITION;
}
boolean contRead = true;
try {
while (undecodedChunk.readable() && contRead) {
char read = (char) undecodedChunk.readUnsignedByte();
currentpos++;
switch (currentStatus) {
case DISPOSITION:// search '='
if (read == '=') {
currentStatus = MultiPartStatus.FIELD;
equalpos = currentpos - 1;
String key = decodeAttribute(
undecodedChunk.toString(firstpos, equalpos - firstpos, charset),
charset);
currentAttribute = factory.createAttribute(request, key);
firstpos = currentpos;
} else if (read == '&') { // special empty FIELD
currentStatus = MultiPartStatus.DISPOSITION;
ampersandpos = currentpos - 1;
String key = decodeAttribute(undecodedChunk.toString(firstpos, ampersandpos - firstpos, charset), charset);
currentAttribute = factory.createAttribute(request, key);
currentAttribute.setValue(""); // empty
addHttpData(currentAttribute);
currentAttribute = null;
firstpos = currentpos;
contRead = true;
}
break;
case FIELD:// search '&' or end of line
if (read == '&') {
currentStatus = MultiPartStatus.DISPOSITION;
ampersandpos = currentpos - 1;
setFinalBuffer(undecodedChunk.slice(firstpos, ampersandpos - firstpos));
firstpos = currentpos;
contRead = true;
} else if (read == HttpCodecUtil.CR) {
if (undecodedChunk.readable()) {
read = (char) undecodedChunk.readUnsignedByte();
currentpos++;
if (read == HttpCodecUtil.LF) {
currentStatus = MultiPartStatus.PREEPILOGUE;
ampersandpos = currentpos - 2;
setFinalBuffer(
undecodedChunk.slice(firstpos, ampersandpos - firstpos));
firstpos = currentpos;
contRead = false;
} else {
// Error
contRead = false;
throw new ErrorDataDecoderException("Bad end of line");
}
} else {
currentpos--;
}
} else if (read == HttpCodecUtil.LF) {
currentStatus = MultiPartStatus.PREEPILOGUE;
ampersandpos = currentpos - 1;
setFinalBuffer(
undecodedChunk.slice(firstpos, ampersandpos - firstpos));
firstpos = currentpos;
contRead = false;
}
break;
default:
// just stop
contRead = false;
}
}
if (isLastChunk && currentAttribute != null) {
// special case
ampersandpos = currentpos;
if (ampersandpos > firstpos) {
setFinalBuffer(
undecodedChunk.slice(firstpos, ampersandpos - firstpos));
} else if (! currentAttribute.isCompleted()) {
setFinalBuffer(ChannelBuffers.EMPTY_BUFFER);
}
firstpos = currentpos;
currentStatus = MultiPartStatus.EPILOGUE;
return;
}
if (contRead && currentAttribute != null) {
// reset index except if to continue in case of FIELD status
if (currentStatus == MultiPartStatus.FIELD) {
currentAttribute.addContent(
undecodedChunk.slice(firstpos, currentpos - firstpos),
false);
firstpos = currentpos;
}
undecodedChunk.readerIndex(firstpos);
} else {
// end of line so keep index
}
} catch (ErrorDataDecoderException e) {
// error while decoding
undecodedChunk.readerIndex(firstpos);
throw e;
} catch (IOException e) {
// error while decoding
undecodedChunk.readerIndex(firstpos);
throw new ErrorDataDecoderException(e);
}
}
private void setFinalBuffer(ChannelBuffer buffer) throws ErrorDataDecoderException, IOException {
currentAttribute.addContent(buffer, true);
String value = decodeAttribute(
currentAttribute.getChannelBuffer().toString(charset),
charset);
currentAttribute.setValue(value);
addHttpData(currentAttribute);
currentAttribute = null;
}
/**
* Decode component
* @param s
* @param charset
* @return the decoded component
* @throws ErrorDataDecoderException
*/
private static String decodeAttribute(String s, Charset charset)
throws ErrorDataDecoderException {
if (s == null) {
return "";
}
try {
return URLDecoder.decode(s, charset.name());
} catch (UnsupportedEncodingException e) {
throw new ErrorDataDecoderException(charset.toString(), e);
}
}
/**
* Parse the Body for multipart
*
* @throws ErrorDataDecoderException if there is a problem with the charset decoding or other errors
*/
private void parseBodyMultipart() throws ErrorDataDecoderException {
if (undecodedChunk == null || undecodedChunk.readableBytes() == 0) {
// nothing to decode
return;
}
InterfaceHttpData data = decodeMultipart(currentStatus);
while (data != null) {
addHttpData(data);
if (currentStatus == MultiPartStatus.PREEPILOGUE ||
currentStatus == MultiPartStatus.EPILOGUE) {
break;
}
data = decodeMultipart(currentStatus);
}
}
/**
* Decode a multipart request by pieces<br>
* <br>
* NOTSTARTED PREAMBLE (<br>
* (HEADERDELIMITER DISPOSITION (FIELD | FILEUPLOAD))*<br>
* (HEADERDELIMITER DISPOSITION MIXEDPREAMBLE<br>
* (MIXEDDELIMITER MIXEDDISPOSITION MIXEDFILEUPLOAD)+<br>
* MIXEDCLOSEDELIMITER)*<br>
* CLOSEDELIMITER)+ EPILOGUE<br>
*
* Inspired from HttpMessageDecoder
*
* @param state
* @return the next decoded InterfaceHttpData or null if none until now.
* @throws ErrorDataDecoderException if an error occurs
*/
private InterfaceHttpData decodeMultipart(MultiPartStatus state)
throws ErrorDataDecoderException {
switch (state) {
case NOTSTARTED:
throw new ErrorDataDecoderException(
"Should not be called with the current status");
case PREAMBLE:
// Content-type: multipart/form-data, boundary=AaB03x
throw new ErrorDataDecoderException(
"Should not be called with the current status");
case HEADERDELIMITER: {
// --AaB03x or --AaB03x--
return findMultipartDelimiter(multipartDataBoundary,
MultiPartStatus.DISPOSITION, MultiPartStatus.PREEPILOGUE);
}
case DISPOSITION: {
// content-disposition: form-data; name="field1"
// content-disposition: form-data; name="pics"; filename="file1.txt"
// and other immediate values like
// Content-type: image/gif
// Content-Type: text/plain
// Content-Type: text/plain; charset=ISO-8859-1
// Content-Transfer-Encoding: binary
// The following line implies a change of mode (mixed mode)
// Content-type: multipart/mixed, boundary=BbC04y
return findMultipartDisposition();
}
case FIELD: {
// Now get value according to Content-Type and Charset
Charset localCharset = null;
Attribute charsetAttribute = currentFieldAttributes
.get(HttpHeaders.Values.CHARSET);
if (charsetAttribute != null) {
try {
localCharset = Charset.forName(charsetAttribute.getValue());
} catch (IOException e) {
throw new ErrorDataDecoderException(e);
}
}
Attribute nameAttribute = currentFieldAttributes
.get(HttpPostBodyUtil.NAME);
if (currentAttribute == null) {
try {
currentAttribute = factory.createAttribute(request, nameAttribute
.getValue());
} catch (NullPointerException e) {
throw new ErrorDataDecoderException(e);
} catch (IllegalArgumentException e) {
throw new ErrorDataDecoderException(e);
} catch (IOException e) {
throw new ErrorDataDecoderException(e);
}
if (localCharset != null) {
currentAttribute.setCharset(localCharset);
}
}
// load data
try {
loadFieldMultipart(multipartDataBoundary);
} catch (NotEnoughDataDecoderException e) {
return null;
}
Attribute finalAttribute = currentAttribute;
currentAttribute = null;
currentFieldAttributes = null;
// ready to load the next one
currentStatus = MultiPartStatus.HEADERDELIMITER;
return finalAttribute;
}
case FILEUPLOAD: {
// eventually restart from existing FileUpload
return getFileUpload(multipartDataBoundary);
}
case MIXEDDELIMITER: {
// --AaB03x or --AaB03x--
// Note that currentFieldAttributes exists
return findMultipartDelimiter(multipartMixedBoundary,
MultiPartStatus.MIXEDDISPOSITION,
MultiPartStatus.HEADERDELIMITER);
}
case MIXEDDISPOSITION: {
return findMultipartDisposition();
}
case MIXEDFILEUPLOAD: {
// eventually restart from existing FileUpload
return getFileUpload(multipartMixedBoundary);
}
case PREEPILOGUE:
return null;
case EPILOGUE:
return null;
default:
throw new ErrorDataDecoderException("Shouldn't reach here.");
}
}
/**
* Find the next Multipart Delimiter
* @param delimiter delimiter to find
* @param dispositionStatus the next status if the delimiter is a start
* @param closeDelimiterStatus the next status if the delimiter is a close delimiter
* @return the next InterfaceHttpData if any
* @throws ErrorDataDecoderException
*/
private InterfaceHttpData findMultipartDelimiter(String delimiter,
MultiPartStatus dispositionStatus,
MultiPartStatus closeDelimiterStatus)
throws ErrorDataDecoderException {
// --AaB03x or --AaB03x--
int readerIndex = undecodedChunk.readerIndex();
HttpPostBodyUtil.skipControlCharacters(undecodedChunk);
skipOneLine();
String newline;
try {
newline = readLine();
} catch (NotEnoughDataDecoderException e) {
undecodedChunk.readerIndex(readerIndex);
return null;
}
if (newline.equals(delimiter)) {
currentStatus = dispositionStatus;
return decodeMultipart(dispositionStatus);
} else if (newline.equals(delimiter + "--")) {
// CLOSEDELIMITER or MIXED CLOSEDELIMITER found
currentStatus = closeDelimiterStatus;
if (currentStatus == MultiPartStatus.HEADERDELIMITER) {
// MIXEDCLOSEDELIMITER
// end of the Mixed part
currentFieldAttributes = null;
return decodeMultipart(MultiPartStatus.HEADERDELIMITER);
}
return null;
}
undecodedChunk.readerIndex(readerIndex);
throw new ErrorDataDecoderException("No Multipart delimiter found");
}
/**
* Find the next Disposition
* @return the next InterfaceHttpData if any
* @throws ErrorDataDecoderException
*/
private InterfaceHttpData findMultipartDisposition()
throws ErrorDataDecoderException {
int readerIndex = undecodedChunk.readerIndex();
if (currentStatus == MultiPartStatus.DISPOSITION) {
currentFieldAttributes = new TreeMap<String, Attribute>(
CaseIgnoringComparator.INSTANCE);
}
// read many lines until empty line with newline found! Store all data
while (!skipOneLine()) {
HttpPostBodyUtil.skipControlCharacters(undecodedChunk);
String newline;
try {
newline = readLine();
} catch (NotEnoughDataDecoderException e) {
undecodedChunk.readerIndex(readerIndex);
return null;
}
String[] contents = splitMultipartHeader(newline);
if (contents[0].equalsIgnoreCase(HttpPostBodyUtil.CONTENT_DISPOSITION)) {
boolean checkSecondArg = false;
if (currentStatus == MultiPartStatus.DISPOSITION) {
checkSecondArg = contents[1]
.equalsIgnoreCase(HttpPostBodyUtil.FORM_DATA);
} else {
checkSecondArg = contents[1]
.equalsIgnoreCase(HttpPostBodyUtil.ATTACHMENT) ||
contents[1]
.equalsIgnoreCase(HttpPostBodyUtil.FILE);
}
if (checkSecondArg) {
// read next values and store them in the map as Attribute
for (int i = 2; i < contents.length; i ++) {
String[] values = contents[i].split("=");
Attribute attribute;
try {
attribute = factory.createAttribute(request, values[0].trim(),
decodeAttribute(cleanString(values[1]), charset));
} catch (NullPointerException e) {
throw new ErrorDataDecoderException(e);
} catch (IllegalArgumentException e) {
throw new ErrorDataDecoderException(e);
}
currentFieldAttributes.put(attribute.getName(),
attribute);
}
}
} else if (contents[0]
.equalsIgnoreCase(HttpHeaders.Names.CONTENT_TRANSFER_ENCODING)) {
Attribute attribute;
try {
attribute = factory.createAttribute(request,
HttpHeaders.Names.CONTENT_TRANSFER_ENCODING,
cleanString(contents[1]));
} catch (NullPointerException e) {
throw new ErrorDataDecoderException(e);
} catch (IllegalArgumentException e) {
throw new ErrorDataDecoderException(e);
}
currentFieldAttributes.put(
HttpHeaders.Names.CONTENT_TRANSFER_ENCODING, attribute);
} else if (contents[0]
.equalsIgnoreCase(HttpHeaders.Names.CONTENT_LENGTH)) {
Attribute attribute;
try {
attribute = factory.createAttribute(request,
HttpHeaders.Names.CONTENT_LENGTH,
cleanString(contents[1]));
} catch (NullPointerException e) {
throw new ErrorDataDecoderException(e);
} catch (IllegalArgumentException e) {
throw new ErrorDataDecoderException(e);
}
currentFieldAttributes.put(HttpHeaders.Names.CONTENT_LENGTH,
attribute);
} else if (contents[0].equalsIgnoreCase(HttpHeaders.Names.CONTENT_TYPE)) {
// Take care of possible "multipart/mixed"
if (contents[1].equalsIgnoreCase(HttpPostBodyUtil.MULTIPART_MIXED)) {
if (currentStatus == MultiPartStatus.DISPOSITION) {
String[] values = contents[2].split("=");
multipartMixedBoundary = "--" + values[1];
currentStatus = MultiPartStatus.MIXEDDELIMITER;
return decodeMultipart(MultiPartStatus.MIXEDDELIMITER);
} else {
throw new ErrorDataDecoderException(
"Mixed Multipart found in a previous Mixed Multipart");
}
} else {
for (int i = 1; i < contents.length; i ++) {
if (contents[i].toLowerCase().startsWith(
HttpHeaders.Values.CHARSET)) {
String[] values = contents[i].split("=");
Attribute attribute;
try {
attribute = factory.createAttribute(request,
HttpHeaders.Values.CHARSET,
cleanString(values[1]));
} catch (NullPointerException e) {
throw new ErrorDataDecoderException(e);
} catch (IllegalArgumentException e) {
throw new ErrorDataDecoderException(e);
}
currentFieldAttributes.put(HttpHeaders.Values.CHARSET,
attribute);
} else {
Attribute attribute;
try {
attribute = factory.createAttribute(request,
contents[0].trim(),
decodeAttribute(cleanString(contents[i]), charset));
} catch (NullPointerException e) {
throw new ErrorDataDecoderException(e);
} catch (IllegalArgumentException e) {
throw new ErrorDataDecoderException(e);
}
currentFieldAttributes.put(attribute.getName(),
attribute);
}
}
}
} else {
throw new ErrorDataDecoderException("Unknown Params: " +
newline);
}
}
// Is it a FileUpload
Attribute filenameAttribute = currentFieldAttributes
.get(HttpPostBodyUtil.FILENAME);
if (currentStatus == MultiPartStatus.DISPOSITION) {
if (filenameAttribute != null) {
// FileUpload
currentStatus = MultiPartStatus.FILEUPLOAD;
// do not change the buffer position
return decodeMultipart(MultiPartStatus.FILEUPLOAD);
} else {
// Field
currentStatus = MultiPartStatus.FIELD;
// do not change the buffer position
return decodeMultipart(MultiPartStatus.FIELD);
}
} else {
if (filenameAttribute != null) {
// FileUpload
currentStatus = MultiPartStatus.MIXEDFILEUPLOAD;
// do not change the buffer position
return decodeMultipart(MultiPartStatus.MIXEDFILEUPLOAD);
} else {
// Field is not supported in MIXED mode
throw new ErrorDataDecoderException("Filename not found");
}
}
}
/**
* Get the FileUpload (new one or current one)
* @param delimiter the delimiter to use
* @return the InterfaceHttpData if any
* @throws ErrorDataDecoderException
*/
private InterfaceHttpData getFileUpload(String delimiter)
throws ErrorDataDecoderException {
// eventually restart from existing FileUpload
// Now get value according to Content-Type and Charset
Attribute encoding = currentFieldAttributes
.get(HttpHeaders.Names.CONTENT_TRANSFER_ENCODING);
Charset localCharset = charset;
// Default
TransferEncodingMechanism mechanism = TransferEncodingMechanism.BIT7;
if (encoding != null) {
String code;
try {
code = encoding.getValue().toLowerCase();
} catch (IOException e) {
throw new ErrorDataDecoderException(e);
}
if (code.equals(HttpPostBodyUtil.TransferEncodingMechanism.BIT7.value)) {
localCharset = HttpPostBodyUtil.US_ASCII;
} else if (code.equals(HttpPostBodyUtil.TransferEncodingMechanism.BIT8.value)) {
localCharset = HttpPostBodyUtil.ISO_8859_1;
mechanism = TransferEncodingMechanism.BIT8;
} else if (code
.equals(HttpPostBodyUtil.TransferEncodingMechanism.BINARY.value)) {
// no real charset, so let the default
mechanism = TransferEncodingMechanism.BINARY;
} else {
throw new ErrorDataDecoderException(
"TransferEncoding Unknown: " + code);
}
}
Attribute charsetAttribute = currentFieldAttributes
.get(HttpHeaders.Values.CHARSET);
if (charsetAttribute != null) {
try {
localCharset = Charset.forName(charsetAttribute.getValue());
} catch (IOException e) {
throw new ErrorDataDecoderException(e);
}
}
if (currentFileUpload == null) {
Attribute filenameAttribute = currentFieldAttributes
.get(HttpPostBodyUtil.FILENAME);
Attribute nameAttribute = currentFieldAttributes
.get(HttpPostBodyUtil.NAME);
Attribute contentTypeAttribute = currentFieldAttributes
.get(HttpHeaders.Names.CONTENT_TYPE);
if (contentTypeAttribute == null) {
throw new ErrorDataDecoderException(
"Content-Type is absent but required");
}
Attribute lengthAttribute = currentFieldAttributes
.get(HttpHeaders.Names.CONTENT_LENGTH);
long size;
try {
size = lengthAttribute != null? Long.parseLong(lengthAttribute
.getValue()) : 0L;
} catch (IOException e) {
throw new ErrorDataDecoderException(e);
} catch (NumberFormatException e) {
size = 0;
}
try {
currentFileUpload = factory.createFileUpload(
request,
nameAttribute.getValue(), filenameAttribute.getValue(),
contentTypeAttribute.getValue(), mechanism.value,
localCharset, size);
} catch (NullPointerException e) {
throw new ErrorDataDecoderException(e);
} catch (IllegalArgumentException e) {
throw new ErrorDataDecoderException(e);
} catch (IOException e) {
throw new ErrorDataDecoderException(e);
}
}
// load data as much as possible
try {
readFileUploadByteMultipart(delimiter);
} catch (NotEnoughDataDecoderException e) {
// do not change the buffer position
// since some can be already saved into FileUpload
// So do not change the currentStatus
return null;
}
if (currentFileUpload.isCompleted()) {
// ready to load the next one
if (currentStatus == MultiPartStatus.FILEUPLOAD) {
currentStatus = MultiPartStatus.HEADERDELIMITER;
currentFieldAttributes = null;
} else {
currentStatus = MultiPartStatus.MIXEDDELIMITER;
cleanMixedAttributes();
}
FileUpload fileUpload = currentFileUpload;
currentFileUpload = null;
return fileUpload;
}
// do not change the buffer position
// since some can be already saved into FileUpload
// So do not change the currentStatus
return null;
}
/**
* Clean all HttpDatas (on Disk) for the current request.
*/
public void cleanFiles() {
factory.cleanRequestHttpDatas(request);
}
/**
* Remove the given FileUpload from the list of FileUploads to clean
*/
public void removeHttpDataFromClean(InterfaceHttpData data) {
factory.removeHttpDataFromClean(request, data);
}
/**
* Remove all Attributes that should be cleaned between two FileUpload in Mixed mode
*/
private void cleanMixedAttributes() {
currentFieldAttributes.remove(HttpHeaders.Values.CHARSET);
currentFieldAttributes.remove(HttpHeaders.Names.CONTENT_LENGTH);
currentFieldAttributes.remove(HttpHeaders.Names.CONTENT_TRANSFER_ENCODING);
currentFieldAttributes.remove(HttpHeaders.Names.CONTENT_TYPE);
currentFieldAttributes.remove(HttpPostBodyUtil.FILENAME);
}
/**
* Read one line up to the CRLF or LF
* @return the String from one line
* @throws NotEnoughDataDecoderException Need more chunks and
* reset the readerInder to the previous value
*/
private String readLine() throws NotEnoughDataDecoderException {
int readerIndex = undecodedChunk.readerIndex();
try {
StringBuilder sb = new StringBuilder(64);
while (undecodedChunk.readable()) {
byte nextByte = undecodedChunk.readByte();
if (nextByte == HttpCodecUtil.CR) {
nextByte = undecodedChunk.readByte();
if (nextByte == HttpCodecUtil.LF) {
return sb.toString();
}
} else if (nextByte == HttpCodecUtil.LF) {
return sb.toString();
} else {
sb.append((char) nextByte);
}
}
} catch (IndexOutOfBoundsException e) {
undecodedChunk.readerIndex(readerIndex);
throw new NotEnoughDataDecoderException(e);
}
undecodedChunk.readerIndex(readerIndex);
throw new NotEnoughDataDecoderException();
}
/**
* Read a FileUpload data as Byte (Binary) and add the bytes directly to the
* FileUpload. If the delimiter is found, the FileUpload is completed.
* @param delimiter
* @throws NotEnoughDataDecoderException Need more chunks but
* do not reset the readerInder since some values will be already added to the FileOutput
* @throws ErrorDataDecoderException write IO error occurs with the FileUpload
*/
private void readFileUploadByteMultipart(String delimiter)
throws NotEnoughDataDecoderException, ErrorDataDecoderException {
int readerIndex = undecodedChunk.readerIndex();
// found the decoder limit
boolean newLine = true;
int index = 0;
int lastPosition = undecodedChunk.readerIndex();
boolean found = false;
while (undecodedChunk.readable()) {
byte nextByte = undecodedChunk.readByte();
if (newLine) {
// Check the delimiter
if (nextByte == delimiter.codePointAt(index)) {
index ++;
if (delimiter.length() == index) {
found = true;
break;
}
continue;
} else {
newLine = false;
index = 0;
// continue until end of line
if (nextByte == HttpCodecUtil.CR) {
if (undecodedChunk.readable()) {
nextByte = undecodedChunk.readByte();
if (nextByte == HttpCodecUtil.LF) {
newLine = true;
index = 0;
lastPosition = undecodedChunk.readerIndex() - 2;
}
}
} else if (nextByte == HttpCodecUtil.LF) {
newLine = true;
index = 0;
lastPosition = undecodedChunk.readerIndex() - 1;
} else {
// save last valid position
lastPosition = undecodedChunk.readerIndex();
}
}
} else {
// continue until end of line
if (nextByte == HttpCodecUtil.CR) {
if (undecodedChunk.readable()) {
nextByte = undecodedChunk.readByte();
if (nextByte == HttpCodecUtil.LF) {
newLine = true;
index = 0;
lastPosition = undecodedChunk.readerIndex() - 2;
}
}
} else if (nextByte == HttpCodecUtil.LF) {
newLine = true;
index = 0;
lastPosition = undecodedChunk.readerIndex() - 1;
} else {
// save last valid position
lastPosition = undecodedChunk.readerIndex();
}
}
}
ChannelBuffer buffer = undecodedChunk.slice(readerIndex, lastPosition -
readerIndex);
if (found) {
// found so lastPosition is correct and final
try {
currentFileUpload.addContent(buffer, true);
// just before the CRLF and delimiter
undecodedChunk.readerIndex(lastPosition);
} catch (IOException e) {
throw new ErrorDataDecoderException(e);
}
} else {
// possibly the delimiter is partially found but still the last position is OK
try {
currentFileUpload.addContent(buffer, false);
// last valid char (not CR, not LF, not beginning of delimiter)
undecodedChunk.readerIndex(lastPosition);
throw new NotEnoughDataDecoderException();
} catch (IOException e) {
throw new ErrorDataDecoderException(e);
}
}
}
/**
* Load the field value from a Multipart request
* @throws NotEnoughDataDecoderException Need more chunks
* @throws ErrorDataDecoderException
*/
private void loadFieldMultipart(String delimiter)
throws NotEnoughDataDecoderException, ErrorDataDecoderException {
int readerIndex = undecodedChunk.readerIndex();
try {
// found the decoder limit
boolean newLine = true;
int index = 0;
int lastPosition = undecodedChunk.readerIndex();
boolean found = false;
while (undecodedChunk.readable()) {
byte nextByte = undecodedChunk.readByte();
if (newLine) {
// Check the delimiter
if (nextByte == delimiter.codePointAt(index)) {
index ++;
if (delimiter.length() == index) {
found = true;
break;
}
continue;
} else {
newLine = false;
index = 0;
// continue until end of line
if (nextByte == HttpCodecUtil.CR) {
if (undecodedChunk.readable()) {
nextByte = undecodedChunk.readByte();
if (nextByte == HttpCodecUtil.LF) {
newLine = true;
index = 0;
lastPosition = undecodedChunk.readerIndex() - 2;
}
}
} else if (nextByte == HttpCodecUtil.LF) {
newLine = true;
index = 0;
lastPosition = undecodedChunk.readerIndex() - 1;
} else {
lastPosition = undecodedChunk.readerIndex();
}
}
} else {
// continue until end of line
if (nextByte == HttpCodecUtil.CR) {
if (undecodedChunk.readable()) {
nextByte = undecodedChunk.readByte();
if (nextByte == HttpCodecUtil.LF) {
newLine = true;
index = 0;
lastPosition = undecodedChunk.readerIndex() - 2;
}
}
} else if (nextByte == HttpCodecUtil.LF) {
newLine = true;
index = 0;
lastPosition = undecodedChunk.readerIndex() - 1;
} else {
lastPosition = undecodedChunk.readerIndex();
}
}
}
if (found) {
// found so lastPosition is correct
// but position is just after the delimiter (either close delimiter or simple one)
// so go back of delimiter size
try {
currentAttribute.addContent(
undecodedChunk.slice(readerIndex, lastPosition - readerIndex),
true);
} catch (IOException e) {
throw new ErrorDataDecoderException(e);
}
undecodedChunk.readerIndex(lastPosition);
} else {
try {
currentAttribute.addContent(
undecodedChunk.slice(readerIndex, lastPosition - readerIndex),
false);
} catch (IOException e) {
throw new ErrorDataDecoderException(e);
}
undecodedChunk.readerIndex(lastPosition);
throw new NotEnoughDataDecoderException();
}
} catch (IndexOutOfBoundsException e) {
undecodedChunk.readerIndex(readerIndex);
throw new NotEnoughDataDecoderException(e);
}
}
/**
* Clean the String from any unallowed character
* @return the cleaned String
*/
private String cleanString(String field) {
StringBuilder sb = new StringBuilder(field.length());
int i = 0;
for (i = 0; i < field.length(); i ++) {
char nextChar = field.charAt(i);
if (nextChar == HttpCodecUtil.COLON) {
sb.append(HttpCodecUtil.SP);
} else if (nextChar == HttpCodecUtil.COMMA) {
sb.append(HttpCodecUtil.SP);
} else if (nextChar == HttpCodecUtil.EQUALS) {
sb.append(HttpCodecUtil.SP);
} else if (nextChar == HttpCodecUtil.SEMICOLON) {
sb.append(HttpCodecUtil.SP);
} else if (nextChar == HttpCodecUtil.HT) {
sb.append(HttpCodecUtil.SP);
} else if (nextChar == HttpCodecUtil.DOUBLE_QUOTE) {
// nothing added, just removes it
} else {
sb.append(nextChar);
}
}
return sb.toString().trim();
}
/**
* Skip one empty line
* @return True if one empty line was skipped
*/
private boolean skipOneLine() {
if (!undecodedChunk.readable()) {
return false;
}
byte nextByte = undecodedChunk.readByte();
if (nextByte == HttpCodecUtil.CR) {
if (!undecodedChunk.readable()) {
undecodedChunk.readerIndex(undecodedChunk.readerIndex() - 1);
return false;
}
nextByte = undecodedChunk.readByte();
if (nextByte == HttpCodecUtil.LF) {
return true;
}
undecodedChunk.readerIndex(undecodedChunk.readerIndex() - 2);
return false;
} else if (nextByte == HttpCodecUtil.LF) {
return true;
}
undecodedChunk.readerIndex(undecodedChunk.readerIndex() - 1);
return false;
}
/**
* Split the very first line (Content-Type value) in 2 Strings
* @param sb
* @return the array of 2 Strings
*/
private String[] splitHeaderContentType(String sb) {
int size = sb.length();
int aStart;
int aEnd;
int bStart;
int bEnd;
aStart = HttpPostBodyUtil.findNonWhitespace(sb, 0);
aEnd = HttpPostBodyUtil.findWhitespace(sb, aStart);
if (aEnd >= size) {
return new String[] { sb, "" };
}
if (sb.charAt(aEnd) == ';') {
aEnd --;
}
bStart = HttpPostBodyUtil.findNonWhitespace(sb, aEnd);
bEnd = HttpPostBodyUtil.findEndOfString(sb);
return new String[] { sb.substring(aStart, aEnd),
sb.substring(bStart, bEnd) };
}
/**
* Split one header in Multipart
* @param sb
* @return an array of String where rank 0 is the name of the header, follows by several
* values that were separated by ';' or ','
*/
private String[] splitMultipartHeader(String sb) {
ArrayList<String> headers = new ArrayList<String>(1);
int nameStart;
int nameEnd;
int colonEnd;
int valueStart;
int valueEnd;
nameStart = HttpPostBodyUtil.findNonWhitespace(sb, 0);
for (nameEnd = nameStart; nameEnd < sb.length(); nameEnd ++) {
char ch = sb.charAt(nameEnd);
if (ch == ':' || Character.isWhitespace(ch)) {
break;
}
}
for (colonEnd = nameEnd; colonEnd < sb.length(); colonEnd ++) {
if (sb.charAt(colonEnd) == ':') {
colonEnd ++;
break;
}
}
valueStart = HttpPostBodyUtil.findNonWhitespace(sb, colonEnd);
valueEnd = HttpPostBodyUtil.findEndOfString(sb);
headers.add(sb.substring(nameStart, nameEnd));
String svalue = sb.substring(valueStart, valueEnd);
String[] values = null;
if (svalue.indexOf(";") >= 0) {
values = svalue.split(";");
} else {
values = svalue.split(",");
}
for (String value: values) {
headers.add(value.trim());
}
String[] array = new String[headers.size()];
for (int i = 0; i < headers.size(); i ++) {
array[i] = headers.get(i);
}
return array;
}
/**
* Exception when try reading data from request in chunked format, and not enough
* data are available (need more chunks)
*/
public static class NotEnoughDataDecoderException extends Exception {
/**
*/
private static final long serialVersionUID = -7846841864603865638L;
/**
*/
public NotEnoughDataDecoderException() {
}
/**
* @param arg0
*/
public NotEnoughDataDecoderException(String arg0) {
super(arg0);
}
/**
* @param arg0
*/
public NotEnoughDataDecoderException(Throwable arg0) {
super(arg0);
}
/**
* @param arg0
* @param arg1
*/
public NotEnoughDataDecoderException(String arg0, Throwable arg1) {
super(arg0, arg1);
}
}
/**
* Exception when the body is fully decoded, even if there is still data
*/
public static class EndOfDataDecoderException extends Exception {
/**
*/
private static final long serialVersionUID = 1336267941020800769L;
}
/**
* Exception when an error occurs while decoding
*/
public static class ErrorDataDecoderException extends Exception {
/**
*/
private static final long serialVersionUID = 5020247425493164465L;
/**
*/
public ErrorDataDecoderException() {
}
/**
* @param arg0
*/
public ErrorDataDecoderException(String arg0) {
super(arg0);
}
/**
* @param arg0
*/
public ErrorDataDecoderException(Throwable arg0) {
super(arg0);
}
/**
* @param arg0
* @param arg1
*/
public ErrorDataDecoderException(String arg0, Throwable arg1) {
super(arg0, arg1);
}
}
/**
* Exception when an unappropriated method was called on a request
*/
public static class IncompatibleDataDecoderException extends Exception {
/**
*/
private static final long serialVersionUID = -953268047926250267L;
/**
*/
public IncompatibleDataDecoderException() {
}
/**
* @param arg0
*/
public IncompatibleDataDecoderException(String arg0) {
super(arg0);
}
/**
* @param arg0
*/
public IncompatibleDataDecoderException(Throwable arg0) {
super(arg0);
}
/**
* @param arg0
* @param arg1
*/
public IncompatibleDataDecoderException(String arg0, Throwable arg1) {
super(arg0, arg1);
}
}
}
|
Optimize Buffer access while decoding by going through backend array when possible (divide by almost 2 the time spent in decoding)
|
codec-http/src/main/java/io/netty/handler/codec/http/HttpPostRequestDecoder.java
|
Optimize Buffer access while decoding by going through backend array when possible (divide by almost 2 the time spent in decoding)
|
<ide><path>odec-http/src/main/java/io/netty/handler/codec/http/HttpPostRequestDecoder.java
<ide>
<ide> import io.netty.buffer.ChannelBuffer;
<ide> import io.netty.buffer.ChannelBuffers;
<add>import org.jboss.netty.handler.codec.http2.HttpPostBodyUtil.SeekAheadNoBackArray;
<add>import org.jboss.netty.handler.codec.http2.HttpPostBodyUtil.SeekAheadOptimize;
<ide> import io.netty.handler.codec.http.HttpPostBodyUtil.TransferEncodingMechanism;
<ide>
<ide> /**
<ide> * @throws ErrorDataDecoderException if there is a problem with the charset decoding or
<ide> * other errors
<ide> */
<del> private void parseBodyAttributes() throws ErrorDataDecoderException {
<add> private void parseBodyAttributesStandard() throws ErrorDataDecoderException {
<ide> int firstpos = undecodedChunk.readerIndex();
<ide> int currentpos = firstpos;
<ide> int equalpos = firstpos;
<ide> }
<ide> }
<ide>
<add> /**
<add> * This method fill the map and list with as much Attribute as possible from Body in
<add> * not Multipart mode.
<add> *
<add> * @throws ErrorDataDecoderException if there is a problem with the charset decoding or
<add> * other errors
<add> */
<add> private void parseBodyAttributes() throws ErrorDataDecoderException {
<add> SeekAheadOptimize sao = null;
<add> try {
<add> sao = new SeekAheadOptimize(undecodedChunk);
<add> } catch (SeekAheadNoBackArray e1) {
<add> parseBodyAttributesStandard();
<add> return;
<add> }
<add> int firstpos = undecodedChunk.readerIndex();
<add> int currentpos = firstpos;
<add> int equalpos = firstpos;
<add> int ampersandpos = firstpos;
<add> if (currentStatus == MultiPartStatus.NOTSTARTED) {
<add> currentStatus = MultiPartStatus.DISPOSITION;
<add> }
<add> boolean contRead = true;
<add> try {
<add> loop:
<add> while (sao.pos < sao.limit) {
<add> char read = (char) (sao.bytes[sao.pos ++] & 0xFF);
<add> currentpos ++;
<add> switch (currentStatus) {
<add> case DISPOSITION:// search '='
<add> if (read == '=') {
<add> currentStatus = MultiPartStatus.FIELD;
<add> equalpos = currentpos - 1;
<add> String key = decodeAttribute(
<add> undecodedChunk.toString(firstpos, equalpos - firstpos, charset),
<add> charset);
<add> currentAttribute = factory.createAttribute(request, key);
<add> firstpos = currentpos;
<add> } else if (read == '&') { // special empty FIELD
<add> currentStatus = MultiPartStatus.DISPOSITION;
<add> ampersandpos = currentpos - 1;
<add> String key = decodeAttribute(undecodedChunk.toString(firstpos, ampersandpos - firstpos, charset), charset);
<add> currentAttribute = factory.createAttribute(request, key);
<add> currentAttribute.setValue(""); // empty
<add> addHttpData(currentAttribute);
<add> currentAttribute = null;
<add> firstpos = currentpos;
<add> contRead = true;
<add> }
<add> break;
<add> case FIELD:// search '&' or end of line
<add> if (read == '&') {
<add> currentStatus = MultiPartStatus.DISPOSITION;
<add> ampersandpos = currentpos - 1;
<add> setFinalBuffer(undecodedChunk.slice(firstpos, ampersandpos - firstpos));
<add> firstpos = currentpos;
<add> contRead = true;
<add> } else if (read == HttpCodecUtil.CR) {
<add> if (sao.pos < sao.limit) {
<add> read = (char) (sao.bytes[sao.pos ++] & 0xFF);
<add> currentpos++;
<add> if (read == HttpCodecUtil.LF) {
<add> currentStatus = MultiPartStatus.PREEPILOGUE;
<add> ampersandpos = currentpos - 2;
<add> sao.setReadPosition(0);
<add> setFinalBuffer(
<add> undecodedChunk.slice(firstpos, ampersandpos - firstpos));
<add> firstpos = currentpos;
<add> contRead = false;
<add> break loop;
<add> } else {
<add> // Error
<add> sao.setReadPosition(0);
<add> contRead = false;
<add> throw new ErrorDataDecoderException("Bad end of line");
<add> }
<add> } else {
<add> if (sao.limit > 0) {
<add> currentpos --;
<add> }
<add> }
<add> } else if (read == HttpCodecUtil.LF) {
<add> currentStatus = MultiPartStatus.PREEPILOGUE;
<add> ampersandpos = currentpos - 1;
<add> sao.setReadPosition(0);
<add> setFinalBuffer(
<add> undecodedChunk.slice(firstpos, ampersandpos - firstpos));
<add> firstpos = currentpos;
<add> contRead = false;
<add> break loop;
<add> }
<add> break;
<add> default:
<add> // just stop
<add> sao.setReadPosition(0);
<add> contRead = false;
<add> break loop;
<add> }
<add> }
<add> if (isLastChunk && currentAttribute != null) {
<add> // special case
<add> ampersandpos = currentpos;
<add> if (ampersandpos > firstpos) {
<add> setFinalBuffer(
<add> undecodedChunk.slice(firstpos, ampersandpos - firstpos));
<add> } else if (! currentAttribute.isCompleted()) {
<add> setFinalBuffer(ChannelBuffers.EMPTY_BUFFER);
<add> }
<add> firstpos = currentpos;
<add> currentStatus = MultiPartStatus.EPILOGUE;
<add> return;
<add> }
<add> if (contRead && currentAttribute != null) {
<add> // reset index except if to continue in case of FIELD status
<add> if (currentStatus == MultiPartStatus.FIELD) {
<add> currentAttribute.addContent(
<add> undecodedChunk.slice(firstpos, currentpos - firstpos),
<add> false);
<add> firstpos = currentpos;
<add> }
<add> undecodedChunk.readerIndex(firstpos);
<add> } else {
<add> // end of line so keep index
<add> }
<add> } catch (ErrorDataDecoderException e) {
<add> // error while decoding
<add> undecodedChunk.readerIndex(firstpos);
<add> throw e;
<add> } catch (IOException e) {
<add> // error while decoding
<add> undecodedChunk.readerIndex(firstpos);
<add> throw new ErrorDataDecoderException(e);
<add> }
<add> }
<add>
<ide> private void setFinalBuffer(ChannelBuffer buffer) throws ErrorDataDecoderException, IOException {
<ide> currentAttribute.addContent(buffer, true);
<ide> String value = decodeAttribute(
<ide> }
<ide> }
<ide>
<add>
<add> /**
<add> * Skip control Characters
<add> */
<add> void skipControlCharacters() {
<add> SeekAheadOptimize sao = null;
<add> try {
<add> sao = new SeekAheadOptimize(undecodedChunk);
<add> } catch (SeekAheadNoBackArray e) {
<add> skipControlCharactersStandard(undecodedChunk);
<add> return;
<add> }
<add>
<add> while (sao.pos < sao.limit) {
<add> char c = (char) sao.bytes[sao.pos ++];
<add> if (!Character.isISOControl(c) && !Character.isWhitespace(c)) {
<add> sao.setReadPosition(1);
<add> return;
<add> }
<add> }
<add> sao.setReadPosition(0);
<add> }
<add> static void skipControlCharactersStandard(ChannelBuffer buffer) {
<add> for (;;) {
<add> char c = (char) buffer.readUnsignedByte();
<add> if (!Character.isISOControl(c) && !Character.isWhitespace(c)) {
<add> buffer.readerIndex(buffer.readerIndex() - 1);
<add> break;
<add> }
<add> }
<add> }
<add>
<ide> /**
<ide> * Find the next Multipart Delimiter
<ide> * @param delimiter delimiter to find
<ide> throws ErrorDataDecoderException {
<ide> // --AaB03x or --AaB03x--
<ide> int readerIndex = undecodedChunk.readerIndex();
<del> HttpPostBodyUtil.skipControlCharacters(undecodedChunk);
<add> skipControlCharacters(undecodedChunk);
<ide> skipOneLine();
<ide> String newline;
<ide> try {
<ide> }
<ide> // read many lines until empty line with newline found! Store all data
<ide> while (!skipOneLine()) {
<del> HttpPostBodyUtil.skipControlCharacters(undecodedChunk);
<add> skipControlCharacters(undecodedChunk);
<ide> String newline;
<ide> try {
<ide> newline = readLine();
<ide> * @throws NotEnoughDataDecoderException Need more chunks and
<ide> * reset the readerInder to the previous value
<ide> */
<del> private String readLine() throws NotEnoughDataDecoderException {
<add> private String readLineStandard() throws NotEnoughDataDecoderException {
<ide> int readerIndex = undecodedChunk.readerIndex();
<ide> try {
<ide> StringBuilder sb = new StringBuilder(64);
<ide> }
<ide>
<ide> /**
<add> * Read one line up to the CRLF or LF
<add> * @return the String from one line
<add> * @throws NotEnoughDataDecoderException Need more chunks and
<add> * reset the readerInder to the previous value
<add> */
<add> private String readLine() throws NotEnoughDataDecoderException {
<add> SeekAheadOptimize sao = null;
<add> try {
<add> sao = new SeekAheadOptimize(undecodedChunk);
<add> } catch (SeekAheadNoBackArray e1) {
<add> return readLineStandard();
<add> }
<add> int readerIndex = undecodedChunk.readerIndex();
<add> try {
<add> StringBuilder sb = new StringBuilder(64);
<add> while (sao.pos < sao.limit) {
<add> byte nextByte = sao.bytes[sao.pos ++];
<add> if (nextByte == HttpCodecUtil.CR) {
<add> if (sao.pos < sao.limit) {
<add> nextByte = sao.bytes[sao.pos ++];
<add> if (nextByte == HttpCodecUtil.LF) {
<add> sao.setReadPosition(0);
<add> return sb.toString();
<add> }
<add> } else {
<add> sb.append((char) nextByte);
<add> }
<add> } else if (nextByte == HttpCodecUtil.LF) {
<add> sao.setReadPosition(0);
<add> return sb.toString();
<add> } else {
<add> sb.append((char) nextByte);
<add> }
<add> }
<add> } catch (IndexOutOfBoundsException e) {
<add> undecodedChunk.readerIndex(readerIndex);
<add> throw new NotEnoughDataDecoderException(e);
<add> }
<add> undecodedChunk.readerIndex(readerIndex);
<add> throw new NotEnoughDataDecoderException();
<add> }
<add>
<add> /**
<ide> * Read a FileUpload data as Byte (Binary) and add the bytes directly to the
<ide> * FileUpload. If the delimiter is found, the FileUpload is completed.
<ide> * @param delimiter
<ide> * do not reset the readerInder since some values will be already added to the FileOutput
<ide> * @throws ErrorDataDecoderException write IO error occurs with the FileUpload
<ide> */
<del> private void readFileUploadByteMultipart(String delimiter)
<add> private void readFileUploadByteMultipartStandard(String delimiter)
<ide> throws NotEnoughDataDecoderException, ErrorDataDecoderException {
<ide> int readerIndex = undecodedChunk.readerIndex();
<ide> // found the decoder limit
<ide> }
<ide>
<ide> /**
<add> * Read a FileUpload data as Byte (Binary) and add the bytes directly to the
<add> * FileUpload. If the delimiter is found, the FileUpload is completed.
<add> * @param delimiter
<add> * @throws NotEnoughDataDecoderException Need more chunks but
<add> * do not reset the readerInder since some values will be already added to the FileOutput
<add> * @throws ErrorDataDecoderException write IO error occurs with the FileUpload
<add> */
<add> private void readFileUploadByteMultipart(String delimiter)
<add> throws NotEnoughDataDecoderException, ErrorDataDecoderException {
<add> SeekAheadOptimize sao = null;
<add> try {
<add> sao = new SeekAheadOptimize(undecodedChunk);
<add> } catch (SeekAheadNoBackArray e1) {
<add> readFileUploadByteMultipartStandard(delimiter);
<add> return;
<add> }
<add> int readerIndex = undecodedChunk.readerIndex();
<add> // found the decoder limit
<add> boolean newLine = true;
<add> int index = 0;
<add> int lastPosition = undecodedChunk.readerIndex();
<add> boolean found = false;
<add>
<add> while (sao.pos < sao.limit) {
<add> byte nextByte = sao.bytes[sao.pos ++];
<add> if (newLine) {
<add> // Check the delimiter
<add> if (nextByte == delimiter.codePointAt(index)) {
<add> index ++;
<add> if (delimiter.length() == index) {
<add> found = true;
<add> sao.setReadPosition(0);
<add> break;
<add> }
<add> continue;
<add> } else {
<add> newLine = false;
<add> index = 0;
<add> // continue until end of line
<add> if (nextByte == HttpCodecUtil.CR) {
<add> if (sao.pos < sao.limit) {
<add> nextByte = sao.bytes[sao.pos ++];
<add> if (nextByte == HttpCodecUtil.LF) {
<add> newLine = true;
<add> index = 0;
<add> sao.setReadPosition(0);
<add> lastPosition = undecodedChunk.readerIndex() - 2;
<add> }
<add> } else {
<add> // save last valid position
<add> sao.setReadPosition(0);
<add> lastPosition = undecodedChunk.readerIndex();
<add> }
<add> } else if (nextByte == HttpCodecUtil.LF) {
<add> newLine = true;
<add> index = 0;
<add> sao.setReadPosition(0);
<add> lastPosition = undecodedChunk.readerIndex() - 1;
<add> } else {
<add> // save last valid position
<add> sao.setReadPosition(0);
<add> lastPosition = undecodedChunk.readerIndex();
<add> }
<add> }
<add> } else {
<add> // continue until end of line
<add> if (nextByte == HttpCodecUtil.CR) {
<add> if (sao.pos < sao.limit) {
<add> nextByte = sao.bytes[sao.pos ++];
<add> if (nextByte == HttpCodecUtil.LF) {
<add> newLine = true;
<add> index = 0;
<add> sao.setReadPosition(0);
<add> lastPosition = undecodedChunk.readerIndex() - 2;
<add> }
<add> } else {
<add> // save last valid position
<add> sao.setReadPosition(0);
<add> lastPosition = undecodedChunk.readerIndex();
<add> }
<add> } else if (nextByte == HttpCodecUtil.LF) {
<add> newLine = true;
<add> index = 0;
<add> sao.setReadPosition(0);
<add> lastPosition = undecodedChunk.readerIndex() - 1;
<add> } else {
<add> // save last valid position
<add> sao.setReadPosition(0);
<add> lastPosition = undecodedChunk.readerIndex();
<add> }
<add> }
<add> }
<add> ChannelBuffer buffer = undecodedChunk.slice(readerIndex, lastPosition - readerIndex);
<add> if (found) {
<add> // found so lastPosition is correct and final
<add> try {
<add> currentFileUpload.addContent(buffer, true);
<add> // just before the CRLF and delimiter
<add> undecodedChunk.readerIndex(lastPosition);
<add> } catch (IOException e) {
<add> throw new ErrorDataDecoderException(e);
<add> }
<add> } else {
<add> // possibly the delimiter is partially found but still the last position is OK
<add> try {
<add> currentFileUpload.addContent(buffer, false);
<add> // last valid char (not CR, not LF, not beginning of delimiter)
<add> undecodedChunk.readerIndex(lastPosition);
<add> throw new NotEnoughDataDecoderException();
<add> } catch (IOException e) {
<add> throw new ErrorDataDecoderException(e);
<add> }
<add> }
<add> }
<add>
<add> /**
<ide> * Load the field value from a Multipart request
<ide> * @throws NotEnoughDataDecoderException Need more chunks
<ide> * @throws ErrorDataDecoderException
<ide> */
<del> private void loadFieldMultipart(String delimiter)
<add> private void loadFieldMultipartStandard(String delimiter)
<ide> throws NotEnoughDataDecoderException, ErrorDataDecoderException {
<ide> int readerIndex = undecodedChunk.readerIndex();
<ide> try {
<ide> }
<ide>
<ide> /**
<add> * Load the field value from a Multipart request
<add> * @throws NotEnoughDataDecoderException Need more chunks
<add> * @throws ErrorDataDecoderException
<add> */
<add> private void loadFieldMultipart(String delimiter)
<add> throws NotEnoughDataDecoderException, ErrorDataDecoderException {
<add> SeekAheadOptimize sao = null;
<add> try {
<add> sao = new SeekAheadOptimize(undecodedChunk);
<add> } catch (SeekAheadNoBackArray e1) {
<add> loadFieldMultipartStandard(delimiter);
<add> return;
<add> }
<add> int readerIndex = undecodedChunk.readerIndex();
<add> try {
<add> // found the decoder limit
<add> boolean newLine = true;
<add> int index = 0;
<add> int lastPosition = undecodedChunk.readerIndex();
<add> boolean found = false;
<add>
<add> while (sao.pos < sao.limit) {
<add> byte nextByte = sao.bytes[sao.pos ++];
<add> if (newLine) {
<add> // Check the delimiter
<add> if (nextByte == delimiter.codePointAt(index)) {
<add> index ++;
<add> if (delimiter.length() == index) {
<add> found = true;
<add> sao.setReadPosition(0);
<add> break;
<add> }
<add> continue;
<add> } else {
<add> newLine = false;
<add> index = 0;
<add> // continue until end of line
<add> if (nextByte == HttpCodecUtil.CR) {
<add> if (sao.pos < sao.limit) {
<add> nextByte = sao.bytes[sao.pos ++];
<add> if (nextByte == HttpCodecUtil.LF) {
<add> newLine = true;
<add> index = 0;
<add> sao.setReadPosition(0);
<add> lastPosition = undecodedChunk.readerIndex() - 2;
<add> }
<add> } else {
<add> sao.setReadPosition(0);
<add> lastPosition = undecodedChunk.readerIndex();
<add> }
<add> } else if (nextByte == HttpCodecUtil.LF) {
<add> newLine = true;
<add> index = 0;
<add> sao.setReadPosition(0);
<add> lastPosition = undecodedChunk.readerIndex() - 1;
<add> } else {
<add> sao.setReadPosition(0);
<add> lastPosition = undecodedChunk.readerIndex();
<add> }
<add> }
<add> } else {
<add> // continue until end of line
<add> if (nextByte == HttpCodecUtil.CR) {
<add> if (sao.pos < sao.limit) {
<add> nextByte = sao.bytes[sao.pos ++];
<add> if (nextByte == HttpCodecUtil.LF) {
<add> newLine = true;
<add> index = 0;
<add> sao.setReadPosition(0);
<add> lastPosition = undecodedChunk.readerIndex() - 2;
<add> }
<add> } else {
<add> sao.setReadPosition(0);
<add> lastPosition = undecodedChunk.readerIndex();
<add> }
<add> } else if (nextByte == HttpCodecUtil.LF) {
<add> newLine = true;
<add> index = 0;
<add> sao.setReadPosition(0);
<add> lastPosition = undecodedChunk.readerIndex() - 1;
<add> } else {
<add> sao.setReadPosition(0);
<add> lastPosition = undecodedChunk.readerIndex();
<add> }
<add> }
<add> }
<add> if (found) {
<add> // found so lastPosition is correct
<add> // but position is just after the delimiter (either close delimiter or simple one)
<add> // so go back of delimiter size
<add> try {
<add> currentAttribute.addContent(
<add> undecodedChunk.slice(readerIndex, lastPosition - readerIndex), true);
<add> } catch (IOException e) {
<add> throw new ErrorDataDecoderException(e);
<add> }
<add> undecodedChunk.readerIndex(lastPosition);
<add> } else {
<add> try {
<add> currentAttribute.addContent(
<add> undecodedChunk.slice(readerIndex, lastPosition - readerIndex), false);
<add> } catch (IOException e) {
<add> throw new ErrorDataDecoderException(e);
<add> }
<add> undecodedChunk.readerIndex(lastPosition);
<add> throw new NotEnoughDataDecoderException();
<add> }
<add> } catch (IndexOutOfBoundsException e) {
<add> undecodedChunk.readerIndex(readerIndex);
<add> throw new NotEnoughDataDecoderException(e);
<add> }
<add> }
<add>
<add> /**
<ide> * Clean the String from any unallowed character
<ide> * @return the cleaned String
<ide> */
|
|
Java
|
mit
|
bd208d0cd38afaa7b9fddeb5263d4367309d3c7e
| 0 |
rstueven/beerme-mobile-android
|
package com.beerme.android.database;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.Builder;
import android.util.Log;
import com.beerme.android.R;
import com.beerme.android.utils.ErrLog;
import com.beerme.android.utils.UrlToFileDownloader;
import com.beerme.android.utils.UrlToFileDownloader.UrlToFileDownloadListener;
import com.beerme.android.utils.Utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
public class TableDefs_6 extends TableDefs {
private SQLiteDatabase mDb = null;
private UpdateListener mListener = null;
public enum Table {
BREWERY("brewery"), BEER("beer"), STYLE("style");
private final String name;
Table(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public TableDefs_6() {
super();
}
// MEDIUM: AND0103: RFE: Localize style text
@Override
protected void initTableDefs() {
createStatements.put(TABLE_BREWERYNOTES, "CREATE TABLE IF NOT EXISTS "
+ TABLE_BREWERYNOTES + " (" + "_id INTEGER PRIMARY KEY, "
+ "breweryid INTEGER NOT NULL, "
+ "date TEXT DEFAULT CURRENT_DATE NOT NULL, " + "rating REAL, "
+ "notes TEXT NOT NULL " + ")");
indexStatements.put(TABLE_BREWERYNOTES,
new String[]{createIndex(TABLE_BREWERYNOTES, "breweryid"),
createIndex(TABLE_BREWERYNOTES, "date")});
createStatements.put(TABLE_BEERNOTES, "CREATE TABLE IF NOT EXISTS "
+ TABLE_BEERNOTES + " (" + "_id INTEGER PRIMARY KEY, "
+ "beerid INTEGER NOT NULL, " + "package TEXT DEFAULT '', "
+ "sampled TEXT DEFAULT CURRENT_DATE, "
+ "place TEXT DEFAULT '', " + "appscore REAL DEFAULT 0, "
+ "appearance TEXT DEFAULT '', " + "aroscore REAL DEFAULT 0, "
+ "aroma TEXT DEFAULT '', " + "mouscore REAL DEFAULT 0, "
+ "mouthfeel TEXT DEFAULT '', " + "ovrscore REAL DEFAULT 0, "
+ "notes TEXT DEFAULT ''" + ")");
indexStatements.put(TABLE_BEERNOTES,
new String[]{createIndex(TABLE_BEERNOTES, "beerid"),
createIndex(TABLE_BEERNOTES, "sampled")});
createStatements.put(TABLE_BREWERY, "CREATE TABLE " + TABLE_BREWERY
+ " (" + "_id INTEGER PRIMARY KEY, " + "name TEXT NOT NULL, "
+ "address TEXT NOT NULL, " + "latitude REAL NOT NULL, "
+ "longitude REAL NOT NULL, " + "status INTEGER NOT NULL, "
+ "hours TEXT, " + "phone TEXT, " + "web TEXT, "
+ "services INTEGER NOT NULL DEFAULT 0, " + "image TEXT, "
+ "updated TEXT NOT NULL DEFAULT CURRENT_DATE" + ")");
indexStatements.put(
TABLE_BREWERY,
new String[]{createIndex(TABLE_BREWERY, "name"),
createIndex(TABLE_BREWERY, "status"),
createIndex(TABLE_BREWERY, "latitude"),
createIndex(TABLE_BREWERY, "longitude"),
createIndex(TABLE_BREWERY, "updated")});
createStatements.put(TABLE_BEER, "CREATE TABLE " + TABLE_BEER + " ("
+ "_id INTEGER PRIMARY KEY, " + "breweryid INTEGER NOT NULL, "
+ "name TEXT NOT NULL, " + "style INTEGER, " + "abv REAL, "
+ "image TEXT, "
+ "updated TEXT NOT NULL DEFAULT CURRENT_DATE, "
+ "beermerating REAL" + ")");
indexStatements.put(
TABLE_BEER,
new String[]{createIndex(TABLE_BEER, "breweryid"),
createIndex(TABLE_BEER, "name"),
createIndex(TABLE_BEER, "updated")});
createStatements.put(TABLE_STYLE, "CREATE TABLE " + TABLE_STYLE + " ("
+ "_id INTEGER PRIMARY KEY, " + "name TEXT NOT NULL, "
+ "updated TEXT NOT NULL DEFAULT CURRENT_DATE" + ")");
indexStatements.put(TABLE_STYLE,
new String[]{createIndex(TABLE_STYLE, "updated")});
}
@Override
public void upgrade(SQLiteDatabase db) {
// Upgrade to v6
// add beer.beermerating
Log.i(Utils.APPTAG, "Upgrading database from 5 to 6");
mDb = db;
upgradeOldTables(db);
}
@Override
protected void upgradeOldTables(SQLiteDatabase db) {
mDb = db;
db.beginTransaction();
DbOpenHelper.setUpdating(mContext, true);
try {
// Deleting all the beer data and reloading it is more efficient
// than saving the data and downloading just the ratings.
db.execSQL("DROP TABLE IF EXISTS " + TABLE_BEER);
db.execSQL(createStatements.get(TABLE_BEER));
db.setTransactionSuccessful();
resetLastUpdate(mContext);
} catch (SQLException e) {
ErrLog.log(mContext, "onUpgrade(5 to 6)", e,
R.string.Database_upgrade_failed);
} finally {
db.endTransaction();
DbOpenHelper.setUpdating(mContext, false);
}
}
@Override
public void updateData(SQLiteDatabase db, UpdateListener listener) {
if (Utils.isOnline(mContext)) {
mDb = db;
mListener = listener;
String lastUpdate = getLastUpdate(mContext);
String now = DbOpenHelper.sqlDateFormat.format(Calendar.getInstance()
.getTime());
if (now.compareTo(lastUpdate) > 0) {
HandlerThread uiThread = new HandlerThread("UIHandler");
uiThread.start();
UpdateHandler handler = new UpdateHandler(uiThread.getLooper(),
this);
handler.sendEmptyMessage(UpdateHandler.BREWERY_START);
} else {
if (listener != null) {
listener.onDataUpdated();
}
}
// } else {
// ErrLog.log(mContext, "TableDefs_6.updateData()", null, R.string
// .Requires_network_access_to_update_database);
}
}
protected final static class UpdateHandler extends Handler {
public static final int BREWERY_START = 1;
public static final int BREWERY_END = 2;
public static final int BEER_START = 3;
public static final int BEER_END = 4;
public static final int STYLE_START = 5;
public static final int STYLE_END = 6;
private TableDefs_6 mRef;
private Context mContext;
private SQLiteDatabase mDb;
private UpdateListener mListener;
private boolean doneBrewery = false;
private boolean doneBeer = false;
private boolean doneStyle = false;
public UpdateHandler(Looper looper, TableDefs_6 obj) {
super(looper);
WeakReference<TableDefs_6> ref = new WeakReference<>(obj);
mRef = ref.get();
mContext = mRef.mContext;
mDb = mRef.mDb;
mListener = mRef.mListener;
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case BREWERY_START:
doneBrewery = false;
DbOpenHelper.setUpdating(mContext, true);
updateDataByTable(mContext, mDb, Table.BREWERY, this);
break;
case BREWERY_END:
doneBrewery = true;
DbOpenHelper.setUpdating(mContext, false);
sendEmptyMessage(BEER_START);
break;
case BEER_START:
doneBeer = false;
DbOpenHelper.setUpdating(mContext, true);
updateDataByTable(mContext, mDb, Table.BEER, this);
break;
case BEER_END:
doneBeer = true;
DbOpenHelper.setUpdating(mContext, false);
sendEmptyMessage(STYLE_START);
break;
case STYLE_START:
DbOpenHelper.setUpdating(mContext, true);
doneStyle = false;
updateDataByTable(mContext, mDb, Table.STYLE, this);
break;
case STYLE_END:
doneStyle = true;
DbOpenHelper.setUpdating(mContext, false);
break;
default:
super.handleMessage(msg);
}
if (doneBrewery && doneBeer && doneStyle) {
setLastUpdate(mContext);
if (mListener != null) {
mListener.onDataUpdated();
}
}
}
}
protected static final String URL_INIT_BREWERY_LIST = "breweryList.php";
protected static final String URL_INIT_BEER_LIST = "beerList.php";
protected static final String URL_INIT_STYLE_LIST = "styleList.php";
private static void updateDataByTable(Context context, SQLiteDatabase db,
Table table, UpdateHandler handler) {
int notification;
String urlInit;
switch (table) {
case BREWERY:
notification = TableDefs.NOTIFICATION_BREWERY_DOWNLOAD;
urlInit = URL_INIT_BREWERY_LIST;
break;
case BEER:
notification = TableDefs.NOTIFICATION_BEER_DOWNLOAD;
urlInit = URL_INIT_BEER_LIST;
break;
case STYLE:
notification = TableDefs.NOTIFICATION_STYLE_DOWNLOAD;
urlInit = URL_INIT_STYLE_LIST;
break;
default:
throw new IllegalArgumentException("invalid table: "
+ table.getName());
}
String tableName = table.getName();
String lastUpdate = getLastUpdateByTable(db, tableName);
startDownloadProgress(context, String.format(
context.getString(R.string.TABLE_data), tableName),
notification);
URL url;
try {
url = Utils.buildUrl(urlInit, new String[]{"t=" + lastUpdate});
UrlToFileDownloader.download(context, url,
TableDataListener.getInstance(context, db, table, handler));
} catch (MalformedURLException e) {
ErrLog.log(context, "updateDataByTable(" + tableName + ")", e,
"Malformed URL");
}
}
private static abstract class TableDataListener implements
UrlToFileDownloadListener {
private static final String INSERT_BREWERY = "INSERT OR REPLACE INTO brewery (_id, name, address, latitude, longitude, status, hours, phone, web, services, image, updated) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
private static final String INSERT_BEER = "INSERT OR REPLACE INTO beer (_id, breweryid, name, style, abv, image, updated, beermerating) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
private static final String INSERT_STYLE = "INSERT OR REPLACE INTO style (_id, name, updated) VALUES (?, ?, ?)";
private Context mContext = null;
private SQLiteDatabase mDb = null;
private Table mTable = null;
private String mName = null;
private UpdateHandler mHandler = null;
private NotificationManager mNotifyManager = null;
private String mInsertSql = null;
private int mNotificationDownload = -1;
private int mNotificationLoad = -1;
private int mNextStep = -1;
public TableDataListener(Context context, SQLiteDatabase db,
Table table, UpdateHandler handler) {
mContext = context;
mDb = db;
mTable = table;
mHandler = handler;
mNotifyManager = (NotificationManager) mContext
.getSystemService(Context.NOTIFICATION_SERVICE);
switch (table) {
case BREWERY:
mInsertSql = INSERT_BREWERY;
mNotificationDownload = TableDefs.NOTIFICATION_BREWERY_DOWNLOAD;
mNotificationLoad = TableDefs.NOTIFICATION_BREWERY_LOAD;
mNextStep = UpdateHandler.BREWERY_END;
break;
case BEER:
mInsertSql = INSERT_BEER;
mNotificationDownload = TableDefs.NOTIFICATION_BEER_DOWNLOAD;
mNotificationLoad = TableDefs.NOTIFICATION_BEER_LOAD;
mNextStep = UpdateHandler.BEER_END;
break;
case STYLE:
mInsertSql = INSERT_STYLE;
mNotificationDownload = TableDefs.NOTIFICATION_STYLE_DOWNLOAD;
mNotificationLoad = TableDefs.NOTIFICATION_STYLE_LOAD;
mNextStep = UpdateHandler.STYLE_END;
break;
default:
throw new IllegalArgumentException("invalid table: "
+ table.getName());
}
mName = mTable.getName();
}
public static TableDataListener getInstance(Context context,
SQLiteDatabase db, Table table, UpdateHandler handler) {
switch (table) {
case BREWERY:
return new TableDataListener_Brewery(context, db, table,
handler);
case BEER:
return new TableDataListener_Beer(context, db, table, handler);
case STYLE:
return new TableDataListener_Style(context, db, table, handler);
default:
throw new IllegalArgumentException("invalid table: "
+ table.getName());
}
}
@Override
public void onUrlToFileDownloaded(String fileName) {
mNotifyManager.cancel(mNotificationDownload);
if (fileName != null) {
if ("".equals(fileName)) {
throw new IllegalArgumentException(
"TableDataListener: empty fileName");
}
Builder builder = new NotificationCompat.Builder(mContext)
.setContentTitle(
String.format(
mContext.getString(R.string.TABLE_data),
mName))
.setContentText(
String.format(
mContext.getString(R.string.Loading_TABLE_data),
mName))
.setSmallIcon(R.drawable.ic_home)
.setProgress(0, 0, true)
.setContentIntent(
PendingIntent.getActivity(mContext, 0,
new Intent(), 0));
File file = new File(fileName);
long start;
SQLiteStatement insertStatement;
start = System.currentTimeMillis();
insertStatement = mDb.compileStatement(mInsertSql);
try {
mDb.beginTransaction();
parse(file, insertStatement, builder);
mDb.setTransactionSuccessful();
} catch (FileNotFoundException e) {
ErrLog.log(mContext,
"onUrlToFileDownloaded(" + fileName + "): FileNotFoundException: ",
e,
String.format(mContext.getString(R.string.Failed_to_update_TABLE_data), mName));
} catch (IOException e) {
ErrLog.log(mContext, "onUrlToFileDownloaded(" + fileName + "): IOException: ",
e,
String.format(mContext
.getString(R.string.Failed_to_update_TABLE_data), mName));
} finally {
if (mDb.inTransaction()) {
mDb.endTransaction();
}
file.delete();
Log.i(Utils.APPTAG, "onUrlToFileDownloaded(" + mName
+ ") elapsed: "
+ (System.currentTimeMillis() - start) + " ms");
mNotifyManager.cancel(mNotificationLoad);
mHandler.sendEmptyMessage(mNextStep);
}
}
}
public void parse(File file, SQLiteStatement insertStatement,
Builder builder) throws IOException {
String[] fields;
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = reader.readLine();
if (line != null) {
fields = line.split("\\|", -1);
int max = Integer.parseInt(fields[0]);
reader.close();
int onePercent = Math.max(max / 100, 1);
reader = new BufferedReader(new FileReader(file));
int id;
while ((line = reader.readLine()) != null) {
fields = line.split("\\|", -1);
id = Integer.parseInt(fields[0]);
if (id % onePercent == 0) {
builder.setProgress(max, max - id, false);
mNotifyManager.notify(mNotificationLoad,
builder.build());
}
parseFields(id, fields, insertStatement);
insertStatement.executeInsert();
}
reader.close();
}
}
public abstract void parseFields(int id, String[] fields,
SQLiteStatement insertStatement);
}
private static class TableDataListener_Brewery extends TableDataListener {
public TableDataListener_Brewery(Context context, SQLiteDatabase db,
Table table, UpdateHandler handler) {
super(context, db, table, handler);
}
@Override
public void parseFields(int id, String[] fields,
SQLiteStatement insertStatement) {
String name = fields[1];
String address = fields[2];
double latitude = Double.parseDouble(fields[3]);
double longitude = Double.parseDouble(fields[4]);
int status = Integer.parseInt(fields[5]);
int services = Integer.parseInt(fields[6]);
String updated = fields[7];
String phone = fields[8];
String hours = fields[9];
String web = fields[10];
String image = fields[11];
insertStatement.bindLong(1, id);
insertStatement.bindString(2, name);
insertStatement.bindString(3, address);
insertStatement.bindDouble(4, latitude);
insertStatement.bindDouble(5, longitude);
insertStatement.bindLong(6, status);
insertStatement.bindString(7, hours);
insertStatement.bindString(8, phone);
insertStatement.bindString(9, web);
insertStatement.bindLong(10, services);
insertStatement.bindString(11, image);
insertStatement.bindString(12, updated);
}
}
private static class TableDataListener_Beer extends TableDataListener {
public TableDataListener_Beer(Context context, SQLiteDatabase db,
Table table, UpdateHandler handler) {
super(context, db, table, handler);
}
@Override
public void parseFields(int id, String[] fields,
SQLiteStatement insertStatement) {
int breweryid = Integer.parseInt(fields[1]);
String name = fields[2];
int style;
try {
style = Integer.parseInt(fields[4]);
} catch (NumberFormatException e) {
style = -1;
}
double abv;
try {
abv = Double.parseDouble(fields[5]);
} catch (NumberFormatException e) {
abv = -1;
}
String image = fields[6];
String updated = fields[3];
double beermerating;
try {
beermerating = Double.parseDouble(fields[7]);
} catch (NumberFormatException e) {
beermerating = -1;
}
insertStatement.bindLong(1, id);
insertStatement.bindLong(2, breweryid);
insertStatement.bindString(3, name);
if (style >= 0) {
insertStatement.bindLong(4, style);
} else {
insertStatement.bindNull(4);
}
if (abv >= 0) {
insertStatement.bindDouble(5, abv);
} else {
insertStatement.bindNull(5);
}
insertStatement.bindString(6, image);
insertStatement.bindString(7, updated);
if (beermerating >= 0) {
insertStatement.bindDouble(8, beermerating);
} else {
insertStatement.bindNull(8);
}
}
}
private static class TableDataListener_Style extends TableDataListener {
public TableDataListener_Style(Context context, SQLiteDatabase db,
Table table, UpdateHandler handler) {
super(context, db, table, handler);
}
@Override
public void parseFields(int id, String[] fields,
SQLiteStatement insertStatement) {
String name = fields[1];
String updated = fields[2];
insertStatement.bindLong(1, id);
insertStatement.bindString(2, name);
insertStatement.bindString(3, updated);
}
}
}
|
beerme/src/main/java/com/beerme/android/database/TableDefs_6.java
|
package com.beerme.android.database;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.Builder;
import android.util.Log;
import com.beerme.android.R;
import com.beerme.android.utils.ErrLog;
import com.beerme.android.utils.UrlToFileDownloader;
import com.beerme.android.utils.UrlToFileDownloader.UrlToFileDownloadListener;
import com.beerme.android.utils.Utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
public class TableDefs_6 extends TableDefs {
private SQLiteDatabase mDb = null;
private UpdateListener mListener = null;
public enum Table {
BREWERY("brewery"), BEER("beer"), STYLE("style");
private final String name;
Table(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public TableDefs_6() {
super();
}
// MEDIUM: AND0103: RFE: Localize style text
@Override
protected void initTableDefs() {
createStatements.put(TABLE_BREWERYNOTES, "CREATE TABLE IF NOT EXISTS "
+ TABLE_BREWERYNOTES + " (" + "_id INTEGER PRIMARY KEY, "
+ "breweryid INTEGER NOT NULL, "
+ "date TEXT DEFAULT CURRENT_DATE NOT NULL, " + "rating REAL, "
+ "notes TEXT NOT NULL " + ")");
indexStatements.put(TABLE_BREWERYNOTES,
new String[]{createIndex(TABLE_BREWERYNOTES, "breweryid"),
createIndex(TABLE_BREWERYNOTES, "date")});
createStatements.put(TABLE_BEERNOTES, "CREATE TABLE IF NOT EXISTS "
+ TABLE_BEERNOTES + " (" + "_id INTEGER PRIMARY KEY, "
+ "beerid INTEGER NOT NULL, " + "package TEXT DEFAULT '', "
+ "sampled TEXT DEFAULT CURRENT_DATE, "
+ "place TEXT DEFAULT '', " + "appscore REAL DEFAULT 0, "
+ "appearance TEXT DEFAULT '', " + "aroscore REAL DEFAULT 0, "
+ "aroma TEXT DEFAULT '', " + "mouscore REAL DEFAULT 0, "
+ "mouthfeel TEXT DEFAULT '', " + "ovrscore REAL DEFAULT 0, "
+ "notes TEXT DEFAULT ''" + ")");
indexStatements.put(TABLE_BEERNOTES,
new String[]{createIndex(TABLE_BEERNOTES, "beerid"),
createIndex(TABLE_BEERNOTES, "sampled")});
createStatements.put(TABLE_BREWERY, "CREATE TABLE " + TABLE_BREWERY
+ " (" + "_id INTEGER PRIMARY KEY, " + "name TEXT NOT NULL, "
+ "address TEXT NOT NULL, " + "latitude REAL NOT NULL, "
+ "longitude REAL NOT NULL, " + "status INTEGER NOT NULL, "
+ "hours TEXT, " + "phone TEXT, " + "web TEXT, "
+ "services INTEGER NOT NULL DEFAULT 0, " + "image TEXT, "
+ "updated TEXT NOT NULL DEFAULT CURRENT_DATE" + ")");
indexStatements.put(
TABLE_BREWERY,
new String[]{createIndex(TABLE_BREWERY, "name"),
createIndex(TABLE_BREWERY, "status"),
createIndex(TABLE_BREWERY, "latitude"),
createIndex(TABLE_BREWERY, "longitude"),
createIndex(TABLE_BREWERY, "updated")});
createStatements.put(TABLE_BEER, "CREATE TABLE " + TABLE_BEER + " ("
+ "_id INTEGER PRIMARY KEY, " + "breweryid INTEGER NOT NULL, "
+ "name TEXT NOT NULL, " + "style INTEGER, " + "abv REAL, "
+ "image TEXT, "
+ "updated TEXT NOT NULL DEFAULT CURRENT_DATE, "
+ "beermerating REAL" + ")");
indexStatements.put(
TABLE_BEER,
new String[]{createIndex(TABLE_BEER, "breweryid"),
createIndex(TABLE_BEER, "name"),
createIndex(TABLE_BEER, "updated")});
createStatements.put(TABLE_STYLE, "CREATE TABLE " + TABLE_STYLE + " ("
+ "_id INTEGER PRIMARY KEY, " + "name TEXT NOT NULL, "
+ "updated TEXT NOT NULL DEFAULT CURRENT_DATE" + ")");
indexStatements.put(TABLE_STYLE,
new String[]{createIndex(TABLE_STYLE, "updated")});
}
@Override
public void upgrade(SQLiteDatabase db) {
// Upgrade to v6
// add beer.beermerating
Log.i(Utils.APPTAG, "Upgrading database from 5 to 6");
mDb = db;
upgradeOldTables(db);
}
@Override
protected void upgradeOldTables(SQLiteDatabase db) {
mDb = db;
db.beginTransaction();
DbOpenHelper.setUpdating(mContext, true);
try {
// Deleting all the beer data and reloading it is more efficient
// than saving the data and downloading just the ratings.
db.execSQL("DROP TABLE IF EXISTS " + TABLE_BEER);
db.execSQL(createStatements.get(TABLE_BEER));
db.setTransactionSuccessful();
resetLastUpdate(mContext);
} catch (SQLException e) {
ErrLog.log(mContext, "onUpgrade(5 to 6)", e,
R.string.Database_upgrade_failed);
} finally {
db.endTransaction();
DbOpenHelper.setUpdating(mContext, false);
}
}
@Override
public void updateData(SQLiteDatabase db, UpdateListener listener) {
if (Utils.isOnline(mContext)) {
mDb = db;
mListener = listener;
String lastUpdate = getLastUpdate(mContext);
String now = DbOpenHelper.sqlDateFormat.format(Calendar.getInstance()
.getTime());
if (now.compareTo(lastUpdate) > 0) {
HandlerThread uiThread = new HandlerThread("UIHandler");
uiThread.start();
UpdateHandler handler = new UpdateHandler(uiThread.getLooper(),
this);
handler.sendEmptyMessage(UpdateHandler.BREWERY_START);
} else {
if (listener != null) {
listener.onDataUpdated();
}
}
// } else {
// ErrLog.log(mContext, "TableDefs_6.updateData()", null, R.string
// .Requires_network_access_to_update_database);
}
}
protected final static class UpdateHandler extends Handler {
public static final int BREWERY_START = 1;
public static final int BREWERY_END = 2;
public static final int BEER_START = 3;
public static final int BEER_END = 4;
public static final int STYLE_START = 5;
public static final int STYLE_END = 6;
private TableDefs_6 mRef;
private Context mContext;
private SQLiteDatabase mDb;
private UpdateListener mListener;
private boolean doneBrewery = false;
private boolean doneBeer = false;
private boolean doneStyle = false;
public UpdateHandler(Looper looper, TableDefs_6 obj) {
super(looper);
WeakReference<TableDefs_6> ref = new WeakReference<>(obj);
mRef = ref.get();
mContext = mRef.mContext;
mDb = mRef.mDb;
mListener = mRef.mListener;
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case BREWERY_START:
doneBrewery = false;
DbOpenHelper.setUpdating(mContext, true);
updateDataByTable(mContext, mDb, Table.BREWERY, this);
break;
case BREWERY_END:
doneBrewery = true;
DbOpenHelper.setUpdating(mContext, false);
sendEmptyMessage(BEER_START);
break;
case BEER_START:
doneBeer = false;
DbOpenHelper.setUpdating(mContext, true);
updateDataByTable(mContext, mDb, Table.BEER, this);
break;
case BEER_END:
doneBeer = true;
DbOpenHelper.setUpdating(mContext, false);
sendEmptyMessage(STYLE_START);
break;
case STYLE_START:
DbOpenHelper.setUpdating(mContext, true);
doneStyle = false;
updateDataByTable(mContext, mDb, Table.STYLE, this);
break;
case STYLE_END:
doneStyle = true;
DbOpenHelper.setUpdating(mContext, false);
break;
default:
super.handleMessage(msg);
}
if (doneBrewery && doneBeer && doneStyle) {
setLastUpdate(mContext);
if (mListener != null) {
mListener.onDataUpdated();
}
}
}
}
protected static final String URL_INIT_BREWERY_LIST = "breweryList.php";
protected static final String URL_INIT_BEER_LIST = "beerList.php";
protected static final String URL_INIT_STYLE_LIST = "styleList.php";
private static void updateDataByTable(Context context, SQLiteDatabase db,
Table table, UpdateHandler handler) {
int notification;
String urlInit;
switch (table) {
case BREWERY:
notification = TableDefs.NOTIFICATION_BREWERY_DOWNLOAD;
urlInit = URL_INIT_BREWERY_LIST;
break;
case BEER:
notification = TableDefs.NOTIFICATION_BEER_DOWNLOAD;
urlInit = URL_INIT_BEER_LIST;
break;
case STYLE:
notification = TableDefs.NOTIFICATION_STYLE_DOWNLOAD;
urlInit = URL_INIT_STYLE_LIST;
break;
default:
throw new IllegalArgumentException("invalid table: "
+ table.getName());
}
String tableName = table.getName();
String lastUpdate = getLastUpdateByTable(db, tableName);
startDownloadProgress(context, String.format(
context.getString(R.string.TABLE_data), tableName),
notification);
URL url;
try {
url = Utils.buildUrl(urlInit, new String[]{"t=" + lastUpdate});
UrlToFileDownloader.download(context, url,
TableDataListener.getInstance(context, db, table, handler));
} catch (MalformedURLException e) {
ErrLog.log(context, "updateDataByTable(" + tableName + ")", e,
"Malformed URL");
}
}
private static abstract class TableDataListener implements
UrlToFileDownloadListener {
private static final String INSERT_BREWERY = "INSERT OR REPLACE INTO brewery (_id, name, address, latitude, longitude, status, hours, phone, web, services, image, updated) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
private static final String INSERT_BEER = "INSERT OR REPLACE INTO beer (_id, breweryid, name, style, abv, image, updated, beermerating) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
private static final String INSERT_STYLE = "INSERT OR REPLACE INTO style (_id, name, updated) VALUES (?, ?, ?)";
private Context mContext = null;
private SQLiteDatabase mDb = null;
private Table mTable = null;
private String mName = null;
private UpdateHandler mHandler = null;
private NotificationManager mNotifyManager = null;
private String mInsertSql = null;
private int mNotificationDownload = -1;
private int mNotificationLoad = -1;
private int mNextStep = -1;
public TableDataListener(Context context, SQLiteDatabase db,
Table table, UpdateHandler handler) {
mContext = context;
mDb = db;
mTable = table;
mHandler = handler;
mNotifyManager = (NotificationManager) mContext
.getSystemService(Context.NOTIFICATION_SERVICE);
switch (table) {
case BREWERY:
mInsertSql = INSERT_BREWERY;
mNotificationDownload = TableDefs.NOTIFICATION_BREWERY_DOWNLOAD;
mNotificationLoad = TableDefs.NOTIFICATION_BREWERY_LOAD;
mNextStep = UpdateHandler.BREWERY_END;
break;
case BEER:
mInsertSql = INSERT_BEER;
mNotificationDownload = TableDefs.NOTIFICATION_BEER_DOWNLOAD;
mNotificationLoad = TableDefs.NOTIFICATION_BEER_LOAD;
mNextStep = UpdateHandler.BEER_END;
break;
case STYLE:
mInsertSql = INSERT_STYLE;
mNotificationDownload = TableDefs.NOTIFICATION_STYLE_DOWNLOAD;
mNotificationLoad = TableDefs.NOTIFICATION_STYLE_LOAD;
mNextStep = UpdateHandler.STYLE_END;
break;
default:
throw new IllegalArgumentException("invalid table: "
+ table.getName());
}
mName = mTable.getName();
}
public static TableDataListener getInstance(Context context,
SQLiteDatabase db, Table table, UpdateHandler handler) {
switch (table) {
case BREWERY:
return new TableDataListener_Brewery(context, db, table,
handler);
case BEER:
return new TableDataListener_Beer(context, db, table, handler);
case STYLE:
return new TableDataListener_Style(context, db, table, handler);
default:
throw new IllegalArgumentException("invalid table: "
+ table.getName());
}
}
@Override
public void onUrlToFileDownloaded(String fileName) {
mNotifyManager.cancel(mNotificationDownload);
if (fileName != null) {
if ("".equals(fileName)) {
throw new IllegalArgumentException(
"TableDataListener: empty fileName");
}
Builder builder = new NotificationCompat.Builder(mContext)
.setContentTitle(
String.format(
mContext.getString(R.string.TABLE_data),
mName))
.setContentText(
String.format(
mContext.getString(R.string.Loading_TABLE_data),
mName))
.setSmallIcon(R.drawable.ic_home)
.setProgress(0, 0, true)
.setContentIntent(
PendingIntent.getActivity(mContext, 0,
new Intent(), 0));
File file = new File(fileName);
long start;
SQLiteStatement insertStatement;
start = System.currentTimeMillis();
insertStatement = mDb.compileStatement(mInsertSql);
try {
mDb.beginTransaction();
parse(file, insertStatement, builder);
mDb.setTransactionSuccessful();
} catch (FileNotFoundException e) {
ErrLog.log(
mContext,
"onUrlToFileDownloaded(" + fileName
+ "): FileNotFoundException: ",
e,
String.format(
mContext.getString(R.string.Failed_to_update_TABLE_data),
mName));
} catch (IOException e) {
ErrLog.log(mContext, "onUrlToFileDownloaded(" + fileName
+ "): IOException: ", e, String.format(mContext
.getString(R.string.Failed_to_update_TABLE_data),
mName));
} finally {
mDb.endTransaction();
file.delete();
Log.i(Utils.APPTAG, "onUrlToFileDownloaded(" + mName
+ ") elapsed: "
+ (System.currentTimeMillis() - start) + " ms");
mNotifyManager.cancel(mNotificationLoad);
mHandler.sendEmptyMessage(mNextStep);
}
}
}
public void parse(File file, SQLiteStatement insertStatement,
Builder builder) throws IOException {
String[] fields;
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = reader.readLine();
if (line != null) {
fields = line.split("\\|", -1);
int max = Integer.parseInt(fields[0]);
reader.close();
int onePercent = Math.max(max / 100, 1);
reader = new BufferedReader(new FileReader(file));
int id;
while ((line = reader.readLine()) != null) {
fields = line.split("\\|", -1);
id = Integer.parseInt(fields[0]);
if (id % onePercent == 0) {
builder.setProgress(max, max - id, false);
mNotifyManager.notify(mNotificationLoad,
builder.build());
}
parseFields(id, fields, insertStatement);
insertStatement.executeInsert();
}
reader.close();
}
}
public abstract void parseFields(int id, String[] fields,
SQLiteStatement insertStatement);
}
private static class TableDataListener_Brewery extends TableDataListener {
public TableDataListener_Brewery(Context context, SQLiteDatabase db,
Table table, UpdateHandler handler) {
super(context, db, table, handler);
}
@Override
public void parseFields(int id, String[] fields,
SQLiteStatement insertStatement) {
String name = fields[1];
String address = fields[2];
double latitude = Double.parseDouble(fields[3]);
double longitude = Double.parseDouble(fields[4]);
int status = Integer.parseInt(fields[5]);
int services = Integer.parseInt(fields[6]);
String updated = fields[7];
String phone = fields[8];
String hours = fields[9];
String web = fields[10];
String image = fields[11];
insertStatement.bindLong(1, id);
insertStatement.bindString(2, name);
insertStatement.bindString(3, address);
insertStatement.bindDouble(4, latitude);
insertStatement.bindDouble(5, longitude);
insertStatement.bindLong(6, status);
insertStatement.bindString(7, hours);
insertStatement.bindString(8, phone);
insertStatement.bindString(9, web);
insertStatement.bindLong(10, services);
insertStatement.bindString(11, image);
insertStatement.bindString(12, updated);
}
}
private static class TableDataListener_Beer extends TableDataListener {
public TableDataListener_Beer(Context context, SQLiteDatabase db,
Table table, UpdateHandler handler) {
super(context, db, table, handler);
}
@Override
public void parseFields(int id, String[] fields,
SQLiteStatement insertStatement) {
int breweryid = Integer.parseInt(fields[1]);
String name = fields[2];
int style;
try {
style = Integer.parseInt(fields[4]);
} catch (NumberFormatException e) {
style = -1;
}
double abv;
try {
abv = Double.parseDouble(fields[5]);
} catch (NumberFormatException e) {
abv = -1;
}
String image = fields[6];
String updated = fields[3];
double beermerating;
try {
beermerating = Double.parseDouble(fields[7]);
} catch (NumberFormatException e) {
beermerating = -1;
}
insertStatement.bindLong(1, id);
insertStatement.bindLong(2, breweryid);
insertStatement.bindString(3, name);
if (style >= 0) {
insertStatement.bindLong(4, style);
} else {
insertStatement.bindNull(4);
}
if (abv >= 0) {
insertStatement.bindDouble(5, abv);
} else {
insertStatement.bindNull(5);
}
insertStatement.bindString(6, image);
insertStatement.bindString(7, updated);
if (beermerating >= 0) {
insertStatement.bindDouble(8, beermerating);
} else {
insertStatement.bindNull(8);
}
}
}
private static class TableDataListener_Style extends TableDataListener {
public TableDataListener_Style(Context context, SQLiteDatabase db,
Table table, UpdateHandler handler) {
super(context, db, table, handler);
}
@Override
public void parseFields(int id, String[] fields,
SQLiteStatement insertStatement) {
String name = fields[1];
String updated = fields[2];
insertStatement.bindLong(1, id);
insertStatement.bindString(2, name);
insertStatement.bindString(3, updated);
}
}
}
|
Fix database IllegalStateException
|
beerme/src/main/java/com/beerme/android/database/TableDefs_6.java
|
Fix database IllegalStateException
|
<ide><path>eerme/src/main/java/com/beerme/android/database/TableDefs_6.java
<ide> parse(file, insertStatement, builder);
<ide> mDb.setTransactionSuccessful();
<ide> } catch (FileNotFoundException e) {
<del> ErrLog.log(
<del> mContext,
<del> "onUrlToFileDownloaded(" + fileName
<del> + "): FileNotFoundException: ",
<add> ErrLog.log(mContext,
<add> "onUrlToFileDownloaded(" + fileName + "): FileNotFoundException: ",
<ide> e,
<del> String.format(
<del> mContext.getString(R.string.Failed_to_update_TABLE_data),
<del> mName));
<add> String.format(mContext.getString(R.string.Failed_to_update_TABLE_data), mName));
<ide> } catch (IOException e) {
<del> ErrLog.log(mContext, "onUrlToFileDownloaded(" + fileName
<del> + "): IOException: ", e, String.format(mContext
<del> .getString(R.string.Failed_to_update_TABLE_data),
<del> mName));
<add> ErrLog.log(mContext, "onUrlToFileDownloaded(" + fileName + "): IOException: ",
<add> e,
<add> String.format(mContext
<add> .getString(R.string.Failed_to_update_TABLE_data), mName));
<ide> } finally {
<del> mDb.endTransaction();
<add> if (mDb.inTransaction()) {
<add> mDb.endTransaction();
<add> }
<ide> file.delete();
<ide> Log.i(Utils.APPTAG, "onUrlToFileDownloaded(" + mName
<ide> + ") elapsed: "
|
|
JavaScript
|
mit
|
c9d65f1f3caf10fc8db28fb791b4782c7b65d2cd
| 0 |
sitespeedio/sitespeed.io,sitespeedio/sitespeed.io,sitespeedio/sitespeed.io,sitespeedio/sitespeed.io
|
'use strict';
const Stats = require('fast-stats').Stats,
get = require('lodash.get'),
set = require('lodash.set');
function percentileName(percentile) {
if (percentile === 0) {
return 'min';
} else if (percentile === 100) {
return 'max';
} else {
return 'p' + String(percentile).replace('.', '_');
}
}
function isFiniteNumber(n) {
return typeof n === 'number' && isFinite(n);
}
module.exports = {
/**
* Create or update a fast-stats#Stats object in target at path.
*/
pushStats(target, path, data) {
if (!isFiniteNumber(data))
throw new Error(`Tried to add ${data} to stats for path ${path}`);
const stats = get(target, path, new Stats());
stats.push(data);
set(target, path, stats);
},
pushGroupStats(target, domainTarget, path, data) {
this.pushStats(target, path, data);
this.pushStats(domainTarget, path, data);
},
/**
* Summarize stats and put result in target at path
*/
setStatsSummary(target, path, stats) {
set(target, path, this.summarizeStats(stats));
},
summarizeStats(stats, options) {
if (stats.length === 0) {
return undefined;
}
options = options || {};
let percentiles = options.percentiles || [0, 90, 100];
let decimals = options.decimals || 0;
let data = {
median: parseFloat(stats.median().toFixed(decimals)),
mean: parseFloat(stats.amean().toFixed(decimals))
};
percentiles.forEach(p => {
let name = percentileName(p);
const percentile = stats.percentile(p);
if (Number.isFinite(percentile)) {
data[name] = parseFloat(percentile.toFixed(decimals));
} else {
throw new Error(
'Failed to calculate ' +
name +
' for stats: ' +
JSON.stringify(stats, null, 2)
);
}
});
if (options.includeSum) {
data.sum = parseFloat(stats.Σ().toFixed(decimals));
}
return data;
}
};
|
lib/support/statsHelpers.js
|
'use strict';
const Stats = require('fast-stats').Stats,
get = require('lodash.get'),
set = require('lodash.set');
function percentileName(percentile) {
if (percentile === 0) {
return 'min';
} else if (percentile === 100) {
return 'max';
} else {
return 'p' + String(percentile).replace('.', '_');
}
}
function isFiniteNumber(n) {
return typeof n === 'number' && isFinite(n);
}
module.exports = {
/**
* Create or update a fast-stats#Stats object in target at path.
*/
pushStats(target, path, data) {
if (!isFiniteNumber(data))
throw new Error(`Tried to add ${data} to stats for path ${path}`);
const stats = get(target, path, new Stats());
stats.push(data);
set(target, path, stats);
},
pushGroupStats(target, domainTarget, path, data) {
this.pushStats(target, path, data);
this.pushStats(domainTarget, path, data);
},
/**
* Summarize stats and put result in target at path
*/
setStatsSummary(target, path, stats) {
set(target, path, this.summarizeStats(stats));
},
summarizeStats(stats, options) {
if (stats.length === 0) {
return undefined;
}
options = options || {};
let percentiles = options.percentiles || [0, 90, 100];
let decimals = options.decimals || 0;
let data = {
median: parseInt(stats.median().toFixed(decimals)),
mean: parseInt(stats.amean().toFixed(decimals))
};
percentiles.forEach(p => {
let name = percentileName(p);
const percentile = stats.percentile(p);
if (Number.isFinite(percentile)) {
data[name] = parseInt(percentile.toFixed(decimals));
} else {
throw new Error(
'Failed to calculate ' +
name +
' for stats: ' +
JSON.stringify(stats, null, 2)
);
}
});
if (options.includeSum) {
data.sum = parseInt(stats.Σ().toFixed(decimals));
}
return data;
}
};
|
Fix statsHelper handling for float number statistics (#2674) (#2675)
|
lib/support/statsHelpers.js
|
Fix statsHelper handling for float number statistics (#2674) (#2675)
|
<ide><path>ib/support/statsHelpers.js
<ide> let percentiles = options.percentiles || [0, 90, 100];
<ide> let decimals = options.decimals || 0;
<ide> let data = {
<del> median: parseInt(stats.median().toFixed(decimals)),
<del> mean: parseInt(stats.amean().toFixed(decimals))
<add> median: parseFloat(stats.median().toFixed(decimals)),
<add> mean: parseFloat(stats.amean().toFixed(decimals))
<ide> };
<ide> percentiles.forEach(p => {
<ide> let name = percentileName(p);
<ide> const percentile = stats.percentile(p);
<ide> if (Number.isFinite(percentile)) {
<del> data[name] = parseInt(percentile.toFixed(decimals));
<add> data[name] = parseFloat(percentile.toFixed(decimals));
<ide> } else {
<ide> throw new Error(
<ide> 'Failed to calculate ' +
<ide> }
<ide> });
<ide> if (options.includeSum) {
<del> data.sum = parseInt(stats.Σ().toFixed(decimals));
<add> data.sum = parseFloat(stats.Σ().toFixed(decimals));
<ide> }
<ide>
<ide> return data;
|
|
Java
|
apache-2.0
|
a8fc937678db2d72616b7f0fd415b1ca4e30863c
| 0 |
apache/archiva,apache/archiva,apache/archiva,emsouza/archiva,ricardojbasilio/archiva,emsouza/archiva,Altiscale/archiva,sadlil/archiva,apache/archiva,olamy/archiva,flomotlik/archiva,sadlil/archiva,Altiscale/archiva,flomotlik/archiva,emsouza/archiva,ricardojbasilio/archiva,flomotlik/archiva,Altiscale/archiva,Altiscale/archiva,emsouza/archiva,olamy/archiva,flomotlik/archiva,ricardojbasilio/archiva,ricardojbasilio/archiva,sadlil/archiva,sadlil/archiva,sadlil/archiva,olamy/archiva,olamy/archiva,apache/archiva
|
package org.apache.archiva.scheduler.indexing;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.archiva.admin.model.RepositoryAdminException;
import org.apache.archiva.admin.model.beans.NetworkProxy;
import org.apache.archiva.admin.model.beans.RemoteRepository;
import org.apache.archiva.admin.model.remote.RemoteRepositoryAdmin;
import org.apache.archiva.proxy.common.WagonFactory;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.StopWatch;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.impl.nio.codecs.LengthDelimitedDecoder;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.client.methods.ZeroCopyConsumer;
import org.apache.http.nio.protocol.HttpAsyncRequestProducer;
import org.apache.http.protocol.HttpContext;
import org.apache.maven.index.context.IndexingContext;
import org.apache.maven.index.updater.IndexUpdateRequest;
import org.apache.maven.index.updater.IndexUpdater;
import org.apache.maven.index.updater.ResourceFetcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* @author Olivier Lamy
* @since 1.4-M1
*/
public class DownloadRemoteIndexTask
implements Runnable
{
private Logger log = LoggerFactory.getLogger( getClass() );
private RemoteRepository remoteRepository;
private RemoteRepositoryAdmin remoteRepositoryAdmin;
private WagonFactory wagonFactory;
private NetworkProxy networkProxy;
private boolean fullDownload;
private List<String> runningRemoteDownloadIds;
private IndexUpdater indexUpdater;
public DownloadRemoteIndexTask( DownloadRemoteIndexTaskRequest downloadRemoteIndexTaskRequest,
List<String> runningRemoteDownloadIds )
{
this.remoteRepository = downloadRemoteIndexTaskRequest.getRemoteRepository();
this.wagonFactory = downloadRemoteIndexTaskRequest.getWagonFactory();
this.networkProxy = downloadRemoteIndexTaskRequest.getNetworkProxy();
this.fullDownload = downloadRemoteIndexTaskRequest.isFullDownload();
this.runningRemoteDownloadIds = runningRemoteDownloadIds;
this.indexUpdater = downloadRemoteIndexTaskRequest.getIndexUpdater();
this.remoteRepositoryAdmin = downloadRemoteIndexTaskRequest.getRemoteRepositoryAdmin();
}
public void run()
{
// so short lock : not sure we need it
synchronized ( this.runningRemoteDownloadIds )
{
if ( this.runningRemoteDownloadIds.contains( this.remoteRepository.getId() ) )
{
// skip it as it's running
log.info( "skip download index remote for repo {} it's already running",
this.remoteRepository.getId() );
return;
}
this.runningRemoteDownloadIds.add( this.remoteRepository.getId() );
}
File tempIndexDirectory = null;
StopWatch stopWatch = new StopWatch();
stopWatch.start();
try
{
log.info( "start download remote index for remote repository {}", this.remoteRepository.getId() );
IndexingContext indexingContext = remoteRepositoryAdmin.createIndexContext( this.remoteRepository );
// create a temp directory to download files
tempIndexDirectory = new File( indexingContext.getIndexDirectoryFile().getParent(), ".tmpIndex" );
File indexCacheDirectory = new File( indexingContext.getIndexDirectoryFile().getParent(), ".indexCache" );
indexCacheDirectory.mkdirs();
if ( tempIndexDirectory.exists() )
{
FileUtils.deleteDirectory( tempIndexDirectory );
}
tempIndexDirectory.mkdirs();
tempIndexDirectory.deleteOnExit();
String baseIndexUrl = indexingContext.getIndexUpdateUrl();
URL indexUrl = new URL( baseIndexUrl );
/*
String wagonProtocol = new URL( this.remoteRepository.getUrl() ).getProtocol();
final StreamWagon wagon = (StreamWagon) wagonFactory.getWagon(
new WagonFactoryRequest( wagonProtocol, this.remoteRepository.getExtraHeaders() ).networkProxy(
this.networkProxy ) );
int timeoutInMilliseconds = remoteRepository.getTimeout() * 1000;
// FIXME olamy having 2 config values
wagon.setReadTimeout( timeoutInMilliseconds );
wagon.setTimeout( timeoutInMilliseconds );
if ( wagon instanceof AbstractHttpClientWagon )
{
HttpConfiguration httpConfiguration = new HttpConfiguration();
HttpMethodConfiguration httpMethodConfiguration = new HttpMethodConfiguration();
httpMethodConfiguration.setUsePreemptive( true );
httpMethodConfiguration.setReadTimeout( timeoutInMilliseconds );
httpConfiguration.setGet( httpMethodConfiguration );
( (AbstractHttpClientWagon) wagon ).setHttpConfiguration( httpConfiguration );
}
wagon.addTransferListener( new DownloadListener() );
ProxyInfo proxyInfo = null;
if ( this.networkProxy != null )
{
proxyInfo = new ProxyInfo();
proxyInfo.setHost( this.networkProxy.getHost() );
proxyInfo.setPort( this.networkProxy.getPort() );
proxyInfo.setUserName( this.networkProxy.getUsername() );
proxyInfo.setPassword( this.networkProxy.getPassword() );
}
AuthenticationInfo authenticationInfo = null;
if ( this.remoteRepository.getUserName() != null )
{
authenticationInfo = new AuthenticationInfo();
authenticationInfo.setUserName( this.remoteRepository.getUserName() );
authenticationInfo.setPassword( this.remoteRepository.getPassword() );
}
wagon.connect( new Repository( this.remoteRepository.getId(), baseIndexUrl ), authenticationInfo,
proxyInfo );
*/
//---------------------------------------------
HttpAsyncClientBuilder builder = HttpAsyncClientBuilder.create();
BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
if ( this.networkProxy != null )
{
HttpHost httpHost = new HttpHost( this.networkProxy.getHost(), this.networkProxy.getPort() );
builder = builder.setProxy( httpHost );
if ( this.networkProxy.getUsername() != null )
{
basicCredentialsProvider.setCredentials(
new AuthScope( this.networkProxy.getHost(), this.networkProxy.getPort(), null, null ),
new UsernamePasswordCredentials( this.networkProxy.getUsername(),
this.networkProxy.getPassword() ) );
}
}
if ( this.remoteRepository.getUserName() != null )
{
basicCredentialsProvider.setCredentials(
new AuthScope( indexUrl.getHost(), indexUrl.getPort(), null, null ),
new UsernamePasswordCredentials( this.remoteRepository.getUserName(),
this.remoteRepository.getPassword() ) );
}
builder = builder.setDefaultCredentialsProvider( basicCredentialsProvider );
File indexDirectory = indexingContext.getIndexDirectoryFile();
if ( !indexDirectory.exists() )
{
indexDirectory.mkdirs();
}
CloseableHttpAsyncClient closeableHttpAsyncClient = builder.build();
closeableHttpAsyncClient.start();
ResourceFetcher resourceFetcher =
new ZeroCopyResourceFetcher( log, tempIndexDirectory, remoteRepository, closeableHttpAsyncClient,
baseIndexUrl );
IndexUpdateRequest request = new IndexUpdateRequest( indexingContext, resourceFetcher );
request.setForceFullUpdate( this.fullDownload );
request.setLocalIndexCacheDir( indexCacheDirectory );
this.indexUpdater.fetchAndUpdateIndex( request );
stopWatch.stop();
log.info( "time update index from remote for repository {}: {} s", this.remoteRepository.getId(),
( stopWatch.getTime() / 1000 ) );
// index packing optionnal ??
//IndexPackingRequest indexPackingRequest =
// new IndexPackingRequest( indexingContext, indexingContext.getIndexDirectoryFile() );
//indexPacker.packIndex( indexPackingRequest );
indexingContext.updateTimestamp( true );
}
catch ( MalformedURLException e )
{
log.error( e.getMessage(), e );
throw new RuntimeException( e.getMessage(), e );
}
catch ( IOException e )
{
log.error( e.getMessage(), e );
throw new RuntimeException( e.getMessage(), e );
}
catch ( RepositoryAdminException e )
{
log.error( e.getMessage(), e );
throw new RuntimeException( e.getMessage(), e );
}
finally
{
deleteDirectoryQuiet( tempIndexDirectory );
this.runningRemoteDownloadIds.remove( this.remoteRepository.getId() );
}
log.info( "end download remote index for remote repository " + this.remoteRepository.getId() );
}
private void deleteDirectoryQuiet( File f )
{
try
{
FileUtils.deleteDirectory( f );
}
catch ( IOException e )
{
log.warn( "skip error delete {} : {}", f, e.getMessage() );
}
}
private static class ZeroCopyConsumerListener
extends ZeroCopyConsumer
{
private Logger log = LoggerFactory.getLogger( getClass() );
private String resourceName;
private long startTime;
private long totalLength = 0;
//private long currentLength = 0;
private ZeroCopyConsumerListener( File file, String resourceName )
throws FileNotFoundException
{
super( file );
this.resourceName = resourceName;
}
@Override
protected File process( final HttpResponse response, final File file, final ContentType contentType )
throws Exception
{
if ( response.getStatusLine().getStatusCode() != HttpStatus.SC_OK )
{
throw new ClientProtocolException( "Upload failed: " + response.getStatusLine() );
}
long endTime = System.currentTimeMillis();
log.info( "end of transfer file {} {} kb: {}s", resourceName, this.totalLength / 1024,
( endTime - startTime ) / 1000 );
return file;
}
@Override
protected void onContentReceived( ContentDecoder decoder, IOControl ioControl )
throws IOException
{
if ( decoder instanceof LengthDelimitedDecoder )
{
LengthDelimitedDecoder ldl = LengthDelimitedDecoder.class.cast( decoder );
long len = getLen( ldl );
if ( len > -1 )
{
log.debug( "transfer of {} : {}/{}", resourceName, len / 1024, this.totalLength / 1024 );
}
}
super.onContentReceived( decoder, ioControl );
}
@Override
protected void onResponseReceived( HttpResponse response )
{
this.startTime = System.currentTimeMillis();
super.onResponseReceived( response );
this.totalLength = response.getEntity().getContentLength();
log.info( "start transfer of {}, contentLength: {}", resourceName, this.totalLength / 1024 );
}
@Override
protected void onEntityEnclosed( HttpEntity entity, ContentType contentType )
throws IOException
{
super.onEntityEnclosed( entity, contentType );
}
private long getLen( LengthDelimitedDecoder ldl )
{
try
{
Field lenField = LengthDelimitedDecoder.class.getDeclaredField( "len" );
lenField.setAccessible( true );
long len = (Long) lenField.get( ldl );
return len;
}
catch ( NoSuchFieldException e )
{
log.debug( e.getMessage(), e );
return -1;
}
catch ( IllegalAccessException e )
{
log.debug( e.getMessage(), e );
return -1;
}
}
}
private static class ZeroCopyResourceFetcher
implements ResourceFetcher
{
Logger log;
File tempIndexDirectory;
final RemoteRepository remoteRepository;
CloseableHttpAsyncClient httpclient;
String baseIndexUrl;
private ZeroCopyResourceFetcher( Logger log, File tempIndexDirectory, RemoteRepository remoteRepository,
CloseableHttpAsyncClient httpclient, String baseIndexUrl )
{
this.log = log;
this.tempIndexDirectory = tempIndexDirectory;
this.remoteRepository = remoteRepository;
this.httpclient = httpclient;
this.baseIndexUrl = baseIndexUrl;
}
public void connect( String id, String url )
throws IOException
{
//no op
}
public void disconnect()
throws IOException
{
// no op
}
public InputStream retrieve( final String name )
throws IOException
{
log.info( "index update retrieve file, name:{}", name );
File file = new File( tempIndexDirectory, name );
if ( file.exists() )
{
file.delete();
}
file.deleteOnExit();
ZeroCopyConsumer<File> consumer = new ZeroCopyConsumerListener( file, name );
URL targetUrl = new URL( this.baseIndexUrl );
final HttpHost targetHost = new HttpHost( targetUrl.getHost(), targetUrl.getPort() );
Future<File> httpResponseFuture = httpclient.execute( new HttpAsyncRequestProducer()
{
@Override
public HttpHost getTarget()
{
return targetHost;
}
@Override
public HttpRequest generateRequest()
throws IOException, HttpException
{
StringBuilder url = new StringBuilder( baseIndexUrl );
if ( !StringUtils.endsWith( baseIndexUrl, "/" ) )
{
url.append( '/' );
}
HttpGet httpGet = new HttpGet( url.append( addParameters( name, remoteRepository ) ).toString() );
return httpGet;
}
@Override
public void produceContent( ContentEncoder encoder, IOControl ioctrl )
throws IOException
{
// no op
}
@Override
public void requestCompleted( HttpContext context )
{
log.debug( "requestCompleted" );
}
@Override
public void failed( Exception ex )
{
log.error( "http request failed", ex );
}
@Override
public boolean isRepeatable()
{
log.debug( "isRepeatable" );
return true;
}
@Override
public void resetRequest()
throws IOException
{
log.debug( "resetRequest" );
}
@Override
public void close()
throws IOException
{
log.debug( "close" );
}
}, consumer, null );
try
{
int timeOut = this.remoteRepository.getRemoteDownloadTimeout();
file = timeOut > 0 ? httpResponseFuture.get( timeOut, TimeUnit.SECONDS ) : httpResponseFuture.get();
}
catch ( InterruptedException e )
{
throw new IOException( e.getMessage(), e );
}
catch ( ExecutionException e )
{
throw new IOException( e.getMessage(), e );
}
catch ( TimeoutException e )
{
throw new IOException( e.getMessage(), e );
}
return new FileInputStream( file );
}
}
// FIXME remove crappy copy/paste
protected static String addParameters( String path, RemoteRepository remoteRepository )
{
if ( remoteRepository.getExtraParameters().isEmpty() )
{
return path;
}
boolean question = false;
StringBuilder res = new StringBuilder( path == null ? "" : path );
for ( Map.Entry<String, String> entry : remoteRepository.getExtraParameters().entrySet() )
{
if ( !question )
{
res.append( '?' ).append( entry.getKey() ).append( '=' ).append( entry.getValue() );
}
}
return res.toString();
}
}
|
archiva-modules/archiva-scheduler/archiva-scheduler-indexing/src/main/java/org/apache/archiva/scheduler/indexing/DownloadRemoteIndexTask.java
|
package org.apache.archiva.scheduler.indexing;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.archiva.admin.model.RepositoryAdminException;
import org.apache.archiva.admin.model.beans.NetworkProxy;
import org.apache.archiva.admin.model.beans.RemoteRepository;
import org.apache.archiva.admin.model.remote.RemoteRepositoryAdmin;
import org.apache.archiva.proxy.common.WagonFactory;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.StopWatch;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.impl.nio.codecs.LengthDelimitedDecoder;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.client.methods.ZeroCopyConsumer;
import org.apache.http.nio.protocol.HttpAsyncRequestProducer;
import org.apache.http.protocol.HttpContext;
import org.apache.maven.index.context.IndexingContext;
import org.apache.maven.index.updater.IndexUpdateRequest;
import org.apache.maven.index.updater.IndexUpdater;
import org.apache.maven.index.updater.ResourceFetcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* @author Olivier Lamy
* @since 1.4-M1
*/
public class DownloadRemoteIndexTask
implements Runnable
{
private Logger log = LoggerFactory.getLogger( getClass() );
private RemoteRepository remoteRepository;
private RemoteRepositoryAdmin remoteRepositoryAdmin;
private WagonFactory wagonFactory;
private NetworkProxy networkProxy;
private boolean fullDownload;
private List<String> runningRemoteDownloadIds;
private IndexUpdater indexUpdater;
public DownloadRemoteIndexTask( DownloadRemoteIndexTaskRequest downloadRemoteIndexTaskRequest,
List<String> runningRemoteDownloadIds )
{
this.remoteRepository = downloadRemoteIndexTaskRequest.getRemoteRepository();
this.wagonFactory = downloadRemoteIndexTaskRequest.getWagonFactory();
this.networkProxy = downloadRemoteIndexTaskRequest.getNetworkProxy();
this.fullDownload = downloadRemoteIndexTaskRequest.isFullDownload();
this.runningRemoteDownloadIds = runningRemoteDownloadIds;
this.indexUpdater = downloadRemoteIndexTaskRequest.getIndexUpdater();
this.remoteRepositoryAdmin = downloadRemoteIndexTaskRequest.getRemoteRepositoryAdmin();
}
public void run()
{
// so short lock : not sure we need it
synchronized ( this.runningRemoteDownloadIds )
{
if ( this.runningRemoteDownloadIds.contains( this.remoteRepository.getId() ) )
{
// skip it as it's running
log.info( "skip download index remote for repo {} it's already running",
this.remoteRepository.getId() );
return;
}
this.runningRemoteDownloadIds.add( this.remoteRepository.getId() );
}
File tempIndexDirectory = null;
StopWatch stopWatch = new StopWatch();
stopWatch.start();
try
{
log.info( "start download remote index for remote repository {}", this.remoteRepository.getId() );
IndexingContext indexingContext = remoteRepositoryAdmin.createIndexContext( this.remoteRepository );
// create a temp directory to download files
tempIndexDirectory = new File( indexingContext.getIndexDirectoryFile().getParent(), ".tmpIndex" );
File indexCacheDirectory = new File( indexingContext.getIndexDirectoryFile().getParent(), ".indexCache" );
indexCacheDirectory.mkdirs();
if ( tempIndexDirectory.exists() )
{
FileUtils.deleteDirectory( tempIndexDirectory );
}
tempIndexDirectory.mkdirs();
tempIndexDirectory.deleteOnExit();
String baseIndexUrl = indexingContext.getIndexUpdateUrl();
URL indexUrl = new URL( baseIndexUrl );
/*
String wagonProtocol = new URL( this.remoteRepository.getUrl() ).getProtocol();
final StreamWagon wagon = (StreamWagon) wagonFactory.getWagon(
new WagonFactoryRequest( wagonProtocol, this.remoteRepository.getExtraHeaders() ).networkProxy(
this.networkProxy ) );
int timeoutInMilliseconds = remoteRepository.getTimeout() * 1000;
// FIXME olamy having 2 config values
wagon.setReadTimeout( timeoutInMilliseconds );
wagon.setTimeout( timeoutInMilliseconds );
if ( wagon instanceof AbstractHttpClientWagon )
{
HttpConfiguration httpConfiguration = new HttpConfiguration();
HttpMethodConfiguration httpMethodConfiguration = new HttpMethodConfiguration();
httpMethodConfiguration.setUsePreemptive( true );
httpMethodConfiguration.setReadTimeout( timeoutInMilliseconds );
httpConfiguration.setGet( httpMethodConfiguration );
( (AbstractHttpClientWagon) wagon ).setHttpConfiguration( httpConfiguration );
}
wagon.addTransferListener( new DownloadListener() );
ProxyInfo proxyInfo = null;
if ( this.networkProxy != null )
{
proxyInfo = new ProxyInfo();
proxyInfo.setHost( this.networkProxy.getHost() );
proxyInfo.setPort( this.networkProxy.getPort() );
proxyInfo.setUserName( this.networkProxy.getUsername() );
proxyInfo.setPassword( this.networkProxy.getPassword() );
}
AuthenticationInfo authenticationInfo = null;
if ( this.remoteRepository.getUserName() != null )
{
authenticationInfo = new AuthenticationInfo();
authenticationInfo.setUserName( this.remoteRepository.getUserName() );
authenticationInfo.setPassword( this.remoteRepository.getPassword() );
}
wagon.connect( new Repository( this.remoteRepository.getId(), baseIndexUrl ), authenticationInfo,
proxyInfo );
*/
//---------------------------------------------
HttpAsyncClientBuilder builder = HttpAsyncClientBuilder.create();
BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
if ( this.networkProxy != null )
{
HttpHost httpHost = new HttpHost( this.networkProxy.getHost(), this.networkProxy.getPort() );
builder = builder.setProxy( httpHost );
if ( this.networkProxy.getUsername() != null )
{
basicCredentialsProvider.setCredentials(
new AuthScope( this.networkProxy.getHost(), this.networkProxy.getPort(), null, null ),
new UsernamePasswordCredentials( this.networkProxy.getUsername(),
this.networkProxy.getPassword() ) );
}
}
if ( this.remoteRepository.getUserName() != null )
{
basicCredentialsProvider.setCredentials(
new AuthScope( indexUrl.getHost(), indexUrl.getPort(), null, null ),
new UsernamePasswordCredentials( this.remoteRepository.getUserName(),
this.remoteRepository.getPassword() ) );
}
builder = builder.setDefaultCredentialsProvider( basicCredentialsProvider );
File indexDirectory = indexingContext.getIndexDirectoryFile();
if ( !indexDirectory.exists() )
{
indexDirectory.mkdirs();
}
CloseableHttpAsyncClient closeableHttpAsyncClient = builder.build();
closeableHttpAsyncClient.start();
ResourceFetcher resourceFetcher =
new ZeroCopyResourceFetcher( log, tempIndexDirectory, remoteRepository, closeableHttpAsyncClient,
baseIndexUrl );
IndexUpdateRequest request = new IndexUpdateRequest( indexingContext, resourceFetcher );
request.setForceFullUpdate( this.fullDownload );
request.setLocalIndexCacheDir( indexCacheDirectory );
this.indexUpdater.fetchAndUpdateIndex( request );
stopWatch.stop();
log.info( "time update index from remote for repository {}: {} s", this.remoteRepository.getId(),
( stopWatch.getTime() / 1000 ) );
// index packing optionnal ??
//IndexPackingRequest indexPackingRequest =
// new IndexPackingRequest( indexingContext, indexingContext.getIndexDirectoryFile() );
//indexPacker.packIndex( indexPackingRequest );
indexingContext.updateTimestamp( true );
}
catch ( MalformedURLException e )
{
log.error( e.getMessage(), e );
throw new RuntimeException( e.getMessage(), e );
}
catch ( IOException e )
{
log.error( e.getMessage(), e );
throw new RuntimeException( e.getMessage(), e );
}
catch ( RepositoryAdminException e )
{
log.error( e.getMessage(), e );
throw new RuntimeException( e.getMessage(), e );
}
finally
{
deleteDirectoryQuiet( tempIndexDirectory );
this.runningRemoteDownloadIds.remove( this.remoteRepository.getId() );
}
log.info( "end download remote index for remote repository " + this.remoteRepository.getId() );
}
private void deleteDirectoryQuiet( File f )
{
try
{
FileUtils.deleteDirectory( f );
}
catch ( IOException e )
{
log.warn( "skip error delete {} : {}", f, e.getMessage() );
}
}
private static class ZeroCopyConsumerListener
extends ZeroCopyConsumer
{
private Logger log = LoggerFactory.getLogger( getClass() );
private String resourceName;
private long startTime;
private long totalLength = 0;
//private long currentLength = 0;
private ZeroCopyConsumerListener( File file, String resourceName )
throws FileNotFoundException
{
super( file );
this.resourceName = resourceName;
}
@Override
protected File process( final HttpResponse response, final File file, final ContentType contentType )
throws Exception
{
if ( response.getStatusLine().getStatusCode() != HttpStatus.SC_OK )
{
throw new ClientProtocolException( "Upload failed: " + response.getStatusLine() );
}
long endTime = System.currentTimeMillis();
log.info( "end of transfer file {} {} kb: {}s", resourceName, this.totalLength / 1024,
( endTime - startTime ) / 1000 );
return file;
}
@Override
protected void onContentReceived( ContentDecoder decoder, IOControl ioControl )
throws IOException
{
if ( decoder instanceof LengthDelimitedDecoder )
{
LengthDelimitedDecoder ldl = LengthDelimitedDecoder.class.cast( decoder );
long len = getLen( ldl );
if ( len > -1 )
{
log.debug( "transfer of {} : {}/{}", resourceName, len / 1024, this.totalLength / 1024 );
}
}
super.onContentReceived( decoder, ioControl );
}
@Override
protected void onResponseReceived( HttpResponse response )
{
this.startTime = System.currentTimeMillis();
super.onResponseReceived( response );
this.totalLength = response.getEntity().getContentLength();
log.info( "start transfer of {}, contentLength: {}", resourceName, this.totalLength / 1024 );
}
@Override
protected void onEntityEnclosed( HttpEntity entity, ContentType contentType )
throws IOException
{
super.onEntityEnclosed( entity, contentType );
}
private long getLen( LengthDelimitedDecoder ldl )
{
try
{
Field lenField = LengthDelimitedDecoder.class.getDeclaredField( "len" );
lenField.setAccessible( true );
long len = (Long) lenField.get( ldl );
return len;
}
catch ( NoSuchFieldException e )
{
log.debug( e.getMessage(), e );
return -1;
}
catch ( IllegalAccessException e )
{
log.debug( e.getMessage(), e );
return -1;
}
}
}
private static class ZeroCopyResourceFetcher
implements ResourceFetcher
{
Logger log;
File tempIndexDirectory;
final RemoteRepository remoteRepository;
CloseableHttpAsyncClient httpclient;
String baseIndexUrl;
private ZeroCopyResourceFetcher( Logger log, File tempIndexDirectory, RemoteRepository remoteRepository,
CloseableHttpAsyncClient httpclient, String baseIndexUrl )
{
this.log = log;
this.tempIndexDirectory = tempIndexDirectory;
this.remoteRepository = remoteRepository;
this.httpclient = httpclient;
this.baseIndexUrl = baseIndexUrl;
}
public void connect( String id, String url )
throws IOException
{
//no op
}
public void disconnect()
throws IOException
{
// no op
}
public InputStream retrieve( final String name )
throws IOException
{
log.info( "index update retrieve file, name:{}", name );
File file = new File( tempIndexDirectory, name );
if ( file.exists() )
{
file.delete();
}
file.deleteOnExit();
ZeroCopyConsumer<File> consumer = new ZeroCopyConsumerListener( file, name );
URL targetUrl = new URL( this.baseIndexUrl );
final HttpHost targetHost = new HttpHost( targetUrl.getHost(), targetUrl.getPort() );
Future<File> httpResponseFuture = httpclient.execute( new HttpAsyncRequestProducer()
{
@Override
public HttpHost getTarget()
{
return targetHost;
}
@Override
public HttpRequest generateRequest()
throws IOException, HttpException
{
StringBuilder url = new StringBuilder( baseIndexUrl );
if ( !StringUtils.endsWith( baseIndexUrl, "/" ) )
{
url.append( '/' );
}
HttpGet httpGet = new HttpGet( url.append( addParameters( name, remoteRepository ) ).toString() );
return httpGet;
}
@Override
public void produceContent( ContentEncoder encoder, IOControl ioctrl )
throws IOException
{
// no op
}
@Override
public void requestCompleted( HttpContext context )
{
log.debug( "requestCompleted" );
}
@Override
public void failed( Exception ex )
{
log.error( "http request failed", ex );
}
@Override
public boolean isRepeatable()
{
log.debug( "isRepeatable" );
return true;
}
@Override
public void resetRequest()
throws IOException
{
log.debug( "resetRequest" );
}
@Override
public void close()
throws IOException
{
log.debug( "close" );
}
}, consumer, null );
try
{
file = httpResponseFuture.get( this.remoteRepository.getTimeout(), TimeUnit.SECONDS );
}
catch ( InterruptedException e )
{
throw new IOException( e.getMessage(), e );
}
catch ( ExecutionException e )
{
throw new IOException( e.getMessage(), e );
}
catch ( TimeoutException e )
{
throw new IOException( e.getMessage(), e );
}
return new FileInputStream( file );
}
}
// FIXME remove crappy copy/paste
protected static String addParameters( String path, RemoteRepository remoteRepository )
{
if ( remoteRepository.getExtraParameters().isEmpty() )
{
return path;
}
boolean question = false;
StringBuilder res = new StringBuilder( path == null ? "" : path );
for ( Map.Entry<String, String> entry : remoteRepository.getExtraParameters().entrySet() )
{
if ( !question )
{
res.append( '?' ).append( entry.getKey() ).append( '=' ).append( entry.getValue() );
}
}
return res.toString();
}
}
|
fix timeout
git-svn-id: 5a9cb29c8d7fce18aac47241089437545778aaf0@1539888 13f79535-47bb-0310-9956-ffa450edef68
|
archiva-modules/archiva-scheduler/archiva-scheduler-indexing/src/main/java/org/apache/archiva/scheduler/indexing/DownloadRemoteIndexTask.java
|
fix timeout
|
<ide><path>rchiva-modules/archiva-scheduler/archiva-scheduler-indexing/src/main/java/org/apache/archiva/scheduler/indexing/DownloadRemoteIndexTask.java
<ide> }, consumer, null );
<ide> try
<ide> {
<del> file = httpResponseFuture.get( this.remoteRepository.getTimeout(), TimeUnit.SECONDS );
<add> int timeOut = this.remoteRepository.getRemoteDownloadTimeout();
<add> file = timeOut > 0 ? httpResponseFuture.get( timeOut, TimeUnit.SECONDS ) : httpResponseFuture.get();
<ide> }
<ide> catch ( InterruptedException e )
<ide> {
|
|
Java
|
apache-2.0
|
371dbce1eab748a46b5321a51f99c322025857cc
| 0 |
google/copybara,google/copybara,google/copybara
|
/*
* Copyright (C) 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.copybara.git;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.Iterables;
import com.google.copybara.CannotResolveRevisionException;
import com.google.copybara.Change;
import com.google.copybara.GeneralOptions;
import com.google.copybara.Options;
import com.google.copybara.Origin;
import com.google.copybara.RepoException;
import com.google.copybara.ValidationException;
import com.google.copybara.authoring.Authoring;
import com.google.copybara.git.ChangeReader.GitChange;
import com.google.copybara.git.GitRepository.Submodule;
import com.google.copybara.git.GitRepository.TreeElement;
import com.google.copybara.util.BadExitStatusWithOutputException;
import com.google.copybara.util.CommandOutputWithStatus;
import com.google.copybara.util.CommandUtil;
import com.google.copybara.util.Glob;
import com.google.copybara.util.console.Console;
import com.google.copybara.util.console.Consoles;
import com.google.devtools.build.lib.shell.Command;
import com.google.devtools.build.lib.shell.CommandException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import javax.annotation.Nullable;
/**
* A class for manipulating Git repositories
*/
public class GitOrigin implements Origin<GitRevision> {
enum SubmoduleStrategy {
/** Don't download any submodule. */
NO,
/** Download just the first level of submodules, but don't download recursively */
YES,
/** Download all the submodules recursively */
RECURSIVE
}
static final String GIT_LOG_COMMENT_PREFIX = " ";
final GitRepository repository;
/**
* Url of the repository
*/
protected final String repoUrl;
/**
* Default reference to track
*/
@Nullable
private final String configRef;
private final Console console;
private final GeneralOptions generalOptions;
private final GitRepoType repoType;
private final GitOptions gitOptions;
private final boolean verbose;
@Nullable
private final Map<String, String> environment;
private final SubmoduleStrategy submoduleStrategy;
private final boolean includeBranchCommitLogs;
GitOrigin(GeneralOptions generalOptions, GitRepository repository, String repoUrl,
@Nullable String configRef, GitRepoType repoType, GitOptions gitOptions, boolean verbose,
@Nullable Map<String, String> environment, SubmoduleStrategy submoduleStrategy,
boolean includeBranchCommitLogs) {
this.generalOptions = generalOptions;
this.console = generalOptions.console();
this.repository = checkNotNull(repository);
// Remove a possible trailing '/' so that the url is normalized.
this.repoUrl = checkNotNull(repoUrl).endsWith("/")
? repoUrl.substring(0, repoUrl.length() - 1)
: repoUrl;
this.configRef = configRef;
this.repoType = checkNotNull(repoType);
this.gitOptions = gitOptions;
this.verbose = verbose;
this.environment = environment;
this.submoduleStrategy = submoduleStrategy;
this.includeBranchCommitLogs = includeBranchCommitLogs;
}
public GitRepository getRepository() {
return repository;
}
private class ReaderImpl implements Reader<GitRevision> {
final Glob originFiles;
final Authoring authoring;
ReaderImpl(Glob originFiles, Authoring authoring) {
this.originFiles = checkNotNull(originFiles, "originFiles");
this.authoring = checkNotNull(authoring, "authoring");
}
private ChangeReader.Builder changeReaderBuilder() {
return ChangeReader.Builder.forOrigin(authoring, repository, console, originFiles)
.setVerbose(verbose)
.setIncludeBranchCommitLogs(includeBranchCommitLogs);
}
/**
* Creates a worktree with the contents of the git reference
*
* <p>Any content in the workdir is removed/overwritten.
*/
@Override
public void checkout(GitRevision ref, Path workdir)
throws RepoException, CannotResolveRevisionException {
checkoutRepo(repository, repoUrl, workdir, submoduleStrategy, ref);
if (!Strings.isNullOrEmpty(gitOptions.originCheckoutHook)) {
runCheckoutOrigin(workdir);
}
}
private void checkoutRepo(GitRepository repository, String currentRemoteUrl, Path workdir,
SubmoduleStrategy submoduleStrategy, GitRevision ref)
throws RepoException, CannotResolveRevisionException {
GitRepository repo = repository.withWorkTree(workdir);
repo.simpleCommand("checkout", "-q", "-f", ref.asString());
if (submoduleStrategy == SubmoduleStrategy.NO) {
return;
}
for (Submodule submodule : repo.listSubmodules(currentRemoteUrl)) {
ImmutableList<TreeElement> elements = repo.lsTree(ref, submodule.getPath());
if (elements.size() != 1) {
throw new RepoException(String
.format("Cannot find one tree element for submodule %s."
+ " Found the following elements: %s", submodule.getPath(), elements));
}
TreeElement element = Iterables.getOnlyElement(elements);
Preconditions.checkArgument(element.getPath().equals(submodule.getPath()));
GitRepository subRepo = GitRepository.bareRepoInCache(
submodule.getUrl(), environment, verbose, gitOptions.repoStorage);
subRepo.initGitDir();
subRepo.fetchSingleRef(submodule.getUrl(), submodule.getBranch());
GitRevision submoduleRef = subRepo.resolveReference(element.getRef(), submodule.getName());
Path subdir = workdir.resolve(submodule.getPath());
try {
Files.createDirectories(workdir.resolve(submodule.getPath()));
} catch (IOException e) {
throw new RepoException(String.format(
"Cannot create subdirectory %s for submodule: %s", subdir, submodule));
}
checkoutRepo(subRepo, submodule.getUrl(), subdir,
submoduleStrategy == SubmoduleStrategy.RECURSIVE
? SubmoduleStrategy.RECURSIVE
: SubmoduleStrategy.NO, submoduleRef);
}
}
@Override
public ImmutableList<Change<GitRevision>> changes(@Nullable GitRevision fromRef,
GitRevision toRef) throws RepoException {
String refRange = fromRef == null
? toRef.asString()
: fromRef.asString() + ".." + toRef.asString();
ChangeReader changeReader = changeReaderBuilder().build();
return asChanges(changeReader.run(refRange));
}
@Override
public Change<GitRevision> change(GitRevision ref) throws RepoException {
// The limit=1 flag guarantees that only one change is returned
ChangeReader changeReader = changeReaderBuilder()
.setLimit(1)
.build();
return Iterables.getOnlyElement(asChanges(changeReader.run(ref.asString())));
}
@Override
public void visitChanges(GitRevision start, ChangesVisitor visitor)
throws RepoException, CannotResolveRevisionException {
ChangeReader queryChanges = changeReaderBuilder()
.setLimit(1)
.build();
ImmutableList<GitChange> result = queryChanges.run(start.asString());
if (result.isEmpty()) {
throw new CannotResolveRevisionException("Cannot resolve reference " + start.asString());
}
GitChange current = Iterables.getOnlyElement(result);
while (current != null) {
if (visitor.visit(current.getChange()) == VisitResult.TERMINATE
|| current.getParents().isEmpty()) {
break;
}
String parentRef = current.getParents().get(0).asString();
ImmutableList<GitChange> changes = queryChanges.run(parentRef);
if (changes.isEmpty()) {
throw new CannotResolveRevisionException(String.format(
"'%s' revision cannot be found in the origin. But it is referenced as parent of"
+ " revision '%s'", parentRef, current.getChange().getRevision().asString()));
}
current = Iterables.getOnlyElement(changes);
}
}
}
@Override
public Reader<GitRevision> newReader(Glob originFiles, Authoring authoring) {
return new ReaderImpl(originFiles, authoring);
}
private void runCheckoutOrigin(Path workdir) throws RepoException {
try {
CommandOutputWithStatus result = CommandUtil.executeCommand(
new Command(new String[]{gitOptions.originCheckoutHook},
environment, workdir.toFile()), verbose);
Consoles.logLines(console, "git.origin hook (Stdout): ", result.getStdout());
Consoles.logLines(console, "git.origin hook (Stderr): ", result.getStderr());
} catch (BadExitStatusWithOutputException e) {
Consoles.logLines(console, "git.origin hook (Stdout): ", e.getOutput().getStdout());
Consoles.logLines(console, "git.origin hook (Stderr): ", e.getOutput().getStderr());
throw new RepoException(
"Error executing the git checkout hook: " + gitOptions.originCheckoutHook, e);
} catch (CommandException e) {
throw new RepoException(
"Error executing the git checkout hook: " + gitOptions.originCheckoutHook, e);
}
}
@Override
public GitRevision resolve(@Nullable String reference)
throws RepoException, ValidationException {
console.progress("Git Origin: Initializing local repo");
repository.initGitDir();
String ref;
if (Strings.isNullOrEmpty(reference)) {
if (configRef == null) {
throw new ValidationException("No reference was passed as an command line argument for "
+ repoUrl + " and no default reference was configured in the config file");
}
ref = configRef;
} else {
ref = reference;
}
return repoType.resolveRef(repository, repoUrl, ref, generalOptions);
}
private ImmutableList<Change<GitRevision>> asChanges(ImmutableList<GitChange> gitChanges) {
ImmutableList.Builder<Change<GitRevision>> result = ImmutableList.builder();
for (GitChange gitChange : gitChanges) {
result.add(gitChange.getChange());
}
return result.build();
}
@Override
public String getLabelName() {
return GitRepository.GIT_ORIGIN_REV_ID;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("repoUrl", repoUrl)
.add("ref", configRef)
.add("repoType", repoType)
.toString();
}
/**
* Builds a new {@link GitOrigin}.
*/
static GitOrigin newGitOrigin(Options options, String url, String ref, GitRepoType type, SubmoduleStrategy submoduleStrategy,
boolean includeBranchCommitLogs) {
GitOptions gitConfig = options.get(GitOptions.class);
boolean verbose = options.get(GeneralOptions.class).isVerbose();
Map<String, String> environment = options.get(GeneralOptions.class).getEnvironment();
return new GitOrigin(
options.get(GeneralOptions.class),
GitRepository.bareRepoInCache(url, environment, verbose, gitConfig.repoStorage),
url, ref, type, options.get(GitOptions.class), verbose, environment, submoduleStrategy,
includeBranchCommitLogs);
}
@Override
public ImmutableSetMultimap<String, String> describe(@Nullable Glob originFiles) {
ImmutableSetMultimap.Builder<String, String> builder =
new ImmutableSetMultimap.Builder<String, String>()
.put("type", "git.origin")
.put("repoType", repoType.name())
.put("url", repoUrl)
.put("submodules", submoduleStrategy.name());
if (configRef != null) {
builder.put("ref", configRef);
}
return builder.build();
}
}
|
java/com/google/copybara/git/GitOrigin.java
|
/*
* Copyright (C) 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.copybara.git;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.Iterables;
import com.google.copybara.CannotResolveRevisionException;
import com.google.copybara.Change;
import com.google.copybara.GeneralOptions;
import com.google.copybara.Options;
import com.google.copybara.Origin;
import com.google.copybara.RepoException;
import com.google.copybara.ValidationException;
import com.google.copybara.authoring.Authoring;
import com.google.copybara.git.ChangeReader.GitChange;
import com.google.copybara.git.GitRepository.Submodule;
import com.google.copybara.git.GitRepository.TreeElement;
import com.google.copybara.util.BadExitStatusWithOutputException;
import com.google.copybara.util.CommandOutputWithStatus;
import com.google.copybara.util.CommandUtil;
import com.google.copybara.util.Glob;
import com.google.copybara.util.console.Console;
import com.google.copybara.util.console.Consoles;
import com.google.devtools.build.lib.shell.Command;
import com.google.devtools.build.lib.shell.CommandException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import javax.annotation.Nullable;
/**
* A class for manipulating Git repositories
*/
public class GitOrigin implements Origin<GitRevision> {
enum SubmoduleStrategy {
/** Don't download any submodule. */
NO,
/** Download just the first level of submodules, but don't download recursively */
YES,
/** Download all the submodules recursively */
RECURSIVE
}
static final String GIT_LOG_COMMENT_PREFIX = " ";
final GitRepository repository;
/**
* Url of the repository
*/
protected final String repoUrl;
/**
* Default reference to track
*/
@Nullable
private final String configRef;
private final Console console;
private final GeneralOptions generalOptions;
private final GitRepoType repoType;
private final GitOptions gitOptions;
private final boolean verbose;
@Nullable
private final Map<String, String> environment;
private final SubmoduleStrategy submoduleStrategy;
private final boolean includeBranchCommitLogs;
GitOrigin(GeneralOptions generalOptions, GitRepository repository, String repoUrl,
@Nullable String configRef, GitRepoType repoType, GitOptions gitOptions, boolean verbose,
@Nullable Map<String, String> environment, SubmoduleStrategy submoduleStrategy,
boolean includeBranchCommitLogs) {
this.generalOptions = generalOptions;
this.console = generalOptions.console();
this.repository = checkNotNull(repository);
// Remove a possible trailing '/' so that the url is normalized.
this.repoUrl = checkNotNull(repoUrl).endsWith("/")
? repoUrl.substring(0, repoUrl.length() - 1)
: repoUrl;
this.configRef = configRef;
this.repoType = checkNotNull(repoType);
this.gitOptions = gitOptions;
this.verbose = verbose;
this.environment = environment;
this.submoduleStrategy = submoduleStrategy;
this.includeBranchCommitLogs = includeBranchCommitLogs;
}
public GitRepository getRepository() {
return repository;
}
private class ReaderImpl implements Reader<GitRevision> {
final Glob originFiles;
final Authoring authoring;
ReaderImpl(Glob originFiles, Authoring authoring) {
this.originFiles = checkNotNull(originFiles, "originFiles");
this.authoring = checkNotNull(authoring, "authoring");
}
private ChangeReader.Builder changeReaderBuilder() {
return ChangeReader.Builder.forOrigin(authoring, repository, console, originFiles)
.setVerbose(verbose)
.setIncludeBranchCommitLogs(includeBranchCommitLogs);
}
/**
* Creates a worktree with the contents of the git reference
*
* <p>Any content in the workdir is removed/overwritten.
*/
@Override
public void checkout(GitRevision ref, Path workdir)
throws RepoException, CannotResolveRevisionException {
checkoutRepo(repository, repoUrl, workdir, submoduleStrategy, ref);
if (!Strings.isNullOrEmpty(gitOptions.originCheckoutHook)) {
runCheckoutOrigin(workdir);
}
}
private void checkoutRepo(GitRepository repository, String currentRemoteUrl, Path workdir,
SubmoduleStrategy submoduleStrategy, GitRevision ref)
throws RepoException, CannotResolveRevisionException {
GitRepository repo = repository.withWorkTree(workdir);
repo.simpleCommand("checkout", "-q", "-f", ref.asString());
if (submoduleStrategy == SubmoduleStrategy.NO) {
return;
}
for (Submodule submodule : repo.listSubmodules(currentRemoteUrl)) {
ImmutableList<TreeElement> elements = repo.lsTree(ref, submodule.getPath());
if (elements.size() != 1) {
throw new RepoException(String
.format("Cannot find one tree element for submodule %s."
+ " Found the following elements: %s", submodule.getPath(), elements));
}
TreeElement element = Iterables.getOnlyElement(elements);
Preconditions.checkArgument(element.getPath().equals(submodule.getPath()));
GitRepository subRepo = GitRepository.bareRepoInCache(
submodule.getUrl(), environment, verbose, gitOptions.repoStorage);
subRepo.initGitDir();
subRepo.fetchSingleRef(submodule.getUrl(), submodule.getBranch());
GitRevision submoduleRef = subRepo.resolveReference(element.getRef(), submodule.getName());
Path subdir = workdir.resolve(submodule.getPath());
try {
Files.createDirectories(workdir.resolve(submodule.getPath()));
} catch (IOException e) {
throw new RepoException(String.format(
"Cannot create subdirectory %s for submodule: %s", subdir, submodule));
}
checkoutRepo(subRepo, submodule.getUrl(), subdir,
submoduleStrategy == SubmoduleStrategy.RECURSIVE
? SubmoduleStrategy.RECURSIVE
: SubmoduleStrategy.NO, submoduleRef);
}
}
@Override
public ImmutableList<Change<GitRevision>> changes(@Nullable GitRevision fromRef,
GitRevision toRef) throws RepoException {
String refRange = fromRef == null
? toRef.asString()
: fromRef.asString() + ".." + toRef.asString();
ChangeReader changeReader = changeReaderBuilder().build();
return asChanges(changeReader.run(refRange));
}
@Override
public Change<GitRevision> change(GitRevision ref) throws RepoException {
// The limit=1 flag guarantees that only one change is returned
ChangeReader changeReader = changeReaderBuilder()
.setLimit(1)
.build();
return Iterables.getOnlyElement(asChanges(changeReader.run(ref.asString())));
}
@Override
public void visitChanges(GitRevision start, ChangesVisitor visitor)
throws RepoException, CannotResolveRevisionException {
ChangeReader queryChanges = changeReaderBuilder()
.setLimit(1)
.build();
ImmutableList<GitChange> result = queryChanges.run(start.asString());
if (result.isEmpty()) {
throw new CannotResolveRevisionException("Cannot resolve reference " + start.asString());
}
GitChange current = Iterables.getOnlyElement(result);
while (current != null) {
if (visitor.visit(current.getChange()) == VisitResult.TERMINATE
|| current.getParents().isEmpty()) {
break;
}
current =
Iterables.getOnlyElement(queryChanges.run(current.getParents().get(0).asString()));
}
}
}
@Override
public Reader<GitRevision> newReader(Glob originFiles, Authoring authoring) {
return new ReaderImpl(originFiles, authoring);
}
private void runCheckoutOrigin(Path workdir) throws RepoException {
try {
CommandOutputWithStatus result = CommandUtil.executeCommand(
new Command(new String[]{gitOptions.originCheckoutHook},
environment, workdir.toFile()), verbose);
Consoles.logLines(console, "git.origin hook (Stdout): ", result.getStdout());
Consoles.logLines(console, "git.origin hook (Stderr): ", result.getStderr());
} catch (BadExitStatusWithOutputException e) {
Consoles.logLines(console, "git.origin hook (Stdout): ", e.getOutput().getStdout());
Consoles.logLines(console, "git.origin hook (Stderr): ", e.getOutput().getStderr());
throw new RepoException(
"Error executing the git checkout hook: " + gitOptions.originCheckoutHook, e);
} catch (CommandException e) {
throw new RepoException(
"Error executing the git checkout hook: " + gitOptions.originCheckoutHook, e);
}
}
@Override
public GitRevision resolve(@Nullable String reference)
throws RepoException, ValidationException {
console.progress("Git Origin: Initializing local repo");
repository.initGitDir();
String ref;
if (Strings.isNullOrEmpty(reference)) {
if (configRef == null) {
throw new ValidationException("No reference was passed as an command line argument for "
+ repoUrl + " and no default reference was configured in the config file");
}
ref = configRef;
} else {
ref = reference;
}
return repoType.resolveRef(repository, repoUrl, ref, generalOptions);
}
private ImmutableList<Change<GitRevision>> asChanges(ImmutableList<GitChange> gitChanges) {
ImmutableList.Builder<Change<GitRevision>> result = ImmutableList.builder();
for (GitChange gitChange : gitChanges) {
result.add(gitChange.getChange());
}
return result.build();
}
@Override
public String getLabelName() {
return GitRepository.GIT_ORIGIN_REV_ID;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("repoUrl", repoUrl)
.add("ref", configRef)
.add("repoType", repoType)
.toString();
}
/**
* Builds a new {@link GitOrigin}.
*/
static GitOrigin newGitOrigin(Options options, String url, String ref, GitRepoType type, SubmoduleStrategy submoduleStrategy,
boolean includeBranchCommitLogs) {
GitOptions gitConfig = options.get(GitOptions.class);
boolean verbose = options.get(GeneralOptions.class).isVerbose();
Map<String, String> environment = options.get(GeneralOptions.class).getEnvironment();
return new GitOrigin(
options.get(GeneralOptions.class),
GitRepository.bareRepoInCache(url, environment, verbose, gitConfig.repoStorage),
url, ref, type, options.get(GitOptions.class), verbose, environment, submoduleStrategy,
includeBranchCommitLogs);
}
@Override
public ImmutableSetMultimap<String, String> describe(@Nullable Glob originFiles) {
ImmutableSetMultimap.Builder<String, String> builder =
new ImmutableSetMultimap.Builder<String, String>()
.put("type", "git.origin")
.put("repoType", repoType.name())
.put("url", repoUrl)
.put("submodules", submoduleStrategy.name());
if (configRef != null) {
builder.put("ref", configRef);
}
return builder.build();
}
}
|
Added better error if parent SHA-1 cannot be found
There are scenarios where the parent cannot be found. For example in
a swallow clone.
BUG=37940397
Change-Id: I65931390c5bf5114eb6eff2d0a763f7de332041b
|
java/com/google/copybara/git/GitOrigin.java
|
Added better error if parent SHA-1 cannot be found
|
<ide><path>ava/com/google/copybara/git/GitOrigin.java
<ide> || current.getParents().isEmpty()) {
<ide> break;
<ide> }
<del> current =
<del> Iterables.getOnlyElement(queryChanges.run(current.getParents().get(0).asString()));
<add> String parentRef = current.getParents().get(0).asString();
<add> ImmutableList<GitChange> changes = queryChanges.run(parentRef);
<add> if (changes.isEmpty()) {
<add> throw new CannotResolveRevisionException(String.format(
<add> "'%s' revision cannot be found in the origin. But it is referenced as parent of"
<add> + " revision '%s'", parentRef, current.getChange().getRevision().asString()));
<add> }
<add> current = Iterables.getOnlyElement(changes);
<ide> }
<ide> }
<ide> }
|
|
JavaScript
|
agpl-3.0
|
a47fbe1fa6c721cc4377519c4a6c2c8978e219ce
| 0 |
Trifido/proyecto,Trifido/proyecto
|
//Variables
var activeCameras = 0;
var maxCameras = 4;
var selectedCamera = 0;
//Funcion para cargar una camara nueva
function loadNewCamera(){
if (activeCameras >= maxCameras || !RoomInit)
return;
else {
activePoints.push(0);
activeCameras += 1;
//Crear una camara
var img = $('<img/>', { src : './img/camera/camera.png', alt : 'Image', class: 'img-responsive', onclick : 'loadCamera(' + activeCameras + ')' });
var a = $('<a/>', {});
var div = $('<div/>', {class: 'col-xs-3', id : 'camera'+activeCameras });
//Aniadir la camara
$('#cameras').append(div.append(a.append(img)));
newCamera = new Camera('camara'+activeCameras, './img/camera/cameraT.png', 0, 0);
loadCamera(activeCameras);
}
$('#btnAddPoint').removeAttr('disabled');
$('#btnRemPoint').attr('disabled','disabled');
}
//Funcion para seleccionar una camara ya creada
function loadCamera( id ){
selectedCamera = id;
//Actualizar el canvas
updateCamera();
updatePoints();
updateLines();
//Seleccionar en el menú
updateCameraBorder( id );
// Actualizar la ficha
// Camara
$('.camera').each(function (i, obj) { //Buscar el objeto SVG
var aux = obj.getAttributeNS(null, 'nombre').substr(6, 1); //Indice
if (selectedCamera == aux) updateFileCoords('camera', obj.getAttributeNS(null, 'cX'), obj.getAttributeNS(null, 'cY'));
});
//Puntos
$('#pointAccordion').empty(); //Limpia todos los hijos
for (i = 0; i < activePoints[selectedCamera-1]; i++) //Crea los hijos correspondientes (no se actualizan aun)
createFilePoint(i+1);
// Actualizar botones de la interfaz
if (activePoints[selectedCamera-1] > 0)
$('#btnRemPoint').removeAttr('disabled');
else
$('#btnRemPoint').attr('disabled','disabled');
}
function removeCamera( id ) {
$('#camera'+id).remove();
updateCameraIndex( id );
activeCameras -= 1;
activePoints.splice( id-1 , 1 );
if (selectedCamera == id)
loadCamera(1);
if (activeCameras == 0)
$('#btnAddPoint').attr('disabled','disabled');
}
//Activa el borde en el carousel para la cámara activa
function updateCameraBorder( id ){
for (i=1; i<=activeCameras; i++){
$('#camera'+i+' img').css('border', '0px solid #D80000');
}
$('#camera' + id + ' img').css('border', '2px solid #D80000');
}
// Activar los puntos de control correspondientes a la camara cargada
function updateCamera() {
$('.camera').each(function (i, obj) {
var aux = obj.getAttributeNS(null, 'nombre').substr(6, 1); //Indice de la camara a la que pertenece
if (selectedCamera == aux){ // Traer al frente
document.getElementById('camera_level').appendChild(obj);
}
else{ //Llevar al fondo
document.getElementById('hidden_level').appendChild(obj);
}
});
}
// Activar los puntos de control correspondientes a la camara cargada
function updatePoints() {
$('.point').each(function (i, obj) {
var aux = obj.getAttributeNS(null, 'nombre').substr(5, 1); //Indice de la camara a la que pertenece
if (selectedCamera == aux){ // Traer al frente
document.getElementById('point_level').appendChild(obj);
}
else{ //Llevar al fondo
document.getElementById('hidden_level').appendChild(obj);
}
});
}
// Activar los puntos de control correspondientes a la camara cargada
function updateLines() {
$('.line').each(function (i, obj) {
var aux = obj.getAttributeNS(null, 'name').substr(5, 1); //Indice de la linea a la que pertenece
if (selectedCamera == aux){ // Traer al frente
document.getElementById('line_level').appendChild(obj);
}
else{ //Llevar al fondo
document.getElementById('hidden_level').appendChild(obj);
}
});
}
//Cambia los nombres de las etiquetas correspondientes al índice anterior
//Por ejemplo: camara2 -> camara1
function updateCameraIndex( deletedIndex ) {
for (i = deletedIndex; i <= activeCameras; i++) {
var indice = (i - 1);
var nuevoNombre = 'loadCamera(' + indice + ')';
$('#camera' + i + ' img').attr('onclick', nuevoNombre);
nuevoNombre = 'camera' + indice;
$('#camera' + i).attr('id', nuevoNombre);
}
}
|
scripts/loadCamera.js
|
//Variables
var activeCameras = 0;
var maxCameras = 4;
var selectedCamera = 0;
//Funcion para cargar una camara nueva
function loadNewCamera(){
if (activeCameras >= maxCameras || !RoomInit)
return;
else {
activePoints.push(0);
activeCameras += 1;
//Crear una camara
var img = $('<img/>', { src : './img/camera/camera.png', alt : 'Image', class: 'img-responsive', onclick : 'loadCamera(' + activeCameras + ')' });
var a = $('<a/>', {});
var div = $('<div/>', {class: 'col-xs-3', id : 'camera'+activeCameras });
//Aniadir la camara
$('#cameras').append(div.append(a.append(img)));
newCamera = new Camera('camara'+activeCameras, './img/camera/cameraT.png', 0, 0);
loadCamera(activeCameras);
}
$('#btnAddPoint').removeAttr('disabled');
$('#btnRemPoint').attr('disabled','disabled');
}
//Funcion para seleccionar una camara ya creada
function loadCamera( id ){
selectedCamera = id;
//Actualizar el canvas
updateCamera();
updatePoints();
updateLines();
//Seleccionar en el menú
updateCameraBorder( id );
// Actualizar la ficha
// Camara
$('.camera').each(function (i, obj) { //Buscar el objeto SVG
var aux = obj.getAttributeNS(null, 'nombre').substr(6, 1); //Indice
if (selectedCamera == aux) updateFileCoords('camera', obj.getAttributeNS(null, 'cX'), obj.getAttributeNS(null, 'cY'));
});
//Puntos
$('#pointAccordion').empty(); //Limpia todos los hijos
for (i = 0; i < activePoints[selectedCamera-1]; i++) //Crea los hijos correspondientes (no se actualizan aun)
createFilePoint(i+1);
// Actualizar botones de la interfaz
if (activePoints[selectedCamera-1] > 0)
$('#btnRemPoint').removeAttr('disabled');
else
$('#btnRemPoint').attr('disabled','disabled');
}
function removeCamera( id ) {
$('#camera'+id).remove();
updateCameraIndex( id );
if (selectedCamera == id)
loadCamera(1);
activeCameras -= 1;
activePoints.splice( id-1 , 1 );
if (activeCameras == 0)
$('#btnAddPoint').attr('disabled','disabled');
}
//Activa el borde en el carousel para la cámara activa
function updateCameraBorder( id ){
for (i=1; i<=activeCameras; i++){
$('#camera'+i+' img').css('border', '0px solid #D80000');
}
$('#camera' + id + ' img').css('border', '2px solid #D80000');
}
// Activar los puntos de control correspondientes a la camara cargada
function updateCamera() {
$('.camera').each(function (i, obj) {
var aux = obj.getAttributeNS(null, 'nombre').substr(6, 1); //Indice de la camara a la que pertenece
if (selectedCamera == aux){ // Traer al frente
document.getElementById('camera_level').appendChild(obj);
}
else{ //Llevar al fondo
document.getElementById('hidden_level').appendChild(obj);
}
});
}
// Activar los puntos de control correspondientes a la camara cargada
function updatePoints() {
$('.point').each(function (i, obj) {
var aux = obj.getAttributeNS(null, 'nombre').substr(5, 1); //Indice de la camara a la que pertenece
if (selectedCamera == aux){ // Traer al frente
document.getElementById('point_level').appendChild(obj);
}
else{ //Llevar al fondo
document.getElementById('hidden_level').appendChild(obj);
}
});
}
// Activar los puntos de control correspondientes a la camara cargada
function updateLines() {
$('.line').each(function (i, obj) {
var aux = obj.getAttributeNS(null, 'name').substr(5, 1); //Indice de la linea a la que pertenece
if (selectedCamera == aux){ // Traer al frente
document.getElementById('line_level').appendChild(obj);
}
else{ //Llevar al fondo
document.getElementById('hidden_level').appendChild(obj);
}
});
}
//Cambia los nombres de las etiquetas correspondientes al índice anterior
//Por ejemplo: camara2 -> camara1
function updateCameraIndex( deletedIndex ) {
for (i = deletedIndex; i <= activeCameras; i++) {
var indice = (i - 1);
var nuevoNombre = 'loadCamera(' + indice + ')';
$('#camera' + i + ' img').attr('onclick', nuevoNombre);
nuevoNombre = 'camera' + indice;
$('#camera' + i).attr('id', nuevoNombre);
}
}
|
Error al borrar primera camara
|
scripts/loadCamera.js
|
Error al borrar primera camara
|
<ide><path>cripts/loadCamera.js
<ide> });
<ide> //Puntos
<ide> $('#pointAccordion').empty(); //Limpia todos los hijos
<add>
<ide> for (i = 0; i < activePoints[selectedCamera-1]; i++) //Crea los hijos correspondientes (no se actualizan aun)
<ide> createFilePoint(i+1);
<ide>
<ide>
<ide> updateCameraIndex( id );
<ide>
<add> activeCameras -= 1;
<add> activePoints.splice( id-1 , 1 );
<add>
<ide> if (selectedCamera == id)
<ide> loadCamera(1);
<del>
<del> activeCameras -= 1;
<del> activePoints.splice( id-1 , 1 );
<ide>
<ide> if (activeCameras == 0)
<ide> $('#btnAddPoint').attr('disabled','disabled');
|
|
Java
|
apache-2.0
|
89b706bcc8cfda5ed6add7ce9d8558001e97cf3f
| 0 |
FabricMC/fabric-base
|
/*
* Copyright 2016 FabricMC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.fabricmc.loader.impl.util;
import java.io.File;
import java.net.JarURLConnection;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Path;
import java.nio.file.Paths;
public final class UrlUtil {
private UrlUtil() { }
public static URL getSource(String filename, URL resourceURL) throws UrlConversionException {
URL codeSourceURL;
try {
URLConnection connection = resourceURL.openConnection();
if (connection instanceof JarURLConnection) {
codeSourceURL = ((JarURLConnection) connection).getJarFileURL();
} else {
String path = resourceURL.getPath();
if (path.endsWith(filename)) {
codeSourceURL = new URL(resourceURL.getProtocol(), resourceURL.getHost(), resourceURL.getPort(), path.substring(0, path.length() - filename.length()));
} else {
throw new UrlConversionException("Could not figure out code source for file '" + filename + "' and URL '" + resourceURL + "'!");
}
}
} catch (Exception e) {
throw new UrlConversionException(e);
}
return codeSourceURL;
}
public static Path getSourcePath(String filename, URL resourceURL) throws UrlConversionException {
try {
return asPath(getSource(filename, resourceURL));
} catch (URISyntaxException e) {
throw new UrlConversionException(e);
}
}
public static Path asPath(URL url) throws URISyntaxException {
return Paths.get(url.toURI());
}
public static URL asUrl(File file) throws MalformedURLException {
return file.toURI().toURL();
}
public static URL asUrl(Path path) throws MalformedURLException {
return path.toUri().toURL();
}
}
|
src/main/java/net/fabricmc/loader/impl/util/UrlUtil.java
|
/*
* Copyright 2016 FabricMC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.fabricmc.loader.impl.util;
import java.io.File;
import java.net.JarURLConnection;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Path;
import java.nio.file.Paths;
public final class UrlUtil {
private UrlUtil() { }
public static URL getSource(String filename, URL resourceURL) throws UrlConversionException {
URL codeSourceURL;
try {
URLConnection connection = resourceURL.openConnection();
if (connection instanceof JarURLConnection) {
codeSourceURL = ((JarURLConnection) connection).getJarFileURL();
} else {
String path = resourceURL.getPath();
if (path.endsWith(filename)) {
codeSourceURL = new URL(resourceURL.getProtocol(), resourceURL.getHost(), resourceURL.getPort(), path.substring(0, path.length() - filename.length()));
} else {
throw new UrlConversionException("Could not figure out code source for file '" + filename + "' and URL '" + resourceURL + "'!");
}
}
} catch (Exception e) {
throw new UrlConversionException(e);
}
return codeSourceURL;
}
public static Path getSourcePath(String filename, URL resourceURL) throws UrlConversionException {
try {
return asPath(getSource(filename, resourceURL));
} catch (URISyntaxException e) {
throw new UrlConversionException(e);
}
}
public static File asFile(URL url) throws URISyntaxException {
return new File(url.toURI());
}
public static Path asPath(URL url) throws URISyntaxException {
return Paths.get(url.toURI());
}
public static URL asUrl(File file) throws MalformedURLException {
return file.toURI().toURL();
}
public static URL asUrl(Path path) throws MalformedURLException {
return path.toUri().toURL();
}
}
|
Remove unused and incorrect URI->File conversion method (proper way is Paths.get(uri).toFile())
|
src/main/java/net/fabricmc/loader/impl/util/UrlUtil.java
|
Remove unused and incorrect URI->File conversion method (proper way is Paths.get(uri).toFile())
|
<ide><path>rc/main/java/net/fabricmc/loader/impl/util/UrlUtil.java
<ide> }
<ide> }
<ide>
<del> public static File asFile(URL url) throws URISyntaxException {
<del> return new File(url.toURI());
<del> }
<del>
<ide> public static Path asPath(URL url) throws URISyntaxException {
<ide> return Paths.get(url.toURI());
<ide> }
|
|
JavaScript
|
mit
|
82279672de6046426b18d24ae42d6b55a94ba319
| 0 |
mikaelbr/node-notifier,mikaelbr/node-notifier
|
var NotificationCenter = require('../notifiers/notificationcenter');
var Growl = require('../notifiers/growl');
var utils = require('../lib/utils');
var path = require('path');
var os = require('os');
var fs = require('fs');
var testUtils = require('./_test-utils');
var notifier = null;
var originalUtils = utils.fileCommandJson;
var originalMacVersion = utils.isMountainLion;
var originalType = os.type;
describe('Mac fallback', function() {
var original = utils.isMountainLion;
var originalMac = utils.isMac;
afterEach(function() {
utils.isMountainLion = original;
utils.isMac = originalMac;
});
it(
'should default to Growl notification if older Mac OSX than 10.8',
function(done) {
utils.isMountainLion = function() {
return false;
};
utils.isMac = function() {
return true;
};
var n = new NotificationCenter({ withFallback: true });
n.notify({ message: 'Hello World' }, function(_, response) {
expect(this).toBeInstanceOf(Growl);
done();
});
}
);
it(
'should not fallback to Growl notification if withFallback is false',
function(done) {
utils.isMountainLion = function() {
return false;
};
utils.isMac = function() {
return true;
};
var n = new NotificationCenter();
n.notify({ message: 'Hello World' }, function(err, response) {
expect(err).toBeTruthy();
expect(this).not.toBeInstanceOf(Growl);
done();
});
}
);
});
describe('terminal-notifier', function() {
beforeEach(function() {
os.type = function() {
return 'Darwin';
};
utils.isMountainLion = function() {
return true;
};
});
beforeEach(function() {
notifier = new NotificationCenter();
});
afterEach(function() {
os.type = originalType;
utils.isMountainLion = originalMacVersion;
});
// Simulate async operation, move to end of message queue.
function asyncify (fn) {
return function () {
var args = arguments;
setTimeout(function () {
fn.apply(null, args);
}, 0);
};
}
describe('#notify()', function() {
beforeEach(function() {
utils.fileCommandJson = asyncify(function(n, o, cb) {
cb(null, '');
});
});
afterEach(function() {
utils.fileCommandJson = originalUtils;
});
it('should notify with a message', function(done) {
notifier.notify({ message: 'Hello World' }, function(err, response) {
expect(err).toBeNull();
done();
});
});
it('should be chainable', function(done) {
notifier
.notify({ message: 'First test' })
.notify({ message: 'Second test' }, function(err, response) {
expect(err).toBeNull();
done();
});
});
it('should be able to list all notifications', function(done) {
utils.fileCommandJson = asyncify(function(n, o, cb) {
cb(
null,
fs
.readFileSync(path.join(__dirname, '/fixture/listAll.txt'))
.toString()
);
});
notifier.notify({ list: 'ALL' }, function(_, response) {
expect(response).toBeTruthy();
done();
});
});
it('should be able to remove all messages', function(done) {
utils.fileCommandJson = asyncify(function(n, o, cb) {
cb(
null,
fs
.readFileSync(path.join(__dirname, '/fixture/removeAll.txt'))
.toString()
);
});
notifier.notify({ remove: 'ALL' }, function(_, response) {
expect(response).toBeTruthy();
utils.fileCommandJson = asyncify(function(n, o, cb) {
cb(null, '');
});
notifier.notify({ list: 'ALL' }, function(_, response) {
expect(response).toBeFalsy();
done();
});
});
});
});
describe('arguments', function() {
beforeEach(function() {
this.original = utils.fileCommandJson;
});
afterEach(function() {
utils.fileCommandJson = this.original;
});
function expectArgsListToBe(expected, done) {
utils.fileCommandJson = asyncify(function(notifier, argsList, callback) {
expect(argsList).toEqual(expected);
callback();
done();
});
}
it('should allow for non-sensical arguments (fail gracefully)', function(
done
) {
var expected = [
'-title',
'"title"',
'-message',
'"body"',
'-tullball',
'"notValid"',
'-json',
'"true"'
];
expectArgsListToBe(expected, done);
var notifier = new NotificationCenter();
notifier.isNotifyChecked = true;
notifier.hasNotifier = true;
notifier.notify({
title: 'title',
message: 'body',
tullball: 'notValid'
});
});
it(
'should validate and transform sound to default sound if Windows sound is selected',
function(done) {
utils.fileCommandJson = asyncify(function(notifier, argsList, callback) {
expect(testUtils.getOptionValue(argsList, '-title')).toBe('"Heya"');
expect(testUtils.getOptionValue(argsList, '-sound')).toBe('"Bottle"');
callback();
done();
});
var notifier = new NotificationCenter();
notifier.notify({
title: 'Heya',
message: 'foo bar',
sound: 'Notification.Default'
});
}
);
it('should convert list of actions to flat list', function(done) {
var expected = [
'-title',
'"title \\"message\\""',
'-message',
'"body \\"message\\""',
'-actions',
'foo,bar,baz "foo" bar',
'-json',
'"true"'
];
expectArgsListToBe(expected, done);
var notifier = new NotificationCenter();
notifier.isNotifyChecked = true;
notifier.hasNotifier = true;
notifier.notify({
title: 'title "message"',
message: 'body "message"',
actions: [ 'foo', 'bar', 'baz "foo" bar' ]
});
});
it('should still support wait flag with default timeout', function(done) {
var expected = [
'-title',
'"Title"',
'-message',
'"Message"',
'-timeout',
'"5"',
'-json',
'"true"'
];
expectArgsListToBe(expected, done);
var notifier = new NotificationCenter();
notifier.isNotifyChecked = true;
notifier.hasNotifier = true;
notifier.notify({ title: 'Title', message: 'Message', wait: true });
});
it('should let timeout set precedence over wait', function(done) {
var expected = [
'-title',
'"Title"',
'-message',
'"Message"',
'-timeout',
'"10"',
'-json',
'"true"'
];
expectArgsListToBe(expected, done);
var notifier = new NotificationCenter();
notifier.isNotifyChecked = true;
notifier.hasNotifier = true;
notifier.notify({
title: 'Title',
message: 'Message',
wait: true,
timeout: 10
});
});
it('should escape all title and message', function(done) {
var expected = [
'-title',
'"title \\"message\\""',
'-message',
'"body \\"message\\""',
'-tullball',
'"notValid"',
'-json',
'"true"'
];
expectArgsListToBe(expected, done);
var notifier = new NotificationCenter();
notifier.isNotifyChecked = true;
notifier.hasNotifier = true;
notifier.notify({
title: 'title "message"',
message: 'body "message"',
tullball: 'notValid'
});
});
});
});
|
test/terminal-notifier.js
|
var NotificationCenter = require('../notifiers/notificationcenter');
var Growl = require('../notifiers/growl');
var utils = require('../lib/utils');
var path = require('path');
var os = require('os');
var fs = require('fs');
var testUtils = require('./_test-utils');
var notifier = null;
var originalUtils = utils.fileCommandJson;
var originalMacVersion = utils.isMountainLion;
var originalType = os.type;
describe('Mac fallback', function() {
var original = utils.isMountainLion;
var originalMac = utils.isMac;
afterEach(function() {
utils.isMountainLion = original;
utils.isMac = originalMac;
});
it(
'should default to Growl notification if older Mac OSX than 10.8',
function(done) {
utils.isMountainLion = function() {
return false;
};
utils.isMac = function() {
return true;
};
var n = new NotificationCenter({ withFallback: true });
n.notify({ message: 'Hello World' }, function(_, response) {
expect(this).toBeInstanceOf(Growl);
done();
});
}
);
it(
'should not fallback to Growl notification if withFallback is false',
function(done) {
utils.isMountainLion = function() {
return false;
};
utils.isMac = function() {
return true;
};
var n = new NotificationCenter();
n.notify({ message: 'Hello World' }, function(err, response) {
expect(err).toBeTruthy();
expect(this).not.toBeInstanceOf(Growl);
done();
});
}
);
});
describe('terminal-notifier', function() {
beforeEach(function() {
os.type = function() {
return 'Darwin';
};
utils.isMountainLion = function() {
return true;
};
});
beforeEach(function() {
notifier = new NotificationCenter();
});
afterEach(function() {
os.type = originalType;
utils.isMountainLion = originalMacVersion;
});
describe('#notify()', function() {
beforeEach(function() {
utils.fileCommandJson = function(n, o, cb) {
cb(null, '');
};
});
afterEach(function() {
utils.fileCommandJson = originalUtils;
});
it('should notify with a message', function(done) {
notifier.notify({ message: 'Hello World' }, function(err, response) {
expect(err).toBeNull();
done();
});
});
it('should be chainable', function(done) {
notifier
.notify({ message: 'First test' })
.notify({ message: 'Second test' }, function(err, response) {
expect(err).toBeNull();
done();
});
});
it('should be able to list all notifications', function(done) {
utils.fileCommandJson = function(n, o, cb) {
cb(
null,
fs
.readFileSync(path.join(__dirname, '/fixture/listAll.txt'))
.toString()
);
};
notifier.notify({ list: 'ALL' }, function(_, response) {
expect(response).toBeTruthy();
done();
});
});
it('should be able to remove all messages', function(done) {
utils.fileCommandJson = function(n, o, cb) {
cb(
null,
fs
.readFileSync(path.join(__dirname, '/fixture/removeAll.txt'))
.toString()
);
};
notifier.notify({ remove: 'ALL' }, function(_, response) {
expect(response).toBeTruthy();
utils.fileCommandJson = function(n, o, cb) {
cb(null, '');
};
notifier.notify({ list: 'ALL' }, function(_, response) {
expect(response).toBeFalsy();
done();
});
});
});
});
describe('arguments', function() {
beforeEach(function() {
this.original = utils.fileCommandJson;
});
afterEach(function() {
utils.fileCommandJson = this.original;
});
function expectArgsListToBe(expected, done) {
utils.fileCommandJson = function(notifier, argsList, callback) {
expect(argsList).toEqual(expected);
done();
};
}
it('should allow for non-sensical arguments (fail gracefully)', function(
done
) {
var expected = [
'-title',
'"title"',
'-message',
'"body"',
'-tullball',
'"notValid"',
'-json',
'"true"'
];
expectArgsListToBe(expected, done);
var notifier = new NotificationCenter();
notifier.isNotifyChecked = true;
notifier.hasNotifier = true;
notifier.notify({
title: 'title',
message: 'body',
tullball: 'notValid'
});
});
it(
'should validate and transform sound to default sound if Windows sound is selected',
function(done) {
utils.fileCommandJson = function(notifier, argsList, callback) {
expect(testUtils.getOptionValue(argsList, '-title')).toBe('"Heya"');
expect(testUtils.getOptionValue(argsList, '-sound')).toBe('"Bottle"');
done();
};
var notifier = new NotificationCenter();
notifier.notify({
title: 'Heya',
message: 'foo bar',
sound: 'Notification.Default'
});
}
);
it('should convert list of actions to flat list', function(done) {
var expected = [
'-title',
'"title \\"message\\""',
'-message',
'"body \\"message\\""',
'-actions',
'foo,bar,baz "foo" bar',
'-json',
'"true"'
];
expectArgsListToBe(expected, done);
var notifier = new NotificationCenter();
notifier.isNotifyChecked = true;
notifier.hasNotifier = true;
notifier.notify({
title: 'title "message"',
message: 'body "message"',
actions: [ 'foo', 'bar', 'baz "foo" bar' ]
});
});
it('should still support wait flag with default timeout', function(done) {
var expected = [
'-title',
'"Title"',
'-message',
'"Message"',
'-timeout',
'"5"',
'-json',
'"true"'
];
expectArgsListToBe(expected, done);
var notifier = new NotificationCenter();
notifier.isNotifyChecked = true;
notifier.hasNotifier = true;
notifier.notify({ title: 'Title', message: 'Message', wait: true });
});
it('should let timeout set precedence over wait', function(done) {
var expected = [
'-title',
'"Title"',
'-message',
'"Message"',
'-timeout',
'"10"',
'-json',
'"true"'
];
expectArgsListToBe(expected, done);
var notifier = new NotificationCenter();
notifier.isNotifyChecked = true;
notifier.hasNotifier = true;
notifier.notify({
title: 'Title',
message: 'Message',
wait: true,
timeout: 10
});
});
it('should escape all title and message', function(done) {
var expected = [
'-title',
'"title \\"message\\""',
'-message',
'"body \\"message\\""',
'-tullball',
'"notValid"',
'-json',
'"true"'
];
expectArgsListToBe(expected, done);
var notifier = new NotificationCenter();
notifier.isNotifyChecked = true;
notifier.hasNotifier = true;
notifier.notify({
title: 'title "message"',
message: 'body "message"',
tullball: 'notValid'
});
});
});
});
|
Fixes tests for memory leak workaround
|
test/terminal-notifier.js
|
Fixes tests for memory leak workaround
|
<ide><path>est/terminal-notifier.js
<ide> utils.isMountainLion = originalMacVersion;
<ide> });
<ide>
<add> // Simulate async operation, move to end of message queue.
<add> function asyncify (fn) {
<add> return function () {
<add> var args = arguments;
<add> setTimeout(function () {
<add> fn.apply(null, args);
<add> }, 0);
<add> };
<add> }
<add>
<ide> describe('#notify()', function() {
<ide> beforeEach(function() {
<del> utils.fileCommandJson = function(n, o, cb) {
<add> utils.fileCommandJson = asyncify(function(n, o, cb) {
<ide> cb(null, '');
<del> };
<add> });
<ide> });
<ide>
<ide> afterEach(function() {
<ide> });
<ide>
<ide> it('should be able to list all notifications', function(done) {
<del> utils.fileCommandJson = function(n, o, cb) {
<add> utils.fileCommandJson = asyncify(function(n, o, cb) {
<ide> cb(
<ide> null,
<ide> fs
<ide> .readFileSync(path.join(__dirname, '/fixture/listAll.txt'))
<ide> .toString()
<ide> );
<del> };
<add> });
<ide>
<ide> notifier.notify({ list: 'ALL' }, function(_, response) {
<ide> expect(response).toBeTruthy();
<ide> });
<ide>
<ide> it('should be able to remove all messages', function(done) {
<del> utils.fileCommandJson = function(n, o, cb) {
<add> utils.fileCommandJson = asyncify(function(n, o, cb) {
<ide> cb(
<ide> null,
<ide> fs
<ide> .readFileSync(path.join(__dirname, '/fixture/removeAll.txt'))
<ide> .toString()
<ide> );
<del> };
<add> });
<ide>
<ide> notifier.notify({ remove: 'ALL' }, function(_, response) {
<ide> expect(response).toBeTruthy();
<ide>
<del> utils.fileCommandJson = function(n, o, cb) {
<add> utils.fileCommandJson = asyncify(function(n, o, cb) {
<ide> cb(null, '');
<del> };
<add> });
<ide>
<ide> notifier.notify({ list: 'ALL' }, function(_, response) {
<ide> expect(response).toBeFalsy();
<ide> });
<ide>
<ide> function expectArgsListToBe(expected, done) {
<del> utils.fileCommandJson = function(notifier, argsList, callback) {
<add> utils.fileCommandJson = asyncify(function(notifier, argsList, callback) {
<ide> expect(argsList).toEqual(expected);
<del> done();
<del> };
<add> callback();
<add> done();
<add> });
<ide> }
<ide>
<ide> it('should allow for non-sensical arguments (fail gracefully)', function(
<ide> it(
<ide> 'should validate and transform sound to default sound if Windows sound is selected',
<ide> function(done) {
<del> utils.fileCommandJson = function(notifier, argsList, callback) {
<add> utils.fileCommandJson = asyncify(function(notifier, argsList, callback) {
<ide> expect(testUtils.getOptionValue(argsList, '-title')).toBe('"Heya"');
<ide> expect(testUtils.getOptionValue(argsList, '-sound')).toBe('"Bottle"');
<add> callback();
<ide> done();
<del> };
<add> });
<ide> var notifier = new NotificationCenter();
<ide> notifier.notify({
<ide> title: 'Heya',
|
|
Java
|
mit
|
69344832f80853a6a49191766e99c067bc951f12
| 0 |
jpfiset/n2android_mobile1,jpfiset/n2android_mobile1,jpfiset/n2android_mobile1
|
package ca.carleton.gcrc.n2android_mobile1.activities;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Parcelable;
import android.support.design.widget.NavigationView;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import org.apache.cordova.CordovaActivity;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import ca.carleton.gcrc.n2android_mobile1.R;
import ca.carleton.gcrc.n2android_mobile1.connection.ConnectionInfoDb;
import ca.carleton.gcrc.n2android_mobile1.connection.ConnectionManagementService;
import ca.carleton.gcrc.n2android_mobile1.couchbase.CouchbaseLiteService;
import ca.carleton.gcrc.n2android_mobile1.connection.ConnectionInfo;
import ca.carleton.gcrc.n2android_mobile1.Nunaliit;
import ca.carleton.gcrc.n2android_mobile1.couchbase.CouchbaseManager;
import ca.carleton.gcrc.utils.AtlasPictureSingleton;
/**
* Created by jpfiset on 3/9/16.
*/
public class EmbeddedCordovaActivity extends CordovaActivity {
final protected String TAG = this.getClass().getSimpleName();
private DrawerLayout drawerLayout;
private NavigationView navigationView;
private List<ConnectionInfo> displayedConnections = null;
private boolean manageMode = false;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
CouchbaseLiteService.CouchDbBinder binder = (CouchbaseLiteService.CouchDbBinder) service;
mService = binder.getService();
mBound = true;
serviceReporting(mService);
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
private CouchbaseLiteService mService;
private boolean mBound = false;
ConnectionInfo connectionInfo = null;
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
receiveBroadcast(intent);
}
};
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Bind to CouchbaseLiteService
Intent intent = new Intent(this, CouchbaseLiteService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
// Set by <content src="index.html" /> in config.xml
loadUrl(launchUrl);
drawerLayout = findViewById(R.id.drawer_layout);
drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
@Override
public void onDrawerStateChanged(int newState) {
EmbeddedCordovaActivity.this.manageMode = false;
Menu menu = navigationView.getMenu();
for (int i=0; i<displayedConnections.size(); i++) {
MenuItem item = menu.getItem(i);
ConnectionInfo connInfo = displayedConnections.get(i);
setAtlasInitialsIcon(item, connInfo);
}
}
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {}
@Override
public void onDrawerOpened(View drawerView) {}
@Override
public void onDrawerClosed(View drawerView) {}
});
navigationView = findViewById(R.id.nav_view);
navigationView.setItemIconTintList(null);
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
if (menuItem.getItemId() == 10000) {
synchronizeConnection(connectionInfo);
showProgressBar();
} else if (menuItem.getItemId() == 10001) {
manageMode = !manageMode;
Menu menu = navigationView.getMenu();
for (int i=0; i<displayedConnections.size(); i++) {
MenuItem item = menu.getItem(i);
if (manageMode) {
item.setIcon(R.drawable.ic_trash);
} else {
ConnectionInfo connInfo = displayedConnections.get(i);
setAtlasInitialsIcon(item, connInfo);
}
}
} else if (menuItem.getItemId() == 10002) {
startAddConnectionActivity();
} else if (menuItem.getItemId() < 10000) {
final ConnectionInfo newConnection = displayedConnections.get(menuItem.getItemId());
if (!manageMode) {
if (!connectionInfo.getId().equals(newConnection.getId())) {
startConnectionActivity(newConnection);
} else {
drawerLayout.closeDrawers();
return true;
}
} else {
Log.d(TAG, "Delete Atlas");
AlertDialog.Builder builder = new AlertDialog.Builder(EmbeddedCordovaActivity.this);
builder.setTitle("Remove Account");
builder.setMessage("Are you sure you want to remove the account from your device?");
builder.setPositiveButton("REMOVE", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
deleteConnection(newConnection);
showProgressBar();
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {}
});
final AlertDialog dialog = builder.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialogInterface) {
dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(Color.BLACK);
}
});
dialog.show();
}
}
return true;
}
});
LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
lbm.registerReceiver(
broadcastReceiver,
new IntentFilter(ConnectionManagementService.RESULT_GET_CONNECTION_INFOS)
);
lbm.registerReceiver(
broadcastReceiver,
new IntentFilter(ConnectionManagementService.ERROR_GET_CONNECTION_INFOS)
);
lbm.registerReceiver(
broadcastReceiver,
new IntentFilter(ConnectionManagementService.RESULT_SYNC)
);
lbm.registerReceiver(
broadcastReceiver,
new IntentFilter(ConnectionManagementService.RESULT_DELETE_CONNECTION)
);
lbm.registerReceiver(
broadcastReceiver,
new IntentFilter(ConnectionManagementService.ERROR_DELETE_CONNECTION)
);
// Request for list of connection infos
{
Intent connectionIntent = new Intent(this, ConnectionManagementService.class);
connectionIntent.setAction(ConnectionManagementService.ACTION_GET_CONNECTION_INFOS);
startService(connectionIntent);
}
}
private void showProgressBar() {
appView.getView().setVisibility(View.GONE);
findViewById(R.id.sync_progress).setVisibility(View.VISIBLE);
drawerLayout.closeDrawers();
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
}
@Override
public void onDestroy() {
// Unbind from the service
if (mBound) {
unbindService(mConnection);
mBound = false;
}
LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
lbm.unregisterReceiver(broadcastReceiver);
super.onDestroy();
}
@SuppressLint("ResourceType")
@Override
protected void createViews() {
//Why are we setting a constant as the ID? This should be investigated
appView.getView().setId(100);
appView.getView().setLayoutParams(new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
setContentView(R.layout.activity_cordova);
ViewGroup layout = findViewById(R.id.content_container);
layout.addView(appView.getView(), 0);
retrieveConnection();
if (preferences.contains("BackgroundColor")) {
try {
int backgroundColor = preferences.getInteger("BackgroundColor", Color.BLACK);
// Background of activity:
appView.getView().setBackgroundColor(backgroundColor);
}
catch (NumberFormatException e){
e.printStackTrace();
}
}
appView.getView().requestFocusFromTouch();
}
public void serviceReporting(CouchbaseLiteService service){
retrieveConnection();
}
public ConnectionInfo retrieveConnection(){
if( null == connectionInfo ){
String connectionId = null;
Intent intent = getIntent();
if( null != intent ){
connectionId = intent.getStringExtra(Nunaliit.EXTRA_CONNECTION_ID);
}
if( null != mService && null != connectionId ){
try {
CouchbaseManager couchbaseMgr = mService.getCouchbaseManager();
ConnectionInfoDb infoDb = couchbaseMgr.getConnectionsDb();
connectionInfo = infoDb.getConnectionInfo(connectionId);
} catch(Exception e) {
Log.e(TAG,"Unable to retrieve connection info",e);
}
}
}
configureUI();
return connectionInfo;
}
private void configureUI () {
this.runOnUiThread(new Runnable() {
@Override
public void run() {
TextView atlasNameTextView = findViewById(R.id.atlas_title);
TextView atlasNameTextUrl = findViewById(R.id.atlas_url);
Toolbar toolbar = findViewById(R.id.cordova_toolbar);
if (connectionInfo != null && atlasNameTextView != null && atlasNameTextUrl != null && toolbar != null) {
atlasNameTextView.setText(connectionInfo.getName());
atlasNameTextUrl.setText(connectionInfo.getUrl());
toolbar.setTitle(connectionInfo.getName());
toolbar.setTitleTextColor(Color.WHITE);
toolbar.setNavigationIcon(R.drawable.ic_menu);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!drawerLayout.isDrawerOpen(navigationView) &&
drawerLayout.getDrawerLockMode(navigationView) != DrawerLayout.LOCK_MODE_LOCKED_CLOSED) {
drawerLayout.openDrawer(navigationView);
} else {
drawerLayout.closeDrawer(navigationView);
}
}
});
}
}
});
}
public CouchbaseLiteService getCouchDbService(){
return mService;
}
protected void receiveBroadcast(Intent intent){
Log.v(TAG, "Received broadcast :" + intent.getAction() + Nunaliit.threadId());
if( ConnectionManagementService.RESULT_GET_CONNECTION_INFOS.equals(intent.getAction()) ){
ArrayList<Parcelable> parcelables = intent.getParcelableArrayListExtra(Nunaliit.EXTRA_CONNECTION_INFOS);
List<ConnectionInfo> connectionInfos = new Vector<ConnectionInfo>();
for(Parcelable parcelable : parcelables){
if( parcelable instanceof ConnectionInfo ){
ConnectionInfo connInfo = (ConnectionInfo)parcelable;
connectionInfos.add(connInfo);
}
}
displayedConnections = connectionInfos;
drawList();
retrieveConnection();
} else if (ConnectionManagementService.RESULT_SYNC.equals(intent.getAction())) {
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, navigationView);
startConnectionActivity(connectionInfo);
} else if( ConnectionManagementService.RESULT_DELETE_CONNECTION.equals(intent.getAction()) ){
String connectionId = intent.getStringExtra(Nunaliit.EXTRA_CONNECTION_ID);
if (connectionId.equals(connectionInfo.getId())) {
// If there is another connection other than the old connection
if (displayedConnections.size() > 1) {
ConnectionInfo newConnection = displayedConnections.get(0);
if (newConnection.getId().equals(connectionId)) {
newConnection = displayedConnections.get(1);
}
startConnectionActivity(newConnection);
} else {
startMainActivity();
}
} else {
startConnectionActivity(connectionInfo);
}
} else {
Log.w(TAG, "Ignoring received intent :" + intent.getAction() + Nunaliit.threadId());
}
}
private void drawList() {
if( null != displayedConnections ) {
for (int i = 0, e = displayedConnections.size(); i < e; ++i) {
ConnectionInfo connectionInfo = displayedConnections.get(i);
MenuItem menuItem = navigationView.getMenu().add(Menu.NONE, i, i, connectionInfo.getName());
ConnectionInfo connInfo = displayedConnections.get(i);
setAtlasInitialsIcon(menuItem, connInfo);
}
MenuItem synchronizeAtlasMenuItem = navigationView.getMenu().add(Menu.NONE, 10000, 10000, "Synchronize Atlas");
synchronizeAtlasMenuItem.setIcon(R.drawable.ic_synchronize);
MenuItem manageAtlasMenuItem = navigationView.getMenu().add(Menu.NONE, 10001, 10001, "Manage Atlas");
manageAtlasMenuItem.setIcon(R.drawable.ic_manage);
MenuItem addAtlasMenuItem = navigationView.getMenu().add(Menu.NONE, 10002, 10002, "Add Atlas");
}
}
private void synchronizeConnection(ConnectionInfo connInfo) {
Intent syncIntent = new Intent(this, ConnectionManagementService.class);
syncIntent.setAction(ConnectionManagementService.ACTION_SYNC);
Log.v(TAG, "action:" + syncIntent.getAction() + Nunaliit.threadId());
syncIntent.putExtra(Nunaliit.EXTRA_CONNECTION_ID, connInfo.getId());
startService(syncIntent);
}
public void startMainActivity() {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
private void deleteConnection(ConnectionInfo connInfo) {
Intent intent = new Intent(this, ConnectionManagementService.class);
intent.setAction(ConnectionManagementService.ACTION_DELETE_CONNECTION);
Log.v(TAG, "action:" + intent.getAction() + Nunaliit.threadId());
intent.putExtra(Nunaliit.EXTRA_CONNECTION_ID, connInfo.getId());
startService(intent);
}
public void startConnectionActivity(ConnectionInfo connInfo){
Intent intent = new Intent(this, EmbeddedCordovaActivity.class);
intent.putExtra(Nunaliit.EXTRA_CONNECTION_ID, connInfo.getId());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
private void setAtlasInitialsIcon(MenuItem menuItem, ConnectionInfo connInfo) {
String name = connInfo.getName().length() > 0 ? "" + connInfo.getName().charAt(0) : "";
Bitmap atlasInitial = AtlasPictureSingleton.getInstance().getUserInitialsBitmap(name, 48, this);
Drawable drawable = new BitmapDrawable(getResources(), atlasInitial);
menuItem.setIcon(drawable);
}
public void startAddConnectionActivity(){
Intent intent = new Intent(this, AddConnectionActivity.class);
startActivity(intent);
}
}
|
app/src/main/java/ca/carleton/gcrc/n2android_mobile1/activities/EmbeddedCordovaActivity.java
|
package ca.carleton.gcrc.n2android_mobile1.activities;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Parcelable;
import android.support.design.widget.NavigationView;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import org.apache.cordova.CordovaActivity;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import ca.carleton.gcrc.n2android_mobile1.R;
import ca.carleton.gcrc.n2android_mobile1.connection.ConnectionInfoDb;
import ca.carleton.gcrc.n2android_mobile1.connection.ConnectionManagementService;
import ca.carleton.gcrc.n2android_mobile1.couchbase.CouchbaseLiteService;
import ca.carleton.gcrc.n2android_mobile1.connection.ConnectionInfo;
import ca.carleton.gcrc.n2android_mobile1.Nunaliit;
import ca.carleton.gcrc.n2android_mobile1.couchbase.CouchbaseManager;
import ca.carleton.gcrc.utils.AtlasPictureSingleton;
/**
* Created by jpfiset on 3/9/16.
*/
public class EmbeddedCordovaActivity extends CordovaActivity {
final protected String TAG = this.getClass().getSimpleName();
private DrawerLayout drawerLayout;
private NavigationView navigationView;
private List<ConnectionInfo> displayedConnections = null;
private boolean manageMode = false;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
CouchbaseLiteService.CouchDbBinder binder = (CouchbaseLiteService.CouchDbBinder) service;
mService = binder.getService();
mBound = true;
serviceReporting(mService);
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
private CouchbaseLiteService mService;
private boolean mBound = false;
ConnectionInfo connectionInfo = null;
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
receiveBroadcast(intent);
}
};
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Bind to CouchbaseLiteService
Intent intent = new Intent(this, CouchbaseLiteService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
// Set by <content src="index.html" /> in config.xml
loadUrl(launchUrl);
drawerLayout = findViewById(R.id.drawer_layout);
drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
@Override
public void onDrawerStateChanged(int newState) {
EmbeddedCordovaActivity.this.manageMode = false;
Menu menu = navigationView.getMenu();
for (int i=0; i<displayedConnections.size(); i++) {
MenuItem item = menu.getItem(i);
ConnectionInfo connInfo = displayedConnections.get(i);
setAtlasInitialsIcon(item, connInfo);
}
}
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {}
@Override
public void onDrawerOpened(View drawerView) {}
@Override
public void onDrawerClosed(View drawerView) {}
});
navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
if (menuItem.getItemId() == 10000) {
synchronizeConnection(connectionInfo);
appView.getView().setVisibility(View.GONE);
findViewById(R.id.sync_progress).setVisibility(View.VISIBLE);
drawerLayout.closeDrawers();
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
} else if (menuItem.getItemId() == 10001) {
manageMode = !manageMode;
Menu menu = navigationView.getMenu();
for (int i=0; i<displayedConnections.size(); i++) {
MenuItem item = menu.getItem(i);
if (manageMode) {
item.setIcon(R.drawable.ic_trash);
} else {
ConnectionInfo connInfo = displayedConnections.get(i);
setAtlasInitialsIcon(item, connInfo);
}
}
} else if (menuItem.getItemId() == 10002) {
startAddConnectionActivity();
} else if (menuItem.getItemId() < 10000) {
ConnectionInfo newConnection = displayedConnections.get(menuItem.getItemId());
if (!connectionInfo.getId().equals(newConnection.getId())) {
startConnectionActivity(newConnection);
} else {
drawerLayout.closeDrawers();
}
}
return true;
}
});
LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
lbm.registerReceiver(
broadcastReceiver,
new IntentFilter(ConnectionManagementService.RESULT_GET_CONNECTION_INFOS)
);
lbm.registerReceiver(
broadcastReceiver,
new IntentFilter(ConnectionManagementService.ERROR_GET_CONNECTION_INFOS)
);
lbm.registerReceiver(
broadcastReceiver,
new IntentFilter(ConnectionManagementService.RESULT_SYNC)
);
// Request for list of connection infos
{
Intent connectionIntent = new Intent(this, ConnectionManagementService.class);
connectionIntent.setAction(ConnectionManagementService.ACTION_GET_CONNECTION_INFOS);
startService(connectionIntent);
}
}
@Override
public void onDestroy() {
// Unbind from the service
if (mBound) {
unbindService(mConnection);
mBound = false;
}
LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
lbm.unregisterReceiver(broadcastReceiver);
super.onDestroy();
}
@SuppressLint("ResourceType")
@Override
protected void createViews() {
//Why are we setting a constant as the ID? This should be investigated
appView.getView().setId(100);
appView.getView().setLayoutParams(new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
setContentView(R.layout.activity_cordova);
ViewGroup layout = findViewById(R.id.content_container);
layout.addView(appView.getView(), 0);
retrieveConnection();
if (preferences.contains("BackgroundColor")) {
try {
int backgroundColor = preferences.getInteger("BackgroundColor", Color.BLACK);
// Background of activity:
appView.getView().setBackgroundColor(backgroundColor);
}
catch (NumberFormatException e){
e.printStackTrace();
}
}
appView.getView().requestFocusFromTouch();
}
public void serviceReporting(CouchbaseLiteService service){
retrieveConnection();
}
public ConnectionInfo retrieveConnection(){
if( null == connectionInfo ){
String connectionId = null;
Intent intent = getIntent();
if( null != intent ){
connectionId = intent.getStringExtra(Nunaliit.EXTRA_CONNECTION_ID);
}
if( null != mService && null != connectionId ){
try {
CouchbaseManager couchbaseMgr = mService.getCouchbaseManager();
ConnectionInfoDb infoDb = couchbaseMgr.getConnectionsDb();
connectionInfo = infoDb.getConnectionInfo(connectionId);
} catch(Exception e) {
Log.e(TAG,"Unable to retrieve connection info",e);
}
}
}
configureUI();
return connectionInfo;
}
private void configureUI () {
this.runOnUiThread(new Runnable() {
@Override
public void run() {
TextView atlasNameTextView = findViewById(R.id.atlas_title);
TextView atlasNameTextUrl = findViewById(R.id.atlas_url);
Toolbar toolbar = findViewById(R.id.cordova_toolbar);
if (connectionInfo != null && atlasNameTextView != null && atlasNameTextUrl != null && toolbar != null) {
atlasNameTextView.setText(connectionInfo.getName());
atlasNameTextUrl.setText(connectionInfo.getUrl());
toolbar.setTitle(connectionInfo.getName());
toolbar.setTitleTextColor(Color.WHITE);
toolbar.setNavigationIcon(R.drawable.ic_menu);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!drawerLayout.isDrawerOpen(navigationView) &&
drawerLayout.getDrawerLockMode(navigationView) != DrawerLayout.LOCK_MODE_LOCKED_CLOSED) {
drawerLayout.openDrawer(navigationView);
} else {
drawerLayout.closeDrawer(navigationView);
}
}
});
}
}
});
}
public CouchbaseLiteService getCouchDbService(){
return mService;
}
protected void receiveBroadcast(Intent intent){
Log.v(TAG, "Received broadcast :" + intent.getAction() + Nunaliit.threadId());
if( ConnectionManagementService.RESULT_GET_CONNECTION_INFOS.equals(intent.getAction()) ){
ArrayList<Parcelable> parcelables = intent.getParcelableArrayListExtra(Nunaliit.EXTRA_CONNECTION_INFOS);
List<ConnectionInfo> connectionInfos = new Vector<ConnectionInfo>();
for(Parcelable parcelable : parcelables){
if( parcelable instanceof ConnectionInfo ){
ConnectionInfo connInfo = (ConnectionInfo)parcelable;
connectionInfos.add(connInfo);
}
}
displayedConnections = connectionInfos;
drawList();
retrieveConnection();
} else if (ConnectionManagementService.RESULT_SYNC.equals(intent.getAction())) {
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, navigationView);
startConnectionActivity(connectionInfo);
} else {
Log.w(TAG, "Ignoring received intent :" + intent.getAction() + Nunaliit.threadId());
}
}
private void drawList() {
if( null != displayedConnections ) {
for (int i = 0, e = displayedConnections.size(); i < e; ++i) {
ConnectionInfo connectionInfo = displayedConnections.get(i);
MenuItem menuItem = navigationView.getMenu().add(Menu.NONE, i, i, connectionInfo.getName());
ConnectionInfo connInfo = displayedConnections.get(i);
setAtlasInitialsIcon(menuItem, connInfo);
}
MenuItem synchronizeAtlasMenuItem = navigationView.getMenu().add(Menu.NONE, 10000, 10000, "Synchronize Atlas");
synchronizeAtlasMenuItem.setIcon(R.drawable.ic_synchronize);
MenuItem manageAtlasMenuItem = navigationView.getMenu().add(Menu.NONE, 10001, 10001, "Manage Atlas");
manageAtlasMenuItem.setIcon(R.drawable.ic_manage);
MenuItem addAtlasMenuItem = navigationView.getMenu().add(Menu.NONE, 10002, 10002, "Add Atlas");
}
}
private void synchronizeConnection(ConnectionInfo connInfo) {
Intent syncIntent = new Intent(this, ConnectionManagementService.class);
syncIntent.setAction(ConnectionManagementService.ACTION_SYNC);
Log.v(TAG, "action:" + syncIntent.getAction() + Nunaliit.threadId());
syncIntent.putExtra(Nunaliit.EXTRA_CONNECTION_ID, connInfo.getId());
startService(syncIntent);
}
public void startConnectionActivity(ConnectionInfo connInfo){
Intent intent = new Intent(this, EmbeddedCordovaActivity.class);
intent.putExtra(Nunaliit.EXTRA_CONNECTION_ID, connInfo.getId());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
private void setAtlasInitialsIcon(MenuItem menuItem, ConnectionInfo connInfo) {
String name = connInfo.getName().length() > 0 ? "" + connInfo.getName().charAt(0) : "";
Bitmap atlasInitial = AtlasPictureSingleton.getInstance().getUserInitialsBitmap(name, 48, this);
Drawable drawable = new BitmapDrawable(getResources(), atlasInitial);
menuItem.setIcon(drawable);
}
public void startAddConnectionActivity(){
Intent intent = new Intent(this, AddConnectionActivity.class);
startActivity(intent);
}
}
|
Deleting an atlas from the main cordova activity
|
app/src/main/java/ca/carleton/gcrc/n2android_mobile1/activities/EmbeddedCordovaActivity.java
|
Deleting an atlas from the main cordova activity
|
<ide><path>pp/src/main/java/ca/carleton/gcrc/n2android_mobile1/activities/EmbeddedCordovaActivity.java
<ide> package ca.carleton.gcrc.n2android_mobile1.activities;
<ide>
<ide> import android.annotation.SuppressLint;
<add>import android.app.AlertDialog;
<ide> import android.content.BroadcastReceiver;
<ide> import android.content.ComponentName;
<ide> import android.content.Context;
<add>import android.content.DialogInterface;
<ide> import android.content.Intent;
<ide> import android.content.IntentFilter;
<ide> import android.content.ServiceConnection;
<ide> });
<ide>
<ide> navigationView = findViewById(R.id.nav_view);
<add> navigationView.setItemIconTintList(null);
<ide> navigationView.setNavigationItemSelectedListener(
<ide> new NavigationView.OnNavigationItemSelectedListener() {
<ide> @Override
<ide> public boolean onNavigationItemSelected(MenuItem menuItem) {
<ide> if (menuItem.getItemId() == 10000) {
<ide> synchronizeConnection(connectionInfo);
<del> appView.getView().setVisibility(View.GONE);
<del> findViewById(R.id.sync_progress).setVisibility(View.VISIBLE);
<del> drawerLayout.closeDrawers();
<del> drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
<add> showProgressBar();
<ide> } else if (menuItem.getItemId() == 10001) {
<ide> manageMode = !manageMode;
<ide>
<ide> } else if (menuItem.getItemId() == 10002) {
<ide> startAddConnectionActivity();
<ide> } else if (menuItem.getItemId() < 10000) {
<del> ConnectionInfo newConnection = displayedConnections.get(menuItem.getItemId());
<del> if (!connectionInfo.getId().equals(newConnection.getId())) {
<del> startConnectionActivity(newConnection);
<add> final ConnectionInfo newConnection = displayedConnections.get(menuItem.getItemId());
<add>
<add> if (!manageMode) {
<add> if (!connectionInfo.getId().equals(newConnection.getId())) {
<add> startConnectionActivity(newConnection);
<add> } else {
<add> drawerLayout.closeDrawers();
<add> return true;
<add> }
<ide> } else {
<del> drawerLayout.closeDrawers();
<add> Log.d(TAG, "Delete Atlas");
<add>
<add> AlertDialog.Builder builder = new AlertDialog.Builder(EmbeddedCordovaActivity.this);
<add>
<add> builder.setTitle("Remove Account");
<add> builder.setMessage("Are you sure you want to remove the account from your device?");
<add> builder.setPositiveButton("REMOVE", new DialogInterface.OnClickListener() {
<add> @Override
<add> public void onClick(DialogInterface dialogInterface, int i) {
<add> deleteConnection(newConnection);
<add> showProgressBar();
<add> }
<add> });
<add> builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
<add> @Override
<add> public void onClick(DialogInterface dialogInterface, int i) {}
<add> });
<add>
<add> final AlertDialog dialog = builder.create();
<add> dialog.setOnShowListener(new DialogInterface.OnShowListener() {
<add> @Override
<add> public void onShow(DialogInterface dialogInterface) {
<add> dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(Color.BLACK);
<add> }
<add> });
<add>
<add> dialog.show();
<add>
<ide> }
<ide> }
<ide>
<ide> broadcastReceiver,
<ide> new IntentFilter(ConnectionManagementService.RESULT_SYNC)
<ide> );
<add> lbm.registerReceiver(
<add> broadcastReceiver,
<add> new IntentFilter(ConnectionManagementService.RESULT_DELETE_CONNECTION)
<add> );
<add> lbm.registerReceiver(
<add> broadcastReceiver,
<add> new IntentFilter(ConnectionManagementService.ERROR_DELETE_CONNECTION)
<add> );
<ide>
<ide> // Request for list of connection infos
<ide> {
<ide> connectionIntent.setAction(ConnectionManagementService.ACTION_GET_CONNECTION_INFOS);
<ide> startService(connectionIntent);
<ide> }
<add> }
<add>
<add> private void showProgressBar() {
<add> appView.getView().setVisibility(View.GONE);
<add> findViewById(R.id.sync_progress).setVisibility(View.VISIBLE);
<add> drawerLayout.closeDrawers();
<add> drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
<ide> }
<ide>
<ide> @Override
<ide> } else if (ConnectionManagementService.RESULT_SYNC.equals(intent.getAction())) {
<ide> drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, navigationView);
<ide> startConnectionActivity(connectionInfo);
<add> } else if( ConnectionManagementService.RESULT_DELETE_CONNECTION.equals(intent.getAction()) ){
<add> String connectionId = intent.getStringExtra(Nunaliit.EXTRA_CONNECTION_ID);
<add> if (connectionId.equals(connectionInfo.getId())) {
<add> // If there is another connection other than the old connection
<add> if (displayedConnections.size() > 1) {
<add> ConnectionInfo newConnection = displayedConnections.get(0);
<add> if (newConnection.getId().equals(connectionId)) {
<add> newConnection = displayedConnections.get(1);
<add> }
<add> startConnectionActivity(newConnection);
<add> } else {
<add> startMainActivity();
<add> }
<add> } else {
<add> startConnectionActivity(connectionInfo);
<add> }
<ide> } else {
<ide> Log.w(TAG, "Ignoring received intent :" + intent.getAction() + Nunaliit.threadId());
<ide> }
<ide> startService(syncIntent);
<ide> }
<ide>
<add> public void startMainActivity() {
<add> Intent intent = new Intent(this, MainActivity.class);
<add> intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
<add> startActivity(intent);
<add> }
<add>
<add> private void deleteConnection(ConnectionInfo connInfo) {
<add> Intent intent = new Intent(this, ConnectionManagementService.class);
<add> intent.setAction(ConnectionManagementService.ACTION_DELETE_CONNECTION);
<add> Log.v(TAG, "action:" + intent.getAction() + Nunaliit.threadId());
<add> intent.putExtra(Nunaliit.EXTRA_CONNECTION_ID, connInfo.getId());
<add> startService(intent);
<add> }
<add>
<ide> public void startConnectionActivity(ConnectionInfo connInfo){
<ide> Intent intent = new Intent(this, EmbeddedCordovaActivity.class);
<ide> intent.putExtra(Nunaliit.EXTRA_CONNECTION_ID, connInfo.getId());
|
|
Java
|
agpl-3.0
|
19d3ae56fa3df4dbc6868e1ade9af7fe60d5cd22
| 0 |
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
|
b1346fbc-2e60-11e5-9284-b827eb9e62be
|
hello.java
|
b12f023e-2e60-11e5-9284-b827eb9e62be
|
b1346fbc-2e60-11e5-9284-b827eb9e62be
|
hello.java
|
b1346fbc-2e60-11e5-9284-b827eb9e62be
|
<ide><path>ello.java
<del>b12f023e-2e60-11e5-9284-b827eb9e62be
<add>b1346fbc-2e60-11e5-9284-b827eb9e62be
|
|
Java
|
lgpl-2.1
|
87f72733878173620d4669e8923e193a6907e0dc
| 0 |
Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,justincc/intermine,elsiklab/intermine,zebrafishmine/intermine,tomck/intermine,joshkh/intermine,JoeCarlson/intermine,joshkh/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,justincc/intermine,justincc/intermine,justincc/intermine,tomck/intermine,kimrutherford/intermine,tomck/intermine,elsiklab/intermine,justincc/intermine,zebrafishmine/intermine,elsiklab/intermine,JoeCarlson/intermine,tomck/intermine,JoeCarlson/intermine,tomck/intermine,justincc/intermine,justincc/intermine,elsiklab/intermine,Arabidopsis-Information-Portal/intermine,tomck/intermine,JoeCarlson/intermine,joshkh/intermine,kimrutherford/intermine,justincc/intermine,JoeCarlson/intermine,zebrafishmine/intermine,Arabidopsis-Information-Portal/intermine,Arabidopsis-Information-Portal/intermine,joshkh/intermine,kimrutherford/intermine,zebrafishmine/intermine,zebrafishmine/intermine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,elsiklab/intermine,zebrafishmine/intermine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,tomck/intermine,elsiklab/intermine,joshkh/intermine,elsiklab/intermine,Arabidopsis-Information-Portal/intermine,JoeCarlson/intermine,joshkh/intermine,zebrafishmine/intermine,joshkh/intermine,tomck/intermine,justincc/intermine,zebrafishmine/intermine,Arabidopsis-Information-Portal/intermine,tomck/intermine,JoeCarlson/intermine,JoeCarlson/intermine,joshkh/intermine,zebrafishmine/intermine,joshkh/intermine,elsiklab/intermine,JoeCarlson/intermine,kimrutherford/intermine,kimrutherford/intermine,kimrutherford/intermine
|
package org.intermine.bio.dataconversion;
/*
* Copyright (C) 2002-2011 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.intermine.dataconversion.ItemWriter;
import org.intermine.metadata.Model;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.sql.Database;
import org.intermine.util.StringUtil;
import org.intermine.xml.full.Item;
import org.intermine.xml.full.ReferenceList;
/**
* Read Ensembl SNP data directly from MySQL variation database.
* @author Richard Smith
*/
public class EnsemblSnpDbConverter extends BioDBConverter
{
private static final String DATASET_TITLE = "Ensembl SNP data";
private static final String DATA_SOURCE_NAME = "Ensembl";
private final Map<String, Set<String>> pendingSnpConsequences =
new HashMap<String, Set<String>>();
private final Map<String, Integer> storedSnpIds = new HashMap<String, Integer>();
private final Map<String, String> storedSnpItemIdentifiers = new HashMap<String, String>();
private Set<String> snpSourceIds = null;
// store a mapping from variation_id in ensembl database to stored SNP id in objectstore
//private IntToIntMap variationIdToObjectId = new IntToIntMap();
private Map<Integer, String> variationIdToItemIdentifier = new HashMap<Integer, String>();
// default to human or take value set by parser
Integer taxonId = null;
private static final int PLANT = 3702;
// There may be SNPs from multiple sources in the database, optionally restrict them
Set<String> snpSources = new HashSet<String>();
// Edit to restrict to loading fewer chromosomes
private static final int MIN_CHROMOSOME = 1;
private Map<String, String> sources = new HashMap<String, String>();
private Map<String, String> states = new HashMap<String, String>();
private Map<String, String> transcripts = new HashMap<String, String>();
private Map<String, String> noTranscriptConsequences = new HashMap<String, String>();
private static final Logger LOG = Logger.getLogger(EnsemblSnpDbConverter.class);
/**
* Construct a new EnsemblSnpDbConverter.
* @param database the database to read from
* @param model the Model used by the object store we will write to with the ItemWriter
* @param writer an ItemWriter used to handle Items created
*/
public EnsemblSnpDbConverter(Database database, Model model, ItemWriter writer) {
super(database, model, writer, DATA_SOURCE_NAME, DATASET_TITLE);
}
/**
* Set the organism to load
* @param taxonId the organism to load
*/
public void setOrganism(String taxonId) {
this.taxonId = Integer.parseInt(taxonId);
}
/**
* Optionally restrict the sources of SNPs to load by entries in source table, e.g. to dbSNP.
* @param sourceStr a space-separated list of sources
*/
public void setSources(String sourceStr) {
for (String source : sourceStr.split(" ")) {
snpSources.add(source.trim());
}
}
/**
* {@inheritDoc}
*/
public void process() throws Exception {
// a database has been initialised from properties starting with db.ensembl-snp-db
if (this.taxonId == null) {
throw new IllegalArgumentException("Must supply a taxon id for this variation database"
+ " set the 'organism' property in project.xml");
}
Connection connection = getDatabase().getConnection();
List<String> chrNames = new ArrayList<String>();
for (int i = MIN_CHROMOSOME; i <= 22; i++) {
chrNames.add("" + i);
}
chrNames.add("X");
chrNames.add("Y");
chrNames.add("MT");
chrNames.add("Mt");
chrNames.add("Pt");
for (String chrName : chrNames) {
process(connection, chrName);
}
storeFinalSnps();
if (PLANT == this.taxonId.intValue()) {
processGenotypes(connection);
}
connection.close();
}
private void storeFinalSnps() throws Exception {
LOG.info("storeFinalSnps() pendingConsequences.size(): " + pendingSnpConsequences.size());
LOG.info("storeFinalSnps() storedSnpIds.size(): " + storedSnpIds.size());
for (String rsNumber : pendingSnpConsequences.keySet()) {
Integer storedSnpId = storedSnpIds.get(rsNumber);
Set<String> consequenceIdentifiers = pendingSnpConsequences.get(rsNumber);
ReferenceList col =
new ReferenceList("consequences", new ArrayList<String>(consequenceIdentifiers));
store(col, storedSnpId);
}
}
/**
* {@inheritDoc}
*/
public void process(Connection connection, String chrName) throws Exception {
LOG.info("Starting to process chromosome " + chrName);
ResultSet res = queryVariation(connection, chrName);
int counter = 0;
int snpCounter = 0;
Item currentSnp = null;
Set<String> seenLocsForSnp = new HashSet<String>();
String previousRsNumber = null;
Boolean previousUniqueLocation = true;
Set<String> consequenceIdentifiers = new HashSet<String>();
boolean storeSnp = false;
String currentSnpIdentifier = null;
Set<String> snpSynonyms = new HashSet<String>();
Integer currentVariationId = null;
// This code is complicated because not all SNPs map to a unique location and often have
// locations on multiple chromosomes - we're processing one chromosome at a time for faster
// queries to mySQL.
while (res.next()) {
counter++;
String rsNumber = res.getString("variation_name");
boolean newSnp = rsNumber.equals(previousRsNumber) ? false : true;
if (newSnp) {
// starting a new SNP, store the one just finished - previousRsNumber
Integer storedSnpId = storedSnpIds.get(previousRsNumber);
// if we didn't get back a storedSnpId this was the first time we found this SNP,
// so store it now
if (storeSnp && storedSnpId == null) {
storedSnpId = storeSnp(currentSnp, snpSynonyms);
variationIdToItemIdentifier.put(currentVariationId, currentSnp.getIdentifier());
snpCounter++;
}
if (previousUniqueLocation) {
// the SNP we just stored has only one location so we won't see it again
storeSnpCollections(storedSnpId, consequenceIdentifiers);
} else {
// we'll see this SNP multiple times so hang onto data
Set<String> snpConsequences = pendingSnpConsequences.get(previousRsNumber);
if (snpConsequences == null) {
snpConsequences = new HashSet<String>();
pendingSnpConsequences.put(previousRsNumber, snpConsequences);
}
snpConsequences.addAll(consequenceIdentifiers);
if (!storedSnpIds.containsKey(previousRsNumber)) {
storedSnpIds.put(previousRsNumber, storedSnpId);
storedSnpItemIdentifiers.put(previousRsNumber, currentSnp.getIdentifier());
}
}
// START NEW SNP
previousRsNumber = rsNumber;
seenLocsForSnp = new HashSet<String>();
consequenceIdentifiers = new HashSet<String>();
snpSynonyms = new HashSet<String>();
storeSnp = true;
// map weight is the number of chromosome locations for the SNP, in practice there
// are sometimes fewer locations than the map_weight indicates
int mapWeight = res.getInt("map_weight");
boolean uniqueLocation = (mapWeight == 1) ? true : false;
previousUniqueLocation = uniqueLocation;
// if not a unique location and we've seen the SNP before, don't store
if (!uniqueLocation && pendingSnpConsequences.containsKey(rsNumber)) {
storeSnp = false;
currentSnpIdentifier = storedSnpItemIdentifiers.get(rsNumber);
}
if (storeSnp) {
currentSnp = createItem("SNP");
currentSnp.setAttribute("primaryIdentifier", rsNumber);
currentSnp.setReference("organism", getOrganismItem(taxonId));
currentSnp.setAttribute("uniqueLocation", "" + uniqueLocation);
currentSnpIdentifier = currentSnp.getIdentifier();
currentVariationId = res.getInt("variation_id");
String alleles = res.getString("allele_string");
if (!StringUtils.isBlank(alleles)) {
currentSnp.setAttribute("alleles", alleles);
}
String type = determineType(alleles);
if (type != null) {
currentSnp.setAttribute("type", type);
}
// CHROMOSOME AND LOCATION
// if SNP is mapped to multiple locations don't set chromosome and
// chromosomeLocation references
int start = res.getInt("seq_region_start");
int end = res.getInt("seq_region_end");
int chrStrand = res.getInt("seq_region_strand");
int chrStart = Math.min(start, end);
int chrEnd = Math.max(start, end);
Item loc = createItem("Location");
loc.setAttribute("start", "" + chrStart);
loc.setAttribute("end", "" + chrEnd);
loc.setAttribute("strand", "" + chrStrand);
loc.setReference("locatedOn", getChromosome(chrName, taxonId));
loc.setReference("feature", currentSnpIdentifier);
store(loc);
// if mapWeight is 1 there is only one chromosome location, so set shortcuts
if (uniqueLocation) {
currentSnp.setReference("chromosome", getChromosome(chrName, taxonId));
currentSnp.setReference("chromosomeLocation", loc);
}
seenLocsForSnp.add(chrName + ":" + chrStart);
// SOURCE
String source = res.getString("s.name");
currentSnp.setReference("source", getSourceIdentifier(source));
// VALIDATION STATES
String validationStatus = res.getString("validation_status");
List<String> validationStates = getValidationStateCollection(validationStatus);
if (!validationStates.isEmpty()) {
currentSnp.setCollection("validations", validationStates);
}
}
}
int mapWeight = res.getInt("map_weight");
boolean uniqueLocation = (mapWeight == 1) ? true : false;
// we're on the same SNP but maybe a new location
int start = res.getInt("seq_region_start");
int end = res.getInt("seq_region_end");
int strand = res.getInt("seq_region_strand");
int chrStart = Math.min(start, end);
int chrEnd = Math.max(start, end);
if (currentSnp == null) {
LOG.error("currentSNP is null. vf.variation_feature_id: "
+ res.getString("variation_feature_id") + " rsNumber: " + rsNumber
+ " previousRsNumber: " + previousRsNumber + " storeSnp: " + storeSnp);
}
String chrLocStr = chrName + ":" + chrStart;
if (!seenLocsForSnp.contains(chrLocStr)) {
seenLocsForSnp.add(chrLocStr);
// if this location is on a chromosome we want, store it
Item loc = createItem("Location");
loc.setAttribute("start", "" + chrStart);
loc.setAttribute("end", "" + chrEnd);
loc.setAttribute("strand", "" + strand);
loc.setReference("feature", currentSnpIdentifier);
loc.setReference("locatedOn", getChromosome(chrName, taxonId));
store(loc);
}
// CONSEQUENCE TYPES
// for SNPs without a uniqueLocation there will be different consequences at each one.
// some consequences will need to stored a the end
String cdnaStart = res.getString("cdna_start");
if (StringUtils.isBlank(cdnaStart)) {
String typeStr = res.getString("vf.consequence_type");
for (String type : typeStr.split(",")) {
consequenceIdentifiers.add(getConsequenceIdentifier(type));
}
} else {
String type = res.getString("tv.consequence_types");
// Seen one example so far where consequence type is an empty string
if (StringUtils.isBlank(type)) {
type = "UNKOWN";
}
String peptideAlleles = res.getString("pep_allele_string");
String transcriptStableId = res.getString("feature_stable_id");
Item consequenceItem = createItem("Consequence");
consequenceItem.setAttribute("type", type);
if (!StringUtils.isBlank(peptideAlleles)) {
consequenceItem.setAttribute("peptideAlleles", peptideAlleles);
}
if (!StringUtils.isBlank(transcriptStableId)) {
consequenceItem.setReference("transcript",
getTranscriptIdentifier(transcriptStableId));
}
consequenceIdentifiers.add(consequenceItem.getIdentifier());
store(consequenceItem);
}
// SYNONYMS
// we may see the same synonym on multiple row but the Set will make them unique
String synonym = res.getString("vs.name");
if (!StringUtils.isBlank(synonym)) {
snpSynonyms.add(synonym);
}
if (counter % 100000 == 0) {
LOG.info("Read " + counter + " rows total, stored " + snpCounter + " SNPs. for chr "
+ chrName);
}
}
if (currentSnp != null && storeSnp) {
Integer storedSnpId = storeSnp(currentSnp, snpSynonyms);
variationIdToItemIdentifier.put(currentVariationId, currentSnp.getIdentifier());
if (!storedSnpIds.containsKey(storedSnpId)) {
storeSnpCollections(storedSnpId, consequenceIdentifiers);
}
}
LOG.info("Finished " + counter + " rows total, stored " + snpCounter + " SNPs for chr "
+ chrName);
LOG.info("variationIdToItemIdentifier.size() = " + variationIdToItemIdentifier.size());
}
private void processGenotypes(Connection connection) throws Exception {
// query for strains
ResultSet res = queryStrains(connection);
int strainCounter = 0;
while (res.next()) {
Integer strainId = res.getInt("sample_id");
String strainName = res.getString("name");
Item strain = createItem("Strain");
strain.setAttribute("name", strainName);
store(strain);
// for each strain query and store genotypes
processGenotypesForStrain(connection, strainId, strain.getIdentifier());
strainCounter++;
if (strainCounter >= 100) {
break;
}
}
}
private void processGenotypesForStrain(Connection connection, Integer strainId,
String strainIdentifier) throws Exception {
ResultSet res = queryGenotypesForStrain(connection, strainId);
int snpReferenceCount = 0;
int ignoredCount = 0;
while (res.next()) {
Integer variationId = res.getInt("variation_id");
String allele1 = res.getString("allele_1");
String allele2 = res.getString("allele_2");
String snpItemIdentifier = variationIdToItemIdentifier.get(variationId);
Item genotype = createItem("Genotype");
genotype.setAttribute("allele1", allele1);
genotype.setAttribute("allele2", allele2);
if (snpItemIdentifier != null) {
genotype.setReference("snp", snpItemIdentifier);
snpReferenceCount++;
}
else {
ignoredCount++;
}
genotype.setReference("strain", strainIdentifier);
store(genotype);
}
String message = "For strain " + strainId + " snp ref: " + snpReferenceCount + ", no ref: "
+ ignoredCount;
LOG.info(message);
System.out.println(message);
}
private ResultSet queryGenotypesForStrain(Connection connection, Integer strainId)
throws SQLException{
String query = "SELECT variation_id, allele_1, allele_2"
+ " FROM tmp_individual_genotype_single_bp"
+ " WHERE sample_id = " + strainId;
LOG.warn(query);
System.out.println(query);
Statement stmt = connection.createStatement();
ResultSet res = stmt.executeQuery(query);
return res;
}
private Integer storeSnp(Item snp, Set<String> synonyms) throws ObjectStoreException {
Integer storedSnpId = store(snp);
for (String synonym : synonyms) {
createSynonym(snp.getIdentifier(), synonym, true);
}
return storedSnpId;
}
private void storeSnpCollections(Integer storedSnpId, Set<String> consequenceIdentifiers)
throws ObjectStoreException {
if (!consequenceIdentifiers.isEmpty()) {
ReferenceList col =
new ReferenceList("consequences", new ArrayList<String>(consequenceIdentifiers));
store(col, storedSnpId);
}
}
/**
* Given an allele string read from the database determine the type of variation, e.g. snp,
* in-del, etc. This is a re-implementation of code from the Ensembl perl API, see:
* http://www.ensembl.org/info/docs/Pdoc/ensembl-variation/
* modules/Bio/EnsEMBL/Variation/Utils/Sequence.html#CODE4
* @param alleleStr the alleles to determine the type for
* @return a variation class or null if none can be determined
*/
protected String determineType(String alleleStr) {
String type = null;
final String VALID_BASES = "ATUGCYRSWKMBDHVN";
alleleStr = alleleStr.toUpperCase();
if (!StringUtils.isBlank(alleleStr)) {
// snp if e.g. A/C or A|C
if (alleleStr.matches("^[" + VALID_BASES + "]([\\/\\|\\\\][" + VALID_BASES + "])+$")) {
type = "snp";
} else if ("CNV".equals(alleleStr)) {
type = alleleStr.toLowerCase();
} else if ("CNV_PROBE".equals(alleleStr)) {
type = "cnv probe";
} else if ("HGMD_MUTATION".equals(alleleStr)) {
type = alleleStr.toLowerCase();
} else {
String[] alleles = alleleStr.split("[\\|\\/\\\\]");
if (alleles.length == 1) {
type = "het";
} else if (alleles.length == 2) {
if ((StringUtils.containsOnly(alleles[0],
VALID_BASES) && "-".equals(alleles[1]))
|| (StringUtils.containsOnly(alleles[1], VALID_BASES)
&& "-".equals(alleles[0]))) {
type = "in-del";
} else if (containsOneOf(alleles[0], "LARGE", "INS", "DEL")
|| containsOneOf(alleles[1], "LARGE", "INS", "DEL")) {
type = "named";
} else if ((StringUtils.containsOnly(alleles[0], VALID_BASES)
&& alleles[0].length() > 1)
|| (StringUtils.containsOnly(alleles[1], VALID_BASES)
&& alleles[1].length() > 1)) {
// AA/GC 2 alleles
type = "substitution";
}
} else if (alleles.length > 2) {
if (containsDigit(alleles[0])) {
type = "microsat";
} else if (anyContainChar(alleles, "-")) {
type = "mixed";
}
}
if (type == null) {
LOG.warn("Failed to work out allele type for: " + alleleStr);
}
}
}
return type;
}
private String getSourceIdentifier(String name) throws ObjectStoreException {
String sourceIdentifier = sources.get(name);
if (sourceIdentifier == null) {
Item source = createItem("Source");
source.setAttribute("name", name);
store(source);
sourceIdentifier = source.getIdentifier();
sources.put(name, sourceIdentifier);
}
return sourceIdentifier;
}
private String getTranscriptIdentifier(String transcriptStableId) throws ObjectStoreException {
String transcriptIdentifier = transcripts.get(transcriptStableId);
if (transcriptIdentifier == null) {
Item transcript = createItem("Transcript");
transcript.setAttribute("primaryIdentifier", transcriptStableId);
store(transcript);
transcriptIdentifier = transcript.getIdentifier();
transcripts.put(transcriptStableId, transcriptIdentifier);
}
return transcriptIdentifier;
}
private List<String> getValidationStateCollection(String input) throws ObjectStoreException {
List<String> stateIdentifiers = new ArrayList<String>();
if (!StringUtils.isBlank(input)) {
for (String state : input.split(",")) {
stateIdentifiers.add(getStateIdentifier(state));
}
}
return stateIdentifiers;
}
private String getStateIdentifier(String name) throws ObjectStoreException {
String stateIdentifier = states.get(name);
if (stateIdentifier == null) {
Item state = createItem("ValidationState");
state.setAttribute("name", name);
store(state);
stateIdentifier = state.getIdentifier();
states.put(name, stateIdentifier);
}
return stateIdentifier;
}
private String getConsequenceIdentifier(String type) throws ObjectStoreException {
String consequenceIdentifier = noTranscriptConsequences.get(type);
if (consequenceIdentifier == null) {
Item consequence = createItem("Consequence");
consequence.setAttribute("type", type);
store(consequence);
consequenceIdentifier = consequence.getIdentifier();
noTranscriptConsequences.put(type, consequenceIdentifier);
}
return consequenceIdentifier;
}
private ResultSet queryVariation(Connection connection, String chrName)
throws SQLException {
String query = "SELECT vf.variation_feature_id, vf.variation_name, vf.variation_id,"
+ " vf.allele_string, sr.name,"
+ " vf.map_weight, vf.seq_region_start, vf.seq_region_end, vf.seq_region_strand, "
+ " s.name,"
+ " vf.validation_status,"
+ " vf.consequence_type,"
+ " tv.cdna_start,tv.consequence_types,tv.pep_allele_string,tv.feature_stable_id,"
+ " vs.name"
+ " FROM seq_region sr, source s, variation_feature vf "
+ " LEFT JOIN (transcript_variation tv)"
+ " ON (vf.variation_feature_id = tv.variation_feature_id"
+ " AND tv.cdna_start is not null)"
+ " LEFT JOIN (variation_synonym vs)"
+ " ON (vf.variation_id = vs.variation_id"
+ " AND vs.source_id IN (" + makeInList(getSnpSourceIds(connection)) + ")"
+ " WHERE vf.seq_region_id = sr.seq_region_id"
+ " AND vf.source_id = s.source_id"
+ " AND sr.name = '" + chrName + "'"
+ " ORDER BY vf.variation_id";
LOG.warn(query);
System.out.println(query);
Statement stmt = connection.createStatement();
ResultSet res = stmt.executeQuery(query);
return res;
}
private String makeInList(Collection<String> strings) {
Set<String> quoted = new HashSet<String>();
for (String s : strings) {
quoted.add("'" + s + "'");
}
return StringUtil.join(quoted, ",");
}
private Set<String> getSnpSourceIds(Connection connection) throws SQLException {
if (snpSourceIds == null) {
snpSourceIds = new HashSet<String>();
String sql = "SELECT source_id FROM source";
if (snpSources != null && !snpSources.isEmpty()) {
sql += "WHERE name IN (" + StringUtil.join(snpSources, ",") + ")";
}
Statement stmt = connection.createStatement();
ResultSet res = stmt.executeQuery(sql);
while (res.next()) {
snpSourceIds.add(res.getString("source_id"));
}
if (snpSourceIds.isEmpty()) {
throw new RuntimeException("Failed to retrieve source_ids for dbSNP source");
}
}
return snpSourceIds;
}
private ResultSet queryStrains(Connection connection)
throws SQLException {
String query = "SELECT sample_id, name from sample";
LOG.warn(query);
System.out.println(query);
Statement stmt = connection.createStatement();
ResultSet res = stmt.executeQuery(query);
return res;
}
/**
* {@inheritDoc}
*/
@Override
public String getDataSetTitle(int taxonId) {
return DATASET_TITLE;
}
private boolean containsOneOf(String target, String... substrings) {
for (String substring : substrings) {
if (target.contains(substring)) {
return true;
}
}
return false;
}
private boolean anyContainChar(String[] targets, String substring) {
for (String target : targets) {
if (target.contains(substring)) {
return true;
}
}
return false;
}
private boolean containsDigit(String target) {
for (int i = 0; i < target.length(); i++) {
if (Character.isDigit(target.charAt(i))) {
return true;
}
}
return false;
}
}
|
bio/sources/ensembl-snp-db/main/src/org/intermine/bio/dataconversion/EnsemblSnpDbConverter.java
|
package org.intermine.bio.dataconversion;
/*
* Copyright (C) 2002-2011 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.intermine.dataconversion.ItemWriter;
import org.intermine.metadata.Model;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.sql.Database;
import org.intermine.util.StringUtil;
import org.intermine.xml.full.Item;
import org.intermine.xml.full.ReferenceList;
/**
* Read Ensembl SNP data directly from MySQL variation database.
* @author Richard Smith
*/
public class EnsemblSnpDbConverter extends BioDBConverter
{
private static final String DATASET_TITLE = "Ensembl SNP data";
private static final String DATA_SOURCE_NAME = "Ensembl";
private final Map<String, Set<String>> pendingSnpConsequences =
new HashMap<String, Set<String>>();
private final Map<String, Integer> storedSnpIds = new HashMap<String, Integer>();
private final Map<String, String> storedSnpItemIdentifiers = new HashMap<String, String>();
private Set<String> snpSourceIds = null;
// store a mapping from variation_id in ensembl database to stored SNP id in objectstore
//private IntToIntMap variationIdToObjectId = new IntToIntMap();
private Map<Integer, String> variationIdToItemIdentifier = new HashMap<Integer, String>();
// default to human or take value set by parser
Integer taxonId = null;
private static final int PLANT = 3702;
// There may be SNPs from multiple sources in the database, optionally restrict them
Set<String> snpSources = new HashSet<String>();
// Edit to restrict to loading fewer chromosomes
private static final int MIN_CHROMOSOME = 1;
private Map<String, String> sources = new HashMap<String, String>();
private Map<String, String> states = new HashMap<String, String>();
private Map<String, String> transcripts = new HashMap<String, String>();
private Map<String, String> noTranscriptConsequences = new HashMap<String, String>();
private static final Logger LOG = Logger.getLogger(EnsemblSnpDbConverter.class);
/**
* Construct a new EnsemblSnpDbConverter.
* @param database the database to read from
* @param model the Model used by the object store we will write to with the ItemWriter
* @param writer an ItemWriter used to handle Items created
*/
public EnsemblSnpDbConverter(Database database, Model model, ItemWriter writer) {
super(database, model, writer, DATA_SOURCE_NAME, DATASET_TITLE);
}
/**
* Set the organism to load
* @param taxonId the organism to load
*/
public void setOrganism(String taxonId) {
this.taxonId = Integer.parseInt(taxonId);
}
/**
* Optionally restrict the sources of SNPs to load by entries in source table, e.g. to dbSNP.
* @param sourceStr a space-separated list of sources
*/
public void setSources(String sourceStr) {
for (String source : sourceStr.split(" ")) {
snpSources.add(source.trim());
}
}
/**
* {@inheritDoc}
*/
public void process() throws Exception {
// a database has been initialised from properties starting with db.ensembl-snp-db
if (this.taxonId == null) {
throw new IllegalArgumentException("Must supply a taxon id for this variation database"
+ " set the 'organism' property in project.xml");
}
Connection connection = getDatabase().getConnection();
List<String> chrNames = new ArrayList<String>();
for (int i = MIN_CHROMOSOME; i <= 22; i++) {
chrNames.add("" + i);
}
chrNames.add("X");
chrNames.add("Y");
chrNames.add("MT");
chrNames.add("Mt");
chrNames.add("Pt");
for (String chrName : chrNames) {
process(connection, chrName);
}
storeFinalSnps();
if (PLANT == this.taxonId.intValue()) {
processGenotypes(connection);
}
connection.close();
}
private void storeFinalSnps() throws Exception {
LOG.info("storeFinalSnps() pendingConsequences.size(): " + pendingSnpConsequences.size());
LOG.info("storeFinalSnps() storedSnpIds.size(): " + storedSnpIds.size());
for (String rsNumber : pendingSnpConsequences.keySet()) {
Integer storedSnpId = storedSnpIds.get(rsNumber);
Set<String> consequenceIdentifiers = pendingSnpConsequences.get(rsNumber);
ReferenceList col =
new ReferenceList("consequences", new ArrayList<String>(consequenceIdentifiers));
store(col, storedSnpId);
}
}
/**
* {@inheritDoc}
*/
public void process(Connection connection, String chrName) throws Exception {
LOG.info("Starting to process chromosome " + chrName);
ResultSet res = queryVariation(connection, chrName);
int counter = 0;
int snpCounter = 0;
Item currentSnp = null;
Set<String> seenLocsForSnp = new HashSet<String>();
String previousRsNumber = null;
Boolean previousUniqueLocation = true;
Set<String> consequenceIdentifiers = new HashSet<String>();
boolean storeSnp = false;
String currentSnpIdentifier = null;
Set<String> snpSynonyms = new HashSet<String>();
Integer currentVariationId = null;
// This code is complicated because not all SNPs map to a unique location and often have
// locations on multiple chromosomes - we're processing one chromosome at a time for faster
// queries to mySQL.
while (res.next()) {
counter++;
String rsNumber = res.getString("variation_name");
boolean newSnp = rsNumber.equals(previousRsNumber) ? false : true;
if (newSnp) {
// starting a new SNP, store the one just finished - previousRsNumber
Integer storedSnpId = storedSnpIds.get(previousRsNumber);
// if we didn't get back a storedSnpId this was the first time we found this SNP,
// so store it now
if (storeSnp && storedSnpId == null) {
storedSnpId = storeSnp(currentSnp, snpSynonyms);
variationIdToItemIdentifier.put(currentVariationId, currentSnp.getIdentifier());
snpCounter++;
}
if (previousUniqueLocation) {
// the SNP we just stored has only one location so we won't see it again
storeSnpCollections(storedSnpId, consequenceIdentifiers);
} else {
// we'll see this SNP multiple times so hang onto data
Set<String> snpConsequences = pendingSnpConsequences.get(previousRsNumber);
if (snpConsequences == null) {
snpConsequences = new HashSet<String>();
pendingSnpConsequences.put(previousRsNumber, snpConsequences);
}
snpConsequences.addAll(consequenceIdentifiers);
if (!storedSnpIds.containsKey(previousRsNumber)) {
storedSnpIds.put(previousRsNumber, storedSnpId);
storedSnpItemIdentifiers.put(previousRsNumber, currentSnp.getIdentifier());
}
}
// START NEW SNP
previousRsNumber = rsNumber;
seenLocsForSnp = new HashSet<String>();
consequenceIdentifiers = new HashSet<String>();
snpSynonyms = new HashSet<String>();
storeSnp = true;
// map weight is the number of chromosome locations for the SNP, in practice there
// are sometimes fewer locations than the map_weight indicates
int mapWeight = res.getInt("map_weight");
boolean uniqueLocation = (mapWeight == 1) ? true : false;
previousUniqueLocation = uniqueLocation;
// if not a unique location and we've seen the SNP before, don't store
if (!uniqueLocation && pendingSnpConsequences.containsKey(rsNumber)) {
storeSnp = false;
currentSnpIdentifier = storedSnpItemIdentifiers.get(rsNumber);
}
if (storeSnp) {
currentSnp = createItem("SNP");
currentSnp.setAttribute("primaryIdentifier", rsNumber);
currentSnp.setReference("organism", getOrganismItem(taxonId));
currentSnp.setAttribute("uniqueLocation", "" + uniqueLocation);
currentSnpIdentifier = currentSnp.getIdentifier();
currentVariationId = res.getInt("variation_id");
String alleles = res.getString("allele_string");
if (!StringUtils.isBlank(alleles)) {
currentSnp.setAttribute("alleles", alleles);
}
String type = determineType(alleles);
if (type != null) {
currentSnp.setAttribute("type", type);
}
// CHROMOSOME AND LOCATION
// if SNP is mapped to multiple locations don't set chromosome and
// chromosomeLocation references
int start = res.getInt("seq_region_start");
int end = res.getInt("seq_region_end");
int chrStrand = res.getInt("seq_region_strand");
int chrStart = Math.min(start, end);
int chrEnd = Math.max(start, end);
Item loc = createItem("Location");
loc.setAttribute("start", "" + chrStart);
loc.setAttribute("end", "" + chrEnd);
loc.setAttribute("strand", "" + chrStrand);
loc.setReference("locatedOn", getChromosome(chrName, taxonId));
loc.setReference("feature", currentSnpIdentifier);
store(loc);
// if mapWeight is 1 there is only one chromosome location, so set shortcuts
if (uniqueLocation) {
currentSnp.setReference("chromosome", getChromosome(chrName, taxonId));
currentSnp.setReference("chromosomeLocation", loc);
}
seenLocsForSnp.add(chrName + ":" + chrStart);
// SOURCE
String source = res.getString("s.name");
currentSnp.setReference("source", getSourceIdentifier(source));
// VALIDATION STATES
String validationStatus = res.getString("validation_status");
List<String> validationStates = getValidationStateCollection(validationStatus);
if (!validationStates.isEmpty()) {
currentSnp.setCollection("validations", validationStates);
}
}
}
int mapWeight = res.getInt("map_weight");
boolean uniqueLocation = (mapWeight == 1) ? true : false;
// we're on the same SNP but maybe a new location
int start = res.getInt("seq_region_start");
int end = res.getInt("seq_region_end");
int strand = res.getInt("seq_region_strand");
int chrStart = Math.min(start, end);
int chrEnd = Math.max(start, end);
if (currentSnp == null) {
LOG.error("currentSNP is null. vf.variation_feature_id: "
+ res.getString("variation_feature_id") + " rsNumber: " + rsNumber
+ " previousRsNumber: " + previousRsNumber + " storeSnp: " + storeSnp);
}
String chrLocStr = chrName + ":" + chrStart;
if (!seenLocsForSnp.contains(chrLocStr)) {
seenLocsForSnp.add(chrLocStr);
// if this location is on a chromosome we want, store it
Item loc = createItem("Location");
loc.setAttribute("start", "" + chrStart);
loc.setAttribute("end", "" + chrEnd);
loc.setAttribute("strand", "" + strand);
loc.setReference("feature", currentSnpIdentifier);
loc.setReference("locatedOn", getChromosome(chrName, taxonId));
store(loc);
}
// CONSEQUENCE TYPES
// for SNPs without a uniqueLocation there will be different consequences at each one.
// some consequences will need to stored a the end
String cdnaStart = res.getString("cdna_start");
if (StringUtils.isBlank(cdnaStart)) {
String typeStr = res.getString("vf.consequence_type");
for (String type : typeStr.split(",")) {
consequenceIdentifiers.add(getConsequenceIdentifier(type));
}
} else {
String type = res.getString("tv.consequence_types");
// Seen one example so far where consequence type is an empty string
if (StringUtils.isBlank(type)) {
type = "UNKOWN";
}
String peptideAlleles = res.getString("pep_allele_string");
String transcriptStableId = res.getString("feature_stable_id");
Item consequenceItem = createItem("Consequence");
consequenceItem.setAttribute("type", type);
if (!StringUtils.isBlank(peptideAlleles)) {
consequenceItem.setAttribute("peptideAlleles", peptideAlleles);
}
if (!StringUtils.isBlank(transcriptStableId)) {
consequenceItem.setReference("transcript",
getTranscriptIdentifier(transcriptStableId));
}
consequenceIdentifiers.add(consequenceItem.getIdentifier());
store(consequenceItem);
}
// SYNONYMS
// we may see the same synonym on multiple row but the Set will make them unique
String synonym = res.getString("vs.name");
if (!StringUtils.isBlank(synonym)) {
snpSynonyms.add(synonym);
}
if (counter % 100000 == 0) {
LOG.info("Read " + counter + " rows total, stored " + snpCounter + " SNPs. for chr "
+ chrName);
}
}
if (currentSnp != null && storeSnp) {
Integer storedSnpId = storeSnp(currentSnp, snpSynonyms);
variationIdToItemIdentifier.put(currentVariationId, currentSnp.getIdentifier());
if (!storedSnpIds.containsKey(storedSnpId)) {
storeSnpCollections(storedSnpId, consequenceIdentifiers);
}
}
LOG.info("Finished " + counter + " rows total, stored " + snpCounter + " SNPs for chr "
+ chrName);
LOG.info("variationIdToItemIdentifier.size() = " + variationIdToItemIdentifier.size());
}
private void processGenotypes(Connection connection) throws Exception {
// query for strains
ResultSet res = queryStrains(connection);
int strainCounter = 0;
while (res.next()) {
Integer strainId = res.getInt("sample_id");
String strainName = res.getString("name");
Item strain = createItem("Strain");
strain.setAttribute("name", strainName);
store(strain);
// for each strain query and store genotypes
processGenotypesForStrain(connection, strainId, strain.getIdentifier());
strainCounter++;
if (strainCounter >= 100) {
break;
}
}
}
private void processGenotypesForStrain(Connection connection, Integer strainId,
String strainIdentifier) throws Exception {
ResultSet res = queryGenotypesForStrain(connection, strainId);
int snpReferenceCount = 0;
int ignoredCount = 0;
while (res.next()) {
Integer variationId = res.getInt("variation_id");
String allele1 = res.getString("allele_1");
String allele2 = res.getString("allele_2");
String snpItemIdentifier = variationIdToItemIdentifier.get(variationId);
Item genotype = createItem("Genotype");
genotype.setAttribute("allele1", allele1);
genotype.setAttribute("allele2", allele2);
if (snpItemIdentifier != null) {
genotype.setReference("snp", snpItemIdentifier);
snpReferenceCount++;
}
else {
ignoredCount++;
}
genotype.setReference("strain", strainIdentifier);
store(genotype);
}
String message = "For strain " + strainId + " snp ref: " + snpReferenceCount + ", no ref: "
+ ignoredCount;
LOG.info(message);
System.out.println(message);
}
private ResultSet queryGenotypesForStrain(Connection connection, Integer strainId)
throws SQLException{
String query = "SELECT variation_id, allele_1, allele_2"
+ " FROM tmp_individual_genotype_single_bp"
+ " WHERE sample_id = " + strainId;
LOG.warn(query);
System.out.println(query);
Statement stmt = connection.createStatement();
ResultSet res = stmt.executeQuery(query);
return res;
}
private Integer storeSnp(Item snp, Set<String> synonyms) throws ObjectStoreException {
Integer storedSnpId = store(snp);
for (String synonym : synonyms) {
createSynonym(snp.getIdentifier(), synonym, true);
}
return storedSnpId;
}
private void storeSnpCollections(Integer storedSnpId, Set<String> consequenceIdentifiers)
throws ObjectStoreException {
if (!consequenceIdentifiers.isEmpty()) {
ReferenceList col =
new ReferenceList("consequences", new ArrayList<String>(consequenceIdentifiers));
store(col, storedSnpId);
}
}
/**
* Given an allele string read from the database determine the type of variation, e.g. snp,
* in-del, etc. This is a re-implementation of code from the Ensembl perl API, see:
* http://www.ensembl.org/info/docs/Pdoc/ensembl-variation/
* modules/Bio/EnsEMBL/Variation/Utils/Sequence.html#CODE4
* @param alleleStr the alleles to determine the type for
* @return a variation class or null if none can be determined
*/
protected String determineType(String alleleStr) {
String type = null;
final String VALID_BASES = "ATUGCYRSWKMBDHVN";
alleleStr = alleleStr.toUpperCase();
if (!StringUtils.isBlank(alleleStr)) {
// snp if e.g. A/C or A|C
if (alleleStr.matches("^[" + VALID_BASES + "]([\\/\\|\\\\][" + VALID_BASES + "])+$")) {
type = "snp";
} else if ("CNV".equals(alleleStr)) {
type = alleleStr.toLowerCase();
} else if ("CNV_PROBE".equals(alleleStr)) {
type = "cnv probe";
} else if ("HGMD_MUTATION".equals(alleleStr)) {
type = alleleStr.toLowerCase();
} else {
String[] alleles = alleleStr.split("[\\|\\/\\\\]");
if (alleles.length == 1) {
type = "het";
} else if (alleles.length == 2) {
if ((StringUtils.containsOnly(alleles[0],
VALID_BASES) && "-".equals(alleles[1]))
|| (StringUtils.containsOnly(alleles[1], VALID_BASES)
&& "-".equals(alleles[0]))) {
type = "in-del";
} else if (containsOneOf(alleles[0], "LARGE", "INS", "DEL")
|| containsOneOf(alleles[1], "LARGE", "INS", "DEL")) {
type = "named";
} else if ((StringUtils.containsOnly(alleles[0], VALID_BASES)
&& alleles[0].length() > 1)
|| (StringUtils.containsOnly(alleles[1], VALID_BASES)
&& alleles[1].length() > 1)) {
// AA/GC 2 alleles
type = "substitution";
}
} else if (alleles.length > 2) {
if (containsDigit(alleles[0])) {
type = "microsat";
} else if (anyContainChar(alleles, "-")) {
type = "mixed";
}
}
if (type == null) {
LOG.warn("Failed to work out allele type for: " + alleleStr);
}
}
}
return type;
}
private String getSourceIdentifier(String name) throws ObjectStoreException {
String sourceIdentifier = sources.get(name);
if (sourceIdentifier == null) {
Item source = createItem("Source");
source.setAttribute("name", name);
store(source);
sourceIdentifier = source.getIdentifier();
sources.put(name, sourceIdentifier);
}
return sourceIdentifier;
}
private String getTranscriptIdentifier(String transcriptStableId) throws ObjectStoreException {
String transcriptIdentifier = transcripts.get(transcriptStableId);
if (transcriptIdentifier == null) {
Item transcript = createItem("Transcript");
transcript.setAttribute("primaryIdentifier", transcriptStableId);
store(transcript);
transcriptIdentifier = transcript.getIdentifier();
transcripts.put(transcriptStableId, transcriptIdentifier);
}
return transcriptIdentifier;
}
private List<String> getValidationStateCollection(String input) throws ObjectStoreException {
List<String> stateIdentifiers = new ArrayList<String>();
if (!StringUtils.isBlank(input)) {
for (String state : input.split(",")) {
stateIdentifiers.add(getStateIdentifier(state));
}
}
return stateIdentifiers;
}
private String getStateIdentifier(String name) throws ObjectStoreException {
String stateIdentifier = states.get(name);
if (stateIdentifier == null) {
Item state = createItem("ValidationState");
state.setAttribute("name", name);
store(state);
stateIdentifier = state.getIdentifier();
states.put(name, stateIdentifier);
}
return stateIdentifier;
}
private String getConsequenceIdentifier(String type) throws ObjectStoreException {
String consequenceIdentifier = noTranscriptConsequences.get(type);
if (consequenceIdentifier == null) {
Item consequence = createItem("Consequence");
consequence.setAttribute("type", type);
store(consequence);
consequenceIdentifier = consequence.getIdentifier();
noTranscriptConsequences.put(type, consequenceIdentifier);
}
return consequenceIdentifier;
}
private ResultSet queryVariation(Connection connection, String chrName)
throws SQLException {
String query = "SELECT vf.variation_feature_id, vf.variation_name, vf.variation_id,"
+ " vf.allele_string, sr.name,"
+ " vf.map_weight, vf.seq_region_start, vf.seq_region_end, vf.seq_region_strand, "
+ " s.name,"
+ " vf.validation_status,"
+ " vf.consequence_type,"
+ " tv.cdna_start,tv.consequence_types,tv.pep_allele_string,tv.feature_stable_id,"
+ " vs.name"
+ " FROM seq_region sr, source s, variation_feature vf "
+ " LEFT JOIN (transcript_variation tv)"
+ " ON (vf.variation_feature_id = tv.variation_feature_id"
+ " AND tv.cdna_start is not null)"
+ " LEFT JOIN (variation_synonym vs)"
+ " ON (vf.variation_id = vs.variation_id"
+ " AND vs.source_id IN (" + StringUtil.join(getSnpSourceIds(connection), ",") + ")"
+ " WHERE vf.seq_region_id = sr.seq_region_id"
+ " AND vf.source_id = s.source_id"
+ " AND sr.name = '" + chrName + "'"
+ " ORDER BY vf.variation_id";
LOG.warn(query);
System.out.println(query);
Statement stmt = connection.createStatement();
ResultSet res = stmt.executeQuery(query);
return res;
}
private Set<String> getSnpSourceIds(Connection connection) throws SQLException {
if (snpSourceIds == null) {
snpSourceIds = new HashSet<String>();
String sql = "SELECT source_id FROM source";
if (snpSources != null && !snpSources.isEmpty()) {
sql += "WHERE name IN (" + StringUtil.join(snpSources, ",") + ")";
}
Statement stmt = connection.createStatement();
ResultSet res = stmt.executeQuery(sql);
while (res.next()) {
snpSourceIds.add(res.getString("source_id"));
}
if (snpSourceIds.isEmpty()) {
throw new RuntimeException("Failed to retrieve source_ids for dbSNP source");
}
}
return snpSourceIds;
}
private ResultSet queryStrains(Connection connection)
throws SQLException {
String query = "SELECT sample_id, name from sample";
LOG.warn(query);
System.out.println(query);
Statement stmt = connection.createStatement();
ResultSet res = stmt.executeQuery(query);
return res;
}
/**
* {@inheritDoc}
*/
@Override
public String getDataSetTitle(int taxonId) {
return DATASET_TITLE;
}
private boolean containsOneOf(String target, String... substrings) {
for (String substring : substrings) {
if (target.contains(substring)) {
return true;
}
}
return false;
}
private boolean anyContainChar(String[] targets, String substring) {
for (String target : targets) {
if (target.contains(substring)) {
return true;
}
}
return false;
}
private boolean containsDigit(String target) {
for (int i = 0; i < target.length(); i++) {
if (Character.isDigit(target.charAt(i))) {
return true;
}
}
return false;
}
}
|
Fix SQL query.
|
bio/sources/ensembl-snp-db/main/src/org/intermine/bio/dataconversion/EnsemblSnpDbConverter.java
|
Fix SQL query.
|
<ide><path>io/sources/ensembl-snp-db/main/src/org/intermine/bio/dataconversion/EnsemblSnpDbConverter.java
<ide> + " AND tv.cdna_start is not null)"
<ide> + " LEFT JOIN (variation_synonym vs)"
<ide> + " ON (vf.variation_id = vs.variation_id"
<del> + " AND vs.source_id IN (" + StringUtil.join(getSnpSourceIds(connection), ",") + ")"
<add> + " AND vs.source_id IN (" + makeInList(getSnpSourceIds(connection)) + ")"
<ide> + " WHERE vf.seq_region_id = sr.seq_region_id"
<ide> + " AND vf.source_id = s.source_id"
<ide> + " AND sr.name = '" + chrName + "'"
<ide> ResultSet res = stmt.executeQuery(query);
<ide> return res;
<ide> }
<add>
<add> private String makeInList(Collection<String> strings) {
<add> Set<String> quoted = new HashSet<String>();
<add> for (String s : strings) {
<add> quoted.add("'" + s + "'");
<add> }
<add> return StringUtil.join(quoted, ",");
<add> }
<add>
<ide>
<ide> private Set<String> getSnpSourceIds(Connection connection) throws SQLException {
<ide> if (snpSourceIds == null) {
|
|
Java
|
bsd-2-clause
|
error: pathspec 'src/main/java/forBiic/VisWithVNC.java' did not match any file(s) known to git
|
2c19493d660b4f410670685e22fa4976e891d627
| 1 |
saalfeldlab/template-building,saalfeldlab/template-building,saalfeldlab/template-building,saalfeldlab/template-building,saalfeldlab/template-building
|
package forBiic;
import bdv.util.Bdv;
import bdv.util.BdvFunctions;
import ij.IJ;
import ij.ImagePlus;
import net.imglib2.FinalInterval;
import net.imglib2.img.Img;
import net.imglib2.img.display.imagej.ImageJFunctions;
import net.imglib2.type.numeric.real.FloatType;
import net.imglib2.util.Intervals;
import net.imglib2.view.IntervalView;
import net.imglib2.view.Views;
/**
*
* Visualize current nicest brain and vnc templates for biic conference.
*
* Manually oriented the brain and vnc relative to one another, saved the settings here:
* /groups/saalfeld/public/fly-template/joint-brain-vnc-2.xml
*
* TODO - incorporate that transformation into this script
*/
public class VisWithVNC
{
public static void main( String[] args )
{
String brainTemplate = "/groups/saalfeld/public/fly-template/template.tif";
String vncTemplate = "/nrs/saalfeld/john/projects/flyChemStainAtlas/VNC_take6/all-flip-r1p5-affineCC/hiResRenders/VNC-template.tif";
ImagePlus brainIp = IJ.openImage( brainTemplate );
ImagePlus vncIp = IJ.openImage( vncTemplate );
Img< FloatType > brainimg = ImageJFunctions.convertFloat( brainIp );
Img< FloatType > vncimg = ImageJFunctions.convertFloat( vncIp );
FinalInterval unionInterval = Intervals.union( brainimg, vncimg );
// IntervalView< FloatType > both = Views.permute(
// Views.addDimension(
// Views.stack( brainimg, vncimg ), 0, 1),
// 4, 3);
IntervalView< FloatType > brainpad = Views.interval( Views.extendZero( brainimg ), unionInterval );
IntervalView< FloatType > vncpad = Views.interval( Views.extendZero( vncimg ), unionInterval );
IntervalView< FloatType > bothpad = Views.permute(
Views.addDimension(
Views.stack( brainpad, vncpad ), 0, 1),
4, 3);
Bdv bdv = BdvFunctions.show( bothpad, "Brain and VNC" );
bdv.getBdvHandle().getSetupAssignments().getMinMaxGroups().get( 0 ).setRange( 0, 1000 );
}
}
|
src/main/java/forBiic/VisWithVNC.java
|
Add script to create visualization for biic2017
|
src/main/java/forBiic/VisWithVNC.java
|
Add script to create visualization for biic2017
|
<ide><path>rc/main/java/forBiic/VisWithVNC.java
<add>package forBiic;
<add>
<add>import bdv.util.Bdv;
<add>import bdv.util.BdvFunctions;
<add>import ij.IJ;
<add>import ij.ImagePlus;
<add>import net.imglib2.FinalInterval;
<add>import net.imglib2.img.Img;
<add>import net.imglib2.img.display.imagej.ImageJFunctions;
<add>import net.imglib2.type.numeric.real.FloatType;
<add>import net.imglib2.util.Intervals;
<add>import net.imglib2.view.IntervalView;
<add>import net.imglib2.view.Views;
<add>
<add>/**
<add> *
<add> * Visualize current nicest brain and vnc templates for biic conference.
<add> *
<add> * Manually oriented the brain and vnc relative to one another, saved the settings here:
<add> * /groups/saalfeld/public/fly-template/joint-brain-vnc-2.xml
<add> *
<add> * TODO - incorporate that transformation into this script
<add> */
<add>public class VisWithVNC
<add>{
<add>
<add> public static void main( String[] args )
<add> {
<add> String brainTemplate = "/groups/saalfeld/public/fly-template/template.tif";
<add> String vncTemplate = "/nrs/saalfeld/john/projects/flyChemStainAtlas/VNC_take6/all-flip-r1p5-affineCC/hiResRenders/VNC-template.tif";
<add>
<add> ImagePlus brainIp = IJ.openImage( brainTemplate );
<add> ImagePlus vncIp = IJ.openImage( vncTemplate );
<add>
<add> Img< FloatType > brainimg = ImageJFunctions.convertFloat( brainIp );
<add> Img< FloatType > vncimg = ImageJFunctions.convertFloat( vncIp );
<add>
<add> FinalInterval unionInterval = Intervals.union( brainimg, vncimg );
<add>
<add>// IntervalView< FloatType > both = Views.permute(
<add>// Views.addDimension(
<add>// Views.stack( brainimg, vncimg ), 0, 1),
<add>// 4, 3);
<add>
<add> IntervalView< FloatType > brainpad = Views.interval( Views.extendZero( brainimg ), unionInterval );
<add> IntervalView< FloatType > vncpad = Views.interval( Views.extendZero( vncimg ), unionInterval );
<add>
<add> IntervalView< FloatType > bothpad = Views.permute(
<add> Views.addDimension(
<add> Views.stack( brainpad, vncpad ), 0, 1),
<add> 4, 3);
<add>
<add> Bdv bdv = BdvFunctions.show( bothpad, "Brain and VNC" );
<add> bdv.getBdvHandle().getSetupAssignments().getMinMaxGroups().get( 0 ).setRange( 0, 1000 );
<add> }
<add>
<add>}
|
|
JavaScript
|
mit
|
a4b022e263704709a7acdc3ca9683465e3880dde
| 0 |
FreeFeed/freefeed-server,golozubov/freefeed-server,golozubov/freefeed-server,FreeFeed/freefeed-server
|
import _ from 'lodash'
import validator from 'validator'
import NodeCache from 'node-cache'
import redis from 'redis'
import cacheManager from 'cache-manager'
import redisStore from 'cache-manager-redis'
import pgFormat from 'pg-format';
import { promisifyAll } from 'bluebird'
import { load as configLoader } from '../../config/config'
import { Attachment, Comment, Group, Post, Timeline, User } from '../models'
promisifyAll(redis.RedisClient.prototype);
promisifyAll(redis.Multi.prototype);
const unexistedUID = '00000000-0000-0000-C000-000000000046';
const USER_COLUMNS = {
username: 'username',
screenName: 'screen_name',
email: 'email',
description: 'description',
type: 'type',
profilePictureUuid: 'profile_picture_uuid',
createdAt: 'created_at',
updatedAt: 'updated_at',
directsReadAt: 'directs_read_at',
isPrivate: 'is_private',
isProtected: 'is_protected',
isRestricted: 'is_restricted',
hashedPassword: 'hashed_password',
resetPasswordToken: 'reset_password_token',
resetPasswordSentAt: 'reset_password_sent_at',
resetPasswordExpiresAt: 'reset_password_expires_at',
frontendPreferences: 'frontend_preferences'
}
const USER_COLUMNS_MAPPING = {
username: (username) => {return username.toLowerCase()},
createdAt: (timestamp) => {
const d = new Date()
d.setTime(timestamp)
return d.toISOString()
},
updatedAt: (timestamp) => {
const d = new Date()
d.setTime(timestamp)
return d.toISOString()
},
directsReadAt: (timestamp) => {
const d = new Date()
d.setTime(timestamp)
return d.toISOString()
},
isPrivate: (is_private) => {return is_private === '1'},
isProtected: (is_protected) => {return is_protected === '1'},
isRestricted: (is_restricted) => {return is_restricted === '1'},
resetPasswordSentAt: (timestamp) => {
const d = new Date()
d.setTime(timestamp)
return d.toISOString()
}
}
const USER_FIELDS = {
uid: 'id',
username: 'username',
screen_name: 'screenName',
email: 'email',
description: 'description',
type: 'type',
profile_picture_uuid: 'profilePictureUuid',
created_at: 'createdAt',
updated_at: 'updatedAt',
directs_read_at: 'directsReadAt',
is_private: 'isPrivate',
is_protected: 'isProtected',
is_restricted: 'isRestricted',
hashed_password: 'hashedPassword',
reset_password_token: 'resetPasswordToken',
reset_password_sent_at: 'resetPasswordSentAt',
reset_password_expires_at: 'resetPasswordExpiresAt',
frontend_preferences: 'frontendPreferences',
subscribed_feed_ids: 'subscribedFeedIds',
private_meta: 'privateMeta'
};
const USER_FIELDS_MAPPING = {
created_at: (time) => { return time.getTime().toString() },
updated_at: (time) => { return time.getTime().toString() },
is_private: (is_private) => {return is_private ? '1' : '0' },
is_protected: (is_protected) => {return is_protected ? '1' : '0' },
is_restricted: (is_restricted) => {return is_restricted ? '1' : '0' },
reset_password_sent_at: (time) => { return time && time.getTime() },
reset_password_expires_at: (time) => { return time && time.getTime() },
private_meta: (data) => data || {}
};
const USER_STATS_FIELDS = {
posts_count: 'posts',
likes_count: 'likes',
comments_count: 'comments',
subscribers_count: 'subscribers',
subscriptions_count: 'subscriptions'
}
const ATTACHMENT_COLUMNS = {
createdAt: 'created_at',
updatedAt: 'updated_at',
fileName: 'file_name',
fileSize: 'file_size',
mimeType: 'mime_type',
mediaType: 'media_type',
fileExtension: 'file_extension',
noThumbnail: 'no_thumbnail',
imageSizes: 'image_sizes',
artist: 'artist',
title: 'title',
userId: 'user_id',
postId: 'post_id'
}
const ATTACHMENT_COLUMNS_MAPPING = {
createdAt: (timestamp) => {
const d = new Date()
d.setTime(timestamp)
return d.toISOString()
},
updatedAt: (timestamp) => {
const d = new Date()
d.setTime(timestamp)
return d.toISOString()
},
noThumbnail: (no_thumbnail) => {return no_thumbnail === '1'},
fileSize: (file_size) => {
return parseInt(file_size, 10)
},
postId: (post_id) => {
if (validator.isUUID(post_id, 4)) {
return post_id
}
return null
},
userId: (user_id) => {
if (validator.isUUID(user_id, 4)) {
return user_id
}
return null
}
}
const ATTACHMENT_FIELDS = {
uid: 'id',
created_at: 'createdAt',
updated_at: 'updatedAt',
file_name: 'fileName',
file_size: 'fileSize',
mime_type: 'mimeType',
media_type: 'mediaType',
file_extension: 'fileExtension',
no_thumbnail: 'noThumbnail',
image_sizes: 'imageSizes',
artist: 'artist',
title: 'title',
user_id: 'userId',
post_id: 'postId'
}
const ATTACHMENT_FIELDS_MAPPING = {
created_at: (time) => { return time.getTime().toString() },
updated_at: (time) => { return time.getTime().toString() },
no_thumbnail: (no_thumbnail) => {return no_thumbnail ? '1' : '0' },
file_size: (file_size) => {return file_size && file_size.toString()},
post_id: (post_id) => {return post_id ? post_id : ''},
user_id: (user_id) => {return user_id ? user_id : ''}
}
const COMMENT_COLUMNS = {
createdAt: 'created_at',
updatedAt: 'updated_at',
body: 'body',
postId: 'post_id',
userId: 'user_id'
}
const COMMENT_COLUMNS_MAPPING = {
createdAt: (timestamp) => {
const d = new Date()
d.setTime(timestamp)
return d.toISOString()
},
updatedAt: (timestamp) => {
const d = new Date()
d.setTime(timestamp)
return d.toISOString()
}
}
const COMMENT_FIELDS = {
uid: 'id',
created_at: 'createdAt',
updated_at: 'updatedAt',
body: 'body',
user_id: 'userId',
post_id: 'postId'
}
const COMMENT_FIELDS_MAPPING = {
created_at: (time) => { return time.getTime().toString() },
updated_at: (time) => { return time.getTime().toString() },
post_id: (post_id) => {return post_id ? post_id : ''},
user_id: (user_id) => {return user_id ? user_id : ''}
}
const FEED_COLUMNS = {
createdAt: 'created_at',
updatedAt: 'updated_at',
name: 'name',
userId: 'user_id'
}
const FEED_COLUMNS_MAPPING = {
createdAt: (timestamp) => {
const d = new Date()
d.setTime(timestamp)
return d.toISOString()
},
updatedAt: (timestamp) => {
const d = new Date()
d.setTime(timestamp)
return d.toISOString()
}
}
const FEED_FIELDS = {
id: 'intId',
uid: 'id',
created_at: 'createdAt',
updated_at: 'updatedAt',
name: 'name',
user_id: 'userId'
}
const FEED_FIELDS_MAPPING = {
created_at: (time) => { return time.getTime().toString() },
updated_at: (time) => { return time.getTime().toString() },
user_id: (user_id) => {return user_id ? user_id : ''}
}
const POST_COLUMNS = {
createdAt: 'created_at',
updatedAt: 'updated_at',
userId: 'user_id',
body: 'body',
commentsDisabled: 'comments_disabled',
isPrivate: 'is_private',
isProtected: 'is_protected',
}
const POST_COLUMNS_MAPPING = {
createdAt: (timestamp) => {
const d = new Date()
d.setTime(timestamp)
return d.toISOString()
},
updatedAt: (timestamp) => {
const d = new Date()
d.setTime(timestamp)
return d.toISOString()
},
commentsDisabled: (comments_disabled) => {return comments_disabled === '1'},
userId: (user_id) => {
if (validator.isUUID(user_id, 4)) {
return user_id
}
return null
},
isPrivate: (is_private) => {return is_private === '1'},
isProtected: (is_protected) => {return is_protected === '1'},
}
const POST_FIELDS = {
uid: 'id',
created_at: 'createdAt',
updated_at: 'updatedAt',
user_id: 'userId',
body: 'body',
comments_disabled: 'commentsDisabled',
feed_ids: 'feedIntIds',
destination_feed_ids: 'destinationFeedIds',
comments_count: 'commentsCount',
likes_count: 'likesCount',
is_private: 'isPrivate',
is_protected: 'isProtected',
}
const POST_FIELDS_MAPPING = {
created_at: (time) => { return time.getTime().toString() },
updated_at: (time) => { return time.getTime().toString() },
comments_disabled: (comments_disabled) => {return comments_disabled ? '1' : '0' },
user_id: (user_id) => {return user_id ? user_id : ''},
is_private: (is_private) => {return is_private ? '1' : '0' },
is_protected: (is_protected) => {return is_protected ? '1' : '0' },
}
export class DbAdapter {
constructor(database) {
this.database = database
this.statsCache = promisifyAll(new NodeCache({ stdTTL: 300 }))
const config = configLoader()
const CACHE_TTL = 60 * 60 * 24 // 24 hours
this.memoryCache = cacheManager.caching({ store: 'memory', max: 5000, ttl: CACHE_TTL })
this.cache = cacheManager.caching({ store: redisStore, host: config.redis.host, port: config.redis.port, ttl: CACHE_TTL })
promisifyAll(this.cache)
promisifyAll(this.memoryCache)
promisifyAll(this.cache.store)
}
static initObject(classDef, attrs, id, params) {
return new classDef({ ...attrs, ...{ id }, ...params })
}
///////////////////////////////////////////////////
// User
///////////////////////////////////////////////////
_prepareModelPayload(payload, namesMapping, valuesMapping) {
return _.transform(payload, (result, val, key) => {
let mappedVal = val
if (valuesMapping[key]) {
mappedVal = valuesMapping[key](val)
}
const mappedKey = namesMapping[key]
if (mappedKey) {
result[mappedKey] = mappedVal
}
})
}
initUserObject = (attrs) => {
if (!attrs) {
return null;
}
attrs = this._prepareModelPayload(attrs, USER_FIELDS, USER_FIELDS_MAPPING)
return DbAdapter.initObject(attrs.type === 'group' ? Group : User, attrs, attrs.id)
}
async createUser(payload) {
const preparedPayload = this._prepareModelPayload(payload, USER_COLUMNS, USER_COLUMNS_MAPPING)
const res = await this.database('users').returning('uid').insert(preparedPayload)
const uid = res[0]
await this.createUserStats(uid)
return uid
}
updateUser(userId, payload) {
const tokenExpirationTime = new Date(Date.now())
const expireAfter = 60 * 60 * 24 // 24 hours
const preparedPayload = this._prepareModelPayload(payload, USER_COLUMNS, USER_COLUMNS_MAPPING)
if (_.has(preparedPayload, 'reset_password_token')) {
tokenExpirationTime.setHours(tokenExpirationTime.getHours() + expireAfter)
preparedPayload['reset_password_expires_at'] = tokenExpirationTime.toISOString()
}
this.cacheFlushUser(userId)
return this.database('users').where('uid', userId).update(preparedPayload)
}
setUpdatedAtInGroupsByIds = async (groupIds, time) => {
const updatedAt = new Date();
updatedAt.setTime(time);
const sql = pgFormat(`UPDATE "users" SET "updated_at" = ? WHERE "uid" IN (%L) AND "type"='group' RETURNING "uid"`, groupIds);
const uids = await this.database.raw(sql, [updatedAt.toISOString()]);
const flushPromises = uids.rows.map((row) => this.cacheFlushUser(row.uid));
await Promise.all(flushPromises);
};
async existsUser(userId) {
const res = await this.database('users').where('uid', userId).count()
return parseInt(res[0].count)
}
async existsUsername(username) {
const res = await this.database('users').where('username', username).count()
return parseInt(res[0].count)
}
async existsUserEmail(email) {
const res = await this.database('users').whereRaw('LOWER(email)=LOWER(?)', email).count()
return parseInt(res[0].count)
}
async getUserById(id) {
const user = await this.getFeedOwnerById(id)
if (!user) {
return null
}
if (!(user instanceof User)) {
throw new Error(`Expected User, got ${user.constructor.name}`)
}
return user
}
async getUsersByIds(userIds) {
const users = await this.getFeedOwnersByIds(userIds)
_.each(users, (user) => {
if (!(user instanceof User)) {
throw new Error(`Expected User, got ${user.constructor.name}`)
}
})
return users
}
async getUserByUsername(username) {
const feed = await this.getFeedOwnerByUsername(username)
if (null === feed) {
return null
}
if (!(feed instanceof User)) {
throw new Error(`Expected User, got ${feed.constructor.name}`)
}
return feed
}
async getUserByResetToken(token) {
const attrs = await this.database('users').first().where('reset_password_token', token)
if (!attrs) {
return null
}
if (attrs.type !== 'user') {
throw new Error(`Expected User, got ${attrs.type}`)
}
const now = new Date().getTime()
if (attrs.reset_password_expires_at < now) {
return null
}
return this.initUserObject(attrs);
}
async getUserByEmail(email) {
const attrs = await this.database('users').first().whereRaw('LOWER(email)=LOWER(?)', email)
if (!attrs) {
return null
}
if (attrs.type !== 'user') {
throw new Error(`Expected User, got ${attrs.type}`)
}
return this.initUserObject(attrs);
}
async getFeedOwnerById(id) {
if (!validator.isUUID(id, 4)) {
return null
}
return this.initUserObject(await this.fetchUser(id));
}
async getFeedOwnersByIds(ids) {
return (await this.fetchUsers(ids)).map(this.initUserObject);
}
async getUsersByIdsAssoc(ids) {
return _.mapValues(await this.fetchUsersAssoc(ids), this.initUserObject);
}
async getFeedOwnerByUsername(username) {
const attrs = await this.database('users').first().where('username', username.toLowerCase())
return this.initUserObject(attrs);
}
async getGroupById(id) {
const user = await this.getFeedOwnerById(id)
if (!user) {
return null
}
if (!(user instanceof Group)) {
throw new Error(`Expected Group, got ${user.constructor.name}`)
}
return user
}
async getGroupByUsername(username) {
const feed = await this.getFeedOwnerByUsername(username)
if (null === feed) {
return null
}
if (!(feed instanceof Group)) {
throw new Error(`Expected Group, got ${feed.constructor.name}`)
}
return feed
}
async getUserSubscribersIds(userId) {
return await this.database
.pluck('s.user_id')
.from('subscriptions as s')
.innerJoin('feeds as f', 'f.uid', 's.feed_id')
.where('f.name', 'Posts')
.where('f.user_id', userId)
.orderBy('s.created_at', 'desc');
}
///////////////////////////////////////////////////
// User's attributes caching
///////////////////////////////////////////////////
async cacheFlushUser(id) {
const cacheKey = `user_${id}`
await this.cache.delAsync(cacheKey)
}
fixDateType = (date) => {
if (_.isString(date)) {
return new Date(date);
}
if (_.isDate(date)) {
return date;
}
return null;
};
fixCachedUserAttrs = (attrs) => {
if (!attrs) {
return null;
}
// Convert dates back to the Date type
attrs['created_at'] = this.fixDateType(attrs['created_at']);
attrs['updated_at'] = this.fixDateType(attrs['updated_at']);
attrs['reset_password_sent_at'] = this.fixDateType(attrs['reset_password_sent_at']);
attrs['reset_password_expires_at'] = this.fixDateType(attrs['reset_password_expires_at']);
return attrs;
};
getCachedUserAttrs = async (id) => {
return this.fixCachedUserAttrs(await this.cache.getAsync(`user_${id}`))
};
async fetchUser(id) {
let attrs = await this.getCachedUserAttrs(id);
if (!attrs) {
// Cache miss, read from the database
attrs = await this.database('users').first().where('uid', id) || null;
if (attrs) {
await this.cache.setAsync(`user_${id}`, attrs);
}
}
return attrs;
}
/**
* Returns plain object with ids as keys and user attributes as values
*/
async fetchUsersAssoc(ids) {
const idToUser = {};
if (_.isEmpty(ids)) {
return idToUser;
}
const uniqIds = _.uniq(ids);
let cachedUsers;
if (this.cache.store.name === 'redis') {
const { client, done } = await this.cache.store.getClientAsync();
try {
const cacheKeys = ids.map((id) => `user_${id}`);
const result = await client.mgetAsync(cacheKeys);
cachedUsers = result.map((x) => x ? JSON.parse(x) : null).map(this.fixCachedUserAttrs);
} finally {
done();
}
} else {
cachedUsers = await Promise.all(uniqIds.map(this.getCachedUserAttrs));
}
const notFoundIds = _.compact(cachedUsers.map((attrs, i) => attrs ? null : uniqIds[i]));
const dbUsers = notFoundIds.length === 0 ? [] : await this.database('users').whereIn('uid', notFoundIds);
await Promise.all(dbUsers.map((attrs) => this.cache.setAsync(`user_${attrs.uid}`, attrs)));
_.compact(cachedUsers).forEach((attrs) => idToUser[attrs.uid] = attrs);
dbUsers.forEach((attrs) => idToUser[attrs.uid] = attrs);
return idToUser;
}
async fetchUsers(ids) {
const idToUser = await this.fetchUsersAssoc(ids);
return ids.map((id) => idToUser[id] || null);
}
async someUsersArePublic(userIds, anonymousFriendly) {
const anonymousCondition = anonymousFriendly ? 'AND not "is_protected"' : '';
const q = pgFormat(`SELECT COUNT("id") AS "cnt" FROM "users" WHERE not "is_private" ${anonymousCondition} AND "uid" IN (%L)`, userIds);
const res = await this.database.raw(q);
return res.rows[0].cnt > 0;
}
///////////////////////////////////////////////////
// User statistics
///////////////////////////////////////////////////
async createUserStats(userId) {
const res = await this.database('user_stats').insert({ user_id: userId })
return res
}
async getUserStats(userId) {
let userStats
// Check the cache first
const cachedUserStats = await this.statsCache.getAsync(userId)
if (typeof cachedUserStats != 'undefined') {
// Cache hit
userStats = cachedUserStats
} else {
// Cache miss, read from the database
const res = await this.database('user_stats').where('user_id', userId)
userStats = res[0]
await this.statsCache.setAsync(userId, userStats)
}
return this._prepareModelPayload(userStats, USER_STATS_FIELDS, {})
}
/**
* Returns plain object with user ids as keys and user stats as values
*/
async getUsersStatsAssoc(ids) {
const idToStat = {};
if (_.isEmpty(ids)) {
return idToStat;
}
const uniqIds = _.compact(_.uniq(ids));
const cachedStats = await Promise.all(uniqIds.map((id) => this.statsCache.getAsync(id)));
const notFoundIds = _.compact(cachedStats.map((stat, i) => stat ? null : uniqIds[i]));
const dbStats = notFoundIds.length === 0 ? [] : await this.database('user_stats').whereIn('user_id', notFoundIds);
await Promise.all(dbStats.map((stat) => this.statsCache.setAsync(stat.user_id, stat)));
_.compact(cachedStats).forEach((stat) => idToStat[stat.user_id] = this._prepareModelPayload(stat, USER_STATS_FIELDS, {}));
dbStats.forEach((stat) => idToStat[stat.user_id] = this._prepareModelPayload(stat, USER_STATS_FIELDS, {}));
return idToStat;
}
async calculateUserStats(userId) {
const userFeeds = await this.database('users').select('subscribed_feed_ids').where('uid', userId)
const readableFeedsIds = userFeeds[0].subscribed_feed_ids
const userPostsFeed = await this.database('feeds').returning('uid').where({
user_id: userId,
name: 'Posts'
});
if (!userPostsFeed[0]) {
// hard-reserved username without other data-structures
return;
}
const userPostsFeedId = userPostsFeed[0].uid
const readablePostFeeds = this.database('feeds').whereIn('id', readableFeedsIds).where('name', 'Posts')
const promises = [
this.getUserPostsCount(userId),
this.getUserLikesCount(userId),
this.getUserCommentsCount(userId),
this.getTimelineSubscribersIds(userPostsFeedId),
readablePostFeeds
]
const values = await Promise.all(promises)
const payload = {
posts_count: values[0],
likes_count: values[1],
comments_count: values[2],
subscribers_count: values[3].length,
subscriptions_count: values[4].length
}
await this.database('user_stats').where('user_id', userId).update(payload)
// Invalidate cache
await this.statsCache.delAsync(userId)
}
statsCommentCreated(authorId) {
return this.incrementStatsCounter(authorId, 'comments_count')
}
statsCommentDeleted(authorId) {
return this.decrementStatsCounter(authorId, 'comments_count')
}
statsLikeCreated(authorId) {
return this.incrementStatsCounter(authorId, 'likes_count')
}
statsLikeDeleted(authorId) {
return this.decrementStatsCounter(authorId, 'likes_count')
}
statsPostCreated(authorId) {
return this.incrementStatsCounter(authorId, 'posts_count')
}
async statsPostDeleted(authorId, postId) {
const postLikers = await this.getPostLikersIdsWithoutBannedUsers(postId, null)
const promises = postLikers.map((id) => {
return this.calculateUserStats(id)
})
await Promise.all(promises)
if (!postLikers.includes(authorId)) {
return this.decrementStatsCounter(authorId, 'posts_count')
}
return null
}
statsSubscriptionCreated(userId) {
return this.incrementStatsCounter(userId, 'subscriptions_count')
}
statsSubscriptionDeleted(userId) {
return this.decrementStatsCounter(userId, 'subscriptions_count')
}
statsSubscriberAdded(userId) {
return this.incrementStatsCounter(userId, 'subscribers_count')
}
statsSubscriberRemoved(userId) {
return this.decrementStatsCounter(userId, 'subscribers_count')
}
async incrementStatsCounter(userId, counterName) {
await this.database.transaction(async (trx) => {
try {
const res = await this.database('user_stats')
.transacting(trx).forUpdate()
.where('user_id', userId)
const stats = res[0]
const val = parseInt(stats[counterName], 10) + 1
stats[counterName] = val
await this.database('user_stats')
.transacting(trx)
.where('user_id', userId)
.update(stats)
await trx.commit();
} catch (e) {
await trx.rollback();
throw e;
}
});
// Invalidate cache
await this.statsCache.delAsync(userId)
}
async decrementStatsCounter(userId, counterName) {
await this.database.transaction(async (trx) => {
try {
const res = await this.database('user_stats')
.transacting(trx).forUpdate()
.where('user_id', userId)
const stats = res[0]
const val = parseInt(stats[counterName]) - 1
if (val < 0) {
throw new Error(`Negative user stats: ${counterName} of ${userId}`);
}
stats[counterName] = val
await this.database('user_stats')
.transacting(trx)
.where('user_id', userId)
.update(stats)
await trx.commit();
} catch (e) {
await trx.rollback();
throw e;
}
});
// Invalidate cache
await this.statsCache.delAsync(userId)
}
///////////////////////////////////////////////////
// Subscription requests
///////////////////////////////////////////////////
createSubscriptionRequest(fromUserId, toUserId) {
const currentTime = new Date().toISOString()
const payload = {
from_user_id: fromUserId,
to_user_id: toUserId,
created_at: currentTime
}
return this.database('subscription_requests').returning('id').insert(payload)
}
deleteSubscriptionRequest(toUserId, fromUserId) {
return this.database('subscription_requests').where({
from_user_id: fromUserId,
to_user_id: toUserId
}).delete()
}
async getUserSubscriptionRequestsIds(toUserId) {
const res = await this.database('subscription_requests').select('from_user_id').orderBy('created_at', 'desc').where('to_user_id', toUserId)
const attrs = res.map((record) => {
return record.from_user_id
})
return attrs
}
async isSubscriptionRequestPresent(fromUserId, toUserId) {
const res = await this.database('subscription_requests').where({
from_user_id: fromUserId,
to_user_id: toUserId
}).count()
return parseInt(res[0].count) != 0
}
async getUserSubscriptionPendingRequestsIds(fromUserId) {
const res = await this.database('subscription_requests').select('to_user_id').orderBy('created_at', 'desc').where('from_user_id', fromUserId)
const attrs = res.map((record) => {
return record.to_user_id
})
return attrs
}
///////////////////////////////////////////////////
// Bans
///////////////////////////////////////////////////
async getUserBansIds(userId) {
const res = await this.database('bans').select('banned_user_id').orderBy('created_at', 'desc').where('user_id', userId);
return res.map((record) => record.banned_user_id);
}
async getUserIdsWhoBannedUser(userId) {
const res = await this.database('bans').select('user_id').orderBy('created_at', 'desc').where('banned_user_id', userId);
return res.map((record) => record.user_id);
}
async getBannedFeedsIntIds(userId) {
return await this.database
.pluck('feeds.id')
.from('feeds')
.innerJoin('bans', 'bans.banned_user_id', 'feeds.user_id')
.where('feeds.name', 'Posts')
.where('bans.user_id', userId);
}
async getBanMatrixByUsersForPostReader(bannersUserIds, targetUserId) {
let res = [];
if (targetUserId) {
res = await this.database('bans')
.where('banned_user_id', targetUserId)
.where('user_id', 'in', bannersUserIds)
.orderByRaw(`position(user_id::text in '${bannersUserIds.toString()}')`)
}
const matrix = bannersUserIds.map((id) => {
const foundBan = res.find((record) => record.user_id == id);
return foundBan ? [id, true] : [id, false];
});
return matrix
}
createUserBan(currentUserId, bannedUserId) {
const currentTime = new Date().toISOString()
const payload = {
user_id: currentUserId,
banned_user_id: bannedUserId,
created_at: currentTime
}
return this.database('bans').returning('id').insert(payload)
}
deleteUserBan(currentUserId, bannedUserId) {
return this.database('bans').where({
user_id: currentUserId,
banned_user_id: bannedUserId
}).delete()
}
///////////////////////////////////////////////////
// Group administrators
///////////////////////////////////////////////////
getGroupAdministratorsIds(groupId) {
return this.database('group_admins').pluck('user_id').orderBy('created_at', 'desc').where('group_id', groupId)
}
/**
* Returns plain object with group UIDs as keys and arrays of admin UIDs as values
*/
async getGroupsAdministratorsIds(groupIds) {
const rows = await this.database.select('group_id', 'user_id').from('group_admins').where('group_id', 'in', groupIds);
const res = {};
rows.forEach(({ group_id, user_id }) => {
if (!res.hasOwnProperty(group_id)) {
res[group_id] = [];
}
res[group_id].push(user_id);
});
return res;
}
addAdministratorToGroup(groupId, adminId) {
const currentTime = new Date().toISOString()
const payload = {
user_id: adminId,
group_id: groupId,
created_at: currentTime
}
return this.database('group_admins').returning('id').insert(payload)
}
removeAdministratorFromGroup(groupId, adminId) {
return this.database('group_admins').where({
user_id: adminId,
group_id: groupId
}).delete()
}
getManagedGroupIds(userId) {
return this.database('group_admins').pluck('group_id').orderBy('created_at', 'desc').where('user_id', userId);
}
async userHavePendingGroupRequests(userId) {
const res = await this.database.first('r.id')
.from('subscription_requests as r')
.innerJoin('group_admins as a', 'a.group_id', 'r.to_user_id')
.where({ 'a.user_id': userId })
.limit(1);
return !!res;
}
/**
* Returns plain object with group UIDs as keys and arrays of requester's UIDs as values
*/
async getPendingGroupRequests(groupsAdminId) {
const rows = await this.database.select('r.from_user_id as user_id', 'r.to_user_id as group_id')
.from('subscription_requests as r')
.innerJoin('group_admins as a', 'a.group_id', 'r.to_user_id')
.where({ 'a.user_id': groupsAdminId });
const res = {};
rows.forEach(({ group_id, user_id }) => {
if (!res.hasOwnProperty(group_id)) {
res[group_id] = [];
}
res[group_id].push(user_id);
});
return res;
}
///////////////////////////////////////////////////
// Attachments
///////////////////////////////////////////////////
initAttachmentObject = (attrs) => {
if (!attrs) {
return null;
}
attrs = this._prepareModelPayload(attrs, ATTACHMENT_FIELDS, ATTACHMENT_FIELDS_MAPPING);
return DbAdapter.initObject(Attachment, attrs, attrs.id);
};
async createAttachment(payload) {
const preparedPayload = this._prepareModelPayload(payload, ATTACHMENT_COLUMNS, ATTACHMENT_COLUMNS_MAPPING)
const res = await this.database('attachments').returning('uid').insert(preparedPayload)
return res[0]
}
async getAttachmentById(id) {
if (!validator.isUUID(id, 4)) {
return null
}
const attrs = await this.database('attachments').first().where('uid', id)
return this.initAttachmentObject(attrs);
}
async getAttachmentsByIds(ids) {
const responses = await this.database('attachments').whereIn('uid', ids).orderByRaw(`position(uid::text in '${ids.toString()}')`)
return responses.map(this.initAttachmentObject)
}
updateAttachment(attachmentId, payload) {
const preparedPayload = this._prepareModelPayload(payload, ATTACHMENT_COLUMNS, ATTACHMENT_COLUMNS_MAPPING)
return this.database('attachments').where('uid', attachmentId).update(preparedPayload)
}
linkAttachmentToPost(attachmentId, postId) {
const payload = { post_id: postId }
return this.database('attachments').where('uid', attachmentId).update(payload)
}
unlinkAttachmentFromPost(attachmentId, postId) {
const payload = { post_id: null }
return this.database('attachments').where('uid', attachmentId).where('post_id', postId).update(payload)
}
async getPostAttachments(postId) {
const res = await this.database('attachments').select('uid').orderBy('created_at', 'asc').where('post_id', postId)
const attrs = res.map((record) => {
return record.uid
})
return attrs
}
async getAttachmentsOfPost(postId) {
const responses = await this.database('attachments').orderBy('created_at', 'asc').where('post_id', postId)
return responses.map(this.initAttachmentObject)
}
///////////////////////////////////////////////////
// Likes
///////////////////////////////////////////////////
createUserPostLike(postId, userId) {
const currentTime = new Date().toISOString()
const payload = {
post_id: postId,
user_id: userId,
created_at: currentTime
}
return this.database('likes').returning('id').insert(payload)
}
async getPostLikesCount(postId) {
const res = await this.database('likes').where({ post_id: postId }).count()
return parseInt(res[0].count)
}
async getUserLikesCount(userId) {
const res = await this.database('likes').where({ user_id: userId }).count()
return parseInt(res[0].count)
}
async getPostLikersIdsWithoutBannedUsers(postId, viewerUserId) {
let query = this.database('likes').select('user_id').orderBy('created_at', 'desc').where('post_id', postId);
if (viewerUserId) {
const subquery = this.database('bans').select('banned_user_id').where('user_id', viewerUserId)
query = query.where('user_id', 'not in', subquery)
}
const res = await query;
const userIds = res.map((record) => record.user_id)
return userIds
}
async hasUserLikedPost(userId, postId) {
const res = await this.database('likes').where({
post_id: postId,
user_id: userId
}).count()
return parseInt(res[0].count) != 0
}
async getUserPostLikedTime(userId, postId) {
const res = await this.database('likes').select('created_at').where({
post_id: postId,
user_id: userId
})
const record = res[0]
if (!record) {
return null
}
return record.created_at.getTime()
}
removeUserPostLike(postId, userId) {
return this.database('likes').where({
post_id: postId,
user_id: userId
}).delete()
}
_deletePostLikes(postId) {
return this.database('likes').where({ post_id: postId }).delete()
}
///////////////////////////////////////////////////
// Comments
///////////////////////////////////////////////////
initCommentObject = (attrs) => {
if (!attrs) {
return null;
}
attrs = this._prepareModelPayload(attrs, COMMENT_FIELDS, COMMENT_FIELDS_MAPPING);
return DbAdapter.initObject(Comment, attrs, attrs.id);
};
async createComment(payload) {
const preparedPayload = this._prepareModelPayload(payload, COMMENT_COLUMNS, COMMENT_COLUMNS_MAPPING)
const res = await this.database('comments').returning('uid').insert(preparedPayload)
return res[0]
}
async getCommentById(id) {
if (!validator.isUUID(id, 4)) {
return null
}
const attrs = await this.database('comments').first().where('uid', id)
return this.initCommentObject(attrs);
}
updateComment(commentId, payload) {
const preparedPayload = this._prepareModelPayload(payload, COMMENT_COLUMNS, COMMENT_COLUMNS_MAPPING)
return this.database('comments').where('uid', commentId).update(preparedPayload)
}
deleteComment(commentId, postId) {
return this.database('comments').where({
uid: commentId,
post_id: postId
}).delete()
}
async getPostCommentsCount(postId) {
const res = await this.database('comments').where({ post_id: postId }).count()
return parseInt(res[0].count)
}
async getUserCommentsCount(userId) {
const res = await this.database('comments').where({ user_id: userId }).count()
return parseInt(res[0].count)
}
async getAllPostCommentsWithoutBannedUsers(postId, viewerUserId) {
let query = this.database('comments').orderBy('created_at', 'asc').where('post_id', postId);
if (viewerUserId) {
const subquery = this.database('bans').select('banned_user_id').where('user_id', viewerUserId);
query = query.where('user_id', 'not in', subquery);
}
const responses = await query;
return responses.map(this.initCommentObject);
}
_deletePostComments(postId) {
return this.database('comments').where({ post_id: postId }).delete()
}
///////////////////////////////////////////////////
// Feeds
///////////////////////////////////////////////////
initTimelineObject = (attrs, params) => {
if (!attrs) {
return null;
}
attrs = this._prepareModelPayload(attrs, FEED_FIELDS, FEED_FIELDS_MAPPING)
return DbAdapter.initObject(Timeline, attrs, attrs.id, params)
}
async createTimeline(payload) {
const preparedPayload = this._prepareModelPayload(payload, FEED_COLUMNS, FEED_COLUMNS_MAPPING)
if (preparedPayload.name == 'MyDiscussions') {
preparedPayload.uid = preparedPayload.user_id
}
const res = await this.database('feeds').returning(['id', 'uid']).insert(preparedPayload)
return { intId: res[0].id, id: res[0].uid }
}
createUserTimelines(userId, timelineNames) {
const currentTime = new Date().getTime()
const promises = timelineNames.map((n) => {
const payload = {
'name': n,
userId,
'createdAt': currentTime.toString(),
'updatedAt': currentTime.toString()
}
return this.createTimeline(payload)
})
return Promise.all(promises)
}
async cacheFetchUserTimelinesIds(userId) {
const cacheKey = `timelines_user_${userId}`;
// Check the cache first
const cachedTimelines = await this.memoryCache.getAsync(cacheKey);
if (typeof cachedTimelines != 'undefined' && cachedTimelines) {
// Cache hit
return cachedTimelines;
}
// Cache miss, read from the database
const res = await this.database('feeds').where('user_id', userId);
const riverOfNews = _.filter(res, (record) => { return record.name == 'RiverOfNews'});
const hides = _.filter(res, (record) => { return record.name == 'Hides'});
const comments = _.filter(res, (record) => { return record.name == 'Comments'});
const likes = _.filter(res, (record) => { return record.name == 'Likes'});
const posts = _.filter(res, (record) => { return record.name == 'Posts'});
const directs = _.filter(res, (record) => { return record.name == 'Directs'});
const myDiscussions = _.filter(res, (record) => { return record.name == 'MyDiscussions'});
const timelines = {
'RiverOfNews': riverOfNews[0] && riverOfNews[0].uid,
'Hides': hides[0] && hides[0].uid,
'Comments': comments[0] && comments[0].uid,
'Likes': likes[0] && likes[0].uid,
'Posts': posts[0] && posts[0].uid
};
if (directs[0]) {
timelines['Directs'] = directs[0].uid;
}
if (myDiscussions[0]) {
timelines['MyDiscussions'] = myDiscussions[0].uid;
}
if (res.length) {
// Don not cache empty feeds lists
await this.memoryCache.setAsync(cacheKey, timelines);
}
return timelines;
}
async getUserTimelinesIds(userId) {
return await this.cacheFetchUserTimelinesIds(userId);
}
async getTimelineById(id, params) {
if (!validator.isUUID(id, 4)) {
return null
}
const attrs = await this.database('feeds').first().where('uid', id);
return this.initTimelineObject(attrs, params);
}
async getTimelineByIntId(id, params) {
const attrs = await this.database('feeds').first().where('id', id);
return this.initTimelineObject(attrs, params);
}
async getTimelinesByIds(ids, params) {
const responses = await this.database('feeds').whereIn('uid', ids).orderByRaw(`position(uid::text in '${ids.toString()}')`);
return responses.map((r) => this.initTimelineObject(r, params));
}
async getTimelinesByIntIds(ids, params) {
const responses = await this.database('feeds').whereIn('id', ids).orderByRaw(`position(id::text in '${ids.toString()}')`);
return responses.map((r) => this.initTimelineObject(r, params));
}
async getTimelinesIntIdsByUUIDs(uuids) {
const responses = await this.database('feeds').select('id').whereIn('uid', uuids);
return responses.map((record) => record.id);
}
async getTimelinesUUIDsByIntIds(ids) {
const responses = await this.database('feeds').select('uid').whereIn('id', ids)
const uuids = responses.map((record) => {
return record.uid
})
return uuids
}
async getTimelinesUserSubscribed(userId, feedType = null) {
const where = { 's.user_id': userId };
if (feedType !== null) {
where['f.name'] = feedType;
}
const records = await this.database
.select('f.*')
.from('subscriptions as s')
.innerJoin('feeds as f', 's.feed_id', 'f.uid')
.where(where)
.orderBy('s.created_at', 'desc');
return records.map(this.initTimelineObject);
}
async getUserNamedFeedId(userId, name) {
const response = await this.database('feeds').select('uid').where({
user_id: userId,
name
});
if (response.length === 0) {
return null;
}
return response[0].uid;
}
async getUserNamedFeed(userId, name, params) {
const response = await this.database('feeds').first().returning('uid').where({
user_id: userId,
name
});
return this.initTimelineObject(response, params);
}
async getUserNamedFeedsIntIds(userId, names) {
const responses = await this.database('feeds').select('id').where('user_id', userId).where('name', 'in', names)
const ids = responses.map((record) => {
return record.id
})
return ids
}
async getUsersNamedFeedsIntIds(userIds, names) {
const responses = await this.database('feeds').select('id').where('user_id', 'in', userIds).where('name', 'in', names);
return responses.map((record) => record.id);
}
async deleteUser(uid) {
await this.database('users').where({ uid }).delete();
await this.cacheFlushUser(uid)
}
///////////////////////////////////////////////////
// Post
///////////////////////////////////////////////////
initPostObject = (attrs, params) => {
if (!attrs) {
return null;
}
attrs = this._prepareModelPayload(attrs, POST_FIELDS, POST_FIELDS_MAPPING);
return DbAdapter.initObject(Post, attrs, attrs.id, params);
}
async createPost(payload, destinationsIntIds) {
const preparedPayload = this._prepareModelPayload(payload, POST_COLUMNS, POST_COLUMNS_MAPPING)
preparedPayload.destination_feed_ids = destinationsIntIds
const res = await this.database('posts').returning('uid').insert(preparedPayload)
return res[0]
}
updatePost(postId, payload) {
const preparedPayload = this._prepareModelPayload(payload, POST_COLUMNS, POST_COLUMNS_MAPPING)
return this.database('posts').where('uid', postId).update(preparedPayload)
}
async getPostById(id, params) {
if (!validator.isUUID(id, 4)) {
return null
}
const attrs = await this.database('posts').first().where('uid', id)
return this.initPostObject(attrs, params)
}
async getPostsByIds(ids, params) {
const responses = await this.database('posts').orderBy('updated_at', 'desc').whereIn('uid', ids)
return responses.map((attrs) => this.initPostObject(attrs, params))
}
async getUserPostsCount(userId) {
const res = await this.database('posts').where({ user_id: userId }).count()
return parseInt(res[0].count)
}
setPostUpdatedAt(postId, time) {
const d = new Date()
d.setTime(time)
const payload = { updated_at: d.toISOString() }
return this.database('posts').where('uid', postId).update(payload)
}
async deletePost(postId) {
await this.database('posts').where({ uid: postId }).delete()
// TODO: delete post local bumps
return await Promise.all([
this._deletePostLikes(postId),
this._deletePostComments(postId)
])
}
async getPostUsagesInTimelines(postId) {
const res = await this.database('posts').where('uid', postId)
const attrs = res[0]
if (!attrs) {
return []
}
return this.getTimelinesUUIDsByIntIds(attrs.feed_ids)
}
async insertPostIntoFeeds(feedIntIds, postId) {
if (!feedIntIds || feedIntIds.length == 0) {
return null
}
return this.database.raw('UPDATE posts SET feed_ids = (feed_ids | ?) WHERE uid = ?', [feedIntIds, postId]);
}
async withdrawPostFromFeeds(feedIntIds, postUUID) {
return this.database.raw('UPDATE posts SET feed_ids = (feed_ids - ?) WHERE uid = ?', [feedIntIds, postUUID]);
}
async isPostPresentInTimeline(timelineId, postId) {
const res = await this.database('posts').where('uid', postId);
const postData = res[0];
return postData.feed_ids.includes(timelineId);
}
async getTimelinePostsRange(timelineId, offset, limit) {
const res = await this.database('posts').select('uid', 'updated_at').orderBy('updated_at', 'desc').offset(offset).limit(limit).whereRaw('feed_ids && ?', [[timelineId]])
const postIds = res.map((record) => {
return record.uid
})
return postIds
}
async getFeedsPostsRange(timelineIds, offset, limit, params) {
const responses = await this.database('posts')
.select('uid', 'created_at', 'updated_at', 'user_id', 'body', 'comments_disabled', 'feed_ids', 'destination_feed_ids')
.orderBy('updated_at', 'desc')
.offset(offset).limit(limit)
.whereRaw('feed_ids && ?', [timelineIds]);
const postUids = responses.map((p) => p.uid)
const commentsCount = {}
const likesCount = {}
const groupedComments = await this.database('comments')
.select('post_id', this.database.raw('count(id) as comments_count'))
.where('post_id', 'in', postUids)
.groupBy('post_id')
for (const group of groupedComments) {
if (!commentsCount[group.post_id]) {
commentsCount[group.post_id] = 0
}
commentsCount[group.post_id] += parseInt(group.comments_count)
}
const groupedLikes = await this.database('likes')
.select('post_id', this.database.raw('count(id) as likes_count'))
.where('post_id', 'in', postUids)
.groupBy('post_id')
for (const group of groupedLikes) {
if (!likesCount[group.post_id]) {
likesCount[group.post_id] = 0
}
likesCount[group.post_id] += parseInt(group.likes_count)
}
const objects = responses.map((attrs) => {
if (attrs) {
attrs.comments_count = commentsCount[attrs.uid] || 0
attrs.likes_count = likesCount[attrs.uid] || 0
attrs = this._prepareModelPayload(attrs, POST_FIELDS, POST_FIELDS_MAPPING)
}
return DbAdapter.initObject(Post, attrs, attrs.id, params)
})
return objects
}
/**
* Returns UIDs of timeline posts
*/
async getTimelinePostsIds(timelineIntId, viewerId = null, params = {}) {
params = {
limit: 30,
offset: 0,
sort: 'updated',
withLocalBumps: false,
...params,
};
params.withLocalBumps = params.withLocalBumps && !!viewerId && params.sort === 'updated';
// Private feeds viewer can read
const visiblePrivateFeedIntIds = [];
// Users who banned viewer or banned by viewer (viewer should not see their posts)
const bannedUsersIds = [];
if (viewerId) {
const privateSQL = `
select f.id from
feeds f
join subscriptions s on f.uid = s.feed_id or f.user_id = :viewerId -- viewer's own feed is always visible
join users u on u.uid = f.user_id and u.is_private
where s.user_id = :viewerId and f.name = 'Posts'
`;
const bansSQL = `
select
distinct coalesce( nullif( user_id, :viewerId ), banned_user_id ) as id
from
bans
where
user_id = :viewerId
or banned_user_id = :viewerId
`;
const [
{ rows: privateRows },
{ rows: banRows },
directsFeed,
] = await Promise.all([
this.database.raw(privateSQL, { viewerId }),
this.database.raw(bansSQL, { viewerId }),
this.getUserNamedFeed(viewerId, 'Directs'),
]);
visiblePrivateFeedIntIds.push(..._.map(privateRows, 'id'));
visiblePrivateFeedIntIds.push(directsFeed.intId);
bannedUsersIds.push(..._.map(banRows, 'id'));
}
if (bannedUsersIds.length === 0) {
bannedUsersIds.push(unexistedUID);
}
let sql;
if (params.withLocalBumps) {
sql = pgFormat(`
select p.uid
from
posts p
left join local_bumps b on p.uid = b.post_id and b.user_id = %L
where
p.feed_ids && %L
and not p.user_id in (%L) -- bans
and (not is_private or destination_feed_ids && %L) -- privates
order by
greatest(p.updated_at, b.created_at) desc
limit %L offset %L
`,
viewerId,
`{${timelineIntId}}`,
bannedUsersIds,
`{${visiblePrivateFeedIntIds.join(',')}}`,
params.limit,
params.offset
);
} else {
sql = pgFormat(`
select uid
from
posts
where
feed_ids && %L
and not user_id in (%L) -- bans
and ${viewerId ?
pgFormat(`(not is_private or destination_feed_ids && %L)`, `{${visiblePrivateFeedIntIds.join(',')}}`) :
'not is_protected'
}
order by
%I desc
limit %L offset %L
`, `{${timelineIntId}}`, bannedUsersIds, `${params.sort}_at`, params.limit, params.offset);
}
return (await this.database.raw(sql)).rows.map((r) => r.uid);
}
// merges posts from "source" into "destination"
async createMergedPostsTimeline(destinationTimelineId, sourceTimelineIds) {
const transaction = async (trx) => {
await trx.raw(
'UPDATE "posts" SET "feed_ids" = ("feed_ids" | ?) WHERE "feed_ids" && ?',
[[destinationTimelineId], sourceTimelineIds]
);
};
await this.executeSerizlizableTransaction(transaction);
}
async getTimelinesIntersectionPostIds(timelineId1, timelineId2) {
const res1 = await this.database('posts').select('uid', 'updated_at').orderBy('updated_at', 'desc').whereRaw('feed_ids && ?', [[timelineId1]])
const postIds1 = res1.map((record) => {
return record.uid
})
const res2 = await this.database('posts').select('uid', 'updated_at').orderBy('updated_at', 'desc').whereRaw('feed_ids && ?', [[timelineId2]])
const postIds2 = res2.map((record) => {
return record.uid
})
return _.intersection(postIds1, postIds2)
}
/**
* Show all PUBLIC posts with
* 10+ likes
* 15+ comments by 5+ users
* Created less than 60 days ago
*/
bestPosts = async (currentUser, offset = 0, limit = 30) => {
const MIN_LIKES = 10;
const MIN_COMMENTS = 15;
const MIN_COMMENT_AUTHORS = 5;
const MAX_DAYS = 60;
let bannedUsersFilter = '';
let usersWhoBannedMeFilter = '';
const publicOrVisibleForAnonymous = currentUser ? 'not "users"."is_private"' : 'not "users"."is_protected"'
if (currentUser) {
const [iBanned, bannedMe] = await Promise.all([
this.getUserBansIds(currentUser.id),
this.getUserIdsWhoBannedUser(currentUser.id)
]);
bannedUsersFilter = this._getPostsFromBannedUsersSearchFilterCondition(iBanned);
if (bannedMe.length > 0) {
usersWhoBannedMeFilter = pgFormat('AND "feeds"."user_id" NOT IN (%L) ', bannedMe);
}
}
const sql = `
SELECT
DISTINCT "posts".* FROM "posts"
LEFT JOIN (SELECT post_id, COUNT("id") AS "comments_count", COUNT(DISTINCT "user_id") as "comment_authors_count" FROM "comments" GROUP BY "comments"."post_id") AS "c" ON "c"."post_id" = "posts"."uid"
LEFT JOIN (SELECT post_id, COUNT("id") AS "likes_count" FROM "likes" GROUP BY "likes"."post_id") AS "l" ON "l"."post_id" = "posts"."uid"
INNER JOIN "feeds" ON "posts"."destination_feed_ids" # feeds.id > 0 AND "feeds"."name" = 'Posts'
INNER JOIN "users" ON "feeds"."user_id" = "users"."uid" AND ${publicOrVisibleForAnonymous}
WHERE
"l"."likes_count" >= ${MIN_LIKES} AND "c"."comments_count" >= ${MIN_COMMENTS} AND "c"."comment_authors_count" >= ${MIN_COMMENT_AUTHORS} AND "posts"."created_at" > (current_date - ${MAX_DAYS} * interval '1 day')
${bannedUsersFilter}
${usersWhoBannedMeFilter}
ORDER BY "posts"."updated_at" DESC
OFFSET ${offset} LIMIT ${limit}`;
const res = await this.database.raw(sql);
return res.rows;
};
/**
* Returns array of objects with the following structure:
* {
* post: <Post object>
* destinations: <array of {id (feed UID), name (feed type), user (feed owner UID)}
* objects of posts' destination timelines>
* attachments: <array of Attachment objects>
* comments: <array of Comments objects>
* omittedComments: <number>
* likes: <array of liker's UIDs>
* omittedLikes: <number>
* }
*/
async getPostsWithStuffByIds(postsIds, viewerId = null, params = {}) {
if (_.isEmpty(postsIds)) {
return [];
}
params = {
foldComments: true,
foldLikes: true,
maxUnfoldedComments: 3,
maxUnfoldedLikes: 4,
visibleFoldedLikes: 3,
...params,
};
const uniqPostsIds = _.uniq(postsIds);
const postFields = _.without(Object.keys(POST_FIELDS), 'comments_count', 'likes_count').map((k) => pgFormat('%I', k));
const attFields = Object.keys(ATTACHMENT_FIELDS).map((k) => pgFormat('%I', k));
const commentFields = Object.keys(COMMENT_FIELDS).map((k) => pgFormat('%I', k));
const destinationsSQL = pgFormat(`
with posts as (
-- unwind all destination_feed_ids from posts
select distinct
p.uid,
unnest(p.destination_feed_ids) as feed_id
from
posts p
where
p.uid in (%L)
)
select
p.uid as post_id, f.uid as id, f.name, f.user_id as user
from
feeds f join posts p on f.id = p.feed_id
`, uniqPostsIds);
const [
bannedUsersIds,
friendsIds,
postsData,
attData,
{ rows: destData },
] = await Promise.all([
viewerId ? this.getUserBansIds(viewerId) : [],
viewerId ? this.getUserFriendIds(viewerId) : [],
this.database.select(...postFields).from('posts').whereIn('uid', uniqPostsIds),
this.database.select(...attFields).from('attachments').orderBy('created_at', 'asc').whereIn('post_id', uniqPostsIds),
this.database.raw(destinationsSQL),
]);
if (bannedUsersIds.length === 0) {
bannedUsersIds.push(unexistedUID);
}
if (friendsIds.length === 0) {
friendsIds.push(unexistedUID);
}
const allLikesSQL = pgFormat(`
select
post_id, user_id,
rank() over (partition by post_id order by
user_id in (%L) desc,
user_id in (%L) desc,
created_at desc,
id desc
),
count(*) over (partition by post_id)
from likes
where post_id in (%L) and user_id not in (%L)
`, [viewerId], friendsIds, uniqPostsIds, bannedUsersIds);
const likesSQL = `
with likes as (${allLikesSQL})
select post_id, array_agg(user_id) as likes, count from likes
${params.foldLikes ?
pgFormat(`where count <= %L or rank <= %L`, params.maxUnfoldedLikes, params.visibleFoldedLikes) :
``}
group by post_id, count
`;
const allCommentsSQL = pgFormat(`
select
${commentFields.join(', ')}, id,
rank() over (partition by post_id order by created_at, id),
count(*) over (partition by post_id)
from comments
where post_id in (%L) and user_id not in (%L)
`, uniqPostsIds, bannedUsersIds);
const commentsSQL = `
with comments as (${allCommentsSQL})
select ${commentFields.join(', ')}, id, count from comments
${params.foldComments ?
pgFormat(`where count <= %L or rank = 1 or rank = count`, params.maxUnfoldedComments) :
``}
order by created_at, id
`;
const [
{ rows: likesData },
{ rows: commentsData },
] = await Promise.all([
this.database.raw(likesSQL),
this.database.raw(commentsSQL),
]);
const results = {};
for (const post of postsData) {
results[post.uid] = {
post: this.initPostObject(post),
destinations: [],
attachments: [],
comments: [],
omittedComments: 0,
likes: [],
omittedLikes: 0,
};
}
for (const dest of destData) {
results[dest.post_id].destinations.push(_.omit(dest, 'post_id'));
}
for (const att of attData) {
results[att.post_id].attachments.push(this.initAttachmentObject(att));
}
for (const lk of likesData) {
results[lk.post_id].likes = lk.likes;
results[lk.post_id].omittedLikes = lk.count - lk.likes.length;
}
for (const comm of commentsData) {
results[comm.post_id].comments.push(this.initCommentObject(comm));
results[comm.post_id].omittedComments = comm.count <= 3 ? 0 : comm.count - 2;
}
return postsIds.map((id) => results[id] || null);
}
///////////////////////////////////////////////////
// Subscriptions
///////////////////////////////////////////////////
getUserSubscriptionsIds(userId) {
return this.database('subscriptions').pluck('feed_id').orderBy('created_at', 'desc').where('user_id', userId)
}
getUserSubscriptionsIdsByType(userId, feedType) {
return this.database
.pluck('s.feed_id')
.from('subscriptions as s').innerJoin('feeds as f', 's.feed_id', 'f.uid')
.where({ 's.user_id': userId, 'f.name': feedType })
.orderBy('s.created_at', 'desc')
}
getUserFriendIds(userId) {
const feedType = 'Posts';
return this.database
.pluck('f.user_id')
.from('subscriptions as s')
.innerJoin('feeds as f', 's.feed_id', 'f.uid')
.where({ 's.user_id': userId, 'f.name': feedType })
.orderBy('s.created_at', 'desc');
}
async isUserSubscribedToTimeline(currentUserId, timelineId) {
const res = await this.database('subscriptions').where({
feed_id: timelineId,
user_id: currentUserId
}).count()
return parseInt(res[0].count) != 0
}
async isUserSubscribedToOneOfTimelines(currentUserId, timelineIds) {
const q = pgFormat('SELECT COUNT(*) AS "cnt" FROM "subscriptions" WHERE "feed_id" IN (%L) AND "user_id" = ?', timelineIds);
const res = await this.database.raw(q, [currentUserId]);
return res.rows[0].cnt > 0;
}
async getTimelineSubscribersIds(timelineId) {
return await this.database('subscriptions').pluck('user_id').orderBy('created_at', 'desc').where('feed_id', timelineId)
}
async getTimelineSubscribers(timelineIntId) {
const responses = this.database('users').whereRaw('subscribed_feed_ids && ?', [[timelineIntId]])
return responses.map(this.initUserObject)
}
async subscribeUserToTimelines(timelineIds, currentUserId) {
const subsPromises = timelineIds.map((id) => {
const currentTime = new Date().toISOString()
const payload = {
feed_id: id,
user_id: currentUserId,
created_at: currentTime
}
return this.database('subscriptions').returning('id').insert(payload)
})
await Promise.all(subsPromises)
const feedIntIds = await this.getTimelinesIntIdsByUUIDs(timelineIds)
const res = await this.database.raw(
'UPDATE users SET subscribed_feed_ids = (subscribed_feed_ids | ?) WHERE uid = ? RETURNING subscribed_feed_ids',
[feedIntIds, currentUserId]
);
await this.cacheFlushUser(currentUserId)
return res.rows[0].subscribed_feed_ids
}
async unsubscribeUserFromTimelines(timelineIds, currentUserId) {
const unsubsPromises = timelineIds.map((id) => {
return this.database('subscriptions').where({
feed_id: id,
user_id: currentUserId
}).delete()
})
await Promise.all(unsubsPromises)
const feedIntIds = await this.getTimelinesIntIdsByUUIDs(timelineIds)
const res = await this.database.raw(
'UPDATE users SET subscribed_feed_ids = (subscribed_feed_ids - ?) WHERE uid = ? RETURNING subscribed_feed_ids',
[feedIntIds, currentUserId]
);
await this.cacheFlushUser(currentUserId)
return res.rows[0].subscribed_feed_ids
}
/**
* Executes SERIALIZABLE transaction until it succeeds
* @param transaction
*/
async executeSerizlizableTransaction(transaction) {
while (true) { // eslint-disable-line no-constant-condition
try {
await this.database.transaction(async (trx) => { // eslint-disable-line babel/no-await-in-loop
await trx.raw('SET TRANSACTION ISOLATION LEVEL SERIALIZABLE');
return transaction(trx);
});
break;
} catch (e) {
if (e.code === '40001') {
// Serialization failure (other transaction has changed the data). RETRY
continue;
}
throw e;
}
}
}
///////////////////////////////////////////////////
// LocalBumps
///////////////////////////////////////////////////
async createLocalBump(postId, userId) {
const existingPostLocalBumps = await this.database('local_bumps').where({
post_id: postId,
user_id: userId
}).count()
if (parseInt(existingPostLocalBumps[0].count) > 0) {
return true
}
const payload = {
post_id: postId,
user_id: userId
}
return this.database('local_bumps').returning('id').insert(payload)
}
async getUserLocalBumps(userId, newerThan) {
const time = new Date()
if (newerThan) {
time.setTime(newerThan)
}
const res = await this.database('local_bumps').orderBy('created_at', 'desc').where('user_id', userId).where('created_at', '>', time.toISOString())
const bumps = res.map((record) => {
return {
postId: record.post_id,
bumpedAt: record.created_at.getTime()
}
})
return bumps
}
///////////////////////////////////////////////////
// Search
///////////////////////////////////////////////////
async searchPosts(query, currentUserId, visibleFeedIds, bannedUserIds, offset, limit) {
const textSearchConfigName = this.database.client.config.textSearchConfigName
const bannedUsersFilter = this._getPostsFromBannedUsersSearchFilterCondition(bannedUserIds)
const bannedCommentAuthorFilter = this._getCommentsFromBannedUsersSearchFilterCondition(bannedUserIds)
const searchCondition = this._getTextSearchCondition(query, textSearchConfigName)
const commentSearchCondition = this._getCommentSearchCondition(query, textSearchConfigName)
const publicOrVisibleForAnonymous = currentUserId ? 'not users.is_private' : 'not users.is_protected'
if (!visibleFeedIds || visibleFeedIds.length == 0) {
visibleFeedIds = 'NULL'
}
const publicPostsSubQuery = 'select "posts".* from "posts" ' +
'inner join "feeds" on posts.destination_feed_ids # feeds.id > 0 and feeds.name=\'Posts\' ' +
`inner join "users" on feeds.user_id=users.uid and ${publicOrVisibleForAnonymous} ` +
`where ${searchCondition} ${bannedUsersFilter}`;
const publicPostsByCommentsSubQuery = 'select "posts".* from "posts" ' +
'inner join "feeds" on posts.destination_feed_ids # feeds.id > 0 and feeds.name=\'Posts\' ' +
`inner join "users" on feeds.user_id=users.uid and ${publicOrVisibleForAnonymous} ` +
`where
posts.uid in (
select post_id from comments where ${commentSearchCondition} ${bannedCommentAuthorFilter}
) ${bannedUsersFilter}`;
let subQueries = [publicPostsSubQuery, publicPostsByCommentsSubQuery];
if (currentUserId) {
const myPostsSubQuery = 'select "posts".* from "posts" ' +
`where "posts"."user_id" = '${currentUserId}' and ${searchCondition}`;
const myPostsByCommentsSubQuery = 'select "posts".* from "posts" ' +
`where "posts"."user_id" = '${currentUserId}' and
posts.uid in (
select post_id from comments where ${commentSearchCondition} ${bannedCommentAuthorFilter}
) `;
const visiblePrivatePostsSubQuery = 'select "posts".* from "posts" ' +
'inner join "feeds" on posts.destination_feed_ids # feeds.id > 0 and feeds.name=\'Posts\' ' +
'inner join "users" on feeds.user_id=users.uid and users.is_private=true ' +
`where ${searchCondition} and "feeds"."id" in (${visibleFeedIds}) ${bannedUsersFilter}`;
const visiblePrivatePostsByCommentsSubQuery = 'select "posts".* from "posts" ' +
'inner join "feeds" on posts.destination_feed_ids # feeds.id > 0 and feeds.name=\'Posts\' ' +
'inner join "users" on feeds.user_id=users.uid and users.is_private=true ' +
`where
posts.uid in (
select post_id from comments where ${commentSearchCondition} ${bannedCommentAuthorFilter}
)
and "feeds"."id" in (${visibleFeedIds}) ${bannedUsersFilter}`;
subQueries = [...subQueries, myPostsSubQuery, myPostsByCommentsSubQuery, visiblePrivatePostsSubQuery, visiblePrivatePostsByCommentsSubQuery];
}
const res = await this.database.raw(
`select * from (${subQueries.join(' union ')}) as found_posts order by found_posts.updated_at desc offset ${offset} limit ${limit}`
)
return res.rows
}
async searchUserPosts(query, targetUserId, visibleFeedIds, bannedUserIds, offset, limit) {
const textSearchConfigName = this.database.client.config.textSearchConfigName
const bannedUsersFilter = this._getPostsFromBannedUsersSearchFilterCondition(bannedUserIds)
const bannedCommentAuthorFilter = this._getCommentsFromBannedUsersSearchFilterCondition(bannedUserIds)
const searchCondition = this._getTextSearchCondition(query, textSearchConfigName)
const commentSearchCondition = this._getCommentSearchCondition(query, textSearchConfigName)
const publicPostsSubQuery = 'select "posts".* from "posts" ' +
'inner join "feeds" on posts.destination_feed_ids # feeds.id > 0 and feeds.name=\'Posts\' ' +
'inner join "users" on feeds.user_id=users.uid and users.is_private=false ' +
`where ${searchCondition} ${bannedUsersFilter}`;
const publicPostsByCommentsSubQuery = 'select "posts".* from "posts" ' +
'inner join "feeds" on posts.destination_feed_ids # feeds.id > 0 and feeds.name=\'Posts\' ' +
'inner join "users" on feeds.user_id=users.uid and users.is_private=false ' +
`where
posts.uid in (
select post_id from comments where ${commentSearchCondition} ${bannedCommentAuthorFilter}
) ${bannedUsersFilter}`;
let subQueries = [publicPostsSubQuery, publicPostsByCommentsSubQuery];
if (visibleFeedIds && visibleFeedIds.length > 0) {
const visiblePrivatePostsSubQuery = 'select "posts".* from "posts" ' +
'inner join "feeds" on posts.destination_feed_ids # feeds.id > 0 and feeds.name=\'Posts\' ' +
'inner join "users" on feeds.user_id=users.uid and users.is_private=true ' +
`where ${searchCondition} and "feeds"."id" in (${visibleFeedIds}) ${bannedUsersFilter}`;
const visiblePrivatePostsByCommentsSubQuery = 'select "posts".* from "posts" ' +
'inner join "feeds" on posts.destination_feed_ids # feeds.id > 0 and feeds.name=\'Posts\' ' +
'inner join "users" on feeds.user_id=users.uid and users.is_private=true ' +
`where
posts.uid in (
select post_id from comments where ${commentSearchCondition} ${bannedCommentAuthorFilter}
)
and "feeds"."id" in (${visibleFeedIds}) ${bannedUsersFilter}`;
subQueries = [...subQueries, visiblePrivatePostsSubQuery, visiblePrivatePostsByCommentsSubQuery];
}
const res = await this.database.raw(
`select * from (${subQueries.join(' union ')}) as found_posts where found_posts.user_id='${targetUserId}' order by found_posts.updated_at desc offset ${offset} limit ${limit}`
)
return res.rows
}
async searchGroupPosts(query, groupFeedId, visibleFeedIds, bannedUserIds, offset, limit) {
const textSearchConfigName = this.database.client.config.textSearchConfigName
const bannedUsersFilter = this._getPostsFromBannedUsersSearchFilterCondition(bannedUserIds)
const bannedCommentAuthorFilter = this._getCommentsFromBannedUsersSearchFilterCondition(bannedUserIds)
const searchCondition = this._getTextSearchCondition(query, textSearchConfigName)
const commentSearchCondition = this._getCommentSearchCondition(query, textSearchConfigName)
if (!visibleFeedIds || visibleFeedIds.length == 0) {
visibleFeedIds = 'NULL'
}
const publicPostsSubQuery = 'select "posts".* from "posts" ' +
`inner join "feeds" on posts.destination_feed_ids # feeds.id > 0 and feeds.name=\'Posts\' and feeds.uid='${groupFeedId}' ` +
'inner join "users" on feeds.user_id=users.uid and users.is_private=false ' +
`where ${searchCondition} ${bannedUsersFilter}`;
const publicPostsByCommentsSubQuery = 'select "posts".* from "posts" ' +
`inner join "feeds" on posts.destination_feed_ids # feeds.id > 0 and feeds.name=\'Posts\' and feeds.uid='${groupFeedId}' ` +
'inner join "users" on feeds.user_id=users.uid and users.is_private=false ' +
`where
posts.uid in (
select post_id from comments where ${commentSearchCondition} ${bannedCommentAuthorFilter}
) ${bannedUsersFilter}`;
let subQueries = [publicPostsSubQuery, publicPostsByCommentsSubQuery];
if (visibleFeedIds && visibleFeedIds.length > 0) {
const visiblePrivatePostsSubQuery = 'select "posts".* from "posts" ' +
`inner join "feeds" on posts.destination_feed_ids # feeds.id > 0 and feeds.name=\'Posts\' and feeds.uid='${groupFeedId}' ` +
'inner join "users" on feeds.user_id=users.uid and users.is_private=true ' +
`where ${searchCondition} and "feeds"."id" in (${visibleFeedIds}) ${bannedUsersFilter}`;
const visiblePrivatePostsByCommentsSubQuery = 'select "posts".* from "posts" ' +
`inner join "feeds" on posts.destination_feed_ids # feeds.id > 0 and feeds.name=\'Posts\' and feeds.uid='${groupFeedId}' ` +
'inner join "users" on feeds.user_id=users.uid and users.is_private=true ' +
`where
posts.uid in (
select post_id from comments where ${commentSearchCondition} ${bannedCommentAuthorFilter}
)
and "feeds"."id" in (${visibleFeedIds}) ${bannedUsersFilter}`;
subQueries = [...subQueries, visiblePrivatePostsSubQuery, visiblePrivatePostsByCommentsSubQuery];
}
const res = await this.database.raw(
`select * from (${subQueries.join(' union ')}) as found_posts order by found_posts.updated_at desc offset ${offset} limit ${limit}`
)
return res.rows
}
initRawPosts(rawPosts, params) {
const objects = rawPosts.map((attrs) => {
if (attrs) {
attrs = this._prepareModelPayload(attrs, POST_FIELDS, POST_FIELDS_MAPPING)
}
return DbAdapter.initObject(Post, attrs, attrs.id, params)
})
return objects
}
_getPostsFromBannedUsersSearchFilterCondition(bannedUserIds) {
if (bannedUserIds.length === 0) {
return '';
}
return pgFormat('and posts.user_id not in (%L) ', bannedUserIds);
}
_getCommentsFromBannedUsersSearchFilterCondition(bannedUserIds) {
if (bannedUserIds.length === 0) {
return '';
}
return pgFormat(`and comments.user_id not in (%L) `, bannedUserIds)
}
_getTextSearchCondition(parsedQuery, textSearchConfigName) {
const searchConditions = []
if (parsedQuery.query.length > 2) {
const sql = pgFormat(`to_tsvector(%L, posts.body) @@ to_tsquery(%L, %L)`, textSearchConfigName, textSearchConfigName, parsedQuery.query)
searchConditions.push(sql)
}
if (parsedQuery.quotes.length > 0) {
const quoteConditions = parsedQuery.quotes.map((quote) => {
const regex = `([[:<:]]|\\W|^)${_.escapeRegExp(quote)}([[:>:]]|\\W|$)`;
return pgFormat(`posts.body ~ %L`, regex)
});
searchConditions.push(`${quoteConditions.join(' and ')}`)
}
if (parsedQuery.hashtags.length > 0) {
const hashtagConditions = parsedQuery.hashtags.map((tag) => {
return pgFormat(`posts.uid in (
select u.entity_id from hashtag_usages as u where u.hashtag_id in (
select hashtags.id from hashtags where hashtags.name = %L
) and u.type = 'post'
)`, tag)
})
searchConditions.push(`${hashtagConditions.join(' and ')}`)
}
if (searchConditions.length == 0) {
return ' 1=0 '
}
return `${searchConditions.join(' and ')} `
}
_getCommentSearchCondition(parsedQuery, textSearchConfigName) {
const searchConditions = []
if (parsedQuery.query.length > 2) {
const sql = pgFormat(`to_tsvector(%L, comments.body) @@ to_tsquery(%L, %L)`, textSearchConfigName, textSearchConfigName, parsedQuery.query)
searchConditions.push(sql)
}
if (parsedQuery.quotes.length > 0) {
const quoteConditions = parsedQuery.quotes.map((quote) => {
const regex = `([[:<:]]|\\W|^)${_.escapeRegExp(quote)}([[:>:]]|\\W|$)`;
return pgFormat(`comments.body ~ %L`, regex)
});
searchConditions.push(`${quoteConditions.join(' and ')}`)
}
if (parsedQuery.hashtags.length > 0) {
const hashtagConditions = parsedQuery.hashtags.map((tag) => {
return pgFormat(`comments.uid in (
select u.entity_id from hashtag_usages as u where u.hashtag_id in (
select hashtags.id from hashtags where hashtags.name = %L
) and u.type = 'comment'
)`, tag)
})
searchConditions.push(`${hashtagConditions.join(' and ')}`)
}
if (searchConditions.length == 0) {
return ' 1=0 '
}
return `${searchConditions.join(' and ')} `
}
///////////////////////////////////////////////////
// Hashtags
///////////////////////////////////////////////////
async getHashtagIdsByNames(names) {
if (!names || names.length == 0) {
return []
}
const lowerCaseNames = names.map((hashtag) => {
return hashtag.toLowerCase()
})
const res = await this.database('hashtags').select('id', 'name').where('name', 'in', lowerCaseNames)
return res.map((t) => t.id)
}
async getOrCreateHashtagIdsByNames(names) {
if (!names || names.length == 0) {
return []
}
const lowerCaseNames = names.map((hashtag) => {
return hashtag.toLowerCase()
})
const targetTagNames = _.sortBy(lowerCaseNames)
const existingTags = await this.database('hashtags').select('id', 'name').where('name', 'in', targetTagNames)
const existingTagNames = _.sortBy(existingTags.map((t) => t.name))
const nonExistingTagNames = _.difference(targetTagNames, existingTagNames)
let tags = existingTags.map((t) => t.id)
if (nonExistingTagNames.length > 0) {
const createdTags = await this.createHashtags(nonExistingTagNames)
if (createdTags.length > 0) {
tags = tags.concat(createdTags)
}
}
return tags
}
getPostHashtags(postId) {
return this.database.select('hashtags.id', 'hashtags.name').from('hashtags')
.join('hashtag_usages', { 'hashtag_usages.hashtag_id': 'hashtags.id' })
.where('hashtag_usages.entity_id', '=', postId).andWhere('hashtag_usages.type', 'post')
}
getCommentHashtags(commentId) {
return this.database.select('hashtags.id', 'hashtags.name').from('hashtags')
.join('hashtag_usages', { 'hashtag_usages.hashtag_id': 'hashtags.id' })
.where('hashtag_usages.entity_id', '=', commentId).andWhere('hashtag_usages.type', 'comment')
}
async createHashtags(names) {
if (!names || names.length == 0) {
return []
}
const payload = names.map((name) => {
return pgFormat(`(%L)`, name.toLowerCase())
}).join(',')
const res = await this.database.raw(`insert into hashtags ("name") values ${payload} on conflict do nothing returning "id" `)
return res.rows.map((t) => t.id)
}
linkHashtags(tagIds, entityId, toPost = true) {
if (tagIds.length == 0) {
return false
}
const entityType = toPost ? 'post' : 'comment'
const payload = tagIds.map((hashtagId) => {
return pgFormat(`(%L, %L, %L)`, hashtagId, entityId, entityType)
}).join(',')
return this.database.raw(`insert into hashtag_usages ("hashtag_id", "entity_id", "type") values ${payload} on conflict do nothing`)
}
unlinkHashtags(tagIds, entityId, fromPost = true) {
if (tagIds.length == 0) {
return false
}
let entityType = 'post'
if (!fromPost) {
entityType = 'comment'
}
return this.database('hashtag_usages').where('hashtag_id', 'in', tagIds).where('entity_id', entityId).where('type', entityType).del()
}
async linkPostHashtagsByNames(names, postId) {
if (!names || names.length == 0) {
return false
}
const hashtagIds = await this.getOrCreateHashtagIdsByNames(names)
if (!hashtagIds || hashtagIds.length == 0) {
return false
}
return this.linkHashtags(hashtagIds, postId)
}
async unlinkPostHashtagsByNames(names, postId) {
if (!names || names.length == 0) {
return false
}
const hashtagIds = await this.getHashtagIdsByNames(names)
if (!hashtagIds || hashtagIds.length == 0) {
return false
}
return this.unlinkHashtags(hashtagIds, postId)
}
async linkCommentHashtagsByNames(names, commentId) {
if (!names || names.length == 0) {
return false
}
const hashtagIds = await this.getOrCreateHashtagIdsByNames(names)
if (!hashtagIds || hashtagIds.length == 0) {
return false
}
return this.linkHashtags(hashtagIds, commentId, false)
}
async unlinkCommentHashtagsByNames(names, commentId) {
if (!names || names.length == 0) {
return false
}
const hashtagIds = await this.getHashtagIdsByNames(names)
if (!hashtagIds || hashtagIds.length == 0) {
return false
}
return this.unlinkHashtags(hashtagIds, commentId, false)
}
///////////////////////////////////////////////////
// Unread directs counter
///////////////////////////////////////////////////
async markAllDirectsAsRead(userId) {
const currentTime = new Date().toISOString()
const payload = { directs_read_at: currentTime }
return this.database('users').where('uid', userId).update(payload)
}
async getUnreadDirectsNumber(userId) {
const [
[directsFeedId],
[directsReadAt],
] = await Promise.all([
this.database.pluck('id').from('feeds').where({ 'user_id': userId, 'name': 'Directs' }),
this.database.pluck('directs_read_at').from('users').where({ 'uid': userId }),
]);
/*
Select posts from my Directs feed, created after the directs_read_at authored by
users other than me and then add posts from my Directs feed, having comments created after the directs_read_at
authored by users other than me
*/
const sql = `
select count(distinct unread.id) as cnt from (
select id from
posts
where
destination_feed_ids && :feeds
and user_id != :userId
and created_at > :directsReadAt
union
select p.id from
comments c
join posts p on p.uid = c.post_id
where
p.destination_feed_ids && :feeds
and c.user_id != :userId
and c.created_at > :directsReadAt
) as unread`;
const res = await this.database.raw(sql, { feeds: `{${directsFeedId}}`, userId, directsReadAt });
return res.rows[0].cnt;
}
///////////////////////////////////////////////////
// Stats
///////////////////////////////////////////////////
async getStats(data, start_date, end_date) {
const supported_metrics = ['comments', 'comments_creates', 'posts', 'posts_creates', 'users', 'registrations',
'active_users', 'likes', 'likes_creates', 'groups', 'groups_creates'];
const metrics = data.split(',').sort();
let metrics_req = ``, metrics_list = `''null''`;
for (const metric of metrics) {
if (supported_metrics.includes(metric)) {
metrics_req += `, "${metric}" bigint`;
metrics_list += `, ''${metric}''`;
} else {
throw new Error(`ERROR: unsupported metric: ${metric}`);
}
}
if (!metrics_req.length) {
return null;
}
const sql = pgFormat(`
select * from crosstab(
'select to_char(dt, ''YYYY-MM-DD'') as date, metric, value from stats
where dt between '%L' and '%L'
and metric in (%s)
order by 1,2;')
AS ct ("date" text %s);`, start_date, end_date, metrics_list, metrics_req);
const res = await this.database.raw(sql);
return res.rows;
}
}
|
app/support/DbAdapter.js
|
import _ from 'lodash'
import validator from 'validator'
import NodeCache from 'node-cache'
import redis from 'redis'
import cacheManager from 'cache-manager'
import redisStore from 'cache-manager-redis'
import pgFormat from 'pg-format';
import { promisifyAll } from 'bluebird'
import { load as configLoader } from '../../config/config'
import { Attachment, Comment, Group, Post, Timeline, User } from '../models'
promisifyAll(redis.RedisClient.prototype);
promisifyAll(redis.Multi.prototype);
const unexistedUID = '00000000-0000-0000-C000-000000000046';
const USER_COLUMNS = {
username: 'username',
screenName: 'screen_name',
email: 'email',
description: 'description',
type: 'type',
profilePictureUuid: 'profile_picture_uuid',
createdAt: 'created_at',
updatedAt: 'updated_at',
directsReadAt: 'directs_read_at',
isPrivate: 'is_private',
isProtected: 'is_protected',
isRestricted: 'is_restricted',
hashedPassword: 'hashed_password',
resetPasswordToken: 'reset_password_token',
resetPasswordSentAt: 'reset_password_sent_at',
resetPasswordExpiresAt: 'reset_password_expires_at',
frontendPreferences: 'frontend_preferences'
}
const USER_COLUMNS_MAPPING = {
username: (username) => {return username.toLowerCase()},
createdAt: (timestamp) => {
const d = new Date()
d.setTime(timestamp)
return d.toISOString()
},
updatedAt: (timestamp) => {
const d = new Date()
d.setTime(timestamp)
return d.toISOString()
},
directsReadAt: (timestamp) => {
const d = new Date()
d.setTime(timestamp)
return d.toISOString()
},
isPrivate: (is_private) => {return is_private === '1'},
isProtected: (is_protected) => {return is_protected === '1'},
isRestricted: (is_restricted) => {return is_restricted === '1'},
resetPasswordSentAt: (timestamp) => {
const d = new Date()
d.setTime(timestamp)
return d.toISOString()
}
}
const USER_FIELDS = {
uid: 'id',
username: 'username',
screen_name: 'screenName',
email: 'email',
description: 'description',
type: 'type',
profile_picture_uuid: 'profilePictureUuid',
created_at: 'createdAt',
updated_at: 'updatedAt',
directs_read_at: 'directsReadAt',
is_private: 'isPrivate',
is_protected: 'isProtected',
is_restricted: 'isRestricted',
hashed_password: 'hashedPassword',
reset_password_token: 'resetPasswordToken',
reset_password_sent_at: 'resetPasswordSentAt',
reset_password_expires_at: 'resetPasswordExpiresAt',
frontend_preferences: 'frontendPreferences',
subscribed_feed_ids: 'subscribedFeedIds',
private_meta: 'privateMeta'
};
const USER_FIELDS_MAPPING = {
created_at: (time) => { return time.getTime().toString() },
updated_at: (time) => { return time.getTime().toString() },
is_private: (is_private) => {return is_private ? '1' : '0' },
is_protected: (is_protected) => {return is_protected ? '1' : '0' },
is_restricted: (is_restricted) => {return is_restricted ? '1' : '0' },
reset_password_sent_at: (time) => { return time && time.getTime() },
reset_password_expires_at: (time) => { return time && time.getTime() },
private_meta: (data) => data || {}
};
const USER_STATS_FIELDS = {
posts_count: 'posts',
likes_count: 'likes',
comments_count: 'comments',
subscribers_count: 'subscribers',
subscriptions_count: 'subscriptions'
}
const ATTACHMENT_COLUMNS = {
createdAt: 'created_at',
updatedAt: 'updated_at',
fileName: 'file_name',
fileSize: 'file_size',
mimeType: 'mime_type',
mediaType: 'media_type',
fileExtension: 'file_extension',
noThumbnail: 'no_thumbnail',
imageSizes: 'image_sizes',
artist: 'artist',
title: 'title',
userId: 'user_id',
postId: 'post_id'
}
const ATTACHMENT_COLUMNS_MAPPING = {
createdAt: (timestamp) => {
const d = new Date()
d.setTime(timestamp)
return d.toISOString()
},
updatedAt: (timestamp) => {
const d = new Date()
d.setTime(timestamp)
return d.toISOString()
},
noThumbnail: (no_thumbnail) => {return no_thumbnail === '1'},
fileSize: (file_size) => {
return parseInt(file_size, 10)
},
postId: (post_id) => {
if (validator.isUUID(post_id, 4)) {
return post_id
}
return null
},
userId: (user_id) => {
if (validator.isUUID(user_id, 4)) {
return user_id
}
return null
}
}
const ATTACHMENT_FIELDS = {
uid: 'id',
created_at: 'createdAt',
updated_at: 'updatedAt',
file_name: 'fileName',
file_size: 'fileSize',
mime_type: 'mimeType',
media_type: 'mediaType',
file_extension: 'fileExtension',
no_thumbnail: 'noThumbnail',
image_sizes: 'imageSizes',
artist: 'artist',
title: 'title',
user_id: 'userId',
post_id: 'postId'
}
const ATTACHMENT_FIELDS_MAPPING = {
created_at: (time) => { return time.getTime().toString() },
updated_at: (time) => { return time.getTime().toString() },
no_thumbnail: (no_thumbnail) => {return no_thumbnail ? '1' : '0' },
file_size: (file_size) => {return file_size && file_size.toString()},
post_id: (post_id) => {return post_id ? post_id : ''},
user_id: (user_id) => {return user_id ? user_id : ''}
}
const COMMENT_COLUMNS = {
createdAt: 'created_at',
updatedAt: 'updated_at',
body: 'body',
postId: 'post_id',
userId: 'user_id'
}
const COMMENT_COLUMNS_MAPPING = {
createdAt: (timestamp) => {
const d = new Date()
d.setTime(timestamp)
return d.toISOString()
},
updatedAt: (timestamp) => {
const d = new Date()
d.setTime(timestamp)
return d.toISOString()
}
}
const COMMENT_FIELDS = {
uid: 'id',
created_at: 'createdAt',
updated_at: 'updatedAt',
body: 'body',
user_id: 'userId',
post_id: 'postId'
}
const COMMENT_FIELDS_MAPPING = {
created_at: (time) => { return time.getTime().toString() },
updated_at: (time) => { return time.getTime().toString() },
post_id: (post_id) => {return post_id ? post_id : ''},
user_id: (user_id) => {return user_id ? user_id : ''}
}
const FEED_COLUMNS = {
createdAt: 'created_at',
updatedAt: 'updated_at',
name: 'name',
userId: 'user_id'
}
const FEED_COLUMNS_MAPPING = {
createdAt: (timestamp) => {
const d = new Date()
d.setTime(timestamp)
return d.toISOString()
},
updatedAt: (timestamp) => {
const d = new Date()
d.setTime(timestamp)
return d.toISOString()
}
}
const FEED_FIELDS = {
id: 'intId',
uid: 'id',
created_at: 'createdAt',
updated_at: 'updatedAt',
name: 'name',
user_id: 'userId'
}
const FEED_FIELDS_MAPPING = {
created_at: (time) => { return time.getTime().toString() },
updated_at: (time) => { return time.getTime().toString() },
user_id: (user_id) => {return user_id ? user_id : ''}
}
const POST_COLUMNS = {
createdAt: 'created_at',
updatedAt: 'updated_at',
userId: 'user_id',
body: 'body',
commentsDisabled: 'comments_disabled',
isPrivate: 'is_private',
isProtected: 'is_protected',
}
const POST_COLUMNS_MAPPING = {
createdAt: (timestamp) => {
const d = new Date()
d.setTime(timestamp)
return d.toISOString()
},
updatedAt: (timestamp) => {
const d = new Date()
d.setTime(timestamp)
return d.toISOString()
},
commentsDisabled: (comments_disabled) => {return comments_disabled === '1'},
userId: (user_id) => {
if (validator.isUUID(user_id, 4)) {
return user_id
}
return null
},
isPrivate: (is_private) => {return is_private === '1'},
isProtected: (is_protected) => {return is_protected === '1'},
}
const POST_FIELDS = {
uid: 'id',
created_at: 'createdAt',
updated_at: 'updatedAt',
user_id: 'userId',
body: 'body',
comments_disabled: 'commentsDisabled',
feed_ids: 'feedIntIds',
destination_feed_ids: 'destinationFeedIds',
comments_count: 'commentsCount',
likes_count: 'likesCount',
is_private: 'isPrivate',
is_protected: 'isProtected',
}
const POST_FIELDS_MAPPING = {
created_at: (time) => { return time.getTime().toString() },
updated_at: (time) => { return time.getTime().toString() },
comments_disabled: (comments_disabled) => {return comments_disabled ? '1' : '0' },
user_id: (user_id) => {return user_id ? user_id : ''},
is_private: (is_private) => {return is_private ? '1' : '0' },
is_protected: (is_protected) => {return is_protected ? '1' : '0' },
}
export class DbAdapter {
constructor(database) {
this.database = database
this.statsCache = promisifyAll(new NodeCache({ stdTTL: 300 }))
const config = configLoader()
const CACHE_TTL = 60 * 60 * 24 // 24 hours
this.memoryCache = cacheManager.caching({ store: 'memory', max: 5000, ttl: CACHE_TTL })
this.cache = cacheManager.caching({ store: redisStore, host: config.redis.host, port: config.redis.port, ttl: CACHE_TTL })
promisifyAll(this.cache)
promisifyAll(this.memoryCache)
promisifyAll(this.cache.store)
}
static initObject(classDef, attrs, id, params) {
return new classDef({ ...attrs, ...{ id }, ...params })
}
///////////////////////////////////////////////////
// User
///////////////////////////////////////////////////
_prepareModelPayload(payload, namesMapping, valuesMapping) {
return _.transform(payload, (result, val, key) => {
let mappedVal = val
if (valuesMapping[key]) {
mappedVal = valuesMapping[key](val)
}
const mappedKey = namesMapping[key]
if (mappedKey) {
result[mappedKey] = mappedVal
}
})
}
initUserObject = (attrs) => {
if (!attrs) {
return null;
}
attrs = this._prepareModelPayload(attrs, USER_FIELDS, USER_FIELDS_MAPPING)
return DbAdapter.initObject(attrs.type === 'group' ? Group : User, attrs, attrs.id)
}
async createUser(payload) {
const preparedPayload = this._prepareModelPayload(payload, USER_COLUMNS, USER_COLUMNS_MAPPING)
const res = await this.database('users').returning('uid').insert(preparedPayload)
const uid = res[0]
await this.createUserStats(uid)
return uid
}
updateUser(userId, payload) {
const tokenExpirationTime = new Date(Date.now())
const expireAfter = 60 * 60 * 24 // 24 hours
const preparedPayload = this._prepareModelPayload(payload, USER_COLUMNS, USER_COLUMNS_MAPPING)
if (_.has(preparedPayload, 'reset_password_token')) {
tokenExpirationTime.setHours(tokenExpirationTime.getHours() + expireAfter)
preparedPayload['reset_password_expires_at'] = tokenExpirationTime.toISOString()
}
this.cacheFlushUser(userId)
return this.database('users').where('uid', userId).update(preparedPayload)
}
setUpdatedAtInGroupsByIds = async (groupIds, time) => {
const updatedAt = new Date();
updatedAt.setTime(time);
const sql = pgFormat(`UPDATE "users" SET "updated_at" = ? WHERE "uid" IN (%L) AND "type"='group' RETURNING "uid"`, groupIds);
const uids = await this.database.raw(sql, [updatedAt.toISOString()]);
const flushPromises = uids.rows.map((row) => this.cacheFlushUser(row.uid));
await Promise.all(flushPromises);
};
async existsUser(userId) {
const res = await this.database('users').where('uid', userId).count()
return parseInt(res[0].count)
}
async existsUsername(username) {
const res = await this.database('users').where('username', username).count()
return parseInt(res[0].count)
}
async existsUserEmail(email) {
const res = await this.database('users').whereRaw('LOWER(email)=LOWER(?)', email).count()
return parseInt(res[0].count)
}
async getUserById(id) {
const user = await this.getFeedOwnerById(id)
if (!user) {
return null
}
if (!(user instanceof User)) {
throw new Error(`Expected User, got ${user.constructor.name}`)
}
return user
}
async getUsersByIds(userIds) {
const users = await this.getFeedOwnersByIds(userIds)
_.each(users, (user) => {
if (!(user instanceof User)) {
throw new Error(`Expected User, got ${user.constructor.name}`)
}
})
return users
}
async getUserByUsername(username) {
const feed = await this.getFeedOwnerByUsername(username)
if (null === feed) {
return null
}
if (!(feed instanceof User)) {
throw new Error(`Expected User, got ${feed.constructor.name}`)
}
return feed
}
async getUserByResetToken(token) {
const attrs = await this.database('users').first().where('reset_password_token', token)
if (!attrs) {
return null
}
if (attrs.type !== 'user') {
throw new Error(`Expected User, got ${attrs.type}`)
}
const now = new Date().getTime()
if (attrs.reset_password_expires_at < now) {
return null
}
return this.initUserObject(attrs);
}
async getUserByEmail(email) {
const attrs = await this.database('users').first().whereRaw('LOWER(email)=LOWER(?)', email)
if (!attrs) {
return null
}
if (attrs.type !== 'user') {
throw new Error(`Expected User, got ${attrs.type}`)
}
return this.initUserObject(attrs);
}
async getFeedOwnerById(id) {
if (!validator.isUUID(id, 4)) {
return null
}
return this.initUserObject(await this.fetchUser(id));
}
async getFeedOwnersByIds(ids) {
return (await this.fetchUsers(ids)).map(this.initUserObject);
}
async getUsersByIdsAssoc(ids) {
return _.mapValues(await this.fetchUsersAssoc(ids), this.initUserObject);
}
async getFeedOwnerByUsername(username) {
const attrs = await this.database('users').first().where('username', username.toLowerCase())
return this.initUserObject(attrs);
}
async getGroupById(id) {
const user = await this.getFeedOwnerById(id)
if (!user) {
return null
}
if (!(user instanceof Group)) {
throw new Error(`Expected Group, got ${user.constructor.name}`)
}
return user
}
async getGroupByUsername(username) {
const feed = await this.getFeedOwnerByUsername(username)
if (null === feed) {
return null
}
if (!(feed instanceof Group)) {
throw new Error(`Expected Group, got ${feed.constructor.name}`)
}
return feed
}
async getUserSubscribers(id) {
if (!validator.isUUID(id, 4)) {
return null;
}
const sql = `
select user_id from subscriptions
where feed_id in (
select uid from feeds where user_id = ? and name = 'Posts'
)
order by created_at`;
const res = await this.database.raw(sql, id);
return res.rows;
}
///////////////////////////////////////////////////
// User's attributes caching
///////////////////////////////////////////////////
async cacheFlushUser(id) {
const cacheKey = `user_${id}`
await this.cache.delAsync(cacheKey)
}
fixDateType = (date) => {
if (_.isString(date)) {
return new Date(date);
}
if (_.isDate(date)) {
return date;
}
return null;
};
fixCachedUserAttrs = (attrs) => {
if (!attrs) {
return null;
}
// Convert dates back to the Date type
attrs['created_at'] = this.fixDateType(attrs['created_at']);
attrs['updated_at'] = this.fixDateType(attrs['updated_at']);
attrs['reset_password_sent_at'] = this.fixDateType(attrs['reset_password_sent_at']);
attrs['reset_password_expires_at'] = this.fixDateType(attrs['reset_password_expires_at']);
return attrs;
};
getCachedUserAttrs = async (id) => {
return this.fixCachedUserAttrs(await this.cache.getAsync(`user_${id}`))
};
async fetchUser(id) {
let attrs = await this.getCachedUserAttrs(id);
if (!attrs) {
// Cache miss, read from the database
attrs = await this.database('users').first().where('uid', id) || null;
if (attrs) {
await this.cache.setAsync(`user_${id}`, attrs);
}
}
return attrs;
}
/**
* Returns plain object with ids as keys and user attributes as values
*/
async fetchUsersAssoc(ids) {
const idToUser = {};
if (_.isEmpty(ids)) {
return idToUser;
}
const uniqIds = _.uniq(ids);
let cachedUsers;
if (this.cache.store.name === 'redis') {
const { client, done } = await this.cache.store.getClientAsync();
try {
const cacheKeys = ids.map((id) => `user_${id}`);
const result = await client.mgetAsync(cacheKeys);
cachedUsers = result.map((x) => x ? JSON.parse(x) : null).map(this.fixCachedUserAttrs);
} finally {
done();
}
} else {
cachedUsers = await Promise.all(uniqIds.map(this.getCachedUserAttrs));
}
const notFoundIds = _.compact(cachedUsers.map((attrs, i) => attrs ? null : uniqIds[i]));
const dbUsers = notFoundIds.length === 0 ? [] : await this.database('users').whereIn('uid', notFoundIds);
await Promise.all(dbUsers.map((attrs) => this.cache.setAsync(`user_${attrs.uid}`, attrs)));
_.compact(cachedUsers).forEach((attrs) => idToUser[attrs.uid] = attrs);
dbUsers.forEach((attrs) => idToUser[attrs.uid] = attrs);
return idToUser;
}
async fetchUsers(ids) {
const idToUser = await this.fetchUsersAssoc(ids);
return ids.map((id) => idToUser[id] || null);
}
async someUsersArePublic(userIds, anonymousFriendly) {
const anonymousCondition = anonymousFriendly ? 'AND not "is_protected"' : '';
const q = pgFormat(`SELECT COUNT("id") AS "cnt" FROM "users" WHERE not "is_private" ${anonymousCondition} AND "uid" IN (%L)`, userIds);
const res = await this.database.raw(q);
return res.rows[0].cnt > 0;
}
///////////////////////////////////////////////////
// User statistics
///////////////////////////////////////////////////
async createUserStats(userId) {
const res = await this.database('user_stats').insert({ user_id: userId })
return res
}
async getUserStats(userId) {
let userStats
// Check the cache first
const cachedUserStats = await this.statsCache.getAsync(userId)
if (typeof cachedUserStats != 'undefined') {
// Cache hit
userStats = cachedUserStats
} else {
// Cache miss, read from the database
const res = await this.database('user_stats').where('user_id', userId)
userStats = res[0]
await this.statsCache.setAsync(userId, userStats)
}
return this._prepareModelPayload(userStats, USER_STATS_FIELDS, {})
}
/**
* Returns plain object with user ids as keys and user stats as values
*/
async getUsersStatsAssoc(ids) {
const idToStat = {};
if (_.isEmpty(ids)) {
return idToStat;
}
const uniqIds = _.compact(_.uniq(ids));
const cachedStats = await Promise.all(uniqIds.map((id) => this.statsCache.getAsync(id)));
const notFoundIds = _.compact(cachedStats.map((stat, i) => stat ? null : uniqIds[i]));
const dbStats = notFoundIds.length === 0 ? [] : await this.database('user_stats').whereIn('user_id', notFoundIds);
await Promise.all(dbStats.map((stat) => this.statsCache.setAsync(stat.user_id, stat)));
_.compact(cachedStats).forEach((stat) => idToStat[stat.user_id] = this._prepareModelPayload(stat, USER_STATS_FIELDS, {}));
dbStats.forEach((stat) => idToStat[stat.user_id] = this._prepareModelPayload(stat, USER_STATS_FIELDS, {}));
return idToStat;
}
async calculateUserStats(userId) {
const userFeeds = await this.database('users').select('subscribed_feed_ids').where('uid', userId)
const readableFeedsIds = userFeeds[0].subscribed_feed_ids
const userPostsFeed = await this.database('feeds').returning('uid').where({
user_id: userId,
name: 'Posts'
});
if (!userPostsFeed[0]) {
// hard-reserved username without other data-structures
return;
}
const userPostsFeedId = userPostsFeed[0].uid
const readablePostFeeds = this.database('feeds').whereIn('id', readableFeedsIds).where('name', 'Posts')
const promises = [
this.getUserPostsCount(userId),
this.getUserLikesCount(userId),
this.getUserCommentsCount(userId),
this.getTimelineSubscribersIds(userPostsFeedId),
readablePostFeeds
]
const values = await Promise.all(promises)
const payload = {
posts_count: values[0],
likes_count: values[1],
comments_count: values[2],
subscribers_count: values[3].length,
subscriptions_count: values[4].length
}
await this.database('user_stats').where('user_id', userId).update(payload)
// Invalidate cache
await this.statsCache.delAsync(userId)
}
statsCommentCreated(authorId) {
return this.incrementStatsCounter(authorId, 'comments_count')
}
statsCommentDeleted(authorId) {
return this.decrementStatsCounter(authorId, 'comments_count')
}
statsLikeCreated(authorId) {
return this.incrementStatsCounter(authorId, 'likes_count')
}
statsLikeDeleted(authorId) {
return this.decrementStatsCounter(authorId, 'likes_count')
}
statsPostCreated(authorId) {
return this.incrementStatsCounter(authorId, 'posts_count')
}
async statsPostDeleted(authorId, postId) {
const postLikers = await this.getPostLikersIdsWithoutBannedUsers(postId, null)
const promises = postLikers.map((id) => {
return this.calculateUserStats(id)
})
await Promise.all(promises)
if (!postLikers.includes(authorId)) {
return this.decrementStatsCounter(authorId, 'posts_count')
}
return null
}
statsSubscriptionCreated(userId) {
return this.incrementStatsCounter(userId, 'subscriptions_count')
}
statsSubscriptionDeleted(userId) {
return this.decrementStatsCounter(userId, 'subscriptions_count')
}
statsSubscriberAdded(userId) {
return this.incrementStatsCounter(userId, 'subscribers_count')
}
statsSubscriberRemoved(userId) {
return this.decrementStatsCounter(userId, 'subscribers_count')
}
async incrementStatsCounter(userId, counterName) {
await this.database.transaction(async (trx) => {
try {
const res = await this.database('user_stats')
.transacting(trx).forUpdate()
.where('user_id', userId)
const stats = res[0]
const val = parseInt(stats[counterName], 10) + 1
stats[counterName] = val
await this.database('user_stats')
.transacting(trx)
.where('user_id', userId)
.update(stats)
await trx.commit();
} catch (e) {
await trx.rollback();
throw e;
}
});
// Invalidate cache
await this.statsCache.delAsync(userId)
}
async decrementStatsCounter(userId, counterName) {
await this.database.transaction(async (trx) => {
try {
const res = await this.database('user_stats')
.transacting(trx).forUpdate()
.where('user_id', userId)
const stats = res[0]
const val = parseInt(stats[counterName]) - 1
if (val < 0) {
throw new Error(`Negative user stats: ${counterName} of ${userId}`);
}
stats[counterName] = val
await this.database('user_stats')
.transacting(trx)
.where('user_id', userId)
.update(stats)
await trx.commit();
} catch (e) {
await trx.rollback();
throw e;
}
});
// Invalidate cache
await this.statsCache.delAsync(userId)
}
///////////////////////////////////////////////////
// Subscription requests
///////////////////////////////////////////////////
createSubscriptionRequest(fromUserId, toUserId) {
const currentTime = new Date().toISOString()
const payload = {
from_user_id: fromUserId,
to_user_id: toUserId,
created_at: currentTime
}
return this.database('subscription_requests').returning('id').insert(payload)
}
deleteSubscriptionRequest(toUserId, fromUserId) {
return this.database('subscription_requests').where({
from_user_id: fromUserId,
to_user_id: toUserId
}).delete()
}
async getUserSubscriptionRequestsIds(toUserId) {
const res = await this.database('subscription_requests').select('from_user_id').orderBy('created_at', 'desc').where('to_user_id', toUserId)
const attrs = res.map((record) => {
return record.from_user_id
})
return attrs
}
async isSubscriptionRequestPresent(fromUserId, toUserId) {
const res = await this.database('subscription_requests').where({
from_user_id: fromUserId,
to_user_id: toUserId
}).count()
return parseInt(res[0].count) != 0
}
async getUserSubscriptionPendingRequestsIds(fromUserId) {
const res = await this.database('subscription_requests').select('to_user_id').orderBy('created_at', 'desc').where('from_user_id', fromUserId)
const attrs = res.map((record) => {
return record.to_user_id
})
return attrs
}
///////////////////////////////////////////////////
// Bans
///////////////////////////////////////////////////
async getUserBansIds(userId) {
const res = await this.database('bans').select('banned_user_id').orderBy('created_at', 'desc').where('user_id', userId);
return res.map((record) => record.banned_user_id);
}
async getUserIdsWhoBannedUser(userId) {
const res = await this.database('bans').select('user_id').orderBy('created_at', 'desc').where('banned_user_id', userId);
return res.map((record) => record.user_id);
}
async getBannedFeedsIntIds(userId) {
return await this.database
.pluck('feeds.id')
.from('feeds')
.innerJoin('bans', 'bans.banned_user_id', 'feeds.user_id')
.where('feeds.name', 'Posts')
.where('bans.user_id', userId);
}
async getBanMatrixByUsersForPostReader(bannersUserIds, targetUserId) {
let res = [];
if (targetUserId) {
res = await this.database('bans')
.where('banned_user_id', targetUserId)
.where('user_id', 'in', bannersUserIds)
.orderByRaw(`position(user_id::text in '${bannersUserIds.toString()}')`)
}
const matrix = bannersUserIds.map((id) => {
const foundBan = res.find((record) => record.user_id == id);
return foundBan ? [id, true] : [id, false];
});
return matrix
}
createUserBan(currentUserId, bannedUserId) {
const currentTime = new Date().toISOString()
const payload = {
user_id: currentUserId,
banned_user_id: bannedUserId,
created_at: currentTime
}
return this.database('bans').returning('id').insert(payload)
}
deleteUserBan(currentUserId, bannedUserId) {
return this.database('bans').where({
user_id: currentUserId,
banned_user_id: bannedUserId
}).delete()
}
///////////////////////////////////////////////////
// Group administrators
///////////////////////////////////////////////////
getGroupAdministratorsIds(groupId) {
return this.database('group_admins').pluck('user_id').orderBy('created_at', 'desc').where('group_id', groupId)
}
/**
* Returns plain object with group UIDs as keys and arrays of admin UIDs as values
*/
async getGroupsAdministratorsIds(groupIds) {
const rows = await this.database.select('group_id', 'user_id').from('group_admins').where('group_id', 'in', groupIds);
const res = {};
rows.forEach(({ group_id, user_id }) => {
if (!res.hasOwnProperty(group_id)) {
res[group_id] = [];
}
res[group_id].push(user_id);
});
return res;
}
addAdministratorToGroup(groupId, adminId) {
const currentTime = new Date().toISOString()
const payload = {
user_id: adminId,
group_id: groupId,
created_at: currentTime
}
return this.database('group_admins').returning('id').insert(payload)
}
removeAdministratorFromGroup(groupId, adminId) {
return this.database('group_admins').where({
user_id: adminId,
group_id: groupId
}).delete()
}
getManagedGroupIds(userId) {
return this.database('group_admins').pluck('group_id').orderBy('created_at', 'desc').where('user_id', userId);
}
async userHavePendingGroupRequests(userId) {
const res = await this.database.first('r.id')
.from('subscription_requests as r')
.innerJoin('group_admins as a', 'a.group_id', 'r.to_user_id')
.where({ 'a.user_id': userId })
.limit(1);
return !!res;
}
/**
* Returns plain object with group UIDs as keys and arrays of requester's UIDs as values
*/
async getPendingGroupRequests(groupsAdminId) {
const rows = await this.database.select('r.from_user_id as user_id', 'r.to_user_id as group_id')
.from('subscription_requests as r')
.innerJoin('group_admins as a', 'a.group_id', 'r.to_user_id')
.where({ 'a.user_id': groupsAdminId });
const res = {};
rows.forEach(({ group_id, user_id }) => {
if (!res.hasOwnProperty(group_id)) {
res[group_id] = [];
}
res[group_id].push(user_id);
});
return res;
}
///////////////////////////////////////////////////
// Attachments
///////////////////////////////////////////////////
initAttachmentObject = (attrs) => {
if (!attrs) {
return null;
}
attrs = this._prepareModelPayload(attrs, ATTACHMENT_FIELDS, ATTACHMENT_FIELDS_MAPPING);
return DbAdapter.initObject(Attachment, attrs, attrs.id);
};
async createAttachment(payload) {
const preparedPayload = this._prepareModelPayload(payload, ATTACHMENT_COLUMNS, ATTACHMENT_COLUMNS_MAPPING)
const res = await this.database('attachments').returning('uid').insert(preparedPayload)
return res[0]
}
async getAttachmentById(id) {
if (!validator.isUUID(id, 4)) {
return null
}
const attrs = await this.database('attachments').first().where('uid', id)
return this.initAttachmentObject(attrs);
}
async getAttachmentsByIds(ids) {
const responses = await this.database('attachments').whereIn('uid', ids).orderByRaw(`position(uid::text in '${ids.toString()}')`)
return responses.map(this.initAttachmentObject)
}
updateAttachment(attachmentId, payload) {
const preparedPayload = this._prepareModelPayload(payload, ATTACHMENT_COLUMNS, ATTACHMENT_COLUMNS_MAPPING)
return this.database('attachments').where('uid', attachmentId).update(preparedPayload)
}
linkAttachmentToPost(attachmentId, postId) {
const payload = { post_id: postId }
return this.database('attachments').where('uid', attachmentId).update(payload)
}
unlinkAttachmentFromPost(attachmentId, postId) {
const payload = { post_id: null }
return this.database('attachments').where('uid', attachmentId).where('post_id', postId).update(payload)
}
async getPostAttachments(postId) {
const res = await this.database('attachments').select('uid').orderBy('created_at', 'asc').where('post_id', postId)
const attrs = res.map((record) => {
return record.uid
})
return attrs
}
async getAttachmentsOfPost(postId) {
const responses = await this.database('attachments').orderBy('created_at', 'asc').where('post_id', postId)
return responses.map(this.initAttachmentObject)
}
///////////////////////////////////////////////////
// Likes
///////////////////////////////////////////////////
createUserPostLike(postId, userId) {
const currentTime = new Date().toISOString()
const payload = {
post_id: postId,
user_id: userId,
created_at: currentTime
}
return this.database('likes').returning('id').insert(payload)
}
async getPostLikesCount(postId) {
const res = await this.database('likes').where({ post_id: postId }).count()
return parseInt(res[0].count)
}
async getUserLikesCount(userId) {
const res = await this.database('likes').where({ user_id: userId }).count()
return parseInt(res[0].count)
}
async getPostLikersIdsWithoutBannedUsers(postId, viewerUserId) {
let query = this.database('likes').select('user_id').orderBy('created_at', 'desc').where('post_id', postId);
if (viewerUserId) {
const subquery = this.database('bans').select('banned_user_id').where('user_id', viewerUserId)
query = query.where('user_id', 'not in', subquery)
}
const res = await query;
const userIds = res.map((record) => record.user_id)
return userIds
}
async hasUserLikedPost(userId, postId) {
const res = await this.database('likes').where({
post_id: postId,
user_id: userId
}).count()
return parseInt(res[0].count) != 0
}
async getUserPostLikedTime(userId, postId) {
const res = await this.database('likes').select('created_at').where({
post_id: postId,
user_id: userId
})
const record = res[0]
if (!record) {
return null
}
return record.created_at.getTime()
}
removeUserPostLike(postId, userId) {
return this.database('likes').where({
post_id: postId,
user_id: userId
}).delete()
}
_deletePostLikes(postId) {
return this.database('likes').where({ post_id: postId }).delete()
}
///////////////////////////////////////////////////
// Comments
///////////////////////////////////////////////////
initCommentObject = (attrs) => {
if (!attrs) {
return null;
}
attrs = this._prepareModelPayload(attrs, COMMENT_FIELDS, COMMENT_FIELDS_MAPPING);
return DbAdapter.initObject(Comment, attrs, attrs.id);
};
async createComment(payload) {
const preparedPayload = this._prepareModelPayload(payload, COMMENT_COLUMNS, COMMENT_COLUMNS_MAPPING)
const res = await this.database('comments').returning('uid').insert(preparedPayload)
return res[0]
}
async getCommentById(id) {
if (!validator.isUUID(id, 4)) {
return null
}
const attrs = await this.database('comments').first().where('uid', id)
return this.initCommentObject(attrs);
}
updateComment(commentId, payload) {
const preparedPayload = this._prepareModelPayload(payload, COMMENT_COLUMNS, COMMENT_COLUMNS_MAPPING)
return this.database('comments').where('uid', commentId).update(preparedPayload)
}
deleteComment(commentId, postId) {
return this.database('comments').where({
uid: commentId,
post_id: postId
}).delete()
}
async getPostCommentsCount(postId) {
const res = await this.database('comments').where({ post_id: postId }).count()
return parseInt(res[0].count)
}
async getUserCommentsCount(userId) {
const res = await this.database('comments').where({ user_id: userId }).count()
return parseInt(res[0].count)
}
async getAllPostCommentsWithoutBannedUsers(postId, viewerUserId) {
let query = this.database('comments').orderBy('created_at', 'asc').where('post_id', postId);
if (viewerUserId) {
const subquery = this.database('bans').select('banned_user_id').where('user_id', viewerUserId);
query = query.where('user_id', 'not in', subquery);
}
const responses = await query;
return responses.map(this.initCommentObject);
}
_deletePostComments(postId) {
return this.database('comments').where({ post_id: postId }).delete()
}
///////////////////////////////////////////////////
// Feeds
///////////////////////////////////////////////////
initTimelineObject = (attrs, params) => {
if (!attrs) {
return null;
}
attrs = this._prepareModelPayload(attrs, FEED_FIELDS, FEED_FIELDS_MAPPING)
return DbAdapter.initObject(Timeline, attrs, attrs.id, params)
}
async createTimeline(payload) {
const preparedPayload = this._prepareModelPayload(payload, FEED_COLUMNS, FEED_COLUMNS_MAPPING)
if (preparedPayload.name == 'MyDiscussions') {
preparedPayload.uid = preparedPayload.user_id
}
const res = await this.database('feeds').returning(['id', 'uid']).insert(preparedPayload)
return { intId: res[0].id, id: res[0].uid }
}
createUserTimelines(userId, timelineNames) {
const currentTime = new Date().getTime()
const promises = timelineNames.map((n) => {
const payload = {
'name': n,
userId,
'createdAt': currentTime.toString(),
'updatedAt': currentTime.toString()
}
return this.createTimeline(payload)
})
return Promise.all(promises)
}
async cacheFetchUserTimelinesIds(userId) {
const cacheKey = `timelines_user_${userId}`;
// Check the cache first
const cachedTimelines = await this.memoryCache.getAsync(cacheKey);
if (typeof cachedTimelines != 'undefined' && cachedTimelines) {
// Cache hit
return cachedTimelines;
}
// Cache miss, read from the database
const res = await this.database('feeds').where('user_id', userId);
const riverOfNews = _.filter(res, (record) => { return record.name == 'RiverOfNews'});
const hides = _.filter(res, (record) => { return record.name == 'Hides'});
const comments = _.filter(res, (record) => { return record.name == 'Comments'});
const likes = _.filter(res, (record) => { return record.name == 'Likes'});
const posts = _.filter(res, (record) => { return record.name == 'Posts'});
const directs = _.filter(res, (record) => { return record.name == 'Directs'});
const myDiscussions = _.filter(res, (record) => { return record.name == 'MyDiscussions'});
const timelines = {
'RiverOfNews': riverOfNews[0] && riverOfNews[0].uid,
'Hides': hides[0] && hides[0].uid,
'Comments': comments[0] && comments[0].uid,
'Likes': likes[0] && likes[0].uid,
'Posts': posts[0] && posts[0].uid
};
if (directs[0]) {
timelines['Directs'] = directs[0].uid;
}
if (myDiscussions[0]) {
timelines['MyDiscussions'] = myDiscussions[0].uid;
}
if (res.length) {
// Don not cache empty feeds lists
await this.memoryCache.setAsync(cacheKey, timelines);
}
return timelines;
}
async getUserTimelinesIds(userId) {
return await this.cacheFetchUserTimelinesIds(userId);
}
async getTimelineById(id, params) {
if (!validator.isUUID(id, 4)) {
return null
}
const attrs = await this.database('feeds').first().where('uid', id);
return this.initTimelineObject(attrs, params);
}
async getTimelineByIntId(id, params) {
const attrs = await this.database('feeds').first().where('id', id);
return this.initTimelineObject(attrs, params);
}
async getTimelinesByIds(ids, params) {
const responses = await this.database('feeds').whereIn('uid', ids).orderByRaw(`position(uid::text in '${ids.toString()}')`);
return responses.map((r) => this.initTimelineObject(r, params));
}
async getTimelinesByIntIds(ids, params) {
const responses = await this.database('feeds').whereIn('id', ids).orderByRaw(`position(id::text in '${ids.toString()}')`);
return responses.map((r) => this.initTimelineObject(r, params));
}
async getTimelinesIntIdsByUUIDs(uuids) {
const responses = await this.database('feeds').select('id').whereIn('uid', uuids);
return responses.map((record) => record.id);
}
async getTimelinesUUIDsByIntIds(ids) {
const responses = await this.database('feeds').select('uid').whereIn('id', ids)
const uuids = responses.map((record) => {
return record.uid
})
return uuids
}
async getTimelinesUserSubscribed(userId, feedType = null) {
const where = { 's.user_id': userId };
if (feedType !== null) {
where['f.name'] = feedType;
}
const records = await this.database
.select('f.*')
.from('subscriptions as s')
.innerJoin('feeds as f', 's.feed_id', 'f.uid')
.where(where)
.orderBy('s.created_at', 'desc');
return records.map(this.initTimelineObject);
}
async getUserNamedFeedId(userId, name) {
const response = await this.database('feeds').select('uid').where({
user_id: userId,
name
});
if (response.length === 0) {
return null;
}
return response[0].uid;
}
async getUserNamedFeed(userId, name, params) {
const response = await this.database('feeds').first().returning('uid').where({
user_id: userId,
name
});
return this.initTimelineObject(response, params);
}
async getUserNamedFeedsIntIds(userId, names) {
const responses = await this.database('feeds').select('id').where('user_id', userId).where('name', 'in', names)
const ids = responses.map((record) => {
return record.id
})
return ids
}
async getUsersNamedFeedsIntIds(userIds, names) {
const responses = await this.database('feeds').select('id').where('user_id', 'in', userIds).where('name', 'in', names);
return responses.map((record) => record.id);
}
async deleteUser(uid) {
await this.database('users').where({ uid }).delete();
await this.cacheFlushUser(uid)
}
///////////////////////////////////////////////////
// Post
///////////////////////////////////////////////////
initPostObject = (attrs, params) => {
if (!attrs) {
return null;
}
attrs = this._prepareModelPayload(attrs, POST_FIELDS, POST_FIELDS_MAPPING);
return DbAdapter.initObject(Post, attrs, attrs.id, params);
}
async createPost(payload, destinationsIntIds) {
const preparedPayload = this._prepareModelPayload(payload, POST_COLUMNS, POST_COLUMNS_MAPPING)
preparedPayload.destination_feed_ids = destinationsIntIds
const res = await this.database('posts').returning('uid').insert(preparedPayload)
return res[0]
}
updatePost(postId, payload) {
const preparedPayload = this._prepareModelPayload(payload, POST_COLUMNS, POST_COLUMNS_MAPPING)
return this.database('posts').where('uid', postId).update(preparedPayload)
}
async getPostById(id, params) {
if (!validator.isUUID(id, 4)) {
return null
}
const attrs = await this.database('posts').first().where('uid', id)
return this.initPostObject(attrs, params)
}
async getPostsByIds(ids, params) {
const responses = await this.database('posts').orderBy('updated_at', 'desc').whereIn('uid', ids)
return responses.map((attrs) => this.initPostObject(attrs, params))
}
async getUserPostsCount(userId) {
const res = await this.database('posts').where({ user_id: userId }).count()
return parseInt(res[0].count)
}
setPostUpdatedAt(postId, time) {
const d = new Date()
d.setTime(time)
const payload = { updated_at: d.toISOString() }
return this.database('posts').where('uid', postId).update(payload)
}
async deletePost(postId) {
await this.database('posts').where({ uid: postId }).delete()
// TODO: delete post local bumps
return await Promise.all([
this._deletePostLikes(postId),
this._deletePostComments(postId)
])
}
async getPostUsagesInTimelines(postId) {
const res = await this.database('posts').where('uid', postId)
const attrs = res[0]
if (!attrs) {
return []
}
return this.getTimelinesUUIDsByIntIds(attrs.feed_ids)
}
async insertPostIntoFeeds(feedIntIds, postId) {
if (!feedIntIds || feedIntIds.length == 0) {
return null
}
return this.database.raw('UPDATE posts SET feed_ids = (feed_ids | ?) WHERE uid = ?', [feedIntIds, postId]);
}
async withdrawPostFromFeeds(feedIntIds, postUUID) {
return this.database.raw('UPDATE posts SET feed_ids = (feed_ids - ?) WHERE uid = ?', [feedIntIds, postUUID]);
}
async isPostPresentInTimeline(timelineId, postId) {
const res = await this.database('posts').where('uid', postId);
const postData = res[0];
return postData.feed_ids.includes(timelineId);
}
async getTimelinePostsRange(timelineId, offset, limit) {
const res = await this.database('posts').select('uid', 'updated_at').orderBy('updated_at', 'desc').offset(offset).limit(limit).whereRaw('feed_ids && ?', [[timelineId]])
const postIds = res.map((record) => {
return record.uid
})
return postIds
}
async getFeedsPostsRange(timelineIds, offset, limit, params) {
const responses = await this.database('posts')
.select('uid', 'created_at', 'updated_at', 'user_id', 'body', 'comments_disabled', 'feed_ids', 'destination_feed_ids')
.orderBy('updated_at', 'desc')
.offset(offset).limit(limit)
.whereRaw('feed_ids && ?', [timelineIds]);
const postUids = responses.map((p) => p.uid)
const commentsCount = {}
const likesCount = {}
const groupedComments = await this.database('comments')
.select('post_id', this.database.raw('count(id) as comments_count'))
.where('post_id', 'in', postUids)
.groupBy('post_id')
for (const group of groupedComments) {
if (!commentsCount[group.post_id]) {
commentsCount[group.post_id] = 0
}
commentsCount[group.post_id] += parseInt(group.comments_count)
}
const groupedLikes = await this.database('likes')
.select('post_id', this.database.raw('count(id) as likes_count'))
.where('post_id', 'in', postUids)
.groupBy('post_id')
for (const group of groupedLikes) {
if (!likesCount[group.post_id]) {
likesCount[group.post_id] = 0
}
likesCount[group.post_id] += parseInt(group.likes_count)
}
const objects = responses.map((attrs) => {
if (attrs) {
attrs.comments_count = commentsCount[attrs.uid] || 0
attrs.likes_count = likesCount[attrs.uid] || 0
attrs = this._prepareModelPayload(attrs, POST_FIELDS, POST_FIELDS_MAPPING)
}
return DbAdapter.initObject(Post, attrs, attrs.id, params)
})
return objects
}
/**
* Returns UIDs of timeline posts
*/
async getTimelinePostsIds(timelineIntId, viewerId = null, params = {}) {
params = {
limit: 30,
offset: 0,
sort: 'updated',
withLocalBumps: false,
...params,
};
params.withLocalBumps = params.withLocalBumps && !!viewerId && params.sort === 'updated';
// Private feeds viewer can read
const visiblePrivateFeedIntIds = [];
// Users who banned viewer or banned by viewer (viewer should not see their posts)
const bannedUsersIds = [];
if (viewerId) {
const privateSQL = `
select f.id from
feeds f
join subscriptions s on f.uid = s.feed_id or f.user_id = :viewerId -- viewer's own feed is always visible
join users u on u.uid = f.user_id and u.is_private
where s.user_id = :viewerId and f.name = 'Posts'
`;
const bansSQL = `
select
distinct coalesce( nullif( user_id, :viewerId ), banned_user_id ) as id
from
bans
where
user_id = :viewerId
or banned_user_id = :viewerId
`;
const [
{ rows: privateRows },
{ rows: banRows },
directsFeed,
] = await Promise.all([
this.database.raw(privateSQL, { viewerId }),
this.database.raw(bansSQL, { viewerId }),
this.getUserNamedFeed(viewerId, 'Directs'),
]);
visiblePrivateFeedIntIds.push(..._.map(privateRows, 'id'));
visiblePrivateFeedIntIds.push(directsFeed.intId);
bannedUsersIds.push(..._.map(banRows, 'id'));
}
if (bannedUsersIds.length === 0) {
bannedUsersIds.push(unexistedUID);
}
let sql;
if (params.withLocalBumps) {
sql = pgFormat(`
select p.uid
from
posts p
left join local_bumps b on p.uid = b.post_id and b.user_id = %L
where
p.feed_ids && %L
and not p.user_id in (%L) -- bans
and (not is_private or destination_feed_ids && %L) -- privates
order by
greatest(p.updated_at, b.created_at) desc
limit %L offset %L
`,
viewerId,
`{${timelineIntId}}`,
bannedUsersIds,
`{${visiblePrivateFeedIntIds.join(',')}}`,
params.limit,
params.offset
);
} else {
sql = pgFormat(`
select uid
from
posts
where
feed_ids && %L
and not user_id in (%L) -- bans
and ${viewerId ?
pgFormat(`(not is_private or destination_feed_ids && %L)`, `{${visiblePrivateFeedIntIds.join(',')}}`) :
'not is_protected'
}
order by
%I desc
limit %L offset %L
`, `{${timelineIntId}}`, bannedUsersIds, `${params.sort}_at`, params.limit, params.offset);
}
return (await this.database.raw(sql)).rows.map((r) => r.uid);
}
// merges posts from "source" into "destination"
async createMergedPostsTimeline(destinationTimelineId, sourceTimelineIds) {
const transaction = async (trx) => {
await trx.raw(
'UPDATE "posts" SET "feed_ids" = ("feed_ids" | ?) WHERE "feed_ids" && ?',
[[destinationTimelineId], sourceTimelineIds]
);
};
await this.executeSerizlizableTransaction(transaction);
}
async getTimelinesIntersectionPostIds(timelineId1, timelineId2) {
const res1 = await this.database('posts').select('uid', 'updated_at').orderBy('updated_at', 'desc').whereRaw('feed_ids && ?', [[timelineId1]])
const postIds1 = res1.map((record) => {
return record.uid
})
const res2 = await this.database('posts').select('uid', 'updated_at').orderBy('updated_at', 'desc').whereRaw('feed_ids && ?', [[timelineId2]])
const postIds2 = res2.map((record) => {
return record.uid
})
return _.intersection(postIds1, postIds2)
}
/**
* Show all PUBLIC posts with
* 10+ likes
* 15+ comments by 5+ users
* Created less than 60 days ago
*/
bestPosts = async (currentUser, offset = 0, limit = 30) => {
const MIN_LIKES = 10;
const MIN_COMMENTS = 15;
const MIN_COMMENT_AUTHORS = 5;
const MAX_DAYS = 60;
let bannedUsersFilter = '';
let usersWhoBannedMeFilter = '';
const publicOrVisibleForAnonymous = currentUser ? 'not "users"."is_private"' : 'not "users"."is_protected"'
if (currentUser) {
const [iBanned, bannedMe] = await Promise.all([
this.getUserBansIds(currentUser.id),
this.getUserIdsWhoBannedUser(currentUser.id)
]);
bannedUsersFilter = this._getPostsFromBannedUsersSearchFilterCondition(iBanned);
if (bannedMe.length > 0) {
usersWhoBannedMeFilter = pgFormat('AND "feeds"."user_id" NOT IN (%L) ', bannedMe);
}
}
const sql = `
SELECT
DISTINCT "posts".* FROM "posts"
LEFT JOIN (SELECT post_id, COUNT("id") AS "comments_count", COUNT(DISTINCT "user_id") as "comment_authors_count" FROM "comments" GROUP BY "comments"."post_id") AS "c" ON "c"."post_id" = "posts"."uid"
LEFT JOIN (SELECT post_id, COUNT("id") AS "likes_count" FROM "likes" GROUP BY "likes"."post_id") AS "l" ON "l"."post_id" = "posts"."uid"
INNER JOIN "feeds" ON "posts"."destination_feed_ids" # feeds.id > 0 AND "feeds"."name" = 'Posts'
INNER JOIN "users" ON "feeds"."user_id" = "users"."uid" AND ${publicOrVisibleForAnonymous}
WHERE
"l"."likes_count" >= ${MIN_LIKES} AND "c"."comments_count" >= ${MIN_COMMENTS} AND "c"."comment_authors_count" >= ${MIN_COMMENT_AUTHORS} AND "posts"."created_at" > (current_date - ${MAX_DAYS} * interval '1 day')
${bannedUsersFilter}
${usersWhoBannedMeFilter}
ORDER BY "posts"."updated_at" DESC
OFFSET ${offset} LIMIT ${limit}`;
const res = await this.database.raw(sql);
return res.rows;
};
/**
* Returns array of objects with the following structure:
* {
* post: <Post object>
* destinations: <array of {id (feed UID), name (feed type), user (feed owner UID)}
* objects of posts' destination timelines>
* attachments: <array of Attachment objects>
* comments: <array of Comments objects>
* omittedComments: <number>
* likes: <array of liker's UIDs>
* omittedLikes: <number>
* }
*/
async getPostsWithStuffByIds(postsIds, viewerId = null, params = {}) {
if (_.isEmpty(postsIds)) {
return [];
}
params = {
foldComments: true,
foldLikes: true,
maxUnfoldedComments: 3,
maxUnfoldedLikes: 4,
visibleFoldedLikes: 3,
...params,
};
const uniqPostsIds = _.uniq(postsIds);
const postFields = _.without(Object.keys(POST_FIELDS), 'comments_count', 'likes_count').map((k) => pgFormat('%I', k));
const attFields = Object.keys(ATTACHMENT_FIELDS).map((k) => pgFormat('%I', k));
const commentFields = Object.keys(COMMENT_FIELDS).map((k) => pgFormat('%I', k));
const destinationsSQL = pgFormat(`
with posts as (
-- unwind all destination_feed_ids from posts
select distinct
p.uid,
unnest(p.destination_feed_ids) as feed_id
from
posts p
where
p.uid in (%L)
)
select
p.uid as post_id, f.uid as id, f.name, f.user_id as user
from
feeds f join posts p on f.id = p.feed_id
`, uniqPostsIds);
const [
bannedUsersIds,
friendsIds,
postsData,
attData,
{ rows: destData },
] = await Promise.all([
viewerId ? this.getUserBansIds(viewerId) : [],
viewerId ? this.getUserFriendIds(viewerId) : [],
this.database.select(...postFields).from('posts').whereIn('uid', uniqPostsIds),
this.database.select(...attFields).from('attachments').orderBy('created_at', 'asc').whereIn('post_id', uniqPostsIds),
this.database.raw(destinationsSQL),
]);
if (bannedUsersIds.length === 0) {
bannedUsersIds.push(unexistedUID);
}
if (friendsIds.length === 0) {
friendsIds.push(unexistedUID);
}
const allLikesSQL = pgFormat(`
select
post_id, user_id,
rank() over (partition by post_id order by
user_id in (%L) desc,
user_id in (%L) desc,
created_at desc,
id desc
),
count(*) over (partition by post_id)
from likes
where post_id in (%L) and user_id not in (%L)
`, [viewerId], friendsIds, uniqPostsIds, bannedUsersIds);
const likesSQL = `
with likes as (${allLikesSQL})
select post_id, array_agg(user_id) as likes, count from likes
${params.foldLikes ?
pgFormat(`where count <= %L or rank <= %L`, params.maxUnfoldedLikes, params.visibleFoldedLikes) :
``}
group by post_id, count
`;
const allCommentsSQL = pgFormat(`
select
${commentFields.join(', ')}, id,
rank() over (partition by post_id order by created_at, id),
count(*) over (partition by post_id)
from comments
where post_id in (%L) and user_id not in (%L)
`, uniqPostsIds, bannedUsersIds);
const commentsSQL = `
with comments as (${allCommentsSQL})
select ${commentFields.join(', ')}, id, count from comments
${params.foldComments ?
pgFormat(`where count <= %L or rank = 1 or rank = count`, params.maxUnfoldedComments) :
``}
order by created_at, id
`;
const [
{ rows: likesData },
{ rows: commentsData },
] = await Promise.all([
this.database.raw(likesSQL),
this.database.raw(commentsSQL),
]);
const results = {};
for (const post of postsData) {
results[post.uid] = {
post: this.initPostObject(post),
destinations: [],
attachments: [],
comments: [],
omittedComments: 0,
likes: [],
omittedLikes: 0,
};
}
for (const dest of destData) {
results[dest.post_id].destinations.push(_.omit(dest, 'post_id'));
}
for (const att of attData) {
results[att.post_id].attachments.push(this.initAttachmentObject(att));
}
for (const lk of likesData) {
results[lk.post_id].likes = lk.likes;
results[lk.post_id].omittedLikes = lk.count - lk.likes.length;
}
for (const comm of commentsData) {
results[comm.post_id].comments.push(this.initCommentObject(comm));
results[comm.post_id].omittedComments = comm.count <= 3 ? 0 : comm.count - 2;
}
return postsIds.map((id) => results[id] || null);
}
///////////////////////////////////////////////////
// Subscriptions
///////////////////////////////////////////////////
getUserSubscriptionsIds(userId) {
return this.database('subscriptions').pluck('feed_id').orderBy('created_at', 'desc').where('user_id', userId)
}
getUserSubscriptionsIdsByType(userId, feedType) {
return this.database
.pluck('s.feed_id')
.from('subscriptions as s').innerJoin('feeds as f', 's.feed_id', 'f.uid')
.where({ 's.user_id': userId, 'f.name': feedType })
.orderBy('s.created_at', 'desc')
}
getUserFriendIds(userId) {
const feedType = 'Posts';
return this.database
.pluck('f.user_id')
.from('subscriptions as s')
.innerJoin('feeds as f', 's.feed_id', 'f.uid')
.where({ 's.user_id': userId, 'f.name': feedType })
.orderBy('s.created_at', 'desc');
}
async isUserSubscribedToTimeline(currentUserId, timelineId) {
const res = await this.database('subscriptions').where({
feed_id: timelineId,
user_id: currentUserId
}).count()
return parseInt(res[0].count) != 0
}
async isUserSubscribedToOneOfTimelines(currentUserId, timelineIds) {
const q = pgFormat('SELECT COUNT(*) AS "cnt" FROM "subscriptions" WHERE "feed_id" IN (%L) AND "user_id" = ?', timelineIds);
const res = await this.database.raw(q, [currentUserId]);
return res.rows[0].cnt > 0;
}
async getTimelineSubscribersIds(timelineId) {
return await this.database('subscriptions').pluck('user_id').orderBy('created_at', 'desc').where('feed_id', timelineId)
}
async getTimelineSubscribers(timelineIntId) {
const responses = this.database('users').whereRaw('subscribed_feed_ids && ?', [[timelineIntId]])
return responses.map(this.initUserObject)
}
async subscribeUserToTimelines(timelineIds, currentUserId) {
const subsPromises = timelineIds.map((id) => {
const currentTime = new Date().toISOString()
const payload = {
feed_id: id,
user_id: currentUserId,
created_at: currentTime
}
return this.database('subscriptions').returning('id').insert(payload)
})
await Promise.all(subsPromises)
const feedIntIds = await this.getTimelinesIntIdsByUUIDs(timelineIds)
const res = await this.database.raw(
'UPDATE users SET subscribed_feed_ids = (subscribed_feed_ids | ?) WHERE uid = ? RETURNING subscribed_feed_ids',
[feedIntIds, currentUserId]
);
await this.cacheFlushUser(currentUserId)
return res.rows[0].subscribed_feed_ids
}
async unsubscribeUserFromTimelines(timelineIds, currentUserId) {
const unsubsPromises = timelineIds.map((id) => {
return this.database('subscriptions').where({
feed_id: id,
user_id: currentUserId
}).delete()
})
await Promise.all(unsubsPromises)
const feedIntIds = await this.getTimelinesIntIdsByUUIDs(timelineIds)
const res = await this.database.raw(
'UPDATE users SET subscribed_feed_ids = (subscribed_feed_ids - ?) WHERE uid = ? RETURNING subscribed_feed_ids',
[feedIntIds, currentUserId]
);
await this.cacheFlushUser(currentUserId)
return res.rows[0].subscribed_feed_ids
}
/**
* Executes SERIALIZABLE transaction until it succeeds
* @param transaction
*/
async executeSerizlizableTransaction(transaction) {
while (true) { // eslint-disable-line no-constant-condition
try {
await this.database.transaction(async (trx) => { // eslint-disable-line babel/no-await-in-loop
await trx.raw('SET TRANSACTION ISOLATION LEVEL SERIALIZABLE');
return transaction(trx);
});
break;
} catch (e) {
if (e.code === '40001') {
// Serialization failure (other transaction has changed the data). RETRY
continue;
}
throw e;
}
}
}
///////////////////////////////////////////////////
// LocalBumps
///////////////////////////////////////////////////
async createLocalBump(postId, userId) {
const existingPostLocalBumps = await this.database('local_bumps').where({
post_id: postId,
user_id: userId
}).count()
if (parseInt(existingPostLocalBumps[0].count) > 0) {
return true
}
const payload = {
post_id: postId,
user_id: userId
}
return this.database('local_bumps').returning('id').insert(payload)
}
async getUserLocalBumps(userId, newerThan) {
const time = new Date()
if (newerThan) {
time.setTime(newerThan)
}
const res = await this.database('local_bumps').orderBy('created_at', 'desc').where('user_id', userId).where('created_at', '>', time.toISOString())
const bumps = res.map((record) => {
return {
postId: record.post_id,
bumpedAt: record.created_at.getTime()
}
})
return bumps
}
///////////////////////////////////////////////////
// Search
///////////////////////////////////////////////////
async searchPosts(query, currentUserId, visibleFeedIds, bannedUserIds, offset, limit) {
const textSearchConfigName = this.database.client.config.textSearchConfigName
const bannedUsersFilter = this._getPostsFromBannedUsersSearchFilterCondition(bannedUserIds)
const bannedCommentAuthorFilter = this._getCommentsFromBannedUsersSearchFilterCondition(bannedUserIds)
const searchCondition = this._getTextSearchCondition(query, textSearchConfigName)
const commentSearchCondition = this._getCommentSearchCondition(query, textSearchConfigName)
const publicOrVisibleForAnonymous = currentUserId ? 'not users.is_private' : 'not users.is_protected'
if (!visibleFeedIds || visibleFeedIds.length == 0) {
visibleFeedIds = 'NULL'
}
const publicPostsSubQuery = 'select "posts".* from "posts" ' +
'inner join "feeds" on posts.destination_feed_ids # feeds.id > 0 and feeds.name=\'Posts\' ' +
`inner join "users" on feeds.user_id=users.uid and ${publicOrVisibleForAnonymous} ` +
`where ${searchCondition} ${bannedUsersFilter}`;
const publicPostsByCommentsSubQuery = 'select "posts".* from "posts" ' +
'inner join "feeds" on posts.destination_feed_ids # feeds.id > 0 and feeds.name=\'Posts\' ' +
`inner join "users" on feeds.user_id=users.uid and ${publicOrVisibleForAnonymous} ` +
`where
posts.uid in (
select post_id from comments where ${commentSearchCondition} ${bannedCommentAuthorFilter}
) ${bannedUsersFilter}`;
let subQueries = [publicPostsSubQuery, publicPostsByCommentsSubQuery];
if (currentUserId) {
const myPostsSubQuery = 'select "posts".* from "posts" ' +
`where "posts"."user_id" = '${currentUserId}' and ${searchCondition}`;
const myPostsByCommentsSubQuery = 'select "posts".* from "posts" ' +
`where "posts"."user_id" = '${currentUserId}' and
posts.uid in (
select post_id from comments where ${commentSearchCondition} ${bannedCommentAuthorFilter}
) `;
const visiblePrivatePostsSubQuery = 'select "posts".* from "posts" ' +
'inner join "feeds" on posts.destination_feed_ids # feeds.id > 0 and feeds.name=\'Posts\' ' +
'inner join "users" on feeds.user_id=users.uid and users.is_private=true ' +
`where ${searchCondition} and "feeds"."id" in (${visibleFeedIds}) ${bannedUsersFilter}`;
const visiblePrivatePostsByCommentsSubQuery = 'select "posts".* from "posts" ' +
'inner join "feeds" on posts.destination_feed_ids # feeds.id > 0 and feeds.name=\'Posts\' ' +
'inner join "users" on feeds.user_id=users.uid and users.is_private=true ' +
`where
posts.uid in (
select post_id from comments where ${commentSearchCondition} ${bannedCommentAuthorFilter}
)
and "feeds"."id" in (${visibleFeedIds}) ${bannedUsersFilter}`;
subQueries = [...subQueries, myPostsSubQuery, myPostsByCommentsSubQuery, visiblePrivatePostsSubQuery, visiblePrivatePostsByCommentsSubQuery];
}
const res = await this.database.raw(
`select * from (${subQueries.join(' union ')}) as found_posts order by found_posts.updated_at desc offset ${offset} limit ${limit}`
)
return res.rows
}
async searchUserPosts(query, targetUserId, visibleFeedIds, bannedUserIds, offset, limit) {
const textSearchConfigName = this.database.client.config.textSearchConfigName
const bannedUsersFilter = this._getPostsFromBannedUsersSearchFilterCondition(bannedUserIds)
const bannedCommentAuthorFilter = this._getCommentsFromBannedUsersSearchFilterCondition(bannedUserIds)
const searchCondition = this._getTextSearchCondition(query, textSearchConfigName)
const commentSearchCondition = this._getCommentSearchCondition(query, textSearchConfigName)
const publicPostsSubQuery = 'select "posts".* from "posts" ' +
'inner join "feeds" on posts.destination_feed_ids # feeds.id > 0 and feeds.name=\'Posts\' ' +
'inner join "users" on feeds.user_id=users.uid and users.is_private=false ' +
`where ${searchCondition} ${bannedUsersFilter}`;
const publicPostsByCommentsSubQuery = 'select "posts".* from "posts" ' +
'inner join "feeds" on posts.destination_feed_ids # feeds.id > 0 and feeds.name=\'Posts\' ' +
'inner join "users" on feeds.user_id=users.uid and users.is_private=false ' +
`where
posts.uid in (
select post_id from comments where ${commentSearchCondition} ${bannedCommentAuthorFilter}
) ${bannedUsersFilter}`;
let subQueries = [publicPostsSubQuery, publicPostsByCommentsSubQuery];
if (visibleFeedIds && visibleFeedIds.length > 0) {
const visiblePrivatePostsSubQuery = 'select "posts".* from "posts" ' +
'inner join "feeds" on posts.destination_feed_ids # feeds.id > 0 and feeds.name=\'Posts\' ' +
'inner join "users" on feeds.user_id=users.uid and users.is_private=true ' +
`where ${searchCondition} and "feeds"."id" in (${visibleFeedIds}) ${bannedUsersFilter}`;
const visiblePrivatePostsByCommentsSubQuery = 'select "posts".* from "posts" ' +
'inner join "feeds" on posts.destination_feed_ids # feeds.id > 0 and feeds.name=\'Posts\' ' +
'inner join "users" on feeds.user_id=users.uid and users.is_private=true ' +
`where
posts.uid in (
select post_id from comments where ${commentSearchCondition} ${bannedCommentAuthorFilter}
)
and "feeds"."id" in (${visibleFeedIds}) ${bannedUsersFilter}`;
subQueries = [...subQueries, visiblePrivatePostsSubQuery, visiblePrivatePostsByCommentsSubQuery];
}
const res = await this.database.raw(
`select * from (${subQueries.join(' union ')}) as found_posts where found_posts.user_id='${targetUserId}' order by found_posts.updated_at desc offset ${offset} limit ${limit}`
)
return res.rows
}
async searchGroupPosts(query, groupFeedId, visibleFeedIds, bannedUserIds, offset, limit) {
const textSearchConfigName = this.database.client.config.textSearchConfigName
const bannedUsersFilter = this._getPostsFromBannedUsersSearchFilterCondition(bannedUserIds)
const bannedCommentAuthorFilter = this._getCommentsFromBannedUsersSearchFilterCondition(bannedUserIds)
const searchCondition = this._getTextSearchCondition(query, textSearchConfigName)
const commentSearchCondition = this._getCommentSearchCondition(query, textSearchConfigName)
if (!visibleFeedIds || visibleFeedIds.length == 0) {
visibleFeedIds = 'NULL'
}
const publicPostsSubQuery = 'select "posts".* from "posts" ' +
`inner join "feeds" on posts.destination_feed_ids # feeds.id > 0 and feeds.name=\'Posts\' and feeds.uid='${groupFeedId}' ` +
'inner join "users" on feeds.user_id=users.uid and users.is_private=false ' +
`where ${searchCondition} ${bannedUsersFilter}`;
const publicPostsByCommentsSubQuery = 'select "posts".* from "posts" ' +
`inner join "feeds" on posts.destination_feed_ids # feeds.id > 0 and feeds.name=\'Posts\' and feeds.uid='${groupFeedId}' ` +
'inner join "users" on feeds.user_id=users.uid and users.is_private=false ' +
`where
posts.uid in (
select post_id from comments where ${commentSearchCondition} ${bannedCommentAuthorFilter}
) ${bannedUsersFilter}`;
let subQueries = [publicPostsSubQuery, publicPostsByCommentsSubQuery];
if (visibleFeedIds && visibleFeedIds.length > 0) {
const visiblePrivatePostsSubQuery = 'select "posts".* from "posts" ' +
`inner join "feeds" on posts.destination_feed_ids # feeds.id > 0 and feeds.name=\'Posts\' and feeds.uid='${groupFeedId}' ` +
'inner join "users" on feeds.user_id=users.uid and users.is_private=true ' +
`where ${searchCondition} and "feeds"."id" in (${visibleFeedIds}) ${bannedUsersFilter}`;
const visiblePrivatePostsByCommentsSubQuery = 'select "posts".* from "posts" ' +
`inner join "feeds" on posts.destination_feed_ids # feeds.id > 0 and feeds.name=\'Posts\' and feeds.uid='${groupFeedId}' ` +
'inner join "users" on feeds.user_id=users.uid and users.is_private=true ' +
`where
posts.uid in (
select post_id from comments where ${commentSearchCondition} ${bannedCommentAuthorFilter}
)
and "feeds"."id" in (${visibleFeedIds}) ${bannedUsersFilter}`;
subQueries = [...subQueries, visiblePrivatePostsSubQuery, visiblePrivatePostsByCommentsSubQuery];
}
const res = await this.database.raw(
`select * from (${subQueries.join(' union ')}) as found_posts order by found_posts.updated_at desc offset ${offset} limit ${limit}`
)
return res.rows
}
initRawPosts(rawPosts, params) {
const objects = rawPosts.map((attrs) => {
if (attrs) {
attrs = this._prepareModelPayload(attrs, POST_FIELDS, POST_FIELDS_MAPPING)
}
return DbAdapter.initObject(Post, attrs, attrs.id, params)
})
return objects
}
_getPostsFromBannedUsersSearchFilterCondition(bannedUserIds) {
if (bannedUserIds.length === 0) {
return '';
}
return pgFormat('and posts.user_id not in (%L) ', bannedUserIds);
}
_getCommentsFromBannedUsersSearchFilterCondition(bannedUserIds) {
if (bannedUserIds.length === 0) {
return '';
}
return pgFormat(`and comments.user_id not in (%L) `, bannedUserIds)
}
_getTextSearchCondition(parsedQuery, textSearchConfigName) {
const searchConditions = []
if (parsedQuery.query.length > 2) {
const sql = pgFormat(`to_tsvector(%L, posts.body) @@ to_tsquery(%L, %L)`, textSearchConfigName, textSearchConfigName, parsedQuery.query)
searchConditions.push(sql)
}
if (parsedQuery.quotes.length > 0) {
const quoteConditions = parsedQuery.quotes.map((quote) => {
const regex = `([[:<:]]|\\W|^)${_.escapeRegExp(quote)}([[:>:]]|\\W|$)`;
return pgFormat(`posts.body ~ %L`, regex)
});
searchConditions.push(`${quoteConditions.join(' and ')}`)
}
if (parsedQuery.hashtags.length > 0) {
const hashtagConditions = parsedQuery.hashtags.map((tag) => {
return pgFormat(`posts.uid in (
select u.entity_id from hashtag_usages as u where u.hashtag_id in (
select hashtags.id from hashtags where hashtags.name = %L
) and u.type = 'post'
)`, tag)
})
searchConditions.push(`${hashtagConditions.join(' and ')}`)
}
if (searchConditions.length == 0) {
return ' 1=0 '
}
return `${searchConditions.join(' and ')} `
}
_getCommentSearchCondition(parsedQuery, textSearchConfigName) {
const searchConditions = []
if (parsedQuery.query.length > 2) {
const sql = pgFormat(`to_tsvector(%L, comments.body) @@ to_tsquery(%L, %L)`, textSearchConfigName, textSearchConfigName, parsedQuery.query)
searchConditions.push(sql)
}
if (parsedQuery.quotes.length > 0) {
const quoteConditions = parsedQuery.quotes.map((quote) => {
const regex = `([[:<:]]|\\W|^)${_.escapeRegExp(quote)}([[:>:]]|\\W|$)`;
return pgFormat(`comments.body ~ %L`, regex)
});
searchConditions.push(`${quoteConditions.join(' and ')}`)
}
if (parsedQuery.hashtags.length > 0) {
const hashtagConditions = parsedQuery.hashtags.map((tag) => {
return pgFormat(`comments.uid in (
select u.entity_id from hashtag_usages as u where u.hashtag_id in (
select hashtags.id from hashtags where hashtags.name = %L
) and u.type = 'comment'
)`, tag)
})
searchConditions.push(`${hashtagConditions.join(' and ')}`)
}
if (searchConditions.length == 0) {
return ' 1=0 '
}
return `${searchConditions.join(' and ')} `
}
///////////////////////////////////////////////////
// Hashtags
///////////////////////////////////////////////////
async getHashtagIdsByNames(names) {
if (!names || names.length == 0) {
return []
}
const lowerCaseNames = names.map((hashtag) => {
return hashtag.toLowerCase()
})
const res = await this.database('hashtags').select('id', 'name').where('name', 'in', lowerCaseNames)
return res.map((t) => t.id)
}
async getOrCreateHashtagIdsByNames(names) {
if (!names || names.length == 0) {
return []
}
const lowerCaseNames = names.map((hashtag) => {
return hashtag.toLowerCase()
})
const targetTagNames = _.sortBy(lowerCaseNames)
const existingTags = await this.database('hashtags').select('id', 'name').where('name', 'in', targetTagNames)
const existingTagNames = _.sortBy(existingTags.map((t) => t.name))
const nonExistingTagNames = _.difference(targetTagNames, existingTagNames)
let tags = existingTags.map((t) => t.id)
if (nonExistingTagNames.length > 0) {
const createdTags = await this.createHashtags(nonExistingTagNames)
if (createdTags.length > 0) {
tags = tags.concat(createdTags)
}
}
return tags
}
getPostHashtags(postId) {
return this.database.select('hashtags.id', 'hashtags.name').from('hashtags')
.join('hashtag_usages', { 'hashtag_usages.hashtag_id': 'hashtags.id' })
.where('hashtag_usages.entity_id', '=', postId).andWhere('hashtag_usages.type', 'post')
}
getCommentHashtags(commentId) {
return this.database.select('hashtags.id', 'hashtags.name').from('hashtags')
.join('hashtag_usages', { 'hashtag_usages.hashtag_id': 'hashtags.id' })
.where('hashtag_usages.entity_id', '=', commentId).andWhere('hashtag_usages.type', 'comment')
}
async createHashtags(names) {
if (!names || names.length == 0) {
return []
}
const payload = names.map((name) => {
return pgFormat(`(%L)`, name.toLowerCase())
}).join(',')
const res = await this.database.raw(`insert into hashtags ("name") values ${payload} on conflict do nothing returning "id" `)
return res.rows.map((t) => t.id)
}
linkHashtags(tagIds, entityId, toPost = true) {
if (tagIds.length == 0) {
return false
}
const entityType = toPost ? 'post' : 'comment'
const payload = tagIds.map((hashtagId) => {
return pgFormat(`(%L, %L, %L)`, hashtagId, entityId, entityType)
}).join(',')
return this.database.raw(`insert into hashtag_usages ("hashtag_id", "entity_id", "type") values ${payload} on conflict do nothing`)
}
unlinkHashtags(tagIds, entityId, fromPost = true) {
if (tagIds.length == 0) {
return false
}
let entityType = 'post'
if (!fromPost) {
entityType = 'comment'
}
return this.database('hashtag_usages').where('hashtag_id', 'in', tagIds).where('entity_id', entityId).where('type', entityType).del()
}
async linkPostHashtagsByNames(names, postId) {
if (!names || names.length == 0) {
return false
}
const hashtagIds = await this.getOrCreateHashtagIdsByNames(names)
if (!hashtagIds || hashtagIds.length == 0) {
return false
}
return this.linkHashtags(hashtagIds, postId)
}
async unlinkPostHashtagsByNames(names, postId) {
if (!names || names.length == 0) {
return false
}
const hashtagIds = await this.getHashtagIdsByNames(names)
if (!hashtagIds || hashtagIds.length == 0) {
return false
}
return this.unlinkHashtags(hashtagIds, postId)
}
async linkCommentHashtagsByNames(names, commentId) {
if (!names || names.length == 0) {
return false
}
const hashtagIds = await this.getOrCreateHashtagIdsByNames(names)
if (!hashtagIds || hashtagIds.length == 0) {
return false
}
return this.linkHashtags(hashtagIds, commentId, false)
}
async unlinkCommentHashtagsByNames(names, commentId) {
if (!names || names.length == 0) {
return false
}
const hashtagIds = await this.getHashtagIdsByNames(names)
if (!hashtagIds || hashtagIds.length == 0) {
return false
}
return this.unlinkHashtags(hashtagIds, commentId, false)
}
///////////////////////////////////////////////////
// Unread directs counter
///////////////////////////////////////////////////
async markAllDirectsAsRead(userId) {
const currentTime = new Date().toISOString()
const payload = { directs_read_at: currentTime }
return this.database('users').where('uid', userId).update(payload)
}
async getUnreadDirectsNumber(userId) {
const [
[directsFeedId],
[directsReadAt],
] = await Promise.all([
this.database.pluck('id').from('feeds').where({ 'user_id': userId, 'name': 'Directs' }),
this.database.pluck('directs_read_at').from('users').where({ 'uid': userId }),
]);
/*
Select posts from my Directs feed, created after the directs_read_at authored by
users other than me and then add posts from my Directs feed, having comments created after the directs_read_at
authored by users other than me
*/
const sql = `
select count(distinct unread.id) as cnt from (
select id from
posts
where
destination_feed_ids && :feeds
and user_id != :userId
and created_at > :directsReadAt
union
select p.id from
comments c
join posts p on p.uid = c.post_id
where
p.destination_feed_ids && :feeds
and c.user_id != :userId
and c.created_at > :directsReadAt
) as unread`;
const res = await this.database.raw(sql, { feeds: `{${directsFeedId}}`, userId, directsReadAt });
return res.rows[0].cnt;
}
///////////////////////////////////////////////////
// Stats
///////////////////////////////////////////////////
async getStats(data, start_date, end_date) {
const supported_metrics = ['comments', 'comments_creates', 'posts', 'posts_creates', 'users', 'registrations',
'active_users', 'likes', 'likes_creates', 'groups', 'groups_creates'];
const metrics = data.split(',').sort();
let metrics_req = ``, metrics_list = `''null''`;
for (const metric of metrics) {
if (supported_metrics.includes(metric)) {
metrics_req += `, "${metric}" bigint`;
metrics_list += `, ''${metric}''`;
} else {
throw new Error(`ERROR: unsupported metric: ${metric}`);
}
}
if (!metrics_req.length) {
return null;
}
const sql = pgFormat(`
select * from crosstab(
'select to_char(dt, ''YYYY-MM-DD'') as date, metric, value from stats
where dt between '%L' and '%L'
and metric in (%s)
order by 1,2;')
AS ct ("date" text %s);`, start_date, end_date, metrics_list, metrics_req);
const res = await this.database.raw(sql);
return res.rows;
}
}
|
Optimize the getUserSubscribersIds method
|
app/support/DbAdapter.js
|
Optimize the getUserSubscribersIds method
|
<ide><path>pp/support/DbAdapter.js
<ide> return feed
<ide> }
<ide>
<del> async getUserSubscribers(id) {
<del> if (!validator.isUUID(id, 4)) {
<del> return null;
<del> }
<del>
<del> const sql = `
<del> select user_id from subscriptions
<del> where feed_id in (
<del> select uid from feeds where user_id = ? and name = 'Posts'
<del> )
<del> order by created_at`;
<del>
<del> const res = await this.database.raw(sql, id);
<del> return res.rows;
<add> async getUserSubscribersIds(userId) {
<add> return await this.database
<add> .pluck('s.user_id')
<add> .from('subscriptions as s')
<add> .innerJoin('feeds as f', 'f.uid', 's.feed_id')
<add> .where('f.name', 'Posts')
<add> .where('f.user_id', userId)
<add> .orderBy('s.created_at', 'desc');
<ide> }
<ide>
<ide> ///////////////////////////////////////////////////
|
|
Java
|
apache-2.0
|
047c818c9e32e0f734df5dbf7e8cfe31d7be7d6e
| 0 |
google/j2cl,google/j2cl,google/j2cl,google/j2cl,google/j2cl
|
/*
* Copyright 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.j2cl.transpiler.ast;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.j2cl.common.SourcePosition;
import com.google.j2cl.common.visitor.Processor;
import com.google.j2cl.common.visitor.Visitable;
import javax.annotation.Nullable;
/** If Statement. */
@Visitable
public class IfStatement extends Statement {
@Visitable Expression conditionExpression;
@Visitable Statement thenStatement;
@Visitable @Nullable Statement elseStatement;
private IfStatement(
SourcePosition sourcePosition,
Expression conditionExpression,
Statement thenStatement,
@Nullable Statement elseStatement) {
super(sourcePosition);
this.conditionExpression = checkNotNull(conditionExpression);
this.thenStatement = checkNotNull(thenStatement);
this.elseStatement = elseStatement;
}
public Expression getConditionExpression() {
return conditionExpression;
}
public Statement getThenStatement() {
return thenStatement;
}
@Nullable
public Statement getElseStatement() {
return elseStatement;
}
@Override
public IfStatement clone() {
return new IfStatement(
getSourcePosition(),
conditionExpression.clone(),
thenStatement.clone(),
AstUtils.clone(elseStatement));
}
@Override
public Node accept(Processor processor) {
return Visitor_IfStatement.visit(processor, this);
}
public static Builder newBuilder() {
return new Builder();
}
/** A Builder for IfStatement. */
public static class Builder {
private Expression conditionExpression;
private Statement thenStatement;
private Statement elseStatement;
private SourcePosition sourcePosition;
public static Builder from(IfStatement ifStatement) {
return new Builder()
.setSourcePosition(ifStatement.getSourcePosition())
.setConditionExpression(ifStatement.getConditionExpression())
.setThenStatement(ifStatement.getThenStatement())
.setElseStatement(ifStatement.getElseStatement());
}
public Builder setSourcePosition(SourcePosition sourcePosition) {
this.sourcePosition = sourcePosition;
return this;
}
public Builder setConditionExpression(Expression conditionExpression) {
this.conditionExpression = conditionExpression;
return this;
}
public Builder setThenStatement(Statement thenStatement) {
this.thenStatement = thenStatement;
return this;
}
public Builder setElseStatement(Statement elseStatement) {
this.elseStatement = elseStatement;
return this;
}
public IfStatement build() {
return new IfStatement(sourcePosition, conditionExpression, thenStatement, elseStatement);
}
}
}
|
transpiler/java/com/google/j2cl/transpiler/ast/IfStatement.java
|
/*
* Copyright 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.j2cl.transpiler.ast;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.j2cl.common.SourcePosition;
import com.google.j2cl.common.visitor.Processor;
import com.google.j2cl.common.visitor.Visitable;
import javax.annotation.Nullable;
/** If Statement. */
@Visitable
public class IfStatement extends Statement {
@Visitable Expression conditionExpression;
@Visitable Statement thenStatement;
@Visitable @Nullable Statement elseStatement;
private IfStatement(
SourcePosition sourcePosition,
Expression conditionExpression,
Statement thenStatement,
Statement elseStatement) {
super(sourcePosition);
this.conditionExpression = checkNotNull(conditionExpression);
this.thenStatement = checkNotNull(thenStatement);
this.elseStatement = elseStatement;
}
public Expression getConditionExpression() {
return conditionExpression;
}
public Statement getThenStatement() {
return thenStatement;
}
public Statement getElseStatement() {
return elseStatement;
}
@Override
public IfStatement clone() {
return new IfStatement(
getSourcePosition(),
conditionExpression.clone(),
thenStatement.clone(),
AstUtils.clone(elseStatement));
}
@Override
public Node accept(Processor processor) {
return Visitor_IfStatement.visit(processor, this);
}
public static Builder newBuilder() {
return new Builder();
}
/** A Builder for IfStatement. */
public static class Builder {
private Expression conditionExpression;
private Statement thenStatement;
private Statement elseStatement;
private SourcePosition sourcePosition;
public static Builder from(IfStatement ifStatement) {
return new Builder()
.setSourcePosition(ifStatement.getSourcePosition())
.setConditionExpression(ifStatement.getConditionExpression())
.setThenStatement(ifStatement.getThenStatement())
.setElseStatement(ifStatement.getElseStatement());
}
public Builder setSourcePosition(SourcePosition sourcePosition) {
this.sourcePosition = sourcePosition;
return this;
}
public Builder setConditionExpression(Expression conditionExpression) {
this.conditionExpression = conditionExpression;
return this;
}
public Builder setThenStatement(Statement thenStatement) {
this.thenStatement = thenStatement;
return this;
}
public Builder setElseStatement(Statement elseStatement) {
this.elseStatement = elseStatement;
return this;
}
public IfStatement build() {
return new IfStatement(sourcePosition, conditionExpression, thenStatement, elseStatement);
}
}
}
|
Add @Nullable annotation to IfStatement.getElseStatement().
PiperOrigin-RevId: 480931633
|
transpiler/java/com/google/j2cl/transpiler/ast/IfStatement.java
|
Add @Nullable annotation to IfStatement.getElseStatement().
|
<ide><path>ranspiler/java/com/google/j2cl/transpiler/ast/IfStatement.java
<ide> SourcePosition sourcePosition,
<ide> Expression conditionExpression,
<ide> Statement thenStatement,
<del> Statement elseStatement) {
<add> @Nullable Statement elseStatement) {
<ide> super(sourcePosition);
<ide> this.conditionExpression = checkNotNull(conditionExpression);
<ide> this.thenStatement = checkNotNull(thenStatement);
<ide> return thenStatement;
<ide> }
<ide>
<add> @Nullable
<ide> public Statement getElseStatement() {
<ide> return elseStatement;
<ide> }
|
|
Java
|
lgpl-2.1
|
2e30ac1d3ddfe0d8c2482d528cc0a8d030cea2ea
| 0 |
celements/celements-core,celements/celements-core
|
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package com.celements.web.plugin.cmd;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.velocity.VelocityContext;
import org.xwiki.context.Execution;
import org.xwiki.model.reference.DocumentReference;
import com.celements.emptycheck.internal.IDefaultEmptyDocStrategyRole;
import com.celements.web.service.IWebUtilsService;
import com.celements.web.token.NewCelementsTokenForUserCommand;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.api.Attachment;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.web.Utils;
public class PasswordRecoveryAndEmailValidationCommand {
private static final String CEL_PASSWORD_RECOVERY_SUBJECT_KEY = "cel_password_recovery_default_subject";
private static Log LOGGER = LogFactory.getFactory().getInstance(
PasswordRecoveryAndEmailValidationCommand.class);
static final String CEL_ACOUNT_ACTIVATION_MAIL_SUBJECT_KEY =
"cel_register_acount_activation_mail_subject";
private CelSendMail injectedCelSendMail;
IWebUtilsService injected_webUtilsService;
public String recoverPassword() {
String email = getContext().getRequest().get("j_username");
if((email != null) && !"".equals(email.trim())) {
try {
String account = new UserNameForUserDataCommand().getUsernameForUserData(email,
"email", getContext());
return recoverPassword(account, email);
} catch (XWikiException e) {
LOGGER.error("Exception getting userdoc for email '" + email + "'", e);
}
}
List<String> params = new ArrayList<String>();
params.add(email);
return getContext().getMessageTool().get("cel_password_recovery_failed", params);
}
// Allow recovery exclusively for email input
public String recoverPassword(String account, String input) {
List<String> params = new ArrayList<String>();
params.add(input);
String resultMsgKey = "cel_password_recovery_failed";
if((account != null) && (!"".equals(account.trim()))) {
account = completeAccountFN(account);
DocumentReference accountDocRef = getWebUtilsService().resolveDocumentReference(
account);
XWikiDocument userDoc = null;
BaseObject userObj = null;
if(getContext().getWiki().exists(accountDocRef, getContext())){
try {
userDoc = getContext().getWiki().getDocument(accountDocRef, getContext());
} catch (XWikiException e) {
LOGGER.error("Exception getting document '" + account + "'", e);
}
userObj = userDoc.getXObject(getUserClassRef(accountDocRef.getWikiReference(
).getName()));
}
if((userDoc != null) && (userObj != null)){
String sendResult = null;
try {
sendResult = setForcePwdAndSendMail(account, userObj, userDoc);
} catch (XWikiException e) {
LOGGER.error("Exception setting ForcePwd or sending mail for user '" + account
+ "'", e);
}
if(sendResult != null) {
resultMsgKey = sendResult;
}
}
}
LOGGER.debug("recover result msg: '" + resultMsgKey + "' param: '" + params.get(0) +
"'");
return getContext().getMessageTool().get(resultMsgKey, params);
}
private String completeAccountFN(String account) {
if(!account.contains(".")) {
account = "XWiki." + account;
}
return account;
}
private String setForcePwdAndSendMail(String account, BaseObject userObj,
XWikiDocument userDoc) throws XWikiException {
String result = null;
if(userObj.getIntValue("active") == 0) {
sendNewValidation(account);
result = "cel_password_recovery_success";
} else {
String email = userObj.getStringValue("email");
LOGGER.debug("email: '" + email + "'");
if((email != null) && (email.trim().length() > 0)) {
String validkey = setUserFieldsForPasswordRecovery(userDoc, userObj);
VelocityContext vcontext = (VelocityContext) getContext().get("vcontext");
vcontext.put("email", email);
vcontext.put("validkey", validkey);
int sendRecoveryMail = sendRecoveryMail(email, getWebUtilsService(
).getAdminLanguage(userDoc.getDocumentReference()), getWebUtilsService(
).getDefaultAdminLanguage());
LOGGER.debug("sendRecoveryMail: '" + sendRecoveryMail + "'");
if(sendRecoveryMail == 0) { // successfully sent == 0
result = "cel_password_recovery_success";
}
}
}
return result;
}
private String setUserFieldsForPasswordRecovery(XWikiDocument userDoc,
BaseObject userObj) throws XWikiException {
userObj.set("force_pwd_change", 1, getContext());
String validkey = new NewCelementsTokenForUserCommand().getUniqueValidationKey(
getContext());
userObj.set("validkey", validkey, getContext());
getContext().getWiki().saveDocument(userDoc,
"Password Recovery - set validkey and force_pwd_change", true, getContext());
return validkey;
}
private int sendRecoveryMail(String email, String lang, String defLang
) throws XWikiException {
String sender = new CelMailConfiguration().getDefaultAdminSenderAddress();
String subject = getPasswordRecoverySubject(lang, defLang);
String textContent = getPasswordRecoveryMailContent("PasswordRecoverMailTextContent",
lang, defLang);
String htmlContent = getPasswordRecoveryMailContent("PasswordRecoverMailHtmlContent",
lang, defLang);
if((htmlContent != null) || (textContent != null)) {
return sendMail(sender, null, email, null, null, subject, htmlContent, textContent,
null, null);
}
return -1;
}
private String getPasswordRecoveryMailContent(String template, String lang,
String defLang) throws XWikiException {
String mailContent = null;
String newContent = "";
XWikiDocument doc = getRTEDocWithCelementswebFallback(new DocumentReference(
getContext().getDatabase(), "Tools", template));
if (doc != null) {
newContent = getContext().getWiki().getRenderingEngine().renderText(
doc.getTranslatedContent(getContext()), getContext().getDoc(), getContext());
}
if ("".equals(newContent)) {
newContent = getWebUtilsService().renderInheritableDocument(new DocumentReference(
getContext().getDatabase(), "Mails", template), lang, defLang);
}
if (!"".equals(newContent)) {
mailContent = newContent;
}
return mailContent;
}
private String getPasswordRecoverySubject(String lang, String defLang
) throws XWikiException {
String subject = "";
XWikiDocument doc = getRTEDocWithCelementswebFallback(new DocumentReference(
getContext().getDatabase(), "Tools", "PasswordRecoverMailTextContent"));
if(doc == null) {
doc = getRTEDocWithCelementswebFallback(new DocumentReference(
getContext().getDatabase(), "Tools", "PasswordRecoverMailHtmlContent"));
}
if ((doc != null) && (doc.getTitle() != null) && !"".equals(doc.getTitle().trim())) {
subject = doc.getTitle();
}
subject = getContext().getWiki().getRenderingEngine().renderText(subject,
getContext().getDoc(), getContext());
if (getDefaultEmptyDocStrategy().isEmptyRTEString(subject)) {
List<String> params = Arrays.asList(getContext().getRequest().getHeader("host"));
subject = getWebUtilsService().getMessageTool(lang).get(
CEL_PASSWORD_RECOVERY_SUBJECT_KEY, params);
if (CEL_PASSWORD_RECOVERY_SUBJECT_KEY.equals(subject) && (defLang != null)) {
subject = getWebUtilsService().getMessageTool(defLang).get(
CEL_PASSWORD_RECOVERY_SUBJECT_KEY, params);
}
}
return subject;
}
private XWikiDocument getRTEDocWithCelementswebFallback(
DocumentReference templateDocRef) throws XWikiException {
XWikiDocument doc = null;
DocumentReference templateCentralDocRef = new DocumentReference("celements2web",
templateDocRef.getLastSpaceReference().getName(), templateDocRef.getName());
if(!getDefaultEmptyDocStrategy().isEmptyDocumentTranslated(templateDocRef)) {
doc = getContext().getWiki().getDocument(templateDocRef, getContext());
} else if(!getDefaultEmptyDocStrategy().isEmptyDocumentTranslated(
templateCentralDocRef)) {
doc = getContext().getWiki().getDocument(templateCentralDocRef, getContext());
}
return doc;
}
public boolean sendNewValidation(String login, String possibleFields
) throws XWikiException {
String user = new UserNameForUserDataCommand().getUsernameForUserData(login,
possibleFields, getContext());
return sendNewValidation(user);
}
public void sendNewValidation(String login, String possibleFields,
DocumentReference activationMailDocRef) throws XWikiException {
String user = new UserNameForUserDataCommand().getUsernameForUserData(login,
possibleFields, getContext());
sendNewValidation(user, activationMailDocRef);
}
public boolean sendNewValidation(String accountName) throws XWikiException {
return sendNewValidation(accountName, (DocumentReference)null);
}
public boolean sendNewValidation(String accountName, DocumentReference activationMailDocRef
) throws XWikiException {
accountName = completeAccountFN(accountName);
DocumentReference accountDocRef = getWebUtilsService().resolveDocumentReference(
accountName);
String validkey = getNewValidationTokenForUser(accountDocRef);
XWikiDocument doc = getContext().getWiki().getDocument(accountDocRef, getContext());
BaseObject obj = doc.getXObject(getUserClassRef(accountDocRef.getWikiReference(
).getName()));
String oldLanguage = getContext().getLanguage();
String newAdminLanguage = obj.getStringValue("admin_language");
VelocityContext vcontext = (VelocityContext) getContext().get("vcontext");
Object oldAdminLanguage = vcontext.get("admin_language");
if ((newAdminLanguage != null) && !"".equals(newAdminLanguage)) {
getContext().setLanguage(newAdminLanguage);
vcontext.put("admin_language", newAdminLanguage);
vcontext.put("adminMsg", getWebUtilsService().getAdminMessageTool());
}
if (activationMailDocRef == null) {
activationMailDocRef = getDefaultAccountActivationMailDocRef();
} else if (!getContext().getWiki().exists(activationMailDocRef, getContext())) {
LOGGER.warn("Failed to get activation mail [" + activationMailDocRef
+ "] now using default.");
activationMailDocRef = getDefaultAccountActivationMailDocRef();
}
boolean sentSuccessful = false;
try {
sentSuccessful = sendValidationMessage(obj.getStringValue("email"), validkey,
activationMailDocRef, newAdminLanguage, getWebUtilsService(
).getDefaultAdminLanguage());
} finally {
getContext().setLanguage(oldLanguage);
vcontext.put("admin_language", oldAdminLanguage);
vcontext.put("adminMsg", getWebUtilsService().getAdminMessageTool());
}
return sentSuccessful;
}
private DocumentReference getDefaultAccountActivationMailDocRef() {
return new DocumentReference(getContext().getDatabase(), "Tools",
"AccountActivationMail");
}
/**
*
* @param accountName
* @param context
* @return
* @throws XWikiException
*
* @Deprecated since 2.14.0 instead use getNewValidationTokenForUser(DocumentReference)
*/
@Deprecated
public String getNewValidationTokenForUser(String accountName,
XWikiContext context) throws XWikiException {
return getNewValidationTokenForUser(getWebUtilsService().resolveDocumentReference(
accountName));
}
public String getNewValidationTokenForUser(DocumentReference accountDocRef
) throws XWikiException {
String validkey = null;
if (getContext().getWiki().exists(accountDocRef, getContext())) {
validkey = new NewCelementsTokenForUserCommand().getUniqueValidationKey(
getContext());
XWikiDocument doc1 = getContext().getWiki().getDocument(accountDocRef,
getContext());
BaseObject obj1 = doc1.getXObject(getUserClassRef(accountDocRef.getWikiReference(
).getName()));
obj1.set("validkey", validkey, getContext());
getContext().getWiki().saveDocument(doc1, getContext());
}
return validkey;
}
private DocumentReference getUserClassRef(String dbName) {
return new DocumentReference(dbName, "XWiki", "XWikiUsers");
}
/**
*
* @param to
* @param validkey
* @param contentDocName
* @param context
* @throws XWikiException
*
* @Deprecated since 2.14.0 instead use sendValidationMessage(String, String,
* DocumentReference)
*/
@Deprecated
public void sendValidationMessage(String to, String validkey, String contentDocName,
XWikiContext context) throws XWikiException {
DocumentReference contentDocRef = getWebUtilsService().resolveDocumentReference(
contentDocName);
sendValidationMessage(to, validkey, contentDocRef);
}
/**
*
* @param to
* @param validkey
* @param contentDocRef
* @throws XWikiException
*
* @Deprecated since 2.34.0 instead use sendValidationMessage(String, String,
* DocumentReference, String)
*/
@Deprecated
public void sendValidationMessage(String to, String validkey,
DocumentReference contentDocRef) throws XWikiException {
sendValidationMessage(to, validkey, contentDocRef,
getWebUtilsService().getDefaultAdminLanguage());
}
public void sendValidationMessage(String to, String validkey,
DocumentReference contentDocRef, String lang) throws XWikiException {
sendValidationMessage(to, validkey, contentDocRef, lang, null);
}
public boolean sendValidationMessage(String to, String validkey,
DocumentReference contentDocRef, String lang, String defLang
) throws XWikiException {
String sender = "";
String subject = "";
String content = "";
XWikiDocument contentDoc = null;
DocumentReference contentCentralDocRef = new DocumentReference("celements2web",
contentDocRef.getLastSpaceReference().getName(), contentDocRef.getName());
if (getContext().getWiki().exists(contentDocRef, getContext())) {
contentDoc = getContext().getWiki().getDocument(contentDocRef, getContext());
} else if (getContext().getWiki().exists(contentCentralDocRef, getContext())) {
contentDoc = getContext().getWiki().getDocument(contentCentralDocRef, getContext());
}
sender = getFromEmailAdr(sender, contentDoc);
setValidationInfoInContext(to, validkey);
content = getValidationEmailContent(contentDoc, lang, defLang);
subject = getValidationEmailSubject(contentDoc, lang, defLang);
return sendMail(sender, null, to, null, null, subject, content, "", null, null) == 0;
}
public String getValidationEmailSubject(XWikiDocument contentDoc, String lang,
String defLang) throws XWikiException {
String subject = "";
if (contentDoc != null) {
//For syntaxes other than xwiki/1.0: set output syntax for renderedTitle
subject = contentDoc.getTranslatedDocument(lang, getContext()).getTitle();
subject = getContext().getWiki().getRenderingEngine().interpretText(subject,
contentDoc, getContext());
}
if (getDefaultEmptyDocStrategy().isEmptyRTEString(subject)) {
List<String> params = Arrays.asList(getContext().getRequest().getHeader("host"));
subject = getWebUtilsService().getMessageTool(lang).get(
CEL_ACOUNT_ACTIVATION_MAIL_SUBJECT_KEY, params);
if (CEL_ACOUNT_ACTIVATION_MAIL_SUBJECT_KEY.equals(subject) && (defLang != null)) {
subject = getWebUtilsService().getMessageTool(defLang).get(
CEL_ACOUNT_ACTIVATION_MAIL_SUBJECT_KEY, params);
}
}
return subject;
}
public String getValidationEmailContent(XWikiDocument contentDoc, String lang,
String defLang) throws XWikiException {
String content = "";
if (contentDoc != null) {
content = contentDoc.getTranslatedDocument(lang, getContext()).getRenderedContent(
getContext());
}
if (getDefaultEmptyDocStrategy().isEmptyRTEString(content)) {
content = getWebUtilsService().renderInheritableDocument(getDefaultMailDocRef(),
lang, defLang);
}
return content;
}
DocumentReference getDefaultMailDocRef() {
return new DocumentReference(getContext().getDatabase(), "Mails",
"AccountActivationMail");
}
public String getFromEmailAdr(String sender, XWikiDocument contentDoc) {
if (contentDoc != null) {
DocumentReference mailSenderClassRef = new DocumentReference(getContext(
).getDatabase(), "Celements2", "FormMailClass");
BaseObject senderObj = contentDoc.getXObject(mailSenderClassRef);
if(senderObj != null) {
sender = senderObj.getStringValue("emailFrom");
}
}
if("".equals(sender.trim())) {
sender = new CelMailConfiguration().getDefaultAdminSenderAddress();
}
return sender;
}
void setValidationInfoInContext(String to, String validkey) throws XWikiException {
VelocityContext vcontext = (VelocityContext) getContext().get("vcontext");
vcontext.put("email", to);
vcontext.put("validkey", validkey);
vcontext.put("activationLink", getActivationLink(to, validkey));
}
String getActivationLink(String to, String validkey) throws XWikiException {
try {
if (getContext().getWiki().getRightService().hasAccessLevel("view",
"XWiki.XWikiGuest", "Content.login", getContext())) {
return getContext().getWiki().getExternalURL(
"Content.login", "view", "email=" + URLEncoder.encode(to, "UTF-8") + "&ac="
+ validkey, getContext());
} else {
return getContext().getWiki().getExternalURL(
"XWiki.XWikiLogin", "login", "email=" + URLEncoder.encode(to, "UTF-8")
+ "&ac=" + validkey, getContext());
}
} catch (UnsupportedEncodingException exp) {
LOGGER.error("Failed to encode [" + to + "] for activation link.", exp);
}
return null;
}
int sendMail(
String from, String replyTo,
String to, String cc, String bcc,
String subject, String htmlContent, String textContent,
List<Attachment> attachments, Map<String, String> others){
CelSendMail sender = getCelSendMail();
sender.setFrom(from);
sender.setReplyTo(replyTo);
sender.setTo(to);
sender.setCc(cc);
sender.setBcc(bcc);
sender.setSubject(subject);
sender.setHtmlContent(htmlContent, false);
sender.setTextContent(textContent);
sender.setAttachments(attachments);
sender.setOthers(others);
return sender.sendMail();
}
void injectCelSendMail(CelSendMail celSendMail) {
this.injectedCelSendMail = celSendMail;
}
CelSendMail getCelSendMail() {
if(injectedCelSendMail != null) {
return injectedCelSendMail;
}
return new CelSendMail();
}
private XWikiContext getContext() {
return (XWikiContext)Utils.getComponent(Execution.class).getContext().getProperty(
"xwikicontext");
}
IWebUtilsService getWebUtilsService() {
if (injected_webUtilsService != null) {
return injected_webUtilsService;
}
return Utils.getComponent(IWebUtilsService.class);
}
private IDefaultEmptyDocStrategyRole getDefaultEmptyDocStrategy() {
return Utils.getComponent(IDefaultEmptyDocStrategyRole.class);
}
}
|
src/main/java/com/celements/web/plugin/cmd/PasswordRecoveryAndEmailValidationCommand.java
|
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package com.celements.web.plugin.cmd;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.velocity.VelocityContext;
import org.xwiki.context.Execution;
import org.xwiki.model.reference.DocumentReference;
import com.celements.emptycheck.internal.IDefaultEmptyDocStrategyRole;
import com.celements.web.service.IWebUtilsService;
import com.celements.web.token.NewCelementsTokenForUserCommand;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.api.Attachment;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.web.Utils;
public class PasswordRecoveryAndEmailValidationCommand {
private static final String CEL_PASSWORD_RECOVERY_SUBJECT_KEY = "cel_password_recovery_default_subject";
private static Log LOGGER = LogFactory.getFactory().getInstance(
PasswordRecoveryAndEmailValidationCommand.class);
static final String CEL_ACOUNT_ACTIVATION_MAIL_SUBJECT_KEY =
"cel_register_acount_activation_mail_subject";
private CelSendMail injectedCelSendMail;
IWebUtilsService injected_webUtilsService;
public String recoverPassword() {
String email = getContext().getRequest().get("j_username");
if((email != null) && !"".equals(email.trim())) {
try {
String account = new UserNameForUserDataCommand().getUsernameForUserData(email,
"email", getContext());
return recoverPassword(account, email);
} catch (XWikiException e) {
LOGGER.error("Exception getting userdoc for email '" + email + "'", e);
}
}
List<String> params = new ArrayList<String>();
params.add(email);
return getContext().getMessageTool().get("cel_password_recovery_failed", params);
}
// Allow recovery exclusively for email input
public String recoverPassword(String account, String input) {
List<String> params = new ArrayList<String>();
params.add(input);
String resultMsgKey = "cel_password_recovery_failed";
if((account != null) && (!"".equals(account.trim()))) {
account = completeAccountFN(account);
DocumentReference accountDocRef = getWebUtilsService().resolveDocumentReference(
account);
XWikiDocument userDoc = null;
BaseObject userObj = null;
if(getContext().getWiki().exists(accountDocRef, getContext())){
try {
userDoc = getContext().getWiki().getDocument(accountDocRef, getContext());
} catch (XWikiException e) {
LOGGER.error("Exception getting document '" + account + "'", e);
}
userObj = userDoc.getXObject(getUserClassRef(accountDocRef.getWikiReference(
).getName()));
}
if((userDoc != null) && (userObj != null)){
String sendResult = null;
try {
sendResult = setForcePwdAndSendMail(account, userObj, userDoc);
} catch (XWikiException e) {
LOGGER.error("Exception setting ForcePwd or sending mail for user '" + account
+ "'", e);
}
if(sendResult != null) {
resultMsgKey = sendResult;
}
}
}
LOGGER.debug("recover result msg: '" + resultMsgKey + "' param: '" + params.get(0) +
"'");
return getContext().getMessageTool().get(resultMsgKey, params);
}
private String completeAccountFN(String account) {
if(!account.contains(".")) {
account = "XWiki." + account;
}
return account;
}
private String setForcePwdAndSendMail(String account, BaseObject userObj,
XWikiDocument userDoc) throws XWikiException {
String result = null;
if(userObj.getIntValue("active") == 0) {
sendNewValidation(account);
result = "cel_password_recovery_success";
} else {
String email = userObj.getStringValue("email");
LOGGER.debug("email: '" + email + "'");
if((email != null) && (email.trim().length() > 0)) {
String validkey = setUserFieldsForPasswordRecovery(userDoc, userObj);
VelocityContext vcontext = (VelocityContext) getContext().get("vcontext");
vcontext.put("email", email);
vcontext.put("validkey", validkey);
int sendRecoveryMail = sendRecoveryMail(email, getWebUtilsService(
).getAdminLanguage(userDoc.getDocumentReference()), getWebUtilsService(
).getDefaultAdminLanguage());
LOGGER.debug("sendRecoveryMail: '" + sendRecoveryMail + "'");
if(sendRecoveryMail == 0) { // successfully sent == 0
result = "cel_password_recovery_success";
}
}
}
return result;
}
private String setUserFieldsForPasswordRecovery(XWikiDocument userDoc,
BaseObject userObj) throws XWikiException {
userObj.set("force_pwd_change", 1, getContext());
String validkey = new NewCelementsTokenForUserCommand().getUniqueValidationKey(
getContext());
userObj.set("validkey", validkey, getContext());
getContext().getWiki().saveDocument(userDoc,
"Password Recovery - set validkey and force_pwd_change", true, getContext());
return validkey;
}
private int sendRecoveryMail(String email, String lang, String defLang
) throws XWikiException {
String sender = getContext().getWiki().getXWikiPreference("admin_email",
getContext());
String subject = getPasswordRecoverySubject(lang, defLang);
String textContent = getPasswordRecoveryMailContent("PasswordRecoverMailTextContent",
lang, defLang);
String htmlContent = getPasswordRecoveryMailContent("PasswordRecoverMailHtmlContent",
lang, defLang);
if((htmlContent != null) || (textContent != null)) {
return sendMail(sender, null, email, null, null, subject, htmlContent, textContent,
null, null);
}
return -1;
}
private String getPasswordRecoveryMailContent(String template, String lang,
String defLang) throws XWikiException {
String mailContent = null;
String newContent = "";
XWikiDocument doc = getRTEDocWithCelementswebFallback(new DocumentReference(
getContext().getDatabase(), "Tools", template));
if (doc != null) {
newContent = getContext().getWiki().getRenderingEngine().renderText(
doc.getTranslatedContent(getContext()), getContext().getDoc(), getContext());
}
if ("".equals(newContent)) {
newContent = getWebUtilsService().renderInheritableDocument(new DocumentReference(
getContext().getDatabase(), "Mails", template), lang, defLang);
}
if (!"".equals(newContent)) {
mailContent = newContent;
}
return mailContent;
}
private String getPasswordRecoverySubject(String lang, String defLang
) throws XWikiException {
String subject = "";
XWikiDocument doc = getRTEDocWithCelementswebFallback(new DocumentReference(
getContext().getDatabase(), "Tools", "PasswordRecoverMailTextContent"));
if(doc == null) {
doc = getRTEDocWithCelementswebFallback(new DocumentReference(
getContext().getDatabase(), "Tools", "PasswordRecoverMailHtmlContent"));
}
if ((doc != null) && (doc.getTitle() != null) && !"".equals(doc.getTitle().trim())) {
subject = doc.getTitle();
}
subject = getContext().getWiki().getRenderingEngine().renderText(subject,
getContext().getDoc(), getContext());
if (getDefaultEmptyDocStrategy().isEmptyRTEString(subject)) {
List<String> params = Arrays.asList(getContext().getRequest().getHeader("host"));
subject = getWebUtilsService().getMessageTool(lang).get(
CEL_PASSWORD_RECOVERY_SUBJECT_KEY, params);
if (CEL_PASSWORD_RECOVERY_SUBJECT_KEY.equals(subject) && (defLang != null)) {
subject = getWebUtilsService().getMessageTool(defLang).get(
CEL_PASSWORD_RECOVERY_SUBJECT_KEY, params);
}
}
return subject;
}
private XWikiDocument getRTEDocWithCelementswebFallback(
DocumentReference templateDocRef) throws XWikiException {
XWikiDocument doc = null;
DocumentReference templateCentralDocRef = new DocumentReference("celements2web",
templateDocRef.getLastSpaceReference().getName(), templateDocRef.getName());
if(!getDefaultEmptyDocStrategy().isEmptyDocumentTranslated(templateDocRef)) {
doc = getContext().getWiki().getDocument(templateDocRef, getContext());
} else if(!getDefaultEmptyDocStrategy().isEmptyDocumentTranslated(
templateCentralDocRef)) {
doc = getContext().getWiki().getDocument(templateCentralDocRef, getContext());
}
return doc;
}
public boolean sendNewValidation(String login, String possibleFields
) throws XWikiException {
String user = new UserNameForUserDataCommand().getUsernameForUserData(login,
possibleFields, getContext());
return sendNewValidation(user);
}
public void sendNewValidation(String login, String possibleFields,
DocumentReference activationMailDocRef) throws XWikiException {
String user = new UserNameForUserDataCommand().getUsernameForUserData(login,
possibleFields, getContext());
sendNewValidation(user, activationMailDocRef);
}
public boolean sendNewValidation(String accountName) throws XWikiException {
return sendNewValidation(accountName, (DocumentReference)null);
}
public boolean sendNewValidation(String accountName, DocumentReference activationMailDocRef
) throws XWikiException {
accountName = completeAccountFN(accountName);
DocumentReference accountDocRef = getWebUtilsService().resolveDocumentReference(
accountName);
String validkey = getNewValidationTokenForUser(accountDocRef);
XWikiDocument doc = getContext().getWiki().getDocument(accountDocRef, getContext());
BaseObject obj = doc.getXObject(getUserClassRef(accountDocRef.getWikiReference(
).getName()));
String oldLanguage = getContext().getLanguage();
String newAdminLanguage = obj.getStringValue("admin_language");
VelocityContext vcontext = (VelocityContext) getContext().get("vcontext");
Object oldAdminLanguage = vcontext.get("admin_language");
if ((newAdminLanguage != null) && !"".equals(newAdminLanguage)) {
getContext().setLanguage(newAdminLanguage);
vcontext.put("admin_language", newAdminLanguage);
vcontext.put("adminMsg", getWebUtilsService().getAdminMessageTool());
}
if (activationMailDocRef == null) {
activationMailDocRef = getDefaultAccountActivationMailDocRef();
} else if (!getContext().getWiki().exists(activationMailDocRef, getContext())) {
LOGGER.warn("Failed to get activation mail [" + activationMailDocRef
+ "] now using default.");
activationMailDocRef = getDefaultAccountActivationMailDocRef();
}
boolean sentSuccessful = false;
try {
sentSuccessful = sendValidationMessage(obj.getStringValue("email"), validkey,
activationMailDocRef, newAdminLanguage, getWebUtilsService(
).getDefaultAdminLanguage());
} finally {
getContext().setLanguage(oldLanguage);
vcontext.put("admin_language", oldAdminLanguage);
vcontext.put("adminMsg", getWebUtilsService().getAdminMessageTool());
}
return sentSuccessful;
}
private DocumentReference getDefaultAccountActivationMailDocRef() {
return new DocumentReference(getContext().getDatabase(), "Tools",
"AccountActivationMail");
}
/**
*
* @param accountName
* @param context
* @return
* @throws XWikiException
*
* @Deprecated since 2.14.0 instead use getNewValidationTokenForUser(DocumentReference)
*/
@Deprecated
public String getNewValidationTokenForUser(String accountName,
XWikiContext context) throws XWikiException {
return getNewValidationTokenForUser(getWebUtilsService().resolveDocumentReference(
accountName));
}
public String getNewValidationTokenForUser(DocumentReference accountDocRef
) throws XWikiException {
String validkey = null;
if (getContext().getWiki().exists(accountDocRef, getContext())) {
validkey = new NewCelementsTokenForUserCommand().getUniqueValidationKey(
getContext());
XWikiDocument doc1 = getContext().getWiki().getDocument(accountDocRef,
getContext());
BaseObject obj1 = doc1.getXObject(getUserClassRef(accountDocRef.getWikiReference(
).getName()));
obj1.set("validkey", validkey, getContext());
getContext().getWiki().saveDocument(doc1, getContext());
}
return validkey;
}
private DocumentReference getUserClassRef(String dbName) {
return new DocumentReference(dbName, "XWiki", "XWikiUsers");
}
/**
*
* @param to
* @param validkey
* @param contentDocName
* @param context
* @throws XWikiException
*
* @Deprecated since 2.14.0 instead use sendValidationMessage(String, String,
* DocumentReference)
*/
@Deprecated
public void sendValidationMessage(String to, String validkey, String contentDocName,
XWikiContext context) throws XWikiException {
DocumentReference contentDocRef = getWebUtilsService().resolveDocumentReference(
contentDocName);
sendValidationMessage(to, validkey, contentDocRef);
}
/**
*
* @param to
* @param validkey
* @param contentDocRef
* @throws XWikiException
*
* @Deprecated since 2.34.0 instead use sendValidationMessage(String, String,
* DocumentReference, String)
*/
@Deprecated
public void sendValidationMessage(String to, String validkey,
DocumentReference contentDocRef) throws XWikiException {
sendValidationMessage(to, validkey, contentDocRef,
getWebUtilsService().getDefaultAdminLanguage());
}
public void sendValidationMessage(String to, String validkey,
DocumentReference contentDocRef, String lang) throws XWikiException {
sendValidationMessage(to, validkey, contentDocRef, lang, null);
}
public boolean sendValidationMessage(String to, String validkey,
DocumentReference contentDocRef, String lang, String defLang
) throws XWikiException {
String sender = "";
String subject = "";
String content = "";
XWikiDocument contentDoc = null;
DocumentReference contentCentralDocRef = new DocumentReference("celements2web",
contentDocRef.getLastSpaceReference().getName(), contentDocRef.getName());
if (getContext().getWiki().exists(contentDocRef, getContext())) {
contentDoc = getContext().getWiki().getDocument(contentDocRef, getContext());
} else if (getContext().getWiki().exists(contentCentralDocRef, getContext())) {
contentDoc = getContext().getWiki().getDocument(contentCentralDocRef, getContext());
}
sender = getFromEmailAdr(sender, contentDoc);
setValidationInfoInContext(to, validkey);
content = getValidationEmailContent(contentDoc, lang, defLang);
subject = getValidationEmailSubject(contentDoc, lang, defLang);
return sendMail(sender, null, to, null, null, subject, content, "", null, null) == 0;
}
public String getValidationEmailSubject(XWikiDocument contentDoc, String lang,
String defLang) throws XWikiException {
String subject = "";
if (contentDoc != null) {
//For syntaxes other than xwiki/1.0: set output syntax for renderedTitle
subject = contentDoc.getTranslatedDocument(lang, getContext()).getTitle();
subject = getContext().getWiki().getRenderingEngine().interpretText(subject,
contentDoc, getContext());
}
if (getDefaultEmptyDocStrategy().isEmptyRTEString(subject)) {
List<String> params = Arrays.asList(getContext().getRequest().getHeader("host"));
subject = getWebUtilsService().getMessageTool(lang).get(
CEL_ACOUNT_ACTIVATION_MAIL_SUBJECT_KEY, params);
if (CEL_ACOUNT_ACTIVATION_MAIL_SUBJECT_KEY.equals(subject) && (defLang != null)) {
subject = getWebUtilsService().getMessageTool(defLang).get(
CEL_ACOUNT_ACTIVATION_MAIL_SUBJECT_KEY, params);
}
}
return subject;
}
public String getValidationEmailContent(XWikiDocument contentDoc, String lang,
String defLang) throws XWikiException {
String content = "";
if (contentDoc != null) {
content = contentDoc.getTranslatedDocument(lang, getContext()).getRenderedContent(
getContext());
}
if (getDefaultEmptyDocStrategy().isEmptyRTEString(content)) {
content = getWebUtilsService().renderInheritableDocument(getDefaultMailDocRef(),
lang, defLang);
}
return content;
}
DocumentReference getDefaultMailDocRef() {
return new DocumentReference(getContext().getDatabase(), "Mails",
"AccountActivationMail");
}
public String getFromEmailAdr(String sender, XWikiDocument contentDoc) {
if (contentDoc != null) {
DocumentReference mailSenderClassRef = new DocumentReference(getContext(
).getDatabase(), "Celements2", "FormMailClass");
BaseObject senderObj = contentDoc.getXObject(mailSenderClassRef);
if(senderObj != null) {
sender = senderObj.getStringValue("emailFrom");
}
}
if("".equals(sender.trim())) {
sender = new CelMailConfiguration().getDefaultAdminSenderAddress();
}
return sender;
}
void setValidationInfoInContext(String to, String validkey) throws XWikiException {
VelocityContext vcontext = (VelocityContext) getContext().get("vcontext");
vcontext.put("email", to);
vcontext.put("validkey", validkey);
vcontext.put("activationLink", getActivationLink(to, validkey));
}
String getActivationLink(String to, String validkey) throws XWikiException {
try {
if (getContext().getWiki().getRightService().hasAccessLevel("view",
"XWiki.XWikiGuest", "Content.login", getContext())) {
return getContext().getWiki().getExternalURL(
"Content.login", "view", "email=" + URLEncoder.encode(to, "UTF-8") + "&ac="
+ validkey, getContext());
} else {
return getContext().getWiki().getExternalURL(
"XWiki.XWikiLogin", "login", "email=" + URLEncoder.encode(to, "UTF-8")
+ "&ac=" + validkey, getContext());
}
} catch (UnsupportedEncodingException exp) {
LOGGER.error("Failed to encode [" + to + "] for activation link.", exp);
}
return null;
}
int sendMail(
String from, String replyTo,
String to, String cc, String bcc,
String subject, String htmlContent, String textContent,
List<Attachment> attachments, Map<String, String> others){
CelSendMail sender = getCelSendMail();
sender.setFrom(from);
sender.setReplyTo(replyTo);
sender.setTo(to);
sender.setCc(cc);
sender.setBcc(bcc);
sender.setSubject(subject);
sender.setHtmlContent(htmlContent, false);
sender.setTextContent(textContent);
sender.setAttachments(attachments);
sender.setOthers(others);
return sender.sendMail();
}
void injectCelSendMail(CelSendMail celSendMail) {
this.injectedCelSendMail = celSendMail;
}
CelSendMail getCelSendMail() {
if(injectedCelSendMail != null) {
return injectedCelSendMail;
}
return new CelSendMail();
}
private XWikiContext getContext() {
return (XWikiContext)Utils.getComponent(Execution.class).getContext().getProperty(
"xwikicontext");
}
IWebUtilsService getWebUtilsService() {
if (injected_webUtilsService != null) {
return injected_webUtilsService;
}
return Utils.getComponent(IWebUtilsService.class);
}
private IDefaultEmptyDocStrategyRole getDefaultEmptyDocStrategy() {
return Utils.getComponent(IDefaultEmptyDocStrategyRole.class);
}
}
|
fix sender for RecoveryMail
|
src/main/java/com/celements/web/plugin/cmd/PasswordRecoveryAndEmailValidationCommand.java
|
fix sender for RecoveryMail
|
<ide><path>rc/main/java/com/celements/web/plugin/cmd/PasswordRecoveryAndEmailValidationCommand.java
<ide>
<ide> private int sendRecoveryMail(String email, String lang, String defLang
<ide> ) throws XWikiException {
<del> String sender = getContext().getWiki().getXWikiPreference("admin_email",
<del> getContext());
<add> String sender = new CelMailConfiguration().getDefaultAdminSenderAddress();
<ide> String subject = getPasswordRecoverySubject(lang, defLang);
<ide> String textContent = getPasswordRecoveryMailContent("PasswordRecoverMailTextContent",
<ide> lang, defLang);
|
|
Java
|
mit
|
7c3fe3aacbe889a4a9838bfc8977a766cbb248d3
| 0 |
Thatsmusic99/HeadsPlus
|
package io.github.thatsmusic99.headsplus.util;
import com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException;
import io.github.thatsmusic99.headsplus.HeadsPlus;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
public class NewMySQLAPI {
private static final Connection connection = HeadsPlus.getInstance().getConnection();
public static void createTable() {
for (String str : Arrays.asList("headspluslb", "headsplussh", "headspluscraft")) {
try {
StringBuilder arg = new StringBuilder();
arg.append(str).append("(`id` INT NOT NULL AUTO_INCREMENT, `uuid` VARCHAR(256), `total` VARCHAR(256), ");
for (String entity : EntityDataManager.ableEntities) {
arg.append(entity).append(" VARCHAR(256), ");
}
arg.append("PLAYER VARCHAR(256), PRIMARY KEY (`id`))");
update(OperationType.CREATE, arg.toString());
if (!query(OperationType.SELECT_COUNT, str, "uuid", "server-total").next()) {
update(OperationType.INSERT_INTO, str, "uuid", "server-total");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
static void addToTotal(String database, int addition, String section, String uuid) {
try {
if (!doesPlayerExist(database, uuid)) addPlayer(database, uuid);
ResultSet set = query(OperationType.SELECT, section, database, "uuid", uuid);
set.next();
int total = set.getInt("total");
int totalSec = set.getInt(section);
update(OperationType.UPDATE, database, section, String.valueOf(totalSec + addition), String.valueOf(total + addition), "uuid", uuid);
} catch (MySQLSyntaxErrorException e) {
try {
update(OperationType.ALTER, database, section);
} catch (SQLException ex) {
ex.printStackTrace();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
static LinkedHashMap<OfflinePlayer, Integer> getScores(String section, String database) {
try {
String mdatabase = "";
switch (database) {
case "hunting":
mdatabase = "headspluslb";
break;
case "selling":
mdatabase = "headsplussh";
break;
case "crafting":
mdatabase = "headspluscraft";
break;
}
LinkedHashMap<OfflinePlayer, Integer> hs = new LinkedHashMap<>();
ResultSet rs = query(OperationType.SELECT_ORDER, "uuid", section, mdatabase);
while (rs.next()) {
try {
UUID uuid = UUID.fromString(rs.getString("uuid"));
OfflinePlayer player = Bukkit.getOfflinePlayer(uuid);
hs.put(player, rs.getInt(section));
} catch (Exception ignored) {
}
}
hs = DataManager.sortHashMapByValues(hs);
LeaderboardsCache.init(database + "_" + section, hs);
return hs;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
private static boolean doesPlayerExist(String database, String uuid) {
try {
return query(OperationType.SELECT_COUNT, database, "uuid", uuid).next();
} catch (SQLException e) {
return false;
}
}
private static void addPlayer(String database, String uuid) {
try {
update(OperationType.INSERT_INTO, database, "uuid", uuid);
} catch (SQLException e) {
e.printStackTrace();
}
}
private static void update(OperationType type, String... args) throws SQLException {
prepareStatement(type, args).executeUpdate();
}
private static ResultSet query(OperationType type, String... args) throws SQLException {
return prepareStatement(type, args).executeQuery();
}
private static PreparedStatement prepareStatement(OperationType type, String... args) throws SQLException {
return connection.prepareStatement(String.format(type.syntax, args));
}
private enum OperationType {
SELECT("SELECT %1$s, total FROM %2$s WHERE %3$s='%4$s'"),
INSERT_TABLE("INSERT TABLE %1$s ADD COLUMN `%2$s` VARCHAR(45)"),
INSERT_INTO("INSERT INTO %1$s (`%2$s`) VALUES ('%3$s')"),
UPDATE("UPDATE %1$s SET %2$s='%3$s', total=%4$s WHERE %5$s='%6$s'"),
CREATE("CREATE TABLE IF NOT EXISTS %1$s"),
ALTER("ALTER TABLE %1$s ADD COLUMN %2$s VARCHAR(45)"),
SELECT_ORDER("SELECT %1$s, %2$s FROM %3$s ORDER BY `id`"),
SELECT_COUNT("SELECT 1 FROM %1$s WHERE `%2$s`='%3$s'");
String syntax;
OperationType(String syntax) {
this.syntax = syntax;
}
}
}
|
src/main/java/io/github/thatsmusic99/headsplus/util/NewMySQLAPI.java
|
package io.github.thatsmusic99.headsplus.util;
import com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException;
import io.github.thatsmusic99.headsplus.HeadsPlus;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
public class NewMySQLAPI {
private static final Connection connection = HeadsPlus.getInstance().getConnection();
public static void createTable() {
for (String str : Arrays.asList("headspluslb", "headsplussh", "headspluscraft")) {
try {
StringBuilder arg = new StringBuilder();
arg.append(str).append("(`id` INT NOT NULL AUTO_INCREMENT, `uuid` VARCHAR(45), `total` VARCHAR(45), ");
arg.append(entity).append(" VARCHAR(45), ");
for (String entity : EntityDataManager.ableEntities) {
}
arg.append("PLAYER VARCHAR(45), PRIMARY KEY (`id`))");
update(OperationType.CREATE, arg.toString());
if (!query(OperationType.SELECT_COUNT, str, "uuid", "server-total").next()) {
update(OperationType.INSERT_INTO, str, "uuid", "server-total");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
static void addToTotal(String database, int addition, String section, String uuid) {
try {
if (!doesPlayerExist(database, uuid)) addPlayer(database, uuid);
ResultSet set = query(OperationType.SELECT, section, database, "uuid", uuid);
set.next();
int total = set.getInt("total");
int totalSec = set.getInt(section);
update(OperationType.UPDATE, database, section, String.valueOf(totalSec + addition), String.valueOf(total + addition), "uuid", uuid);
} catch (MySQLSyntaxErrorException e) {
try {
update(OperationType.ALTER, database, section);
} catch (SQLException ex) {
ex.printStackTrace();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
static LinkedHashMap<OfflinePlayer, Integer> getScores(String section, String database) {
try {
String mdatabase = "";
switch (database) {
case "hunting":
mdatabase = "headspluslb";
break;
case "selling":
mdatabase = "headsplussh";
break;
case "crafting":
mdatabase = "headspluscraft";
break;
}
LinkedHashMap<OfflinePlayer, Integer> hs = new LinkedHashMap<>();
ResultSet rs = query(OperationType.SELECT_ORDER, "uuid", section, mdatabase);
while (rs.next()) {
try {
UUID uuid = UUID.fromString(rs.getString("uuid"));
OfflinePlayer player = Bukkit.getOfflinePlayer(uuid);
hs.put(player, rs.getInt(section));
} catch (Exception ignored) {
}
}
hs = DataManager.sortHashMapByValues(hs);
LeaderboardsCache.init(database + "_" + section, hs);
return hs;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
private static boolean doesPlayerExist(String database, String uuid) {
try {
return query(OperationType.SELECT_COUNT, database, "uuid", uuid).next();
} catch (SQLException e) {
return false;
}
}
private static void addPlayer(String database, String uuid) {
try {
update(OperationType.INSERT_INTO, database, "uuid", uuid);
} catch (SQLException e) {
e.printStackTrace();
}
}
private static void update(OperationType type, String... args) throws SQLException {
prepareStatement(type, args).executeUpdate();
}
private static ResultSet query(OperationType type, String... args) throws SQLException {
return prepareStatement(type, args).executeQuery();
}
private static PreparedStatement prepareStatement(OperationType type, String... args) throws SQLException {
return connection.prepareStatement(String.format(type.syntax, args));
}
private enum OperationType {
SELECT("SELECT %1$s, total FROM %2$s WHERE %3$s='%4$s'"),
INSERT_TABLE("INSERT TABLE %1$s ADD COLUMN `%2$s` VARCHAR(45)"),
INSERT_INTO("INSERT INTO %1$s (`%2$s`) VALUES ('%3$s')"),
UPDATE("UPDATE %1$s SET %2$s='%3$s', total=%4$s WHERE %5$s='%6$s'"),
CREATE("CREATE TABLE IF NOT EXISTS %1$s"),
ALTER("ALTER TABLE %1$s ADD COLUMN %2$s VARCHAR(45)"),
SELECT_ORDER("SELECT %1$s, %2$s FROM %3$s ORDER BY `id`"),
SELECT_COUNT("SELECT 1 FROM %1$s WHERE `%2$s`='%3$s'");
String syntax;
OperationType(String syntax) {
this.syntax = syntax;
}
}
}
|
Should fix problems with #27 (already closed but alas)
|
src/main/java/io/github/thatsmusic99/headsplus/util/NewMySQLAPI.java
|
Should fix problems with #27 (already closed but alas)
|
<ide><path>rc/main/java/io/github/thatsmusic99/headsplus/util/NewMySQLAPI.java
<ide> for (String str : Arrays.asList("headspluslb", "headsplussh", "headspluscraft")) {
<ide> try {
<ide> StringBuilder arg = new StringBuilder();
<del> arg.append(str).append("(`id` INT NOT NULL AUTO_INCREMENT, `uuid` VARCHAR(45), `total` VARCHAR(45), ");
<del> arg.append(entity).append(" VARCHAR(45), ");
<add> arg.append(str).append("(`id` INT NOT NULL AUTO_INCREMENT, `uuid` VARCHAR(256), `total` VARCHAR(256), ");
<ide> for (String entity : EntityDataManager.ableEntities) {
<add> arg.append(entity).append(" VARCHAR(256), ");
<ide>
<ide> }
<del> arg.append("PLAYER VARCHAR(45), PRIMARY KEY (`id`))");
<add> arg.append("PLAYER VARCHAR(256), PRIMARY KEY (`id`))");
<ide> update(OperationType.CREATE, arg.toString());
<ide> if (!query(OperationType.SELECT_COUNT, str, "uuid", "server-total").next()) {
<ide> update(OperationType.INSERT_INTO, str, "uuid", "server-total");
|
|
Java
|
apache-2.0
|
b853f275ce91963431026df0b78f12be52581189
| 0 |
isharac/carbon-apimgt,wso2/carbon-apimgt,isharac/carbon-apimgt,prasa7/carbon-apimgt,chamilaadhi/carbon-apimgt,ruks/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,tharindu1st/carbon-apimgt,wso2/carbon-apimgt,ruks/carbon-apimgt,isharac/carbon-apimgt,praminda/carbon-apimgt,wso2/carbon-apimgt,prasa7/carbon-apimgt,tharindu1st/carbon-apimgt,malinthaprasan/carbon-apimgt,tharindu1st/carbon-apimgt,ruks/carbon-apimgt,praminda/carbon-apimgt,chamilaadhi/carbon-apimgt,ruks/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,chamilaadhi/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,malinthaprasan/carbon-apimgt,wso2/carbon-apimgt,prasa7/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,prasa7/carbon-apimgt,malinthaprasan/carbon-apimgt,chamilaadhi/carbon-apimgt,isharac/carbon-apimgt,praminda/carbon-apimgt,tharindu1st/carbon-apimgt,malinthaprasan/carbon-apimgt
|
package org.wso2.carbon.apimgt.impl.definitions;
import io.apicurio.datamodels.Library;
import io.apicurio.datamodels.asyncapi.models.AaiChannelItem;
import io.apicurio.datamodels.asyncapi.models.AaiDocument;
import io.apicurio.datamodels.asyncapi.models.AaiOperation;
import io.apicurio.datamodels.asyncapi.v2.models.Aai20ChannelItem;
import io.apicurio.datamodels.asyncapi.v2.models.Aai20Document;
import io.apicurio.datamodels.asyncapi.v2.models.Aai20ImplicitOAuthFlow;
import io.apicurio.datamodels.asyncapi.v2.models.Aai20OAuthFlows;
import io.apicurio.datamodels.asyncapi.v2.models.Aai20Operation;
import io.apicurio.datamodels.asyncapi.v2.models.Aai20SecurityScheme;
import io.apicurio.datamodels.asyncapi.v2.models.Aai20Server;
import io.apicurio.datamodels.core.models.Extension;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.everit.json.schema.Schema;
import org.everit.json.schema.ValidationException;
import org.everit.json.schema.loader.SchemaLoader;
import org.json.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.wso2.carbon.apimgt.api.APIDefinition;
import org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.model.API;
import org.wso2.carbon.apimgt.api.model.APIProduct;
import org.wso2.carbon.apimgt.api.model.Scope;
import org.wso2.carbon.apimgt.api.model.SwaggerData;
import org.wso2.carbon.apimgt.api.model.URITemplate;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.utils.APIUtil;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
public class AsyncApiParser extends APIDefinition {
String metaSchema = "{\n" + " \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n"
+ " \"$id\": \"http://json-schema.org/draft-07/schema#\",\n"
+ " \"title\": \"Core schema meta-schema\",\n" + " \"definitions\": {\n"
+ " \"schemaArray\": {\n" + " \"type\": \"array\",\n" + " \"minItems\": 1,\n"
+ " \"items\": { \"$ref\": \"#\" }\n" + " },\n" + " \"nonNegativeInteger\": {\n"
+ " \"type\": \"integer\",\n" + " \"minimum\": 0\n" + " },\n"
+ " \"nonNegativeIntegerDefault0\": {\n" + " \"allOf\": [\n"
+ " { \"$ref\": \"#/definitions/nonNegativeInteger\" },\n"
+ " { \"default\": 0 }\n" + " ]\n" + " },\n"
+ " \"simpleTypes\": {\n" + " \"enum\": [\n" + " \"array\",\n"
+ " \"boolean\",\n" + " \"integer\",\n" + " \"null\",\n"
+ " \"number\",\n" + " \"object\",\n" + " \"string\"\n"
+ " ]\n" + " },\n" + " \"stringArray\": {\n" + " \"type\": \"array\",\n"
+ " \"items\": { \"type\": \"string\" },\n" + " \"uniqueItems\": true,\n"
+ " \"default\": []\n" + " }\n" + " },\n"
+ " \"type\": [\"object\", \"boolean\"],\n" + " \"properties\": {\n" + " \"$id\": {\n"
+ " \"type\": \"string\",\n" + " \"format\": \"uri-reference\"\n" + " },\n"
+ " \"$schema\": {\n" + " \"type\": \"string\",\n" + " \"format\": \"uri\"\n"
+ " },\n" + " \"$ref\": {\n" + " \"type\": \"string\",\n"
+ " \"format\": \"uri-reference\"\n" + " },\n" + " \"$comment\": {\n"
+ " \"type\": \"string\"\n" + " },\n" + " \"title\": {\n"
+ " \"type\": \"string\"\n" + " },\n" + " \"description\": {\n"
+ " \"type\": \"string\"\n" + " },\n" + " \"default\": true,\n"
+ " \"readOnly\": {\n" + " \"type\": \"boolean\",\n" + " \"default\": false\n"
+ " },\n" + " \"writeOnly\": {\n" + " \"type\": \"boolean\",\n"
+ " \"default\": false\n" + " },\n" + " \"examples\": {\n"
+ " \"type\": \"array\",\n" + " \"items\": true\n" + " },\n"
+ " \"multipleOf\": {\n" + " \"type\": \"number\",\n"
+ " \"exclusiveMinimum\": 0\n" + " },\n" + " \"maximum\": {\n"
+ " \"type\": \"number\"\n" + " },\n" + " \"exclusiveMaximum\": {\n"
+ " \"type\": \"number\"\n" + " },\n" + " \"minimum\": {\n"
+ " \"type\": \"number\"\n" + " },\n" + " \"exclusiveMinimum\": {\n"
+ " \"type\": \"number\"\n" + " },\n"
+ " \"maxLength\": { \"$ref\": \"#/definitions/nonNegativeInteger\" },\n"
+ " \"minLength\": { \"$ref\": \"#/definitions/nonNegativeIntegerDefault0\" },\n"
+ " \"pattern\": {\n" + " \"type\": \"string\",\n" + " \"format\": \"regex\"\n"
+ " },\n" + " \"additionalItems\": { \"$ref\": \"#\" },\n" + " \"items\": {\n"
+ " \"anyOf\": [\n" + " { \"$ref\": \"#\" },\n"
+ " { \"$ref\": \"#/definitions/schemaArray\" }\n" + " ],\n"
+ " \"default\": true\n" + " },\n"
+ " \"maxItems\": { \"$ref\": \"#/definitions/nonNegativeInteger\" },\n"
+ " \"minItems\": { \"$ref\": \"#/definitions/nonNegativeIntegerDefault0\" },\n"
+ " \"uniqueItems\": {\n" + " \"type\": \"boolean\",\n"
+ " \"default\": false\n" + " },\n" + " \"contains\": { \"$ref\": \"#\" },\n"
+ " \"maxProperties\": { \"$ref\": \"#/definitions/nonNegativeInteger\" },\n"
+ " \"minProperties\": { \"$ref\": \"#/definitions/nonNegativeIntegerDefault0\" },\n"
+ " \"required\": { \"$ref\": \"#/definitions/stringArray\" },\n"
+ " \"additionalProperties\": { \"$ref\": \"#\" },\n" + " \"definitions\": {\n"
+ " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\": \"#\" },\n"
+ " \"default\": {}\n" + " },\n" + " \"properties\": {\n"
+ " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\": \"#\" },\n"
+ " \"default\": {}\n" + " },\n" + " \"patternProperties\": {\n"
+ " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\": \"#\" },\n"
+ " \"propertyNames\": { \"format\": \"regex\" },\n" + " \"default\": {}\n"
+ " },\n" + " \"dependencies\": {\n" + " \"type\": \"object\",\n"
+ " \"additionalProperties\": {\n" + " \"anyOf\": [\n"
+ " { \"$ref\": \"#\" },\n"
+ " { \"$ref\": \"#/definitions/stringArray\" }\n" + " ]\n"
+ " }\n" + " },\n" + " \"propertyNames\": { \"$ref\": \"#\" },\n"
+ " \"const\": true,\n" + " \"enum\": {\n" + " \"type\": \"array\",\n"
+ " \"items\": true,\n" + " \"minItems\": 1,\n"
+ " \"uniqueItems\": true\n" + " },\n" + " \"type\": {\n"
+ " \"anyOf\": [\n" + " { \"$ref\": \"#/definitions/simpleTypes\" },\n"
+ " {\n" + " \"type\": \"array\",\n"
+ " \"items\": { \"$ref\": \"#/definitions/simpleTypes\" },\n"
+ " \"minItems\": 1,\n" + " \"uniqueItems\": true\n"
+ " }\n" + " ]\n" + " },\n"
+ " \"format\": { \"type\": \"string\" },\n"
+ " \"contentMediaType\": { \"type\": \"string\" },\n"
+ " \"contentEncoding\": { \"type\": \"string\" },\n" + " \"if\": { \"$ref\": \"#\" },\n"
+ " \"then\": { \"$ref\": \"#\" },\n" + " \"else\": { \"$ref\": \"#\" },\n"
+ " \"allOf\": { \"$ref\": \"#/definitions/schemaArray\" },\n"
+ " \"anyOf\": { \"$ref\": \"#/definitions/schemaArray\" },\n"
+ " \"oneOf\": { \"$ref\": \"#/definitions/schemaArray\" },\n"
+ " \"not\": { \"$ref\": \"#\" }\n" + " },\n" + " \"default\": true\n" + "}";
private static final String ASYNCAPI_JSON_HYPERSCHEMA = "{\n" +
" \"title\": \"AsyncAPI 2.0.0 schema.\",\n" +
" \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n" +
" \"type\": \"object\",\n" +
" \"required\": [\n" +
" \"asyncapi\",\n" +
" \"info\",\n" +
" \"channels\"\n" +
" ],\n" +
" \"additionalProperties\": false,\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"properties\": {\n" +
" \"asyncapi\": {\n" +
" \"type\": \"string\",\n" +
" \"enum\": [\n" +
" \"2.0.0\"\n" +
" ],\n" +
" \"description\": \"The AsyncAPI specification version of this document.\"\n" +
" },\n" +
" \"id\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"A unique id representing the application.\",\n" +
" \"format\": \"uri\"\n" +
" },\n" +
" \"info\": {\n" +
" \"$ref\": \"#/definitions/info\"\n" +
" },\n" +
" \"servers\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": {\n" +
" \"$ref\": \"#/definitions/server\"\n" +
" }\n" +
" },\n" +
" \"defaultContentType\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"channels\": {\n" +
" \"$ref\": \"#/definitions/channels\"\n" +
" },\n" +
" \"components\": {\n" +
" \"$ref\": \"#/definitions/components\"\n" +
" },\n" +
" \"tags\": {\n" +
" \"type\": \"array\",\n" +
" \"items\": {\n" +
" \"$ref\": \"#/definitions/tag\"\n" +
" },\n" +
" \"uniqueItems\": true\n" +
" },\n" +
" \"externalDocs\": {\n" +
" \"$ref\": \"#/definitions/externalDocs\"\n" +
" }\n" +
" },\n" +
" \"definitions\": {\n" +
" \"Reference\": {\n" +
" \"type\": \"object\",\n" +
" \"required\": [\n" +
" \"$ref\"\n" +
" ],\n" +
" \"properties\": {\n" +
" \"$ref\": {\n" +
" \"$ref\": \"#/definitions/ReferenceObject\"\n" +
" }\n" +
" }\n" +
" },\n" +
" \"ReferenceObject\": {\n" +
" \"type\": \"string\",\n" +
" \"format\": \"uri-reference\"\n" +
" },\n" +
" \"info\": {\n" +
" \"type\": \"object\",\n" +
" \"description\": \"General information about the API.\",\n" +
" \"required\": [\n" +
" \"version\",\n" +
" \"title\"\n" +
" ],\n" +
" \"additionalProperties\": false,\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"properties\": {\n" +
" \"title\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"A unique and precise title of the API.\"\n" +
" },\n" +
" \"version\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"A semantic version number of the API.\"\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"A longer description of the API. Should be different from the title. CommonMark is allowed.\"\n" +
" },\n" +
" \"termsOfService\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"A URL to the Terms of Service for the API. MUST be in the format of a URL.\",\n" +
" \"format\": \"uri\"\n" +
" },\n" +
" \"contact\": {\n" +
" \"$ref\": \"#/definitions/contact\"\n" +
" },\n" +
" \"license\": {\n" +
" \"$ref\": \"#/definitions/license\"\n" +
" }\n" +
" }\n" +
" },\n" +
" \"contact\": {\n" +
" \"type\": \"object\",\n" +
" \"description\": \"Contact information for the owners of the API.\",\n" +
" \"additionalProperties\": false,\n" +
" \"properties\": {\n" +
" \"name\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"The identifying name of the contact person/organization.\"\n" +
" },\n" +
" \"url\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"The URL pointing to the contact information.\",\n" +
" \"format\": \"uri\"\n" +
" },\n" +
" \"email\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"The email address of the contact person/organization.\",\n" +
" \"format\": \"email\"\n" +
" }\n" +
" },\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" }\n" +
" },\n" +
" \"license\": {\n" +
" \"type\": \"object\",\n" +
" \"required\": [\n" +
" \"name\"\n" +
" ],\n" +
" \"additionalProperties\": false,\n" +
" \"properties\": {\n" +
" \"name\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"The name of the license type. It's encouraged to use an OSI compatible license.\"\n" +
" },\n" +
" \"url\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"The URL pointing to the license.\",\n" +
" \"format\": \"uri\"\n" +
" }\n" +
" },\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" }\n" +
" },\n" +
" \"server\": {\n" +
" \"type\": \"object\",\n" +
" \"description\": \"An object representing a Server.\",\n" +
" \"required\": [\n" +
" \"url\",\n" +
" \"protocol\"\n" +
" ],\n" +
" \"additionalProperties\": false,\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"properties\": {\n" +
" \"url\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"protocol\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"The transfer protocol.\"\n" +
" },\n" +
" \"protocolVersion\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"variables\": {\n" +
" \"$ref\": \"#/definitions/serverVariables\"\n" +
" },\n" +
" \"security\": {\n" +
" \"type\": \"array\",\n" +
" \"items\": {\n" +
" \"$ref\": \"#/definitions/SecurityRequirement\"\n" +
" }\n" +
" },\n" +
" \"bindings\": {\n" +
" \"$ref\": \"#/definitions/bindingsObject\"\n" +
" }\n" +
" }\n" +
" },\n" +
" \"serverVariables\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": {\n" +
" \"$ref\": \"#/definitions/serverVariable\"\n" +
" }\n" +
" },\n" +
" \"serverVariable\": {\n" +
" \"type\": \"object\",\n" +
" \"description\": \"An object representing a Server Variable for server URL template substitution.\",\n" +
" \"additionalProperties\": false,\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"properties\": {\n" +
" \"enum\": {\n" +
" \"type\": \"array\",\n" +
" \"items\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"uniqueItems\": true\n" +
" },\n" +
" \"default\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"examples\": {\n" +
" \"type\": \"array\",\n" +
" \"items\": {\n" +
" \"type\": \"string\"\n" +
" }\n" +
" }\n" +
" }\n" +
" },\n" +
" \"channels\": {\n" +
" \"type\": \"object\",\n" +
" \"propertyNames\": {\n" +
" \"type\": \"string\",\n" +
" \"format\": \"uri-template\",\n" +
" \"minLength\": 1\n" +
" },\n" +
" \"additionalProperties\": {\n" +
" \"$ref\": \"#/definitions/channelItem\"\n" +
" }\n" +
" },\n" +
" \"components\": {\n" +
" \"type\": \"object\",\n" +
" \"description\": \"An object to hold a set of reusable objects for different aspects of the AsyncAPI Specification.\",\n" +
" \"additionalProperties\": false,\n" +
" \"properties\": {\n" +
" \"schemas\": {\n" +
" \"$ref\": \"#/definitions/schemas\"\n" +
" },\n" +
" \"messages\": {\n" +
" \"$ref\": \"#/definitions/messages\"\n" +
" },\n" +
" \"securitySchemes\": {\n" +
" \"type\": \"object\",\n" +
" \"patternProperties\": {\n" +
" \"^[\\\\w\\\\d\\\\.\\\\-_]+$\": {\n" +
" \"oneOf\": [\n" +
" {\n" +
" \"$ref\": \"#/definitions/Reference\"\n" +
" },\n" +
" {\n" +
" \"$ref\": \"#/definitions/SecurityScheme\"\n" +
" }\n" +
" ]\n" +
" }\n" +
" }\n" +
" },\n" +
" \"parameters\": {\n" +
" \"$ref\": \"#/definitions/parameters\"\n" +
" },\n" +
" \"correlationIds\": {\n" +
" \"type\": \"object\",\n" +
" \"patternProperties\": {\n" +
" \"^[\\\\w\\\\d\\\\.\\\\-_]+$\": {\n" +
" \"oneOf\": [\n" +
" {\n" +
" \"$ref\": \"#/definitions/Reference\"\n" +
" },\n" +
" {\n" +
" \"$ref\": \"#/definitions/correlationId\"\n" +
" }\n" +
" ]\n" +
" }\n" +
" }\n" +
" },\n" +
" \"operationTraits\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": {\n" +
" \"$ref\": \"#/definitions/operationTrait\"\n" +
" }\n" +
" },\n" +
" \"messageTraits\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": {\n" +
" \"$ref\": \"#/definitions/messageTrait\"\n" +
" }\n" +
" },\n" +
" \"serverBindings\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": {\n" +
" \"$ref\": \"#/definitions/bindingsObject\"\n" +
" }\n" +
" },\n" +
" \"channelBindings\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": {\n" +
" \"$ref\": \"#/definitions/bindingsObject\"\n" +
" }\n" +
" },\n" +
" \"operationBindings\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": {\n" +
" \"$ref\": \"#/definitions/bindingsObject\"\n" +
" }\n" +
" },\n" +
" \"messageBindings\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": {\n" +
" \"$ref\": \"#/definitions/bindingsObject\"\n" +
" }\n" +
" }\n" +
" }\n" +
" },\n" +
" \"schemas\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": {\n" +
" \"$ref\": \"#/definitions/schema\"\n" +
" },\n" +
" \"description\": \"JSON objects describing schemas the API uses.\"\n" +
" },\n" +
" \"messages\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": {\n" +
" \"$ref\": \"#/definitions/message\"\n" +
" },\n" +
" \"description\": \"JSON objects describing the messages being consumed and produced by the API.\"\n" +
" },\n" +
" \"parameters\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": {\n" +
" \"$ref\": \"#/definitions/parameter\"\n" +
" },\n" +
" \"description\": \"JSON objects describing re-usable channel parameters.\"\n" +
" },\n" +
" \"schema\": {\n" +
" \"allOf\": [\n" +
" {\n" +
" \"$ref\": \"http://json-schema.org/draft-07/schema#\"\n" +
" },\n" +
" {\n" +
" \"type\": \"object\",\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"properties\": {\n" +
" \"additionalProperties\": {\n" +
" \"anyOf\": [\n" +
" {\n" +
" \"$ref\": \"#/definitions/schema\"\n" +
" },\n" +
" {\n" +
" \"type\": \"boolean\"\n" +
" }\n" +
" ],\n" +
" \"default\": {}\n" +
" },\n" +
" \"items\": {\n" +
" \"anyOf\": [\n" +
" {\n" +
" \"$ref\": \"#/definitions/schema\"\n" +
" },\n" +
" {\n" +
" \"type\": \"array\",\n" +
" \"minItems\": 1,\n" +
" \"items\": {\n" +
" \"$ref\": \"#/definitions/schema\"\n" +
" }\n" +
" }\n" +
" ],\n" +
" \"default\": {}\n" +
" },\n" +
" \"allOf\": {\n" +
" \"type\": \"array\",\n" +
" \"minItems\": 1,\n" +
" \"items\": {\n" +
" \"$ref\": \"#/definitions/schema\"\n" +
" }\n" +
" },\n" +
" \"oneOf\": {\n" +
" \"type\": \"array\",\n" +
" \"minItems\": 2,\n" +
" \"items\": {\n" +
" \"$ref\": \"#/definitions/schema\"\n" +
" }\n" +
" },\n" +
" \"anyOf\": {\n" +
" \"type\": \"array\",\n" +
" \"minItems\": 2,\n" +
" \"items\": {\n" +
" \"$ref\": \"#/definitions/schema\"\n" +
" }\n" +
" },\n" +
" \"not\": {\n" +
" \"$ref\": \"#/definitions/schema\"\n" +
" },\n" +
" \"properties\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": {\n" +
" \"$ref\": \"#/definitions/schema\"\n" +
" },\n" +
" \"default\": {}\n" +
" },\n" +
" \"patternProperties\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": {\n" +
" \"$ref\": \"#/definitions/schema\"\n" +
" },\n" +
" \"default\": {}\n" +
" },\n" +
" \"propertyNames\": {\n" +
" \"$ref\": \"#/definitions/schema\"\n" +
" },\n" +
" \"contains\": {\n" +
" \"$ref\": \"#/definitions/schema\"\n" +
" },\n" +
" \"discriminator\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"externalDocs\": {\n" +
" \"$ref\": \"#/definitions/externalDocs\"\n" +
" },\n" +
" \"deprecated\": {\n" +
" \"type\": \"boolean\",\n" +
" \"default\": false\n" +
" }\n" +
" }\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"externalDocs\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": false,\n" +
" \"description\": \"information about external documentation\",\n" +
" \"required\": [\n" +
" \"url\"\n" +
" ],\n" +
" \"properties\": {\n" +
" \"description\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"url\": {\n" +
" \"type\": \"string\",\n" +
" \"format\": \"uri\"\n" +
" }\n" +
" },\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" }\n" +
" },\n" +
" \"channelItem\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": false,\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"properties\": {\n" +
" \"$ref\": {\n" +
" \"$ref\": \"#/definitions/ReferenceObject\"\n" +
" },\n" +
" \"parameters\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": {\n" +
" \"$ref\": \"#/definitions/parameter\"\n" +
" }\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"A description of the channel.\"\n" +
" },\n" +
" \"publish\": {\n" +
" \"$ref\": \"#/definitions/operation\"\n" +
" },\n" +
" \"subscribe\": {\n" +
" \"$ref\": \"#/definitions/operation\"\n" +
" },\n" +
" \"deprecated\": {\n" +
" \"type\": \"boolean\",\n" +
" \"default\": false\n" +
" },\n" +
" \"bindings\": {\n" +
" \"$ref\": \"#/definitions/bindingsObject\"\n" +
" }\n" +
" }\n" +
" },\n" +
" \"parameter\": {\n" +
" \"additionalProperties\": false,\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"properties\": {\n" +
" \"description\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed.\"\n" +
" },\n" +
" \"schema\": {\n" +
" \"$ref\": \"#/definitions/schema\"\n" +
" },\n" +
" \"location\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"A runtime expression that specifies the location of the parameter value\",\n" +
" \"pattern\": \"^\\\\$message\\\\.(header|payload)\\\\#(\\\\/(([^\\\\/~])|(~[01]))*)*\"\n" +
" },\n" +
" \"$ref\": {\n" +
" \"$ref\": \"#/definitions/ReferenceObject\"\n" +
" }\n" +
" }\n" +
" },\n" +
" \"operation\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": false,\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"properties\": {\n" +
" \"traits\": {\n" +
" \"type\": \"array\",\n" +
" \"items\": {\n" +
" \"oneOf\": [\n" +
" {\n" +
" \"$ref\": \"#/definitions/Reference\"\n" +
" },\n" +
" {\n" +
" \"$ref\": \"#/definitions/operationTrait\"\n" +
" },\n" +
" {\n" +
" \"type\": \"array\",\n" +
" \"items\": [\n" +
" {\n" +
" \"oneOf\": [\n" +
" {\n" +
" \"$ref\": \"#/definitions/Reference\"\n" +
" },\n" +
" {\n" +
" \"$ref\": \"#/definitions/operationTrait\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"type\": \"object\",\n" +
" \"additionalItems\": true\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
" }\n" +
" },\n" +
" \"summary\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"tags\": {\n" +
" \"type\": \"array\",\n" +
" \"items\": {\n" +
" \"$ref\": \"#/definitions/tag\"\n" +
" },\n" +
" \"uniqueItems\": true\n" +
" },\n" +
" \"externalDocs\": {\n" +
" \"$ref\": \"#/definitions/externalDocs\"\n" +
" },\n" +
" \"operationId\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"bindings\": {\n" +
" \"$ref\": \"#/definitions/bindingsObject\"\n" +
" },\n" +
" \"message\": {\n" +
" \"$ref\": \"#/definitions/message\"\n" +
" }\n" +
" }\n" +
" },\n" +
" \"message\": {\n" +
" \"oneOf\": [\n" +
" {\n" +
" \"$ref\": \"#/definitions/Reference\"\n" +
" },\n" +
" {\n" +
" \"oneOf\": [\n" +
" {\n" +
" \"type\": \"object\",\n" +
" \"required\": [\n" +
" \"oneOf\"\n" +
" ],\n" +
" \"additionalProperties\": false,\n" +
" \"properties\": {\n" +
" \"oneOf\": {\n" +
" \"type\": \"array\",\n" +
" \"items\": {\n" +
" \"$ref\": \"#/definitions/message\"\n" +
" }\n" +
" }\n" +
" }\n" +
" },\n" +
" {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": false,\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"properties\": {\n" +
" \"schemaFormat\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"contentType\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"headers\": {\n" +
" \"allOf\": [\n" +
" { \"$ref\": \"#/definitions/schema\" },\n" +
" { \"properties\": {\n" +
" \"type\": { \"const\": \"object\" }\n" +
" }\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"payload\": {},\n" +
" \"correlationId\": {\n" +
" \"oneOf\": [\n" +
" {\n" +
" \"$ref\": \"#/definitions/Reference\"\n" +
" },\n" +
" {\n" +
" \"$ref\": \"#/definitions/correlationId\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"tags\": {\n" +
" \"type\": \"array\",\n" +
" \"items\": {\n" +
" \"$ref\": \"#/definitions/tag\"\n" +
" },\n" +
" \"uniqueItems\": true\n" +
" },\n" +
" \"summary\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"A brief summary of the message.\"\n" +
" },\n" +
" \"name\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"Name of the message.\"\n" +
" },\n" +
" \"title\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"A human-friendly title for the message.\"\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"A longer description of the message. CommonMark is allowed.\"\n" +
" },\n" +
" \"externalDocs\": {\n" +
" \"$ref\": \"#/definitions/externalDocs\"\n" +
" },\n" +
" \"deprecated\": {\n" +
" \"type\": \"boolean\",\n" +
" \"default\": false\n" +
" },\n" +
" \"examples\": {\n" +
" \"type\": \"array\",\n" +
" \"items\": {\n" +
" \"type\": \"object\"\n" +
" }\n" +
" },\n" +
" \"bindings\": {\n" +
" \"$ref\": \"#/definitions/bindingsObject\"\n" +
" },\n" +
" \"traits\": {\n" +
" \"type\": \"array\",\n" +
" \"items\": {\n" +
" \"oneOf\": [\n" +
" {\n" +
" \"$ref\": \"#/definitions/Reference\"\n" +
" },\n" +
" {\n" +
" \"$ref\": \"#/definitions/messageTrait\"\n" +
" },\n" +
" {\n" +
" \"type\": \"array\",\n" +
" \"items\": [\n" +
" {\n" +
" \"oneOf\": [\n" +
" {\n" +
" \"$ref\": \"#/definitions/Reference\"\n" +
" },\n" +
" {\n" +
" \"$ref\": \"#/definitions/messageTrait\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"type\": \"object\",\n" +
" \"additionalItems\": true\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"bindingsObject\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": true,\n" +
" \"properties\": {\n" +
" \"http\": {},\n" +
" \"ws\": {},\n" +
" \"amqp\": {},\n" +
" \"amqp1\": {},\n" +
" \"mqtt\": {},\n" +
" \"mqtt5\": {},\n" +
" \"kafka\": {},\n" +
" \"nats\": {},\n" +
" \"jms\": {},\n" +
" \"sns\": {},\n" +
" \"sqs\": {},\n" +
" \"stomp\": {},\n" +
" \"redis\": {},\n" +
" \"mercure\": {}\n" +
" }\n" +
" },\n" +
" \"correlationId\": {\n" +
" \"type\": \"object\",\n" +
" \"required\": [\n" +
" \"location\"\n" +
" ],\n" +
" \"additionalProperties\": false,\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"properties\": {\n" +
" \"description\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"A optional description of the correlation ID. GitHub Flavored Markdown is allowed.\"\n" +
" },\n" +
" \"location\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"A runtime expression that specifies the location of the correlation ID\",\n" +
" \"pattern\": \"^\\\\$message\\\\.(header|payload)\\\\#(\\\\/(([^\\\\/~])|(~[01]))*)*\"\n" +
" }\n" +
" }\n" +
" },\n" +
" \"specificationExtension\": {\n" +
" \"description\": \"Any property starting with x- is valid.\",\n" +
" \"additionalProperties\": true,\n" +
" \"additionalItems\": true\n" +
" },\n" +
" \"tag\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": false,\n" +
" \"required\": [\n" +
" \"name\"\n" +
" ],\n" +
" \"properties\": {\n" +
" \"name\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"externalDocs\": {\n" +
" \"$ref\": \"#/definitions/externalDocs\"\n" +
" }\n" +
" },\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" }\n" +
" },\n" +
" \"operationTrait\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": false,\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"properties\": {\n" +
" \"summary\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"tags\": {\n" +
" \"type\": \"array\",\n" +
" \"items\": {\n" +
" \"$ref\": \"#/definitions/tag\"\n" +
" },\n" +
" \"uniqueItems\": true\n" +
" },\n" +
" \"externalDocs\": {\n" +
" \"$ref\": \"#/definitions/externalDocs\"\n" +
" },\n" +
" \"operationId\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"bindings\": {\n" +
" \"$ref\": \"#/definitions/bindingsObject\"\n" +
" }\n" +
" }\n" +
" },\n" +
" \"messageTrait\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": false,\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"properties\": {\n" +
" \"schemaFormat\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"contentType\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"headers\": {\n" +
" \"oneOf\": [\n" +
" {\n" +
" \"$ref\": \"#/definitions/Reference\"\n" +
" },\n" +
" {\n" +
" \"$ref\": \"#/definitions/schema\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"correlationId\": {\n" +
" \"oneOf\": [\n" +
" {\n" +
" \"$ref\": \"#/definitions/Reference\"\n" +
" },\n" +
" {\n" +
" \"$ref\": \"#/definitions/correlationId\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"tags\": {\n" +
" \"type\": \"array\",\n" +
" \"items\": {\n" +
" \"$ref\": \"#/definitions/tag\"\n" +
" },\n" +
" \"uniqueItems\": true\n" +
" },\n" +
" \"summary\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"A brief summary of the message.\"\n" +
" },\n" +
" \"name\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"Name of the message.\"\n" +
" },\n" +
" \"title\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"A human-friendly title for the message.\"\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"A longer description of the message. CommonMark is allowed.\"\n" +
" },\n" +
" \"externalDocs\": {\n" +
" \"$ref\": \"#/definitions/externalDocs\"\n" +
" },\n" +
" \"deprecated\": {\n" +
" \"type\": \"boolean\",\n" +
" \"default\": false\n" +
" },\n" +
" \"examples\": {\n" +
" \"type\": \"array\",\n" +
" \"items\": {\n" +
" \"type\": \"object\"\n" +
" }\n" +
" },\n" +
" \"bindings\": {\n" +
" \"$ref\": \"#/definitions/bindingsObject\"\n" +
" }\n" +
" }\n" +
" },\n" +
" \"SecurityScheme\": {\n" +
" \"oneOf\": [\n" +
" {\n" +
" \"$ref\": \"#/definitions/userPassword\"\n" +
" },\n" +
" {\n" +
" \"$ref\": \"#/definitions/apiKey\"\n" +
" },\n" +
" {\n" +
" \"$ref\": \"#/definitions/X509\"\n" +
" },\n" +
" {\n" +
" \"$ref\": \"#/definitions/symmetricEncryption\"\n" +
" },\n" +
" {\n" +
" \"$ref\": \"#/definitions/asymmetricEncryption\"\n" +
" },\n" +
" {\n" +
" \"$ref\": \"#/definitions/HTTPSecurityScheme\"\n" +
" },\n" +
" {\n" +
" \"$ref\": \"#/definitions/oauth2Flows\"\n" +
" },\n" +
" {\n" +
" \"$ref\": \"#/definitions/openIdConnect\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"userPassword\": {\n" +
" \"type\": \"object\",\n" +
" \"required\": [\n" +
" \"type\"\n" +
" ],\n" +
" \"properties\": {\n" +
" \"type\": {\n" +
" \"type\": \"string\",\n" +
" \"enum\": [\n" +
" \"userPassword\"\n" +
" ]\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\"\n" +
" }\n" +
" },\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"additionalProperties\": false\n" +
" },\n" +
" \"apiKey\": {\n" +
" \"type\": \"object\",\n" +
" \"required\": [\n" +
" \"type\",\n" +
" \"in\"\n" +
" ],\n" +
" \"properties\": {\n" +
" \"type\": {\n" +
" \"type\": \"string\",\n" +
" \"enum\": [\n" +
" \"apiKey\"\n" +
" ]\n" +
" },\n" +
" \"in\": {\n" +
" \"type\": \"string\",\n" +
" \"enum\": [\n" +
" \"user\",\n" +
" \"password\"\n" +
" ]\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\"\n" +
" }\n" +
" },\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"additionalProperties\": false\n" +
" },\n" +
" \"X509\": {\n" +
" \"type\": \"object\",\n" +
" \"required\": [\n" +
" \"type\"\n" +
" ],\n" +
" \"properties\": {\n" +
" \"type\": {\n" +
" \"type\": \"string\",\n" +
" \"enum\": [\n" +
" \"X509\"\n" +
" ]\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\"\n" +
" }\n" +
" },\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"additionalProperties\": false\n" +
" },\n" +
" \"symmetricEncryption\": {\n" +
" \"type\": \"object\",\n" +
" \"required\": [\n" +
" \"type\"\n" +
" ],\n" +
" \"properties\": {\n" +
" \"type\": {\n" +
" \"type\": \"string\",\n" +
" \"enum\": [\n" +
" \"symmetricEncryption\"\n" +
" ]\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\"\n" +
" }\n" +
" },\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"additionalProperties\": false\n" +
" },\n" +
" \"asymmetricEncryption\": {\n" +
" \"type\": \"object\",\n" +
" \"required\": [\n" +
" \"type\"\n" +
" ],\n" +
" \"properties\": {\n" +
" \"type\": {\n" +
" \"type\": \"string\",\n" +
" \"enum\": [\n" +
" \"asymmetricEncryption\"\n" +
" ]\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\"\n" +
" }\n" +
" },\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"additionalProperties\": false\n" +
" },\n" +
" \"HTTPSecurityScheme\": {\n" +
" \"oneOf\": [\n" +
" {\n" +
" \"$ref\": \"#/definitions/NonBearerHTTPSecurityScheme\"\n" +
" },\n" +
" {\n" +
" \"$ref\": \"#/definitions/BearerHTTPSecurityScheme\"\n" +
" },\n" +
" {\n" +
" \"$ref\": \"#/definitions/APIKeyHTTPSecurityScheme\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"NonBearerHTTPSecurityScheme\": {\n" +
" \"not\": {\n" +
" \"type\": \"object\",\n" +
" \"properties\": {\n" +
" \"scheme\": {\n" +
" \"type\": \"string\",\n" +
" \"enum\": [\n" +
" \"bearer\"\n" +
" ]\n" +
" }\n" +
" }\n" +
" },\n" +
" \"type\": \"object\",\n" +
" \"required\": [\n" +
" \"scheme\",\n" +
" \"type\"\n" +
" ],\n" +
" \"properties\": {\n" +
" \"scheme\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"type\": {\n" +
" \"type\": \"string\",\n" +
" \"enum\": [\n" +
" \"http\"\n" +
" ]\n" +
" }\n" +
" },\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"additionalProperties\": false\n" +
" },\n" +
" \"BearerHTTPSecurityScheme\": {\n" +
" \"type\": \"object\",\n" +
" \"required\": [\n" +
" \"type\",\n" +
" \"scheme\"\n" +
" ],\n" +
" \"properties\": {\n" +
" \"scheme\": {\n" +
" \"type\": \"string\",\n" +
" \"enum\": [\n" +
" \"bearer\"\n" +
" ]\n" +
" },\n" +
" \"bearerFormat\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"type\": {\n" +
" \"type\": \"string\",\n" +
" \"enum\": [\n" +
" \"http\"\n" +
" ]\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\"\n" +
" }\n" +
" },\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"additionalProperties\": false\n" +
" },\n" +
" \"APIKeyHTTPSecurityScheme\": {\n" +
" \"type\": \"object\",\n" +
" \"required\": [\n" +
" \"type\",\n" +
" \"name\",\n" +
" \"in\"\n" +
" ],\n" +
" \"properties\": {\n" +
" \"type\": {\n" +
" \"type\": \"string\",\n" +
" \"enum\": [\n" +
" \"httpApiKey\"\n" +
" ]\n" +
" },\n" +
" \"name\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"in\": {\n" +
" \"type\": \"string\",\n" +
" \"enum\": [\n" +
" \"header\",\n" +
" \"query\",\n" +
" \"cookie\"\n" +
" ]\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\"\n" +
" }\n" +
" },\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"additionalProperties\": false\n" +
" },\n" +
" \"oauth2Flows\": {\n" +
" \"type\": \"object\",\n" +
" \"required\": [\n" +
" \"type\",\n" +
" \"flows\"\n" +
" ],\n" +
" \"properties\": {\n" +
" \"type\": {\n" +
" \"type\": \"string\",\n" +
" \"enum\": [\n" +
" \"oauth2\"\n" +
" ]\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"flows\": {\n" +
" \"type\": \"object\",\n" +
" \"properties\": {\n" +
" \"implicit\": {\n" +
" \"allOf\": [\n" +
" {\n" +
" \"$ref\": \"#/definitions/oauth2Flow\"\n" +
" },\n" +
" {\n" +
" \"required\": [\n" +
" \"authorizationUrl\",\n" +
" \"scopes\"\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"not\": {\n" +
" \"required\": [\n" +
" \"tokenUrl\"\n" +
" ]\n" +
" }\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"password\": {\n" +
" \"allOf\": [\n" +
" {\n" +
" \"$ref\": \"#/definitions/oauth2Flow\"\n" +
" },\n" +
" {\n" +
" \"required\": [\n" +
" \"tokenUrl\",\n" +
" \"scopes\"\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"not\": {\n" +
" \"required\": [\n" +
" \"authorizationUrl\"\n" +
" ]\n" +
" }\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"clientCredentials\": {\n" +
" \"allOf\": [\n" +
" {\n" +
" \"$ref\": \"#/definitions/oauth2Flow\"\n" +
" },\n" +
" {\n" +
" \"required\": [\n" +
" \"tokenUrl\",\n" +
" \"scopes\"\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"not\": {\n" +
" \"required\": [\n" +
" \"authorizationUrl\"\n" +
" ]\n" +
" }\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"authorizationCode\": {\n" +
" \"allOf\": [\n" +
" {\n" +
" \"$ref\": \"#/definitions/oauth2Flow\"\n" +
" },\n" +
" {\n" +
" \"required\": [\n" +
" \"authorizationUrl\",\n" +
" \"tokenUrl\",\n" +
" \"scopes\"\n" +
" ]\n" +
" }\n" +
" ]\n" +
" }\n" +
" },\n" +
" \"additionalProperties\": false\n" +
" }\n" +
" },\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" }\n" +
" },\n" +
" \"oauth2Flow\": {\n" +
" \"type\": \"object\",\n" +
" \"properties\": {\n" +
" \"authorizationUrl\": {\n" +
" \"type\": \"string\",\n" +
" \"format\": \"uri\"\n" +
" },\n" +
" \"tokenUrl\": {\n" +
" \"type\": \"string\",\n" +
" \"format\": \"uri\"\n" +
" },\n" +
" \"refreshUrl\": {\n" +
" \"type\": \"string\",\n" +
" \"format\": \"uri\"\n" +
" },\n" +
" \"scopes\": {\n" +
" \"$ref\": \"#/definitions/oauth2Scopes\"\n" +
" }\n" +
" },\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"additionalProperties\": false\n" +
" },\n" +
" \"oauth2Scopes\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": {\n" +
" \"type\": \"string\"\n" +
" }\n" +
" },\n" +
" \"openIdConnect\": {\n" +
" \"type\": \"object\",\n" +
" \"required\": [\n" +
" \"type\",\n" +
" \"openIdConnectUrl\"\n" +
" ],\n" +
" \"properties\": {\n" +
" \"type\": {\n" +
" \"type\": \"string\",\n" +
" \"enum\": [\n" +
" \"openIdConnect\"\n" +
" ]\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"openIdConnectUrl\": {\n" +
" \"type\": \"string\",\n" +
" \"format\": \"uri\"\n" +
" }\n" +
" },\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"additionalProperties\": false\n" +
" },\n" +
" \"SecurityRequirement\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": {\n" +
" \"type\": \"array\",\n" +
" \"items\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"uniqueItems\": true\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
private static final Log log = LogFactory.getLog(AsyncApiParser.class);
private List<String> otherSchemes;
public List<String> getOtherSchemes() {
return otherSchemes;
}
public void setOtherSchemes(List<String> otherSchemes) {
this.otherSchemes = otherSchemes;
}
@Override
public Map<String, Object> generateExample(String apiDefinition) throws APIManagementException{
return null;
}
@Override
public Set<URITemplate> getURITemplates(String resourceConfigsJSON) throws APIManagementException {
return getURITemplates(resourceConfigsJSON, true);
}
public Set<URITemplate> getURITemplates(String apiDefinition, boolean includePublish)
throws APIManagementException {
Set<URITemplate> uriTemplates = new HashSet<>();
Set<Scope> scopes = getScopes(apiDefinition);
Aai20Document document = (Aai20Document) Library.readDocumentFromJSONString(apiDefinition);
if (document.channels != null && document.channels.size() > 0) {
for (Map.Entry<String, AaiChannelItem> entry : document.channels.entrySet()) {
Aai20ChannelItem channel = (Aai20ChannelItem) entry.getValue();
if (includePublish && channel.publish != null) {
uriTemplates.add(buildURITemplate(entry.getKey(), APIConstants.HTTP_VERB_PUBLISH,
(Aai20Operation) channel.publish, scopes, channel));
}
if (channel.subscribe != null) {
uriTemplates.add(buildURITemplate(entry.getKey(), APIConstants.HTTP_VERB_SUBSCRIBE,
(Aai20Operation) channel.subscribe, scopes, channel));
}
}
}
return uriTemplates;
}
private URITemplate buildURITemplate(String target, String verb, Aai20Operation operation, Set<Scope> scopes,
Aai20ChannelItem channel) throws APIManagementException {
URITemplate template = new URITemplate();
template.setHTTPVerb(verb);
template.setHttpVerbs(verb);
template.setUriTemplate(target);
Extension authTypeExtension = channel.getExtension(APIConstants.SWAGGER_X_AUTH_TYPE);
if (authTypeExtension != null && authTypeExtension.value instanceof String) {
template.setAuthType(authTypeExtension.value.toString());
}
List<String> opScopes = getScopeOfOperations(operation);
if (!opScopes.isEmpty()) {
if (opScopes.size() == 1) {
String firstScope = opScopes.get(0);
Scope scope = APIUtil.findScopeByKey(scopes, firstScope);
if (scope == null) {
throw new APIManagementException("Scope '" + firstScope + "' not found.");
}
template.setScope(scope);
template.setScopes(scope);
} else {
for (String scopeName : opScopes) {
Scope scope = APIUtil.findScopeByKey(scopes, scopeName);
if (scope == null) {
throw new APIManagementException("Resource Scope '" + scopeName + "' not found.");
}
template.setScopes(scope);
}
}
}
return template;
}
private List<String> getScopeOfOperations(Aai20Operation operation) {
return getScopeOfOperationsFromExtensions(operation);
}
private List<String> getScopeOfOperationsFromExtensions(Aai20Operation operation) {
Extension scopeBindings = operation.getExtension("x-scopes");
if (scopeBindings != null) {
if (scopeBindings.value instanceof LinkedHashMap) {
return (List<String>) ((LinkedHashMap) scopeBindings.value)
.values()
.stream()
.collect(Collectors.toList());
}
if (scopeBindings.value instanceof ArrayList) {
return (List<String>) scopeBindings.value;
}
}
return Collections.emptyList();
}
@Override
public Set<Scope> getScopes(String resourceConfigsJSON) throws APIManagementException {
Set<Scope> scopeSet = new LinkedHashSet<>();
Aai20Document document = (Aai20Document) Library.readDocumentFromJSONString(resourceConfigsJSON);
if (document.components != null && document.components.securitySchemes != null) {
Aai20SecurityScheme oauth2 = (Aai20SecurityScheme) document.components.securitySchemes.get("oauth2");
if (oauth2 != null && oauth2.flows != null && oauth2.flows.implicit != null) {
Map<String, String> scopes = oauth2.flows.implicit.scopes;
Extension xScopesBindings = oauth2.flows.implicit.getExtension(APIConstants.SWAGGER_X_SCOPES_BINDINGS);
Map<String, String> scopeBindings = new HashMap<>();
if (xScopesBindings != null) {
scopeBindings = (Map<String, String>) xScopesBindings.value;
}
if (scopes != null) {
for (Map.Entry<String, String> entry : scopes.entrySet()) {
Scope scope = new Scope();
scope.setKey(entry.getKey());
scope.setName(entry.getKey());
scope.setDescription(entry.getValue());
String scopeBinding = scopeBindings.get(scope.getKey());
if (scopeBinding != null) {
scope.setRoles(scopeBinding);
}
scopeSet.add(scope);
}
}
}
}
return scopeSet;
}
@Override
public String generateAPIDefinition(SwaggerData swaggerData) throws APIManagementException {
return null;
}
@Override
public String generateAPIDefinition(SwaggerData swaggerData, String swagger) throws APIManagementException {
return null;
}
@Override
public APIDefinitionValidationResponse validateAPIDefinition(String apiDefinition, String url, boolean returnJsonContent) throws APIManagementException {
return null;
}
@Override
public APIDefinitionValidationResponse validateAPIDefinition(String apiDefinition, boolean returnJsonContent) throws APIManagementException {
APIDefinitionValidationResponse validationResponse = new APIDefinitionValidationResponse();
//import and load AsyncAPI HyperSchema for JSON schema validation
JSONObject hyperSchema = new JSONObject(ASYNCAPI_JSON_HYPERSCHEMA);
String protocol = StringUtils.EMPTY;
boolean validationSuccess = false;
List<String> validationErrorMessages = null;
boolean isWebSocket = false;
JSONObject schemaToBeValidated = new JSONObject(apiDefinition);
//validate AsyncAPI using JSON schema validation
try {
JSONParser parser = new JSONParser();
org.json.simple.JSONObject json = (org.json.simple.JSONObject) parser.parse(metaSchema);
SchemaLoader schemaLoader = SchemaLoader.builder().registerSchemaByURI
(new URI("http://json-schema.org/draft-07/schema#"), json).schemaJson(hyperSchema).build();
Schema schemaValidator = schemaLoader.load().build();
schemaValidator.validate(schemaToBeValidated);
validationSuccess = true;
} catch(ParseException e) {
//validation error messages
// validationErrorMessages = e.getAllMessages();
} catch (URISyntaxException e) {
e.printStackTrace();
}
// TODO: Validation is failing. Need to fix this. Therefore overriding the value as True.
validationSuccess = true;
if (validationSuccess) {
AaiDocument asyncApiDocument = (AaiDocument) Library.readDocumentFromJSONString(apiDefinition);
ArrayList<String> endpoints = new ArrayList<>();
if (asyncApiDocument.getServers().size() == 1) {
protocol = asyncApiDocument.getServers().get(0).protocol;
}
/*for (AaiServer x : asyncApiDocument.getServers()){
endpoints.add(x.url);
}
AsyncApiParserUtil.updateValidationResponseAsSuccess(
validationResponse,
apiDefinition,
asyncApiDocument.asyncapi,
asyncApiDocument.info.title,
asyncApiDocument.info.version,
null, //asyncApiDocument.getChannels().get(0)._name,
asyncApiDocument.info.description,
endpoints
);*/
/*if (isWebSocket) {
for (AaiServer x : asyncApiDocument.getServers()){
endpoints.add(x.url);
}
AsyncApiParserUtil.updateValidationResponseAsSuccess(
validationResponse,
apiDefinition,
asyncApiDocument.asyncapi,
asyncApiDocument.info.title,
asyncApiDocument.info.version,
asyncApiDocument.getChannels().get(0)._name, //make this null
asyncApiDocument.info.description,
endpoints
);
} else {
AsyncApiParserUtil.updateValidationResponseAsSuccess(
validationResponse,
apiDefinition,
asyncApiDocument.asyncapi,
asyncApiDocument.info.title,
asyncApiDocument.info.version,
null,
asyncApiDocument.info.description,
null
);
}*/
AsyncApiParserUtil.updateValidationResponseAsSuccess(
validationResponse,
apiDefinition,
asyncApiDocument.asyncapi,
asyncApiDocument.info.title,
asyncApiDocument.info.version,
null,
asyncApiDocument.info.description,
null
);
validationResponse.setParser(this);
if (returnJsonContent) {
validationResponse.setJsonContent(apiDefinition);
}
if (StringUtils.isNotEmpty(protocol)) {
validationResponse.setProtocol(protocol);
}
} else {
if (validationErrorMessages != null){
validationResponse.setValid(false);
for (String errorMessage: validationErrorMessages){
AsyncApiParserUtil.addErrorToValidationResponse(validationResponse, errorMessage);
}
}
}
return validationResponse;
}
@Override
public String populateCustomManagementInfo(String oasDefinition, SwaggerData swaggerData) throws APIManagementException {
return null;
}
@Override
public String getOASDefinitionForStore(API api, String oasDefinition, Map<String, String> hostsWithSchemes) throws APIManagementException {
return null;
}
@Override
public String getOASDefinitionForStore(APIProduct product, String oasDefinition, Map<String, String> hostsWithSchemes) throws APIManagementException {
return null;
}
@Override
public String getOASDefinitionForPublisher(API api, String oasDefinition) throws APIManagementException {
return null;
}
@Override
public String getOASVersion(String oasDefinition) throws APIManagementException {
return null;
}
@Override
public String getOASDefinitionWithTierContentAwareProperty(String oasDefinition, List<String> contentAwareTiersList, String apiLevelTier) throws APIManagementException {
return null;
}
@Override
public String processOtherSchemeScopes(String resourceConfigsJSON) throws APIManagementException {
return null;
}
@Override
public API setExtensionsToAPI(String swaggerContent, API api) throws APIManagementException {
return null;
}
@Override
public String copyVendorExtensions(String existingOASContent, String updatedOASContent) throws APIManagementException {
return null;
}
@Override
public String processDisableSecurityExtension(String swaggerContent) throws APIManagementException{
return null;
}
@Override
public String injectMgwThrottlingExtensionsToDefault(String swaggerContent) throws APIManagementException{
return null;
}
public String generateAsyncAPIDefinition(API api) throws APIManagementException {
Aai20Document aaiDocument = new Aai20Document();
aaiDocument.info = aaiDocument.createInfo();
aaiDocument.info.title = api.getId().getName();
aaiDocument.info.version = api.getId().getVersion();
if (!APIConstants.API_TYPE_WEBSUB.equals(api.getType())) {
Aai20Server server = (Aai20Server) aaiDocument.createServer("production");
JSONObject endpointConfig = new JSONObject(api.getEndpointConfig());
server.url = endpointConfig.getJSONObject("production_endpoints").getString("url");
server.protocol = api.getType().toLowerCase();
aaiDocument.addServer("production", server);
}
Map<String, AaiChannelItem> channels = new HashMap<>();
for (URITemplate uriTemplate : api.getUriTemplates()) {
Aai20ChannelItem channelItem = aaiDocument.createChannelItem(uriTemplate.getUriTemplate());
Aai20Operation subscribeOp = new Aai20Operation(channelItem,"subscribe");
channelItem.subscribe = subscribeOp;
if (APIConstants.API_TYPE_WS.equals(api.getType())) {
Aai20Operation publishOp = new Aai20Operation(channelItem,"publish");
channelItem.publish = publishOp;
}
channels.put(uriTemplate.getUriTemplate(), channelItem);
}
aaiDocument.channels = channels;
return Library.writeDocumentToJSONString(aaiDocument);
}
/**
* Update AsyncAPI definition for store
*
* @param api API
* @param asyncAPIDefinition AsyncAPI definition
* @param hostsWithSchemes host addresses with protocol mapping
* @return AsyncAPI definition
* @throws APIManagementException throws if an error occurred
*/
public String getAsyncApiDefinitionForStore(API api, String asyncAPIDefinition, Map<String, String> hostsWithSchemes)
throws APIManagementException {
Aai20Document aai20Document = (Aai20Document) Library.readDocumentFromJSONString(asyncAPIDefinition);
String channelName = api.getContext();
String transports = api.getTransports();
String url = StringUtils.EMPTY;
String[] apiTransports = transports.split(",");
if (ArrayUtils.contains(apiTransports, APIConstants.WSS_PROTOCOL)
&& hostsWithSchemes.get(APIConstants.WSS_PROTOCOL) != null) {
url = hostsWithSchemes.get(APIConstants.WSS_PROTOCOL).trim()
.replace(APIConstants.WSS_PROTOCOL_URL_PREFIX, "");
}
if (ArrayUtils.contains(apiTransports, APIConstants.WSS_PROTOCOL)
&& hostsWithSchemes.get(APIConstants.WS_PROTOCOL) != null) {
if (StringUtils.isEmpty(url)) {
url = hostsWithSchemes.get(APIConstants.WS_PROTOCOL).trim()
.replace(APIConstants.WS_PROTOCOL_URL_PREFIX, "");
}
}
Aai20Server server = (Aai20Server) aai20Document.getServers().get(0);
server.url = url;
Map<String, AaiChannelItem> channels = aai20Document.channels;
Aai20ChannelItem channelDetails = null;
for (String x : channels.keySet()) {
channelDetails = (Aai20ChannelItem) channels.get(x);
aai20Document.channels.remove(x);
}
assert channelDetails != null;
channelDetails._name = channelName;
aai20Document.channels.put(channelName, channelDetails);
return Library.writeDocumentToJSONString(aai20Document);
}
public String updateAsyncAPIDefinition(String oldDefinition, API apiToUpdate) {
Aai20Document document = (Aai20Document) Library.readDocumentFromJSONString(oldDefinition);
if (document.components == null) {
document.components = document.createComponents();
}
// add scopes
if (document.components.securitySchemes == null) {
document.components.securitySchemes = new HashMap<>();
}
Aai20SecurityScheme oauth2SecurityScheme = new Aai20SecurityScheme(document.components,
APIConstants.DEFAULT_API_SECURITY_OAUTH2);
oauth2SecurityScheme.type = APIConstants.DEFAULT_API_SECURITY_OAUTH2;
if (oauth2SecurityScheme.flows == null) {
oauth2SecurityScheme.flows = new Aai20OAuthFlows(oauth2SecurityScheme);
}
if (oauth2SecurityScheme.flows.implicit == null) {
oauth2SecurityScheme.flows.implicit = new Aai20ImplicitOAuthFlow(oauth2SecurityScheme.flows);
}
oauth2SecurityScheme.flows.implicit.authorizationUrl = "http://localhost:9999";
Map<String, String> scopes = new HashMap<>();
Map<String, String> scopeBindings = new HashMap<>();
Iterator<Scope> iterator = apiToUpdate.getScopes().iterator();
while (iterator.hasNext()) {
Scope scope = iterator.next();
scopes.put(scope.getName(), scope.getDescription());
scopeBindings.put(scope.getName(), scope.getRoles());
}
oauth2SecurityScheme.flows.implicit.scopes = scopes;
Extension xScopeBindings = oauth2SecurityScheme.flows.implicit.createExtension();
xScopeBindings.name = APIConstants.SWAGGER_X_SCOPES_BINDINGS;
xScopeBindings.value = scopeBindings;
oauth2SecurityScheme.flows.implicit.addExtension(APIConstants.SWAGGER_X_SCOPES_BINDINGS, xScopeBindings);
document.components.securitySchemes.put(APIConstants.DEFAULT_API_SECURITY_OAUTH2, oauth2SecurityScheme);
return Library.writeDocumentToJSONString(document);
}
public Map<String,String> buildWSUriMapping(String apiDefinition) {
Map<String,String> wsUriMapping = new HashMap<>();
Aai20Document document = (Aai20Document) Library.readDocumentFromJSONString(apiDefinition);
for (Map.Entry<String, AaiChannelItem> entry : document.channels.entrySet()) {
AaiOperation publishOperation = entry.getValue().publish;
if (publishOperation != null) {
Extension xUriMapping = publishOperation.getExtension("x-uri-mapping");
if (xUriMapping != null) {
wsUriMapping.put("PUBLISH_" + entry.getKey(), xUriMapping.value.toString());
}
}
AaiOperation subscribeOperation = entry.getValue().subscribe;
if (subscribeOperation != null) {
Extension xUriMapping = subscribeOperation.getExtension("x-uri-mapping");
if (xUriMapping != null) {
wsUriMapping.put("SUBSCRIBE_" + entry.getKey(), xUriMapping.value.toString());
}
}
}
return wsUriMapping;
}
}
|
components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/definitions/AsyncApiParser.java
|
package org.wso2.carbon.apimgt.impl.definitions;
import io.apicurio.datamodels.Library;
import io.apicurio.datamodels.asyncapi.models.AaiChannelItem;
import io.apicurio.datamodels.asyncapi.models.AaiDocument;
import io.apicurio.datamodels.asyncapi.models.AaiOperation;
import io.apicurio.datamodels.asyncapi.v2.models.Aai20ChannelItem;
import io.apicurio.datamodels.asyncapi.v2.models.Aai20Document;
import io.apicurio.datamodels.asyncapi.v2.models.Aai20ImplicitOAuthFlow;
import io.apicurio.datamodels.asyncapi.v2.models.Aai20OAuthFlows;
import io.apicurio.datamodels.asyncapi.v2.models.Aai20Operation;
import io.apicurio.datamodels.asyncapi.v2.models.Aai20SecurityScheme;
import io.apicurio.datamodels.asyncapi.v2.models.Aai20Server;
import io.apicurio.datamodels.core.models.Extension;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.everit.json.schema.Schema;
import org.everit.json.schema.ValidationException;
import org.everit.json.schema.loader.SchemaLoader;
import org.json.JSONObject;
import org.wso2.carbon.apimgt.api.APIDefinition;
import org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.model.API;
import org.wso2.carbon.apimgt.api.model.APIProduct;
import org.wso2.carbon.apimgt.api.model.Scope;
import org.wso2.carbon.apimgt.api.model.SwaggerData;
import org.wso2.carbon.apimgt.api.model.URITemplate;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.utils.APIUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
public class AsyncApiParser extends APIDefinition {
private static final String ASYNCAPI_JSON_HYPERSCHEMA = "{\n" +
" \"title\": \"AsyncAPI 2.0.0 schema.\",\n" +
" \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n" +
" \"type\": \"object\",\n" +
" \"required\": [\n" +
" \"asyncapi\",\n" +
" \"info\",\n" +
" \"channels\"\n" +
" ],\n" +
" \"additionalProperties\": false,\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"properties\": {\n" +
" \"asyncapi\": {\n" +
" \"type\": \"string\",\n" +
" \"enum\": [\n" +
" \"2.0.0\"\n" +
" ],\n" +
" \"description\": \"The AsyncAPI specification version of this document.\"\n" +
" },\n" +
" \"id\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"A unique id representing the application.\",\n" +
" \"format\": \"uri\"\n" +
" },\n" +
" \"info\": {\n" +
" \"$ref\": \"#/definitions/info\"\n" +
" },\n" +
" \"servers\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": {\n" +
" \"$ref\": \"#/definitions/server\"\n" +
" }\n" +
" },\n" +
" \"defaultContentType\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"channels\": {\n" +
" \"$ref\": \"#/definitions/channels\"\n" +
" },\n" +
" \"components\": {\n" +
" \"$ref\": \"#/definitions/components\"\n" +
" },\n" +
" \"tags\": {\n" +
" \"type\": \"array\",\n" +
" \"items\": {\n" +
" \"$ref\": \"#/definitions/tag\"\n" +
" },\n" +
" \"uniqueItems\": true\n" +
" },\n" +
" \"externalDocs\": {\n" +
" \"$ref\": \"#/definitions/externalDocs\"\n" +
" }\n" +
" },\n" +
" \"definitions\": {\n" +
" \"Reference\": {\n" +
" \"type\": \"object\",\n" +
" \"required\": [\n" +
" \"$ref\"\n" +
" ],\n" +
" \"properties\": {\n" +
" \"$ref\": {\n" +
" \"$ref\": \"#/definitions/ReferenceObject\"\n" +
" }\n" +
" }\n" +
" },\n" +
" \"ReferenceObject\": {\n" +
" \"type\": \"string\",\n" +
" \"format\": \"uri-reference\"\n" +
" },\n" +
" \"info\": {\n" +
" \"type\": \"object\",\n" +
" \"description\": \"General information about the API.\",\n" +
" \"required\": [\n" +
" \"version\",\n" +
" \"title\"\n" +
" ],\n" +
" \"additionalProperties\": false,\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"properties\": {\n" +
" \"title\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"A unique and precise title of the API.\"\n" +
" },\n" +
" \"version\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"A semantic version number of the API.\"\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"A longer description of the API. Should be different from the title. CommonMark is allowed.\"\n" +
" },\n" +
" \"termsOfService\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"A URL to the Terms of Service for the API. MUST be in the format of a URL.\",\n" +
" \"format\": \"uri\"\n" +
" },\n" +
" \"contact\": {\n" +
" \"$ref\": \"#/definitions/contact\"\n" +
" },\n" +
" \"license\": {\n" +
" \"$ref\": \"#/definitions/license\"\n" +
" }\n" +
" }\n" +
" },\n" +
" \"contact\": {\n" +
" \"type\": \"object\",\n" +
" \"description\": \"Contact information for the owners of the API.\",\n" +
" \"additionalProperties\": false,\n" +
" \"properties\": {\n" +
" \"name\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"The identifying name of the contact person/organization.\"\n" +
" },\n" +
" \"url\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"The URL pointing to the contact information.\",\n" +
" \"format\": \"uri\"\n" +
" },\n" +
" \"email\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"The email address of the contact person/organization.\",\n" +
" \"format\": \"email\"\n" +
" }\n" +
" },\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" }\n" +
" },\n" +
" \"license\": {\n" +
" \"type\": \"object\",\n" +
" \"required\": [\n" +
" \"name\"\n" +
" ],\n" +
" \"additionalProperties\": false,\n" +
" \"properties\": {\n" +
" \"name\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"The name of the license type. It's encouraged to use an OSI compatible license.\"\n" +
" },\n" +
" \"url\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"The URL pointing to the license.\",\n" +
" \"format\": \"uri\"\n" +
" }\n" +
" },\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" }\n" +
" },\n" +
" \"server\": {\n" +
" \"type\": \"object\",\n" +
" \"description\": \"An object representing a Server.\",\n" +
" \"required\": [\n" +
" \"url\",\n" +
" \"protocol\"\n" +
" ],\n" +
" \"additionalProperties\": false,\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"properties\": {\n" +
" \"url\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"protocol\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"The transfer protocol.\"\n" +
" },\n" +
" \"protocolVersion\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"variables\": {\n" +
" \"$ref\": \"#/definitions/serverVariables\"\n" +
" },\n" +
" \"security\": {\n" +
" \"type\": \"array\",\n" +
" \"items\": {\n" +
" \"$ref\": \"#/definitions/SecurityRequirement\"\n" +
" }\n" +
" },\n" +
" \"bindings\": {\n" +
" \"$ref\": \"#/definitions/bindingsObject\"\n" +
" }\n" +
" }\n" +
" },\n" +
" \"serverVariables\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": {\n" +
" \"$ref\": \"#/definitions/serverVariable\"\n" +
" }\n" +
" },\n" +
" \"serverVariable\": {\n" +
" \"type\": \"object\",\n" +
" \"description\": \"An object representing a Server Variable for server URL template substitution.\",\n" +
" \"additionalProperties\": false,\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"properties\": {\n" +
" \"enum\": {\n" +
" \"type\": \"array\",\n" +
" \"items\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"uniqueItems\": true\n" +
" },\n" +
" \"default\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"examples\": {\n" +
" \"type\": \"array\",\n" +
" \"items\": {\n" +
" \"type\": \"string\"\n" +
" }\n" +
" }\n" +
" }\n" +
" },\n" +
" \"channels\": {\n" +
" \"type\": \"object\",\n" +
" \"propertyNames\": {\n" +
" \"type\": \"string\",\n" +
" \"format\": \"uri-template\",\n" +
" \"minLength\": 1\n" +
" },\n" +
" \"additionalProperties\": {\n" +
" \"$ref\": \"#/definitions/channelItem\"\n" +
" }\n" +
" },\n" +
" \"components\": {\n" +
" \"type\": \"object\",\n" +
" \"description\": \"An object to hold a set of reusable objects for different aspects of the AsyncAPI Specification.\",\n" +
" \"additionalProperties\": false,\n" +
" \"properties\": {\n" +
" \"schemas\": {\n" +
" \"$ref\": \"#/definitions/schemas\"\n" +
" },\n" +
" \"messages\": {\n" +
" \"$ref\": \"#/definitions/messages\"\n" +
" },\n" +
" \"securitySchemes\": {\n" +
" \"type\": \"object\",\n" +
" \"patternProperties\": {\n" +
" \"^[\\\\w\\\\d\\\\.\\\\-_]+$\": {\n" +
" \"oneOf\": [\n" +
" {\n" +
" \"$ref\": \"#/definitions/Reference\"\n" +
" },\n" +
" {\n" +
" \"$ref\": \"#/definitions/SecurityScheme\"\n" +
" }\n" +
" ]\n" +
" }\n" +
" }\n" +
" },\n" +
" \"parameters\": {\n" +
" \"$ref\": \"#/definitions/parameters\"\n" +
" },\n" +
" \"correlationIds\": {\n" +
" \"type\": \"object\",\n" +
" \"patternProperties\": {\n" +
" \"^[\\\\w\\\\d\\\\.\\\\-_]+$\": {\n" +
" \"oneOf\": [\n" +
" {\n" +
" \"$ref\": \"#/definitions/Reference\"\n" +
" },\n" +
" {\n" +
" \"$ref\": \"#/definitions/correlationId\"\n" +
" }\n" +
" ]\n" +
" }\n" +
" }\n" +
" },\n" +
" \"operationTraits\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": {\n" +
" \"$ref\": \"#/definitions/operationTrait\"\n" +
" }\n" +
" },\n" +
" \"messageTraits\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": {\n" +
" \"$ref\": \"#/definitions/messageTrait\"\n" +
" }\n" +
" },\n" +
" \"serverBindings\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": {\n" +
" \"$ref\": \"#/definitions/bindingsObject\"\n" +
" }\n" +
" },\n" +
" \"channelBindings\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": {\n" +
" \"$ref\": \"#/definitions/bindingsObject\"\n" +
" }\n" +
" },\n" +
" \"operationBindings\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": {\n" +
" \"$ref\": \"#/definitions/bindingsObject\"\n" +
" }\n" +
" },\n" +
" \"messageBindings\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": {\n" +
" \"$ref\": \"#/definitions/bindingsObject\"\n" +
" }\n" +
" }\n" +
" }\n" +
" },\n" +
" \"schemas\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": {\n" +
" \"$ref\": \"#/definitions/schema\"\n" +
" },\n" +
" \"description\": \"JSON objects describing schemas the API uses.\"\n" +
" },\n" +
" \"messages\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": {\n" +
" \"$ref\": \"#/definitions/message\"\n" +
" },\n" +
" \"description\": \"JSON objects describing the messages being consumed and produced by the API.\"\n" +
" },\n" +
" \"parameters\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": {\n" +
" \"$ref\": \"#/definitions/parameter\"\n" +
" },\n" +
" \"description\": \"JSON objects describing re-usable channel parameters.\"\n" +
" },\n" +
" \"schema\": {\n" +
" \"allOf\": [\n" +
" {\n" +
" \"$ref\": \"http://json-schema.org/draft-07/schema#\"\n" +
" },\n" +
" {\n" +
" \"type\": \"object\",\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"properties\": {\n" +
" \"additionalProperties\": {\n" +
" \"anyOf\": [\n" +
" {\n" +
" \"$ref\": \"#/definitions/schema\"\n" +
" },\n" +
" {\n" +
" \"type\": \"boolean\"\n" +
" }\n" +
" ],\n" +
" \"default\": {}\n" +
" },\n" +
" \"items\": {\n" +
" \"anyOf\": [\n" +
" {\n" +
" \"$ref\": \"#/definitions/schema\"\n" +
" },\n" +
" {\n" +
" \"type\": \"array\",\n" +
" \"minItems\": 1,\n" +
" \"items\": {\n" +
" \"$ref\": \"#/definitions/schema\"\n" +
" }\n" +
" }\n" +
" ],\n" +
" \"default\": {}\n" +
" },\n" +
" \"allOf\": {\n" +
" \"type\": \"array\",\n" +
" \"minItems\": 1,\n" +
" \"items\": {\n" +
" \"$ref\": \"#/definitions/schema\"\n" +
" }\n" +
" },\n" +
" \"oneOf\": {\n" +
" \"type\": \"array\",\n" +
" \"minItems\": 2,\n" +
" \"items\": {\n" +
" \"$ref\": \"#/definitions/schema\"\n" +
" }\n" +
" },\n" +
" \"anyOf\": {\n" +
" \"type\": \"array\",\n" +
" \"minItems\": 2,\n" +
" \"items\": {\n" +
" \"$ref\": \"#/definitions/schema\"\n" +
" }\n" +
" },\n" +
" \"not\": {\n" +
" \"$ref\": \"#/definitions/schema\"\n" +
" },\n" +
" \"properties\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": {\n" +
" \"$ref\": \"#/definitions/schema\"\n" +
" },\n" +
" \"default\": {}\n" +
" },\n" +
" \"patternProperties\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": {\n" +
" \"$ref\": \"#/definitions/schema\"\n" +
" },\n" +
" \"default\": {}\n" +
" },\n" +
" \"propertyNames\": {\n" +
" \"$ref\": \"#/definitions/schema\"\n" +
" },\n" +
" \"contains\": {\n" +
" \"$ref\": \"#/definitions/schema\"\n" +
" },\n" +
" \"discriminator\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"externalDocs\": {\n" +
" \"$ref\": \"#/definitions/externalDocs\"\n" +
" },\n" +
" \"deprecated\": {\n" +
" \"type\": \"boolean\",\n" +
" \"default\": false\n" +
" }\n" +
" }\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"externalDocs\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": false,\n" +
" \"description\": \"information about external documentation\",\n" +
" \"required\": [\n" +
" \"url\"\n" +
" ],\n" +
" \"properties\": {\n" +
" \"description\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"url\": {\n" +
" \"type\": \"string\",\n" +
" \"format\": \"uri\"\n" +
" }\n" +
" },\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" }\n" +
" },\n" +
" \"channelItem\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": false,\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"properties\": {\n" +
" \"$ref\": {\n" +
" \"$ref\": \"#/definitions/ReferenceObject\"\n" +
" },\n" +
" \"parameters\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": {\n" +
" \"$ref\": \"#/definitions/parameter\"\n" +
" }\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"A description of the channel.\"\n" +
" },\n" +
" \"publish\": {\n" +
" \"$ref\": \"#/definitions/operation\"\n" +
" },\n" +
" \"subscribe\": {\n" +
" \"$ref\": \"#/definitions/operation\"\n" +
" },\n" +
" \"deprecated\": {\n" +
" \"type\": \"boolean\",\n" +
" \"default\": false\n" +
" },\n" +
" \"bindings\": {\n" +
" \"$ref\": \"#/definitions/bindingsObject\"\n" +
" }\n" +
" }\n" +
" },\n" +
" \"parameter\": {\n" +
" \"additionalProperties\": false,\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"properties\": {\n" +
" \"description\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed.\"\n" +
" },\n" +
" \"schema\": {\n" +
" \"$ref\": \"#/definitions/schema\"\n" +
" },\n" +
" \"location\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"A runtime expression that specifies the location of the parameter value\",\n" +
" \"pattern\": \"^\\\\$message\\\\.(header|payload)\\\\#(\\\\/(([^\\\\/~])|(~[01]))*)*\"\n" +
" },\n" +
" \"$ref\": {\n" +
" \"$ref\": \"#/definitions/ReferenceObject\"\n" +
" }\n" +
" }\n" +
" },\n" +
" \"operation\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": false,\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"properties\": {\n" +
" \"traits\": {\n" +
" \"type\": \"array\",\n" +
" \"items\": {\n" +
" \"oneOf\": [\n" +
" {\n" +
" \"$ref\": \"#/definitions/Reference\"\n" +
" },\n" +
" {\n" +
" \"$ref\": \"#/definitions/operationTrait\"\n" +
" },\n" +
" {\n" +
" \"type\": \"array\",\n" +
" \"items\": [\n" +
" {\n" +
" \"oneOf\": [\n" +
" {\n" +
" \"$ref\": \"#/definitions/Reference\"\n" +
" },\n" +
" {\n" +
" \"$ref\": \"#/definitions/operationTrait\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"type\": \"object\",\n" +
" \"additionalItems\": true\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
" }\n" +
" },\n" +
" \"summary\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"tags\": {\n" +
" \"type\": \"array\",\n" +
" \"items\": {\n" +
" \"$ref\": \"#/definitions/tag\"\n" +
" },\n" +
" \"uniqueItems\": true\n" +
" },\n" +
" \"externalDocs\": {\n" +
" \"$ref\": \"#/definitions/externalDocs\"\n" +
" },\n" +
" \"operationId\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"bindings\": {\n" +
" \"$ref\": \"#/definitions/bindingsObject\"\n" +
" },\n" +
" \"message\": {\n" +
" \"$ref\": \"#/definitions/message\"\n" +
" }\n" +
" }\n" +
" },\n" +
" \"message\": {\n" +
" \"oneOf\": [\n" +
" {\n" +
" \"$ref\": \"#/definitions/Reference\"\n" +
" },\n" +
" {\n" +
" \"oneOf\": [\n" +
" {\n" +
" \"type\": \"object\",\n" +
" \"required\": [\n" +
" \"oneOf\"\n" +
" ],\n" +
" \"additionalProperties\": false,\n" +
" \"properties\": {\n" +
" \"oneOf\": {\n" +
" \"type\": \"array\",\n" +
" \"items\": {\n" +
" \"$ref\": \"#/definitions/message\"\n" +
" }\n" +
" }\n" +
" }\n" +
" },\n" +
" {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": false,\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"properties\": {\n" +
" \"schemaFormat\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"contentType\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"headers\": {\n" +
" \"allOf\": [\n" +
" { \"$ref\": \"#/definitions/schema\" },\n" +
" { \"properties\": {\n" +
" \"type\": { \"const\": \"object\" }\n" +
" }\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"payload\": {},\n" +
" \"correlationId\": {\n" +
" \"oneOf\": [\n" +
" {\n" +
" \"$ref\": \"#/definitions/Reference\"\n" +
" },\n" +
" {\n" +
" \"$ref\": \"#/definitions/correlationId\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"tags\": {\n" +
" \"type\": \"array\",\n" +
" \"items\": {\n" +
" \"$ref\": \"#/definitions/tag\"\n" +
" },\n" +
" \"uniqueItems\": true\n" +
" },\n" +
" \"summary\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"A brief summary of the message.\"\n" +
" },\n" +
" \"name\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"Name of the message.\"\n" +
" },\n" +
" \"title\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"A human-friendly title for the message.\"\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"A longer description of the message. CommonMark is allowed.\"\n" +
" },\n" +
" \"externalDocs\": {\n" +
" \"$ref\": \"#/definitions/externalDocs\"\n" +
" },\n" +
" \"deprecated\": {\n" +
" \"type\": \"boolean\",\n" +
" \"default\": false\n" +
" },\n" +
" \"examples\": {\n" +
" \"type\": \"array\",\n" +
" \"items\": {\n" +
" \"type\": \"object\"\n" +
" }\n" +
" },\n" +
" \"bindings\": {\n" +
" \"$ref\": \"#/definitions/bindingsObject\"\n" +
" },\n" +
" \"traits\": {\n" +
" \"type\": \"array\",\n" +
" \"items\": {\n" +
" \"oneOf\": [\n" +
" {\n" +
" \"$ref\": \"#/definitions/Reference\"\n" +
" },\n" +
" {\n" +
" \"$ref\": \"#/definitions/messageTrait\"\n" +
" },\n" +
" {\n" +
" \"type\": \"array\",\n" +
" \"items\": [\n" +
" {\n" +
" \"oneOf\": [\n" +
" {\n" +
" \"$ref\": \"#/definitions/Reference\"\n" +
" },\n" +
" {\n" +
" \"$ref\": \"#/definitions/messageTrait\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"type\": \"object\",\n" +
" \"additionalItems\": true\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"bindingsObject\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": true,\n" +
" \"properties\": {\n" +
" \"http\": {},\n" +
" \"ws\": {},\n" +
" \"amqp\": {},\n" +
" \"amqp1\": {},\n" +
" \"mqtt\": {},\n" +
" \"mqtt5\": {},\n" +
" \"kafka\": {},\n" +
" \"nats\": {},\n" +
" \"jms\": {},\n" +
" \"sns\": {},\n" +
" \"sqs\": {},\n" +
" \"stomp\": {},\n" +
" \"redis\": {},\n" +
" \"mercure\": {}\n" +
" }\n" +
" },\n" +
" \"correlationId\": {\n" +
" \"type\": \"object\",\n" +
" \"required\": [\n" +
" \"location\"\n" +
" ],\n" +
" \"additionalProperties\": false,\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"properties\": {\n" +
" \"description\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"A optional description of the correlation ID. GitHub Flavored Markdown is allowed.\"\n" +
" },\n" +
" \"location\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"A runtime expression that specifies the location of the correlation ID\",\n" +
" \"pattern\": \"^\\\\$message\\\\.(header|payload)\\\\#(\\\\/(([^\\\\/~])|(~[01]))*)*\"\n" +
" }\n" +
" }\n" +
" },\n" +
" \"specificationExtension\": {\n" +
" \"description\": \"Any property starting with x- is valid.\",\n" +
" \"additionalProperties\": true,\n" +
" \"additionalItems\": true\n" +
" },\n" +
" \"tag\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": false,\n" +
" \"required\": [\n" +
" \"name\"\n" +
" ],\n" +
" \"properties\": {\n" +
" \"name\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"externalDocs\": {\n" +
" \"$ref\": \"#/definitions/externalDocs\"\n" +
" }\n" +
" },\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" }\n" +
" },\n" +
" \"operationTrait\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": false,\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"properties\": {\n" +
" \"summary\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"tags\": {\n" +
" \"type\": \"array\",\n" +
" \"items\": {\n" +
" \"$ref\": \"#/definitions/tag\"\n" +
" },\n" +
" \"uniqueItems\": true\n" +
" },\n" +
" \"externalDocs\": {\n" +
" \"$ref\": \"#/definitions/externalDocs\"\n" +
" },\n" +
" \"operationId\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"bindings\": {\n" +
" \"$ref\": \"#/definitions/bindingsObject\"\n" +
" }\n" +
" }\n" +
" },\n" +
" \"messageTrait\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": false,\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"properties\": {\n" +
" \"schemaFormat\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"contentType\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"headers\": {\n" +
" \"oneOf\": [\n" +
" {\n" +
" \"$ref\": \"#/definitions/Reference\"\n" +
" },\n" +
" {\n" +
" \"$ref\": \"#/definitions/schema\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"correlationId\": {\n" +
" \"oneOf\": [\n" +
" {\n" +
" \"$ref\": \"#/definitions/Reference\"\n" +
" },\n" +
" {\n" +
" \"$ref\": \"#/definitions/correlationId\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"tags\": {\n" +
" \"type\": \"array\",\n" +
" \"items\": {\n" +
" \"$ref\": \"#/definitions/tag\"\n" +
" },\n" +
" \"uniqueItems\": true\n" +
" },\n" +
" \"summary\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"A brief summary of the message.\"\n" +
" },\n" +
" \"name\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"Name of the message.\"\n" +
" },\n" +
" \"title\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"A human-friendly title for the message.\"\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\",\n" +
" \"description\": \"A longer description of the message. CommonMark is allowed.\"\n" +
" },\n" +
" \"externalDocs\": {\n" +
" \"$ref\": \"#/definitions/externalDocs\"\n" +
" },\n" +
" \"deprecated\": {\n" +
" \"type\": \"boolean\",\n" +
" \"default\": false\n" +
" },\n" +
" \"examples\": {\n" +
" \"type\": \"array\",\n" +
" \"items\": {\n" +
" \"type\": \"object\"\n" +
" }\n" +
" },\n" +
" \"bindings\": {\n" +
" \"$ref\": \"#/definitions/bindingsObject\"\n" +
" }\n" +
" }\n" +
" },\n" +
" \"SecurityScheme\": {\n" +
" \"oneOf\": [\n" +
" {\n" +
" \"$ref\": \"#/definitions/userPassword\"\n" +
" },\n" +
" {\n" +
" \"$ref\": \"#/definitions/apiKey\"\n" +
" },\n" +
" {\n" +
" \"$ref\": \"#/definitions/X509\"\n" +
" },\n" +
" {\n" +
" \"$ref\": \"#/definitions/symmetricEncryption\"\n" +
" },\n" +
" {\n" +
" \"$ref\": \"#/definitions/asymmetricEncryption\"\n" +
" },\n" +
" {\n" +
" \"$ref\": \"#/definitions/HTTPSecurityScheme\"\n" +
" },\n" +
" {\n" +
" \"$ref\": \"#/definitions/oauth2Flows\"\n" +
" },\n" +
" {\n" +
" \"$ref\": \"#/definitions/openIdConnect\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"userPassword\": {\n" +
" \"type\": \"object\",\n" +
" \"required\": [\n" +
" \"type\"\n" +
" ],\n" +
" \"properties\": {\n" +
" \"type\": {\n" +
" \"type\": \"string\",\n" +
" \"enum\": [\n" +
" \"userPassword\"\n" +
" ]\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\"\n" +
" }\n" +
" },\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"additionalProperties\": false\n" +
" },\n" +
" \"apiKey\": {\n" +
" \"type\": \"object\",\n" +
" \"required\": [\n" +
" \"type\",\n" +
" \"in\"\n" +
" ],\n" +
" \"properties\": {\n" +
" \"type\": {\n" +
" \"type\": \"string\",\n" +
" \"enum\": [\n" +
" \"apiKey\"\n" +
" ]\n" +
" },\n" +
" \"in\": {\n" +
" \"type\": \"string\",\n" +
" \"enum\": [\n" +
" \"user\",\n" +
" \"password\"\n" +
" ]\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\"\n" +
" }\n" +
" },\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"additionalProperties\": false\n" +
" },\n" +
" \"X509\": {\n" +
" \"type\": \"object\",\n" +
" \"required\": [\n" +
" \"type\"\n" +
" ],\n" +
" \"properties\": {\n" +
" \"type\": {\n" +
" \"type\": \"string\",\n" +
" \"enum\": [\n" +
" \"X509\"\n" +
" ]\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\"\n" +
" }\n" +
" },\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"additionalProperties\": false\n" +
" },\n" +
" \"symmetricEncryption\": {\n" +
" \"type\": \"object\",\n" +
" \"required\": [\n" +
" \"type\"\n" +
" ],\n" +
" \"properties\": {\n" +
" \"type\": {\n" +
" \"type\": \"string\",\n" +
" \"enum\": [\n" +
" \"symmetricEncryption\"\n" +
" ]\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\"\n" +
" }\n" +
" },\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"additionalProperties\": false\n" +
" },\n" +
" \"asymmetricEncryption\": {\n" +
" \"type\": \"object\",\n" +
" \"required\": [\n" +
" \"type\"\n" +
" ],\n" +
" \"properties\": {\n" +
" \"type\": {\n" +
" \"type\": \"string\",\n" +
" \"enum\": [\n" +
" \"asymmetricEncryption\"\n" +
" ]\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\"\n" +
" }\n" +
" },\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"additionalProperties\": false\n" +
" },\n" +
" \"HTTPSecurityScheme\": {\n" +
" \"oneOf\": [\n" +
" {\n" +
" \"$ref\": \"#/definitions/NonBearerHTTPSecurityScheme\"\n" +
" },\n" +
" {\n" +
" \"$ref\": \"#/definitions/BearerHTTPSecurityScheme\"\n" +
" },\n" +
" {\n" +
" \"$ref\": \"#/definitions/APIKeyHTTPSecurityScheme\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"NonBearerHTTPSecurityScheme\": {\n" +
" \"not\": {\n" +
" \"type\": \"object\",\n" +
" \"properties\": {\n" +
" \"scheme\": {\n" +
" \"type\": \"string\",\n" +
" \"enum\": [\n" +
" \"bearer\"\n" +
" ]\n" +
" }\n" +
" }\n" +
" },\n" +
" \"type\": \"object\",\n" +
" \"required\": [\n" +
" \"scheme\",\n" +
" \"type\"\n" +
" ],\n" +
" \"properties\": {\n" +
" \"scheme\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"type\": {\n" +
" \"type\": \"string\",\n" +
" \"enum\": [\n" +
" \"http\"\n" +
" ]\n" +
" }\n" +
" },\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"additionalProperties\": false\n" +
" },\n" +
" \"BearerHTTPSecurityScheme\": {\n" +
" \"type\": \"object\",\n" +
" \"required\": [\n" +
" \"type\",\n" +
" \"scheme\"\n" +
" ],\n" +
" \"properties\": {\n" +
" \"scheme\": {\n" +
" \"type\": \"string\",\n" +
" \"enum\": [\n" +
" \"bearer\"\n" +
" ]\n" +
" },\n" +
" \"bearerFormat\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"type\": {\n" +
" \"type\": \"string\",\n" +
" \"enum\": [\n" +
" \"http\"\n" +
" ]\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\"\n" +
" }\n" +
" },\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"additionalProperties\": false\n" +
" },\n" +
" \"APIKeyHTTPSecurityScheme\": {\n" +
" \"type\": \"object\",\n" +
" \"required\": [\n" +
" \"type\",\n" +
" \"name\",\n" +
" \"in\"\n" +
" ],\n" +
" \"properties\": {\n" +
" \"type\": {\n" +
" \"type\": \"string\",\n" +
" \"enum\": [\n" +
" \"httpApiKey\"\n" +
" ]\n" +
" },\n" +
" \"name\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"in\": {\n" +
" \"type\": \"string\",\n" +
" \"enum\": [\n" +
" \"header\",\n" +
" \"query\",\n" +
" \"cookie\"\n" +
" ]\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\"\n" +
" }\n" +
" },\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"additionalProperties\": false\n" +
" },\n" +
" \"oauth2Flows\": {\n" +
" \"type\": \"object\",\n" +
" \"required\": [\n" +
" \"type\",\n" +
" \"flows\"\n" +
" ],\n" +
" \"properties\": {\n" +
" \"type\": {\n" +
" \"type\": \"string\",\n" +
" \"enum\": [\n" +
" \"oauth2\"\n" +
" ]\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"flows\": {\n" +
" \"type\": \"object\",\n" +
" \"properties\": {\n" +
" \"implicit\": {\n" +
" \"allOf\": [\n" +
" {\n" +
" \"$ref\": \"#/definitions/oauth2Flow\"\n" +
" },\n" +
" {\n" +
" \"required\": [\n" +
" \"authorizationUrl\",\n" +
" \"scopes\"\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"not\": {\n" +
" \"required\": [\n" +
" \"tokenUrl\"\n" +
" ]\n" +
" }\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"password\": {\n" +
" \"allOf\": [\n" +
" {\n" +
" \"$ref\": \"#/definitions/oauth2Flow\"\n" +
" },\n" +
" {\n" +
" \"required\": [\n" +
" \"tokenUrl\",\n" +
" \"scopes\"\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"not\": {\n" +
" \"required\": [\n" +
" \"authorizationUrl\"\n" +
" ]\n" +
" }\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"clientCredentials\": {\n" +
" \"allOf\": [\n" +
" {\n" +
" \"$ref\": \"#/definitions/oauth2Flow\"\n" +
" },\n" +
" {\n" +
" \"required\": [\n" +
" \"tokenUrl\",\n" +
" \"scopes\"\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"not\": {\n" +
" \"required\": [\n" +
" \"authorizationUrl\"\n" +
" ]\n" +
" }\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"authorizationCode\": {\n" +
" \"allOf\": [\n" +
" {\n" +
" \"$ref\": \"#/definitions/oauth2Flow\"\n" +
" },\n" +
" {\n" +
" \"required\": [\n" +
" \"authorizationUrl\",\n" +
" \"tokenUrl\",\n" +
" \"scopes\"\n" +
" ]\n" +
" }\n" +
" ]\n" +
" }\n" +
" },\n" +
" \"additionalProperties\": false\n" +
" }\n" +
" },\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" }\n" +
" },\n" +
" \"oauth2Flow\": {\n" +
" \"type\": \"object\",\n" +
" \"properties\": {\n" +
" \"authorizationUrl\": {\n" +
" \"type\": \"string\",\n" +
" \"format\": \"uri\"\n" +
" },\n" +
" \"tokenUrl\": {\n" +
" \"type\": \"string\",\n" +
" \"format\": \"uri\"\n" +
" },\n" +
" \"refreshUrl\": {\n" +
" \"type\": \"string\",\n" +
" \"format\": \"uri\"\n" +
" },\n" +
" \"scopes\": {\n" +
" \"$ref\": \"#/definitions/oauth2Scopes\"\n" +
" }\n" +
" },\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"additionalProperties\": false\n" +
" },\n" +
" \"oauth2Scopes\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": {\n" +
" \"type\": \"string\"\n" +
" }\n" +
" },\n" +
" \"openIdConnect\": {\n" +
" \"type\": \"object\",\n" +
" \"required\": [\n" +
" \"type\",\n" +
" \"openIdConnectUrl\"\n" +
" ],\n" +
" \"properties\": {\n" +
" \"type\": {\n" +
" \"type\": \"string\",\n" +
" \"enum\": [\n" +
" \"openIdConnect\"\n" +
" ]\n" +
" },\n" +
" \"description\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"openIdConnectUrl\": {\n" +
" \"type\": \"string\",\n" +
" \"format\": \"uri\"\n" +
" }\n" +
" },\n" +
" \"patternProperties\": {\n" +
" \"^x-[\\\\w\\\\d\\\\.\\\\-\\\\_]+$\": {\n" +
" \"$ref\": \"#/definitions/specificationExtension\"\n" +
" }\n" +
" },\n" +
" \"additionalProperties\": false\n" +
" },\n" +
" \"SecurityRequirement\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": {\n" +
" \"type\": \"array\",\n" +
" \"items\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"uniqueItems\": true\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
private static final Log log = LogFactory.getLog(AsyncApiParser.class);
private List<String> otherSchemes;
public List<String> getOtherSchemes() {
return otherSchemes;
}
public void setOtherSchemes(List<String> otherSchemes) {
this.otherSchemes = otherSchemes;
}
@Override
public Map<String, Object> generateExample(String apiDefinition) throws APIManagementException{
return null;
}
@Override
public Set<URITemplate> getURITemplates(String resourceConfigsJSON) throws APIManagementException {
return getURITemplates(resourceConfigsJSON, true);
}
public Set<URITemplate> getURITemplates(String apiDefinition, boolean includePublish)
throws APIManagementException {
Set<URITemplate> uriTemplates = new HashSet<>();
Set<Scope> scopes = getScopes(apiDefinition);
Aai20Document document = (Aai20Document) Library.readDocumentFromJSONString(apiDefinition);
if (document.channels != null && document.channels.size() > 0) {
for (Map.Entry<String, AaiChannelItem> entry : document.channels.entrySet()) {
Aai20ChannelItem channel = (Aai20ChannelItem) entry.getValue();
if (includePublish && channel.publish != null) {
uriTemplates.add(buildURITemplate(entry.getKey(), APIConstants.HTTP_VERB_PUBLISH,
(Aai20Operation) channel.publish, scopes, channel));
}
if (channel.subscribe != null) {
uriTemplates.add(buildURITemplate(entry.getKey(), APIConstants.HTTP_VERB_SUBSCRIBE,
(Aai20Operation) channel.subscribe, scopes, channel));
}
}
}
return uriTemplates;
}
private URITemplate buildURITemplate(String target, String verb, Aai20Operation operation, Set<Scope> scopes,
Aai20ChannelItem channel) throws APIManagementException {
URITemplate template = new URITemplate();
template.setHTTPVerb(verb);
template.setHttpVerbs(verb);
template.setUriTemplate(target);
Extension authTypeExtension = channel.getExtension(APIConstants.SWAGGER_X_AUTH_TYPE);
if (authTypeExtension != null && authTypeExtension.value instanceof String) {
template.setAuthType(authTypeExtension.value.toString());
}
List<String> opScopes = getScopeOfOperations(operation);
if (!opScopes.isEmpty()) {
if (opScopes.size() == 1) {
String firstScope = opScopes.get(0);
Scope scope = APIUtil.findScopeByKey(scopes, firstScope);
if (scope == null) {
throw new APIManagementException("Scope '" + firstScope + "' not found.");
}
template.setScope(scope);
template.setScopes(scope);
} else {
for (String scopeName : opScopes) {
Scope scope = APIUtil.findScopeByKey(scopes, scopeName);
if (scope == null) {
throw new APIManagementException("Resource Scope '" + scopeName + "' not found.");
}
template.setScopes(scope);
}
}
}
return template;
}
private List<String> getScopeOfOperations(Aai20Operation operation) {
return getScopeOfOperationsFromExtensions(operation);
}
private List<String> getScopeOfOperationsFromExtensions(Aai20Operation operation) {
Extension scopeBindings = operation.getExtension("x-scopes");
if (scopeBindings != null) {
if (scopeBindings.value instanceof LinkedHashMap) {
return (List<String>) ((LinkedHashMap) scopeBindings.value)
.values()
.stream()
.collect(Collectors.toList());
}
if (scopeBindings.value instanceof ArrayList) {
return (List<String>) scopeBindings.value;
}
}
return Collections.emptyList();
}
@Override
public Set<Scope> getScopes(String resourceConfigsJSON) throws APIManagementException {
Set<Scope> scopeSet = new LinkedHashSet<>();
Aai20Document document = (Aai20Document) Library.readDocumentFromJSONString(resourceConfigsJSON);
if (document.components != null && document.components.securitySchemes != null) {
Aai20SecurityScheme oauth2 = (Aai20SecurityScheme) document.components.securitySchemes.get("oauth2");
if (oauth2 != null && oauth2.flows != null && oauth2.flows.implicit != null) {
Map<String, String> scopes = oauth2.flows.implicit.scopes;
Extension xScopesBindings = oauth2.flows.implicit.getExtension(APIConstants.SWAGGER_X_SCOPES_BINDINGS);
Map<String, String> scopeBindings = new HashMap<>();
if (xScopesBindings != null) {
scopeBindings = (Map<String, String>) xScopesBindings.value;
}
if (scopes != null) {
for (Map.Entry<String, String> entry : scopes.entrySet()) {
Scope scope = new Scope();
scope.setKey(entry.getKey());
scope.setName(entry.getKey());
scope.setDescription(entry.getValue());
String scopeBinding = scopeBindings.get(scope.getKey());
if (scopeBinding != null) {
scope.setRoles(scopeBinding);
}
scopeSet.add(scope);
}
}
}
}
return scopeSet;
}
@Override
public String generateAPIDefinition(SwaggerData swaggerData) throws APIManagementException {
return null;
}
@Override
public String generateAPIDefinition(SwaggerData swaggerData, String swagger) throws APIManagementException {
return null;
}
@Override
public APIDefinitionValidationResponse validateAPIDefinition(String apiDefinition, String url, boolean returnJsonContent) throws APIManagementException {
return null;
}
@Override
public APIDefinitionValidationResponse validateAPIDefinition(String apiDefinition, boolean returnJsonContent) throws APIManagementException {
APIDefinitionValidationResponse validationResponse = new APIDefinitionValidationResponse();
//import and load AsyncAPI HyperSchema for JSON schema validation
JSONObject hyperSchema = new JSONObject(ASYNCAPI_JSON_HYPERSCHEMA);
Schema schemaValidator = SchemaLoader.load(hyperSchema);
String protocol = StringUtils.EMPTY;
boolean validationSuccess = false;
List<String> validationErrorMessages = null;
boolean isWebSocket = false;
JSONObject schemaToBeValidated = new JSONObject(apiDefinition);
//validate AsyncAPI using JSON schema validation
try {
schemaValidator.validate(schemaToBeValidated);
/*AaiDocument asyncApiDocument = (AaiDocument) Library.readDocumentFromJSONString(apiDefinition);
validationErrorMessages = new ArrayList<>();
if (asyncApiDocument.getServers().size() == 1) {
if (!APIConstants.WS_PROTOCOL.equalsIgnoreCase(asyncApiDocument.getServers().get(0).protocol)) {
validationErrorMessages.add("#:The protocol of the server should be 'ws' for websockets");
}
}
if (asyncApiDocument.getServers().size() > 1) {
validationErrorMessages.add("#:The AsyncAPI definition should contain only a single server for websockets");
}
if (asyncApiDocument.getChannels().size() > 1) {
validationErrorMessages.add("#:The AsyncAPI definition should contain only a single channel for websockets");
}
if (validationErrorMessages.size() == 0) {
validationSuccess = true;
validationErrorMessages = null;
}*/
//AaiDocument asyncApiDocument = (AaiDocument) Library.readDocumentFromJSONString(apiDefinition);
/*//Checking whether it is a websocket
validationErrorMessages = new ArrayList<>();
if (APIConstants.WS_PROTOCOL.equalsIgnoreCase(asyncApiDocument.getServers().get(0).protocol)) {
if (APIConstants.WS_PROTOCOL.equalsIgnoreCase(protocol)) {
isWebSocket = true;
}
}*/
//validating channel count for websockets
/*if (isWebSocket) {
if (asyncApiDocument.getChannels().size() > 1) {
validationErrorMessages.add("#:The AsyncAPI definition should contain only a single channel for websockets");
}
}*/
/*if (validationErrorMessages.size() == 0) {
validationSuccess = true;
validationErrorMessages = null;
}*/
validationSuccess = true;
} catch (ValidationException e){
//validation error messages
validationErrorMessages = e.getAllMessages();
}
// TODO: Validation is failing. Need to fix this. Therefore overriding the value as True.
validationSuccess = true;
if (validationSuccess) {
AaiDocument asyncApiDocument = (AaiDocument) Library.readDocumentFromJSONString(apiDefinition);
ArrayList<String> endpoints = new ArrayList<>();
if (asyncApiDocument.getServers().size() == 1) {
protocol = asyncApiDocument.getServers().get(0).protocol;
}
/*for (AaiServer x : asyncApiDocument.getServers()){
endpoints.add(x.url);
}
AsyncApiParserUtil.updateValidationResponseAsSuccess(
validationResponse,
apiDefinition,
asyncApiDocument.asyncapi,
asyncApiDocument.info.title,
asyncApiDocument.info.version,
null, //asyncApiDocument.getChannels().get(0)._name,
asyncApiDocument.info.description,
endpoints
);*/
/*if (isWebSocket) {
for (AaiServer x : asyncApiDocument.getServers()){
endpoints.add(x.url);
}
AsyncApiParserUtil.updateValidationResponseAsSuccess(
validationResponse,
apiDefinition,
asyncApiDocument.asyncapi,
asyncApiDocument.info.title,
asyncApiDocument.info.version,
asyncApiDocument.getChannels().get(0)._name, //make this null
asyncApiDocument.info.description,
endpoints
);
} else {
AsyncApiParserUtil.updateValidationResponseAsSuccess(
validationResponse,
apiDefinition,
asyncApiDocument.asyncapi,
asyncApiDocument.info.title,
asyncApiDocument.info.version,
null,
asyncApiDocument.info.description,
null
);
}*/
AsyncApiParserUtil.updateValidationResponseAsSuccess(
validationResponse,
apiDefinition,
asyncApiDocument.asyncapi,
asyncApiDocument.info.title,
asyncApiDocument.info.version,
null,
asyncApiDocument.info.description,
null
);
validationResponse.setParser(this);
if (returnJsonContent) {
validationResponse.setJsonContent(apiDefinition);
}
if (StringUtils.isNotEmpty(protocol)) {
validationResponse.setProtocol(protocol);
}
} else {
if (validationErrorMessages != null){
validationResponse.setValid(false);
for (String errorMessage: validationErrorMessages){
AsyncApiParserUtil.addErrorToValidationResponse(validationResponse, errorMessage);
}
}
}
return validationResponse;
}
@Override
public String populateCustomManagementInfo(String oasDefinition, SwaggerData swaggerData) throws APIManagementException {
return null;
}
@Override
public String getOASDefinitionForStore(API api, String oasDefinition, Map<String, String> hostsWithSchemes) throws APIManagementException {
return null;
}
@Override
public String getOASDefinitionForStore(APIProduct product, String oasDefinition, Map<String, String> hostsWithSchemes) throws APIManagementException {
return null;
}
@Override
public String getOASDefinitionForPublisher(API api, String oasDefinition) throws APIManagementException {
return null;
}
@Override
public String getOASVersion(String oasDefinition) throws APIManagementException {
return null;
}
@Override
public String getOASDefinitionWithTierContentAwareProperty(String oasDefinition, List<String> contentAwareTiersList, String apiLevelTier) throws APIManagementException {
return null;
}
@Override
public String processOtherSchemeScopes(String resourceConfigsJSON) throws APIManagementException {
return null;
}
@Override
public API setExtensionsToAPI(String swaggerContent, API api) throws APIManagementException {
return null;
}
@Override
public String copyVendorExtensions(String existingOASContent, String updatedOASContent) throws APIManagementException {
return null;
}
@Override
public String processDisableSecurityExtension(String swaggerContent) throws APIManagementException{
return null;
}
@Override
public String injectMgwThrottlingExtensionsToDefault(String swaggerContent) throws APIManagementException{
return null;
}
public String generateAsyncAPIDefinition(API api) throws APIManagementException {
Aai20Document aaiDocument = new Aai20Document();
aaiDocument.info = aaiDocument.createInfo();
aaiDocument.info.title = api.getId().getName();
aaiDocument.info.version = api.getId().getVersion();
if (!APIConstants.API_TYPE_WEBSUB.equals(api.getType())) {
Aai20Server server = (Aai20Server) aaiDocument.createServer("production");
JSONObject endpointConfig = new JSONObject(api.getEndpointConfig());
server.url = endpointConfig.getJSONObject("production_endpoints").getString("url");
server.protocol = api.getType().toLowerCase();
aaiDocument.addServer("production", server);
}
Map<String, AaiChannelItem> channels = new HashMap<>();
for (URITemplate uriTemplate : api.getUriTemplates()) {
Aai20ChannelItem channelItem = aaiDocument.createChannelItem(uriTemplate.getUriTemplate());
Aai20Operation subscribeOp = new Aai20Operation(channelItem,"subscribe");
channelItem.subscribe = subscribeOp;
if (APIConstants.API_TYPE_WS.equals(api.getType())) {
Aai20Operation publishOp = new Aai20Operation(channelItem,"publish");
channelItem.publish = publishOp;
}
channels.put(uriTemplate.getUriTemplate(), channelItem);
}
aaiDocument.channels = channels;
return Library.writeDocumentToJSONString(aaiDocument);
}
/**
* Update AsyncAPI definition for store
*
* @param api API
* @param asyncAPIDefinition AsyncAPI definition
* @param hostsWithSchemes host addresses with protocol mapping
* @return AsyncAPI definition
* @throws APIManagementException throws if an error occurred
*/
public String getAsyncApiDefinitionForStore(API api, String asyncAPIDefinition, Map<String, String> hostsWithSchemes)
throws APIManagementException {
Aai20Document aai20Document = (Aai20Document) Library.readDocumentFromJSONString(asyncAPIDefinition);
String channelName = api.getContext();
String transports = api.getTransports();
String url = StringUtils.EMPTY;
String[] apiTransports = transports.split(",");
if (ArrayUtils.contains(apiTransports, APIConstants.WSS_PROTOCOL)
&& hostsWithSchemes.get(APIConstants.WSS_PROTOCOL) != null) {
url = hostsWithSchemes.get(APIConstants.WSS_PROTOCOL).trim()
.replace(APIConstants.WSS_PROTOCOL_URL_PREFIX, "");
}
if (ArrayUtils.contains(apiTransports, APIConstants.WSS_PROTOCOL)
&& hostsWithSchemes.get(APIConstants.WS_PROTOCOL) != null) {
if (StringUtils.isEmpty(url)) {
url = hostsWithSchemes.get(APIConstants.WS_PROTOCOL).trim()
.replace(APIConstants.WS_PROTOCOL_URL_PREFIX, "");
}
}
Aai20Server server = (Aai20Server) aai20Document.getServers().get(0);
server.url = url;
Map<String, AaiChannelItem> channels = aai20Document.channels;
Aai20ChannelItem channelDetails = null;
for (String x : channels.keySet()) {
channelDetails = (Aai20ChannelItem) channels.get(x);
aai20Document.channels.remove(x);
}
assert channelDetails != null;
channelDetails._name = channelName;
aai20Document.channels.put(channelName, channelDetails);
return Library.writeDocumentToJSONString(aai20Document);
}
public String updateAsyncAPIDefinition(String oldDefinition, API apiToUpdate) {
Aai20Document document = (Aai20Document) Library.readDocumentFromJSONString(oldDefinition);
if (document.components == null) {
document.components = document.createComponents();
}
// add scopes
if (document.components.securitySchemes == null) {
document.components.securitySchemes = new HashMap<>();
}
Aai20SecurityScheme oauth2SecurityScheme = new Aai20SecurityScheme(document.components,
APIConstants.DEFAULT_API_SECURITY_OAUTH2);
oauth2SecurityScheme.type = APIConstants.DEFAULT_API_SECURITY_OAUTH2;
if (oauth2SecurityScheme.flows == null) {
oauth2SecurityScheme.flows = new Aai20OAuthFlows(oauth2SecurityScheme);
}
if (oauth2SecurityScheme.flows.implicit == null) {
oauth2SecurityScheme.flows.implicit = new Aai20ImplicitOAuthFlow(oauth2SecurityScheme.flows);
}
oauth2SecurityScheme.flows.implicit.authorizationUrl = "http://localhost:9999";
Map<String, String> scopes = new HashMap<>();
Map<String, String> scopeBindings = new HashMap<>();
Iterator<Scope> iterator = apiToUpdate.getScopes().iterator();
while (iterator.hasNext()) {
Scope scope = iterator.next();
scopes.put(scope.getName(), scope.getDescription());
scopeBindings.put(scope.getName(), scope.getRoles());
}
oauth2SecurityScheme.flows.implicit.scopes = scopes;
Extension xScopeBindings = oauth2SecurityScheme.flows.implicit.createExtension();
xScopeBindings.name = APIConstants.SWAGGER_X_SCOPES_BINDINGS;
xScopeBindings.value = scopeBindings;
oauth2SecurityScheme.flows.implicit.addExtension(APIConstants.SWAGGER_X_SCOPES_BINDINGS, xScopeBindings);
document.components.securitySchemes.put(APIConstants.DEFAULT_API_SECURITY_OAUTH2, oauth2SecurityScheme);
return Library.writeDocumentToJSONString(document);
}
public Map<String,String> buildWSUriMapping(String apiDefinition) {
Map<String,String> wsUriMapping = new HashMap<>();
Aai20Document document = (Aai20Document) Library.readDocumentFromJSONString(apiDefinition);
for (Map.Entry<String, AaiChannelItem> entry : document.channels.entrySet()) {
AaiOperation publishOperation = entry.getValue().publish;
if (publishOperation != null) {
Extension xUriMapping = publishOperation.getExtension("x-uri-mapping");
if (xUriMapping != null) {
wsUriMapping.put("PUBLISH_" + entry.getKey(), xUriMapping.value.toString());
}
}
AaiOperation subscribeOperation = entry.getValue().subscribe;
if (subscribeOperation != null) {
Extension xUriMapping = subscribeOperation.getExtension("x-uri-mapping");
if (xUriMapping != null) {
wsUriMapping.put("SUBSCRIBE_" + entry.getKey(), xUriMapping.value.toString());
}
}
}
return wsUriMapping;
}
}
|
fixed network connection issue in schema loading
|
components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/definitions/AsyncApiParser.java
|
fixed network connection issue in schema loading
|
<ide><path>omponents/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/definitions/AsyncApiParser.java
<ide> import org.everit.json.schema.ValidationException;
<ide> import org.everit.json.schema.loader.SchemaLoader;
<ide> import org.json.JSONObject;
<add>import org.json.simple.parser.JSONParser;
<add>import org.json.simple.parser.ParseException;
<ide> import org.wso2.carbon.apimgt.api.APIDefinition;
<ide> import org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse;
<ide> import org.wso2.carbon.apimgt.api.APIManagementException;
<ide> import org.wso2.carbon.apimgt.impl.APIConstants;
<ide> import org.wso2.carbon.apimgt.impl.utils.APIUtil;
<ide>
<add>import java.net.URI;
<add>import java.net.URISyntaxException;
<ide> import java.util.ArrayList;
<ide> import java.util.Collections;
<ide> import java.util.HashMap;
<ide> import java.util.stream.Collectors;
<ide>
<ide> public class AsyncApiParser extends APIDefinition {
<add>
<add> String metaSchema = "{\n" + " \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n"
<add> + " \"$id\": \"http://json-schema.org/draft-07/schema#\",\n"
<add> + " \"title\": \"Core schema meta-schema\",\n" + " \"definitions\": {\n"
<add> + " \"schemaArray\": {\n" + " \"type\": \"array\",\n" + " \"minItems\": 1,\n"
<add> + " \"items\": { \"$ref\": \"#\" }\n" + " },\n" + " \"nonNegativeInteger\": {\n"
<add> + " \"type\": \"integer\",\n" + " \"minimum\": 0\n" + " },\n"
<add> + " \"nonNegativeIntegerDefault0\": {\n" + " \"allOf\": [\n"
<add> + " { \"$ref\": \"#/definitions/nonNegativeInteger\" },\n"
<add> + " { \"default\": 0 }\n" + " ]\n" + " },\n"
<add> + " \"simpleTypes\": {\n" + " \"enum\": [\n" + " \"array\",\n"
<add> + " \"boolean\",\n" + " \"integer\",\n" + " \"null\",\n"
<add> + " \"number\",\n" + " \"object\",\n" + " \"string\"\n"
<add> + " ]\n" + " },\n" + " \"stringArray\": {\n" + " \"type\": \"array\",\n"
<add> + " \"items\": { \"type\": \"string\" },\n" + " \"uniqueItems\": true,\n"
<add> + " \"default\": []\n" + " }\n" + " },\n"
<add> + " \"type\": [\"object\", \"boolean\"],\n" + " \"properties\": {\n" + " \"$id\": {\n"
<add> + " \"type\": \"string\",\n" + " \"format\": \"uri-reference\"\n" + " },\n"
<add> + " \"$schema\": {\n" + " \"type\": \"string\",\n" + " \"format\": \"uri\"\n"
<add> + " },\n" + " \"$ref\": {\n" + " \"type\": \"string\",\n"
<add> + " \"format\": \"uri-reference\"\n" + " },\n" + " \"$comment\": {\n"
<add> + " \"type\": \"string\"\n" + " },\n" + " \"title\": {\n"
<add> + " \"type\": \"string\"\n" + " },\n" + " \"description\": {\n"
<add> + " \"type\": \"string\"\n" + " },\n" + " \"default\": true,\n"
<add> + " \"readOnly\": {\n" + " \"type\": \"boolean\",\n" + " \"default\": false\n"
<add> + " },\n" + " \"writeOnly\": {\n" + " \"type\": \"boolean\",\n"
<add> + " \"default\": false\n" + " },\n" + " \"examples\": {\n"
<add> + " \"type\": \"array\",\n" + " \"items\": true\n" + " },\n"
<add> + " \"multipleOf\": {\n" + " \"type\": \"number\",\n"
<add> + " \"exclusiveMinimum\": 0\n" + " },\n" + " \"maximum\": {\n"
<add> + " \"type\": \"number\"\n" + " },\n" + " \"exclusiveMaximum\": {\n"
<add> + " \"type\": \"number\"\n" + " },\n" + " \"minimum\": {\n"
<add> + " \"type\": \"number\"\n" + " },\n" + " \"exclusiveMinimum\": {\n"
<add> + " \"type\": \"number\"\n" + " },\n"
<add> + " \"maxLength\": { \"$ref\": \"#/definitions/nonNegativeInteger\" },\n"
<add> + " \"minLength\": { \"$ref\": \"#/definitions/nonNegativeIntegerDefault0\" },\n"
<add> + " \"pattern\": {\n" + " \"type\": \"string\",\n" + " \"format\": \"regex\"\n"
<add> + " },\n" + " \"additionalItems\": { \"$ref\": \"#\" },\n" + " \"items\": {\n"
<add> + " \"anyOf\": [\n" + " { \"$ref\": \"#\" },\n"
<add> + " { \"$ref\": \"#/definitions/schemaArray\" }\n" + " ],\n"
<add> + " \"default\": true\n" + " },\n"
<add> + " \"maxItems\": { \"$ref\": \"#/definitions/nonNegativeInteger\" },\n"
<add> + " \"minItems\": { \"$ref\": \"#/definitions/nonNegativeIntegerDefault0\" },\n"
<add> + " \"uniqueItems\": {\n" + " \"type\": \"boolean\",\n"
<add> + " \"default\": false\n" + " },\n" + " \"contains\": { \"$ref\": \"#\" },\n"
<add> + " \"maxProperties\": { \"$ref\": \"#/definitions/nonNegativeInteger\" },\n"
<add> + " \"minProperties\": { \"$ref\": \"#/definitions/nonNegativeIntegerDefault0\" },\n"
<add> + " \"required\": { \"$ref\": \"#/definitions/stringArray\" },\n"
<add> + " \"additionalProperties\": { \"$ref\": \"#\" },\n" + " \"definitions\": {\n"
<add> + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\": \"#\" },\n"
<add> + " \"default\": {}\n" + " },\n" + " \"properties\": {\n"
<add> + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\": \"#\" },\n"
<add> + " \"default\": {}\n" + " },\n" + " \"patternProperties\": {\n"
<add> + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\": \"#\" },\n"
<add> + " \"propertyNames\": { \"format\": \"regex\" },\n" + " \"default\": {}\n"
<add> + " },\n" + " \"dependencies\": {\n" + " \"type\": \"object\",\n"
<add> + " \"additionalProperties\": {\n" + " \"anyOf\": [\n"
<add> + " { \"$ref\": \"#\" },\n"
<add> + " { \"$ref\": \"#/definitions/stringArray\" }\n" + " ]\n"
<add> + " }\n" + " },\n" + " \"propertyNames\": { \"$ref\": \"#\" },\n"
<add> + " \"const\": true,\n" + " \"enum\": {\n" + " \"type\": \"array\",\n"
<add> + " \"items\": true,\n" + " \"minItems\": 1,\n"
<add> + " \"uniqueItems\": true\n" + " },\n" + " \"type\": {\n"
<add> + " \"anyOf\": [\n" + " { \"$ref\": \"#/definitions/simpleTypes\" },\n"
<add> + " {\n" + " \"type\": \"array\",\n"
<add> + " \"items\": { \"$ref\": \"#/definitions/simpleTypes\" },\n"
<add> + " \"minItems\": 1,\n" + " \"uniqueItems\": true\n"
<add> + " }\n" + " ]\n" + " },\n"
<add> + " \"format\": { \"type\": \"string\" },\n"
<add> + " \"contentMediaType\": { \"type\": \"string\" },\n"
<add> + " \"contentEncoding\": { \"type\": \"string\" },\n" + " \"if\": { \"$ref\": \"#\" },\n"
<add> + " \"then\": { \"$ref\": \"#\" },\n" + " \"else\": { \"$ref\": \"#\" },\n"
<add> + " \"allOf\": { \"$ref\": \"#/definitions/schemaArray\" },\n"
<add> + " \"anyOf\": { \"$ref\": \"#/definitions/schemaArray\" },\n"
<add> + " \"oneOf\": { \"$ref\": \"#/definitions/schemaArray\" },\n"
<add> + " \"not\": { \"$ref\": \"#\" }\n" + " },\n" + " \"default\": true\n" + "}";
<ide>
<ide> private static final String ASYNCAPI_JSON_HYPERSCHEMA = "{\n" +
<ide> " \"title\": \"AsyncAPI 2.0.0 schema.\",\n" +
<ide>
<ide> //import and load AsyncAPI HyperSchema for JSON schema validation
<ide> JSONObject hyperSchema = new JSONObject(ASYNCAPI_JSON_HYPERSCHEMA);
<del> Schema schemaValidator = SchemaLoader.load(hyperSchema);
<ide> String protocol = StringUtils.EMPTY;
<ide>
<ide> boolean validationSuccess = false;
<ide>
<ide> //validate AsyncAPI using JSON schema validation
<ide> try {
<add> JSONParser parser = new JSONParser();
<add> org.json.simple.JSONObject json = (org.json.simple.JSONObject) parser.parse(metaSchema);
<add> SchemaLoader schemaLoader = SchemaLoader.builder().registerSchemaByURI
<add> (new URI("http://json-schema.org/draft-07/schema#"), json).schemaJson(hyperSchema).build();
<add> Schema schemaValidator = schemaLoader.load().build();
<ide> schemaValidator.validate(schemaToBeValidated);
<del> /*AaiDocument asyncApiDocument = (AaiDocument) Library.readDocumentFromJSONString(apiDefinition);
<del> validationErrorMessages = new ArrayList<>();
<del> if (asyncApiDocument.getServers().size() == 1) {
<del> if (!APIConstants.WS_PROTOCOL.equalsIgnoreCase(asyncApiDocument.getServers().get(0).protocol)) {
<del> validationErrorMessages.add("#:The protocol of the server should be 'ws' for websockets");
<del> }
<del> }
<del> if (asyncApiDocument.getServers().size() > 1) {
<del> validationErrorMessages.add("#:The AsyncAPI definition should contain only a single server for websockets");
<del> }
<del> if (asyncApiDocument.getChannels().size() > 1) {
<del> validationErrorMessages.add("#:The AsyncAPI definition should contain only a single channel for websockets");
<del> }
<del> if (validationErrorMessages.size() == 0) {
<del> validationSuccess = true;
<del> validationErrorMessages = null;
<del> }*/
<del>
<del> //AaiDocument asyncApiDocument = (AaiDocument) Library.readDocumentFromJSONString(apiDefinition);
<del> /*//Checking whether it is a websocket
<del> validationErrorMessages = new ArrayList<>();
<del> if (APIConstants.WS_PROTOCOL.equalsIgnoreCase(asyncApiDocument.getServers().get(0).protocol)) {
<del> if (APIConstants.WS_PROTOCOL.equalsIgnoreCase(protocol)) {
<del> isWebSocket = true;
<del> }
<del> }*/
<del>
<del> //validating channel count for websockets
<del> /*if (isWebSocket) {
<del> if (asyncApiDocument.getChannels().size() > 1) {
<del> validationErrorMessages.add("#:The AsyncAPI definition should contain only a single channel for websockets");
<del> }
<del> }*/
<del>
<del> /*if (validationErrorMessages.size() == 0) {
<del> validationSuccess = true;
<del> validationErrorMessages = null;
<del> }*/
<del>
<ide> validationSuccess = true;
<del>
<del> } catch (ValidationException e){
<add> } catch(ParseException e) {
<ide> //validation error messages
<del> validationErrorMessages = e.getAllMessages();
<add> // validationErrorMessages = e.getAllMessages();
<add>
<add> } catch (URISyntaxException e) {
<add> e.printStackTrace();
<ide> }
<ide>
<ide> // TODO: Validation is failing. Need to fix this. Therefore overriding the value as True.
|
|
JavaScript
|
mpl-2.0
|
49d19dbbe782403844212dc2de3d05d1e53546b7
| 0 |
slidewiki/slidewiki-platform,slidewiki/slidewiki-platform,slidewiki/slidewiki-platform
|
import createElement from 'virtual-dom/create-element';
import VNode from 'virtual-dom/vnode/vnode';
import VText from 'virtual-dom/vnode/vtext';
const convertHTML = require('html-to-vdom')({
VNode: VNode,
VText: VText
});
import $ from 'jquery';
import _ from 'lodash';
import * as jsdiff from 'diff';
//TODO CHECK meta-date changes. Title changes -> result in new revisions
const CKEditor_vars = ['span', 'var', 'em', 'strong', 'u'];
const toHTML = (string) => (
createElement(convertHTML(string))
);
const deepSearch = (obj, key) => {
if (_.has(obj, key)) // or just (key in obj)
return [obj];
// elegant:
// return _.flatten(_.map(obj, function(v) {
// return typeof v == "object" ? fn(v, key) : [];
// }), true);
// or efficient:
let res = [];
_.forEach(obj, (v) => {
if (typeof v == 'object' && (v = deepSearch(v, key)).length)
res.push.apply(res, v);
});
return res;
};
// Fn resposible for comparing 2 root IDs
const compareWrapperIds = (initSrc, finalSrc) => {
const finalRoot = toHTML(finalSrc);
const initRoot = toHTML(initSrc);
return ($(finalRoot)[0].id === $(initRoot)[0].id) ? true : false;
};
const getParentId = (finalSrc, id) => {
const finalRoot = toHTML(finalSrc);
const parent = $(finalRoot).find(`#${id}`).parent();
return parent[0].id;
};
const getClosestDiv = (finalSrc, id) => {
const finalRoot = toHTML(finalSrc);
const parent = $(finalRoot).find(`#${id}`).closest('div');
return parent[0].id;
};
const handleTEXT = (oldText, newText, source) => {
const oldStr = oldText.text,
newStr = newText.text;
let color = '',
container = null,
diff = jsdiff.diffWords(oldStr, newStr),
temp = document.createElement('div');
diff.forEach((part) => {
// green for additions, red for deletions
color = part.added ? 'ins' : part.removed ? 'del' : '';
container = document.createElement('span');
container.className = color;
container.appendChild(document.createTextNode(part.value));
temp.appendChild(container);
});
const markedText = temp.innerHTML;
source = source.replace(oldStr, markedText);
return source;
};
const handleINSERT = (el, source, finalsource) => {
const elem = createElement(el.patch);
const _id = el.patch.key;
const tag = el.patch.tagName;
let root = toHTML(source);
if(_.includes(CKEditor_vars, tag)) {
let parent = getClosestDiv(finalsource, _id);
$(root).find(`#${parent}`).addClass('modified');
} else {
let targetElement = $(elem);
// let targetElement = $(elem).children().first();
targetElement.addClass('added');
if(tag === 'li'){
let parent = getParentId(finalsource, _id);
$(root).find(`#${parent}`).append(elem);
} else {
$(root).append(elem);
}
}
source = root.outerHTML;
return source;
};
const handleREMOVE = (el, source, finalsource) => {
const _id = el.vNode.key;
const tag = el.vNode.tagName;
let root = toHTML(source);
if(_.includes(CKEditor_vars, tag)) {
let parent = getClosestDiv(finalsource, _id);
$(root).find(`#${parent}`).addClass('modified');
} else {
if(_id){
let targetElement = $(root).find(`#${_id}`);
// let targetElement = $(root).find(`#${_id}`).children().first();
targetElement.addClass('deleted');
}
}
source = root.outerHTML;
return source;
};
const handlePROPS = (node, patch, source) => {
console.log(node);
const tag = node.tagName;
let styles = patch.style;
if(styles) Object.keys(styles).forEach((key) => styles[key] === undefined ? delete styles[key] : '');
let attrs = patch.attributes;
if(attrs) Object.keys(attrs).forEach((key) => attrs[key] === undefined ? delete attrs[key] : '');
let change = (_.isEmpty(styles)) ? attrs : styles;
let key = Object.keys(change)[0];
let vals = Object.values(change)[0];
// console.log(`Patch obj: ${change}, Key: ${key}, Value: ${vals}`);
let root = createElement(convertHTML(source));
//TODO. UPDATE SEARCH. TEXT ONLY FINDS IF FIRST CHILD AND NOT DEEPLY NESTED. BY ID IS GOOD
if (key && vals) {
const _id = node.key;
if (_id) {
//[Problem] if node tags are changed. span -> h2
// let targetElement = $(root).find(`${tag}[_id='${_id}']`);
let targetElement = $(root).find(`#${_id}`);
// let targetElement = $(root).find(`#${_id}`).children().first();
targetElement.addClass('modified');
//TODO add attributes to the node [QA] use old styles or apply new styles ?
// targetElement.css(`${key}`, `${vals}`);
}
}
/*else if (patch === 'attributes') {
node.properties[`${change}`][`${key}`] = vals;
//$(root).find(`${tag}.${vals}`).addClass('modified');
}*/
source = root.outerHTML;
return source;
};
const preprocessSrc = (source, mode) => {
source = source
.replace(/ /g, ' ')
.replace(/(?:\r\n|\r|\n)/g, '')
.replace(/​/g, '');
if (mode) {
//canvas slide
const vTreeObject = convertHTML(source);
let root;
vTreeObject.length > 1 ? root = createElement(vTreeObject[0]) : root = createElement(vTreeObject);
$(root).find('br').remove();
$(root).find('.drawing-container').remove();
$(root).find('p:empty').remove();
$(root).find('span:empty').remove();
$(root).find('div:empty').remove();
// CKEditor related
$(root).find('.cke_image_resizer, .cke_widget_drag_handler_container').remove();
source = root.outerHTML;
} else {
//created slide
//wrap in a root node
source = `<div class='root'>${source}</div>`;
}
return source;
};
const setKeys = (source) => {
//apply keys for proper change detection
source = convertHTML({
getVNodeKey: function(attributes) {
return attributes.id;
}
}, source);
return source;
};
/**
* @params:
@ PatchObject:list of diff changes
@ string:initSrc - apply changes on top of this source string
@ string:mode: uploaded/created
*/
const detectnPatch = (list, initSrc, mode, finalSrc) => {
let elem;
console.group();
console.info('Changes');
list.map((el) => {
let type;
switch (el.type) {
case 0:
console.warn('NONE');
break;
case 1:
console.warn('TEXT');
const textArray = deepSearch(el, 'text');
initSrc = handleTEXT(textArray[0], textArray[1], initSrc);
break;
case 2:
console.warn('VNODE');
type = el.vNode.constructor.name;
if(type === 'VirtualText') initSrc = handleTEXT(el.vNode, el.patch.children[0], initSrc);
if(type === 'VirtualNode') initSrc = handlePROPS(el.patch, el.patch.properties, initSrc);
break;
case 3:
console.warn('WIDGET');
elem = createElement(el.vNode);
break;
case 4:
console.warn('PROPS');
initSrc = handlePROPS(el.vNode, el.patch, initSrc);
break;
case 5:
console.warn('ORDER');
elem = createElement(el.patch);
break;
case 6:
console.warn('INSERTED');
initSrc = handleINSERT(el, initSrc, finalSrc);
break;
case 7:
console.warn('REMOVE');
nodeType = el.vNode.constructor.name;
if(nodeType === 'VirtualNode') initSrc = handleREMOVE(el, initSrc, finalSrc);
break;
default:
console.warn('default');
}
});
console.groupEnd();
return initSrc;
};
module.exports = {
preprocess: preprocessSrc,
construct: detectnPatch,
setKeys: setKeys,
compareWrapperIds: compareWrapperIds
};
|
components/Deck/ContentModulesPanel/ContentDiffviewPanel/diff_funcs.js
|
import createElement from 'virtual-dom/create-element';
import VNode from 'virtual-dom/vnode/vnode';
import VText from 'virtual-dom/vnode/vtext';
const convertHTML = require('html-to-vdom')({
VNode: VNode,
VText: VText
});
import $ from 'jquery';
import _ from 'lodash';
import * as jsdiff from 'diff';
//TODO CHECK meta-date changes. Title changes -> result in new revisions
const CKEditor_vars = ['span', 'var', 'em', 'strong', 'u'];
const toHTML = (string) => (
createElement(convertHTML(string))
);
const deepSearch = (obj, key) => {
if (_.has(obj, key)) // or just (key in obj)
return [obj];
// elegant:
// return _.flatten(_.map(obj, function(v) {
// return typeof v == "object" ? fn(v, key) : [];
// }), true);
// or efficient:
let res = [];
_.forEach(obj, (v) => {
if (typeof v == 'object' && (v = deepSearch(v, key)).length)
res.push.apply(res, v);
});
return res;
};
// Fn resposible for comparing 2 root IDs
const compareWrapperIds = (initSrc, finalSrc) => {
const finalRoot = toHTML(finalSrc);
const initRoot = toHTML(initSrc);
return ($(finalRoot)[0].id === $(initRoot)[0].id) ? true : false;
};
const getParentId = (finalSrc, id) => {
const finalRoot = toHTML(finalSrc);
const parent = $(finalRoot).find(`#${id}`).parent();
return parent[0].id;
};
const getClosestDiv = (finalSrc, id) => {
const finalRoot = toHTML(finalSrc);
const parent = $(finalRoot).find(`#${id}`).closest('div');
return parent[0].id;
};
const handleTEXT = (oldText, newText, source) => {
const oldStr = oldText.text,
newStr = newText.text;
let color = '',
container = null,
diff = jsdiff.diffWords(oldStr, newStr),
temp = document.createElement('div');
diff.forEach((part) => {
// green for additions, red for deletions
color = part.added ? 'ins' : part.removed ? 'del' : '';
container = document.createElement('span');
container.className = color;
container.appendChild(document.createTextNode(part.value));
temp.appendChild(container);
});
const markedText = temp.innerHTML;
source = source.replace(oldStr, markedText);
return source;
};
const getParentId = (finalsource, id) => {
const finalRoot = createElement(convertHTML(finalsource));
const parent = $(finalRoot).find(`#${id}`).parent();
return parent[0].id;
};
const handleINSERT = (el, source, finalsource) => {
const elem = createElement(el.patch);
const tag = el.patch.tagName;
const _id = el.patch.key;
let targetElement = $(elem);
// let targetElement = $(elem).children().first();
targetElement.addClass('added');
let root = createElement(convertHTML(source));
if(tag === 'li'){
let parent = getParentId(finalsource, _id);
$(root).find(`#${parent}`).append(elem);
} else {
$(root).append(elem);
}
source = root.outerHTML;
return source;
};
const handleREMOVE = (el, source, finalsource) => {
const _id = el.vNode.key;
const tag = el.vNode.tagName;
let root = toHTML(source);
if(_.includes(CKEditor_vars, tag)) {
let parent = getClosestDiv(finalsource, _id);
$(root).find(`#${parent}`).addClass('modified');
} else {
if(_id){
let targetElement = $(root).find(`#${_id}`);
// let targetElement = $(root).find(`#${_id}`).children().first();
targetElement.addClass('deleted');
}
}
source = root.outerHTML;
return source;
};
const handlePROPS = (node, patch, source) => {
console.log(node);
const tag = node.tagName;
let styles = patch.style;
if(styles) Object.keys(styles).forEach((key) => styles[key] === undefined ? delete styles[key] : '');
let attrs = patch.attributes;
if(attrs) Object.keys(attrs).forEach((key) => attrs[key] === undefined ? delete attrs[key] : '');
let change = (_.isEmpty(styles)) ? attrs : styles;
let key = Object.keys(change)[0];
let vals = Object.values(change)[0];
// console.log(`Patch obj: ${change}, Key: ${key}, Value: ${vals}`);
let root = createElement(convertHTML(source));
//TODO. UPDATE SEARCH. TEXT ONLY FINDS IF FIRST CHILD AND NOT DEEPLY NESTED. BY ID IS GOOD
if (key && vals) {
const _id = node.key;
if (_id) {
//[Problem] if node tags are changed. span -> h2
// let targetElement = $(root).find(`${tag}[_id='${_id}']`);
let targetElement = $(root).find(`#${_id}`);
// let targetElement = $(root).find(`#${_id}`).children().first();
targetElement.addClass('modified');
//TODO add attributes to the node [QA] use old styles or apply new styles ?
// targetElement.css(`${key}`, `${vals}`);
}
}
/*else if (patch === 'attributes') {
node.properties[`${change}`][`${key}`] = vals;
//$(root).find(`${tag}.${vals}`).addClass('modified');
}*/
source = root.outerHTML;
return source;
};
const preprocessSrc = (source, mode) => {
source = source
.replace(/ /g, ' ')
.replace(/(?:\r\n|\r|\n)/g, '')
.replace(/​/g, '');
if (mode) {
//canvas slide
const vTreeObject = convertHTML(source);
let root;
vTreeObject.length > 1 ? root = createElement(vTreeObject[0]) : root = createElement(vTreeObject);
$(root).find('br').remove();
$(root).find('.drawing-container').remove();
$(root).find('p:empty').remove();
$(root).find('span:empty').remove();
$(root).find('div:empty').remove();
// CKEditor related
$(root).find('.cke_image_resizer, .cke_widget_drag_handler_container').remove();
source = root.outerHTML;
} else {
//created slide
//wrap in a root node
source = `<div class='root'>${source}</div>`;
}
return source;
};
const setKeys = (source) => {
//apply keys for proper change detection
source = convertHTML({
getVNodeKey: function(attributes) {
return attributes.id;
}
}, source);
return source;
};
/**
* @params:
@ PatchObject:list of diff changes
@ string:initSrc - apply changes on top of this source string
@ string:mode: uploaded/created
*/
const detectnPatch = (list, initSrc, mode, finalSrc) => {
let elem;
console.group();
console.info('Changes');
list.map((el) => {
let type;
switch (el.type) {
case 0:
console.warn('NONE');
break;
case 1:
console.warn('TEXT');
const textArray = deepSearch(el, 'text');
initSrc = handleTEXT(textArray[0], textArray[1], initSrc);
break;
case 2:
console.warn('VNODE');
type = el.vNode.constructor.name;
if(type === 'VirtualText') initSrc = handleTEXT(el.vNode, el.patch.children[0], initSrc);
if(type === 'VirtualNode') initSrc = handlePROPS(el.patch, el.patch.properties, initSrc);
break;
case 3:
console.warn('WIDGET');
elem = createElement(el.vNode);
break;
case 4:
console.warn('PROPS');
initSrc = handlePROPS(el.vNode, el.patch, initSrc);
break;
case 5:
console.warn('ORDER');
elem = createElement(el.patch);
break;
case 6:
console.warn('INSERTED');
initSrc = handleINSERT(el, initSrc, finalSrc);
break;
case 7:
console.warn('REMOVE');
nodeType = el.vNode.constructor.name;
if(nodeType === 'VirtualNode') initSrc = handleREMOVE(el, initSrc, finalSrc);
break;
default:
console.warn('default');
}
});
console.groupEnd();
return initSrc;
};
module.exports = {
preprocess: preprocessSrc,
construct: detectnPatch,
setKeys: setKeys,
compareWrapperIds: compareWrapperIds
};
|
update handleINSERT function
- insert li’s into correct lists
- check for CKeditor tags
|
components/Deck/ContentModulesPanel/ContentDiffviewPanel/diff_funcs.js
|
update handleINSERT function
|
<ide><path>omponents/Deck/ContentModulesPanel/ContentDiffviewPanel/diff_funcs.js
<ide> return source;
<ide> };
<ide>
<del>const getParentId = (finalsource, id) => {
<del> const finalRoot = createElement(convertHTML(finalsource));
<del> const parent = $(finalRoot).find(`#${id}`).parent();
<del>
<del> return parent[0].id;
<del>};
<del>
<ide> const handleINSERT = (el, source, finalsource) => {
<del>
<ide> const elem = createElement(el.patch);
<add> const _id = el.patch.key;
<ide> const tag = el.patch.tagName;
<del> const _id = el.patch.key;
<del>
<del> let targetElement = $(elem);
<del> // let targetElement = $(elem).children().first();
<del> targetElement.addClass('added');
<del> let root = createElement(convertHTML(source));
<del>
<del> if(tag === 'li'){
<del> let parent = getParentId(finalsource, _id);
<del> $(root).find(`#${parent}`).append(elem);
<add> let root = toHTML(source);
<add>
<add> if(_.includes(CKEditor_vars, tag)) {
<add> let parent = getClosestDiv(finalsource, _id);
<add> $(root).find(`#${parent}`).addClass('modified');
<ide> } else {
<del> $(root).append(elem);
<add> let targetElement = $(elem);
<add> // let targetElement = $(elem).children().first();
<add> targetElement.addClass('added');
<add>
<add> if(tag === 'li'){
<add> let parent = getParentId(finalsource, _id);
<add> $(root).find(`#${parent}`).append(elem);
<add> } else {
<add> $(root).append(elem);
<add> }
<ide> }
<ide>
<ide> source = root.outerHTML;
|
|
Java
|
apache-2.0
|
d6cc16eac52f1199f0e32c01bd7550f0eb5f256e
| 0 |
secdec/zap-extensions,zapbot/zap-extensions,psiinon/zap-extensions,psiinon/zap-extensions,psiinon/zap-extensions,zaproxy/zap-extensions,secdec/zap-extensions,kingthorin/zap-extensions,veggiespam/zap-extensions,veggiespam/zap-extensions,zapbot/zap-extensions,secdec/zap-extensions,denniskniep/zap-extensions,kingthorin/zap-extensions,thc202/zap-extensions,psiinon/zap-extensions,kingthorin/zap-extensions,denniskniep/zap-extensions,kingthorin/zap-extensions,zapbot/zap-extensions,thc202/zap-extensions,secdec/zap-extensions,zaproxy/zap-extensions,kingthorin/zap-extensions,veggiespam/zap-extensions,psiinon/zap-extensions,veggiespam/zap-extensions,zapbot/zap-extensions,psiinon/zap-extensions,zaproxy/zap-extensions,thc202/zap-extensions,secdec/zap-extensions,denniskniep/zap-extensions,zapbot/zap-extensions,denniskniep/zap-extensions,zapbot/zap-extensions,thc202/zap-extensions,denniskniep/zap-extensions,denniskniep/zap-extensions,zaproxy/zap-extensions,secdec/zap-extensions,zaproxy/zap-extensions,veggiespam/zap-extensions,zaproxy/zap-extensions,secdec/zap-extensions,thc202/zap-extensions,veggiespam/zap-extensions,kingthorin/zap-extensions,thc202/zap-extensions
|
/*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2012 The ZAP development team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.zaproxy.zap.extension.pscanrulesAlpha;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.htmlparser.jericho.Source;
import org.apache.log4j.Logger;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.core.scanner.Alert;
import org.parosproxy.paros.network.HttpMessage;
import org.zaproxy.zap.extension.pscan.PassiveScanThread;
import org.zaproxy.zap.extension.pscan.PluginPassiveScanner;
/**
* A class to passively scan response for application Source Code, using source code signatures
* @author [email protected]
*
*/
public class SourceCodeDisclosureScanner extends PluginPassiveScanner {
private PassiveScanThread parent = null;
private static final Logger log = Logger.getLogger(SourceCodeDisclosureScanner.class);
/**
* a consistently ordered map of: a regular expression pattern to the Programming language (string) to which the pattern most likely corresponds
*/
static Map <Pattern, String> languagePatterns = new LinkedHashMap <Pattern, String> ();
static {
//PHP
languagePatterns.put(Pattern.compile("<\\?php\\s*.+?;\\s*\\?>", Pattern.MULTILINE | Pattern.DOTALL), "PHP"); //PHP standard tags
languagePatterns.put(Pattern.compile("<\\?=\\s*.+?\\s*\\?>", Pattern.MULTILINE | Pattern.DOTALL), "PHP"); //PHP "echo short tag"
//languagePatterns.put(Pattern.compile("<\\?\\s*.+?\\s*\\?>", Pattern.MULTILINE | Pattern.DOTALL), "PHP"); //PHP "short tag", need short_open_tag enabled in php.ini - raises false positives with XML tags..
//languagePatterns.put(Pattern.compile("phpinfo\\s*\\(\\s*\\)"), "PHP"); //features in "/index.php?=PHPB8B5F2A0-3C92-11d3-A3A9-4C7B08C10000", which is not a Source Code Disclosure issue.
languagePatterns.put(Pattern.compile("\\$_POST\\s*\\["), "PHP");
languagePatterns.put(Pattern.compile("\\$_GET\\s*\\["), "PHP");
languagePatterns.put(Pattern.compile("<\\?php\\s*.+?;", Pattern.MULTILINE | Pattern.DOTALL), "PHP"); //PHP standard tags, without a closing tag (yes, it's apparently valid, and ZAP uses it!!)
//JSP (Java based)
languagePatterns.put(Pattern.compile("<%@\\s*page\\s+.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "JSP");
languagePatterns.put(Pattern.compile("<%@\\s*include.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "JSP");
languagePatterns.put(Pattern.compile("<%@\\s*taglib.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "JSP");
languagePatterns.put(Pattern.compile("<jsp:directive\\.page.+?>", Pattern.MULTILINE | Pattern.DOTALL), "JSP");
languagePatterns.put(Pattern.compile("<jsp:directive\\.include.+?>", Pattern.MULTILINE | Pattern.DOTALL), "JSP");
languagePatterns.put(Pattern.compile("<jsp:directive\\.taglib.+?>", Pattern.MULTILINE | Pattern.DOTALL), "JSP");
//Servlet (Java based)
languagePatterns.put(Pattern.compile("import\\s+javax\\.servlet\\.http\\.HttpServlet\\s*;"), "Servlet");
languagePatterns.put(Pattern.compile("import\\s+javax\\.servlet\\.http\\.\\*\\s*;"), "Servlet");
languagePatterns.put(Pattern.compile("@WebServlet\\s*\\(\\s*\"/[a-z0-9]+\"\\s*\\)", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "Servlet");
languagePatterns.put(Pattern.compile("public\\s+class\\s+[a-z0-9]+\\s+extends\\s+(javax\\.servlet\\.http\\.)?HttpServlet", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "Servlet");
languagePatterns.put(Pattern.compile("public\\s+void\\s+doGet\\s*\\(\\s*HttpServletRequest\\s+[a-z0-9]+\\s*,\\s*HttpServletResponse\\s+[a-z0-9]+\\s*\\)", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "Servlet");
languagePatterns.put(Pattern.compile("public\\s+void\\s+doPost\\s*\\(\\s*HttpServletRequest\\s+[a-z0-9]+\\s*,\\s*HttpServletResponse\\s+[a-z0-9]+\\s*\\)", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "Servlet");
//Java
languagePatterns.put(Pattern.compile("^package\\s+[a-z0-9.]+;", Pattern.CASE_INSENSITIVE), "Java");
languagePatterns.put(Pattern.compile("^import\\s+[a-z0-9.]+;", Pattern.CASE_INSENSITIVE), "Java");
languagePatterns.put(Pattern.compile("class\\s+[a-z0-9]+\\s*\\{.+\\}", Pattern.MULTILINE | Pattern.DOTALL ), "Java");
languagePatterns.put(Pattern.compile("public\\s+static\\s+void\\s+main\\s*\\(\\s*String\\s+[a-z0-9]+\\s*\\[\\s*\\]\\s*\\)\\s*\\{", Pattern.MULTILINE | Pattern.DOTALL), "Java");
languagePatterns.put(Pattern.compile("public\\s+static\\s+void\\s+main\\s*\\(\\s*String\\s*\\[\\s*\\]\\s*[a-z0-9]+\\s*\\)\\s*\\{", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "Java");
//ASP
languagePatterns.put(Pattern.compile("On\\s+Error\\s+Resume\\s+Next", Pattern.CASE_INSENSITIVE), "ASP");
languagePatterns.put(Pattern.compile("Server.CreateObject\\s*\\(\\s*\"[a-z0-9.]+\"\\s*\\)", Pattern.CASE_INSENSITIVE), "ASP");
languagePatterns.put(Pattern.compile("Request.QueryString\\s*\\(\\s*\"[a-z0-9]+\"\\s*\\)", Pattern.CASE_INSENSITIVE), "ASP");
languagePatterns.put(Pattern.compile("If\\s*\\(\\s*Err.Number\\s*.+\\)\\s*Then", Pattern.CASE_INSENSITIVE), "ASP");
languagePatterns.put(Pattern.compile("<%@\\s+LANGUAGE\\s*=\\s*\"VBSCRIPT\"\\s*%>", Pattern.CASE_INSENSITIVE), "ASP");
//ASP.NET
languagePatterns.put(Pattern.compile("<%@\\s+Page.*?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<script\\s+runat\\s*=\\s*\"", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%Assembly.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%Control.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%Implements.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%MasterType.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%Master.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%Page.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%OutputCache.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%PreviousPageType.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%Reference.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%Register.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("@RenderPage\\s*\\(\\s*\".*?\"\\)", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("@RenderBody\\s*\\(\\s*\\)", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("@RenderSection\\s*\\(\\s*\".+?\"\\s*\\)", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
//languagePatterns.put(Pattern.compile("@\\{[\\u0000-\\u007F]{5,}?\\}", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET"); //Too many false positives
//languagePatterns.put(Pattern.compile("@if\\s*\\(.+?\\)\\s*\\{", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET"); //false positives with IE conditional compilation directives in JavaScript
languagePatterns.put(Pattern.compile("Request\\s*\\[\".+?\"\\]", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("@foreach\\s*", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("Database.Open\\s*\\(\\s*\"", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("db.Query\\s*\\(\\s*\"", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("@switch\\s*\\(.+?\\)\\s*\\{", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("^\\s*<asp:Menu"), "ASP.NET");
languagePatterns.put(Pattern.compile("^\\s*<asp:TreeView"), "ASP.NET");
languagePatterns.put(Pattern.compile("^\\s*<asp:SiteMapPath"), "ASP.NET");
//C#
languagePatterns.put(Pattern.compile("^<%@\\s+Page\\s+Language\\s*=\\s*\"C#\""), "C#");
languagePatterns.put(Pattern.compile("^using\\s+System\\s*;"), "C#");
languagePatterns.put(Pattern.compile("^namespace\\s+[a-z.]+\\s*\\{", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "C#");
languagePatterns.put(Pattern.compile("^static\\s+void\\s+Main\\s*\\(\\s*string\\s*\\[\\s*\\]\\s*[a-z0-9]+\\s*\\)", Pattern.MULTILINE ), "C#");
//generates false positives for JavaScript code, which also uses "var" to declare variables.
//languagePatterns.put(Pattern.compile("var\\s+[a-z]+?\\s*=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL), "C#");
languagePatterns.put(Pattern.compile("@for\\s*\\(\\s*var\\s+", Pattern.MULTILINE | Pattern.DOTALL), "C#");
languagePatterns.put(Pattern.compile("@foreach\\s*\\(\\s*var\\s+", Pattern.MULTILINE | Pattern.DOTALL), "C#");
//VB.NET
languagePatterns.put(Pattern.compile("^Imports\\s+System[a-zA-Z0-9.]*\\s*$"), "VB.NET");
languagePatterns.put(Pattern.compile("^dim\\s+[a-z0-9]+\\s*=", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "VB.NET");
languagePatterns.put(Pattern.compile("@for\\s+[a-z0-9]+\\s*=\\s*[0-9]+\\s+to\\s+[0-9]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "VB.NET");
languagePatterns.put(Pattern.compile("@for\\s+each\\s+[a-z0-9]+\\s+in\\s+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "VB.NET");
languagePatterns.put(Pattern.compile("@Select\\s+Case", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "VB.NET");
//languagePatterns.put(Pattern.compile("end\\s+select", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "VB.NET"); //False positives. Insufficiently anchored.
//SQL (ie, generic Structured Query Language, not "Microsoft SQL Server", which some incorrectly refer to as just "SQL")
//languagePatterns.put(Pattern.compile("select\\s+[a-z0-9., \"\'()*]+\\s+from\\s+[a-z0-9., ]+\\s+where\\s+", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("select\\s+[a-z0-9., \"\'()*]+\\s+from\\s+[a-z0-9._, ]+", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("select\\s+@@[a-z]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("insert\\s+into\\s+[a-z0-9._]+\\s+values\\s*\\(", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("insert\\s+into\\s+[a-z0-9._]+\\s*\\([a-z0-9_, \\t]+\\)\\s+values\\s*\\(", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
//languagePatterns.put(Pattern.compile("insert\\s+into\\s+[a-z0-9._]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("insert\\s+[a-z0-9._]+\\s+\\(.+?\\)\\s+values\\s*\\(.+?\\)", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("insert\\s+[a-z0-9._]+\\s+values\\s*\\(.+?\\)", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("insert\\s+[a-z0-9._]+\\s+select\\s+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("update\\s+[a-z0-9._]+\\s+set\\s+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("update\\s+[a-z0-9._]+\\s+[a-z0-9_]+\\s+set\\s+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL"); //allow a table alias
languagePatterns.put(Pattern.compile("delete\\s+from\\s+[a-z0-9._]+(\\s+where\\s+)?", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
//causes false positives on normal JavaScript: delete B.fn;
//languagePatterns.put(Pattern.compile("delete\\s+[a-z0-9._]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("truncate\\s+table\\s+[a-z0-9._]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("create\\s+database\\s+[a-z0-9._]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
//languagePatterns.put(Pattern.compile("create\\s+table\\s+[a-z0-9.]+\\s+\\(.+?\\)", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("create\\s+table\\s+(if\\s+not\\s+exists\\s+)?[a-z0-9._]+\\s*\\([^)]+\\)", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("create\\s+view\\s+[a-z0-9._]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("create\\s+index\\s+[a-z0-9._]+\\s+on\\s+[a-z0-9._]+\\s*\\(", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("create\\s+procedure\\s+[a-z0-9._]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("create\\s+function\\s+[a-z0-9._]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("drop\\s+database\\s+[a-z0-9._]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("drop\\s+table\\s+[a-z0-9._]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("drop\\s+view\\s+[a-z0-9._]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("drop\\s+index\\s+[a-z0-9._]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("drop\\s+procedure\\s+[a-z0-9._]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("drop\\s+function\\s+[a-z0-9._]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("grant\\s+[a-z]+\\s+on\\s+[a-z0-9._]+\\s+to\\s+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("revoke\\s+[a-z0-9 (),]+\\s+on\\s+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
//Perl
languagePatterns.put(Pattern.compile("^#!/usr/bin/perl"), "Perl");
languagePatterns.put(Pattern.compile("^use\\s+strict\\s*;\\s*$"), "Perl");
languagePatterns.put(Pattern.compile("^use\\s+warnings\\s*;\\s*$"), "Perl");
languagePatterns.put(Pattern.compile("^use\\s+[A-Za-z:]+\\s*;\\s*$"), "Perl");
languagePatterns.put(Pattern.compile("foreach\\s+my\\s+\\$[a-z0-9]+\\s*\\(", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Perl");
//languagePatterns.put(Pattern.compile("next unless"), "Perl");
languagePatterns.put(Pattern.compile("^\\s*my\\s+\\$[a-z0-9]+\\s*", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Perl");
languagePatterns.put(Pattern.compile("^\\s*my\\s+%[a-z0-9]+\\s*", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Perl");
languagePatterns.put(Pattern.compile("^\\s*my\\s+@[a-z0-9]+\\s*", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Perl");
languagePatterns.put(Pattern.compile("@[a-z0-9]+\\s+[a-z0-9]+\\s*=\\s*\\(", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Perl");
languagePatterns.put(Pattern.compile("\\$#[a-z0-9]{4,}", Pattern.CASE_INSENSITIVE), "Perl");
languagePatterns.put(Pattern.compile("\\$[a-z0-9]+\\s*\\{'[a-z0-9]+'\\}\\s*=\\s*", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Perl");
languagePatterns.put(Pattern.compile("die\\s+\".*?\\$!.*?\""), "Perl");
//Objective C (probably an iPhone app)
languagePatterns.put(Pattern.compile("^#\\s+import\\s+<[a-zA-Z0-9/.]+>", Pattern.MULTILINE), "Objective C");
languagePatterns.put(Pattern.compile("^#\\s+import\\s+\"[a-zA-Z0-9/.]+\"", Pattern.MULTILINE), "Objective C");
//languagePatterns.put(Pattern.compile("^\\[+[a-zA-Z0-9 :]{5,}\\]", Pattern.MULTILINE), "Objective C"); //false positives for INI files.
languagePatterns.put(Pattern.compile("@interface\\s*[a-zA-Z0-9]+\\s*:\\s*[a-zA-Z0-9]+\\s*\\{"), "Objective C");
//languagePatterns.put(Pattern.compile("\\+\\s*\\(\\s*[a-z]{5,}\\s*\\)"), "Objective C");
//languagePatterns.put(Pattern.compile("\\-\\s*\\(\\s*[a-z]{5,}\\s*\\)"), "Objective C");
languagePatterns.put(Pattern.compile("@implementation\\s+[a-z]"), "Objective C");
languagePatterns.put(Pattern.compile("@interface\\s+[a-zA-Z0-9]+\\s*:\\s*[a-zA-Z0-9]+\\s*<[a-zA-Z0-9]+>"), "Objective C");
languagePatterns.put(Pattern.compile("@protocol\\s+[a-zA-Z0-9]+"), "Objective C");
//languagePatterns.put(Pattern.compile("@public"), "Objective C"); //prone to false positives
//languagePatterns.put(Pattern.compile("@private"), "Objective C"); //prone to false positives
//languagePatterns.put(Pattern.compile("@property"), "Objective C"); //prone to false positives
languagePatterns.put(Pattern.compile("@end\\s*$"), "Objective C"); //anchor to $ to reduce false positives in C++ code comments.
languagePatterns.put(Pattern.compile("@synthesize"), "Objective C");
//C
//do not anchor the start pf the # lines with ^. This causes the match to fail. Why??
languagePatterns.put(Pattern.compile("#include\\s+<[a-zA-Z0-9/]+\\.h>"), "C");
languagePatterns.put(Pattern.compile("#include\\s+\"[a-zA-Z0-9/]+\\.h\""), "C");
languagePatterns.put(Pattern.compile("#define\\s+.+?$"), "C");
languagePatterns.put(Pattern.compile("#ifndef\\s+.+?$"), "C");
languagePatterns.put(Pattern.compile("#endif\\s*$"), "C");
languagePatterns.put(Pattern.compile("\\s*char\\s*\\*\\*\\s*[a-zA-Z0-9_]+\\s*;"), "C");
//C++
languagePatterns.put(Pattern.compile("#include\\s+<iostream\\.h>"), "C++");
languagePatterns.put(Pattern.compile("^[a-z0-9]+::[a-z0-9]+\\s*\\(\\s*\\).*?\\{.+?\\}", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "C++"); //constructor
languagePatterns.put(Pattern.compile("(std::)?cout\\s*<<\\s*\".+?\"\\s*;"), "C++");
//Shell Script
languagePatterns.put(Pattern.compile("^#!/bin/[a-z]*sh"), "Shell Script");
//Node.js
languagePatterns.put(Pattern.compile("^#!/usr/bin/env\\s+node"), "Node.js");
//Python
languagePatterns.put(Pattern.compile("#!/usr/bin/python.*$"), "Python");
languagePatterns.put(Pattern.compile("#!/usr/bin/env\\s+python"), "Python");
languagePatterns.put(Pattern.compile("^\\s*def\\s+[a-z0-9]+\\s*\\(\\s*[a-z0-9]+\\s*\\)\\s*:", Pattern.CASE_INSENSITIVE), "Python");
languagePatterns.put(Pattern.compile("\\s*for\\s+[a-z0-9]+\\s+in\\s+[a-z0-9]+:", Pattern.CASE_INSENSITIVE), "Python");
languagePatterns.put(Pattern.compile("^\\s*try\\s*:", Pattern.CASE_INSENSITIVE), "Python");
languagePatterns.put(Pattern.compile("^\\s*except\\s*:", Pattern.CASE_INSENSITIVE), "Python");
languagePatterns.put(Pattern.compile("^\\s*def\\s+main\\s*\\(\\s*\\)\\s*:", Pattern.CASE_INSENSITIVE), "Python");
//Ruby
languagePatterns.put(Pattern.compile("^\\s*require\\s+\".+?\"\\s*$", Pattern.CASE_INSENSITIVE), "Ruby");
languagePatterns.put(Pattern.compile("^\\s*describe\\s+[a-z0-9:]+\\s+do", Pattern.CASE_INSENSITIVE), "Ruby");
languagePatterns.put(Pattern.compile("^\\s*class\\s+[a-z0-9]+\\s+<\\s*[a-z0-9:]+", Pattern.CASE_INSENSITIVE), "Ruby");
languagePatterns.put(Pattern.compile("^\\s*def\\s+[a-z0-9]+\\s*.+?^\\s*end\\s*$", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "Ruby");
languagePatterns.put(Pattern.compile("@@active\\s*=\\s*", Pattern.CASE_INSENSITIVE), "Ruby");
//Cold Fusion
languagePatterns.put(Pattern.compile("<cfoutput"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfset"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfexecute"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfexit"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfcomponent"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cffunction"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfreturn"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfargument"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfscript"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfloop"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfquery"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfqueryparam"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfdump"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfloop"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfif"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfelseif"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfelse"), "Cold Fusion");
languagePatterns.put(Pattern.compile("writeOutput\\s*\\("), "Cold Fusion");
//languagePatterns.put(Pattern.compile("component\\s*\\{"), "Cold Fusion"); //cannot find original example, and too prone to false positives.
//Visual FoxPro / ActiveVFP
languagePatterns.put(Pattern.compile("oRequest\\.querystring\\s*\\(\\s*\"[a-z0-9]+\"\\s*\\)", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE),"ActiveVFP");
languagePatterns.put(Pattern.compile("define\\s+class\\s+[a-z0-9]+\\s+as\\s+[a-z0-9]+", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE),"ActiveVFP");
languagePatterns.put(Pattern.compile("for\\s+[a-z0-9]+\\s*=\\s*[0-9]+\\s+to\\s+[0-9]+.+?\\s+endfor", Pattern.CASE_INSENSITIVE),"ActiveVFP");
languagePatterns.put(Pattern.compile("do\\s+while\\s+.+?\\s+enddo", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE),"ActiveVFP");
languagePatterns.put(Pattern.compile("if\\s+.+?\\s+endif", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE),"ActiveVFP");
languagePatterns.put(Pattern.compile("do\\s+case\\s+case\\s+.+?\\s+endcase", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE),"ActiveVFP");
languagePatterns.put(Pattern.compile("for\\s+each\\s+.+?\\s+endfor", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE),"ActiveVFP");
//languagePatterns.put(Pattern.compile("oRequest"),"ActiveVFP"); //prone to false positives
//languagePatterns.put(Pattern.compile("oResponse"),"ActiveVFP"); //prone to false positives
//languagePatterns.put(Pattern.compile("oSession"),"ActiveVFP"); //prone to false positives
//Pascal
languagePatterns.put(Pattern.compile("^program\\s+[a-z0-9]+;.*?begin.+?end", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "Pascal");
//Latex (yes, this is a programming language)
languagePatterns.put(Pattern.compile("\\documentclass\\s*\\{[a-z]+\\}", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Latex");
languagePatterns.put(Pattern.compile("\\begin\\s*\\{[a-z]+\\}", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Latex");
languagePatterns.put(Pattern.compile("\\end\\s*\\{[a-z]+\\}", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Latex");
//Actionscript 3
languagePatterns.put(Pattern.compile("package\\s+[a-z0-9.]+\\s*\\{(.*import\\s+[a-z0-9.]+\\s*;)?.+\\}", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE),"ActionScript 3.0");
//TODO: consider sorting the patterns by decreasing pattern length, so more specific patterns are tried before more general patterns
}
/**
* Prefix for internationalized messages used by this rule
*/
private static final String MESSAGE_PREFIX = "pscanalpha.sourcecodedisclosure.";
/**
* construct the class, and register for i18n
*/
/**
* gets the name of the scanner
* @return
*/
@Override
public String getName() {
return Constant.messages.getString(MESSAGE_PREFIX + "name");
}
/**
* scans the HTTP request sent (in fact, does nothing)
* @param msg
* @param id
*/
@Override
public void scanHttpRequestSend(HttpMessage msg, int id) {
// do nothing
}
/**
* scans the HTTP response for Source Code signatures
* @param msg
* @param id
* @param source unused
*/
@Override
public void scanHttpResponseReceive(HttpMessage msg, int id, Source source) {
//get the body contents as a String, so we can match against it
String responsebody = msg.getResponseBody().toString();
//try each of the patterns in turn against the response.
//we deliberately do not assume that only status 200 responses will contain source code.
String evidence = null;
String programminglanguage = null;
Iterator<Pattern> patternIterator = languagePatterns.keySet().iterator();
while (patternIterator.hasNext()) {
Pattern languagePattern = patternIterator.next();
programminglanguage = languagePatterns.get(languagePattern);
Matcher matcher = languagePattern.matcher(responsebody);
if (matcher.find()) {
evidence = matcher.group();
if (log.isDebugEnabled()) {
log.debug("Passive Source Code Disclosure on pattern "+ languagePattern + ", evidence: "+ evidence);
}
break; //use the first match
}
}
if (evidence!=null && evidence.length() > 0) {
//we found something
Alert alert = new Alert(getPluginId(), Alert.RISK_HIGH, Alert.CONFIDENCE_MEDIUM, getName() + " - "+ programminglanguage );
alert.setDetail(
getDescription() + " - "+ programminglanguage,
msg.getRequestHeader().getURI().toString(),
"", //param
"", //attack
getExtraInfo(msg, evidence), //other info
getSolution(),
getReference(),
evidence,
540, //Information Exposure Through Source Code
13, //WASC-13: Information Leakage
msg);
parent.raiseAlert(id, alert);
}
}
/**
* sets the parent
* @param parent
*/
@Override
public void setParent(PassiveScanThread parent) {
this.parent = parent;
}
/**
* get the id of the scanner
* @return
*/
@Override
public int getPluginId() {
return 10099;
}
/**
* get the description of the alert
* @return
*/
private String getDescription() {
return Constant.messages.getString(MESSAGE_PREFIX + "desc");
}
/**
* get the solution for the alert
* @return
*/
private String getSolution() {
return Constant.messages.getString(MESSAGE_PREFIX + "soln");
}
/**
* gets references for the alert
* @return
*/
private String getReference() {
return Constant.messages.getString(MESSAGE_PREFIX + "refs");
}
/**
* gets extra information associated with the alert
* @param msg
* @param arg0
* @return
*/
private String getExtraInfo(HttpMessage msg, String arg0) {
return Constant.messages.getString(MESSAGE_PREFIX + "extrainfo", arg0);
}
}
|
src/org/zaproxy/zap/extension/pscanrulesAlpha/SourceCodeDisclosureScanner.java
|
/*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2012 The ZAP development team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.zaproxy.zap.extension.pscanrulesAlpha;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.htmlparser.jericho.Source;
import org.apache.log4j.Logger;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.core.scanner.Alert;
import org.parosproxy.paros.network.HttpMessage;
import org.zaproxy.zap.extension.pscan.PassiveScanThread;
import org.zaproxy.zap.extension.pscan.PluginPassiveScanner;
/**
* A class to passively scan response for application Source Code, using source code signatures
* @author [email protected]
*
*/
public class SourceCodeDisclosureScanner extends PluginPassiveScanner {
private PassiveScanThread parent = null;
private static final Logger log = Logger.getLogger(SourceCodeDisclosureScanner.class);
/**
* a consistently ordered map of: a regular expression pattern to the Programming language (string) to which the pattern most likely corresponds
*/
static Map <Pattern, String> languagePatterns = new LinkedHashMap <Pattern, String> ();
static {
//PHP
languagePatterns.put(Pattern.compile("<\\?php\\s*.+?;\\s*\\?>", Pattern.MULTILINE | Pattern.DOTALL), "PHP"); //PHP standard tags
languagePatterns.put(Pattern.compile("<\\?=\\s*.+?\\s*\\?>", Pattern.MULTILINE | Pattern.DOTALL), "PHP"); //PHP "echo short tag"
//languagePatterns.put(Pattern.compile("<\\?\\s*.+?\\s*\\?>", Pattern.MULTILINE | Pattern.DOTALL), "PHP"); //PHP "short tag", need short_open_tag enabled in php.ini - raises false positives with XML tags..
//languagePatterns.put(Pattern.compile("phpinfo\\s*\\(\\s*\\)"), "PHP"); //features in "/index.php?=PHPB8B5F2A0-3C92-11d3-A3A9-4C7B08C10000", which is not a Source Code Disclosure issue.
languagePatterns.put(Pattern.compile("\\$_POST\\s*\\["), "PHP");
languagePatterns.put(Pattern.compile("\\$_GET\\s*\\["), "PHP");
languagePatterns.put(Pattern.compile("<\\?php\\s*.+?;", Pattern.MULTILINE | Pattern.DOTALL), "PHP"); //PHP standard tags, without a closing tag (yes, it's apparently valid, and ZAP uses it!!)
//JSP (Java based)
languagePatterns.put(Pattern.compile("<%@\\s*page\\s+.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "JSP");
languagePatterns.put(Pattern.compile("<%@\\s*include.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "JSP");
languagePatterns.put(Pattern.compile("<%@\\s*taglib.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "JSP");
languagePatterns.put(Pattern.compile("<jsp:directive\\.page.+?>", Pattern.MULTILINE | Pattern.DOTALL), "JSP");
languagePatterns.put(Pattern.compile("<jsp:directive\\.include.+?>", Pattern.MULTILINE | Pattern.DOTALL), "JSP");
languagePatterns.put(Pattern.compile("<jsp:directive\\.taglib.+?>", Pattern.MULTILINE | Pattern.DOTALL), "JSP");
//Servlet (Java based)
languagePatterns.put(Pattern.compile("import\\s+javax\\.servlet\\.http\\.HttpServlet\\s*;"), "Servlet");
languagePatterns.put(Pattern.compile("import\\s+javax\\.servlet\\.http\\.\\*\\s*;"), "Servlet");
languagePatterns.put(Pattern.compile("@WebServlet\\s*\\(\\s*\"/[a-z0-9]+\"\\s*\\)", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "Servlet");
languagePatterns.put(Pattern.compile("public\\s+class\\s+[a-z0-9]+\\s+extends\\s+(javax\\.servlet\\.http\\.)?HttpServlet", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "Servlet");
languagePatterns.put(Pattern.compile("public\\s+void\\s+doGet\\s*\\(\\s*HttpServletRequest\\s+[a-z0-9]+\\s*,\\s*HttpServletResponse\\s+[a-z0-9]+\\s*\\)", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "Servlet");
languagePatterns.put(Pattern.compile("public\\s+void\\s+doPost\\s*\\(\\s*HttpServletRequest\\s+[a-z0-9]+\\s*,\\s*HttpServletResponse\\s+[a-z0-9]+\\s*\\)", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "Servlet");
//Java
languagePatterns.put(Pattern.compile("^package\\s+[a-z0-9.]+;", Pattern.CASE_INSENSITIVE), "Java");
languagePatterns.put(Pattern.compile("^import\\s+[a-z0-9.]+;", Pattern.CASE_INSENSITIVE), "Java");
languagePatterns.put(Pattern.compile("class\\s+[a-z0-9]+\\s*\\{.+\\}", Pattern.MULTILINE | Pattern.DOTALL ), "Java");
languagePatterns.put(Pattern.compile("public\\s+static\\s+void\\s+main\\s*\\(\\s*String\\s+[a-z0-9]+\\s*\\[\\s*\\]\\s*\\)\\s*\\{", Pattern.MULTILINE | Pattern.DOTALL), "Java");
languagePatterns.put(Pattern.compile("public\\s+static\\s+void\\s+main\\s*\\(\\s*String\\s*\\[\\s*\\]\\s*[a-z0-9]+\\s*\\)\\s*\\{", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "Java");
//ASP
languagePatterns.put(Pattern.compile("On\\s*Error\\s*Resume\\s*Next", Pattern.CASE_INSENSITIVE), "ASP");
languagePatterns.put(Pattern.compile("Server.CreateObject\\s*\\(\\s*\"[a-z0-9.]+\"\\s*\\)", Pattern.CASE_INSENSITIVE), "ASP");
languagePatterns.put(Pattern.compile("Request.QueryString\\s*\\(\\s*\"[a-z0-9]+\"\\s*\\)", Pattern.CASE_INSENSITIVE), "ASP");
languagePatterns.put(Pattern.compile("If\\s*\\(\\s*Err.Number\\s*.+\\)\\s*Then", Pattern.CASE_INSENSITIVE), "ASP");
languagePatterns.put(Pattern.compile("<%@\\s+LANGUAGE\\s*=\\s*\"VBSCRIPT\"\\s*%>", Pattern.CASE_INSENSITIVE), "ASP");
//ASP.NET
languagePatterns.put(Pattern.compile("<%@\\s+Page.*?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<script\\s+runat\\s*=\\s*\"", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%Assembly.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%Control.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%Implements.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%MasterType.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%Master.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%Page.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%OutputCache.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%PreviousPageType.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%Reference.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%Register.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("@RenderPage\\s*\\(\\s*\".*?\"\\)", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("@RenderBody\\s*\\(\\s*\\)", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("@RenderSection\\s*\\(\\s*\".+?\"\\s*\\)", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
//languagePatterns.put(Pattern.compile("@\\{[\\u0000-\\u007F]{5,}?\\}", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET"); //Too many false positives
//languagePatterns.put(Pattern.compile("@if\\s*\\(.+?\\)\\s*\\{", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET"); //false positives with IE conditional compilation directives in JavaScript
languagePatterns.put(Pattern.compile("Request\\s*\\[\".+?\"\\]", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("@foreach\\s*", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("Database.Open\\s*\\(\\s*\"", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("db.Query\\s*\\(\\s*\"", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("@switch\\s*\\(.+?\\)\\s*\\{", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("^\\s*<asp:Menu"), "ASP.NET");
languagePatterns.put(Pattern.compile("^\\s*<asp:TreeView"), "ASP.NET");
languagePatterns.put(Pattern.compile("^\\s*<asp:SiteMapPath"), "ASP.NET");
//C#
languagePatterns.put(Pattern.compile("^<%@\\s+Page\\s+Language\\s*=\\s*\"C#\""), "C#");
languagePatterns.put(Pattern.compile("^using\\s+System\\s*;"), "C#");
languagePatterns.put(Pattern.compile("^namespace\\s+[a-z.]+\\s*\\{", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "C#");
languagePatterns.put(Pattern.compile("^static\\s+void\\s+Main\\s*\\(\\s*string\\s*\\[\\s*\\]\\s*[a-z0-9]+\\s*\\)", Pattern.MULTILINE ), "C#");
//generates false positives for JavaScript code, which also uses "var" to declare variables.
//languagePatterns.put(Pattern.compile("var\\s+[a-z]+?\\s*=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL), "C#");
languagePatterns.put(Pattern.compile("@for\\s*\\(\\s*var\\s+", Pattern.MULTILINE | Pattern.DOTALL), "C#");
languagePatterns.put(Pattern.compile("@foreach\\s*\\(\\s*var\\s+", Pattern.MULTILINE | Pattern.DOTALL), "C#");
//VB.NET
languagePatterns.put(Pattern.compile("^Imports\\s+System[a-zA-Z0-9.]*\\s*$"), "VB.NET");
languagePatterns.put(Pattern.compile("^dim\\s+[a-z0-9]+\\s*=", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "VB.NET");
languagePatterns.put(Pattern.compile("@for\\s+[a-z0-9]+\\s*=\\s*[0-9]+\\s+to\\s+[0-9]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "VB.NET");
languagePatterns.put(Pattern.compile("@for\\s+each\\s+[a-z0-9]+\\s+in\\s+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "VB.NET");
languagePatterns.put(Pattern.compile("@Select\\s+Case", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "VB.NET");
//languagePatterns.put(Pattern.compile("end\\s+select", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "VB.NET"); //False positives. Insufficiently anchored.
//SQL (ie, generic Structured Query Language, not "Microsoft SQL Server", which some incorrectly refer to as just "SQL")
//languagePatterns.put(Pattern.compile("select\\s+[a-z0-9., \"\'()*]+\\s+from\\s+[a-z0-9., ]+\\s+where\\s+", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("select\\s+[a-z0-9., \"\'()*]+\\s+from\\s+[a-z0-9._, ]+", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("select\\s+@@[a-z]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("insert\\s+into\\s+[a-z0-9._]+\\s+values\\s*\\(", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("insert\\s+into\\s+[a-z0-9._]+\\s*\\([a-z0-9_, \\t]+\\)\\s+values\\s*\\(", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
//languagePatterns.put(Pattern.compile("insert\\s+into\\s+[a-z0-9._]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("insert\\s+[a-z0-9._]+\\s+\\(.+?\\)\\s+values\\s*\\(.+?\\)", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("insert\\s+[a-z0-9._]+\\s+values\\s*\\(.+?\\)", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("insert\\s+[a-z0-9._]+\\s+select\\s+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("update\\s+[a-z0-9._]+\\s+set\\s+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("update\\s+[a-z0-9._]+\\s+[a-z0-9_]+\\s+set\\s+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL"); //allow a table alias
languagePatterns.put(Pattern.compile("delete\\s+from\\s+[a-z0-9._]+(\\s+where\\s+)?", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
//causes false positives on normal JavaScript: delete B.fn;
//languagePatterns.put(Pattern.compile("delete\\s+[a-z0-9._]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("truncate\\s+table\\s+[a-z0-9._]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("create\\s+database\\s+[a-z0-9._]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
//languagePatterns.put(Pattern.compile("create\\s+table\\s+[a-z0-9.]+\\s+\\(.+?\\)", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("create\\s+table\\s+(if\\s+not\\s+exists\\s+)?[a-z0-9._]+\\s*\\([^)]+\\)", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("create\\s+view\\s+[a-z0-9._]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("create\\s+index\\s+[a-z0-9._]+\\s+on\\s+[a-z0-9._]+\\s*\\(", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("create\\s+procedure\\s+[a-z0-9._]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("create\\s+function\\s+[a-z0-9._]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("drop\\s+database\\s+[a-z0-9._]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("drop\\s+table\\s+[a-z0-9._]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("drop\\s+view\\s+[a-z0-9._]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("drop\\s+index\\s+[a-z0-9._]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("drop\\s+procedure\\s+[a-z0-9._]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("drop\\s+function\\s+[a-z0-9._]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("grant\\s+[a-z]+\\s+on\\s+[a-z0-9._]+\\s+to\\s+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
languagePatterns.put(Pattern.compile("revoke\\s+[a-z0-9 (),]+\\s+on\\s+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "SQL");
//Perl
languagePatterns.put(Pattern.compile("^#!/usr/bin/perl"), "Perl");
languagePatterns.put(Pattern.compile("^use\\s+strict\\s*;\\s*$"), "Perl");
languagePatterns.put(Pattern.compile("^use\\s+warnings\\s*;\\s*$"), "Perl");
languagePatterns.put(Pattern.compile("^use\\s+[A-Za-z:]+\\s*;\\s*$"), "Perl");
languagePatterns.put(Pattern.compile("foreach\\s+my\\s+\\$[a-z0-9]+\\s*\\(", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Perl");
//languagePatterns.put(Pattern.compile("next unless"), "Perl");
languagePatterns.put(Pattern.compile("^\\s*my\\s+\\$[a-z0-9]+\\s*", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Perl");
languagePatterns.put(Pattern.compile("^\\s*my\\s+%[a-z0-9]+\\s*", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Perl");
languagePatterns.put(Pattern.compile("^\\s*my\\s+@[a-z0-9]+\\s*", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Perl");
languagePatterns.put(Pattern.compile("@[a-z0-9]+\\s+[a-z0-9]+\\s*=\\s*\\(", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Perl");
languagePatterns.put(Pattern.compile("\\$#[a-z0-9]{4,}", Pattern.CASE_INSENSITIVE), "Perl");
languagePatterns.put(Pattern.compile("\\$[a-z0-9]+\\s*\\{'[a-z0-9]+'\\}\\s*=\\s*", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Perl");
languagePatterns.put(Pattern.compile("die\\s+\".*?\\$!.*?\""), "Perl");
//Objective C (probably an iPhone app)
languagePatterns.put(Pattern.compile("^#\\s+import\\s+<[a-zA-Z0-9/.]+>", Pattern.MULTILINE), "Objective C");
languagePatterns.put(Pattern.compile("^#\\s+import\\s+\"[a-zA-Z0-9/.]+\"", Pattern.MULTILINE), "Objective C");
//languagePatterns.put(Pattern.compile("^\\[+[a-zA-Z0-9 :]{5,}\\]", Pattern.MULTILINE), "Objective C"); //false positives for INI files.
languagePatterns.put(Pattern.compile("@interface\\s*[a-zA-Z0-9]+\\s*:\\s*[a-zA-Z0-9]+\\s*\\{"), "Objective C");
//languagePatterns.put(Pattern.compile("\\+\\s*\\(\\s*[a-z]{5,}\\s*\\)"), "Objective C");
//languagePatterns.put(Pattern.compile("\\-\\s*\\(\\s*[a-z]{5,}\\s*\\)"), "Objective C");
languagePatterns.put(Pattern.compile("@implementation\\s+[a-z]"), "Objective C");
languagePatterns.put(Pattern.compile("@interface\\s+[a-zA-Z0-9]+\\s*:\\s*[a-zA-Z0-9]+\\s*<[a-zA-Z0-9]+>"), "Objective C");
languagePatterns.put(Pattern.compile("@protocol\\s+[a-zA-Z0-9]+"), "Objective C");
//languagePatterns.put(Pattern.compile("@public"), "Objective C"); //prone to false positives
//languagePatterns.put(Pattern.compile("@private"), "Objective C"); //prone to false positives
//languagePatterns.put(Pattern.compile("@property"), "Objective C"); //prone to false positives
languagePatterns.put(Pattern.compile("@end\\s*$"), "Objective C"); //anchor to $ to reduce false positives in C++ code comments.
languagePatterns.put(Pattern.compile("@synthesize"), "Objective C");
//C
//do not anchor the start pf the # lines with ^. This causes the match to fail. Why??
languagePatterns.put(Pattern.compile("#include\\s+<[a-zA-Z0-9/]+\\.h>"), "C");
languagePatterns.put(Pattern.compile("#include\\s+\"[a-zA-Z0-9/]+\\.h\""), "C");
languagePatterns.put(Pattern.compile("#define\\s+.+?$"), "C");
languagePatterns.put(Pattern.compile("#ifndef\\s+.+?$"), "C");
languagePatterns.put(Pattern.compile("#endif\\s*$"), "C");
languagePatterns.put(Pattern.compile("\\s*char\\s*\\*\\*\\s*[a-zA-Z0-9_]+\\s*;"), "C");
//C++
languagePatterns.put(Pattern.compile("#include\\s+<iostream\\.h>"), "C++");
languagePatterns.put(Pattern.compile("^[a-z0-9]+::[a-z0-9]+\\s*\\(\\s*\\).*?\\{.+?\\}", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "C++"); //constructor
languagePatterns.put(Pattern.compile("(std::)?cout\\s*<<\\s*\".+?\"\\s*;"), "C++");
//Shell Script
languagePatterns.put(Pattern.compile("^#!/bin/[a-z]*sh"), "Shell Script");
//Node.js
languagePatterns.put(Pattern.compile("^#!/usr/bin/env\\s+node"), "Node.js");
//Python
languagePatterns.put(Pattern.compile("#!/usr/bin/python.*$"), "Python");
languagePatterns.put(Pattern.compile("#!/usr/bin/env\\s+python"), "Python");
languagePatterns.put(Pattern.compile("^\\s*def\\s+[a-z0-9]+\\s*\\(\\s*[a-z0-9]+\\s*\\)\\s*:", Pattern.CASE_INSENSITIVE), "Python");
languagePatterns.put(Pattern.compile("\\s*for\\s+[a-z0-9]+\\s+in\\s+[a-z0-9]+:", Pattern.CASE_INSENSITIVE), "Python");
languagePatterns.put(Pattern.compile("^\\s*try\\s*:", Pattern.CASE_INSENSITIVE), "Python");
languagePatterns.put(Pattern.compile("^\\s*except\\s*:", Pattern.CASE_INSENSITIVE), "Python");
languagePatterns.put(Pattern.compile("^\\s*def\\s+main\\s*\\(\\s*\\)\\s*:", Pattern.CASE_INSENSITIVE), "Python");
//Ruby
languagePatterns.put(Pattern.compile("^\\s*require\\s+\".+?\"\\s*$", Pattern.CASE_INSENSITIVE), "Ruby");
languagePatterns.put(Pattern.compile("^\\s*describe\\s+[a-z0-9:]+\\s+do", Pattern.CASE_INSENSITIVE), "Ruby");
languagePatterns.put(Pattern.compile("^\\s*class\\s+[a-z0-9]+\\s+<\\s*[a-z0-9:]+", Pattern.CASE_INSENSITIVE), "Ruby");
languagePatterns.put(Pattern.compile("^\\s*def\\s+[a-z0-9]+\\s*.+?^\\s*end\\s*$", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "Ruby");
languagePatterns.put(Pattern.compile("@@active\\s*=\\s*", Pattern.CASE_INSENSITIVE), "Ruby");
//Cold Fusion
languagePatterns.put(Pattern.compile("<cfoutput"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfset"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfexecute"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfexit"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfcomponent"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cffunction"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfreturn"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfargument"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfscript"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfloop"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfquery"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfqueryparam"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfdump"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfloop"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfif"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfelseif"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfelse"), "Cold Fusion");
languagePatterns.put(Pattern.compile("writeOutput\\s*\\("), "Cold Fusion");
//languagePatterns.put(Pattern.compile("component\\s*\\{"), "Cold Fusion"); //cannot find original example, and too prone to false positives.
//Visual FoxPro / ActiveVFP
languagePatterns.put(Pattern.compile("oRequest\\.querystring\\s*\\(\\s*\"[a-z0-9]+\"\\s*\\)", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE),"ActiveVFP");
languagePatterns.put(Pattern.compile("define\\s+class\\s+[a-z0-9]+\\s+as\\s+[a-z0-9]+", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE),"ActiveVFP");
languagePatterns.put(Pattern.compile("for\\s+[a-z0-9]+\\s*=\\s*[0-9]+\\s+to\\s+[0-9]+.+?\\s+endfor", Pattern.CASE_INSENSITIVE),"ActiveVFP");
languagePatterns.put(Pattern.compile("do\\s+while\\s+.+?\\s+enddo", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE),"ActiveVFP");
languagePatterns.put(Pattern.compile("if\\s+.+?\\s+endif", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE),"ActiveVFP");
languagePatterns.put(Pattern.compile("do\\s+case\\s+case\\s+.+?\\s+endcase", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE),"ActiveVFP");
languagePatterns.put(Pattern.compile("for\\s+each\\s+.+?\\s+endfor", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE),"ActiveVFP");
//languagePatterns.put(Pattern.compile("oRequest"),"ActiveVFP"); //prone to false positives
//languagePatterns.put(Pattern.compile("oResponse"),"ActiveVFP"); //prone to false positives
//languagePatterns.put(Pattern.compile("oSession"),"ActiveVFP"); //prone to false positives
//Pascal
languagePatterns.put(Pattern.compile("^program\\s+[a-z0-9]+;.*?begin.+?end", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "Pascal");
//Latex (yes, this is a programming language)
languagePatterns.put(Pattern.compile("\\documentclass\\s*\\{[a-z]+\\}", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Latex");
languagePatterns.put(Pattern.compile("\\begin\\s*\\{[a-z]+\\}", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Latex");
languagePatterns.put(Pattern.compile("\\end\\s*\\{[a-z]+\\}", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Latex");
//Actionscript 3
languagePatterns.put(Pattern.compile("package\\s+[a-z0-9.]+\\s*\\{(.*import\\s+[a-z0-9.]+\\s*;)?.+\\}", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE),"ActionScript 3.0");
//TODO: consider sorting the patterns by decreasing pattern length, so more specific patterns are tried before more general patterns
}
/**
* Prefix for internationalized messages used by this rule
*/
private static final String MESSAGE_PREFIX = "pscanalpha.sourcecodedisclosure.";
/**
* construct the class, and register for i18n
*/
/**
* gets the name of the scanner
* @return
*/
@Override
public String getName() {
return Constant.messages.getString(MESSAGE_PREFIX + "name");
}
/**
* scans the HTTP request sent (in fact, does nothing)
* @param msg
* @param id
*/
@Override
public void scanHttpRequestSend(HttpMessage msg, int id) {
// do nothing
}
/**
* scans the HTTP response for Source Code signatures
* @param msg
* @param id
* @param source unused
*/
@Override
public void scanHttpResponseReceive(HttpMessage msg, int id, Source source) {
//get the body contents as a String, so we can match against it
String responsebody = msg.getResponseBody().toString();
//try each of the patterns in turn against the response.
//we deliberately do not assume that only status 200 responses will contain source code.
String evidence = null;
String programminglanguage = null;
Iterator<Pattern> patternIterator = languagePatterns.keySet().iterator();
while (patternIterator.hasNext()) {
Pattern languagePattern = patternIterator.next();
programminglanguage = languagePatterns.get(languagePattern);
Matcher matcher = languagePattern.matcher(responsebody);
if (matcher.find()) {
evidence = matcher.group();
if (log.isDebugEnabled()) {
log.debug("Passive Source Code Disclosure on pattern "+ languagePattern + ", evidence: "+ evidence);
}
break; //use the first match
}
}
if (evidence!=null && evidence.length() > 0) {
//we found something
Alert alert = new Alert(getPluginId(), Alert.RISK_HIGH, Alert.CONFIDENCE_MEDIUM, getName() + " - "+ programminglanguage );
alert.setDetail(
getDescription() + " - "+ programminglanguage,
msg.getRequestHeader().getURI().toString(),
"", //param
"", //attack
getExtraInfo(msg, evidence), //other info
getSolution(),
getReference(),
evidence,
540, //Information Exposure Through Source Code
13, //WASC-13: Information Leakage
msg);
parent.raiseAlert(id, alert);
}
}
/**
* sets the parent
* @param parent
*/
@Override
public void setParent(PassiveScanThread parent) {
this.parent = parent;
}
/**
* get the id of the scanner
* @return
*/
@Override
public int getPluginId() {
return 10099;
}
/**
* get the description of the alert
* @return
*/
private String getDescription() {
return Constant.messages.getString(MESSAGE_PREFIX + "desc");
}
/**
* get the solution for the alert
* @return
*/
private String getSolution() {
return Constant.messages.getString(MESSAGE_PREFIX + "soln");
}
/**
* gets references for the alert
* @return
*/
private String getReference() {
return Constant.messages.getString(MESSAGE_PREFIX + "refs");
}
/**
* gets extra information associated with the alert
* @param msg
* @param arg0
* @return
*/
private String getExtraInfo(HttpMessage msg, String arg0) {
return Constant.messages.getString(MESSAGE_PREFIX + "extrainfo", arg0);
}
}
|
False positive caused by ASP 'On Error resume Next' pattern also matching Rx.Observable.onErrorResumeNext in RxJS
|
src/org/zaproxy/zap/extension/pscanrulesAlpha/SourceCodeDisclosureScanner.java
|
False positive caused by ASP 'On Error resume Next' pattern also matching Rx.Observable.onErrorResumeNext in RxJS
|
<ide><path>rc/org/zaproxy/zap/extension/pscanrulesAlpha/SourceCodeDisclosureScanner.java
<ide> languagePatterns.put(Pattern.compile("public\\s+static\\s+void\\s+main\\s*\\(\\s*String\\s*\\[\\s*\\]\\s*[a-z0-9]+\\s*\\)\\s*\\{", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "Java");
<ide>
<ide> //ASP
<del> languagePatterns.put(Pattern.compile("On\\s*Error\\s*Resume\\s*Next", Pattern.CASE_INSENSITIVE), "ASP");
<add> languagePatterns.put(Pattern.compile("On\\s+Error\\s+Resume\\s+Next", Pattern.CASE_INSENSITIVE), "ASP");
<ide> languagePatterns.put(Pattern.compile("Server.CreateObject\\s*\\(\\s*\"[a-z0-9.]+\"\\s*\\)", Pattern.CASE_INSENSITIVE), "ASP");
<ide> languagePatterns.put(Pattern.compile("Request.QueryString\\s*\\(\\s*\"[a-z0-9]+\"\\s*\\)", Pattern.CASE_INSENSITIVE), "ASP");
<ide> languagePatterns.put(Pattern.compile("If\\s*\\(\\s*Err.Number\\s*.+\\)\\s*Then", Pattern.CASE_INSENSITIVE), "ASP");
|
|
Java
|
mit
|
86f0f2ec8b591a1594374fc9591e33bdaeacd6bc
| 0 |
schmave/demschooltools,schmave/demschooltools,schmave/demschooltools,schmave/demschooltools,schmave/demschooltools
|
package models;
import java.util.*;
import javax.persistence.*;
import play.data.*;
import play.data.validation.Constraints.*;
import play.db.ebean.*;
@Entity
public class PersonTag extends Model {
@Id
public long tag_id;
@Id
public long person_id;
public static Finder<Integer, PersonTag> find = new Finder(
Integer.class, PersonTag.class
);
public static PersonTag create(Tag t, Person p) {
PersonTag result = new PersonTag();
result.tag_id = t.id;
result.person_id = p.person_id;
result.save();
return result;
}
}
|
app/models/PersonTag.java
|
package models;
import java.util.*;
import javax.persistence.*;
import play.data.*;
import play.data.validation.Constraints.*;
import play.db.ebean.*;
@Entity
public class PersonTag extends Model {
@Id
public long tag_id;
@Id
public long person_id;
//@Id
//@ManyToOne()
//@JoinColumn(name="tag_id")
//public Tag tag;
//
//@Id
//@ManyToOne()
//@JoinColumn(name="person_id")
//public Person person;
public static Finder<Integer, PersonTag> find = new Finder(
Integer.class, PersonTag.class
);
public static PersonTag create(Tag t, Person p) {
PersonTag result = new PersonTag();
result.tag_id = t.id;
result.person_id = p.person_id;
result.save();
return result;
}
}
|
Remove unneeded comment
|
app/models/PersonTag.java
|
Remove unneeded comment
|
<ide><path>pp/models/PersonTag.java
<ide>
<ide> @Id
<ide> public long person_id;
<del> //@Id
<del> //@ManyToOne()
<del> //@JoinColumn(name="tag_id")
<del> //public Tag tag;
<del> //
<del> //@Id
<del> //@ManyToOne()
<del> //@JoinColumn(name="person_id")
<del> //public Person person;
<ide>
<ide> public static Finder<Integer, PersonTag> find = new Finder(
<ide> Integer.class, PersonTag.class
|
|
Java
|
apache-2.0
|
2bfd8bbfe1a9fc57abab09c3d13eb1edc50e7102
| 0 |
Pronin73/Pronin73
|
package ru.homework;
public class Main {
public static void main(String[] args) {
Point P1 = new Point();
Point P2 = new Point();
P1.x = 0;
P1.y = 1;
P2.x = 5;
P2.y = 3;
distance(P1, P2);
System.out.println( "Расстояние между двумя точками" + " = " + distance(P1, P2));
}
public static double distance(Point P1, Point P2){
return Math.sqrt((P1.x - P2.x)*(P1.x - P2.x) + (P1.y - P2.y)*(P1.y - P2.y));
}
}
|
SendBox/src/main/Java/ru/homework/Main.java
|
package ru.homework;
public class Main {
public static void main(String[] args) {
Point P1 = new Point();
Point P2 = new Point();
double x1 = 0;
double y1 = 1;
double x2 = 5;
double y2 = 3;
distance( x1, y1, x2, y2);
System.out.println( "Расстояние между двумя точками" + " = " + distance(x1, y1, x2, y2));
}
public static double distance(Point P1, Point P2){
double d = 0;
d = Math.sqrt((P1.x - P2.x)*(P1.x - P2.x) + (P1.y - P2.y)*(P1.y - P2.y));
return d;
}
}
|
Реализация домашнего задания 1-3.
|
SendBox/src/main/Java/ru/homework/Main.java
|
Реализация домашнего задания 1-3.
|
<ide><path>endBox/src/main/Java/ru/homework/Main.java
<ide> Point P1 = new Point();
<ide> Point P2 = new Point();
<ide>
<del> double x1 = 0;
<del> double y1 = 1;
<del> double x2 = 5;
<del> double y2 = 3;
<del> distance( x1, y1, x2, y2);
<del> System.out.println( "Расстояние между двумя точками" + " = " + distance(x1, y1, x2, y2));
<add> P1.x = 0;
<add> P1.y = 1;
<add> P2.x = 5;
<add> P2.y = 3;
<add> distance(P1, P2);
<add> System.out.println( "Расстояние между двумя точками" + " = " + distance(P1, P2));
<ide>
<ide> }
<ide>
<ide> public static double distance(Point P1, Point P2){
<del> double d = 0;
<del> d = Math.sqrt((P1.x - P2.x)*(P1.x - P2.x) + (P1.y - P2.y)*(P1.y - P2.y));
<del> return d;
<add>
<add> return Math.sqrt((P1.x - P2.x)*(P1.x - P2.x) + (P1.y - P2.y)*(P1.y - P2.y));
<add>
<ide> }
<ide> }
|
|
Java
|
apache-2.0
|
ab17d1478850d2c83ec1316e49c24ada4498b283
| 0 |
apache/pdfbox,kalaspuffar/pdfbox,kalaspuffar/pdfbox,apache/pdfbox
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pdfbox.pdfparser;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pdfbox.cos.COSArray;
import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.cos.COSNull;
import org.apache.pdfbox.cos.COSNumber;
import org.apache.pdfbox.cos.COSObject;
import org.apache.pdfbox.cos.COSObjectKey;
import org.apache.pdfbox.cos.COSStream;
import org.apache.pdfbox.cos.ICOSParser;
import org.apache.pdfbox.io.IOUtils;
import org.apache.pdfbox.io.RandomAccessRead;
import org.apache.pdfbox.pdfparser.XrefTrailerResolver.XRefType;
import org.apache.pdfbox.pdmodel.encryption.AccessPermission;
import org.apache.pdfbox.pdmodel.encryption.DecryptionMaterial;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
import org.apache.pdfbox.pdmodel.encryption.PDEncryption;
import org.apache.pdfbox.pdmodel.encryption.PublicKeyDecryptionMaterial;
import org.apache.pdfbox.pdmodel.encryption.SecurityHandler;
import org.apache.pdfbox.pdmodel.encryption.StandardDecryptionMaterial;
/**
* COS-Parser which first reads startxref and xref tables in order to know valid objects and parse only these objects.
*
* This class is a much enhanced version of <code>QuickParser</code> presented in
* <a href="https://issues.apache.org/jira/browse/PDFBOX-1104">PDFBOX-1104</a> by Jeremy Villalobos.
*/
public class COSParser extends BaseParser implements ICOSParser
{
private static final String PDF_HEADER = "%PDF-";
private static final String FDF_HEADER = "%FDF-";
private static final String PDF_DEFAULT_VERSION = "1.4";
private static final String FDF_DEFAULT_VERSION = "1.0";
private static final char[] XREF_TABLE = new char[] { 'x', 'r', 'e', 'f' };
private static final char[] XREF_STREAM = new char[] { '/', 'X', 'R', 'e', 'f' };
private static final char[] STARTXREF = new char[] { 's','t','a','r','t','x','r','e','f' };
private static final byte[] ENDSTREAM = new byte[] { E, N, D, S, T, R, E, A, M };
private static final byte[] ENDOBJ = new byte[] { E, N, D, O, B, J };
private static final long MINIMUM_SEARCH_OFFSET = 6;
private static final int X = 'x';
private static final int STRMBUFLEN = 2048;
private final byte[] strmBuf = new byte[ STRMBUFLEN ];
protected final RandomAccessRead source;
private AccessPermission accessPermission;
private InputStream keyStoreInputStream = null;
@SuppressWarnings({"squid:S2068"})
private String password = "";
private String keyAlias = null;
/**
* The range within the %%EOF marker will be searched.
* Useful if there are additional characters after %%EOF within the PDF.
*/
public static final String SYSPROP_EOFLOOKUPRANGE =
"org.apache.pdfbox.pdfparser.nonSequentialPDFParser.eofLookupRange";
/**
* How many trailing bytes to read for EOF marker.
*/
private static final int DEFAULT_TRAIL_BYTECOUNT = 2048;
/**
* EOF-marker.
*/
protected static final char[] EOF_MARKER = new char[] { '%', '%', 'E', 'O', 'F' };
/**
* obj-marker.
*/
protected static final char[] OBJ_MARKER = new char[] { 'o', 'b', 'j' };
/**
* trailer-marker.
*/
private static final char[] TRAILER_MARKER = new char[] { 't', 'r', 'a', 'i', 'l', 'e', 'r' };
/**
* ObjStream-marker.
*/
private static final char[] OBJ_STREAM = new char[] { '/', 'O', 'b', 'j', 'S', 't', 'm' };
/**
* file length.
*/
protected long fileLen;
/**
* is parser using auto healing capacity ?
*/
private boolean isLenient = true;
protected boolean initialParseDone = false;
private boolean trailerWasRebuild = false;
/**
* Contains all found objects of a brute force search.
*/
private Map<COSObjectKey, Long> bfSearchCOSObjectKeyOffsets = null;
private List<Long> bfSearchXRefTablesOffsets = null;
private List<Long> bfSearchXRefStreamsOffsets = null;
private PDEncryption encryption = null;
/**
* The security handler.
*/
protected SecurityHandler securityHandler = null;
/**
* how many trailing bytes to read for EOF marker.
*/
private int readTrailBytes = DEFAULT_TRAIL_BYTECOUNT;
private static final Log LOG = LogFactory.getLog(COSParser.class);
/**
* Collects all Xref/trailer objects and resolves them into single
* object using startxref reference.
*/
protected XrefTrailerResolver xrefTrailerResolver = new XrefTrailerResolver();
/**
* The prefix for the temp file being used.
*/
public static final String TMP_FILE_PREFIX = "tmpPDF";
/**
* Default constructor.
*
* @param source input representing the pdf.
*/
public COSParser(RandomAccessRead source)
{
super(new RandomAccessSource(source));
this.source = source;
}
/**
* Constructor for encrypted pdfs.
*
* @param source input representing the pdf.
* @param password password to be used for decryption.
* @param keyStore key store to be used for decryption when using public key security
* @param keyAlias alias to be used for decryption when using public key security
*
*/
public COSParser(RandomAccessRead source, String password, InputStream keyStore,
String keyAlias)
{
super(new RandomAccessSource(source));
this.source = source;
this.password = password;
this.keyAlias = keyAlias;
keyStoreInputStream = keyStore;
}
/**
* Sets how many trailing bytes of PDF file are searched for EOF marker and 'startxref' marker. If not set we use
* default value {@link #DEFAULT_TRAIL_BYTECOUNT}.
*
* <p>We check that new value is at least 16. However for practical use cases this value should not be lower than
* 1000; even 2000 was found to not be enough in some cases where some trailing garbage like HTML snippets followed
* the EOF marker.</p>
*
* <p>
* In case system property {@link #SYSPROP_EOFLOOKUPRANGE} is defined this value will be set on initialization but
* can be overwritten later.
* </p>
*
* @param byteCount number of trailing bytes
*/
public void setEOFLookupRange(int byteCount)
{
if (byteCount > 15)
{
readTrailBytes = byteCount;
}
}
/**
* Read the trailer information and provide a COSDictionary containing the trailer information.
*
* @return a COSDictionary containing the trailer information
* @throws IOException if something went wrong
*/
protected COSDictionary retrieveTrailer() throws IOException
{
COSDictionary trailer = null;
boolean rebuildTrailer = false;
try
{
// parse startxref
// TODO FDF files don't have a startxref value, so that rebuildTrailer is triggered
long startXRefOffset = getStartxrefOffset();
if (startXRefOffset > -1)
{
trailer = parseXref(startXRefOffset);
}
else
{
rebuildTrailer = isLenient();
}
}
catch (IOException exception)
{
if (isLenient())
{
rebuildTrailer = true;
}
else
{
throw exception;
}
}
// check if the trailer contains a Root object
if (trailer != null && trailer.getItem(COSName.ROOT) == null)
{
rebuildTrailer = isLenient();
}
if (rebuildTrailer)
{
trailer = rebuildTrailer();
}
else
{
// prepare decryption if necessary
prepareDecryption();
if (bfSearchCOSObjectKeyOffsets != null && !bfSearchCOSObjectKeyOffsets.isEmpty())
{
bfSearchForObjStreams();
}
}
return trailer;
}
/**
* Parses cross reference tables.
*
* @param startXRefOffset start offset of the first table
* @return the trailer dictionary
* @throws IOException if something went wrong
*/
private COSDictionary parseXref(long startXRefOffset) throws IOException
{
source.seek(startXRefOffset);
long startXrefOffset = Math.max(0, parseStartXref());
// check the startxref offset
long fixedOffset = checkXRefOffset(startXrefOffset);
if (fixedOffset > -1)
{
startXrefOffset = fixedOffset;
}
document.setStartXref(startXrefOffset);
long prev = startXrefOffset;
// ---- parse whole chain of xref tables/object streams using PREV reference
Set<Long> prevSet = new HashSet<>();
while (prev > 0)
{
// seek to xref table
source.seek(prev);
// skip white spaces
skipSpaces();
// -- parse xref
if (source.peek() == X)
{
// xref table and trailer
// use existing parser to parse xref table
if (!parseXrefTable(prev) || !parseTrailer())
{
throw new IOException("Expected trailer object at offset "
+ source.getPosition());
}
COSDictionary trailer = xrefTrailerResolver.getCurrentTrailer();
// check for a XRef stream, it may contain some object ids of compressed objects
if(trailer.containsKey(COSName.XREF_STM))
{
int streamOffset = trailer.getInt(COSName.XREF_STM);
// check the xref stream reference
fixedOffset = checkXRefOffset(streamOffset);
if (fixedOffset > -1 && fixedOffset != streamOffset)
{
LOG.warn("/XRefStm offset " + streamOffset + " is incorrect, corrected to " + fixedOffset);
streamOffset = (int)fixedOffset;
trailer.setInt(COSName.XREF_STM, streamOffset);
}
if (streamOffset > 0)
{
source.seek(streamOffset);
skipSpaces();
try
{
parseXrefObjStream(prev, false);
}
catch (IOException ex)
{
if (isLenient)
{
LOG.error("Failed to parse /XRefStm at offset " + streamOffset, ex);
}
else
{
throw ex;
}
}
}
else
{
if(isLenient)
{
LOG.error("Skipped XRef stream due to a corrupt offset:"+streamOffset);
}
else
{
throw new IOException("Skipped XRef stream due to a corrupt offset:"+streamOffset);
}
}
}
prev = trailer.getLong(COSName.PREV);
if (prev > 0)
{
// check the xref table reference
fixedOffset = checkXRefOffset(prev);
if (fixedOffset > -1 && fixedOffset != prev)
{
prev = fixedOffset;
trailer.setLong(COSName.PREV, prev);
}
}
}
else
{
// parse xref stream
prev = parseXrefObjStream(prev, true);
if (prev > 0)
{
// check the xref table reference
fixedOffset = checkXRefOffset(prev);
if (fixedOffset > -1 && fixedOffset != prev)
{
prev = fixedOffset;
COSDictionary trailer = xrefTrailerResolver.getCurrentTrailer();
trailer.setLong(COSName.PREV, prev);
}
}
}
if (prevSet.contains(prev))
{
throw new IOException("/Prev loop at offset " + prev);
}
prevSet.add(prev);
}
// ---- build valid xrefs out of the xref chain
xrefTrailerResolver.setStartxref(startXrefOffset);
COSDictionary trailer = xrefTrailerResolver.getTrailer();
document.setTrailer(trailer);
document.setIsXRefStream(XRefType.STREAM == xrefTrailerResolver.getXrefType());
// check the offsets of all referenced objects
checkXrefOffsets();
// copy xref table
document.addXRefTable(xrefTrailerResolver.getXrefTable());
return trailer;
}
/**
* Parses an xref object stream starting with indirect object id.
*
* @return value of PREV item in dictionary or <code>-1</code> if no such item exists
*/
private long parseXrefObjStream(long objByteOffset, boolean isStandalone) throws IOException
{
// ---- parse indirect object head
long objectNumber = readObjectNumber();
// remember the highest XRef object number to avoid it being reused in incremental saving
long currentHighestXRefObjectNumber = document.getHighestXRefObjectNumber();
document.setHighestXRefObjectNumber(Math.max(currentHighestXRefObjectNumber, objectNumber));
readGenerationNumber();
readExpectedString(OBJ_MARKER, true);
COSDictionary dict = parseCOSDictionary();
try (COSStream xrefStream = parseCOSStream(dict))
{
parseXrefStream(xrefStream, objByteOffset, isStandalone);
}
return dict.getLong(COSName.PREV);
}
/**
* Looks for and parses startxref. We first look for last '%%EOF' marker (within last
* {@link #DEFAULT_TRAIL_BYTECOUNT} bytes (or range set via {@link #setEOFLookupRange(int)}) and go back to find
* <code>startxref</code>.
*
* @return the offset of StartXref
* @throws IOException If something went wrong.
*/
private long getStartxrefOffset() throws IOException
{
byte[] buf;
long skipBytes;
// read trailing bytes into buffer
try
{
final int trailByteCount = (fileLen < readTrailBytes) ? (int) fileLen : readTrailBytes;
buf = new byte[trailByteCount];
skipBytes = fileLen - trailByteCount;
source.seek(skipBytes);
int off = 0;
int readBytes;
while (off < trailByteCount)
{
readBytes = source.read(buf, off, trailByteCount - off);
// in order to not get stuck in a loop we check readBytes (this should never happen)
if (readBytes < 1)
{
throw new IOException(
"No more bytes to read for trailing buffer, but expected: "
+ (trailByteCount - off));
}
off += readBytes;
}
}
finally
{
source.seek(0);
}
// find last '%%EOF'
int bufOff = lastIndexOf(EOF_MARKER, buf, buf.length);
if (bufOff < 0)
{
if (isLenient)
{
// in lenient mode the '%%EOF' isn't needed
bufOff = buf.length;
LOG.debug("Missing end of file marker '" + new String(EOF_MARKER) + "'");
}
else
{
throw new IOException("Missing end of file marker '" + new String(EOF_MARKER) + "'");
}
}
// find last startxref preceding EOF marker
bufOff = lastIndexOf(STARTXREF, buf, bufOff);
if (bufOff < 0)
{
throw new IOException("Missing 'startxref' marker.");
}
else
{
return skipBytes + bufOff;
}
}
/**
* Searches last appearance of pattern within buffer. Lookup before _lastOff and goes back until 0.
*
* @param pattern pattern to search for
* @param buf buffer to search pattern in
* @param endOff offset (exclusive) where lookup starts at
*
* @return start offset of pattern within buffer or <code>-1</code> if pattern could not be found
*/
protected int lastIndexOf(final char[] pattern, final byte[] buf, final int endOff)
{
final int lastPatternChOff = pattern.length - 1;
int bufOff = endOff;
int patOff = lastPatternChOff;
char lookupCh = pattern[patOff];
while (--bufOff >= 0)
{
if (buf[bufOff] == lookupCh)
{
if (--patOff < 0)
{
// whole pattern matched
return bufOff;
}
// matched current char, advance to preceding one
lookupCh = pattern[patOff];
}
else if (patOff < lastPatternChOff)
{
// no char match but already matched some chars; reset
patOff = lastPatternChOff;
lookupCh = pattern[patOff];
}
}
return -1;
}
/**
* Return true if parser is lenient. Meaning auto healing capacity of the parser are used.
*
* @return true if parser is lenient
*/
public boolean isLenient()
{
return isLenient;
}
/**
* Change the parser leniency flag.
*
* This method can only be called before the parsing of the file.
*
* @param lenient try to handle malformed PDFs.
*
*/
protected void setLenient(boolean lenient)
{
if (initialParseDone)
{
throw new IllegalArgumentException("Cannot change leniency after parsing");
}
this.isLenient = lenient;
}
@Override
public COSBase dereferenceCOSObject(COSObject obj) throws IOException
{
long currentPos = source.getPosition();
COSBase parsedObj = parseObjectDynamically(obj.getObjectNumber(), obj.getGenerationNumber(),
false);
if (currentPos > 0)
{
source.seek(currentPos);
}
return parsedObj;
}
/**
* Parse the object for the given object number.
*
* @param objNr object number of object to be parsed
* @param objGenNr object generation number of object to be parsed
* @param requireExistingNotCompressedObj if <code>true</code> the object to be parsed must be defined in xref
* (comment: null objects may be missing from xref) and it must not be a compressed object within object stream
* (this is used to circumvent being stuck in a loop in a malicious PDF)
*
* @return the parsed object (which is also added to document object)
*
* @throws IOException If an IO error occurs.
*/
protected synchronized COSBase parseObjectDynamically(long objNr, int objGenNr,
boolean requireExistingNotCompressedObj) throws IOException
{
// ---- create object key and get object (container) from pool
final COSObjectKey objKey = new COSObjectKey(objNr, objGenNr);
final COSObject pdfObject = document.getObjectFromPool(objKey);
COSBase referencedObject = !pdfObject.isObjectNull() ? pdfObject.getObject() : null;
// not previously parsed
if (referencedObject == null)
{
// read offset or object stream object number from xref table
Long offsetOrObjstmObNr = document.getXrefTable().get(objKey);
// maybe something is wrong with the xref table -> perform brute force search for all objects
if (offsetOrObjstmObNr == null && isLenient)
{
Map<COSObjectKey, Long> bfCOSObjectKeyOffsets = getBFCOSObjectOffsets();
offsetOrObjstmObNr = bfCOSObjectKeyOffsets.get(objKey);
if (offsetOrObjstmObNr != null)
{
LOG.debug("Set missing offset " + offsetOrObjstmObNr + " for object " + objKey);
document.getXrefTable().put(objKey, offsetOrObjstmObNr);
}
}
// sanity test to circumvent loops with broken documents
if (requireExistingNotCompressedObj
&& ((offsetOrObjstmObNr == null) || (offsetOrObjstmObNr <= 0)))
{
throw new IOException("Object must be defined and must not be compressed object: "
+ objKey.getNumber() + ":" + objKey.getGeneration());
}
if (offsetOrObjstmObNr == null)
{
// not defined object -> NULL object (Spec. 1.7, chap. 3.2.9)
// remove parser to avoid endless recursion
pdfObject.setToNull();
}
else if (offsetOrObjstmObNr > 0)
{
// offset of indirect object in file
referencedObject = parseFileObject(offsetOrObjstmObNr, objKey);
}
else
{
// xref value is object nr of object stream containing object to be parsed
// since our object was not found it means object stream was not parsed so far
referencedObject = parseObjectStreamObject((int) -offsetOrObjstmObNr, objKey);
}
if (referencedObject == null || referencedObject instanceof COSNull)
{
pdfObject.setToNull();
}
}
return referencedObject;
}
private COSBase parseFileObject(Long offsetOrObjstmObNr, final COSObjectKey objKey)
throws IOException
{
// ---- go to object start
source.seek(offsetOrObjstmObNr);
// ---- we must have an indirect object
final long readObjNr = readObjectNumber();
final int readObjGen = readGenerationNumber();
readExpectedString(OBJ_MARKER, true);
// ---- consistency check
if ((readObjNr != objKey.getNumber()) || (readObjGen != objKey.getGeneration()))
{
throw new IOException("XREF for " + objKey.getNumber() + ":"
+ objKey.getGeneration() + " points to wrong object: " + readObjNr
+ ":" + readObjGen + " at offset " + offsetOrObjstmObNr);
}
skipSpaces();
COSBase parsedObject = parseDirObject();
String endObjectKey = readString();
if (endObjectKey.equals(STREAM_STRING))
{
source.rewind(endObjectKey.getBytes(StandardCharsets.ISO_8859_1).length);
if (parsedObject instanceof COSDictionary)
{
COSStream stream = parseCOSStream((COSDictionary) parsedObject);
if (securityHandler != null)
{
securityHandler.decryptStream(stream, objKey.getNumber(), objKey.getGeneration());
}
parsedObject = stream;
}
else
{
// this is not legal
// the combination of a dict and the stream/endstream
// forms a complete stream object
throw new IOException("Stream not preceded by dictionary (offset: "
+ offsetOrObjstmObNr + ").");
}
skipSpaces();
endObjectKey = readLine();
// we have case with a second 'endstream' before endobj
if (!endObjectKey.startsWith(ENDOBJ_STRING) && endObjectKey.startsWith(ENDSTREAM_STRING))
{
endObjectKey = endObjectKey.substring(9).trim();
if (endObjectKey.length() == 0)
{
// no other characters in extra endstream line
// read next line
endObjectKey = readLine();
}
}
}
else if (securityHandler != null)
{
securityHandler.decrypt(parsedObject, objKey.getNumber(), objKey.getGeneration());
}
if (!endObjectKey.startsWith(ENDOBJ_STRING))
{
if (isLenient)
{
LOG.warn("Object (" + readObjNr + ":" + readObjGen + ") at offset "
+ offsetOrObjstmObNr + " does not end with 'endobj' but with '"
+ endObjectKey + "'");
}
else
{
throw new IOException("Object (" + readObjNr + ":" + readObjGen
+ ") at offset " + offsetOrObjstmObNr
+ " does not end with 'endobj' but with '" + endObjectKey + "'");
}
}
return parsedObject;
}
/**
* Parse the object with the given key from the object stream with the given number.
*
* @param objstmObjNr the number of the offset stream
* @param key the key of the object to be parsed
* @return the parsed object
* @throws IOException if something went wrong when parsing the object
*/
protected COSBase parseObjectStreamObject(int objstmObjNr, COSObjectKey key) throws IOException
{
final COSBase objstmBaseObj = parseObjectDynamically(objstmObjNr, 0, true);
COSBase objectStreamObject = null;
if (objstmBaseObj instanceof COSStream)
{
// parse object stream
PDFObjectStreamParser parser = null;
try
{
parser = new PDFObjectStreamParser((COSStream) objstmBaseObj, document);
objectStreamObject = parser.parseObject(key.getNumber());
}
catch (IOException ex)
{
if (isLenient)
{
LOG.error("object stream " + objstmObjNr
+ " could not be parsed due to an exception", ex);
}
else
{
throw ex;
}
}
}
return objectStreamObject;
}
/**
* Returns length value referred to or defined in given object.
*/
private COSNumber getLength(final COSBase lengthBaseObj) throws IOException
{
if (lengthBaseObj == null)
{
return null;
}
// maybe length was given directly
if (lengthBaseObj instanceof COSNumber)
{
return (COSNumber) lengthBaseObj;
}
// length in referenced object
if (lengthBaseObj instanceof COSObject)
{
COSObject lengthObj = (COSObject) lengthBaseObj;
COSBase length = lengthObj.getObject();
if (length == null)
{
throw new IOException("Length object content was not read.");
}
if (COSNull.NULL == length)
{
LOG.warn("Length object (" + lengthObj.getObjectNumber() + " "
+ lengthObj.getGenerationNumber() + ") not found");
return null;
}
if (length instanceof COSNumber)
{
return (COSNumber) length;
}
throw new IOException("Wrong type of referenced length object " + lengthObj + ": "
+ length.getClass().getSimpleName());
}
throw new IOException(
"Wrong type of length object: " + lengthBaseObj.getClass().getSimpleName());
}
private static final int STREAMCOPYBUFLEN = 8192;
private final byte[] streamCopyBuf = new byte[STREAMCOPYBUFLEN];
/**
* This will read a COSStream from the input stream using length attribute within dictionary. If
* length attribute is a indirect reference it is first resolved to get the stream length. This
* means we copy stream data without testing for 'endstream' or 'endobj' and thus it is no
* problem if these keywords occur within stream. We require 'endstream' to be found after
* stream data is read.
*
* @param dic dictionary that goes with this stream.
*
* @return parsed pdf stream.
*
* @throws IOException if an error occurred reading the stream, like problems with reading
* length attribute, stream does not end with 'endstream' after data read, stream too short etc.
*/
protected COSStream parseCOSStream(COSDictionary dic) throws IOException
{
COSStream stream = document.createCOSStream(dic);
// read 'stream'; this was already tested in parseObjectsDynamically()
readString();
skipWhiteSpaces();
/*
* This needs to be dic.getItem because when we are parsing, the underlying object might still be null.
*/
COSNumber streamLengthObj = getLength(dic.getItem(COSName.LENGTH));
if (streamLengthObj == null)
{
if (isLenient)
{
LOG.warn("The stream doesn't provide any stream length, using fallback readUntilEnd, at offset "
+ source.getPosition());
}
else
{
throw new IOException("Missing length for stream.");
}
}
// get output stream to copy data to
try (OutputStream out = stream.createRawOutputStream())
{
if (streamLengthObj != null && validateStreamLength(streamLengthObj.longValue()))
{
readValidStream(out, streamLengthObj);
}
else
{
readUntilEndStream(new EndstreamOutputStream(out));
}
}
String endStream = readString();
if (endStream.equals("endobj") && isLenient)
{
LOG.warn("stream ends with 'endobj' instead of 'endstream' at offset "
+ source.getPosition());
// avoid follow-up warning about missing endobj
source.rewind(ENDOBJ.length);
}
else if (endStream.length() > 9 && isLenient && endStream.substring(0,9).equals(ENDSTREAM_STRING))
{
LOG.warn("stream ends with '" + endStream + "' instead of 'endstream' at offset "
+ source.getPosition());
// unread the "extra" bytes
source.rewind(endStream.substring(9).getBytes(StandardCharsets.ISO_8859_1).length);
}
else if (!endStream.equals(ENDSTREAM_STRING))
{
throw new IOException(
"Error reading stream, expected='endstream' actual='"
+ endStream + "' at offset " + source.getPosition());
}
return stream;
}
/**
* This method will read through the current stream object until
* we find the keyword "endstream" meaning we're at the end of this
* object. Some pdf files, however, forget to write some endstream tags
* and just close off objects with an "endobj" tag so we have to handle
* this case as well.
*
* This method is optimized using buffered IO and reduced number of
* byte compare operations.
*
* @param out stream we write out to.
*
* @throws IOException if something went wrong
*/
private void readUntilEndStream( final OutputStream out ) throws IOException
{
int bufSize;
int charMatchCount = 0;
byte[] keyw = ENDSTREAM;
// last character position of shortest keyword ('endobj')
final int quickTestOffset = 5;
// read next chunk into buffer; already matched chars are added to beginning of buffer
while ( ( bufSize = source.read( strmBuf, charMatchCount, STRMBUFLEN - charMatchCount ) ) > 0 )
{
bufSize += charMatchCount;
int bIdx = charMatchCount;
int quickTestIdx;
// iterate over buffer, trying to find keyword match
for ( int maxQuicktestIdx = bufSize - quickTestOffset; bIdx < bufSize; bIdx++ )
{
// reduce compare operations by first test last character we would have to
// match if current one matches; if it is not a character from keywords
// we can move behind the test character; this shortcut is inspired by the
// Boyer-Moore string search algorithm and can reduce parsing time by approx. 20%
quickTestIdx = bIdx + quickTestOffset;
if (charMatchCount == 0 && quickTestIdx < maxQuicktestIdx)
{
final byte ch = strmBuf[quickTestIdx];
if ( ( ch > 't' ) || ( ch < 'a' ) )
{
// last character we would have to match if current character would match
// is not a character from keywords -> jump behind and start over
bIdx = quickTestIdx;
continue;
}
}
// could be negative - but we only compare to ASCII
final byte ch = strmBuf[bIdx];
if ( ch == keyw[ charMatchCount ] )
{
if ( ++charMatchCount == keyw.length )
{
// match found
bIdx++;
break;
}
}
else
{
if ( ( charMatchCount == 3 ) && ( ch == ENDOBJ[ charMatchCount ] ) )
{
// maybe ENDSTREAM is missing but we could have ENDOBJ
keyw = ENDOBJ;
charMatchCount++;
}
else
{
// no match; incrementing match start by 1 would be dumb since we already know
// matched chars depending on current char read we may already have beginning
// of a new match: 'e': first char matched; 'n': if we are at match position
// idx 7 we already read 'e' thus 2 chars matched for each other char we have
// to start matching first keyword char beginning with next read position
charMatchCount = ( ch == E ) ? 1 : ( ( ch == N ) && ( charMatchCount == 7 ) ) ? 2 : 0;
// search again for 'endstream'
keyw = ENDSTREAM;
}
}
}
int contentBytes = Math.max( 0, bIdx - charMatchCount );
// write buffer content until first matched char to output stream
if ( contentBytes > 0 )
{
out.write( strmBuf, 0, contentBytes );
}
if ( charMatchCount == keyw.length )
{
// keyword matched; unread matched keyword (endstream/endobj) and following buffered content
source.rewind( bufSize - contentBytes );
break;
}
else
{
// copy matched chars at start of buffer
System.arraycopy( keyw, 0, strmBuf, 0, charMatchCount );
}
}
// this writes a lonely CR or drops trailing CR LF and LF
out.flush();
}
private void readValidStream(OutputStream out, COSNumber streamLengthObj) throws IOException
{
long remainBytes = streamLengthObj.longValue();
while (remainBytes > 0)
{
final int chunk = (remainBytes > STREAMCOPYBUFLEN) ? STREAMCOPYBUFLEN : (int) remainBytes;
final int readBytes = source.read(streamCopyBuf, 0, chunk);
if (readBytes <= 0)
{
// shouldn't happen, the stream length has already been validated
throw new IOException("read error at offset " + source.getPosition()
+ ": expected " + chunk + " bytes, but read() returns " + readBytes);
}
out.write(streamCopyBuf, 0, readBytes);
remainBytes -= readBytes;
}
}
private boolean validateStreamLength(long streamLength) throws IOException
{
boolean streamLengthIsValid = true;
long originOffset = source.getPosition();
long expectedEndOfStream = originOffset + streamLength;
if (expectedEndOfStream > fileLen)
{
streamLengthIsValid = false;
LOG.warn("The end of the stream is out of range, using workaround to read the stream, "
+ "stream start position: " + originOffset + ", length: " + streamLength
+ ", expected end position: " + expectedEndOfStream);
}
else
{
source.seek(expectedEndOfStream);
skipSpaces();
if (!isString(ENDSTREAM))
{
streamLengthIsValid = false;
LOG.warn("The end of the stream doesn't point to the correct offset, using workaround to read the stream, "
+ "stream start position: " + originOffset + ", length: " + streamLength
+ ", expected end position: " + expectedEndOfStream);
}
source.seek(originOffset);
}
return streamLengthIsValid;
}
/**
* Check if the cross reference table/stream can be found at the current offset.
*
* @param startXRefOffset
* @return the revised offset
* @throws IOException
*/
private long checkXRefOffset(long startXRefOffset) throws IOException
{
// repair mode isn't available in non-lenient mode
if (!isLenient)
{
return startXRefOffset;
}
source.seek(startXRefOffset);
skipSpaces();
if (isString(XREF_TABLE))
{
return startXRefOffset;
}
if (startXRefOffset > 0)
{
if (checkXRefStreamOffset(startXRefOffset))
{
return startXRefOffset;
}
else
{
return calculateXRefFixedOffset(startXRefOffset);
}
}
// can't find a valid offset
return -1;
}
/**
* Check if the cross reference stream can be found at the current offset.
*
* @param startXRefOffset the expected start offset of the XRef stream
* @return the revised offset
* @throws IOException if something went wrong
*/
private boolean checkXRefStreamOffset(long startXRefOffset) throws IOException
{
// repair mode isn't available in non-lenient mode
if (!isLenient || startXRefOffset == 0)
{
return true;
}
// seek to offset-1
source.seek(startXRefOffset-1);
int nextValue = source.read();
// the first character has to be a whitespace, and then a digit
if (isWhitespace(nextValue))
{
skipSpaces();
if (isDigit())
{
try
{
// it's a XRef stream
readObjectNumber();
readGenerationNumber();
readExpectedString(OBJ_MARKER, true);
// check the dictionary to avoid false positives
COSDictionary dict = parseCOSDictionary();
source.seek(startXRefOffset);
if ("XRef".equals(dict.getNameAsString(COSName.TYPE)))
{
return true;
}
}
catch (IOException exception)
{
// there wasn't an object of a xref stream
LOG.debug("No Xref stream at given location " + startXRefOffset, exception);
source.seek(startXRefOffset);
}
}
}
return false;
}
/**
* Try to find a fixed offset for the given xref table/stream.
*
* @param objectOffset the given offset where to look at
* @return the fixed offset
*
* @throws IOException if something went wrong
*/
private long calculateXRefFixedOffset(long objectOffset) throws IOException
{
if (objectOffset < 0)
{
LOG.error("Invalid object offset " + objectOffset + " when searching for a xref table/stream");
return 0;
}
// start a brute force search for all xref tables and try to find the offset we are looking for
long newOffset = bfSearchForXRef(objectOffset);
if (newOffset > -1)
{
LOG.debug("Fixed reference for xref table/stream " + objectOffset + " -> " + newOffset);
return newOffset;
}
LOG.error("Can't find the object xref table/stream at offset " + objectOffset);
return 0;
}
private boolean validateXrefOffsets(Map<COSObjectKey, Long> xrefOffset) throws IOException
{
if (xrefOffset == null)
{
return true;
}
for (Entry<COSObjectKey, Long> objectEntry : xrefOffset.entrySet())
{
COSObjectKey objectKey = objectEntry.getKey();
Long objectOffset = objectEntry.getValue();
// a negative offset number represents an object number itself
// see type 2 entry in xref stream
if (objectOffset != null && objectOffset >= 0
&& !checkObjectKey(objectKey, objectOffset))
{
LOG.debug("Stop checking xref offsets as at least one (" + objectKey
+ ") couldn't be dereferenced");
return false;
}
}
return true;
}
/**
* Check the XRef table by dereferencing all objects and fixing the offset if necessary.
*
* @throws IOException if something went wrong.
*/
private void checkXrefOffsets() throws IOException
{
// repair mode isn't available in non-lenient mode
if (!isLenient)
{
return;
}
Map<COSObjectKey, Long> xrefOffset = xrefTrailerResolver.getXrefTable();
if (!validateXrefOffsets(xrefOffset))
{
Map<COSObjectKey, Long> bfCOSObjectKeyOffsets = getBFCOSObjectOffsets();
if (!bfCOSObjectKeyOffsets.isEmpty())
{
LOG.debug("Replaced read xref table with the results of a brute force search");
xrefOffset.clear();
xrefOffset.putAll(bfCOSObjectKeyOffsets);
}
}
}
/**
* Check if the given object can be found at the given offset.
*
* @param objectKey the object we are looking for
* @param offset the offset where to look
* @return returns true if the given object can be dereferenced at the given offset
* @throws IOException if something went wrong
*/
private boolean checkObjectKey(COSObjectKey objectKey, long offset) throws IOException
{
// there can't be any object at the very beginning of a pdf
if (offset < MINIMUM_SEARCH_OFFSET)
{
return false;
}
boolean objectKeyFound = false;
try
{
source.seek(offset);
// try to read the given object/generation number
if (objectKey.getNumber() == readObjectNumber())
{
int genNumber = readGenerationNumber();
if (genNumber == objectKey.getGeneration())
{
// finally try to read the object marker
readExpectedString(OBJ_MARKER, true);
objectKeyFound = true;
}
else if (isLenient && genNumber > objectKey.getGeneration())
{
// finally try to read the object marker
readExpectedString(OBJ_MARKER, true);
objectKeyFound = true;
objectKey.fixGeneration(genNumber);
}
}
}
catch (IOException exception)
{
// Swallow the exception, obviously there isn't any valid object number
LOG.debug("No valid object at given location " + offset + " - ignoring", exception);
}
// return resulting value
return objectKeyFound;
}
private Map<COSObjectKey, Long> getBFCOSObjectOffsets() throws IOException
{
if (bfSearchCOSObjectKeyOffsets == null)
{
bfSearchForObjects();
}
return bfSearchCOSObjectKeyOffsets;
}
/**
* Brute force search for every object in the pdf.
*
* @throws IOException if something went wrong
*/
private void bfSearchForObjects() throws IOException
{
long lastEOFMarker = bfSearchForLastEOFMarker();
bfSearchCOSObjectKeyOffsets = new HashMap<>();
long originOffset = source.getPosition();
long currentOffset = MINIMUM_SEARCH_OFFSET;
long lastObjectId = Long.MIN_VALUE;
int lastGenID = Integer.MIN_VALUE;
long lastObjOffset = Long.MIN_VALUE;
char[] endobjString = "ndo".toCharArray();
char[] endobjRemainingString = "bj".toCharArray();
boolean endOfObjFound = false;
do
{
source.seek(currentOffset);
int nextChar = source.read();
currentOffset++;
if (isWhitespace(nextChar) && isString(OBJ_MARKER))
{
long tempOffset = currentOffset - 2;
source.seek(tempOffset);
int genID = source.peek();
// is the next char a digit?
if (isDigit(genID))
{
genID -= 48;
tempOffset--;
source.seek(tempOffset);
if (isWhitespace())
{
while (tempOffset > MINIMUM_SEARCH_OFFSET && isWhitespace())
{
source.seek(--tempOffset);
}
boolean objectIDFound = false;
while (tempOffset > MINIMUM_SEARCH_OFFSET && isDigit())
{
source.seek(--tempOffset);
objectIDFound = true;
}
if (objectIDFound)
{
source.read();
long objectId = readObjectNumber();
if (lastObjOffset > 0)
{
// add the former object ID only if there was a subsequent object ID
bfSearchCOSObjectKeyOffsets.put(
new COSObjectKey(lastObjectId, lastGenID), lastObjOffset);
}
lastObjectId = objectId;
lastGenID = genID;
lastObjOffset = tempOffset + 1;
currentOffset += OBJ_MARKER.length - 1;
endOfObjFound = false;
}
}
}
}
// check for "endo" as abbreviation for "endobj", as the pdf may be cut off
// in the middle of the keyword, see PDFBOX-3936.
// We could possibly implement a more intelligent algorithm if necessary
else if (nextChar == 'e' && isString(endobjString))
{
currentOffset += endobjString.length;
source.seek(currentOffset);
if (source.isEOF())
{
endOfObjFound = true;
continue;
}
if (isString(endobjRemainingString))
{
currentOffset += endobjRemainingString.length;
endOfObjFound = true;
continue;
}
}
} while (currentOffset < lastEOFMarker && !source.isEOF());
if ((lastEOFMarker < Long.MAX_VALUE || endOfObjFound) && lastObjOffset > 0)
{
// if the pdf wasn't cut off in the middle or if the last object ends with a "endobj" marker
// the last object id has to be added here so that it can't get lost as there isn't any subsequent object id
bfSearchCOSObjectKeyOffsets.put(new COSObjectKey(lastObjectId, lastGenID),
lastObjOffset);
}
// reestablish origin position
source.seek(originOffset);
}
/**
* Search for the offset of the given xref table/stream among those found by a brute force search.
*
* @return the offset of the xref entry
* @throws IOException if something went wrong
*/
private long bfSearchForXRef(long xrefOffset) throws IOException
{
long newOffset = -1;
// initialize bfSearchXRefTablesOffsets -> not null
bfSearchForXRefTables();
// initialize bfSearchXRefStreamsOffsets -> not null
bfSearchForXRefStreams();
// TODO to be optimized, this won't work in every case
long newOffsetTable = searchNearestValue(bfSearchXRefTablesOffsets, xrefOffset);
// TODO to be optimized, this won't work in every case
long newOffsetStream = searchNearestValue(bfSearchXRefStreamsOffsets, xrefOffset);
// choose the nearest value
if (newOffsetTable > -1 && newOffsetStream > -1)
{
long differenceTable = xrefOffset - newOffsetTable;
long differenceStream = xrefOffset - newOffsetStream;
if (Math.abs(differenceTable) > Math.abs(differenceStream))
{
newOffset = newOffsetStream;
bfSearchXRefStreamsOffsets.remove(newOffsetStream);
}
else
{
newOffset = newOffsetTable;
bfSearchXRefTablesOffsets.remove(newOffsetTable);
}
}
else if (newOffsetTable > -1)
{
newOffset = newOffsetTable;
bfSearchXRefTablesOffsets.remove(newOffsetTable);
}
else if (newOffsetStream > -1)
{
newOffset = newOffsetStream;
bfSearchXRefStreamsOffsets.remove(newOffsetStream);
}
return newOffset;
}
private long searchNearestValue(List<Long> values, long offset)
{
long newValue = -1;
Long currentDifference = null;
int currentOffsetIndex = -1;
int numberOfOffsets = values.size();
// find the nearest value
for (int i = 0; i < numberOfOffsets; i++)
{
long newDifference = offset - values.get(i);
// find the nearest offset
if (currentDifference == null
|| (Math.abs(currentDifference) > Math.abs(newDifference)))
{
currentDifference = newDifference;
currentOffsetIndex = i;
}
}
if (currentOffsetIndex > -1)
{
newValue = values.get(currentOffsetIndex);
}
return newValue;
}
/**
* Brute force search for all trailer marker.
*
* @throws IOException if something went wrong
*/
private boolean bfSearchForTrailer(COSDictionary trailer) throws IOException
{
Map<String, COSDictionary> trailerDicts = new HashMap<>();
long originOffset = source.getPosition();
source.seek(MINIMUM_SEARCH_OFFSET);
// search for trailer marker
long trailerOffset = findString(TRAILER_MARKER);
while (trailerOffset != -1)
{
try
{
boolean rootFound = false;
boolean infoFound = false;
skipSpaces();
COSDictionary trailerDict = parseCOSDictionary();
StringBuilder trailerKeys = new StringBuilder();
COSObject rootObj = trailerDict.getCOSObject(COSName.ROOT);
if (rootObj != null)
{
long objNumber = rootObj.getObjectNumber();
int genNumber = rootObj.getGenerationNumber();
trailerKeys.append(objNumber).append(" ");
trailerKeys.append(genNumber).append(" ");
rootFound = true;
}
COSObject infoObj = trailerDict.getCOSObject(COSName.INFO);
if (infoObj != null)
{
long objNumber = infoObj.getObjectNumber();
int genNumber = infoObj.getGenerationNumber();
trailerKeys.append(objNumber).append(" ");
trailerKeys.append(genNumber).append(" ");
infoFound = true;
}
if (rootFound && infoFound)
{
trailerDicts.put(trailerKeys.toString(), trailerDict);
}
}
catch (IOException exception)
{
LOG.debug("An exception occurred during brute force search for trailer - ignoring",
exception);
}
trailerOffset = findString(TRAILER_MARKER);
}
source.seek(originOffset);
// eliminate double entries
int trailerdictsSize = trailerDicts.size();
String firstEntry = null;
if (trailerdictsSize > 0)
{
String[] keys = new String[trailerdictsSize];
trailerDicts.keySet().toArray(keys);
firstEntry = keys[0];
for (int i = 1; i < trailerdictsSize; i++)
{
if (firstEntry.equals(keys[i]))
{
trailerDicts.remove(keys[i]);
}
}
}
// continue if one entry is left only
if (trailerDicts.size() == 1)
{
boolean rootFound = false;
boolean infoFound = false;
COSDictionary trailerDict = trailerDicts.get(firstEntry);
COSBase rootObj = trailerDict.getItem(COSName.ROOT);
if (rootObj instanceof COSObject)
{
// check if the dictionary can be dereferenced and is the one we are looking for
COSBase rootDict = ((COSObject) rootObj).getObject();
if (rootDict instanceof COSDictionary && isCatalog((COSDictionary) rootDict))
{
rootFound = true;
}
}
COSBase infoObj = trailerDict.getItem(COSName.INFO);
if (infoObj instanceof COSObject)
{
// check if the dictionary can be dereferenced and is the one we are looking for
COSBase infoDict = ((COSObject) infoObj).getObject();
if (infoDict instanceof COSDictionary && isInfo((COSDictionary) infoDict))
{
infoFound = true;
}
}
if (rootFound && infoFound)
{
trailer.setItem(COSName.ROOT, rootObj);
trailer.setItem(COSName.INFO, infoObj);
if (trailerDict.containsKey(COSName.ENCRYPT))
{
COSBase encObj = trailerDict.getItem(COSName.ENCRYPT);
if (encObj instanceof COSObject)
{
// check if the dictionary can be dereferenced
// TODO check if the dictionary is an encryption dictionary?
COSBase encDict = ((COSObject) encObj).getObject();
if (encDict instanceof COSDictionary)
{
trailer.setItem(COSName.ENCRYPT, encObj);
}
}
}
if (trailerDict.containsKey(COSName.ID))
{
COSBase idObj = trailerDict.getItem(COSName.ID);
if (idObj instanceof COSArray)
{
trailer.setItem(COSName.ID, idObj);
}
}
return true;
}
}
return false;
}
/**
* Brute force search for the last EOF marker.
*
* @throws IOException if something went wrong
*/
private long bfSearchForLastEOFMarker() throws IOException
{
long lastEOFMarker = -1;
long originOffset = source.getPosition();
source.seek(MINIMUM_SEARCH_OFFSET);
long tempMarker = findString(EOF_MARKER);
while (tempMarker != -1)
{
try
{
// check if the following data is some valid pdf content
// which most likely indicates that the pdf is linearized,
// updated or just cut off somewhere in the middle
skipSpaces();
if (!isString(XREF_TABLE))
{
readObjectNumber();
readGenerationNumber();
}
}
catch (IOException exception)
{
// save the EOF marker as the following data is most likely some garbage
LOG.debug("An exception occurred during brute force for last EOF - ignoring",
exception);
lastEOFMarker = tempMarker;
}
tempMarker = findString(EOF_MARKER);
}
source.seek(originOffset);
// no EOF marker found
if (lastEOFMarker == -1)
{
lastEOFMarker = Long.MAX_VALUE;
}
return lastEOFMarker;
}
/**
* Brute force search for all object streams.
*
* @throws IOException if something went wrong
*/
private void bfSearchForObjStreams() throws IOException
{
// save origin offset
long originOffset = source.getPosition();
Map<Long, COSObjectKey> bfSearchForObjStreamOffsets = bfSearchForObjStreamOffsets();
// log warning about skipped stream
bfSearchForObjStreamOffsets.entrySet().stream() //
.filter(o -> bfSearchCOSObjectKeyOffsets.get(o.getValue()) == null) //
.forEach(o -> LOG.warn(
"Skipped incomplete object stream:" + o.getValue() + " at " + o.getKey()));
// collect all stream offsets
List<Long> objStreamOffsets = bfSearchForObjStreamOffsets.entrySet().stream() //
.filter(o -> bfSearchCOSObjectKeyOffsets.get(o.getValue()) != null) //
.filter(o -> o.getKey().equals(bfSearchCOSObjectKeyOffsets.get(o.getValue()))) //
.map(Map.Entry::getKey) //
.collect(Collectors.toList());
// add all found compressed objects to the brute force search result
for (Long offset : objStreamOffsets)
{
source.seek(offset);
long stmObjNumber = readObjectNumber();
int stmGenNumber = readGenerationNumber();
readExpectedString(OBJ_MARKER, true);
COSStream stream = null;
try
{
COSDictionary dict = parseCOSDictionary();
stream = parseCOSStream(dict);
if (securityHandler != null)
{
securityHandler.decryptStream(stream, stmObjNumber, stmGenNumber);
}
PDFObjectStreamParser objStreamParser = new PDFObjectStreamParser(stream, document);
Map<Long, Integer> objectNumbers = objStreamParser.readObjectNumbers();
Map<COSObjectKey, Long> xrefOffset = xrefTrailerResolver.getXrefTable();
for (Long objNumber : objectNumbers.keySet())
{
COSObjectKey objKey = new COSObjectKey(objNumber, 0);
Long existingOffset = bfSearchCOSObjectKeyOffsets.get(objKey);
if (existingOffset != null && existingOffset < 0)
{
// translate stream object key to its offset
COSObjectKey objStmKey = new COSObjectKey(Math.abs(existingOffset), 0);
existingOffset = bfSearchCOSObjectKeyOffsets.get(objStmKey);
}
if (existingOffset == null || offset > existingOffset)
{
bfSearchCOSObjectKeyOffsets.put(objKey, -stmObjNumber);
xrefOffset.put(objKey, -stmObjNumber);
}
}
}
catch (IOException exception)
{
LOG.debug("Skipped corrupt stream: (" + stmObjNumber + " 0 at offset " + offset,
exception);
}
finally
{
if (stream != null)
{
stream.close();
}
}
}
// restore origin offset
source.seek(originOffset);
}
/**
* Search for all offsets of object streams within the given pdf
*
* @return a map of all offsets for object streams
* @throws IOException if something went wrong
*/
private Map<Long, COSObjectKey> bfSearchForObjStreamOffsets() throws IOException
{
HashMap<Long, COSObjectKey> bfSearchObjStreamsOffsets = new HashMap<>();
source.seek(MINIMUM_SEARCH_OFFSET);
char[] string = " obj".toCharArray();
// search for object stream marker
long positionObjStream = findString(OBJ_STREAM);
while (positionObjStream != -1)
{
// search backwards for the beginning of the object
long newOffset = -1;
boolean objFound = false;
for (int i = 1; i < 40 && !objFound; i++)
{
long currentOffset = positionObjStream - (i * 10);
if (currentOffset > 0)
{
source.seek(currentOffset);
for (int j = 0; j < 10; j++)
{
if (isString(string))
{
long tempOffset = currentOffset - 1;
source.seek(tempOffset);
int genID = source.peek();
// is the next char a digit?
if (isDigit(genID))
{
tempOffset--;
source.seek(tempOffset);
if (isSpace())
{
int length = 0;
source.seek(--tempOffset);
while (tempOffset > MINIMUM_SEARCH_OFFSET && isDigit())
{
source.seek(--tempOffset);
length++;
}
if (length > 0)
{
source.read();
newOffset = source.getPosition();
long objNumber = readObjectNumber();
int genNumber = readGenerationNumber();
COSObjectKey streamObjectKey = new COSObjectKey(objNumber,
genNumber);
bfSearchObjStreamsOffsets.put(newOffset, streamObjectKey);
}
}
}
LOG.debug("Dictionary start for object stream -> " + newOffset);
objFound = true;
break;
}
else
{
currentOffset++;
source.read();
}
}
}
}
source.seek(positionObjStream + OBJ_STREAM.length);
positionObjStream = findString(OBJ_STREAM);
}
return bfSearchObjStreamsOffsets;
}
/**
* Brute force search for all xref entries (tables).
*
* @throws IOException if something went wrong
*/
private void bfSearchForXRefTables() throws IOException
{
if (bfSearchXRefTablesOffsets == null)
{
// a pdf may contain more than one xref entry
bfSearchXRefTablesOffsets = new ArrayList<>();
source.seek(MINIMUM_SEARCH_OFFSET);
// search for xref tables
long newOffset = findString(XREF_TABLE);
while (newOffset != -1)
{
source.seek(newOffset - 1);
// ensure that we don't read "startxref" instead of "xref"
if (isWhitespace())
{
bfSearchXRefTablesOffsets.add(newOffset);
}
source.seek(newOffset + 4);
newOffset = findString(XREF_TABLE);
}
}
}
/**
* Brute force search for all /XRef entries (streams).
*
* @throws IOException if something went wrong
*/
private void bfSearchForXRefStreams() throws IOException
{
if (bfSearchXRefStreamsOffsets == null)
{
// a pdf may contain more than one /XRef entry
bfSearchXRefStreamsOffsets = new ArrayList<>();
source.seek(MINIMUM_SEARCH_OFFSET);
// search for XRef streams
String objString = " obj";
char[] string = objString.toCharArray();
long xrefOffset = findString(XREF_STREAM);
while (xrefOffset != -1)
{
// search backwards for the beginning of the stream
long newOffset = -1;
boolean objFound = false;
for (int i = 1; i < 40 && !objFound; i++)
{
long currentOffset = xrefOffset - (i * 10);
if (currentOffset > 0)
{
source.seek(currentOffset);
for (int j = 0; j < 10; j++)
{
if (isString(string))
{
long tempOffset = currentOffset - 1;
source.seek(tempOffset);
int genID = source.peek();
// is the next char a digit?
if (isDigit(genID))
{
tempOffset--;
source.seek(tempOffset);
if (isSpace())
{
int length = 0;
source.seek(--tempOffset);
while (tempOffset > MINIMUM_SEARCH_OFFSET && isDigit())
{
source.seek(--tempOffset);
length++;
}
if (length > 0)
{
source.read();
newOffset = source.getPosition();
}
}
}
LOG.debug("Fixed reference for xref stream " + xrefOffset + " -> "
+ newOffset);
objFound = true;
break;
}
else
{
currentOffset++;
source.read();
}
}
}
}
if (newOffset > -1)
{
bfSearchXRefStreamsOffsets.add(newOffset);
}
source.seek(xrefOffset + 5);
xrefOffset = findString(XREF_STREAM);
}
}
}
/**
* Rebuild the trailer dictionary if startxref can't be found.
*
* @return the rebuild trailer dictionary
*
* @throws IOException if something went wrong
*/
private COSDictionary rebuildTrailer() throws IOException
{
COSDictionary trailer = null;
bfSearchForObjects();
if (bfSearchCOSObjectKeyOffsets != null)
{
// reset trailer resolver
xrefTrailerResolver.reset();
// use the found objects to rebuild the trailer resolver
xrefTrailerResolver.nextXrefObj(0, XRefType.TABLE);
for (Entry<COSObjectKey, Long> entry : bfSearchCOSObjectKeyOffsets.entrySet())
{
xrefTrailerResolver.setXRef(entry.getKey(), entry.getValue());
}
xrefTrailerResolver.setStartxref(0);
trailer = xrefTrailerResolver.getTrailer();
document.setTrailer(trailer);
boolean searchForObjStreamsDone = false;
if (!bfSearchForTrailer(trailer) && !searchForTrailerItems(trailer))
{
// root entry wasn't found, maybe it is part of an object stream
bfSearchForObjStreams();
searchForObjStreamsDone = true;
// search again for the root entry
searchForTrailerItems(trailer);
}
// prepare decryption if necessary
prepareDecryption();
if (!searchForObjStreamsDone)
{
bfSearchForObjStreams();
}
}
trailerWasRebuild = true;
return trailer;
}
/**
* Search for the different parts of the trailer dictionary.
*
* @param trailer
* @return true if the root was found, false if not.
*/
private boolean searchForTrailerItems(COSDictionary trailer)
{
boolean rootFound = false;
for (COSObjectKey key : bfSearchCOSObjectKeyOffsets.keySet())
{
COSObject cosObject = document.getObjectFromPool(key);
COSBase baseObject = cosObject.getObject();
if (!(baseObject instanceof COSDictionary))
{
continue;
}
COSDictionary dictionary = (COSDictionary) baseObject;
// document catalog
if (isCatalog(dictionary))
{
trailer.setItem(COSName.ROOT, cosObject);
rootFound = true;
}
// info dictionary
else if (isInfo(dictionary))
{
trailer.setItem(COSName.INFO, cosObject);
}
// encryption dictionary, if existing, is lost
// We can't run "Algorithm 2" from PDF specification because of missing ID
}
return rootFound;
}
/**
* Check if all entries of the pages dictionary are present. Those which can't be dereferenced are removed.
*
* @param root the root dictionary of the pdf
* @throws java.io.IOException if the page tree root is null
*/
protected void checkPages(COSDictionary root) throws IOException
{
if (trailerWasRebuild)
{
// check if all page objects are dereferenced
COSBase pages = root.getDictionaryObject(COSName.PAGES);
if (pages instanceof COSDictionary)
{
checkPagesDictionary((COSDictionary) pages, new HashSet<>());
}
}
if (!(root.getDictionaryObject(COSName.PAGES) instanceof COSDictionary))
{
throw new IOException("Page tree root must be a dictionary");
}
}
private int checkPagesDictionary(COSDictionary pagesDict, Set<COSObject> set)
{
// check for kids
COSBase kids = pagesDict.getDictionaryObject(COSName.KIDS);
int numberOfPages = 0;
if (kids instanceof COSArray)
{
COSArray kidsArray = (COSArray) kids;
List<? extends COSBase> kidsList = kidsArray.toList();
for (COSBase kid : kidsList)
{
if (!(kid instanceof COSObject) || set.contains((COSObject) kid))
{
kidsArray.remove(kid);
continue;
}
COSObject kidObject = (COSObject) kid;
COSBase kidBaseobject = kidObject.getObject();
// object wasn't dereferenced -> remove it
if (kidBaseobject == null || kidBaseobject.equals(COSNull.NULL))
{
LOG.warn("Removed null object " + kid + " from pages dictionary");
kidsArray.remove(kid);
}
else if (kidBaseobject instanceof COSDictionary)
{
COSDictionary kidDictionary = (COSDictionary) kidBaseobject;
COSName type = kidDictionary.getCOSName(COSName.TYPE);
if (COSName.PAGES.equals(type))
{
// process nested pages dictionaries
set.add(kidObject);
numberOfPages += checkPagesDictionary(kidDictionary, set);
}
else if (COSName.PAGE.equals(type))
{
// count pages
numberOfPages++;
}
}
}
}
// fix counter
pagesDict.setInt(COSName.COUNT, numberOfPages);
return numberOfPages;
}
/**
* Tell if the dictionary is a PDF catalog. Override this for an FDF catalog.
*
* @param dictionary
* @return true if the given dictionary is a root dictionary
*/
protected boolean isCatalog(COSDictionary dictionary)
{
return COSName.CATALOG.equals(dictionary.getCOSName(COSName.TYPE));
}
/**
* Tell if the dictionary is an info dictionary.
*
* @param dictionary
* @return true if the given dictionary is an info dictionary
*/
private boolean isInfo(COSDictionary dictionary)
{
if (dictionary.containsKey(COSName.PARENT) || dictionary.containsKey(COSName.A)
|| dictionary.containsKey(COSName.DEST))
{
return false;
}
if (!dictionary.containsKey(COSName.MOD_DATE) && !dictionary.containsKey(COSName.TITLE)
&& !dictionary.containsKey(COSName.AUTHOR)
&& !dictionary.containsKey(COSName.SUBJECT)
&& !dictionary.containsKey(COSName.KEYWORDS)
&& !dictionary.containsKey(COSName.CREATOR)
&& !dictionary.containsKey(COSName.PRODUCER)
&& !dictionary.containsKey(COSName.CREATION_DATE))
{
return false;
}
return true;
}
/**
* This will parse the startxref section from the stream. The startxref value is ignored.
*
* @return the startxref value or -1 on parsing error
* @throws IOException If an IO error occurs.
*/
private long parseStartXref() throws IOException
{
long startXref = -1;
if (isString(STARTXREF))
{
readString();
skipSpaces();
// This integer is the byte offset of the first object referenced by the xref or xref stream
startXref = readLong();
}
return startXref;
}
/**
* Checks if the given string can be found at the current offset.
*
* @param string the bytes of the string to look for
* @return true if the bytes are in place, false if not
* @throws IOException if something went wrong
*/
private boolean isString(byte[] string) throws IOException
{
boolean bytesMatching = true;
long originOffset = source.getPosition();
for (byte c : string)
{
if (source.read() != c)
{
bytesMatching = false;
break;
}
}
source.seek(originOffset);
return bytesMatching;
}
/**
* Checks if the given string can be found at the current offset.
*
* @param string the bytes of the string to look for
* @return true if the bytes are in place, false if not
* @throws IOException if something went wrong
*/
private boolean isString(char[] string) throws IOException
{
boolean bytesMatching = true;
long originOffset = source.getPosition();
for (char c : string)
{
if (source.read() != c)
{
bytesMatching = false;
break;
}
}
source.seek(originOffset);
return bytesMatching;
}
/**
* Search for the given string. The search starts at the current position and returns the start position if the
* string was found. -1 is returned if there isn't any further occurrence of the given string. After returning the
* current position is either the end of the string or the end of the input.
*
* @param string the string to be searched
* @return the start position of the found string
* @throws IOException if something went wrong
*/
private long findString(char[] string) throws IOException
{
long position = -1L;
int stringLength = string.length;
int counter = 0;
int readChar = source.read();
while (readChar != -1)
{
if (readChar == string[counter])
{
if (counter == 0)
{
position = source.getPosition();
}
counter++;
if (counter == stringLength)
{
return position;
}
}
else if (counter > 0)
{
counter = 0;
position = -1L;
continue;
}
readChar = source.read();
}
return position;
}
/**
* This will parse the trailer from the stream and add it to the state.
*
* @return false on parsing error
* @throws IOException If an IO error occurs.
*/
private boolean parseTrailer() throws IOException
{
// parse the last trailer.
long trailerOffset = source.getPosition();
// PDFBOX-1739 skip extra xref entries in RegisSTAR documents
if (isLenient)
{
int nextCharacter = source.peek();
while (nextCharacter != 't' && isDigit(nextCharacter))
{
if (source.getPosition() == trailerOffset)
{
// warn only the first time
LOG.warn("Expected trailer object at offset " + trailerOffset
+ ", keep trying");
}
readLine();
nextCharacter = source.peek();
}
}
if(source.peek() != 't')
{
return false;
}
//read "trailer"
long currentOffset = source.getPosition();
String nextLine = readLine();
if( !nextLine.trim().equals( "trailer" ) )
{
// in some cases the EOL is missing and the trailer immediately
// continues with "<<" or with a blank character
// even if this does not comply with PDF reference we want to support as many PDFs as possible
// Acrobat reader can also deal with this.
if (nextLine.startsWith("trailer"))
{
// we can't just unread a portion of the read data as we don't know if the EOL consist of 1 or 2 bytes
int len = "trailer".length();
// jump back right after "trailer"
source.seek(currentOffset + len);
}
else
{
return false;
}
}
// in some cases the EOL is missing and the trailer continues with " <<"
// even if this does not comply with PDF reference we want to support as many PDFs as possible
// Acrobat reader can also deal with this.
skipSpaces();
COSDictionary parsedTrailer = parseCOSDictionary();
xrefTrailerResolver.setTrailer( parsedTrailer );
skipSpaces();
return true;
}
/**
* Parse the header of a pdf.
*
* @return true if a PDF header was found
* @throws IOException if something went wrong
*/
protected boolean parsePDFHeader() throws IOException
{
return parseHeader(PDF_HEADER, PDF_DEFAULT_VERSION);
}
/**
* Parse the header of a fdf.
*
* @return true if a FDF header was found
* @throws IOException if something went wrong
*/
protected boolean parseFDFHeader() throws IOException
{
return parseHeader(FDF_HEADER, FDF_DEFAULT_VERSION);
}
private boolean parseHeader(String headerMarker, String defaultVersion) throws IOException
{
// read first line
String header = readLine();
// some pdf-documents are broken and the pdf-version is in one of the following lines
if (!header.contains(headerMarker))
{
header = readLine();
while (!header.contains(headerMarker))
{
// if a line starts with a digit, it has to be the first one with data in it
if ((header.length() > 0) && (Character.isDigit(header.charAt(0))))
{
break;
}
header = readLine();
}
}
// nothing found
if (!header.contains(headerMarker))
{
source.seek(0);
return false;
}
//sometimes there is some garbage in the header before the header
//actually starts, so lets try to find the header first.
int headerStart = header.indexOf( headerMarker );
// greater than zero because if it is zero then there is no point of trimming
if ( headerStart > 0 )
{
//trim off any leading characters
header = header.substring( headerStart, header.length() );
}
// This is used if there is garbage after the header on the same line
if (header.startsWith(headerMarker) && !header.matches(headerMarker + "\\d.\\d"))
{
if (header.length() < headerMarker.length() + 3)
{
// No version number at all, set to 1.4 as default
header = headerMarker + defaultVersion;
LOG.debug("No version found, set to " + defaultVersion + " as default.");
}
else
{
String headerGarbage = header.substring(headerMarker.length() + 3, header.length()) + "\n";
header = header.substring(0, headerMarker.length() + 3);
source.rewind(headerGarbage.getBytes(StandardCharsets.ISO_8859_1).length);
}
}
float headerVersion = -1;
try
{
String[] headerParts = header.split("-");
if (headerParts.length == 2)
{
headerVersion = Float.parseFloat(headerParts[1]);
}
}
catch (NumberFormatException exception)
{
LOG.debug("Can't parse the header version.", exception);
}
if (headerVersion < 0)
{
if (isLenient)
{
headerVersion = 1.7f;
}
else
{
throw new IOException("Error getting header version: " + header);
}
}
document.setVersion(headerVersion);
// rewind
source.seek(0);
return true;
}
/**
* This will parse the xref table from the stream and add it to the state
* The XrefTable contents are ignored.
* @param startByteOffset the offset to start at
* @return false on parsing error
* @throws IOException If an IO error occurs.
*/
protected boolean parseXrefTable(long startByteOffset) throws IOException
{
if(source.peek() != 'x')
{
return false;
}
String xref = readString();
if( !xref.trim().equals( "xref" ) )
{
return false;
}
// check for trailer after xref
String str = readString();
byte[] b = str.getBytes(StandardCharsets.ISO_8859_1);
source.rewind(b.length);
// signal start of new XRef
xrefTrailerResolver.nextXrefObj( startByteOffset, XRefType.TABLE );
if (str.startsWith("trailer"))
{
LOG.warn("skipping empty xref table");
return false;
}
// Xref tables can have multiple sections. Each starts with a starting object id and a count.
while(true)
{
String currentLine = readLine();
String[] splitString = currentLine.split("\\s");
if (splitString.length != 2)
{
LOG.warn("Unexpected XRefTable Entry: " + currentLine);
return false;
}
// first obj id
long currObjID;
try
{
currObjID = Long.parseLong(splitString[0]);
}
catch (NumberFormatException exception)
{
LOG.warn("XRefTable: invalid ID for the first object: " + currentLine);
return false;
}
// the number of objects in the xref table
int count = 0;
try
{
count = Integer.parseInt(splitString[1]);
}
catch (NumberFormatException exception)
{
LOG.warn("XRefTable: invalid number of objects: " + currentLine);
return false;
}
skipSpaces();
for(int i = 0; i < count; i++)
{
if(source.isEOF() || isEndOfName((char)source.peek()))
{
break;
}
if(source.peek() == 't')
{
break;
}
//Ignore table contents
currentLine = readLine();
splitString = currentLine.split("\\s");
if (splitString.length < 3)
{
LOG.warn("invalid xref line: " + currentLine);
break;
}
/* This supports the corrupt table as reported in
* PDFBOX-474 (XXXX XXX XX n) */
if(splitString[splitString.length-1].equals("n"))
{
try
{
long currOffset = Long.parseLong(splitString[0]);
int currGenID = Integer.parseInt(splitString[1]);
COSObjectKey objKey = new COSObjectKey(currObjID, currGenID);
xrefTrailerResolver.setXRef(objKey, currOffset);
}
catch(NumberFormatException e)
{
throw new IOException(e);
}
}
else if(!splitString[2].equals("f"))
{
throw new IOException("Corrupt XRefTable Entry - ObjID:" + currObjID);
}
currObjID++;
skipSpaces();
}
skipSpaces();
if (!isDigit())
{
break;
}
}
return true;
}
/**
* Fills XRefTrailerResolver with data of given stream.
* Stream must be of type XRef.
* @param stream the stream to be read
* @param objByteOffset the offset to start at
* @param isStandalone should be set to true if the stream is not part of a hybrid xref table
* @throws IOException if there is an error parsing the stream
*/
private void parseXrefStream(COSStream stream, long objByteOffset, boolean isStandalone) throws IOException
{
// the cross reference stream of a hybrid xref table will be added to the existing one
// and we must not override the offset and the trailer
if ( isStandalone )
{
xrefTrailerResolver.nextXrefObj( objByteOffset, XRefType.STREAM );
xrefTrailerResolver.setTrailer( stream );
}
PDFXrefStreamParser parser = new PDFXrefStreamParser(stream, document, xrefTrailerResolver);
parser.parse();
}
/**
* This will get the encryption dictionary. The document must be parsed before this is called.
*
* @return The encryption dictionary of the document that was parsed.
*
* @throws IOException If there is an error getting the document.
*/
public PDEncryption getEncryption() throws IOException
{
if (document == null)
{
throw new IOException(
"You must parse the document first before calling getEncryption()");
}
return encryption;
}
/**
* This will get the AccessPermission. The document must be parsed before this is called.
*
* @return The access permission of document that was parsed.
*
* @throws IOException If there is an error getting the document.
*/
public AccessPermission getAccessPermission() throws IOException
{
if (document == null)
{
throw new IOException(
"You must parse the document first before calling getAccessPermission()");
}
return accessPermission;
}
/**
* Prepare for decryption.
*
* @throws InvalidPasswordException If the password is incorrect.
* @throws IOException if something went wrong
*/
private void prepareDecryption() throws IOException
{
if (encryption != null)
{
return;
}
COSBase trailerEncryptItem = document.getTrailer().getItem(COSName.ENCRYPT);
if (trailerEncryptItem == null || trailerEncryptItem instanceof COSNull)
{
return;
}
try
{
encryption = new PDEncryption(document.getEncryptionDictionary());
DecryptionMaterial decryptionMaterial;
if (keyStoreInputStream != null)
{
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(keyStoreInputStream, password.toCharArray());
decryptionMaterial = new PublicKeyDecryptionMaterial(ks, keyAlias, password);
}
else
{
decryptionMaterial = new StandardDecryptionMaterial(password);
}
securityHandler = encryption.getSecurityHandler();
securityHandler.prepareForDecryption(encryption, document.getDocumentID(),
decryptionMaterial);
accessPermission = securityHandler.getCurrentAccessPermission();
}
catch (IOException e)
{
throw e;
}
catch (GeneralSecurityException e)
{
throw new IOException("Error (" + e.getClass().getSimpleName()
+ ") while creating security handler for decryption", e);
}
finally
{
if (keyStoreInputStream != null)
{
IOUtils.closeQuietly(keyStoreInputStream);
}
}
}
}
|
pdfbox/src/main/java/org/apache/pdfbox/pdfparser/COSParser.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pdfbox.pdfparser;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pdfbox.cos.COSArray;
import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.cos.COSNull;
import org.apache.pdfbox.cos.COSNumber;
import org.apache.pdfbox.cos.COSObject;
import org.apache.pdfbox.cos.COSObjectKey;
import org.apache.pdfbox.cos.COSStream;
import org.apache.pdfbox.cos.ICOSParser;
import org.apache.pdfbox.io.IOUtils;
import org.apache.pdfbox.io.RandomAccessRead;
import org.apache.pdfbox.pdfparser.XrefTrailerResolver.XRefType;
import org.apache.pdfbox.pdmodel.encryption.AccessPermission;
import org.apache.pdfbox.pdmodel.encryption.DecryptionMaterial;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
import org.apache.pdfbox.pdmodel.encryption.PDEncryption;
import org.apache.pdfbox.pdmodel.encryption.PublicKeyDecryptionMaterial;
import org.apache.pdfbox.pdmodel.encryption.SecurityHandler;
import org.apache.pdfbox.pdmodel.encryption.StandardDecryptionMaterial;
/**
* COS-Parser which first reads startxref and xref tables in order to know valid objects and parse only these objects.
*
* This class is a much enhanced version of <code>QuickParser</code> presented in
* <a href="https://issues.apache.org/jira/browse/PDFBOX-1104">PDFBOX-1104</a> by Jeremy Villalobos.
*/
public class COSParser extends BaseParser implements ICOSParser
{
private static final String PDF_HEADER = "%PDF-";
private static final String FDF_HEADER = "%FDF-";
private static final String PDF_DEFAULT_VERSION = "1.4";
private static final String FDF_DEFAULT_VERSION = "1.0";
private static final char[] XREF_TABLE = new char[] { 'x', 'r', 'e', 'f' };
private static final char[] XREF_STREAM = new char[] { '/', 'X', 'R', 'e', 'f' };
private static final char[] STARTXREF = new char[] { 's','t','a','r','t','x','r','e','f' };
private static final byte[] ENDSTREAM = new byte[] { E, N, D, S, T, R, E, A, M };
private static final byte[] ENDOBJ = new byte[] { E, N, D, O, B, J };
private static final long MINIMUM_SEARCH_OFFSET = 6;
private static final int X = 'x';
private static final int STRMBUFLEN = 2048;
private final byte[] strmBuf = new byte[ STRMBUFLEN ];
protected final RandomAccessRead source;
private AccessPermission accessPermission;
private InputStream keyStoreInputStream = null;
@SuppressWarnings({"squid:S2068"})
private String password = "";
private String keyAlias = null;
/**
* The range within the %%EOF marker will be searched.
* Useful if there are additional characters after %%EOF within the PDF.
*/
public static final String SYSPROP_EOFLOOKUPRANGE =
"org.apache.pdfbox.pdfparser.nonSequentialPDFParser.eofLookupRange";
/**
* How many trailing bytes to read for EOF marker.
*/
private static final int DEFAULT_TRAIL_BYTECOUNT = 2048;
/**
* EOF-marker.
*/
protected static final char[] EOF_MARKER = new char[] { '%', '%', 'E', 'O', 'F' };
/**
* obj-marker.
*/
protected static final char[] OBJ_MARKER = new char[] { 'o', 'b', 'j' };
/**
* trailer-marker.
*/
private static final char[] TRAILER_MARKER = new char[] { 't', 'r', 'a', 'i', 'l', 'e', 'r' };
/**
* ObjStream-marker.
*/
private static final char[] OBJ_STREAM = new char[] { '/', 'O', 'b', 'j', 'S', 't', 'm' };
/**
* file length.
*/
protected long fileLen;
/**
* is parser using auto healing capacity ?
*/
private boolean isLenient = true;
protected boolean initialParseDone = false;
private boolean trailerWasRebuild = false;
/**
* Contains all found objects of a brute force search.
*/
private Map<COSObjectKey, Long> bfSearchCOSObjectKeyOffsets = null;
private List<Long> bfSearchXRefTablesOffsets = null;
private List<Long> bfSearchXRefStreamsOffsets = null;
private PDEncryption encryption = null;
/**
* The security handler.
*/
protected SecurityHandler securityHandler = null;
/**
* how many trailing bytes to read for EOF marker.
*/
private int readTrailBytes = DEFAULT_TRAIL_BYTECOUNT;
private static final Log LOG = LogFactory.getLog(COSParser.class);
/**
* Collects all Xref/trailer objects and resolves them into single
* object using startxref reference.
*/
protected XrefTrailerResolver xrefTrailerResolver = new XrefTrailerResolver();
/**
* The prefix for the temp file being used.
*/
public static final String TMP_FILE_PREFIX = "tmpPDF";
/**
* Default constructor.
*
* @param source input representing the pdf.
*/
public COSParser(RandomAccessRead source)
{
super(new RandomAccessSource(source));
this.source = source;
}
/**
* Constructor for encrypted pdfs.
*
* @param source input representing the pdf.
* @param password password to be used for decryption.
* @param keyStore key store to be used for decryption when using public key security
* @param keyAlias alias to be used for decryption when using public key security
*
*/
public COSParser(RandomAccessRead source, String password, InputStream keyStore,
String keyAlias)
{
super(new RandomAccessSource(source));
this.source = source;
this.password = password;
this.keyAlias = keyAlias;
keyStoreInputStream = keyStore;
}
/**
* Sets how many trailing bytes of PDF file are searched for EOF marker and 'startxref' marker. If not set we use
* default value {@link #DEFAULT_TRAIL_BYTECOUNT}.
*
* <p>We check that new value is at least 16. However for practical use cases this value should not be lower than
* 1000; even 2000 was found to not be enough in some cases where some trailing garbage like HTML snippets followed
* the EOF marker.</p>
*
* <p>
* In case system property {@link #SYSPROP_EOFLOOKUPRANGE} is defined this value will be set on initialization but
* can be overwritten later.
* </p>
*
* @param byteCount number of trailing bytes
*/
public void setEOFLookupRange(int byteCount)
{
if (byteCount > 15)
{
readTrailBytes = byteCount;
}
}
/**
* Read the trailer information and provide a COSDictionary containing the trailer information.
*
* @return a COSDictionary containing the trailer information
* @throws IOException if something went wrong
*/
protected COSDictionary retrieveTrailer() throws IOException
{
COSDictionary trailer = null;
boolean rebuildTrailer = false;
try
{
// parse startxref
// TODO FDF files don't have a startxref value, so that rebuildTrailer is triggered
long startXRefOffset = getStartxrefOffset();
if (startXRefOffset > -1)
{
trailer = parseXref(startXRefOffset);
}
else
{
rebuildTrailer = isLenient();
}
}
catch (IOException exception)
{
if (isLenient())
{
rebuildTrailer = true;
}
else
{
throw exception;
}
}
// check if the trailer contains a Root object
if (trailer != null && trailer.getItem(COSName.ROOT) == null)
{
rebuildTrailer = isLenient();
}
if (rebuildTrailer)
{
trailer = rebuildTrailer();
}
else
{
// prepare decryption if necessary
prepareDecryption();
if (bfSearchCOSObjectKeyOffsets != null && !bfSearchCOSObjectKeyOffsets.isEmpty())
{
bfSearchForObjStreams();
}
}
return trailer;
}
/**
* Parses cross reference tables.
*
* @param startXRefOffset start offset of the first table
* @return the trailer dictionary
* @throws IOException if something went wrong
*/
private COSDictionary parseXref(long startXRefOffset) throws IOException
{
source.seek(startXRefOffset);
long startXrefOffset = Math.max(0, parseStartXref());
// check the startxref offset
long fixedOffset = checkXRefOffset(startXrefOffset);
if (fixedOffset > -1)
{
startXrefOffset = fixedOffset;
}
document.setStartXref(startXrefOffset);
long prev = startXrefOffset;
// ---- parse whole chain of xref tables/object streams using PREV reference
Set<Long> prevSet = new HashSet<>();
while (prev > 0)
{
// seek to xref table
source.seek(prev);
// skip white spaces
skipSpaces();
// -- parse xref
if (source.peek() == X)
{
// xref table and trailer
// use existing parser to parse xref table
if (!parseXrefTable(prev) || !parseTrailer())
{
throw new IOException("Expected trailer object at offset "
+ source.getPosition());
}
COSDictionary trailer = xrefTrailerResolver.getCurrentTrailer();
// check for a XRef stream, it may contain some object ids of compressed objects
if(trailer.containsKey(COSName.XREF_STM))
{
int streamOffset = trailer.getInt(COSName.XREF_STM);
// check the xref stream reference
fixedOffset = checkXRefOffset(streamOffset);
if (fixedOffset > -1 && fixedOffset != streamOffset)
{
LOG.warn("/XRefStm offset " + streamOffset + " is incorrect, corrected to " + fixedOffset);
streamOffset = (int)fixedOffset;
trailer.setInt(COSName.XREF_STM, streamOffset);
}
if (streamOffset > 0)
{
source.seek(streamOffset);
skipSpaces();
try
{
parseXrefObjStream(prev, false);
}
catch (IOException ex)
{
if (isLenient)
{
LOG.error("Failed to parse /XRefStm at offset " + streamOffset, ex);
}
else
{
throw ex;
}
}
}
else
{
if(isLenient)
{
LOG.error("Skipped XRef stream due to a corrupt offset:"+streamOffset);
}
else
{
throw new IOException("Skipped XRef stream due to a corrupt offset:"+streamOffset);
}
}
}
prev = trailer.getLong(COSName.PREV);
if (prev > 0)
{
// check the xref table reference
fixedOffset = checkXRefOffset(prev);
if (fixedOffset > -1 && fixedOffset != prev)
{
prev = fixedOffset;
trailer.setLong(COSName.PREV, prev);
}
}
}
else
{
// parse xref stream
prev = parseXrefObjStream(prev, true);
if (prev > 0)
{
// check the xref table reference
fixedOffset = checkXRefOffset(prev);
if (fixedOffset > -1 && fixedOffset != prev)
{
prev = fixedOffset;
COSDictionary trailer = xrefTrailerResolver.getCurrentTrailer();
trailer.setLong(COSName.PREV, prev);
}
}
}
if (prevSet.contains(prev))
{
throw new IOException("/Prev loop at offset " + prev);
}
prevSet.add(prev);
}
// ---- build valid xrefs out of the xref chain
xrefTrailerResolver.setStartxref(startXrefOffset);
COSDictionary trailer = xrefTrailerResolver.getTrailer();
document.setTrailer(trailer);
document.setIsXRefStream(XRefType.STREAM == xrefTrailerResolver.getXrefType());
// check the offsets of all referenced objects
checkXrefOffsets();
// copy xref table
document.addXRefTable(xrefTrailerResolver.getXrefTable());
return trailer;
}
/**
* Parses an xref object stream starting with indirect object id.
*
* @return value of PREV item in dictionary or <code>-1</code> if no such item exists
*/
private long parseXrefObjStream(long objByteOffset, boolean isStandalone) throws IOException
{
// ---- parse indirect object head
long objectNumber = readObjectNumber();
// remember the highest XRef object number to avoid it being reused in incremental saving
long currentHighestXRefObjectNumber = document.getHighestXRefObjectNumber();
document.setHighestXRefObjectNumber(Math.max(currentHighestXRefObjectNumber, objectNumber));
readGenerationNumber();
readExpectedString(OBJ_MARKER, true);
COSDictionary dict = parseCOSDictionary();
try (COSStream xrefStream = parseCOSStream(dict))
{
parseXrefStream(xrefStream, objByteOffset, isStandalone);
}
return dict.getLong(COSName.PREV);
}
/**
* Looks for and parses startxref. We first look for last '%%EOF' marker (within last
* {@link #DEFAULT_TRAIL_BYTECOUNT} bytes (or range set via {@link #setEOFLookupRange(int)}) and go back to find
* <code>startxref</code>.
*
* @return the offset of StartXref
* @throws IOException If something went wrong.
*/
private long getStartxrefOffset() throws IOException
{
byte[] buf;
long skipBytes;
// read trailing bytes into buffer
try
{
final int trailByteCount = (fileLen < readTrailBytes) ? (int) fileLen : readTrailBytes;
buf = new byte[trailByteCount];
skipBytes = fileLen - trailByteCount;
source.seek(skipBytes);
int off = 0;
int readBytes;
while (off < trailByteCount)
{
readBytes = source.read(buf, off, trailByteCount - off);
// in order to not get stuck in a loop we check readBytes (this should never happen)
if (readBytes < 1)
{
throw new IOException(
"No more bytes to read for trailing buffer, but expected: "
+ (trailByteCount - off));
}
off += readBytes;
}
}
finally
{
source.seek(0);
}
// find last '%%EOF'
int bufOff = lastIndexOf(EOF_MARKER, buf, buf.length);
if (bufOff < 0)
{
if (isLenient)
{
// in lenient mode the '%%EOF' isn't needed
bufOff = buf.length;
LOG.debug("Missing end of file marker '" + new String(EOF_MARKER) + "'");
}
else
{
throw new IOException("Missing end of file marker '" + new String(EOF_MARKER) + "'");
}
}
// find last startxref preceding EOF marker
bufOff = lastIndexOf(STARTXREF, buf, bufOff);
if (bufOff < 0)
{
throw new IOException("Missing 'startxref' marker.");
}
else
{
return skipBytes + bufOff;
}
}
/**
* Searches last appearance of pattern within buffer. Lookup before _lastOff and goes back until 0.
*
* @param pattern pattern to search for
* @param buf buffer to search pattern in
* @param endOff offset (exclusive) where lookup starts at
*
* @return start offset of pattern within buffer or <code>-1</code> if pattern could not be found
*/
protected int lastIndexOf(final char[] pattern, final byte[] buf, final int endOff)
{
final int lastPatternChOff = pattern.length - 1;
int bufOff = endOff;
int patOff = lastPatternChOff;
char lookupCh = pattern[patOff];
while (--bufOff >= 0)
{
if (buf[bufOff] == lookupCh)
{
if (--patOff < 0)
{
// whole pattern matched
return bufOff;
}
// matched current char, advance to preceding one
lookupCh = pattern[patOff];
}
else if (patOff < lastPatternChOff)
{
// no char match but already matched some chars; reset
patOff = lastPatternChOff;
lookupCh = pattern[patOff];
}
}
return -1;
}
/**
* Return true if parser is lenient. Meaning auto healing capacity of the parser are used.
*
* @return true if parser is lenient
*/
public boolean isLenient()
{
return isLenient;
}
/**
* Change the parser leniency flag.
*
* This method can only be called before the parsing of the file.
*
* @param lenient try to handle malformed PDFs.
*
*/
protected void setLenient(boolean lenient)
{
if (initialParseDone)
{
throw new IllegalArgumentException("Cannot change leniency after parsing");
}
this.isLenient = lenient;
}
@Override
public COSBase dereferenceCOSObject(COSObject obj) throws IOException
{
long currentPos = source.getPosition();
COSBase parsedObj = parseObjectDynamically(obj.getObjectNumber(), obj.getGenerationNumber(),
false);
if (currentPos > 0)
{
source.seek(currentPos);
}
return parsedObj;
}
/**
* Parse the object for the given object number.
*
* @param objNr object number of object to be parsed
* @param objGenNr object generation number of object to be parsed
* @param requireExistingNotCompressedObj if <code>true</code> the object to be parsed must be defined in xref
* (comment: null objects may be missing from xref) and it must not be a compressed object within object stream
* (this is used to circumvent being stuck in a loop in a malicious PDF)
*
* @return the parsed object (which is also added to document object)
*
* @throws IOException If an IO error occurs.
*/
protected synchronized COSBase parseObjectDynamically(long objNr, int objGenNr,
boolean requireExistingNotCompressedObj) throws IOException
{
// ---- create object key and get object (container) from pool
final COSObjectKey objKey = new COSObjectKey(objNr, objGenNr);
final COSObject pdfObject = document.getObjectFromPool(objKey);
COSBase referencedObject = !pdfObject.isObjectNull() ? pdfObject.getObject() : null;
// not previously parsed
if (referencedObject == null)
{
// read offset or object stream object number from xref table
Long offsetOrObjstmObNr = document.getXrefTable().get(objKey);
// maybe something is wrong with the xref table -> perform brute force search for all objects
if (offsetOrObjstmObNr == null && isLenient)
{
Map<COSObjectKey, Long> bfCOSObjectKeyOffsets = getBFCOSObjectOffsets();
offsetOrObjstmObNr = bfCOSObjectKeyOffsets.get(objKey);
if (offsetOrObjstmObNr != null)
{
LOG.debug("Set missing offset " + offsetOrObjstmObNr + " for object " + objKey);
document.getXrefTable().put(objKey, offsetOrObjstmObNr);
}
}
// sanity test to circumvent loops with broken documents
if (requireExistingNotCompressedObj
&& ((offsetOrObjstmObNr == null) || (offsetOrObjstmObNr <= 0)))
{
throw new IOException("Object must be defined and must not be compressed object: "
+ objKey.getNumber() + ":" + objKey.getGeneration());
}
if (offsetOrObjstmObNr == null)
{
// not defined object -> NULL object (Spec. 1.7, chap. 3.2.9)
// remove parser to avoid endless recursion
pdfObject.setToNull();
}
else if (offsetOrObjstmObNr > 0)
{
// offset of indirect object in file
referencedObject = parseFileObject(offsetOrObjstmObNr, objKey);
}
else
{
// xref value is object nr of object stream containing object to be parsed
// since our object was not found it means object stream was not parsed so far
referencedObject = parseObjectStreamObject((int) -offsetOrObjstmObNr, objKey);
}
if (referencedObject == null || referencedObject instanceof COSNull)
{
pdfObject.setToNull();
}
}
return referencedObject;
}
private COSBase parseFileObject(Long offsetOrObjstmObNr, final COSObjectKey objKey)
throws IOException
{
// ---- go to object start
source.seek(offsetOrObjstmObNr);
// ---- we must have an indirect object
final long readObjNr = readObjectNumber();
final int readObjGen = readGenerationNumber();
readExpectedString(OBJ_MARKER, true);
// ---- consistency check
if ((readObjNr != objKey.getNumber()) || (readObjGen != objKey.getGeneration()))
{
throw new IOException("XREF for " + objKey.getNumber() + ":"
+ objKey.getGeneration() + " points to wrong object: " + readObjNr
+ ":" + readObjGen + " at offset " + offsetOrObjstmObNr);
}
skipSpaces();
COSBase parsedObject = parseDirObject();
String endObjectKey = readString();
if (endObjectKey.equals(STREAM_STRING))
{
source.rewind(endObjectKey.getBytes(StandardCharsets.ISO_8859_1).length);
if (parsedObject instanceof COSDictionary)
{
COSStream stream = parseCOSStream((COSDictionary) parsedObject);
if (securityHandler != null)
{
securityHandler.decryptStream(stream, objKey.getNumber(), objKey.getGeneration());
}
parsedObject = stream;
}
else
{
// this is not legal
// the combination of a dict and the stream/endstream
// forms a complete stream object
throw new IOException("Stream not preceded by dictionary (offset: "
+ offsetOrObjstmObNr + ").");
}
skipSpaces();
endObjectKey = readLine();
// we have case with a second 'endstream' before endobj
if (!endObjectKey.startsWith(ENDOBJ_STRING) && endObjectKey.startsWith(ENDSTREAM_STRING))
{
endObjectKey = endObjectKey.substring(9).trim();
if (endObjectKey.length() == 0)
{
// no other characters in extra endstream line
// read next line
endObjectKey = readLine();
}
}
}
else if (securityHandler != null)
{
securityHandler.decrypt(parsedObject, objKey.getNumber(), objKey.getGeneration());
}
if (!endObjectKey.startsWith(ENDOBJ_STRING))
{
if (isLenient)
{
LOG.warn("Object (" + readObjNr + ":" + readObjGen + ") at offset "
+ offsetOrObjstmObNr + " does not end with 'endobj' but with '"
+ endObjectKey + "'");
}
else
{
throw new IOException("Object (" + readObjNr + ":" + readObjGen
+ ") at offset " + offsetOrObjstmObNr
+ " does not end with 'endobj' but with '" + endObjectKey + "'");
}
}
return parsedObject;
}
/**
* Parse the object with the given key from the object stream with the given number.
*
* @param objstmObjNr the number of the offset stream
* @param key the key of the object to be parsed
* @return the parsed object
* @throws IOException if something went wrong when parsing the object
*/
protected COSBase parseObjectStreamObject(int objstmObjNr, COSObjectKey key) throws IOException
{
final COSBase objstmBaseObj = parseObjectDynamically(objstmObjNr, 0, true);
COSBase objectStreamObject = null;
if (objstmBaseObj instanceof COSStream)
{
// parse object stream
PDFObjectStreamParser parser = null;
try
{
parser = new PDFObjectStreamParser((COSStream) objstmBaseObj, document);
objectStreamObject = parser.parseObject(key.getNumber());
}
catch (IOException ex)
{
if (isLenient)
{
LOG.error("object stream " + objstmObjNr
+ " could not be parsed due to an exception", ex);
}
else
{
throw ex;
}
}
}
return objectStreamObject;
}
/**
* Returns length value referred to or defined in given object.
*/
private COSNumber getLength(final COSBase lengthBaseObj) throws IOException
{
if (lengthBaseObj == null)
{
return null;
}
// maybe length was given directly
if (lengthBaseObj instanceof COSNumber)
{
return (COSNumber) lengthBaseObj;
}
// length in referenced object
if (lengthBaseObj instanceof COSObject)
{
COSObject lengthObj = (COSObject) lengthBaseObj;
COSBase length = lengthObj.getObject();
if (length == null)
{
throw new IOException("Length object content was not read.");
}
if (COSNull.NULL == length)
{
LOG.warn("Length object (" + lengthObj.getObjectNumber() + " "
+ lengthObj.getGenerationNumber() + ") not found");
return null;
}
if (length instanceof COSNumber)
{
return (COSNumber) length;
}
throw new IOException("Wrong type of referenced length object " + lengthObj + ": "
+ length.getClass().getSimpleName());
}
throw new IOException(
"Wrong type of length object: " + lengthBaseObj.getClass().getSimpleName());
}
private static final int STREAMCOPYBUFLEN = 8192;
private final byte[] streamCopyBuf = new byte[STREAMCOPYBUFLEN];
/**
* This will read a COSStream from the input stream using length attribute within dictionary. If
* length attribute is a indirect reference it is first resolved to get the stream length. This
* means we copy stream data without testing for 'endstream' or 'endobj' and thus it is no
* problem if these keywords occur within stream. We require 'endstream' to be found after
* stream data is read.
*
* @param dic dictionary that goes with this stream.
*
* @return parsed pdf stream.
*
* @throws IOException if an error occurred reading the stream, like problems with reading
* length attribute, stream does not end with 'endstream' after data read, stream too short etc.
*/
protected COSStream parseCOSStream(COSDictionary dic) throws IOException
{
COSStream stream = document.createCOSStream(dic);
// read 'stream'; this was already tested in parseObjectsDynamically()
readString();
skipWhiteSpaces();
/*
* This needs to be dic.getItem because when we are parsing, the underlying object might still be null.
*/
COSNumber streamLengthObj = getLength(dic.getItem(COSName.LENGTH));
if (streamLengthObj == null)
{
if (isLenient)
{
LOG.warn("The stream doesn't provide any stream length, using fallback readUntilEnd, at offset "
+ source.getPosition());
}
else
{
throw new IOException("Missing length for stream.");
}
}
// get output stream to copy data to
try (OutputStream out = stream.createRawOutputStream())
{
if (streamLengthObj != null && validateStreamLength(streamLengthObj.longValue()))
{
readValidStream(out, streamLengthObj);
}
else
{
readUntilEndStream(new EndstreamOutputStream(out));
}
}
String endStream = readString();
if (endStream.equals("endobj") && isLenient)
{
LOG.warn("stream ends with 'endobj' instead of 'endstream' at offset "
+ source.getPosition());
// avoid follow-up warning about missing endobj
source.rewind(ENDOBJ.length);
}
else if (endStream.length() > 9 && isLenient && endStream.substring(0,9).equals(ENDSTREAM_STRING))
{
LOG.warn("stream ends with '" + endStream + "' instead of 'endstream' at offset "
+ source.getPosition());
// unread the "extra" bytes
source.rewind(endStream.substring(9).getBytes(StandardCharsets.ISO_8859_1).length);
}
else if (!endStream.equals(ENDSTREAM_STRING))
{
throw new IOException(
"Error reading stream, expected='endstream' actual='"
+ endStream + "' at offset " + source.getPosition());
}
return stream;
}
/**
* This method will read through the current stream object until
* we find the keyword "endstream" meaning we're at the end of this
* object. Some pdf files, however, forget to write some endstream tags
* and just close off objects with an "endobj" tag so we have to handle
* this case as well.
*
* This method is optimized using buffered IO and reduced number of
* byte compare operations.
*
* @param out stream we write out to.
*
* @throws IOException if something went wrong
*/
private void readUntilEndStream( final OutputStream out ) throws IOException
{
int bufSize;
int charMatchCount = 0;
byte[] keyw = ENDSTREAM;
// last character position of shortest keyword ('endobj')
final int quickTestOffset = 5;
// read next chunk into buffer; already matched chars are added to beginning of buffer
while ( ( bufSize = source.read( strmBuf, charMatchCount, STRMBUFLEN - charMatchCount ) ) > 0 )
{
bufSize += charMatchCount;
int bIdx = charMatchCount;
int quickTestIdx;
// iterate over buffer, trying to find keyword match
for ( int maxQuicktestIdx = bufSize - quickTestOffset; bIdx < bufSize; bIdx++ )
{
// reduce compare operations by first test last character we would have to
// match if current one matches; if it is not a character from keywords
// we can move behind the test character; this shortcut is inspired by the
// Boyer-Moore string search algorithm and can reduce parsing time by approx. 20%
quickTestIdx = bIdx + quickTestOffset;
if (charMatchCount == 0 && quickTestIdx < maxQuicktestIdx)
{
final byte ch = strmBuf[quickTestIdx];
if ( ( ch > 't' ) || ( ch < 'a' ) )
{
// last character we would have to match if current character would match
// is not a character from keywords -> jump behind and start over
bIdx = quickTestIdx;
continue;
}
}
// could be negative - but we only compare to ASCII
final byte ch = strmBuf[bIdx];
if ( ch == keyw[ charMatchCount ] )
{
if ( ++charMatchCount == keyw.length )
{
// match found
bIdx++;
break;
}
}
else
{
if ( ( charMatchCount == 3 ) && ( ch == ENDOBJ[ charMatchCount ] ) )
{
// maybe ENDSTREAM is missing but we could have ENDOBJ
keyw = ENDOBJ;
charMatchCount++;
}
else
{
// no match; incrementing match start by 1 would be dumb since we already know
// matched chars depending on current char read we may already have beginning
// of a new match: 'e': first char matched; 'n': if we are at match position
// idx 7 we already read 'e' thus 2 chars matched for each other char we have
// to start matching first keyword char beginning with next read position
charMatchCount = ( ch == E ) ? 1 : ( ( ch == N ) && ( charMatchCount == 7 ) ) ? 2 : 0;
// search again for 'endstream'
keyw = ENDSTREAM;
}
}
}
int contentBytes = Math.max( 0, bIdx - charMatchCount );
// write buffer content until first matched char to output stream
if ( contentBytes > 0 )
{
out.write( strmBuf, 0, contentBytes );
}
if ( charMatchCount == keyw.length )
{
// keyword matched; unread matched keyword (endstream/endobj) and following buffered content
source.rewind( bufSize - contentBytes );
break;
}
else
{
// copy matched chars at start of buffer
System.arraycopy( keyw, 0, strmBuf, 0, charMatchCount );
}
}
// this writes a lonely CR or drops trailing CR LF and LF
out.flush();
}
private void readValidStream(OutputStream out, COSNumber streamLengthObj) throws IOException
{
long remainBytes = streamLengthObj.longValue();
while (remainBytes > 0)
{
final int chunk = (remainBytes > STREAMCOPYBUFLEN) ? STREAMCOPYBUFLEN : (int) remainBytes;
final int readBytes = source.read(streamCopyBuf, 0, chunk);
if (readBytes <= 0)
{
// shouldn't happen, the stream length has already been validated
throw new IOException("read error at offset " + source.getPosition()
+ ": expected " + chunk + " bytes, but read() returns " + readBytes);
}
out.write(streamCopyBuf, 0, readBytes);
remainBytes -= readBytes;
}
}
private boolean validateStreamLength(long streamLength) throws IOException
{
boolean streamLengthIsValid = true;
long originOffset = source.getPosition();
long expectedEndOfStream = originOffset + streamLength;
if (expectedEndOfStream > fileLen)
{
streamLengthIsValid = false;
LOG.warn("The end of the stream is out of range, using workaround to read the stream, "
+ "stream start position: " + originOffset + ", length: " + streamLength
+ ", expected end position: " + expectedEndOfStream);
}
else
{
source.seek(expectedEndOfStream);
skipSpaces();
if (!isString(ENDSTREAM))
{
streamLengthIsValid = false;
LOG.warn("The end of the stream doesn't point to the correct offset, using workaround to read the stream, "
+ "stream start position: " + originOffset + ", length: " + streamLength
+ ", expected end position: " + expectedEndOfStream);
}
source.seek(originOffset);
}
return streamLengthIsValid;
}
/**
* Check if the cross reference table/stream can be found at the current offset.
*
* @param startXRefOffset
* @return the revised offset
* @throws IOException
*/
private long checkXRefOffset(long startXRefOffset) throws IOException
{
// repair mode isn't available in non-lenient mode
if (!isLenient)
{
return startXRefOffset;
}
source.seek(startXRefOffset);
skipSpaces();
if (source.peek() == X && isString(XREF_TABLE))
{
return startXRefOffset;
}
if (startXRefOffset > 0)
{
if (checkXRefStreamOffset(startXRefOffset))
{
return startXRefOffset;
}
else
{
return calculateXRefFixedOffset(startXRefOffset);
}
}
// can't find a valid offset
return -1;
}
/**
* Check if the cross reference stream can be found at the current offset.
*
* @param startXRefOffset the expected start offset of the XRef stream
* @return the revised offset
* @throws IOException if something went wrong
*/
private boolean checkXRefStreamOffset(long startXRefOffset) throws IOException
{
// repair mode isn't available in non-lenient mode
if (!isLenient || startXRefOffset == 0)
{
return true;
}
// seek to offset-1
source.seek(startXRefOffset-1);
int nextValue = source.read();
// the first character has to be a whitespace, and then a digit
if (isWhitespace(nextValue))
{
skipSpaces();
if (isDigit())
{
try
{
// it's a XRef stream
readObjectNumber();
readGenerationNumber();
readExpectedString(OBJ_MARKER, true);
// check the dictionary to avoid false positives
COSDictionary dict = parseCOSDictionary();
source.seek(startXRefOffset);
if ("XRef".equals(dict.getNameAsString(COSName.TYPE)))
{
return true;
}
}
catch (IOException exception)
{
// there wasn't an object of a xref stream
LOG.debug("No Xref stream at given location " + startXRefOffset, exception);
source.seek(startXRefOffset);
}
}
}
return false;
}
/**
* Try to find a fixed offset for the given xref table/stream.
*
* @param objectOffset the given offset where to look at
* @return the fixed offset
*
* @throws IOException if something went wrong
*/
private long calculateXRefFixedOffset(long objectOffset) throws IOException
{
if (objectOffset < 0)
{
LOG.error("Invalid object offset " + objectOffset + " when searching for a xref table/stream");
return 0;
}
// start a brute force search for all xref tables and try to find the offset we are looking for
long newOffset = bfSearchForXRef(objectOffset);
if (newOffset > -1)
{
LOG.debug("Fixed reference for xref table/stream " + objectOffset + " -> " + newOffset);
return newOffset;
}
LOG.error("Can't find the object xref table/stream at offset " + objectOffset);
return 0;
}
private boolean validateXrefOffsets(Map<COSObjectKey, Long> xrefOffset) throws IOException
{
if (xrefOffset == null)
{
return true;
}
for (Entry<COSObjectKey, Long> objectEntry : xrefOffset.entrySet())
{
COSObjectKey objectKey = objectEntry.getKey();
Long objectOffset = objectEntry.getValue();
// a negative offset number represents an object number itself
// see type 2 entry in xref stream
if (objectOffset != null && objectOffset >= 0
&& !checkObjectKey(objectKey, objectOffset))
{
LOG.debug("Stop checking xref offsets as at least one (" + objectKey
+ ") couldn't be dereferenced");
return false;
}
}
return true;
}
/**
* Check the XRef table by dereferencing all objects and fixing the offset if necessary.
*
* @throws IOException if something went wrong.
*/
private void checkXrefOffsets() throws IOException
{
// repair mode isn't available in non-lenient mode
if (!isLenient)
{
return;
}
Map<COSObjectKey, Long> xrefOffset = xrefTrailerResolver.getXrefTable();
if (!validateXrefOffsets(xrefOffset))
{
Map<COSObjectKey, Long> bfCOSObjectKeyOffsets = getBFCOSObjectOffsets();
if (!bfCOSObjectKeyOffsets.isEmpty())
{
LOG.debug("Replaced read xref table with the results of a brute force search");
xrefOffset.clear();
xrefOffset.putAll(bfCOSObjectKeyOffsets);
}
}
}
/**
* Check if the given object can be found at the given offset.
*
* @param objectKey the object we are looking for
* @param offset the offset where to look
* @return returns true if the given object can be dereferenced at the given offset
* @throws IOException if something went wrong
*/
private boolean checkObjectKey(COSObjectKey objectKey, long offset) throws IOException
{
// there can't be any object at the very beginning of a pdf
if (offset < MINIMUM_SEARCH_OFFSET)
{
return false;
}
boolean objectKeyFound = false;
try
{
source.seek(offset);
// try to read the given object/generation number
if (objectKey.getNumber() == readObjectNumber())
{
int genNumber = readGenerationNumber();
if (genNumber == objectKey.getGeneration())
{
// finally try to read the object marker
readExpectedString(OBJ_MARKER, true);
objectKeyFound = true;
}
else if (isLenient && genNumber > objectKey.getGeneration())
{
// finally try to read the object marker
readExpectedString(OBJ_MARKER, true);
objectKeyFound = true;
objectKey.fixGeneration(genNumber);
}
}
}
catch (IOException exception)
{
// Swallow the exception, obviously there isn't any valid object number
LOG.debug("No valid object at given location " + offset + " - ignoring", exception);
}
// return resulting value
return objectKeyFound;
}
private Map<COSObjectKey, Long> getBFCOSObjectOffsets() throws IOException
{
if (bfSearchCOSObjectKeyOffsets == null)
{
bfSearchForObjects();
}
return bfSearchCOSObjectKeyOffsets;
}
/**
* Brute force search for every object in the pdf.
*
* @throws IOException if something went wrong
*/
private void bfSearchForObjects() throws IOException
{
long lastEOFMarker = bfSearchForLastEOFMarker();
bfSearchCOSObjectKeyOffsets = new HashMap<>();
long originOffset = source.getPosition();
long currentOffset = MINIMUM_SEARCH_OFFSET;
long lastObjectId = Long.MIN_VALUE;
int lastGenID = Integer.MIN_VALUE;
long lastObjOffset = Long.MIN_VALUE;
char[] endobjString = "ndo".toCharArray();
char[] endobjRemainingString = "bj".toCharArray();
boolean endOfObjFound = false;
do
{
source.seek(currentOffset);
int nextChar = source.read();
currentOffset++;
if (isWhitespace(nextChar) && isString(OBJ_MARKER))
{
long tempOffset = currentOffset - 2;
source.seek(tempOffset);
int genID = source.peek();
// is the next char a digit?
if (isDigit(genID))
{
genID -= 48;
tempOffset--;
source.seek(tempOffset);
if (isWhitespace())
{
while (tempOffset > MINIMUM_SEARCH_OFFSET && isWhitespace())
{
source.seek(--tempOffset);
}
boolean objectIDFound = false;
while (tempOffset > MINIMUM_SEARCH_OFFSET && isDigit())
{
source.seek(--tempOffset);
objectIDFound = true;
}
if (objectIDFound)
{
source.read();
long objectId = readObjectNumber();
if (lastObjOffset > 0)
{
// add the former object ID only if there was a subsequent object ID
bfSearchCOSObjectKeyOffsets.put(
new COSObjectKey(lastObjectId, lastGenID), lastObjOffset);
}
lastObjectId = objectId;
lastGenID = genID;
lastObjOffset = tempOffset + 1;
currentOffset += OBJ_MARKER.length - 1;
endOfObjFound = false;
}
}
}
}
// check for "endo" as abbreviation for "endobj", as the pdf may be cut off
// in the middle of the keyword, see PDFBOX-3936.
// We could possibly implement a more intelligent algorithm if necessary
else if (nextChar == 'e' && isString(endobjString))
{
currentOffset += endobjString.length;
source.seek(currentOffset);
if (source.isEOF())
{
endOfObjFound = true;
continue;
}
if (isString(endobjRemainingString))
{
currentOffset += endobjRemainingString.length;
endOfObjFound = true;
continue;
}
}
} while (currentOffset < lastEOFMarker && !source.isEOF());
if ((lastEOFMarker < Long.MAX_VALUE || endOfObjFound) && lastObjOffset > 0)
{
// if the pdf wasn't cut off in the middle or if the last object ends with a "endobj" marker
// the last object id has to be added here so that it can't get lost as there isn't any subsequent object id
bfSearchCOSObjectKeyOffsets.put(new COSObjectKey(lastObjectId, lastGenID),
lastObjOffset);
}
// reestablish origin position
source.seek(originOffset);
}
/**
* Search for the offset of the given xref table/stream among those found by a brute force search.
*
* @return the offset of the xref entry
* @throws IOException if something went wrong
*/
private long bfSearchForXRef(long xrefOffset) throws IOException
{
long newOffset = -1;
// initialize bfSearchXRefTablesOffsets -> not null
bfSearchForXRefTables();
// initialize bfSearchXRefStreamsOffsets -> not null
bfSearchForXRefStreams();
// TODO to be optimized, this won't work in every case
long newOffsetTable = searchNearestValue(bfSearchXRefTablesOffsets, xrefOffset);
// TODO to be optimized, this won't work in every case
long newOffsetStream = searchNearestValue(bfSearchXRefStreamsOffsets, xrefOffset);
// choose the nearest value
if (newOffsetTable > -1 && newOffsetStream > -1)
{
long differenceTable = xrefOffset - newOffsetTable;
long differenceStream = xrefOffset - newOffsetStream;
if (Math.abs(differenceTable) > Math.abs(differenceStream))
{
newOffset = newOffsetStream;
bfSearchXRefStreamsOffsets.remove(newOffsetStream);
}
else
{
newOffset = newOffsetTable;
bfSearchXRefTablesOffsets.remove(newOffsetTable);
}
}
else if (newOffsetTable > -1)
{
newOffset = newOffsetTable;
bfSearchXRefTablesOffsets.remove(newOffsetTable);
}
else if (newOffsetStream > -1)
{
newOffset = newOffsetStream;
bfSearchXRefStreamsOffsets.remove(newOffsetStream);
}
return newOffset;
}
private long searchNearestValue(List<Long> values, long offset)
{
long newValue = -1;
Long currentDifference = null;
int currentOffsetIndex = -1;
int numberOfOffsets = values.size();
// find the nearest value
for (int i = 0; i < numberOfOffsets; i++)
{
long newDifference = offset - values.get(i);
// find the nearest offset
if (currentDifference == null
|| (Math.abs(currentDifference) > Math.abs(newDifference)))
{
currentDifference = newDifference;
currentOffsetIndex = i;
}
}
if (currentOffsetIndex > -1)
{
newValue = values.get(currentOffsetIndex);
}
return newValue;
}
/**
* Brute force search for all trailer marker.
*
* @throws IOException if something went wrong
*/
private boolean bfSearchForTrailer(COSDictionary trailer) throws IOException
{
Map<String, COSDictionary> trailerDicts = new HashMap<>();
long originOffset = source.getPosition();
source.seek(MINIMUM_SEARCH_OFFSET);
while (!source.isEOF())
{
// search for trailer marker
if (isString(TRAILER_MARKER))
{
source.seek(source.getPosition() + TRAILER_MARKER.length);
try
{
boolean rootFound = false;
boolean infoFound = false;
skipSpaces();
COSDictionary trailerDict = parseCOSDictionary();
StringBuilder trailerKeys = new StringBuilder();
COSObject rootObj = trailerDict.getCOSObject(COSName.ROOT);
if (rootObj != null)
{
long objNumber = rootObj.getObjectNumber();
int genNumber = rootObj.getGenerationNumber();
trailerKeys.append(objNumber).append(" ");
trailerKeys.append(genNumber).append(" ");
rootFound = true;
}
COSObject infoObj = trailerDict.getCOSObject(COSName.INFO);
if (infoObj != null)
{
long objNumber = infoObj.getObjectNumber();
int genNumber = infoObj.getGenerationNumber();
trailerKeys.append(objNumber).append(" ");
trailerKeys.append(genNumber).append(" ");
infoFound = true;
}
if (rootFound && infoFound)
{
trailerDicts.put(trailerKeys.toString(), trailerDict);
}
}
catch (IOException exception)
{
LOG.debug("An exception occurred during brute force search for trailer - ignoring", exception);
continue;
}
}
source.read();
}
source.seek(originOffset);
// eliminate double entries
int trailerdictsSize = trailerDicts.size();
String firstEntry = null;
if (trailerdictsSize > 0)
{
String[] keys = new String[trailerdictsSize];
trailerDicts.keySet().toArray(keys);
firstEntry = keys[0];
for (int i = 1; i < trailerdictsSize; i++)
{
if (firstEntry.equals(keys[i]))
{
trailerDicts.remove(keys[i]);
}
}
}
// continue if one entry is left only
if (trailerDicts.size() == 1)
{
boolean rootFound = false;
boolean infoFound = false;
COSDictionary trailerDict = trailerDicts.get(firstEntry);
COSBase rootObj = trailerDict.getItem(COSName.ROOT);
if (rootObj instanceof COSObject)
{
// check if the dictionary can be dereferenced and is the one we are looking for
COSBase rootDict = ((COSObject) rootObj).getObject();
if (rootDict instanceof COSDictionary && isCatalog((COSDictionary) rootDict))
{
rootFound = true;
}
}
COSBase infoObj = trailerDict.getItem(COSName.INFO);
if (infoObj instanceof COSObject)
{
// check if the dictionary can be dereferenced and is the one we are looking for
COSBase infoDict = ((COSObject) infoObj).getObject();
if (infoDict instanceof COSDictionary && isInfo((COSDictionary) infoDict))
{
infoFound = true;
}
}
if (rootFound && infoFound)
{
trailer.setItem(COSName.ROOT, rootObj);
trailer.setItem(COSName.INFO, infoObj);
if (trailerDict.containsKey(COSName.ENCRYPT))
{
COSBase encObj = trailerDict.getItem(COSName.ENCRYPT);
if (encObj instanceof COSObject)
{
// check if the dictionary can be dereferenced
// TODO check if the dictionary is an encryption dictionary?
COSBase encDict = ((COSObject) encObj).getObject();
if (encDict instanceof COSDictionary)
{
trailer.setItem(COSName.ENCRYPT, encObj);
}
}
}
if (trailerDict.containsKey(COSName.ID))
{
COSBase idObj = trailerDict.getItem(COSName.ID);
if (idObj instanceof COSArray)
{
trailer.setItem(COSName.ID, idObj);
}
}
return true;
}
}
return false;
}
/**
* Brute force search for the last EOF marker.
*
* @throws IOException if something went wrong
*/
private long bfSearchForLastEOFMarker() throws IOException
{
long lastEOFMarker = -1;
long originOffset = source.getPosition();
source.seek(MINIMUM_SEARCH_OFFSET);
while (!source.isEOF())
{
// search for EOF marker
if (isString(EOF_MARKER))
{
long tempMarker = source.getPosition();
source.seek(tempMarker + 5);
try
{
// check if the following data is some valid pdf content
// which most likely indicates that the pdf is linearized,
// updated or just cut off somewhere in the middle
skipSpaces();
if (!isString(XREF_TABLE))
{
readObjectNumber();
readGenerationNumber();
}
}
catch (IOException exception)
{
// save the EOF marker as the following data is most likely some garbage
LOG.debug("An exception occurred during brute force for last EOF - ignoring",
exception);
lastEOFMarker = tempMarker;
}
}
source.read();
}
source.seek(originOffset);
// no EOF marker found
if (lastEOFMarker == -1)
{
lastEOFMarker = Long.MAX_VALUE;
}
return lastEOFMarker;
}
/**
* Brute force search for all object streams.
*
* @throws IOException if something went wrong
*/
private void bfSearchForObjStreams() throws IOException
{
// save origin offset
long originOffset = source.getPosition();
// log warning about skipped stream
bfSearchForObjStreamOffsets().entrySet().stream() //
.filter(o -> bfSearchCOSObjectKeyOffsets.get(o.getValue()) == null) //
.forEach(o -> LOG.warn(
"Skipped incomplete object stream:" + o.getValue() + " at " + o.getKey()));
// collect all stream offsets
List<Long> objStreamOffsets = bfSearchForObjStreamOffsets().entrySet().stream() //
.filter(o -> bfSearchCOSObjectKeyOffsets.get(o.getValue()) != null) //
.filter(o -> o.getKey().equals(bfSearchCOSObjectKeyOffsets.get(o.getValue()))) //
.map(Map.Entry::getKey) //
.collect(Collectors.toList());
// add all found compressed objects to the brute force search result
for (Long offset : objStreamOffsets)
{
source.seek(offset);
long stmObjNumber = readObjectNumber();
int stmGenNumber = readGenerationNumber();
readExpectedString(OBJ_MARKER, true);
COSStream stream = null;
try
{
COSDictionary dict = parseCOSDictionary();
stream = parseCOSStream(dict);
if (securityHandler != null)
{
securityHandler.decryptStream(stream, stmObjNumber, stmGenNumber);
}
PDFObjectStreamParser objStreamParser = new PDFObjectStreamParser(stream, document);
Map<Long, Integer> objectNumbers = objStreamParser.readObjectNumbers();
Map<COSObjectKey, Long> xrefOffset = xrefTrailerResolver.getXrefTable();
for (Long objNumber : objectNumbers.keySet())
{
COSObjectKey objKey = new COSObjectKey(objNumber, 0);
Long existingOffset = bfSearchCOSObjectKeyOffsets.get(objKey);
if (existingOffset != null && existingOffset < 0)
{
// translate stream object key to its offset
COSObjectKey objStmKey = new COSObjectKey(Math.abs(existingOffset), 0);
existingOffset = bfSearchCOSObjectKeyOffsets.get(objStmKey);
}
if (existingOffset == null || offset > existingOffset)
{
bfSearchCOSObjectKeyOffsets.put(objKey, -stmObjNumber);
xrefOffset.put(objKey, -stmObjNumber);
}
}
}
catch (IOException exception)
{
LOG.debug("Skipped corrupt stream: (" + stmObjNumber + " 0 at offset " + offset,
exception);
}
finally
{
if (stream != null)
{
stream.close();
}
}
}
// restore origin offset
source.seek(originOffset);
}
/**
* Search for all offsets of object streams within the given pdf
*
* @return a map of all offsets for object streams
* @throws IOException if something went wrong
*/
private Map<Long, COSObjectKey> bfSearchForObjStreamOffsets() throws IOException
{
HashMap<Long, COSObjectKey> bfSearchObjStreamsOffsets = new HashMap<>();
source.seek(MINIMUM_SEARCH_OFFSET);
char[] string = " obj".toCharArray();
while (!source.isEOF())
{
// search for object stream marker
if (isString(OBJ_STREAM))
{
long currentPosition = source.getPosition();
// search backwards for the beginning of the object
long newOffset = -1;
boolean objFound = false;
for (int i = 1; i < 40 && !objFound; i++)
{
long currentOffset = currentPosition - (i * 10);
if (currentOffset > 0)
{
source.seek(currentOffset);
for (int j = 0; j < 10; j++)
{
if (isString(string))
{
long tempOffset = currentOffset - 1;
source.seek(tempOffset);
int genID = source.peek();
// is the next char a digit?
if (isDigit(genID))
{
tempOffset--;
source.seek(tempOffset);
if (isSpace())
{
int length = 0;
source.seek(--tempOffset);
while (tempOffset > MINIMUM_SEARCH_OFFSET && isDigit())
{
source.seek(--tempOffset);
length++;
}
if (length > 0)
{
source.read();
newOffset = source.getPosition();
long objNumber = readObjectNumber();
int genNumber = readGenerationNumber();
COSObjectKey streamObjectKey = new COSObjectKey(
objNumber, genNumber);
bfSearchObjStreamsOffsets.put(newOffset,
streamObjectKey);
}
}
}
LOG.debug("Dictionary start for object stream -> " + newOffset);
objFound = true;
break;
}
else
{
currentOffset++;
source.read();
}
}
}
}
source.seek(currentPosition + OBJ_STREAM.length);
}
source.read();
}
return bfSearchObjStreamsOffsets;
}
/**
* Brute force search for all xref entries (tables).
*
* @throws IOException if something went wrong
*/
private void bfSearchForXRefTables() throws IOException
{
if (bfSearchXRefTablesOffsets == null)
{
// a pdf may contain more than one xref entry
bfSearchXRefTablesOffsets = new ArrayList<>();
long originOffset = source.getPosition();
source.seek(MINIMUM_SEARCH_OFFSET);
// search for xref tables
while (!source.isEOF())
{
if (isString(XREF_TABLE))
{
long newOffset = source.getPosition();
source.seek(newOffset - 1);
// ensure that we don't read "startxref" instead of "xref"
if (isWhitespace())
{
bfSearchXRefTablesOffsets.add(newOffset);
}
source.seek(newOffset + 4);
}
source.read();
}
source.seek(originOffset);
}
}
/**
* Brute force search for all /XRef entries (streams).
*
* @throws IOException if something went wrong
*/
private void bfSearchForXRefStreams() throws IOException
{
if (bfSearchXRefStreamsOffsets == null)
{
// a pdf may contain more than one /XRef entry
bfSearchXRefStreamsOffsets = new ArrayList<>();
long originOffset = source.getPosition();
source.seek(MINIMUM_SEARCH_OFFSET);
// search for XRef streams
String objString = " obj";
char[] string = objString.toCharArray();
while (!source.isEOF())
{
if (isString(XREF_STREAM))
{
// search backwards for the beginning of the stream
long newOffset = -1;
long xrefOffset = source.getPosition();
boolean objFound = false;
for (int i = 1; i < 40 && !objFound; i++)
{
long currentOffset = xrefOffset - (i * 10);
if (currentOffset > 0)
{
source.seek(currentOffset);
for (int j = 0; j < 10; j++)
{
if (isString(string))
{
long tempOffset = currentOffset - 1;
source.seek(tempOffset);
int genID = source.peek();
// is the next char a digit?
if (isDigit(genID))
{
tempOffset--;
source.seek(tempOffset);
if (isSpace())
{
int length = 0;
source.seek(--tempOffset);
while (tempOffset > MINIMUM_SEARCH_OFFSET && isDigit())
{
source.seek(--tempOffset);
length++;
}
if (length > 0)
{
source.read();
newOffset = source.getPosition();
}
}
}
LOG.debug("Fixed reference for xref stream " + xrefOffset
+ " -> " + newOffset);
objFound = true;
break;
}
else
{
currentOffset++;
source.read();
}
}
}
}
if (newOffset > -1)
{
bfSearchXRefStreamsOffsets.add(newOffset);
}
source.seek(xrefOffset + 5);
}
source.read();
}
source.seek(originOffset);
}
}
/**
* Rebuild the trailer dictionary if startxref can't be found.
*
* @return the rebuild trailer dictionary
*
* @throws IOException if something went wrong
*/
private COSDictionary rebuildTrailer() throws IOException
{
COSDictionary trailer = null;
bfSearchForObjects();
if (bfSearchCOSObjectKeyOffsets != null)
{
// reset trailer resolver
xrefTrailerResolver.reset();
// use the found objects to rebuild the trailer resolver
xrefTrailerResolver.nextXrefObj(0, XRefType.TABLE);
for (Entry<COSObjectKey, Long> entry : bfSearchCOSObjectKeyOffsets.entrySet())
{
xrefTrailerResolver.setXRef(entry.getKey(), entry.getValue());
}
xrefTrailerResolver.setStartxref(0);
trailer = xrefTrailerResolver.getTrailer();
document.setTrailer(trailer);
boolean searchForObjStreamsDone = false;
if (!bfSearchForTrailer(trailer) && !searchForTrailerItems(trailer))
{
// root entry wasn't found, maybe it is part of an object stream
bfSearchForObjStreams();
searchForObjStreamsDone = true;
// search again for the root entry
searchForTrailerItems(trailer);
}
// prepare decryption if necessary
prepareDecryption();
if (!searchForObjStreamsDone)
{
bfSearchForObjStreams();
}
}
trailerWasRebuild = true;
return trailer;
}
/**
* Search for the different parts of the trailer dictionary.
*
* @param trailer
* @return true if the root was found, false if not.
*/
private boolean searchForTrailerItems(COSDictionary trailer)
{
boolean rootFound = false;
for (COSObjectKey key : bfSearchCOSObjectKeyOffsets.keySet())
{
COSObject cosObject = document.getObjectFromPool(key);
COSBase baseObject = cosObject.getObject();
if (!(baseObject instanceof COSDictionary))
{
continue;
}
COSDictionary dictionary = (COSDictionary) baseObject;
// document catalog
if (isCatalog(dictionary))
{
trailer.setItem(COSName.ROOT, cosObject);
rootFound = true;
}
// info dictionary
else if (isInfo(dictionary))
{
trailer.setItem(COSName.INFO, cosObject);
}
// encryption dictionary, if existing, is lost
// We can't run "Algorithm 2" from PDF specification because of missing ID
}
return rootFound;
}
/**
* Check if all entries of the pages dictionary are present. Those which can't be dereferenced are removed.
*
* @param root the root dictionary of the pdf
* @throws java.io.IOException if the page tree root is null
*/
protected void checkPages(COSDictionary root) throws IOException
{
if (trailerWasRebuild)
{
// check if all page objects are dereferenced
COSBase pages = root.getDictionaryObject(COSName.PAGES);
if (pages instanceof COSDictionary)
{
checkPagesDictionary((COSDictionary) pages, new HashSet<>());
}
}
if (!(root.getDictionaryObject(COSName.PAGES) instanceof COSDictionary))
{
throw new IOException("Page tree root must be a dictionary");
}
}
private int checkPagesDictionary(COSDictionary pagesDict, Set<COSObject> set)
{
// check for kids
COSBase kids = pagesDict.getDictionaryObject(COSName.KIDS);
int numberOfPages = 0;
if (kids instanceof COSArray)
{
COSArray kidsArray = (COSArray) kids;
List<? extends COSBase> kidsList = kidsArray.toList();
for (COSBase kid : kidsList)
{
if (!(kid instanceof COSObject) || set.contains((COSObject) kid))
{
kidsArray.remove(kid);
continue;
}
COSObject kidObject = (COSObject) kid;
COSBase kidBaseobject = kidObject.getObject();
// object wasn't dereferenced -> remove it
if (kidBaseobject == null || kidBaseobject.equals(COSNull.NULL))
{
LOG.warn("Removed null object " + kid + " from pages dictionary");
kidsArray.remove(kid);
}
else if (kidBaseobject instanceof COSDictionary)
{
COSDictionary kidDictionary = (COSDictionary) kidBaseobject;
COSName type = kidDictionary.getCOSName(COSName.TYPE);
if (COSName.PAGES.equals(type))
{
// process nested pages dictionaries
set.add(kidObject);
numberOfPages += checkPagesDictionary(kidDictionary, set);
}
else if (COSName.PAGE.equals(type))
{
// count pages
numberOfPages++;
}
}
}
}
// fix counter
pagesDict.setInt(COSName.COUNT, numberOfPages);
return numberOfPages;
}
/**
* Tell if the dictionary is a PDF catalog. Override this for an FDF catalog.
*
* @param dictionary
* @return true if the given dictionary is a root dictionary
*/
protected boolean isCatalog(COSDictionary dictionary)
{
return COSName.CATALOG.equals(dictionary.getCOSName(COSName.TYPE));
}
/**
* Tell if the dictionary is an info dictionary.
*
* @param dictionary
* @return true if the given dictionary is an info dictionary
*/
private boolean isInfo(COSDictionary dictionary)
{
if (dictionary.containsKey(COSName.PARENT) || dictionary.containsKey(COSName.A)
|| dictionary.containsKey(COSName.DEST))
{
return false;
}
if (!dictionary.containsKey(COSName.MOD_DATE) && !dictionary.containsKey(COSName.TITLE)
&& !dictionary.containsKey(COSName.AUTHOR)
&& !dictionary.containsKey(COSName.SUBJECT)
&& !dictionary.containsKey(COSName.KEYWORDS)
&& !dictionary.containsKey(COSName.CREATOR)
&& !dictionary.containsKey(COSName.PRODUCER)
&& !dictionary.containsKey(COSName.CREATION_DATE))
{
return false;
}
return true;
}
/**
* This will parse the startxref section from the stream. The startxref value is ignored.
*
* @return the startxref value or -1 on parsing error
* @throws IOException If an IO error occurs.
*/
private long parseStartXref() throws IOException
{
long startXref = -1;
if (isString(STARTXREF))
{
readString();
skipSpaces();
// This integer is the byte offset of the first object referenced by the xref or xref stream
startXref = readLong();
}
return startXref;
}
/**
* Checks if the given string can be found at the current offset.
*
* @param string the bytes of the string to look for
* @return true if the bytes are in place, false if not
* @throws IOException if something went wrong
*/
private boolean isString(byte[] string) throws IOException
{
boolean bytesMatching = false;
if (source.peek() == string[0])
{
int length = string.length;
byte[] bytesRead = new byte[length];
int numberOfBytes = source.read(bytesRead, 0, length);
while (numberOfBytes < length)
{
int readMore = source.read(bytesRead, numberOfBytes, length - numberOfBytes);
if (readMore < 0)
{
break;
}
numberOfBytes += readMore;
}
bytesMatching = Arrays.equals(string, bytesRead);
source.rewind(numberOfBytes);
}
return bytesMatching;
}
/**
* Checks if the given string can be found at the current offset.
*
* @param string the bytes of the string to look for
* @return true if the bytes are in place, false if not
* @throws IOException if something went wrong
*/
private boolean isString(char[] string) throws IOException
{
boolean bytesMatching = true;
long originOffset = source.getPosition();
for (char c : string)
{
if (source.read() != c)
{
bytesMatching = false;
break;
}
}
source.seek(originOffset);
return bytesMatching;
}
/**
* This will parse the trailer from the stream and add it to the state.
*
* @return false on parsing error
* @throws IOException If an IO error occurs.
*/
private boolean parseTrailer() throws IOException
{
// parse the last trailer.
long trailerOffset = source.getPosition();
// PDFBOX-1739 skip extra xref entries in RegisSTAR documents
if (isLenient)
{
int nextCharacter = source.peek();
while (nextCharacter != 't' && isDigit(nextCharacter))
{
if (source.getPosition() == trailerOffset)
{
// warn only the first time
LOG.warn("Expected trailer object at offset " + trailerOffset
+ ", keep trying");
}
readLine();
nextCharacter = source.peek();
}
}
if(source.peek() != 't')
{
return false;
}
//read "trailer"
long currentOffset = source.getPosition();
String nextLine = readLine();
if( !nextLine.trim().equals( "trailer" ) )
{
// in some cases the EOL is missing and the trailer immediately
// continues with "<<" or with a blank character
// even if this does not comply with PDF reference we want to support as many PDFs as possible
// Acrobat reader can also deal with this.
if (nextLine.startsWith("trailer"))
{
// we can't just unread a portion of the read data as we don't know if the EOL consist of 1 or 2 bytes
int len = "trailer".length();
// jump back right after "trailer"
source.seek(currentOffset + len);
}
else
{
return false;
}
}
// in some cases the EOL is missing and the trailer continues with " <<"
// even if this does not comply with PDF reference we want to support as many PDFs as possible
// Acrobat reader can also deal with this.
skipSpaces();
COSDictionary parsedTrailer = parseCOSDictionary();
xrefTrailerResolver.setTrailer( parsedTrailer );
skipSpaces();
return true;
}
/**
* Parse the header of a pdf.
*
* @return true if a PDF header was found
* @throws IOException if something went wrong
*/
protected boolean parsePDFHeader() throws IOException
{
return parseHeader(PDF_HEADER, PDF_DEFAULT_VERSION);
}
/**
* Parse the header of a fdf.
*
* @return true if a FDF header was found
* @throws IOException if something went wrong
*/
protected boolean parseFDFHeader() throws IOException
{
return parseHeader(FDF_HEADER, FDF_DEFAULT_VERSION);
}
private boolean parseHeader(String headerMarker, String defaultVersion) throws IOException
{
// read first line
String header = readLine();
// some pdf-documents are broken and the pdf-version is in one of the following lines
if (!header.contains(headerMarker))
{
header = readLine();
while (!header.contains(headerMarker))
{
// if a line starts with a digit, it has to be the first one with data in it
if ((header.length() > 0) && (Character.isDigit(header.charAt(0))))
{
break;
}
header = readLine();
}
}
// nothing found
if (!header.contains(headerMarker))
{
source.seek(0);
return false;
}
//sometimes there is some garbage in the header before the header
//actually starts, so lets try to find the header first.
int headerStart = header.indexOf( headerMarker );
// greater than zero because if it is zero then there is no point of trimming
if ( headerStart > 0 )
{
//trim off any leading characters
header = header.substring( headerStart, header.length() );
}
// This is used if there is garbage after the header on the same line
if (header.startsWith(headerMarker) && !header.matches(headerMarker + "\\d.\\d"))
{
if (header.length() < headerMarker.length() + 3)
{
// No version number at all, set to 1.4 as default
header = headerMarker + defaultVersion;
LOG.debug("No version found, set to " + defaultVersion + " as default.");
}
else
{
String headerGarbage = header.substring(headerMarker.length() + 3, header.length()) + "\n";
header = header.substring(0, headerMarker.length() + 3);
source.rewind(headerGarbage.getBytes(StandardCharsets.ISO_8859_1).length);
}
}
float headerVersion = -1;
try
{
String[] headerParts = header.split("-");
if (headerParts.length == 2)
{
headerVersion = Float.parseFloat(headerParts[1]);
}
}
catch (NumberFormatException exception)
{
LOG.debug("Can't parse the header version.", exception);
}
if (headerVersion < 0)
{
if (isLenient)
{
headerVersion = 1.7f;
}
else
{
throw new IOException("Error getting header version: " + header);
}
}
document.setVersion(headerVersion);
// rewind
source.seek(0);
return true;
}
/**
* This will parse the xref table from the stream and add it to the state
* The XrefTable contents are ignored.
* @param startByteOffset the offset to start at
* @return false on parsing error
* @throws IOException If an IO error occurs.
*/
protected boolean parseXrefTable(long startByteOffset) throws IOException
{
if(source.peek() != 'x')
{
return false;
}
String xref = readString();
if( !xref.trim().equals( "xref" ) )
{
return false;
}
// check for trailer after xref
String str = readString();
byte[] b = str.getBytes(StandardCharsets.ISO_8859_1);
source.rewind(b.length);
// signal start of new XRef
xrefTrailerResolver.nextXrefObj( startByteOffset, XRefType.TABLE );
if (str.startsWith("trailer"))
{
LOG.warn("skipping empty xref table");
return false;
}
// Xref tables can have multiple sections. Each starts with a starting object id and a count.
while(true)
{
String currentLine = readLine();
String[] splitString = currentLine.split("\\s");
if (splitString.length != 2)
{
LOG.warn("Unexpected XRefTable Entry: " + currentLine);
return false;
}
// first obj id
long currObjID;
try
{
currObjID = Long.parseLong(splitString[0]);
}
catch (NumberFormatException exception)
{
LOG.warn("XRefTable: invalid ID for the first object: " + currentLine);
return false;
}
// the number of objects in the xref table
int count = 0;
try
{
count = Integer.parseInt(splitString[1]);
}
catch (NumberFormatException exception)
{
LOG.warn("XRefTable: invalid number of objects: " + currentLine);
return false;
}
skipSpaces();
for(int i = 0; i < count; i++)
{
if(source.isEOF() || isEndOfName((char)source.peek()))
{
break;
}
if(source.peek() == 't')
{
break;
}
//Ignore table contents
currentLine = readLine();
splitString = currentLine.split("\\s");
if (splitString.length < 3)
{
LOG.warn("invalid xref line: " + currentLine);
break;
}
/* This supports the corrupt table as reported in
* PDFBOX-474 (XXXX XXX XX n) */
if(splitString[splitString.length-1].equals("n"))
{
try
{
long currOffset = Long.parseLong(splitString[0]);
int currGenID = Integer.parseInt(splitString[1]);
COSObjectKey objKey = new COSObjectKey(currObjID, currGenID);
xrefTrailerResolver.setXRef(objKey, currOffset);
}
catch(NumberFormatException e)
{
throw new IOException(e);
}
}
else if(!splitString[2].equals("f"))
{
throw new IOException("Corrupt XRefTable Entry - ObjID:" + currObjID);
}
currObjID++;
skipSpaces();
}
skipSpaces();
if (!isDigit())
{
break;
}
}
return true;
}
/**
* Fills XRefTrailerResolver with data of given stream.
* Stream must be of type XRef.
* @param stream the stream to be read
* @param objByteOffset the offset to start at
* @param isStandalone should be set to true if the stream is not part of a hybrid xref table
* @throws IOException if there is an error parsing the stream
*/
private void parseXrefStream(COSStream stream, long objByteOffset, boolean isStandalone) throws IOException
{
// the cross reference stream of a hybrid xref table will be added to the existing one
// and we must not override the offset and the trailer
if ( isStandalone )
{
xrefTrailerResolver.nextXrefObj( objByteOffset, XRefType.STREAM );
xrefTrailerResolver.setTrailer( stream );
}
PDFXrefStreamParser parser = new PDFXrefStreamParser(stream, document, xrefTrailerResolver);
parser.parse();
}
/**
* This will get the encryption dictionary. The document must be parsed before this is called.
*
* @return The encryption dictionary of the document that was parsed.
*
* @throws IOException If there is an error getting the document.
*/
public PDEncryption getEncryption() throws IOException
{
if (document == null)
{
throw new IOException(
"You must parse the document first before calling getEncryption()");
}
return encryption;
}
/**
* This will get the AccessPermission. The document must be parsed before this is called.
*
* @return The access permission of document that was parsed.
*
* @throws IOException If there is an error getting the document.
*/
public AccessPermission getAccessPermission() throws IOException
{
if (document == null)
{
throw new IOException(
"You must parse the document first before calling getAccessPermission()");
}
return accessPermission;
}
/**
* Prepare for decryption.
*
* @throws InvalidPasswordException If the password is incorrect.
* @throws IOException if something went wrong
*/
private void prepareDecryption() throws IOException
{
if (encryption != null)
{
return;
}
COSBase trailerEncryptItem = document.getTrailer().getItem(COSName.ENCRYPT);
if (trailerEncryptItem == null || trailerEncryptItem instanceof COSNull)
{
return;
}
try
{
encryption = new PDEncryption(document.getEncryptionDictionary());
DecryptionMaterial decryptionMaterial;
if (keyStoreInputStream != null)
{
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(keyStoreInputStream, password.toCharArray());
decryptionMaterial = new PublicKeyDecryptionMaterial(ks, keyAlias, password);
}
else
{
decryptionMaterial = new StandardDecryptionMaterial(password);
}
securityHandler = encryption.getSecurityHandler();
securityHandler.prepareForDecryption(encryption, document.getDocumentID(),
decryptionMaterial);
accessPermission = securityHandler.getCurrentAccessPermission();
}
catch (IOException e)
{
throw e;
}
catch (GeneralSecurityException e)
{
throw new IOException("Error (" + e.getClass().getSimpleName()
+ ") while creating security handler for decryption", e);
}
finally
{
if (keyStoreInputStream != null)
{
IOUtils.closeQuietly(keyStoreInputStream);
}
}
}
}
|
PDFBOX-3888: reduce number of seek operations, inspired by https://github.com/TomRoush/PdfBox-Android/pull/204
git-svn-id: c3ad59981690829a43dc34c293c4e2cd04bcd994@1874427 13f79535-47bb-0310-9956-ffa450edef68
|
pdfbox/src/main/java/org/apache/pdfbox/pdfparser/COSParser.java
|
PDFBOX-3888: reduce number of seek operations, inspired by https://github.com/TomRoush/PdfBox-Android/pull/204
|
<ide><path>dfbox/src/main/java/org/apache/pdfbox/pdfparser/COSParser.java
<ide> import java.security.GeneralSecurityException;
<ide> import java.security.KeyStore;
<ide> import java.util.ArrayList;
<del>import java.util.Arrays;
<ide> import java.util.HashMap;
<ide> import java.util.HashSet;
<ide> import java.util.List;
<ide> private static final int X = 'x';
<ide>
<ide> private static final int STRMBUFLEN = 2048;
<del> private final byte[] strmBuf = new byte[ STRMBUFLEN ];
<add> private final byte[] strmBuf = new byte[ STRMBUFLEN ];
<ide>
<ide> protected final RandomAccessRead source;
<ide>
<ide> }
<ide> source.seek(startXRefOffset);
<ide> skipSpaces();
<del> if (source.peek() == X && isString(XREF_TABLE))
<add> if (isString(XREF_TABLE))
<ide> {
<ide> return startXRefOffset;
<ide> }
<ide> Map<String, COSDictionary> trailerDicts = new HashMap<>();
<ide> long originOffset = source.getPosition();
<ide> source.seek(MINIMUM_SEARCH_OFFSET);
<del> while (!source.isEOF())
<del> {
<del> // search for trailer marker
<del> if (isString(TRAILER_MARKER))
<del> {
<del> source.seek(source.getPosition() + TRAILER_MARKER.length);
<del> try
<del> {
<del> boolean rootFound = false;
<del> boolean infoFound = false;
<del> skipSpaces();
<del> COSDictionary trailerDict = parseCOSDictionary();
<del> StringBuilder trailerKeys = new StringBuilder();
<del> COSObject rootObj = trailerDict.getCOSObject(COSName.ROOT);
<del> if (rootObj != null)
<del> {
<del> long objNumber = rootObj.getObjectNumber();
<del> int genNumber = rootObj.getGenerationNumber();
<del> trailerKeys.append(objNumber).append(" ");
<del> trailerKeys.append(genNumber).append(" ");
<del> rootFound = true;
<del> }
<del> COSObject infoObj = trailerDict.getCOSObject(COSName.INFO);
<del> if (infoObj != null)
<del> {
<del> long objNumber = infoObj.getObjectNumber();
<del> int genNumber = infoObj.getGenerationNumber();
<del> trailerKeys.append(objNumber).append(" ");
<del> trailerKeys.append(genNumber).append(" ");
<del> infoFound = true;
<del> }
<del> if (rootFound && infoFound)
<del> {
<del> trailerDicts.put(trailerKeys.toString(), trailerDict);
<del> }
<del> }
<del> catch (IOException exception)
<del> {
<del> LOG.debug("An exception occurred during brute force search for trailer - ignoring", exception);
<del> continue;
<del> }
<del> }
<del> source.read();
<add> // search for trailer marker
<add> long trailerOffset = findString(TRAILER_MARKER);
<add> while (trailerOffset != -1)
<add> {
<add> try
<add> {
<add> boolean rootFound = false;
<add> boolean infoFound = false;
<add> skipSpaces();
<add> COSDictionary trailerDict = parseCOSDictionary();
<add> StringBuilder trailerKeys = new StringBuilder();
<add> COSObject rootObj = trailerDict.getCOSObject(COSName.ROOT);
<add> if (rootObj != null)
<add> {
<add> long objNumber = rootObj.getObjectNumber();
<add> int genNumber = rootObj.getGenerationNumber();
<add> trailerKeys.append(objNumber).append(" ");
<add> trailerKeys.append(genNumber).append(" ");
<add> rootFound = true;
<add> }
<add> COSObject infoObj = trailerDict.getCOSObject(COSName.INFO);
<add> if (infoObj != null)
<add> {
<add> long objNumber = infoObj.getObjectNumber();
<add> int genNumber = infoObj.getGenerationNumber();
<add> trailerKeys.append(objNumber).append(" ");
<add> trailerKeys.append(genNumber).append(" ");
<add> infoFound = true;
<add> }
<add> if (rootFound && infoFound)
<add> {
<add> trailerDicts.put(trailerKeys.toString(), trailerDict);
<add> }
<add> }
<add> catch (IOException exception)
<add> {
<add> LOG.debug("An exception occurred during brute force search for trailer - ignoring",
<add> exception);
<add> }
<add> trailerOffset = findString(TRAILER_MARKER);
<ide> }
<ide> source.seek(originOffset);
<ide> // eliminate double entries
<ide> long lastEOFMarker = -1;
<ide> long originOffset = source.getPosition();
<ide> source.seek(MINIMUM_SEARCH_OFFSET);
<del> while (!source.isEOF())
<del> {
<del> // search for EOF marker
<del> if (isString(EOF_MARKER))
<del> {
<del> long tempMarker = source.getPosition();
<del> source.seek(tempMarker + 5);
<del> try
<del> {
<del> // check if the following data is some valid pdf content
<del> // which most likely indicates that the pdf is linearized,
<del> // updated or just cut off somewhere in the middle
<del> skipSpaces();
<del> if (!isString(XREF_TABLE))
<del> {
<del> readObjectNumber();
<del> readGenerationNumber();
<del> }
<del> }
<del> catch (IOException exception)
<del> {
<del> // save the EOF marker as the following data is most likely some garbage
<del> LOG.debug("An exception occurred during brute force for last EOF - ignoring",
<del> exception);
<del> lastEOFMarker = tempMarker;
<del> }
<del> }
<del> source.read();
<add> long tempMarker = findString(EOF_MARKER);
<add> while (tempMarker != -1)
<add> {
<add> try
<add> {
<add> // check if the following data is some valid pdf content
<add> // which most likely indicates that the pdf is linearized,
<add> // updated or just cut off somewhere in the middle
<add> skipSpaces();
<add> if (!isString(XREF_TABLE))
<add> {
<add> readObjectNumber();
<add> readGenerationNumber();
<add> }
<add> }
<add> catch (IOException exception)
<add> {
<add> // save the EOF marker as the following data is most likely some garbage
<add> LOG.debug("An exception occurred during brute force for last EOF - ignoring",
<add> exception);
<add> lastEOFMarker = tempMarker;
<add> }
<add> tempMarker = findString(EOF_MARKER);
<ide> }
<ide> source.seek(originOffset);
<ide> // no EOF marker found
<ide> // save origin offset
<ide> long originOffset = source.getPosition();
<ide>
<add> Map<Long, COSObjectKey> bfSearchForObjStreamOffsets = bfSearchForObjStreamOffsets();
<ide> // log warning about skipped stream
<del> bfSearchForObjStreamOffsets().entrySet().stream() //
<add> bfSearchForObjStreamOffsets.entrySet().stream() //
<ide> .filter(o -> bfSearchCOSObjectKeyOffsets.get(o.getValue()) == null) //
<ide> .forEach(o -> LOG.warn(
<ide> "Skipped incomplete object stream:" + o.getValue() + " at " + o.getKey()));
<ide>
<ide> // collect all stream offsets
<del> List<Long> objStreamOffsets = bfSearchForObjStreamOffsets().entrySet().stream() //
<add> List<Long> objStreamOffsets = bfSearchForObjStreamOffsets.entrySet().stream() //
<ide> .filter(o -> bfSearchCOSObjectKeyOffsets.get(o.getValue()) != null) //
<ide> .filter(o -> o.getKey().equals(bfSearchCOSObjectKeyOffsets.get(o.getValue()))) //
<ide> .map(Map.Entry::getKey) //
<ide> HashMap<Long, COSObjectKey> bfSearchObjStreamsOffsets = new HashMap<>();
<ide> source.seek(MINIMUM_SEARCH_OFFSET);
<ide> char[] string = " obj".toCharArray();
<del> while (!source.isEOF())
<del> {
<del> // search for object stream marker
<del> if (isString(OBJ_STREAM))
<del> {
<del> long currentPosition = source.getPosition();
<del> // search backwards for the beginning of the object
<add> // search for object stream marker
<add> long positionObjStream = findString(OBJ_STREAM);
<add> while (positionObjStream != -1)
<add> {
<add> // search backwards for the beginning of the object
<add> long newOffset = -1;
<add> boolean objFound = false;
<add> for (int i = 1; i < 40 && !objFound; i++)
<add> {
<add> long currentOffset = positionObjStream - (i * 10);
<add> if (currentOffset > 0)
<add> {
<add> source.seek(currentOffset);
<add> for (int j = 0; j < 10; j++)
<add> {
<add> if (isString(string))
<add> {
<add> long tempOffset = currentOffset - 1;
<add> source.seek(tempOffset);
<add> int genID = source.peek();
<add> // is the next char a digit?
<add> if (isDigit(genID))
<add> {
<add> tempOffset--;
<add> source.seek(tempOffset);
<add> if (isSpace())
<add> {
<add> int length = 0;
<add> source.seek(--tempOffset);
<add> while (tempOffset > MINIMUM_SEARCH_OFFSET && isDigit())
<add> {
<add> source.seek(--tempOffset);
<add> length++;
<add> }
<add> if (length > 0)
<add> {
<add> source.read();
<add> newOffset = source.getPosition();
<add> long objNumber = readObjectNumber();
<add> int genNumber = readGenerationNumber();
<add> COSObjectKey streamObjectKey = new COSObjectKey(objNumber,
<add> genNumber);
<add> bfSearchObjStreamsOffsets.put(newOffset, streamObjectKey);
<add> }
<add> }
<add> }
<add> LOG.debug("Dictionary start for object stream -> " + newOffset);
<add> objFound = true;
<add> break;
<add> }
<add> else
<add> {
<add> currentOffset++;
<add> source.read();
<add> }
<add> }
<add> }
<add> }
<add> source.seek(positionObjStream + OBJ_STREAM.length);
<add> positionObjStream = findString(OBJ_STREAM);
<add> }
<add> return bfSearchObjStreamsOffsets;
<add> }
<add> /**
<add> * Brute force search for all xref entries (tables).
<add> *
<add> * @throws IOException if something went wrong
<add> */
<add> private void bfSearchForXRefTables() throws IOException
<add> {
<add> if (bfSearchXRefTablesOffsets == null)
<add> {
<add> // a pdf may contain more than one xref entry
<add> bfSearchXRefTablesOffsets = new ArrayList<>();
<add> source.seek(MINIMUM_SEARCH_OFFSET);
<add> // search for xref tables
<add> long newOffset = findString(XREF_TABLE);
<add> while (newOffset != -1)
<add> {
<add> source.seek(newOffset - 1);
<add> // ensure that we don't read "startxref" instead of "xref"
<add> if (isWhitespace())
<add> {
<add> bfSearchXRefTablesOffsets.add(newOffset);
<add> }
<add> source.seek(newOffset + 4);
<add> newOffset = findString(XREF_TABLE);
<add> }
<add> }
<add> }
<add>
<add> /**
<add> * Brute force search for all /XRef entries (streams).
<add> *
<add> * @throws IOException if something went wrong
<add> */
<add> private void bfSearchForXRefStreams() throws IOException
<add> {
<add> if (bfSearchXRefStreamsOffsets == null)
<add> {
<add> // a pdf may contain more than one /XRef entry
<add> bfSearchXRefStreamsOffsets = new ArrayList<>();
<add> source.seek(MINIMUM_SEARCH_OFFSET);
<add> // search for XRef streams
<add> String objString = " obj";
<add> char[] string = objString.toCharArray();
<add> long xrefOffset = findString(XREF_STREAM);
<add> while (xrefOffset != -1)
<add> {
<add> // search backwards for the beginning of the stream
<ide> long newOffset = -1;
<ide> boolean objFound = false;
<ide> for (int i = 1; i < 40 && !objFound; i++)
<ide> {
<del> long currentOffset = currentPosition - (i * 10);
<add> long currentOffset = xrefOffset - (i * 10);
<ide> if (currentOffset > 0)
<ide> {
<ide> source.seek(currentOffset);
<ide> {
<ide> source.read();
<ide> newOffset = source.getPosition();
<del> long objNumber = readObjectNumber();
<del> int genNumber = readGenerationNumber();
<del> COSObjectKey streamObjectKey = new COSObjectKey(
<del> objNumber, genNumber);
<del> bfSearchObjStreamsOffsets.put(newOffset,
<del> streamObjectKey);
<ide> }
<ide> }
<ide> }
<del> LOG.debug("Dictionary start for object stream -> " + newOffset);
<add> LOG.debug("Fixed reference for xref stream " + xrefOffset + " -> "
<add> + newOffset);
<ide> objFound = true;
<ide> break;
<ide> }
<ide> }
<ide> }
<ide> }
<del> source.seek(currentPosition + OBJ_STREAM.length);
<del> }
<del> source.read();
<del> }
<del> return bfSearchObjStreamsOffsets;
<del> }
<del> /**
<del> * Brute force search for all xref entries (tables).
<del> *
<del> * @throws IOException if something went wrong
<del> */
<del> private void bfSearchForXRefTables() throws IOException
<del> {
<del> if (bfSearchXRefTablesOffsets == null)
<del> {
<del> // a pdf may contain more than one xref entry
<del> bfSearchXRefTablesOffsets = new ArrayList<>();
<del> long originOffset = source.getPosition();
<del> source.seek(MINIMUM_SEARCH_OFFSET);
<del> // search for xref tables
<del> while (!source.isEOF())
<del> {
<del> if (isString(XREF_TABLE))
<del> {
<del> long newOffset = source.getPosition();
<del> source.seek(newOffset - 1);
<del> // ensure that we don't read "startxref" instead of "xref"
<del> if (isWhitespace())
<del> {
<del> bfSearchXRefTablesOffsets.add(newOffset);
<del> }
<del> source.seek(newOffset + 4);
<del> }
<del> source.read();
<del> }
<del> source.seek(originOffset);
<del> }
<del> }
<del>
<del> /**
<del> * Brute force search for all /XRef entries (streams).
<del> *
<del> * @throws IOException if something went wrong
<del> */
<del> private void bfSearchForXRefStreams() throws IOException
<del> {
<del> if (bfSearchXRefStreamsOffsets == null)
<del> {
<del> // a pdf may contain more than one /XRef entry
<del> bfSearchXRefStreamsOffsets = new ArrayList<>();
<del> long originOffset = source.getPosition();
<del> source.seek(MINIMUM_SEARCH_OFFSET);
<del> // search for XRef streams
<del> String objString = " obj";
<del> char[] string = objString.toCharArray();
<del> while (!source.isEOF())
<del> {
<del> if (isString(XREF_STREAM))
<del> {
<del> // search backwards for the beginning of the stream
<del> long newOffset = -1;
<del> long xrefOffset = source.getPosition();
<del> boolean objFound = false;
<del> for (int i = 1; i < 40 && !objFound; i++)
<del> {
<del> long currentOffset = xrefOffset - (i * 10);
<del> if (currentOffset > 0)
<del> {
<del> source.seek(currentOffset);
<del> for (int j = 0; j < 10; j++)
<del> {
<del> if (isString(string))
<del> {
<del> long tempOffset = currentOffset - 1;
<del> source.seek(tempOffset);
<del> int genID = source.peek();
<del> // is the next char a digit?
<del> if (isDigit(genID))
<del> {
<del> tempOffset--;
<del> source.seek(tempOffset);
<del> if (isSpace())
<del> {
<del> int length = 0;
<del> source.seek(--tempOffset);
<del> while (tempOffset > MINIMUM_SEARCH_OFFSET && isDigit())
<del> {
<del> source.seek(--tempOffset);
<del> length++;
<del> }
<del> if (length > 0)
<del> {
<del> source.read();
<del> newOffset = source.getPosition();
<del> }
<del> }
<del> }
<del> LOG.debug("Fixed reference for xref stream " + xrefOffset
<del> + " -> " + newOffset);
<del> objFound = true;
<del> break;
<del> }
<del> else
<del> {
<del> currentOffset++;
<del> source.read();
<del> }
<del> }
<del> }
<del> }
<del> if (newOffset > -1)
<del> {
<del> bfSearchXRefStreamsOffsets.add(newOffset);
<del> }
<del> source.seek(xrefOffset + 5);
<del> }
<del> source.read();
<del> }
<del> source.seek(originOffset);
<add> if (newOffset > -1)
<add> {
<add> bfSearchXRefStreamsOffsets.add(newOffset);
<add> }
<add> source.seek(xrefOffset + 5);
<add> xrefOffset = findString(XREF_STREAM);
<add> }
<ide> }
<ide> }
<ide>
<ide> */
<ide> private boolean isString(byte[] string) throws IOException
<ide> {
<del> boolean bytesMatching = false;
<del> if (source.peek() == string[0])
<del> {
<del> int length = string.length;
<del> byte[] bytesRead = new byte[length];
<del> int numberOfBytes = source.read(bytesRead, 0, length);
<del> while (numberOfBytes < length)
<del> {
<del> int readMore = source.read(bytesRead, numberOfBytes, length - numberOfBytes);
<del> if (readMore < 0)
<del> {
<del> break;
<del> }
<del> numberOfBytes += readMore;
<del> }
<del> bytesMatching = Arrays.equals(string, bytesRead);
<del> source.rewind(numberOfBytes);
<del> }
<add> boolean bytesMatching = true;
<add> long originOffset = source.getPosition();
<add> for (byte c : string)
<add> {
<add> if (source.read() != c)
<add> {
<add> bytesMatching = false;
<add> break;
<add> }
<add> }
<add> source.seek(originOffset);
<ide> return bytesMatching;
<ide> }
<ide>
<ide> return bytesMatching;
<ide> }
<ide>
<add> /**
<add> * Search for the given string. The search starts at the current position and returns the start position if the
<add> * string was found. -1 is returned if there isn't any further occurrence of the given string. After returning the
<add> * current position is either the end of the string or the end of the input.
<add> *
<add> * @param string the string to be searched
<add> * @return the start position of the found string
<add> * @throws IOException if something went wrong
<add> */
<add> private long findString(char[] string) throws IOException
<add> {
<add> long position = -1L;
<add> int stringLength = string.length;
<add> int counter = 0;
<add> int readChar = source.read();
<add> while (readChar != -1)
<add> {
<add> if (readChar == string[counter])
<add> {
<add> if (counter == 0)
<add> {
<add> position = source.getPosition();
<add> }
<add> counter++;
<add> if (counter == stringLength)
<add> {
<add> return position;
<add> }
<add> }
<add> else if (counter > 0)
<add> {
<add> counter = 0;
<add> position = -1L;
<add> continue;
<add> }
<add> readChar = source.read();
<add> }
<add> return position;
<add> }
<ide> /**
<ide> * This will parse the trailer from the stream and add it to the state.
<ide> *
|
|
JavaScript
|
mit
|
69e5c2f56b733c77ba47187cc0203a02e08db796
| 0 |
ssidorchick/mementomovie
|
'use strict';
angular.module('mementoMovieApp')
.service('Movie', function ($http, $q, Auth, Profile) {
var fetchMovies = function() {
return $http.get('/api/movies')
.then(function(res) { return res.data; });
};
var populateProfileMovies = function(result) {
if (_.isArray(result[0])) {
return result[0].map(function(movie) {
return _.find(result[1], { _id: movie._id }) || movie;
});
} else {
return _.find(result[1], { _id: result[0]._id }) || result[0];
}
};
this.getAll = function() {
if (Auth.isLoggedIn()) {
return $q.all([fetchMovies(), Profile.getMovies()])
.then(populateProfileMovies);
} else {
return fetchMovies();
}
};
this.get = function(id) {
return $http.get('/api/movies/' + id)
.then(function(res) {
if (Auth.isLoggedIn()) {
var deferred = $q.defer();
deferred.resolve(res.data);
return $q.all([deferred.promise, Profile.getMovies()])
.then(populateProfileMovies);
} else {
return res.data;
}
});
};
});
|
client/app/services/movie/movie.service.js
|
'use strict';
angular.module('mementoMovieApp')
.service('Movie', function ($http, $q, Auth, Profile) {
var fetchMovies = function() {
return $http.get('/api/movies')
.then(function(res) { return res.data; });
};
var populateProfileMovies = function(result) {
if (_.isArray(result[0])) {
return result[0].map(function(movie) {
return _.find(result[1], { _id: movie._id }) || movie;
});
} else {
return _.find(result[1], { _id: result[0]._id }) || movie;
}
};
this.getAll = function() {
if (Auth.isLoggedIn()) {
return $q.all([fetchMovies(), Profile.getMovies()])
.then(populateProfileMovies);
} else {
return fetchMovies();
}
};
this.get = function(id) {
return $http.get('/api/movies/' + id)
.then(function(res) {
if (Auth.isLoggedIn()) {
var deferred = $q.defer();
deferred.resolve(res.data);
return $q.all([deferred.promise, Profile.getMovies()])
.then(populateProfileMovies);
} else {
return res.data;
}
});
};
});
|
Fix movie service issues with populating following movies.
|
client/app/services/movie/movie.service.js
|
Fix movie service issues with populating following movies.
|
<ide><path>lient/app/services/movie/movie.service.js
<ide> return _.find(result[1], { _id: movie._id }) || movie;
<ide> });
<ide> } else {
<del> return _.find(result[1], { _id: result[0]._id }) || movie;
<add> return _.find(result[1], { _id: result[0]._id }) || result[0];
<ide> }
<ide> };
<ide>
|
|
Java
|
apache-2.0
|
error: pathspec 'TeamworkApiDemo/app/src/main/java/com/vishnus1224/teamworkapidemo/ui/view/ProjectsView.java' did not match any file(s) known to git
|
b5bc0f0d2761748c7336ec3172e278d5e1d42f2d
| 1 |
vishnus1224/RxJavaTeamworkClient
|
package com.vishnus1224.teamworkapidemo.ui.view;
import com.vishnus1224.teamworkapidemo.model.ProjectDto;
import java.util.List;
/**
* Created by Vishnu on 9/4/2016.
*/
public interface ProjectsView extends BaseView {
void showProjects(List<ProjectDto> projectDtoList);
void showError();
void showProjectsView();
void hideProjectsView();
void showNoProjectsView();
void hideNoProjectsView();
void showProgressBar();
void hideProgressBar();
}
|
TeamworkApiDemo/app/src/main/java/com/vishnus1224/teamworkapidemo/ui/view/ProjectsView.java
|
interface representing ui events to be shown on the projects screen
|
TeamworkApiDemo/app/src/main/java/com/vishnus1224/teamworkapidemo/ui/view/ProjectsView.java
|
interface representing ui events to be shown on the projects screen
|
<ide><path>eamworkApiDemo/app/src/main/java/com/vishnus1224/teamworkapidemo/ui/view/ProjectsView.java
<add>package com.vishnus1224.teamworkapidemo.ui.view;
<add>
<add>import com.vishnus1224.teamworkapidemo.model.ProjectDto;
<add>
<add>import java.util.List;
<add>
<add>/**
<add> * Created by Vishnu on 9/4/2016.
<add> */
<add>public interface ProjectsView extends BaseView {
<add>
<add> void showProjects(List<ProjectDto> projectDtoList);
<add>
<add> void showError();
<add>
<add> void showProjectsView();
<add>
<add> void hideProjectsView();
<add>
<add> void showNoProjectsView();
<add>
<add> void hideNoProjectsView();
<add>
<add> void showProgressBar();
<add>
<add> void hideProgressBar();
<add>}
|
|
Java
|
mit
|
286300910aa2c5b2881788d558d5d7a1ea82715c
| 0 |
carojkov/voltmeter,carojkov/voltmeter
|
package carojkov.voltmeter;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.DecimalFormat;
import java.util.Calendar;
public class Voltmeter implements TestStand
{
private RandomAccessFile _meter;
private float _voltFactor = 0.0556f;
private boolean _isVerbose = false;
private DecimalFormat _format = new DecimalFormat("0000");
public Voltmeter(String meterFile, boolean isVerbose) throws IOException
{
_meter = new RandomAccessFile(meterFile, "rwd");
_isVerbose = isVerbose;
Runtime.getRuntime().addShutdownHook(new Thread()
{
public void run()
{
try {
close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
}
@Override
public void reset(Calendar date,
int cycle,
int check,
boolean isFirst,
boolean isLast)
{
if (isFirst) {
reset();
configure();
}
if (!isFirst || isLast) {
test(date, cycle, check);
}
resetVoltage();
if (!isLast)
test(date, cycle, check);
}
@Override
public void test(Calendar date, int cycle, int check)
{
float[] values = measure();
String str = String.format("%s\t%d\t%f\t%f",
date.getTime(),
check,
values[0],
values[1]);
System.out.println(str);
}
public float[] measure()
{
try {
switchOn();
return readVoltage();
} finally {
switchOff();
}
}
private void reset()
{
send("R\r");
String feedback = read();
log(feedback);
}
private void resetVoltage()
{
send("PO,B,1,1\r");
String feedback = read();
assert "OK".equals(feedback);
try {
Thread.sleep(1000 * 2);
} catch (InterruptedException e) {
}
send("PO,B,1,0\r");
feedback = read();
assert "OK".equals(feedback);
}
private void switchOn()
{
send("PO,B,0,1\r");
String feedback = read();
assert "OK".equals(feedback);
log(feedback);
}
private void switchOff()
{
send("PO,B,0,0\r");
String feedback = read();
assert "OK".equals(feedback);
log(feedback);
}
private void log(String message)
{
if (_isVerbose)
System.out.println(message);
}
private void configure()
{
send("C,3,0,0,2\r");
String feedback = read();
log(feedback);
}
private void send(String command)
{
try {
_meter.write(command.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
private String read()
{
try {
byte[] buffer = new byte[256];
int i;
i = _meter.read(buffer);
return new String(buffer, 0, i);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public void run()
{
try {
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private float[] readVoltage()
{
float[] result = new float[]{-1, -1};
try {
send("A\r");
String value = read();// A,0024,0008
log("raw-value: " + value);
String[] valueParts = value.split(",");
result[0] = _format.parse(valueParts[1]).intValue() * _voltFactor;
result[1] = _format.parse(valueParts[2]).intValue() * _voltFactor;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
private void close() throws Exception
{
RandomAccessFile file = _meter;
_meter = null;
if (file != null)
file.close();
}
}
|
src/carojkov/voltmeter/Voltmeter.java
|
package carojkov.voltmeter;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.DecimalFormat;
import java.util.Calendar;
public class Voltmeter implements TestStand
{
private RandomAccessFile _meter;
private float _voltFactor = 0.0556f;
private boolean _isVerbose = false;
private DecimalFormat _format = new DecimalFormat("0000");
public Voltmeter(String meterFile, boolean isVerbose) throws IOException
{
_meter = new RandomAccessFile(meterFile, "rwd");
_isVerbose = isVerbose;
Runtime.getRuntime().addShutdownHook(new Thread()
{
public void run()
{
try {
close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
}
@Override
public void reset(Calendar date,
int cycle,
int check,
boolean isFirst,
boolean isLast)
{
if (isFirst) {
reset();
configure();
}
if (!isFirst || isLast) {
test(date, cycle, check);
}
resetVoltage();
test(date, cycle, check);
}
@Override
public void test(Calendar date, int cycle, int check)
{
float[] values = measure();
String str = String.format("%s\t%d\t%f\t%f",
date.getTime(),
check,
values[0],
values[1]);
System.out.println(str);
}
public float[] measure()
{
try {
switchOn();
return readVoltage();
} finally {
switchOff();
}
}
private void reset()
{
send("R\r");
String feedback = read();
log(feedback);
}
private void resetVoltage()
{
send("PO,B,1,1\r");
String feedback = read();
assert "OK".equals(feedback);
try {
Thread.sleep(1000 * 2);
} catch (InterruptedException e) {
}
send("PO,B,1,0\r");
feedback = read();
assert "OK".equals(feedback);
}
private void switchOn()
{
send("PO,B,0,1\r");
String feedback = read();
assert "OK".equals(feedback);
log(feedback);
}
private void switchOff()
{
send("PO,B,0,0\r");
String feedback = read();
assert "OK".equals(feedback);
log(feedback);
}
private void log(String message)
{
if (_isVerbose)
System.out.println(message);
}
private void configure()
{
send("C,3,0,0,2\r");
String feedback = read();
log(feedback);
}
private void send(String command)
{
try {
_meter.write(command.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
private String read()
{
try {
byte[] buffer = new byte[256];
int i;
i = _meter.read(buffer);
return new String(buffer, 0, i);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public void run()
{
try {
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private float[] readVoltage()
{
float[] result = new float[]{-1, -1};
try {
send("A\r");
String value = read();// A,0024,0008
log("raw-value: " + value);
String[] valueParts = value.split(",");
result[0] = _format.parse(valueParts[1]).intValue() * _voltFactor;
result[1] = _format.parse(valueParts[2]).intValue() * _voltFactor;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
private void close() throws Exception
{
RandomAccessFile file = _meter;
_meter = null;
if (file != null)
file.close();
}
}
|
debug
|
src/carojkov/voltmeter/Voltmeter.java
|
debug
|
<ide><path>rc/carojkov/voltmeter/Voltmeter.java
<ide>
<ide> resetVoltage();
<ide>
<del> test(date, cycle, check);
<add> if (!isLast)
<add> test(date, cycle, check);
<ide> }
<ide>
<ide> @Override
|
|
Java
|
agpl-3.0
|
6e8d76913dab3a43dab9517e146744c3f9364c3c
| 0 |
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
|
3f597ffe-2e60-11e5-9284-b827eb9e62be
|
hello.java
|
3f53fb9c-2e60-11e5-9284-b827eb9e62be
|
3f597ffe-2e60-11e5-9284-b827eb9e62be
|
hello.java
|
3f597ffe-2e60-11e5-9284-b827eb9e62be
|
<ide><path>ello.java
<del>3f53fb9c-2e60-11e5-9284-b827eb9e62be
<add>3f597ffe-2e60-11e5-9284-b827eb9e62be
|
|
Java
|
epl-1.0
|
2adb0c00bb050d2e3d3a35b646f2172fa88af8da
| 0 |
edgarmueller/emfstore-rest
|
/*******************************************************************************
* Copyright (c) 2008-2012 EclipseSource Muenchen GmbH.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
******************************************************************************/
package org.eclipse.emf.emfstore.client.ui.dialogs.login;
import java.util.HashSet;
import java.util.concurrent.Callable;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.emfstore.client.model.ServerInfo;
import org.eclipse.emf.emfstore.client.model.Usersession;
import org.eclipse.emf.emfstore.client.model.WorkspaceManager;
import org.eclipse.emf.emfstore.client.ui.common.RunInUI;
import org.eclipse.emf.emfstore.server.exceptions.AccessControlException;
import org.eclipse.emf.emfstore.server.exceptions.EmfStoreException;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Display;
/**
* The login dialog controller manages a given {@link Usersession} and/or a {@link ServerInfo} to determine
* when it is necessary to open a {@link LoginDialog} in order to authenticate the user.
* It does not, however, open a dialog, if the usersession is already logged in.
*
* @author ovonwesen
* @author emueller
*/
public class LoginDialogController implements ILoginDialogController {
private Usersession usersession;
private ServerInfo serverInfo;
/**
*
* {@inheritDoc}
*
* @see org.eclipse.emf.emfstore.client.ui.dialogs.login.ILoginDialogController#getKnownUsersessions()
*/
public Usersession[] getKnownUsersessions() {
HashSet<Object> set = new HashSet<Object>();
for (Usersession session : WorkspaceManager.getInstance().getCurrentWorkspace().getUsersessions()) {
if (getServerInfo().equals(session.getServerInfo())) {
set.add(session);
}
}
return set.toArray(new Usersession[set.size()]);
}
private Usersession login() throws EmfStoreException {
return RunInUI.WithException.runWithResult(new Callable<Usersession>() {
public Usersession call() throws Exception {
if (serverInfo.getLastUsersession() != null && serverInfo.getLastUsersession().isLoggedIn()) {
return serverInfo.getLastUsersession();
}
LoginDialog dialog = new LoginDialog(Display.getCurrent().getActiveShell(), LoginDialogController.this);
dialog.setBlockOnOpen(true);
if (dialog.open() != Window.OK || usersession == null) {
throw new AccessControlException("Couldn't login.");
}
// contract: #validate() sets the usersession;
return usersession;
}
});
}
/**
*
* {@inheritDoc}
*
* @see org.eclipse.emf.emfstore.client.ui.dialogs.login.ILoginDialogController#isUsersessionLocked()
*/
public boolean isUsersessionLocked() {
if (getUsersession() == null) {
return false;
}
return true;
}
/**
*
* {@inheritDoc}
*
* @see org.eclipse.emf.emfstore.client.ui.dialogs.login.ILoginDialogController#getServerLabel()
*/
public String getServerLabel() {
return getServerInfo().getName();
}
/**
*
* {@inheritDoc}
*
* @see org.eclipse.emf.emfstore.client.ui.dialogs.login.ILoginDialogController#validate(org.eclipse.emf.emfstore.client.model.Usersession)
*/
public void validate(Usersession usersession) throws EmfStoreException {
// TODO login code
usersession.logIn();
// if successful, else exception is thrown prior reaching this code
EList<Usersession> usersessions = WorkspaceManager.getInstance().getCurrentWorkspace().getUsersessions();
if (!usersessions.contains(usersession)) {
usersessions.add(usersession);
}
this.usersession = usersession;
WorkspaceManager.getInstance().getCurrentWorkspace().save();
}
/**
*
* {@inheritDoc}
*
* @see org.eclipse.emf.emfstore.client.ui.dialogs.login.ILoginDialogController#getUsersession()
*/
public Usersession getUsersession() {
return usersession;
}
/**
*
* {@inheritDoc}
*
* @see org.eclipse.emf.emfstore.client.ui.dialogs.login.ILoginDialogController#getServerInfo()
*/
public ServerInfo getServerInfo() {
if (serverInfo != null) {
return serverInfo;
}
return usersession.getServerInfo();
}
/**
* Perform a login using an {@link Usersession} that can be determined
* with the given {@link ServerInfo}.
*
*
* @param serverInfo
* the server info to be used in order to determine a valid usersession
* @return a logged-in usersession
* @throws EmfStoreException
* in case the login fails
*/
public Usersession login(ServerInfo serverInfo) throws EmfStoreException {
this.serverInfo = serverInfo;
this.usersession = null;
return login();
}
/**
* Perform a login using the given {@link Usersession}.
*
* @param usersession
* the usersession to be used during login
* @throws EmfStoreException
* in case the login fails
*/
public void login(Usersession usersession) throws EmfStoreException {
this.serverInfo = null;
this.usersession = usersession;
login();
}
}
|
org.eclipse.emf.emfstore.client.ui/src/org/eclipse/emf/emfstore/client/ui/dialogs/login/LoginDialogController.java
|
/*******************************************************************************
* Copyright (c) 2008-2012 EclipseSource Muenchen GmbH.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
******************************************************************************/
package org.eclipse.emf.emfstore.client.ui.dialogs.login;
import java.util.HashSet;
import java.util.concurrent.Callable;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.emfstore.client.model.ServerInfo;
import org.eclipse.emf.emfstore.client.model.Usersession;
import org.eclipse.emf.emfstore.client.model.WorkspaceManager;
import org.eclipse.emf.emfstore.client.ui.common.RunInUI;
import org.eclipse.emf.emfstore.server.exceptions.AccessControlException;
import org.eclipse.emf.emfstore.server.exceptions.EmfStoreException;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Display;
/**
* The login dialog controller manages a given {@link Usersession} and/or a {@link ServerInfo} to determine
* when it is necessary to open a {@link LoginDialog} in order to authenticate the user.
* It does not, however, open a dialog, if the usersession is already logged in.
*
* @author ovonwesen
* @author emueller
*/
public class LoginDialogController implements ILoginDialogController {
private Usersession usersession;
private ServerInfo serverInfo;
/**
*
* {@inheritDoc}
*
* @see org.eclipse.emf.emfstore.client.ui.dialogs.login.ILoginDialogController#getKnownUsersessions()
*/
public Usersession[] getKnownUsersessions() {
HashSet<Object> set = new HashSet<Object>();
for (Usersession session : WorkspaceManager.getInstance().getCurrentWorkspace().getUsersessions()) {
if (getServerInfo().equals(session.getServerInfo())) {
set.add(session);
}
}
return set.toArray(new Usersession[set.size()]);
}
private Usersession login() throws EmfStoreException {
return RunInUI.WithException.runWithResult(new Callable<Usersession>() {
public Usersession call() throws Exception {
LoginDialog dialog = new LoginDialog(Display.getCurrent().getActiveShell(), LoginDialogController.this);
dialog.setBlockOnOpen(true);
if (dialog.open() != Window.OK || usersession == null) {
throw new AccessControlException("Couldn't login.");
}
// contract: #validate() sets the usersession;
return usersession;
}
});
}
/**
*
* {@inheritDoc}
*
* @see org.eclipse.emf.emfstore.client.ui.dialogs.login.ILoginDialogController#isUsersessionLocked()
*/
public boolean isUsersessionLocked() {
if (getUsersession() == null) {
return false;
}
return true;
}
/**
*
* {@inheritDoc}
*
* @see org.eclipse.emf.emfstore.client.ui.dialogs.login.ILoginDialogController#getServerLabel()
*/
public String getServerLabel() {
return getServerInfo().getName();
}
/**
*
* {@inheritDoc}
*
* @see org.eclipse.emf.emfstore.client.ui.dialogs.login.ILoginDialogController#validate(org.eclipse.emf.emfstore.client.model.Usersession)
*/
public void validate(Usersession usersession) throws EmfStoreException {
// TODO login code
usersession.logIn();
// if successful, else exception is thrown prior reaching this code
EList<Usersession> usersessions = WorkspaceManager.getInstance().getCurrentWorkspace().getUsersessions();
if (!usersessions.contains(usersession)) {
usersessions.add(usersession);
}
this.usersession = usersession;
WorkspaceManager.getInstance().getCurrentWorkspace().save();
}
/**
*
* {@inheritDoc}
*
* @see org.eclipse.emf.emfstore.client.ui.dialogs.login.ILoginDialogController#getUsersession()
*/
public Usersession getUsersession() {
return usersession;
}
/**
*
* {@inheritDoc}
*
* @see org.eclipse.emf.emfstore.client.ui.dialogs.login.ILoginDialogController#getServerInfo()
*/
public ServerInfo getServerInfo() {
if (serverInfo != null) {
return serverInfo;
}
return usersession.getServerInfo();
}
/**
* Perform a login using an {@link Usersession} that can be determined
* with the given {@link ServerInfo}.
*
*
* @param serverInfo
* the server info to be used in order to determine a valid usersession
* @return a logged-in usersession
* @throws EmfStoreException
* in case the login fails
*/
public Usersession login(ServerInfo serverInfo) throws EmfStoreException {
this.serverInfo = serverInfo;
this.usersession = null;
return login();
}
/**
* Perform a login using the given {@link Usersession}.
*
* @param usersession
* the usersession to be used during login
* @throws EmfStoreException
* in case the login fails
*/
public void login(Usersession usersession) throws EmfStoreException {
this.serverInfo = null;
this.usersession = usersession;
login();
}
}
|
given a server info the login dialog controller logs in the last
usersession, if available
|
org.eclipse.emf.emfstore.client.ui/src/org/eclipse/emf/emfstore/client/ui/dialogs/login/LoginDialogController.java
|
given a server info the login dialog controller logs in the last usersession, if available
|
<ide><path>rg.eclipse.emf.emfstore.client.ui/src/org/eclipse/emf/emfstore/client/ui/dialogs/login/LoginDialogController.java
<ide> private Usersession login() throws EmfStoreException {
<ide> return RunInUI.WithException.runWithResult(new Callable<Usersession>() {
<ide> public Usersession call() throws Exception {
<add>
<add> if (serverInfo.getLastUsersession() != null && serverInfo.getLastUsersession().isLoggedIn()) {
<add> return serverInfo.getLastUsersession();
<add> }
<add>
<ide> LoginDialog dialog = new LoginDialog(Display.getCurrent().getActiveShell(), LoginDialogController.this);
<ide> dialog.setBlockOnOpen(true);
<ide>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.