lang
stringclasses
1 value
license
stringclasses
13 values
stderr
stringlengths
0
350
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
7
45.1k
new_contents
stringlengths
0
1.87M
new_file
stringlengths
6
292
old_contents
stringlengths
0
1.87M
message
stringlengths
6
9.26k
old_file
stringlengths
6
292
subject
stringlengths
0
4.45k
Java
mit
ed2a0fa35e30f9c63c02c0867d96cf4aa219cf9c
0
k-egor-smirnov/detour
package ru.alphach1337.detour; import java.util.ArrayList; import java.util.HashMap; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; public class Main extends JavaPlugin{ HashMap<Location, String> loc2 = new HashMap<Location, String>(); ArrayList<Location> loc = new ArrayList<Location>(); ArrayList<String> ignorePlayers = new ArrayList<String>(); public boolean isDetour = false; @Override public void onEnable() { } @Override public void onDisable() { } public boolean onCommand(final CommandSender sender, final Command cmd,final String commandLabel, final String[] args) { if (!(sender instanceof Player)){ return false; } if (args.length == 0){ return false; } Player p = (Player) sender; if (args[0].equalsIgnoreCase("join")) { if (!isDetour){ return false; } for (Location l2 : loc2.keySet()) { if (p.getName().equals(loc2.get(l2))) { return false; } } if (ignorePlayers.contains(p.getName())){ return false; } Location l = p.getLocation().clone(); loc2.put(l.clone(), p.getName()); loc.add(l.clone()); return true; } if (args[0].equalsIgnoreCase("next")) { if (!p.isOp()){ return false; } if (loc.isEmpty()) { return false; } p.teleport(loc.get(0)); for (Location st : loc2.keySet()) { if (loc.get(0).equals(st)){ String pl = loc2.get(st); loc.remove(0); loc2.remove(st); ignorePlayers.add(pl); p.sendMessage("Добро пожаловать к игроку " + pl); try { Player p2 = Bukkit.getPlayer(pl); p.sendMessage("Игрок " + p2.getName() + " онлайн"); } catch (Exception e) { p.sendMessage("Игрок " + pl + " оффлайн"); } return true; } } return true; } if (args[0].equalsIgnoreCase("start")) { if (!p.isOp()){ return false; } if (isDetour){ return false; } isDetour = true; //send msg; return true; } if (args[0].equalsIgnoreCase("stop")) { if (!p.isOp()){ return false; } if (!isDetour) { return false; } isDetour = false; loc.clear(); loc2.clear(); ignorePlayers.clear(); //send msg; return true; } return false; } }
src/ru/alphach1337/detour/Main.java
package ru.alphach1337.detour; import java.util.ArrayList; import java.util.HashMap; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.Listener; import org.bukkit.plugin.java.JavaPlugin; public class Main extends JavaPlugin{ HashMap<Location, String> loc2 = new HashMap<Location, String>(); ArrayList<Location> loc = new ArrayList<Location>(); ArrayList<String> ignorePlayers = new ArrayList<String>(); public boolean isDetour = false; @Override public void onEnable() { } @Override public void onDisable() { } public boolean onCommand(final CommandSender sender, final Command cmd,final String commandLabel, final String[] args) { if (!(sender instanceof Player)){ return false; } if (args.length == 0){ return false; } Player p = (Player) sender; if (args[0].equalsIgnoreCase("join")) { if (!isDetour) return false; if (ignorePlayers.contains(p.getName())) return false; Location l = p.getLocation().clone(); loc2.put(l.clone(), p.getName()); loc.add(l.clone()); return true; } if (args[0].equalsIgnoreCase("next")) { if (!p.isOp()){ return false; } if (loc.isEmpty()) { return false; } p.teleport(loc.get(0)); for (Location st : loc2.keySet()) { if (loc.get(0).equals(st)){ String pl = loc2.get(st); loc.remove(0); loc2.remove(st); ignorePlayers.add(pl); p.sendMessage("Добро пожаловать к игроку " + pl); try { Player p2 = Bukkit.getPlayer(pl); p.sendMessage("Игрок " + p2.getName() + " онлайн"); } catch (Exception e) { p.sendMessage("Игрок " + pl + " оффлайн"); } return true; } } return true; } if (args[0].equalsIgnoreCase("start")) { if (!p.isOp()){ return false; } if (isDetour){ return false; } isDetour = true; //send msg; return true; } if (args[0].equalsIgnoreCase("stop")) { if (!p.isOp()){ return false; } if (!isDetour) { return false; } isDetour = false; loc.clear(); loc2.clear(); ignorePlayers.clear(); //send msg; return true; } return false; } }
update
src/ru/alphach1337/detour/Main.java
update
Java
mit
673910c3be9e1e8415f734b8be63ffb3c81ad563
0
erogenousbeef/BeefCore
package erogenousbeef.core.multiblock; import java.util.HashSet; import java.util.LinkedList; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.IChunkProvider; import cpw.mods.fml.common.FMLLog; import erogenousbeef.core.common.CoordTriplet; /** * This class contains the base logic for "multiblock controllers". Conceptually, they are * meta-TileEntities. They govern the logic for an associated group of TileEntities. * * Subordinate TileEntities implement the IMultiblockPart class and, generally, should not have an update() loop. */ public abstract class MultiblockControllerBase { public static final short DIMENSION_UNBOUNDED = -1; // Multiblock stuff - do not mess with protected World worldObj; // Disassembled -> Assembled; Assembled -> Disassembled OR Paused; Paused -> Assembled protected enum AssemblyState { Disassembled, Assembled, Paused }; protected AssemblyState assemblyState; protected Set<CoordTriplet> connectedBlocks; /** This is a deterministically-picked coordinate that identifies this * multiblock uniquely in its dimension. * Currently, this is the coord with the lowest X, Y and Z coordinates, in that order of evaluation. * i.e. If something has a lower X but higher Y/Z coordinates, it will still be the reference. * If something has the same X but a lower Y coordinate, it will be the reference. Etc. */ protected CoordTriplet referenceCoord; /** * Minimum bounding box coordinate. Blocks do not necessarily exist at this coord if your machine * is not a cube/rectangular prism. */ private CoordTriplet minimumCoord; /** * Maximum bounding box coordinate. Blocks do not necessarily exist at this coord if your machine * is not a cube/rectangular prism. */ private CoordTriplet maximumCoord; /** * Set to true whenever a part is removed from this controller. */ private boolean shouldCheckForDisconnections; /** * Set whenever we validate the multiblock */ private MultiblockValidationException lastValidationException; protected boolean debugMode; protected MultiblockControllerBase(World world) { // Multiblock stuff worldObj = world; connectedBlocks = new HashSet<CoordTriplet>(); referenceCoord = null; assemblyState = AssemblyState.Disassembled; minimumCoord = new CoordTriplet(0,0,0); maximumCoord = new CoordTriplet(0,0,0); shouldCheckForDisconnections = true; lastValidationException = null; debugMode = false; } public void setDebugMode(boolean active) { debugMode = active; } public boolean isDebugMode() { return debugMode; } /** * Call when a block with cached save-delegate data is added to the multiblock. * The part will be notified that the data has been used after this call completes. * @param part The NBT tag containing this controller's data. */ public abstract void onAttachedPartWithMultiblockData(IMultiblockPart part, NBTTagCompound data); /** * Check if a block is being tracked by this machine. * @param blockCoord Coordinate to check. * @return True if the tile entity at blockCoord is being tracked by this machine, false otherwise. */ public boolean hasBlock(CoordTriplet blockCoord) { return connectedBlocks.contains(blockCoord); } /** * Attach a new part to this machine. * @param part The part to add. */ public void attachBlock(IMultiblockPart part) { IMultiblockPart candidate; CoordTriplet coord = part.getWorldLocation(); // No need to re-add a block if(connectedBlocks.contains(coord)) { FMLLog.warning("[%s] Controller %s is double-adding a block @ %s. This is unusual. If you encounter odd behavior, please tear down the machine and rebuild it.", (worldObj.isRemote?"CLIENT":"SERVER"), hashCode(), coord); } connectedBlocks.add(coord); part.onAttached(this); this.onBlockAdded(part); if(part.hasMultiblockSaveData()) { NBTTagCompound savedData = part.getMultiblockSaveData(); onAttachedPartWithMultiblockData(part, savedData); part.onMultiblockDataAssimilated(); } if(this.referenceCoord == null) { referenceCoord = coord; part.becomeMultiblockSaveDelegate(); } else if(coord.compareTo(referenceCoord) < 0) { TileEntity te = this.worldObj.getBlockTileEntity(referenceCoord.x, referenceCoord.y, referenceCoord.z); ((IMultiblockPart)te).forfeitMultiblockSaveDelegate(); referenceCoord = coord; part.becomeMultiblockSaveDelegate(); } else { part.forfeitMultiblockSaveDelegate(); } MultiblockRegistry.addDirtyController(worldObj, this); } /** * Called when a new part is added to the machine. Good time to register things into lists. * @param newPart The part being added. */ protected abstract void onBlockAdded(IMultiblockPart newPart); /** * Called when a part is removed from the machine. Good time to clean up lists. * @param oldPart The part being removed. */ protected abstract void onBlockRemoved(IMultiblockPart oldPart); /** * Called when a machine is assembled from a disassembled state. */ protected abstract void onMachineAssembled(); /** * Called when a machine is restored to the assembled state from a paused state. */ protected abstract void onMachineRestored(); /** * Called when a machine is paused from an assembled state * This generally only happens due to chunk-loads and other "system" events. */ protected abstract void onMachinePaused(); /** * Called when a machine is disassembled from an assembled state. * This happens due to user or in-game actions (e.g. explosions) */ protected abstract void onMachineDisassembled(); /** * Callback whenever a part is removed (or will very shortly be removed) from a controller. * Do housekeeping/callbacks. * @param part The part being removed. */ private void onDetachBlock(IMultiblockPart part) { // Strip out this part part.onDetached(this); this.onBlockRemoved(part); part.forfeitMultiblockSaveDelegate(); shouldCheckForDisconnections = true; } /** * Call to detach a block from this machine. Generally, this should be called * when the tile entity is being released, e.g. on block destruction. * @param part The part to detach from this machine. * @param chunkUnloading Is this entity detaching due to the chunk unloading? If true, the multiblock will be paused instead of broken. */ public void detachBlock(IMultiblockPart part, boolean chunkUnloading) { CoordTriplet coord = part.getWorldLocation(); if(chunkUnloading && this.assemblyState == AssemblyState.Assembled) { this.assemblyState = AssemblyState.Paused; this.onMachinePaused(); } // Strip out this part onDetachBlock(part); connectedBlocks.remove(coord); if(referenceCoord != null && referenceCoord.equals(coord)) { referenceCoord = null; } if(connectedBlocks.isEmpty()) { // Destroy/unregister MultiblockRegistry.addDeadController(this.worldObj, this); return; } MultiblockRegistry.addDirtyController(this.worldObj, this); // Find new save delegate if we need to. if(referenceCoord == null) { IChunkProvider chunkProvider = worldObj.getChunkProvider(); TileEntity theChosenOne = null; for(CoordTriplet connectedCoord : connectedBlocks) { if(!chunkProvider.chunkExists(connectedCoord.getChunkX(), connectedCoord.getChunkZ())) { // Chunk is unloading, skip this coord to prevent chunk thrashing continue; } // Check if TE has been removed for some reason, if so, we'll detach it soon. TileEntity te = this.worldObj.getBlockTileEntity(connectedCoord.x, connectedCoord.y, connectedCoord.z); if(te == null) { continue; } if(referenceCoord == null || connectedCoord.compareTo(referenceCoord) < 0) { referenceCoord = connectedCoord; theChosenOne = te; } } if(referenceCoord != null && theChosenOne != null) { ((IMultiblockPart)theChosenOne).becomeMultiblockSaveDelegate(); } // Else, wtf? } } /** * Helper method so we don't check for a whole machine until we have enough blocks * to actually assemble it. This isn't as simple as xmax*ymax*zmax for non-cubic machines * or for machines with hollow/complex interiors. * @return The minimum number of blocks connected to the machine for it to be assembled. */ protected abstract int getMinimumNumberOfBlocksForAssembledMachine(); /** * Returns the maximum X dimension size of the machine, or -1 (DIMENSION_UNBOUNDED) to disable * dimension checking in X. (This is not recommended.) * @return The maximum X dimension size of the machine, or -1 */ protected abstract int getMaximumXSize(); /** * Returns the maximum Z dimension size of the machine, or -1 (DIMENSION_UNBOUNDED) to disable * dimension checking in X. (This is not recommended.) * @return The maximum Z dimension size of the machine, or -1 */ protected abstract int getMaximumZSize(); /** * Returns the maximum Y dimension size of the machine, or -1 (DIMENSION_UNBOUNDED) to disable * dimension checking in X. (This is not recommended.) * @return The maximum Y dimension size of the machine, or -1 */ protected abstract int getMaximumYSize(); /** * Returns the minimum X dimension size of the machine. Must be at least 1, because nothing else makes sense. * @return The minimum X dimension size of the machine */ protected int getMinimumXSize() { return 1; } /** * Returns the minimum Y dimension size of the machine. Must be at least 1, because nothing else makes sense. * @return The minimum Y dimension size of the machine */ protected int getMinimumYSize() { return 1; } /** * Returns the minimum Z dimension size of the machine. Must be at least 1, because nothing else makes sense. * @return The minimum Z dimension size of the machine */ protected int getMinimumZSize() { return 1; } /** * @return An exception representing the last error encountered when trying to assemble this * multiblock, or null if there is no error. */ public MultiblockValidationException getLastValidationException() { return lastValidationException; } /** * @return True if the machine is "whole" and should be assembled. False otherwise. */ protected boolean isMachineWhole() throws MultiblockValidationException { if(connectedBlocks.size() < getMinimumNumberOfBlocksForAssembledMachine()) { throw new MultiblockValidationException("Machine is too small."); } // Quickly check for exceeded dimensions int deltaX = maximumCoord.x - minimumCoord.x + 1; int deltaY = maximumCoord.y - minimumCoord.y + 1; int deltaZ = maximumCoord.z - minimumCoord.z + 1; int maxX = getMaximumXSize(); int maxY = getMaximumYSize(); int maxZ = getMaximumZSize(); int minX = getMinimumXSize(); int minY = getMinimumYSize(); int minZ = getMinimumZSize(); if(maxX > 0 && deltaX > maxX) { throw new MultiblockValidationException(String.format("Machine is too large, it may be at most %d blocks in the X dimension", maxX)); } if(maxY > 0 && deltaY > maxY) { throw new MultiblockValidationException(String.format("Machine is too large, it may be at most %d blocks in the Y dimension", maxY)); } if(maxZ > 0 && deltaZ > maxZ) { throw new MultiblockValidationException(String.format("Machine is too large, it may be at most %d blocks in the Z dimension", maxZ)); } if(deltaX < minX) { throw new MultiblockValidationException(String.format("Machine is too small, it must be at least %d blocks in the X dimension", minX)); } if(deltaY < minY) { throw new MultiblockValidationException(String.format("Machine is too small, it must be at least %d blocks in the Y dimension", minY)); } if(deltaZ < minZ) { throw new MultiblockValidationException(String.format("Machine is too small, it must be at least %d blocks in the Z dimension", minZ)); } // Now we run a simple check on each block within that volume. // Any block deviating = NO DEAL SIR TileEntity te; IMultiblockPart part; for(int x = minimumCoord.x; x <= maximumCoord.x; x++) { for(int y = minimumCoord.y; y <= maximumCoord.y; y++) { for(int z = minimumCoord.z; z <= maximumCoord.z; z++) { // Okay, figure out what sort of block this should be. te = this.worldObj.getBlockTileEntity(x, y, z); if(te instanceof IMultiblockPart) { part = (IMultiblockPart)te; } else { // This is permitted so that we can incorporate certain non-multiblock parts inside interiors part = null; } // Validate block type against both part-level and material-level validators. int extremes = 0; if(x == minimumCoord.x) { extremes++; } if(y == minimumCoord.y) { extremes++; } if(z == minimumCoord.z) { extremes++; } if(x == maximumCoord.x) { extremes++; } if(y == maximumCoord.y) { extremes++; } if(z == maximumCoord.z) { extremes++; } if(extremes >= 2) { if(part != null) { part.isGoodForFrame(); } else { isBlockGoodForFrame(this.worldObj, x, y, z); } } else if(extremes == 1) { if(y == maximumCoord.y) { if(part != null) { part.isGoodForTop(); } else { isBlockGoodForTop(this.worldObj, x, y, z); } } else if(y == minimumCoord.y) { if(part != null) { part.isGoodForBottom(); } else { isBlockGoodForBottom(this.worldObj, x, y, z); } } else { // Side if(part != null) { part.isGoodForSides(); } else { isBlockGoodForSides(this.worldObj, x, y, z); } } } else { if(part != null) { part.isGoodForInterior(); } else { isBlockGoodForInterior(this.worldObj, x, y, z); } } } } } return true; } /** * Check if the machine is whole or not. * If the machine was not whole, but now is, assemble the machine. * If the machine was whole, but no longer is, disassemble the machine. * @return */ public void checkIfMachineIsWhole() { AssemblyState oldState = this.assemblyState; boolean isWhole; lastValidationException = null; try { isWhole = isMachineWhole(); } catch (MultiblockValidationException e) { lastValidationException = e; isWhole = false; } if(isWhole) { // This will alter assembly state assembleMachine(oldState); } else if(oldState == AssemblyState.Assembled) { // This will alter assembly state disassembleMachine(); if(isDebugMode()) { FMLLog.info("[%s] Machine %d is disassembling. Check above here for stacktraces indicating why this reactor broke.", worldObj.isRemote?"CLIENT":"SERVER", hashCode()); } } // Else Paused, do nothing } /** * Called when a machine becomes "whole" and should begin * functioning as a game-logically finished machine. * Calls onMachineAssembled on all attached parts. */ private void assembleMachine(AssemblyState oldState) { TileEntity te; // No chunk safety checks because these things should all be in loaded chunks already for(CoordTriplet coord : connectedBlocks) { te = this.worldObj.getBlockTileEntity(coord.x, coord.y, coord.z); if(te instanceof IMultiblockPart) { ((IMultiblockPart)te).onMachineAssembled(this); } } this.assemblyState = AssemblyState.Assembled; if(oldState == assemblyState.Paused) { onMachineRestored(); } else { onMachineAssembled(); } } /** * Called when the machine needs to be disassembled. * It is not longer "whole" and should not be functional, usually * as a result of a block being removed. * Calls onMachineBroken on all attached parts. */ private void disassembleMachine() { TileEntity te; IChunkProvider chunkProvider = worldObj.getChunkProvider(); for(CoordTriplet coord : connectedBlocks) { if(!chunkProvider.chunkExists(coord.getChunkX(), coord.getChunkZ())) { // Chunk is already unloaded, don't fetch the TE. // This happens on SMP servers when players log out. continue; } te = this.worldObj.getBlockTileEntity(coord.x, coord.y, coord.z); if(te instanceof IMultiblockPart) { ((IMultiblockPart)te).onMachineBroken(); } } this.assemblyState = AssemblyState.Disassembled; onMachineDisassembled(); } /** * Assimilate another controller into this controller. * Acquire all of the other controller's blocks and attach them * to this one. * * @param other The controller to merge into this one. */ public void assimilate(MultiblockControllerBase other) { if(other.referenceCoord != null && this.referenceCoord.compareTo(other.referenceCoord) >= 0) { throw new IllegalArgumentException("The controller with the lowest minimum-coord value must consume the one with the higher coords"); } TileEntity te; Set<CoordTriplet> blocksToAcquire = new CopyOnWriteArraySet<CoordTriplet>(other.connectedBlocks); // releases all blocks and references gently so they can be incorporated into another multiblock other._onAssimilated(this); IMultiblockPart acquiredPart; for(CoordTriplet coord : blocksToAcquire) { // By definition, none of these can be the minimum block. te = this.worldObj.getBlockTileEntity(coord.x, coord.y, coord.z); if(te instanceof IMultiblockPart) { acquiredPart = (IMultiblockPart)te; this.connectedBlocks.add(coord); acquiredPart.onAssimilated(this); this.onBlockAdded(acquiredPart); } } this.onAssimilate(other); other.onAssimilated(this); } /** * Called when this machine is consumed by another controller. * Essentially, forcibly tear down this object. * @param otherController The controller consuming this controller. */ private void _onAssimilated(MultiblockControllerBase otherController) { if(referenceCoord != null) { if(worldObj.getChunkProvider().chunkExists(referenceCoord.getChunkX(), referenceCoord.getChunkZ())) { TileEntity te = this.worldObj.getBlockTileEntity(referenceCoord.x, referenceCoord.y, referenceCoord.z); if(te instanceof IMultiblockPart) { ((IMultiblockPart)te).forfeitMultiblockSaveDelegate(); } } this.referenceCoord = null; } this.connectedBlocks.clear(); } /** * Callback. Called after this controller assimilates all the blocks * from another controller. * Use this to absorb that controller's game data. * @param assimilated The controller whose uniqueness was added to our own. */ protected abstract void onAssimilate(MultiblockControllerBase assimilated); /** * Callback. Called after this controller is assimilated into another controller. * All blocks have been stripped out of this object and handed over to the * other controller. * This is intended primarily for cleanup. * @param assimilator The controller which has assimilated this controller. */ protected abstract void onAssimilated(MultiblockControllerBase assimilator); /** * Driver for the update loop. If the machine is assembled, runs * the game logic update method. * @see erogenousbeef.core.multiblock.MultiblockControllerBase#update() */ public final void updateMultiblockEntity() { if(connectedBlocks.isEmpty()) { // This shouldn't happen, but just in case... MultiblockRegistry.addDeadController(this.worldObj, this); return; } if(this.assemblyState != AssemblyState.Assembled) { // Not assembled - don't run game logic return; } if(worldObj.isRemote) { updateClient(); } else if(updateServer()) { // If this returns true, the server has changed its internal data. // If our chunks are loaded (they should be), we must mark our chunks as dirty. if(this.worldObj.checkChunksExist(minimumCoord.x, minimumCoord.y, minimumCoord.z, maximumCoord.x, maximumCoord.y, maximumCoord.z)) { int minChunkX = minimumCoord.x >> 4; int minChunkZ = minimumCoord.z >> 4; int maxChunkX = maximumCoord.x >> 4; int maxChunkZ = maximumCoord.z >> 4; for(int x = minChunkX; x <= maxChunkX; x++) { for(int z = minChunkZ; z <= maxChunkZ; z++) { // Ensure that we save our data, even if the our save delegate is in has no TEs. Chunk chunkToSave = this.worldObj.getChunkFromChunkCoords(x, z); chunkToSave.setChunkModified(); } } } } // Else: Server, but no need to save data. } /** * The server-side update loop! Use this similarly to a TileEntity's update loop. * You do not need to call your superclass' update() if you're directly * derived from MultiblockControllerBase. This is a callback. * Note that this will only be called when the machine is assembled. * @return True if the multiblock should save data, i.e. its internal game state has changed. False otherwise. */ protected abstract boolean updateServer(); /** * Client-side update loop. Generally, this shouldn't do anything, but if you want * to do some interpolation or something, do it here. */ protected abstract void updateClient(); // Validation helpers /** * The "frame" consists of the outer edges of the machine, plus the corners. * * @param world World object for the world in which this controller is located. * @param x X coordinate of the block being tested * @param y Y coordinate of the block being tested * @param z Z coordinate of the block being tested * @throws MultiblockValidationException if the tested block is not allowed on the machine's frame */ protected void isBlockGoodForFrame(World world, int x, int y, int z) throws MultiblockValidationException { throw new MultiblockValidationException(String.format("%d, %d, %d - Block is not valid for use in the machine's interior", x, y, z)); } /** * The top consists of the top face, minus the edges. * @param world World object for the world in which this controller is located. * @param x X coordinate of the block being tested * @param y Y coordinate of the block being tested * @param z Z coordinate of the block being tested * @throws MultiblockValidationException if the tested block is not allowed on the machine's top face */ protected void isBlockGoodForTop(World world, int x, int y, int z) throws MultiblockValidationException { throw new MultiblockValidationException(String.format("%d, %d, %d - Block is not valid for use in the machine's interior", x, y, z)); } /** * The bottom consists of the bottom face, minus the edges. * @param world World object for the world in which this controller is located. * @param x X coordinate of the block being tested * @param y Y coordinate of the block being tested * @param z Z coordinate of the block being tested * @throws MultiblockValidationException if the tested block is not allowed on the machine's bottom face */ protected void isBlockGoodForBottom(World world, int x, int y, int z) throws MultiblockValidationException { throw new MultiblockValidationException(String.format("%d, %d, %d - Block is not valid for use in the machine's interior", x, y, z)); } /** * The sides consists of the N/E/S/W-facing faces, minus the edges. * @param world World object for the world in which this controller is located. * @param x X coordinate of the block being tested * @param y Y coordinate of the block being tested * @param z Z coordinate of the block being tested * @throws MultiblockValidationException if the tested block is not allowed on the machine's side faces */ protected void isBlockGoodForSides(World world, int x, int y, int z) throws MultiblockValidationException { throw new MultiblockValidationException(String.format("%d, %d, %d - Block is not valid for use in the machine's interior", x, y, z)); } /** * The interior is any block that does not touch blocks outside the machine. * @param world World object for the world in which this controller is located. * @param x X coordinate of the block being tested * @param y Y coordinate of the block being tested * @param z Z coordinate of the block being tested * @throws MultiblockValidationException if the tested block is not allowed in the machine's interior */ protected void isBlockGoodForInterior(World world, int x, int y, int z) throws MultiblockValidationException { throw new MultiblockValidationException(String.format("%d, %d, %d - Block is not valid for use in the machine's interior", x, y, z)); } /** * @return The reference coordinate, the block with the lowest x, y, z coordinates, evaluated in that order. */ public CoordTriplet getReferenceCoord() { return referenceCoord; } /** * @return The number of blocks connected to this controller. */ public int getNumConnectedBlocks() { return connectedBlocks.size(); } public abstract void writeToNBT(NBTTagCompound data); public abstract void readFromNBT(NBTTagCompound data); /** * Force this multiblock to recalculate its minimum and maximum coordinates * from the list of connected parts. */ public void recalculateMinMaxCoords() { minimumCoord.x = minimumCoord.y = minimumCoord.z = Integer.MAX_VALUE; maximumCoord.x = maximumCoord.y = maximumCoord.z = Integer.MIN_VALUE; for(CoordTriplet coord : connectedBlocks) { if(coord.x < minimumCoord.x) { minimumCoord.x = coord.x; } if(coord.x > maximumCoord.x) { maximumCoord.x = coord.x; } if(coord.y < minimumCoord.y) { minimumCoord.y = coord.y; } if(coord.y > maximumCoord.y) { maximumCoord.y = coord.y; } if(coord.z < minimumCoord.z) { minimumCoord.z = coord.z; } if(coord.z > maximumCoord.z) { maximumCoord.z = coord.z; } } } /** * @return The minimum bounding-box coordinate containing this machine's blocks. */ public CoordTriplet getMinimumCoord() { return minimumCoord.copy(); } /** * @return The maximum bounding-box coordinate containing this machine's blocks. */ public CoordTriplet getMaximumCoord() { return maximumCoord.copy(); } /** * Called when the save delegate's tile entity is being asked for its description packet * @param tag A fresh compound tag to write your multiblock data into */ public abstract void formatDescriptionPacket(NBTTagCompound data); /** * Called when the save delegate's tile entity receiving a description packet * @param tag A compound tag containing multiblock data to import */ public abstract void decodeDescriptionPacket(NBTTagCompound data); /** * @return True if this controller has no associated blocks, false otherwise */ public boolean isEmpty() { return this.connectedBlocks.isEmpty(); } /** * Tests whether this multiblock should consume the other multiblock * and become the new multiblock master when the two multiblocks * are adjacent. Assumes both multiblocks are the same type. * @param otherController The other multiblock controller. * @return True if this multiblock should consume the other, false otherwise. */ public boolean shouldConsume(MultiblockControllerBase otherController) { if(!otherController.getClass().equals(getClass())) { throw new IllegalArgumentException("Attempting to merge two multiblocks with different master classes - this should never happen!"); } if(otherController == this) { return false; } // Don't be silly, don't eat yourself. CoordTriplet myCoord = getReferenceCoord(); CoordTriplet theirCoord = otherController.getReferenceCoord(); // Always consume other controllers if their reference coordinate is null - this means they're empty and can be assimilated on the cheap if(theirCoord == null) { return true; } int res = myCoord.compareTo(theirCoord); if(res < 0) { return true; } else if(res > 0) { return false; } else { FMLLog.severe("My Controller (%d): size (%d), coords: %s", hashCode(), connectedBlocks.size(), java.util.Arrays.toString(connectedBlocks.toArray())); FMLLog.severe("Other Controller (%d): size (%d), coords: %s", otherController.hashCode(), otherController.connectedBlocks.size(), java.util.Arrays.toString(otherController.connectedBlocks.toArray())); throw new IllegalArgumentException("[" + (worldObj.isRemote?"CLIENT":"SERVER") + "] Two controllers with the same reference coord - this should never happen!"); } } /** * Called when this machine may need to check for blocks that are no * longer physically connected to the reference coordinate. * @return */ public Set<IMultiblockPart> checkForDisconnections() { if(!this.shouldCheckForDisconnections) { return null; } if(this.isEmpty()) { return null; } // We've run the checks from here on out. shouldCheckForDisconnections = false; TileEntity te; IChunkProvider chunkProvider = worldObj.getChunkProvider(); // Ensure that our current reference coord is valid. If not, invalidate it. if(referenceCoord != null) { if(!chunkProvider.chunkExists(referenceCoord.getChunkX(), referenceCoord.getChunkZ()) || worldObj.getBlockTileEntity(referenceCoord.x, referenceCoord.y, referenceCoord.z) == null) { referenceCoord = null; } } // Reset visitations and find the minimum coordinate Set<CoordTriplet> deadCoords = new HashSet<CoordTriplet>(); IMultiblockPart part = null; int originalSize = connectedBlocks.size(); for(CoordTriplet c: connectedBlocks) { // This happens during chunk unload. if(!chunkProvider.chunkExists(c.x >> 4, c.z >> 4)) { deadCoords.add(c); continue; } te = this.worldObj.getBlockTileEntity(c.x, c.y, c.z); if(!(te instanceof IMultiblockPart)) { // This happens during chunk unload. Consider it valid, move on. deadCoords.add(c); continue; } part = (IMultiblockPart)te; part.setUnvisited(); if(referenceCoord == null) { referenceCoord = c; } else if(c.compareTo(referenceCoord) < 0) { referenceCoord = c; } } connectedBlocks.removeAll(deadCoords); deadCoords.clear(); if(referenceCoord == null || isEmpty()) { // There are no valid parts remaining. The entire multiblock was unloaded during a chunk unload. Halt. return null; } IMultiblockPart referencePart = (IMultiblockPart)worldObj.getBlockTileEntity(referenceCoord.x, referenceCoord.y, referenceCoord.z); // Now visit all connected parts, breadth-first, starting from reference coord's part LinkedList<IMultiblockPart> partsToCheck = new LinkedList<IMultiblockPart>(); IMultiblockPart[] nearbyParts = null; partsToCheck.add(referencePart); int visitedParts = 0; while(!partsToCheck.isEmpty()) { part = partsToCheck.removeFirst(); part.setVisited(); visitedParts++; nearbyParts = part.getNeighboringParts(); // Chunk-safe on server, but not on client for(IMultiblockPart nearbyPart : nearbyParts) { // Ignore different machines if(nearbyPart.getMultiblockController() != this) { continue; } if(!nearbyPart.isVisited()) { nearbyPart.setVisited(); partsToCheck.add(nearbyPart); } } } // Finally, remove all parts that remain disconnected. Set<IMultiblockPart> removedParts = new HashSet<IMultiblockPart>(); IMultiblockPart orphanCandidate; for(CoordTriplet c : connectedBlocks) { te = worldObj.getBlockTileEntity(c.x, c.y, c.z); if(!(te instanceof IMultiblockPart)) { // Weird chunk problems? deadCoords.add(c); continue; } orphanCandidate = (IMultiblockPart)te; if (!orphanCandidate.isVisited()) { deadCoords.add(c); orphanCandidate.onOrphaned(this, originalSize, visitedParts); onDetachBlock(orphanCandidate); removedParts.add(orphanCandidate); } } // Trim any blocks that were invalid, or were removed. this.connectedBlocks.removeAll(deadCoords); // Cleanup. Not necessary, really. deadCoords.clear(); return removedParts; } /** * Detach all parts. Return a set of all parts which still * have a valid tile entity. Chunk-safe. * @return A set of all parts which still have a valid tile entity. */ public Set<IMultiblockPart> detachAllBlocks() { Set<IMultiblockPart> detachedParts = new HashSet<IMultiblockPart>(); if(worldObj == null) { return detachedParts; } IChunkProvider chunkProvider = worldObj.getChunkProvider(); TileEntity te; IMultiblockPart part; for(CoordTriplet c : connectedBlocks) { if(chunkProvider.chunkExists(c.getChunkX(), c.getChunkZ())) { te = worldObj.getBlockTileEntity(c.x, c.y, c.z); if(te instanceof IMultiblockPart) { part = (IMultiblockPart)te; onDetachBlock(part); detachedParts.add(part); } } } connectedBlocks.clear(); return detachedParts; } /** * Called from a part that wishes to store data from this controller when it gets orphaned. * Generally, this data will be read back in during onAddedPartWithMultiblockData(). * @param newOrphan The part being orphaned. * @param oldSize The size of the controller before detaching orphans. * @param newSize The size of the controller after detaching orphans. * @param dataContainer An NBT Compound Tag into which to write data. */ public abstract void getOrphanData(IMultiblockPart newOrphan, int oldSize, int newSize, NBTTagCompound dataContainer); /** * @return True if this multiblock machine is considered assembled and ready to go. */ public boolean isAssembled() { return this.assemblyState == AssemblyState.Assembled; } }
erogenousbeef/core/multiblock/MultiblockControllerBase.java
package erogenousbeef.core.multiblock; import java.util.HashSet; import java.util.LinkedList; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.IChunkProvider; import cpw.mods.fml.common.FMLLog; import erogenousbeef.core.common.CoordTriplet; /** * This class contains the base logic for "multiblock controllers". Conceptually, they are * meta-TileEntities. They govern the logic for an associated group of TileEntities. * * Subordinate TileEntities implement the IMultiblockPart class and, generally, should not have an update() loop. */ public abstract class MultiblockControllerBase { public static final short DIMENSION_UNBOUNDED = -1; // Multiblock stuff - do not mess with protected World worldObj; // Disassembled -> Assembled; Assembled -> Disassembled OR Paused; Paused -> Assembled protected enum AssemblyState { Disassembled, Assembled, Paused }; protected AssemblyState assemblyState; protected Set<CoordTriplet> connectedBlocks; /** This is a deterministically-picked coordinate that identifies this * multiblock uniquely in its dimension. * Currently, this is the coord with the lowest X, Y and Z coordinates, in that order of evaluation. * i.e. If something has a lower X but higher Y/Z coordinates, it will still be the reference. * If something has the same X but a lower Y coordinate, it will be the reference. Etc. */ protected CoordTriplet referenceCoord; /** * Minimum bounding box coordinate. Blocks do not necessarily exist at this coord if your machine * is not a cube/rectangular prism. */ private CoordTriplet minimumCoord; /** * Maximum bounding box coordinate. Blocks do not necessarily exist at this coord if your machine * is not a cube/rectangular prism. */ private CoordTriplet maximumCoord; /** * Set to true whenever a part is removed from this controller. */ private boolean shouldCheckForDisconnections; /** * Set whenever we validate the multiblock */ private MultiblockValidationException lastValidationException; protected boolean debugMode; protected MultiblockControllerBase(World world) { // Multiblock stuff worldObj = world; connectedBlocks = new HashSet<CoordTriplet>(); referenceCoord = null; assemblyState = AssemblyState.Disassembled; minimumCoord = new CoordTriplet(0,0,0); maximumCoord = new CoordTriplet(0,0,0); shouldCheckForDisconnections = true; lastValidationException = null; debugMode = false; } public void setDebugMode(boolean active) { debugMode = active; } public boolean isDebugMode() { return debugMode; } /** * Call when a block with cached save-delegate data is added to the multiblock. * The part will be notified that the data has been used after this call completes. * @param part The NBT tag containing this controller's data. */ public abstract void onAttachedPartWithMultiblockData(IMultiblockPart part, NBTTagCompound data); /** * Check if a block is being tracked by this machine. * @param blockCoord Coordinate to check. * @return True if the tile entity at blockCoord is being tracked by this machine, false otherwise. */ public boolean hasBlock(CoordTriplet blockCoord) { return connectedBlocks.contains(blockCoord); } /** * Attach a new part to this machine. * @param part The part to add. */ public void attachBlock(IMultiblockPart part) { IMultiblockPart candidate; CoordTriplet coord = part.getWorldLocation(); // No need to re-add a block if(connectedBlocks.contains(coord)) { FMLLog.warning("[%s] Controller %s is double-adding a block @ %s. This is unusual. If you encounter odd behavior, please tear down the machine and rebuild it.", (worldObj.isRemote?"CLIENT":"SERVER"), hashCode(), coord); } connectedBlocks.add(coord); part.onAttached(this); this.onBlockAdded(part); if(part.hasMultiblockSaveData()) { NBTTagCompound savedData = part.getMultiblockSaveData(); onAttachedPartWithMultiblockData(part, savedData); part.onMultiblockDataAssimilated(); } if(this.referenceCoord == null) { referenceCoord = coord; part.becomeMultiblockSaveDelegate(); } else if(coord.compareTo(referenceCoord) < 0) { TileEntity te = this.worldObj.getBlockTileEntity(referenceCoord.x, referenceCoord.y, referenceCoord.z); ((IMultiblockPart)te).forfeitMultiblockSaveDelegate(); referenceCoord = coord; part.becomeMultiblockSaveDelegate(); } else { part.forfeitMultiblockSaveDelegate(); } MultiblockRegistry.addDirtyController(worldObj, this); } /** * Called when a new part is added to the machine. Good time to register things into lists. * @param newPart The part being added. */ protected abstract void onBlockAdded(IMultiblockPart newPart); /** * Called when a part is removed from the machine. Good time to clean up lists. * @param oldPart The part being removed. */ protected abstract void onBlockRemoved(IMultiblockPart oldPart); /** * Called when a machine is assembled from a disassembled state. */ protected abstract void onMachineAssembled(); /** * Called when a machine is restored to the assembled state from a paused state. */ protected abstract void onMachineRestored(); /** * Called when a machine is paused from an assembled state * This generally only happens due to chunk-loads and other "system" events. */ protected abstract void onMachinePaused(); /** * Called when a machine is disassembled from an assembled state. * This happens due to user or in-game actions (e.g. explosions) */ protected abstract void onMachineDisassembled(); /** * Callback whenever a part is removed (or will very shortly be removed) from a controller. * Do housekeeping/callbacks. * @param part The part being removed. */ private void onDetachBlock(IMultiblockPart part) { // Strip out this part part.onDetached(this); this.onBlockRemoved(part); part.forfeitMultiblockSaveDelegate(); shouldCheckForDisconnections = true; } /** * Call to detach a block from this machine. Generally, this should be called * when the tile entity is being released, e.g. on block destruction. * @param part The part to detach from this machine. * @param chunkUnloading Is this entity detaching due to the chunk unloading? If true, the multiblock will be paused instead of broken. */ public void detachBlock(IMultiblockPart part, boolean chunkUnloading) { CoordTriplet coord = part.getWorldLocation(); if(chunkUnloading && this.assemblyState == AssemblyState.Assembled) { this.assemblyState = AssemblyState.Paused; this.onMachinePaused(); } // Strip out this part onDetachBlock(part); connectedBlocks.remove(coord); if(referenceCoord != null && referenceCoord.equals(coord)) { referenceCoord = null; } if(connectedBlocks.isEmpty()) { // Destroy/unregister MultiblockRegistry.addDeadController(this.worldObj, this); return; } MultiblockRegistry.addDirtyController(this.worldObj, this); // Find new save delegate if we need to. if(referenceCoord == null) { IChunkProvider chunkProvider = worldObj.getChunkProvider(); TileEntity theChosenOne = null; for(CoordTriplet connectedCoord : connectedBlocks) { if(!chunkProvider.chunkExists(connectedCoord.getChunkX(), connectedCoord.getChunkZ())) { // Chunk is unloading, skip this coord to prevent chunk thrashing continue; } // Check if TE has been removed for some reason, if so, we'll detach it soon. TileEntity te = this.worldObj.getBlockTileEntity(connectedCoord.x, connectedCoord.y, connectedCoord.z); if(te == null) { continue; } if(referenceCoord == null || connectedCoord.compareTo(referenceCoord) < 0) { referenceCoord = connectedCoord; theChosenOne = te; } } if(referenceCoord != null && theChosenOne != null) { ((IMultiblockPart)theChosenOne).becomeMultiblockSaveDelegate(); } // Else, wtf? } } /** * Helper method so we don't check for a whole machine until we have enough blocks * to actually assemble it. This isn't as simple as xmax*ymax*zmax for non-cubic machines * or for machines with hollow/complex interiors. * @return The minimum number of blocks connected to the machine for it to be assembled. */ protected abstract int getMinimumNumberOfBlocksForAssembledMachine(); /** * Returns the maximum X dimension size of the machine, or -1 (DIMENSION_UNBOUNDED) to disable * dimension checking in X. (This is not recommended.) * @return The maximum X dimension size of the machine, or -1 */ protected abstract int getMaximumXSize(); /** * Returns the maximum Z dimension size of the machine, or -1 (DIMENSION_UNBOUNDED) to disable * dimension checking in X. (This is not recommended.) * @return The maximum Z dimension size of the machine, or -1 */ protected abstract int getMaximumZSize(); /** * Returns the maximum Y dimension size of the machine, or -1 (DIMENSION_UNBOUNDED) to disable * dimension checking in X. (This is not recommended.) * @return The maximum Y dimension size of the machine, or -1 */ protected abstract int getMaximumYSize(); /** * Returns the minimum X dimension size of the machine. Must be at least 1, because nothing else makes sense. * @return The minimum X dimension size of the machine */ protected int getMinimumXSize() { return 1; } /** * Returns the minimum Y dimension size of the machine. Must be at least 1, because nothing else makes sense. * @return The minimum Y dimension size of the machine */ protected int getMinimumYSize() { return 1; } /** * Returns the minimum Z dimension size of the machine. Must be at least 1, because nothing else makes sense. * @return The minimum Z dimension size of the machine */ protected int getMinimumZSize() { return 1; } /** * @return An exception representing the last error encountered when trying to assemble this * multiblock, or null if there is no error. */ public MultiblockValidationException getLastValidationException() { return lastValidationException; } /** * @return True if the machine is "whole" and should be assembled. False otherwise. */ protected boolean isMachineWhole() throws MultiblockValidationException { if(connectedBlocks.size() < getMinimumNumberOfBlocksForAssembledMachine()) { throw new MultiblockValidationException("Machine is too small."); } // Quickly check for exceeded dimensions int deltaX = maximumCoord.x - minimumCoord.x + 1; int deltaY = maximumCoord.y - minimumCoord.y + 1; int deltaZ = maximumCoord.z - minimumCoord.z + 1; int maxX = getMaximumXSize(); int maxY = getMaximumYSize(); int maxZ = getMaximumZSize(); int minX = getMinimumXSize(); int minY = getMinimumYSize(); int minZ = getMinimumZSize(); if(maxX > 0 && deltaX > maxX) { throw new MultiblockValidationException(String.format("Machine is too large, it may be at most %d blocks in the X dimension", maxX)); } if(maxY > 0 && deltaY > maxY) { throw new MultiblockValidationException(String.format("Machine is too large, it may be at most %d blocks in the Y dimension", maxY)); } if(maxZ > 0 && deltaZ > maxZ) { throw new MultiblockValidationException(String.format("Machine is too large, it may be at most %d blocks in the Z dimension", maxZ)); } if(deltaX < minX) { throw new MultiblockValidationException(String.format("Machine is too small, it must be at least %d blocks in the X dimension", minX)); } if(deltaY < minY) { throw new MultiblockValidationException(String.format("Machine is too small, it must be at least %d blocks in the Y dimension", minY)); } if(deltaZ < minZ) { throw new MultiblockValidationException(String.format("Machine is too small, it must be at least %d blocks in the Z dimension", minZ)); } // Now we run a simple check on each block within that volume. // Any block deviating = NO DEAL SIR TileEntity te; IMultiblockPart part; for(int x = minimumCoord.x; x <= maximumCoord.x; x++) { for(int y = minimumCoord.y; y <= maximumCoord.y; y++) { for(int z = minimumCoord.z; z <= maximumCoord.z; z++) { // Okay, figure out what sort of block this should be. te = this.worldObj.getBlockTileEntity(x, y, z); if(te instanceof IMultiblockPart) { part = (IMultiblockPart)te; } else { // This is permitted so that we can incorporate certain non-multiblock parts inside interiors part = null; } // Validate block type against both part-level and material-level validators. int extremes = 0; if(x == minimumCoord.x) { extremes++; } if(y == minimumCoord.y) { extremes++; } if(z == minimumCoord.z) { extremes++; } if(x == maximumCoord.x) { extremes++; } if(y == maximumCoord.y) { extremes++; } if(z == maximumCoord.z) { extremes++; } if(extremes >= 2) { if(part != null) { part.isGoodForFrame(); } else { isBlockGoodForFrame(this.worldObj, x, y, z); } } else if(extremes == 1) { if(y == maximumCoord.y) { if(part != null) { part.isGoodForTop(); } else { isBlockGoodForTop(this.worldObj, x, y, z); } } else if(y == minimumCoord.y) { if(part != null) { part.isGoodForBottom(); } else { isBlockGoodForBottom(this.worldObj, x, y, z); } } else { // Side if(part != null) { part.isGoodForSides(); } else { isBlockGoodForSides(this.worldObj, x, y, z); } } } else { if(part != null) { part.isGoodForInterior(); } else { isBlockGoodForInterior(this.worldObj, x, y, z); } } } } } return true; } /** * Check if the machine is whole or not. * If the machine was not whole, but now is, assemble the machine. * If the machine was whole, but no longer is, disassemble the machine. * @return */ public void checkIfMachineIsWhole() { AssemblyState oldState = this.assemblyState; boolean isWhole; lastValidationException = null; try { isWhole = isMachineWhole(); } catch (MultiblockValidationException e) { lastValidationException = e; isWhole = false; } if(isWhole) { // This will alter assembly state assembleMachine(oldState); } else if(oldState == AssemblyState.Assembled) { // This will alter assembly state disassembleMachine(); if(isDebugMode()) { FMLLog.info("[%s] Machine %d is disassembling. Check above here for stacktraces indicating why this reactor broke.", worldObj.isRemote?"CLIENT":"SERVER", hashCode()); } } // Else Paused, do nothing } /** * Called when a machine becomes "whole" and should begin * functioning as a game-logically finished machine. * Calls onMachineAssembled on all attached parts. */ private void assembleMachine(AssemblyState oldState) { TileEntity te; // No chunk safety checks because these things should all be in loaded chunks already for(CoordTriplet coord : connectedBlocks) { te = this.worldObj.getBlockTileEntity(coord.x, coord.y, coord.z); if(te instanceof IMultiblockPart) { ((IMultiblockPart)te).onMachineAssembled(this); } } this.assemblyState = AssemblyState.Assembled; if(oldState == assemblyState.Paused) { onMachineRestored(); } else { onMachineAssembled(); } } /** * Called when the machine needs to be disassembled. * It is not longer "whole" and should not be functional, usually * as a result of a block being removed. * Calls onMachineBroken on all attached parts. */ private void disassembleMachine() { TileEntity te; IChunkProvider chunkProvider = worldObj.getChunkProvider(); for(CoordTriplet coord : connectedBlocks) { if(!chunkProvider.chunkExists(coord.getChunkX(), coord.getChunkZ())) { // Chunk is already unloaded, don't fetch the TE. // This happens on SMP servers when players log out. continue; } te = this.worldObj.getBlockTileEntity(coord.x, coord.y, coord.z); if(te instanceof IMultiblockPart) { ((IMultiblockPart)te).onMachineBroken(); } } this.assemblyState = AssemblyState.Disassembled; onMachineDisassembled(); } /** * Assimilate another controller into this controller. * Acquire all of the other controller's blocks and attach them * to this one. * * @param other The controller to merge into this one. */ public void assimilate(MultiblockControllerBase other) { if(other.referenceCoord != null && this.referenceCoord.compareTo(other.referenceCoord) >= 0) { throw new IllegalArgumentException("The controller with the lowest minimum-coord value must consume the one with the higher coords"); } TileEntity te; Set<CoordTriplet> blocksToAcquire = new CopyOnWriteArraySet<CoordTriplet>(other.connectedBlocks); // releases all blocks and references gently so they can be incorporated into another multiblock other._onAssimilated(this); IMultiblockPart acquiredPart; for(CoordTriplet coord : blocksToAcquire) { // By definition, none of these can be the minimum block. te = this.worldObj.getBlockTileEntity(coord.x, coord.y, coord.z); if(te instanceof IMultiblockPart) { acquiredPart = (IMultiblockPart)te; this.connectedBlocks.add(coord); acquiredPart.onAssimilated(this); this.onBlockAdded(acquiredPart); } } this.onAssimilate(other); other.onAssimilated(this); } /** * Called when this machine is consumed by another controller. * Essentially, forcibly tear down this object. * @param otherController The controller consuming this controller. */ private void _onAssimilated(MultiblockControllerBase otherController) { if(referenceCoord != null) { if(worldObj.getChunkProvider().chunkExists(referenceCoord.getChunkX(), referenceCoord.getChunkZ())) { TileEntity te = this.worldObj.getBlockTileEntity(referenceCoord.x, referenceCoord.y, referenceCoord.z); if(te instanceof IMultiblockPart) { ((IMultiblockPart)te).forfeitMultiblockSaveDelegate(); } } this.referenceCoord = null; } this.connectedBlocks.clear(); } /** * Callback. Called after this controller assimilates all the blocks * from another controller. * Use this to absorb that controller's game data. * @param assimilated The controller whose uniqueness was added to our own. */ protected abstract void onAssimilate(MultiblockControllerBase assimilated); /** * Callback. Called after this controller is assimilated into another controller. * All blocks have been stripped out of this object and handed over to the * other controller. * This is intended primarily for cleanup. * @param assimilator The controller which has assimilated this controller. */ protected abstract void onAssimilated(MultiblockControllerBase assimilator); /** * Driver for the update loop. If the machine is assembled, runs * the game logic update method. * @see erogenousbeef.core.multiblock.MultiblockControllerBase#update() */ public final void updateMultiblockEntity() { if(connectedBlocks.isEmpty()) { // This shouldn't happen, but just in case... MultiblockRegistry.addDeadController(this.worldObj, this); return; } if(this.assemblyState != AssemblyState.Assembled) { // Not assembled - don't run game logic return; } if(worldObj.isRemote) { updateClient(); } else if(updateServer()) { // If this returns true, the server has changed its internal data. // If our chunks are loaded (they should be), we must mark our chunks as dirty. if(this.worldObj.checkChunksExist(minimumCoord.x, minimumCoord.y, minimumCoord.z, maximumCoord.x, maximumCoord.y, maximumCoord.z)) { int minChunkX = minimumCoord.x >> 4; int minChunkZ = minimumCoord.z >> 4; int maxChunkX = maximumCoord.x >> 4; int maxChunkZ = maximumCoord.z >> 4; for(int x = minChunkX; x <= maxChunkX; x++) { for(int z = minChunkZ; z <= maxChunkZ; z++) { // Ensure that we save our data, even if the our save delegate is in has no TEs. Chunk chunkToSave = this.worldObj.getChunkFromChunkCoords(x, z); chunkToSave.setChunkModified(); } } } } // Else: Server, but no need to save data. } /** * The server-side update loop! Use this similarly to a TileEntity's update loop. * You do not need to call your superclass' update() if you're directly * derived from MultiblockControllerBase. This is a callback. * Note that this will only be called when the machine is assembled. * @return True if the multiblock should save data, i.e. its internal game state has changed. False otherwise. */ protected abstract boolean updateServer(); /** * Client-side update loop. Generally, this shouldn't do anything, but if you want * to do some interpolation or something, do it here. */ protected abstract void updateClient(); // Validation helpers /** * The "frame" consists of the outer edges of the machine, plus the corners. * * @param world World object for the world in which this controller is located. * @param x X coordinate of the block being tested * @param y Y coordinate of the block being tested * @param z Z coordinate of the block being tested * @throws MultiblockValidationException if the tested block is not allowed on the machine's frame */ protected void isBlockGoodForFrame(World world, int x, int y, int z) throws MultiblockValidationException { throw new MultiblockValidationException(String.format("%d, %d, %d - Block is not valid for use in the machine's interior", x, y, z)); } /** * The top consists of the top face, minus the edges. * @param world World object for the world in which this controller is located. * @param x X coordinate of the block being tested * @param y Y coordinate of the block being tested * @param z Z coordinate of the block being tested * @throws MultiblockValidationException if the tested block is not allowed on the machine's top face */ protected void isBlockGoodForTop(World world, int x, int y, int z) throws MultiblockValidationException { throw new MultiblockValidationException(String.format("%d, %d, %d - Block is not valid for use in the machine's interior", x, y, z)); } /** * The bottom consists of the bottom face, minus the edges. * @param world World object for the world in which this controller is located. * @param x X coordinate of the block being tested * @param y Y coordinate of the block being tested * @param z Z coordinate of the block being tested * @throws MultiblockValidationException if the tested block is not allowed on the machine's bottom face */ protected void isBlockGoodForBottom(World world, int x, int y, int z) throws MultiblockValidationException { throw new MultiblockValidationException(String.format("%d, %d, %d - Block is not valid for use in the machine's interior", x, y, z)); } /** * The sides consists of the N/E/S/W-facing faces, minus the edges. * @param world World object for the world in which this controller is located. * @param x X coordinate of the block being tested * @param y Y coordinate of the block being tested * @param z Z coordinate of the block being tested * @throws MultiblockValidationException if the tested block is not allowed on the machine's side faces */ protected void isBlockGoodForSides(World world, int x, int y, int z) throws MultiblockValidationException { throw new MultiblockValidationException(String.format("%d, %d, %d - Block is not valid for use in the machine's interior", x, y, z)); } /** * The interior is any block that does not touch blocks outside the machine. * @param world World object for the world in which this controller is located. * @param x X coordinate of the block being tested * @param y Y coordinate of the block being tested * @param z Z coordinate of the block being tested * @throws MultiblockValidationException if the tested block is not allowed in the machine's interior */ protected void isBlockGoodForInterior(World world, int x, int y, int z) throws MultiblockValidationException { throw new MultiblockValidationException(String.format("%d, %d, %d - Block is not valid for use in the machine's interior", x, y, z)); } /** * @return The reference coordinate, the block with the lowest x, y, z coordinates, evaluated in that order. */ public CoordTriplet getReferenceCoord() { return referenceCoord; } /** * @return The number of blocks connected to this controller. */ public int getNumConnectedBlocks() { return connectedBlocks.size(); } public abstract void writeToNBT(NBTTagCompound data); public abstract void readFromNBT(NBTTagCompound data); /** * Force this multiblock to recalculate its minimum and maximum coordinates * from the list of connected parts. */ public void recalculateMinMaxCoords() { minimumCoord.x = minimumCoord.y = minimumCoord.z = Integer.MAX_VALUE; maximumCoord.x = maximumCoord.y = maximumCoord.z = Integer.MIN_VALUE; for(CoordTriplet coord : connectedBlocks) { if(coord.x < minimumCoord.x) { minimumCoord.x = coord.x; } if(coord.x > maximumCoord.x) { maximumCoord.x = coord.x; } if(coord.y < minimumCoord.y) { minimumCoord.y = coord.y; } if(coord.y > maximumCoord.y) { maximumCoord.y = coord.y; } if(coord.z < minimumCoord.z) { minimumCoord.z = coord.z; } if(coord.z > maximumCoord.z) { maximumCoord.z = coord.z; } } } /** * @return The minimum bounding-box coordinate containing this machine's blocks. */ public CoordTriplet getMinimumCoord() { return minimumCoord.copy(); } /** * @return The maximum bounding-box coordinate containing this machine's blocks. */ public CoordTriplet getMaximumCoord() { return maximumCoord.copy(); } /** * Called when the save delegate's tile entity is being asked for its description packet * @param tag A fresh compound tag to write your multiblock data into */ public abstract void formatDescriptionPacket(NBTTagCompound data); /** * Called when the save delegate's tile entity receiving a description packet * @param tag A compound tag containing multiblock data to import */ public abstract void decodeDescriptionPacket(NBTTagCompound data); /** * @return True if this controller has no associated blocks, false otherwise */ public boolean isEmpty() { return this.connectedBlocks.isEmpty(); } /** * Tests whether this multiblock should consume the other multiblock * and become the new multiblock master when the two multiblocks * are adjacent. Assumes both multiblocks are the same type. * @param otherController The other multiblock controller. * @return True if this multiblock should consume the other, false otherwise. */ public boolean shouldConsume(MultiblockControllerBase otherController) { if(!otherController.getClass().equals(getClass())) { throw new IllegalArgumentException("Attempting to merge two multiblocks with different master classes - this should never happen!"); } if(otherController == this) { return false; } // Don't be silly, don't eat yourself. CoordTriplet myCoord = getReferenceCoord(); CoordTriplet theirCoord = otherController.getReferenceCoord(); int res = myCoord.compareTo(theirCoord); if(res < 0) { return true; } else if(res > 0) { return false; } else { FMLLog.severe("My Controller (%d): size (%d), coords: %s", hashCode(), connectedBlocks.size(), java.util.Arrays.toString(connectedBlocks.toArray())); FMLLog.severe("Other Controller (%d): size (%d), coords: %s", otherController.hashCode(), otherController.connectedBlocks.size(), java.util.Arrays.toString(otherController.connectedBlocks.toArray())); throw new IllegalArgumentException("[" + (worldObj.isRemote?"CLIENT":"SERVER") + "] Two controllers with the same reference coord - this should never happen!"); } } /** * Called when this machine may need to check for blocks that are no * longer physically connected to the reference coordinate. * @return */ public Set<IMultiblockPart> checkForDisconnections() { if(!this.shouldCheckForDisconnections) { return null; } if(this.isEmpty()) { return null; } // We've run the checks from here on out. shouldCheckForDisconnections = false; TileEntity te; IChunkProvider chunkProvider = worldObj.getChunkProvider(); // Ensure that our current reference coord is valid. If not, invalidate it. if(referenceCoord != null) { if(!chunkProvider.chunkExists(referenceCoord.getChunkX(), referenceCoord.getChunkZ()) || worldObj.getBlockTileEntity(referenceCoord.x, referenceCoord.y, referenceCoord.z) == null) { referenceCoord = null; } } // Reset visitations and find the minimum coordinate Set<CoordTriplet> deadCoords = new HashSet<CoordTriplet>(); IMultiblockPart part = null; int originalSize = connectedBlocks.size(); for(CoordTriplet c: connectedBlocks) { // This happens during chunk unload. if(!chunkProvider.chunkExists(c.x >> 4, c.z >> 4)) { deadCoords.add(c); continue; } te = this.worldObj.getBlockTileEntity(c.x, c.y, c.z); if(!(te instanceof IMultiblockPart)) { // This happens during chunk unload. Consider it valid, move on. deadCoords.add(c); continue; } part = (IMultiblockPart)te; part.setUnvisited(); if(referenceCoord == null) { referenceCoord = c; } else if(c.compareTo(referenceCoord) < 0) { referenceCoord = c; } } connectedBlocks.removeAll(deadCoords); deadCoords.clear(); if(referenceCoord == null || isEmpty()) { // There are no valid parts remaining. The entire multiblock was unloaded during a chunk unload. Halt. return null; } IMultiblockPart referencePart = (IMultiblockPart)worldObj.getBlockTileEntity(referenceCoord.x, referenceCoord.y, referenceCoord.z); // Now visit all connected parts, breadth-first, starting from reference coord's part LinkedList<IMultiblockPart> partsToCheck = new LinkedList<IMultiblockPart>(); IMultiblockPart[] nearbyParts = null; partsToCheck.add(referencePart); int visitedParts = 0; while(!partsToCheck.isEmpty()) { part = partsToCheck.removeFirst(); part.setVisited(); visitedParts++; nearbyParts = part.getNeighboringParts(); // Chunk-safe on server, but not on client for(IMultiblockPart nearbyPart : nearbyParts) { // Ignore different machines if(nearbyPart.getMultiblockController() != this) { continue; } if(!nearbyPart.isVisited()) { nearbyPart.setVisited(); partsToCheck.add(nearbyPart); } } } // Finally, remove all parts that remain disconnected. Set<IMultiblockPart> removedParts = new HashSet<IMultiblockPart>(); IMultiblockPart orphanCandidate; for(CoordTriplet c : connectedBlocks) { te = worldObj.getBlockTileEntity(c.x, c.y, c.z); if(!(te instanceof IMultiblockPart)) { // Weird chunk problems? deadCoords.add(c); continue; } orphanCandidate = (IMultiblockPart)te; if (!orphanCandidate.isVisited()) { deadCoords.add(c); orphanCandidate.onOrphaned(this, originalSize, visitedParts); onDetachBlock(orphanCandidate); removedParts.add(orphanCandidate); } } // Trim any blocks that were invalid, or were removed. this.connectedBlocks.removeAll(deadCoords); // Cleanup. Not necessary, really. deadCoords.clear(); return removedParts; } /** * Detach all parts. Return a set of all parts which still * have a valid tile entity. Chunk-safe. * @return A set of all parts which still have a valid tile entity. */ public Set<IMultiblockPart> detachAllBlocks() { Set<IMultiblockPart> detachedParts = new HashSet<IMultiblockPart>(); if(worldObj == null) { return detachedParts; } IChunkProvider chunkProvider = worldObj.getChunkProvider(); TileEntity te; IMultiblockPart part; for(CoordTriplet c : connectedBlocks) { if(chunkProvider.chunkExists(c.getChunkX(), c.getChunkZ())) { te = worldObj.getBlockTileEntity(c.x, c.y, c.z); if(te instanceof IMultiblockPart) { part = (IMultiblockPart)te; onDetachBlock(part); detachedParts.add(part); } } } connectedBlocks.clear(); return detachedParts; } /** * Called from a part that wishes to store data from this controller when it gets orphaned. * Generally, this data will be read back in during onAddedPartWithMultiblockData(). * @param newOrphan The part being orphaned. * @param oldSize The size of the controller before detaching orphans. * @param newSize The size of the controller after detaching orphans. * @param dataContainer An NBT Compound Tag into which to write data. */ public abstract void getOrphanData(IMultiblockPart newOrphan, int oldSize, int newSize, NBTTagCompound dataContainer); /** * @return True if this multiblock machine is considered assembled and ready to go. */ public boolean isAssembled() { return this.assemblyState == AssemblyState.Assembled; } }
Likely fix for erogenousbeef/BigReactors#95 On very slow world loads, empty controllers can be spawned due to slow world ticks and processing of incoming blocks. We should be able to absorb empty controllers anyway, and a null check fixes this.
erogenousbeef/core/multiblock/MultiblockControllerBase.java
Likely fix for erogenousbeef/BigReactors#95
Java
mit
d5381238235c9d9b6ce87df0ad66a1319aefbb27
0
Slikey/EffectLib,HolagLP/EffectLib,stormtrooper28/EffectLib,HolagLP/EffectLib,Slikey/EffectLib,stormtrooper28/EffectLib
package de.slikey.effectlib; import org.apache.commons.lang.Validate; import org.bukkit.Location; import org.bukkit.entity.Entity; import org.bukkit.util.Vector; import java.lang.ref.WeakReference; public abstract class Effect implements Runnable { /** * Handles the type, the effect is played. * * @see {@link de.slikey.effectlib.EffectType} */ public EffectType type = EffectType.INSTANT; /** * Delay to wait for delayed effects. * * @see {@link de.slikey.effectlib.EffectType} */ public int delay = 0; /** * Interval to wait for repeating effects. * * @see {@link de.slikey.effectlib.EffectType} */ public int period = 1; /** * Amount of repititions to do. * Set this to -1 for an infinite effect * * @see {@link de.slikey.effectlib.EffectType} */ public int iterations = 0; /** * Callback to run, after effect is done. * * @see {@link java.lang.Runnable} */ public Runnable callback = null; /** * Display particles to players within this radius. Squared radius for * performance reasons. */ public float visibleRange = 32; /** * The interval at which we will update the cached Entity Location. * This value is specified in milliseconds. * * A value of 0 indicates no caching should be done- this may be * expensive. */ public int locationUpdateInterval = 100; /** * If true, and a "target" Location or Entity is set, the two Locations * will orient to face one another. */ public boolean autoOrient = true; private Location location = null; private WeakReference<Entity> entity = new WeakReference<Entity>(null); private Location target = null; private WeakReference<Entity> targetEntity = new WeakReference<Entity>(null); private long lastLocationUpdate = 0; private long lastTargetUpdate = 0; private boolean done = false; private final EffectManager effectManager; public Effect(EffectManager effectManager) { Validate.notNull(effectManager, "EffectManager cannot be null!"); this.effectManager = effectManager; } public final void cancel() { cancel(true); } public final void cancel(boolean callback) { if (callback) done(); else done = true; } private void done() { done = true; effectManager.done(this); } public final boolean isDone() { return done; } public abstract void onRun(); @Override public final void run() { if (!validate()) { cancel(); return; } if (done) return; onRun(); if (type == EffectType.REPEATING) { if (iterations == -1) return; iterations--; if (iterations < 1) done(); } else { done(); } } protected boolean validate() { // Check for a valid Location Location location = getLocation(); if (location == null) return false; if (autoOrient) { Location target = getTarget(); if (target != null) { Vector direction = target.toVector().subtract(location.toVector()); location.setDirection(direction); target.setDirection(direction.multiply(-1)); } } return true; } public final void start() { effectManager.start(this); } public final void infinite() { type = EffectType.REPEATING; iterations = -1; } /** * Extending Effect classes can use this to determine the Entity this * Effect is centered upon. * * This may return null, even for an Effect that was set with an Entity, * if the Entity gets GC'd. */ public Entity getEntity() { return this.entity.get(); } /** * Extending Effect classes can use this to determine the Entity this * Effect is targeted upon. This is probably a very rare case, such as * an Effect that "links" two Entities together somehow. (Idea!) * * This may return null, even for an Effect that was set with a target Entity, * if the Entity gets GC'd. */ public Entity getTargetEntity() { return this.targetEntity.get(); } /** * Extending Effect classes should use this method to obtain the * current "root" Location of the effect. * * This method will not return null when called from onRun. Effects * with invalid locations will be cancelled. */ public Location getLocation() { Entity entityReference = entity.get(); if (entityReference != null) { long now = System.currentTimeMillis(); if (locationUpdateInterval == 0 || lastLocationUpdate == 0 || lastLocationUpdate + locationUpdateInterval > now) { location = entityReference.getLocation(); } } return location; } /** * Extending Effect classes should use this method to obtain the * current "target" Location of the effect. * * Unlike getLocation, this may return null. */ public Location getTarget() { Entity entityReference = targetEntity.get(); if (entityReference != null) { long now = System.currentTimeMillis(); if (locationUpdateInterval == 0 || lastTargetUpdate == 0 || lastTargetUpdate + locationUpdateInterval > now) { target = entityReference.getLocation(); } } return target; } /** * Set the Entity this Effect is centered on. */ public void setEntity(Entity entity) { this.entity = new WeakReference<Entity>(entity); } /** * Set the Entity this Effect is targeting. */ public void setTargetEntity(Entity entity) { this.targetEntity = new WeakReference<Entity>(entity); } /** * Set the Location this Effect is centered on. */ public void setLocation(Location location) { this.location = location.clone(); } /** * Set the Location this Effect is targeting. */ public void setTarget(Location location) { this.target = location.clone(); } }
src/main/java/de/slikey/effectlib/Effect.java
package de.slikey.effectlib; import org.apache.commons.lang.Validate; import org.bukkit.Location; import org.bukkit.entity.Entity; import java.lang.ref.WeakReference; public abstract class Effect implements Runnable { /** * Handles the type, the effect is played. * * @see {@link de.slikey.effectlib.EffectType} */ public EffectType type = EffectType.INSTANT; /** * Delay to wait for delayed effects. * * @see {@link de.slikey.effectlib.EffectType} */ public int delay = 0; /** * Interval to wait for repeating effects. * * @see {@link de.slikey.effectlib.EffectType} */ public int period = 1; /** * Amount of repititions to do. * Set this to -1 for an infinite effect * * @see {@link de.slikey.effectlib.EffectType} */ public int iterations = 0; /** * Callback to run, after effect is done. * * @see {@link java.lang.Runnable} */ public Runnable callback = null; /** * Display particles to players within this radius. Squared radius for * performance reasons. */ public float visibleRange = 32; /** * The interval at which we will update the cached Entity Location. * This value is specified in milliseconds. * * A value of 0 indicates no caching should be done- this may be * expensive. */ public int locationUpdateInterval = 250; private Location location = null; private WeakReference<Entity> entity = new WeakReference<Entity>(null); private Location target = null; private WeakReference<Entity> targetEntity = new WeakReference<Entity>(null); private long lastLocationUpdate = 0; private long lastTargetUpdate = 0; private boolean done = false; private final EffectManager effectManager; public Effect(EffectManager effectManager) { Validate.notNull(effectManager, "EffectManager cannot be null!"); this.effectManager = effectManager; } public final void cancel() { cancel(true); } public final void cancel(boolean callback) { if (callback) done(); else done = true; } private void done() { done = true; effectManager.done(this); } public final boolean isDone() { return done; } public abstract void onRun(); @Override public final void run() { if (!isValid()) { cancel(); return; } if (done) return; onRun(); if (type == EffectType.REPEATING) { if (iterations == -1) return; iterations--; if (iterations < 1) done(); } else { done(); } } protected boolean isValid() { // Check for a valid Location return getLocation() != null; } public final void start() { effectManager.start(this); } public final void infinite() { type = EffectType.REPEATING; iterations = -1; } /** * Extending Effect classes can use this to determine the Entity this * Effect is centered upon. * * This may return null, even for an Effect that was set with an Entity, * if the Entity gets GC'd. */ public Entity getEntity() { return this.entity.get(); } /** * Extending Effect classes can use this to determine the Entity this * Effect is targeted upon. This is probably a very rare case, such as * an Effect that "links" two Entities together somehow. (Idea!) * * This may return null, even for an Effect that was set with a target Entity, * if the Entity gets GC'd. */ public Entity getTargetEntity() { return this.targetEntity.get(); } /** * Extending Effect classes should use this method to obtain the * current "root" Location of the effect. * * This method will not return null when called from onRun. Effects * with invalid locations will be cancelled. */ public Location getLocation() { Entity entityReference = entity.get(); if (entityReference != null) { long now = System.currentTimeMillis(); if (locationUpdateInterval == 0 || lastLocationUpdate == 0 || lastLocationUpdate + locationUpdateInterval > now) { location = entityReference.getLocation(); } } return location; } /** * Extending Effect classes should use this method to obtain the * current "target" Location of the effect. * * Unlike getLocation, this may return null. */ public Location getTarget() { Entity entityReference = targetEntity.get(); if (entityReference != null) { long now = System.currentTimeMillis(); if (locationUpdateInterval == 0 || lastTargetUpdate == 0 || lastTargetUpdate + locationUpdateInterval > now) { target = entityReference.getLocation(); } } return target; } /** * Set the Entity this Effect is centered on. */ public void setEntity(Entity entity) { this.entity = new WeakReference<Entity>(entity); } /** * Set the Entity this Effect is targeting. */ public void setTargetEntity(Entity entity) { this.targetEntity = new WeakReference<Entity>(entity); } /** * Set the Location this Effect is centered on. */ public void setLocation(Location location) { this.location = location.clone(); } /** * Set the Location this Effect is targeting. */ public void setTarget(Location location) { this.target = location.clone(); } }
Add autoOrient option
src/main/java/de/slikey/effectlib/Effect.java
Add autoOrient option
Java
epl-1.0
8ca188cc46bfa1839ceba5bbaf94e55e8494e17c
0
ibaton/3House,ibaton/3House,pravussum/3House
package treehou.se.habit.core; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import java.util.List; public class Util { public static Gson gson = null; public synchronized static Gson createGsonBuilder(){ if (gson == null) { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(new TypeToken<List<Widget>>() {}.getType(), new WidgetDeserializer()); gsonBuilder.registerTypeAdapter(new TypeToken<List<Sitemap>>() {}.getType(), new SitemapDeserializer()); gsonBuilder.registerTypeAdapter(new TypeToken<List<Widget.Mapping>>() {}.getType(), new WidgetMappingDeserializer()); gsonBuilder.registerTypeAdapter(Item.class, new ItemDeserializer()); gson = gsonBuilder.create(); } return gson; } }
mobile/src/main/java/treehou/se/habit/core/Util.java
package treehou.se.habit.core; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import java.util.List; /** * Created by ibaton on 2014-10-18. */ public class Util { public static Gson createGsonBuilder(){ GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(new TypeToken<List<Widget>>() {}.getType(), new WidgetDeserializer()); gsonBuilder.registerTypeAdapter(new TypeToken<List<Sitemap>>() {}.getType(), new SitemapDeserializer()); gsonBuilder.registerTypeAdapter(new TypeToken<List<Widget.Mapping>>() {}.getType(), new WidgetMappingDeserializer()); gsonBuilder.registerTypeAdapter(Item.class, new ItemDeserializer()); return gsonBuilder.create(); } }
Speedup to gson builder.
mobile/src/main/java/treehou/se/habit/core/Util.java
Speedup to gson builder.
Java
mpl-2.0
98333ff5b8816dcb6da7a6082c814c47dcfa813b
0
Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV
package org.helioviewer.gl3d.model.image; import java.util.List; import javax.media.opengl.GL; import org.helioviewer.base.physics.Constants; import org.helioviewer.gl3d.scenegraph.GL3DState; import org.helioviewer.gl3d.scenegraph.math.GL3DVec2d; import org.helioviewer.gl3d.scenegraph.math.GL3DVec3d; import org.helioviewer.gl3d.scenegraph.math.GL3DVec4d; import org.helioviewer.gl3d.view.GL3DImageTextureView; import org.helioviewer.viewmodel.metadata.MetaData; import org.helioviewer.viewmodel.view.opengl.shader.GLFragmentShaderProgram; import org.helioviewer.viewmodel.view.opengl.shader.GLVertexShaderProgram; /** * Maps the solar disc part of an image layer onto an adaptive mesh that either * covers the entire solar disc or the just the part that is visible in the view * frustum. * * @author Simon Spoerri (simon.spoerri@fhnw.ch) * */ public class GL3DImageSphere extends GL3DImageMesh { private final GL3DImageLayer layer; public GL3DImageSphere(GL3DImageTextureView imageTextureView, GLVertexShaderProgram vertexShaderProgram, GLFragmentShaderProgram fragmentShaderProgram, GL3DImageLayer imageLayer) { super("Sphere", imageTextureView, vertexShaderProgram, fragmentShaderProgram); layer = imageLayer; } @Override public void shapeDraw(GL3DState state) { state.gl.glEnable(GL.GL_CULL_FACE); state.gl.glEnable(GL.GL_DEPTH_TEST); state.gl.glEnable(GL.GL_BLEND); super.shapeDraw(state); } @Override public GL3DMeshPrimitive createMesh(GL3DState state, List<GL3DVec3d> positions, List<GL3DVec3d> normals, List<GL3DVec2d> textCoords, List<Integer> indices, List<GL3DVec4d> colors) { if (this.capturedRegion != null) { int resolutionX = 20; int resolutionY = 20; int numberOfPositions = 0; for (int latNumber = 0; latNumber <= resolutionX; latNumber++) { double theta = latNumber * Math.PI / resolutionX; double sinTheta = Math.sin(theta); double cosTheta = Math.cos(theta); for (int longNumber = 0; longNumber <= resolutionY; longNumber++) { double phi = longNumber * 2 * Math.PI / resolutionY; double sinPhi = Math.sin(phi); double cosPhi = Math.cos(phi); double x = cosPhi * sinTheta; double y = cosTheta; double z = sinPhi * sinTheta; positions.add(new GL3DVec3d(Constants.SunRadius * x, Constants.SunRadius * y, Constants.SunRadius * z)); numberOfPositions++; } } for (int latNumber = 0; latNumber < resolutionX; latNumber++) { for (int longNumber = 0; longNumber < resolutionY; longNumber++) { int first = (latNumber * (resolutionY + 1)) + longNumber; int second = first + resolutionY + 1; indices.add(first); indices.add(first + 1); indices.add(second + 1); indices.add(first); indices.add(second + 1); indices.add(second); } } MetaData metaData = this.layer.metaDataView.getMetaData(); int beginPositionNumberCorona = numberOfPositions; positions.add(new GL3DVec3d(-40., 40., 0.)); numberOfPositions++; positions.add(new GL3DVec3d(40., 40., 0.)); numberOfPositions++; positions.add(new GL3DVec3d(40., -40., 0.)); numberOfPositions++; positions.add(new GL3DVec3d(-40., -40., 0.)); numberOfPositions++; indices.add(beginPositionNumberCorona + 0); indices.add(beginPositionNumberCorona + 2); indices.add(beginPositionNumberCorona + 1); indices.add(beginPositionNumberCorona + 2); indices.add(beginPositionNumberCorona + 0); indices.add(beginPositionNumberCorona + 3); } return GL3DMeshPrimitive.TRIANGLES; } }
src/jhv-3d/src/org/helioviewer/gl3d/model/image/GL3DImageSphere.java
package org.helioviewer.gl3d.model.image; import java.util.List; import javax.media.opengl.GL; import org.helioviewer.base.math.Vector2dDouble; import org.helioviewer.base.physics.Constants; import org.helioviewer.gl3d.scenegraph.GL3DState; import org.helioviewer.gl3d.scenegraph.math.GL3DVec2d; import org.helioviewer.gl3d.scenegraph.math.GL3DVec3d; import org.helioviewer.gl3d.scenegraph.math.GL3DVec4d; import org.helioviewer.gl3d.view.GL3DImageTextureView; import org.helioviewer.viewmodel.metadata.MetaData; import org.helioviewer.viewmodel.view.opengl.shader.GLFragmentShaderProgram; import org.helioviewer.viewmodel.view.opengl.shader.GLVertexShaderProgram; /** * Maps the solar disc part of an image layer onto an adaptive mesh that either * covers the entire solar disc or the just the part that is visible in the view * frustum. * * @author Simon Spoerri (simon.spoerri@fhnw.ch) * */ public class GL3DImageSphere extends GL3DImageMesh { private final GL3DImageLayer layer; public GL3DImageSphere(GL3DImageTextureView imageTextureView, GLVertexShaderProgram vertexShaderProgram, GLFragmentShaderProgram fragmentShaderProgram, GL3DImageLayer imageLayer) { super("Sphere", imageTextureView, vertexShaderProgram, fragmentShaderProgram); layer = imageLayer; } @Override public void shapeDraw(GL3DState state) { state.gl.glEnable(GL.GL_CULL_FACE); state.gl.glEnable(GL.GL_DEPTH_TEST); state.gl.glEnable(GL.GL_BLEND); super.shapeDraw(state); } @Override public GL3DMeshPrimitive createMesh(GL3DState state, List<GL3DVec3d> positions, List<GL3DVec3d> normals, List<GL3DVec2d> textCoords, List<Integer> indices, List<GL3DVec4d> colors) { if (this.capturedRegion != null) { int resolutionX = 20; int resolutionY = 20; int numberOfPositions = 0; for (int latNumber = 0; latNumber <= resolutionX; latNumber++) { double theta = latNumber * Math.PI / resolutionX; double sinTheta = Math.sin(theta); double cosTheta = Math.cos(theta); for (int longNumber = 0; longNumber <= resolutionY; longNumber++) { double phi = longNumber * 2 * Math.PI / resolutionY; double sinPhi = Math.sin(phi); double cosPhi = Math.cos(phi); double x = cosPhi * sinTheta; double y = cosTheta; double z = sinPhi * sinTheta; positions.add(new GL3DVec3d(Constants.SunRadius * x, Constants.SunRadius * y, Constants.SunRadius * z)); numberOfPositions++; } } for (int latNumber = 0; latNumber < resolutionX; latNumber++) { for (int longNumber = 0; longNumber < resolutionY; longNumber++) { int first = (latNumber * (resolutionY + 1)) + longNumber; int second = first + resolutionY + 1; indices.add(first); indices.add(first + 1); indices.add(second + 1); indices.add(first); indices.add(second + 1); indices.add(second); } } MetaData metaData = this.layer.metaDataView.getMetaData(); Vector2dDouble ul = metaData.getPhysicalUpperLeft(); Vector2dDouble ur = metaData.getPhysicalUpperRight(); Vector2dDouble lr = metaData.getPhysicalLowerRight(); Vector2dDouble ll = metaData.getPhysicalLowerLeft(); int beginPositionNumberCorona = numberOfPositions; positions.add(new GL3DVec3d(-40., 40., 0.)); numberOfPositions++; positions.add(new GL3DVec3d(40., 40., 0.)); numberOfPositions++; positions.add(new GL3DVec3d(40., -40., 0.)); numberOfPositions++; positions.add(new GL3DVec3d(-40., -40., 0.)); numberOfPositions++; indices.add(beginPositionNumberCorona + 0); indices.add(beginPositionNumberCorona + 2); indices.add(beginPositionNumberCorona + 1); indices.add(beginPositionNumberCorona + 2); indices.add(beginPositionNumberCorona + 0); indices.add(beginPositionNumberCorona + 3); } return GL3DMeshPrimitive.TRIANGLES; } }
Remove unused vars git-svn-id: 4e353c0944fe8da334633afc35765ef362dec675@1382 b4e469a2-07ce-4b26-9273-4d7d95a670c7
src/jhv-3d/src/org/helioviewer/gl3d/model/image/GL3DImageSphere.java
Remove unused vars
Java
agpl-3.0
f7c7d9ff0747142daa1524b725519932972e1f91
0
m-sc/yamcs,yamcs/yamcs,m-sc/yamcs,fqqb/yamcs,yamcs/yamcs,yamcs/yamcs,fqqb/yamcs,m-sc/yamcs,yamcs/yamcs,yamcs/yamcs,fqqb/yamcs,fqqb/yamcs,m-sc/yamcs,fqqb/yamcs,m-sc/yamcs,m-sc/yamcs,fqqb/yamcs,yamcs/yamcs
package org.yamcs.cfdp.pdu; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Map; import com.google.common.collect.Maps; public class AckPacket extends CfdpPacket { private FileDirectiveCode directiveCode; private FileDirectiveSubtypeCode directiveSubtypeCode; private ConditionCode conditionCode; private TransactionStatus transactionStatus; public enum TransactionStatus { Undefined((byte) 0x00), Active((byte) 0x01), Terminated((byte) 0x02), Unrecognized((byte) 0x03); private byte status; public static final Map<Byte, TransactionStatus> Lookup = Maps.uniqueIndex( Arrays.asList(TransactionStatus.values()), TransactionStatus::getStatus); private TransactionStatus(byte status) { this.status = status; } public byte getStatus() { return status; } private static TransactionStatus fromStatus(byte status) { return Lookup.get(status); } public static TransactionStatus readTransactionStatus(byte b) { return TransactionStatus.fromStatus((byte) (b & 0x03)); } } public enum FileDirectiveSubtypeCode { FinishedByWaypoint((byte) 0x00), FinishedByEndSystem((byte) 0x01), Other((byte) 0x00); private byte code; public static final Map<Byte, FileDirectiveSubtypeCode> Lookup = Maps.uniqueIndex( Arrays.asList(FileDirectiveSubtypeCode.values()), FileDirectiveSubtypeCode::getCode); private FileDirectiveSubtypeCode(byte code) { this.code = code; } public byte getCode() { return code; } private static FileDirectiveSubtypeCode fromCode(byte code) { return Lookup.get(code); } public static FileDirectiveSubtypeCode readSubtypeCode(byte b) { return FileDirectiveSubtypeCode.fromCode((byte) (b & 0x0f)); } } public AckPacket(FileDirectiveCode code, FileDirectiveSubtypeCode subcode, ConditionCode conditionCode, TransactionStatus status, CfdpHeader header) { super(header); this.directiveCode = code; this.directiveSubtypeCode = subcode; this.conditionCode = conditionCode; this.transactionStatus = status; finishConstruction(); } public AckPacket(ByteBuffer buffer, CfdpHeader header) { super(buffer, header); byte temp = buffer.get(); this.directiveCode = FileDirectiveCode.readFileDirectiveCode(temp); this.directiveSubtypeCode = FileDirectiveSubtypeCode.readSubtypeCode(temp); this.conditionCode = ConditionCode.readConditionCode(buffer.get()); } @Override protected void writeCFDPPacket(ByteBuffer buffer) { buffer.put((byte) (this.directiveCode.getCode() << 4 | this.directiveSubtypeCode.getCode())); buffer.put((byte) (this.conditionCode.getCode() << 4 | this.transactionStatus.getStatus())); } @Override protected int calculateDataFieldLength() { return 3; } }
yamcs-core/src/main/java/org/yamcs/cfdp/pdu/AckPacket.java
package org.yamcs.cfdp.pdu; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Map; import com.google.common.collect.Maps; public class AckPacket extends CfdpPacket { private FileDirectiveCode directiveCode; private FileDirectiveSubtypeCode directiveSubtypeCode; private ConditionCode conditionCode; private TransactionStatus transactionStatus; public enum TransactionStatus { Undefined((byte) 0x00), Active((byte) 0x01), Terminated((byte) 0x02), Unrecognized((byte) 0x03); private byte status; public static final Map<Byte, TransactionStatus> Lookup = Maps.uniqueIndex( Arrays.asList(TransactionStatus.values()), TransactionStatus::getStatus); private TransactionStatus(byte status) { this.status = status; } public byte getStatus() { return status; } private static TransactionStatus fromStatus(byte status) { return Lookup.get(status); } public static TransactionStatus readTransactionStatus(byte b) { return TransactionStatus.fromStatus((byte) (b & 0x03)); } } public enum FileDirectiveSubtypeCode { FinishedByWaypoint((byte) 0x00), FinishedByEndSystem((byte) 0x01), Other((byte) 0x00); private byte code; public static final Map<Byte, FileDirectiveSubtypeCode> Lookup = Maps.uniqueIndex( Arrays.asList(FileDirectiveSubtypeCode.values()), FileDirectiveSubtypeCode::getCode); private FileDirectiveSubtypeCode(byte code) { this.code = code; } public byte getCode() { return code; } private static FileDirectiveSubtypeCode fromCode(byte code) { return Lookup.get(code); } public static FileDirectiveSubtypeCode readSubtypeCode(byte b) { return FileDirectiveSubtypeCode.fromCode((byte) (b & 0x0f)); } } public AckPacket(ByteBuffer buffer, CfdpHeader header) { super(buffer, header); byte temp = buffer.get(); this.directiveCode = FileDirectiveCode.readFileDirectiveCode(temp); this.directiveSubtypeCode = FileDirectiveSubtypeCode.readSubtypeCode(temp); this.conditionCode = ConditionCode.readConditionCode(buffer.get()); } @Override protected void writeCFDPPacket(ByteBuffer buffer) { buffer.put((byte) (this.directiveCode.getCode() << 4 | this.directiveSubtypeCode.getCode())); buffer.put((byte) (this.conditionCode.getCode() << 4 | this.transactionStatus.getStatus())); } @Override protected CfdpHeader createHeader() { // TODO Auto-generated method stub return null; } }
further implemented AckPacket
yamcs-core/src/main/java/org/yamcs/cfdp/pdu/AckPacket.java
further implemented AckPacket
Java
agpl-3.0
1bbd85b06a16c940176564306789b3cbbf2f9897
0
aihua/opennms,aihua/opennms,aihua/opennms,aihua/opennms,aihua/opennms,aihua/opennms,aihua/opennms,aihua/opennms,aihua/opennms
/******************************************************************************* * This file is part of OpenNMS(R). Copyright (C) 2014 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc. OpenNMS(R) is * a registered trademark of The OpenNMS Group, Inc. OpenNMS(R) is free * software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. OpenNMS(R) 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 Affero General Public * License for more details. You should have received a copy of the GNU Affero * General Public License along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ For more information contact: OpenNMS(R) * Licensing <license@opennms.org> http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.enlinkd; import static org.opennms.core.utils.InetAddressUtils.str; import static org.opennms.core.utils.InetAddressUtils.isValidBridgeAddress; import static org.opennms.core.utils.InetAddressUtils.isValidStpBridgeId; import static org.opennms.core.utils.InetAddressUtils.getBridgeAddressFromStpBridgeId; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.opennms.netmgt.enlinkd.snmp.CiscoVtpTracker; import org.opennms.netmgt.enlinkd.snmp.CiscoVtpVlanTableTracker; import org.opennms.netmgt.enlinkd.snmp.Dot1dBasePortTableTracker; import org.opennms.netmgt.enlinkd.snmp.Dot1dBaseTracker; import org.opennms.netmgt.enlinkd.snmp.Dot1dStpPortTableTracker; import org.opennms.netmgt.enlinkd.snmp.Dot1dTpFdbTableTracker; import org.opennms.netmgt.enlinkd.snmp.Dot1qTpFdbTableTracker; import org.opennms.netmgt.model.BridgeElement; import org.opennms.netmgt.model.BridgeElement.BridgeDot1dBaseType; import org.opennms.netmgt.model.BridgeMacLink; import org.opennms.netmgt.model.BridgeMacLink.BridgeDot1qTpFdbStatus; import org.opennms.netmgt.model.BridgeStpLink; import org.opennms.netmgt.snmp.SnmpAgentConfig; import org.opennms.netmgt.snmp.SnmpUtils; import org.opennms.netmgt.snmp.SnmpWalker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class is designed to collect the necessary SNMP information from the * target address and store the collected information. When the class is * initially constructed no information is collected. The SNMP Session * creating and collection occurs in the main run method of the instance. This * allows the collection to occur in a thread if necessary. */ public final class NodeDiscoveryBridge extends NodeDiscovery { private static final Logger LOG = LoggerFactory.getLogger(NodeDiscoveryBridge.class); // public final static String CISCO_ENTERPRISE_OID = ".1.3.6.1.4.1.9"; /** * Constructs a new SNMP collector for Bridge Node Discovery. The * collection does not occur until the <code>run</code> method is invoked. * * @param EnhancedLinkd * linkd * @param LinkableNode * node */ public NodeDiscoveryBridge(final EnhancedLinkd linkd, final Node node) { super(linkd, node); } protected void runCollection() { LOG.info("run: start: node discovery operations for bridge: '{}'",getNodeId()); final Date now = new Date(); Map<Integer,String> vlanmap = getVtpVlanMap(getPeer()); List<BridgeMacLink> bft = new ArrayList<BridgeMacLink>(); String community = getPeer().getReadCommunity(); Map<Integer,Integer> bridgeifindex = new HashMap<Integer, Integer>(); for (Entry<Integer, String> entry : vlanmap.entrySet()) { LOG.debug("run: cisco vlan collection setting peer community: {} with VLAN {}", community, entry.getKey()); SnmpAgentConfig peer = getPeer(); if (entry.getKey() != null) peer.setReadCommunity(community + "@" + entry.getKey()); LOG.debug("run: Bridge Linkd node scan : ready to walk dot1d basedata on {}, vlan {}, vlanname {}.", getNodeId(), entry.getKey(), entry.getValue()); BridgeElement bridge = getDot1dBridgeBase(peer); if (bridge != null) { bridge.setVlan(entry.getKey()); bridge.setVlanname(entry.getValue()); m_linkd.getQueryManager().store(getNodeId(), bridge); } else { LOG.debug("run: Bridge Linkd node scan : no dot1d data found on {}, vlan {}, vlanname {}. skipping other operations", getNodeId(), entry.getKey(), entry.getValue()); continue; } Map<Integer,Integer> vlanbridgetoifindex = walkDot1dBasePortTable(peer); LOG.debug("run: found on node: '{}' vlan: '{}', bridge ifindex map {}", getNodeId(), entry.getValue(), vlanbridgetoifindex); if (!isValidStpBridgeId(bridge.getStpDesignatedRoot())) { LOG.info("run: invalid Stp designated root: spanning tree not supported on: {}", getNodeId()); } else if (bridge.getBaseBridgeAddress().equals(getBridgeAddressFromStpBridgeId(bridge.getStpDesignatedRoot()))) { LOG.info("run: designated root of spanning tree is itself on bridge {}, on: {}", bridge.getStpDesignatedRoot(), getNodeId()); } else { for (BridgeStpLink stplink: walkSpanningTree(peer, bridge.getBaseBridgeAddress())) { stplink.setVlan(entry.getKey()); stplink.setStpPortIfIndex(vlanbridgetoifindex.get(stplink.getStpPort())); m_linkd.getQueryManager().store(getNodeId(), stplink); } } bridgeifindex.putAll(vlanbridgetoifindex); bft = walkDot1dTpFdp(entry.getKey(), bridgeifindex, bft, peer); } LOG.debug("run: found on node: '{}' bridge ifindex map {}", getNodeId(), bridgeifindex); bft = walkDot1qTpFdb(getPeer(),bridgeifindex, bft); m_linkd.getQueryManager().store(getNodeId(), bft); LOG.debug("run: reconciling bridge: '{}' time {}", getNodeId(), now); m_linkd.getQueryManager().reconcileBridge(getNodeId(), now); LOG.debug("run: updating topology bridge: '{}'", getNodeId()); LOG.info("run: end: node discovery operations for bridge: '{}'", getNodeId()); } private BridgeElement getDot1dBridgeBase(SnmpAgentConfig peer) { String trackerName = "dot1dbase"; final Dot1dBaseTracker dot1dbase = new Dot1dBaseTracker(); SnmpWalker walker = SnmpUtils.createWalker(peer, trackerName, dot1dbase); walker.start(); try { walker.waitFor(); if (walker.timedOut()) { LOG.info("run:Aborting Bridge Linkd node scan : Agent timed out while scanning the {} table", trackerName); return null; } else if (walker.failed()) { LOG.info("run:Aborting Bridge Linkd node scan : Agent failed while scanning the {} table: {}", trackerName, walker.getErrorMessage()); return null; } } catch (final InterruptedException e) { LOG.error("run: Bridge Linkd node collection interrupted, exiting", e); return null; } BridgeElement bridge = dot1dbase.getBridgeElement(); if (bridge.getBaseBridgeAddress() == null) { LOG.info("run: base bridge address is null: bridge mib not supported on: {}", getNodeId()); return null; } if (!isValidBridgeAddress(bridge.getBaseBridgeAddress())) { LOG.info("run: bridge not supported, base address identifier {} is not valid on: {}", dot1dbase.getBridgeAddress(), getNodeId()); return null; } if (bridge.getBaseNumPorts() == null || bridge.getBaseNumPorts().intValue() == 0) { LOG.info("run: bridge {} has 0 port active, on: {}", dot1dbase.getBridgeAddress(), getNodeId()); return null; } LOG.info("run: bridge {} has is if type {}, on: {}", dot1dbase.getBridgeAddress(), BridgeDot1dBaseType.getTypeString(dot1dbase.getBridgeType()), getNodeId()); if (bridge.getBaseType() == BridgeDot1dBaseType.DOT1DBASETYPE_SOURCEROUTE_ONLY) { LOG.info("run: {}: source route only type bridge, on: {}", dot1dbase.getBridgeAddress(), getNodeId()); return null; } return bridge; } private Map<Integer, String> getVtpVlanMap(SnmpAgentConfig peer) { final Map<Integer, String> vlanmap = new HashMap<Integer, String>(); String trackerName = "vtpVersion"; final CiscoVtpTracker vtpStatus = new CiscoVtpTracker(); SnmpWalker walker = SnmpUtils.createWalker(peer, trackerName, vtpStatus); walker.start(); try { walker.waitFor(); if (walker.timedOut()) { LOG.info("run:Aborting Bridge Linkd node scan : Agent timed out while scanning the {} table", trackerName); return vlanmap; } else if (walker.failed()) { LOG.info("run:Aborting Bridge Linkd node scan : Agent failed while scanning the {} table: {}", trackerName, walker.getErrorMessage()); return vlanmap; } } catch (final InterruptedException e) { LOG.error("run: Bridge Linkd node collection interrupted, exiting", e); return vlanmap; } if (vtpStatus.getVtpVersion() == null) { LOG.info("run: cisco vtp mib not supported, on: {}", getNodeId()); return vlanmap; } LOG.info("run: cisco vtp mib supported, on: {}", getNodeId()); LOG.info("run: walking cisco vtp, on: {}", getNodeId()); trackerName = "ciscoVtpVlan"; final CiscoVtpVlanTableTracker ciscoVtpVlanTableTracker = new CiscoVtpVlanTableTracker() { @Override public void processCiscoVtpVlanRow(final CiscoVtpVlanRow row) { if (row.isTypeEthernet() && row.isStatusOperational()) { vlanmap.put(row.getVlanIndex(), row.getVlanName()); } } }; walker = SnmpUtils.createWalker(peer, trackerName, ciscoVtpVlanTableTracker); walker.start(); try { walker.waitFor(); if (walker.timedOut()) { LOG.info("run:Aborting Bridge Linkd node scan : Agent timed out while scanning the {} table", trackerName); } else if (walker.failed()) { LOG.info("run:Aborting Bridge Linkd node scan : Agent failed while scanning the {} table: {}", trackerName, walker.getErrorMessage()); } } catch (final InterruptedException e) { LOG.error("run: Bridge Linkd node collection interrupted, exiting", e); } if (vlanmap.isEmpty()) { vlanmap.put(null, null); } return vlanmap; } private Map<Integer, Integer> walkDot1dBasePortTable(SnmpAgentConfig peer) { final Map<Integer, Integer> bridgetoifindex = new HashMap<Integer, Integer>(); String trackerName = "dot1dBasePortTable"; Dot1dBasePortTableTracker dot1dBasePortTableTracker = new Dot1dBasePortTableTracker() { @Override public void processDot1dBasePortRow(final Dot1dBasePortRow row) { bridgetoifindex.put(row.getBaseBridgePort(), row.getBaseBridgePortIfindex()); } }; SnmpWalker walker = SnmpUtils.createWalker(peer, trackerName, dot1dBasePortTableTracker); walker.start(); try { walker.waitFor(); if (walker.timedOut()) { LOG.info("run:Aborting Bridge Linkd node scan : Agent timed out while scanning the {} table", trackerName); } else if (walker.failed()) { LOG.info("run:Aborting Bridge Linkd node scan : Agent failed while scanning the {} table: {}", trackerName, walker.getErrorMessage()); } } catch (final InterruptedException e) { LOG.error("run: Bridge Linkd node collection interrupted, exiting", e); } return bridgetoifindex; } private List<BridgeMacLink> walkDot1dTpFdp(final Integer vlan, final Map<Integer, Integer> bridgeifindex, List<BridgeMacLink> bft, SnmpAgentConfig peer) { String trackerName = "dot1dTbFdbPortTable"; Dot1dTpFdbTableTracker stpPortTableTracker = new Dot1dTpFdbTableTracker() { @Override public void processDot1dTpFdbRow(final Dot1dTpFdbRow row) { BridgeMacLink link = row.getLink(); if (link.getBridgeDot1qTpFdbStatus() == null) { LOG.warn("processDot1dTpFdbRow: row has null status. mac {}: vlan {}: on port {}", row.getDot1dTpFdbAddress(), vlan, row.getDot1dTpFdbPort()); return; } if (link.getBridgePort() == null) { LOG.warn("processDot1dTpFdbRow: row has null bridge port. mac {}: vlan {}: on port {} status {}", row.getDot1dTpFdbAddress(), vlan, row.getDot1dTpFdbPort(), link.getBridgeDot1qTpFdbStatus()); return; } if (link.getMacAddress() == null || !isValidBridgeAddress(link.getMacAddress())) { LOG.warn("processDot1dTpFdbRow: row has invalid mac. mac {}: vlan {}: on port {} ifindex {} status {}", row.getDot1dTpFdbAddress(), vlan, row.getDot1dTpFdbPort(), link.getBridgePortIfIndex(), link.getBridgeDot1qTpFdbStatus()); return; } link.setVlan(vlan); if (!bridgeifindex.containsKey(link.getBridgePort()) && link.getBridgeDot1qTpFdbStatus() != BridgeDot1qTpFdbStatus.DOT1D_TP_FDB_STATUS_SELF) { LOG.warn("processDot1dTpFdbRow: row has invalid bridge port no ifindex found. mac {}: vlan {}: on port {} ifindex {} status {}", row.getDot1dTpFdbAddress(), vlan, row.getDot1dTpFdbPort(), link.getBridgePortIfIndex(), link.getBridgeDot1qTpFdbStatus()); return; } link.setBridgePortIfIndex(bridgeifindex.get(link.getBridgePort())); LOG.info("processDot1dTpFdbRow: row processed: mac {}: vlan {}: on port {} ifindex {} status {}", link.getMacAddress(), link.getVlan(), link.getBridgePort(), link.getBridgePortIfIndex(), link.getBridgeDot1qTpFdbStatus()); bft.add(link); } }; SnmpWalker walker = SnmpUtils.createWalker(peer, trackerName, stpPortTableTracker); walker.start(); try { walker.waitFor(); if (walker.timedOut()) { LOG.info("run:Aborting Bridge Linkd node scan : Agent timed out while scanning the {} table", trackerName); return bft; } else if (walker.failed()) { LOG.info("run:Aborting Bridge Linkd node scan : Agent failed while scanning the {} table: {}", trackerName, walker.getErrorMessage()); return bft; } } catch (final InterruptedException e) { LOG.error("run: Bridge Linkd node collection interrupted, exiting", e); return bft; } return bft; } private List<BridgeMacLink> walkDot1qTpFdb(SnmpAgentConfig peer, final Map<Integer, Integer> bridgeifindex, final List<BridgeMacLink> bft) { String trackerName = "dot1qTbFdbPortTable"; Dot1qTpFdbTableTracker dot1qTpFdbTableTracker = new Dot1qTpFdbTableTracker() { @Override public void processDot1qTpFdbRow(final Dot1qTpFdbRow row) { BridgeMacLink link = row.getLink(); if (link.getBridgeDot1qTpFdbStatus() == null) { LOG.warn("processDot1qTpFdbRow: row has null status. mac {}: on port {}", row.getDot1qTpFdbAddress(), row.getDot1qTpFdbPort()); return; } if (link.getBridgePort() == null) { LOG.warn("processDot1qTpFdbRow: row has null bridge port. mac {}: on port {} status {}", row.getDot1qTpFdbAddress(), row.getDot1qTpFdbPort(), link.getBridgeDot1qTpFdbStatus()); return; } if (link.getMacAddress() == null || !isValidBridgeAddress(link.getMacAddress())) { LOG.warn("processDot1qTpFdbRow: row has invalid mac. mac {}: on port {} ifindex {} status {}", row.getDot1qTpFdbAddress(), row.getDot1qTpFdbPort(), link.getBridgePortIfIndex(), link.getBridgeDot1qTpFdbStatus()); return; } if (!bridgeifindex.containsKey(link.getBridgePort()) && link.getBridgeDot1qTpFdbStatus() != BridgeDot1qTpFdbStatus.DOT1D_TP_FDB_STATUS_SELF) { LOG.warn("processDot1qTpFdbRow: row has invalid bridgeport no ifindex found. mac {}: on port {} ifindex {} status {}", row.getDot1qTpFdbAddress(), row.getDot1qTpFdbPort(), link.getBridgePortIfIndex(), link.getBridgeDot1qTpFdbStatus()); return; } link.setBridgePortIfIndex(bridgeifindex.get(link.getBridgePort())); LOG.info("processDot1qTpFdbRow: row processed: mac {}: vlan {}: on port {} ifindex {} status {}", link.getMacAddress(), link.getVlan(), link.getBridgePort(), link.getBridgePortIfIndex(), link.getBridgeDot1qTpFdbStatus()); bft.add(link); } }; SnmpWalker walker = SnmpUtils.createWalker(peer, trackerName, dot1qTpFdbTableTracker); walker.start(); try { walker.waitFor(); if (walker.timedOut()) { LOG.info("run:Aborting Bridge Linkd node scan : Agent timed out while scanning the {} table", trackerName); } else if (walker.failed()) { LOG.info("run:Aborting Bridge Linkd node scan : Agent failed while scanning the {} table: {}", trackerName, walker.getErrorMessage()); } } catch (final InterruptedException e) { LOG.error("run: Bridge Linkd node collection interrupted, exiting", e); return bft; } return bft; } private List<BridgeStpLink> walkSpanningTree(SnmpAgentConfig peer, final String baseBridgeAddress) { String trackerName = "dot1dStpPortTable"; final List<BridgeStpLink> stplinks = new ArrayList<BridgeStpLink>(); Dot1dStpPortTableTracker stpPortTableTracker = new Dot1dStpPortTableTracker() { @Override public void processDot1dStpPortRow(final Dot1dStpPortRow row) { BridgeStpLink link = row.getLink(); if (isValidStpBridgeId(link.getDesignatedRoot()) && isValidStpBridgeId(link.getDesignatedBridge()) && !baseBridgeAddress.equals(link.getDesignatedBridgeAddress())) { stplinks.add(link); } } }; SnmpWalker walker = SnmpUtils.createWalker(peer, trackerName, stpPortTableTracker); walker.start(); try { walker.waitFor(); if (walker.timedOut()) { LOG.info("run:Aborting Bridge Linkd node scan : Agent timed out while scanning the {} table", trackerName); } else if (walker.failed()) { LOG.info("run:Aborting Bridge Linkd node scan : Agent failed while scanning the {} table: {}", trackerName, walker.getErrorMessage()); } } catch (final InterruptedException e) { LOG.error("run: Bridge Linkd node collection interrupted, exiting", e); } return stplinks; } @Override public String getInfo() { return "ReadyRunnable BridgeLinkNodeDiscovery" + " ip=" + str(getTarget()) + " port=" + getPort() + " community=" + getReadCommunity() + " package=" + getPackageName(); } @Override public String getName() { return "BridgeLinkDiscovery"; } }
opennms-services/src/main/java/org/opennms/netmgt/enlinkd/NodeDiscoveryBridge.java
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2014 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.enlinkd; import static org.opennms.core.utils.InetAddressUtils.str; import static org.opennms.core.utils.InetAddressUtils.isValidBridgeAddress; import static org.opennms.core.utils.InetAddressUtils.isValidStpBridgeId; import static org.opennms.core.utils.InetAddressUtils.getBridgeAddressFromStpBridgeId; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.opennms.netmgt.enlinkd.snmp.CiscoVtpTracker; import org.opennms.netmgt.enlinkd.snmp.CiscoVtpVlanTableTracker; import org.opennms.netmgt.enlinkd.snmp.Dot1dBasePortTableTracker; import org.opennms.netmgt.enlinkd.snmp.Dot1dBaseTracker; import org.opennms.netmgt.enlinkd.snmp.Dot1dStpPortTableTracker; import org.opennms.netmgt.enlinkd.snmp.Dot1dTpFdbTableTracker; import org.opennms.netmgt.enlinkd.snmp.Dot1qTpFdbTableTracker; import org.opennms.netmgt.model.BridgeElement; import org.opennms.netmgt.model.BridgeElement.BridgeDot1dBaseType; import org.opennms.netmgt.model.BridgeMacLink; import org.opennms.netmgt.model.BridgeMacLink.BridgeDot1qTpFdbStatus; import org.opennms.netmgt.model.BridgeStpLink; import org.opennms.netmgt.snmp.SnmpAgentConfig; import org.opennms.netmgt.snmp.SnmpUtils; import org.opennms.netmgt.snmp.SnmpWalker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class is designed to collect the necessary SNMP information from the * target address and store the collected information. When the class is * initially constructed no information is collected. The SNMP Session creating * and collection occurs in the main run method of the instance. This allows the * collection to occur in a thread if necessary. */ public final class NodeDiscoveryBridge extends NodeDiscovery { private static final Logger LOG = LoggerFactory.getLogger(NodeDiscoveryBridge.class); //public final static String CISCO_ENTERPRISE_OID = ".1.3.6.1.4.1.9"; /** * Constructs a new SNMP collector for Bridge Node Discovery. The collection * does not occur until the <code>run</code> method is invoked. * * @param EnhancedLinkd * linkd * @param LinkableNode * node */ public NodeDiscoveryBridge(final EnhancedLinkd linkd, final Node node) { super(linkd, node); } protected void runCollection() { LOG.info("run: start: node discovery operations for bridge: '{}'",getNodeId()); final Date now = new Date(); LOG.debug("run: collecting: {}", getPeer()); Map<Integer,String> vlanmap = getVtpVlanMap(); Map<Integer,Integer> bridgeifindex = new HashMap<Integer, Integer>(); List<BridgeMacLink> bft = new ArrayList<BridgeMacLink>(); if (vlanmap.isEmpty()) { bridgeifindex.putAll(walkDot1d(null,null)); bft = walkDot1dTpFdp(null,bridgeifindex,bft,getPeer()); } else { String community = getPeer().getReadCommunity(); for (Entry<Integer, String> entry: vlanmap.entrySet()) { LOG.debug("run: cisco vlan collection setting peer community: {} with VLAN {}", community, entry.getKey()); SnmpAgentConfig peer = getPeer(); peer.setReadCommunity(community + "@" + entry.getKey()); bridgeifindex.putAll(walkDot1d(entry.getKey(), entry.getValue())); bft = walkDot1dTpFdp(entry.getKey(),bridgeifindex,bft,peer); } } LOG.debug("run: found on node: '{}' bridge ifindex map {}",getNodeId(), bridgeifindex); bft = walkDot1qTpFdb(bridgeifindex,bft); m_linkd.getQueryManager().store(getNodeId(), bft); LOG.debug("run: reconciling bridge: '{}' time {}",getNodeId(), now); m_linkd.getQueryManager().reconcileBridge(getNodeId(), now); LOG.debug("run: updating topology bridge: '{}'",getNodeId()); LOG.info("run: end: node discovery operations for bridge: '{}'",getNodeId()); } private Map<Integer,String> getVtpVlanMap() { final Map<Integer,String> vlanmap = new HashMap<Integer, String>(); String trackerName = "vtpVersion"; final CiscoVtpTracker vtpStatus = new CiscoVtpTracker(); SnmpWalker walker = SnmpUtils.createWalker(getPeer(), trackerName, vtpStatus); walker.start(); try { walker.waitFor(); if (walker.timedOut()) { LOG.info("run:Aborting Bridge Linkd node scan : Agent timed out while scanning the {} table", trackerName); return vlanmap; } else if (walker.failed()) { LOG.info("run:Aborting Bridge Linkd node scan : Agent failed while scanning the {} table: {}", trackerName, walker.getErrorMessage()); return vlanmap; } } catch (final InterruptedException e) { LOG.error("run: Bridge Linkd node collection interrupted, exiting", e); return vlanmap; } if (vtpStatus.getVtpVersion() == null) { LOG.info("run: cisco vtp mib not supported, on: {}", getNodeId()); return vlanmap; } LOG.info("run: cisco vtp mib supported, on: {}", getNodeId()); LOG.info("run: walking cisco vtp, on: {}", getNodeId()); trackerName = "ciscoVtpVlan"; final CiscoVtpVlanTableTracker ciscoVtpVlanTableTracker = new CiscoVtpVlanTableTracker() { @Override public void processCiscoVtpVlanRow(final CiscoVtpVlanRow row) { if (row.isTypeEthernet() && row.isStatusOperational()) { vlanmap.put(row.getVlanIndex(), row.getVlanName()); } } }; walker = SnmpUtils.createWalker(getPeer(), trackerName, ciscoVtpVlanTableTracker); walker.start(); try { walker.waitFor(); if (walker.timedOut()) { LOG.info("run:Aborting Bridge Linkd node scan : Agent timed out while scanning the {} table", trackerName); } else if (walker.failed()) { LOG.info("run:Aborting Bridge Linkd node scan : Agent failed while scanning the {} table: {}", trackerName, walker.getErrorMessage()); } } catch (final InterruptedException e) { LOG.error("run: Bridge Linkd node collection interrupted, exiting",e); } return vlanmap; } protected Map<Integer,Integer> walkDot1d(Integer vlan, String vlanname) { LOG.debug("run: Bridge Linkd node scan : ready to walk dot1d data on {}, vlan {}, vlanname {}.", getNodeId(),vlan,vlanname); String trackerName = "dot1dbase"; final Dot1dBaseTracker dot1dbase = new Dot1dBaseTracker(); SnmpWalker walker = SnmpUtils.createWalker(getPeer(), trackerName, dot1dbase); walker.start(); try { walker.waitFor(); if (walker.timedOut()) { LOG.info("run:Aborting Bridge Linkd node scan : Agent timed out while scanning the {} table", trackerName); return new HashMap<Integer, Integer>(); } else if (walker.failed()) { LOG.info("run:Aborting Bridge Linkd node scan : Agent failed while scanning the {} table: {}", trackerName, walker.getErrorMessage()); return new HashMap<Integer, Integer>(); } } catch (final InterruptedException e) { LOG.error("run: Bridge Linkd node collection interrupted, exiting",e); return new HashMap<Integer, Integer>(); } BridgeElement bridge = dot1dbase.getBridgeElement(); bridge.setVlan(vlan); bridge.setVlanname(vlanname); if (bridge.getBaseBridgeAddress() == null) { LOG.info("run: base bridge address is null: bridge mib not supported on: {}", getNodeId()); return new HashMap<Integer, Integer>(); } if (!isValidBridgeAddress(bridge.getBaseBridgeAddress())) { LOG.info("run: bridge not supported, base address identifier {} is not valid on: {}", dot1dbase.getBridgeAddress(), getNodeId()); return new HashMap<Integer, Integer>(); } if (bridge.getBaseNumPorts() == null || bridge.getBaseNumPorts().intValue() == 0) { LOG.info("run: bridge {} has 0 port active, on: {}", dot1dbase.getBridgeAddress(), getNodeId()); return new HashMap<Integer, Integer>(); } LOG.info("run: bridge {} has is if type {}, on: {}", dot1dbase .getBridgeAddress(), BridgeDot1dBaseType.getTypeString(dot1dbase.getBridgeType()),getNodeId()); if (bridge.getBaseType() == BridgeDot1dBaseType.DOT1DBASETYPE_SOURCEROUTE_ONLY) { LOG.info("run: {}: source route only type bridge, on: {}", dot1dbase.getBridgeAddress(), getNodeId()); return new HashMap<Integer, Integer>(); } m_linkd.getQueryManager().store(getNodeId(), bridge); Map<Integer,Integer> bridgetoifindex = walkDot1dBasePortTable(); LOG.debug("run: found on node: '{}' vlan: '{}', bridge ifindex map {}",getNodeId(), vlanname, bridgetoifindex); if (!isValidStpBridgeId(bridge.getStpDesignatedRoot())) { LOG.info("run: invalid Stp designated root: spanning tree not supported on: {}", getNodeId()); } else if (bridge.getBaseBridgeAddress().equals(getBridgeAddressFromStpBridgeId(bridge.getStpDesignatedRoot()))) { LOG.info("run: designated root of spanning tree is itself on bridge {}, on: {}", bridge.getStpDesignatedRoot(), getNodeId()); } else { walkSpanningTree(bridge.getBaseBridgeAddress(),vlan, bridgetoifindex); } return bridgetoifindex; } private Map<Integer,Integer> walkDot1dBasePortTable() { final Map<Integer,Integer> bridgetoifindex = new HashMap<Integer, Integer>(); String trackerName = "dot1dBasePortTable"; Dot1dBasePortTableTracker dot1dBasePortTableTracker = new Dot1dBasePortTableTracker() { @Override public void processDot1dBasePortRow(final Dot1dBasePortRow row) { bridgetoifindex.put(row.getBaseBridgePort(), row.getBaseBridgePortIfindex()); } }; SnmpWalker walker = SnmpUtils.createWalker(getPeer(), trackerName, dot1dBasePortTableTracker); walker.start(); try { walker.waitFor(); if (walker.timedOut()) { LOG.info("run:Aborting Bridge Linkd node scan : Agent timed out while scanning the {} table", trackerName); } else if (walker.failed()) { LOG.info("run:Aborting Bridge Linkd node scan : Agent failed while scanning the {} table: {}", trackerName, walker.getErrorMessage()); } } catch (final InterruptedException e) { LOG.error("run: Bridge Linkd node collection interrupted, exiting",e); } return bridgetoifindex; } private List<BridgeMacLink> walkDot1dTpFdp(final Integer vlan, final Map<Integer,Integer> bridgeifindex,List<BridgeMacLink> bft, SnmpAgentConfig peer) { String trackerName = "dot1dTbFdbPortTable"; Dot1dTpFdbTableTracker stpPortTableTracker = new Dot1dTpFdbTableTracker() { @Override public void processDot1dTpFdbRow(final Dot1dTpFdbRow row) { BridgeMacLink link = row.getLink(); if (link.getBridgeDot1qTpFdbStatus() == null) { LOG.warn("processDot1dTpFdbRow: row has null status. mac {}: vlan {}: on port {}", row.getDot1dTpFdbAddress(), vlan, row.getDot1dTpFdbPort()); return; } if (link.getBridgePort() == null) { LOG.warn("processDot1dTpFdbRow: row has null bridge port. mac {}: vlan {}: on port {} status {}", row.getDot1dTpFdbAddress(), vlan, row.getDot1dTpFdbPort(),link.getBridgeDot1qTpFdbStatus()); return; } if (link.getMacAddress() == null || !isValidBridgeAddress(link.getMacAddress())) { LOG.warn("processDot1dTpFdbRow: row has invalid mac. mac {}: vlan {}: on port {} ifindex {} status {}", row.getDot1dTpFdbAddress(), vlan, row.getDot1dTpFdbPort(),link.getBridgePortIfIndex(),link.getBridgeDot1qTpFdbStatus()); return; } link.setVlan(vlan); if (!bridgeifindex.containsKey(link.getBridgePort()) && link.getBridgeDot1qTpFdbStatus() != BridgeDot1qTpFdbStatus.DOT1D_TP_FDB_STATUS_SELF) { LOG.warn("processDot1dTpFdbRow: row has invalid bridge port no ifindex found. mac {}: vlan {}: on port {} ifindex {} status {}", row.getDot1dTpFdbAddress(), vlan, row.getDot1dTpFdbPort(),link.getBridgePortIfIndex(),link.getBridgeDot1qTpFdbStatus()); return; } link.setBridgePortIfIndex(bridgeifindex.get(link.getBridgePort())); LOG.info("processDot1dTpFdbRow: row processed: mac {}: vlan {}: on port {} ifindex {} status {}", link.getMacAddress(), link.getVlan(), link.getBridgePort() ,link.getBridgePortIfIndex(),link.getBridgeDot1qTpFdbStatus()); bft.add(link); } }; SnmpWalker walker = SnmpUtils.createWalker(peer, trackerName, stpPortTableTracker); walker.start(); try { walker.waitFor(); if (walker.timedOut()) { LOG.info("run:Aborting Bridge Linkd node scan : Agent timed out while scanning the {} table", trackerName); return bft; } else if (walker.failed()) { LOG.info("run:Aborting Bridge Linkd node scan : Agent failed while scanning the {} table: {}", trackerName, walker.getErrorMessage()); return bft; } } catch (final InterruptedException e) { LOG.error("run: Bridge Linkd node collection interrupted, exiting",e); return bft; } return bft; } private List<BridgeMacLink> walkDot1qTpFdb(final Map<Integer,Integer> bridgeifindex, final List<BridgeMacLink> bft) { String trackerName = "dot1qTbFdbPortTable"; Dot1qTpFdbTableTracker dot1qTpFdbTableTracker = new Dot1qTpFdbTableTracker() { @Override public void processDot1qTpFdbRow(final Dot1qTpFdbRow row) { BridgeMacLink link = row.getLink(); if (link.getBridgeDot1qTpFdbStatus() == null) { LOG.warn("processDot1qTpFdbRow: row has null status. mac {}: on port {}", row.getDot1qTpFdbAddress(),row.getDot1qTpFdbPort()); return; } if (link.getBridgePort() == null) { LOG.warn("processDot1qTpFdbRow: row has null bridge port. mac {}: on port {} status {}", row.getDot1qTpFdbAddress(), row.getDot1qTpFdbPort(),link.getBridgeDot1qTpFdbStatus()); return; } if (link.getMacAddress() == null || !isValidBridgeAddress(link.getMacAddress())) { LOG.warn("processDot1qTpFdbRow: row has invalid mac. mac {}: on port {} ifindex {} status {}", row.getDot1qTpFdbAddress(),row.getDot1qTpFdbPort(),link.getBridgePortIfIndex(),link.getBridgeDot1qTpFdbStatus()); return; } if (!bridgeifindex.containsKey(link.getBridgePort()) && link.getBridgeDot1qTpFdbStatus() != BridgeDot1qTpFdbStatus.DOT1D_TP_FDB_STATUS_SELF) { LOG.warn("processDot1qTpFdbRow: row has invalid bridgeport no ifindex found. mac {}: on port {} ifindex {} status {}", row.getDot1qTpFdbAddress(),row.getDot1qTpFdbPort(),link.getBridgePortIfIndex(),link.getBridgeDot1qTpFdbStatus()); return; } link.setBridgePortIfIndex(bridgeifindex.get(link.getBridgePort())); LOG.info("processDot1qTpFdbRow: row processed: mac {}: vlan {}: on port {} ifindex {} status {}", link.getMacAddress(), link.getVlan(), link.getBridgePort() ,link.getBridgePortIfIndex(),link.getBridgeDot1qTpFdbStatus()); bft.add(link); } }; SnmpWalker walker = SnmpUtils.createWalker(getPeer(), trackerName, dot1qTpFdbTableTracker); walker.start(); try { walker.waitFor(); if (walker.timedOut()) { LOG.info("run:Aborting Bridge Linkd node scan : Agent timed out while scanning the {} table", trackerName); } else if (walker.failed()) { LOG.info("run:Aborting Bridge Linkd node scan : Agent failed while scanning the {} table: {}", trackerName, walker.getErrorMessage()); } } catch (final InterruptedException e) { LOG.error("run: Bridge Linkd node collection interrupted, exiting",e); return bft; } return bft; } private void walkSpanningTree(final String baseBridgeAddress, final Integer vlan, final Map<Integer,Integer> bridgeifindex) { String trackerName = "dot1dStpPortTable"; Dot1dStpPortTableTracker stpPortTableTracker = new Dot1dStpPortTableTracker() { @Override public void processDot1dStpPortRow(final Dot1dStpPortRow row) { BridgeStpLink link = row.getLink(); link.setVlan(vlan); link.setStpPortIfIndex(bridgeifindex.get(link.getStpPort())); if (isValidStpBridgeId(link.getDesignatedRoot()) && isValidStpBridgeId(link.getDesignatedBridge()) && !baseBridgeAddress.equals(link.getDesignatedBridgeAddress())) { m_linkd.getQueryManager().store(getNodeId(),link); } } }; SnmpWalker walker = SnmpUtils.createWalker(getPeer(), trackerName, stpPortTableTracker); walker.start(); try { walker.waitFor(); if (walker.timedOut()) { LOG.info("run:Aborting Bridge Linkd node scan : Agent timed out while scanning the {} table", trackerName); } else if (walker.failed()) { LOG.info("run:Aborting Bridge Linkd node scan : Agent failed while scanning the {} table: {}", trackerName, walker.getErrorMessage()); } } catch (final InterruptedException e) { LOG.error("run: Bridge Linkd node collection interrupted, exiting",e); } } @Override public String getInfo() { return "ReadyRunnable BridgeLinkNodeDiscovery" + " ip=" + str(getTarget()) + " port=" + getPort() + " community=" + getReadCommunity() + " package=" + getPackageName(); } @Override public String getName() { return "BridgeLinkDiscovery"; } }
Fix NMS-8619: Lost Bridge Forwarding Table Links Fixed community for Cisco devices
opennms-services/src/main/java/org/opennms/netmgt/enlinkd/NodeDiscoveryBridge.java
Fix NMS-8619: Lost Bridge Forwarding Table Links
Java
agpl-3.0
d72a566b1582c8aecbefa6c3204b9cb92dab77de
0
MarkehMe/FactionsPlus
package markehme.factionsplus.Cmds; import markehme.factionsplus.FactionsPlus; import markehme.factionsplus.config.Config; import markehme.factionsplus.references.FP; import org.bukkit.ChatColor; import com.massivecraft.factions.cmd.req.ReqFactionsEnabled; public class CmdReloadFP extends FPCommand { public CmdReloadFP() { super(); this.aliases.add( "reloadfp" ); //this.optionalArgs.put( "all|conf|templates", "all"); this.errorOnToManyArgs = false; this.addRequirements( ReqFactionsEnabled.get() ); this.setHelp( "reloads FactionPlus config" ); this.setDesc( "reloads FactionPlus config" ); } @SuppressWarnings( "boxing" ) @Override public void performfp() { if(!FactionsPlus.permission.has(sender, "factionsplus.reload")) { msg(ChatColor.RED + "No permission!"); return; } long startTime = System.nanoTime(); boolean ret = false; try { // Templates have been moved into the config // (in the future, templates should work off the same system as config // but in a seperate file) /* if ( what.startsWith( "conf" ) ) { fileWhat=Config.fileConfig.getName(); ret = Config.reloadConfig(); } else if ( what.startsWith( "templ" ) ) { fileWhat=Config.templatesFile.getName(); ret = Config.reloadTemplates(); } else if ( what.equals( "all" ) ) {*/ Config.reload(); ret = true; // otherwise it would just throw /*} else { msg( "<b>Invalid file specified. <i>Valid files: all, conf, templates" ); return; }*/ } catch ( Throwable t ) { t.printStackTrace(); ret = false; } finally { long endTime = System.nanoTime() - startTime; if ( ret ) { msg( "<i>Reloaded FactionPlus <i>from disk, took <h>%,2dms<i>.", endTime / 1000000 );//ns to ms } else { msg( ChatColor.RED+"Errors occurred while reloading. See console for details." ); } } } }
src/markehme/factionsplus/Cmds/CmdReloadFP.java
package markehme.factionsplus.Cmds; import markehme.factionsplus.config.Config; import org.bukkit.ChatColor; import com.massivecraft.factions.cmd.req.ReqFactionsEnabled; public class CmdReloadFP extends FPCommand { public CmdReloadFP() { super(); this.aliases.add( "reloadfp" ); //this.optionalArgs.put( "all|conf|templates", "all"); this.errorOnToManyArgs = false; this.addRequirements( ReqFactionsEnabled.get() ); this.setHelp( "reloads FactionPlus config" ); this.setDesc( "reloads FactionPlus config" ); } @SuppressWarnings( "boxing" ) @Override public void performfp() { long startTime = System.nanoTime(); boolean ret = false; try { // Templates have been moved into the config // (in the future, templates should work off the same system as config // but in a seperate file) /* if ( what.startsWith( "conf" ) ) { fileWhat=Config.fileConfig.getName(); ret = Config.reloadConfig(); } else if ( what.startsWith( "templ" ) ) { fileWhat=Config.templatesFile.getName(); ret = Config.reloadTemplates(); } else if ( what.equals( "all" ) ) {*/ Config.reload(); ret = true; // otherwise it would just throw /*} else { msg( "<b>Invalid file specified. <i>Valid files: all, conf, templates" ); return; }*/ } catch ( Throwable t ) { t.printStackTrace(); ret = false; } finally { long endTime = System.nanoTime() - startTime; if ( ret ) { msg( "<i>Reloaded FactionPlus <i>from disk, took <h>%,2dms<i>.", endTime / 1000000 );//ns to ms } else { msg( ChatColor.RED+"Errors occurred while reloading. See console for details." ); } } } }
Permission check for reload
src/markehme/factionsplus/Cmds/CmdReloadFP.java
Permission check for reload
Java
lgpl-2.1
a173e799cd32b96122618bea84ba5b4202088174
0
kaffe/kaffe,kaffe/kaffe,kaffe/kaffe,kaffe/kaffe,kaffe/kaffe
package java.awt; import java.awt.event.ActionEvent; import java.awt.event.AdjustmentEvent; import java.awt.event.ComponentEvent; import java.awt.event.ContainerEvent; import java.awt.event.FocusEvent; import java.awt.event.ItemEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.TextEvent; import java.awt.event.WindowEvent; import java.util.EventObject; import java.util.Stack; import kaffe.util.Ptr; /** * * Copyright (c) 1998 * Transvirtual Technologies Inc. All rights reserved. * * See the file "license.terms" for information on usage and redistribution * of this file. * * @author P.C.Mehlitz */ public class AWTEvent extends EventObject { protected int id; protected boolean consumed = false; protected AWTEvent next; final public static int COMPONENT_EVENT_MASK = 0x01; final public static int CONTAINER_EVENT_MASK = 0x02; final public static int FOCUS_EVENT_MASK = 0x04; final public static int KEY_EVENT_MASK = 0x08; final public static int MOUSE_EVENT_MASK = 0x10; final public static int MOUSE_MOTION_EVENT_MASK = 0x20; final public static int WINDOW_EVENT_MASK = 0x40; final public static int ACTION_EVENT_MASK = 0x80; final public static int ADJUSTMENT_EVENT_MASK = 0x100; final public static int ITEM_EVENT_MASK = 0x200; final public static int TEXT_EVENT_MASK = 0x400; final public static int RESERVED_ID_MAX = 1999; final static int DISABLED_MASK = 0x80000000; static Component keyTgt; static Window activeWindow; static Component mouseTgt; protected static int inputModifier; protected static boolean accelHint; protected static Component[] sources; static int nSources; protected static Object evtLock = new Object(); protected static RootWindow root; protected static Component nativeSource; static { sources = Toolkit.evtInit(); } protected AWTEvent ( Object source, int id ) { super( source); this.id = id; } public void consume () { consumed = true; } protected void dispatch () { // standard processing of non-system events ((Component)source).processEvent( this); } public int getID () { return id; } static int getID ( AWTEvent evt ) { return evt.id; } static Object getSource ( AWTEvent evt ) { return evt.source; } protected static Component getToplevel ( Component c ) { // Note that this will fail in case 'c' is already removeNotified (has no parent, // anymore). But returning 'null' would just shift the problem into the caller - // a dispatch() method - and that would slow down dispatching. Since it also would be // difficult to decide what to do (because of inconsistent global state), we prefer a // clean cut and rely on no events being dispatched on removeNotified Components while ( ! (c instanceof Window) ){ c = c.parent; } return c; } protected Event initOldEvent ( Event e ) { // this is the generic version, to be resolved by the relevant subclasses return null; } protected boolean isConsumed () { return consumed; } protected boolean isLiveEventFor( Object src ) { return false; } protected boolean isObsoletePaint( Object src, int x, int y, int w, int h ) { return false; } public String paramString () { return ""; } protected void recycle () { source = null; next = null; } static void registerSource ( Component c, Ptr nativeData ) { int idx = Toolkit.evtRegisterSource( nativeData); sources[idx] = c; if ( ++nSources == 1 ) Toolkit.startDispatch(); } MouseEvent retarget ( Component target, int dx, int dy ) { return null; } protected static void sendEvent ( AWTEvent e, boolean sync ) { if ( sync ) e.dispatch(); else Toolkit.eventQueue.postEvent( e); } public void setSource ( Object newSource ) { source = newSource; } public String toString () { return getClass().getName() + ':' + paramString() + ", source: " + source; } static void unregisterSource ( Component c, Ptr nativeData ) { int idx = Toolkit.evtUnregisterSource( nativeData); sources[idx] = null; if ( c == nativeSource ) // just a matter of safety (avoid temp garbage) nativeSource = null; if ( (--nSources == 0) && Defaults.AutoStop ) { // give the SecurityManager a chance to step in before // closing down the Toolkit System.getSecurityManager().checkExit( 0); Toolkit.terminate(); System.exit( 0); // not strictly required (if there are no persistent daemons) } } }
libraries/javalib/java/awt/AWTEvent.java
package java.awt; import java.awt.event.ActionEvent; import java.awt.event.AdjustmentEvent; import java.awt.event.ComponentEvent; import java.awt.event.ContainerEvent; import java.awt.event.FocusEvent; import java.awt.event.ItemEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.TextEvent; import java.awt.event.WindowEvent; import java.util.EventObject; import java.util.Stack; import kaffe.util.Ptr; /** * * Copyright (c) 1998 * Transvirtual Technologies Inc. All rights reserved. * * See the file "license.terms" for information on usage and redistribution * of this file. * * @author P.C.Mehlitz */ public class AWTEvent extends EventObject { protected int id; protected boolean consumed = false; protected AWTEvent next; final public static int COMPONENT_EVENT_MASK = 0x01; final public static int CONTAINER_EVENT_MASK = 0x02; final public static int FOCUS_EVENT_MASK = 0x04; final public static int KEY_EVENT_MASK = 0x08; final public static int MOUSE_EVENT_MASK = 0x10; final public static int MOUSE_MOTION_EVENT_MASK = 0x20; final public static int WINDOW_EVENT_MASK = 0x40; final public static int ACTION_EVENT_MASK = 0x80; final public static int ADJUSTMENT_EVENT_MASK = 0x100; final public static int ITEM_EVENT_MASK = 0x200; final public static int TEXT_EVENT_MASK = 0x400; final public static int RESERVED_ID_MAX = 1999; final static int DISABLED_MASK = 0x80000000; static Component keyTgt; static Window activeWindow; static Component mouseTgt; protected static int inputModifier; protected static boolean accelHint; protected static Component[] sources; static int nSources; protected static Object evtLock = new Object(); protected static RootWindow root; protected static Component nativeSource; static { sources = Toolkit.evtInit(); } protected AWTEvent ( Object source, int id ) { super( source); this.id = id; } public void consume () { consumed = true; } protected void dispatch () { // standard processing of non-system events ((Component)source).processEvent( this); } public int getID () { return id; } static int getID ( AWTEvent evt ) { return evt.id; } static Object getSource ( AWTEvent evt ) { return evt.source; } protected static Component getToplevel ( Component c ) { // Note that this will fail in case 'c' is already removeNotified (has no parent, // anymore). But returning 'null' would just shift the problem into the caller - // a dispatch() method - and that would slow down dispatching. Since it also would be // difficult to decide what to do (because of inconsistent global state), we prefer a // clean cut and rely on no events being dispatched on removeNotified Components while ( ! (c instanceof Window) ){ c = c.parent; } return c; } protected Event initOldEvent ( Event e ) { // this is the generic version, to be resolved by the relevant subclasses return null; } protected boolean isConsumed () { return consumed; } protected boolean isLiveEventFor( Object src ) { return false; } protected boolean isObsoletePaint( Object src, int x, int y, int w, int h ) { return false; } public String paramString () { return ""; } protected void recycle () { source = null; next = null; } static void registerSource ( Component c, Ptr nativeData ) { int idx = Toolkit.evtRegisterSource( nativeData); sources[idx] = c; if ( ++nSources == 1 ) Toolkit.startDispatch(); } MouseEvent retarget ( Component target, int dx, int dy ) { return null; } protected static void sendEvent ( AWTEvent e, boolean sync ) { if ( sync ) e.dispatch(); else Toolkit.eventQueue.postEvent( e); } void setSource ( Object newSource ) { source = newSource; } public String toString () { return getClass().getName() + ':' + paramString() + ", source: " + source; } static void unregisterSource ( Component c, Ptr nativeData ) { int idx = Toolkit.evtUnregisterSource( nativeData); sources[idx] = null; if ( c == nativeSource ) // just a matter of safety (avoid temp garbage) nativeSource = null; if ( (--nSources == 0) && Defaults.AutoStop ) { // give the SecurityManager a chance to step in before // closing down the Toolkit System.getSecurityManager().checkExit( 0); Toolkit.terminate(); System.exit( 0); // not strictly required (if there are no persistent daemons) } } }
Make setSource() public instead of package to fix compilation error. Not sure if this is the "right" fix.
libraries/javalib/java/awt/AWTEvent.java
Make setSource() public instead of package to fix compilation error. Not sure if this is the "right" fix.
Java
lgpl-2.1
f577e8f745fd13af3de4a982053addb1b61015ef
0
cytoscape/cytoscape-impl,cytoscape/cytoscape-impl,cytoscape/cytoscape-impl,cytoscape/cytoscape-impl,cytoscape/cytoscape-impl
package org.cytoscape.filter.internal.range; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.JFormattedTextField; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.cytoscape.filter.internal.view.look.FilterPanelStyle; @SuppressWarnings("serial") public class RangeChooser<N extends Number & Comparable<N>> extends JPanel { private JRangeSlider slider; private JFormattedTextField lowField; private JFormattedTextField highField; private JLabel label1; private JLabel label2; private JPanel spacerPanel; private JLabel label3; private PropertyChangeListener textListener; private ChangeListener sliderListener; RangeChooser(FilterPanelStyle style, RangeChooserController<N> controller) { slider = new JRangeSlider(controller.getSliderModel().getBoundedRangeModel(), JRangeSlider.HORIZONTAL); lowField = style.createFormattedTextField(controller.getFormatterFactory()); lowField.setHorizontalAlignment(JTextField.TRAILING); lowField.setColumns(6); highField = style.createFormattedTextField(controller.getFormatterFactory()); highField.setHorizontalAlignment(JTextField.TRAILING); highField.setColumns(6); sliderListener = new ChangeListener() { public void stateChanged(ChangeEvent event) { controller.sliderChanged(); } }; textListener = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent event) { controller.textFieldChanged(); } }; addListeners(controller); label1 = style.createLabel("between "); label2 = style.createLabel(" and "); label3 = style.createLabel(" inclusive."); spacerPanel = new JPanel(); spacerPanel.setOpaque(false); setLayout(new GridBagLayout()); setOpaque(false); } void addListeners(RangeChooserController<N> controller) { slider.addChangeListener(sliderListener); lowField.addPropertyChangeListener("value", textListener); highField.addPropertyChangeListener("value", textListener); } void removeListeners() { slider.removeChangeListener(sliderListener); lowField.removePropertyChangeListener("value", textListener); highField.removePropertyChangeListener("value", textListener); } public JFormattedTextField getLowField() { return lowField; } public JFormattedTextField getHighField() { return highField; } public void setInteractive(boolean isInteractive) { removeAll(); int row = 0; add(label1, new GridBagConstraints(0, row, 1, 1, 0, 0, GridBagConstraints.BASELINE_LEADING, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); add(lowField, new GridBagConstraints(1, row, 1, 1, 0, 0, GridBagConstraints.BASELINE_LEADING, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); add(label2, new GridBagConstraints(2, row, 1, 1, 0, 0, GridBagConstraints.BASELINE_LEADING, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); add(highField, new GridBagConstraints(3, row, 1, 1, 0, 0, GridBagConstraints.BASELINE_LEADING, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); add(label3, new GridBagConstraints(4, row, 1, 1, 0, 0, GridBagConstraints.BASELINE_LEADING, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); add(spacerPanel, new GridBagConstraints(5, row, 1, 1, 1, 0, GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); row++; // Why are we hiding the slider? //if (isInteractive) { add(slider, new GridBagConstraints(0, row, 6, 1, 1, 0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 3, 3), 0, 0)); slider.invalidate(); //} revalidate(); } }
filter2-impl/src/main/java/org/cytoscape/filter/internal/range/RangeChooser.java
package org.cytoscape.filter.internal.range; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.JFormattedTextField; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.cytoscape.filter.internal.view.look.FilterPanelStyle; @SuppressWarnings("serial") public class RangeChooser<N extends Number & Comparable<N>> extends JPanel { private JRangeSlider slider; private JFormattedTextField lowField; private JFormattedTextField highField; private JLabel label1; private JLabel label2; private JPanel spacerPanel; private JLabel label3; private PropertyChangeListener textListener; private ChangeListener sliderListener; RangeChooser(FilterPanelStyle style, RangeChooserController<N> controller) { slider = new JRangeSlider(controller.getSliderModel().getBoundedRangeModel(), JRangeSlider.HORIZONTAL); lowField = style.createFormattedTextField(controller.getFormatterFactory()); lowField.setHorizontalAlignment(JTextField.TRAILING); lowField.setColumns(6); highField = style.createFormattedTextField(controller.getFormatterFactory()); highField.setHorizontalAlignment(JTextField.TRAILING); highField.setColumns(6); sliderListener = new ChangeListener() { public void stateChanged(ChangeEvent event) { controller.sliderChanged(); } }; textListener = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent event) { controller.textFieldChanged(); } }; addListeners(controller); label1 = style.createLabel("between "); label2 = style.createLabel(" and "); label3 = style.createLabel(" inclusive."); spacerPanel = new JPanel(); spacerPanel.setOpaque(false); setLayout(new GridBagLayout()); setOpaque(false); } void addListeners(RangeChooserController<N> controller) { slider.addChangeListener(sliderListener); lowField.addPropertyChangeListener("value", textListener); highField.addPropertyChangeListener("value", textListener); } void removeListeners() { slider.removeChangeListener(sliderListener); lowField.removePropertyChangeListener("value", textListener); highField.removePropertyChangeListener("value", textListener); } public JFormattedTextField getLowField() { return lowField; } public JFormattedTextField getHighField() { return highField; } public void setInteractive(boolean isInteractive) { removeAll(); int row = 0; add(label1, new GridBagConstraints(0, row, 1, 1, 0, 0, GridBagConstraints.BASELINE_LEADING, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); add(lowField, new GridBagConstraints(1, row, 1, 1, 0, 0, GridBagConstraints.BASELINE_LEADING, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); add(label2, new GridBagConstraints(2, row, 1, 1, 0, 0, GridBagConstraints.BASELINE_LEADING, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); add(highField, new GridBagConstraints(3, row, 1, 1, 0, 0, GridBagConstraints.BASELINE_LEADING, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); add(label3, new GridBagConstraints(4, row, 1, 1, 0, 0, GridBagConstraints.BASELINE_LEADING, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); add(spacerPanel, new GridBagConstraints(5, row, 1, 1, 1, 0, GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); row++; if (isInteractive) { add(slider, new GridBagConstraints(0, row, 6, 1, 1, 0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 3, 3), 0, 0)); slider.invalidate(); } revalidate(); } }
Refs #3290. Always show range sliders on column filters.
filter2-impl/src/main/java/org/cytoscape/filter/internal/range/RangeChooser.java
Refs #3290. Always show range sliders on column filters.
Java
lgpl-2.1
25d4aee10b111fb5b5c43b713b225e8c1e21e58b
0
CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine
package org.jetel.graph; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.net.URL; import java.util.Arrays; import java.util.concurrent.Future; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jetel.graph.runtime.EngineInitializer; import org.jetel.graph.runtime.GraphRuntimeContext; import org.jetel.main.runGraph; import org.jetel.test.CloverTestCase; import org.jetel.util.file.FileUtils; import org.jetel.util.string.StringUtils; /* * Copyright (c) 2004-2005 Javlin Consulting s.r.o. All rights reserved. * */ public class ResetTest extends CloverTestCase { private final static String SCENARIOS_RELATIVE_PATH = "../cloveretl.test.scenarios/"; private final static String[] EXAMPLE_PATH = { "../cloveretl.examples/SimpleExamples/", "../cloveretl.examples/AdvancedExamples/", "../cloveretl.examples/CTL1FunctionsTutorial/", "../cloveretl.examples/CTL2FunctionsTutorial/", "../cloveretl.examples/DataProfiling/", "../cloveretl.examples/DataSampling/", "../cloveretl.examples/ExtExamples/", "../cloveretl.test.scenarios/", "../cloveretl.examples.commercial/", "../cloveretl.examples/CompanyTransactionsTutorial/" }; private final static String[] NEEDS_SCENARIOS_CONNECTION = { "graphRevenues.grf", "graphDBExecuteMsSql.grf", "graphDBExecuteMySql.grf", "graphDBExecuteOracle.grf", "graphDBExecutePostgre.grf", "graphDBExecuteSybase.grf", "graphInfobrightDataWriterRemote.grf", "graphLdapReaderWriter.grf" }; private final static String[] NEEDS_SCENARIOS_LIB = { "graphDBExecuteOracle.grf", "graphDBExecuteSybase.grf", "graphLdapReaderWriter.grf" }; private final static String GRAPHS_DIR = "graph"; private final static String TRANS_DIR = "trans"; private final static String[] OUT_DIRS = {"data-out/", "data-tmp/", "seq/"}; private final String basePath; private final File graphFile; private final boolean batchMode; private boolean cleanUp = true; private static Log logger = LogFactory.getLog(ResetTest.class); public static Test suite() { final TestSuite suite = new TestSuite(); for (int i = 0; i < EXAMPLE_PATH.length; i++) { logger.info("Testing graphs in " + EXAMPLE_PATH[i]); final File graphsDir = new File(EXAMPLE_PATH[i], GRAPHS_DIR); if(!graphsDir.exists()){ throw new IllegalStateException("Graphs directory " + graphsDir.getAbsolutePath() +" not found"); } File[] graphFiles =graphsDir.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.getName().endsWith(".grf") && !pathname.getName().startsWith("TPCH")// ok, performance tests - last very long && !pathname.getName().contains("Performance")// ok, performance tests - last very long && !pathname.getName().equals("graphJoinData.grf") // ok, uses class file that is not created && !pathname.getName().equals("graphJoinHash.grf") // ok, uses class file that is not created && !pathname.getName().equals("graphOrdersReformat.grf") // ok, uses class file that is not created && !pathname.getName().equals("graphDataGeneratorExt.grf") // ok, uses class file that is not created && !pathname.getName().equals("graphApproximativeJoin.grf") // ok, uses class file that is not created && !pathname.getName().equals("graphDBJoin.grf") // ok, uses class file that is not created && !pathname.getName().equals("conversionNum2num.grf") // ok, should fail && !pathname.getName().equals("outPortWriting.grf") // ok, should fail && !pathname.getName().equals("graphDb2Load.grf") // ok, can only work with db2 client && !pathname.getName().equals("graphMsSqlDataWriter.grf") // ok, can only work with MsSql client && !pathname.getName().equals("graphMysqlDataWriter.grf") // ok, can only work with MySql client && !pathname.getName().equals("graphOracleDataWriter.grf") // ok, can only work with Oracle client && !pathname.getName().equals("graphPostgreSqlDataWriter.grf") // ok, can only work with postgre client && !pathname.getName().equals("graphInformixDataWriter.grf") // ok, can only work with informix server && !pathname.getName().equals("graphInfobrightDataWriter.grf") // ok, can only work with infobright server && !pathname.getName().equals("graphSystemExecuteWin.grf") // ok, graph for Windows && !pathname.getName().equals("graphLdapReader_Uninett.grf") // ok, invalid server && !pathname.getName().equals("graphSequenceChecker.grf") // ok, is to fail && !pathname.getName().equals("FixedData.grf") // ok, is to fail && !pathname.getName().equals("xpathReaderStates.grf") // ok, is to fail && !pathname.getName().equals("graphDataPolicy.grf") // ok, is to fail && !pathname.getName().equals("conversionDecimal2integer.grf") // ok, is to fail && !pathname.getName().equals("conversionDecimal2long.grf") // ok, is to fail && !pathname.getName().equals("conversionDouble2integer.grf") // ok, is to fail && !pathname.getName().equals("conversionDouble2long.grf") // ok, is to fail && !pathname.getName().equals("conversionLong2integer.grf") // ok, is to fail && !pathname.getName().equals("nativeSortTestGraph.grf") // ok, invalid paths && !pathname.getName().equals("mountainsInformix.grf") // see issue 2550 && !pathname.getName().equals("SystemExecuteWin_EchoFromFile.grf") // graph for windows && !pathname.getName().equals("XLSEncryptedFail.grf") // ok, is to fail && !pathname.getName().equals("XLSXEncryptedFail.grf") // ok, is to fail && !pathname.getName().equals("XLSInvalidFile.grf") // ok, is to fail && !pathname.getName().equals("XLSReaderOrderMappingFail.grf") // ok, is to fail && !pathname.getName().equals("XLSXReaderOrderMappingFail.grf") // ok, is to fail && !pathname.getName().equals("XLSWildcardStrict.grf") // ok, is to fail && !pathname.getName().equals("XLSXWildcardStrict.grf") // ok, is to fail && !pathname.getName().equals("XLSWildcardControlled1.grf") // ok, is to fail && !pathname.getName().equals("XLSXWildcardControlled1.grf") // ok, is to fail && !pathname.getName().equals("XLSWildcardControlled7.grf") // ok, is to fail && !pathname.getName().equals("XLSXWildcardControlled7.grf") // ok, is to fail && !pathname.getName().equals("SSWRITER_MultilineInsertIntoTemplate.grf") // uses graph parameter definition from after-commit.ts && !pathname.getName().equals("SSWRITER_FormatInMetadata.grf") // uses graph parameter definition from after-commit.ts && !pathname.getName().equals("WSC_NamespaceBindingsDefined.grf") // ok, is to fail && !pathname.getName().equals("FailingGraph.grf") // ok, is to fail && !pathname.getName().equals("RunGraph_FailWhenUnderlyingGraphFails.grf") // probably should fail, recheck after added to after-commit.ts && !pathname.getName().equals("DataIntersection_order_check_A.grf") // ok, is to fail && !pathname.getName().equals("DataIntersection_order_check_B.grf") // ok, is to fail && !pathname.getName().equals("UDR_Logging_SFTP_CL1469.grf") // ok, is to fail && !pathname.getName().startsWith("AddressDoctor") //wrong path to db file, try to fix when AD installed on jenkins machines && !pathname.getName().equals("EmailReader_Local.grf") // remove after CL-2167 solved && !pathname.getName().equals("EmailReader_Server.grf") // remove after CLD-3437 solved (or mail.javlin.eu has valid certificate) && !pathname.getName().contains("firebird") // remove after CL-2170 solved && !pathname.getName().startsWith("ListOfRecords_Functions_02_") // remove after CL-2173 solved && !pathname.getName().equals("UDR_FileURL_OneZipMultipleFilesUnspecified.grf") // remove after CL-2174 solved && !pathname.getName().equals("UDR_FileURL_OneZipOneFileUnspecified.grf") // remove after CL-2174 solved && !pathname.getName().startsWith("MapOfRecords_Functions_01_Compiled_") // remove after CL-2175 solved && !pathname.getName().startsWith("MapOfRecords_Functions_01_Interpreted_") // remove after CL-2176 solved && !pathname.getName().equals("manyRecords.grf") // remove after CL-1825 implemented && !pathname.getName().equals("packedDecimal.grf") // remove after CL-1811 solved && !pathname.getName().equals("SimpleZipWrite.grf") // used by ArchiveFlushTest.java, doesn't make sense to run it separately && !pathname.getName().equals("XMLExtract_TKLK_003_Back.grf") // needs output from XMLWriter_LKTW_003.grf && !pathname.getName().equals("SQLDataParser_precision_CL2187.grf") // ok, is to fail && !pathname.getName().equals("incrementalReadingDB_explicitMapping.grf") // remove after CL-2239 solved && !pathname.getName().equals("HTTPConnector_get_bodyparams.grf") // ok, is to fail && !pathname.getName().equals("HTTPConnector_get_error_unknownhost.grf") // ok, is to fail && !pathname.getName().equals("HTTPConnector_get_error_unknownprotocol.grf") // ok, is to fail && !pathname.getName().equals("HTTPConnector_get_inputfield.grf") // ok, is to fail && !pathname.getName().equals("HTTPConnector_get_inputfileURL.grf") // ok, is to fail && !pathname.getName().equals("HTTPConnector_get_requestcontent.grf") // ok, is to fail && !pathname.getName().equals("HTTPConnector_post_error_unknownhost.grf") // ok, is to fail && !pathname.getName().equals("HTTPConnector_post_error_unknownprotocol.grf") // ok, is to fail && !pathname.getName().equals("HTTPConnector_inputmapping_null_values.grf") // ok, is to fail && !pathname.getName().equals("HttpConnector_errHandlingNoRedir.grf") // ok, is to fail && !pathname.getName().equals("XMLExtract_fileURL_not_xml.grf") // ok, is to fail && !pathname.getName().equals("XMLExtract_charset_invalid.grf") // ok, is to fail && !pathname.getName().equals("XMLExtract_mappingURL_missing.grf") // ok, is to fail && !pathname.getName().equals("XMLExtract_fileURL_not_exists.grf") // ok, is to fail && !pathname.getName().equals("XMLExtract_charset_not_default_fail.grf") // ok, is to fail && !pathname.getName().equals("RunGraph_differentOutputMetadataFail.grf") // ok, is to fail && !pathname.getName().equals("SandboxOperationHandlerTest.grf") // runs only on server && !pathname.getName().equals("DenormalizerWithoutInputFile.grf") // probably subgraph not supposed to be executed separately && !pathname.getName().equals("BeanWriterReader_employees.grf"); // remove after CL-2474 solved } }); Arrays.sort(graphFiles); for( int j = 0; j < graphFiles.length; j++){ suite.addTest(new ResetTest(EXAMPLE_PATH[i], graphFiles[j], false, false)); suite.addTest(new ResetTest(EXAMPLE_PATH[i], graphFiles[j], true, j == graphFiles.length - 1 ? true : false)); } } return suite; } @Override protected void setUp() throws Exception { super.setUp(); initEngine(); } protected static String getTestName(String basePath, File graphFile, boolean batchMode) { final StringBuilder ret = new StringBuilder(); final String n = graphFile.getName(); int lastDot = n.lastIndexOf('.'); if (lastDot == -1) { ret.append(n); } else { ret.append(n.substring(0, lastDot)); } if (batchMode) { ret.append("-batch"); } else { ret.append("-nobatch"); } return ret.toString(); } protected ResetTest(String basePath, File graphFile, boolean batchMode, boolean cleanup) { super(getTestName(basePath, graphFile, batchMode)); this.basePath = basePath; this.graphFile = graphFile; this.batchMode = batchMode; this.cleanUp = cleanup; } @Override protected void runTest() throws Throwable { final String beseAbsolutePath = new File(basePath).getAbsolutePath().replace('\\', '/'); logger.info("Project dir: " + beseAbsolutePath); logger.info("Analyzing graph " + graphFile.getPath()); logger.info("Batch mode: " + batchMode); final GraphRuntimeContext runtimeContext = new GraphRuntimeContext(); runtimeContext.setUseJMX(false); runtimeContext.setContextURL(FileUtils.getFileURL(basePath)); // absolute path in PROJECT parameter is required for graphs using Derby database runtimeContext.addAdditionalProperty("PROJECT", beseAbsolutePath); if (StringUtils.findString(graphFile.getName(), NEEDS_SCENARIOS_CONNECTION) != -1) { final String connDir = new File(SCENARIOS_RELATIVE_PATH + "conn").getAbsolutePath(); runtimeContext.addAdditionalProperty("CONN_DIR", connDir); logger.info("CONN_DIR set to " + connDir); } if (StringUtils.findString(graphFile.getName(), NEEDS_SCENARIOS_LIB) != -1) {// set LIB_DIR to jdbc drivers directory final String libDir = new File(SCENARIOS_RELATIVE_PATH + "lib").getAbsolutePath(); runtimeContext.addAdditionalProperty("LIB_DIR", libDir); logger.info("LIB_DIR set to " + libDir); } // for scenarios graphs, add the TRANS dir to the classpath if (basePath.contains("cloveretl.test.scenarios")) { runtimeContext.setRuntimeClassPath(new URL[] {FileUtils.getFileURL(FileUtils.appendSlash(beseAbsolutePath) + TRANS_DIR + "/")}); runtimeContext.setCompileClassPath(runtimeContext.getRuntimeClassPath()); } runtimeContext.setBatchMode(batchMode); final TransformationGraph graph = TransformationGraphXMLReaderWriter.loadGraph(new FileInputStream(graphFile), runtimeContext); try { graph.setDebugMode(false); EngineInitializer.initGraph(graph); for (int i = 0; i < 3; i++) { final Future<Result> futureResult = runGraph.executeGraph(graph, runtimeContext); Result result = Result.N_A; result = futureResult.get(); switch (result) { case FINISHED_OK: // everything O.K. logger.info("Execution of graph successful !"); break; case ABORTED: // execution was ABORTED !! logger.info("Execution of graph failed !"); fail("Execution of graph failed !"); break; default: logger.info("Execution of graph failed !"); fail("Execution of graph failed !"); } } } catch (Throwable e) { throw new IllegalStateException("Error executing grap " + graphFile, e); } finally { if (cleanUp) { cleanupData(); } logger.info("Transformation graph is freeing.\n"); graph.free(); } } private void cleanupData() { for (String outDir : OUT_DIRS) { File outDirFile = new File(basePath, outDir); File[] file = outDirFile.listFiles(new FileFilter() { @Override public boolean accept(File f) { return f.isFile(); } }); for (int i = 0; i < file.length; i++) { final boolean drt = file[i].delete(); if (drt) { logger.info("Cleanup: deleted file " + file[i].getAbsolutePath()); } else { logger.info("Cleanup: error delete file " + file[i].getAbsolutePath()); } } } } }
cloveretl.engine/test/org/jetel/graph/ResetTest.java
package org.jetel.graph; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.net.URL; import java.util.Arrays; import java.util.concurrent.Future; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jetel.graph.runtime.EngineInitializer; import org.jetel.graph.runtime.GraphRuntimeContext; import org.jetel.main.runGraph; import org.jetel.test.CloverTestCase; import org.jetel.util.file.FileUtils; import org.jetel.util.string.StringUtils; /* * Copyright (c) 2004-2005 Javlin Consulting s.r.o. All rights reserved. * */ public class ResetTest extends CloverTestCase { private final static String SCENARIOS_RELATIVE_PATH = "../cloveretl.test.scenarios/"; private final static String[] EXAMPLE_PATH = { "../cloveretl.examples/SimpleExamples/", "../cloveretl.examples/AdvancedExamples/", "../cloveretl.examples/CTL1FunctionsTutorial/", "../cloveretl.examples/CTL2FunctionsTutorial/", "../cloveretl.examples/DataProfiling/", "../cloveretl.examples/DataSampling/", "../cloveretl.examples/ExtExamples/", "../cloveretl.test.scenarios/", "../cloveretl.examples.commercial/", "../cloveretl.examples/CompanyTransactionsTutorial/" }; private final static String[] NEEDS_SCENARIOS_CONNECTION = { "graphRevenues.grf", "graphDBExecuteMsSql.grf", "graphDBExecuteMySql.grf", "graphDBExecuteOracle.grf", "graphDBExecutePostgre.grf", "graphDBExecuteSybase.grf", "graphInfobrightDataWriterRemote.grf", "graphLdapReaderWriter.grf" }; private final static String[] NEEDS_SCENARIOS_LIB = { "graphDBExecuteOracle.grf", "graphDBExecuteSybase.grf", "graphLdapReaderWriter.grf" }; private final static String GRAPHS_DIR = "graph"; private final static String TRANS_DIR = "trans"; private final static String[] OUT_DIRS = {"data-out/", "data-tmp/", "seq/"}; private final String basePath; private final File graphFile; private final boolean batchMode; private boolean cleanUp = true; private static Log logger = LogFactory.getLog(ResetTest.class); public static Test suite() { final TestSuite suite = new TestSuite(); for (int i = 0; i < EXAMPLE_PATH.length; i++) { logger.info("Testing graphs in " + EXAMPLE_PATH[i]); final File graphsDir = new File(EXAMPLE_PATH[i], GRAPHS_DIR); if(!graphsDir.exists()){ throw new IllegalStateException("Graphs directory " + graphsDir.getAbsolutePath() +" not found"); } File[] graphFiles =graphsDir.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.getName().endsWith(".grf") && pathname.getName().startsWith("graph")// temporary, just for debugging && !pathname.getName().startsWith("TPCH")// ok, performance tests - last very long && !pathname.getName().contains("Performance")// ok, performance tests - last very long && !pathname.getName().equals("graphJoinData.grf") // ok, uses class file that is not created && !pathname.getName().equals("graphJoinHash.grf") // ok, uses class file that is not created && !pathname.getName().equals("graphOrdersReformat.grf") // ok, uses class file that is not created && !pathname.getName().equals("graphDataGeneratorExt.grf") // ok, uses class file that is not created && !pathname.getName().equals("graphApproximativeJoin.grf") // ok, uses class file that is not created && !pathname.getName().equals("graphDBJoin.grf") // ok, uses class file that is not created && !pathname.getName().equals("conversionNum2num.grf") // ok, should fail && !pathname.getName().equals("outPortWriting.grf") // ok, should fail && !pathname.getName().equals("graphDb2Load.grf") // ok, can only work with db2 client && !pathname.getName().equals("graphMsSqlDataWriter.grf") // ok, can only work with MsSql client && !pathname.getName().equals("graphMysqlDataWriter.grf") // ok, can only work with MySql client && !pathname.getName().equals("graphOracleDataWriter.grf") // ok, can only work with Oracle client && !pathname.getName().equals("graphPostgreSqlDataWriter.grf") // ok, can only work with postgre client && !pathname.getName().equals("graphInformixDataWriter.grf") // ok, can only work with informix server && !pathname.getName().equals("graphInfobrightDataWriter.grf") // ok, can only work with infobright server && !pathname.getName().equals("graphSystemExecuteWin.grf") // ok, graph for Windows && !pathname.getName().equals("graphLdapReader_Uninett.grf") // ok, invalid server && !pathname.getName().equals("graphSequenceChecker.grf") // ok, is to fail && !pathname.getName().equals("FixedData.grf") // ok, is to fail && !pathname.getName().equals("xpathReaderStates.grf") // ok, is to fail && !pathname.getName().equals("graphDataPolicy.grf") // ok, is to fail && !pathname.getName().equals("conversionDecimal2integer.grf") // ok, is to fail && !pathname.getName().equals("conversionDecimal2long.grf") // ok, is to fail && !pathname.getName().equals("conversionDouble2integer.grf") // ok, is to fail && !pathname.getName().equals("conversionDouble2long.grf") // ok, is to fail && !pathname.getName().equals("conversionLong2integer.grf") // ok, is to fail && !pathname.getName().equals("nativeSortTestGraph.grf") // ok, invalid paths && !pathname.getName().equals("mountainsInformix.grf") // see issue 2550 && !pathname.getName().equals("SystemExecuteWin_EchoFromFile.grf") // graph for windows && !pathname.getName().equals("XLSEncryptedFail.grf") // ok, is to fail && !pathname.getName().equals("XLSXEncryptedFail.grf") // ok, is to fail && !pathname.getName().equals("XLSInvalidFile.grf") // ok, is to fail && !pathname.getName().equals("XLSReaderOrderMappingFail.grf") // ok, is to fail && !pathname.getName().equals("XLSXReaderOrderMappingFail.grf") // ok, is to fail && !pathname.getName().equals("XLSWildcardStrict.grf") // ok, is to fail && !pathname.getName().equals("XLSXWildcardStrict.grf") // ok, is to fail && !pathname.getName().equals("XLSWildcardControlled1.grf") // ok, is to fail && !pathname.getName().equals("XLSXWildcardControlled1.grf") // ok, is to fail && !pathname.getName().equals("XLSWildcardControlled7.grf") // ok, is to fail && !pathname.getName().equals("XLSXWildcardControlled7.grf") // ok, is to fail && !pathname.getName().equals("SSWRITER_MultilineInsertIntoTemplate.grf") // uses graph parameter definition from after-commit.ts && !pathname.getName().equals("SSWRITER_FormatInMetadata.grf") // uses graph parameter definition from after-commit.ts && !pathname.getName().equals("WSC_NamespaceBindingsDefined.grf") // ok, is to fail && !pathname.getName().equals("FailingGraph.grf") // ok, is to fail && !pathname.getName().equals("RunGraph_FailWhenUnderlyingGraphFails.grf") // probably should fail, recheck after added to after-commit.ts && !pathname.getName().equals("DataIntersection_order_check_A.grf") // ok, is to fail && !pathname.getName().equals("DataIntersection_order_check_B.grf") // ok, is to fail && !pathname.getName().equals("UDR_Logging_SFTP_CL1469.grf") // ok, is to fail && !pathname.getName().startsWith("AddressDoctor") //wrong path to db file, try to fix when AD installed on jenkins machines && !pathname.getName().equals("EmailReader_Local.grf") // remove after CL-2167 solved && !pathname.getName().equals("EmailReader_Server.grf") // remove after CLD-3437 solved (or mail.javlin.eu has valid certificate) && !pathname.getName().contains("firebird") // remove after CL-2170 solved && !pathname.getName().startsWith("ListOfRecords_Functions_02_") // remove after CL-2173 solved && !pathname.getName().equals("UDR_FileURL_OneZipMultipleFilesUnspecified.grf") // remove after CL-2174 solved && !pathname.getName().equals("UDR_FileURL_OneZipOneFileUnspecified.grf") // remove after CL-2174 solved && !pathname.getName().startsWith("MapOfRecords_Functions_01_Compiled_") // remove after CL-2175 solved && !pathname.getName().startsWith("MapOfRecords_Functions_01_Interpreted_") // remove after CL-2176 solved && !pathname.getName().equals("manyRecords.grf") // remove after CL-1825 implemented && !pathname.getName().equals("packedDecimal.grf") // remove after CL-1811 solved && !pathname.getName().equals("SimpleZipWrite.grf") // used by ArchiveFlushTest.java, doesn't make sense to run it separately && !pathname.getName().equals("XMLExtract_TKLK_003_Back.grf") // needs output from XMLWriter_LKTW_003.grf && !pathname.getName().equals("testdata_intersection.grf") // remove after CL-1792 solved && !pathname.getName().equals("SQLDataParser_precision_CL2187.grf") // ok, is to fail && !pathname.getName().equals("incrementalReadingDB_explicitMapping.grf") // remove after CL-2239 solved && !pathname.getName().equals("HTTPConnector_get_bodyparams.grf") // ok, is to fail && !pathname.getName().equals("HTTPConnector_get_error_unknownhost.grf") // ok, is to fail && !pathname.getName().equals("HTTPConnector_get_error_unknownprotocol.grf") // ok, is to fail && !pathname.getName().equals("HTTPConnector_get_inputfield.grf") // ok, is to fail && !pathname.getName().equals("HTTPConnector_get_inputfileURL.grf") // ok, is to fail && !pathname.getName().equals("HTTPConnector_get_requestcontent.grf") // ok, is to fail && !pathname.getName().equals("HTTPConnector_post_error_unknownhost.grf") // ok, is to fail && !pathname.getName().equals("HTTPConnector_post_error_unknownprotocol.grf") // ok, is to fail && !pathname.getName().equals("HTTPConnector_inputmapping_null_values.grf") // ok, is to fail && !pathname.getName().equals("HttpConnector_errHandlingNoRedir.grf") // ok, is to fail && !pathname.getName().equals("XMLExtract_fileURL_not_xml.grf") // ok, is to fail && !pathname.getName().equals("XMLExtract_charset_invalid.grf") // ok, is to fail && !pathname.getName().equals("XMLExtract_mappingURL_missing.grf") // ok, is to fail && !pathname.getName().equals("XMLExtract_fileURL_not_exists.grf") // ok, is to fail && !pathname.getName().equals("XMLExtract_charset_not_default_fail.grf") // ok, is to fail && !pathname.getName().equals("RunGraph_differentOutputMetadataFail.grf") // ok, is to fail && !pathname.getName().equals("SandboxOperationHandlerTest.grf") // runs only on server && !pathname.getName().equals("DenormalizerWithoutInputFile.grf") // probably subgraph not supposed to be executed separately && !pathname.getName().equals("BeanWriterReader_employees.grf"); // remove after CL-2474 solved } }); Arrays.sort(graphFiles); for( int j = 0; j < graphFiles.length; j++){ suite.addTest(new ResetTest(EXAMPLE_PATH[i], graphFiles[j], false, false)); suite.addTest(new ResetTest(EXAMPLE_PATH[i], graphFiles[j], true, j == graphFiles.length - 1 ? true : false)); } } return suite; } @Override protected void setUp() throws Exception { super.setUp(); initEngine(); } protected static String getTestName(String basePath, File graphFile, boolean batchMode) { final StringBuilder ret = new StringBuilder(); final String n = graphFile.getName(); int lastDot = n.lastIndexOf('.'); if (lastDot == -1) { ret.append(n); } else { ret.append(n.substring(0, lastDot)); } if (batchMode) { ret.append("-batch"); } else { ret.append("-nobatch"); } return ret.toString(); } protected ResetTest(String basePath, File graphFile, boolean batchMode, boolean cleanup) { super(getTestName(basePath, graphFile, batchMode)); this.basePath = basePath; this.graphFile = graphFile; this.batchMode = batchMode; this.cleanUp = cleanup; } @Override protected void runTest() throws Throwable { final String beseAbsolutePath = new File(basePath).getAbsolutePath().replace('\\', '/'); logger.info("Project dir: " + beseAbsolutePath); logger.info("Analyzing graph " + graphFile.getPath()); logger.info("Batch mode: " + batchMode); final GraphRuntimeContext runtimeContext = new GraphRuntimeContext(); runtimeContext.setUseJMX(false); runtimeContext.setContextURL(FileUtils.getFileURL(basePath)); // absolute path in PROJECT parameter is required for graphs using Derby database runtimeContext.addAdditionalProperty("PROJECT", beseAbsolutePath); if (StringUtils.findString(graphFile.getName(), NEEDS_SCENARIOS_CONNECTION) != -1) { final String connDir = new File(SCENARIOS_RELATIVE_PATH + "conn").getAbsolutePath(); runtimeContext.addAdditionalProperty("CONN_DIR", connDir); logger.info("CONN_DIR set to " + connDir); } if (StringUtils.findString(graphFile.getName(), NEEDS_SCENARIOS_LIB) != -1) {// set LIB_DIR to jdbc drivers directory final String libDir = new File(SCENARIOS_RELATIVE_PATH + "lib").getAbsolutePath(); runtimeContext.addAdditionalProperty("LIB_DIR", libDir); logger.info("LIB_DIR set to " + libDir); } // for scenarios graphs, add the TRANS dir to the classpath if (basePath.contains("cloveretl.test.scenarios")) { runtimeContext.setRuntimeClassPath(new URL[] {FileUtils.getFileURL(FileUtils.appendSlash(beseAbsolutePath) + TRANS_DIR + "/")}); runtimeContext.setCompileClassPath(runtimeContext.getRuntimeClassPath()); } runtimeContext.setBatchMode(batchMode); final TransformationGraph graph = TransformationGraphXMLReaderWriter.loadGraph(new FileInputStream(graphFile), runtimeContext); try { graph.setDebugMode(false); EngineInitializer.initGraph(graph); for (int i = 0; i < 3; i++) { final Future<Result> futureResult = runGraph.executeGraph(graph, runtimeContext); Result result = Result.N_A; result = futureResult.get(); switch (result) { case FINISHED_OK: // everything O.K. logger.info("Execution of graph successful !"); break; case ABORTED: // execution was ABORTED !! logger.info("Execution of graph failed !"); fail("Execution of graph failed !"); break; default: logger.info("Execution of graph failed !"); fail("Execution of graph failed !"); } } } catch (Throwable e) { throw new IllegalStateException("Error executing grap " + graphFile, e); } finally { if (cleanUp) { cleanupData(); } logger.info("Transformation graph is freeing.\n"); graph.free(); } } private void cleanupData() { for (String outDir : OUT_DIRS) { File outDirFile = new File(basePath, outDir); File[] file = outDirFile.listFiles(new FileFilter() { @Override public boolean accept(File f) { return f.isFile(); } }); for (int i = 0; i < file.length; i++) { final boolean drt = file[i].delete(); if (drt) { logger.info("Cleanup: deleted file " + file[i].getAbsolutePath()); } else { logger.info("Cleanup: error delete file " + file[i].getAbsolutePath()); } } } } }
MINOR: updated accept list git-svn-id: ea4e32a9c087aaafabd002c256df6ce060387585@12866 a09ad3ba-1a0f-0410-b1b9-c67202f10d70
cloveretl.engine/test/org/jetel/graph/ResetTest.java
MINOR: updated accept list
Java
unlicense
29c6c36e1ab197af13dd6b07c5bb666c7b5ea22e
0
tiagox/untref-aydoo-tp-garispe-srojo
package untref.aydoo.tp; import java.util.Date; import java.util.List; public class PromocionExtranjero extends Promocion { private final Double distanciaMinima = 200.0; private final Double descuento = 0.5; public PromocionExtranjero(List<Atraccion> atracciones, Date desde, Date hasta, Coordenada domicilio) { this.atracciones = atracciones; this.desde = desde; this.hasta = hasta; if (!aplicaPromocion(domicilio)) { throw new Error( "La promocion solo es aplicable a los usuarios con domicilio a mas de " + distanciaMinima + " km de las atracciones."); } } private Boolean aplicaPromocion(Coordenada domicilio) { return getDistanciaAtraccionMasCercanaA(domicilio) > this.distanciaMinima; } private Double getDistanciaAtraccionMasCercanaA(Coordenada domicilio) { Double distanciaMinima = domicilio.calcularDistanciaA(this.atracciones .get(0).getUbicacion()); Double distanciaActual = distanciaMinima; for (Atraccion atraccion : this.atracciones) { distanciaActual = domicilio.calcularDistanciaA(atraccion .getUbicacion()); if (distanciaActual < distanciaMinima) { distanciaMinima = distanciaActual; } } return distanciaMinima; } @Override public Double getPrecio() { return super.getPrecio() * this.descuento; } }
src/untref/aydoo/tp/PromocionExtranjero.java
package untref.aydoo.tp; import java.util.Date; import java.util.List; public class PromocionExtranjero extends Promocion { private final Double distanciaMinima = 200.0; private final Double descuento = 0.5; public PromocionExtranjero(List<Atraccion> atracciones, Date desde, Date hasta, Coordenada domicilio) { this.atracciones = atracciones; this.desde = desde; this.hasta = hasta; if (!aplicaPromocion(domicilio)) { throw new Error( "La promocin solo es aplicable a los usuarios con domicilio a ms de " + distanciaMinima + " km de las atracciones."); } } private Boolean aplicaPromocion(Coordenada domicilio) { return getDistanciaAtraccionMasCercanaA(domicilio) > this.distanciaMinima; } private Double getDistanciaAtraccionMasCercanaA(Coordenada domicilio) { Double distanciaMinima = domicilio.calcularDistanciaA(this.atracciones .get(0).getUbicacion()); Double distanciaActual = distanciaMinima; for (Atraccion atraccion : this.atracciones) { distanciaActual = domicilio.calcularDistanciaA(atraccion .getUbicacion()); if (distanciaActual < distanciaMinima) { distanciaMinima = distanciaActual; } } return distanciaMinima; } @Override public Double getPrecio() { return super.getPrecio() * this.descuento; } }
Correccion de caracteres
src/untref/aydoo/tp/PromocionExtranjero.java
Correccion de caracteres
Java
apache-2.0
e7ab51e3b6e707ec08c4f8d92d0a28548948d958
0
subclipse/svnclientadapter
/* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2000 The Apache Software Foundation. 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 end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software develby the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * 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 THE APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.tigris.subversion.svnclientadapter; import java.io.IOException; import java.io.InputStream; /** * not a very efficient implementation for now ... */ public class AnnotateInputStream extends InputStream { private ISVNAnnotations annotations; private int currentLineNumber; private int currentPos; private String currentLine; private int available; public AnnotateInputStream(ISVNAnnotations annotations) { this.annotations = annotations; initialize(); } private void initialize() { currentLine = annotations.getLine(0); currentLineNumber = 0; currentPos = 0; int available = 0; for (int i = 0; i < annotations.size();i++) { available += annotations.getLine(i).length()+1; // +1 for \n } } /* * (non-Javadoc) * @see java.io.InputStream#read() */ public int read() throws IOException { if (currentLineNumber >= annotations.size()) return -1; // end of stream if (currentPos > currentLine.length()) { getNextLine(); if (currentLineNumber >= annotations.size()) return -1; // end of stream } int character; if (currentPos == currentLine.length()) return '\n'; character = currentLine.charAt(currentPos); currentPos++; available--; return character; } private void getNextLine() { currentLineNumber++; currentPos = 0; currentLine = annotations.getLine(currentLineNumber); } /* * (non-Javadoc) * @see java.io.InputStream#available() */ public int available() throws IOException { return available; } /* (non-Javadoc) * @see java.io.InputStream#reset() */ public synchronized void reset() throws IOException { initialize(); } }
src/main/org/tigris/subversion/svnclientadapter/AnnotateInputStream.java
/* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2000 The Apache Software Foundation. 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 end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software develby the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * 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 THE APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.tigris.subversion.svnclientadapter; import java.io.IOException; import java.io.InputStream; /** * not a very efficient implementation for now ... */ public class AnnotateInputStream extends InputStream { private ISVNAnnotations annotations; private int currentLineNumber; private int currentPos; private String currentLine; private int available; public AnnotateInputStream(ISVNAnnotations annotations) { this.annotations = annotations; currentLine = annotations.getLine(0); currentLineNumber = 0; currentPos = 0; int available = 0; for (int i = 0; i < annotations.size();i++) { available += annotations.getLine(i).length()+1; // +1 for \n } } /* * (non-Javadoc) * @see java.io.InputStream#read() */ public int read() throws IOException { if (currentLineNumber >= annotations.size()) return -1; // end of stream if (currentPos > currentLine.length()) { getNextLine(); if (currentLineNumber >= annotations.size()) return -1; // end of stream } int character; if (currentPos == currentLine.length()) return '\n'; character = currentLine.charAt(currentPos); currentPos++; available--; return character; } private void getNextLine() { currentLineNumber++; currentPos = 0; currentLine = annotations.getLine(currentLineNumber); } /* * (non-Javadoc) * @see java.io.InputStream#available() */ public int available() throws IOException { return available; } }
* AnnotateInputStream.java added reset method
src/main/org/tigris/subversion/svnclientadapter/AnnotateInputStream.java
* AnnotateInputStream.java added reset method
Java
apache-2.0
61d11659e3082d27f64337f3a8cd6d69ae60a42a
0
pageseeder/diffx
/* * Copyright 2010-2015 Allette Systems (Australia) * http://www.allette.com.au * * 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.pageseeder.diffx.algorithm; import java.io.IOException; import java.util.concurrent.atomic.AtomicInteger; import org.pageseeder.diffx.action.Operator; import org.pageseeder.diffx.core.DiffAlgorithm; import org.pageseeder.diffx.core.KumarRanganAlgorithm; import org.pageseeder.diffx.format.DiffXFormatter; import org.pageseeder.diffx.handler.FormattingAdapter; import org.pageseeder.diffx.sequence.EventSequence; /** * Performs the diff comparison using an optimized version of the linear space algorithm * of S.Kiran Kumar and C.Pandu Rangan. * * <p>Implementation note: this algorithm effectively detects the correct changes in the * sequences, but suffers from two main problems: * <ul> * <li>When the events are formatted directly from reading the matrix, the XML is not * necessarily well-formed, this occurs mostly when some elements are swapped, because * the closing tags will not necessarily reported in an order that allows the XML to * be well-formed.<br> * Using the {@link org.pageseeder.diffx.format.SmartXMLFormatter} helps in solving the * problem as it maintains a stack of the elements that are being written and actually * ignores the name of the closing element, so all the elements are closed properly. * </li> * </ul> * * <p>For S. Kiran Kumar and C. Pandu Rangan. <i>A linear space algorithm for the LCS problem</i>, * Acta Informatica. Volume 24 , Issue 3 (June 1987); Copyright Springer-Verlag 1987 * * <p>This class reuses portions of code originally written by Mikko Koivisto and Tuomo Saarni. * * <p><a href="http://dblp.uni-trier.de/rec/bibtex/journals/acta/KumarR87"> * http://dblp.uni-trier.de/rec/bibtex/journals/acta/KumarR87</a> * * <p><a href="http://users.utu.fi/~tuiisa/Java/">http://users.utu.fi/~tuiisa/Java/</a> * * @author Christophe Lauret * * @version 0.9.0 * @since 0.6.0 */ public final class DiffXKumarRangan extends DiffXAlgorithmBase { /** * The length of the LCS. */ private int length = -1; /** * Creates a new DiffXAlgorithmBase. * * @param first The first sequence to compare. * @param second The second sequence to compare. */ public DiffXKumarRangan(EventSequence first, EventSequence second) { super(first, second); } /** * Calculates the length of LCS and returns it. * * <p>If the length is calculated already it'll not be calculated repeatedly. * * <p>This algorithm starts from the length of the first sequence as the maximum possible * LCS and reduces the length for every difference with the second sequence. * * <p>The time complexity is O(n(m-p)) and the space complexity is O(n+m). * * @return The length of LCS */ @Override public int length() { if (this.length < 0) { DiffAlgorithm algo = new KumarRanganAlgorithm(); AtomicInteger length = new AtomicInteger(); algo.diff(this.sequence1.events(), this.sequence2.events(), (operator, event) -> { if (operator == Operator.MATCH) length.getAndIncrement(); }); this.length = length.get(); } return this.length; } /** * Writes the diff sequence using the specified formatter. * * @param formatter The formatter that will handle the output. * * @throws IOException If thrown by the formatter. */ @Override public void process(DiffXFormatter formatter) throws IOException { DiffAlgorithm algo = new KumarRanganAlgorithm(); FormattingAdapter adapter = new FormattingAdapter(formatter); algo.diff(this.sequence1.events(), this.sequence2.events(), adapter); } }
src/main/java/org/pageseeder/diffx/algorithm/DiffXKumarRangan.java
/* * Copyright 2010-2015 Allette Systems (Australia) * http://www.allette.com.au * * 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.pageseeder.diffx.algorithm; import java.io.IOException; import java.util.concurrent.atomic.AtomicInteger; import org.pageseeder.diffx.action.Operator; import org.pageseeder.diffx.core.DiffAlgorithm; import org.pageseeder.diffx.core.KumarRanganAlgorithm; import org.pageseeder.diffx.format.DiffXFormatter; import org.pageseeder.diffx.handler.FormattingAdapter; import org.pageseeder.diffx.sequence.EventSequence; /** * Performs the diff comparison using an optimized version of the linear space algorithm * of S.Kiran Kumar and C.Pandu Rangan. * * <p>Implementation note: this algorithm effectively detects the correct changes in the * sequences, but suffers from two main problems: * <ul> * <li>When the events are formatted directly from reading the matrix, the XML is not * necessarily well-formed, this occurs mostly when some elements are swapped, because * the closing tags will not necessarily reported in an order that allows the XML to * be well-formed.<br> * Using the {@link org.pageseeder.diffx.format.SmartXMLFormatter} helps in solving the * problem as it maintains a stack of the elements that are being written and actually * ignores the name of the closing element, so all the elements are closed properly. * </li> * </ul> * * <p>For S. Kiran Kumar and C. Pandu Rangan. <i>A linear space algorithm for the LCS problem</i>, * Acta Informatica. Volume 24 , Issue 3 (June 1987); Copyright Springer-Verlag 1987 * * <p>This class reuses portions of code originally written by Mikko Koivisto and Tuomo Saarni. * * <p><a href="http://dblp.uni-trier.de/rec/bibtex/journals/acta/KumarR87"> * http://dblp.uni-trier.de/rec/bibtex/journals/acta/KumarR87</a> * * <p><a href="http://users.utu.fi/~tuiisa/Java/">http://users.utu.fi/~tuiisa/Java/</a> * * @author Christophe Lauret * @version 9 March 2005 */ public final class DiffXKumarRangan extends DiffXAlgorithmBase { /** * Set to <code>true</code> to show debug info. */ private static final boolean DEBUG = false; // state variables ---------------------------------------------------------------------------- // Global integer arrays needed in the computation of the LCS private int[] R1, R2; private int[] LL, LL1, LL2; /** * Global integer variable needed in the computation of the LCS. */ private int R; /** * Global integer variable needed in the computation of the LCS. */ private int S; /** * A counter for the index of the second sequence when generating the diff. */ private int iSeq2 = 0; /** * The length of the LCS. */ private int length = -1; /** * The formatter to use for the write diff function. */ private DiffXFormatter df = null; // constructor -------------------------------------------------------------------------------- /** * Creates a new DiffXAlgorithmBase. * * @param first The first sequence to compare. * @param second The second sequence to compare. */ public DiffXKumarRangan(EventSequence first, EventSequence second) { super(first, second); } // methods ------------------------------------------------------------------------------------ /** * Calculates the length of LCS and returns it. * * <p>If the length is calculated already it'll not be calculated repeatedly. * * <p>This algorithm starts from the length of the first sequence as the maximum possible * LCS and reduces the length for every difference with the second sequence. * * <p>The time complexity is O(n(m-p)) and the space complexity is O(n+m). * * @return The length of LCS */ @Override public int length() { DiffAlgorithm algo = new KumarRanganAlgorithm(); AtomicInteger length = new AtomicInteger(); algo.diff(this.sequence1.events(), this.sequence2.events(), (operator, event) -> { if (operator == Operator.MATCH) length.getAndIncrement(); }); return length.get(); } /** * Writes the diff sequence using the specified formatter. * * @param formatter The formatter that will handle the output. * * @throws IOException If thrown by the formatter. */ @Override public void process(DiffXFormatter formatter) throws IOException { DiffAlgorithm algo = new KumarRanganAlgorithm(); FormattingAdapter adapter = new FormattingAdapter(formatter); algo.diff(this.sequence1.events(), this.sequence2.events(), adapter); } }
Remove used variables
src/main/java/org/pageseeder/diffx/algorithm/DiffXKumarRangan.java
Remove used variables
Java
apache-2.0
16fd2d49a1bbb847554c7cbbcfef4e783de618a8
0
cbeyls/fosdem-companion-android
package be.digitalia.fosdem.activities; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.app.Dialog; import android.app.SearchManager; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.drawable.Animatable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.nfc.NdefRecord; import android.os.Build; import android.os.Bundle; import android.text.format.DateUtils; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; import androidx.annotation.IdRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.SearchView; import androidx.appcompat.widget.Toolbar; import androidx.browser.customtabs.CustomTabsIntent; import androidx.core.content.ContextCompat; import androidx.core.view.GravityCompat; import androidx.core.view.ViewCompat; import androidx.drawerlayout.widget.DrawerLayout; import androidx.fragment.app.DialogFragment; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import androidx.lifecycle.Observer; import be.digitalia.fosdem.BuildConfig; import be.digitalia.fosdem.R; import be.digitalia.fosdem.api.FosdemApi; import be.digitalia.fosdem.api.FosdemUrls; import be.digitalia.fosdem.db.AppDatabase; import be.digitalia.fosdem.fragments.*; import be.digitalia.fosdem.livedata.SingleEvent; import be.digitalia.fosdem.model.DownloadScheduleResult; import be.digitalia.fosdem.utils.NfcUtils; import com.google.android.material.navigation.NavigationView; import com.google.android.material.snackbar.Snackbar; /** * Main entry point of the application. Allows to switch between section fragments and update the database. * * @author Christophe Beyls */ public class MainActivity extends AppCompatActivity implements NfcUtils.CreateNfcAppDataCallback { public static final String ACTION_SHORTCUT_BOOKMARKS = BuildConfig.APPLICATION_ID + ".intent.action.SHORTCUT_BOOKMARKS"; public static final String ACTION_SHORTCUT_LIVE = BuildConfig.APPLICATION_ID + ".intent.action.SHORTCUT_LIVE"; private enum Section { TRACKS(R.id.menu_tracks, true, true) { @Override public Fragment createFragment() { return new TracksFragment(); } }, BOOKMARKS(R.id.menu_bookmarks, false, false) { @Override public Fragment createFragment() { return new BookmarksListFragment(); } }, LIVE(R.id.menu_live, true, false) { @Override public Fragment createFragment() { return new LiveFragment(); } }, SPEAKERS(R.id.menu_speakers, false, false) { @Override public Fragment createFragment() { return new PersonsListFragment(); } }, MAP(R.id.menu_map, false, false) { @Override public Fragment createFragment() { return new MapFragment(); } }; private final int menuItemId; private final boolean extendsAppBar; private final boolean keep; Section(@IdRes int menuItemId, boolean extendsAppBar, boolean keep) { this.menuItemId = menuItemId; this.extendsAppBar = extendsAppBar; this.keep = keep; } @IdRes public int getMenuItemId() { return menuItemId; } public abstract Fragment createFragment(); public boolean extendsAppBar() { return extendsAppBar; } public boolean shouldKeep() { return keep; } @Nullable public static Section fromMenuItemId(@IdRes int menuItemId) { for (Section section : Section.values()) { if (section.menuItemId == menuItemId) { return section; } } return null; } } private static final long DATABASE_VALIDITY_DURATION = DateUtils.DAY_IN_MILLIS; private static final long DOWNLOAD_REMINDER_SNOOZE_DURATION = DateUtils.DAY_IN_MILLIS; private static final String PREF_LAST_DOWNLOAD_REMINDER_TIME = "last_download_reminder_time"; private static final String LAST_UPDATE_DATE_FORMAT = "d MMM yyyy kk:mm:ss"; private Toolbar toolbar; // Main menu Section currentSection; MenuItem pendingNavigationMenuItem = null; DrawerLayout drawerLayout; private ActionBarDrawerToggle drawerToggle; View mainMenu; private NavigationView navigationView; private TextView lastUpdateTextView; private MenuItem searchMenuItem; private final Observer<SingleEvent<DownloadScheduleResult>> scheduleDownloadResultObserver = singleEvent -> { final DownloadScheduleResult result = singleEvent.consume(); if (result == null) { return; } String message; if (result.isError()) { message = getString(R.string.schedule_loading_error); } else if (result.isUpToDate()) { message = getString(R.string.events_download_up_to_date); } else { int eventsCount = result.getEventsCount(); if (eventsCount == 0) { message = getString(R.string.events_download_empty); } else { message = getResources().getQuantityString(R.plurals.events_download_completed, eventsCount, eventsCount); } } Snackbar.make(findViewById(R.id.content), message, Snackbar.LENGTH_LONG).show(); }; public static class DownloadScheduleReminderDialogFragment extends DialogFragment { @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { return new AlertDialog.Builder(getContext()) .setTitle(R.string.download_reminder_title) .setMessage(R.string.download_reminder_message) .setPositiveButton(android.R.string.ok, (dialog, which) -> FosdemApi.downloadSchedule(getContext())) .setNegativeButton(android.R.string.cancel, null) .create(); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); // Progress bar setup final ProgressBar progressBar = findViewById(R.id.progress); FosdemApi.getDownloadScheduleProgress().observe(this, progressInteger -> { int progress = progressInteger; if (progress != 100) { // Visible if (progressBar.getVisibility() == View.GONE) { progressBar.clearAnimation(); progressBar.setVisibility(View.VISIBLE); } if (progress == -1) { progressBar.setIndeterminate(true); } else { progressBar.setIndeterminate(false); progressBar.setProgress(progress); } } else { // Invisible if (progressBar.getVisibility() == View.VISIBLE) { // Hide the progress bar with a fill and fade out animation progressBar.setIndeterminate(false); progressBar.setProgress(100); progressBar.animate() .alpha(0f) .withLayer() .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { progressBar.setVisibility(View.GONE); progressBar.setAlpha(1f); } }); } } }); // Monitor the schedule download result FosdemApi.getDownloadScheduleResult().observe(this, scheduleDownloadResultObserver); // Setup drawer layout getSupportActionBar().setDisplayHomeAsUpEnabled(true); drawerLayout = findViewById(R.id.drawer_layout); drawerLayout.setDrawerShadow(ContextCompat.getDrawable(this, R.drawable.drawer_shadow_start), GravityCompat.START); drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.main_menu, R.string.close_menu) { @Override public void onDrawerStateChanged(int newState) { super.onDrawerStateChanged(newState); if (newState == DrawerLayout.STATE_DRAGGING) { pendingNavigationMenuItem = null; } } @Override public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); // Make keypad navigation easier mainMenu.requestFocus(); } @Override public void onDrawerClosed(View drawerView) { super.onDrawerClosed(drawerView); if (pendingNavigationMenuItem != null) { handleNavigationMenuItem(pendingNavigationMenuItem); pendingNavigationMenuItem = null; } } }; drawerToggle.setDrawerIndicatorEnabled(true); drawerLayout.addDrawerListener(drawerToggle); // Disable drawerLayout focus to allow trackball navigation. // We handle the drawer closing on back press ourselves. drawerLayout.setFocusable(false); // Setup Main menu mainMenu = findViewById(R.id.main_menu); // Forward window insets to NavigationView ViewCompat.setOnApplyWindowInsetsListener(mainMenu, (v, insets) -> insets); navigationView = findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(menuItem -> { pendingNavigationMenuItem = menuItem; drawerLayout.closeDrawer(mainMenu); return true; }); // Last update date, below the list lastUpdateTextView = mainMenu.findViewById(R.id.last_update); AppDatabase.getInstance(this).getScheduleDao().getLastUpdateTime() .observe(this, lastUpdateTimeObserver); if (savedInstanceState == null) { // Select initial section currentSection = Section.TRACKS; String action = getIntent().getAction(); if (action != null) { switch (action) { case ACTION_SHORTCUT_BOOKMARKS: currentSection = Section.BOOKMARKS; break; case ACTION_SHORTCUT_LIVE: currentSection = Section.LIVE; break; } } navigationView.setCheckedItem(currentSection.getMenuItemId()); getSupportFragmentManager().beginTransaction() .add(R.id.content, currentSection.createFragment(), currentSection.name()) .commit(); } NfcUtils.setAppDataPushMessageCallbackIfAvailable(this, this); } private void updateActionBar(@NonNull Section section, @NonNull MenuItem menuItem) { setTitle(menuItem.getTitle()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { toolbar.setElevation(section.extendsAppBar() ? 0f : getResources().getDimension(R.dimen.toolbar_elevation)); } } private final Observer<Long> lastUpdateTimeObserver = new Observer<Long>() { @Override public void onChanged(Long lastUpdateTime) { lastUpdateTextView.setText(getString(R.string.last_update, (lastUpdateTime == -1L) ? getString(R.string.never) : android.text.format.DateFormat.format(LAST_UPDATE_DATE_FORMAT, lastUpdateTime))); } }; @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); drawerToggle.syncState(); // Restore current section from NavigationView final MenuItem menuItem = navigationView.getCheckedItem(); if (menuItem != null) { if (currentSection == null) { currentSection = Section.fromMenuItemId(menuItem.getItemId()); } if (currentSection != null) { updateActionBar(currentSection, menuItem); } } } @Override public void onBackPressed() { if (drawerLayout.isDrawerOpen(mainMenu)) { drawerLayout.closeDrawer(mainMenu); } else { super.onBackPressed(); } } @Override protected void onSaveInstanceState(Bundle outState) { // Ensure no fragment transaction attempt will occur after onSaveInstanceState() if (pendingNavigationMenuItem != null) { pendingNavigationMenuItem = null; if (currentSection != null) { navigationView.setCheckedItem(currentSection.getMenuItemId()); } } super.onSaveInstanceState(outState); } @Override protected void onStart() { super.onStart(); // Download reminder long now = System.currentTimeMillis(); Long timeValue = AppDatabase.getInstance(this).getScheduleDao().getLastUpdateTime().getValue(); long time = (timeValue == null) ? -1L : timeValue; if ((time == -1L) || (time < (now - DATABASE_VALIDITY_DURATION))) { SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE); time = prefs.getLong(PREF_LAST_DOWNLOAD_REMINDER_TIME, -1L); if ((time == -1L) || (time < (now - DOWNLOAD_REMINDER_SNOOZE_DURATION))) { prefs.edit() .putLong(PREF_LAST_DOWNLOAD_REMINDER_TIME, now) .apply(); FragmentManager fm = getSupportFragmentManager(); if (fm.findFragmentByTag("download_reminder") == null) { new DownloadScheduleReminderDialogFragment().show(fm, "download_reminder"); } } } } @Override protected void onStop() { if ((searchMenuItem != null) && searchMenuItem.isActionViewExpanded()) { searchMenuItem.collapseActionView(); } super.onStop(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); MenuItem searchMenuItem = menu.findItem(R.id.search); this.searchMenuItem = searchMenuItem; searchMenuItem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() { @Override public boolean onMenuItemActionExpand(MenuItem item) { return true; } @Override public boolean onMenuItemActionCollapse(MenuItem item) { // Workaround for disappearing menu items bug supportInvalidateOptionsMenu(); return true; } }); // Associate searchable configuration with the SearchView SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); SearchView searchView = (SearchView) searchMenuItem.getActionView(); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Will close the drawer if the home button is pressed if (drawerToggle.onOptionsItemSelected(item)) { return true; } switch (item.getItemId()) { case R.id.refresh: Drawable icon = item.getIcon(); if (icon instanceof Animatable) { // Hack: reset the icon to make sure the MenuItem will redraw itself properly item.setIcon(icon); ((Animatable) icon).start(); } FosdemApi.downloadSchedule(this); return true; } return false; } // MAIN MENU void handleNavigationMenuItem(@NonNull MenuItem menuItem) { final int menuItemId = menuItem.getItemId(); final Section section = Section.fromMenuItemId(menuItemId); if (section != null) { selectMenuSection(section, menuItem); } else { switch (menuItemId) { case R.id.menu_settings: startActivity(new Intent(MainActivity.this, SettingsActivity.class)); overridePendingTransition(R.anim.slide_in_right, R.anim.partial_zoom_out); break; case R.id.menu_volunteer: try { new CustomTabsIntent.Builder() .setToolbarColor(ContextCompat.getColor(this, R.color.color_primary)) .setShowTitle(true) .build() .launchUrl(this, Uri.parse(FosdemUrls.getVolunteer())); } catch (ActivityNotFoundException ignore) { } break; } } } void selectMenuSection(@NonNull Section section, @NonNull MenuItem menuItem) { if (section != currentSection) { // Switch to new section FragmentManager fm = getSupportFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); Fragment f = fm.findFragmentById(R.id.content); if (f != null) { if (currentSection.shouldKeep()) { ft.detach(f); } else { ft.remove(f); } } if (section.shouldKeep() && ((f = fm.findFragmentByTag(section.name())) != null)) { ft.attach(f); } else { ft.add(R.id.content, section.createFragment(), section.name()); } ft.commit(); currentSection = section; updateActionBar(section, menuItem); } } @Nullable @Override public NdefRecord createNfcAppData() { // Delegate to the currently displayed fragment if it provides NFC data Fragment f = getSupportFragmentManager().findFragmentById(R.id.content); if (f instanceof NfcUtils.CreateNfcAppDataCallback) { return ((NfcUtils.CreateNfcAppDataCallback) f).createNfcAppData(); } return null; } }
app/src/main/java/be/digitalia/fosdem/activities/MainActivity.java
package be.digitalia.fosdem.activities; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.app.Dialog; import android.app.SearchManager; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.drawable.Animatable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.nfc.NdefRecord; import android.os.Build; import android.os.Bundle; import android.text.format.DateUtils; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; import androidx.annotation.IdRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.SearchView; import androidx.appcompat.widget.Toolbar; import androidx.browser.customtabs.CustomTabsIntent; import androidx.core.content.ContextCompat; import androidx.core.view.GravityCompat; import androidx.core.view.ViewCompat; import androidx.drawerlayout.widget.DrawerLayout; import androidx.fragment.app.DialogFragment; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import androidx.lifecycle.Observer; import be.digitalia.fosdem.BuildConfig; import be.digitalia.fosdem.R; import be.digitalia.fosdem.api.FosdemApi; import be.digitalia.fosdem.api.FosdemUrls; import be.digitalia.fosdem.db.AppDatabase; import be.digitalia.fosdem.fragments.*; import be.digitalia.fosdem.livedata.SingleEvent; import be.digitalia.fosdem.model.DownloadScheduleResult; import be.digitalia.fosdem.utils.NfcUtils; import com.google.android.material.navigation.NavigationView; import com.google.android.material.snackbar.Snackbar; /** * Main entry point of the application. Allows to switch between section fragments and update the database. * * @author Christophe Beyls */ public class MainActivity extends AppCompatActivity implements NfcUtils.CreateNfcAppDataCallback { public static final String ACTION_SHORTCUT_BOOKMARKS = BuildConfig.APPLICATION_ID + ".intent.action.SHORTCUT_BOOKMARKS"; public static final String ACTION_SHORTCUT_LIVE = BuildConfig.APPLICATION_ID + ".intent.action.SHORTCUT_LIVE"; private enum Section { TRACKS(R.id.menu_tracks, true, true) { @Override public Fragment createFragment() { return new TracksFragment(); } }, BOOKMARKS(R.id.menu_bookmarks, false, false) { @Override public Fragment createFragment() { return new BookmarksListFragment(); } }, LIVE(R.id.menu_live, true, false) { @Override public Fragment createFragment() { return new LiveFragment(); } }, SPEAKERS(R.id.menu_speakers, false, false) { @Override public Fragment createFragment() { return new PersonsListFragment(); } }, MAP(R.id.menu_map, false, false) { @Override public Fragment createFragment() { return new MapFragment(); } }; private final int menuItemId; private final boolean extendsAppBar; private final boolean keep; Section(@IdRes int menuItemId, boolean extendsAppBar, boolean keep) { this.menuItemId = menuItemId; this.extendsAppBar = extendsAppBar; this.keep = keep; } @IdRes public int getMenuItemId() { return menuItemId; } public abstract Fragment createFragment(); public boolean extendsAppBar() { return extendsAppBar; } public boolean shouldKeep() { return keep; } @Nullable public static Section fromMenuItemId(@IdRes int menuItemId) { for (Section section : Section.values()) { if (section.menuItemId == menuItemId) { return section; } } return null; } } private static final long DATABASE_VALIDITY_DURATION = DateUtils.DAY_IN_MILLIS; private static final long DOWNLOAD_REMINDER_SNOOZE_DURATION = DateUtils.DAY_IN_MILLIS; private static final String PREF_LAST_DOWNLOAD_REMINDER_TIME = "last_download_reminder_time"; private static final String LAST_UPDATE_DATE_FORMAT = "d MMM yyyy kk:mm:ss"; private Toolbar toolbar; // Main menu Section currentSection; MenuItem pendingNavigationMenuItem = null; DrawerLayout drawerLayout; private ActionBarDrawerToggle drawerToggle; View mainMenu; private NavigationView navigationView; private TextView lastUpdateTextView; private MenuItem searchMenuItem; private final Observer<SingleEvent<DownloadScheduleResult>> scheduleDownloadResultObserver = singleEvent -> { final DownloadScheduleResult result = singleEvent.consume(); if (result == null) { return; } String message; if (result.isError()) { message = getString(R.string.schedule_loading_error); } else if (result.isUpToDate()) { message = getString(R.string.events_download_up_to_date); } else { int eventsCount = result.getEventsCount(); if (eventsCount == 0) { message = getString(R.string.events_download_empty); } else { message = getResources().getQuantityString(R.plurals.events_download_completed, eventsCount, eventsCount); } } Snackbar.make(findViewById(R.id.content), message, Snackbar.LENGTH_LONG).show(); }; public static class DownloadScheduleReminderDialogFragment extends DialogFragment { @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { return new AlertDialog.Builder(getContext()) .setTitle(R.string.download_reminder_title) .setMessage(R.string.download_reminder_message) .setPositiveButton(android.R.string.ok, (dialog, which) -> FosdemApi.downloadSchedule(getContext())) .setNegativeButton(android.R.string.cancel, null) .create(); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); // Progress bar setup final ProgressBar progressBar = findViewById(R.id.progress); FosdemApi.getDownloadScheduleProgress().observe(this, progressInteger -> { int progress = progressInteger; if (progress != 100) { // Visible if (progressBar.getVisibility() == View.GONE) { progressBar.clearAnimation(); progressBar.setVisibility(View.VISIBLE); } if (progress == -1) { progressBar.setIndeterminate(true); } else { progressBar.setIndeterminate(false); progressBar.setProgress(progress); } } else { // Invisible if (progressBar.getVisibility() == View.VISIBLE) { // Hide the progress bar with a fill and fade out animation progressBar.setIndeterminate(false); progressBar.setProgress(100); progressBar.animate() .alpha(0f) .withLayer() .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { progressBar.setVisibility(View.GONE); progressBar.setAlpha(1f); } }); } } }); // Monitor the schedule download result FosdemApi.getDownloadScheduleResult().observe(this, scheduleDownloadResultObserver); // Setup drawer layout getSupportActionBar().setDisplayHomeAsUpEnabled(true); drawerLayout = findViewById(R.id.drawer_layout); drawerLayout.setDrawerShadow(ContextCompat.getDrawable(this, R.drawable.drawer_shadow_start), GravityCompat.START); drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.main_menu, R.string.close_menu) { @Override public void onDrawerStateChanged(int newState) { super.onDrawerStateChanged(newState); if (newState == DrawerLayout.STATE_DRAGGING) { pendingNavigationMenuItem = null; } } @Override public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); // Make keypad navigation easier mainMenu.requestFocus(); } @Override public void onDrawerClosed(View drawerView) { super.onDrawerClosed(drawerView); if (pendingNavigationMenuItem != null) { handleNavigationMenuItem(pendingNavigationMenuItem); pendingNavigationMenuItem = null; } } }; drawerToggle.setDrawerIndicatorEnabled(true); drawerLayout.addDrawerListener(drawerToggle); // Disable drawerLayout focus to allow trackball navigation. // We handle the drawer closing on back press ourselves. drawerLayout.setFocusable(false); // Setup Main menu mainMenu = findViewById(R.id.main_menu); // Forward window insets to NavigationView ViewCompat.setOnApplyWindowInsetsListener(mainMenu, (v, insets) -> insets); navigationView = findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(menuItem -> { pendingNavigationMenuItem = menuItem; drawerLayout.closeDrawer(mainMenu); return true; }); // Last update date, below the list lastUpdateTextView = mainMenu.findViewById(R.id.last_update); AppDatabase.getInstance(this).getScheduleDao().getLastUpdateTime() .observe(this, lastUpdateTimeObserver); if (savedInstanceState == null) { // Select initial section currentSection = Section.TRACKS; String action = getIntent().getAction(); if (action != null) { switch (action) { case ACTION_SHORTCUT_BOOKMARKS: currentSection = Section.BOOKMARKS; break; case ACTION_SHORTCUT_LIVE: currentSection = Section.LIVE; break; } } navigationView.setCheckedItem(currentSection.getMenuItemId()); getSupportFragmentManager().beginTransaction() .add(R.id.content, currentSection.createFragment(), currentSection.name()) .commit(); } NfcUtils.setAppDataPushMessageCallbackIfAvailable(this, this); } private void updateActionBar(@NonNull Section section, @NonNull MenuItem menuItem) { setTitle(menuItem.getTitle()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { toolbar.setElevation(section.extendsAppBar() ? 0f : getResources().getDimension(R.dimen.toolbar_elevation)); } } private final Observer<Long> lastUpdateTimeObserver = new Observer<Long>() { @Override public void onChanged(Long lastUpdateTime) { lastUpdateTextView.setText(getString(R.string.last_update, (lastUpdateTime == -1L) ? getString(R.string.never) : android.text.format.DateFormat.format(LAST_UPDATE_DATE_FORMAT, lastUpdateTime))); } }; @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); drawerToggle.syncState(); // Restore current section from NavigationView final MenuItem menuItem = navigationView.getCheckedItem(); if (menuItem != null) { if (currentSection == null) { currentSection = Section.fromMenuItemId(menuItem.getItemId()); } if (currentSection != null) { updateActionBar(currentSection, menuItem); } } } @Override public void onBackPressed() { if (drawerLayout.isDrawerOpen(mainMenu)) { drawerLayout.closeDrawer(mainMenu); } else { super.onBackPressed(); } } @Override protected void onSaveInstanceState(Bundle outState) { // Ensure no fragment transaction attempt will occur after onSaveInstanceState() if (pendingNavigationMenuItem != null) { pendingNavigationMenuItem = null; if (currentSection != null) { navigationView.setCheckedItem(currentSection.getMenuItemId()); } } super.onSaveInstanceState(outState); } @Override protected void onStart() { super.onStart(); // Download reminder long now = System.currentTimeMillis(); Long timeValue = AppDatabase.getInstance(this).getScheduleDao().getLastUpdateTime().getValue(); long time = (timeValue == null) ? -1L : timeValue; if ((time == -1L) || (time < (now - DATABASE_VALIDITY_DURATION))) { SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE); time = prefs.getLong(PREF_LAST_DOWNLOAD_REMINDER_TIME, -1L); if ((time == -1L) || (time < (now - DOWNLOAD_REMINDER_SNOOZE_DURATION))) { prefs.edit() .putLong(PREF_LAST_DOWNLOAD_REMINDER_TIME, now) .apply(); FragmentManager fm = getSupportFragmentManager(); if (fm.findFragmentByTag("download_reminder") == null) { new DownloadScheduleReminderDialogFragment().show(fm, "download_reminder"); } } } } @Override protected void onStop() { if ((searchMenuItem != null) && searchMenuItem.isActionViewExpanded()) { searchMenuItem.collapseActionView(); } super.onStop(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); MenuItem searchMenuItem = menu.findItem(R.id.search); this.searchMenuItem = searchMenuItem; // Associate searchable configuration with the SearchView SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); SearchView searchView = (SearchView) searchMenuItem.getActionView(); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Will close the drawer if the home button is pressed if (drawerToggle.onOptionsItemSelected(item)) { return true; } switch (item.getItemId()) { case R.id.refresh: Drawable icon = item.getIcon(); if (icon instanceof Animatable) { // Hack: reset the icon to make sure the MenuItem will redraw itself properly item.setIcon(icon); ((Animatable) icon).start(); } FosdemApi.downloadSchedule(this); return true; } return false; } // MAIN MENU void handleNavigationMenuItem(@NonNull MenuItem menuItem) { final int menuItemId = menuItem.getItemId(); final Section section = Section.fromMenuItemId(menuItemId); if (section != null) { selectMenuSection(section, menuItem); } else { switch (menuItemId) { case R.id.menu_settings: startActivity(new Intent(MainActivity.this, SettingsActivity.class)); overridePendingTransition(R.anim.slide_in_right, R.anim.partial_zoom_out); break; case R.id.menu_volunteer: try { new CustomTabsIntent.Builder() .setToolbarColor(ContextCompat.getColor(this, R.color.color_primary)) .setShowTitle(true) .build() .launchUrl(this, Uri.parse(FosdemUrls.getVolunteer())); } catch (ActivityNotFoundException ignore) { } break; } } } void selectMenuSection(@NonNull Section section, @NonNull MenuItem menuItem) { if (section != currentSection) { // Switch to new section FragmentManager fm = getSupportFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); Fragment f = fm.findFragmentById(R.id.content); if (f != null) { if (currentSection.shouldKeep()) { ft.detach(f); } else { ft.remove(f); } } if (section.shouldKeep() && ((f = fm.findFragmentByTag(section.name())) != null)) { ft.attach(f); } else { ft.add(R.id.content, section.createFragment(), section.name()); } ft.commit(); currentSection = section; updateActionBar(section, menuItem); } } @Nullable @Override public NdefRecord createNfcAppData() { // Delegate to the currently displayed fragment if it provides NFC data Fragment f = getSupportFragmentManager().findFragmentById(R.id.content); if (f instanceof NfcUtils.CreateNfcAppDataCallback) { return ((NfcUtils.CreateNfcAppDataCallback) f).createNfcAppData(); } return null; } }
Implement workaround for disappearing menu items bug, fixes #47
app/src/main/java/be/digitalia/fosdem/activities/MainActivity.java
Implement workaround for disappearing menu items bug, fixes #47
Java
apache-2.0
5fde65fc4231ec2b47a89860f014fb8fff5cfed6
0
nanata1115/pentaho-kettle,nicoben/pentaho-kettle,aminmkhan/pentaho-kettle,alina-ipatina/pentaho-kettle,kurtwalker/pentaho-kettle,wseyler/pentaho-kettle,rmansoor/pentaho-kettle,codek/pentaho-kettle,ivanpogodin/pentaho-kettle,GauravAshara/pentaho-kettle,ddiroma/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,ddiroma/pentaho-kettle,eayoungs/pentaho-kettle,HiromuHota/pentaho-kettle,skofra0/pentaho-kettle,eayoungs/pentaho-kettle,lgrill-pentaho/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,stepanovdg/pentaho-kettle,ivanpogodin/pentaho-kettle,emartin-pentaho/pentaho-kettle,Advent51/pentaho-kettle,jbrant/pentaho-kettle,kurtwalker/pentaho-kettle,stevewillcock/pentaho-kettle,brosander/pentaho-kettle,bmorrise/pentaho-kettle,SergeyTravin/pentaho-kettle,mkambol/pentaho-kettle,EcoleKeine/pentaho-kettle,pentaho/pentaho-kettle,cjsonger/pentaho-kettle,zlcnju/kettle,SergeyTravin/pentaho-kettle,emartin-pentaho/pentaho-kettle,matrix-stone/pentaho-kettle,mkambol/pentaho-kettle,nantunes/pentaho-kettle,mattyb149/pentaho-kettle,ivanpogodin/pentaho-kettle,gretchiemoran/pentaho-kettle,mattyb149/pentaho-kettle,codek/pentaho-kettle,yshakhau/pentaho-kettle,denisprotopopov/pentaho-kettle,pminutillo/pentaho-kettle,wseyler/pentaho-kettle,rmansoor/pentaho-kettle,pentaho/pentaho-kettle,eayoungs/pentaho-kettle,tmcsantos/pentaho-kettle,lgrill-pentaho/pentaho-kettle,EcoleKeine/pentaho-kettle,ccaspanello/pentaho-kettle,rfellows/pentaho-kettle,mbatchelor/pentaho-kettle,DFieldFL/pentaho-kettle,wseyler/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,graimundo/pentaho-kettle,YuryBY/pentaho-kettle,Advent51/pentaho-kettle,mbatchelor/pentaho-kettle,alina-ipatina/pentaho-kettle,matrix-stone/pentaho-kettle,pedrofvteixeira/pentaho-kettle,ViswesvarSekar/pentaho-kettle,sajeetharan/pentaho-kettle,stepanovdg/pentaho-kettle,e-cuellar/pentaho-kettle,marcoslarsen/pentaho-kettle,MikhailHubanau/pentaho-kettle,akhayrutdinov/pentaho-kettle,nantunes/pentaho-kettle,nanata1115/pentaho-kettle,matthewtckr/pentaho-kettle,zlcnju/kettle,rmansoor/pentaho-kettle,pminutillo/pentaho-kettle,hudak/pentaho-kettle,aminmkhan/pentaho-kettle,andrei-viaryshka/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,YuryBY/pentaho-kettle,ccaspanello/pentaho-kettle,stevewillcock/pentaho-kettle,mbatchelor/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,pymjer/pentaho-kettle,marcoslarsen/pentaho-kettle,GauravAshara/pentaho-kettle,bmorrise/pentaho-kettle,HiromuHota/pentaho-kettle,pymjer/pentaho-kettle,matrix-stone/pentaho-kettle,ma459006574/pentaho-kettle,ivanpogodin/pentaho-kettle,rmansoor/pentaho-kettle,ddiroma/pentaho-kettle,akhayrutdinov/pentaho-kettle,pminutillo/pentaho-kettle,YuryBY/pentaho-kettle,DFieldFL/pentaho-kettle,tkafalas/pentaho-kettle,ViswesvarSekar/pentaho-kettle,pedrofvteixeira/pentaho-kettle,dkincade/pentaho-kettle,EcoleKeine/pentaho-kettle,e-cuellar/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,emartin-pentaho/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,andrei-viaryshka/pentaho-kettle,airy-ict/pentaho-kettle,roboguy/pentaho-kettle,marcoslarsen/pentaho-kettle,flbrino/pentaho-kettle,stevewillcock/pentaho-kettle,codek/pentaho-kettle,YuryBY/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,lgrill-pentaho/pentaho-kettle,Advent51/pentaho-kettle,drndos/pentaho-kettle,denisprotopopov/pentaho-kettle,cjsonger/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,HiromuHota/pentaho-kettle,graimundo/pentaho-kettle,brosander/pentaho-kettle,dkincade/pentaho-kettle,rfellows/pentaho-kettle,yshakhau/pentaho-kettle,birdtsai/pentaho-kettle,wseyler/pentaho-kettle,kurtwalker/pentaho-kettle,bmorrise/pentaho-kettle,stepanovdg/pentaho-kettle,eayoungs/pentaho-kettle,birdtsai/pentaho-kettle,GauravAshara/pentaho-kettle,CapeSepias/pentaho-kettle,flbrino/pentaho-kettle,sajeetharan/pentaho-kettle,graimundo/pentaho-kettle,roboguy/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,pavel-sakun/pentaho-kettle,emartin-pentaho/pentaho-kettle,pentaho/pentaho-kettle,akhayrutdinov/pentaho-kettle,mbatchelor/pentaho-kettle,yshakhau/pentaho-kettle,mdamour1976/pentaho-kettle,flbrino/pentaho-kettle,graimundo/pentaho-kettle,nicoben/pentaho-kettle,airy-ict/pentaho-kettle,sajeetharan/pentaho-kettle,ma459006574/pentaho-kettle,matthewtckr/pentaho-kettle,CapeSepias/pentaho-kettle,MikhailHubanau/pentaho-kettle,hudak/pentaho-kettle,pentaho/pentaho-kettle,nantunes/pentaho-kettle,akhayrutdinov/pentaho-kettle,brosander/pentaho-kettle,birdtsai/pentaho-kettle,ma459006574/pentaho-kettle,nicoben/pentaho-kettle,cjsonger/pentaho-kettle,skofra0/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,mkambol/pentaho-kettle,zlcnju/kettle,aminmkhan/pentaho-kettle,flbrino/pentaho-kettle,denisprotopopov/pentaho-kettle,tkafalas/pentaho-kettle,tmcsantos/pentaho-kettle,alina-ipatina/pentaho-kettle,zlcnju/kettle,hudak/pentaho-kettle,yshakhau/pentaho-kettle,matrix-stone/pentaho-kettle,stevewillcock/pentaho-kettle,tkafalas/pentaho-kettle,bmorrise/pentaho-kettle,pymjer/pentaho-kettle,gretchiemoran/pentaho-kettle,DFieldFL/pentaho-kettle,GauravAshara/pentaho-kettle,MikhailHubanau/pentaho-kettle,nicoben/pentaho-kettle,ccaspanello/pentaho-kettle,airy-ict/pentaho-kettle,EcoleKeine/pentaho-kettle,matthewtckr/pentaho-kettle,mattyb149/pentaho-kettle,jbrant/pentaho-kettle,ViswesvarSekar/pentaho-kettle,aminmkhan/pentaho-kettle,mdamour1976/pentaho-kettle,CapeSepias/pentaho-kettle,mdamour1976/pentaho-kettle,gretchiemoran/pentaho-kettle,nantunes/pentaho-kettle,rfellows/pentaho-kettle,mkambol/pentaho-kettle,nanata1115/pentaho-kettle,nanata1115/pentaho-kettle,sajeetharan/pentaho-kettle,birdtsai/pentaho-kettle,airy-ict/pentaho-kettle,matthewtckr/pentaho-kettle,ma459006574/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,drndos/pentaho-kettle,drndos/pentaho-kettle,DFieldFL/pentaho-kettle,e-cuellar/pentaho-kettle,Advent51/pentaho-kettle,jbrant/pentaho-kettle,codek/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,lgrill-pentaho/pentaho-kettle,CapeSepias/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,mattyb149/pentaho-kettle,cjsonger/pentaho-kettle,denisprotopopov/pentaho-kettle,drndos/pentaho-kettle,skofra0/pentaho-kettle,gretchiemoran/pentaho-kettle,mdamour1976/pentaho-kettle,marcoslarsen/pentaho-kettle,jbrant/pentaho-kettle,dkincade/pentaho-kettle,dkincade/pentaho-kettle,roboguy/pentaho-kettle,HiromuHota/pentaho-kettle,pedrofvteixeira/pentaho-kettle,skofra0/pentaho-kettle,andrei-viaryshka/pentaho-kettle,stepanovdg/pentaho-kettle,ccaspanello/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,tmcsantos/pentaho-kettle,alina-ipatina/pentaho-kettle,kurtwalker/pentaho-kettle,tmcsantos/pentaho-kettle,pavel-sakun/pentaho-kettle,SergeyTravin/pentaho-kettle,tkafalas/pentaho-kettle,e-cuellar/pentaho-kettle,SergeyTravin/pentaho-kettle,pedrofvteixeira/pentaho-kettle,ddiroma/pentaho-kettle,brosander/pentaho-kettle,roboguy/pentaho-kettle,hudak/pentaho-kettle,pavel-sakun/pentaho-kettle,pminutillo/pentaho-kettle,ViswesvarSekar/pentaho-kettle,pymjer/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,pavel-sakun/pentaho-kettle
/* * Copyright (c) 2007 Pentaho Corporation. All rights reserved. * This software was developed by Pentaho Corporation and is provided under the terms * of the GNU Lesser General Public License, Version 2.1. You may not use * this file except in compliance with the license. If you need a copy of the license, * please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho * Data Integration. The Initial Developer is Pentaho Corporation. * * Software distributed under the GNU Lesser Public License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to * the license for the specific language governing your rights and limitations. */ package org.pentaho.di.core.database; import org.pentaho.di.core.plugins.DatabaseMetaPlugin; /** * Contains Database Connection information through static final members for a PALO database. * These connections are typically custom-made. * That means that reading, writing, etc, is not done through JDBC. * * @author Matt * @since 18-Sep-2007 */ @DatabaseMetaPlugin(type = "PALO", typeDescription = "Palo MOLAP Server") public class PALODatabaseMeta extends GenericDatabaseMeta implements DatabaseInterface { public int[] getAccessTypeList() { return new int[] { DatabaseMeta.TYPE_ACCESS_PLUGIN, }; } public int getDefaultDatabasePort() { return 7777; } public String getDatabaseFactoryName() { return "org.pentaho.di.palo.core.PaloHelper"; } /** * @return true if this is a relational database you can explore. * Return false for SAP, PALO, etc. */ public boolean isExplorable() { return false; } }
src-plugins/kettle-palo-plugin/src/org/pentaho/di/core/database/PALODatabaseMeta.java
/* * Copyright (c) 2007 Pentaho Corporation. All rights reserved. * This software was developed by Pentaho Corporation and is provided under the terms * of the GNU Lesser General Public License, Version 2.1. You may not use * this file except in compliance with the license. If you need a copy of the license, * please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho * Data Integration. The Initial Developer is Pentaho Corporation. * * Software distributed under the GNU Lesser Public License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to * the license for the specific language governing your rights and limitations. */ package org.pentaho.di.core.database; import org.pentaho.di.core.plugins.DatabaseMetaPlugin; /** * Contains Database Connection information through static final members for a PALO database. * These connections are typically custom-made. * That means that reading, writing, etc, is not done through JDBC. * * @author Matt * @since 18-Sep-2007 */ @DatabaseMetaPlugin(type = "PALODatabaseMeta", typeDescription = "Palo MOLAP Server") public class PALODatabaseMeta extends GenericDatabaseMeta implements DatabaseInterface { public int[] getAccessTypeList() { return new int[] { DatabaseMeta.TYPE_ACCESS_PLUGIN, }; } public int getDefaultDatabasePort() { return 7777; } public String getDatabaseFactoryName() { return "org.pentaho.di.palo.core.PaloHelper"; } /** * @return true if this is a relational database you can explore. * Return false for SAP, PALO, etc. */ public boolean isExplorable() { return false; } }
PDI-6596 - Changed type from PALODatabaseMeta to PALO git-svn-id: 51b39fcfd0d3a6ea7caa15377cad4af13b9d2664@15667 5fb7f6ec-07c1-534a-b4ca-9155e429e800
src-plugins/kettle-palo-plugin/src/org/pentaho/di/core/database/PALODatabaseMeta.java
PDI-6596 - Changed type from PALODatabaseMeta to PALO
Java
apache-2.0
c629bb4f66f73b9d5d0d03404eca9ead19de201c
0
openengsb-attic/opencit,openengsb-attic/opencit,openengsb-attic/opencit,openengsb-attic/opencit
/** * Copyright 2010 OpenEngSB Division, Vienna University of Technology * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openengsb.opencit.ui.web.WizardSteps; 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 org.apache.wicket.extensions.wizard.dynamic.DynamicWizardStep; import org.apache.wicket.extensions.wizard.dynamic.IDynamicWizardStep; import org.apache.wicket.markup.html.form.DropDownChoice; import org.apache.wicket.model.IModel; import org.apache.wicket.model.LoadableDetachableModel; import org.apache.wicket.model.Model; import org.apache.wicket.model.ResourceModel; import org.openengsb.core.common.Domain; import org.openengsb.domain.build.BuildDomain; import org.openengsb.domain.deploy.DeployDomain; import org.openengsb.domain.notification.NotificationDomain; import org.openengsb.domain.report.ReportDomain; import org.openengsb.domain.scm.ScmDomain; import org.openengsb.domain.test.TestDomain; import org.openengsb.opencit.core.projectmanager.model.Project; public class DomainSelectionStep extends DynamicWizardStep { private String domainDropDown = ""; private Project project; private Map<String, Class<? extends Domain>> managersMap = new HashMap<String, Class<? extends Domain>>(); public DomainSelectionStep(Project project) { super(new CreateProjectStep(project), new ResourceModel("selectDomain.title"), new ResourceModel("selectDomain.summary"), new Model<Project>(project)); this.project = project; managersMap.put("SCM Domain", ScmDomain.class); managersMap.put("Notification Domain", NotificationDomain.class); managersMap.put("Build Domain", BuildDomain.class); managersMap.put("Test Domain", TestDomain.class); managersMap.put("Deploy Domain", DeployDomain.class); managersMap.put("Report Domain", ReportDomain.class); Map<Class<? extends Domain>, String> services = project.getServices(); Set<String> toRemove = new HashSet<String>(); for (Entry<String, Class<? extends Domain>> entry : managersMap.entrySet()) { if (services.containsKey(entry.getValue())) { toRemove.add(entry.getKey()); } } for (String s : toRemove) { managersMap.remove(s); } domainDropDown = managersMap.keySet().iterator().next(); DropDownChoice<String> descriptorDropDownChoice = initSCMDomains(); add(descriptorDropDownChoice); } private DropDownChoice<String> initSCMDomains() { IModel<List<String>> dropDownModel = new LoadableDetachableModel<List<String>>() { @Override protected List<String> load() { Set<String> domains = new HashSet<String>(managersMap.keySet()); return new ArrayList<String>(domains); } }; DropDownChoice<String> descriptorDropDownChoice = new DropDownChoice<String>("domainDropDown", new IModel<String>() { public String getObject() { return domainDropDown; } public void setObject(String object) { domainDropDown = object; } public void detach() { } }, dropDownModel); return descriptorDropDownChoice; } @Override public boolean isLastStep() { return false; } @Override public IDynamicWizardStep next() { Class<? extends Domain> domain = managersMap.get(domainDropDown); return new SelectServiceStep(project, domain); } @Override public boolean isComplete() { return domainDropDown != null && !"".equals(domainDropDown); } }
ui/web/src/main/java/org/openengsb/opencit/ui/web/WizardSteps/DomainSelectionStep.java
/** * Copyright 2010 OpenEngSB Division, Vienna University of Technology * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openengsb.opencit.ui.web.WizardSteps; 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.wicket.extensions.wizard.dynamic.DynamicWizardStep; import org.apache.wicket.extensions.wizard.dynamic.IDynamicWizardStep; import org.apache.wicket.markup.html.form.DropDownChoice; import org.apache.wicket.markup.html.form.IChoiceRenderer; import org.apache.wicket.model.IModel; import org.apache.wicket.model.LoadableDetachableModel; import org.apache.wicket.model.Model; import org.apache.wicket.model.ResourceModel; import org.openengsb.core.common.Domain; import org.openengsb.domain.build.BuildDomain; import org.openengsb.domain.deploy.DeployDomain; import org.openengsb.domain.notification.NotificationDomain; import org.openengsb.domain.report.ReportDomain; import org.openengsb.domain.scm.ScmDomain; import org.openengsb.domain.test.TestDomain; import org.openengsb.opencit.core.projectmanager.model.Project; public class DomainSelectionStep extends DynamicWizardStep { private String domainDropDown = ""; private Project project; private Map<String, Class<? extends Domain>> managersMap = new HashMap<String, Class<? extends Domain>>(); public DomainSelectionStep(Project project) { super(new CreateProjectStep(project), new ResourceModel("selectDomain.title"), new ResourceModel("selectDomain.summary"), new Model<Project>(project)); this.project = project; managersMap.put("SCM Domain", ScmDomain.class); managersMap.put("Notification Domain", NotificationDomain.class); managersMap.put("Build Domain", BuildDomain.class); managersMap.put("Test Domain", TestDomain.class); managersMap.put("Deploy Domain", DeployDomain.class); managersMap.put("Report Domain", ReportDomain.class); DropDownChoice<String> descriptorDropDownChoice = initSCMDomains(); add(descriptorDropDownChoice); } private DropDownChoice<String> initSCMDomains() { IModel<List<String>> dropDownModel = new LoadableDetachableModel<List<String>>() { @Override protected List<String> load() { Set<String> domains = new HashSet<String>(managersMap.keySet()); return new ArrayList<String>(domains); } }; DropDownChoice<String> descriptorDropDownChoice = new DropDownChoice<String>("domainDropDown", dropDownModel, new IChoiceRenderer<String>() { public String getDisplayValue(String object) { return object; } public String getIdValue(String object, int index) { return object; } }) { @Override protected boolean wantOnSelectionChangedNotifications() { return true; } @Override protected void onSelectionChanged(String newSelection) { super.onSelectionChanged(newSelection); domainDropDown = newSelection; } }; return descriptorDropDownChoice; } @Override public boolean isLastStep() { return false; } @Override public IDynamicWizardStep next() { Class<? extends Domain> domain = managersMap.get(domainDropDown); return new SelectServiceStep(project, domain); } @Override public boolean isComplete() { return domainDropDown != null && !"".equals(domainDropDown); } }
OPENCIT-6 only show unconfigured domains in drop down list. Signed-off-by: Michael Handler <331a76cd0f162b0218893a3dfa4df5a8bf659d1e@fullstop.at>
ui/web/src/main/java/org/openengsb/opencit/ui/web/WizardSteps/DomainSelectionStep.java
OPENCIT-6 only show unconfigured domains in drop down list.
Java
apache-2.0
f6e91f5f6a6f11c346f21e3c522b4b3d6584d4c8
0
javamelody/javamelody,javamelody/javamelody,javamelody/javamelody
/* * Copyright 2008-2010 by Emeric Vernat * * This file is part of Java Melody. * * Java Melody is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Java Melody 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 Java Melody. If not, see <http://www.gnu.org/licenses/>. */ package net.bull.javamelody; import static net.bull.javamelody.HttpParameters.SESSIONS_PART; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.io.StringWriter; import java.sql.Connection; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Random; import java.util.Timer; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.SimpleTrigger; import org.quartz.Trigger; import org.quartz.impl.StdSchedulerFactory; /** * Test unitaire de la classe HtmlReport. * @author Emeric Vernat */ public class TestHtmlReport { private Timer timer; private List<JavaInformations> javaInformationsList; private Counter sqlCounter; private Counter servicesCounter; private Counter counter; private Counter errorCounter; private Collector collector; private StringWriter writer; /** Initialisation. */ @Before public void setUp() { timer = new Timer("test timer", true); javaInformationsList = Collections.singletonList(new JavaInformations(null, true)); sqlCounter = new Counter("sql", "db.png"); sqlCounter.setDisplayed(false); servicesCounter = new Counter("services", "beans.png", sqlCounter); // counterName doit être http, sql ou ejb pour que les libellés de graph soient trouvés dans les traductions counter = new Counter("http", "dbweb.png", sqlCounter); errorCounter = new Counter(Counter.ERROR_COUNTER_NAME, null); final Counter jobCounter = new Counter(Counter.JOB_COUNTER_NAME, "jobs.png"); collector = new Collector("test", Arrays.asList(counter, sqlCounter, servicesCounter, errorCounter, jobCounter), timer); writer = new StringWriter(); } /** Finalisation. */ @After public void tearDown() { timer.cancel(); } /** Test. * @throws IOException e */ @Test public void testEmptyCounter() throws IOException { final HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList, Period.TOUT, writer); // rapport avec counter sans requête counter.clear(); errorCounter.clear(); htmlReport.toHtml(null); assertNotEmptyAndClear(writer); } /** Test. * @throws IOException e */ @Test public void testDoubleJavaInformations() throws IOException { final List<JavaInformations> myJavaInformationsList = Arrays.asList(new JavaInformations( null, true), new JavaInformations(null, true)); final HtmlReport htmlReport = new HtmlReport(collector, null, myJavaInformationsList, Period.TOUT, writer); htmlReport.toHtml(null); assertNotEmptyAndClear(writer); } /** Test. * @throws IOException e */ @Test public void testCounter() throws IOException { // counter avec 3 requêtes setProperty(Parameter.WARNING_THRESHOLD_MILLIS, "500"); setProperty(Parameter.SEVERE_THRESHOLD_MILLIS, "1500"); setProperty(Parameter.ANALYTICS_ID, "123456789"); counter.addRequest("test1", 0, 0, false, 1000); counter.addRequest("test2", 1000, 500, false, 1000); counter.addRequest("test3", 100000, 50000, true, 10000); collector.collectWithoutErrors(javaInformationsList); final HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList, Period.TOUT, writer); htmlReport.toHtml("message 2"); assertNotEmptyAndClear(writer); setProperty(Parameter.NO_DATABASE, "true"); collector.collectWithoutErrors(javaInformationsList); htmlReport.toHtml("message 2"); assertNotEmptyAndClear(writer); setProperty(Parameter.NO_DATABASE, "false"); } /** Test. * @throws IOException e */ @Test public void testErrorCounter() throws IOException { // errorCounter errorCounter.addRequestForSystemError("error", -1, -1, null); errorCounter.addRequestForSystemError("error2", -1, -1, "ma stack-trace"); collector.collectWithoutErrors(javaInformationsList); final HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList, Period.TOUT, writer); htmlReport.toHtml("message 3"); assertNotEmptyAndClear(writer); for (final CounterRequest request : errorCounter.getRequests()) { htmlReport.writeRequestAndGraphDetail(request.getId()); } htmlReport.writeRequestAndGraphDetail("n'importe quoi"); assertNotEmptyAndClear(writer); } /** Test. * @throws IOException e */ @Test public void testPeriodeNonTout() throws IOException { // counter avec période non TOUT et des requêtes collector.collectWithoutErrors(javaInformationsList); final String requestName = "test 1"; counter.bindContext(requestName, "complete test 1"); sqlCounter.addRequest("sql1", 10, 10, false, -1); counter.addRequest(requestName, 0, 0, false, 1000); counter.addRequest("test2", 1000, 500, false, 1000); counter.addRequest("test3", 10000, 500, true, 10000); collector.collectWithoutErrors(javaInformationsList); final HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList, Period.SEMAINE, writer); htmlReport.toHtml("message 6"); assertNotEmptyAndClear(writer); // période personnalisée final HtmlReport htmlReportRange = new HtmlReport(collector, null, javaInformationsList, Range.createCustomRange(new Date(), new Date()), writer); htmlReportRange.toHtml("message 6"); assertNotEmptyAndClear(writer); } /** Test. * @throws Exception e */ @Test public void testAllWrite() throws Exception { // NOPMD final HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList, Period.SEMAINE, writer); htmlReport.writeRequestAndGraphDetail("httpHitsRate"); // writeRequestAndGraphDetail avec drill-down collector.collectWithoutErrors(javaInformationsList); // si sqlCounter reste à displayed=false, // il ne sera pas utilisé dans writeRequestAndGraphDetail sqlCounter.setDisplayed(true); final String requestName = "test 1"; counter.bindContext(requestName, "complete test 1"); servicesCounter.bindContext("service1", "service1"); sqlCounter.bindContext("sql1", "complete sql1"); sqlCounter.addRequest("sql1", 5, -1, false, -1); servicesCounter.addRequest("service1", 10, 10, false, -1); servicesCounter.bindContext("service2", "service2"); servicesCounter.addRequest("service2", 10, 10, false, -1); counter.addRequest(requestName, 0, 0, false, 1000); collector.collectWithoutErrors(javaInformationsList); final HtmlReport toutHtmlReport = new HtmlReport(collector, null, javaInformationsList, Period.TOUT, writer); for (final Counter collectorCounter : collector.getCounters()) { for (final CounterRequest request : collectorCounter.getRequests()) { toutHtmlReport.writeRequestAndGraphDetail(request.getId()); toutHtmlReport.writeRequestUsages(request.getId()); } } sqlCounter.setDisplayed(false); htmlReport.writeSessionDetail("", null); htmlReport.writeSessions(Collections.<SessionInformations> emptyList(), "message", SESSIONS_PART); htmlReport .writeSessions(Collections.<SessionInformations> emptyList(), null, SESSIONS_PART); final String fileName = ProcessInformations.WINDOWS ? "/tasklist.txt" : "/ps.txt"; htmlReport.writeProcesses(ProcessInformations.buildProcessInformations(getClass() .getResourceAsStream(fileName), ProcessInformations.WINDOWS)); // avant initH2 pour avoir une liste de connexions vide htmlReport.writeConnections(JdbcWrapper.getConnectionInformationsList(), false); final Connection connection = TestDatabaseInformations.initH2(); try { htmlReport.writeConnections(JdbcWrapper.getConnectionInformationsList(), false); htmlReport.writeConnections(JdbcWrapper.getConnectionInformationsList(), true); htmlReport.writeDatabase(new DatabaseInformations(0)); HtmlReport.writeAddAndRemoveApplicationLinks(null, writer); HtmlReport.writeAddAndRemoveApplicationLinks("test", writer); setProperty(Parameter.SYSTEM_ACTIONS_ENABLED, "true"); htmlReport.toHtml(null); // writeSystemActionsLinks assertNotEmptyAndClear(writer); setProperty(Parameter.NO_DATABASE, "true"); htmlReport.toHtml(null); // writeSystemActionsLinks assertNotEmptyAndClear(writer); setProperty(Parameter.SYSTEM_ACTIONS_ENABLED, "false"); setProperty(Parameter.NO_DATABASE, "false"); } finally { connection.close(); } } /** Test. * @throws IOException e */ @Test public void testRootContexts() throws IOException { HtmlReport htmlReport; // addRequest pour que CounterRequestContext.getCpuTime() soit appelée counter.addRequest("first request", 100, 100, false, 1000); TestCounter.bindRootContexts("first request", counter, 3); sqlCounter.bindContext("sql", "sql"); htmlReport = new HtmlReport(collector, null, javaInformationsList, Period.TOUT, writer); htmlReport.toHtml("message a"); assertNotEmptyAndClear(writer); final Counter myCounter = new Counter("http", null); final Collector collector2 = new Collector("test 2", Arrays.asList(myCounter), timer); myCounter.bindContext("my context", "my context"); htmlReport = new HtmlReport(collector2, null, javaInformationsList, Period.SEMAINE, writer); htmlReport.toHtml("message b"); assertNotEmptyAndClear(writer); } /** Test. * @throws IOException e */ @Test public void testCache() throws IOException { final String cacheName = "test 1"; final CacheManager cacheManager = CacheManager.getInstance(); cacheManager.addCache(cacheName); final String cacheName2 = "test 2"; try { final Cache cache = cacheManager.getCache(cacheName); cache.put(new Element(1, Math.random())); cache.get(1); cache.get(0); cacheManager.addCache(cacheName2); final Cache cache2 = cacheManager.getCache(cacheName2); cache2.getCacheConfiguration().setOverflowToDisk(false); cache2.getCacheConfiguration().setEternal(true); // JavaInformations doit être réinstancié pour récupérer les caches final List<JavaInformations> javaInformationsList2 = Collections .singletonList(new JavaInformations(null, true)); final HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList2, Period.TOUT, writer); htmlReport.toHtml(null); assertNotEmptyAndClear(writer); } finally { cacheManager.removeCache(cacheName); cacheManager.removeCache(cacheName2); } } /** Test. * @throws IOException e * @throws SchedulerException e */ @Test public void testJob() throws IOException, SchedulerException { //Grab the Scheduler instance from the Factory final Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); try { // and start it off scheduler.start(); //Define job instance final Random random = new Random(); final JobDetail job = new JobDetail("job" + random.nextInt(), null, JobTestImpl.class); //Define a Trigger that will fire "now" final Trigger trigger = new SimpleTrigger("trigger" + random.nextInt(), null, new Date()); //Schedule the job with the trigger scheduler.scheduleJob(job, trigger); //Define a Trigger that will fire "later" final JobDetail job2 = new JobDetail("job" + random.nextInt(), null, JobTestImpl.class); final Trigger trigger2 = new SimpleTrigger("trigger" + random.nextInt(), null, new Date(System.currentTimeMillis() + random.nextInt(60000))); scheduler.scheduleJob(job2, trigger2); // JavaInformations doit être réinstancié pour récupérer les jobs final List<JavaInformations> javaInformationsList2 = Collections .singletonList(new JavaInformations(null, true)); final HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList2, Period.TOUT, writer); htmlReport.toHtml(null); assertNotEmptyAndClear(writer); } finally { scheduler.shutdown(); } } /** Test. * @throws IOException e */ @Test public void testWithCollectorServer() throws IOException { final CollectorServer collectorServer = new CollectorServer(); final HtmlReport htmlReport = new HtmlReport(collector, collectorServer, javaInformationsList, Period.TOUT, writer); htmlReport.toHtml(null); assertNotEmptyAndClear(writer); collectorServer.collectWithoutErrors(); htmlReport.toHtml(null); assertNotEmptyAndClear(writer); } /** Test. * @throws IOException e */ @Test public void testWithNoDatabase() throws IOException { final HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList, Period.TOUT, writer); htmlReport.toHtml(null); assertNotEmptyAndClear(writer); } /** Test. * @throws IOException e */ @Test public void testEmptyHtmlCounterRequestContext() throws IOException { final HtmlCounterRequestContextReport report = new HtmlCounterRequestContextReport( Collections.<CounterRequestContext> emptyList(), Collections .<String, HtmlCounterReport> emptyMap(), Collections .<ThreadInformations> emptyList(), true, writer); report.toHtml(); if (writer.getBuffer().length() != 0) { fail("HtmlCounterRequestContextReport"); } } private static void setProperty(Parameter parameter, String value) { System.setProperty(Parameters.PARAMETER_SYSTEM_PREFIX + parameter.getCode(), value); } private static void assertNotEmptyAndClear(final StringWriter writer) { assertTrue("rapport vide", writer.getBuffer().length() > 0); writer.getBuffer().setLength(0); } /** Test. * @throws IOException e */ @Test public void testToHtmlEn() throws IOException { I18N.bindLocale(Locale.UK); try { assertEquals("locale en", Locale.UK, I18N.getCurrentLocale()); // counter avec 3 requêtes counter.addRequest("test1", 0, 0, false, 1000); counter.addRequest("test2", 1000, 500, false, 1000); counter.addRequest("test3", 10000, 5000, true, 10000); final HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList, Period.TOUT, writer); htmlReport.toHtml("message"); assertNotEmptyAndClear(writer); } finally { I18N.unbindLocale(); } } }
javamelody-core/src/test/java/net/bull/javamelody/TestHtmlReport.java
/* * Copyright 2008-2010 by Emeric Vernat * * This file is part of Java Melody. * * Java Melody is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Java Melody 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 Java Melody. If not, see <http://www.gnu.org/licenses/>. */ package net.bull.javamelody; import static net.bull.javamelody.HttpParameters.SESSIONS_PART; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.io.StringWriter; import java.sql.Connection; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Random; import java.util.Timer; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.SimpleTrigger; import org.quartz.Trigger; import org.quartz.impl.StdSchedulerFactory; /** * Test unitaire de la classe HtmlReport. * @author Emeric Vernat */ public class TestHtmlReport { private Timer timer; private List<JavaInformations> javaInformationsList; private Counter sqlCounter; private Counter servicesCounter; private Counter counter; private Counter errorCounter; private Collector collector; private StringWriter writer; /** Initialisation. */ @Before public void setUp() { timer = new Timer("test timer", true); javaInformationsList = Collections.singletonList(new JavaInformations(null, true)); sqlCounter = new Counter("sql", "db.png"); sqlCounter.setDisplayed(false); servicesCounter = new Counter("services", "beans.png", sqlCounter); // counterName doit être http, sql ou ejb pour que les libellés de graph soient trouvés dans les traductions counter = new Counter("http", "dbweb.png", sqlCounter); errorCounter = new Counter(Counter.ERROR_COUNTER_NAME, null); final Counter jobCounter = new Counter(Counter.JOB_COUNTER_NAME, "jobs.png"); collector = new Collector("test", Arrays.asList(counter, sqlCounter, servicesCounter, errorCounter, jobCounter), timer); writer = new StringWriter(); } /** Finalisation. */ @After public void tearDown() { timer.cancel(); } /** Test. * @throws IOException e */ @Test public void testEmptyCounter() throws IOException { final HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList, Period.TOUT, writer); // rapport avec counter sans requête counter.clear(); errorCounter.clear(); htmlReport.toHtml(null); assertNotEmptyAndClear(writer); } /** Test. * @throws IOException e */ @Test public void testDoubleJavaInformations() throws IOException { final List<JavaInformations> myJavaInformationsList = Arrays.asList(new JavaInformations( null, true), new JavaInformations(null, true)); final HtmlReport htmlReport = new HtmlReport(collector, null, myJavaInformationsList, Period.TOUT, writer); htmlReport.toHtml(null); assertNotEmptyAndClear(writer); } /** Test. * @throws IOException e */ @Test public void testCounter() throws IOException { // counter avec 3 requêtes setProperty(Parameter.WARNING_THRESHOLD_MILLIS, "500"); setProperty(Parameter.SEVERE_THRESHOLD_MILLIS, "1500"); setProperty(Parameter.ANALYTICS_ID, "123456789"); counter.addRequest("test1", 0, 0, false, 1000); counter.addRequest("test2", 1000, 500, false, 1000); counter.addRequest("test3", 100000, 50000, true, 10000); collector.collectWithoutErrors(javaInformationsList); final HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList, Period.TOUT, writer); htmlReport.toHtml("message 2"); assertNotEmptyAndClear(writer); setProperty(Parameter.NO_DATABASE, "true"); collector.collectWithoutErrors(javaInformationsList); htmlReport.toHtml("message 2"); assertNotEmptyAndClear(writer); setProperty(Parameter.NO_DATABASE, "false"); } /** Test. * @throws IOException e */ @Test public void testErrorCounter() throws IOException { // errorCounter errorCounter.addRequestForSystemError("error", -1, -1, null); errorCounter.addRequestForSystemError("error2", -1, -1, "ma stack-trace"); collector.collectWithoutErrors(javaInformationsList); final HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList, Period.TOUT, writer); htmlReport.toHtml("message 3"); assertNotEmptyAndClear(writer); for (final CounterRequest request : errorCounter.getRequests()) { htmlReport.writeRequestAndGraphDetail(request.getId()); } htmlReport.writeRequestAndGraphDetail("n'importe quoi"); assertNotEmptyAndClear(writer); } /** Test. * @throws IOException e */ @Test public void testPeriodeNonTout() throws IOException { // counter avec période non TOUT et des requêtes collector.collectWithoutErrors(javaInformationsList); final String requestName = "test 1"; counter.bindContext(requestName, "complete test 1"); sqlCounter.addRequest("sql1", 10, 10, false, -1); counter.addRequest(requestName, 0, 0, false, 1000); counter.addRequest("test2", 1000, 500, false, 1000); counter.addRequest("test3", 10000, 500, true, 10000); collector.collectWithoutErrors(javaInformationsList); final HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList, Period.SEMAINE, writer); htmlReport.toHtml("message 6"); assertNotEmptyAndClear(writer); } /** Test. * @throws Exception e */ @Test public void testAllWrite() throws Exception { // NOPMD final HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList, Period.SEMAINE, writer); htmlReport.writeRequestAndGraphDetail("httpHitsRate"); // writeRequestAndGraphDetail avec drill-down collector.collectWithoutErrors(javaInformationsList); // si sqlCounter reste à displayed=false, // il ne sera pas utilisé dans writeRequestAndGraphDetail sqlCounter.setDisplayed(true); final String requestName = "test 1"; counter.bindContext(requestName, "complete test 1"); servicesCounter.bindContext("service1", "service1"); sqlCounter.bindContext("sql1", "complete sql1"); sqlCounter.addRequest("sql1", 5, -1, false, -1); servicesCounter.addRequest("service1", 10, 10, false, -1); servicesCounter.bindContext("service2", "service2"); servicesCounter.addRequest("service2", 10, 10, false, -1); counter.addRequest(requestName, 0, 0, false, 1000); collector.collectWithoutErrors(javaInformationsList); final HtmlReport toutHtmlReport = new HtmlReport(collector, null, javaInformationsList, Period.TOUT, writer); for (final Counter collectorCounter : collector.getCounters()) { for (final CounterRequest request : collectorCounter.getRequests()) { toutHtmlReport.writeRequestAndGraphDetail(request.getId()); toutHtmlReport.writeRequestUsages(request.getId()); } } sqlCounter.setDisplayed(false); htmlReport.writeSessionDetail("", null); htmlReport.writeSessions(Collections.<SessionInformations> emptyList(), "message", SESSIONS_PART); htmlReport .writeSessions(Collections.<SessionInformations> emptyList(), null, SESSIONS_PART); final String fileName = ProcessInformations.WINDOWS ? "/tasklist.txt" : "/ps.txt"; htmlReport.writeProcesses(ProcessInformations.buildProcessInformations(getClass() .getResourceAsStream(fileName), ProcessInformations.WINDOWS)); // avant initH2 pour avoir une liste de connexions vide htmlReport.writeConnections(JdbcWrapper.getConnectionInformationsList(), false); final Connection connection = TestDatabaseInformations.initH2(); try { htmlReport.writeConnections(JdbcWrapper.getConnectionInformationsList(), false); htmlReport.writeConnections(JdbcWrapper.getConnectionInformationsList(), true); htmlReport.writeDatabase(new DatabaseInformations(0)); HtmlReport.writeAddAndRemoveApplicationLinks(null, writer); HtmlReport.writeAddAndRemoveApplicationLinks("test", writer); setProperty(Parameter.SYSTEM_ACTIONS_ENABLED, "true"); htmlReport.toHtml(null); // writeSystemActionsLinks assertNotEmptyAndClear(writer); setProperty(Parameter.NO_DATABASE, "true"); htmlReport.toHtml(null); // writeSystemActionsLinks assertNotEmptyAndClear(writer); setProperty(Parameter.SYSTEM_ACTIONS_ENABLED, "false"); setProperty(Parameter.NO_DATABASE, "false"); } finally { connection.close(); } } /** Test. * @throws IOException e */ @Test public void testRootContexts() throws IOException { HtmlReport htmlReport; // addRequest pour que CounterRequestContext.getCpuTime() soit appelée counter.addRequest("first request", 100, 100, false, 1000); TestCounter.bindRootContexts("first request", counter, 3); sqlCounter.bindContext("sql", "sql"); htmlReport = new HtmlReport(collector, null, javaInformationsList, Period.TOUT, writer); htmlReport.toHtml("message a"); assertNotEmptyAndClear(writer); final Counter myCounter = new Counter("http", null); final Collector collector2 = new Collector("test 2", Arrays.asList(myCounter), timer); myCounter.bindContext("my context", "my context"); htmlReport = new HtmlReport(collector2, null, javaInformationsList, Period.SEMAINE, writer); htmlReport.toHtml("message b"); assertNotEmptyAndClear(writer); } /** Test. * @throws IOException e */ @Test public void testCache() throws IOException { final String cacheName = "test 1"; final CacheManager cacheManager = CacheManager.getInstance(); cacheManager.addCache(cacheName); final String cacheName2 = "test 2"; try { final Cache cache = cacheManager.getCache(cacheName); cache.put(new Element(1, Math.random())); cache.get(1); cache.get(0); cacheManager.addCache(cacheName2); final Cache cache2 = cacheManager.getCache(cacheName2); cache2.getCacheConfiguration().setOverflowToDisk(false); cache2.getCacheConfiguration().setEternal(true); // JavaInformations doit être réinstancié pour récupérer les caches final List<JavaInformations> javaInformationsList2 = Collections .singletonList(new JavaInformations(null, true)); final HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList2, Period.TOUT, writer); htmlReport.toHtml(null); assertNotEmptyAndClear(writer); } finally { cacheManager.removeCache(cacheName); cacheManager.removeCache(cacheName2); } } /** Test. * @throws IOException e * @throws SchedulerException e */ @Test public void testJob() throws IOException, SchedulerException { //Grab the Scheduler instance from the Factory final Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); try { // and start it off scheduler.start(); //Define job instance final Random random = new Random(); final JobDetail job = new JobDetail("job" + random.nextInt(), null, JobTestImpl.class); //Define a Trigger that will fire "now" final Trigger trigger = new SimpleTrigger("trigger" + random.nextInt(), null, new Date()); //Schedule the job with the trigger scheduler.scheduleJob(job, trigger); //Define a Trigger that will fire "later" final JobDetail job2 = new JobDetail("job" + random.nextInt(), null, JobTestImpl.class); final Trigger trigger2 = new SimpleTrigger("trigger" + random.nextInt(), null, new Date(System.currentTimeMillis() + random.nextInt(60000))); scheduler.scheduleJob(job2, trigger2); // JavaInformations doit être réinstancié pour récupérer les jobs final List<JavaInformations> javaInformationsList2 = Collections .singletonList(new JavaInformations(null, true)); final HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList2, Period.TOUT, writer); htmlReport.toHtml(null); assertNotEmptyAndClear(writer); } finally { scheduler.shutdown(); } } /** Test. * @throws IOException e */ @Test public void testWithCollectorServer() throws IOException { final CollectorServer collectorServer = new CollectorServer(); final HtmlReport htmlReport = new HtmlReport(collector, collectorServer, javaInformationsList, Period.TOUT, writer); htmlReport.toHtml(null); assertNotEmptyAndClear(writer); collectorServer.collectWithoutErrors(); htmlReport.toHtml(null); assertNotEmptyAndClear(writer); } /** Test. * @throws IOException e */ @Test public void testWithNoDatabase() throws IOException { final HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList, Period.TOUT, writer); htmlReport.toHtml(null); assertNotEmptyAndClear(writer); } /** Test. * @throws IOException e */ @Test public void testEmptyHtmlCounterRequestContext() throws IOException { final HtmlCounterRequestContextReport report = new HtmlCounterRequestContextReport( Collections.<CounterRequestContext> emptyList(), Collections .<String, HtmlCounterReport> emptyMap(), Collections .<ThreadInformations> emptyList(), true, writer); report.toHtml(); if (writer.getBuffer().length() != 0) { fail("HtmlCounterRequestContextReport"); } } private static void setProperty(Parameter parameter, String value) { System.setProperty(Parameters.PARAMETER_SYSTEM_PREFIX + parameter.getCode(), value); } private static void assertNotEmptyAndClear(final StringWriter writer) { assertTrue("rapport vide", writer.getBuffer().length() > 0); writer.getBuffer().setLength(0); } /** Test. * @throws IOException e */ @Test public void testToHtmlEn() throws IOException { I18N.bindLocale(Locale.UK); try { assertEquals("locale en", Locale.UK, I18N.getCurrentLocale()); // counter avec 3 requêtes counter.addRequest("test1", 0, 0, false, 1000); counter.addRequest("test2", 1000, 500, false, 1000); counter.addRequest("test3", 10000, 5000, true, 10000); final HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList, Period.TOUT, writer); htmlReport.toHtml("message"); assertNotEmptyAndClear(writer); } finally { I18N.unbindLocale(); } } }
compléments tests unitaires
javamelody-core/src/test/java/net/bull/javamelody/TestHtmlReport.java
compléments tests unitaires
Java
apache-2.0
312c661f266dec1f8ce34ae818b41bf7013a669c
0
Velosoda/SimpleFighting
Enemy.java
package pack; public class Enemy extends Fighter { Enemy(double avgAttack, double avgHealth) { String[] typeList = {"Chest", "Arms", "Legs", "Neutral"}; this.type = typeList[this.rand.nextInt(4)]; this.attack = avgAttack; this.health = avgHealth; this.maxHealth = avgHealth; this.name = "rip bongs"; } }
Delete Enemy.java
Enemy.java
Delete Enemy.java
Java
apache-2.0
5fabcd11c3a69db5273c24b4448c4309db4f030d
0
blstream/myHoard_Android,blstream/myHoard_Android
package com.myhoard.app.fragments; import android.app.AlertDialog; import android.content.AsyncQueryHandler; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.ActionBar; import android.content.Context; import android.database.Cursor; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v7.app.ActionBarActivity; import android.text.Editable; import android.text.TextWatcher; import android.view.ContextMenu; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.EditText; import android.widget.GridView; import android.widget.TextView; import com.myhoard.app.R; import com.myhoard.app.activities.ElementActivity; import com.myhoard.app.images.ImageAdapterList; import com.myhoard.app.provider.DataStorage; /** * Created by Piotr Brzozowski on 01.03.14. * SearchFragment class used to search concrete sentence in table of elements */ public class SearchFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> { private static final String SEARCH_COLLECTION_ID = "SearchCollection"; private static final String TEXT_TO_SEARCH = "TextSearch"; private static final String SEARCH_BY_NAME_TAB = "name"; private static final String SEARCH_ALL_TAB = "all"; private static final String SEARCH_BY_DESCRIPTION_TAB = "description"; private static final String NEW_FACEBOOK_FRAGMENT_NAME = "FacebookFragment"; private static final int DELETE_ID = Menu.FIRST + 1; private static final int SHARE_ID = Menu.FIRST + 3; private static final int TEXT_TO_SEARCH_MIN_LENGTH = 2; private static final int SEARCH_ALL = 0; private static final int SEARCH_BY_NAME = 1; private static final int SEARCH_BY_DESCRIPTION = 2; private static int sSelectedTypeOfSearch = SEARCH_ALL; private String mTextToSearch = ""; private EditText mSearchText; private Context mContext; private ImageAdapterList mImageAdapterList; private Long mCollectionId; private TextView mSearchByName; private TextView mSearchAll; private TextView mSearchByDescription; private GridView mGridView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View v = inflater.inflate(R.layout.fragment_search, container, false); setHasOptionsMenu(true); Bundle b = this.getArguments(); mCollectionId = b.getLong(SEARCH_COLLECTION_ID); mContext = getActivity(); mGridView = (GridView) v.findViewById(R.id.gridViewSearch); //Create adapter to adapt data to individual list row mImageAdapterList = new ImageAdapterList(mContext, null, 0); //Set adapter for ListView mGridView.setAdapter(mImageAdapterList); ActionBar actionBar = ((ActionBarActivity)getActivity()).getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); actionBar.setCustomView(R.layout.action_bar_search); mSearchText = (EditText)actionBar.getCustomView().findViewById(R.id.editTextSearcher); createSearchAllTab(actionBar); createSearchByNameTab(actionBar); createSearchByDescriptionTab(actionBar); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_HOME_AS_UP); //Use text changed listener by mSearchTest EditText object to find elements in real time of search textListener(); return v; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent in = new Intent(getActivity(), ElementActivity.class); in.putExtra("elementId",id); startActivity(in); } }); registerForContextMenu(mGridView); } public void createSearchByNameTab(ActionBar actionBar){ ActionBar.Tab actionBarTabSearchByName = actionBar.newTab(); actionBarTabSearchByName.setCustomView(R.layout.search_tab); mSearchByName = (TextView)actionBarTabSearchByName.getCustomView().findViewById(R.id.tab_text_search); setUnselectedTabSearchByName(SEARCH_BY_NAME_TAB); ActionBar.TabListener searchByNameTabListener = new ActionBar.TabListener() { @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { setSelectedTabSearchByName(SEARCH_BY_NAME_TAB); sSelectedTypeOfSearch = SEARCH_BY_NAME; checkText(mTextToSearch); } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { setUnselectedTabSearchByName(SEARCH_BY_NAME_TAB); } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { setSelectedTabSearchByName(SEARCH_BY_NAME_TAB); sSelectedTypeOfSearch = SEARCH_BY_NAME; checkText(mTextToSearch); } }; actionBarTabSearchByName.setTabListener(searchByNameTabListener); actionBar.addTab(actionBarTabSearchByName); } public void createSearchAllTab(ActionBar actionBar){ ActionBar.Tab actionBarTabSearchAll = actionBar.newTab(); actionBarTabSearchAll.setCustomView(R.layout.search_tab); mSearchAll = (TextView)actionBarTabSearchAll.getCustomView().findViewById(R.id.tab_text_search); setSelectedTabSearchAll(SEARCH_ALL_TAB); ActionBar.TabListener searchAllTabListener = new ActionBar.TabListener() { @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { setSelectedTabSearchAll(SEARCH_ALL_TAB); sSelectedTypeOfSearch = SEARCH_ALL; checkText(mTextToSearch); } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { setUnselectedTabSearchAll(SEARCH_ALL_TAB); } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { setSelectedTabSearchAll(SEARCH_ALL_TAB); sSelectedTypeOfSearch = SEARCH_ALL; checkText(mTextToSearch); } }; actionBarTabSearchAll.setTabListener(searchAllTabListener); actionBar.addTab(actionBarTabSearchAll); } public void createSearchByDescriptionTab(ActionBar actionBar){ ActionBar.Tab actionBarTabSearchByDescription = actionBar.newTab(); actionBarTabSearchByDescription.setCustomView(R.layout.search_tab); mSearchByDescription = (TextView)actionBarTabSearchByDescription.getCustomView().findViewById(R.id.tab_text_search); setUnselectedTabSearchByDescription(SEARCH_BY_DESCRIPTION_TAB); ActionBar.TabListener searchByDescriptionTabListener = new ActionBar.TabListener() { @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { setSelectedTabSearchByDescription(SEARCH_BY_DESCRIPTION_TAB); sSelectedTypeOfSearch = SEARCH_BY_DESCRIPTION; checkText(mTextToSearch); } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { setUnselectedTabSearchByDescription(SEARCH_BY_DESCRIPTION_TAB); } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { setSelectedTabSearchByDescription(SEARCH_BY_DESCRIPTION_TAB); sSelectedTypeOfSearch = SEARCH_BY_DESCRIPTION; checkText(mTextToSearch); } }; actionBarTabSearchByDescription.setTabListener(searchByDescriptionTabListener); actionBar.addTab(actionBarTabSearchByDescription); } public void textListener(){ mSearchText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { assert mSearchText.getText() != null; mTextToSearch = mSearchText.getText().toString(); mTextToSearch = mTextToSearch.trim(); mTextToSearch = mTextToSearch.toLowerCase(); //Search element when text to search have more than two characters checkText(mTextToSearch); } @Override public void afterTextChanged(Editable s) { } }); } public void checkText(String collectionElementText){ if (collectionElementText.length() >= TEXT_TO_SEARCH_MIN_LENGTH) { Bundle args = new Bundle(); //Put text to search to Bundle object args.putString(TEXT_TO_SEARCH, collectionElementText); //Restart to load data when user query is changed getLoaderManager().restartLoader(sSelectedTypeOfSearch, args, SearchFragment.this); } else { //Clear screen mImageAdapterList.swapCursor(null); } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); menu.clear(); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); int groupId = 0; menu.add(groupId, DELETE_ID, DELETE_ID, R.string.menu_delete); menu.add(groupId, SHARE_ID, SHARE_ID, R.string.menu_share); } @Override public boolean onContextItemSelected(MenuItem item) { final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); switch (item.getItemId()) { // Sharing item from list case SHARE_ID: if(info!=null) { newFacebookShareFragment(info.id); } return true; case DELETE_ID: new AlertDialog.Builder(getActivity()) .setTitle(mContext.getString(R.string.edit_colection_dialog_title)) .setMessage(mContext.getString(R.string.edit_colection_dialog_message)) .setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if (info != null) { deleteElement(info.id); } } }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // Do nothing. } }).show(); return true; } return super.onContextItemSelected(item); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { //Get text to search from args object String collectionElementText = args.getString(TEXT_TO_SEARCH); String selection = null; switch(id){ case SEARCH_ALL: selection = String.format("%s = %s AND %s!=%d AND (%s=%d OR %s is null) AND (%s LIKE '%%%s%%' OR %s LIKE '%%%s%%')", mCollectionId,DataStorage.Items.ID_COLLECTION,DataStorage.Items.TABLE_NAME + "." +DataStorage.Items.DELETED,1, DataStorage.Media.AVATAR,1,DataStorage.Media.AVATAR, DataStorage.Items.DESCRIPTION,collectionElementText,DataStorage.Items.NAME,collectionElementText); break; case SEARCH_BY_NAME: selection = String.format("%s = %s AND %s!=%d AND (%s=%d OR %s is null) AND %s LIKE '%%%s%%'", mCollectionId,DataStorage.Items.ID_COLLECTION,DataStorage.Items.TABLE_NAME + "." +DataStorage.Items.DELETED,1, DataStorage.Media.AVATAR,1,DataStorage.Media.AVATAR, DataStorage.Items.NAME,collectionElementText); break; case SEARCH_BY_DESCRIPTION: selection = String.format("%s = %s AND %s!=%d AND (%s=%d OR %s is null) AND %s LIKE '%%%s%%'", mCollectionId,DataStorage.Items.ID_COLLECTION,DataStorage.Items.TABLE_NAME + "." +DataStorage.Items.DELETED,1, DataStorage.Media.AVATAR,1,DataStorage.Media.AVATAR, DataStorage.Items.DESCRIPTION,collectionElementText); break; } //CursorLoader used to get data from user query return new CursorLoader(mContext, DataStorage.Items.CONTENT_URI, new String[]{DataStorage.Items.NAME, DataStorage.Media.FILE_NAME, DataStorage.Items.TABLE_NAME + "." + DataStorage.Items._ID}, selection, null, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { //Change cursor with data from database mImageAdapterList.swapCursor(data); } @Override public void onLoaderReset(Loader<Cursor> loader) { mImageAdapterList.swapCursor(null); } private void setSelectedTabSearchByName(String text) { mSearchByName.setTextColor(getResources().getColor(R.color.selected_tab_text_color)); mSearchByName.setText(text); } public void setUnselectedTabSearchByName(String text) { mSearchByName.setTextColor(getResources().getColor(R.color.black)); mSearchByName.setText(text); } private void setSelectedTabSearchAll(String text) { mSearchAll.setTextColor(getResources().getColor(R.color.selected_tab_text_color)); mSearchAll.setText(text); } public void setUnselectedTabSearchAll(String text) { mSearchAll.setTextColor(getResources().getColor(R.color.black)); mSearchAll.setText(text); } private void setSelectedTabSearchByDescription(String text) { mSearchByDescription.setTextColor(getResources().getColor(R.color.selected_tab_text_color)); mSearchByDescription.setText(text); } public void setUnselectedTabSearchByDescription(String text) { mSearchByDescription.setTextColor(getResources().getColor(R.color.black)); mSearchByDescription.setText(text); } @Override public void onDestroyView() { super.onDestroyView(); resetActionBarNavigationMode(); } @Override public void onResume() { super.onResume(); mSearchText.setText(mTextToSearch); checkText(mTextToSearch); } private void resetActionBarNavigationMode() { //getting the action bar from the MainActivity ActionBar actionBar = ((ActionBarActivity) getActivity()).getSupportActionBar(); actionBar.removeAllTabs(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_HOME_AS_UP); actionBar.setDisplayShowTitleEnabled(true); } private void newFacebookShareFragment(long id) { Fragment newFragment = new FacebookItemsToShare(); FragmentTransaction transaction = getFragmentManager().beginTransaction(); Bundle bundle = new Bundle(); bundle.putLong(FacebookItemsToShare.ITEM_ID,id); newFragment.setArguments(bundle); transaction.replace(R.id.container,newFragment,NEW_FACEBOOK_FRAGMENT_NAME); transaction.addToBackStack(NEW_FACEBOOK_FRAGMENT_NAME); transaction.commit(); } private void deleteElement(long id){ ContentValues values = new ContentValues(); values.put(DataStorage.Items.DELETED,true); AsyncQueryHandler asyncHandler = new AsyncQueryHandler(getActivity().getContentResolver()) { }; asyncHandler.startUpdate(0,null,DataStorage.Items.CONTENT_URI,values,DataStorage.Items._ID + " = ?", new String[]{String.valueOf(id)}); checkText(mTextToSearch); } }
myHoard/src/main/java/com/myhoard/app/fragments/SearchFragment.java
package com.myhoard.app.fragments; import android.content.Intent; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.ActionBar; import android.content.Context; import android.database.Cursor; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v7.app.ActionBarActivity; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.EditText; import android.widget.GridView; import android.widget.TextView; import com.myhoard.app.R; import com.myhoard.app.activities.ElementActivity; import com.myhoard.app.images.ImageAdapterList; import com.myhoard.app.provider.DataStorage; /** * Created by Piotr Brzozowski on 01.03.14. * SearchFragment class used to search concrete sentence in table of elements */ public class SearchFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> { private static final String SEARCH_COLLECTION_ID = "SearchCollection"; private static final String TEXT_TO_SEARCH = "TextSearch"; private static final String SEARCH_BY_NAME_TAB = "name"; private static final String SEARCH_ALL_TAB = "all"; private static final String SEARCH_BY_DESCRIPTION_TAB = "description"; private static final int TEXT_TO_SEARCH_MIN_LENGTH = 2; private static final int SEARCH_ALL = 0; private static final int SEARCH_BY_NAME = 1; private static final int SEARCH_BY_DESCRIPTION = 2; private static int sSelectedTypeOfSearch = SEARCH_ALL; private String mTextToSearch =""; private EditText mSearchText; private Context mContext; private ImageAdapterList mImageAdapterList; private Long mCollectionId; private TextView mSearchByName; private TextView mSearchAll; private TextView mSearchByDescription; private GridView mGridView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View v = inflater.inflate(R.layout.fragment_search, container, false); setHasOptionsMenu(true); Bundle b = this.getArguments(); mCollectionId = b.getLong(SEARCH_COLLECTION_ID); mContext = getActivity(); mGridView = (GridView) v.findViewById(R.id.gridViewSearch); //Create adapter to adapt data to individual list row mImageAdapterList = new ImageAdapterList(mContext, null, 0); //Set adapter for ListView mGridView.setAdapter(mImageAdapterList); ActionBar actionBar = ((ActionBarActivity)getActivity()).getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); actionBar.setCustomView(R.layout.action_bar_search); mSearchText = (EditText)actionBar.getCustomView().findViewById(R.id.editTextSearcher); createSearchAllTab(actionBar); createSearchByNameTab(actionBar); createSearchByDescriptionTab(actionBar); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_HOME_AS_UP); //Use text changed listener by mSearchTest EditText object to find elements in real time of search textListener(); return v; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent in = new Intent(getActivity(), ElementActivity.class); in.putExtra("elementId",id); startActivity(in); } }); registerForContextMenu(mGridView); } public void createSearchByNameTab(ActionBar actionBar){ ActionBar.Tab actionBarTabSearchByName = actionBar.newTab(); actionBarTabSearchByName.setCustomView(R.layout.search_tab); mSearchByName = (TextView)actionBarTabSearchByName.getCustomView().findViewById(R.id.tab_text_search); setUnselectedTabSearchByName(SEARCH_BY_NAME_TAB); ActionBar.TabListener searchByNameTabListener = new ActionBar.TabListener() { @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { setSelectedTabSearchByName(SEARCH_BY_NAME_TAB); sSelectedTypeOfSearch = SEARCH_BY_NAME; checkText(mTextToSearch); } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { setUnselectedTabSearchByName(SEARCH_BY_NAME_TAB); } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { setSelectedTabSearchByName(SEARCH_BY_NAME_TAB); sSelectedTypeOfSearch = SEARCH_BY_NAME; checkText(mTextToSearch); } }; actionBarTabSearchByName.setTabListener(searchByNameTabListener); actionBar.addTab(actionBarTabSearchByName); } public void createSearchAllTab(ActionBar actionBar){ ActionBar.Tab actionBarTabSearchAll = actionBar.newTab(); actionBarTabSearchAll.setCustomView(R.layout.search_tab); mSearchAll = (TextView)actionBarTabSearchAll.getCustomView().findViewById(R.id.tab_text_search); setSelectedTabSearchAll(SEARCH_ALL_TAB); ActionBar.TabListener searchAllTabListener = new ActionBar.TabListener() { @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { setSelectedTabSearchAll(SEARCH_ALL_TAB); sSelectedTypeOfSearch = SEARCH_ALL; checkText(mTextToSearch); } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { setUnselectedTabSearchAll(SEARCH_ALL_TAB); } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { setSelectedTabSearchAll(SEARCH_ALL_TAB); sSelectedTypeOfSearch = SEARCH_ALL; checkText(mTextToSearch); } }; actionBarTabSearchAll.setTabListener(searchAllTabListener); actionBar.addTab(actionBarTabSearchAll); } public void createSearchByDescriptionTab(ActionBar actionBar){ ActionBar.Tab actionBarTabSearchByDescription = actionBar.newTab(); actionBarTabSearchByDescription.setCustomView(R.layout.search_tab); mSearchByDescription = (TextView)actionBarTabSearchByDescription.getCustomView().findViewById(R.id.tab_text_search); setUnselectedTabSearchByDescription(SEARCH_BY_DESCRIPTION_TAB); ActionBar.TabListener searchByDescriptionTabListener = new ActionBar.TabListener() { @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { setSelectedTabSearchByDescription(SEARCH_BY_DESCRIPTION_TAB); sSelectedTypeOfSearch = SEARCH_BY_DESCRIPTION; checkText(mTextToSearch); } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { setUnselectedTabSearchByDescription(SEARCH_BY_DESCRIPTION_TAB); } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { setSelectedTabSearchByDescription(SEARCH_BY_DESCRIPTION_TAB); sSelectedTypeOfSearch = SEARCH_BY_DESCRIPTION; checkText(mTextToSearch); } }; actionBarTabSearchByDescription.setTabListener(searchByDescriptionTabListener); actionBar.addTab(actionBarTabSearchByDescription); } public void textListener(){ mSearchText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { assert mSearchText.getText() != null; mTextToSearch = mSearchText.getText().toString(); mTextToSearch = mTextToSearch.trim(); mTextToSearch = mTextToSearch.toLowerCase(); //Search element when text to search have more than two characters checkText(mTextToSearch); } @Override public void afterTextChanged(Editable s) { } }); } public void checkText(String collectionElementText){ if (collectionElementText.length() >= TEXT_TO_SEARCH_MIN_LENGTH) { Bundle args = new Bundle(); //Put text to search to Bundle object args.putString(TEXT_TO_SEARCH, collectionElementText); //Restart to load data when user query is changed getLoaderManager().restartLoader(sSelectedTypeOfSearch, args, SearchFragment.this); } else { //Clear screen mImageAdapterList.swapCursor(null); } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); menu.clear(); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { //Get text to search from args object String collectionElementText = args.getString(TEXT_TO_SEARCH); String selection = null; switch(id){ case SEARCH_ALL: selection = String.format("%s = %s AND %s!=%d AND (%s=%d OR %s is null) AND (%s LIKE '%%%s%%' OR %s LIKE '%%%s%%')", mCollectionId,DataStorage.Items.ID_COLLECTION,DataStorage.Items.TABLE_NAME + "." +DataStorage.Items.DELETED,1, DataStorage.Media.AVATAR,1,DataStorage.Media.AVATAR, DataStorage.Items.DESCRIPTION,collectionElementText,DataStorage.Items.NAME,collectionElementText); break; case SEARCH_BY_NAME: selection = String.format("%s = %s AND %s!=%d AND (%s=%d OR %s is null) AND %s LIKE '%%%s%%'", mCollectionId,DataStorage.Items.ID_COLLECTION,DataStorage.Items.TABLE_NAME + "." +DataStorage.Items.DELETED,1, DataStorage.Media.AVATAR,1,DataStorage.Media.AVATAR, DataStorage.Items.NAME,collectionElementText); break; case SEARCH_BY_DESCRIPTION: selection = String.format("%s = %s AND %s!=%d AND (%s=%d OR %s is null) AND %s LIKE '%%%s%%'", mCollectionId,DataStorage.Items.ID_COLLECTION,DataStorage.Items.TABLE_NAME + "." +DataStorage.Items.DELETED,1, DataStorage.Media.AVATAR,1,DataStorage.Media.AVATAR, DataStorage.Items.DESCRIPTION,collectionElementText); break; } //CursorLoader used to get data from user query return new CursorLoader(mContext, DataStorage.Items.CONTENT_URI, new String[]{DataStorage.Items.NAME, DataStorage.Media.FILE_NAME, DataStorage.Items.TABLE_NAME + "." + DataStorage.Items._ID}, selection, null, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { //Change cursor with data from database mImageAdapterList.swapCursor(data); } @Override public void onLoaderReset(Loader<Cursor> loader) { mImageAdapterList.swapCursor(null); } private void setSelectedTabSearchByName(String text) { mSearchByName.setTextColor(getResources().getColor(R.color.selected_tab_text_color)); mSearchByName.setText(text); } public void setUnselectedTabSearchByName(String text) { mSearchByName.setTextColor(getResources().getColor(R.color.black)); mSearchByName.setText(text); } private void setSelectedTabSearchAll(String text) { mSearchAll.setTextColor(getResources().getColor(R.color.selected_tab_text_color)); mSearchAll.setText(text); } public void setUnselectedTabSearchAll(String text) { mSearchAll.setTextColor(getResources().getColor(R.color.black)); mSearchAll.setText(text); } private void setSelectedTabSearchByDescription(String text) { mSearchByDescription.setTextColor(getResources().getColor(R.color.selected_tab_text_color)); mSearchByDescription.setText(text); } public void setUnselectedTabSearchByDescription(String text) { mSearchByDescription.setTextColor(getResources().getColor(R.color.black)); mSearchByDescription.setText(text); } @Override public void onDestroyView() { super.onDestroyView(); resetActionBarNavigationMode(); } @Override public void onResume() { super.onResume(); checkText(mTextToSearch); } private void resetActionBarNavigationMode() { //getting the action bar from the MainActivity ActionBar actionBar = ((ActionBarActivity) getActivity()).getSupportActionBar(); actionBar.removeAllTabs(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_HOME_AS_UP); actionBar.setDisplayShowTitleEnabled(true); } }
[ADD] context menu in SearchFragment
myHoard/src/main/java/com/myhoard/app/fragments/SearchFragment.java
[ADD] context menu in SearchFragment
Java
apache-2.0
25fed21759c4d3d99c319cae3084c11fafe282f4
0
cheekiatng/titanium_mobile,KangaCoders/titanium_mobile,peymanmortazavi/titanium_mobile,jhaynie/titanium_mobile,taoger/titanium_mobile,bhatfield/titanium_mobile,formalin14/titanium_mobile,prop/titanium_mobile,smit1625/titanium_mobile,pec1985/titanium_mobile,taoger/titanium_mobile,perdona/titanium_mobile,bright-sparks/titanium_mobile,shopmium/titanium_mobile,mano-mykingdom/titanium_mobile,perdona/titanium_mobile,bhatfield/titanium_mobile,rblalock/titanium_mobile,rblalock/titanium_mobile,KoketsoMabuela92/titanium_mobile,AngelkPetkov/titanium_mobile,mvitr/titanium_mobile,mano-mykingdom/titanium_mobile,prop/titanium_mobile,mano-mykingdom/titanium_mobile,prop/titanium_mobile,jvkops/titanium_mobile,KangaCoders/titanium_mobile,formalin14/titanium_mobile,shopmium/titanium_mobile,kopiro/titanium_mobile,shopmium/titanium_mobile,pinnamur/titanium_mobile,emilyvon/titanium_mobile,indera/titanium_mobile,AngelkPetkov/titanium_mobile,falkolab/titanium_mobile,bhatfield/titanium_mobile,benbahrenburg/titanium_mobile,pinnamur/titanium_mobile,linearhub/titanium_mobile,taoger/titanium_mobile,smit1625/titanium_mobile,KoketsoMabuela92/titanium_mobile,KoketsoMabuela92/titanium_mobile,smit1625/titanium_mobile,KangaCoders/titanium_mobile,openbaoz/titanium_mobile,collinprice/titanium_mobile,jhaynie/titanium_mobile,taoger/titanium_mobile,bright-sparks/titanium_mobile,KangaCoders/titanium_mobile,perdona/titanium_mobile,mvitr/titanium_mobile,rblalock/titanium_mobile,sriks/titanium_mobile,bright-sparks/titanium_mobile,smit1625/titanium_mobile,KangaCoders/titanium_mobile,smit1625/titanium_mobile,sriks/titanium_mobile,indera/titanium_mobile,emilyvon/titanium_mobile,peymanmortazavi/titanium_mobile,FokkeZB/titanium_mobile,sriks/titanium_mobile,benbahrenburg/titanium_mobile,ashcoding/titanium_mobile,linearhub/titanium_mobile,perdona/titanium_mobile,jvkops/titanium_mobile,linearhub/titanium_mobile,jhaynie/titanium_mobile,FokkeZB/titanium_mobile,pinnamur/titanium_mobile,csg-coder/titanium_mobile,mano-mykingdom/titanium_mobile,linearhub/titanium_mobile,FokkeZB/titanium_mobile,shopmium/titanium_mobile,openbaoz/titanium_mobile,csg-coder/titanium_mobile,bright-sparks/titanium_mobile,shopmium/titanium_mobile,ashcoding/titanium_mobile,jvkops/titanium_mobile,emilyvon/titanium_mobile,perdona/titanium_mobile,formalin14/titanium_mobile,AngelkPetkov/titanium_mobile,mano-mykingdom/titanium_mobile,KoketsoMabuela92/titanium_mobile,emilyvon/titanium_mobile,bhatfield/titanium_mobile,falkolab/titanium_mobile,shopmium/titanium_mobile,bright-sparks/titanium_mobile,collinprice/titanium_mobile,bhatfield/titanium_mobile,KoketsoMabuela92/titanium_mobile,kopiro/titanium_mobile,sriks/titanium_mobile,jvkops/titanium_mobile,taoger/titanium_mobile,indera/titanium_mobile,falkolab/titanium_mobile,linearhub/titanium_mobile,csg-coder/titanium_mobile,jvkops/titanium_mobile,collinprice/titanium_mobile,openbaoz/titanium_mobile,AngelkPetkov/titanium_mobile,linearhub/titanium_mobile,falkolab/titanium_mobile,mvitr/titanium_mobile,cheekiatng/titanium_mobile,prop/titanium_mobile,openbaoz/titanium_mobile,emilyvon/titanium_mobile,mvitr/titanium_mobile,rblalock/titanium_mobile,FokkeZB/titanium_mobile,pinnamur/titanium_mobile,peymanmortazavi/titanium_mobile,ashcoding/titanium_mobile,jhaynie/titanium_mobile,perdona/titanium_mobile,kopiro/titanium_mobile,pec1985/titanium_mobile,pinnamur/titanium_mobile,sriks/titanium_mobile,shopmium/titanium_mobile,benbahrenburg/titanium_mobile,peymanmortazavi/titanium_mobile,formalin14/titanium_mobile,sriks/titanium_mobile,emilyvon/titanium_mobile,pec1985/titanium_mobile,mano-mykingdom/titanium_mobile,peymanmortazavi/titanium_mobile,shopmium/titanium_mobile,smit1625/titanium_mobile,csg-coder/titanium_mobile,sriks/titanium_mobile,indera/titanium_mobile,openbaoz/titanium_mobile,pec1985/titanium_mobile,cheekiatng/titanium_mobile,pec1985/titanium_mobile,collinprice/titanium_mobile,formalin14/titanium_mobile,kopiro/titanium_mobile,AngelkPetkov/titanium_mobile,indera/titanium_mobile,pinnamur/titanium_mobile,KoketsoMabuela92/titanium_mobile,jhaynie/titanium_mobile,falkolab/titanium_mobile,mvitr/titanium_mobile,jvkops/titanium_mobile,prop/titanium_mobile,benbahrenburg/titanium_mobile,rblalock/titanium_mobile,jhaynie/titanium_mobile,rblalock/titanium_mobile,AngelkPetkov/titanium_mobile,indera/titanium_mobile,linearhub/titanium_mobile,kopiro/titanium_mobile,prop/titanium_mobile,prop/titanium_mobile,indera/titanium_mobile,pinnamur/titanium_mobile,rblalock/titanium_mobile,ashcoding/titanium_mobile,mano-mykingdom/titanium_mobile,mvitr/titanium_mobile,sriks/titanium_mobile,formalin14/titanium_mobile,ashcoding/titanium_mobile,falkolab/titanium_mobile,csg-coder/titanium_mobile,jvkops/titanium_mobile,FokkeZB/titanium_mobile,cheekiatng/titanium_mobile,mvitr/titanium_mobile,FokkeZB/titanium_mobile,pinnamur/titanium_mobile,ashcoding/titanium_mobile,csg-coder/titanium_mobile,benbahrenburg/titanium_mobile,cheekiatng/titanium_mobile,mvitr/titanium_mobile,smit1625/titanium_mobile,openbaoz/titanium_mobile,linearhub/titanium_mobile,pec1985/titanium_mobile,KoketsoMabuela92/titanium_mobile,perdona/titanium_mobile,AngelkPetkov/titanium_mobile,AngelkPetkov/titanium_mobile,pec1985/titanium_mobile,bright-sparks/titanium_mobile,benbahrenburg/titanium_mobile,emilyvon/titanium_mobile,taoger/titanium_mobile,emilyvon/titanium_mobile,pinnamur/titanium_mobile,pec1985/titanium_mobile,benbahrenburg/titanium_mobile,collinprice/titanium_mobile,bhatfield/titanium_mobile,openbaoz/titanium_mobile,jvkops/titanium_mobile,prop/titanium_mobile,kopiro/titanium_mobile,kopiro/titanium_mobile,KangaCoders/titanium_mobile,taoger/titanium_mobile,csg-coder/titanium_mobile,KoketsoMabuela92/titanium_mobile,KangaCoders/titanium_mobile,openbaoz/titanium_mobile,falkolab/titanium_mobile,jhaynie/titanium_mobile,kopiro/titanium_mobile,FokkeZB/titanium_mobile,peymanmortazavi/titanium_mobile,peymanmortazavi/titanium_mobile,ashcoding/titanium_mobile,indera/titanium_mobile,FokkeZB/titanium_mobile,KangaCoders/titanium_mobile,mano-mykingdom/titanium_mobile,formalin14/titanium_mobile,bright-sparks/titanium_mobile,perdona/titanium_mobile,csg-coder/titanium_mobile,rblalock/titanium_mobile,bhatfield/titanium_mobile,formalin14/titanium_mobile,collinprice/titanium_mobile,bright-sparks/titanium_mobile,falkolab/titanium_mobile,pec1985/titanium_mobile,jhaynie/titanium_mobile,smit1625/titanium_mobile,cheekiatng/titanium_mobile,cheekiatng/titanium_mobile,taoger/titanium_mobile,cheekiatng/titanium_mobile,peymanmortazavi/titanium_mobile,benbahrenburg/titanium_mobile,collinprice/titanium_mobile,collinprice/titanium_mobile,bhatfield/titanium_mobile,ashcoding/titanium_mobile
/** * Appcelerator Titanium Mobile * Copyright (c) 2009-2012 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ package org.appcelerator.titanium.view; import java.lang.ref.WeakReference; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.appcelerator.kroll.KrollDict; import org.appcelerator.kroll.KrollPropertyChange; import org.appcelerator.kroll.KrollProxy; import org.appcelerator.kroll.KrollProxyListener; import org.appcelerator.kroll.common.Log; import org.appcelerator.kroll.common.TiMessenger; import org.appcelerator.titanium.TiApplication; import org.appcelerator.titanium.TiC; import org.appcelerator.titanium.TiDimension; import org.appcelerator.titanium.proxy.TiViewProxy; import org.appcelerator.titanium.util.TiAnimationBuilder; import org.appcelerator.titanium.util.TiAnimationBuilder.TiMatrixAnimation; import org.appcelerator.titanium.util.TiConvert; import org.appcelerator.titanium.util.TiUIHelper; import org.appcelerator.titanium.view.TiCompositeLayout.LayoutParams; import org.appcelerator.titanium.view.TiGradientDrawable.GradientType; import android.app.Activity; import android.content.Context; import android.graphics.Paint; import android.graphics.Point; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.v4.view.ViewCompat; import android.text.TextUtils; import android.util.Pair; import android.util.SparseArray; import android.view.GestureDetector; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.ScaleGestureDetector.SimpleOnScaleGestureListener; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.view.View.OnKeyListener; import android.view.View.OnLongClickListener; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.ViewParent; import android.view.animation.Animation; import android.view.animation.AnimationSet; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; /** * This class is for Titanium View implementations, that correspond with TiViewProxy. * A TiUIView is responsible for creating and maintaining a native Android View instance. */ public abstract class TiUIView implements KrollProxyListener, OnFocusChangeListener { private static final boolean HONEYCOMB_OR_GREATER = (Build.VERSION.SDK_INT >= 11); private static final int LAYER_TYPE_SOFTWARE = 1; private static final String TAG = "TiUIView"; private static AtomicInteger idGenerator; // When distinguishing twofingertap and pinch events, minimum motion (in pixels) // to qualify as a scale event. private static final float SCALE_THRESHOLD = 6.0f; public static final int SOFT_KEYBOARD_DEFAULT_ON_FOCUS = 0; public static final int SOFT_KEYBOARD_HIDE_ON_FOCUS = 1; public static final int SOFT_KEYBOARD_SHOW_ON_FOCUS = 2; protected View nativeView; // Native View object protected TiViewProxy proxy; protected TiViewProxy parent; protected ArrayList<TiUIView> children = new ArrayList<TiUIView>(); protected LayoutParams layoutParams; protected TiAnimationBuilder animBuilder; protected TiBackgroundDrawable background; protected KrollDict additionalEventData; // Since Android doesn't have a property to check to indicate // the current animated x/y scale (from a scale animation), we track it here // so if another scale animation is done we can gleen the fromX and fromY values // rather than starting the next animation always from scale 1.0f (i.e., normal scale). // This gives us parity with iPhone for scale animations that use the 2-argument variant // of Ti2DMatrix.scale(). private Pair<Float, Float> animatedScaleValues = Pair.create(Float.valueOf(1f), Float.valueOf(1f)); // default = full size (1f) // Same for rotation animation and for alpha animation. private float animatedRotationDegrees = 0f; // i.e., no rotation. private float animatedAlpha = Float.MIN_VALUE; // i.e., no animated alpha. protected KrollDict lastUpEvent = new KrollDict(2); // In the case of heavy-weight windows, the "nativeView" is null, // so this holds a reference to the view which is used for touching, // i.e., the view passed to registerForTouch. private WeakReference<View> touchView = null; private Method mSetLayerTypeMethod = null; // Honeycomb, for turning off hw acceleration. private boolean zIndexChanged = false; private TiBorderWrapperView borderView; // For twofingertap detection private boolean didScale = false; //to maintain sync visibility between borderview and view. Default is visible private int visibility = View.VISIBLE; /** * Constructs a TiUIView object with the associated proxy. * @param proxy the associated proxy. * @module.api */ public TiUIView(TiViewProxy proxy) { if (idGenerator == null) { idGenerator = new AtomicInteger(0); } this.proxy = proxy; this.layoutParams = new TiCompositeLayout.LayoutParams(); } /** * Adds a child view into the ViewGroup. * @param child the view to be added. */ public void add(TiUIView child) { if (child != null) { View cv = child.getOuterView(); if (cv != null) { View nv = getNativeView(); if (nv instanceof ViewGroup) { if (cv.getParent() == null) { ((ViewGroup) nv).addView(cv, child.getLayoutParams()); } children.add(child); child.parent = proxy; } } } } /** * Removes the child view from the ViewGroup, if child exists. * @param child the view to be removed. */ public void remove(TiUIView child) { if (child != null) { View cv = child.getOuterView(); if (cv != null) { View nv = getNativeView(); if (nv instanceof ViewGroup) { ((ViewGroup) nv).removeView(cv); children.remove(child); child.parent = null; } } } } public void setAdditionalEventData(KrollDict dict) { additionalEventData = dict; } public KrollDict getAdditionalEventData() { return additionalEventData; } /** * @return list of views added. */ public List<TiUIView> getChildren() { return children; } /** * @return the view proxy. * @module.api */ public TiViewProxy getProxy() { return proxy; } /** * Sets the view proxy. * @param proxy the proxy to set. * @module.api */ public void setProxy(TiViewProxy proxy) { this.proxy = proxy; } public TiViewProxy getParent() { return parent; } public void setParent(TiViewProxy parent) { this.parent = parent; } /** * @return the view's layout params. * @module.api */ public LayoutParams getLayoutParams() { return layoutParams; } /** * @return the Android native view. * @module.api */ public View getNativeView() { return nativeView; } /** * Sets the nativeView to view. * @param view the view to set * @module.api */ protected void setNativeView(View view) { if (view.getId() == View.NO_ID) { view.setId(idGenerator.incrementAndGet()); } this.nativeView = view; boolean clickable = true; if (proxy.hasProperty(TiC.PROPERTY_TOUCH_ENABLED)) { clickable = TiConvert.toBoolean(proxy.getProperty(TiC.PROPERTY_TOUCH_ENABLED), true); } doSetClickable(nativeView, clickable); nativeView.setOnFocusChangeListener(this); applyAccessibilityProperties(); } protected void setLayoutParams(LayoutParams layoutParams) { this.layoutParams = layoutParams; } /** * Animates the view if there are pending animations. */ public void animate() { if (nativeView == null) { return; } // Pre-honeycomb, if one animation clobbers another you get a problem whereby the background of the // animated view's parent (or the grandparent) bleeds through. It seems to improve if you cancel and clear // the older animation. So here we cancel and clear, then re-queue the desired animation. if (Build.VERSION.SDK_INT < TiC.API_LEVEL_HONEYCOMB) { Animation currentAnimation = nativeView.getAnimation(); if (currentAnimation != null && currentAnimation.hasStarted() && !currentAnimation.hasEnded()) { // Cancel existing animation and // re-queue desired animation. currentAnimation.cancel(); nativeView.clearAnimation(); proxy.handlePendingAnimation(true); return; } } TiAnimationBuilder builder = proxy.getPendingAnimation(); if (builder == null) { return; } proxy.clearAnimation(builder); AnimationSet as = builder.render(proxy, nativeView); // If a view is "visible" but not currently seen (such as because it's covered or // its position is currently set to be fully outside its parent's region), // then Android might not animate it immediately because by default it animates // "on first frame" and apparently "first frame" won't happen right away if the // view has no visible rectangle on screen. In that case invalidate its parent, which will // kick off the pending animation. boolean invalidateParent = false; ViewParent viewParent = nativeView.getParent(); if (this.visibility == View.VISIBLE && viewParent instanceof View) { int width = nativeView.getWidth(); int height = nativeView.getHeight(); if (width == 0 || height == 0) { // Could be animating from nothing to something invalidateParent = true; } else { Rect r = new Rect(0, 0, width, height); Point p = new Point(0, 0); invalidateParent = !(viewParent.getChildVisibleRect(nativeView, r, p)); } } if (Log.isDebugModeEnabled()) { Log.d(TAG, "starting animation: " + as, Log.DEBUG_MODE); } nativeView.startAnimation(as); if (invalidateParent) { ((View) viewParent).postInvalidate(); } } public void listenerAdded(String type, int count, KrollProxy proxy) { } public void listenerRemoved(String type, int count, KrollProxy proxy){ } private boolean hasImage(KrollDict d) { return d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_IMAGE) || d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_SELECTED_IMAGE) || d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_FOCUSED_IMAGE) || d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_DISABLED_IMAGE); } private boolean hasRepeat(KrollDict d) { return d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_REPEAT); } private boolean hasGradient(KrollDict d) { return d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_GRADIENT); } private boolean hasBorder(KrollDict d) { return d.containsKeyAndNotNull(TiC.PROPERTY_BORDER_COLOR) || d.containsKeyAndNotNull(TiC.PROPERTY_BORDER_RADIUS) || d.containsKeyAndNotNull(TiC.PROPERTY_BORDER_WIDTH); } private boolean hasColorState(KrollDict d) { return d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_SELECTED_COLOR) || d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_FOCUSED_COLOR) || d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_FOCUSED_COLOR); } protected void applyTransform(Ti2DMatrix matrix) { layoutParams.optionTransform = matrix; if (animBuilder == null) { animBuilder = new TiAnimationBuilder(); } if (nativeView != null) { if (matrix != null) { TiMatrixAnimation matrixAnimation = animBuilder.createMatrixAnimation(matrix); matrixAnimation.interpolate = false; matrixAnimation.setDuration(1); matrixAnimation.setFillAfter(true); nativeView.startAnimation(matrixAnimation); } else { nativeView.clearAnimation(); } } } public void forceLayoutNativeView(boolean imformParent) { layoutNativeView(imformParent); } protected void layoutNativeView() { if (!this.proxy.isLayoutStarted()) { layoutNativeView(false); } } protected void layoutNativeView(boolean informParent) { if (nativeView != null) { Animation a = nativeView.getAnimation(); if (a != null && a instanceof TiMatrixAnimation) { TiMatrixAnimation matrixAnimation = (TiMatrixAnimation) a; matrixAnimation.invalidateWithMatrix(nativeView); } if (informParent) { if (parent != null) { TiUIView uiv = parent.peekView(); if (uiv != null) { View v = uiv.getNativeView(); if (v instanceof TiCompositeLayout) { ((TiCompositeLayout) v).resort(); } } } } nativeView.requestLayout(); } } public boolean iszIndexChanged() { return zIndexChanged; } public void setzIndexChanged(boolean zIndexChanged) { this.zIndexChanged = zIndexChanged; } public void propertyChanged(String key, Object oldValue, Object newValue, KrollProxy proxy) { if (key.equals(TiC.PROPERTY_LEFT)) { resetPostAnimationValues(); if (newValue != null) { layoutParams.optionLeft = TiConvert.toTiDimension(TiConvert.toString(newValue), TiDimension.TYPE_LEFT); } else { layoutParams.optionLeft = null; } layoutNativeView(); } else if (key.equals(TiC.PROPERTY_TOP)) { resetPostAnimationValues(); if (newValue != null) { layoutParams.optionTop = TiConvert.toTiDimension(TiConvert.toString(newValue), TiDimension.TYPE_TOP); } else { layoutParams.optionTop = null; } layoutNativeView(); } else if (key.equals(TiC.PROPERTY_CENTER)) { resetPostAnimationValues(); TiConvert.updateLayoutCenter(newValue, layoutParams); layoutNativeView(); } else if (key.equals(TiC.PROPERTY_RIGHT)) { resetPostAnimationValues(); if (newValue != null) { layoutParams.optionRight = TiConvert.toTiDimension(TiConvert.toString(newValue), TiDimension.TYPE_RIGHT); } else { layoutParams.optionRight = null; } layoutNativeView(); } else if (key.equals(TiC.PROPERTY_BOTTOM)) { resetPostAnimationValues(); if (newValue != null) { layoutParams.optionBottom = TiConvert.toTiDimension(TiConvert.toString(newValue), TiDimension.TYPE_BOTTOM); } else { layoutParams.optionBottom = null; } layoutNativeView(); } else if (key.equals(TiC.PROPERTY_SIZE)) { if (newValue instanceof HashMap) { @SuppressWarnings("unchecked") HashMap<String, Object> d = (HashMap<String, Object>) newValue; propertyChanged(TiC.PROPERTY_WIDTH, oldValue, d.get(TiC.PROPERTY_WIDTH), proxy); propertyChanged(TiC.PROPERTY_HEIGHT, oldValue, d.get(TiC.PROPERTY_HEIGHT), proxy); }else if (newValue != null){ Log.w(TAG, "Unsupported property type ("+(newValue.getClass().getSimpleName())+") for key: " + key+". Must be an object/dictionary"); } } else if (key.equals(TiC.PROPERTY_HEIGHT)) { resetPostAnimationValues(); if (newValue != null) { layoutParams.optionHeight = null; layoutParams.sizeOrFillHeightEnabled = true; if (newValue.equals(TiC.LAYOUT_SIZE)) { layoutParams.autoFillsHeight = false; } else if (newValue.equals(TiC.LAYOUT_FILL)) { layoutParams.autoFillsHeight = true; } else if (!newValue.equals(TiC.SIZE_AUTO)) { layoutParams.optionHeight = TiConvert.toTiDimension(TiConvert.toString(newValue), TiDimension.TYPE_HEIGHT); layoutParams.sizeOrFillHeightEnabled = false; } } else { layoutParams.optionHeight = null; } layoutNativeView(); } else if (key.equals(TiC.PROPERTY_HORIZONTAL_WRAP)) { if (nativeView instanceof TiCompositeLayout) { ((TiCompositeLayout) nativeView).setEnableHorizontalWrap(TiConvert.toBoolean(newValue,true)); } layoutNativeView(); } else if (key.equals(TiC.PROPERTY_WIDTH)) { resetPostAnimationValues(); if (newValue != null) { layoutParams.optionWidth = null; layoutParams.sizeOrFillWidthEnabled = true; if (newValue.equals(TiC.LAYOUT_SIZE)) { layoutParams.autoFillsWidth = false; } else if (newValue.equals(TiC.LAYOUT_FILL)) { layoutParams.autoFillsWidth = true; } else if (!newValue.equals(TiC.SIZE_AUTO)) { layoutParams.optionWidth = TiConvert.toTiDimension(TiConvert.toString(newValue), TiDimension.TYPE_WIDTH); layoutParams.sizeOrFillWidthEnabled = false; } } else { layoutParams.optionWidth = null; } layoutNativeView(); } else if (key.equals(TiC.PROPERTY_ZINDEX)) { if (newValue != null) { layoutParams.optionZIndex = TiConvert.toInt(newValue); } else { layoutParams.optionZIndex = 0; } if (!this.proxy.isLayoutStarted()) { layoutNativeView(true); } else { setzIndexChanged(true); } } else if (key.equals(TiC.PROPERTY_FOCUSABLE) && newValue != null) { registerForKeyPress(nativeView, TiConvert.toBoolean(newValue, false)); } else if (key.equals(TiC.PROPERTY_TOUCH_ENABLED)) { doSetClickable(TiConvert.toBoolean(newValue)); } else if (key.equals(TiC.PROPERTY_VISIBLE)) { this.setVisibility(TiConvert.toBoolean(newValue) ? View.VISIBLE : View.INVISIBLE); } else if (key.equals(TiC.PROPERTY_ENABLED)) { nativeView.setEnabled(TiConvert.toBoolean(newValue)); } else if (key.startsWith(TiC.PROPERTY_BACKGROUND_PADDING)) { Log.i(TAG, key + " not yet implemented."); } else if (key.equals(TiC.PROPERTY_OPACITY) || key.startsWith(TiC.PROPERTY_BACKGROUND_PREFIX) || key.startsWith(TiC.PROPERTY_BORDER_PREFIX)) { // Update first before querying. proxy.setProperty(key, newValue); KrollDict d = proxy.getProperties(); boolean hasImage = hasImage(d); boolean hasRepeat = hasRepeat(d); boolean hasColorState = hasColorState(d); boolean hasBorder = hasBorder(d); boolean hasGradient = hasGradient(d); boolean nativeViewNull = (nativeView == null); boolean requiresCustomBackground = hasImage || hasRepeat || hasColorState || hasBorder || hasGradient; if (!requiresCustomBackground) { if (background != null) { background.releaseDelegate(); background.setCallback(null); background = null; } if (d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_COLOR)) { Integer bgColor = TiConvert.toColor(d, TiC.PROPERTY_BACKGROUND_COLOR); if (!nativeViewNull) { nativeView.setBackgroundColor(bgColor); nativeView.postInvalidate(); } } else { if (key.equals(TiC.PROPERTY_OPACITY)) { setOpacity(TiConvert.toFloat(newValue, 1f)); } if (!nativeViewNull) { nativeView.setBackgroundDrawable(null); nativeView.postInvalidate(); } } } else { boolean newBackground = background == null; if (newBackground) { background = new TiBackgroundDrawable(); } Integer bgColor = null; if (!hasColorState && !hasGradient) { if (d.get(TiC.PROPERTY_BACKGROUND_COLOR) != null) { bgColor = TiConvert.toColor(d, TiC.PROPERTY_BACKGROUND_COLOR); if (newBackground || (key.equals(TiC.PROPERTY_OPACITY) || key.equals(TiC.PROPERTY_BACKGROUND_COLOR))) { background.setBackgroundColor(bgColor); } } } if (hasImage || hasRepeat || hasColorState || hasGradient) { if (newBackground || key.equals(TiC.PROPERTY_OPACITY) || key.startsWith(TiC.PROPERTY_BACKGROUND_PREFIX)) { handleBackgroundImage(d); } } if (hasBorder) { if (borderView == null && parent != null) { // Since we have to create a new border wrapper view, we need to remove this view, and re-add it. // This will ensure the border wrapper view is added correctly. TiUIView parentView = parent.getOrCreateView(); parentView.remove(this); initializeBorder(d, bgColor); parentView.add(this); } else if (key.startsWith(TiC.PROPERTY_BORDER_PREFIX)) { handleBorderProperty(key, newValue); } } applyCustomBackground(); if (key.equals(TiC.PROPERTY_OPACITY)) { setOpacity(TiConvert.toFloat(newValue, 1f)); } } if (!nativeViewNull) { nativeView.postInvalidate(); } } else if (key.equals(TiC.PROPERTY_SOFT_KEYBOARD_ON_FOCUS)) { Log.w(TAG, "Focus state changed to " + TiConvert.toString(newValue) + " not honored until next focus event.", Log.DEBUG_MODE); } else if (key.equals(TiC.PROPERTY_TRANSFORM)) { if (nativeView != null) { applyTransform((Ti2DMatrix)newValue); } } else if (key.equals(TiC.PROPERTY_KEEP_SCREEN_ON)) { if (nativeView != null) { nativeView.setKeepScreenOn(TiConvert.toBoolean(newValue)); } } else if (key.indexOf("accessibility") == 0 && !key.equals(TiC.PROPERTY_ACCESSIBILITY_HIDDEN)) { applyContentDescription(); } else if (key.equals(TiC.PROPERTY_ACCESSIBILITY_HIDDEN)) { applyAccessibilityHidden(newValue); } else if (Log.isDebugModeEnabled()) { Log.d(TAG, "Unhandled property key: " + key, Log.DEBUG_MODE); } } public void processProperties(KrollDict d) { boolean nativeViewNull = false; if (nativeView == null) { nativeViewNull = true; Log.d(TAG, "Nativeview is null", Log.DEBUG_MODE); } if (d.containsKey(TiC.PROPERTY_LAYOUT)) { String layout = TiConvert.toString(d, TiC.PROPERTY_LAYOUT); if (nativeView instanceof TiCompositeLayout) { ((TiCompositeLayout)nativeView).setLayoutArrangement(layout); } } if (TiConvert.fillLayout(d, layoutParams) && !nativeViewNull) { nativeView.requestLayout(); } if (d.containsKey(TiC.PROPERTY_HORIZONTAL_WRAP)) { if (nativeView instanceof TiCompositeLayout) { ((TiCompositeLayout) nativeView).setEnableHorizontalWrap(TiConvert.toBoolean(d,TiC.PROPERTY_HORIZONTAL_WRAP,true)); } } Integer bgColor = null; // Default background processing. // Prefer image to color. if (hasImage(d) || hasColorState(d) || hasGradient(d)) { handleBackgroundImage(d); } else if (d.containsKey(TiC.PROPERTY_BACKGROUND_COLOR) && !nativeViewNull) { bgColor = TiConvert.toColor(d, TiC.PROPERTY_BACKGROUND_COLOR); // Set the background color on the view directly only // if there is no border. If a border is present we must // use the TiBackgroundDrawable. if (hasBorder(d)) { if (background == null) { applyCustomBackground(false); } background.setBackgroundColor(bgColor); } else { nativeView.setBackgroundColor(bgColor); } } if (d.containsKey(TiC.PROPERTY_VISIBLE) && !nativeViewNull) { setVisibility(TiConvert.toBoolean(d, TiC.PROPERTY_VISIBLE, true) ? View.VISIBLE : View.INVISIBLE); } if (d.containsKey(TiC.PROPERTY_ENABLED) && !nativeViewNull) { nativeView.setEnabled(TiConvert.toBoolean(d, TiC.PROPERTY_ENABLED, true)); } initializeBorder(d, bgColor); if (d.containsKey(TiC.PROPERTY_OPACITY) && !nativeViewNull) { setOpacity(TiConvert.toFloat(d, TiC.PROPERTY_OPACITY, 1f)); } if (d.containsKey(TiC.PROPERTY_TRANSFORM)) { Ti2DMatrix matrix = (Ti2DMatrix) d.get(TiC.PROPERTY_TRANSFORM); if (matrix != null) { applyTransform(matrix); } } if (d.containsKey(TiC.PROPERTY_KEEP_SCREEN_ON) && !nativeViewNull) { nativeView.setKeepScreenOn(TiConvert.toBoolean(d, TiC.PROPERTY_KEEP_SCREEN_ON, false)); } if (d.containsKey(TiC.PROPERTY_ACCESSIBILITY_HINT) || d.containsKey(TiC.PROPERTY_ACCESSIBILITY_LABEL) || d.containsKey(TiC.PROPERTY_ACCESSIBILITY_VALUE) || d.containsKey(TiC.PROPERTY_ACCESSIBILITY_HIDDEN)) { applyAccessibilityProperties(); } } // TODO dead code? @Override public void propertiesChanged(List<KrollPropertyChange> changes, KrollProxy proxy) { for (KrollPropertyChange change : changes) { propertyChanged(change.getName(), change.getOldValue(), change.getNewValue(), proxy); } } private void applyCustomBackground() { applyCustomBackground(true); } private void applyCustomBackground(boolean reuseCurrentDrawable) { if (nativeView != null) { if (background == null) { background = new TiBackgroundDrawable(); Drawable currentDrawable = nativeView.getBackground(); if (currentDrawable != null) { if (reuseCurrentDrawable) { background.setBackgroundDrawable(currentDrawable); } else { nativeView.setBackgroundDrawable(null); currentDrawable.setCallback(null); if (currentDrawable instanceof TiBackgroundDrawable) { ((TiBackgroundDrawable) currentDrawable).releaseDelegate(); } } } } nativeView.setBackgroundDrawable(background); } } public void onFocusChange(final View v, boolean hasFocus) { if (hasFocus) { TiMessenger.postOnMain(new Runnable() { public void run() { TiUIHelper.requestSoftInputChange(proxy, v); } }); fireEvent(TiC.EVENT_FOCUS, getFocusEventObject(hasFocus)); } else { TiMessenger.postOnMain(new Runnable() { public void run() { TiUIHelper.showSoftKeyboard(v, false); } }); fireEvent(TiC.EVENT_BLUR, getFocusEventObject(hasFocus)); } } protected KrollDict getFocusEventObject(boolean hasFocus) { return null; } protected InputMethodManager getIMM() { InputMethodManager imm = null; imm = (InputMethodManager) TiApplication.getInstance().getSystemService(Context.INPUT_METHOD_SERVICE); return imm; } /** * Focuses the view. */ public void focus() { if (nativeView != null) { nativeView.requestFocus(); } } /** * Blurs the view. */ public void blur() { if (nativeView != null) { nativeView.clearFocus(); } } public void release() { if (Log.isDebugModeEnabled()) { Log.d(TAG, "Releasing: " + this, Log.DEBUG_MODE); } View nv = getNativeView(); if (nv != null) { if (nv instanceof ViewGroup) { ViewGroup vg = (ViewGroup) nv; if (Log.isDebugModeEnabled()) { Log.d(TAG, "Group has: " + vg.getChildCount(), Log.DEBUG_MODE); } if (!(vg instanceof AdapterView<?>)) { vg.removeAllViews(); } } Drawable d = nv.getBackground(); if (d != null) { nv.setBackgroundDrawable(null); d.setCallback(null); if (d instanceof TiBackgroundDrawable) { ((TiBackgroundDrawable)d).releaseDelegate(); } d = null; } nativeView = null; borderView = null; if (proxy != null) { proxy.setModelListener(null); } } } private void setVisibility(int visibility) { this.visibility = visibility; if (borderView != null) { borderView.setVisibility(this.visibility); } if (nativeView != null) { nativeView.setVisibility(this.visibility); } } /** * Shows the view, changing the view's visibility to View.VISIBLE. */ public void show() { this.setVisibility(View.VISIBLE); if (borderView == null && nativeView == null) { Log.w(TAG, "Attempt to show null native control", Log.DEBUG_MODE); } } /** * Hides the view, changing the view's visibility to View.INVISIBLE. */ public void hide() { this.setVisibility(View.INVISIBLE); if (borderView == null && nativeView == null) { Log.w(TAG, "Attempt to hide null native control", Log.DEBUG_MODE); } } private String resolveImageUrl(String path) { return path.length() > 0 ? proxy.resolveUrl(null, path) : null; } private void handleBackgroundImage(KrollDict d) { String bg = d.getString(TiC.PROPERTY_BACKGROUND_IMAGE); String bgSelected = d.optString(TiC.PROPERTY_BACKGROUND_SELECTED_IMAGE, bg); String bgFocused = d.optString(TiC.PROPERTY_BACKGROUND_FOCUSED_IMAGE, bg); String bgDisabled = d.optString(TiC.PROPERTY_BACKGROUND_DISABLED_IMAGE, bg); String bgColor = d.getString(TiC.PROPERTY_BACKGROUND_COLOR); String bgSelectedColor = d.optString(TiC.PROPERTY_BACKGROUND_SELECTED_COLOR, bgColor); String bgFocusedColor = d.optString(TiC.PROPERTY_BACKGROUND_FOCUSED_COLOR, bgColor); String bgDisabledColor = d.optString(TiC.PROPERTY_BACKGROUND_DISABLED_COLOR, bgColor); if (bg != null) { bg = resolveImageUrl(bg); } if (bgSelected != null) { bgSelected = resolveImageUrl(bgSelected); } if (bgFocused != null) { bgFocused = resolveImageUrl(bgFocused); } if (bgDisabled != null) { bgDisabled = resolveImageUrl(bgDisabled); } TiGradientDrawable gradientDrawable = null; KrollDict gradientProperties = d.getKrollDict(TiC.PROPERTY_BACKGROUND_GRADIENT); if (gradientProperties != null) { try { gradientDrawable = new TiGradientDrawable(nativeView, gradientProperties); if (gradientDrawable.getGradientType() == GradientType.RADIAL_GRADIENT) { // TODO: Remove this once we support radial gradients. Log.w(TAG, "Android does not support radial gradients."); gradientDrawable = null; } } catch (IllegalArgumentException e) { gradientDrawable = null; } } if (bg != null || bgSelected != null || bgFocused != null || bgDisabled != null || bgColor != null || bgSelectedColor != null || bgFocusedColor != null || bgDisabledColor != null || gradientDrawable != null) { if (background == null) { applyCustomBackground(false); } Drawable bgDrawable = TiUIHelper.buildBackgroundDrawable( bg, TiConvert.toBoolean(d, TiC.PROPERTY_BACKGROUND_REPEAT, false), bgColor, bgSelected, bgSelectedColor, bgDisabled, bgDisabledColor, bgFocused, bgFocusedColor, gradientDrawable); background.setBackgroundDrawable(bgDrawable); } } private void initializeBorder(KrollDict d, Integer bgColor) { if (hasBorder(d)) { if(nativeView != null) { if (borderView == null) { Activity currentActivity = proxy.getActivity(); if (currentActivity == null) { currentActivity = TiApplication.getAppCurrentActivity(); } borderView = new TiBorderWrapperView(currentActivity); // Create new layout params for the child view since we just want the // wrapper to control the layout LayoutParams params = new LayoutParams(); params.height = android.widget.FrameLayout.LayoutParams.MATCH_PARENT; params.width = android.widget.FrameLayout.LayoutParams.MATCH_PARENT; // If the view already has a parent, we need to detach it from the parent // and add the borderView to the parent as the child ViewGroup savedParent = null; if (nativeView.getParent() != null) { ViewParent nativeParent = nativeView.getParent(); if (nativeParent instanceof ViewGroup) { savedParent = (ViewGroup) nativeParent; savedParent.removeView(nativeView); } } borderView.addView(nativeView, params); if (savedParent != null) { savedParent.addView(borderView, getLayoutParams()); } borderView.setVisibility(this.visibility); } if (d.containsKey(TiC.PROPERTY_BORDER_RADIUS)) { float radius = TiConvert.toFloat(d, TiC.PROPERTY_BORDER_RADIUS, 0f); if (radius > 0f && HONEYCOMB_OR_GREATER) { disableHWAcceleration(); } borderView.setRadius(radius); } if (d.containsKey(TiC.PROPERTY_BORDER_COLOR) || d.containsKey(TiC.PROPERTY_BORDER_WIDTH)) { if (d.containsKey(TiC.PROPERTY_BORDER_COLOR)) { borderView.setColor(TiConvert.toColor(d, TiC.PROPERTY_BORDER_COLOR)); } else { if (bgColor != null) { borderView.setColor(bgColor); } } if (d.containsKey(TiC.PROPERTY_BORDER_WIDTH)) { TiDimension width = TiConvert .toTiDimension(d.get(TiC.PROPERTY_BORDER_WIDTH), TiDimension.TYPE_WIDTH); if (width != null) { borderView.setBorderWidth(width.getAsPixels(getNativeView())); } } } } } } private void handleBorderProperty(String property, Object value) { if (TiC.PROPERTY_BORDER_COLOR.equals(property)) { borderView.setColor(TiConvert.toColor(value.toString())); } else if (TiC.PROPERTY_BORDER_RADIUS.equals(property)) { float radius = TiConvert.toFloat(value, 0f); if (radius > 0f && HONEYCOMB_OR_GREATER) { disableHWAcceleration(); } borderView.setRadius(radius); } else if (TiC.PROPERTY_BORDER_WIDTH.equals(property)) { borderView.setBorderWidth(TiConvert.toFloat(value, 0f)); } borderView.postInvalidate(); } private static SparseArray<String> motionEvents = new SparseArray<String>(); static { motionEvents.put(MotionEvent.ACTION_DOWN, TiC.EVENT_TOUCH_START); motionEvents.put(MotionEvent.ACTION_UP, TiC.EVENT_TOUCH_END); motionEvents.put(MotionEvent.ACTION_MOVE, TiC.EVENT_TOUCH_MOVE); motionEvents.put(MotionEvent.ACTION_CANCEL, TiC.EVENT_TOUCH_CANCEL); } protected KrollDict dictFromEvent(MotionEvent e) { KrollDict data = new KrollDict(); data.put(TiC.EVENT_PROPERTY_X, (double)e.getX()); data.put(TiC.EVENT_PROPERTY_Y, (double)e.getY()); data.put(TiC.EVENT_PROPERTY_SOURCE, proxy); return data; } protected KrollDict dictFromEvent(KrollDict dictToCopy){ KrollDict data = new KrollDict(); if (dictToCopy.containsKey(TiC.EVENT_PROPERTY_X)){ data.put(TiC.EVENT_PROPERTY_X, dictToCopy.get(TiC.EVENT_PROPERTY_X)); } else { data.put(TiC.EVENT_PROPERTY_X, (double)0); } if (dictToCopy.containsKey(TiC.EVENT_PROPERTY_Y)){ data.put(TiC.EVENT_PROPERTY_Y, dictToCopy.get(TiC.EVENT_PROPERTY_Y)); } else { data.put(TiC.EVENT_PROPERTY_Y, (double)0); } data.put(TiC.EVENT_PROPERTY_SOURCE, proxy); return data; } protected boolean allowRegisterForTouch() { return true; } /** * @module.api */ protected boolean allowRegisterForKeyPress() { return true; } public View getOuterView() { return borderView == null ? nativeView : borderView; } public void registerForTouch() { if (allowRegisterForTouch()) { registerForTouch(getNativeView()); } } protected void registerTouchEvents(final View touchable) { touchView = new WeakReference<View>(touchable); final ScaleGestureDetector scaleDetector = new ScaleGestureDetector(touchable.getContext(), new SimpleOnScaleGestureListener() { // protect from divide by zero errors long minTimeDelta = 1; float minStartSpan = 1.0f; float startSpan; @Override public boolean onScale(ScaleGestureDetector sgd) { if (proxy.hierarchyHasListener(TiC.EVENT_PINCH)) { float timeDelta = sgd.getTimeDelta() == 0 ? minTimeDelta : sgd.getTimeDelta(); // Suppress scale events (and allow for possible two-finger tap events) // until we've moved at least a few pixels. Without this check, two-finger // taps are very hard to register on some older devices. if (!didScale) { if (Math.abs(sgd.getCurrentSpan() - startSpan) > SCALE_THRESHOLD) { didScale = true; } } if (didScale) { KrollDict data = new KrollDict(); data.put(TiC.EVENT_PROPERTY_SCALE, sgd.getCurrentSpan() / startSpan); data.put(TiC.EVENT_PROPERTY_VELOCITY, (sgd.getScaleFactor() - 1.0f) / timeDelta * 1000); data.put(TiC.EVENT_PROPERTY_SOURCE, proxy); return fireEvent(TiC.EVENT_PINCH, data); } } return false; } @Override public boolean onScaleBegin(ScaleGestureDetector sgd) { startSpan = sgd.getCurrentSpan() == 0 ? minStartSpan : sgd.getCurrentSpan(); return true; } }); final GestureDetector detector = new GestureDetector(touchable.getContext(), new SimpleOnGestureListener() { @Override public boolean onDoubleTap(MotionEvent e) { if (proxy.hierarchyHasListener(TiC.EVENT_DOUBLE_TAP) || proxy.hierarchyHasListener(TiC.EVENT_DOUBLE_CLICK)) { boolean handledTap = fireEvent(TiC.EVENT_DOUBLE_TAP, dictFromEvent(e)); boolean handledClick = fireEvent(TiC.EVENT_DOUBLE_CLICK, dictFromEvent(e)); return handledTap || handledClick; } return false; } @Override public boolean onSingleTapConfirmed(MotionEvent e) { Log.d(TAG, "TAP, TAP, TAP on " + proxy, Log.DEBUG_MODE); if (proxy.hierarchyHasListener(TiC.EVENT_SINGLE_TAP)) { return fireEvent(TiC.EVENT_SINGLE_TAP, dictFromEvent(e)); // Moved click handling to the onTouch listener, because a single tap is not the // same as a click. A single tap is a quick tap only, whereas clicks can be held // before lifting. // boolean handledClick = proxy.fireEvent(TiC.EVENT_CLICK, dictFromEvent(event)); // Note: this return value is irrelevant in our case. We "want" to use it // in onTouch below, when we call detector.onTouchEvent(event); But, in fact, // onSingleTapConfirmed is *not* called in the course of onTouchEvent. It's // called via Handler in GestureDetector. <-- See its Java source. // return handledTap;// || handledClick; } return false; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { Log.d(TAG, "SWIPE on " + proxy, Log.DEBUG_MODE); if (proxy.hierarchyHasListener(TiC.EVENT_SWIPE)) { KrollDict data = dictFromEvent(e2); if (Math.abs(velocityX) > Math.abs(velocityY)) { data.put(TiC.EVENT_PROPERTY_DIRECTION, velocityX > 0 ? "right" : "left"); } else { data.put(TiC.EVENT_PROPERTY_DIRECTION, velocityY > 0 ? "down" : "up"); } return fireEvent(TiC.EVENT_SWIPE, data); } return false; } @Override public void onLongPress(MotionEvent e) { Log.d(TAG, "LONGPRESS on " + proxy, Log.DEBUG_MODE); if (proxy.hierarchyHasListener(TiC.EVENT_LONGPRESS)) { fireEvent(TiC.EVENT_LONGPRESS, dictFromEvent(e)); } } }); touchable.setOnTouchListener(new OnTouchListener() { int pointersDown = 0; public boolean onTouch(View view, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { lastUpEvent.put(TiC.EVENT_PROPERTY_X, (double) event.getX()); lastUpEvent.put(TiC.EVENT_PROPERTY_Y, (double) event.getY()); } scaleDetector.onTouchEvent(event); if (scaleDetector.isInProgress()) { pointersDown = 0; return true; } boolean handled = detector.onTouchEvent(event); if (handled) { pointersDown = 0; return true; } if (event.getActionMasked() == MotionEvent.ACTION_POINTER_UP) { if (didScale) { didScale = false; pointersDown = 0; } else { pointersDown++; } } else if (event.getAction() == MotionEvent.ACTION_UP) { if (pointersDown == 1) { fireEvent(TiC.EVENT_TWOFINGERTAP, dictFromEvent(event)); pointersDown = 0; return true; } pointersDown = 0; } String motionEvent = motionEvents.get(event.getAction()); if (motionEvent != null) { if (proxy.hierarchyHasListener(motionEvent)) { fireEvent(motionEvent, dictFromEvent(event)); } } // Inside View.java, dispatchTouchEvent() does not call onTouchEvent() if this listener returns true. As // a result, click and other motion events do not occur on the native Android side. To prevent this, we // always return false and let Android generate click and other motion events. return false; } }); } protected void registerForTouch(final View touchable) { if (touchable == null) { return; } registerTouchEvents(touchable); // Previously, we used the single tap handling above to fire our click event. It doesn't // work: a single tap is not the same as a click. A click can be held for a while before // lifting the finger; a single-tap is only generated from a quick tap (which will also cause // a click.) We wanted to do it in single-tap handling presumably because the singletap // listener gets a MotionEvent, which gives us the information we want to provide to our // users in our click event, whereas Android's standard OnClickListener does _not_ contain // that info. However, an "up" seems to always occur before the click listener gets invoked, // so we store the last up event's x,y coordinates (see onTouch above) and use them here. // Note: AdapterView throws an exception if you try to put a click listener on it. doSetClickable(touchable); } public void registerForKeyPress() { if (allowRegisterForKeyPress()) { registerForKeyPress(getNativeView()); } } protected void registerForKeyPress(final View v) { if (v == null) { return; } Object focusable = proxy.getProperty(TiC.PROPERTY_FOCUSABLE); if (focusable != null) { registerForKeyPress(v, TiConvert.toBoolean(focusable, false)); } } protected void registerForKeyPress(final View v, boolean focusable) { if (v == null) { return; } v.setFocusable(focusable); // The listener for the "keypressed" event is only triggered when the view has focus. So we only register the // "keypressed" event when the view is focusable. if (focusable) { registerForKeyPressEvents(v); } else { v.setOnKeyListener(null); } } /** * Registers a callback to be invoked when a hardware key is pressed in this view. * * @param v The view to have the key listener to attach to. */ protected void registerForKeyPressEvents(final View v) { if (v == null) { return; } v.setOnKeyListener(new OnKeyListener() { public boolean onKey(View view, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_UP) { KrollDict data = new KrollDict(); data.put(TiC.EVENT_PROPERTY_KEYCODE, keyCode); fireEvent(TiC.EVENT_KEY_PRESSED, data); switch (keyCode) { case KeyEvent.KEYCODE_ENTER: case KeyEvent.KEYCODE_DPAD_CENTER: if (proxy.hasListeners(TiC.EVENT_CLICK)) { fireEvent(TiC.EVENT_CLICK, null); return true; } } } return false; } }); } /** * Sets the nativeView's opacity. * @param opacity the opacity to set. */ public void setOpacity(float opacity) { if (opacity < 0 || opacity > 1) { Log.w(TAG, "Ignoring invalid value for opacity: " + opacity); return; } if (borderView != null) { borderView.setBorderAlpha(Math.round(opacity * 255)); borderView.postInvalidate(); } if (nativeView != null) { if (HONEYCOMB_OR_GREATER) { nativeView.setAlpha(opacity); } else { setOpacity(nativeView, opacity); } nativeView.postInvalidate(); } } /** * Sets the view's opacity. * @param view the view object. * @param opacity the opacity to set. */ protected void setOpacity(View view, float opacity) { if (view != null) { TiUIHelper.setDrawableOpacity(view.getBackground(), opacity); if (opacity == 1) { clearOpacity(view); } } } public void clearOpacity(View view) { Drawable d = view.getBackground(); if (d != null) { d.clearColorFilter(); } } public KrollDict toImage() { return TiUIHelper.viewToImage(proxy.getProperties(), getNativeView()); } private View getTouchView() { if (nativeView != null) { return nativeView; } else { if (touchView != null) { return touchView.get(); } } return null; } private void doSetClickable(View view, boolean clickable) { if (view == null) { return; } if (!clickable) { view.setOnClickListener(null); // This will set clickable to true in the view, so make sure it stays here so the next line turns it off. view.setClickable(false); view.setOnLongClickListener(null); view.setLongClickable(false); } else if ( ! (view instanceof AdapterView) ){ // n.b.: AdapterView throws if click listener set. // n.b.: setting onclicklistener automatically sets clickable to true. setOnClickListener(view); setOnLongClickListener(view); } } private void doSetClickable(boolean clickable) { doSetClickable(getTouchView(), clickable); } /* * Used just to setup the click listener if applicable. */ private void doSetClickable(View view) { if (view == null) { return; } doSetClickable(view, view.isClickable()); } /** * Can be overriden by inheriting views for special click handling. For example, * the Facebook module's login button view needs special click handling. */ protected void setOnClickListener(View view) { view.setOnClickListener(new OnClickListener() { public void onClick(View view) { fireEvent(TiC.EVENT_CLICK, dictFromEvent(lastUpEvent)); } }); } public boolean fireEvent(String eventName, KrollDict data) { return fireEvent(eventName, data, true); } public boolean fireEvent(String eventName, KrollDict data, boolean bubbles) { if (data == null && additionalEventData != null) { data = new KrollDict(additionalEventData); } else if (additionalEventData != null) { data.putAll(additionalEventData); } return proxy.fireEvent(eventName, data, bubbles); } protected void setOnLongClickListener(View view) { view.setOnLongClickListener(new OnLongClickListener() { public boolean onLongClick(View view) { return fireEvent(TiC.EVENT_LONGCLICK, null); } }); } private void disableHWAcceleration() { if (borderView == null) { return; } Log.d(TAG, "Disabling hardware acceleration for instance of " + borderView.getClass().getSimpleName(), Log.DEBUG_MODE); if (mSetLayerTypeMethod == null) { try { Class<? extends View> c = borderView.getClass(); mSetLayerTypeMethod = c.getMethod("setLayerType", int.class, Paint.class); } catch (SecurityException e) { Log.e(TAG, "SecurityException trying to get View.setLayerType to disable hardware acceleration.", e, Log.DEBUG_MODE); } catch (NoSuchMethodException e) { Log.e(TAG, "NoSuchMethodException trying to get View.setLayerType to disable hardware acceleration.", e, Log.DEBUG_MODE); } } if (mSetLayerTypeMethod == null) { return; } try { mSetLayerTypeMethod.invoke(borderView, LAYER_TYPE_SOFTWARE, null); } catch (IllegalArgumentException e) { Log.e(TAG, e.getMessage(), e); } catch (IllegalAccessException e) { Log.e(TAG, e.getMessage(), e); } catch (InvocationTargetException e) { Log.e(TAG, e.getMessage(), e); } } /** * Retrieve the saved animated scale values, which we store here since Android provides no property * for looking them up. */ public Pair<Float, Float> getAnimatedScaleValues() { return animatedScaleValues; } /** * Store the animated x and y scale values (i.e., the scale after an animation) * since Android provides no property for looking them up. */ public void setAnimatedScaleValues(Pair<Float, Float> newValues) { animatedScaleValues = newValues; } /** * Set the animated rotation degrees, since Android provides no property for looking it up. */ public void setAnimatedRotationDegrees(float degrees) { animatedRotationDegrees = degrees; } /** * Retrieve the animated rotation degrees, which we store here since Android provides no property * for looking it up. */ public float getAnimatedRotationDegrees() { return animatedRotationDegrees; } /** * Set the animated alpha values, since Android provides no property for looking it up. */ public void setAnimatedAlpha(float alpha) { animatedAlpha = alpha; } /** * Retrieve the animated alpha value, which we store here since Android provides no property * for looking it up. */ public float getAnimatedAlpha() { return animatedAlpha; } /** * "Forget" the values we save after scale and rotation and alpha animations. */ private void resetPostAnimationValues() { animatedRotationDegrees = 0f; // i.e., no rotation. animatedScaleValues = Pair.create(Float.valueOf(1f), Float.valueOf(1f)); // 1 means no scaling animatedAlpha = Float.MIN_VALUE; // we use min val to signal no val. } private void applyContentDescription() { if (proxy == null || nativeView == null) { return; } String contentDescription = composeContentDescription(); if (contentDescription != null) { nativeView.setContentDescription(contentDescription); } } /** * Our view proxy supports three properties to match iOS regarding * the text that is read aloud (or otherwise communicated) by the * assistive technology: accessibilityLabel, accessibilityHint * and accessibilityValue. * * We combine these to create the single Android property contentDescription. * (e.g., View.setContentDescription(...)); */ protected String composeContentDescription() { if (proxy == null) { return null; } final String punctuationPattern = "^.*\\p{Punct}\\s*$"; StringBuilder buffer = new StringBuilder(); KrollDict properties = proxy.getProperties(); String label, hint, value; label = TiConvert.toString(properties.get(TiC.PROPERTY_ACCESSIBILITY_LABEL)); hint = TiConvert.toString(properties.get(TiC.PROPERTY_ACCESSIBILITY_HINT)); value = TiConvert.toString(properties.get(TiC.PROPERTY_ACCESSIBILITY_VALUE)); if (!TextUtils.isEmpty(label)) { buffer.append(label); if (!label.matches(punctuationPattern)) { buffer.append("."); } } if (!TextUtils.isEmpty(value)) { if (buffer.length() > 0) { buffer.append(" "); } buffer.append(value); if (!value.matches(punctuationPattern)) { buffer.append("."); } } if (!TextUtils.isEmpty(hint)) { if (buffer.length() > 0) { buffer.append(" "); } buffer.append(hint); if (!hint.matches(punctuationPattern)) { buffer.append("."); } } return buffer.toString(); } private void applyAccessibilityProperties() { if (nativeView != null) { applyContentDescription(); applyAccessibilityHidden(); } } private void applyAccessibilityHidden() { if (nativeView == null || proxy == null) { return; } applyAccessibilityHidden(proxy.getProperty(TiC.PROPERTY_ACCESSIBILITY_HIDDEN)); } private void applyAccessibilityHidden(Object hiddenPropertyValue) { if (nativeView == null) { return; } int importanceMode = ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO; if (hiddenPropertyValue != null && TiConvert.toBoolean(hiddenPropertyValue, false)) { importanceMode = ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO; } ViewCompat.setImportantForAccessibility(nativeView, importanceMode); } }
android/titanium/src/java/org/appcelerator/titanium/view/TiUIView.java
/** * Appcelerator Titanium Mobile * Copyright (c) 2009-2012 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ package org.appcelerator.titanium.view; import java.lang.ref.WeakReference; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.appcelerator.kroll.KrollDict; import org.appcelerator.kroll.KrollPropertyChange; import org.appcelerator.kroll.KrollProxy; import org.appcelerator.kroll.KrollProxyListener; import org.appcelerator.kroll.common.Log; import org.appcelerator.kroll.common.TiMessenger; import org.appcelerator.titanium.TiApplication; import org.appcelerator.titanium.TiC; import org.appcelerator.titanium.TiDimension; import org.appcelerator.titanium.proxy.TiViewProxy; import org.appcelerator.titanium.util.TiAnimationBuilder; import org.appcelerator.titanium.util.TiAnimationBuilder.TiMatrixAnimation; import org.appcelerator.titanium.util.TiConvert; import org.appcelerator.titanium.util.TiUIHelper; import org.appcelerator.titanium.view.TiCompositeLayout.LayoutParams; import org.appcelerator.titanium.view.TiGradientDrawable.GradientType; import android.app.Activity; import android.content.Context; import android.graphics.Paint; import android.graphics.Point; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.v4.view.ViewCompat; import android.text.TextUtils; import android.util.Pair; import android.util.SparseArray; import android.view.GestureDetector; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.ScaleGestureDetector.SimpleOnScaleGestureListener; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.view.View.OnKeyListener; import android.view.View.OnLongClickListener; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.ViewParent; import android.view.animation.Animation; import android.view.animation.AnimationSet; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; /** * This class is for Titanium View implementations, that correspond with TiViewProxy. * A TiUIView is responsible for creating and maintaining a native Android View instance. */ public abstract class TiUIView implements KrollProxyListener, OnFocusChangeListener { private static final boolean HONEYCOMB_OR_GREATER = (Build.VERSION.SDK_INT >= 11); private static final int LAYER_TYPE_SOFTWARE = 1; private static final String TAG = "TiUIView"; private static AtomicInteger idGenerator; // When distinguishing twofingertap and pinch events, minimum motion (in pixels) // to qualify as a scale event. private static final float SCALE_THRESHOLD = 6.0f; public static final int SOFT_KEYBOARD_DEFAULT_ON_FOCUS = 0; public static final int SOFT_KEYBOARD_HIDE_ON_FOCUS = 1; public static final int SOFT_KEYBOARD_SHOW_ON_FOCUS = 2; protected View nativeView; // Native View object protected TiViewProxy proxy; protected TiViewProxy parent; protected ArrayList<TiUIView> children = new ArrayList<TiUIView>(); protected LayoutParams layoutParams; protected TiAnimationBuilder animBuilder; protected TiBackgroundDrawable background; protected KrollDict additionalEventData; // Since Android doesn't have a property to check to indicate // the current animated x/y scale (from a scale animation), we track it here // so if another scale animation is done we can gleen the fromX and fromY values // rather than starting the next animation always from scale 1.0f (i.e., normal scale). // This gives us parity with iPhone for scale animations that use the 2-argument variant // of Ti2DMatrix.scale(). private Pair<Float, Float> animatedScaleValues = Pair.create(Float.valueOf(1f), Float.valueOf(1f)); // default = full size (1f) // Same for rotation animation and for alpha animation. private float animatedRotationDegrees = 0f; // i.e., no rotation. private float animatedAlpha = Float.MIN_VALUE; // i.e., no animated alpha. protected KrollDict lastUpEvent = new KrollDict(2); // In the case of heavy-weight windows, the "nativeView" is null, // so this holds a reference to the view which is used for touching, // i.e., the view passed to registerForTouch. private WeakReference<View> touchView = null; private Method mSetLayerTypeMethod = null; // Honeycomb, for turning off hw acceleration. private boolean zIndexChanged = false; private TiBorderWrapperView borderView; // For twofingertap detection private boolean didScale = false; //to maintain sync visibility between borderview and view. Default is visible private int visibility = View.VISIBLE; /** * Constructs a TiUIView object with the associated proxy. * @param proxy the associated proxy. * @module.api */ public TiUIView(TiViewProxy proxy) { if (idGenerator == null) { idGenerator = new AtomicInteger(0); } this.proxy = proxy; this.layoutParams = new TiCompositeLayout.LayoutParams(); } /** * Adds a child view into the ViewGroup. * @param child the view to be added. */ public void add(TiUIView child) { if (child != null) { View cv = child.getOuterView(); if (cv != null) { View nv = getNativeView(); if (nv instanceof ViewGroup) { if (cv.getParent() == null) { ((ViewGroup) nv).addView(cv, child.getLayoutParams()); } children.add(child); child.parent = proxy; } } } } /** * Removes the child view from the ViewGroup, if child exists. * @param child the view to be removed. */ public void remove(TiUIView child) { if (child != null) { View cv = child.getOuterView(); if (cv != null) { View nv = getNativeView(); if (nv instanceof ViewGroup) { ((ViewGroup) nv).removeView(cv); children.remove(child); child.parent = null; } } } } public void setAdditionalEventData(KrollDict dict) { additionalEventData = dict; } public KrollDict getAdditionalEventData() { return additionalEventData; } /** * @return list of views added. */ public List<TiUIView> getChildren() { return children; } /** * @return the view proxy. * @module.api */ public TiViewProxy getProxy() { return proxy; } /** * Sets the view proxy. * @param proxy the proxy to set. * @module.api */ public void setProxy(TiViewProxy proxy) { this.proxy = proxy; } public TiViewProxy getParent() { return parent; } public void setParent(TiViewProxy parent) { this.parent = parent; } /** * @return the view's layout params. * @module.api */ public LayoutParams getLayoutParams() { return layoutParams; } /** * @return the Android native view. * @module.api */ public View getNativeView() { return nativeView; } /** * Sets the nativeView to view. * @param view the view to set * @module.api */ protected void setNativeView(View view) { if (view.getId() == View.NO_ID) { view.setId(idGenerator.incrementAndGet()); } this.nativeView = view; boolean clickable = true; if (proxy.hasProperty(TiC.PROPERTY_TOUCH_ENABLED)) { clickable = TiConvert.toBoolean(proxy.getProperty(TiC.PROPERTY_TOUCH_ENABLED), true); } doSetClickable(nativeView, clickable); nativeView.setOnFocusChangeListener(this); applyAccessibilityProperties(); } protected void setLayoutParams(LayoutParams layoutParams) { this.layoutParams = layoutParams; } /** * Animates the view if there are pending animations. */ public void animate() { if (nativeView == null) { return; } // Pre-honeycomb, if one animation clobbers another you get a problem whereby the background of the // animated view's parent (or the grandparent) bleeds through. It seems to improve if you cancel and clear // the older animation. So here we cancel and clear, then re-queue the desired animation. if (Build.VERSION.SDK_INT < TiC.API_LEVEL_HONEYCOMB) { Animation currentAnimation = nativeView.getAnimation(); if (currentAnimation != null && currentAnimation.hasStarted() && !currentAnimation.hasEnded()) { // Cancel existing animation and // re-queue desired animation. currentAnimation.cancel(); nativeView.clearAnimation(); proxy.handlePendingAnimation(true); return; } } TiAnimationBuilder builder = proxy.getPendingAnimation(); if (builder == null) { return; } proxy.clearAnimation(builder); AnimationSet as = builder.render(proxy, nativeView); // If a view is "visible" but not currently seen (such as because it's covered or // its position is currently set to be fully outside its parent's region), // then Android might not animate it immediately because by default it animates // "on first frame" and apparently "first frame" won't happen right away if the // view has no visible rectangle on screen. In that case invalidate its parent, which will // kick off the pending animation. boolean invalidateParent = false; ViewParent viewParent = nativeView.getParent(); if (this.visibility == View.VISIBLE && viewParent instanceof View) { int width = nativeView.getWidth(); int height = nativeView.getHeight(); if (width == 0 || height == 0) { // Could be animating from nothing to something invalidateParent = true; } else { Rect r = new Rect(0, 0, width, height); Point p = new Point(0, 0); invalidateParent = !(viewParent.getChildVisibleRect(nativeView, r, p)); } } if (Log.isDebugModeEnabled()) { Log.d(TAG, "starting animation: " + as, Log.DEBUG_MODE); } nativeView.startAnimation(as); if (invalidateParent) { ((View) viewParent).postInvalidate(); } } public void listenerAdded(String type, int count, KrollProxy proxy) { } public void listenerRemoved(String type, int count, KrollProxy proxy){ } private boolean hasImage(KrollDict d) { return d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_IMAGE) || d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_SELECTED_IMAGE) || d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_FOCUSED_IMAGE) || d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_DISABLED_IMAGE); } private boolean hasRepeat(KrollDict d) { return d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_REPEAT); } private boolean hasGradient(KrollDict d) { return d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_GRADIENT); } private boolean hasBorder(KrollDict d) { return d.containsKeyAndNotNull(TiC.PROPERTY_BORDER_COLOR) || d.containsKeyAndNotNull(TiC.PROPERTY_BORDER_RADIUS) || d.containsKeyAndNotNull(TiC.PROPERTY_BORDER_WIDTH); } private boolean hasColorState(KrollDict d) { return d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_SELECTED_COLOR) || d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_FOCUSED_COLOR) || d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_FOCUSED_COLOR); } protected void applyTransform(Ti2DMatrix matrix) { layoutParams.optionTransform = matrix; if (animBuilder == null) { animBuilder = new TiAnimationBuilder(); } if (nativeView != null) { if (matrix != null) { TiMatrixAnimation matrixAnimation = animBuilder.createMatrixAnimation(matrix); matrixAnimation.interpolate = false; matrixAnimation.setDuration(1); matrixAnimation.setFillAfter(true); nativeView.startAnimation(matrixAnimation); } else { nativeView.clearAnimation(); } } } public void forceLayoutNativeView(boolean imformParent) { layoutNativeView(imformParent); } protected void layoutNativeView() { if (!this.proxy.isLayoutStarted()) { layoutNativeView(false); } } protected void layoutNativeView(boolean informParent) { if (nativeView != null) { Animation a = nativeView.getAnimation(); if (a != null && a instanceof TiMatrixAnimation) { TiMatrixAnimation matrixAnimation = (TiMatrixAnimation) a; matrixAnimation.invalidateWithMatrix(nativeView); } if (informParent) { if (parent != null) { TiUIView uiv = parent.peekView(); if (uiv != null) { View v = uiv.getNativeView(); if (v instanceof TiCompositeLayout) { ((TiCompositeLayout) v).resort(); } } } } nativeView.requestLayout(); } } public boolean iszIndexChanged() { return zIndexChanged; } public void setzIndexChanged(boolean zIndexChanged) { this.zIndexChanged = zIndexChanged; } public void propertyChanged(String key, Object oldValue, Object newValue, KrollProxy proxy) { if (key.equals(TiC.PROPERTY_LEFT)) { resetPostAnimationValues(); if (newValue != null) { layoutParams.optionLeft = TiConvert.toTiDimension(TiConvert.toString(newValue), TiDimension.TYPE_LEFT); } else { layoutParams.optionLeft = null; } layoutNativeView(); } else if (key.equals(TiC.PROPERTY_TOP)) { resetPostAnimationValues(); if (newValue != null) { layoutParams.optionTop = TiConvert.toTiDimension(TiConvert.toString(newValue), TiDimension.TYPE_TOP); } else { layoutParams.optionTop = null; } layoutNativeView(); } else if (key.equals(TiC.PROPERTY_CENTER)) { resetPostAnimationValues(); TiConvert.updateLayoutCenter(newValue, layoutParams); layoutNativeView(); } else if (key.equals(TiC.PROPERTY_RIGHT)) { resetPostAnimationValues(); if (newValue != null) { layoutParams.optionRight = TiConvert.toTiDimension(TiConvert.toString(newValue), TiDimension.TYPE_RIGHT); } else { layoutParams.optionRight = null; } layoutNativeView(); } else if (key.equals(TiC.PROPERTY_BOTTOM)) { resetPostAnimationValues(); if (newValue != null) { layoutParams.optionBottom = TiConvert.toTiDimension(TiConvert.toString(newValue), TiDimension.TYPE_BOTTOM); } else { layoutParams.optionBottom = null; } layoutNativeView(); } else if (key.equals(TiC.PROPERTY_SIZE)) { if (newValue instanceof HashMap) { @SuppressWarnings("unchecked") HashMap<String, Object> d = (HashMap<String, Object>) newValue; propertyChanged(TiC.PROPERTY_WIDTH, oldValue, d.get(TiC.PROPERTY_WIDTH), proxy); propertyChanged(TiC.PROPERTY_HEIGHT, oldValue, d.get(TiC.PROPERTY_HEIGHT), proxy); }else if (newValue != null){ Log.w(TAG, "Unsupported property type ("+(newValue.getClass().getSimpleName())+") for key: " + key+". Must be an object/dictionary"); } } else if (key.equals(TiC.PROPERTY_HEIGHT)) { resetPostAnimationValues(); if (newValue != null) { layoutParams.optionHeight = null; layoutParams.sizeOrFillHeightEnabled = true; if (newValue.equals(TiC.LAYOUT_SIZE)) { layoutParams.autoFillsHeight = false; } else if (newValue.equals(TiC.LAYOUT_FILL)) { layoutParams.autoFillsHeight = true; } else if (!newValue.equals(TiC.SIZE_AUTO)) { layoutParams.optionHeight = TiConvert.toTiDimension(TiConvert.toString(newValue), TiDimension.TYPE_HEIGHT); layoutParams.sizeOrFillHeightEnabled = false; } } else { layoutParams.optionHeight = null; } layoutNativeView(); } else if (key.equals(TiC.PROPERTY_HORIZONTAL_WRAP)) { if (nativeView instanceof TiCompositeLayout) { ((TiCompositeLayout) nativeView).setEnableHorizontalWrap(TiConvert.toBoolean(newValue,true)); } layoutNativeView(); } else if (key.equals(TiC.PROPERTY_WIDTH)) { resetPostAnimationValues(); if (newValue != null) { layoutParams.optionWidth = null; layoutParams.sizeOrFillWidthEnabled = true; if (newValue.equals(TiC.LAYOUT_SIZE)) { layoutParams.autoFillsWidth = false; } else if (newValue.equals(TiC.LAYOUT_FILL)) { layoutParams.autoFillsWidth = true; } else if (!newValue.equals(TiC.SIZE_AUTO)) { layoutParams.optionWidth = TiConvert.toTiDimension(TiConvert.toString(newValue), TiDimension.TYPE_WIDTH); layoutParams.sizeOrFillWidthEnabled = false; } } else { layoutParams.optionWidth = null; } layoutNativeView(); } else if (key.equals(TiC.PROPERTY_ZINDEX)) { if (newValue != null) { layoutParams.optionZIndex = TiConvert.toInt(newValue); } else { layoutParams.optionZIndex = 0; } if (!this.proxy.isLayoutStarted()) { layoutNativeView(true); } else { setzIndexChanged(true); } } else if (key.equals(TiC.PROPERTY_FOCUSABLE) && newValue != null) { registerForKeyPress(nativeView, TiConvert.toBoolean(newValue, false)); } else if (key.equals(TiC.PROPERTY_TOUCH_ENABLED)) { doSetClickable(TiConvert.toBoolean(newValue)); } else if (key.equals(TiC.PROPERTY_VISIBLE)) { this.setVisibility(TiConvert.toBoolean(newValue) ? View.VISIBLE : View.INVISIBLE); } else if (key.equals(TiC.PROPERTY_ENABLED)) { nativeView.setEnabled(TiConvert.toBoolean(newValue)); } else if (key.startsWith(TiC.PROPERTY_BACKGROUND_PADDING)) { Log.i(TAG, key + " not yet implemented."); } else if (key.equals(TiC.PROPERTY_OPACITY) || key.startsWith(TiC.PROPERTY_BACKGROUND_PREFIX) || key.startsWith(TiC.PROPERTY_BORDER_PREFIX)) { // Update first before querying. proxy.setProperty(key, newValue); KrollDict d = proxy.getProperties(); boolean hasImage = hasImage(d); boolean hasRepeat = hasRepeat(d); boolean hasColorState = hasColorState(d); boolean hasBorder = hasBorder(d); boolean hasGradient = hasGradient(d); boolean nativeViewNull = (nativeView == null); boolean requiresCustomBackground = hasImage || hasRepeat || hasColorState || hasBorder || hasGradient; if (!requiresCustomBackground) { if (background != null) { background.releaseDelegate(); background.setCallback(null); background = null; } if (d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_COLOR)) { Integer bgColor = TiConvert.toColor(d, TiC.PROPERTY_BACKGROUND_COLOR); if (!nativeViewNull) { nativeView.setBackgroundColor(bgColor); nativeView.postInvalidate(); } } else { if (key.equals(TiC.PROPERTY_OPACITY)) { setOpacity(TiConvert.toFloat(newValue, 1f)); } if (!nativeViewNull) { nativeView.setBackgroundDrawable(null); nativeView.postInvalidate(); } } } else { boolean newBackground = background == null; if (newBackground) { background = new TiBackgroundDrawable(); } Integer bgColor = null; if (!hasColorState && !hasGradient) { if (d.get(TiC.PROPERTY_BACKGROUND_COLOR) != null) { bgColor = TiConvert.toColor(d, TiC.PROPERTY_BACKGROUND_COLOR); if (newBackground || (key.equals(TiC.PROPERTY_OPACITY) || key.equals(TiC.PROPERTY_BACKGROUND_COLOR))) { background.setBackgroundColor(bgColor); } } } if (hasImage || hasRepeat || hasColorState || hasGradient) { if (newBackground || key.equals(TiC.PROPERTY_OPACITY) || key.startsWith(TiC.PROPERTY_BACKGROUND_PREFIX)) { handleBackgroundImage(d); } } if (hasBorder) { if (borderView == null && parent != null) { // Since we have to create a new border wrapper view, we need to remove this view, and re-add it. // This will ensure the border wrapper view is added correctly. TiUIView parentView = parent.getOrCreateView(); parentView.remove(this); initializeBorder(d, bgColor); parentView.add(this); } else if (key.startsWith(TiC.PROPERTY_BORDER_PREFIX)) { handleBorderProperty(key, newValue); } } applyCustomBackground(); if (key.equals(TiC.PROPERTY_OPACITY)) { setOpacity(TiConvert.toFloat(newValue, 1f)); } } if (!nativeViewNull) { nativeView.postInvalidate(); } } else if (key.equals(TiC.PROPERTY_SOFT_KEYBOARD_ON_FOCUS)) { Log.w(TAG, "Focus state changed to " + TiConvert.toString(newValue) + " not honored until next focus event.", Log.DEBUG_MODE); } else if (key.equals(TiC.PROPERTY_TRANSFORM)) { if (nativeView != null) { applyTransform((Ti2DMatrix)newValue); } } else if (key.equals(TiC.PROPERTY_KEEP_SCREEN_ON)) { if (nativeView != null) { nativeView.setKeepScreenOn(TiConvert.toBoolean(newValue)); } } else if (key.indexOf("accessibility") == 0 && !key.equals(TiC.PROPERTY_ACCESSIBILITY_HIDDEN)) { applyContentDescription(); } else if (key.equals(TiC.PROPERTY_ACCESSIBILITY_HIDDEN)) { applyAccessibilityHidden(newValue); } else if (Log.isDebugModeEnabled()) { Log.d(TAG, "Unhandled property key: " + key, Log.DEBUG_MODE); } } public void processProperties(KrollDict d) { boolean nativeViewNull = false; if (nativeView == null) { nativeViewNull = true; Log.d(TAG, "Nativeview is null", Log.DEBUG_MODE); } if (d.containsKey(TiC.PROPERTY_LAYOUT)) { String layout = TiConvert.toString(d, TiC.PROPERTY_LAYOUT); if (nativeView instanceof TiCompositeLayout) { ((TiCompositeLayout)nativeView).setLayoutArrangement(layout); } } if (TiConvert.fillLayout(d, layoutParams) && !nativeViewNull) { nativeView.requestLayout(); } if (d.containsKey(TiC.PROPERTY_HORIZONTAL_WRAP)) { if (nativeView instanceof TiCompositeLayout) { ((TiCompositeLayout) nativeView).setEnableHorizontalWrap(TiConvert.toBoolean(d,TiC.PROPERTY_HORIZONTAL_WRAP,true)); } } Integer bgColor = null; // Default background processing. // Prefer image to color. if (hasImage(d) || hasColorState(d) || hasGradient(d)) { handleBackgroundImage(d); } else if (d.containsKey(TiC.PROPERTY_BACKGROUND_COLOR) && !nativeViewNull) { bgColor = TiConvert.toColor(d, TiC.PROPERTY_BACKGROUND_COLOR); // Set the background color on the view directly only // if there is no border. If a border is present we must // use the TiBackgroundDrawable. if (hasBorder(d)) { if (background == null) { applyCustomBackground(false); } background.setBackgroundColor(bgColor); } else { nativeView.setBackgroundColor(bgColor); } } if (d.containsKey(TiC.PROPERTY_VISIBLE) && !nativeViewNull) { setVisibility(TiConvert.toBoolean(d, TiC.PROPERTY_VISIBLE, true) ? View.VISIBLE : View.INVISIBLE); } if (d.containsKey(TiC.PROPERTY_ENABLED) && !nativeViewNull) { nativeView.setEnabled(TiConvert.toBoolean(d, TiC.PROPERTY_ENABLED, true)); } initializeBorder(d, bgColor); if (d.containsKey(TiC.PROPERTY_OPACITY) && !nativeViewNull) { setOpacity(TiConvert.toFloat(d, TiC.PROPERTY_OPACITY, 1f)); } if (d.containsKey(TiC.PROPERTY_TRANSFORM)) { Ti2DMatrix matrix = (Ti2DMatrix) d.get(TiC.PROPERTY_TRANSFORM); if (matrix != null) { applyTransform(matrix); } } if (d.containsKey(TiC.PROPERTY_KEEP_SCREEN_ON) && !nativeViewNull) { nativeView.setKeepScreenOn(TiConvert.toBoolean(d, TiC.PROPERTY_KEEP_SCREEN_ON, false)); } if (d.containsKey(TiC.PROPERTY_ACCESSIBILITY_HINT) || d.containsKey(TiC.PROPERTY_ACCESSIBILITY_LABEL) || d.containsKey(TiC.PROPERTY_ACCESSIBILITY_VALUE) || d.containsKey(TiC.PROPERTY_ACCESSIBILITY_HIDDEN)) { applyAccessibilityProperties(); } } // TODO dead code? @Override public void propertiesChanged(List<KrollPropertyChange> changes, KrollProxy proxy) { for (KrollPropertyChange change : changes) { propertyChanged(change.getName(), change.getOldValue(), change.getNewValue(), proxy); } } private void applyCustomBackground() { applyCustomBackground(true); } private void applyCustomBackground(boolean reuseCurrentDrawable) { if (nativeView != null) { if (background == null) { background = new TiBackgroundDrawable(); Drawable currentDrawable = nativeView.getBackground(); if (currentDrawable != null) { if (reuseCurrentDrawable) { background.setBackgroundDrawable(currentDrawable); } else { nativeView.setBackgroundDrawable(null); currentDrawable.setCallback(null); if (currentDrawable instanceof TiBackgroundDrawable) { ((TiBackgroundDrawable) currentDrawable).releaseDelegate(); } } } } nativeView.setBackgroundDrawable(background); } } public void onFocusChange(final View v, boolean hasFocus) { if (hasFocus) { TiMessenger.postOnMain(new Runnable() { public void run() { TiUIHelper.requestSoftInputChange(proxy, v); } }); fireEvent(TiC.EVENT_FOCUS, getFocusEventObject(hasFocus)); } else { TiMessenger.postOnMain(new Runnable() { public void run() { TiUIHelper.showSoftKeyboard(v, false); } }); fireEvent(TiC.EVENT_BLUR, getFocusEventObject(hasFocus)); } } protected KrollDict getFocusEventObject(boolean hasFocus) { return null; } protected InputMethodManager getIMM() { InputMethodManager imm = null; imm = (InputMethodManager) TiApplication.getInstance().getSystemService(Context.INPUT_METHOD_SERVICE); return imm; } /** * Focuses the view. */ public void focus() { if (nativeView != null) { nativeView.requestFocus(); } } /** * Blurs the view. */ public void blur() { if (nativeView != null) { nativeView.clearFocus(); } } public void release() { if (Log.isDebugModeEnabled()) { Log.d(TAG, "Releasing: " + this, Log.DEBUG_MODE); } View nv = getNativeView(); if (nv != null) { if (nv instanceof ViewGroup) { ViewGroup vg = (ViewGroup) nv; if (Log.isDebugModeEnabled()) { Log.d(TAG, "Group has: " + vg.getChildCount(), Log.DEBUG_MODE); } if (!(vg instanceof AdapterView<?>)) { vg.removeAllViews(); } } Drawable d = nv.getBackground(); if (d != null) { nv.setBackgroundDrawable(null); d.setCallback(null); if (d instanceof TiBackgroundDrawable) { ((TiBackgroundDrawable)d).releaseDelegate(); } d = null; } nativeView = null; borderView = null; if (proxy != null) { proxy.setModelListener(null); } } } private void setVisibility(int visibility) { this.visibility = visibility; if (borderView != null) { borderView.setVisibility(this.visibility); } if (nativeView != null) { nativeView.setVisibility(this.visibility); } } /** * Shows the view, changing the view's visibility to View.VISIBLE. */ public void show() { this.setVisibility(View.VISIBLE); if (borderView == null && nativeView == null) { Log.w(TAG, "Attempt to show null native control", Log.DEBUG_MODE); } } /** * Hides the view, changing the view's visibility to View.INVISIBLE. */ public void hide() { this.setVisibility(View.INVISIBLE); if (borderView == null && nativeView == null) { Log.w(TAG, "Attempt to hide null native control", Log.DEBUG_MODE); } } private String resolveImageUrl(String path) { return path.length() > 0 ? proxy.resolveUrl(null, path) : null; } private void handleBackgroundImage(KrollDict d) { String bg = d.getString(TiC.PROPERTY_BACKGROUND_IMAGE); String bgSelected = d.optString(TiC.PROPERTY_BACKGROUND_SELECTED_IMAGE, bg); String bgFocused = d.optString(TiC.PROPERTY_BACKGROUND_FOCUSED_IMAGE, bg); String bgDisabled = d.optString(TiC.PROPERTY_BACKGROUND_DISABLED_IMAGE, bg); String bgColor = d.getString(TiC.PROPERTY_BACKGROUND_COLOR); String bgSelectedColor = d.optString(TiC.PROPERTY_BACKGROUND_SELECTED_COLOR, bgColor); String bgFocusedColor = d.optString(TiC.PROPERTY_BACKGROUND_FOCUSED_COLOR, bgColor); String bgDisabledColor = d.optString(TiC.PROPERTY_BACKGROUND_DISABLED_COLOR, bgColor); if (bg != null) { bg = resolveImageUrl(bg); } if (bgSelected != null) { bgSelected = resolveImageUrl(bgSelected); } if (bgFocused != null) { bgFocused = resolveImageUrl(bgFocused); } if (bgDisabled != null) { bgDisabled = resolveImageUrl(bgDisabled); } TiGradientDrawable gradientDrawable = null; KrollDict gradientProperties = d.getKrollDict(TiC.PROPERTY_BACKGROUND_GRADIENT); if (gradientProperties != null) { try { gradientDrawable = new TiGradientDrawable(nativeView, gradientProperties); if (gradientDrawable.getGradientType() == GradientType.RADIAL_GRADIENT) { // TODO: Remove this once we support radial gradients. Log.w(TAG, "Android does not support radial gradients."); gradientDrawable = null; } } catch (IllegalArgumentException e) { gradientDrawable = null; } } if (bg != null || bgSelected != null || bgFocused != null || bgDisabled != null || bgColor != null || bgSelectedColor != null || bgFocusedColor != null || bgDisabledColor != null || gradientDrawable != null) { if (background == null) { applyCustomBackground(false); } Drawable bgDrawable = TiUIHelper.buildBackgroundDrawable( bg, TiConvert.toBoolean(d, TiC.PROPERTY_BACKGROUND_REPEAT, false), bgColor, bgSelected, bgSelectedColor, bgDisabled, bgDisabledColor, bgFocused, bgFocusedColor, gradientDrawable); background.setBackgroundDrawable(bgDrawable); } } private void initializeBorder(KrollDict d, Integer bgColor) { if (hasBorder(d)) { if(nativeView != null) { if (borderView == null) { Activity currentActivity = proxy.getActivity(); if (currentActivity == null) { currentActivity = TiApplication.getAppCurrentActivity(); } borderView = new TiBorderWrapperView(currentActivity); // Create new layout params for the child view since we just want the // wrapper to control the layout LayoutParams params = new LayoutParams(); params.height = android.widget.FrameLayout.LayoutParams.MATCH_PARENT; params.width = android.widget.FrameLayout.LayoutParams.MATCH_PARENT; // If the view already has a parent, we need to detach it from the parent // and add the borderView to the parent as the child ViewGroup savedParent = null; android.view.ViewGroup.LayoutParams savedLayoutParams = null; if (nativeView.getParent() != null) { ViewParent nativeParent = nativeView.getParent(); if (nativeParent instanceof ViewGroup) { savedParent = (ViewGroup) nativeParent; savedLayoutParams = savedParent.getLayoutParams(); savedParent.removeView(nativeView); } } borderView.addView(nativeView, params); if (savedParent != null) { savedParent.addView(getOuterView(), savedLayoutParams); } borderView.setVisibility(this.visibility); } if (d.containsKey(TiC.PROPERTY_BORDER_RADIUS)) { float radius = TiConvert.toFloat(d, TiC.PROPERTY_BORDER_RADIUS, 0f); if (radius > 0f && HONEYCOMB_OR_GREATER) { disableHWAcceleration(); } borderView.setRadius(radius); } if (d.containsKey(TiC.PROPERTY_BORDER_COLOR) || d.containsKey(TiC.PROPERTY_BORDER_WIDTH)) { if (d.containsKey(TiC.PROPERTY_BORDER_COLOR)) { borderView.setColor(TiConvert.toColor(d, TiC.PROPERTY_BORDER_COLOR)); } else { if (bgColor != null) { borderView.setColor(bgColor); } } if (d.containsKey(TiC.PROPERTY_BORDER_WIDTH)) { TiDimension width = TiConvert .toTiDimension(d.get(TiC.PROPERTY_BORDER_WIDTH), TiDimension.TYPE_WIDTH); if (width != null) { borderView.setBorderWidth(width.getAsPixels(getNativeView())); } } } } } } private void handleBorderProperty(String property, Object value) { if (TiC.PROPERTY_BORDER_COLOR.equals(property)) { borderView.setColor(TiConvert.toColor(value.toString())); } else if (TiC.PROPERTY_BORDER_RADIUS.equals(property)) { float radius = TiConvert.toFloat(value, 0f); if (radius > 0f && HONEYCOMB_OR_GREATER) { disableHWAcceleration(); } borderView.setRadius(radius); } else if (TiC.PROPERTY_BORDER_WIDTH.equals(property)) { borderView.setBorderWidth(TiConvert.toFloat(value, 0f)); } borderView.postInvalidate(); } private static SparseArray<String> motionEvents = new SparseArray<String>(); static { motionEvents.put(MotionEvent.ACTION_DOWN, TiC.EVENT_TOUCH_START); motionEvents.put(MotionEvent.ACTION_UP, TiC.EVENT_TOUCH_END); motionEvents.put(MotionEvent.ACTION_MOVE, TiC.EVENT_TOUCH_MOVE); motionEvents.put(MotionEvent.ACTION_CANCEL, TiC.EVENT_TOUCH_CANCEL); } protected KrollDict dictFromEvent(MotionEvent e) { KrollDict data = new KrollDict(); data.put(TiC.EVENT_PROPERTY_X, (double)e.getX()); data.put(TiC.EVENT_PROPERTY_Y, (double)e.getY()); data.put(TiC.EVENT_PROPERTY_SOURCE, proxy); return data; } protected KrollDict dictFromEvent(KrollDict dictToCopy){ KrollDict data = new KrollDict(); if (dictToCopy.containsKey(TiC.EVENT_PROPERTY_X)){ data.put(TiC.EVENT_PROPERTY_X, dictToCopy.get(TiC.EVENT_PROPERTY_X)); } else { data.put(TiC.EVENT_PROPERTY_X, (double)0); } if (dictToCopy.containsKey(TiC.EVENT_PROPERTY_Y)){ data.put(TiC.EVENT_PROPERTY_Y, dictToCopy.get(TiC.EVENT_PROPERTY_Y)); } else { data.put(TiC.EVENT_PROPERTY_Y, (double)0); } data.put(TiC.EVENT_PROPERTY_SOURCE, proxy); return data; } protected boolean allowRegisterForTouch() { return true; } /** * @module.api */ protected boolean allowRegisterForKeyPress() { return true; } public View getOuterView() { return borderView == null ? nativeView : borderView; } public void registerForTouch() { if (allowRegisterForTouch()) { registerForTouch(getNativeView()); } } protected void registerTouchEvents(final View touchable) { touchView = new WeakReference<View>(touchable); final ScaleGestureDetector scaleDetector = new ScaleGestureDetector(touchable.getContext(), new SimpleOnScaleGestureListener() { // protect from divide by zero errors long minTimeDelta = 1; float minStartSpan = 1.0f; float startSpan; @Override public boolean onScale(ScaleGestureDetector sgd) { if (proxy.hierarchyHasListener(TiC.EVENT_PINCH)) { float timeDelta = sgd.getTimeDelta() == 0 ? minTimeDelta : sgd.getTimeDelta(); // Suppress scale events (and allow for possible two-finger tap events) // until we've moved at least a few pixels. Without this check, two-finger // taps are very hard to register on some older devices. if (!didScale) { if (Math.abs(sgd.getCurrentSpan() - startSpan) > SCALE_THRESHOLD) { didScale = true; } } if (didScale) { KrollDict data = new KrollDict(); data.put(TiC.EVENT_PROPERTY_SCALE, sgd.getCurrentSpan() / startSpan); data.put(TiC.EVENT_PROPERTY_VELOCITY, (sgd.getScaleFactor() - 1.0f) / timeDelta * 1000); data.put(TiC.EVENT_PROPERTY_SOURCE, proxy); return fireEvent(TiC.EVENT_PINCH, data); } } return false; } @Override public boolean onScaleBegin(ScaleGestureDetector sgd) { startSpan = sgd.getCurrentSpan() == 0 ? minStartSpan : sgd.getCurrentSpan(); return true; } }); final GestureDetector detector = new GestureDetector(touchable.getContext(), new SimpleOnGestureListener() { @Override public boolean onDoubleTap(MotionEvent e) { if (proxy.hierarchyHasListener(TiC.EVENT_DOUBLE_TAP) || proxy.hierarchyHasListener(TiC.EVENT_DOUBLE_CLICK)) { boolean handledTap = fireEvent(TiC.EVENT_DOUBLE_TAP, dictFromEvent(e)); boolean handledClick = fireEvent(TiC.EVENT_DOUBLE_CLICK, dictFromEvent(e)); return handledTap || handledClick; } return false; } @Override public boolean onSingleTapConfirmed(MotionEvent e) { Log.d(TAG, "TAP, TAP, TAP on " + proxy, Log.DEBUG_MODE); if (proxy.hierarchyHasListener(TiC.EVENT_SINGLE_TAP)) { return fireEvent(TiC.EVENT_SINGLE_TAP, dictFromEvent(e)); // Moved click handling to the onTouch listener, because a single tap is not the // same as a click. A single tap is a quick tap only, whereas clicks can be held // before lifting. // boolean handledClick = proxy.fireEvent(TiC.EVENT_CLICK, dictFromEvent(event)); // Note: this return value is irrelevant in our case. We "want" to use it // in onTouch below, when we call detector.onTouchEvent(event); But, in fact, // onSingleTapConfirmed is *not* called in the course of onTouchEvent. It's // called via Handler in GestureDetector. <-- See its Java source. // return handledTap;// || handledClick; } return false; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { Log.d(TAG, "SWIPE on " + proxy, Log.DEBUG_MODE); if (proxy.hierarchyHasListener(TiC.EVENT_SWIPE)) { KrollDict data = dictFromEvent(e2); if (Math.abs(velocityX) > Math.abs(velocityY)) { data.put(TiC.EVENT_PROPERTY_DIRECTION, velocityX > 0 ? "right" : "left"); } else { data.put(TiC.EVENT_PROPERTY_DIRECTION, velocityY > 0 ? "down" : "up"); } return fireEvent(TiC.EVENT_SWIPE, data); } return false; } @Override public void onLongPress(MotionEvent e) { Log.d(TAG, "LONGPRESS on " + proxy, Log.DEBUG_MODE); if (proxy.hierarchyHasListener(TiC.EVENT_LONGPRESS)) { fireEvent(TiC.EVENT_LONGPRESS, dictFromEvent(e)); } } }); touchable.setOnTouchListener(new OnTouchListener() { int pointersDown = 0; public boolean onTouch(View view, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { lastUpEvent.put(TiC.EVENT_PROPERTY_X, (double) event.getX()); lastUpEvent.put(TiC.EVENT_PROPERTY_Y, (double) event.getY()); } scaleDetector.onTouchEvent(event); if (scaleDetector.isInProgress()) { pointersDown = 0; return true; } boolean handled = detector.onTouchEvent(event); if (handled) { pointersDown = 0; return true; } if (event.getActionMasked() == MotionEvent.ACTION_POINTER_UP) { if (didScale) { didScale = false; pointersDown = 0; } else { pointersDown++; } } else if (event.getAction() == MotionEvent.ACTION_UP) { if (pointersDown == 1) { fireEvent(TiC.EVENT_TWOFINGERTAP, dictFromEvent(event)); pointersDown = 0; return true; } pointersDown = 0; } String motionEvent = motionEvents.get(event.getAction()); if (motionEvent != null) { if (proxy.hierarchyHasListener(motionEvent)) { fireEvent(motionEvent, dictFromEvent(event)); } } // Inside View.java, dispatchTouchEvent() does not call onTouchEvent() if this listener returns true. As // a result, click and other motion events do not occur on the native Android side. To prevent this, we // always return false and let Android generate click and other motion events. return false; } }); } protected void registerForTouch(final View touchable) { if (touchable == null) { return; } registerTouchEvents(touchable); // Previously, we used the single tap handling above to fire our click event. It doesn't // work: a single tap is not the same as a click. A click can be held for a while before // lifting the finger; a single-tap is only generated from a quick tap (which will also cause // a click.) We wanted to do it in single-tap handling presumably because the singletap // listener gets a MotionEvent, which gives us the information we want to provide to our // users in our click event, whereas Android's standard OnClickListener does _not_ contain // that info. However, an "up" seems to always occur before the click listener gets invoked, // so we store the last up event's x,y coordinates (see onTouch above) and use them here. // Note: AdapterView throws an exception if you try to put a click listener on it. doSetClickable(touchable); } public void registerForKeyPress() { if (allowRegisterForKeyPress()) { registerForKeyPress(getNativeView()); } } protected void registerForKeyPress(final View v) { if (v == null) { return; } Object focusable = proxy.getProperty(TiC.PROPERTY_FOCUSABLE); if (focusable != null) { registerForKeyPress(v, TiConvert.toBoolean(focusable, false)); } } protected void registerForKeyPress(final View v, boolean focusable) { if (v == null) { return; } v.setFocusable(focusable); // The listener for the "keypressed" event is only triggered when the view has focus. So we only register the // "keypressed" event when the view is focusable. if (focusable) { registerForKeyPressEvents(v); } else { v.setOnKeyListener(null); } } /** * Registers a callback to be invoked when a hardware key is pressed in this view. * * @param v The view to have the key listener to attach to. */ protected void registerForKeyPressEvents(final View v) { if (v == null) { return; } v.setOnKeyListener(new OnKeyListener() { public boolean onKey(View view, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_UP) { KrollDict data = new KrollDict(); data.put(TiC.EVENT_PROPERTY_KEYCODE, keyCode); fireEvent(TiC.EVENT_KEY_PRESSED, data); switch (keyCode) { case KeyEvent.KEYCODE_ENTER: case KeyEvent.KEYCODE_DPAD_CENTER: if (proxy.hasListeners(TiC.EVENT_CLICK)) { fireEvent(TiC.EVENT_CLICK, null); return true; } } } return false; } }); } /** * Sets the nativeView's opacity. * @param opacity the opacity to set. */ public void setOpacity(float opacity) { if (opacity < 0 || opacity > 1) { Log.w(TAG, "Ignoring invalid value for opacity: " + opacity); return; } if (borderView != null) { borderView.setBorderAlpha(Math.round(opacity * 255)); borderView.postInvalidate(); } if (nativeView != null) { if (HONEYCOMB_OR_GREATER) { nativeView.setAlpha(opacity); } else { setOpacity(nativeView, opacity); } nativeView.postInvalidate(); } } /** * Sets the view's opacity. * @param view the view object. * @param opacity the opacity to set. */ protected void setOpacity(View view, float opacity) { if (view != null) { TiUIHelper.setDrawableOpacity(view.getBackground(), opacity); if (opacity == 1) { clearOpacity(view); } } } public void clearOpacity(View view) { Drawable d = view.getBackground(); if (d != null) { d.clearColorFilter(); } } public KrollDict toImage() { return TiUIHelper.viewToImage(proxy.getProperties(), getNativeView()); } private View getTouchView() { if (nativeView != null) { return nativeView; } else { if (touchView != null) { return touchView.get(); } } return null; } private void doSetClickable(View view, boolean clickable) { if (view == null) { return; } if (!clickable) { view.setOnClickListener(null); // This will set clickable to true in the view, so make sure it stays here so the next line turns it off. view.setClickable(false); view.setOnLongClickListener(null); view.setLongClickable(false); } else if ( ! (view instanceof AdapterView) ){ // n.b.: AdapterView throws if click listener set. // n.b.: setting onclicklistener automatically sets clickable to true. setOnClickListener(view); setOnLongClickListener(view); } } private void doSetClickable(boolean clickable) { doSetClickable(getTouchView(), clickable); } /* * Used just to setup the click listener if applicable. */ private void doSetClickable(View view) { if (view == null) { return; } doSetClickable(view, view.isClickable()); } /** * Can be overriden by inheriting views for special click handling. For example, * the Facebook module's login button view needs special click handling. */ protected void setOnClickListener(View view) { view.setOnClickListener(new OnClickListener() { public void onClick(View view) { fireEvent(TiC.EVENT_CLICK, dictFromEvent(lastUpEvent)); } }); } public boolean fireEvent(String eventName, KrollDict data) { return fireEvent(eventName, data, true); } public boolean fireEvent(String eventName, KrollDict data, boolean bubbles) { if (data == null && additionalEventData != null) { data = new KrollDict(additionalEventData); } else if (additionalEventData != null) { data.putAll(additionalEventData); } return proxy.fireEvent(eventName, data, bubbles); } protected void setOnLongClickListener(View view) { view.setOnLongClickListener(new OnLongClickListener() { public boolean onLongClick(View view) { return fireEvent(TiC.EVENT_LONGCLICK, null); } }); } private void disableHWAcceleration() { if (borderView == null) { return; } Log.d(TAG, "Disabling hardware acceleration for instance of " + borderView.getClass().getSimpleName(), Log.DEBUG_MODE); if (mSetLayerTypeMethod == null) { try { Class<? extends View> c = borderView.getClass(); mSetLayerTypeMethod = c.getMethod("setLayerType", int.class, Paint.class); } catch (SecurityException e) { Log.e(TAG, "SecurityException trying to get View.setLayerType to disable hardware acceleration.", e, Log.DEBUG_MODE); } catch (NoSuchMethodException e) { Log.e(TAG, "NoSuchMethodException trying to get View.setLayerType to disable hardware acceleration.", e, Log.DEBUG_MODE); } } if (mSetLayerTypeMethod == null) { return; } try { mSetLayerTypeMethod.invoke(borderView, LAYER_TYPE_SOFTWARE, null); } catch (IllegalArgumentException e) { Log.e(TAG, e.getMessage(), e); } catch (IllegalAccessException e) { Log.e(TAG, e.getMessage(), e); } catch (InvocationTargetException e) { Log.e(TAG, e.getMessage(), e); } } /** * Retrieve the saved animated scale values, which we store here since Android provides no property * for looking them up. */ public Pair<Float, Float> getAnimatedScaleValues() { return animatedScaleValues; } /** * Store the animated x and y scale values (i.e., the scale after an animation) * since Android provides no property for looking them up. */ public void setAnimatedScaleValues(Pair<Float, Float> newValues) { animatedScaleValues = newValues; } /** * Set the animated rotation degrees, since Android provides no property for looking it up. */ public void setAnimatedRotationDegrees(float degrees) { animatedRotationDegrees = degrees; } /** * Retrieve the animated rotation degrees, which we store here since Android provides no property * for looking it up. */ public float getAnimatedRotationDegrees() { return animatedRotationDegrees; } /** * Set the animated alpha values, since Android provides no property for looking it up. */ public void setAnimatedAlpha(float alpha) { animatedAlpha = alpha; } /** * Retrieve the animated alpha value, which we store here since Android provides no property * for looking it up. */ public float getAnimatedAlpha() { return animatedAlpha; } /** * "Forget" the values we save after scale and rotation and alpha animations. */ private void resetPostAnimationValues() { animatedRotationDegrees = 0f; // i.e., no rotation. animatedScaleValues = Pair.create(Float.valueOf(1f), Float.valueOf(1f)); // 1 means no scaling animatedAlpha = Float.MIN_VALUE; // we use min val to signal no val. } private void applyContentDescription() { if (proxy == null || nativeView == null) { return; } String contentDescription = composeContentDescription(); if (contentDescription != null) { nativeView.setContentDescription(contentDescription); } } /** * Our view proxy supports three properties to match iOS regarding * the text that is read aloud (or otherwise communicated) by the * assistive technology: accessibilityLabel, accessibilityHint * and accessibilityValue. * * We combine these to create the single Android property contentDescription. * (e.g., View.setContentDescription(...)); */ protected String composeContentDescription() { if (proxy == null) { return null; } final String punctuationPattern = "^.*\\p{Punct}\\s*$"; StringBuilder buffer = new StringBuilder(); KrollDict properties = proxy.getProperties(); String label, hint, value; label = TiConvert.toString(properties.get(TiC.PROPERTY_ACCESSIBILITY_LABEL)); hint = TiConvert.toString(properties.get(TiC.PROPERTY_ACCESSIBILITY_HINT)); value = TiConvert.toString(properties.get(TiC.PROPERTY_ACCESSIBILITY_VALUE)); if (!TextUtils.isEmpty(label)) { buffer.append(label); if (!label.matches(punctuationPattern)) { buffer.append("."); } } if (!TextUtils.isEmpty(value)) { if (buffer.length() > 0) { buffer.append(" "); } buffer.append(value); if (!value.matches(punctuationPattern)) { buffer.append("."); } } if (!TextUtils.isEmpty(hint)) { if (buffer.length() > 0) { buffer.append(" "); } buffer.append(hint); if (!hint.matches(punctuationPattern)) { buffer.append("."); } } return buffer.toString(); } private void applyAccessibilityProperties() { if (nativeView != null) { applyContentDescription(); applyAccessibilityHidden(); } } private void applyAccessibilityHidden() { if (nativeView == null || proxy == null) { return; } applyAccessibilityHidden(proxy.getProperty(TiC.PROPERTY_ACCESSIBILITY_HIDDEN)); } private void applyAccessibilityHidden(Object hiddenPropertyValue) { if (nativeView == null) { return; } int importanceMode = ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO; if (hiddenPropertyValue != null && TiConvert.toBoolean(hiddenPropertyValue, false)) { importanceMode = ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO; } ViewCompat.setImportantForAccessibility(nativeView, importanceMode); } }
timob-13314: fix listview crash
android/titanium/src/java/org/appcelerator/titanium/view/TiUIView.java
timob-13314: fix listview crash
Java
apache-2.0
b1e4d2ed7ee64a5137f330ade277c53cb1094889
0
nagyistoce/camunda-bpm-assert,remibantos/activiti-assert
package org.camunda.bdd.examples.simple; import static org.mockito.Mockito.mock; import javax.inject.Inject; import org.camunda.bdd.examples.simple.SimpleProcess.Elements; import org.camunda.bpm.engine.history.HistoricActivityInstance; import org.camunda.bpm.engine.runtime.ProcessInstance; import org.camunda.bpm.engine.test.Deployment; import org.camunda.bpm.engine.test.mock.Mocks; import org.camunda.bpm.needle.ProcessEngineNeedleRule; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Deployment unit test of simple process. * * @author Simon Zambrovski, Holisticon AG. * */ public class SimpleDeploymentTest { @Rule public ProcessEngineNeedleRule processEngine = new ProcessEngineNeedleRule(this); @Inject private SimpleProcessAdapter simpleProcessAdapter; class Glue { public void loadContractData(final boolean isAutomatically) { when(simpleProcessAdapter.loadContractData()).thenReturn(isAutomatically); } public void startSimpleProcess() { ProcessInstance startProcessInstance = processEngine.startProcessInstanceByKey(SimpleProcess.PROCESS); assertNotNull(startProcessInstance); } public void processAutomatically(final boolean withErrors) { if (withErrors) { // simulate error event. } } /** * Assert that process execution has run through the activity with given id. * * @param name * name of the activity. */ private void assertActivityVisitedOnce(final String name) { final HistoricActivityInstance singleResult = processEngine.getHistoryService().createHistoricActivityInstanceQuery().finished().activityId(name) .singleResult(); assertNotNull(singleResult); } /** * Assert process end event. * * @param name * name of the end event. */ private void assertEndEvent(final String name) { assertActivityVisitedOnce(name); processEngine.assertNoMoreRunningInstances(); } } private final Glue glue = new Glue(); @Before public void initMocks() { Mocks.register(SimpleProcessAdapter.NAME, mock(SimpleProcessAdapter.class)); } @Test @Deployment(resources = SimpleProcess.BPMN) public void shouldDeploy() { // nothing to do. } @Test @Deployment(resources = SimpleProcess.BPMN) public void shouldStartAndRunAutomatically() { // given glue.loadContractData(true); glue.processAutomatically(false); // when glue.startSimpleProcess(); // then glue.assertEndEvent(Elements.EVENT_CONTRACT_PROCESSED); } }
examples/src/test/java/org/camunda/bdd/examples/simple/SimpleDeploymentTest.java
package org.camunda.bdd.examples.simple; import static org.mockito.Mockito.mock; import javax.inject.Inject; import org.camunda.bdd.examples.simple.SimpleProcess.Elements; import org.camunda.bpm.engine.history.HistoricActivityInstance; import org.camunda.bpm.engine.runtime.ProcessInstance; import org.camunda.bpm.engine.test.Deployment; import org.camunda.bpm.engine.test.mock.Mocks; import org.camunda.bpm.needle.ProcessEngineNeedleRule; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Deployment unit test of simple process. * * @author Simon Zambrovski, Holisticon AG. * */ public class SimpleDeploymentTest { @Rule public ProcessEngineNeedleRule processEngine = new ProcessEngineNeedleRule(this); @Inject private SimpleProcessAdapter simpleProcessAdapter; class Glue { public void loadContractData(final boolean isAutomatically) { when(simpleProcessAdapter.loadContractData()).thenReturn(isAutomatically); } public void startSimpleProcess() { ProcessInstance startProcessInstance = processEngine.startProcessInstanceByKey(SimpleProcess.PROCESS); assertNotNull(startProcessInstance); } public void processAutomatically(final boolean withErrors) { if (withErrors) { // simulate error event. } } /** * Assert that process execution has run through the activity with given id. * * @param name * name of the activity. */ private void assertActivityVisitedOnce(final String name) { final HistoricActivityInstance singleResult = processEngine.getHistoryService().createHistoricActivityInstanceQuery().finished().activityId(name) .singleResult(); assertNotNull(singleResult); } /** * Assert process end event. * * @param name * name of the end event. */ private void assertEndEvent(final String name) { assertActivityVisitedOnce(name); processEngine.assertNoMoreRunningInstances(); } } private final Glue glue = new Glue(); @Before public void initMocks() { Mocks.register(SimpleProcessAdapter.NAME, mock(SimpleProcessAdapter.class)); } @Test @Deployment(resources = SimpleProcess.BPMN) public void shouldDeploy() { // nothing to do. } @Test @Deployment(resources = SimpleProcess.BPMN) public void shouldStartAndRunAutomatically() { // given glue.startSimpleProcess(); // when glue.loadContractData(true); glue.processAutomatically(false); // then glue.assertEndEvent(Elements.EVENT_CONTRACT_PROCESSED); } }
fixing test
examples/src/test/java/org/camunda/bdd/examples/simple/SimpleDeploymentTest.java
fixing test
Java
apache-2.0
77fdc7352b998cd5f104a1f44f543a714d00c6ba
0
rgoldberg/asset-pipeline,rgoldberg/asset-pipeline,rgoldberg/asset-pipeline,rgoldberg/asset-pipeline,rgoldberg/asset-pipeline,rgoldberg/asset-pipeline
package asset.pipeline.utils.net; import java.net.MalformedURLException; import java.net.URL; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author Ross Goldberg */ public final class Urls { private static final Map<String, Integer> DEFAULT_PORT_BY_SCHEME = new ConcurrentHashMap<>(); public static final String URL_SCHEME_SANS_COLON_REGEX = "\\p{L}[\\p{L}\\d+-.]*+"; /** * matches text that starts with either {@code "/"} or a <a href="https://tools.ietf.org/html/std66">URI scheme</a> followed by {@code ":/"} */ public static final Pattern ABSOLUTE_URL_PATTERN = Pattern.compile("^(?:" + URL_SCHEME_SANS_COLON_REGEX + ":)?/"); /** * matches text that starts with either {@code "//"} or a <a href="https://tools.ietf.org/html/std66">URI scheme</a> followed by {@code "://"} */ public static final Pattern HAS_AUTHORITY_URL_PATTERN = Pattern.compile("^(?:" + URL_SCHEME_SANS_COLON_REGEX + ":)?//"); /** * matches text that starts with a <a href="https://tools.ietf.org/html/std66">URI scheme</a> including the colon at the start of text */ public static final Pattern URL_SCHEME_WITH_COLON_PATTERN = Pattern.compile("^" + URL_SCHEME_SANS_COLON_REGEX + ":"); /** * matches text that starts with a <a href="https://tools.ietf.org/html/std66">URI scheme</a> before the colon at the start of text */ public static final Pattern URL_SCHEME_SANS_COLON_PATTERN = Pattern.compile("^" + URL_SCHEME_SANS_COLON_REGEX + "(?=:)"); public static final String URL_COMPONENT_SCHEME = "scheme"; public static final String URL_COMPONENT_USER = "user"; public static final String URL_COMPONENT_PASSWORD = "password"; public static final String URL_COMPONENT_HOST = "host"; public static final String URL_COMPONENT_PORT = "port"; public static final String URL_COMPONENT_PATH = "path"; public static final String URL_COMPONENT_QUERY = "query"; public static final String URL_COMPONENT_FRAGMENT = "fragment"; /** * Named capture groups for URL components * * Does not enforce that: * <ul> * <li>a port can only be an unsigned 16-bit number</li> * <li>a [/?#] must follow any port</li> * </ul> */ public static final Pattern URL_COMPONENT_PATTERN = Pattern.compile( "^(?:(?<" + URL_COMPONENT_SCHEME + ">" + URL_SCHEME_SANS_COLON_REGEX + "):)?" + "(?://" + "(?:" + "(?<" + URL_COMPONENT_USER + ">[^#?/@:]*+)" + "(?::(?<" + URL_COMPONENT_PASSWORD + ">[^#?/@]*+))?" + "@)?" + "(?<" + URL_COMPONENT_HOST + ">[^#?/:]*+)" + "(?::(?<" + URL_COMPONENT_PORT + ">\\d*+))?" + ")?" + "(?<" + URL_COMPONENT_PATH + ">[^#?]*+)" + "(?:\\?(?<" + URL_COMPONENT_QUERY + ">[^#]*+))?" + "(?:#(?<" + URL_COMPONENT_FRAGMENT + ">.*+))?" ) ; public static StringBuilder concatenateUrl( final String scheme, final String user, final String password, final String host, final String port, final String path, final String query, final String fragment ) { final StringBuilder urlSb = new StringBuilder(); if (scheme != null) { urlSb.append(scheme).append(":"); } if ( user != null || password != null || host != null || port != null ) { urlSb.append("//"); if ( user != null || password != null ) { append(urlSb, user); append(urlSb, ':', password); urlSb.append('@'); } append(urlSb, host); append(urlSb, ':', port); if (path != null) { if (path.charAt(0) != '/') { urlSb.append('/'); } urlSb.append(path); } } else { append(urlSb, path); } append(urlSb, '?', query); append(urlSb, '#', fragment); return urlSb; } private static StringBuilder append(final StringBuilder sb, final String s) { return s == null ? sb : sb.append(s) ; } private static StringBuilder append(final StringBuilder sb, final char prefix, final String s) { return s == null ? sb : sb.append(prefix).append(s) ; } public static int getDefaultPort(final String scheme) { Integer port = DEFAULT_PORT_BY_SCHEME.get(scheme); if (port == null) { try { port = new URL(scheme, "localhost", "").getDefaultPort(); DEFAULT_PORT_BY_SCHEME.put(scheme, port); } catch (final MalformedURLException ex) { throw new IllegalArgumentException(scheme + " is an unknown scheme", ex); } } return port; } /** * {@code url} starts with either {@code "/"} or a <a href="https://tools.ietf.org/html/std66">URI scheme</a> followed by {@code ":/"} */ public static boolean isAbsolute(final String url) { return ABSOLUTE_URL_PATTERN.matcher(url).find(); } /** * {@code url} does not start with either {@code "/"} or a <a href="https://tools.ietf.org/html/std66">URI scheme</a> followed by {@code ":/"} */ public static boolean isRelative(final String url) { return ! isAbsolute(url); } /** * {@code url} starts with either {@code "//"} or a <a href="https://tools.ietf.org/html/std66">URI scheme</a> followed by {@code "://"} */ public static boolean hasAuthority(final String url) { return HAS_AUTHORITY_URL_PATTERN.matcher(url).find(); } /** * @return <a href="https://tools.ietf.org/html/std66">URI scheme</a>, including trailing colon, if present; * otherwise, returns {@code null} */ public static String getSchemeWithColon(final String url) { return getSchemeWithColon(url, null); } /** * @return <a href="https://tools.ietf.org/html/std66">URI scheme</a>, including trailing colon, if present; * otherwise, returns {@code defaultScheme} */ public static String getSchemeWithColon(final String url, final String defaultScheme) { final Matcher m = URL_SCHEME_WITH_COLON_PATTERN.matcher(url); return m.find() ? m.group() : defaultScheme ; } /** * @return the substring of {@code url} after any <a href="https://tools.ietf.org/html/std66">URI scheme</a>, if scheme is present; * otherwise, returns {@code url} */ public static String getUrlSansScheme(final String url) { return URL_SCHEME_WITH_COLON_PATTERN.matcher(url).replaceFirst(""); } public static String withScheme(final String url, final Object o) { return o == null ? url : o instanceof Boolean ? withScheme(url, ((Boolean) o).booleanValue()) : withScheme(url, o.toString()) ; } public static String withScheme(final String url, final boolean retainScheme) { return retainScheme ? url : getUrlSansScheme(url) ; } public static String withScheme(final String url, final String scheme) { return scheme + ':' + getUrlSansScheme(url); } private Urls() {} }
asset-pipeline-core/src/main/java/asset/pipeline/utils/net/Urls.java
package asset.pipeline.utils.net; import java.net.MalformedURLException; import java.net.URL; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author Ross Goldberg */ public final class Urls { private static final Map<String, Integer> DEFAULT_PORT_BY_SCHEME = new ConcurrentHashMap<>(); public static final String URL_SCHEME_SANS_COLON_REGEX = "\\p{L}[\\p{L}\\d+-.]*+"; /** * matches text that starts with either {@code "/"} or a <a href="https://tools.ietf.org/html/std66">URI scheme</a> followed by {@code ":/"} */ public static final Pattern ABSOLUTE_URL_PATTERN = Pattern.compile("^(?:" + URL_SCHEME_SANS_COLON_REGEX + ":)?/"); /** * matches text that starts with either {@code "//"} or a <a href="https://tools.ietf.org/html/std66">URI scheme</a> followed by {@code "://"} */ public static final Pattern HAS_AUTHORITY_URL_PATTERN = Pattern.compile("^(?:" + URL_SCHEME_SANS_COLON_REGEX + ":)?//"); /** * matches text that starts with a <a href="https://tools.ietf.org/html/std66">URI scheme</a> including the colon at the start of text */ public static final Pattern URL_SCHEME_WITH_COLON_PATTERN = Pattern.compile("^" + URL_SCHEME_SANS_COLON_REGEX + ":"); /** * matches text that starts with a <a href="https://tools.ietf.org/html/std66">URI scheme</a> before the colon at the start of text */ public static final Pattern URL_SCHEME_SANS_COLON_PATTERN = Pattern.compile("^" + URL_SCHEME_SANS_COLON_REGEX + "(?=:)"); public static final String URL_COMPONENT_SCHEME = "scheme"; public static final String URL_COMPONENT_USER = "user"; public static final String URL_COMPONENT_PASSWORD = "password"; public static final String URL_COMPONENT_HOST = "host"; public static final String URL_COMPONENT_PORT = "port"; public static final String URL_COMPONENT_PATH = "path"; public static final String URL_COMPONENT_QUERY = "query"; public static final String URL_COMPONENT_FRAGMENT = "fragment"; /** * Named capture groups for URL components * * Does not enforce that: * <ul> * <li>a port can only be an unsigned 16-bit number</li> * <li>a [/?#] must follow any port</li> * </ul> */ public static final Pattern URL_COMPONENT_PATTERN = Pattern.compile( "^(?:(?<" + URL_COMPONENT_SCHEME + ">" + URL_SCHEME_SANS_COLON_REGEX + "):)?" + "(?://" + "(?:" + "(?<" + URL_COMPONENT_USER + ">[^#?/@:]*+)" + "(?::(?<" + URL_COMPONENT_PASSWORD + ">[^#?/@]*+))?" + "@)?" + "(?<" + URL_COMPONENT_HOST + ">[^#?/:]*+)" + "(?::(?<" + URL_COMPONENT_PORT + ">\\d*+))?" + ")?" + "(?<" + URL_COMPONENT_PATH + ">[^#?]*+)" + "(?:\\?(?<" + URL_COMPONENT_QUERY + ">[^#]*+))?" + "(?:#(?<" + URL_COMPONENT_FRAGMENT + ">.*+))?" ) ; public static StringBuilder concatenateUrl( final String scheme, final String user, final String password, final String host, final String port, final String path, final String query, final String fragment ) { final StringBuilder urlSb = new StringBuilder(); if (scheme != null) { urlSb.append(scheme).append(":"); } if ( user != null || password != null || host != null || port != null ) { urlSb.append("//"); if ( user != null || password != null ) { append(urlSb, user); append(urlSb, ':', password); urlSb.append('@'); } append(urlSb, host); append(urlSb, ':', port); if (path != null) { if (path.charAt(0) != '/') { urlSb.append('/'); } urlSb.append(path); } } else { append(urlSb, path); } append(urlSb, '?', query); append(urlSb, '#', fragment); return urlSb; } private static StringBuilder append(final StringBuilder sb, final String s) { if (s != null) { sb.append(s); } return sb; } private static StringBuilder append(final StringBuilder sb, final char prefix, final String s) { if (s != null) { sb.append(prefix).append(s); } return sb; } public static int getDefaultPort(final String scheme) { Integer port = DEFAULT_PORT_BY_SCHEME.get(scheme); if (port == null) { try { port = new URL(scheme, "localhost", "").getDefaultPort(); DEFAULT_PORT_BY_SCHEME.put(scheme, port); } catch (final MalformedURLException ex) { throw new IllegalArgumentException(scheme + " is an unknown scheme", ex); } } return port; } /** * {@code url} starts with either {@code "/"} or a <a href="https://tools.ietf.org/html/std66">URI scheme</a> followed by {@code ":/"} */ public static boolean isAbsolute(final String url) { return ABSOLUTE_URL_PATTERN.matcher(url).find(); } /** * {@code url} does not start with either {@code "/"} or a <a href="https://tools.ietf.org/html/std66">URI scheme</a> followed by {@code ":/"} */ public static boolean isRelative(final String url) { return ! isAbsolute(url); } /** * {@code url} starts with either {@code "//"} or a <a href="https://tools.ietf.org/html/std66">URI scheme</a> followed by {@code "://"} */ public static boolean hasAuthority(final String url) { return HAS_AUTHORITY_URL_PATTERN.matcher(url).find(); } /** * @return <a href="https://tools.ietf.org/html/std66">URI scheme</a>, including trailing colon, if present; * otherwise, returns {@code null} */ public static String getSchemeWithColon(final String url) { return getSchemeWithColon(url, null); } /** * @return <a href="https://tools.ietf.org/html/std66">URI scheme</a>, including trailing colon, if present; * otherwise, returns {@code defaultScheme} */ public static String getSchemeWithColon(final String url, final String defaultScheme) { final Matcher m = URL_SCHEME_WITH_COLON_PATTERN.matcher(url); return m.find() ? m.group() : defaultScheme ; } /** * @return the substring of {@code url} after any <a href="https://tools.ietf.org/html/std66">URI scheme</a>, if scheme is present; * otherwise, returns {@code url} */ public static String getUrlSansScheme(final String url) { return URL_SCHEME_WITH_COLON_PATTERN.matcher(url).replaceFirst(""); } public static String withScheme(final String url, final Object o) { return o == null ? url : o instanceof Boolean ? withScheme(url, ((Boolean) o).booleanValue()) : withScheme(url, o.toString()) ; } public static String withScheme(final String url, final boolean retainScheme) { return retainScheme ? url : getUrlSansScheme(url) ; } public static String withScheme(final String url, final String scheme) { return scheme + ':' + getUrlSansScheme(url); } private Urls() {} }
simplified Urls.append(...) helper methods
asset-pipeline-core/src/main/java/asset/pipeline/utils/net/Urls.java
simplified Urls.append(...) helper methods
Java
apache-2.0
d950f02aa481335dacb0ffd0ad63d44b558b4d7c
0
thymeleaf/thymeleaf,thymeleaf/thymeleaf
/* * ============================================================================= * * Copyright (c) 2011-2016, The THYMELEAF team (http://www.thymeleaf.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ============================================================================= */ package thymeleafsandbox.stsm.web.controller; import java.util.Arrays; import java.util.Calendar; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; import thymeleafsandbox.stsm.business.entities.Feature; import thymeleafsandbox.stsm.business.entities.Row; import thymeleafsandbox.stsm.business.entities.SeedStarter; import thymeleafsandbox.stsm.business.entities.Type; import thymeleafsandbox.stsm.business.entities.Variety; import thymeleafsandbox.stsm.business.services.SeedStarterService; import thymeleafsandbox.stsm.business.services.VarietyService; @Controller public class SeedStarterMngController { private VarietyService varietyService; private SeedStarterService seedStarterService; public SeedStarterMngController() { super(); } @Autowired public void setVarietyService(final VarietyService varietyService) { this.varietyService = varietyService; } @Autowired public void setSeedStarterService(final SeedStarterService seedStarterService) { this.seedStarterService = seedStarterService; } @ModelAttribute("allTypes") public List<Type> populateTypes() { return Arrays.asList(Type.ALL); } @ModelAttribute("allFeatures") public List<Feature> populateFeatures() { return Arrays.asList(Feature.ALL); } @ModelAttribute("allVarieties") public List<Variety> populateVarieties() { return this.varietyService.findAll(); } @ModelAttribute("allSeedStarters") public List<SeedStarter> populateSeedStarters() { return this.seedStarterService.findAll(); } /* * NOTE that in this reactive version of STSM we cannot select the controller method to be executed * depending on the presence of a specific request parameter (using the "param" attribute of the * @RequestMapping annotation) because WebFlux does not include as "request parameters" data * coming from forms (see https://jira.spring.io/browse/SPR-15508 ). Doing so would mean blocking * for the time the framework needs for reading the request payload, which goes against the * general reactiveness of the architecture. * * So the ways to access data from form are, either include then as a part of form-backing bean * (in this case SeedStarter), or using exchange.getFormData(). In this case, modifying a model entity * like SeedStarter because of a very specific need of the user interface (adding the "save", * "addRow" or "removeRow" parameters in order to modify the form's structure from the server) would * not be very elegant, so instead we will read exchange.getFormData() and direct to a different * inner (private) controller method depending on the presence of these fields in the form data * coming from the client. */ @RequestMapping({"/","/seedstartermng"}) public Mono<String> doSeedstarter( final SeedStarter seedStarter, final BindingResult bindingResult, final ModelMap model, final ServerWebExchange exchange) { return exchange.getFormData().flatMap( formData -> { if (formData.containsKey("save")) { return saveSeedstarter(seedStarter, bindingResult, model); } if (formData.containsKey("addRow")) { return addRow(seedStarter, bindingResult); } if (formData.containsKey("removeRow")) { final int rowId = Integer.parseInt(formData.getFirst("removeRow")); return removeRow(seedStarter, bindingResult, rowId); } return showSeedstarters(seedStarter); }); } private Mono<String> showSeedstarters(final SeedStarter seedStarter) { seedStarter.setDatePlanted(Calendar.getInstance().getTime()); return Mono.just("seedstartermng"); } private Mono<String> saveSeedstarter(final SeedStarter seedStarter, final BindingResult bindingResult, final ModelMap model) { if (bindingResult.hasErrors()) { return Mono.just("seedstartermng"); } this.seedStarterService.add(seedStarter); model.clear(); return Mono.just("redirect:/seedstartermng"); } private Mono<String> addRow(final SeedStarter seedStarter, final BindingResult bindingResult) { seedStarter.getRows().add(new Row()); return Mono.just("seedstartermng"); } private Mono<String> removeRow( final SeedStarter seedStarter, final BindingResult bindingResult, final int rowId) { seedStarter.getRows().remove(rowId); return Mono.just("seedstartermng"); } }
src/main/java/thymeleafsandbox/stsm/web/controller/SeedStarterMngController.java
/* * ============================================================================= * * Copyright (c) 2011-2016, The THYMELEAF team (http://www.thymeleaf.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ============================================================================= */ package thymeleafsandbox.stsm.web.controller; import java.util.Arrays; import java.util.Calendar; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import thymeleafsandbox.stsm.business.entities.Feature; import thymeleafsandbox.stsm.business.entities.Row; import thymeleafsandbox.stsm.business.entities.SeedStarter; import thymeleafsandbox.stsm.business.entities.Type; import thymeleafsandbox.stsm.business.entities.Variety; import thymeleafsandbox.stsm.business.services.SeedStarterService; import thymeleafsandbox.stsm.business.services.VarietyService; @Controller public class SeedStarterMngController { private VarietyService varietyService; private SeedStarterService seedStarterService; public SeedStarterMngController() { super(); } @Autowired public void setVarietyService(final VarietyService varietyService) { this.varietyService = varietyService; } @Autowired public void setSeedStarterService(final SeedStarterService seedStarterService) { this.seedStarterService = seedStarterService; } @ModelAttribute("allTypes") public List<Type> populateTypes() { return Arrays.asList(Type.ALL); } @ModelAttribute("allFeatures") public List<Feature> populateFeatures() { return Arrays.asList(Feature.ALL); } @ModelAttribute("allVarieties") public List<Variety> populateVarieties() { return this.varietyService.findAll(); } @ModelAttribute("allSeedStarters") public List<SeedStarter> populateSeedStarters() { return this.seedStarterService.findAll(); } @RequestMapping({"/","/seedstartermng"}) public String showSeedstarters(final SeedStarter seedStarter) { seedStarter.setDatePlanted(Calendar.getInstance().getTime()); return "seedstartermng"; } @RequestMapping(value="/seedstartermng", params={"save"}) public String saveSeedstarter(final SeedStarter seedStarter, final BindingResult bindingResult, final ModelMap model) { if (bindingResult.hasErrors()) { return "seedstartermng"; } this.seedStarterService.add(seedStarter); model.clear(); return "redirect:/seedstartermng"; } @RequestMapping(value="/seedstartermng", params={"addRow"}) public String addRow(final SeedStarter seedStarter, final BindingResult bindingResult) { seedStarter.getRows().add(new Row()); return "seedstartermng"; } @RequestMapping(value="/seedstartermng", params={"removeRow"}) public String removeRow( final SeedStarter seedStarter, final BindingResult bindingResult, @RequestParam(value = "removeRow", required = false) Integer rowId) { seedStarter.getRows().remove(rowId.intValue()); return "seedstartermng"; } }
Adapted controller methods to https://jira.spring.io/browse/SPR-15508
src/main/java/thymeleafsandbox/stsm/web/controller/SeedStarterMngController.java
Adapted controller methods to https://jira.spring.io/browse/SPR-15508
Java
apache-2.0
7b5b7eaa265ae5988832b0c7930f375181426ba9
0
JohnPJenkins/swift-t,basheersubei/swift-t,blue42u/swift-t,basheersubei/swift-t,blue42u/swift-t,JohnPJenkins/swift-t,JohnPJenkins/swift-t,JohnPJenkins/swift-t,swift-lang/swift-t,swift-lang/swift-t,swift-lang/swift-t,blue42u/swift-t,blue42u/swift-t,blue42u/swift-t,swift-lang/swift-t,JohnPJenkins/swift-t,blue42u/swift-t,basheersubei/swift-t,JohnPJenkins/swift-t,swift-lang/swift-t,swift-lang/swift-t,basheersubei/swift-t,basheersubei/swift-t,basheersubei/swift-t,swift-lang/swift-t,JohnPJenkins/swift-t,basheersubei/swift-t,blue42u/swift-t
/* * Copyright 2013 University of Chicago and Argonne National Laboratory * * 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 exm.stc.ic.opt; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import exm.stc.common.Logging; import exm.stc.common.lang.Types; import exm.stc.common.lang.Var; import exm.stc.common.lang.Var.VarStorage; import exm.stc.ic.tree.ICContinuations.Continuation; import exm.stc.ic.tree.ICTree.Block; import exm.stc.ic.tree.ICTree.Function; public class DeadCodeEliminator { /** * Eliminates dead code in the current block and child blocks. Since * this is a data flow language, the easiest way to do this is to * find variables which aren't needed, eliminate those and the instructions * which write to them, and then do that repeatedly until we don't have anything * more to eliminate. * * We avoid eliminating any instructions with side-effects, and anything that * contributes to the return value of a function. We currently assume that * all non-builtin functions have side effects, as well as any builtins * operations that are not specifically marked as side-effect free. * @param logger * @param block */ public static void eliminate(Logger logger, Block block) { int i = 1; boolean converged = false; // repeatedly remove code until no more can go. running each of // the two steps here can lead to more unneeded code for the other step, // so it is easiest to just have a loop to make sure all code is eliminated while (!converged) { converged = eliminateIter(logger, block, i); i++; } } private static boolean eliminateIter(Logger logger, Block block, int iteration) { if (logger.isTraceEnabled()) { logger.trace("Dead code elimination iteration " + iteration + " on block: " + System.identityHashCode(block) + "<" + block.getType() + ">" + " with vars: " + block.getVariables()); } boolean converged = true; // First see if we can get rid of any continuations ListIterator<Continuation> it = block.continuationIterator(); while (it.hasNext()) { Continuation c = it.next(); if (c.isNoop()) { it.remove(); converged = false; } } // All dependent sets List<List<Var>> dependentSets = new ArrayList<List<Var>>(); // Vars needed in this block Set<Var> thisBlockNeeded = new HashSet<Var>(); Set<Var> thisBlockWritten = new HashSet<Var>(); block.findThisBlockNeededVars(thisBlockNeeded, thisBlockWritten, dependentSets); if (logger.isTraceEnabled()) { logger.trace("This block needed: " + thisBlockNeeded + " outputs: " + thisBlockWritten + " dependencies: " + dependentSets); } // Now see if we can push down any variable declarations /*var => null means candidate. var => Block means that it already appeared * in a single block */ Map<Var, Block> candidates = new HashMap<Var, Block>(); for (Var v: block.getVariables()) { // Candidates are those not needed in this block if (!thisBlockNeeded.contains(v) && !thisBlockWritten.contains(v)) candidates.put(v, null); } // Vars needed by subblocks List<Set<Var>> subblockNeededVars = new ArrayList<Set<Var>>(); for (Continuation cont: block.getContinuations()) { // All vars used within continuation blocks Set<Var> contAllUsed = new HashSet<Var>(); for (Block subBlock: cont.getBlocks()) { Set<Var> subblockNeeded = new HashSet<Var>(); Set<Var> subblockWritten = new HashSet<Var>(); subBlock.findNeededVars(subblockNeeded, subblockWritten, dependentSets); subblockNeededVars.add(subblockNeeded); if (logger.isTraceEnabled()) { logger.trace("Subblock " + subBlock.getType() + " needed: " + subblockNeeded + " outputs: " + subblockWritten); } // All vars used in subblock Set<Var> subblockAll = new HashSet<Var>(); subblockAll.addAll(subblockNeeded); subblockAll.addAll(subblockWritten); for (Var var: subblockAll) { if (candidates.containsKey(var)) { if (candidates.get(var) == null) { candidates.put(var, subBlock); } else { // Appeared in two places candidates.remove(var); } } } contAllUsed.addAll(subblockAll); } cont.removeUnused(contAllUsed); } // Push down variable declarations pushdownDeclarations(block, candidates); Set<Var> allNeeded = new HashSet<Var>(); allNeeded.addAll(thisBlockNeeded); for (Set<Var> needed: subblockNeededVars) { allNeeded.addAll(needed); } // Then see if we can remove individual instructions Set<Var> unneeded = unneededVars(block, allNeeded, dependentSets); for (Var v: unneeded) { logger.debug("Eliminated variable " + v + " during dead code elimination"); converged = false; } block.removeVars(unneeded); return converged; } private static void pushdownDeclarations(Block block, Map<Var, Block> candidates) { if (candidates.size() > 0) { ListIterator<Var> varIt = block.variableIterator(); while (varIt.hasNext()) { Var var = varIt.next(); if (Types.isArray(var.type()) && var.storage() != VarStorage.ALIAS) { // TODO Temporary fix: can't push array declarations // down into loop if assigned in loop continue; } Block newHome = candidates.get(var); if (newHome != null) { varIt.remove(); newHome.addVariable(var); block.moveCleanups(var, newHome); } } } } public static void eliminate(Logger logger, Function f) { eliminateRec(logger, f.getMainblock()); } public static void eliminateRec(Logger logger, Block block) { // Eliminate from bottom up so that references to vars in // subtrees are eliminated before checking vars in parent for (Continuation c: block.getContinuations()) { for (Block inner: c.getBlocks()) { eliminateRec(logger, inner); } } eliminate(logger, block); } /** * Find unneeded vars declared in local block * @param block * @param stillNeeded * @param dependentSets * @return */ private static Set<Var> unneededVars(Block block, Set<Var> stillNeeded, List<List<Var>> dependentSets) { HashSet<Var> removeCandidates = new HashSet<Var>(); for (Var v: block.getVariables()) { if (!stillNeeded.contains(v)) { removeCandidates.add(v); } } Logger logger = Logging.getSTCLogger(); if (logger.isTraceEnabled()) { logger.trace("start removeCandidates: " + removeCandidates + "\n" + "dependentSets: " + dependentSets); } boolean converged = false; // Check to see if we have to retain additional variables based on // interdependencies. We're really just computing the transitive // closure here in an iterative way. while (!converged && !dependentSets.isEmpty()) { Iterator<List<Var>> it = dependentSets.iterator(); while (it.hasNext()) { List<Var> dependentSet = it.next(); converged = true; // assume converged until something changes boolean hasRemoveCandidate = false; boolean allRemoveCandidates = true; for (Var v: dependentSet) { if (removeCandidates.contains(v)) { hasRemoveCandidate = true; } else { allRemoveCandidates = false; } } if (!hasRemoveCandidate) { // No longer relevant it.remove(); } else if (!allRemoveCandidates) { // Have to keep at least one remove candidate for (Var v: dependentSet) { removeCandidates.remove(v); } converged = false; } } } if (logger.isTraceEnabled()) { logger.trace("final removeCandidates: " + removeCandidates + "\n" + "dependentSets: " + dependentSets); } return removeCandidates; } }
code/src/exm/stc/ic/opt/DeadCodeEliminator.java
/* * Copyright 2013 University of Chicago and Argonne National Laboratory * * 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 exm.stc.ic.opt; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import exm.stc.common.lang.Types; import exm.stc.common.lang.Var; import exm.stc.common.lang.Var.VarStorage; import exm.stc.ic.tree.ICContinuations.Continuation; import exm.stc.ic.tree.ICTree.Block; import exm.stc.ic.tree.ICTree.Function; public class DeadCodeEliminator { /** * Eliminates dead code in the current block and child blocks. Since * this is a data flow language, the easiest way to do this is to * find variables which aren't needed, eliminate those and the instructions * which write to them, and then do that repeatedly until we don't have anything * more to eliminate. * * We avoid eliminating any instructions with side-effects, and anything that * contributes to the return value of a function. We currently assume that * all non-builtin functions have side effects, as well as any builtins * operations that are not specifically marked as side-effect free. * @param logger * @param block */ public static void eliminate(Logger logger, Block block) { int i = 1; boolean converged = false; // repeatedly remove code until no more can go. running each of // the two steps here can lead to more unneeded code for the other step, // so it is easiest to just have a loop to make sure all code is eliminated while (!converged) { converged = eliminateIter(logger, block, i); i++; } } private static boolean eliminateIter(Logger logger, Block block, int iteration) { if (logger.isTraceEnabled()) { logger.trace("Dead code elimination iteration " + iteration + " on block: " + System.identityHashCode(block) + "<" + block.getType() + ">" + " with vars: " + block.getVariables()); } boolean converged = true; // First see if we can get rid of any continuations ListIterator<Continuation> it = block.continuationIterator(); while (it.hasNext()) { Continuation c = it.next(); if (c.isNoop()) { it.remove(); converged = false; } } // All dependent sets List<List<Var>> dependentSets = new ArrayList<List<Var>>(); // Vars needed in this block Set<Var> thisBlockNeeded = new HashSet<Var>(); Set<Var> thisBlockWritten = new HashSet<Var>(); block.findThisBlockNeededVars(thisBlockNeeded, thisBlockWritten, dependentSets); if (logger.isTraceEnabled()) { logger.trace("This block needed: " + thisBlockNeeded + " outputs: " + thisBlockWritten + " dependencies: " + dependentSets); } // Now see if we can push down any variable declarations /*var => null means candidate. var => Block means that it already appeared * in a single block */ Map<Var, Block> candidates = new HashMap<Var, Block>(); for (Var v: block.getVariables()) { // Candidates are those not needed in this block if (!thisBlockNeeded.contains(v) && !thisBlockWritten.contains(v)) candidates.put(v, null); } // Vars needed by subblocks List<Set<Var>> subblockNeededVars = new ArrayList<Set<Var>>(); for (Continuation cont: block.getContinuations()) { // All vars used within continuation blocks Set<Var> contAllUsed = new HashSet<Var>(); for (Block subBlock: cont.getBlocks()) { Set<Var> subblockNeeded = new HashSet<Var>(); Set<Var> subblockWritten = new HashSet<Var>(); subBlock.findNeededVars(subblockNeeded, subblockWritten, dependentSets); subblockNeededVars.add(subblockNeeded); if (logger.isTraceEnabled()) { logger.trace("Subblock " + subBlock.getType() + " needed: " + subblockNeeded + " outputs: " + subblockWritten); } // All vars used in subblock Set<Var> subblockAll = new HashSet<Var>(); subblockAll.addAll(subblockNeeded); subblockAll.addAll(subblockWritten); for (Var var: subblockAll) { if (candidates.containsKey(var)) { if (candidates.get(var) == null) { candidates.put(var, subBlock); } else { // Appeared in two places candidates.remove(var); } } } contAllUsed.addAll(subblockAll); } cont.removeUnused(contAllUsed); } // Push down variable declarations pushdownDeclarations(block, candidates); Set<Var> allNeeded = new HashSet<Var>(); allNeeded.addAll(thisBlockNeeded); for (Set<Var> needed: subblockNeededVars) { allNeeded.addAll(needed); } // Then see if we can remove individual instructions Set<Var> unneeded = unneededVars(block, allNeeded, dependentSets); for (Var v: unneeded) { logger.debug("Eliminated variable " + v + " during dead code elimination"); converged = false; } block.removeVars(unneeded); return converged; } private static void pushdownDeclarations(Block block, Map<Var, Block> candidates) { if (candidates.size() > 0) { ListIterator<Var> varIt = block.variableIterator(); while (varIt.hasNext()) { Var var = varIt.next(); if (Types.isArray(var.type()) && var.storage() != VarStorage.ALIAS) { // TODO Temporary fix: can't push array declarations // down into loop if assigned in loop continue; } Block newHome = candidates.get(var); if (newHome != null) { varIt.remove(); newHome.addVariable(var); block.moveCleanups(var, newHome); } } } } public static void eliminate(Logger logger, Function f) { eliminateRec(logger, f.getMainblock()); } public static void eliminateRec(Logger logger, Block block) { // Eliminate from bottom up so that references to vars in // subtrees are eliminated before checking vars in parent for (Continuation c: block.getContinuations()) { for (Block inner: c.getBlocks()) { eliminateRec(logger, inner); } } eliminate(logger, block); } /** * Find unneeded vars declared in local block * @param block * @param stillNeeded * @param dependentSets * @return */ private static Set<Var> unneededVars(Block block, Set<Var> stillNeeded, List<List<Var>> dependentSets) { HashSet<Var> toRemove = new HashSet<Var>(); // Check to see if we have to retain additional // variables based on interdependencies for (List<Var> dependentSet: dependentSets) { { boolean needed = false; for (Var v: dependentSet) { if (stillNeeded.contains(v)) { needed = true; break; } } if (needed) { for (Var v: dependentSet) { stillNeeded.add(v); } } } } for (Var v: block.getVariables()) { if (!stillNeeded.contains(v)) { toRemove.add(v); } } return toRemove; } }
Fix dependent sets bug for test 118 git-svn-id: 47705994653588c662f4ea400dfe88107361c0e2@6186 dc4e9af1-7f46-4ead-bba6-71afc04862de
code/src/exm/stc/ic/opt/DeadCodeEliminator.java
Fix dependent sets bug for test 118
Java
apache-2.0
3c818601cd734d359186ff372a230a2be653bedf
0
nadundesilva/siddhi,ChariniNana/siddhi,suhothayan/siddhi,sajithshn/siddhi,grainier/siddhi,tishan89/siddhi,mohanvive/siddhi,codemogroup/siddhi,grainier/siddhi,nadundesilva/siddhi,dilini-muthumala/siddhi,tishan89/siddhi,gokul/siddhi,slgobinath/siddhi,minudika/siddhi,dilini-muthumala/siddhi,ramindu90/siddhi,miyurud/siddhi,wso2/siddhi,ksdperera/siddhi,ChariniNana/siddhi,gokul/siddhi,ksdperera/siddhi,suhothayan/siddhi,sajithshn/siddhi,codemogroup/siddhi,wso2/siddhi,mohanvive/siddhi,miyurud/siddhi,ramindu90/siddhi,slgobinath/siddhi,minudika/siddhi
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.siddhi.core; import org.testng.AssertJUnit; import org.wso2.siddhi.core.event.Event; import org.wso2.siddhi.core.query.output.callback.QueryCallback; import org.wso2.siddhi.core.stream.output.StreamCallback; import org.wso2.siddhi.core.util.EventPrinter; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; public class TestUtil { private TestUtil() { } /** * Add a callback to the given {@link SiddhiAppRuntime} and validate the assertions. * * @param siddhiAppRuntime the SiddhiAppRuntime * @param queryName the query * @param expected expected event data * @return TestCallback */ public static TestCallback addQueryCallback(SiddhiAppRuntime siddhiAppRuntime, String queryName, Object[]... expected) { TestQueryCallback callBack = new TestQueryCallback(expected); siddhiAppRuntime.addCallback(queryName, callBack); return callBack; } /** * Add a callback to the given {@link SiddhiAppRuntime} and validate the assertions. * * @param siddhiAppRuntime the SiddhiAppRuntime * @param streamName the stream * @param expected expected event data * @return TestCallback */ public static TestCallback addStreamCallback(SiddhiAppRuntime siddhiAppRuntime, String streamName, Object[]... expected) { TestStreamCallback callBack = new TestStreamCallback(expected); siddhiAppRuntime.addCallback(streamName, callBack); return callBack; } /** * The API which lets the developers to get the statistics of test results. */ public interface TestCallback { /** * Returns a list of assertion errors thrown while testing. * * @return a list of assertion errors */ List<AssertionError> getAssertionErrors(); /** * Returns the number of events received in. * * @return the number of events received in */ int getInEventCount(); /** * Returns the number of events removed from. This method can be called only for QueryCallbacks. Otherwise * throws and {@link UnsupportedOperationException} * * @return the number of events removed from * @throws UnsupportedOperationException if the callback was added for a stream */ int getRemoveEventCount() throws UnsupportedOperationException; /** * Returns true if there is at-least an event received by the query or stream. * * @return true if at-least an event is received otherwise false */ boolean isEventArrived(); /** * Throw all the {@link AssertionError}s captured while testing. */ void throwAssertionErrors(); } private static class TestQueryCallback extends QueryCallback implements TestCallback { private AtomicInteger inEventCount = new AtomicInteger(0); private AtomicInteger removeEventCount = new AtomicInteger(0); private boolean eventArrived; private List<AssertionError> assertionErrors = new ArrayList<>(); private final Object[][] expected; private final int noOfExpectedEvents; public TestQueryCallback(Object[]... expected) { this.expected = expected; this.noOfExpectedEvents = expected.length; } @Override public void receive(long timestamp, Event[] inEvents, Event[] removeEvents) { // Print the events EventPrinter.print(timestamp, inEvents, removeEvents); if (inEvents != null) { eventArrived = true; for (Event event : inEvents) { int inEvent = inEventCount.incrementAndGet(); if (noOfExpectedEvents > 0 && inEvent <= noOfExpectedEvents) { try { AssertJUnit.assertArrayEquals(expected[inEvent - 1], event.getData()); } catch (AssertionError e) { assertionErrors.add(e); } } } } if (removeEvents != null) { removeEventCount.addAndGet(removeEvents.length); } } @Override public List<AssertionError> getAssertionErrors() { return this.assertionErrors; } @Override public int getInEventCount() { return this.inEventCount.get(); } @Override public int getRemoveEventCount() { return this.removeEventCount.get(); } @Override public boolean isEventArrived() { return this.eventArrived; } @Override public void throwAssertionErrors() { for (AssertionError error : this.assertionErrors) { throw error; } } } private static class TestStreamCallback extends StreamCallback implements TestCallback { private AtomicInteger inEventCount = new AtomicInteger(0); private boolean eventArrived; private List<AssertionError> assertionErrors = new ArrayList<>(); private final Object[][] expected; private final int noOfExpectedEvents; public TestStreamCallback(Object[]... expected) { this.expected = expected; this.noOfExpectedEvents = expected.length; } @Override public void receive(Event[] events) { // Print the events EventPrinter.print(events); if (events != null) { eventArrived = true; for (Event event : events) { int inEvent = inEventCount.incrementAndGet(); if (noOfExpectedEvents > 0 && inEvent <= noOfExpectedEvents) { try { AssertJUnit.assertArrayEquals(expected[inEvent - 1], event.getData()); } catch (AssertionError e) { assertionErrors.add(e); } } } } } @Override public List<AssertionError> getAssertionErrors() { return this.assertionErrors; } @Override public int getInEventCount() { return this.inEventCount.get(); } @Override public int getRemoveEventCount() { throw new UnsupportedOperationException("StreamCallback does not receive remove events"); } @Override public boolean isEventArrived() { return this.eventArrived; } @Override public void throwAssertionErrors() { for (AssertionError error : this.assertionErrors) { throw error; } } } }
modules/siddhi-core/src/test/java/org/wso2/siddhi/core/TestUtil.java
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.siddhi.core; import org.junit.Assert; import org.wso2.siddhi.core.event.Event; import org.wso2.siddhi.core.query.output.callback.QueryCallback; import org.wso2.siddhi.core.stream.output.StreamCallback; import org.wso2.siddhi.core.util.EventPrinter; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; public class TestUtil { private TestUtil() { } /** * Add a callback to the given {@link SiddhiAppRuntime} and validate the assertions. * * @param siddhiAppRuntime the SiddhiAppRuntime * @param queryName the query * @param expected expected event data * @return TestCallback */ public static TestCallback addQueryCallback(SiddhiAppRuntime siddhiAppRuntime, String queryName, Object[]... expected) { TestQueryCallback callBack = new TestQueryCallback(expected); siddhiAppRuntime.addCallback(queryName, callBack); return callBack; } /** * Add a callback to the given {@link SiddhiAppRuntime} and validate the assertions. * * @param siddhiAppRuntime the SiddhiAppRuntime * @param streamName the stream * @param expected expected event data * @return TestCallback */ public static TestCallback addStreamCallback(SiddhiAppRuntime siddhiAppRuntime, String streamName, Object[]... expected) { TestStreamCallback callBack = new TestStreamCallback(expected); siddhiAppRuntime.addCallback(streamName, callBack); return callBack; } /** * The API which lets the developers to get the statistics of test results. */ public interface TestCallback { /** * Returns a list of assertion errors thrown while testing. * * @return a list of assertion errors */ List<AssertionError> getAssertionErrors(); /** * Returns the number of events received in. * * @return the number of events received in */ int getInEventCount(); /** * Returns the number of events removed from. This method can be called only for QueryCallbacks. Otherwise * throws and {@link UnsupportedOperationException} * * @return the number of events removed from * @throws UnsupportedOperationException if the callback was added for a stream */ int getRemoveEventCount() throws UnsupportedOperationException; /** * Returns true if there is at-least an event received by the query or stream. * * @return true if at-least an event is received otherwise false */ boolean isEventArrived(); /** * Throw all the {@link AssertionError}s captured while testing. */ void throwAssertionErrors(); } private static class TestQueryCallback extends QueryCallback implements TestCallback { private AtomicInteger inEventCount = new AtomicInteger(0); private AtomicInteger removeEventCount = new AtomicInteger(0); private boolean eventArrived; private List<AssertionError> assertionErrors = new ArrayList<>(); private final Object[][] expected; private final int noOfExpectedEvents; public TestQueryCallback(Object[]... expected) { this.expected = expected; this.noOfExpectedEvents = expected.length; } @Override public void receive(long timestamp, Event[] inEvents, Event[] removeEvents) { // Print the events EventPrinter.print(timestamp, inEvents, removeEvents); if (inEvents != null) { eventArrived = true; for (Event event : inEvents) { int inEvent = inEventCount.incrementAndGet(); if (noOfExpectedEvents > 0 && inEvent <= noOfExpectedEvents) { try { Assert.assertArrayEquals(expected[inEvent - 1], event.getData()); } catch (AssertionError e) { assertionErrors.add(e); } } } } if (removeEvents != null) { removeEventCount.addAndGet(removeEvents.length); } } @Override public List<AssertionError> getAssertionErrors() { return this.assertionErrors; } @Override public int getInEventCount() { return this.inEventCount.get(); } @Override public int getRemoveEventCount() { return this.removeEventCount.get(); } @Override public boolean isEventArrived() { return this.eventArrived; } @Override public void throwAssertionErrors() { for (AssertionError error : this.assertionErrors) { throw error; } } } private static class TestStreamCallback extends StreamCallback implements TestCallback { private AtomicInteger inEventCount = new AtomicInteger(0); private boolean eventArrived; private List<AssertionError> assertionErrors = new ArrayList<>(); private final Object[][] expected; private final int noOfExpectedEvents; public TestStreamCallback(Object[]... expected) { this.expected = expected; this.noOfExpectedEvents = expected.length; } @Override public void receive(Event[] events) { // Print the events EventPrinter.print(events); if (events != null) { eventArrived = true; for (Event event : events) { int inEvent = inEventCount.incrementAndGet(); if (noOfExpectedEvents > 0 && inEvent <= noOfExpectedEvents) { try { Assert.assertArrayEquals(expected[inEvent - 1], event.getData()); } catch (AssertionError e) { assertionErrors.add(e); } } } } } @Override public List<AssertionError> getAssertionErrors() { return this.assertionErrors; } @Override public int getInEventCount() { return this.inEventCount.get(); } @Override public int getRemoveEventCount() { throw new UnsupportedOperationException("StreamCallback does not receive remove events"); } @Override public boolean isEventArrived() { return this.eventArrived; } @Override public void throwAssertionErrors() { for (AssertionError error : this.assertionErrors) { throw error; } } } }
Remove junit dependency from TestUtil class
modules/siddhi-core/src/test/java/org/wso2/siddhi/core/TestUtil.java
Remove junit dependency from TestUtil class
Java
apache-2.0
4ea09ff2e4d854631631cb2b590a2884cfea7c2f
0
andrei-viaryshka/pentaho-hadoop-shims,mkambol/pentaho-hadoop-shims,pentaho/pentaho-hadoop-shims,smaring/pentaho-hadoop-shims,SergeyTravin/pentaho-hadoop-shims
/******************************************************************************* * Pentaho Big Data * <p> * Copyright (C) 2017 by Pentaho : http://www.pentaho.com * <p> * ****************************************************************************** * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. ******************************************************************************/ package org.pentaho.hadoop.shim.common; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.support.membermodification.MemberModifier; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.io.IOException; /** * Created by Vasilina_Terehova on 10/3/2017. */ @RunWith( PowerMockRunner.class ) @PrepareForTest( ShellPrevalidator.class ) public class ShellPrevalidatorTest { @Test public void validateReturnTrueIfFileExist() throws IOException { MemberModifier .stub( MemberModifier.method( ShellPrevalidator.class, "doesFileExist", String.class ) ) .toReturn( true ); MemberModifier .stub( MemberModifier.method( ShellPrevalidator.class, "isWindows" ) ) .toReturn( true ); boolean exist = ShellPrevalidator.doesWinutilsFileExist(); Assert.assertEquals( true, exist ); } @Test( expected = IOException.class ) public void validateThrowIOExceptionWhenNoExist() throws IOException { MemberModifier .stub( MemberModifier.method( ShellPrevalidator.class, "doesFileExist", String.class ) ) .toReturn( false ); MemberModifier .stub( MemberModifier.method( ShellPrevalidator.class, "isWindows" ) ) .toReturn( true ); boolean exist = ShellPrevalidator.doesWinutilsFileExist(); Assert.assertEquals( false, exist ); } @Test( expected = IOException.class ) public void validateThrowExceptionWhenWindowsAndFileNotExist() throws IOException { MemberModifier .stub( MemberModifier.method( ShellPrevalidator.class, "isWindows" ) ) .toReturn( true ); MemberModifier .stub( MemberModifier.method( ShellPrevalidator.class, "doesFileExist", String.class ) ) .toReturn( false ); boolean exist = ShellPrevalidator.doesWinutilsFileExist(); Assert.assertEquals( false, exist ); } @Test public void validateReturnTrueIfNotWindows() throws IOException { MemberModifier .stub( MemberModifier.method( ShellPrevalidator.class, "isWindows" ) ) .toReturn( false ); MemberModifier .stub( MemberModifier.method( ShellPrevalidator.class, "doesFileExist", String.class ) ) .toReturn( false ); boolean exist = ShellPrevalidator.doesWinutilsFileExist(); Assert.assertEquals( true, exist ); } }
common/common-shim/src/test/java/org/pentaho/hadoop/shim/common/ShellPrevalidatorTest.java
/******************************************************************************* * Pentaho Big Data * <p> * Copyright (C) 2017 by Pentaho : http://www.pentaho.com * <p> * ****************************************************************************** * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. ******************************************************************************/ package org.pentaho.hadoop.shim.common; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.support.membermodification.MemberModifier; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.io.IOException; /** * Created by Vasilina_Terehova on 10/3/2017. */ @RunWith( PowerMockRunner.class ) @PrepareForTest( ShellPrevalidator.class ) public class ShellPrevalidatorTest { @Test public void validateReturnTrueIfFileExist() throws IOException { MemberModifier .stub( MemberModifier.method( ShellPrevalidator.class, "doesFileExist", String.class ) ) .toReturn( true ); MemberModifier .stub( MemberModifier.method( ShellPrevalidator.class, "isWindows" ) ) .toReturn( true ); boolean exist = ShellPrevalidator.doesWinutilsFileExist(); Assert.assertEquals( true, exist ); } @Test( expected = IOException.class ) public void validateThrowIOExceptionWhenNoExist() throws IOException { MemberModifier .stub( MemberModifier.method( ShellPrevalidator.class, "doesFileExist", String.class ) ) .toReturn( false ); boolean exist = ShellPrevalidator.doesWinutilsFileExist(); Assert.assertEquals( false, exist ); } @Test( expected = IOException.class ) public void validateThrowExceptionWhenWindowsAndFileNotExist() throws IOException { MemberModifier .stub( MemberModifier.method( ShellPrevalidator.class, "isWindows" ) ) .toReturn( true ); MemberModifier .stub( MemberModifier.method( ShellPrevalidator.class, "doesFileExist", String.class ) ) .toReturn( false ); boolean exist = ShellPrevalidator.doesWinutilsFileExist(); Assert.assertEquals( false, exist ); } @Test public void validateReturnTrueIfNotWindows() throws IOException { MemberModifier .stub( MemberModifier.method( ShellPrevalidator.class, "isWindows" ) ) .toReturn( false ); MemberModifier .stub( MemberModifier.method( ShellPrevalidator.class, "doesFileExist", String.class ) ) .toReturn( false ); boolean exist = ShellPrevalidator.doesWinutilsFileExist(); Assert.assertEquals( true, exist ); } }
[BACKLOG-19086]-Windows OS: Error is thrown in Spoon log on attempt to test shim
common/common-shim/src/test/java/org/pentaho/hadoop/shim/common/ShellPrevalidatorTest.java
[BACKLOG-19086]-Windows OS: Error is thrown in Spoon log on attempt to test shim
Java
apache-2.0
d42c9a68eb1e29c30c5db311498f57b583ea3472
0
ISSC/Bluebit
// vim: et sw=4 sts=4 tabstop=4 package com.issc.ui; import com.issc.Bluebit; import com.issc.data.BLEDevice; import com.issc.impl.GattProxy; import com.issc.impl.GattQueue; import com.issc.R; import com.issc.util.Log; import com.issc.util.Util; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Iterator; import java.util.UUID; import java.util.List; import android.app.Activity; import android.app.Dialog; import android.app.ProgressDialog; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothProfile; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.method.ScrollingMovementMethod; import android.view.View; import android.widget.ArrayAdapter; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener;; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.TabHost; import android.widget.TextView; import android.widget.ToggleButton; import com.samsung.android.sdk.bt.gatt.BluetoothGatt; import com.samsung.android.sdk.bt.gatt.BluetoothGattAdapter; import com.samsung.android.sdk.bt.gatt.BluetoothGattCallback; import com.samsung.android.sdk.bt.gatt.BluetoothGattCharacteristic; import com.samsung.android.sdk.bt.gatt.BluetoothGattService; public class ActivityTransparent extends Activity implements GattQueue.Consumer { private BluetoothDevice mDevice; private BluetoothGatt mGatt; private GattProxy.Listener mListener; private ProgressDialog mConnectionDialog; private ProgressDialog mTimerDialog; protected ViewHandler mViewHandler; private GattQueue mQueue; private final static int PAYLOAD_MAX = 20; // 20 bytes is max? private final static int CONNECTION_DIALOG = 1; private final static int TIMER_DIALOG = 2; private final static int CHOOSE_FILE = 0x101; private final static int SHOW_CONNECTION_DIALOG = 0x1000; private final static int DISMISS_CONNECTION_DIALOG = 0x1001; private final static int CONSUME_TRANSACTION = 0x1002; private final static int DISMISS_TIMER_DIALOG = 0x1003; private TabHost mTabHost; private TextView mMsg; private EditText mInput; private Button mBtnSend; private ToggleButton mToggle; private Spinner mSpinnerDelta; private Spinner mSpinnerSize; private Spinner mSpinnerRepeat; private int[] mValueDelta; private int[] mValueSize; private int[] mValueRepeat; private BluetoothGattCharacteristic mTransTx; private BluetoothGattCharacteristic mTransRx; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_trans); mQueue = new GattQueue(this); mMsg = (TextView)findViewById(R.id.trans_msg); mInput = (EditText)findViewById(R.id.trans_input); mBtnSend = (Button)findViewById(R.id.trans_btn_send); mViewHandler = new ViewHandler(); mTabHost = (TabHost) findViewById(R.id.tabhost); mTabHost.setup(); addTab(mTabHost, "Tab1", "Raw", R.id.tab_raw); addTab(mTabHost, "Tab2", "Timer", R.id.tab_timer); addTab(mTabHost, "Tab3", "Echo", R.id.tab_echo); mMsg.setMovementMethod(ScrollingMovementMethod.getInstance()); BLEDevice device = getIntent().getParcelableExtra(Bluebit.CHOSEN_DEVICE); mDevice = device.getDevice(); mListener = new GattListener(); initSpinners(); } private void initSpinners() { Resources res = getResources(); mSpinnerDelta = (Spinner)findViewById(R.id.timer_delta); mSpinnerSize = (Spinner)findViewById(R.id.timer_size); mSpinnerRepeat = (Spinner)findViewById(R.id.timer_repeat); mValueDelta = res.getIntArray(R.array.delta_value); mValueSize = res.getIntArray(R.array.size_value); mValueRepeat = res.getIntArray(R.array.repeat_value); initSpinner(R.array.delta_text, mSpinnerDelta); initSpinner(R.array.size_text, mSpinnerSize); initSpinner(R.array.repeat_text, mSpinnerRepeat); mSpinnerDelta.setSelection(2); // supposed to select 1000ms mSpinnerSize.setSelection(19); // supposed to select 20bytes mSpinnerRepeat.setSelection(0); // supposed to select Unlimited } private void initSpinner(int textArrayId, Spinner spinner) { ArrayAdapter<CharSequence> adapter; adapter = ArrayAdapter.createFromResource( this, textArrayId, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); } @Override protected void onResume() { super.onResume(); GattProxy proxy = GattProxy.get(this); proxy.addListener(mListener); proxy.retrieveGatt(mListener); } @Override protected void onPause() { super.onPause(); GattProxy proxy = GattProxy.get(this); proxy.rmListener(mListener); } private void addTab(TabHost host, String tag, CharSequence text, int viewResource) { View indicator = getLayoutInflater().inflate(R.layout.tab_indicator, null); TextView tv = (TextView)indicator.findViewById(R.id.indicator_text); tv.setText(text); TabHost.TabSpec spec = host.newTabSpec(tag); spec.setIndicator(indicator); spec.setContent(viewResource); host.addTab(spec); } public void onClickSend(View v) { CharSequence cs = mInput.getText(); send(cs); } public void onClickStartTimer(View v) { showDialog(TIMER_DIALOG); startTimer(); } public void onClickChoose(View v) { /* you should install a file chooser beforehand. */ Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("text/plain"); startActivityForResult(intent, CHOOSE_FILE); } public void onClickToggle(View v) { onSetType(mToggle.isChecked()); } private void onSetType(boolean withResponse) { Log.d("set write with response:" + withResponse); } @Override protected void onActivityResult(int request, int result, Intent data) { if (request == CHOOSE_FILE) { if (result == Activity.RESULT_OK) { Uri uri = data.getData(); String filePath = uri.getPath(); Log.d("chosen file:" + filePath); try { send(Util.readStrFromFile(filePath)); } catch (IOException e) { e.printStackTrace(); Log.d("IO Exception"); } } } } private void send(CharSequence cs) { Log.d("send:" + cs.toString()); mMsg.append("send:"); mMsg.append(cs); mMsg.append("\n"); write(cs); } private void write(CharSequence cs) { byte[] bytes = cs.toString().getBytes(); ByteBuffer buf = ByteBuffer.allocate(bytes.length); while(buf.remaining() != 0) { int size = (buf.remaining() > PAYLOAD_MAX) ? PAYLOAD_MAX: buf.remaining(); byte[] dst = new byte[size]; buf.get(dst, 0, size); mQueue.add(mTransRx, dst); mQueue.consume(); } } @Override public void onTransact(BluetoothGattCharacteristic chr, byte[] value) { chr.setValue(value); int type = mToggle.isChecked() ? BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT: BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE; chr.setWriteType(type); mGatt.writeCharacteristic(chr); } @Override protected Dialog onCreateDialog(int id, Bundle args) { /*FIXME: this function is deprecated. */ if (id == CONNECTION_DIALOG) { mConnectionDialog = new ProgressDialog(this); mConnectionDialog.setMessage(this.getString(R.string.connecting)); mConnectionDialog.setCancelable(true); return mConnectionDialog; } else if (id == TIMER_DIALOG) { mTimerDialog = new ProgressDialog(this); mTimerDialog.setMessage("Timer is running"); mTimerDialog.setOnCancelListener(new Dialog.OnCancelListener() { public void onCancel(DialogInterface dialog) { Log.d("some one canceled me"); stopTimer(); } }); return mTimerDialog; } return null; } private void onTimerSend(int count, int size) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < size; i++) { sb.append("" + count); } Log.d(sb.toString()); write(sb); } private boolean mRunning; private void startTimer() { final int delta = mValueDelta[mSpinnerDelta.getSelectedItemPosition()]; final int size = mValueSize[mSpinnerSize.getSelectedItemPosition()]; final int repeat = mValueRepeat[mSpinnerRepeat.getSelectedItemPosition()]; mRunning = true; Thread runner = new Thread() { public void run() { int counter = 0; try { while(mRunning) { if (repeat != 0 && repeat == counter) { stopTimer(); } else { onTimerSend(counter, size); sleep(delta); counter++; } } } catch (Exception e) { e.printStackTrace(); } updateView(DISMISS_TIMER_DIALOG, null); } }; runner.start(); } private void stopTimer() { mRunning = false; } public void updateView(int tag, Bundle info) { if (info == null) { info = new Bundle(); } mViewHandler.removeMessages(tag); Message msg = mViewHandler.obtainMessage(tag); msg.what = tag; msg.setData(info); mViewHandler.sendMessage(msg); } class ViewHandler extends Handler { public void handleMessage(Message msg) { Bundle bundle = msg.getData(); if (bundle == null) { Log.d("ViewHandler handled a message without information"); return; } int tag = msg.what; if (tag == SHOW_CONNECTION_DIALOG) { showDialog(CONNECTION_DIALOG); } else if (tag == DISMISS_CONNECTION_DIALOG) { if (mConnectionDialog != null && mConnectionDialog.isShowing()) { dismissDialog(CONNECTION_DIALOG); } } else if (tag == DISMISS_TIMER_DIALOG) { if (mTimerDialog != null && mTimerDialog.isShowing()) { dismissDialog(TIMER_DIALOG); } } else if (tag == CONSUME_TRANSACTION) { mQueue.consume(); } } } private void onConnected() { List<BluetoothGattService> list = mGatt.getServices(mDevice); if ((list == null) || (list.size() == 0)) { Log.d("no services, do discovery"); mGatt.discoverServices(mDevice); } else { onDiscovered(); } } private void onDiscovered() { updateView(DISMISS_CONNECTION_DIALOG, null); BluetoothGattService proprietary = mGatt.getService(mDevice, Bluebit.SERVICE_ISSC_PROPRIETARY); mTransTx = proprietary.getCharacteristic(Bluebit.CHR_ISSC_TRANS_TX); mTransRx = proprietary.getCharacteristic(Bluebit.CHR_ISSC_TRANS_RX); Log.d(String.format("found Tx:%b, Rx:%b", mTransTx != null, mTransRx != null)); } class GattListener extends GattProxy.ListenerHelper { GattListener() { super("ActivityTransparent"); } @Override public void onRetrievedGatt(BluetoothGatt gatt) { Log.d(String.format("onRetrievedGatt")); mGatt = gatt; int conn = mGatt.getConnectionState(mDevice); if (conn == BluetoothProfile.STATE_DISCONNECTED) { Log.d("disconnected, connecting to device"); updateView(SHOW_CONNECTION_DIALOG, null); mGatt.connect(mDevice, true); } else { Log.d("already connected"); onConnected(); } } @Override public void onServicesDiscovered(BluetoothDevice device, int status) { onDiscovered(); } @Override public void onCharacteristicRead(BluetoothGattCharacteristic charac, int status) { Log.d("read char, uuid=" + charac.getUuid().toString()); byte[] value = charac.getValue(); Log.d("get value, byte length:" + value.length); for (int i = 0; i < value.length; i++) { Log.d("[" + i + "]" + Byte.toString(value[i])); } } @Override public void onCharacteristicWrite(BluetoothGattCharacteristic charac, int status) { mQueue.consumedOne(); updateView(CONSUME_TRANSACTION, null); } } }
src/com/issc/ui/ActivityTransparent.java
// vim: et sw=4 sts=4 tabstop=4 package com.issc.ui; import com.issc.Bluebit; import com.issc.data.BLEDevice; import com.issc.impl.GattProxy; import com.issc.impl.GattQueue; import com.issc.R; import com.issc.util.Log; import com.issc.util.Util; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Iterator; import java.util.UUID; import java.util.List; import android.app.Activity; import android.app.Dialog; import android.app.ProgressDialog; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothProfile; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.method.ScrollingMovementMethod; import android.view.View; import android.widget.ArrayAdapter; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener;; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.TabHost; import android.widget.TextView; import android.widget.ToggleButton; import com.samsung.android.sdk.bt.gatt.BluetoothGatt; import com.samsung.android.sdk.bt.gatt.BluetoothGattAdapter; import com.samsung.android.sdk.bt.gatt.BluetoothGattCallback; import com.samsung.android.sdk.bt.gatt.BluetoothGattCharacteristic; import com.samsung.android.sdk.bt.gatt.BluetoothGattService; public class ActivityTransparent extends Activity implements GattQueue.Consumer { private BluetoothDevice mDevice; private BluetoothGatt mGatt; private GattProxy.Listener mListener; private ProgressDialog mConnectionDialog; private ProgressDialog mTimerDialog; protected ViewHandler mViewHandler; private GattQueue mQueue; private final static int PAYLOAD_MAX = 20; // 20 bytes is max? private final static int CONNECTION_DIALOG = 1; private final static int TIMER_DIALOG = 2; private final static int CHOOSE_FILE = 0x101; private final static int SHOW_CONNECTION_DIALOG = 0x1000; private final static int DISMISS_CONNECTION_DIALOG = 0x1001; private final static int CONSUME_TRANSACTION = 0x1002; private final static int DISMISS_TIMER_DIALOG = 0x1003; private TabHost mTabHost; private TextView mMsg; private EditText mInput; private Button mBtnSend; private ToggleButton mToggle; private Spinner mSpinnerDelta; private Spinner mSpinnerSize; private Spinner mSpinnerRepeat; private int[] mValueDelta; private int[] mValueSize; private int[] mValueRepeat; private BluetoothGattCharacteristic mTransTx; private BluetoothGattCharacteristic mTransRx; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_trans); mQueue = new GattQueue(this); mMsg = (TextView)findViewById(R.id.trans_msg); mInput = (EditText)findViewById(R.id.trans_input); mBtnSend = (Button)findViewById(R.id.trans_btn_send); mViewHandler = new ViewHandler(); mTabHost = (TabHost) findViewById(R.id.tabhost); mTabHost.setup(); addTab(mTabHost, "Tab1", "Raw", R.id.tab_raw); addTab(mTabHost, "Tab2", "Timer", R.id.tab_timer); addTab(mTabHost, "Tab3", "Echo", R.id.tab_echo); mMsg.setMovementMethod(ScrollingMovementMethod.getInstance()); BLEDevice device = getIntent().getParcelableExtra(Bluebit.CHOSEN_DEVICE); //mDevice = device.getDevice(); mListener = new GattListener(); initSpinners(); } private void initSpinners() { Resources res = getResources(); mSpinnerDelta = (Spinner)findViewById(R.id.timer_delta); mSpinnerSize = (Spinner)findViewById(R.id.timer_size); mSpinnerRepeat = (Spinner)findViewById(R.id.timer_repeat); mValueDelta = res.getIntArray(R.array.delta_value); mValueSize = res.getIntArray(R.array.size_value); mValueRepeat = res.getIntArray(R.array.repeat_value); initSpinner(R.array.delta_text, mSpinnerDelta); initSpinner(R.array.size_text, mSpinnerSize); initSpinner(R.array.repeat_text, mSpinnerRepeat); mSpinnerDelta.setSelection(2); // supposed to select 1000ms mSpinnerSize.setSelection(19); // supposed to select 20bytes mSpinnerRepeat.setSelection(0); // supposed to select Unlimited } private void initSpinner(int textArrayId, Spinner spinner) { ArrayAdapter<CharSequence> adapter; adapter = ArrayAdapter.createFromResource( this, textArrayId, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); } @Override protected void onResume() { super.onResume(); //GattProxy proxy = GattProxy.get(this); //proxy.addListener(mListener); //proxy.retrieveGatt(mListener); } @Override protected void onPause() { super.onPause(); //GattProxy proxy = GattProxy.get(this); //proxy.rmListener(mListener); } private void addTab(TabHost host, String tag, CharSequence text, int viewResource) { View indicator = getLayoutInflater().inflate(R.layout.tab_indicator, null); TextView tv = (TextView)indicator.findViewById(R.id.indicator_text); tv.setText(text); TabHost.TabSpec spec = host.newTabSpec(tag); spec.setIndicator(indicator); spec.setContent(viewResource); host.addTab(spec); } public void onClickSend(View v) { CharSequence cs = mInput.getText(); send(cs); } public void onClickStartTimer(View v) { showDialog(TIMER_DIALOG); startTimer(); } public void onClickChoose(View v) { /* you should install a file chooser beforehand. */ Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("text/plain"); startActivityForResult(intent, CHOOSE_FILE); } public void onClickToggle(View v) { onSetType(mToggle.isChecked()); } private void onSetType(boolean withResponse) { Log.d("set write with response:" + withResponse); } @Override protected void onActivityResult(int request, int result, Intent data) { if (request == CHOOSE_FILE) { if (result == Activity.RESULT_OK) { Uri uri = data.getData(); String filePath = uri.getPath(); Log.d("chosen file:" + filePath); try { send(Util.readStrFromFile(filePath)); } catch (IOException e) { e.printStackTrace(); Log.d("IO Exception"); } } } } private void send(CharSequence cs) { Log.d("send:" + cs.toString()); mMsg.append("send:"); mMsg.append(cs); mMsg.append("\n"); write(cs); } private void write(CharSequence cs) { byte[] bytes = cs.toString().getBytes(); ByteBuffer buf = ByteBuffer.allocate(bytes.length); while(buf.remaining() != 0) { int size = (buf.remaining() > PAYLOAD_MAX) ? PAYLOAD_MAX: buf.remaining(); byte[] dst = new byte[size]; buf.get(dst, 0, size); //mQueue.add(mTransRx, dst); //mQueue.consume(); } } @Override public void onTransact(BluetoothGattCharacteristic chr, byte[] value) { chr.setValue(value); int type = mToggle.isChecked() ? BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT: BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE; chr.setWriteType(type); mGatt.writeCharacteristic(chr); } @Override protected Dialog onCreateDialog(int id, Bundle args) { /*FIXME: this function is deprecated. */ if (id == CONNECTION_DIALOG) { mConnectionDialog = new ProgressDialog(this); mConnectionDialog.setMessage(this.getString(R.string.connecting)); mConnectionDialog.setCancelable(true); return mConnectionDialog; } else if (id == TIMER_DIALOG) { mTimerDialog = new ProgressDialog(this); mTimerDialog.setMessage("Timer is running"); mTimerDialog.setOnCancelListener(new Dialog.OnCancelListener() { public void onCancel(DialogInterface dialog) { Log.d("some one canceled me"); stopTimer(); } }); return mTimerDialog; } return null; } private void onTimerSend(int count, int size) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < size; i++) { sb.append("" + count); } Log.d(sb.toString()); write(sb); } private boolean mRunning; private void startTimer() { final int delta = mValueDelta[mSpinnerDelta.getSelectedItemPosition()]; final int size = mValueSize[mSpinnerSize.getSelectedItemPosition()]; final int repeat = mValueRepeat[mSpinnerRepeat.getSelectedItemPosition()]; mRunning = true; Thread runner = new Thread() { public void run() { int counter = 0; try { while(mRunning) { if (repeat != 0 && repeat == counter) { stopTimer(); } else { onTimerSend(counter, size); sleep(delta); counter++; } } } catch (Exception e) { e.printStackTrace(); } updateView(DISMISS_TIMER_DIALOG, null); } }; runner.start(); } private void stopTimer() { mRunning = false; } public void updateView(int tag, Bundle info) { if (info == null) { info = new Bundle(); } mViewHandler.removeMessages(tag); Message msg = mViewHandler.obtainMessage(tag); msg.what = tag; msg.setData(info); mViewHandler.sendMessage(msg); } class ViewHandler extends Handler { public void handleMessage(Message msg) { Bundle bundle = msg.getData(); if (bundle == null) { Log.d("ViewHandler handled a message without information"); return; } int tag = msg.what; if (tag == SHOW_CONNECTION_DIALOG) { showDialog(CONNECTION_DIALOG); } else if (tag == DISMISS_CONNECTION_DIALOG) { if (mConnectionDialog != null && mConnectionDialog.isShowing()) { dismissDialog(CONNECTION_DIALOG); } } else if (tag == DISMISS_TIMER_DIALOG) { if (mTimerDialog != null && mTimerDialog.isShowing()) { dismissDialog(TIMER_DIALOG); } } else if (tag == CONSUME_TRANSACTION) { mQueue.consume(); } } } private void onConnected() { List<BluetoothGattService> list = mGatt.getServices(mDevice); if ((list == null) || (list.size() == 0)) { Log.d("no services, do discovery"); mGatt.discoverServices(mDevice); } else { onDiscovered(); } } private void onDiscovered() { updateView(DISMISS_CONNECTION_DIALOG, null); BluetoothGattService proprietary = mGatt.getService(mDevice, Bluebit.SERVICE_ISSC_PROPRIETARY); mTransTx = proprietary.getCharacteristic(Bluebit.CHR_ISSC_TRANS_TX); mTransRx = proprietary.getCharacteristic(Bluebit.CHR_ISSC_TRANS_RX); Log.d(String.format("found Tx:%b, Rx:%b", mTransTx != null, mTransRx != null)); } class GattListener extends GattProxy.ListenerHelper { GattListener() { super("ActivityTransparent"); } @Override public void onRetrievedGatt(BluetoothGatt gatt) { Log.d(String.format("onRetrievedGatt")); mGatt = gatt; int conn = mGatt.getConnectionState(mDevice); if (conn == BluetoothProfile.STATE_DISCONNECTED) { Log.d("disconnected, connecting to device"); updateView(SHOW_CONNECTION_DIALOG, null); mGatt.connect(mDevice, true); } else { Log.d("already connected"); onConnected(); } } @Override public void onServicesDiscovered(BluetoothDevice device, int status) { onDiscovered(); } @Override public void onCharacteristicRead(BluetoothGattCharacteristic charac, int status) { Log.d("read char, uuid=" + charac.getUuid().toString()); byte[] value = charac.getValue(); Log.d("get value, byte length:" + value.length); for (int i = 0; i < value.length; i++) { Log.d("[" + i + "]" + Byte.toString(value[i])); } } @Override public void onCharacteristicWrite(BluetoothGattCharacteristic charac, int status) { mQueue.consumedOne(); updateView(CONSUME_TRANSACTION, null); } } }
Revert "disable function since we are working on UI" This reverts commit d5430c9ab6f4a15f3a5a8cf0285b06633cf747e9. UI adjustment finished.
src/com/issc/ui/ActivityTransparent.java
Revert "disable function since we are working on UI"
Java
apache-2.0
396079aa8c9ac79e0e439b1b179b033db227fb5d
0
HubSpot/Baragon,HubSpot/Baragon,HubSpot/Baragon
package com.hubspot.baragon.service; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.atomic.AtomicLong; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.leader.LeaderLatch; import org.apache.curator.retry.ExponentialBackoffRetry; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.regions.Regions; import com.amazonaws.services.elasticloadbalancing.AmazonElasticLoadBalancingClient; import com.google.common.base.Optional; import com.google.common.base.Strings; import com.google.inject.Binder; import com.google.inject.Injector; import com.google.inject.Provides; import com.google.inject.Scopes; import com.google.inject.Singleton; import com.google.inject.multibindings.Multibinder; import com.google.inject.name.Named; import com.hubspot.baragon.BaragonDataModule; import com.hubspot.baragon.config.AuthConfiguration; import com.hubspot.baragon.config.HttpClientConfiguration; import com.hubspot.baragon.config.ZooKeeperConfiguration; import com.hubspot.baragon.data.BaragonConnectionStateListener; import com.hubspot.baragon.data.BaragonWorkerDatastore; import com.hubspot.baragon.service.config.BaragonConfiguration; import com.hubspot.baragon.service.config.EdgeCacheConfiguration; import com.hubspot.baragon.service.config.ElbConfiguration; import com.hubspot.baragon.service.config.SentryConfiguration; import com.hubspot.baragon.service.elb.ApplicationLoadBalancer; import com.hubspot.baragon.service.elb.ClassicLoadBalancer; import com.hubspot.baragon.service.exceptions.BaragonExceptionNotifier; import com.hubspot.baragon.service.healthcheck.ZooKeeperHealthcheck; import com.hubspot.baragon.service.listeners.AbstractLatchListener; import com.hubspot.baragon.service.listeners.ElbSyncWorkerListener; import com.hubspot.baragon.service.listeners.RequestPurgingListener; import com.hubspot.baragon.service.listeners.RequestWorkerListener; import com.hubspot.baragon.service.managed.BaragonExceptionNotifierManaged; import com.hubspot.baragon.service.managed.BaragonGraphiteReporterManaged; import com.hubspot.baragon.service.managed.BaragonManaged; import com.hubspot.baragon.service.managers.AgentManager; import com.hubspot.baragon.service.managers.ElbManager; import com.hubspot.baragon.service.managers.RequestManager; import com.hubspot.baragon.service.managers.ServiceManager; import com.hubspot.baragon.service.managers.StatusManager; import com.hubspot.baragon.service.resources.BaragonResourcesModule; import com.hubspot.baragon.service.worker.BaragonElbSyncWorker; import com.hubspot.baragon.service.worker.BaragonRequestWorker; import com.hubspot.baragon.service.worker.RequestPurgingWorker; import com.hubspot.baragon.utils.JavaUtils; import com.hubspot.dropwizard.guicier.DropwizardAwareModule; import com.ning.http.client.AsyncHttpClient; import com.ning.http.client.AsyncHttpClientConfig; import io.dropwizard.jetty.HttpConnectorFactory; import io.dropwizard.server.SimpleServerFactory; public class BaragonServiceModule extends DropwizardAwareModule<BaragonConfiguration> { public static final String BARAGON_SERVICE_SCHEDULED_EXECUTOR = "baragon.service.scheduledExecutor"; public static final String BARAGON_SERVICE_HTTP_PORT = "baragon.service.http.port"; public static final String BARAGON_SERVICE_HOSTNAME = "baragon.service.hostname"; public static final String BARAGON_SERVICE_LOCAL_HOSTNAME = "baragon.service.local.hostname"; public static final String BARAGON_SERVICE_HTTP_CLIENT = "baragon.service.http.client"; public static final String BARAGON_MASTER_AUTH_KEY = "baragon.master.auth.key"; public static final String BARAGON_URI_BASE = "baragon.uri.base"; public static final String BARAGON_AWS_ELB_CLIENT_V1 = "baragon.aws.elb.client.v1"; public static final String BARAGON_AWS_ELB_CLIENT_V2 = "baragon.aws.elb.client.v2"; @Override public void configure(Binder binder) { binder.requireExplicitBindings(); binder.requireExactBindingAnnotations(); binder.requireAtInjectOnConstructors(); binder.install(new BaragonDataModule()); binder.install(new BaragonResourcesModule()); // Healthcheck binder.bind(ZooKeeperHealthcheck.class).in(Scopes.SINGLETON); binder.bind(BaragonExceptionNotifier.class).in(Scopes.SINGLETON); // Managed binder.bind(BaragonExceptionNotifierManaged.class).in(Scopes.SINGLETON); binder.bind(BaragonGraphiteReporterManaged.class).in(Scopes.SINGLETON); binder.bind(BaragonManaged.class).in(Scopes.SINGLETON); // Managers binder.bind(AgentManager.class).in(Scopes.SINGLETON); binder.bind(ElbManager.class).in(Scopes.SINGLETON); binder.bind(RequestManager.class).in(Scopes.SINGLETON); binder.bind(ServiceManager.class).in(Scopes.SINGLETON); binder.bind(StatusManager.class).in(Scopes.SINGLETON); // Workers binder.bind(BaragonElbSyncWorker.class).in(Scopes.SINGLETON); binder.bind(BaragonRequestWorker.class).in(Scopes.SINGLETON); binder.bind(RequestPurgingWorker.class).in(Scopes.SINGLETON); binder.bind(ClassicLoadBalancer.class); binder.bind(ApplicationLoadBalancer.class); Multibinder<AbstractLatchListener> latchBinder = Multibinder.newSetBinder(binder, AbstractLatchListener.class); latchBinder.addBinding().to(RequestWorkerListener.class).in(Scopes.SINGLETON); latchBinder.addBinding().to(ElbSyncWorkerListener.class).in(Scopes.SINGLETON); latchBinder.addBinding().to(RequestPurgingListener.class).in(Scopes.SINGLETON); } @Provides public ZooKeeperConfiguration provideZooKeeperConfiguration(BaragonConfiguration configuration) { return configuration.getZooKeeperConfiguration(); } @Provides public HttpClientConfiguration provideHttpClientConfiguration(BaragonConfiguration configuration) { return configuration.getHttpClientConfiguration(); } @Provides @Named(BaragonDataModule.BARAGON_AGENT_REQUEST_URI_FORMAT) public String provideAgentUriFormat(BaragonConfiguration configuration) { return configuration.getAgentRequestUriFormat(); } @Provides @Named(BaragonDataModule.BARAGON_AGENT_BATCH_REQUEST_URI_FORMAT) public String provideAgentBatchUriFormat(BaragonConfiguration configuration) { return configuration.getAgentBatchRequestUriFormat(); } @Provides @Named(BaragonDataModule.BARAGON_AGENT_MAX_ATTEMPTS) public Integer provideAgentMaxAttempts(BaragonConfiguration configuration) { return configuration.getAgentMaxAttempts(); } @Provides @Named(BaragonDataModule.BARAGON_AGENT_REQUEST_TIMEOUT_MS) public Long provideAgentMaxRequestTime(BaragonConfiguration configuration) { return configuration.getAgentRequestTimeoutMs(); } @Provides public AuthConfiguration providesAuthConfiguration(BaragonConfiguration configuration) { return configuration.getAuthConfiguration(); } @Provides public Optional<ElbConfiguration> providesElbConfiguration(BaragonConfiguration configuration) { return configuration.getElbConfiguration(); } @Provides public Optional<EdgeCacheConfiguration> providesEdgeCacheConfiguration(BaragonConfiguration configuration) { return configuration.getEdgeCacheConfiguration(); } @Provides @Singleton @Named(BARAGON_SERVICE_SCHEDULED_EXECUTOR) public ScheduledExecutorService providesScheduledExecutor() { return Executors.newScheduledThreadPool(4); } @Provides @Singleton @Named(BaragonDataModule.BARAGON_SERVICE_WORKER_LAST_START) public AtomicLong providesWorkerLastStartAt() { return new AtomicLong(); } @Provides @Singleton @Named(BaragonDataModule.BARAGON_ELB_WORKER_LAST_START) public AtomicLong providesElbWorkerLastStartAt() { return new AtomicLong(); } @Provides @Singleton @Named(BARAGON_SERVICE_HTTP_PORT) public int providesHttpPortProperty(BaragonConfiguration config) { SimpleServerFactory simpleServerFactory = (SimpleServerFactory) config.getServerFactory(); HttpConnectorFactory httpFactory = (HttpConnectorFactory) simpleServerFactory.getConnector(); return httpFactory.getPort(); } @Provides @Named(BARAGON_SERVICE_HOSTNAME) public String providesHostnameProperty(BaragonConfiguration config) throws Exception { return Strings.isNullOrEmpty(config.getHostname()) ? JavaUtils.getHostAddress() : config.getHostname(); } @Provides @Named(BARAGON_SERVICE_LOCAL_HOSTNAME) public String providesLocalHostnameProperty(BaragonConfiguration config) { if (!Strings.isNullOrEmpty(config.getHostname())) { return config.getHostname(); } try { final InetAddress addr = InetAddress.getLocalHost(); return addr.getHostName(); } catch (UnknownHostException e) { throw new RuntimeException("No local hostname found, unable to start without functioning local networking (or configured hostname)", e); } } @Provides @Singleton @Named(BaragonDataModule.BARAGON_SERVICE_LEADER_LATCH) public LeaderLatch providesServiceLeaderLatch(BaragonConfiguration config, BaragonWorkerDatastore datastore, @Named(BARAGON_SERVICE_HTTP_PORT) int httpPort, @Named(BARAGON_SERVICE_HOSTNAME) String hostname) { final String appRoot = ((SimpleServerFactory)config.getServerFactory()).getApplicationContextPath(); final String baseUri = String.format("http://%s:%s%s", hostname, httpPort, appRoot); return datastore.createLeaderLatch(baseUri); } @Provides @Named(BARAGON_MASTER_AUTH_KEY) public String providesMasterAuthKey(BaragonConfiguration configuration) { return configuration.getMasterAuthKey(); } @Provides @Named(BARAGON_URI_BASE) String getBaragonUriBase(final BaragonConfiguration configuration) { final String baragonUiPrefix = configuration.getUiConfiguration().getBaseUrl().or(((SimpleServerFactory) configuration.getServerFactory()).getApplicationContextPath()); return (baragonUiPrefix.endsWith("/")) ? baragonUiPrefix.substring(0, baragonUiPrefix.length() - 1) : baragonUiPrefix; } @Provides @Singleton @Named(BARAGON_SERVICE_HTTP_CLIENT) public AsyncHttpClient providesHttpClient(HttpClientConfiguration config) { AsyncHttpClientConfig.Builder builder = new AsyncHttpClientConfig.Builder(); builder.setMaxRequestRetry(config.getMaxRequestRetry()); builder.setRequestTimeoutInMs(config.getRequestTimeoutInMs()); builder.setFollowRedirects(true); builder.setConnectionTimeoutInMs(config.getConnectionTimeoutInMs()); builder.setUserAgent(config.getUserAgent()); return new AsyncHttpClient(builder.build()); } @Provides @Named(BARAGON_AWS_ELB_CLIENT_V1) public AmazonElasticLoadBalancingClient providesAwsElbClientV1(Optional<ElbConfiguration> configuration) { AmazonElasticLoadBalancingClient elbClient; if (configuration.isPresent() && configuration.get().getAwsAccessKeyId() != null && configuration.get().getAwsAccessKeySecret() != null) { elbClient = new AmazonElasticLoadBalancingClient(new BasicAWSCredentials(configuration.get().getAwsAccessKeyId(), configuration.get().getAwsAccessKeySecret())); } else { elbClient = new AmazonElasticLoadBalancingClient(); } if (configuration.isPresent() && configuration.get().getAwsEndpoint().isPresent()) { elbClient.setEndpoint(configuration.get().getAwsEndpoint().get()); } if (configuration.isPresent() && configuration.get().getAwsRegion().isPresent()) { elbClient.configureRegion(Regions.fromName(configuration.get().getAwsRegion().get())); } return elbClient; } @Provides @Named(BARAGON_AWS_ELB_CLIENT_V2) public com.amazonaws.services.elasticloadbalancingv2.AmazonElasticLoadBalancingClient providesAwsElbClientV2(Optional<ElbConfiguration> configuration) { com.amazonaws.services.elasticloadbalancingv2.AmazonElasticLoadBalancingClient elbClient; if (configuration.isPresent() && configuration.get().getAwsAccessKeyId() != null && configuration.get().getAwsAccessKeySecret() != null) { elbClient = new com.amazonaws.services.elasticloadbalancingv2.AmazonElasticLoadBalancingClient(new BasicAWSCredentials(configuration.get().getAwsAccessKeyId(), configuration.get().getAwsAccessKeySecret())); } else { elbClient = new com.amazonaws.services.elasticloadbalancingv2.AmazonElasticLoadBalancingClient(); } if (configuration.isPresent() && configuration.get().getAwsEndpoint().isPresent()) { elbClient.setEndpoint(configuration.get().getAwsEndpoint().get()); } if (configuration.isPresent() && configuration.get().getAwsRegion().isPresent()) { elbClient.configureRegion(Regions.fromName(configuration.get().getAwsRegion().get())); } return elbClient; } @Singleton @Provides public CuratorFramework provideCurator(ZooKeeperConfiguration config, BaragonConnectionStateListener connectionStateListener) { CuratorFramework client = CuratorFrameworkFactory.builder() .connectString(config.getQuorum()) .sessionTimeoutMs(config.getSessionTimeoutMillis()) .connectionTimeoutMs(config.getConnectTimeoutMillis()) .retryPolicy(new ExponentialBackoffRetry(config.getRetryBaseSleepTimeMilliseconds(), config.getRetryMaxTries())) .defaultData(new byte[0]) .build(); client.getConnectionStateListenable().addListener(connectionStateListener); client.start(); return client.usingNamespace(config.getZkNamespace()); } @Provides @Singleton public Optional<SentryConfiguration> sentryConfiguration(final BaragonConfiguration config) { return config.getSentryConfiguration(); } }
BaragonService/src/main/java/com/hubspot/baragon/service/BaragonServiceModule.java
package com.hubspot.baragon.service; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.atomic.AtomicLong; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.leader.LeaderLatch; import org.apache.curator.retry.ExponentialBackoffRetry; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.regions.Regions; import com.amazonaws.services.elasticloadbalancing.AmazonElasticLoadBalancingClient; import com.google.common.base.Optional; import com.google.common.base.Strings; import com.google.inject.Binder; import com.google.inject.Provides; import com.google.inject.Scopes; import com.google.inject.Singleton; import com.google.inject.multibindings.Multibinder; import com.google.inject.name.Named; import com.hubspot.baragon.BaragonDataModule; import com.hubspot.baragon.config.AuthConfiguration; import com.hubspot.baragon.config.HttpClientConfiguration; import com.hubspot.baragon.config.ZooKeeperConfiguration; import com.hubspot.baragon.data.BaragonConnectionStateListener; import com.hubspot.baragon.data.BaragonWorkerDatastore; import com.hubspot.baragon.service.config.BaragonConfiguration; import com.hubspot.baragon.service.config.ElbConfiguration; import com.hubspot.baragon.service.config.SentryConfiguration; import com.hubspot.baragon.service.elb.ApplicationLoadBalancer; import com.hubspot.baragon.service.elb.ClassicLoadBalancer; import com.hubspot.baragon.service.exceptions.BaragonExceptionNotifier; import com.hubspot.baragon.service.healthcheck.ZooKeeperHealthcheck; import com.hubspot.baragon.service.listeners.AbstractLatchListener; import com.hubspot.baragon.service.listeners.ElbSyncWorkerListener; import com.hubspot.baragon.service.listeners.RequestPurgingListener; import com.hubspot.baragon.service.listeners.RequestWorkerListener; import com.hubspot.baragon.service.managed.BaragonExceptionNotifierManaged; import com.hubspot.baragon.service.managed.BaragonGraphiteReporterManaged; import com.hubspot.baragon.service.managed.BaragonManaged; import com.hubspot.baragon.service.managers.AgentManager; import com.hubspot.baragon.service.managers.ElbManager; import com.hubspot.baragon.service.managers.RequestManager; import com.hubspot.baragon.service.managers.ServiceManager; import com.hubspot.baragon.service.managers.StatusManager; import com.hubspot.baragon.service.resources.BaragonResourcesModule; import com.hubspot.baragon.service.worker.BaragonElbSyncWorker; import com.hubspot.baragon.service.worker.BaragonRequestWorker; import com.hubspot.baragon.service.worker.RequestPurgingWorker; import com.hubspot.baragon.utils.JavaUtils; import com.hubspot.dropwizard.guicier.DropwizardAwareModule; import com.ning.http.client.AsyncHttpClient; import com.ning.http.client.AsyncHttpClientConfig; import io.dropwizard.jetty.HttpConnectorFactory; import io.dropwizard.server.SimpleServerFactory; public class BaragonServiceModule extends DropwizardAwareModule<BaragonConfiguration> { public static final String BARAGON_SERVICE_SCHEDULED_EXECUTOR = "baragon.service.scheduledExecutor"; public static final String BARAGON_SERVICE_HTTP_PORT = "baragon.service.http.port"; public static final String BARAGON_SERVICE_HOSTNAME = "baragon.service.hostname"; public static final String BARAGON_SERVICE_LOCAL_HOSTNAME = "baragon.service.local.hostname"; public static final String BARAGON_SERVICE_HTTP_CLIENT = "baragon.service.http.client"; public static final String BARAGON_MASTER_AUTH_KEY = "baragon.master.auth.key"; public static final String BARAGON_URI_BASE = "baragon.uri.base"; public static final String BARAGON_AWS_ELB_CLIENT_V1 = "baragon.aws.elb.client.v1"; public static final String BARAGON_AWS_ELB_CLIENT_V2 = "baragon.aws.elb.client.v2"; @Override public void configure(Binder binder) { binder.requireExplicitBindings(); binder.requireExactBindingAnnotations(); binder.requireAtInjectOnConstructors(); binder.install(new BaragonDataModule()); binder.install(new BaragonResourcesModule()); // Healthcheck binder.bind(ZooKeeperHealthcheck.class).in(Scopes.SINGLETON); binder.bind(BaragonExceptionNotifier.class).in(Scopes.SINGLETON); // Managed binder.bind(BaragonExceptionNotifierManaged.class).in(Scopes.SINGLETON); binder.bind(BaragonGraphiteReporterManaged.class).in(Scopes.SINGLETON); binder.bind(BaragonManaged.class).in(Scopes.SINGLETON); // Managers binder.bind(AgentManager.class).in(Scopes.SINGLETON); binder.bind(ElbManager.class).in(Scopes.SINGLETON); binder.bind(RequestManager.class).in(Scopes.SINGLETON); binder.bind(ServiceManager.class).in(Scopes.SINGLETON); binder.bind(StatusManager.class).in(Scopes.SINGLETON); // Workers binder.bind(BaragonElbSyncWorker.class).in(Scopes.SINGLETON); binder.bind(BaragonRequestWorker.class).in(Scopes.SINGLETON); binder.bind(RequestPurgingWorker.class).in(Scopes.SINGLETON); binder.bind(ClassicLoadBalancer.class); binder.bind(ApplicationLoadBalancer.class); Multibinder<AbstractLatchListener> latchBinder = Multibinder.newSetBinder(binder, AbstractLatchListener.class); latchBinder.addBinding().to(RequestWorkerListener.class).in(Scopes.SINGLETON); latchBinder.addBinding().to(ElbSyncWorkerListener.class).in(Scopes.SINGLETON); latchBinder.addBinding().to(RequestPurgingListener.class).in(Scopes.SINGLETON); } @Provides public ZooKeeperConfiguration provideZooKeeperConfiguration(BaragonConfiguration configuration) { return configuration.getZooKeeperConfiguration(); } @Provides public HttpClientConfiguration provideHttpClientConfiguration(BaragonConfiguration configuration) { return configuration.getHttpClientConfiguration(); } @Provides @Named(BaragonDataModule.BARAGON_AGENT_REQUEST_URI_FORMAT) public String provideAgentUriFormat(BaragonConfiguration configuration) { return configuration.getAgentRequestUriFormat(); } @Provides @Named(BaragonDataModule.BARAGON_AGENT_BATCH_REQUEST_URI_FORMAT) public String provideAgentBatchUriFormat(BaragonConfiguration configuration) { return configuration.getAgentBatchRequestUriFormat(); } @Provides @Named(BaragonDataModule.BARAGON_AGENT_MAX_ATTEMPTS) public Integer provideAgentMaxAttempts(BaragonConfiguration configuration) { return configuration.getAgentMaxAttempts(); } @Provides @Named(BaragonDataModule.BARAGON_AGENT_REQUEST_TIMEOUT_MS) public Long provideAgentMaxRequestTime(BaragonConfiguration configuration) { return configuration.getAgentRequestTimeoutMs(); } @Provides public AuthConfiguration providesAuthConfiguration(BaragonConfiguration configuration) { return configuration.getAuthConfiguration(); } @Provides public Optional<ElbConfiguration> providesElbConfiguration(BaragonConfiguration configuration) { return configuration.getElbConfiguration(); } @Provides @Singleton @Named(BARAGON_SERVICE_SCHEDULED_EXECUTOR) public ScheduledExecutorService providesScheduledExecutor() { return Executors.newScheduledThreadPool(4); } @Provides @Singleton @Named(BaragonDataModule.BARAGON_SERVICE_WORKER_LAST_START) public AtomicLong providesWorkerLastStartAt() { return new AtomicLong(); } @Provides @Singleton @Named(BaragonDataModule.BARAGON_ELB_WORKER_LAST_START) public AtomicLong providesElbWorkerLastStartAt() { return new AtomicLong(); } @Provides @Singleton @Named(BARAGON_SERVICE_HTTP_PORT) public int providesHttpPortProperty(BaragonConfiguration config) { SimpleServerFactory simpleServerFactory = (SimpleServerFactory) config.getServerFactory(); HttpConnectorFactory httpFactory = (HttpConnectorFactory) simpleServerFactory.getConnector(); return httpFactory.getPort(); } @Provides @Named(BARAGON_SERVICE_HOSTNAME) public String providesHostnameProperty(BaragonConfiguration config) throws Exception { return Strings.isNullOrEmpty(config.getHostname()) ? JavaUtils.getHostAddress() : config.getHostname(); } @Provides @Named(BARAGON_SERVICE_LOCAL_HOSTNAME) public String providesLocalHostnameProperty(BaragonConfiguration config) { if (!Strings.isNullOrEmpty(config.getHostname())) { return config.getHostname(); } try { final InetAddress addr = InetAddress.getLocalHost(); return addr.getHostName(); } catch (UnknownHostException e) { throw new RuntimeException("No local hostname found, unable to start without functioning local networking (or configured hostname)", e); } } @Provides @Singleton @Named(BaragonDataModule.BARAGON_SERVICE_LEADER_LATCH) public LeaderLatch providesServiceLeaderLatch(BaragonConfiguration config, BaragonWorkerDatastore datastore, @Named(BARAGON_SERVICE_HTTP_PORT) int httpPort, @Named(BARAGON_SERVICE_HOSTNAME) String hostname) { final String appRoot = ((SimpleServerFactory)config.getServerFactory()).getApplicationContextPath(); final String baseUri = String.format("http://%s:%s%s", hostname, httpPort, appRoot); return datastore.createLeaderLatch(baseUri); } @Provides @Named(BARAGON_MASTER_AUTH_KEY) public String providesMasterAuthKey(BaragonConfiguration configuration) { return configuration.getMasterAuthKey(); } @Provides @Named(BARAGON_URI_BASE) String getBaragonUriBase(final BaragonConfiguration configuration) { final String baragonUiPrefix = configuration.getUiConfiguration().getBaseUrl().or(((SimpleServerFactory) configuration.getServerFactory()).getApplicationContextPath()); return (baragonUiPrefix.endsWith("/")) ? baragonUiPrefix.substring(0, baragonUiPrefix.length() - 1) : baragonUiPrefix; } @Provides @Singleton @Named(BARAGON_SERVICE_HTTP_CLIENT) public AsyncHttpClient providesHttpClient(HttpClientConfiguration config) { AsyncHttpClientConfig.Builder builder = new AsyncHttpClientConfig.Builder(); builder.setMaxRequestRetry(config.getMaxRequestRetry()); builder.setRequestTimeoutInMs(config.getRequestTimeoutInMs()); builder.setFollowRedirects(true); builder.setConnectionTimeoutInMs(config.getConnectionTimeoutInMs()); builder.setUserAgent(config.getUserAgent()); return new AsyncHttpClient(builder.build()); } @Provides @Named(BARAGON_AWS_ELB_CLIENT_V1) public AmazonElasticLoadBalancingClient providesAwsElbClientV1(Optional<ElbConfiguration> configuration) { AmazonElasticLoadBalancingClient elbClient; if (configuration.isPresent() && configuration.get().getAwsAccessKeyId() != null && configuration.get().getAwsAccessKeySecret() != null) { elbClient = new AmazonElasticLoadBalancingClient(new BasicAWSCredentials(configuration.get().getAwsAccessKeyId(), configuration.get().getAwsAccessKeySecret())); } else { elbClient = new AmazonElasticLoadBalancingClient(); } if (configuration.isPresent() && configuration.get().getAwsEndpoint().isPresent()) { elbClient.setEndpoint(configuration.get().getAwsEndpoint().get()); } if (configuration.isPresent() && configuration.get().getAwsRegion().isPresent()) { elbClient.configureRegion(Regions.fromName(configuration.get().getAwsRegion().get())); } return elbClient; } @Provides @Named(BARAGON_AWS_ELB_CLIENT_V2) public com.amazonaws.services.elasticloadbalancingv2.AmazonElasticLoadBalancingClient providesAwsElbClientV2(Optional<ElbConfiguration> configuration) { com.amazonaws.services.elasticloadbalancingv2.AmazonElasticLoadBalancingClient elbClient; if (configuration.isPresent() && configuration.get().getAwsAccessKeyId() != null && configuration.get().getAwsAccessKeySecret() != null) { elbClient = new com.amazonaws.services.elasticloadbalancingv2.AmazonElasticLoadBalancingClient(new BasicAWSCredentials(configuration.get().getAwsAccessKeyId(), configuration.get().getAwsAccessKeySecret())); } else { elbClient = new com.amazonaws.services.elasticloadbalancingv2.AmazonElasticLoadBalancingClient(); } if (configuration.isPresent() && configuration.get().getAwsEndpoint().isPresent()) { elbClient.setEndpoint(configuration.get().getAwsEndpoint().get()); } if (configuration.isPresent() && configuration.get().getAwsRegion().isPresent()) { elbClient.configureRegion(Regions.fromName(configuration.get().getAwsRegion().get())); } return elbClient; } @Singleton @Provides public CuratorFramework provideCurator(ZooKeeperConfiguration config, BaragonConnectionStateListener connectionStateListener) { CuratorFramework client = CuratorFrameworkFactory.builder() .connectString(config.getQuorum()) .sessionTimeoutMs(config.getSessionTimeoutMillis()) .connectionTimeoutMs(config.getConnectTimeoutMillis()) .retryPolicy(new ExponentialBackoffRetry(config.getRetryBaseSleepTimeMilliseconds(), config.getRetryMaxTries())) .defaultData(new byte[0]) .build(); client.getConnectionStateListenable().addListener(connectionStateListener); client.start(); return client.usingNamespace(config.getZkNamespace()); } @Provides @Singleton public Optional<SentryConfiguration> sentryConfiguration(final BaragonConfiguration config) { return config.getSentryConfiguration(); } }
Wire up EdgeCacheConfiguration into Guice.
BaragonService/src/main/java/com/hubspot/baragon/service/BaragonServiceModule.java
Wire up EdgeCacheConfiguration into Guice.
Java
apache-2.0
aadd4c3df39fef974f0ee0239ca9b8214daf9073
0
Ensembl/ensj-healthcheck,Ensembl/ensj-healthcheck,thomasmaurel/ensj-healthcheck,Ensembl/ensj-healthcheck,thomasmaurel/ensj-healthcheck,Ensembl/ensj-healthcheck,thomasmaurel/ensj-healthcheck,thomasmaurel/ensj-healthcheck
/* * Copyright (C) 2004 EBI, GRL * * This library is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free Software * Foundation; either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with * this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, * Suite 330, Boston, MA 02111-1307 USA */ package org.ensembl.healthcheck.testcase.variation; import java.sql.Connection; import org.ensembl.healthcheck.Team; import org.ensembl.healthcheck.DatabaseRegistryEntry; //import org.ensembl.healthcheck.DatabaseType; import org.ensembl.healthcheck.ReportManager; import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase; // This HC seems a bit useless with Graham's new consequence pipeline. I'll disable it for now and we'll have to discuss what // we want checked before enabling it again. /** * Check that if the peptide_allele_string of transcript_variation is not >1. * It should out >1, unless it filled with numbers */ public class TranscriptVariation extends SingleDatabaseTestCase { /** * Creates a new instance of Check Transcript Variation */ public TranscriptVariation() { //addToGroup("variation"); //addToGroup("variation-release"); setDescription("Check that if the peptide_allele_string of transcript_variation is not >1. It should out >1, unless it filled with numbers"); setTeamResponsible(Team.VARIATION); } /** * Find any matching databases that have peptide_allele_string column. * @param dbre * The database to use. * @return Result. */ public boolean run(DatabaseRegistryEntry dbre) { boolean result = true; // check peptide_allele_string not filled with numbers Connection con = dbre.getConnection(); int rows = getRowCount(con, "SELECT COUNT(*) FROM transcript_variation WHERE pep_allele_string >1"); if (rows >=1) { result = false; ReportManager.problem(this, con, rows + " with peptide_allele_string >1"); } else { // ReportManager.info(this, con, "No transcript_variation have peptide_allele_string >1); } int rows1 = getRowCount(con, "SELECT COUNT(*) FROM transcript_variation WHERE consequence_types=''"); if (rows1 >=1) { result = false; ReportManager.problem(this, con, rows1 + " with consequence_types a empty string"); } else { // ReportManager.info(this, con, "No transcript_variation have consequence_type a empty string"); } int rows2 = getRowCount(con, "SELECT COUNT(*) FROM variation_feature vf WHERE NOT FIND_IN_SET('intergenic_variant',vf.consequence_type) AND NOT EXISTS (SELECT * FROM transcript_variation tv WHERE tv.variation_feature_id = vf.variation_feature_id)"); if (rows2 >=1) { result = false; ReportManager.problem(this, con, rows2 + " with consequence_type != 'intergenic_variant' and there is no corresponding transcript exists in transcript_variation table"); } if (result){ ReportManager.correct(this,con,"transcript_variation have peptide_allele_string >1, indicating column shift, peptide_allele_string become a number or consequence_type a empty string or consequence_type is not a intergenic_variant where there is no transcript exists"); } return result; } // run } // TranscriptVariation
src/org/ensembl/healthcheck/testcase/variation/TranscriptVariation.java
/* * Copyright (C) 2004 EBI, GRL * * This library is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free Software * Foundation; either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with * this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, * Suite 330, Boston, MA 02111-1307 USA */ package org.ensembl.healthcheck.testcase.variation; import java.sql.Connection; import org.ensembl.healthcheck.DatabaseRegistryEntry; //import org.ensembl.healthcheck.DatabaseType; import org.ensembl.healthcheck.ReportManager; import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase; /** * Check that if the peptide_allele_string of transcript_variation is not >1. * It should out >1, unless it filled with numbers */ public class TranscriptVariation extends SingleDatabaseTestCase { /** * Creates a new instance of Check Transcript Variation */ public TranscriptVariation() { addToGroup("variation"); addToGroup("variation-release"); setDescription("Check that if the peptide_allele_string of transcript_variation is not >1. It should out >1, unless it filled with numbers"); } /** * Find any matching databases that have peptide_allele_string column. * @param dbre * The database to use. * @return Result. */ public boolean run(DatabaseRegistryEntry dbre) { boolean result = true; // check peptide_allele_string not filled with numbers Connection con = dbre.getConnection(); int rows = getRowCount(con, "SELECT COUNT(*) FROM transcript_variation WHERE pep_allele_string >1"); if (rows >=1) { result = false; ReportManager.problem(this, con, rows + " with peptide_allele_string >1"); } else { // ReportManager.info(this, con, "No transcript_variation have peptide_allele_string >1); } int rows1 = getRowCount(con, "SELECT COUNT(*) FROM transcript_variation WHERE consequence_types=''"); if (rows1 >=1) { result = false; ReportManager.problem(this, con, rows1 + " with consequence_types a empty string"); } else { // ReportManager.info(this, con, "No transcript_variation have consequence_type a empty string"); } int rows2 = getRowCount(con, "SELECT COUNT(*) FROM variation_feature vf WHERE NOT FIND_IN_SET('intergenic_variant',vf.consequence_type) AND NOT EXISTS (SELECT * FROM transcript_variation tv WHERE tv.variation_feature_id = vf.variation_feature_id)"); if (rows2 >=1) { result = false; ReportManager.problem(this, con, rows2 + " with consequence_type != 'intergenic_variant' and there is no corresponding transcript exists in transcript_variation table"); } if (result){ ReportManager.correct(this,con,"transcript_variation have peptide_allele_string >1, indicating column shift, peptide_allele_string become a number or consequence_type a empty string or consequence_type is not a intergenic_variant where there is no transcript exists"); } return result; } // run } // TranscriptVariation
Disabled until we specify what we should check
src/org/ensembl/healthcheck/testcase/variation/TranscriptVariation.java
Disabled until we specify what we should check
Java
apache-2.0
91ece6703c0d97f0a70a6f8e7d48ea55efa85118
0
jdgwartney/boundary-aws-sqs
/* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.boundary.aws.sqs; import java.util.Date; import java.util.List; import java.util.Map.Entry; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.regions.Region; import com.amazonaws.regions.Regions; import com.amazonaws.services.sqs.AmazonSQS; import com.amazonaws.services.sqs.AmazonSQSClient; import com.amazonaws.services.sqs.model.CreateQueueRequest; import com.amazonaws.services.sqs.model.DeleteMessageRequest; import com.amazonaws.services.sqs.model.DeleteQueueRequest; import com.amazonaws.services.sqs.model.Message; import com.amazonaws.services.sqs.model.ReceiveMessageRequest; import com.amazonaws.services.sqs.model.SendMessageRequest; /** * This sample demonstrates how to make basic requests to Amazon SQS using the * AWS SDK for Java. * <p> * <b>Prerequisites:</b> You must have a valid Amazon Web Services developer * account, and be signed up to use Amazon SQS. For more information on Amazon * SQS, see http://aws.amazon.com/sqs. * <p> * WANRNING:</b> To avoid accidental leakage of your credentials, DO NOT keep * the credentials file in your source directory. */ public class Sample { public static void main(String[] args) throws Exception { String queueName = "boundary-sqs-demo-queue"; /* * The ProfileCredentialsProvider will return your [default] credential * profile by reading from the credentials file located at * (HOME/.aws/credentials). */ AWSCredentials credentials = null; try { credentials = new ProfileCredentialsProvider("default") .getCredentials(); } catch (Exception e) { throw new AmazonClientException("Cannot load the credentials from the credential profiles file. ",e); } AmazonSQS sqs = new AmazonSQSClient(credentials); Region usWest2 = Region.getRegion(Regions.US_WEST_2); sqs.setRegion(usWest2); try { // Create a queue System.out.printf("Creating queue: %s.\n",queueName); CreateQueueRequest createQueueRequest = new CreateQueueRequest(queueName); String myQueueUrl = sqs.createQueue(createQueueRequest).getQueueUrl(); int messageCount = 100; // Send a messages for (int count = 1; count <= messageCount ; count++) { System.out.printf("Sending message %3d to %s.\n",count, queueName); sqs.sendMessage(new SendMessageRequest(myQueueUrl, new Date() + ": This is my message text.")); } for (int count = 1; count <= messageCount ; count++) { ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl); List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages(); for (Message msg : messages) { System.out.printf("Received message: %s queue: %s body: %s\n", msg.getMessageId(),queueName,msg.getBody()); System.out.printf("Deleting message: %s queue: %s\n",msg.getMessageId(), queueName); String messageRecieptHandle = msg.getReceiptHandle(); sqs.deleteMessage(new DeleteMessageRequest(myQueueUrl,messageRecieptHandle)); } } System.out.printf("Deleting queue: %s\n",queueName); sqs.deleteQueue(new DeleteQueueRequest(myQueueUrl)); } catch (AmazonServiceException ase) { System.out .println("Caught an AmazonServiceException, which means your request made it " + "to Amazon SQS, but was rejected with an error response for some reason."); System.out.println("Error Message: " + ase.getMessage()); System.out.println("HTTP Status Code: " + ase.getStatusCode()); System.out.println("AWS Error Code: " + ase.getErrorCode()); System.out.println("Error Type: " + ase.getErrorType()); System.out.println("Request ID: " + ase.getRequestId()); } catch (AmazonClientException ace) { System.out .println("Caught an AmazonClientException, which means the client encountered " + "a serious internal problem while trying to communicate with SQS, such as not " + "being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } sqs.shutdown(); } }
src/main/java/com/boundary/aws/sqs/Sample.java
/* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.boundary.aws.sqs; import java.util.Date; import java.util.List; import java.util.Map.Entry; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.regions.Region; import com.amazonaws.regions.Regions; import com.amazonaws.services.sqs.AmazonSQS; import com.amazonaws.services.sqs.AmazonSQSClient; import com.amazonaws.services.sqs.model.CreateQueueRequest; import com.amazonaws.services.sqs.model.DeleteMessageRequest; import com.amazonaws.services.sqs.model.DeleteQueueRequest; import com.amazonaws.services.sqs.model.Message; import com.amazonaws.services.sqs.model.ReceiveMessageRequest; import com.amazonaws.services.sqs.model.SendMessageRequest; /** * This sample demonstrates how to make basic requests to Amazon SQS using the * AWS SDK for Java. * <p> * <b>Prerequisites:</b> You must have a valid Amazon Web Services developer * account, and be signed up to use Amazon SQS. For more information on Amazon * SQS, see http://aws.amazon.com/sqs. * <p> * WANRNING:</b> To avoid accidental leakage of your credentials, DO NOT keep * the credentials file in your source directory. */ public class Sample { public static void main(String[] args) throws Exception { String queueName = "boundary-sqs-demo-queue"; /* * The ProfileCredentialsProvider will return your [default] credential * profile by reading from the credentials file located at * (HOME/.aws/credentials). */ AWSCredentials credentials = null; try { credentials = new ProfileCredentialsProvider("default") .getCredentials(); } catch (Exception e) { throw new AmazonClientException("Cannot load the credentials from the credential profiles file. ",e); } AmazonSQS sqs = new AmazonSQSClient(credentials); Region usWest2 = Region.getRegion(Regions.US_WEST_2); sqs.setRegion(usWest2); try { // Create a queue System.out.printf("Creating a new SQS queue called %s.\n",queueName); CreateQueueRequest createQueueRequest = new CreateQueueRequest(queueName); String myQueueUrl = sqs.createQueue(createQueueRequest).getQueueUrl(); // List queues System.out.println("Listing all queues in your account.\n"); for (String queueUrl : sqs.listQueues().getQueueUrls()) { System.out.println(" QueueUrl: " + queueUrl); } System.out.println(); int messageCount = 10; // Send a message for (int count = 1; count <= messageCount ; count++) { System.out.printf("Sending message %3d to %s.\n",count, queueName); sqs.sendMessage(new SendMessageRequest(myQueueUrl, new Date() + ": This is my message text.")); sqs.sendMessage(new SendMessageRequest(myQueueUrl, "test")); } System.out.printf("Receiving messages from %s.\n", queueName); for (int count = 1; count <= messageCount ; count++) { ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl); List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages(); for (Message msgReceived : messages) { System.out.println(" Message"); System.out.println(" MessageId: " + msgReceived.getMessageId()); System.out.println(" ReceiptHandle: " + msgReceived.getReceiptHandle()); System.out.println(" MD5OfBody: " + msgReceived.getMD5OfBody()); System.out.println(" Body: " + msgReceived.getBody()); for (Entry<String, String> entry : msgReceived.getAttributes().entrySet()) { System.out.println(" Attribute"); System.out.println(" Name: " + entry.getKey()); System.out.println(" Value: " + entry.getValue()); } } } System.out.println(); for (int count = 1; count <= messageCount ; count++) { ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl); List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages(); for (Message msgDelete : messages) { System.out.printf("Deleting a message %s from %s.\n",msgDelete.getMessageId(), queueName); String messageRecieptHandle = msgDelete.getReceiptHandle(); sqs.deleteMessage(new DeleteMessageRequest(myQueueUrl,messageRecieptHandle)); } } System.out.printf("Deleting %s queue.\n",queueName); sqs.deleteQueue(new DeleteQueueRequest(myQueueUrl)); } catch (AmazonServiceException ase) { System.out .println("Caught an AmazonServiceException, which means your request made it " + "to Amazon SQS, but was rejected with an error response for some reason."); System.out.println("Error Message: " + ase.getMessage()); System.out.println("HTTP Status Code: " + ase.getStatusCode()); System.out.println("AWS Error Code: " + ase.getErrorCode()); System.out.println("Error Type: " + ase.getErrorType()); System.out.println("Request ID: " + ase.getRequestId()); } catch (AmazonClientException ace) { System.out .println("Caught an AmazonClientException, which means the client encountered " + "a serious internal problem while trying to communicate with SQS, such as not " + "being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } Thread.sleep(61000); } }
Simplify output ; remove unwanted api calls
src/main/java/com/boundary/aws/sqs/Sample.java
Simplify output ; remove unwanted api calls
Java
apache-2.0
c12518e51fa4a232826eca5ca46ad9a6aed4d600
0
procandi/jitsi,dkcreinoso/jitsi,iant-gmbh/jitsi,bebo/jitsi,ibauersachs/jitsi,jibaro/jitsi,martin7890/jitsi,jibaro/jitsi,martin7890/jitsi,ibauersachs/jitsi,level7systems/jitsi,HelioGuilherme66/jitsi,ibauersachs/jitsi,level7systems/jitsi,gpolitis/jitsi,bhatvv/jitsi,ibauersachs/jitsi,iant-gmbh/jitsi,marclaporte/jitsi,HelioGuilherme66/jitsi,pplatek/jitsi,gpolitis/jitsi,procandi/jitsi,marclaporte/jitsi,bhatvv/jitsi,gpolitis/jitsi,cobratbq/jitsi,459below/jitsi,ringdna/jitsi,damencho/jitsi,laborautonomo/jitsi,mckayclarey/jitsi,459below/jitsi,jitsi/jitsi,pplatek/jitsi,martin7890/jitsi,laborautonomo/jitsi,pplatek/jitsi,bhatvv/jitsi,459below/jitsi,bebo/jitsi,HelioGuilherme66/jitsi,jibaro/jitsi,jibaro/jitsi,laborautonomo/jitsi,damencho/jitsi,martin7890/jitsi,iant-gmbh/jitsi,459below/jitsi,459below/jitsi,ibauersachs/jitsi,bhatvv/jitsi,level7systems/jitsi,dkcreinoso/jitsi,laborautonomo/jitsi,gpolitis/jitsi,bebo/jitsi,jitsi/jitsi,HelioGuilherme66/jitsi,procandi/jitsi,mckayclarey/jitsi,cobratbq/jitsi,tuijldert/jitsi,marclaporte/jitsi,ringdna/jitsi,procandi/jitsi,bebo/jitsi,marclaporte/jitsi,mckayclarey/jitsi,gpolitis/jitsi,ringdna/jitsi,damencho/jitsi,jitsi/jitsi,damencho/jitsi,dkcreinoso/jitsi,tuijldert/jitsi,HelioGuilherme66/jitsi,cobratbq/jitsi,tuijldert/jitsi,bebo/jitsi,mckayclarey/jitsi,procandi/jitsi,laborautonomo/jitsi,tuijldert/jitsi,jitsi/jitsi,bhatvv/jitsi,iant-gmbh/jitsi,damencho/jitsi,dkcreinoso/jitsi,martin7890/jitsi,tuijldert/jitsi,jibaro/jitsi,dkcreinoso/jitsi,cobratbq/jitsi,level7systems/jitsi,cobratbq/jitsi,jitsi/jitsi,ringdna/jitsi,pplatek/jitsi,iant-gmbh/jitsi,ringdna/jitsi,pplatek/jitsi,mckayclarey/jitsi,level7systems/jitsi,marclaporte/jitsi
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.plugin.reconnectplugin; import java.util.*; import net.java.sip.communicator.service.gui.*; import net.java.sip.communicator.service.netaddr.*; import net.java.sip.communicator.service.netaddr.event.*; import net.java.sip.communicator.service.notification.*; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.service.protocol.event.*; import net.java.sip.communicator.util.*; import org.jitsi.service.configuration.*; import org.jitsi.service.resources.*; import org.osgi.framework.*; /** * Activates the reconnect plug-in. * * @author Damian Minkov */ public class ReconnectPluginActivator implements BundleActivator, ServiceListener, NetworkConfigurationChangeListener, RegistrationStateChangeListener { /** * Logger of this class */ private static final Logger logger = Logger.getLogger(ReconnectPluginActivator.class); /** * The current BundleContext. */ private static BundleContext bundleContext = null; /** * The ui service. */ private static UIService uiService; /** * The resources service. */ private static ResourceManagementService resourcesService; /** * A reference to the ConfigurationService implementation instance that * is currently registered with the bundle context. */ private static ConfigurationService configurationService = null; /** * Notification service. */ private static NotificationService notificationService; /** * Network address manager service will inform us for changes in * network configuration. */ private NetworkAddressManagerService networkAddressManagerService = null; /** * Holds every protocol provider which is can be reconnected and * a list of the available and up interfaces when the provider was * registered. When a provider is unregistered it is removed * from this collection. * Providers REMOVED: * - When provider is removed from osgi * - When a provider is UNREGISTERED * Providers ADDED: * - When a provider is REGISTERED */ private final Map<ProtocolProviderService, List<String>> autoReconnEnabledProviders = new HashMap<ProtocolProviderService, List<String>>(); /** * Holds the currently reconnecting providers and their reconnect tasks. * When they get connected they are removed from this collection. * Providers REMOVED: * - When provider removed from osgi. * - When interface is UP, we remove providers and schedule reconnect * for them * - When interface is DOWN, we remove all providers and schedule reconnect * - When last interface is DOWN, we remove all providers and * unregister them * - On connection failed with no interface connected * - Provider is Registered * - Provider is Unregistered and is missing in unregistered providers list * - After provider is unregistered just before reconnecting, and there * are no connected interfaces * Providers ADDED: * - Before unregister (in new thread) when scheduling a reconnect task * - After provider is unregistered just before reconnecting */ private final Map<ProtocolProviderService, ReconnectTask> currentlyReconnecting = new HashMap<ProtocolProviderService, ReconnectTask>(); /** * If network is down we save here the providers which need * to be reconnected. * Providers REMOVED: * - When provider removed from osgi. * - Remove all providers when interface is up and we will reconnect them * Providers ADDED: * - Interface is down, and there are still active interfaces, add all * auto reconnect enabled and all currently reconnecting * - Provider in connection failed and there are no connected interfaces * - Provider is unregistered or connection failed and there are no * connected interfaces. */ private Set<ProtocolProviderService> needsReconnection = new HashSet<ProtocolProviderService>(); /** * A list of providers on which we have called unregister. This is a * way to differ our unregister calls from calls coming from user, wanting * to stop all reconnects. * Providers REMOVED: * - Provider is Connection failed. * - Provider is registered/unregistered * Providers ADDED: * - Provider is about to be unregistered */ private Set<ProtocolProviderService> unregisteringProviders = new HashSet<ProtocolProviderService>(); /** * A list of currently connected interfaces. If empty network is down. */ private Set<String> connectedInterfaces = new HashSet<String>(); /** * Timer for scheduling all reconnect operations. */ private Timer timer = null; /** * Start of the delay interval when starting a reconnect. */ private static final int RECONNECT_DELAY_MIN = 2; // sec /** * The end of the interval for the initial reconnect. */ private static final int RECONNECT_DELAY_MAX = 4; // sec /** * Max value for growing the reconnect delay, all subsequent reconnects * use this maximum delay. */ private static final int MAX_RECONNECT_DELAY = 300; // sec /** * Network notifications event type. */ public static final String NETWORK_NOTIFICATIONS = "NetworkNotifications"; /** * */ public static final String ATLEAST_ONE_CONNECTION_PROP = "net.java.sip.communicator.plugin.reconnectplugin." + "ATLEAST_ONE_SUCCESSFUL_CONNECTION"; /** * Timer used to filter out too frequent "network down" notifications * on Android. */ private Timer delayedNetworkDown; /** * Delay used for filtering out "network down" notifications. */ private static final long NETWORK_DOWN_THRESHOLD = 30 * 1000; /** * Starts this bundle. * * @param bundleContext the <tt>BundleContext</tt> in which this bundle is * to be started * @throws Exception if anything goes wrong while starting this bundle */ public void start(BundleContext bundleContext) throws Exception { try { logger.logEntry(); ReconnectPluginActivator.bundleContext = bundleContext; } finally { logger.logExit(); } bundleContext.addServiceListener(this); if(timer == null) timer = new Timer("Reconnect timer", true); this.networkAddressManagerService = ServiceUtils.getService( bundleContext, NetworkAddressManagerService.class); this.networkAddressManagerService .addNetworkConfigurationChangeListener(this); ServiceReference[] protocolProviderRefs = null; try { protocolProviderRefs = bundleContext.getServiceReferences( ProtocolProviderService.class.getName(), null); } catch (InvalidSyntaxException ex) { // this shouldn't happen since we're providing no parameter string // but let's log just in case. logger.error( "Error while retrieving service refs", ex); return; } // in case we found any if (protocolProviderRefs != null) { if (logger.isDebugEnabled()) logger.debug("Found " + protocolProviderRefs.length + " already installed providers."); for (int i = 0; i < protocolProviderRefs.length; i++) { ProtocolProviderService provider = (ProtocolProviderService) bundleContext .getService(protocolProviderRefs[i]); this.handleProviderAdded(provider); } } } /** * Stops this bundle. * * @param bundleContext the <tt>BundleContext</tt> in which this bundle is * to be stopped * @throws Exception if anything goes wrong while stopping this bundle */ public void stop(BundleContext bundleContext) throws Exception { if(timer != null) { timer.cancel(); timer = null; } } /** * Returns the <tt>UIService</tt> obtained from the bundle context. * * @return the <tt>UIService</tt> obtained from the bundle context */ public static UIService getUIService() { if (uiService == null) { ServiceReference uiReference = bundleContext.getServiceReference(UIService.class.getName()); uiService = (UIService) bundleContext .getService(uiReference); } return uiService; } /** * Returns resource service. * @return the resource service. */ public static ResourceManagementService getResources() { if (resourcesService == null) { ServiceReference serviceReference = bundleContext .getServiceReference(ResourceManagementService.class.getName()); if(serviceReference == null) return null; resourcesService = (ResourceManagementService) bundleContext .getService(serviceReference); } return resourcesService; } /** * Returns a reference to a ConfigurationService implementation currently * registered in the bundle context or null if no such implementation was * found. * * @return a currently valid implementation of the ConfigurationService. */ public static ConfigurationService getConfigurationService() { if (configurationService == null) { ServiceReference confReference = bundleContext.getServiceReference( ConfigurationService.class.getName()); configurationService = (ConfigurationService) bundleContext .getService(confReference); } return configurationService; } /** * Returns the <tt>NotificationService</tt> obtained from the bundle context. * * @return the <tt>NotificationService</tt> obtained from the bundle context */ public static NotificationService getNotificationService() { if (notificationService == null) { ServiceReference serviceReference = bundleContext .getServiceReference(NotificationService.class.getName()); notificationService = (NotificationService) bundleContext .getService(serviceReference); notificationService.registerDefaultNotificationForEvent( NETWORK_NOTIFICATIONS, NotificationAction.ACTION_POPUP_MESSAGE, null, null); } return notificationService; } /** * When new protocol provider is registered we add needed listeners. * * @param serviceEvent ServiceEvent */ public void serviceChanged(ServiceEvent serviceEvent) { ServiceReference serviceRef = serviceEvent.getServiceReference(); // if the event is caused by a bundle being stopped, we don't want to // know we are shutting down if (serviceRef.getBundle().getState() == Bundle.STOPPING) { return; } Object sService = bundleContext.getService(serviceRef); if(sService instanceof NetworkAddressManagerService) { switch (serviceEvent.getType()) { case ServiceEvent.REGISTERED: if(this.networkAddressManagerService != null) break; this.networkAddressManagerService = (NetworkAddressManagerService)sService; networkAddressManagerService .addNetworkConfigurationChangeListener(this); break; case ServiceEvent.UNREGISTERING: ((NetworkAddressManagerService)sService) .removeNetworkConfigurationChangeListener(this); break; } return; } // we don't care if the source service is not a protocol provider if (!(sService instanceof ProtocolProviderService)) return; switch (serviceEvent.getType()) { case ServiceEvent.REGISTERED: this.handleProviderAdded((ProtocolProviderService)sService); break; case ServiceEvent.UNREGISTERING: this.handleProviderRemoved( (ProtocolProviderService) sService); break; } } /** * Add listeners to newly registered protocols. * * @param provider ProtocolProviderService */ private void handleProviderAdded(ProtocolProviderService provider) { if (logger.isTraceEnabled()) logger.trace("New protocol provider is comming " + provider.getProtocolName()); provider.addRegistrationStateChangeListener(this); } /** * Stop listening for events as the provider is removed. * Providers are removed this way only when there are modified * in the configuration. So as the provider is modified we will erase * every instance we got. * * @param provider the ProtocolProviderService that has been unregistered. */ private void handleProviderRemoved(ProtocolProviderService provider) { if (logger.isTraceEnabled()) logger.trace("Provider modified forget every instance of it"); if(hasAtLeastOneSuccessfulConnection(provider)) { setAtLeastOneSuccessfulConnection(provider, false); } provider.removeRegistrationStateChangeListener(this); autoReconnEnabledProviders.remove(provider); needsReconnection.remove(provider); if(currentlyReconnecting.containsKey(provider)) { currentlyReconnecting.remove(provider).cancel(); } } /** * Fired when a change has occurred in the computer network configuration. * * @param event the change event. */ public synchronized void configurationChanged(ChangeEvent event) { if(event.getType() == ChangeEvent.IFACE_UP) { // no connection so one is up, lets connect if(connectedInterfaces.isEmpty()) { onNetworkUp(); Iterator<ProtocolProviderService> iter = needsReconnection.iterator(); while (iter.hasNext()) { ProtocolProviderService pp = iter.next(); if(currentlyReconnecting.containsKey(pp)) { // now lets cancel it and schedule it again // so it will use this iface currentlyReconnecting.remove(pp).cancel(); } reconnect(pp); } needsReconnection.clear(); } connectedInterfaces.add((String)event.getSource()); } else if(event.getType() == ChangeEvent.IFACE_DOWN) { String ifaceName = (String)event.getSource(); connectedInterfaces.remove(ifaceName); // one is down and at least one more is connected if(connectedInterfaces.size() > 0) { // lets reconnect all that was connected when this one was // available, cause they maybe using it Iterator<Map.Entry<ProtocolProviderService, List<String>>> iter = autoReconnEnabledProviders.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<ProtocolProviderService, List<String>> entry = iter.next(); if(entry.getValue().contains(ifaceName)) { ProtocolProviderService pp = entry.getKey(); // hum someone is reconnecting, lets cancel and // schedule it again if(currentlyReconnecting.containsKey(pp)) { currentlyReconnecting.remove(pp).cancel(); } reconnect(pp); } } } else { // we must disconnect every pp and put all to be need of reconnecting needsReconnection.addAll(autoReconnEnabledProviders.keySet()); // there can by and some that are currently going to reconnect // must take care of them too, cause there is no net and they won't succeed needsReconnection.addAll(currentlyReconnecting.keySet()); Iterator<ProtocolProviderService> iter = needsReconnection.iterator(); while (iter.hasNext()) { ProtocolProviderService pp = iter.next(); // if provider is scheduled for reconnect, // cancel it there is no network if(currentlyReconnecting.containsKey(pp)) { currentlyReconnecting.remove(pp).cancel(); } // don't reconnect just unregister if needed. unregister(pp, false, null, null); } connectedInterfaces.clear(); onNetworkDown(); } } if(logger.isTraceEnabled()) { logger.trace("Event received " + event + " src=" + event.getSource()); traceCurrentPPState(); } } /** * Unregisters the ProtocolProvider. Make sure to do it in separate thread * so we don't block other processing. * @param pp the protocol provider to unregister. * @param reconnect if the protocol provider does not need unregistering * shall we trigger reconnect. Its true when call called from * reconnect. * @param listener the listener used in reconnect method. * @param task the task to use for reconnection. */ private void unregister(final ProtocolProviderService pp, final boolean reconnect, final RegistrationStateChangeListener listener, final ReconnectTask task) { unregisteringProviders.add(pp); new Thread(new Runnable() { public void run() { try { // getRegistrationState() for some protocols(icq) can trigger // registrationStateChanged so make checks here // to prevent synchronize in registrationStateChanged // and deadlock if(pp.getRegistrationState().equals( RegistrationState.UNREGISTERING) || pp.getRegistrationState().equals( RegistrationState.UNREGISTERED) || pp.getRegistrationState().equals( RegistrationState.CONNECTION_FAILED)) { if(reconnect) { if(listener != null) pp.removeRegistrationStateChangeListener( listener); if(timer == null || task == null) return; // cancel any existing task before overriding it if(currentlyReconnecting.containsKey(pp)) currentlyReconnecting.remove(pp).cancel(); currentlyReconnecting.put(pp, task); if (logger.isInfoEnabled()) logger.info("Reconnect " + pp.getAccountID().getDisplayName() + " after " + task.delay + " ms."); timer.schedule(task, task.delay); } return; } pp.unregister(); } catch(Throwable t) { logger.error("Error unregistering pp:" + pp, t); } } }).start(); } /** * Trace prints of current status of the lists with protocol providers, * that are currently in interest of the reconnect plugin. */ private void traceCurrentPPState() { logger.trace("connectedInterfaces: " + connectedInterfaces); logger.trace("autoReconnEnabledProviders: " + autoReconnEnabledProviders.keySet()); logger.trace("currentlyReconnecting: " + currentlyReconnecting.keySet()); logger.trace("needsReconnection: " + needsReconnection); logger.trace("unregisteringProviders: " + unregisteringProviders); logger.trace("----"); } /** * Sends network notification. * @param title the title. * @param i18nKey the resource key of the notification. * @param params and parameters in any. * @param tag extra notification tag object */ private void notify(String title, String i18nKey, String[] params, Object tag) { Map<String,Object> extras = new HashMap<String,Object>(); extras.put( NotificationData.POPUP_MESSAGE_HANDLER_TAG_EXTRA, tag); getNotificationService().fireNotification( NETWORK_NOTIFICATIONS, title, getResources().getI18NString(i18nKey, params), null, extras); } /** * The method is called by a <code>ProtocolProviderService</code> * implementation whenever a change in the registration state of the * corresponding provider had occurred. * * @param evt the event describing the status change. */ public void registrationStateChanged(RegistrationStateChangeEvent evt) { // we don't care about protocol providers that don't support // reconnection and we are interested only in few state changes if(!(evt.getSource() instanceof ProtocolProviderService) || !(evt.getNewState().equals(RegistrationState.REGISTERED) || evt.getNewState().equals(RegistrationState.UNREGISTERED) || evt.getNewState().equals(RegistrationState.CONNECTION_FAILED))) return; synchronized(this) { try { ProtocolProviderService pp = (ProtocolProviderService)evt.getSource(); if(evt.getNewState().equals(RegistrationState.CONNECTION_FAILED)) { if(!hasAtLeastOneSuccessfulConnection(pp)) { // ignore providers which haven't registered successfully // till now, they maybe misconfigured //String notifyMsg; if(evt.getReasonCode() == RegistrationStateChangeEvent.REASON_NON_EXISTING_USER_ID) { notify( getResources().getI18NString("service.gui.ERROR"), "service.gui.NON_EXISTING_USER_ID", new String[]{pp.getAccountID().getService()}, pp.getAccountID()); } else { notify( getResources().getI18NString("service.gui.ERROR"), "plugin.reconnectplugin.CONNECTION_FAILED_MSG", new String[] { pp.getAccountID().getUserID(), pp.getAccountID().getService() }, pp.getAccountID()); } return; } // if this pp is already in needsReconnection, it means // we got conn failed cause the pp has tried to unregister // with sending network packet // but this unregister is scheduled from us so skip if(needsReconnection.contains(pp)) return; if(connectedInterfaces.isEmpty()) { needsReconnection.add(pp); if(currentlyReconnecting.containsKey(pp)) currentlyReconnecting.remove(pp).cancel(); } else { // network is up but something happen and cannot reconnect // strange lets try again after some time reconnect(pp); } // unregister can finish and with connection failed, // the protocol is unable to unregister unregisteringProviders.remove(pp); if(logger.isTraceEnabled()) { logger.trace("Got Connection Failed for " + pp); traceCurrentPPState(); } } else if(evt.getNewState().equals(RegistrationState.REGISTERED)) { if(!hasAtLeastOneSuccessfulConnection(pp)) { setAtLeastOneSuccessfulConnection(pp, true); } autoReconnEnabledProviders.put( pp, new ArrayList<String>(connectedInterfaces)); if(currentlyReconnecting.containsKey(pp)) currentlyReconnecting.remove(pp).cancel(); unregisteringProviders.remove(pp); if(logger.isTraceEnabled()) { logger.trace("Got Registered for " + pp); traceCurrentPPState(); } } else if(evt.getNewState().equals(RegistrationState.UNREGISTERED)) { autoReconnEnabledProviders.remove(pp); if(!unregisteringProviders.contains(pp) && currentlyReconnecting.containsKey(pp)) { currentlyReconnecting.remove(pp).cancel(); } unregisteringProviders.remove(pp); if(logger.isTraceEnabled()) { logger.trace("Got Unregistered for " + pp); if(!currentlyReconnecting.containsKey(pp) && !needsReconnection.contains(pp) && logger.isTraceEnabled()) { // provider is not present in any collection // it will be no longer reconnected, maybe user request // to unregister lets trace check logger.trace( "Provider is unregistered and will not " + "be reconnected (maybe on user request): " + pp + " / reason:" + evt.getReason() + " / reasonCode:" + evt.getReasonCode() + " / oldState:" + evt.getOldState(), new Exception("Trace exception.")); } traceCurrentPPState(); } } } catch(Throwable ex) { logger.error("Error dispatching protocol registration change", ex); } } } /** * Method to schedule a reconnect for a protocol provider. * @param pp the provider. */ private void reconnect(final ProtocolProviderService pp) { long delay; if(currentlyReconnecting.containsKey(pp)) { delay = currentlyReconnecting.get(pp).delay; // we never stop trying //if(delay == MAX_RECONNECT_DELAY*1000) // return; delay = Math.min(delay * 2, MAX_RECONNECT_DELAY*1000); } else { delay = (long)(RECONNECT_DELAY_MIN + Math.random() * RECONNECT_DELAY_MAX)*1000; } final ReconnectTask task = new ReconnectTask(pp); task.delay = delay; // start registering after the pp has unregistered RegistrationStateChangeListener listener = new RegistrationStateChangeListener() { public void registrationStateChanged(RegistrationStateChangeEvent evt) { if(evt.getSource() instanceof ProtocolProviderService) { if(evt.getNewState().equals( RegistrationState.UNREGISTERED) || evt.getNewState().equals( RegistrationState.CONNECTION_FAILED)) { synchronized(this) { pp.removeRegistrationStateChangeListener(this); if(timer == null) return; if(connectedInterfaces.size() == 0) { // well there is no network we just need // this provider in needs reconnection when // there is one // means we started unregistering while // network was going down and meanwhile there // were no connected interface, this happens // when we have more than one connected // interface and we got 2 events for down iface needsReconnection.add(pp); if(currentlyReconnecting.containsKey(pp)) currentlyReconnecting.remove(pp).cancel(); return; } // cancel any existing task before overriding it if(currentlyReconnecting.containsKey(pp)) currentlyReconnecting.remove(pp).cancel(); currentlyReconnecting.put(pp, task); if (logger.isInfoEnabled()) logger.info("Reconnect " + pp.getAccountID().getDisplayName() + " after " + task.delay + " ms."); timer.schedule(task, task.delay); } } /* this unregister one way or another, and will end with unregister or connection failed if we remove listener when unregister come we will end up with unregistered provider without reconnect else if(evt.getNewState().equals( RegistrationState.REGISTERED)) { pp.removeRegistrationStateChangeListener(this); }*/ } } }; pp.addRegistrationStateChangeListener(listener); // as we will reconnect, lets unregister unregister(pp, true, listener, task); } /** * The task executed by the timer when time for reconnect comes. */ private class ReconnectTask extends TimerTask { /** * The provider to reconnect. */ private ProtocolProviderService provider; /** * The delay with which was this task scheduled. */ private long delay; /** * The thread to execute this task. */ private Thread thread = null; /** * Creates the task. * * @param provider the <tt>ProtocolProviderService</tt> to reconnect */ public ReconnectTask(ProtocolProviderService provider) { this.provider = provider; } /** * Reconnects the provider. */ @Override public void run() { if(thread == null || !Thread.currentThread().equals(thread)) { thread = new Thread(this); thread.start(); } else { try { if (logger.isInfoEnabled()) logger.info("Start reconnecting " + provider.getAccountID().getDisplayName()); provider.register( getUIService().getDefaultSecurityAuthority(provider)); } catch (OperationFailedException ex) { logger.error("cannot re-register provider will keep going", ex); } } } } /** * Check does the supplied protocol has the property set for at least * one successful connection. * @param pp the protocol provider * @return true if property exists. */ private boolean hasAtLeastOneSuccessfulConnection(ProtocolProviderService pp) { String value = (String)getConfigurationService().getProperty( ATLEAST_ONE_CONNECTION_PROP + "." + pp.getAccountID().getAccountUniqueID()); if(value == null || !value.equals(Boolean.TRUE.toString())) return false; else return true; } /** * Changes the property about at least one successful connection. * @param pp the protocol provider * @param value the new value true or false. */ private void setAtLeastOneSuccessfulConnection( ProtocolProviderService pp, boolean value) { getConfigurationService().setProperty( ATLEAST_ONE_CONNECTION_PROP + "." + pp.getAccountID().getAccountUniqueID(), Boolean.valueOf(value).toString()); } /** * Called when first connected interface is added to * {@link #connectedInterfaces} list. */ private void onNetworkUp() { if(delayedNetworkDown != null) { delayedNetworkDown.cancel(); delayedNetworkDown = null; } } /** * Called when first there are no more connected interface present in * {@link #connectedInterfaces} list. */ private void onNetworkDown() { if(!org.jitsi.util.OSUtils.IS_ANDROID) { notifyNetworkDown(); } else { // Android never keeps two active connection at the same time // and it may take some time to attach next connection // even if it was already enabled by user if(delayedNetworkDown == null) { delayedNetworkDown = new Timer(); delayedNetworkDown.schedule(new TimerTask() { @Override public void run() { notifyNetworkDown(); } }, NETWORK_DOWN_THRESHOLD); } } } /** * Posts "network is down" notification. */ private void notifyNetworkDown() { if (logger.isTraceEnabled()) logger.trace("Network is down!"); notify("", "plugin.reconnectplugin.NETWORK_DOWN", new String[0], this); } }
src/net/java/sip/communicator/plugin/reconnectplugin/ReconnectPluginActivator.java
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.plugin.reconnectplugin; import java.util.*; import net.java.sip.communicator.service.gui.*; import net.java.sip.communicator.service.netaddr.*; import net.java.sip.communicator.service.netaddr.event.*; import net.java.sip.communicator.service.notification.*; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.service.protocol.event.*; import net.java.sip.communicator.util.*; import org.jitsi.service.configuration.*; import org.jitsi.service.resources.*; import org.osgi.framework.*; /** * Activates the reconnect plug-in. * * @author Damian Minkov */ public class ReconnectPluginActivator implements BundleActivator, ServiceListener, NetworkConfigurationChangeListener, RegistrationStateChangeListener { /** * Logger of this class */ private static final Logger logger = Logger.getLogger(ReconnectPluginActivator.class); /** * The current BundleContext. */ private static BundleContext bundleContext = null; /** * The ui service. */ private static UIService uiService; /** * The resources service. */ private static ResourceManagementService resourcesService; /** * A reference to the ConfigurationService implementation instance that * is currently registered with the bundle context. */ private static ConfigurationService configurationService = null; /** * Notification service. */ private static NotificationService notificationService; /** * Network address manager service will inform us for changes in * network configuration. */ private NetworkAddressManagerService networkAddressManagerService = null; /** * Holds every protocol provider which is can be reconnected and * a list of the available and up interfaces when the provider was * registered. When a provider is unregistered it is removed * from this collection. * Providers REMOVED: * - When provider is removed from osgi * - When a provider is UNREGISTERED * Providers ADDED: * - When a provider is REGISTERED */ private final Map<ProtocolProviderService, List<String>> autoReconnEnabledProviders = new HashMap<ProtocolProviderService, List<String>>(); /** * Holds the currently reconnecting providers and their reconnect tasks. * When they get connected they are removed from this collection. * Providers REMOVED: * - When provider removed from osgi. * - When interface is UP, we remove providers and schedule reconnect * for them * - When interface is DOWN, we remove all providers and schedule reconnect * - When last interface is DOWN, we remove all providers and * unregister them * - On connection failed with no interface connected * - Provider is Registered * - Provider is Unregistered and is missing in unregistered providers list * - After provider is unregistered just before reconnecting, and there * are no connected interfaces * Providers ADDED: * - Before unregister (in new thread) when scheduling a reconnect task * - After provider is unregistered just before reconnecting */ private final Map<ProtocolProviderService, ReconnectTask> currentlyReconnecting = new HashMap<ProtocolProviderService, ReconnectTask>(); /** * If network is down we save here the providers which need * to be reconnected. * Providers REMOVED: * - When provider removed from osgi. * - Remove all providers when interface is up and we will reconnect them * Providers ADDED: * - Interface is down, and there are still active interfaces, add all * auto reconnect enabled and all currently reconnecting * - Provider in connection failed and there are no connected interfaces * - Provider is unregistered or connection failed and there are no * connected interfaces. */ private Set<ProtocolProviderService> needsReconnection = new HashSet<ProtocolProviderService>(); /** * A list of providers on which we have called unregister. This is a * way to differ our unregister calls from calls coming from user, wanting * to stop all reconnects. * Providers REMOVED: * - Provider is Connection failed. * - Provider is registered/unregistered * Providers ADDED: * - Provider is about to be unregistered */ private Set<ProtocolProviderService> unregisteringProviders = new HashSet<ProtocolProviderService>(); /** * A list of currently connected interfaces. If empty network is down. */ private Set<String> connectedInterfaces = new HashSet<String>(); /** * Timer for scheduling all reconnect operations. */ private Timer timer = null; /** * Start of the delay interval when starting a reconnect. */ private static final int RECONNECT_DELAY_MIN = 2; // sec /** * The end of the interval for the initial reconnect. */ private static final int RECONNECT_DELAY_MAX = 4; // sec /** * Max value for growing the reconnect delay, all subsequent reconnects * use this maximum delay. */ private static final int MAX_RECONNECT_DELAY = 300; // sec /** * Network notifications event type. */ public static final String NETWORK_NOTIFICATIONS = "NetworkNotifications"; /** * */ public static final String ATLEAST_ONE_CONNECTION_PROP = "net.java.sip.communicator.plugin.reconnectplugin." + "ATLEAST_ONE_SUCCESSFUL_CONNECTION"; /** * Timer used to filter out too frequent "network down" notifications * on Android. */ private Timer delayedNetworkDown; /** * Delay used for filtering out "network down" notifications. */ private static final long NETWORK_DOWN_THRESHOLD = 30 * 1000; /** * Starts this bundle. * * @param bundleContext the <tt>BundleContext</tt> in which this bundle is * to be started * @throws Exception if anything goes wrong while starting this bundle */ public void start(BundleContext bundleContext) throws Exception { try { logger.logEntry(); ReconnectPluginActivator.bundleContext = bundleContext; } finally { logger.logExit(); } bundleContext.addServiceListener(this); if(timer == null) timer = new Timer("Reconnect timer", true); this.networkAddressManagerService = ServiceUtils.getService( bundleContext, NetworkAddressManagerService.class); this.networkAddressManagerService .addNetworkConfigurationChangeListener(this); ServiceReference[] protocolProviderRefs = null; try { protocolProviderRefs = bundleContext.getServiceReferences( ProtocolProviderService.class.getName(), null); } catch (InvalidSyntaxException ex) { // this shouldn't happen since we're providing no parameter string // but let's log just in case. logger.error( "Error while retrieving service refs", ex); return; } // in case we found any if (protocolProviderRefs != null) { if (logger.isDebugEnabled()) logger.debug("Found " + protocolProviderRefs.length + " already installed providers."); for (int i = 0; i < protocolProviderRefs.length; i++) { ProtocolProviderService provider = (ProtocolProviderService) bundleContext .getService(protocolProviderRefs[i]); this.handleProviderAdded(provider); } } } /** * Stops this bundle. * * @param bundleContext the <tt>BundleContext</tt> in which this bundle is * to be stopped * @throws Exception if anything goes wrong while stopping this bundle */ public void stop(BundleContext bundleContext) throws Exception { if(timer != null) { timer.cancel(); timer = null; } } /** * Returns the <tt>UIService</tt> obtained from the bundle context. * * @return the <tt>UIService</tt> obtained from the bundle context */ public static UIService getUIService() { if (uiService == null) { ServiceReference uiReference = bundleContext.getServiceReference(UIService.class.getName()); uiService = (UIService) bundleContext .getService(uiReference); } return uiService; } /** * Returns resource service. * @return the resource service. */ public static ResourceManagementService getResources() { if (resourcesService == null) { ServiceReference serviceReference = bundleContext .getServiceReference(ResourceManagementService.class.getName()); if(serviceReference == null) return null; resourcesService = (ResourceManagementService) bundleContext .getService(serviceReference); } return resourcesService; } /** * Returns a reference to a ConfigurationService implementation currently * registered in the bundle context or null if no such implementation was * found. * * @return a currently valid implementation of the ConfigurationService. */ public static ConfigurationService getConfigurationService() { if (configurationService == null) { ServiceReference confReference = bundleContext.getServiceReference( ConfigurationService.class.getName()); configurationService = (ConfigurationService) bundleContext .getService(confReference); } return configurationService; } /** * Returns the <tt>NotificationService</tt> obtained from the bundle context. * * @return the <tt>NotificationService</tt> obtained from the bundle context */ public static NotificationService getNotificationService() { if (notificationService == null) { ServiceReference serviceReference = bundleContext .getServiceReference(NotificationService.class.getName()); notificationService = (NotificationService) bundleContext .getService(serviceReference); notificationService.registerDefaultNotificationForEvent( NETWORK_NOTIFICATIONS, NotificationAction.ACTION_POPUP_MESSAGE, null, null); } return notificationService; } /** * When new protocol provider is registered we add needed listeners. * * @param serviceEvent ServiceEvent */ public void serviceChanged(ServiceEvent serviceEvent) { ServiceReference serviceRef = serviceEvent.getServiceReference(); // if the event is caused by a bundle being stopped, we don't want to // know we are shutting down if (serviceRef.getBundle().getState() == Bundle.STOPPING) { return; } Object sService = bundleContext.getService(serviceRef); if(sService instanceof NetworkAddressManagerService) { switch (serviceEvent.getType()) { case ServiceEvent.REGISTERED: if(this.networkAddressManagerService != null) break; this.networkAddressManagerService = (NetworkAddressManagerService)sService; networkAddressManagerService .addNetworkConfigurationChangeListener(this); break; case ServiceEvent.UNREGISTERING: ((NetworkAddressManagerService)sService) .removeNetworkConfigurationChangeListener(this); break; } return; } // we don't care if the source service is not a protocol provider if (!(sService instanceof ProtocolProviderService)) return; switch (serviceEvent.getType()) { case ServiceEvent.REGISTERED: this.handleProviderAdded((ProtocolProviderService)sService); break; case ServiceEvent.UNREGISTERING: this.handleProviderRemoved( (ProtocolProviderService) sService); break; } } /** * Add listeners to newly registered protocols. * * @param provider ProtocolProviderService */ private void handleProviderAdded(ProtocolProviderService provider) { if (logger.isTraceEnabled()) logger.trace("New protocol provider is comming " + provider.getProtocolName()); provider.addRegistrationStateChangeListener(this); } /** * Stop listening for events as the provider is removed. * Providers are removed this way only when there are modified * in the configuration. So as the provider is modified we will erase * every instance we got. * * @param provider the ProtocolProviderService that has been unregistered. */ private void handleProviderRemoved(ProtocolProviderService provider) { if (logger.isTraceEnabled()) logger.trace("Provider modified forget every instance of it"); if(hasAtLeastOneSuccessfulConnection(provider)) { setAtLeastOneSuccessfulConnection(provider, false); } provider.removeRegistrationStateChangeListener(this); autoReconnEnabledProviders.remove(provider); needsReconnection.remove(provider); if(currentlyReconnecting.containsKey(provider)) { currentlyReconnecting.remove(provider).cancel(); } } /** * Fired when a change has occurred in the computer network configuration. * * @param event the change event. */ public synchronized void configurationChanged(ChangeEvent event) { if(event.getType() == ChangeEvent.IFACE_UP) { // no connection so one is up, lets connect if(connectedInterfaces.isEmpty()) { onNetworkUp(); Iterator<ProtocolProviderService> iter = needsReconnection.iterator(); while (iter.hasNext()) { ProtocolProviderService pp = iter.next(); if(currentlyReconnecting.containsKey(pp)) { // now lets cancel it and schedule it again // so it will use this iface currentlyReconnecting.remove(pp).cancel(); } reconnect(pp); } needsReconnection.clear(); } connectedInterfaces.add((String)event.getSource()); } else if(event.getType() == ChangeEvent.IFACE_DOWN) { String ifaceName = (String)event.getSource(); connectedInterfaces.remove(ifaceName); // one is down and at least one more is connected if(connectedInterfaces.size() > 0) { // lets reconnect all that was connected when this one was // available, cause they maybe using it Iterator<Map.Entry<ProtocolProviderService, List<String>>> iter = autoReconnEnabledProviders.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<ProtocolProviderService, List<String>> entry = iter.next(); if(entry.getValue().contains(ifaceName)) { ProtocolProviderService pp = entry.getKey(); // hum someone is reconnecting, lets cancel and // schedule it again if(currentlyReconnecting.containsKey(pp)) { currentlyReconnecting.remove(pp).cancel(); } reconnect(pp); } } } else { // we must disconnect every pp and put all to be need of reconnecting needsReconnection.addAll(autoReconnEnabledProviders.keySet()); // there can by and some that are currently going to reconnect // must take care of them too, cause there is no net and they won't succeed needsReconnection.addAll(currentlyReconnecting.keySet()); Iterator<ProtocolProviderService> iter = needsReconnection.iterator(); while (iter.hasNext()) { ProtocolProviderService pp = iter.next(); // if provider is scheduled for reconnect, // cancel it there is no network if(currentlyReconnecting.containsKey(pp)) { currentlyReconnecting.remove(pp).cancel(); } // don't reconnect just unregister if needed. unregister(pp, false, null, null); } connectedInterfaces.clear(); onNetworkDown(); } } if(logger.isTraceEnabled()) { logger.trace("Event received " + event + " src=" + event.getSource()); traceCurrentPPState(); } } /** * Unregisters the ProtocolProvider. Make sure to do it in separate thread * so we don't block other processing. * @param pp the protocol provider to unregister. * @param reconnect if the protocol provider does not need unregistering * shall we trigger reconnect. Its true when call called from * reconnect. * @param listener the listener used in reconnect method. * @param task the task to use for reconnection. */ private void unregister(final ProtocolProviderService pp, final boolean reconnect, final RegistrationStateChangeListener listener, final ReconnectTask task) { unregisteringProviders.add(pp); new Thread(new Runnable() { public void run() { try { // getRegistrationState() for some protocols(icq) can trigger // registrationStateChanged so make checks here // to prevent synchronize in registrationStateChanged // and deadlock if(pp.getRegistrationState().equals( RegistrationState.UNREGISTERING) || pp.getRegistrationState().equals( RegistrationState.UNREGISTERED) || pp.getRegistrationState().equals( RegistrationState.CONNECTION_FAILED)) { if(reconnect) { if(listener != null) pp.removeRegistrationStateChangeListener( listener); if(timer == null || task == null) return; // cancel any existing task before overriding it if(currentlyReconnecting.containsKey(pp)) currentlyReconnecting.remove(pp).cancel(); currentlyReconnecting.put(pp, task); if (logger.isInfoEnabled()) logger.info("Reconnect " + pp.getAccountID().getDisplayName() + " after " + task.delay + " ms."); timer.schedule(task, task.delay); } return; } pp.unregister(); } catch(Throwable t) { logger.error("Error unregistering pp:" + pp, t); } } }).start(); } /** * Trace prints of current status of the lists with protocol providers, * that are currently in interest of the reconnect plugin. */ private void traceCurrentPPState() { logger.trace("connectedInterfaces: " + connectedInterfaces); logger.trace("autoReconnEnabledProviders: " + autoReconnEnabledProviders.keySet()); logger.trace("currentlyReconnecting: " + currentlyReconnecting.keySet()); logger.trace("needsReconnection: " + needsReconnection); logger.trace("unregisteringProviders: " + unregisteringProviders); logger.trace("----"); } /** * Sends network notification. * @param title the title. * @param i18nKey the resource key of the notification. * @param params and parameters in any. * @param tag extra notification tag object */ private void notify(String title, String i18nKey, String[] params, Object tag) { Map<String,Object> extras = new HashMap<String,Object>(); extras.put( NotificationData.POPUP_MESSAGE_HANDLER_TAG_EXTRA, tag); getNotificationService().fireNotification( NETWORK_NOTIFICATIONS, title, getResources().getI18NString(i18nKey, params), null, extras); } /** * The method is called by a <code>ProtocolProviderService</code> * implementation whenever a change in the registration state of the * corresponding provider had occurred. * * @param evt the event describing the status change. */ public void registrationStateChanged(RegistrationStateChangeEvent evt) { // we don't care about protocol providers that don't support // reconnection and we are interested only in few state changes if(!(evt.getSource() instanceof ProtocolProviderService) || !(evt.getNewState().equals(RegistrationState.REGISTERED) || evt.getNewState().equals(RegistrationState.UNREGISTERED) || evt.getNewState().equals(RegistrationState.CONNECTION_FAILED))) return; synchronized(this) { try { ProtocolProviderService pp = (ProtocolProviderService)evt.getSource(); if(evt.getNewState().equals(RegistrationState.CONNECTION_FAILED)) { if(!hasAtLeastOneSuccessfulConnection(pp)) { // ignore providers which haven't registered successfully // till now, they maybe misconfigured //String notifyMsg; if(evt.getReasonCode() == RegistrationStateChangeEvent.REASON_NON_EXISTING_USER_ID) { notify( getResources().getI18NString("service.gui.ERROR"), "service.gui.NON_EXISTING_USER_ID", new String[]{pp.getAccountID().getService()}, pp.getAccountID()); } else { notify( getResources().getI18NString("service.gui.ERROR"), "plugin.reconnectplugin.CONNECTION_FAILED_MSG", new String[] { pp.getAccountID().getUserID(), pp.getAccountID().getService() }, pp.getAccountID()); } return; } // if this pp is already in needsReconnection, it means // we got conn failed cause the pp has tried to unregister // with sending network packet // but this unregister is scheduled from us so skip if(needsReconnection.contains(pp)) return; if(connectedInterfaces.isEmpty()) { needsReconnection.add(pp); if(currentlyReconnecting.containsKey(pp)) currentlyReconnecting.remove(pp).cancel(); } else { // network is up but something happen and cannot reconnect // strange lets try again after some time reconnect(pp); } // unregister can finish and with connection failed, // the protocol is unable to unregister unregisteringProviders.remove(pp); if(logger.isTraceEnabled()) { logger.trace("Got Connection Failed for " + pp); traceCurrentPPState(); } } else if(evt.getNewState().equals(RegistrationState.REGISTERED)) { if(!hasAtLeastOneSuccessfulConnection(pp)) { setAtLeastOneSuccessfulConnection(pp, true); } autoReconnEnabledProviders.put( pp, new ArrayList<String>(connectedInterfaces)); if(currentlyReconnecting.containsKey(pp)) currentlyReconnecting.remove(pp).cancel(); unregisteringProviders.remove(pp); if(logger.isTraceEnabled()) { logger.trace("Got Registered for " + pp); traceCurrentPPState(); } } else if(evt.getNewState().equals(RegistrationState.UNREGISTERED)) { autoReconnEnabledProviders.remove(pp); if(!unregisteringProviders.contains(pp) && currentlyReconnecting.containsKey(pp)) { currentlyReconnecting.remove(pp).cancel(); } unregisteringProviders.remove(pp); if(logger.isTraceEnabled()) { logger.trace("Got Unregistered for " + pp); traceCurrentPPState(); } } } catch(Throwable ex) { logger.error("Error dispatching protocol registration change", ex); } } } /** * Method to schedule a reconnect for a protocol provider. * @param pp the provider. */ private void reconnect(final ProtocolProviderService pp) { long delay; if(currentlyReconnecting.containsKey(pp)) { delay = currentlyReconnecting.get(pp).delay; // we never stop trying //if(delay == MAX_RECONNECT_DELAY*1000) // return; delay = Math.min(delay * 2, MAX_RECONNECT_DELAY*1000); } else { delay = (long)(RECONNECT_DELAY_MIN + Math.random() * RECONNECT_DELAY_MAX)*1000; } final ReconnectTask task = new ReconnectTask(pp); task.delay = delay; // start registering after the pp has unregistered RegistrationStateChangeListener listener = new RegistrationStateChangeListener() { public void registrationStateChanged(RegistrationStateChangeEvent evt) { if(evt.getSource() instanceof ProtocolProviderService) { if(evt.getNewState().equals( RegistrationState.UNREGISTERED) || evt.getNewState().equals( RegistrationState.CONNECTION_FAILED)) { synchronized(this) { pp.removeRegistrationStateChangeListener(this); if(timer == null) return; if(connectedInterfaces.size() == 0) { // well there is no network we just need // this provider in needs reconnection when // there is one // means we started unregistering while // network was going down and meanwhile there // were no connected interface, this happens // when we have more than one connected // interface and we got 2 events for down iface needsReconnection.add(pp); if(currentlyReconnecting.containsKey(pp)) currentlyReconnecting.remove(pp).cancel(); return; } // cancel any existing task before overriding it if(currentlyReconnecting.containsKey(pp)) currentlyReconnecting.remove(pp).cancel(); currentlyReconnecting.put(pp, task); if (logger.isInfoEnabled()) logger.info("Reconnect " + pp.getAccountID().getDisplayName() + " after " + task.delay + " ms."); timer.schedule(task, task.delay); } } /* this unregister one way or another, and will end with unregister or connection failed if we remove listener when unregister come we will end up with unregistered provider without reconnect else if(evt.getNewState().equals( RegistrationState.REGISTERED)) { pp.removeRegistrationStateChangeListener(this); }*/ } } }; pp.addRegistrationStateChangeListener(listener); // as we will reconnect, lets unregister unregister(pp, true, listener, task); } /** * The task executed by the timer when time for reconnect comes. */ private class ReconnectTask extends TimerTask { /** * The provider to reconnect. */ private ProtocolProviderService provider; /** * The delay with which was this task scheduled. */ private long delay; /** * The thread to execute this task. */ private Thread thread = null; /** * Creates the task. * * @param provider the <tt>ProtocolProviderService</tt> to reconnect */ public ReconnectTask(ProtocolProviderService provider) { this.provider = provider; } /** * Reconnects the provider. */ @Override public void run() { if(thread == null || !Thread.currentThread().equals(thread)) { thread = new Thread(this); thread.start(); } else { try { if (logger.isInfoEnabled()) logger.info("Start reconnecting " + provider.getAccountID().getDisplayName()); provider.register( getUIService().getDefaultSecurityAuthority(provider)); } catch (OperationFailedException ex) { logger.error("cannot re-register provider will keep going", ex); } } } } /** * Check does the supplied protocol has the property set for at least * one successful connection. * @param pp the protocol provider * @return true if property exists. */ private boolean hasAtLeastOneSuccessfulConnection(ProtocolProviderService pp) { String value = (String)getConfigurationService().getProperty( ATLEAST_ONE_CONNECTION_PROP + "." + pp.getAccountID().getAccountUniqueID()); if(value == null || !value.equals(Boolean.TRUE.toString())) return false; else return true; } /** * Changes the property about at least one successful connection. * @param pp the protocol provider * @param value the new value true or false. */ private void setAtLeastOneSuccessfulConnection( ProtocolProviderService pp, boolean value) { getConfigurationService().setProperty( ATLEAST_ONE_CONNECTION_PROP + "." + pp.getAccountID().getAccountUniqueID(), Boolean.valueOf(value).toString()); } /** * Called when first connected interface is added to * {@link #connectedInterfaces} list. */ private void onNetworkUp() { if(delayedNetworkDown != null) { delayedNetworkDown.cancel(); delayedNetworkDown = null; } } /** * Called when first there are no more connected interface present in * {@link #connectedInterfaces} list. */ private void onNetworkDown() { if(!org.jitsi.util.OSUtils.IS_ANDROID) { notifyNetworkDown(); } else { // Android never keeps two active connection at the same time // and it may take some time to attach next connection // even if it was already enabled by user if(delayedNetworkDown == null) { delayedNetworkDown = new Timer(); delayedNetworkDown.schedule(new TimerTask() { @Override public void run() { notifyNetworkDown(); } }, NETWORK_DOWN_THRESHOLD); } } } /** * Posts "network is down" notification. */ private void notifyNetworkDown() { if (logger.isTraceEnabled()) logger.trace("Network is down!"); notify("", "plugin.reconnectplugin.NETWORK_DOWN", new String[0], this); } }
Adds some tracing to track a problem where sip providers are unregistered and no longer reconnected.
src/net/java/sip/communicator/plugin/reconnectplugin/ReconnectPluginActivator.java
Adds some tracing to track a problem where sip providers are unregistered and no longer reconnected.
Java
apache-2.0
f5a336be26b0853437fd7a591ef36e95c1a7ef6b
0
ukwa/w3act,ukwa/w3act,ukwa/w3act,ukwa/w3act
package uk.bl.scope; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.commons.lang3.StringUtils; import models.FieldUrl; import models.LookupEntry; import models.Target; import play.Logger; import uk.bl.Const; import uk.bl.exception.ActException; import uk.bl.exception.WhoisException; import uk.bl.wa.whois.JRubyWhois; import uk.bl.wa.whois.record.WhoisContact; import uk.bl.wa.whois.record.WhoisResult; import com.avaje.ebean.Ebean; import com.avaje.ebean.SqlRow; import com.maxmind.geoip2.DatabaseReader; import com.maxmind.geoip2.model.CityResponse; /** * This class implements scope rule engine. * A Target is in scope if any of the following statements is true: * * Legal Deposit * ============= * 1. Manual rules settings in Target edit page * 1.1. The Target is known to be hosted in the UK (manual boolean field). * 1.2. The Target features an page that specified a UK postal address * (a manual boolean field plus a text field to hold a specific URL that contains the address). * 1.3. The Target is known to be a UK publication, according to correspondence with a curator * (a manual boolean field plus a text field to hold details of the correspondence). * 1.4. The Target is known to be a UK publication, in the professional judgement of a curator * (a manual boolean field plus a text field to hold the justification). * 1.5. If no LD criteria met - checking result for scope is negativeTarget * (a manual boolean field). * * 2. By permission * The Target is one for which we have a license that gives us permission to crawl the site * (and make it available), even if the Target does not fall under any Legal Deposit criteria. * * 3. All URLs for this Target meet at least one of the following automated criteria: * 3.1 The authority of the URI (i.e. the hostname) end with '.uk' or other acceptable TLD (e.g. '.scot'). * 3.2 The IP address associated with the URI is geo-located in the UK * (using this GeoIP2 database, in a manner similar to our H3 GeoIP module). * 3.3 Use whois lookup service to check whether the given domain name is associated with a UK registrant. * */ public enum Scope { INSTANCE; private static final String UK_DOMAIN = ".uk"; private static final String LONDON_DOMAIN = ".london"; private static final String SCOT_DOMAIN = ".scot"; private static final String WALES_DOMAIN = ".wales"; private static final String CYMRU_DOMAIN = ".cymru"; public static List<String> DOMAINS; static { DOMAINS = new ArrayList<String>(); DOMAINS.add(UK_DOMAIN); DOMAINS.add(LONDON_DOMAIN); DOMAINS.add(SCOT_DOMAIN); DOMAINS.add(WALES_DOMAIN); DOMAINS.add(CYMRU_DOMAIN); } public static final String GEO_IP_SERVICE = "GeoLite2-City.mmdb"; public static final String UK_COUNTRY_CODE = "GB"; public static final String HTTP = "http://"; public static final String HTTPS = "https://"; public static final String WWW = "www."; public static final String END_STR = "/"; private static final int WHOIS_TIMEOUT = 15; // Whois lookup timeout (seconds) public static boolean WHOIS_ENABLED = false; // Should whois be used at all? public static DatabaseReader databaseReader; static { // A File object pointing to your GeoIP2 or GeoLite2 database File database = new File(GEO_IP_SERVICE); // This creates the DatabaseReader object, which should be reused across // lookups. try { databaseReader = new DatabaseReader.Builder(database).build(); } catch (IOException e) { Logger.warn("Can't read database file. " + e); } } /** * This method is the rule engine for checking if a given URL is in scope. * * @param url The search URL * @param nidUrl The identifier URL in the project domain model * @param whether to include by-permission as acceptable * * @return true if in scope * @throws WhoisException */ public boolean check(String url, Target target, boolean includedByPermission) { url = normalizeUrl(url); Logger.debug("Scope.check url: " + url); /** * Check if given URL is already in project database in a table LookupEntry. * If this is in return associated value, otherwise process lookup using expert rules. */ /* boolean inProjectDb = false; if (url != null && url.length() > 0) { // List<LookupEntry> lookupEntryCount = LookupEntry.filterByName(url); LookupEntry resLookupEntry = LookupEntry.findBySiteName(url); if (resLookupEntry != null && !resLookupEntry.name.toLowerCase().equals(Const.NONE)) { // if (lookupEntryCount.size() > 0) { inProjectDb = true; res = LookupEntry.getValueByUrl(url); Logger.debug("check lookup entry for '" + url + "' is in database with value: " + res); } } return res; Logger.debug("URL not in database - calculate scope"); */ // read Target fields with manual entries and match to the given NID URL (Rules 1.1 - 1.5) if (target != null && target.checkManualScope() ) { return true; } // Rule 2: by permission if (includedByPermission && target != null && target.checkLicense() ) { return true; } // Rule 3.1: check domain name if (url != null && url.length() > 0 && checkScopeDomain(url)) { return true; } // Rule 3.2: check geo IP if ( url != null && url.length() > 0 && checkGeoIp(url) ) { return true; } // Rule 3.3: check whois lookup service if ( url != null && url.length() > 0 ) { if(checkWhois(url, target) ) { return true; } } return false; } /** * * Checks if a Target is in NPLD scope by running each of it's URL fields through the checks. * * @param target * @return * @throws WhoisException */ public boolean check(Target target, boolean includedByPermission ) { for( FieldUrl url : target.fieldUrls) { if( ! check( url.url, target, includedByPermission) ) { return false; } } return true; } /** * This method queries geo IP from database * * Synchronized in case the underlying database is not thread-safe. * * @param ip - The host IP * @return true if in UK domain */ public synchronized boolean queryDb(String ip) { boolean res = false; try { // Find city by given IP CityResponse response = databaseReader.city(InetAddress.getByName(ip)); Logger.info(response.getCountry().getIsoCode()); Logger.info(response.getCountry().getName()); // Check country code in city response if (response.getCountry().getIsoCode().equals(UK_COUNTRY_CODE)) { res = true; } } catch (Exception e) { Logger.warn("GeoIP error. " + e); } Logger.debug("Geo IP query result: " + res); return res; } /** * This method normalizes passed URL that it is appropriate for IP calculation. * @param url The passed URL * @return normalized URL */ public static String normalizeUrl(String url, boolean slash) { String res = url; if (res != null && res.length() > 0) { //if (!res.contains(WWW) && !res.contains(HTTP) && !res.contains(HTTPS)) { // res = WWW + res; //} if (!res.contains(HTTP)) { if (!res.contains(HTTPS)) { res = HTTP + res; } } if (slash && !res.endsWith(END_STR)) { res = res + END_STR; } } // Logger.debug("normalized URL: " + res); return res; } public static String normalizeUrl(String url) { return normalizeUrl(url, true); } public static String normalizeUrlNoSlash(String url) { return normalizeUrl(url, false); } /** * This method comprises rule engine for checking if a given URL is in scope for rules * associated with Domain analysis. * @param url The search URL * @param nidUrl The identifier URL in the project domain model * @return true if in scope * @throws WhoisException */ public static boolean checkScopeDomain(String ourl) { // Grab the domain part: String domain; try { domain = getDomainFromUrl(normalizeUrl(ourl)); Logger.debug("Checking domain: "+domain); } catch (ActException e) { Logger.error("Exception when normalising "+ourl, e); return false; } // Rule 3.1: check domain name ends with an acceptable suffix: if ( domain != null ) { domain = domain.toLowerCase(); for( String okd : DOMAINS ) { if ( domain.endsWith(okd)) { return true; } } } return false; } /** * This method extracts host from the given URL and checks geo IP using geo IP database. * @param url * @return true if in UK domain */ public boolean checkGeoIp(String url) { boolean res = false; String ip = getIpFromUrl(url); Logger.debug("ip: " + ip); res = queryDb(ip); return res; } /** * Check parsed WHOIS result for UK/GB. * * @param whoIsRes * @return */ public static boolean isUKRegistrant( WhoisResult whoIsRes ) { boolean isUK = false; for( WhoisContact c : whoIsRes.getRegistrantContacts() ) { if( "uk".equalsIgnoreCase(c.getCountry_code()) || "gb".equalsIgnoreCase(c.getCountry_code()) ) { isUK = true; break; } if( "united kingdom".equalsIgnoreCase(c.getCountry()) || "great britain".equalsIgnoreCase(c.getCountry()) ) { isUK = true; break; } } return isUK; } /** * This method extracts domain name from the given URL and checks country or country code * in response using whois lookup service. * @param url * @return true if in UK domain * @throws WhoisException */ public boolean checkWhois(String url, Target target) { if( WHOIS_ENABLED != true ) { Logger.warn("WHOIS is currently disabled!"); return false; } // Perform whois check: Logger.info("Performing whois lookup on "+url); boolean res = false; try { System.getProperties().put("JRUBY_OPTS", "--1.9"); JRubyWhois whoIs = new JRubyWhois(); Logger.debug("checkWhois: " + url); WhoisResult whoIsRes = whoIs.lookup(getDomainFromUrl(url), WHOIS_TIMEOUT); res = isUKRegistrant(whoIsRes); Logger.debug("isUKRegistrant?: " + res); if( whoIsRes.getRegistrantContacts() != null ) { for( WhoisContact wrc : whoIsRes.getRegistrantContacts()) { Logger.debug("WhoIsRes: "+wrc.getName()+" "+wrc.getCountry()+" "+wrc.getCountry_code()); } } if( target != null ) ScopeLookupEntries.storeInProjectDb(url, "WHOIS", res, target); } catch (Exception e) { Logger.warn("whois lookup message: " + e.getMessage(),e); if( target != null ) ScopeLookupEntries.storeInProjectDb(url, "WHOIS", false, target); } Logger.debug("whois res: " + res); return res; } /** * This method converts URL to IP address. * @param url * @return IP address as a string */ public String getIpFromUrl(String url) { String ip = ""; InetAddress address; try { address = InetAddress.getByName(new URL(url).getHost()); ip = address.getHostAddress(); } catch (UnknownHostException e) { Logger.debug("ip calculation unknown host error for url=" + url + ". " + e.getMessage()); } catch (MalformedURLException e) { Logger.debug("ip calculation error for url=" + url + ". " + e.getMessage()); } return ip; } /** * Actually gets the host. * * @param url * @return * @throws ActException */ public static String getDomainFromUrl(String url) throws ActException { URL uri; try { uri = new URL(url); Logger.debug("getDomainFromUrl: "+uri); String domain = uri.getHost(); Logger.debug("getDomainFromUrl GOT: "+domain); if (StringUtils.isNotEmpty(domain)) { return domain.startsWith(WWW) ? domain.substring(4) : domain; } } catch (MalformedURLException e) { throw new ActException(e); } return null; } public boolean isUkHosting(String url) { if (this.checkGeoIp(url)) { return true; } return false; } public boolean isInScopeUkRegistration(String url, Target target) throws WhoisException { return checkWhois(url, target); } // UK GeoIP public boolean isUkHosting(Target target) { for (FieldUrl fieldUrl : target.fieldUrls) { if (!this.checkGeoIp(fieldUrl.url)) return false; } return true; } // UK Domain public static boolean isTopLevelDomain(Target target) { for (FieldUrl fieldUrl : target.fieldUrls) { if( !checkScopeDomain(fieldUrl.url)) return false; } return true; } public boolean isUkRegistration(Target target) { for (FieldUrl fieldUrl : target.fieldUrls) { if (!checkWhois(fieldUrl.url, target)) return false; } return true; } /** * * @param number * @return * @throws WhoisException */ public WhoIsData checkWhois(int number) throws WhoisException { Logger.debug("checkWhoisThread: " + number); boolean res = false; List<Target> targets = new ArrayList<Target>(); int ukRegistrantCount = 0; int nonUKRegistrantCount = 0; int failedCount = 0; JRubyWhois whoIs = new JRubyWhois(); List<Target> targetList = Target.findLastActive(number); Logger.debug("targetList: " + targetList.size()); Iterator<Target> itr = targetList.iterator(); while (itr.hasNext()) { Target target = itr.next(); for (FieldUrl fieldUrl : target.fieldUrls) { try { // Logger.debug("checkWhoisThread URL: " + target.field_url + ", last update: " + String.valueOf(target.lastUpdate)); WhoisResult whoIsRes = whoIs.lookup(getDomainFromUrl(fieldUrl.url)); // Logger.debug("whoIsRes: " + whoIsRes); // DOMAIN A UK REGISTRANT? res = isUKRegistrant(whoIsRes); if (res) ukRegistrantCount++; else nonUKRegistrantCount++; // Logger.debug("isUKRegistrant?: " + res); // STORE Logger.debug("CHECK TO SAVE " + target.fieldUrl()); ScopeLookupEntries.storeInProjectDb(fieldUrl.url, "WHOIS", res, target); // ASSIGN TO TARGET target.isUkRegistration = res; ukRegistrantCount++; } catch (Exception e) { Logger.debug("whois lookup message: " + e.getMessage()); // store in project DB // FAILED - UNCHECKED ScopeLookupEntries.storeInProjectDb(fieldUrl.url, "WHOIS", false, target); // FALSE - WHAT'S DIFF BETWEEN THAT AND NON UK? create a transient field? target.isUkRegistration = false; failedCount++; } } Ebean.update(target); targets.add(target); } // List<Target> result = Target.find.select("title").where().eq(Const.ACTIVE, true).orderBy(Const.LAST_UPDATE + " " + Const.DESC).setMaxRows(number).findList(); // LookupEntry.find.fetch("target").where().select("name").select("target.title") // // StringBuilder lookupSql = new StringBuilder("select l.name as lookup_name, t.title as title, t.updated_at as target_date, l.updated_at as lookup_date, (l.updated_at::timestamp - t.updated_at::timestamp) as diff from Lookup_entry l, Target t "); lookupSql.append(" where l.name in (select f.url from field_url as f, target tar where tar.active = true and tar.id = f.target_id order by tar.updated_at desc "); lookupSql.append(" limit ").append(number).append(") and l.target_id = t.id order by diff desc"); List<SqlRow> results = Ebean.createSqlQuery(lookupSql.toString()).findList(); // for (SqlRow row : results) { // Logger.debug("row: " + row.getString("name") + " - " + row.get("diff")); // } // List<LookupEntry> lookupEntries = LookupEntry.find.where().in("name", result).findList(); // StringBuilder builder = new StringBuilder("name in (select tar.field_url from target tar where tar.active = true order by tar.last_update desc)"); // List<LookupEntry> lookupEntries = LookupEntry.find.where().raw(builder.toString()).findList(); // Logger.debug("lookupEntries: " + lookupEntries.size()); WhoIsData whoIsData = new WhoIsData(targets, results, ukRegistrantCount, nonUKRegistrantCount, failedCount); // Logger.debug("whois res: " + res); return whoIsData; } /** * This method extracts domain name from the given URL and checks country or country code * in response using whois lookup service. * @param number The number of targets for which the elapsed time since the last check is greatest * @return true if in UK domain * @throws ActException * @throws WhoisException */ public boolean checkWhoisThread(int number) throws ActException { Logger.debug("checkWhoisThread: " + number); boolean res = false; JRubyWhois whoIs = new JRubyWhois(); List<Target> targetList = Target.findLastActive(number); Logger.debug("targetList: " + targetList.size()); Iterator<Target> itr = targetList.iterator(); while (itr.hasNext()) { Target target = itr.next(); for (FieldUrl fieldUrl : target.fieldUrls) { Logger.debug("checkWhoisThread URL: " + target.fieldUrl() + ", last update: " + String.valueOf(target.updatedAt)); WhoisResult whoIsRes = whoIs.lookup(getDomainFromUrl(fieldUrl.url)); Logger.debug("whoIsRes: " + whoIsRes); // DOMAIN A UK REGISTRANT? res = isUKRegistrant(whoIsRes); Logger.debug("isUKRegistrant?: " + res); // STORE ScopeLookupEntries.storeInProjectDb(fieldUrl.url, "WHOIS", res, target); // ASSIGN TO TARGET target.isUkRegistration = res; // Logger.debug("whois lookup message: " + e.getMessage()); // // store in project DB // // FAILED - UNCHECKED // storeInProjectDb(fieldUrl.url, false); // // FALSE - WHAT'S DIFF BETWEEN THAT AND NON UK? create a transient field? // target.isInScopeUkRegistration = false; } Ebean.update(target); } // Logger.debug("whois res: " + res); return res; } }
app/uk/bl/scope/Scope.java
package uk.bl.scope; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.commons.lang3.StringUtils; import models.FieldUrl; import models.LookupEntry; import models.Target; import play.Logger; import uk.bl.Const; import uk.bl.exception.ActException; import uk.bl.exception.WhoisException; import uk.bl.wa.whois.JRubyWhois; import uk.bl.wa.whois.record.WhoisContact; import uk.bl.wa.whois.record.WhoisResult; import com.avaje.ebean.Ebean; import com.avaje.ebean.SqlRow; import com.maxmind.geoip2.DatabaseReader; import com.maxmind.geoip2.model.CityResponse; /** * This class implements scope rule engine. * A Target is in scope if any of the following statements is true: * * Legal Deposit * ============= * 1. Manual rules settings in Target edit page * 1.1. The Target is known to be hosted in the UK (manual boolean field). * 1.2. The Target features an page that specified a UK postal address * (a manual boolean field plus a text field to hold a specific URL that contains the address). * 1.3. The Target is known to be a UK publication, according to correspondence with a curator * (a manual boolean field plus a text field to hold details of the correspondence). * 1.4. The Target is known to be a UK publication, in the professional judgement of a curator * (a manual boolean field plus a text field to hold the justification). * 1.5. If no LD criteria met - checking result for scope is negativeTarget * (a manual boolean field). * * 2. By permission * The Target is one for which we have a license that gives us permission to crawl the site * (and make it available), even if the Target does not fall under any Legal Deposit criteria. * * 3. All URLs for this Target meet at least one of the following automated criteria: * 3.1 The authority of the URI (i.e. the hostname) end with '.uk' or other acceptable TLD (e.g. '.scot'). * 3.2 The IP address associated with the URI is geo-located in the UK * (using this GeoIP2 database, in a manner similar to our H3 GeoIP module). * 3.3 Use whois lookup service to check whether the given domain name is associated with a UK registrant. * */ public enum Scope { INSTANCE; private static final String UK_DOMAIN = ".uk"; private static final String LONDON_DOMAIN = ".london"; private static final String SCOT_DOMAIN = ".scot"; private static final String WALES_DOMAIN = ".wales"; private static final String CYMRU_DOMAIN = ".cymru"; public static List<String> DOMAINS; static { DOMAINS = new ArrayList<String>(); DOMAINS.add(UK_DOMAIN); DOMAINS.add(LONDON_DOMAIN); DOMAINS.add(SCOT_DOMAIN); DOMAINS.add(WALES_DOMAIN); DOMAINS.add(CYMRU_DOMAIN); } public static final String GEO_IP_SERVICE = "GeoLite2-City.mmdb"; public static final String UK_COUNTRY_CODE = "GB"; public static final String HTTP = "http://"; public static final String HTTPS = "https://"; public static final String WWW = "www."; public static final String END_STR = "/"; private static final int WHOIS_TIMEOUT = 15; // Whois lookup timeout (seconds) public static boolean WHOIS_ENABLED = true; // Should whois be used at all? public static DatabaseReader databaseReader; static { // A File object pointing to your GeoIP2 or GeoLite2 database File database = new File(GEO_IP_SERVICE); // This creates the DatabaseReader object, which should be reused across // lookups. try { databaseReader = new DatabaseReader.Builder(database).build(); } catch (IOException e) { Logger.warn("Can't read database file. " + e); } } /** * This method is the rule engine for checking if a given URL is in scope. * * @param url The search URL * @param nidUrl The identifier URL in the project domain model * @param whether to include by-permission as acceptable * * @return true if in scope * @throws WhoisException */ public boolean check(String url, Target target, boolean includedByPermission) { url = normalizeUrl(url); Logger.debug("Scope.check url: " + url); /** * Check if given URL is already in project database in a table LookupEntry. * If this is in return associated value, otherwise process lookup using expert rules. */ /* boolean inProjectDb = false; if (url != null && url.length() > 0) { // List<LookupEntry> lookupEntryCount = LookupEntry.filterByName(url); LookupEntry resLookupEntry = LookupEntry.findBySiteName(url); if (resLookupEntry != null && !resLookupEntry.name.toLowerCase().equals(Const.NONE)) { // if (lookupEntryCount.size() > 0) { inProjectDb = true; res = LookupEntry.getValueByUrl(url); Logger.debug("check lookup entry for '" + url + "' is in database with value: " + res); } } return res; Logger.debug("URL not in database - calculate scope"); */ // read Target fields with manual entries and match to the given NID URL (Rules 1.1 - 1.5) if (target != null && target.checkManualScope() ) { return true; } // Rule 2: by permission if (includedByPermission && target != null && target.checkLicense() ) { return true; } // Rule 3.1: check domain name if (url != null && url.length() > 0 && checkScopeDomain(url)) { return true; } // Rule 3.2: check geo IP if ( url != null && url.length() > 0 && checkGeoIp(url) ) { return true; } // Rule 3.3: check whois lookup service if ( url != null && url.length() > 0 ) { if(checkWhois(url, target) ) { return true; } } return false; } /** * * Checks if a Target is in NPLD scope by running each of it's URL fields through the checks. * * @param target * @return * @throws WhoisException */ public boolean check(Target target, boolean includedByPermission ) { for( FieldUrl url : target.fieldUrls) { if( ! check( url.url, target, includedByPermission) ) { return false; } } return true; } /** * This method queries geo IP from database * * Synchronized in case the underlying database is not thread-safe. * * @param ip - The host IP * @return true if in UK domain */ public synchronized boolean queryDb(String ip) { boolean res = false; try { // Find city by given IP CityResponse response = databaseReader.city(InetAddress.getByName(ip)); Logger.info(response.getCountry().getIsoCode()); Logger.info(response.getCountry().getName()); // Check country code in city response if (response.getCountry().getIsoCode().equals(UK_COUNTRY_CODE)) { res = true; } } catch (Exception e) { Logger.warn("GeoIP error. " + e); } Logger.debug("Geo IP query result: " + res); return res; } /** * This method normalizes passed URL that it is appropriate for IP calculation. * @param url The passed URL * @return normalized URL */ public static String normalizeUrl(String url, boolean slash) { String res = url; if (res != null && res.length() > 0) { //if (!res.contains(WWW) && !res.contains(HTTP) && !res.contains(HTTPS)) { // res = WWW + res; //} if (!res.contains(HTTP)) { if (!res.contains(HTTPS)) { res = HTTP + res; } } if (slash && !res.endsWith(END_STR)) { res = res + END_STR; } } // Logger.debug("normalized URL: " + res); return res; } public static String normalizeUrl(String url) { return normalizeUrl(url, true); } public static String normalizeUrlNoSlash(String url) { return normalizeUrl(url, false); } /** * This method comprises rule engine for checking if a given URL is in scope for rules * associated with Domain analysis. * @param url The search URL * @param nidUrl The identifier URL in the project domain model * @return true if in scope * @throws WhoisException */ public static boolean checkScopeDomain(String ourl) { // Grab the domain part: String domain; try { domain = getDomainFromUrl(normalizeUrl(ourl)); Logger.debug("Checking domain: "+domain); } catch (ActException e) { Logger.error("Exception when normalising "+ourl, e); return false; } // Rule 3.1: check domain name ends with an acceptable suffix: if ( domain != null ) { domain = domain.toLowerCase(); for( String okd : DOMAINS ) { if ( domain.endsWith(okd)) { return true; } } } return false; } /** * This method extracts host from the given URL and checks geo IP using geo IP database. * @param url * @return true if in UK domain */ public boolean checkGeoIp(String url) { boolean res = false; String ip = getIpFromUrl(url); Logger.debug("ip: " + ip); res = queryDb(ip); return res; } /** * Check parsed WHOIS result for UK/GB. * * @param whoIsRes * @return */ public static boolean isUKRegistrant( WhoisResult whoIsRes ) { boolean isUK = false; for( WhoisContact c : whoIsRes.getRegistrantContacts() ) { if( "uk".equalsIgnoreCase(c.getCountry_code()) || "gb".equalsIgnoreCase(c.getCountry_code()) ) { isUK = true; break; } if( "united kingdom".equalsIgnoreCase(c.getCountry()) || "great britain".equalsIgnoreCase(c.getCountry()) ) { isUK = true; break; } } return isUK; } /** * This method extracts domain name from the given URL and checks country or country code * in response using whois lookup service. * @param url * @return true if in UK domain * @throws WhoisException */ public boolean checkWhois(String url, Target target) { if( WHOIS_ENABLED != true ) { Logger.warn("WHOIS is currently disabled!"); return false; } // Perform whois check: Logger.info("Performing whois lookup on "+url); boolean res = false; try { System.getProperties().put("JRUBY_OPTS", "--1.9"); JRubyWhois whoIs = new JRubyWhois(); Logger.debug("checkWhois: " + url); WhoisResult whoIsRes = whoIs.lookup(getDomainFromUrl(url), WHOIS_TIMEOUT); res = isUKRegistrant(whoIsRes); Logger.debug("isUKRegistrant?: " + res); if( whoIsRes.getRegistrantContacts() != null ) { for( WhoisContact wrc : whoIsRes.getRegistrantContacts()) { Logger.debug("WhoIsRes: "+wrc.getName()+" "+wrc.getCountry()+" "+wrc.getCountry_code()); } } if( target != null ) ScopeLookupEntries.storeInProjectDb(url, "WHOIS", res, target); } catch (Exception e) { Logger.warn("whois lookup message: " + e.getMessage(),e); if( target != null ) ScopeLookupEntries.storeInProjectDb(url, "WHOIS", false, target); } Logger.debug("whois res: " + res); return res; } /** * This method converts URL to IP address. * @param url * @return IP address as a string */ public String getIpFromUrl(String url) { String ip = ""; InetAddress address; try { address = InetAddress.getByName(new URL(url).getHost()); ip = address.getHostAddress(); } catch (UnknownHostException e) { Logger.debug("ip calculation unknown host error for url=" + url + ". " + e.getMessage()); } catch (MalformedURLException e) { Logger.debug("ip calculation error for url=" + url + ". " + e.getMessage()); } return ip; } /** * Actually gets the host. * * @param url * @return * @throws ActException */ public static String getDomainFromUrl(String url) throws ActException { URL uri; try { uri = new URL(url); Logger.debug("getDomainFromUrl: "+uri); String domain = uri.getHost(); Logger.debug("getDomainFromUrl GOT: "+domain); if (StringUtils.isNotEmpty(domain)) { return domain.startsWith(WWW) ? domain.substring(4) : domain; } } catch (MalformedURLException e) { throw new ActException(e); } return null; } public boolean isUkHosting(String url) { if (this.checkGeoIp(url)) { return true; } return false; } public boolean isInScopeUkRegistration(String url, Target target) throws WhoisException { return checkWhois(url, target); } // UK GeoIP public boolean isUkHosting(Target target) { for (FieldUrl fieldUrl : target.fieldUrls) { if (!this.checkGeoIp(fieldUrl.url)) return false; } return true; } // UK Domain public static boolean isTopLevelDomain(Target target) { for (FieldUrl fieldUrl : target.fieldUrls) { if( !checkScopeDomain(fieldUrl.url)) return false; } return true; } public boolean isUkRegistration(Target target) { for (FieldUrl fieldUrl : target.fieldUrls) { if (!checkWhois(fieldUrl.url, target)) return false; } return true; } /** * * @param number * @return * @throws WhoisException */ public WhoIsData checkWhois(int number) throws WhoisException { Logger.debug("checkWhoisThread: " + number); boolean res = false; List<Target> targets = new ArrayList<Target>(); int ukRegistrantCount = 0; int nonUKRegistrantCount = 0; int failedCount = 0; JRubyWhois whoIs = new JRubyWhois(); List<Target> targetList = Target.findLastActive(number); Logger.debug("targetList: " + targetList.size()); Iterator<Target> itr = targetList.iterator(); while (itr.hasNext()) { Target target = itr.next(); for (FieldUrl fieldUrl : target.fieldUrls) { try { // Logger.debug("checkWhoisThread URL: " + target.field_url + ", last update: " + String.valueOf(target.lastUpdate)); WhoisResult whoIsRes = whoIs.lookup(getDomainFromUrl(fieldUrl.url)); // Logger.debug("whoIsRes: " + whoIsRes); // DOMAIN A UK REGISTRANT? res = isUKRegistrant(whoIsRes); if (res) ukRegistrantCount++; else nonUKRegistrantCount++; // Logger.debug("isUKRegistrant?: " + res); // STORE Logger.debug("CHECK TO SAVE " + target.fieldUrl()); ScopeLookupEntries.storeInProjectDb(fieldUrl.url, "WHOIS", res, target); // ASSIGN TO TARGET target.isUkRegistration = res; ukRegistrantCount++; } catch (Exception e) { Logger.debug("whois lookup message: " + e.getMessage()); // store in project DB // FAILED - UNCHECKED ScopeLookupEntries.storeInProjectDb(fieldUrl.url, "WHOIS", false, target); // FALSE - WHAT'S DIFF BETWEEN THAT AND NON UK? create a transient field? target.isUkRegistration = false; failedCount++; } } Ebean.update(target); targets.add(target); } // List<Target> result = Target.find.select("title").where().eq(Const.ACTIVE, true).orderBy(Const.LAST_UPDATE + " " + Const.DESC).setMaxRows(number).findList(); // LookupEntry.find.fetch("target").where().select("name").select("target.title") // // StringBuilder lookupSql = new StringBuilder("select l.name as lookup_name, t.title as title, t.updated_at as target_date, l.updated_at as lookup_date, (l.updated_at::timestamp - t.updated_at::timestamp) as diff from Lookup_entry l, Target t "); lookupSql.append(" where l.name in (select f.url from field_url as f, target tar where tar.active = true and tar.id = f.target_id order by tar.updated_at desc "); lookupSql.append(" limit ").append(number).append(") and l.target_id = t.id order by diff desc"); List<SqlRow> results = Ebean.createSqlQuery(lookupSql.toString()).findList(); // for (SqlRow row : results) { // Logger.debug("row: " + row.getString("name") + " - " + row.get("diff")); // } // List<LookupEntry> lookupEntries = LookupEntry.find.where().in("name", result).findList(); // StringBuilder builder = new StringBuilder("name in (select tar.field_url from target tar where tar.active = true order by tar.last_update desc)"); // List<LookupEntry> lookupEntries = LookupEntry.find.where().raw(builder.toString()).findList(); // Logger.debug("lookupEntries: " + lookupEntries.size()); WhoIsData whoIsData = new WhoIsData(targets, results, ukRegistrantCount, nonUKRegistrantCount, failedCount); // Logger.debug("whois res: " + res); return whoIsData; } /** * This method extracts domain name from the given URL and checks country or country code * in response using whois lookup service. * @param number The number of targets for which the elapsed time since the last check is greatest * @return true if in UK domain * @throws ActException * @throws WhoisException */ public boolean checkWhoisThread(int number) throws ActException { Logger.debug("checkWhoisThread: " + number); boolean res = false; JRubyWhois whoIs = new JRubyWhois(); List<Target> targetList = Target.findLastActive(number); Logger.debug("targetList: " + targetList.size()); Iterator<Target> itr = targetList.iterator(); while (itr.hasNext()) { Target target = itr.next(); for (FieldUrl fieldUrl : target.fieldUrls) { Logger.debug("checkWhoisThread URL: " + target.fieldUrl() + ", last update: " + String.valueOf(target.updatedAt)); WhoisResult whoIsRes = whoIs.lookup(getDomainFromUrl(fieldUrl.url)); Logger.debug("whoIsRes: " + whoIsRes); // DOMAIN A UK REGISTRANT? res = isUKRegistrant(whoIsRes); Logger.debug("isUKRegistrant?: " + res); // STORE ScopeLookupEntries.storeInProjectDb(fieldUrl.url, "WHOIS", res, target); // ASSIGN TO TARGET target.isUkRegistration = res; // Logger.debug("whois lookup message: " + e.getMessage()); // // store in project DB // // FAILED - UNCHECKED // storeInProjectDb(fieldUrl.url, false); // // FALSE - WHAT'S DIFF BETWEEN THAT AND NON UK? create a transient field? // target.isInScopeUkRegistration = false; } Ebean.update(target); } // Logger.debug("whois res: " + res); return res; } }
Do not enable WHOIS as that is separate from GeoIP lookups.
app/uk/bl/scope/Scope.java
Do not enable WHOIS as that is separate from GeoIP lookups.
Java
apache-2.0
2bb09b2a72a47fa39b867afff1564a45456a8552
0
JavaSaBr/jME3-SpaceShift-Editor
package com.ss.editor.ui.component.asset.tree; import com.ss.editor.config.EditorConfig; import com.ss.editor.file.converter.FileConverterDescription; import com.ss.editor.file.converter.FileConverterRegistry; import com.ss.editor.manager.ExecutorManager; import com.ss.editor.ui.component.asset.tree.context.menu.action.ConvertFileAction; import com.ss.editor.ui.component.asset.tree.context.menu.action.CopyFileAction; import com.ss.editor.ui.component.asset.tree.context.menu.action.CutFileAction; import com.ss.editor.ui.component.asset.tree.context.menu.action.DeleteFileAction; import com.ss.editor.ui.component.asset.tree.context.menu.action.NewFileAction; import com.ss.editor.ui.component.asset.tree.context.menu.action.OpenFileAction; import com.ss.editor.ui.component.asset.tree.context.menu.action.OpenFileByExternalEditorAction; import com.ss.editor.ui.component.asset.tree.context.menu.action.OpenWithFileAction; import com.ss.editor.ui.component.asset.tree.context.menu.action.PasteFileAction; import com.ss.editor.ui.component.asset.tree.context.menu.action.RenameFileAction; import com.ss.editor.ui.component.asset.tree.resource.FileElement; import com.ss.editor.ui.component.asset.tree.resource.FolderElement; import com.ss.editor.ui.component.asset.tree.resource.ResourceElement; import com.ss.editor.ui.component.asset.tree.resource.ResourceElementFactory; import com.ss.editor.ui.component.asset.tree.resource.ResourceLoadingElement; import com.ss.editor.ui.css.CSSClasses; import com.ss.editor.ui.util.UIUtils; import com.ss.editor.util.EditorUtil; import java.nio.file.Path; import java.util.function.Consumer; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.control.ContextMenu; import javafx.scene.control.MenuItem; import javafx.scene.control.MultipleSelectionModel; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeView; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import rlib.ui.util.FXUtils; import rlib.util.StringUtils; import rlib.util.array.Array; import rlib.util.array.ArrayComparator; import rlib.util.array.ArrayFactory; import static com.ss.editor.ui.component.asset.tree.ResourceTreeCell.CELL_FACTORY; import static com.ss.editor.ui.component.asset.tree.resource.ResourceElementFactory.createFor; import static com.ss.editor.ui.css.CSSClasses.MAIN_FONT_13; import static com.ss.editor.ui.util.UIUtils.findItemForValue; /** * Реализация дерева ресурсов. * * @author Ronn */ public class ResourceTree extends TreeView<ResourceElement> { private static final FileConverterRegistry FILE_CONVERTER_REGISTRY = FileConverterRegistry.getInstance(); private static final ExecutorManager EXECUTOR_MANAGER = ExecutorManager.getInstance(); private static final ArrayComparator<ResourceElement> COMPARATOR = ResourceElement::compareTo; private static final ArrayComparator<ResourceElement> NAME_COMPARATOR = (first, second) -> { final int firstLevel = getLevel(first); final int secondLevel = getLevel(second); if (firstLevel != secondLevel) { return firstLevel - secondLevel; } final Path firstFile = first.getFile(); final String firstName = firstFile.getFileName().toString(); final Path secondFile = second.getFile(); final String secondName = secondFile.getFileName().toString(); return StringUtils.compareIgnoreCase(firstName, secondName); }; private static final ArrayComparator<TreeItem<ResourceElement>> ITEM_COMPARATOR = (first, second) -> { final ResourceElement firstElement = first.getValue(); final ResourceElement secondElement = second.getValue(); final int firstLevel = getLevel(firstElement); final int secondLevel = getLevel(secondElement); if (firstLevel != secondLevel) { return firstLevel - secondLevel; } return NAME_COMPARATOR.compare(firstElement, secondElement); }; private static int getLevel(final ResourceElement element) { if (element instanceof FolderElement) { return 1; } return 2; } private static final Consumer<ResourceElement> DEFAULT_FUNCTION = element -> { final OpenFileAction action = new OpenFileAction(element); final EventHandler<ActionEvent> onAction = action.getOnAction(); onAction.handle(null); }; /** * Развернутые элементы. */ private final Array<ResourceElement> expandedElements; /** * Выбранные элементы. */ private final Array<ResourceElement> selectedElements; /** * Функция окрытия файла. */ private final Consumer<ResourceElement> openFunction; /** * Режим только чтения. */ private final boolean readOnly; /** * Список фильтруемых расширений. */ private Array<String> extensionFilter; /** * Пост загрузачный обработчик. */ private Runnable onLoadHandler; public ResourceTree(final boolean readOnly) { this(DEFAULT_FUNCTION, readOnly); } public ResourceTree(final Consumer<ResourceElement> openFunction, final boolean readOnly) { this.openFunction = openFunction; this.readOnly = readOnly; this.expandedElements = ArrayFactory.newConcurrentAtomicArray(ResourceElement.class); this.selectedElements = ArrayFactory.newConcurrentAtomicArray(ResourceElement.class); FXUtils.addClassTo(this, CSSClasses.TRANSPARENT_TREE_VIEW); setCellFactory(CELL_FACTORY); setOnKeyPressed(this::processKey); setShowRoot(true); setContextMenu(new ContextMenu()); } /** * @param extensionFilter список фильтруемых расширений. */ public void setExtensionFilter(Array<String> extensionFilter) { this.extensionFilter = extensionFilter; } /** * @return список фильтруемых расширений. */ private Array<String> getExtensionFilter() { return extensionFilter; } /** * @param onLoadHandler пост загрузачный обработчик. */ public void setOnLoadHandler(Runnable onLoadHandler) { this.onLoadHandler = onLoadHandler; } /** * @return пост загрузачныый обработчик. */ private Runnable getOnLoadHandler() { return onLoadHandler; } /** * @return режим только чтения. */ private boolean isReadOnly() { return readOnly; } /** * Обновление контекстного меню под указанный элемент. */ public void updateContextMenu(final ResourceElement element) { if (isReadOnly()) { return; } final EditorConfig editorConfig = EditorConfig.getInstance(); final Path currentAsset = editorConfig.getCurrentAsset(); final ContextMenu contextMenu = getContextMenu(); final ObservableList<MenuItem> items = contextMenu.getItems(); items.clear(); final Path file = element.getFile(); items.add(new NewFileAction(element)); if (element instanceof FileElement) { items.add(new OpenFileAction(element)); items.add(new OpenFileByExternalEditorAction(element)); items.add(new OpenWithFileAction(element)); final Array<FileConverterDescription> descriptions = FILE_CONVERTER_REGISTRY.getDescriptions(file); if (!descriptions.isEmpty()) { items.add(new ConvertFileAction(element, descriptions)); } } if (EditorUtil.hasFileInClipboard()) { items.add(new PasteFileAction(element)); } if (!currentAsset.equals(file)) { items.add(new CopyFileAction(element)); items.add(new CutFileAction(element)); items.add(new RenameFileAction(element)); items.add(new DeleteFileAction(element)); } final Array<MenuItem> allItems = ArrayFactory.newArray(MenuItem.class); items.forEach(subItem -> UIUtils.getAllItems(allItems, subItem)); allItems.forEach(menuItem -> FXUtils.addClassTo(menuItem, MAIN_FONT_13)); setContextMenu(contextMenu); } /** * Заполнить дерево по новой папке асета. * * @param assetFolder новая папка ассета. */ public void fill(final Path assetFolder) { final TreeItem<ResourceElement> currentRoot = getRoot(); if (currentRoot != null) { setRoot(null); } showLoading(); EXECUTOR_MANAGER.addBackgroundTask(() -> startBackgroundFill(assetFolder)); } /** * @return развернутые элементы. */ public Array<ResourceElement> getExpandedElements() { return expandedElements; } /** * @return выбранные элементы. */ public Array<ResourceElement> getSelectedElements() { return selectedElements; } /** * Обновить дерево. */ public void refresh() { final EditorConfig config = EditorConfig.getInstance(); final Path currentAsset = config.getCurrentAsset(); if (currentAsset == null) { setRoot(null); return; } updateSelectedElements(); updateExpandedElements(); setRoot(null); showLoading(); EXECUTOR_MANAGER.addBackgroundTask(() -> startBackgroundRefresh(currentAsset)); } /** * Обновление развернутых элементов. */ private void updateExpandedElements() { final Array<ResourceElement> expandedElements = getExpandedElements(); expandedElements.writeLock(); try { expandedElements.clear(); final Array<TreeItem<ResourceElement>> allItems = UIUtils.getAllItems(this); allItems.forEach(item -> { if (!item.isExpanded()) { return; } expandedElements.add(item.getValue()); }); } finally { expandedElements.writeUnlock(); } } /** * Обновление списка выбранных элементов. */ private void updateSelectedElements() { final Array<ResourceElement> selectedElements = getSelectedElements(); selectedElements.writeLock(); try { selectedElements.clear(); final MultipleSelectionModel<TreeItem<ResourceElement>> selectionModel = getSelectionModel(); final ObservableList<TreeItem<ResourceElement>> selectedItems = selectionModel.getSelectedItems(); selectedItems.forEach(item -> selectedElements.add(item.getValue())); } finally { selectedElements.writeUnlock(); } } /** * Отобразить прогресс прогрузки. */ private void showLoading() { setRoot(new TreeItem<>(ResourceLoadingElement.getInstance())); } /** * Запустить фоновое построение дерева. */ private void startBackgroundFill(final Path assetFolder) { final ResourceElement rootElement = createFor(assetFolder); final TreeItem<ResourceElement> newRoot = new TreeItem<>(rootElement); newRoot.setExpanded(true); fill(newRoot); final Array<String> extensionFilter = getExtensionFilter(); if (extensionFilter != null) { cleanup(newRoot); } EXECUTOR_MANAGER.addFXTask(() -> { setRoot(newRoot); final Runnable onLoadHandler = getOnLoadHandler(); if (onLoadHandler != null) { onLoadHandler.run(); } }); } /** * Запустить фоновое обновление дерева. */ private void startBackgroundRefresh(final Path assetFolder) { final ResourceElement rootElement = createFor(assetFolder); final TreeItem<ResourceElement> newRoot = new TreeItem<>(rootElement); newRoot.setExpanded(true); fill(newRoot); final Array<ResourceElement> expandedElements = getExpandedElements(); expandedElements.writeLock(); try { expandedElements.sort(COMPARATOR); expandedElements.forEach(element -> { final TreeItem<ResourceElement> item = findItemForValue(newRoot, element); if (item == null) { return; } item.setExpanded(true); }); expandedElements.clear(); } finally { expandedElements.writeUnlock(); } EXECUTOR_MANAGER.addFXTask(() -> { setRoot(newRoot); restoreSelection(); final Runnable onLoadHandler = getOnLoadHandler(); if (onLoadHandler != null) { onLoadHandler.run(); } }); } /** * Восстановление выбранных элементов. */ private void restoreSelection() { EXECUTOR_MANAGER.addFXTask(() -> { final Array<ResourceElement> selectedElements = getSelectedElements(); selectedElements.writeLock(); try { final MultipleSelectionModel<TreeItem<ResourceElement>> selectionModel = getSelectionModel(); selectedElements.forEach(element -> { final TreeItem<ResourceElement> item = findItemForValue(getRoot(), element); if (item == null) { return; } selectionModel.select(item); }); selectedElements.clear(); } finally { selectedElements.writeUnlock(); } }); } /** * Заполнить узел. */ private void fill(final TreeItem<ResourceElement> treeItem) { final ResourceElement element = treeItem.getValue(); final Array<String> extensionFilter = getExtensionFilter(); if (!element.hasChildren(extensionFilter)) { return; } final ObservableList<TreeItem<ResourceElement>> items = treeItem.getChildren(); final Array<ResourceElement> children = element.getChildren(extensionFilter); children.sort(NAME_COMPARATOR); children.forEach(child -> items.add(new TreeItem<>(child))); items.forEach(this::fill); } /** * Уведомление о созданном файле. * * @param file созданный файл. */ public void notifyCreated(final Path file) { final EditorConfig editorConfig = EditorConfig.getInstance(); final Path currentAsset = editorConfig.getCurrentAsset(); final Path folder = file.getParent(); if (!folder.startsWith(currentAsset)) { return; } final ResourceElement element = ResourceElementFactory.createFor(folder); TreeItem<ResourceElement> folderItem = UIUtils.findItemForValue(getRoot(), element); if (folderItem == null) { notifyCreated(folder); folderItem = UIUtils.findItemForValue(getRoot(), folder); } if (folderItem == null) { return; } final TreeItem<ResourceElement> newItem = new TreeItem<>(ResourceElementFactory.createFor(file)); fill(newItem); final ObservableList<TreeItem<ResourceElement>> children = folderItem.getChildren(); children.add(newItem); FXCollections.sort(children, ITEM_COMPARATOR); } /** * Уведомление об удаленном файле. */ public void notifyDeleted(final Path file) { final ResourceElement element = ResourceElementFactory.createFor(file); final TreeItem<ResourceElement> treeItem = UIUtils.findItemForValue(getRoot(), element); if (treeItem == null) { return; } final TreeItem<ResourceElement> parent = treeItem.getParent(); if (parent == null) { return; } final ObservableList<TreeItem<ResourceElement>> children = parent.getChildren(); children.remove(treeItem); } /** * Уведомление о перемещении файла. * * @param prevFile старая версия файла. * @param newFile новая версия файла. */ public void notifyMoved(final Path prevFile, final Path newFile) { final ResourceElement prevElement = ResourceElementFactory.createFor(prevFile); final TreeItem<ResourceElement> prevItem = UIUtils.findItemForValue(getRoot(), prevElement); if (prevItem == null) { return; } final ResourceElement newParentElement = ResourceElementFactory.createFor(newFile.getParent()); final TreeItem<ResourceElement> newParentItem = UIUtils.findItemForValue(getRoot(), newParentElement); if (newParentItem == null) { return; } final TreeItem<ResourceElement> prevParentItem = prevItem.getParent(); final ObservableList<TreeItem<ResourceElement>> prevParentChildren = prevParentItem.getChildren(); prevParentChildren.remove(prevItem); prevItem.setValue(ResourceElementFactory.createFor(newFile)); final Array<TreeItem<ResourceElement>> children = ArrayFactory.newArray(TreeItem.class); UIUtils.getAllItems(children, prevItem); children.fastRemove(prevItem); children.forEach(child -> { final ResourceElement resourceElement = child.getValue(); final Path file = resourceElement.getFile(); final Path relativeFile = file.subpath(prevFile.getNameCount(), file.getNameCount()); final Path resultFile = newFile.resolve(relativeFile); child.setValue(ResourceElementFactory.createFor(resultFile)); }); final ObservableList<TreeItem<ResourceElement>> newParentChildren = newParentItem.getChildren(); newParentChildren.add(prevItem); FXCollections.sort(newParentChildren, ITEM_COMPARATOR); } /** * Уведомление о переименовании файла. * * @param prevFile старая версия файла. * @param newFile новая версия файла. */ public void notifyRenamed(final Path prevFile, final Path newFile) { final ResourceElement prevElement = ResourceElementFactory.createFor(prevFile); final TreeItem<ResourceElement> prevItem = UIUtils.findItemForValue(getRoot(), prevElement); if (prevItem == null) { return; } prevItem.setValue(ResourceElementFactory.createFor(newFile)); final Array<TreeItem<ResourceElement>> children = ArrayFactory.newArray(TreeItem.class); UIUtils.getAllItems(children, prevItem); children.fastRemove(prevItem); children.forEach(child -> { final ResourceElement resourceElement = child.getValue(); final Path file = resourceElement.getFile(); final Path relativeFile = file.subpath(prevFile.getNameCount(), file.getNameCount()); final Path resultFile = newFile.resolve(relativeFile); child.setValue(ResourceElementFactory.createFor(resultFile)); }); } /** * Обработка нажатий на хоткеи. */ private void processKey(final KeyEvent event) { if (isReadOnly()) { return; } final MultipleSelectionModel<TreeItem<ResourceElement>> selectionModel = getSelectionModel(); final TreeItem<ResourceElement> selectedItem = selectionModel.getSelectedItem(); if (selectedItem == null) { return; } final ResourceElement item = selectedItem.getValue(); if (item == null || item instanceof ResourceLoadingElement) { return; } final EditorConfig editorConfig = EditorConfig.getInstance(); final Path currentAsset = editorConfig.getCurrentAsset(); final KeyCode keyCode = event.getCode(); if (event.isControlDown() && keyCode == KeyCode.C && !currentAsset.equals(item.getFile())) { final CopyFileAction action = new CopyFileAction(item); final EventHandler<ActionEvent> onAction = action.getOnAction(); onAction.handle(null); } else if (event.isControlDown() && keyCode == KeyCode.X && !currentAsset.equals(item.getFile())) { final CutFileAction action = new CutFileAction(item); final EventHandler<ActionEvent> onAction = action.getOnAction(); onAction.handle(null); } else if (event.isControlDown() && keyCode == KeyCode.V && EditorUtil.hasFileInClipboard()) { final PasteFileAction action = new PasteFileAction(item); final EventHandler<ActionEvent> onAction = action.getOnAction(); onAction.handle(null); } else if(keyCode == KeyCode.DELETE && !currentAsset.equals(item.getFile())) { final DeleteFileAction action = new DeleteFileAction(item); final EventHandler<ActionEvent> onAction = action.getOnAction(); onAction.handle(null); } } /** * @return функция окрытия файла. */ public Consumer<ResourceElement> getOpenFunction() { return openFunction; } /** * Очистка дерева от пустых узлов. */ public boolean cleanup(final TreeItem<ResourceElement> treeItem) { final ResourceElement element = treeItem.getValue(); if (element instanceof FileElement) { return false; } final ObservableList<TreeItem<ResourceElement>> children = treeItem.getChildren(); for (int i = children.size() - 1; i >= 0; i--) { cleanup(children.get(i)); } if (children.isEmpty() && treeItem.getParent() != null) { final TreeItem<ResourceElement> parent = treeItem.getParent(); final ObservableList<TreeItem<ResourceElement>> parentChildren = parent.getChildren(); parentChildren.remove(treeItem); return true; } return false; } /** * Развернуть девео до указанного файла. */ public void expandTo(final Path file, boolean needSelect) { final ResourceElement element = ResourceElementFactory.createFor(file); final TreeItem<ResourceElement> treeItem = UIUtils.findItemForValue(getRoot(), element); if (treeItem == null) { return; } TreeItem<ResourceElement> parent = treeItem; while (parent != null) { parent.setExpanded(true); parent = parent.getParent(); } if (needSelect) { EXECUTOR_MANAGER.addFXTask(() -> { final MultipleSelectionModel<TreeItem<ResourceElement>> selectionModel = getSelectionModel(); selectionModel.select(treeItem); scrollTo(getRow(treeItem)); }); } } }
src/com/ss/editor/ui/component/asset/tree/ResourceTree.java
package com.ss.editor.ui.component.asset.tree; import com.ss.editor.config.EditorConfig; import com.ss.editor.file.converter.FileConverterDescription; import com.ss.editor.file.converter.FileConverterRegistry; import com.ss.editor.manager.ExecutorManager; import com.ss.editor.ui.component.asset.tree.context.menu.action.ConvertFileAction; import com.ss.editor.ui.component.asset.tree.context.menu.action.CopyFileAction; import com.ss.editor.ui.component.asset.tree.context.menu.action.CutFileAction; import com.ss.editor.ui.component.asset.tree.context.menu.action.DeleteFileAction; import com.ss.editor.ui.component.asset.tree.context.menu.action.NewFileAction; import com.ss.editor.ui.component.asset.tree.context.menu.action.OpenFileAction; import com.ss.editor.ui.component.asset.tree.context.menu.action.OpenFileByExternalEditorAction; import com.ss.editor.ui.component.asset.tree.context.menu.action.OpenWithFileAction; import com.ss.editor.ui.component.asset.tree.context.menu.action.PasteFileAction; import com.ss.editor.ui.component.asset.tree.context.menu.action.RenameFileAction; import com.ss.editor.ui.component.asset.tree.resource.FileElement; import com.ss.editor.ui.component.asset.tree.resource.FolderElement; import com.ss.editor.ui.component.asset.tree.resource.ResourceElement; import com.ss.editor.ui.component.asset.tree.resource.ResourceElementFactory; import com.ss.editor.ui.component.asset.tree.resource.ResourceLoadingElement; import com.ss.editor.ui.css.CSSClasses; import com.ss.editor.ui.util.UIUtils; import com.ss.editor.util.EditorUtil; import java.nio.file.Path; import java.util.function.Consumer; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.control.ContextMenu; import javafx.scene.control.MenuItem; import javafx.scene.control.MultipleSelectionModel; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeView; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import rlib.ui.util.FXUtils; import rlib.util.StringUtils; import rlib.util.array.Array; import rlib.util.array.ArrayComparator; import rlib.util.array.ArrayFactory; import static com.ss.editor.ui.component.asset.tree.ResourceTreeCell.CELL_FACTORY; import static com.ss.editor.ui.component.asset.tree.resource.ResourceElementFactory.createFor; import static com.ss.editor.ui.css.CSSClasses.MAIN_FONT_13; import static com.ss.editor.ui.util.UIUtils.findItemForValue; /** * Реализация дерева ресурсов. * * @author Ronn */ public class ResourceTree extends TreeView<ResourceElement> { private static final FileConverterRegistry FILE_CONVERTER_REGISTRY = FileConverterRegistry.getInstance(); private static final ExecutorManager EXECUTOR_MANAGER = ExecutorManager.getInstance(); private static final ArrayComparator<ResourceElement> COMPARATOR = ResourceElement::compareTo; private static final ArrayComparator<ResourceElement> NAME_COMPARATOR = (first, second) -> { final int firstLevel = getLevel(first); final int secondLevel = getLevel(second); if (firstLevel != secondLevel) { return firstLevel - secondLevel; } final Path firstFile = first.getFile(); final String firstName = firstFile.getFileName().toString(); final Path secondFile = second.getFile(); final String secondName = secondFile.getFileName().toString(); return StringUtils.compareIgnoreCase(firstName, secondName); }; private static final ArrayComparator<TreeItem<ResourceElement>> ITEM_COMPARATOR = (first, second) -> { final ResourceElement firstElement = first.getValue(); final ResourceElement secondElement = second.getValue(); final int firstLevel = getLevel(firstElement); final int secondLevel = getLevel(secondElement); if (firstLevel != secondLevel) { return firstLevel - secondLevel; } return NAME_COMPARATOR.compare(firstElement, secondElement); }; private static int getLevel(final ResourceElement element) { if (element instanceof FolderElement) { return 1; } return 2; } private static final Consumer<ResourceElement> DEFAULT_FUNCTION = element -> { final OpenFileAction action = new OpenFileAction(element); final EventHandler<ActionEvent> onAction = action.getOnAction(); onAction.handle(null); }; /** * Развернутые элементы. */ private final Array<ResourceElement> expandedElements; /** * Выбранные элементы. */ private final Array<ResourceElement> selectedElements; /** * Функция окрытия файла. */ private final Consumer<ResourceElement> openFunction; /** * Режим только чтения. */ private final boolean readOnly; /** * Список фильтруемых расширений. */ private Array<String> extensionFilter; /** * Пост загрузачный обработчик. */ private Runnable onLoadHandler; public ResourceTree(final boolean readOnly) { this(DEFAULT_FUNCTION, readOnly); } public ResourceTree(final Consumer<ResourceElement> openFunction, final boolean readOnly) { this.openFunction = openFunction; this.readOnly = readOnly; this.expandedElements = ArrayFactory.newConcurrentAtomicArray(ResourceElement.class); this.selectedElements = ArrayFactory.newConcurrentAtomicArray(ResourceElement.class); FXUtils.addClassTo(this, CSSClasses.TRANSPARENT_TREE_VIEW); setCellFactory(CELL_FACTORY); setOnKeyPressed(this::processKey); setShowRoot(true); setContextMenu(new ContextMenu()); } /** * @param extensionFilter список фильтруемых расширений. */ public void setExtensionFilter(Array<String> extensionFilter) { this.extensionFilter = extensionFilter; } /** * @return список фильтруемых расширений. */ private Array<String> getExtensionFilter() { return extensionFilter; } /** * @param onLoadHandler пост загрузачный обработчик. */ public void setOnLoadHandler(Runnable onLoadHandler) { this.onLoadHandler = onLoadHandler; } /** * @return пост загрузачныый обработчик. */ private Runnable getOnLoadHandler() { return onLoadHandler; } /** * @return режим только чтения. */ private boolean isReadOnly() { return readOnly; } /** * Обновление контекстного меню под указанный элемент. */ public void updateContextMenu(final ResourceElement element) { if (isReadOnly()) { return; } final EditorConfig editorConfig = EditorConfig.getInstance(); final Path currentAsset = editorConfig.getCurrentAsset(); final ContextMenu contextMenu = getContextMenu(); final ObservableList<MenuItem> items = contextMenu.getItems(); items.clear(); final Path file = element.getFile(); items.add(new NewFileAction(element)); if (element instanceof FileElement) { items.add(new OpenFileAction(element)); items.add(new OpenFileByExternalEditorAction(element)); items.add(new OpenWithFileAction(element)); final Array<FileConverterDescription> descriptions = FILE_CONVERTER_REGISTRY.getDescriptions(file); if (!descriptions.isEmpty()) { items.add(new ConvertFileAction(element, descriptions)); } } if (EditorUtil.hasFileInClipboard()) { items.add(new PasteFileAction(element)); } if (!currentAsset.equals(file)) { items.add(new CopyFileAction(element)); items.add(new CutFileAction(element)); items.add(new RenameFileAction(element)); items.add(new DeleteFileAction(element)); } final Array<MenuItem> allItems = ArrayFactory.newArray(MenuItem.class); items.forEach(subItem -> UIUtils.getAllItems(allItems, subItem)); allItems.forEach(menuItem -> FXUtils.addClassTo(menuItem, MAIN_FONT_13)); setContextMenu(contextMenu); } /** * Заполнить дерево по новой папке асета. * * @param assetFolder новая папка ассета. */ public void fill(final Path assetFolder) { final TreeItem<ResourceElement> currentRoot = getRoot(); if (currentRoot != null) { setRoot(null); } showLoading(); EXECUTOR_MANAGER.addBackgroundTask(() -> startBackgroundFill(assetFolder)); } /** * @return развернутые элементы. */ public Array<ResourceElement> getExpandedElements() { return expandedElements; } /** * @return выбранные элементы. */ public Array<ResourceElement> getSelectedElements() { return selectedElements; } /** * Обновить дерево. */ public void refresh() { final EditorConfig config = EditorConfig.getInstance(); final Path currentAsset = config.getCurrentAsset(); if (currentAsset == null) { setRoot(null); return; } updateSelectedElements(); updateExpandedElements(); setRoot(null); showLoading(); EXECUTOR_MANAGER.addBackgroundTask(() -> startBackgroundRefresh(currentAsset)); } /** * Обновление развернутых элементов. */ private void updateExpandedElements() { final Array<ResourceElement> expandedElements = getExpandedElements(); expandedElements.writeLock(); try { expandedElements.clear(); final Array<TreeItem<ResourceElement>> allItems = UIUtils.getAllItems(this); allItems.forEach(item -> { if (!item.isExpanded()) { return; } expandedElements.add(item.getValue()); }); } finally { expandedElements.writeUnlock(); } } /** * Обновление списка выбранных элементов. */ private void updateSelectedElements() { final Array<ResourceElement> selectedElements = getSelectedElements(); selectedElements.writeLock(); try { selectedElements.clear(); final MultipleSelectionModel<TreeItem<ResourceElement>> selectionModel = getSelectionModel(); final ObservableList<TreeItem<ResourceElement>> selectedItems = selectionModel.getSelectedItems(); selectedItems.forEach(item -> selectedElements.add(item.getValue())); } finally { selectedElements.writeUnlock(); } } /** * Отобразить прогресс прогрузки. */ private void showLoading() { setRoot(new TreeItem<>(ResourceLoadingElement.getInstance())); } /** * Запустить фоновое построение дерева. */ private void startBackgroundFill(final Path assetFolder) { final ResourceElement rootElement = createFor(assetFolder); final TreeItem<ResourceElement> newRoot = new TreeItem<>(rootElement); newRoot.setExpanded(true); fill(newRoot); final Array<String> extensionFilter = getExtensionFilter(); if (extensionFilter != null) { cleanup(newRoot); } EXECUTOR_MANAGER.addFXTask(() -> { setRoot(newRoot); final Runnable onLoadHandler = getOnLoadHandler(); if (onLoadHandler != null) { onLoadHandler.run(); } }); } /** * Запустить фоновое обновление дерева. */ private void startBackgroundRefresh(final Path assetFolder) { final ResourceElement rootElement = createFor(assetFolder); final TreeItem<ResourceElement> newRoot = new TreeItem<>(rootElement); newRoot.setExpanded(true); fill(newRoot); final Array<ResourceElement> expandedElements = getExpandedElements(); expandedElements.writeLock(); try { expandedElements.sort(COMPARATOR); expandedElements.forEach(element -> { final TreeItem<ResourceElement> item = findItemForValue(newRoot, element); if (item == null) { return; } item.setExpanded(true); }); expandedElements.clear(); } finally { expandedElements.writeUnlock(); } EXECUTOR_MANAGER.addFXTask(() -> { setRoot(newRoot); restoreSelection(); final Runnable onLoadHandler = getOnLoadHandler(); if (onLoadHandler != null) { onLoadHandler.run(); } }); } /** * Восстановление выбранных элементов. */ private void restoreSelection() { EXECUTOR_MANAGER.addFXTask(() -> { final Array<ResourceElement> selectedElements = getSelectedElements(); selectedElements.writeLock(); try { final MultipleSelectionModel<TreeItem<ResourceElement>> selectionModel = getSelectionModel(); selectedElements.forEach(element -> { final TreeItem<ResourceElement> item = findItemForValue(getRoot(), element); if (item == null) { return; } selectionModel.select(item); }); selectedElements.clear(); } finally { selectedElements.writeUnlock(); } }); } /** * Заполнить узел. */ private void fill(final TreeItem<ResourceElement> treeItem) { final ResourceElement element = treeItem.getValue(); final Array<String> extensionFilter = getExtensionFilter(); if (!element.hasChildren(extensionFilter)) { return; } final ObservableList<TreeItem<ResourceElement>> items = treeItem.getChildren(); final Array<ResourceElement> children = element.getChildren(extensionFilter); children.sort(NAME_COMPARATOR); children.forEach(child -> items.add(new TreeItem<>(child))); items.forEach(this::fill); } /** * Уведомление о созданном файле. * * @param file созданный файл. */ public void notifyCreated(final Path file) { final EditorConfig editorConfig = EditorConfig.getInstance(); final Path currentAsset = editorConfig.getCurrentAsset(); final Path folder = file.getParent(); if (!folder.startsWith(currentAsset)) { return; } final ResourceElement element = ResourceElementFactory.createFor(folder); TreeItem<ResourceElement> folderItem = UIUtils.findItemForValue(getRoot(), element); if (folderItem == null) { notifyCreated(folder); folderItem = UIUtils.findItemForValue(getRoot(), folder); } if (folderItem == null) { return; } final TreeItem<ResourceElement> newItem = new TreeItem<>(ResourceElementFactory.createFor(file)); fill(newItem); final ObservableList<TreeItem<ResourceElement>> children = folderItem.getChildren(); children.add(newItem); FXCollections.sort(children, ITEM_COMPARATOR); } /** * Уведомление об удаленном файле. */ public void notifyDeleted(final Path file) { final ResourceElement element = ResourceElementFactory.createFor(file); final TreeItem<ResourceElement> treeItem = UIUtils.findItemForValue(getRoot(), element); if (treeItem == null) { return; } final TreeItem<ResourceElement> parent = treeItem.getParent(); if (parent == null) { return; } final ObservableList<TreeItem<ResourceElement>> children = parent.getChildren(); children.remove(treeItem); } /** * Уведомление о перемещении файла. * * @param prevFile старая версия файла. * @param newFile новая версия файла. */ public void notifyMoved(final Path prevFile, final Path newFile) { final ResourceElement prevElement = ResourceElementFactory.createFor(prevFile); final TreeItem<ResourceElement> prevItem = UIUtils.findItemForValue(getRoot(), prevElement); if (prevItem == null) { return; } final ResourceElement newParentElement = ResourceElementFactory.createFor(newFile.getParent()); final TreeItem<ResourceElement> newParentItem = UIUtils.findItemForValue(getRoot(), newParentElement); if (newParentItem == null) { return; } final TreeItem<ResourceElement> prevParentItem = prevItem.getParent(); final ObservableList<TreeItem<ResourceElement>> prevParentChildren = prevParentItem.getChildren(); prevParentChildren.remove(prevItem); prevItem.setValue(ResourceElementFactory.createFor(newFile)); final Array<TreeItem<ResourceElement>> children = ArrayFactory.newArray(TreeItem.class); UIUtils.getAllItems(children, prevItem); children.fastRemove(prevItem); children.forEach(child -> { final ResourceElement resourceElement = child.getValue(); final Path file = resourceElement.getFile(); final Path relativeFile = file.subpath(prevFile.getNameCount(), file.getNameCount()); final Path resultFile = newFile.resolve(relativeFile); child.setValue(ResourceElementFactory.createFor(resultFile)); }); final ObservableList<TreeItem<ResourceElement>> newParentChildren = newParentItem.getChildren(); newParentChildren.add(prevItem); FXCollections.sort(newParentChildren, ITEM_COMPARATOR); } /** * Уведомление о переименовании файла. * * @param prevFile старая версия файла. * @param newFile новая версия файла. */ public void notifyRenamed(final Path prevFile, final Path newFile) { final ResourceElement prevElement = ResourceElementFactory.createFor(prevFile); final TreeItem<ResourceElement> prevItem = UIUtils.findItemForValue(getRoot(), prevElement); if (prevItem == null) { return; } prevItem.setValue(ResourceElementFactory.createFor(newFile)); final Array<TreeItem<ResourceElement>> children = ArrayFactory.newArray(TreeItem.class); UIUtils.getAllItems(children, prevItem); children.fastRemove(prevItem); children.forEach(child -> { final ResourceElement resourceElement = child.getValue(); final Path file = resourceElement.getFile(); final Path relativeFile = file.subpath(prevFile.getNameCount(), file.getNameCount()); final Path resultFile = newFile.resolve(relativeFile); child.setValue(ResourceElementFactory.createFor(resultFile)); }); } /** * Обработка нажатий на хоткеи. */ private void processKey(final KeyEvent event) { if (isReadOnly()) { return; } final MultipleSelectionModel<TreeItem<ResourceElement>> selectionModel = getSelectionModel(); final TreeItem<ResourceElement> selectedItem = selectionModel.getSelectedItem(); if (selectedItem == null) { return; } final ResourceElement item = selectedItem.getValue(); if (item == null || item instanceof ResourceLoadingElement || !event.isControlDown()) { return; } final KeyCode keyCode = event.getCode(); if (keyCode == KeyCode.C) { final CopyFileAction action = new CopyFileAction(item); final EventHandler<ActionEvent> onAction = action.getOnAction(); onAction.handle(null); } else if (keyCode == KeyCode.X) { final CutFileAction action = new CutFileAction(item); final EventHandler<ActionEvent> onAction = action.getOnAction(); onAction.handle(null); } else if (keyCode == KeyCode.V && EditorUtil.hasFileInClipboard()) { final PasteFileAction action = new PasteFileAction(item); final EventHandler<ActionEvent> onAction = action.getOnAction(); onAction.handle(null); } } /** * @return функция окрытия файла. */ public Consumer<ResourceElement> getOpenFunction() { return openFunction; } /** * Очистка дерева от пустых узлов. */ public boolean cleanup(final TreeItem<ResourceElement> treeItem) { final ResourceElement element = treeItem.getValue(); if (element instanceof FileElement) { return false; } final ObservableList<TreeItem<ResourceElement>> children = treeItem.getChildren(); for (int i = children.size() - 1; i >= 0; i--) { cleanup(children.get(i)); } if (children.isEmpty() && treeItem.getParent() != null) { final TreeItem<ResourceElement> parent = treeItem.getParent(); final ObservableList<TreeItem<ResourceElement>> parentChildren = parent.getChildren(); parentChildren.remove(treeItem); return true; } return false; } /** * Развернуть девео до указанного файла. */ public void expandTo(final Path file, boolean needSelect) { final ResourceElement element = ResourceElementFactory.createFor(file); final TreeItem<ResourceElement> treeItem = UIUtils.findItemForValue(getRoot(), element); if (treeItem == null) { return; } TreeItem<ResourceElement> parent = treeItem; while (parent != null) { parent.setExpanded(true); parent = parent.getParent(); } if (needSelect) { EXECUTOR_MANAGER.addFXTask(() -> { final MultipleSelectionModel<TreeItem<ResourceElement>> selectionModel = getSelectionModel(); selectionModel.select(treeItem); scrollTo(getRow(treeItem)); }); } } }
добавление хоткея на удаления файлов
src/com/ss/editor/ui/component/asset/tree/ResourceTree.java
добавление хоткея на удаления файлов
Java
bsd-3-clause
d2a14341e2ba2f2835cc3c4123a327351e41fe49
0
axiastudio/zoefx-core
package com.axiastudio.zoefx.core.controller; import com.axiastudio.zoefx.core.beans.BeanAccess; import com.axiastudio.zoefx.core.beans.BeanClassAccess; import com.axiastudio.zoefx.core.beans.property.ItemObjectProperty; import com.axiastudio.zoefx.core.beans.property.ZoeFXProperty; import com.axiastudio.zoefx.core.db.TimeMachine; import com.axiastudio.zoefx.core.events.DataSetEvent; import com.axiastudio.zoefx.core.events.DataSetEventListener; import com.axiastudio.zoefx.core.db.DataSet; import com.axiastudio.zoefx.core.view.*; import com.axiastudio.zoefx.core.console.ConsoleController; import com.axiastudio.zoefx.core.view.search.SearchController; import javafx.beans.*; import javafx.beans.Observable; import javafx.beans.binding.Bindings; import javafx.beans.property.Property; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXMLLoader; import javafx.fxml.JavaFXBuilderFactory; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.Pane; import javafx.stage.Stage; import javafx.util.Callback; import java.io.IOException; import java.net.URL; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; /** * User: tiziano * Date: 20/03/14 * Time: 23:04 */ public class FXController extends BaseController implements DataSetEventListener { private Scene scene; private DataSet dataset = null; private ZSceneMode mode; private Behavior behavior = null; private TimeMachine timeMachine = null; private Map<String, Property> fxProperties = new HashMap<>(); private Map<String,TableView> tableViews; @Override public void initialize(URL url, ResourceBundle resourceBundle) { } public void setScene(Scene scene){ this.scene = scene; } protected Scene getScene() { return scene; } public void bindDataSet(DataSet dataset){ this.dataset = dataset; if( dataset.size()== 0 ){ dataset.create(); } Model model = dataset.newModel(); scanFXProperties(); initializeChoices(); initializeColumns(); // first show setModel(model); timeMachine.createSnapshot(fxProperties.values()); } private void initializeColumns(){ Model model = dataset.getCurrentModel(); Parent root = this.scene.getRoot(); Pane container = (Pane) root; List<Node> nodes = findNodes(container, new ArrayList<Node>()); tableViews = new HashMap<>(); for( Node node: nodes ){ if( node instanceof TableView){ TableView tableView = (TableView) node; tableViews.put(node.getId(), tableView); ObservableList<TableColumn> columns = tableView.getColumns(); for( TableColumn column: columns ){ String name = node.getId(); //String columnId = column.getId(); String columnId = column.getText().toLowerCase(); // XXX: RT-36633 JavaXFX issue // https://javafx-jira.kenai.com/browse/RT-36633 String lookup=null; if( behavior != null ) { lookup = behavior.getProperties().getProperty(columnId + ".lookup"); } if( lookup != null ) { Callback callback = model.getCallback(name, columnId, lookup); column.setCellValueFactory(callback); } else { Callback callback = model.getCallback(name, columnId); column.setCellValueFactory(callback); } // custom date order BeanClassAccess beanClassAccess = new BeanClassAccess(model.getEntityClass(), columnId); if( beanClassAccess.getReturnType() != null && Date.class.isAssignableFrom(beanClassAccess.getReturnType()) ) { column.setComparator(Comparator.nullsFirst(Comparators.DateComparator)); } //tableView.getItems().addListener(listChangeListener); } } } } private void initializeChoices(){ Model model = dataset.getCurrentModel(); Parent root = this.scene.getRoot(); Pane container = (Pane) root; List<Node> nodes = findNodes(container, new ArrayList<Node>()); for( Node node: nodes ){ if( node instanceof ChoiceBox){ String name = node.getId(); Property property = model.getProperty(name, Object.class); List superset = ((ItemObjectProperty) property).getSuperset(); ObservableList choices = FXCollections.observableArrayList(superset); ((ChoiceBox) node).setItems(choices); } } } private void unsetModel() { Model model = dataset.getCurrentModel(); for( String name: fxProperties.keySet() ){ Property fxProperty = fxProperties.get(name); ZoeFXProperty zoeFXProperty = model.getProperty(name); if( fxProperty != null && zoeFXProperty != null ) { Bindings.unbindBidirectional(fxProperty, zoeFXProperty); fxProperty.removeListener(invalidationListener); } } } private void setModel() { setModel(dataset.newModel()); } private void setModel(Model model) { for( String name: fxProperties.keySet() ){ Property fxProperty = fxProperties.get(name); ZoeFXProperty zoeFXProperty = model.getProperty(name); if( zoeFXProperty == null ){ Node node = scene.lookup("#"+name); if( node instanceof TextField ){ zoeFXProperty = model.getProperty(name, String.class); } else if( node instanceof TextArea ){ zoeFXProperty = model.getProperty(name, String.class); } else if( node instanceof Label ){ zoeFXProperty = model.getProperty(name, String.class); } else if( node instanceof CheckBox ){ zoeFXProperty = model.getProperty(name, Boolean.class); } else if( node instanceof ChoiceBox ){ zoeFXProperty = model.getProperty(name, Object.class); } else if( node instanceof DatePicker ){ zoeFXProperty = model.getProperty(name, Date.class); } else if( node instanceof TableView ){ zoeFXProperty = model.getProperty(name, Collection.class); } } if( fxProperty != null && zoeFXProperty != null ) { Bindings.bindBidirectional(fxProperty, zoeFXProperty); fxProperty.addListener(invalidationListener); } } //updateCache(); } private void scanFXProperties(){ Parent root = scene.getRoot(); Pane container = (Pane) root; List<Node> nodes = findNodes(container, new ArrayList<>()); for( Node node: nodes ){ String name = node.getId(); Property property = null; if( node instanceof TextField ){ property = ((TextField) node).textProperty(); } else if( node instanceof TextArea ){ property = ((TextArea) node).textProperty(); } else if( node instanceof Label ){ property = ((Label) node).textProperty(); } else if( node instanceof CheckBox ){ property = ((CheckBox) node).selectedProperty(); } else if( node instanceof ChoiceBox ){ property = ((ChoiceBox) node).valueProperty(); } else if( node instanceof DatePicker ){ property = ((DatePicker) node).valueProperty(); } else if( node instanceof TableView ){ TableView tableView = (TableView) node; tableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); tableView.setContextMenu(createContextMenu(tableView)); property = tableView.itemsProperty(); } if( property != null ){ fxProperties.put(name, property); } } /* Validator validator = Validators.getValidator(model.getEntityClass(), name); if( validator != null ) { fxProperty.addListener(new TextFieldListener(validator)); } */ } private ContextMenu createContextMenu(TableView tableView){ ContextMenu contextMenu = new ContextMenu(); MenuItem infoItem = new MenuItem("Information"); infoItem.setGraphic(new ImageView(new Image(getClass().getResourceAsStream("/com/axiastudio/zoefx/core/resources/images/info.png")))); infoItem.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { ObservableList selectedItems = tableView.getSelectionModel().getSelectedItems(); if( selectedItems.size()==0 ) { return; } List<Object> newStore = new ArrayList<>(); for( int i=0; i<selectedItems.size(); i++ ) { newStore.add(selectedItems.get(i)); } ZScene newScene = SceneBuilders.queryZScene(newStore, ZSceneMode.DIALOG); if( newScene != null ) { Stage newStage = new Stage(); newStage.setScene(newScene.getScene()); newStage.show(); newStage.requestFocus(); } dataset.getDirty(); /// XXX: to implement a callback? } }); MenuItem openItem = new MenuItem("Open"); openItem.setGraphic(new ImageView(new Image(getClass().getResourceAsStream("/com/axiastudio/zoefx/core/resources/images/open.png")))); openItem.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { ObservableList selectedItems = tableView.getSelectionModel().getSelectedItems(); if (selectedItems.size() == 0) { return; } List<Object> newStore = new ArrayList<>(); String referenceProperty = tableView.getId() + ".reference"; String reference = behavior.getProperties().getProperty(referenceProperty, null); for (int i = 0; i < selectedItems.size(); i++) { Object item = selectedItems.get(i); if (reference != null) { BeanAccess<Object> ba = new BeanAccess<>(item, reference); newStore.add(ba.getValue()); } else { newStore.add(item); } } ZScene newScene = SceneBuilders.queryZScene(newStore, ZSceneMode.WINDOW); if (newScene != null) { Stage newStage = new Stage(); newStage.setScene(newScene.getScene()); newStage.show(); newStage.requestFocus(); } dataset.getDirty(); /// XXX: to implement a callback? } }); MenuItem addItem = new MenuItem("Add"); addItem.setGraphic(new ImageView(new Image(getClass().getResourceAsStream("/com/axiastudio/zoefx/core/resources/images/add.png")))); addItem.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { final String collectionName = tableView.getId(); String referenceProperty = collectionName + ".reference"; String searchcolumnsProperty = collectionName + ".searchcolumns"; String referenceName = behavior.getProperties().getProperty(referenceProperty, null); String searchcolumns = behavior.getProperties().getProperty(searchcolumnsProperty, "caption"); // XXX: default caption? if (referenceName != null) { Class classToSearch = null; try { Class parentEntityClass = dataset.getCurrentModel().getEntityClass(); Class<?> collectionGenericReturnType = (new BeanClassAccess(parentEntityClass, collectionName)).getGenericReturnType(); Class<?> referenceReturnType = (new BeanClassAccess(collectionGenericReturnType, referenceName)).getReturnType(); String className = referenceReturnType.getName(); classToSearch = Class.forName(className); Callback callback = new Callback<List, Boolean>() { @Override public Boolean call(List items) { for( Object item: items ){ Object entity = dataset.create(collectionName); BeanAccess<Object> ba = new BeanAccess<>(entity, referenceName); ba.setValue(item); refresh(); } return true; } }; Stage stage = searchStage(classToSearch, searchcolumns, callback); stage.show(); } catch (ClassNotFoundException e1) { e1.printStackTrace(); } } else { Object entity = dataset.create(collectionName); List<Object> newStore = new ArrayList<>(); newStore.add(entity); ZScene newScene = SceneBuilders.queryZScene(newStore, ZSceneMode.DIALOG); if (newScene != null) { Stage newStage = new Stage(); newStage.setScene(newScene.getScene()); newStage.show(); newStage.requestFocus(); } } //initializeColumns(); dataset.getDirty(); /// XXX: to implement a callback? } }); MenuItem delItem = new MenuItem("Delete"); delItem.setGraphic(new ImageView(new Image(getClass().getResourceAsStream("/com/axiastudio/zoefx/core/resources/images/delete.png")))); delItem.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { //System.out.println("Delete!"); } }); contextMenu.getItems().addAll(infoItem, openItem, addItem, delItem); return contextMenu; } private List<Node> findNodes( Pane container, List<Node> nodes ){ for( Node node: container.getChildren() ){ if( node instanceof Pane ){ nodes = findNodes((Pane) node, nodes); } else if( node instanceof TabPane ){ for( Tab tab: ((TabPane) node).getTabs() ) { nodes = findNodes((Pane) tab.getContent(), nodes); } } else if( node.getId() != null && node.getId() != "" ){ nodes.add(node); } } return nodes; } public DataSet getDataset() { return dataset; } public Model getCurrentModel() { return dataset.getCurrentModel(); } private FXController self(){ return this; } public ZSceneMode getMode() { return mode; } public void setMode(ZSceneMode mode) { this.mode = mode; } public void setBehavior(Behavior behavior) { this.behavior = behavior; } public void setTimeMachine(TimeMachine timeMachine) { this.timeMachine = timeMachine; } public void refresh(){ unsetModel(); Model model = dataset.newModel(); setModel(model); timeMachine.resetAndcreateSnapshot(fxProperties.values()); for( TableView tableView: tableViews.values() ){ // XXX: workaround for https://javafx-jira.kenai.com/browse/RT-22599 ObservableList items = tableView.getItems(); tableView.itemsProperty().removeListener(invalidationListener); tableView.setItems(null); tableView.layout(); tableView.setItems(items); tableView.itemsProperty().addListener(invalidationListener); } } private Stage searchStage(Class classToSearch, String searchcolumns, Callback callback) { return searchStage(classToSearch, searchcolumns, callback, null); } private Stage searchStage(Class classToSearch, String searchcolumns, Callback callback, String searchcriteria) { URL url = getClass().getResource("/com/axiastudio/zoefx/core/view/search/search.fxml"); FXMLLoader loader = new FXMLLoader(); loader.setLocation(url); loader.setBuilderFactory(new JavaFXBuilderFactory()); Parent root = null; try { root = loader.load(url.openStream()); } catch (IOException e1) { e1.printStackTrace(); } // search columns SearchController controller = loader.getController(); controller.setEntityClass(classToSearch); List<String> columns = new ArrayList<>(); if( searchcolumns != null ){ String[] split = searchcolumns.split(","); for( int i=0; i<split.length; i++ ){ columns.add(split[i]); } } controller.setColumns(columns); // search criteria List<String> criteria = new ArrayList<>(); if( searchcriteria != null ){ String[] split = searchcriteria.split(","); for( int i=0; i<split.length; i++ ){ criteria.add(split[i]); } } controller.setCriteria(criteria); // callback controller.setCallback(callback); //controller.setParentDataSet(dataset); Stage stage = new Stage(); stage.setTitle("Search"); stage.setScene(new Scene(root, 450, 450)); return stage; } /* * Navigation Bar */ public EventHandler<ActionEvent> handlerGoFirst = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { unsetModel(); dataset.goFirst(); setModel(dataset.newModel()); timeMachine.resetAndcreateSnapshot(fxProperties.values()); } }; public EventHandler<ActionEvent> handlerGoPrevious = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { unsetModel(); dataset.goPrevious(); setModel(dataset.newModel()); timeMachine.resetAndcreateSnapshot(fxProperties.values()); } }; public EventHandler<ActionEvent> handlerGoNext = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { unsetModel(); dataset.goNext(); setModel(dataset.newModel()); timeMachine.resetAndcreateSnapshot(fxProperties.values()); } }; public EventHandler<ActionEvent> handlerGoLast = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { unsetModel(); dataset.goLast(); setModel(dataset.newModel()); timeMachine.resetAndcreateSnapshot(fxProperties.values()); } }; public EventHandler<ActionEvent> handlerSave = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { dataset.commit(); timeMachine.resetAndcreateSnapshot(fxProperties.values()); } }; public EventHandler<ActionEvent> handlerConfirm = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { ((Stage) scene.getWindow()).close(); // TODO: get the parent dirty } }; public EventHandler<ActionEvent> handlerCancel = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { timeMachine.rollback(); dataset.revert(); timeMachine.resetAndcreateSnapshot(fxProperties.values()); } }; public EventHandler<ActionEvent> handlerAdd = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { dataset.create(); unsetModel(); setModel(dataset.newModel()); } }; public EventHandler<ActionEvent> handlerSearch = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { Class classToSearch = dataset.getCurrentModel().getEntityClass(); String searchcolumns = behavior.getProperties().getProperty("searchcolumns"); String searchcriteria = behavior.getProperties().getProperty("searchcriteria"); Callback callback = new Callback<List, Boolean>() { @Override public Boolean call(List items) { List store = new ArrayList(); for( Object item: items ){ store.add(item); } dataset.setStore(store); return true; } }; Stage stage = searchStage(classToSearch, searchcolumns, callback, searchcriteria); stage.show(); } }; public EventHandler<ActionEvent> handlerDelete = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { dataset.delete(); unsetModel(); setModel(dataset.newModel()); } }; public EventHandler<ActionEvent> handlerRefresh = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { refresh(); } }; public EventHandler<ActionEvent> handlerConsole = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { URL url = getClass().getResource("/com/axiastudio/zoefx/core/console/console.fxml"); FXMLLoader loader = new FXMLLoader(); loader.setLocation(url); loader.setBuilderFactory(new JavaFXBuilderFactory()); Parent root = null; try { root = loader.load(url.openStream()); } catch (IOException e1) { e1.printStackTrace(); } ConsoleController console = loader.getController(); console.setController(self()); Stage stage = new Stage(); stage.setTitle("Zoe FX Script Console"); stage.setScene(new Scene(root, 450, 450)); stage.show(); } }; public EventHandler<ActionEvent> handlerInfo = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { //System.out.println("Info"); } }; /* * Listeners */ public InvalidationListener invalidationListener = new InvalidationListener() { @Override public void invalidated(Observable observable) { dataset.getDirty(); } }; @Override public void dataSetEventHandler(DataSetEvent event) { //System.out.println(event.getEventType()); Logger.getLogger(this.getClass().getName()).log(Level.FINE, "{0} event handled", event.getEventType().getName()); if( event.getEventType().equals(DataSetEvent.STORE_CHANGED) ){ unsetModel(); setModel(); } else if( event.getEventType().equals(DataSetEvent.ROWS_CREATED) ){ refresh(); } } }
src/com/axiastudio/zoefx/core/controller/FXController.java
package com.axiastudio.zoefx.core.controller; import com.axiastudio.zoefx.core.beans.BeanAccess; import com.axiastudio.zoefx.core.beans.BeanClassAccess; import com.axiastudio.zoefx.core.beans.property.ItemObjectProperty; import com.axiastudio.zoefx.core.beans.property.ZoeFXProperty; import com.axiastudio.zoefx.core.db.TimeMachine; import com.axiastudio.zoefx.core.events.DataSetEvent; import com.axiastudio.zoefx.core.events.DataSetEventListener; import com.axiastudio.zoefx.core.db.DataSet; import com.axiastudio.zoefx.core.view.*; import com.axiastudio.zoefx.core.console.ConsoleController; import com.axiastudio.zoefx.core.view.search.SearchController; import javafx.beans.*; import javafx.beans.Observable; import javafx.beans.binding.Bindings; import javafx.beans.property.Property; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXMLLoader; import javafx.fxml.JavaFXBuilderFactory; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.Pane; import javafx.stage.Stage; import javafx.util.Callback; import java.io.IOException; import java.net.URL; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; /** * User: tiziano * Date: 20/03/14 * Time: 23:04 */ public class FXController extends BaseController implements DataSetEventListener { private Scene scene; private DataSet dataset = null; private ZSceneMode mode; private Behavior behavior = null; private TimeMachine timeMachine = null; private Map<String, Property> fxProperties = new HashMap<>(); private Map<String,TableView> tableViews; @Override public void initialize(URL url, ResourceBundle resourceBundle) { } public void setScene(Scene scene){ this.scene = scene; } protected Scene getScene() { return scene; } public void bindDataSet(DataSet dataset){ this.dataset = dataset; if( dataset.size()== 0 ){ dataset.create(); } Model model = dataset.newModel(); scanFXProperties(); initializeChoices(); initializeColumns(); // first show setModel(model); timeMachine.createSnapshot(fxProperties.values()); } private void initializeColumns(){ Model model = dataset.getCurrentModel(); Parent root = this.scene.getRoot(); Pane container = (Pane) root; List<Node> nodes = findNodes(container, new ArrayList<Node>()); tableViews = new HashMap<>(); for( Node node: nodes ){ if( node instanceof TableView){ TableView tableView = (TableView) node; tableViews.put(node.getId(), tableView); ObservableList<TableColumn> columns = tableView.getColumns(); for( TableColumn column: columns ){ String name = node.getId(); //String columnId = column.getId(); String columnId = column.getText().toLowerCase(); // XXX: RT-36633 JavaXFX issue // https://javafx-jira.kenai.com/browse/RT-36633 String lookup=null; if( behavior != null ) { lookup = behavior.getProperties().getProperty(columnId + ".lookup"); } if( lookup != null ) { Callback callback = model.getCallback(name, columnId, lookup); column.setCellValueFactory(callback); } else { Callback callback = model.getCallback(name, columnId); column.setCellValueFactory(callback); } // custom date order BeanClassAccess beanClassAccess = new BeanClassAccess(model.getEntityClass(), columnId); if( beanClassAccess.getReturnType() != null && Date.class.isAssignableFrom(beanClassAccess.getReturnType()) ) { column.setComparator(Comparator.nullsFirst(Comparators.DateComparator)); } //tableView.getItems().addListener(listChangeListener); } } } } private void initializeChoices(){ Model model = dataset.getCurrentModel(); Parent root = this.scene.getRoot(); Pane container = (Pane) root; List<Node> nodes = findNodes(container, new ArrayList<Node>()); for( Node node: nodes ){ if( node instanceof ChoiceBox){ String name = node.getId(); Property property = model.getProperty(name, Object.class); List superset = ((ItemObjectProperty) property).getSuperset(); ObservableList choices = FXCollections.observableArrayList(superset); ((ChoiceBox) node).setItems(choices); } } } private void unsetModel() { Model model = dataset.getCurrentModel(); for( String name: fxProperties.keySet() ){ Property fxProperty = fxProperties.get(name); ZoeFXProperty zoeFXProperty = model.getProperty(name); if( fxProperty != null && zoeFXProperty != null ) { Bindings.unbindBidirectional(fxProperty, zoeFXProperty); fxProperty.removeListener(invalidationListener); } } } private void setModel() { setModel(dataset.newModel()); } private void setModel(Model model) { for( String name: fxProperties.keySet() ){ Property fxProperty = fxProperties.get(name); ZoeFXProperty zoeFXProperty = model.getProperty(name); if( zoeFXProperty == null ){ Node node = scene.lookup("#"+name); if( node instanceof TextField ){ zoeFXProperty = model.getProperty(name, String.class); } else if( node instanceof TextArea ){ zoeFXProperty = model.getProperty(name, String.class); } else if( node instanceof CheckBox ){ zoeFXProperty = model.getProperty(name, Boolean.class); } else if( node instanceof ChoiceBox ){ zoeFXProperty = model.getProperty(name, Object.class); } else if( node instanceof DatePicker ){ zoeFXProperty = model.getProperty(name, Date.class); } else if( node instanceof TableView ){ zoeFXProperty = model.getProperty(name, Collection.class); } } if( fxProperty != null && zoeFXProperty != null ) { Bindings.bindBidirectional(fxProperty, zoeFXProperty); fxProperty.addListener(invalidationListener); } } //updateCache(); } private void scanFXProperties(){ Parent root = scene.getRoot(); Pane container = (Pane) root; List<Node> nodes = findNodes(container, new ArrayList<>()); for( Node node: nodes ){ String name = node.getId(); Property property = null; if( node instanceof TextField ){ property = ((TextField) node).textProperty(); } else if( node instanceof TextArea ){ property = ((TextArea) node).textProperty(); } else if( node instanceof CheckBox ){ property = ((CheckBox) node).selectedProperty(); } else if( node instanceof ChoiceBox ){ property = ((ChoiceBox) node).valueProperty(); } else if( node instanceof DatePicker ){ property = ((DatePicker) node).valueProperty(); } else if( node instanceof TableView ){ TableView tableView = (TableView) node; tableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); tableView.setContextMenu(createContextMenu(tableView)); property = tableView.itemsProperty(); } if( property != null ){ fxProperties.put(name, property); } } /* Validator validator = Validators.getValidator(model.getEntityClass(), name); if( validator != null ) { fxProperty.addListener(new TextFieldListener(validator)); } */ } private ContextMenu createContextMenu(TableView tableView){ ContextMenu contextMenu = new ContextMenu(); MenuItem infoItem = new MenuItem("Information"); infoItem.setGraphic(new ImageView(new Image(getClass().getResourceAsStream("/com/axiastudio/zoefx/core/resources/images/info.png")))); infoItem.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { ObservableList selectedItems = tableView.getSelectionModel().getSelectedItems(); if( selectedItems.size()==0 ) { return; } List<Object> newStore = new ArrayList<>(); for( int i=0; i<selectedItems.size(); i++ ) { newStore.add(selectedItems.get(i)); } ZScene newScene = SceneBuilders.queryZScene(newStore, ZSceneMode.DIALOG); if( newScene != null ) { Stage newStage = new Stage(); newStage.setScene(newScene.getScene()); newStage.show(); newStage.requestFocus(); } dataset.getDirty(); /// XXX: to implement a callback? } }); MenuItem openItem = new MenuItem("Open"); openItem.setGraphic(new ImageView(new Image(getClass().getResourceAsStream("/com/axiastudio/zoefx/core/resources/images/open.png")))); openItem.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { ObservableList selectedItems = tableView.getSelectionModel().getSelectedItems(); if (selectedItems.size() == 0) { return; } List<Object> newStore = new ArrayList<>(); String referenceProperty = tableView.getId() + ".reference"; String reference = behavior.getProperties().getProperty(referenceProperty, null); for (int i = 0; i < selectedItems.size(); i++) { Object item = selectedItems.get(i); if (reference != null) { BeanAccess<Object> ba = new BeanAccess<>(item, reference); newStore.add(ba.getValue()); } else { newStore.add(item); } } ZScene newScene = SceneBuilders.queryZScene(newStore, ZSceneMode.WINDOW); if (newScene != null) { Stage newStage = new Stage(); newStage.setScene(newScene.getScene()); newStage.show(); newStage.requestFocus(); } dataset.getDirty(); /// XXX: to implement a callback? } }); MenuItem addItem = new MenuItem("Add"); addItem.setGraphic(new ImageView(new Image(getClass().getResourceAsStream("/com/axiastudio/zoefx/core/resources/images/add.png")))); addItem.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { final String collectionName = tableView.getId(); String referenceProperty = collectionName + ".reference"; String searchcolumnsProperty = collectionName + ".searchcolumns"; String referenceName = behavior.getProperties().getProperty(referenceProperty, null); String searchcolumns = behavior.getProperties().getProperty(searchcolumnsProperty, "caption"); // XXX: default caption? if (referenceName != null) { Class classToSearch = null; try { Class parentEntityClass = dataset.getCurrentModel().getEntityClass(); Class<?> collectionGenericReturnType = (new BeanClassAccess(parentEntityClass, collectionName)).getGenericReturnType(); Class<?> referenceReturnType = (new BeanClassAccess(collectionGenericReturnType, referenceName)).getReturnType(); String className = referenceReturnType.getName(); classToSearch = Class.forName(className); Callback callback = new Callback<List, Boolean>() { @Override public Boolean call(List items) { for( Object item: items ){ Object entity = dataset.create(collectionName); BeanAccess<Object> ba = new BeanAccess<>(entity, referenceName); ba.setValue(item); refresh(); } return true; } }; Stage stage = searchStage(classToSearch, searchcolumns, callback); stage.show(); } catch (ClassNotFoundException e1) { e1.printStackTrace(); } } else { Object entity = dataset.create(collectionName); List<Object> newStore = new ArrayList<>(); newStore.add(entity); ZScene newScene = SceneBuilders.queryZScene(newStore, ZSceneMode.DIALOG); if (newScene != null) { Stage newStage = new Stage(); newStage.setScene(newScene.getScene()); newStage.show(); newStage.requestFocus(); } } //initializeColumns(); dataset.getDirty(); /// XXX: to implement a callback? } }); MenuItem delItem = new MenuItem("Delete"); delItem.setGraphic(new ImageView(new Image(getClass().getResourceAsStream("/com/axiastudio/zoefx/core/resources/images/delete.png")))); delItem.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { //System.out.println("Delete!"); } }); contextMenu.getItems().addAll(infoItem, openItem, addItem, delItem); return contextMenu; } private List<Node> findNodes( Pane container, List<Node> nodes ){ for( Node node: container.getChildren() ){ if( node instanceof Pane ){ nodes = findNodes((Pane) node, nodes); } else if( node instanceof TabPane ){ for( Tab tab: ((TabPane) node).getTabs() ) { nodes = findNodes((Pane) tab.getContent(), nodes); } } else if( node.getId() != null && node.getId() != "" ){ nodes.add(node); } } return nodes; } public DataSet getDataset() { return dataset; } public Model getCurrentModel() { return dataset.getCurrentModel(); } private FXController self(){ return this; } public ZSceneMode getMode() { return mode; } public void setMode(ZSceneMode mode) { this.mode = mode; } public void setBehavior(Behavior behavior) { this.behavior = behavior; } public void setTimeMachine(TimeMachine timeMachine) { this.timeMachine = timeMachine; } public void refresh(){ unsetModel(); Model model = dataset.newModel(); setModel(model); timeMachine.resetAndcreateSnapshot(fxProperties.values()); for( TableView tableView: tableViews.values() ){ // XXX: workaround for https://javafx-jira.kenai.com/browse/RT-22599 ObservableList items = tableView.getItems(); tableView.itemsProperty().removeListener(invalidationListener); tableView.setItems(null); tableView.layout(); tableView.setItems(items); tableView.itemsProperty().addListener(invalidationListener); } } private Stage searchStage(Class classToSearch, String searchcolumns, Callback callback) { return searchStage(classToSearch, searchcolumns, callback, null); } private Stage searchStage(Class classToSearch, String searchcolumns, Callback callback, String searchcriteria) { URL url = getClass().getResource("/com/axiastudio/zoefx/core/view/search/search.fxml"); FXMLLoader loader = new FXMLLoader(); loader.setLocation(url); loader.setBuilderFactory(new JavaFXBuilderFactory()); Parent root = null; try { root = loader.load(url.openStream()); } catch (IOException e1) { e1.printStackTrace(); } // search columns SearchController controller = loader.getController(); controller.setEntityClass(classToSearch); List<String> columns = new ArrayList<>(); if( searchcolumns != null ){ String[] split = searchcolumns.split(","); for( int i=0; i<split.length; i++ ){ columns.add(split[i]); } } controller.setColumns(columns); // search criteria List<String> criteria = new ArrayList<>(); if( searchcriteria != null ){ String[] split = searchcriteria.split(","); for( int i=0; i<split.length; i++ ){ criteria.add(split[i]); } } controller.setCriteria(criteria); // callback controller.setCallback(callback); //controller.setParentDataSet(dataset); Stage stage = new Stage(); stage.setTitle("Search"); stage.setScene(new Scene(root, 450, 450)); return stage; } /* * Navigation Bar */ public EventHandler<ActionEvent> handlerGoFirst = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { unsetModel(); dataset.goFirst(); setModel(dataset.newModel()); timeMachine.resetAndcreateSnapshot(fxProperties.values()); } }; public EventHandler<ActionEvent> handlerGoPrevious = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { unsetModel(); dataset.goPrevious(); setModel(dataset.newModel()); timeMachine.resetAndcreateSnapshot(fxProperties.values()); } }; public EventHandler<ActionEvent> handlerGoNext = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { unsetModel(); dataset.goNext(); setModel(dataset.newModel()); timeMachine.resetAndcreateSnapshot(fxProperties.values()); } }; public EventHandler<ActionEvent> handlerGoLast = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { unsetModel(); dataset.goLast(); setModel(dataset.newModel()); timeMachine.resetAndcreateSnapshot(fxProperties.values()); } }; public EventHandler<ActionEvent> handlerSave = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { dataset.commit(); timeMachine.resetAndcreateSnapshot(fxProperties.values()); } }; public EventHandler<ActionEvent> handlerConfirm = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { ((Stage) scene.getWindow()).close(); // TODO: get the parent dirty } }; public EventHandler<ActionEvent> handlerCancel = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { timeMachine.rollback(); dataset.revert(); timeMachine.resetAndcreateSnapshot(fxProperties.values()); } }; public EventHandler<ActionEvent> handlerAdd = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { dataset.create(); unsetModel(); setModel(dataset.newModel()); } }; public EventHandler<ActionEvent> handlerSearch = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { Class classToSearch = dataset.getCurrentModel().getEntityClass(); String searchcolumns = behavior.getProperties().getProperty("searchcolumns"); String searchcriteria = behavior.getProperties().getProperty("searchcriteria"); Callback callback = new Callback<List, Boolean>() { @Override public Boolean call(List items) { List store = new ArrayList(); for( Object item: items ){ store.add(item); } dataset.setStore(store); return true; } }; Stage stage = searchStage(classToSearch, searchcolumns, callback, searchcriteria); stage.show(); } }; public EventHandler<ActionEvent> handlerDelete = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { dataset.delete(); unsetModel(); setModel(dataset.newModel()); } }; public EventHandler<ActionEvent> handlerRefresh = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { refresh(); } }; public EventHandler<ActionEvent> handlerConsole = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { URL url = getClass().getResource("/com/axiastudio/zoefx/core/console/console.fxml"); FXMLLoader loader = new FXMLLoader(); loader.setLocation(url); loader.setBuilderFactory(new JavaFXBuilderFactory()); Parent root = null; try { root = loader.load(url.openStream()); } catch (IOException e1) { e1.printStackTrace(); } ConsoleController console = loader.getController(); console.setController(self()); Stage stage = new Stage(); stage.setTitle("Zoe FX Script Console"); stage.setScene(new Scene(root, 450, 450)); stage.show(); } }; public EventHandler<ActionEvent> handlerInfo = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { //System.out.println("Info"); } }; /* * Listeners */ public InvalidationListener invalidationListener = new InvalidationListener() { @Override public void invalidated(Observable observable) { dataset.getDirty(); } }; @Override public void dataSetEventHandler(DataSetEvent event) { //System.out.println(event.getEventType()); Logger.getLogger(this.getClass().getName()).log(Level.FINE, "{0} event handled", event.getEventType().getName()); if( event.getEventType().equals(DataSetEvent.STORE_CHANGED) ){ unsetModel(); setModel(); } else if( event.getEventType().equals(DataSetEvent.ROWS_CREATED) ){ refresh(); } } }
Label node binding.
src/com/axiastudio/zoefx/core/controller/FXController.java
Label node binding.
Java
bsd-3-clause
337d5002d532ca542b51a788a9a8b7b9a9aa889d
0
agaricusb/MiscConfiguration
package agaricus.mods.miscconfiguration; import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.common.IFuelHandler; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.network.NetworkMod; import cpw.mods.fml.common.registry.GameRegistry; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; import net.minecraft.tileentity.TileEntityFurnace; import net.minecraftforge.common.Configuration; import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.oredict.ShapedOreRecipe; import net.minecraftforge.oredict.ShapelessOreRecipe; import java.util.*; import java.util.logging.Level; @Mod(modid = "MiscConfiguration", name = "MiscConfiguration", version = "1.0-SNAPSHOT") // TODO: version from resource @NetworkMod(clientSideRequired = false, serverSideRequired = false) public class MiscConfiguration implements IFuelHandler { private Map<Integer, Integer> fuelTimes = new HashMap<Integer, Integer>(); //private List<ItemStack, Integer> fuelTimes = new ArrayList<ItemStack, Integer>(); // TODO: metadata, NBT private List<IRecipe> recipes = new ArrayList<IRecipe>(); private Map<String, ItemStack> itemNames = new HashMap<String, ItemStack>(); @Mod.PreInit public void preInit(FMLPreInitializationEvent event) { Configuration cfg = new Configuration(event.getSuggestedConfigurationFile()); try { cfg.load(); } catch (Exception e) { FMLLog.log(Level.SEVERE, e, "MiscConfiguration had a problem loading it's configuration"); } finally { cfg.save(); } GameRegistry.registerFuelHandler(this); fuelTimes.put(Block.cobblestone.blockID, TileEntityFurnace.getItemBurnTime(new ItemStack(Item.coal))); // TODO //fuelTimes.put(2631, // Herringbone Parquet Plank // GameRegistry.getFuelValue(new ItemStack(Item.coal.itemID, 1, 0))); //ItemStack output = new ItemStack(12345, 1, 0); //recipes.add(new ShapelessOreRecipe(output, "ingotCopper")); // TODO: read from config FMLLog.log(Level.INFO, "MiscConfiguration enabled"); } @Mod.PostInit public void postInit(FMLPostInitializationEvent event) { for (IRecipe recipe : recipes) { GameRegistry.addRecipe(recipe); } } @Override public int getBurnTime(ItemStack fuel) { System.out.println("getBurnTime "+fuel+" itemID="+fuel.itemID); if (!fuelTimes.containsKey(fuel.itemID)) return 0; // TODO: matching System.out.println("returning "+fuelTimes.get(fuel.itemID)); return fuelTimes.get(fuel.itemID); } /** * Scan item names for lookup */ private void scanItemNames() { // TODO: might have to run at first tick, if this is not late enough for all other mods to be loaded FMLLog.log(Level.INFO, "Scanning items"); for (int id = 0; id < Item.itemsList.length; ++id) { Item item = Item.itemsList[id]; if (item == null) continue; int damage = 0; // TODO: scan damages? ItemStack itemStack = new ItemStack(id, 1, damage); try { System.out.println("id "+id+" is "+itemStack.getItemName()); } catch (Throwable t) { ; } } // TODO: cache in itemNames } private ItemStack itemStackByName(String name) { // TODO //OreDictionary.getOres(name); // gets a list of all matching entries //GameRegistry.findItemStack(modId, name, 1); // need mod id return null; } }
src/main/java/agaricus/mods/miscconfiguration/MiscConfiguration.java
package agaricus.mods.miscconfiguration; import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.common.IFuelHandler; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.network.NetworkMod; import cpw.mods.fml.common.registry.GameRegistry; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; import net.minecraftforge.common.Configuration; import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.oredict.ShapedOreRecipe; import net.minecraftforge.oredict.ShapelessOreRecipe; import java.util.*; import java.util.logging.Level; @Mod(modid = "MiscConfiguration", name = "MiscConfiguration", version = "1.0-SNAPSHOT") // TODO: version from resource @NetworkMod(clientSideRequired = false, serverSideRequired = false) public class MiscConfiguration implements IFuelHandler { private Map<Integer, Integer> fuelTimes = new HashMap<Integer, Integer>(); //private List<ItemStack, Integer> fuelTimes = new ArrayList<ItemStack, Integer>(); // TODO: metadata, NBT private List<IRecipe> recipes = new ArrayList<IRecipe>(); private Map<String, ItemStack> itemNames = new HashMap<String, ItemStack>(); @Mod.PreInit public void preInit(FMLPreInitializationEvent event) { Configuration cfg = new Configuration(event.getSuggestedConfigurationFile()); try { cfg.load(); } catch (Exception e) { FMLLog.log(Level.SEVERE, e, "MiscConfiguration had a problem loading it's configuration"); } finally { cfg.save(); } GameRegistry.registerFuelHandler(this); // TODO fuelTimes.put(2631, // Herringbone Parquet Plank GameRegistry.getFuelValue(new ItemStack(Item.coal.itemID, 1, 0))); //ItemStack output = new ItemStack(12345, 1, 0); //recipes.add(new ShapelessOreRecipe(output, "ingotCopper")); // TODO: read from config FMLLog.log(Level.INFO, "MiscConfiguration enabled"); } @Mod.PostInit public void postInit(FMLPostInitializationEvent event) { for (IRecipe recipe : recipes) { GameRegistry.addRecipe(recipe); } } @Override public int getBurnTime(ItemStack fuel) { if (!fuelTimes.containsKey(fuel.itemID)) return 0; // TODO: matching return fuelTimes.get(fuel.itemID); } /** * Scan item names for lookup */ private void scanItemNames() { // TODO: might have to run at first tick, if this is not late enough for all other mods to be loaded FMLLog.log(Level.INFO, "Scanning items"); for (int id = 0; id < Item.itemsList.length; ++id) { Item item = Item.itemsList[id]; if (item == null) continue; int damage = 0; // TODO: scan damages? ItemStack itemStack = new ItemStack(id, 1, damage); try { System.out.println("id "+id+" is "+itemStack.getItemName()); } catch (Throwable t) { ; } } // TODO: cache in itemNames } private ItemStack itemStackByName(String name) { // TODO //OreDictionary.getOres(name); // gets a list of all matching entries //GameRegistry.findItemStack(modId, name, 1); // need mod id return null; } }
Vanilla fuels aren't in GameRegistry Call TileEntityFurnace.getItemBurnTime() instead of GameRegistry.getFuelValue() to match a test item to coal's fuel value
src/main/java/agaricus/mods/miscconfiguration/MiscConfiguration.java
Vanilla fuels aren't in GameRegistry
Java
bsd-3-clause
97ade3606ef079fa8062cefba5e15dbc59cf7aed
0
PeterMitrano/allwpilib,JLLeitschuh/allwpilib,JLLeitschuh/allwpilib,RAR1741/wpilib,RAR1741/wpilib,robotdotnet/allwpilib,JLLeitschuh/allwpilib,RAR1741/wpilib,robotdotnet/allwpilib,robotdotnet/allwpilib,JLLeitschuh/allwpilib,333fred/allwpilib,RAR1741/wpilib,PatrickPenguinTurtle/allwpilib,PeterMitrano/allwpilib,PatrickPenguinTurtle/allwpilib,PeterMitrano/allwpilib,PeterMitrano/allwpilib,JLLeitschuh/allwpilib,JLLeitschuh/allwpilib,PatrickPenguinTurtle/allwpilib,PatrickPenguinTurtle/allwpilib,333fred/allwpilib,RAR1741/wpilib,333fred/allwpilib,PeterMitrano/allwpilib,robotdotnet/allwpilib,robotdotnet/allwpilib,PeterMitrano/allwpilib,PatrickPenguinTurtle/allwpilib,333fred/allwpilib,RAR1741/wpilib,333fred/allwpilib,PatrickPenguinTurtle/allwpilib,PatrickPenguinTurtle/allwpilib,robotdotnet/allwpilib,JLLeitschuh/allwpilib,PeterMitrano/allwpilib,333fred/allwpilib,RAR1741/wpilib
/*----------------------------------------------------------------------------*/ /* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType; import edu.wpi.first.wpilibj.communication.UsageReporting; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable; import edu.wpi.first.wpilibj.tables.ITable; import edu.wpi.first.wpilibj.util.BoundaryException; /** * Use a rate gyro to return the robots heading relative to a starting position. * The Gyro class tracks the robots heading based on the starting position. As * the robot rotates the new heading is computed by integrating the rate of * rotation returned by the sensor. When the class is instantiated, it does a * short calibration routine where it samples the gyro while at rest to * determine the default offset. This is subtracted from each sample to * determine the heading. */ public class Gyro extends SensorBase implements PIDSource, LiveWindowSendable { static final int kOversampleBits = 10; static final int kAverageBits = 0; static final double kSamplesPerSecond = 50.0; static final double kCalibrationSampleTime = 5.0; static final double kDefaultVoltsPerDegreePerSecond = 0.007; private AnalogInput m_analog; double m_voltsPerDegreePerSecond; double m_offset; int m_center; boolean m_channelAllocated = false; AccumulatorResult result; private PIDSourceParameter m_pidSource; /** * Initialize the gyro. Calibrate the gyro by running for a number of * samples and computing the center value for this part. Then use the center * value as the Accumulator center value for subsequent measurements. It's * important to make sure that the robot is not moving while the centering * calculations are in progress, this is typically done when the robot is * first turned on while it's sitting at rest before the competition starts. */ private void initGyro() { result = new AccumulatorResult(); if (m_analog == null) { System.out.println("Null m_analog"); } m_voltsPerDegreePerSecond = kDefaultVoltsPerDegreePerSecond; m_analog.setAverageBits(kAverageBits); m_analog.setOversampleBits(kOversampleBits); double sampleRate = kSamplesPerSecond * (1 << (kAverageBits + kOversampleBits)); AnalogInput.setGlobalSampleRate(sampleRate); Timer.delay(1.0); m_analog.initAccumulator(); m_analog.resetAccumulator(); Timer.delay(kCalibrationSampleTime); m_analog.getAccumulatorOutput(result); m_center = (int) ((double) result.value / (double) result.count + .5); m_offset = ((double) result.value / (double) result.count) - m_center; m_analog.setAccumulatorCenter(m_center); m_analog.setAccumulatorDeadband(0); // /< TODO: compute / parameterize // this m_analog.resetAccumulator(); setPIDSourceParameter(PIDSourceParameter.kAngle); UsageReporting.report(tResourceType.kResourceType_Gyro, m_analog.getChannel()); LiveWindow.addSensor("Gyro", m_analog.getChannel(), this); } /** * Gyro constructor with only a channel. * * @param channel * The analog channel the gyro is connected to. */ public Gyro(int channel) { this(new AnalogInput(channel)); m_channelAllocated = true; } /** * Gyro constructor with a precreated analog channel object. Use this * constructor when the analog channel needs to be shared. * * @param channel * The AnalogChannel object that the gyro is connected to. */ public Gyro(AnalogInput channel) { m_analog = channel; if (m_analog == null) { throw new NullPointerException("AnalogInput supplied to Gyro constructor is null"); } initGyro(); } /** * Reset the gyro. Resets the gyro to a heading of zero. This can be used if * there is significant drift in the gyro and it needs to be recalibrated * after it has been running. */ public void reset() { if (m_analog != null) { m_analog.resetAccumulator(); } } /** * Delete (free) the accumulator and the analog components used for the * gyro. */ @Override public void free() { if (m_analog != null && m_channelAllocated) { m_analog.free(); } m_analog = null; } /** * Return the actual angle in degrees that the robot is currently facing. * * The angle is based on the current accumulator value corrected by the * oversampling rate, the gyro type and the A/D calibration values. The * angle is continuous, that is can go beyond 360 degrees. This make * algorithms that wouldn't want to see a discontinuity in the gyro output * as it sweeps past 0 on the second time around. * * @return the current heading of the robot in degrees. This heading is * based on integration of the returned rate from the gyro. */ public double getAngle() { if (m_analog == null) { return 0.0; } else { m_analog.getAccumulatorOutput(result); long value = result.value - (long) (result.count * m_offset); double scaledValue = value * 1e-9 * m_analog.getLSBWeight() * (1 << m_analog.getAverageBits()) / (AnalogInput.getGlobalSampleRate() * m_voltsPerDegreePerSecond); return scaledValue; } } /** * Return the rate of rotation of the gyro * * The rate is based on the most recent reading of the gyro analog value * * @return the current rate in degrees per second */ public double getRate() { if (m_analog == null) { return 0.0; } else { return (m_analog.getAverageValue() - (m_center + m_offset)) * 1e-9 * m_analog.getLSBWeight() / ((1 << m_analog.getOversampleBits()) * m_voltsPerDegreePerSecond); } } /** * Set the gyro type based on the sensitivity. This takes the number of * volts/degree/second sensitivity of the gyro and uses it in subsequent * calculations to allow the code to work with multiple gyros. * * @param voltsPerDegreePerSecond * The type of gyro specified as the voltage that represents one * degree/second. */ public void setSensitivity(double voltsPerDegreePerSecond) { m_voltsPerDegreePerSecond = voltsPerDegreePerSecond; } /** * Set which parameter of the encoder you are using as a process control * variable. The Gyro class supports the rate and angle parameters * * @param pidSource * An enum to select the parameter. */ public void setPIDSourceParameter(PIDSourceParameter pidSource) { BoundaryException.assertWithinBounds(pidSource.value, 1, 2); m_pidSource = pidSource; } /** * Get the angle of the gyro for use with PIDControllers * * @return the current angle according to the gyro */ @Override public double pidGet() { switch (m_pidSource.value) { case PIDSourceParameter.kRate_val: return getRate(); case PIDSourceParameter.kAngle_val: return getAngle(); default: return 0.0; } } /* * Live Window code, only does anything if live window is activated. */ @Override public String getSmartDashboardType() { return "Gyro"; } private ITable m_table; /** * {@inheritDoc} */ @Override public void initTable(ITable subtable) { m_table = subtable; updateTable(); } /** * {@inheritDoc} */ @Override public ITable getTable() { return m_table; } /** * {@inheritDoc} */ @Override public void updateTable() { if (m_table != null) { m_table.putNumber("Value", getAngle()); } } /** * {@inheritDoc} */ @Override public void startLiveWindowMode() { } /** * {@inheritDoc} */ @Override public void stopLiveWindowMode() { } }
wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Gyro.java
/*----------------------------------------------------------------------------*/ /* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType; import edu.wpi.first.wpilibj.communication.UsageReporting; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable; import edu.wpi.first.wpilibj.tables.ITable; import edu.wpi.first.wpilibj.util.BoundaryException; /** * Use a rate gyro to return the robots heading relative to a starting position. * The Gyro class tracks the robots heading based on the starting position. As * the robot rotates the new heading is computed by integrating the rate of * rotation returned by the sensor. When the class is instantiated, it does a * short calibration routine where it samples the gyro while at rest to * determine the default offset. This is subtracted from each sample to * determine the heading. */ public class Gyro extends SensorBase implements PIDSource, LiveWindowSendable { static final int kOversampleBits = 10; static final int kAverageBits = 0; static final double kSamplesPerSecond = 50.0; static final double kCalibrationSampleTime = 5.0; static final double kDefaultVoltsPerDegreePerSecond = 0.007; AnalogInput m_analog; double m_voltsPerDegreePerSecond; double m_offset; int m_center; boolean m_channelAllocated; AccumulatorResult result; private PIDSourceParameter m_pidSource; /** * Initialize the gyro. Calibrate the gyro by running for a number of * samples and computing the center value for this part. Then use the center * value as the Accumulator center value for subsequent measurements. It's * important to make sure that the robot is not moving while the centering * calculations are in progress, this is typically done when the robot is * first turned on while it's sitting at rest before the competition starts. */ private void initGyro() { result = new AccumulatorResult(); if (m_analog == null) { System.out.println("Null m_analog"); } m_voltsPerDegreePerSecond = kDefaultVoltsPerDegreePerSecond; m_analog.setAverageBits(kAverageBits); m_analog.setOversampleBits(kOversampleBits); double sampleRate = kSamplesPerSecond * (1 << (kAverageBits + kOversampleBits)); AnalogInput.setGlobalSampleRate(sampleRate); Timer.delay(1.0); m_analog.initAccumulator(); Timer.delay(kCalibrationSampleTime); m_analog.getAccumulatorOutput(result); m_center = (int) ((double) result.value / (double) result.count + .5); m_offset = ((double) result.value / (double) result.count) - (double) m_center; m_analog.setAccumulatorCenter(m_center); m_analog.setAccumulatorDeadband(0); // /< TODO: compute / parameterize // this m_analog.resetAccumulator(); setPIDSourceParameter(PIDSourceParameter.kAngle); UsageReporting.report(tResourceType.kResourceType_Gyro, m_analog.getChannel()); LiveWindow.addSensor("Gyro", m_analog.getChannel(), this); } /** * Gyro constructor with only a channel. * * @param channel * The analog channel the gyro is connected to. */ public Gyro(int channel) { m_analog = new AnalogInput(channel); m_channelAllocated = true; initGyro(); } /** * Gyro constructor with a precreated analog channel object. Use this * constructor when the analog channel needs to be shared. There is no * reference counting when an AnalogChannel is passed to the gyro. * * @param channel * The AnalogChannel object that the gyro is connected to. */ public Gyro(AnalogInput channel) { m_analog = channel; if (m_analog == null) { System.err .println("Analog channel supplied to Gyro constructor is null"); } else { m_channelAllocated = false; initGyro(); } } /** * Reset the gyro. Resets the gyro to a heading of zero. This can be used if * there is significant drift in the gyro and it needs to be recalibrated * after it has been running. */ public void reset() { if (m_analog != null) { m_analog.resetAccumulator(); } } /** * Delete (free) the accumulator and the analog components used for the * gyro. */ public void free() { if (m_analog != null && m_channelAllocated) { m_analog.free(); } m_analog = null; } /** * Return the actual angle in degrees that the robot is currently facing. * * The angle is based on the current accumulator value corrected by the * oversampling rate, the gyro type and the A/D calibration values. The * angle is continuous, that is can go beyond 360 degrees. This make * algorithms that wouldn't want to see a discontinuity in the gyro output * as it sweeps past 0 on the second time around. * * @return the current heading of the robot in degrees. This heading is * based on integration of the returned rate from the gyro. */ public double getAngle() { if (m_analog == null) { return 0.0; } else { m_analog.getAccumulatorOutput(result); long value = result.value - (long) (result.count * m_offset); double scaledValue = value * 1e-9 * m_analog.getLSBWeight() * (1 << m_analog.getAverageBits()) / (AnalogInput.getGlobalSampleRate() * m_voltsPerDegreePerSecond); return scaledValue; } } /** * Return the rate of rotation of the gyro * * The rate is based on the most recent reading of the gyro analog value * * @return the current rate in degrees per second */ public double getRate() { if (m_analog == null) { return 0.0; } else { return (m_analog.getAverageValue() - ((double) m_center + m_offset)) * 1e-9 * m_analog.getLSBWeight() / ((1 << m_analog.getOversampleBits()) * m_voltsPerDegreePerSecond); } } /** * Set the gyro type based on the sensitivity. This takes the number of * volts/degree/second sensitivity of the gyro and uses it in subsequent * calculations to allow the code to work with multiple gyros. * * @param voltsPerDegreePerSecond * The type of gyro specified as the voltage that represents one * degree/second. */ public void setSensitivity(double voltsPerDegreePerSecond) { m_voltsPerDegreePerSecond = voltsPerDegreePerSecond; } /** * Set which parameter of the encoder you are using as a process control * variable. The Gyro class supports the rate and angle parameters * * @param pidSource * An enum to select the parameter. */ public void setPIDSourceParameter(PIDSourceParameter pidSource) { BoundaryException.assertWithinBounds(pidSource.value, 1, 2); m_pidSource = pidSource; } /** * Get the angle of the gyro for use with PIDControllers * * @return the current angle according to the gyro */ public double pidGet() { switch (m_pidSource.value) { case PIDSourceParameter.kRate_val: return getRate(); case PIDSourceParameter.kAngle_val: return getAngle(); default: return 0.0; } } /* * Live Window code, only does anything if live window is activated. */ public String getSmartDashboardType() { return "Gyro"; } private ITable m_table; /** * {@inheritDoc} */ public void initTable(ITable subtable) { m_table = subtable; updateTable(); } /** * {@inheritDoc} */ public ITable getTable() { return m_table; } /** * {@inheritDoc} */ public void updateTable() { if (m_table != null) { m_table.putNumber("Value", getAngle()); } } /** * {@inheritDoc} */ public void startLiveWindowMode() { } /** * {@inheritDoc} */ public void stopLiveWindowMode() { } }
Fixes bugs with the Gyro If the gyro was initialized with an analog input the gyro class would not be calibrated properly. Removes unnecessary type casting. Change-Id: I6baa72919019a33cce7d3074f8477104cbe65396
wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Gyro.java
Fixes bugs with the Gyro
Java
bsd-3-clause
f6750c1ce215fc9be1d45276f50cd7243940b5fb
0
uzen/byteseek
/* * Copyright Matt Palmer 2011-2012, All rights reserved. * * This code is licensed under a standard 3-clause BSD license: * * 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. * * * The names of its contributors may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 net.domesdaybook.reader; import net.domesdaybook.reader.cache.WindowCache; import java.io.IOException; import java.util.Iterator; import java.util.NoSuchElementException; /** * An abstract implementation of the Reader interface, which also implements * Iterable<Window> to allow iterating over the Windows of a Reader. * <p> * It provides common Window and cache management services using a fixed * Window size, and a standard Window iterator {@link WindowIterator}. * * @author Matt Palmer */ public abstract class AbstractReader implements Reader, Iterable<Window> { /** * A constant indicating that there is no byte at the position requested, * returned by the {@link #readByte(long)} method. */ protected final static int NO_BYTE_AT_POSITION = -1; /** * A constant indicating that the length of the reader is currently unknown. */ protected static final long UNKNOWN_LENGTH = -1; /** * The default size in bytes of a Window, unless a different value is provided in * the constructor. */ protected final static int DEFAULT_WINDOW_SIZE = 4096; /** * The default number of Windows to cache, unless a different value is provided * in the constructor. */ protected final static int DEFAULT_CAPACITY = 32; /** * The size in bytes of each Window (assuming there are sufficient bytes to fill it). */ protected final int windowSize; /** * The Window caching mechanism used by this Reader. */ protected final WindowCache cache; /** * The last window acquired in this Reader using the {@link #getWindow(long)} method. * Positions to read from are quite likely to be consecutive or close to the * previous byte read from. * Recording the last window therefore avoids the need to look it up * in the cache if the required position is still inside the last Window. */ private Window lastWindow; /** * Construct the Reader using a default window size, using the WindowCache * provided. * * @param cache The WindowCache to use. * @throws IllegalArgumentException if the WindowCache is null. */ public AbstractReader(final WindowCache cache) { this(DEFAULT_WINDOW_SIZE, cache); } /** * Constructs the Reader using the window size and window cache provided. * * @param windowSize The size of Window to use. * @param cache The WindowCache to use. * @throws IllegalArgumentException if the window size is less than one or the * WindowCache is null. */ public AbstractReader(final int windowSize, final WindowCache cache) { if (windowSize < 1) { throw new IllegalArgumentException("Window size must be at least one."); } if (cache == null) { throw new IllegalArgumentException("Window cache cannot be null."); } this.windowSize = windowSize; this.cache = cache; } /** * Reads a byte in the file at the given position. * * @param position The position in the reader to read a byte from. * @return The byte at the given position (0-255), or a negative number * if there is no byte at the position specified. * @throws IOException if an error occurs reading the byte. */ @Override public int readByte(final long position) throws IOException { final Window window = getWindow(position); final int offset = (int) position % windowSize; if (window == null || offset >= window.length()) { return NO_BYTE_AT_POSITION; } return window.getByte(offset) & 0xFF; } /** * Returns a window onto the data for a given position. The position does not * have to be the beginning of a Window - but the Window returned must include * that position (if such a position exists in the Reader). * * @param position The position in the reader for which a Window is requested. * @return A Window backed by a byte array onto the data for a given position. * If a window can't be provided for the given position, null is returned. * @throws IOException if an IO error occurred trying to create a new window. */ @Override public Window getWindow(final long position) throws IOException { if (position >= 0) { Window window = null; final int offset = (int) position % windowSize; final long windowStart = position - offset; if (lastWindow != null && lastWindow.getWindowPosition() == windowStart) { window = lastWindow; } else { window = cache.getWindow(windowStart); if (window != null) { lastWindow = window; } else { window = createWindow(windowStart); if (window != null) { lastWindow = window; cache.addWindow(window); } } } // Finally, if the position requested is outside the window limit, // don't return a window. The position itself is invalid, even though // that position is part of a window which has valid positions. if (window != null && offset >= window.length()) { window = null; } return window; } return null; } /** * {@inheritDoc} */ @Override public Iterator<Window> iterator() { return new WindowIterator(); } /** * {@inheritDoc} */ @Override public void close() throws IOException { cache.clear(); } /** * {@inheritDoc} */ @Override public int getWindowOffset(final long position) { return (int) position % windowSize; } /** * An abstract method which must create a {@link Window} for the position * given. Returns null if a Window cannot be provided for the position provided. * * @param windowStart The position in the Reader at which the Window should begin. * @return A Window beginning at the position given. If no Window can be created * at the position given (e.g. the position is negative, or past the end of * the underlying byte source), then this method MUST return null. * @throws IOException If the Reader has an issue reading the bytes required for a * valid Window. */ abstract Window createWindow(final long windowStart) throws IOException; /** * An iterator of {@link Window}s over a {@link Reader}. */ private class WindowIterator implements Iterator<Window> { private int position = 0; /** * {@inheritDoc} */ @Override public boolean hasNext(){ try { return getWindow(position) != null; } catch (IOException ex) { return false; } } /** * {@inheritDoc} */ @Override public Window next() { try { final Window window = getWindow(position); if (window != null) { position += windowSize; return window; } } catch (IOException throwNoSuchElementExceptionInstead) { } throw new NoSuchElementException(); } /** * Always throws UnsupportedOperationException. It is not possible to * remove a Window from a Reader. * * @throws UnsupportedOperationException Always throws this exception. */ @Override public void remove() { throw new UnsupportedOperationException("Cannot remove a window from a reader."); } } }
src/net/domesdaybook/reader/AbstractReader.java
/* * Copyright Matt Palmer 2011-2012, All rights reserved. * * This code is licensed under a standard 3-clause BSD license: * * 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. * * * The names of its contributors may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 net.domesdaybook.reader; import net.domesdaybook.reader.cache.WindowCache; import java.io.IOException; import java.util.Iterator; import java.util.NoSuchElementException; /** * An abstract implementation of the Reader interface, which also implements * Iterable<Window> to allow iterating over the Windows of a Reader. * <p> * It provides common Window and cache management services using a fixed * Window size, and a standard Window iterator {@link WindowIterator}. * * @author Matt Palmer */ public abstract class AbstractReader implements Reader, Iterable<Window> { /** * A constant indicating that there is no byte at the position requested, * returned by the {@link #readByte(long)} method. */ protected final static int NO_BYTE_AT_POSITION = -1; /** * The default size in bytes of a Window, unless a different value is provided in * the constructor. */ protected final static int DEFAULT_WINDOW_SIZE = 4096; /** * The default number of Windows to cache, unless a different value is provided * in the constructor. */ protected final static int DEFAULT_CAPACITY = 32; /** * The size in bytes of each Window (assuming there are sufficient bytes to fill it). */ protected final int windowSize; /** * The Window caching mechanism used by this Reader. */ protected final WindowCache cache; /** * The last window acquired in this Reader using the {@link #getWindow(long)} method. * Positions to read from are quite likely to be consecutive or close to the * previous byte read from. * Recording the last window therefore avoids the need to look it up * in the cache if the required position is still inside the last Window. */ private Window lastWindow; /** * Construct the Reader using a default window size, using the WindowCache * provided. * * @param cache The WindowCache to use. * @throws IllegalArgumentException if the WindowCache is null. */ public AbstractReader(final WindowCache cache) { this(DEFAULT_WINDOW_SIZE, cache); } /** * Constructs the Reader using the window size and window cache provided. * * @param windowSize The size of Window to use. * @param cache The WindowCache to use. * @throws IllegalArgumentException if the window size is less than one or the * WindowCache is null. */ public AbstractReader(final int windowSize, final WindowCache cache) { if (windowSize < 1) { throw new IllegalArgumentException("Window size must be at least one."); } if (cache == null) { throw new IllegalArgumentException("Window cache cannot be null."); } this.windowSize = windowSize; this.cache = cache; } /** * Reads a byte in the file at the given position. * * @param position The position in the reader to read a byte from. * @return The byte at the given position (0-255), or a negative number * if there is no byte at the position specified. * @throws IOException if an error occurs reading the byte. */ @Override public int readByte(final long position) throws IOException { final Window window = getWindow(position); final int offset = (int) position % windowSize; if (window == null || offset >= window.length()) { return NO_BYTE_AT_POSITION; } return window.getByte(offset) & 0xFF; } /** * Returns a window onto the data for a given position. The position does not * have to be the beginning of a Window - but the Window returned must include * that position (if such a position exists in the Reader). * * @return A Window backed by a byte array onto the data for a given position. * If a window can't be provided for the given position, null is returned. * @throws IOException if an IO error occurred trying to create a new window. */ @Override public Window getWindow(final long position) throws IOException { if (position >= 0) { Window window = null; final int offset = (int) position % windowSize; final long windowStart = position - offset; if (lastWindow != null && lastWindow.getWindowPosition() == windowStart) { window = lastWindow; } else { window = cache.getWindow(windowStart); if (window != null) { lastWindow = window; } else { window = createWindow(windowStart); if (window != null) { lastWindow = window; cache.addWindow(window); } } } // Finally, if the position requested is outside the window limit, // don't return a window. The position itself is invalid, even though // that position is part of a window which has valid positions. if (window != null && offset >= window.length()) { window = null; } return window; } return null; } /** * {@inheritDoc} */ @Override public Iterator<Window> iterator() { return new WindowIterator(); } /** * {@inheritDoc} */ @Override public void close() throws IOException { cache.clear(); } /** * {@inheritDoc} */ @Override public int getWindowOffset(final long position) { return (int) position % windowSize; } /** * An abstract method which must create a {@link Window} for the position * given. Returns null if a Window cannot be provided for the position provided. * * @param windowStart The position in the Reader at which the Window should begin. * @return A Window beginning at the position given. If no Window can be created * at the position given (e.g. the position is negative, or past the end of * the underlying byte source), then this method MUST return null. * @throws IOException If the Reader has an issue reading the bytes required for a * valid Window. */ abstract Window createWindow(final long windowStart) throws IOException; /** * An iterator of {@link Window}s over a {@link Reader}. */ private class WindowIterator implements Iterator<Window> { private int position = 0; /** * {@inheritDoc} */ @Override public boolean hasNext(){ try { return getWindow(position) != null; } catch (IOException ex) { return false; } } /** * {@inheritDoc} */ @Override public Window next() { try { final Window window = getWindow(position); if (window != null) { position += windowSize; return window; } } catch (IOException throwNoSuchElementExceptionInstead) { } throw new NoSuchElementException(); } /** * Always throws UnsupportedOperationException. It is not possible to * remove a Window from a Reader. * * @throws UnsupportedOperationException Always throws this exception. */ @Override public void remove() { throw new UnsupportedOperationException("Cannot remove a window from a reader."); } } }
Updated javadoc.
src/net/domesdaybook/reader/AbstractReader.java
Updated javadoc.
Java
mit
f4b349526fa26daa8cbcef8049c3eea0e0043b48
0
graphql-java/graphql-java,graphql-java/graphql-java
package graphql.execution.nextgen; import graphql.Internal; import graphql.execution.MissingRootTypeException; import graphql.language.OperationDefinition; import graphql.schema.GraphQLObjectType; import graphql.schema.GraphQLSchema; import java.util.Optional; import static graphql.Assert.assertShouldNeverHappen; import static graphql.language.OperationDefinition.Operation.MUTATION; import static graphql.language.OperationDefinition.Operation.QUERY; import static graphql.language.OperationDefinition.Operation.SUBSCRIPTION; @Internal public class Common { public static GraphQLObjectType getOperationRootType(GraphQLSchema graphQLSchema, OperationDefinition operationDefinition) { OperationDefinition.Operation operation = operationDefinition.getOperation(); if (operation == MUTATION) { GraphQLObjectType mutationType = graphQLSchema.getMutationType(); return Optional.ofNullable(mutationType) .orElseThrow(() -> new MissingRootTypeException("Schema is not configured for mutations.", operationDefinition.getSourceLocation())); } else if (operation == QUERY) { GraphQLObjectType queryType = graphQLSchema.getQueryType(); return Optional.ofNullable(queryType) .orElseThrow(() -> new MissingRootTypeException("Schema does not define the required query root type.", operationDefinition.getSourceLocation())); } else if (operation == SUBSCRIPTION) { GraphQLObjectType subscriptionType = graphQLSchema.getSubscriptionType(); return Optional.ofNullable(subscriptionType) .orElseThrow(() -> new MissingRootTypeException("Schema is not configured for subscriptions.", operationDefinition.getSourceLocation())); } else { return assertShouldNeverHappen("Unhandled case. An extra operation enum has been added without code support"); } } }
src/main/java/graphql/execution/nextgen/Common.java
package graphql.execution.nextgen; import graphql.Internal; import graphql.execution.MissingRootTypeException; import graphql.language.OperationDefinition; import graphql.schema.GraphQLObjectType; import graphql.schema.GraphQLSchema; import static graphql.Assert.assertShouldNeverHappen; import static graphql.language.OperationDefinition.Operation.MUTATION; import static graphql.language.OperationDefinition.Operation.QUERY; import static graphql.language.OperationDefinition.Operation.SUBSCRIPTION; @Internal public class Common { public static GraphQLObjectType getOperationRootType(GraphQLSchema graphQLSchema, OperationDefinition operationDefinition) { OperationDefinition.Operation operation = operationDefinition.getOperation(); if (operation == MUTATION) { GraphQLObjectType mutationType = graphQLSchema.getMutationType(); if (mutationType == null) { throw new MissingRootTypeException("Schema is not configured for mutations.", operationDefinition.getSourceLocation()); } return mutationType; } else if (operation == QUERY) { GraphQLObjectType queryType = graphQLSchema.getQueryType(); if (queryType == null) { throw new MissingRootTypeException("Schema does not define the required query root type.", operationDefinition.getSourceLocation()); } return queryType; } else if (operation == SUBSCRIPTION) { GraphQLObjectType subscriptionType = graphQLSchema.getSubscriptionType(); if (subscriptionType == null) { throw new MissingRootTypeException("Schema is not configured for subscriptions.", operationDefinition.getSourceLocation()); } return subscriptionType; } else { return assertShouldNeverHappen("Unhandled case. An extra operation enum has been added without code support"); } } }
Change the way throwing an exception using Optional (#2375)
src/main/java/graphql/execution/nextgen/Common.java
Change the way throwing an exception using Optional (#2375)
Java
mit
5f9e44c95d58baa79e6c324f9cdd01008a37a1b8
0
nikialeksey/FullScreenDialog
package me.nikialeksey.fullscreendialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // @todo #1:15min First issue } }
app/src/main/java/me/nikialeksey/fullscreendialog/MainActivity.java
package me.nikialeksey.fullscreendialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // @todo #Some } }
Trying 0pdd
app/src/main/java/me/nikialeksey/fullscreendialog/MainActivity.java
Trying 0pdd
Java
mit
47b06672397073537530a130bc1bcd7ee5e03ffd
0
annkupi/picard,nh13/picard,broadinstitute/picard,annkupi/picard,broadinstitute/picard,annkupi/picard,nh13/picard,broadinstitute/picard,nh13/picard,alecw/picard,nh13/picard,broadinstitute/picard,alecw/picard,annkupi/picard,alecw/picard,alecw/picard,broadinstitute/picard
/* * The MIT License * * Copyright (c) 2009 The Broad Institute * * 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 net.sf.picard.analysis; import net.sf.picard.util.CollectionUtil; import net.sf.picard.util.Histogram; import net.sf.picard.sam.ReservedTagConstants; import net.sf.picard.cmdline.CommandLineProgram; import net.sf.picard.cmdline.Option; import net.sf.picard.cmdline.Usage; import net.sf.picard.cmdline.StandardOptionDefinitions; import net.sf.picard.io.IoUtil; import net.sf.picard.metrics.*; import net.sf.picard.reference.ReferenceSequenceFileWalker; import net.sf.picard.analysis.AlignmentSummaryMetrics.Category; import net.sf.picard.util.IlluminaUtil; import net.sf.picard.util.Log; import net.sf.samtools.util.CoordMath; import net.sf.samtools.util.SequenceUtil; import net.sf.samtools.AlignmentBlock; import net.sf.samtools.SAMFileHeader; import net.sf.samtools.SAMFileReader; import net.sf.samtools.SAMRecord; import net.sf.samtools.util.StringUtil; import java.io.File; import java.util.*; /** * A command line tool to read a BAM file and produce standard alignment metrics that would be applicable to any alignment. * Metrics to include, but not limited to: * <ul> * <li>Total number of reads (total, period, no exclusions)</li> * <li>Total number of PF reads (PF == does not fail vendor check flag)</li> * <li>Number of PF noise reads (does not fail vendor check and has noise attr set)</li> * <li>Total aligned PF reads (any PF read that has a sequence and position)</li> * <li>High quality aligned PF reads (high quality == mapping quality >= 20)</li> * <li>High quality aligned PF bases (actual aligned bases, calculate off alignment blocks)</li> * <li>High quality aligned PF Q20 bases (subset of above where base quality >= 20)</li> * <li>Median mismatches in HQ aligned PF reads (how many aligned bases != ref on average)</li> * <li>Reads aligned in pairs (vs. reads aligned with mate unaligned/not present)</li> * <li>Read length (how to handle mixed lengths?)</li> * <li>Bad Cycles - how many machine cycles yielded combined no-call and mismatch rates of >= 80%</li> * <li>Strand balance - reads mapped to positive strand / total mapped reads</li> * </ul> * Metrics are written for the first read of a pair, the second read, and combined for the pair. * * @author Doug Voet (dvoet at broadinstitute dot org) */ public class CollectAlignmentSummaryMetrics extends CommandLineProgram { private static final int MAPPING_QUALITY_THRESHOLD = 20; private static final int BASE_QUALITY_THRESHOLD = 20; private static final int ADAPTER_MATCH_LENGTH = 16; private static final int MAX_ADAPTER_ERRORS = 1; private byte[][] ADAPTER_SEQUENCES; private static final Log log = Log.getInstance(CollectAlignmentSummaryMetrics.class); // Usage and parameters @Usage public String USAGE = "Reads a SAM or BAM file and writes a file containing summary alignment metrics.\n"; @Option(shortName="I", doc="SAM or BAM file") public File INPUT; @Option(shortName="O", doc="File to write insert size metrics to") public File OUTPUT; @Option(shortName="R", doc="Reference sequence file", optional=true) public File REFERENCE_SEQUENCE; @Option(doc="If true (default), \"unsorted\" SAM/BAM files will be considerd coordinate sorted", shortName = StandardOptionDefinitions.ASSUME_SORTED_SHORT_NAME) public Boolean ASSUME_SORTED = Boolean.TRUE; @Option(doc="Paired end reads above this insert size will be considered chimeric along with inter-chromosomal pairs.") public int MAX_INSERT_SIZE = 100000; @Option() public List<String> ADAPTER_SEQUENCE = CollectionUtil.makeList( IlluminaUtil.AdapterPair.SINGLE_END.get5PrimeAdapter(), IlluminaUtil.AdapterPair.SINGLE_END.get3PrimeAdapter(), IlluminaUtil.AdapterPair.PAIRED_END.get5PrimeAdapter(), IlluminaUtil.AdapterPair.PAIRED_END.get3PrimeAdapter(), IlluminaUtil.AdapterPair.INDEXED.get5PrimeAdapter(), IlluminaUtil.AdapterPair.INDEXED.get3PrimeAdapter() ); // also List options are only appended to, not replaced @Option(shortName="BS", doc="Whether the SAM or BAM file consists of bisulfite sequenced reads. ") public boolean IS_BISULFITE_SEQUENCED = false; private ReferenceSequenceFileWalker referenceSequenceWalker; private SAMFileHeader samFileHeader; private boolean doRefMetrics; /** Required main method implementation. */ public static void main(final String[] argv) { System.exit(new CollectAlignmentSummaryMetrics().instanceMain(argv)); } @Override protected int doWork() { prepareAdapterSequences(); doRefMetrics = REFERENCE_SEQUENCE != null; // Check the files are readable/writable IoUtil.assertFileIsReadable(INPUT); if(doRefMetrics) IoUtil.assertFileIsReadable(REFERENCE_SEQUENCE); IoUtil.assertFileIsWritable(OUTPUT); final SAMFileReader in = new SAMFileReader(INPUT); assertCoordinateSortOrder(in); if(doRefMetrics) {this.referenceSequenceWalker = new ReferenceSequenceFileWalker(REFERENCE_SEQUENCE);} this.samFileHeader = in.getFileHeader(); if (!samFileHeader.getSequenceDictionary().isEmpty()) { if(doRefMetrics){ SequenceUtil.assertSequenceDictionariesEqual( samFileHeader.getSequenceDictionary(), this.referenceSequenceWalker.getSequenceDictionary()); } } else { log.warn(INPUT.getAbsoluteFile() + " has no sequence dictionary. If any reads " + "in the file are aligned then alignment summary metrics collection will fail."); } final MetricCollector<AlignmentSummaryMetrics, SAMRecord> unpairedCollector = constructCollector(Category.UNPAIRED); final MetricCollector<AlignmentSummaryMetrics, SAMRecord> firstOfPairCollector = constructCollector(Category.FIRST_OF_PAIR); final MetricCollector<AlignmentSummaryMetrics, SAMRecord> secondOfPairCollector = constructCollector(Category.SECOND_OF_PAIR); final MetricCollector<AlignmentSummaryMetrics, SAMRecord> pairCollector = constructCollector(Category.PAIR); // Loop over the reads applying them to the correct collectors for (final SAMRecord record : in) { if (record.getReadPairedFlag()) { if (record.getFirstOfPairFlag()) firstOfPairCollector.addRecord(record); else secondOfPairCollector.addRecord(record); pairCollector.addRecord(record); } else { unpairedCollector.addRecord(record); } } in.close(); // Let the collectors do any summary computations etc. firstOfPairCollector.onComplete(); secondOfPairCollector.onComplete(); pairCollector.onComplete(); unpairedCollector.onComplete(); final MetricsFile<AlignmentSummaryMetrics, Comparable<?>> file = getMetricsFile(); if (firstOfPairCollector.getMetrics().TOTAL_READS > 0) { // override how bad cycle is determined for paired reads, it should be // the sum of first and second reads pairCollector.getMetrics().BAD_CYCLES = firstOfPairCollector.getMetrics().BAD_CYCLES + secondOfPairCollector.getMetrics().BAD_CYCLES; file.addMetric(firstOfPairCollector.getMetrics()); file.addMetric(secondOfPairCollector.getMetrics()); file.addMetric(pairCollector.getMetrics()); } if (unpairedCollector.getMetrics().TOTAL_READS > 0) { file.addMetric(unpairedCollector.getMetrics()); } file.write(OUTPUT); return 0; } /** * Checks that the SAM is either coordinate sorted according to it's header, or that the header * doesn't specify a sort and that the user has supplied the argument to assume that it is * sorted correctly. */ private void assertCoordinateSortOrder(final SAMFileReader in) { switch (in.getFileHeader().getSortOrder()) { case coordinate: break; case unsorted: if (this.ASSUME_SORTED) { break; } default: log.warn("May not be able collect summary statistics in file " + INPUT.getAbsoluteFile() + " because it is not sorted in coordinate order. If any of the reads are aligned this will blow up."); } } /** Converts the supplied adapter sequences to byte arrays in both fwd and rc. */ protected void prepareAdapterSequences() { final int count = ADAPTER_SEQUENCE.size(); ADAPTER_SEQUENCES = new byte[count * 2][]; for (int i=0; i<count; ++i) { final String adapter = ADAPTER_SEQUENCE.get(i).toUpperCase(); ADAPTER_SEQUENCES[i] = StringUtil.stringToBytes(adapter); ADAPTER_SEQUENCES[i + count] = StringUtil.stringToBytes(SequenceUtil.reverseComplement(adapter)); } } /** * Checks the first ADAPTER_MATCH_LENGTH bases of the read against known adapter sequences and returns * true if the read matches an adapter sequence with MAX_ADAPTER_ERRORS mismsatches or fewer. * * @param read the basecalls for the read in the order and orientation the machine read them * @return true if the read matches an adapter and false otherwise */ protected boolean isAdapterSequence(final byte[] read) { StringUtil.toUpperCase(read); for (final byte[] adapter : ADAPTER_SEQUENCES) { final int lastKmerStart = adapter.length - ADAPTER_MATCH_LENGTH; for (int adapterStart=0; adapterStart<lastKmerStart; ++adapterStart) { int errors = 0; for (int i=0; i<ADAPTER_MATCH_LENGTH && errors <= MAX_ADAPTER_ERRORS; ++i) { if (read[i] != adapter[i + adapterStart]) ++errors; } if (errors <= MAX_ADAPTER_ERRORS) return true; } } return false; } /** Constructs a metrics collector for the supplied category. */ private MetricCollector<AlignmentSummaryMetrics, SAMRecord> constructCollector(final Category category) { final MetricCollector<AlignmentSummaryMetrics, SAMRecord> collector = new AggregateMetricCollector<AlignmentSummaryMetrics, SAMRecord>(new ReadCounter(), new QualityMappingCounter()); collector.setMetrics(new AlignmentSummaryMetrics()); collector.getMetrics().CATEGORY = category; return collector; } /** * Class that counts reads that match various conditions */ private class ReadCounter implements MetricCollector<AlignmentSummaryMetrics, SAMRecord> { private long numPositiveStrand = 0; private final Histogram<Integer> readLengthHistogram = new Histogram<Integer>(); private AlignmentSummaryMetrics metrics; private long chimeras; private long adapterReads; public void addRecord(final SAMRecord record) { if (record.getNotPrimaryAlignmentFlag()) { // only want 1 count per read so skip non primary alignments return; } metrics.TOTAL_READS++; readLengthHistogram.increment(record.getReadBases().length); if (!record.getReadFailsVendorQualityCheckFlag()) { metrics.PF_READS++; if (isNoiseRead(record)) { metrics.PF_NOISE_READS++; } else if (record.getReadUnmappedFlag()) { // If the read is unmapped see if it's adapter sequence if (isAdapterSequence(record.getReadBases())) { this.adapterReads++; } } else { if(doRefMetrics) { metrics.PF_READS_ALIGNED++; if (!record.getReadNegativeStrandFlag()) { numPositiveStrand++; } if (record.getReadPairedFlag() && !record.getMateUnmappedFlag()) { metrics.READS_ALIGNED_IN_PAIRS++; // With both reads mapped we can see if this pair is chimeric if (Math.abs(record.getInferredInsertSize()) > MAX_INSERT_SIZE || !record.getReferenceIndex().equals(record.getMateReferenceIndex())) { // Check that both ends have mapq > minimum final Integer mateMq = record.getIntegerAttribute("MQ"); if (mateMq == null || mateMq >= MAPPING_QUALITY_THRESHOLD && record.getMappingQuality() >= MAPPING_QUALITY_THRESHOLD) { ++this.chimeras; } } } } } } } public void onComplete() { metrics.PCT_PF_READS = (double) metrics.PF_READS / (double) metrics.TOTAL_READS; metrics.PCT_ADAPTER = this.adapterReads / (double) metrics.PF_READS; metrics.MEAN_READ_LENGTH = readLengthHistogram.getMean(); if(doRefMetrics) { metrics.PCT_PF_READS_ALIGNED = (double) metrics.PF_READS_ALIGNED / (double) metrics.PF_READS; metrics.PCT_READS_ALIGNED_IN_PAIRS = (double) metrics.READS_ALIGNED_IN_PAIRS/ (double) metrics.PF_READS_ALIGNED; metrics.STRAND_BALANCE = numPositiveStrand / (double) metrics.PF_READS_ALIGNED; metrics.PCT_CHIMERAS = this.chimeras / (double) metrics.PF_HQ_ALIGNED_READS; } } private boolean isNoiseRead(final SAMRecord record) { final Object noiseAttribute = record.getAttribute(ReservedTagConstants.XN); return (noiseAttribute != null && noiseAttribute.equals(1)); } public void setMetrics(final AlignmentSummaryMetrics metrics) { this.metrics = metrics; } public AlignmentSummaryMetrics getMetrics() { return this.metrics; } } /** * Class that counts quality mappings & base calls that match various conditions */ private class QualityMappingCounter implements MetricCollector<AlignmentSummaryMetrics, SAMRecord> { private final Histogram<Long> mismatchHistogram = new Histogram<Long>(); private final Histogram<Integer> badCycleHistogram = new Histogram<Integer>(); private AlignmentSummaryMetrics metrics; public void addRecord(final SAMRecord record) { if (record.getNotPrimaryAlignmentFlag()) { return; } if (record.getReadUnmappedFlag() || !doRefMetrics) { final byte[] readBases = record.getReadBases(); for (int i = 0; i < readBases.length; i++) { if (SequenceUtil.isNoCall(readBases[i])) { badCycleHistogram.increment(CoordMath.getCycle(record.getReadNegativeStrandFlag(), readBases.length, i)); } } } else { final boolean highQualityMapping = isHighQualityMapping(record); if (highQualityMapping) metrics.PF_HQ_ALIGNED_READS++; final byte[] readBases = record.getReadBases(); final byte[] refBases = referenceSequenceWalker.get(record.getReferenceIndex()).getBases(); final byte[] qualities = record.getBaseQualities(); final int refLength = refBases.length; long mismatchCount = 0; for (final AlignmentBlock alignmentBlock : record.getAlignmentBlocks()) { final int readIndex = alignmentBlock.getReadStart() - 1; final int refIndex = alignmentBlock.getReferenceStart() - 1; final int length = alignmentBlock.getLength(); for (int i=0; i<length && refIndex+i<refLength; ++i) { final int readBaseIndex = readIndex + i; boolean mismatch = !SequenceUtil.basesEqual(readBases[readBaseIndex], refBases[refIndex+i]); boolean bisulfiteBase = false; if (mismatch && IS_BISULFITE_SEQUENCED) { if ( (record.getReadNegativeStrandFlag() && (refBases[refIndex+i] == 'G' || refBases[refIndex+i] =='g') && (readBases[readBaseIndex] == 'A' || readBases[readBaseIndex] == 'a')) || ((!record.getReadNegativeStrandFlag()) && (refBases[refIndex+i] == 'C' || refBases[refIndex+i] == 'c') && (readBases[readBaseIndex] == 'T') || readBases[readBaseIndex] == 't') ) { bisulfiteBase = true; mismatch = false; } } if (highQualityMapping) { metrics.PF_HQ_ALIGNED_BASES++; if (!bisulfiteBase) { metrics.incrementErrorRateDenominator(); } if (qualities[readBaseIndex] >= BASE_QUALITY_THRESHOLD) { metrics.PF_HQ_ALIGNED_Q20_BASES++; } if (mismatch) { mismatchCount++; } } if (mismatch || SequenceUtil.isNoCall(readBases[readBaseIndex])) { badCycleHistogram.increment(CoordMath.getCycle(record.getReadNegativeStrandFlag(), readBases.length, i)); } } } mismatchHistogram.increment(mismatchCount); } } private boolean isHighQualityMapping(final SAMRecord record) { return !record.getReadFailsVendorQualityCheckFlag() && record.getMappingQuality() >= MAPPING_QUALITY_THRESHOLD; } public void onComplete() { if(doRefMetrics) { metrics.PF_HQ_MEDIAN_MISMATCHES = mismatchHistogram.getMedian(); metrics.PF_HQ_ERROR_RATE = mismatchHistogram.getSum() / (double)metrics.getErrorRateDenominator(); } metrics.BAD_CYCLES = 0; for (final Histogram<Integer>.Bin cycleBin : badCycleHistogram.values()) { final double badCyclePercentage = cycleBin.getValue() / metrics.TOTAL_READS; if (badCyclePercentage >= .8) { metrics.BAD_CYCLES++; } } } public void setMetrics(final AlignmentSummaryMetrics metrics) { this.metrics = metrics; } public AlignmentSummaryMetrics getMetrics() { return this.metrics; } } }
src/java/net/sf/picard/analysis/CollectAlignmentSummaryMetrics.java
/* * The MIT License * * Copyright (c) 2009 The Broad Institute * * 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 net.sf.picard.analysis; import net.sf.picard.util.CollectionUtil; import net.sf.picard.util.Histogram; import net.sf.picard.sam.ReservedTagConstants; import net.sf.picard.cmdline.CommandLineProgram; import net.sf.picard.cmdline.Option; import net.sf.picard.cmdline.Usage; import net.sf.picard.cmdline.StandardOptionDefinitions; import net.sf.picard.io.IoUtil; import net.sf.picard.metrics.*; import net.sf.picard.reference.ReferenceSequenceFileWalker; import net.sf.picard.analysis.AlignmentSummaryMetrics.Category; import net.sf.picard.util.IlluminaUtil; import net.sf.picard.util.Log; import net.sf.samtools.util.CoordMath; import net.sf.samtools.util.SequenceUtil; import net.sf.samtools.AlignmentBlock; import net.sf.samtools.SAMFileHeader; import net.sf.samtools.SAMFileReader; import net.sf.samtools.SAMRecord; import net.sf.samtools.util.StringUtil; import java.io.File; import java.util.*; /** * A command line tool to read a BAM file and produce standard alignment metrics that would be applicable to any alignment. * Metrics to include, but not limited to: * <ul> * <li>Total number of reads (total, period, no exclusions)</li> * <li>Total number of PF reads (PF == does not fail vendor check flag)</li> * <li>Number of PF noise reads (does not fail vendor check and has noise attr set)</li> * <li>Total aligned PF reads (any PF read that has a sequence and position)</li> * <li>High quality aligned PF reads (high quality == mapping quality >= 20)</li> * <li>High quality aligned PF bases (actual aligned bases, calculate off alignment blocks)</li> * <li>High quality aligned PF Q20 bases (subset of above where base quality >= 20)</li> * <li>Median mismatches in HQ aligned PF reads (how many aligned bases != ref on average)</li> * <li>Reads aligned in pairs (vs. reads aligned with mate unaligned/not present)</li> * <li>Read length (how to handle mixed lengths?)</li> * <li>Bad Cycles - how many machine cycles yielded combined no-call and mismatch rates of >= 80%</li> * <li>Strand balance - reads mapped to positive strand / total mapped reads</li> * </ul> * Metrics are written for the first read of a pair, the second read, and combined for the pair. * * @author Doug Voet (dvoet at broadinstitute dot org) */ public class CollectAlignmentSummaryMetrics extends CommandLineProgram { private static final int MAPPING_QUALITY_THRESHOLD = 20; private static final int BASE_QUALITY_THRESHOLD = 20; private static final int ADAPTER_MATCH_LENGTH = 16; private static final int MAX_ADAPTER_ERRORS = 1; private byte[][] ADAPTER_SEQUENCES; private static final Log log = Log.getInstance(CollectAlignmentSummaryMetrics.class); // Usage and parameters @Usage public String USAGE = "Reads a SAM or BAM file and writes a file containing summary alignment metrics.\n"; @Option(shortName="I", doc="SAM or BAM file") public File INPUT; @Option(shortName="O", doc="File to write insert size metrics to") public File OUTPUT; @Option(shortName="R", doc="Reference sequence file") public File REFERENCE_SEQUENCE; @Option(doc="If true (default), \"unsorted\" SAM/BAM files will be considerd coordinate sorted", shortName = StandardOptionDefinitions.ASSUME_SORTED_SHORT_NAME) public Boolean ASSUME_SORTED = Boolean.TRUE; @Option(doc="Paired end reads above this insert size will be considered chimeric along with inter-chromosomal pairs.") public int MAX_INSERT_SIZE = 100000; @Option() public List<String> ADAPTER_SEQUENCE = CollectionUtil.makeList( IlluminaUtil.AdapterPair.SINGLE_END.get5PrimeAdapter(), IlluminaUtil.AdapterPair.SINGLE_END.get3PrimeAdapter(), IlluminaUtil.AdapterPair.PAIRED_END.get5PrimeAdapter(), IlluminaUtil.AdapterPair.PAIRED_END.get3PrimeAdapter(), IlluminaUtil.AdapterPair.INDEXED.get5PrimeAdapter(), IlluminaUtil.AdapterPair.INDEXED.get3PrimeAdapter() ); // also List options are only appended to, not replaced @Option(shortName="BS", doc="Whether the SAM or BAM file consists of bisulfite sequenced reads. ") public boolean IS_BISULFITE_SEQUENCED = false; private ReferenceSequenceFileWalker referenceSequenceWalker; private SAMFileHeader samFileHeader; /** Required main method implementation. */ public static void main(final String[] argv) { System.exit(new CollectAlignmentSummaryMetrics().instanceMain(argv)); } @Override protected int doWork() { prepareAdapterSequences(); // Check the files are readable/writable IoUtil.assertFileIsReadable(INPUT); IoUtil.assertFileIsReadable(REFERENCE_SEQUENCE); IoUtil.assertFileIsWritable(OUTPUT); final SAMFileReader in = new SAMFileReader(INPUT); assertCoordinateSortOrder(in); this.referenceSequenceWalker = new ReferenceSequenceFileWalker(REFERENCE_SEQUENCE); this.samFileHeader = in.getFileHeader(); if (!samFileHeader.getSequenceDictionary().isEmpty()) { SequenceUtil.assertSequenceDictionariesEqual( samFileHeader.getSequenceDictionary(), this.referenceSequenceWalker.getSequenceDictionary()); } else { log.warn(INPUT.getAbsoluteFile() + " has no sequence dictionary. If any reads " + "in the file are aligned then alignment summary metrics collection will fail."); } final MetricCollector<AlignmentSummaryMetrics, SAMRecord> unpairedCollector = constructCollector(Category.UNPAIRED); final MetricCollector<AlignmentSummaryMetrics, SAMRecord> firstOfPairCollector = constructCollector(Category.FIRST_OF_PAIR); final MetricCollector<AlignmentSummaryMetrics, SAMRecord> secondOfPairCollector = constructCollector(Category.SECOND_OF_PAIR); final MetricCollector<AlignmentSummaryMetrics, SAMRecord> pairCollector = constructCollector(Category.PAIR); // Loop over the reads applying them to the correct collectors for (SAMRecord record : in) { if (record.getReadPairedFlag()) { if (record.getFirstOfPairFlag()) firstOfPairCollector.addRecord(record); else secondOfPairCollector.addRecord(record); pairCollector.addRecord(record); } else { unpairedCollector.addRecord(record); } } in.close(); // Let the collectors do any summary computations etc. firstOfPairCollector.onComplete(); secondOfPairCollector.onComplete(); pairCollector.onComplete(); unpairedCollector.onComplete(); final MetricsFile<AlignmentSummaryMetrics, Comparable<?>> file = getMetricsFile(); if (firstOfPairCollector.getMetrics().TOTAL_READS > 0) { // override how bad cycle is determined for paired reads, it should be // the sum of first and second reads pairCollector.getMetrics().BAD_CYCLES = firstOfPairCollector.getMetrics().BAD_CYCLES + secondOfPairCollector.getMetrics().BAD_CYCLES; file.addMetric(firstOfPairCollector.getMetrics()); file.addMetric(secondOfPairCollector.getMetrics()); file.addMetric(pairCollector.getMetrics()); } if (unpairedCollector.getMetrics().TOTAL_READS > 0) { file.addMetric(unpairedCollector.getMetrics()); } file.write(OUTPUT); return 0; } /** * Checks that the SAM is either coordinate sorted according to it's header, or that the header * doesn't specify a sort and that the user has supplied the argument to assume that it is * sorted correctly. */ private void assertCoordinateSortOrder(final SAMFileReader in) { switch (in.getFileHeader().getSortOrder()) { case coordinate: break; case unsorted: if (this.ASSUME_SORTED) { break; } default: log.warn("May not be able collect summary statistics in file " + INPUT.getAbsoluteFile() + " because it is not sorted in coordinate order. If any of the reads are aligned this will blow up."); } } /** Converts the supplied adapter sequences to byte arrays in both fwd and rc. */ protected void prepareAdapterSequences() { final int count = ADAPTER_SEQUENCE.size(); ADAPTER_SEQUENCES = new byte[count * 2][]; for (int i=0; i<count; ++i) { String adapter = ADAPTER_SEQUENCE.get(i).toUpperCase(); ADAPTER_SEQUENCES[i] = StringUtil.stringToBytes(adapter); ADAPTER_SEQUENCES[i + count] = StringUtil.stringToBytes(SequenceUtil.reverseComplement(adapter)); } } /** * Checks the first ADAPTER_MATCH_LENGTH bases of the read against known adapter sequences and returns * true if the read matches an adapter sequence with MAX_ADAPTER_ERRORS mismsatches or fewer. * * @param read the basecalls for the read in the order and orientation the machine read them * @return true if the read matches an adapter and false otherwise */ protected boolean isAdapterSequence(final byte[] read) { StringUtil.toUpperCase(read); for (final byte[] adapter : ADAPTER_SEQUENCES) { final int lastKmerStart = adapter.length - ADAPTER_MATCH_LENGTH; for (int adapterStart=0; adapterStart<lastKmerStart; ++adapterStart) { int errors = 0; for (int i=0; i<ADAPTER_MATCH_LENGTH && errors <= MAX_ADAPTER_ERRORS; ++i) { if (read[i] != adapter[i + adapterStart]) ++errors; } if (errors <= MAX_ADAPTER_ERRORS) return true; } } return false; } /** Constructs a metrics collector for the supplied category. */ private MetricCollector<AlignmentSummaryMetrics, SAMRecord> constructCollector(final Category category) { final MetricCollector<AlignmentSummaryMetrics, SAMRecord> collector = new AggregateMetricCollector<AlignmentSummaryMetrics, SAMRecord>(new ReadCounter(), new QualityMappingCounter()); collector.setMetrics(new AlignmentSummaryMetrics()); collector.getMetrics().CATEGORY = category; return collector; } /** * Class that counts reads that match various conditions */ private class ReadCounter implements MetricCollector<AlignmentSummaryMetrics, SAMRecord> { private long numPositiveStrand = 0; private final Histogram<Integer> readLengthHistogram = new Histogram<Integer>(); private AlignmentSummaryMetrics metrics; private long chimeras; private long adapterReads; public void addRecord(final SAMRecord record) { if (record.getNotPrimaryAlignmentFlag()) { // only want 1 count per read so skip non primary alignments return; } metrics.TOTAL_READS++; readLengthHistogram.increment(record.getReadBases().length); if (!record.getReadFailsVendorQualityCheckFlag()) { metrics.PF_READS++; if (isNoiseRead(record)) { metrics.PF_NOISE_READS++; } else if (record.getReadUnmappedFlag()) { // If the read is unmapped see if it's adapter sequence if (isAdapterSequence(record.getReadBases())) { this.adapterReads++; } } else { metrics.PF_READS_ALIGNED++; if (!record.getReadNegativeStrandFlag()) { numPositiveStrand++; } if (record.getReadPairedFlag() && !record.getMateUnmappedFlag()) { metrics.READS_ALIGNED_IN_PAIRS++; // With both reads mapped we can see if this pair is chimeric if (Math.abs(record.getInferredInsertSize()) > MAX_INSERT_SIZE || !record.getReferenceIndex().equals(record.getMateReferenceIndex())) { // Check that both ends have mapq > minimum final Integer mateMq = record.getIntegerAttribute("MQ"); if (mateMq == null || mateMq >= MAPPING_QUALITY_THRESHOLD && record.getMappingQuality() >= MAPPING_QUALITY_THRESHOLD) { ++this.chimeras; } } } } } } public void onComplete() { metrics.PCT_PF_READS = (double) metrics.PF_READS / (double) metrics.TOTAL_READS; metrics.PCT_PF_READS_ALIGNED = (double) metrics.PF_READS_ALIGNED / (double) metrics.PF_READS; metrics.PCT_READS_ALIGNED_IN_PAIRS = (double) metrics.READS_ALIGNED_IN_PAIRS/ (double) metrics.PF_READS_ALIGNED; metrics.MEAN_READ_LENGTH = readLengthHistogram.getMean(); metrics.STRAND_BALANCE = numPositiveStrand / (double) metrics.PF_READS_ALIGNED; metrics.PCT_ADAPTER = this.adapterReads / (double) metrics.PF_READS; metrics.PCT_CHIMERAS = this.chimeras / (double) metrics.PF_HQ_ALIGNED_READS; } private boolean isNoiseRead(final SAMRecord record) { final Object noiseAttribute = record.getAttribute(ReservedTagConstants.XN); return (noiseAttribute != null && noiseAttribute.equals(1)); } public void setMetrics(final AlignmentSummaryMetrics metrics) { this.metrics = metrics; } public AlignmentSummaryMetrics getMetrics() { return this.metrics; } } /** * Class that counts quality mappings & base calls that match various conditions */ private class QualityMappingCounter implements MetricCollector<AlignmentSummaryMetrics, SAMRecord> { private final Histogram<Long> mismatchHistogram = new Histogram<Long>(); private final Histogram<Integer> badCycleHistogram = new Histogram<Integer>(); private AlignmentSummaryMetrics metrics; public void addRecord(final SAMRecord record) { if (record.getNotPrimaryAlignmentFlag()) { return; } if (record.getReadUnmappedFlag()) { final byte[] readBases = record.getReadBases(); for (int i = 0; i < readBases.length; i++) { if (SequenceUtil.isNoCall(readBases[i])) { badCycleHistogram.increment(CoordMath.getCycle(record.getReadNegativeStrandFlag(), readBases.length, i)); } } } else { final boolean highQualityMapping = isHighQualityMapping(record); if (highQualityMapping) metrics.PF_HQ_ALIGNED_READS++; final byte[] readBases = record.getReadBases(); final byte[] refBases = referenceSequenceWalker.get(record.getReferenceIndex()).getBases(); final byte[] qualities = record.getBaseQualities(); final int refLength = refBases.length; long mismatchCount = 0; for (final AlignmentBlock alignmentBlock : record.getAlignmentBlocks()) { final int readIndex = alignmentBlock.getReadStart() - 1; final int refIndex = alignmentBlock.getReferenceStart() - 1; final int length = alignmentBlock.getLength(); for (int i=0; i<length && refIndex+i<refLength; ++i) { final int readBaseIndex = readIndex + i; boolean mismatch = !SequenceUtil.basesEqual(readBases[readBaseIndex], refBases[refIndex+i]); boolean bisulfiteBase = false; if (mismatch && IS_BISULFITE_SEQUENCED) { if ( (record.getReadNegativeStrandFlag() && (refBases[refIndex+i] == 'G' || refBases[refIndex+i] =='g') && (readBases[readBaseIndex] == 'A' || readBases[readBaseIndex] == 'a')) || ((!record.getReadNegativeStrandFlag()) && (refBases[refIndex+i] == 'C' || refBases[refIndex+i] == 'c') && (readBases[readBaseIndex] == 'T') || readBases[readBaseIndex] == 't') ) { bisulfiteBase = true; mismatch = false; } } if (highQualityMapping) { metrics.PF_HQ_ALIGNED_BASES++; if (!bisulfiteBase) { metrics.incrementErrorRateDenominator(); } if (qualities[readBaseIndex] >= BASE_QUALITY_THRESHOLD) { metrics.PF_HQ_ALIGNED_Q20_BASES++; } if (mismatch) { mismatchCount++; } } if (mismatch || SequenceUtil.isNoCall(readBases[readBaseIndex])) { badCycleHistogram.increment(CoordMath.getCycle(record.getReadNegativeStrandFlag(), readBases.length, i)); } } } mismatchHistogram.increment(mismatchCount); } } private boolean isHighQualityMapping(final SAMRecord record) { return !record.getReadFailsVendorQualityCheckFlag() && record.getMappingQuality() >= MAPPING_QUALITY_THRESHOLD; } public void onComplete() { metrics.PF_HQ_MEDIAN_MISMATCHES = mismatchHistogram.getMedian(); metrics.PF_HQ_ERROR_RATE = mismatchHistogram.getSum() / (double)metrics.getErrorRateDenominator(); metrics.BAD_CYCLES = 0; for (final Histogram<Integer>.Bin cycleBin : badCycleHistogram.values()) { final double badCyclePercentage = cycleBin.getValue() / metrics.TOTAL_READS; if (badCyclePercentage >= .8) { metrics.BAD_CYCLES++; } } } public void setMetrics(final AlignmentSummaryMetrics metrics) { this.metrics = metrics; } public AlignmentSummaryMetrics getMetrics() { return this.metrics; } } }
CollectAlignmentSummaryMetrics no longer fails if there is no reference sequence provided.
src/java/net/sf/picard/analysis/CollectAlignmentSummaryMetrics.java
CollectAlignmentSummaryMetrics no longer fails if there is no reference sequence provided.
Java
mit
c012153e622263cd50817b5e3b26e3d50798558d
0
teinvdlugt/Fractals
package com.teinvdlugt.android.fractals; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.widget.ProgressBar; public class FractalView extends View { /** * The lowest real value shown */ protected double startReal = -2; /** * The highest imaginary value shown */ protected double startImg = 2; protected double range = 4; protected int resolution = 512; protected int precision = 400; /** * The bitmap will be updated whilst calculating with for example a new resolution. * {@code updateRows} is the number of rows to include in one update. The higher the * value the higher the performance, but the used memory will increase a bit. */ protected int updateRows = 6; protected ProgressBar progressBar; protected Bitmap bitmap; protected Bitmap scaledBitmap; protected Paint axisPaint; protected Paint zoomPaint; private boolean calculating = false; public void recalculate() { new Thread(new Runnable() { @Override public void run() { calculating = true; if (bitmap == null) { bitmap = Bitmap.createBitmap(resolution, resolution, Bitmap.Config.RGB_565); } else if (bitmap.getWidth() != resolution) { bitmap = Bitmap.createScaledBitmap(bitmap, resolution, resolution, false); } int[] colors = new int[resolution * updateRows]; for (int y = 0; y < resolution; y++) { for (int x = 0; x < resolution; x++) { double cReal = absoluteRealValue(x); double cImg = absoluteImaginaryValue(y); double zReal = cReal, zImg = cImg; int iterations = 0; while (zReal * zReal + zImg * zImg <= 4 && iterations < precision) { double zRealNew = zReal * zReal - zImg * zImg + cReal; zImg = 2 * zReal * zImg + cImg; zReal = zRealNew; iterations++; } colors[(y % updateRows) * resolution + x] = iterations == precision ? Color.BLACK : Color.WHITE; } final int finalY = y; if (progressBar != null) { progressBar.post(new Runnable() { @Override public void run() { progressBar.setProgress(finalY); } }); } if ((y + 1) % updateRows == 0) { bitmap.setPixels(colors, 0, resolution, 0, y - updateRows + 1, resolution, updateRows); if (scaledBitmap != null) { scaledBitmap = Bitmap.createScaledBitmap(bitmap, scaledBitmap.getWidth(), scaledBitmap.getHeight(), false); postInvalidate(); } } else if (y == resolution - 1) { bitmap.setPixels(colors, 0, resolution, 0, resolution - resolution % updateRows, resolution, resolution % updateRows); if (scaledBitmap != null) { scaledBitmap = Bitmap.createScaledBitmap(bitmap, scaledBitmap.getWidth(), scaledBitmap.getHeight(), false); postInvalidate(); } } } if (scaledBitmap != null) { scaledBitmap = Bitmap.createScaledBitmap(bitmap, scaledBitmap.getWidth(), scaledBitmap.getWidth(), false); } post(new Runnable() { @Override public void run() { if (progressBar != null) progressBar.setProgress(0); invalidate(); requestLayout(); } }); calculating = false; } }).start(); } @Override protected void onDraw(Canvas canvas) { // Define square size (the view isn't allowed to be a rectangle) int width = canvas.getWidth(); int height = canvas.getHeight(); int size = Math.min(width, height); // Draw bitmap if (scaledBitmap != null) { if (scaledBitmap.getWidth() != size) { scaledBitmap = Bitmap.createScaledBitmap(scaledBitmap, size, size, false); } } else if (bitmap != null) { scaledBitmap = Bitmap.createScaledBitmap(bitmap, size, size, false); } if (scaledBitmap != null) { canvas.drawBitmap(scaledBitmap, 0f, 0f, null); } // Draw axes float xAxis = (float) (size * (-startReal / range)); float yAxis = (float) (size * (startImg / range)); canvas.drawLine(xAxis, 0, xAxis, size, axisPaint); canvas.drawLine(0, yAxis, size, yAxis, axisPaint); // Draw zoom indication if (zoomStartX != -1 && zoomStartY != -1 && zoomEndX != -1 && zoomEndY != -1) { float left = Math.min(zoomStartX, zoomEndX); float right = Math.max(zoomStartX, zoomEndX); float top = Math.min(zoomStartY, zoomEndY); float bottom = Math.max(zoomStartY, zoomEndY); canvas.drawRect(left, top, right, bottom, zoomPaint); } } protected float zoomStartX = -1, zoomStartY = -1; protected float zoomEndX = -1, zoomEndY = -1; @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { zoomStartX = event.getX(); zoomStartY = event.getY(); zoomEndX = -1; zoomEndY = -1; return true; } else if (event.getAction() == MotionEvent.ACTION_MOVE) { zoomEndX = event.getX(); zoomEndY = event.getY(); invalidate(); requestLayout(); return true; } else if (event.getAction() == MotionEvent.ACTION_UP) { zoomIn(); zoomStartX = zoomStartY = zoomEndX = zoomEndY = -1; recalculate(); return true; } return super.onTouchEvent(event); } private void zoomIn() { double startReal = absoluteRealValue(zoomStartX); double endReal = absoluteRealValue(zoomEndX); double startImg = absoluteImaginaryValue(zoomStartY); double endImg = absoluteImaginaryValue(zoomEndY); double xRange = Math.abs(startReal - endReal); double yRange = Math.abs(startImg - endImg); this.range = Math.max(xRange, yRange); this.startReal = Math.min(startReal, endReal); this.startImg = Math.max(startImg, endImg); } protected int resolveColor(int iterations) { // white --> green --> red --> blue double value = Math.pow(2, iterations / precision); //double value = Math.pow(-Math.log(iterations/precision), -1); //value = 1.0 / (value * value); // low value => blue // high value => white // 1.0 (highest) value => black if (value >= 1.0) return Color.BLACK; // 0.00 blue // 0.33 red // 0.67 green // 0.99 white // 0.00 => 255 blue // 0.33 => 0 blue int blue = (int) Math.max((1.0 - value / 0.33) * 255, 0); // 0.00 => 0 red // 0.33 => 255 red // 0.67 => 0 red int red = (int) Math.max((1.0 - Math.abs(value - 0.33) / 0.33) * 255, 0); int green = (int) Math.max((1.0 - Math.abs(value - 0.67) / 0.33) * 255, 0); // 0.67 => 0.0 white factor // 1.00 => 1.0 white factor double whiteFactor = Math.max((1.0 - Math.abs(value - 1.0) / 0.33), 0); // Whitify: // Only green has to be whitified because red and white can never mix. green += (255 - blue) * whiteFactor; red += (255 - red) * whiteFactor; blue += (255 - blue) * whiteFactor; Log.d("colors", "value: " + value); return Color.rgb(red, green, blue); } protected void init() { axisPaint = new Paint(); zoomPaint = new Paint(); axisPaint.setColor(Color.BLACK); zoomPaint.setARGB(128, 50, 50, 200); } /** * The real value in the complex field represented by a column of virtual pixels. * * @param column The column of the 'virtual' pixels (defined in {@code resolution}) * @return The real value in the complex field */ protected double absoluteRealValue(int column) { // TODO: 18-8-2015 resolution needs to be finalized when calculating process is running return startReal + range / resolution * column; } /** * The imaginary value in the complex field represented by a row of virtual pixels. * * @param row The row of the 'virtual' pixels (defined in {@code resolution}) * @return The imaginary value in the complex field */ protected double absoluteImaginaryValue(int row) { return startImg - range / resolution * row; } /** * The real value in the complex field represented by a device pixel in {@code scaledBitmap}. * * @param x The x position of the device pixel from which to retrieve the real value * @return The real value in the complex field */ protected double absoluteRealValue(float x) { if (scaledBitmap != null) { return startReal + x / scaledBitmap.getWidth() * range; } return -1; } /** * The imaginary value in the complex field represented by a device pixel in {@code scaledBitmap}. * * @param y The y position of the device pixel from which to retrieve the imaginary value * @return The imaginary value in the complex field */ protected double absoluteImaginaryValue(float y) { if (scaledBitmap != null) { return startImg - y / scaledBitmap.getHeight() * range; } return -1; } public ProgressBar getProgressBar() { return progressBar; } /** * The {@code ProgressBar} to which the {@code FractalView} will report its progress. * If you want to detach the {@code ProgressBar} from the {@code FractalView}, pass null. * * @param progressBar Null if you don't want any {@code ProgressBar} to be linked to the * {@code FractalView}. */ public void setProgressBar(@Nullable ProgressBar progressBar) { this.progressBar = progressBar; if (progressBar != null) { progressBar.setMax(resolution); } } public int getResolution() { return resolution; } public void setResolution(int resolution) { if (!calculating) { this.resolution = resolution; progressBar.setMax(resolution); } } public int getPrecision() { return precision; } public void setPrecision(int precision) { if (!calculating) this.precision = precision; } public double getStartReal() { return startReal; } public void setStartReal(double startReal) { this.startReal = startReal; } public double getStartImg() { return startImg; } public void setStartImg(double startImg) { this.startImg = startImg; } public double getRange() { return range; } public void setRange(double range) { this.range = range; } public boolean isCalculating() { return calculating; } public void setCalculating(boolean calculating) { this.calculating = calculating; } public FractalView(Context context) { super(context); init(); } public FractalView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public FractalView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } }
app/src/main/java/com/teinvdlugt/android/fractals/FractalView.java
package com.teinvdlugt.android.fractals; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.widget.ProgressBar; public class FractalView extends View { /** * The lowest real value shown */ protected double startReal = -2; /** * The highest imaginary value shown */ protected double startImg = 2; protected double range = 4; protected int resolution = 512; protected int precision = 400; /** * The bitmap will be updated whilst calculating with for example a new resolution. * {@code updateRows} is the number of rows to include in one update. The higher the * value the higher the performance, but the used memory will increase a bit. */ protected int updateRows = 6; protected ProgressBar progressBar; protected Bitmap bitmap; protected Bitmap scaledBitmap; protected Paint axisPaint; protected Paint zoomPaint; private boolean calculating = false; public void recalculate() { new Thread(new Runnable() { @Override public void run() { calculating = true; if (bitmap == null) { bitmap = Bitmap.createBitmap(resolution, resolution, Bitmap.Config.RGB_565); } else if (bitmap.getWidth() != resolution) { bitmap = Bitmap.createScaledBitmap(bitmap, resolution, resolution, false); } int[] colors = new int[resolution * updateRows]; for (int y = 0; y < resolution; y++) { for (int x = 0; x < resolution; x++) { double cReal = absoluteRealValue(x); double cImg = absoluteImaginaryValue(y); double zReal = cReal, zImg = cImg; int iterations = 0; while (zReal * zReal + zImg * zImg <= 4 && iterations < precision) { double zRealNew = zReal * zReal - zImg * zImg + cReal; zImg = 2 * zReal * zImg + cImg; zReal = zRealNew; iterations++; } colors[(y % updateRows) * resolution + x] = iterations == precision ? Color.BLACK : Color.WHITE; } final int finalY = y; if (progressBar != null) { progressBar.post(new Runnable() { @Override public void run() { progressBar.setProgress(finalY); } }); } if ((y + 1) % updateRows == 0) { bitmap.setPixels(colors, 0, resolution, 0, y - updateRows + 1, resolution, updateRows); if (scaledBitmap != null) { scaledBitmap = Bitmap.createScaledBitmap(bitmap, scaledBitmap.getWidth(), scaledBitmap.getHeight(), false); postInvalidate(); } } } if (scaledBitmap != null) { scaledBitmap = Bitmap.createScaledBitmap(bitmap, scaledBitmap.getWidth(), scaledBitmap.getWidth(), false); } post(new Runnable() { @Override public void run() { if (progressBar != null) progressBar.setProgress(0); invalidate(); requestLayout(); } }); calculating = false; } }).start(); } @Override protected void onDraw(Canvas canvas) { // Define square size (the view isn't allowed to be a rectangle) int width = canvas.getWidth(); int height = canvas.getHeight(); int size = Math.min(width, height); // Draw bitmap if (scaledBitmap != null) { if (scaledBitmap.getWidth() != size) { scaledBitmap = Bitmap.createScaledBitmap(scaledBitmap, size, size, false); } } else if (bitmap != null) { scaledBitmap = Bitmap.createScaledBitmap(bitmap, size, size, false); } if (scaledBitmap != null) { canvas.drawBitmap(scaledBitmap, 0f, 0f, null); } // Draw axes float xAxis = (float) (size * (-startReal / range)); float yAxis = (float) (size * (startImg / range)); canvas.drawLine(xAxis, 0, xAxis, size, axisPaint); canvas.drawLine(0, yAxis, size, yAxis, axisPaint); // Draw zoom indication if (zoomStartX != -1 && zoomStartY != -1 && zoomEndX != -1 && zoomEndY != -1) { float left = Math.min(zoomStartX, zoomEndX); float right = Math.max(zoomStartX, zoomEndX); float top = Math.min(zoomStartY, zoomEndY); float bottom = Math.max(zoomStartY, zoomEndY); canvas.drawRect(left, top, right, bottom, zoomPaint); } } protected float zoomStartX = -1, zoomStartY = -1; protected float zoomEndX = -1, zoomEndY = -1; @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { zoomStartX = event.getX(); zoomStartY = event.getY(); zoomEndX = -1; zoomEndY = -1; return true; } else if (event.getAction() == MotionEvent.ACTION_MOVE) { zoomEndX = event.getX(); zoomEndY = event.getY(); invalidate(); requestLayout(); return true; } else if (event.getAction() == MotionEvent.ACTION_UP) { zoomIn(); zoomStartX = zoomStartY = zoomEndX = zoomEndY = -1; recalculate(); return true; } return super.onTouchEvent(event); } private void zoomIn() { double startReal = absoluteRealValue(zoomStartX); double endReal = absoluteRealValue(zoomEndX); double startImg = absoluteImaginaryValue(zoomStartY); double endImg = absoluteImaginaryValue(zoomEndY); double xRange = Math.abs(startReal - endReal); double yRange = Math.abs(startImg - endImg); this.range = Math.max(xRange, yRange); this.startReal = Math.min(startReal, endReal); this.startImg = Math.max(startImg, endImg); } protected int resolveColor(int iterations) { // white --> green --> red --> blue double value = Math.pow(2, iterations / precision); //double value = Math.pow(-Math.log(iterations/precision), -1); //value = 1.0 / (value * value); // low value => blue // high value => white // 1.0 (highest) value => black if (value >= 1.0) return Color.BLACK; // 0.00 blue // 0.33 red // 0.67 green // 0.99 white // 0.00 => 255 blue // 0.33 => 0 blue int blue = (int) Math.max((1.0 - value / 0.33) * 255, 0); // 0.00 => 0 red // 0.33 => 255 red // 0.67 => 0 red int red = (int) Math.max((1.0 - Math.abs(value - 0.33) / 0.33) * 255, 0); int green = (int) Math.max((1.0 - Math.abs(value - 0.67) / 0.33) * 255, 0); // 0.67 => 0.0 white factor // 1.00 => 1.0 white factor double whiteFactor = Math.max((1.0 - Math.abs(value - 1.0) / 0.33), 0); // Whitify: // Only green has to be whitified because red and white can never mix. green += (255 - blue) * whiteFactor; red += (255 - red) * whiteFactor; blue += (255 - blue) * whiteFactor; Log.d("colors", "value: " + value); return Color.rgb(red, green, blue); } protected void init() { axisPaint = new Paint(); zoomPaint = new Paint(); axisPaint.setColor(Color.BLACK); zoomPaint.setARGB(128, 50, 50, 200); } /** * The real value in the complex field represented by a column of virtual pixels. * * @param column The column of the 'virtual' pixels (defined in {@code resolution}) * @return The real value in the complex field */ protected double absoluteRealValue(int column) { // TODO: 18-8-2015 resolution needs to be finalized when calculating process is running return startReal + range / resolution * column; } /** * The imaginary value in the complex field represented by a row of virtual pixels. * * @param row The row of the 'virtual' pixels (defined in {@code resolution}) * @return The imaginary value in the complex field */ protected double absoluteImaginaryValue(int row) { return startImg - range / resolution * row; } /** * The real value in the complex field represented by a device pixel in {@code scaledBitmap}. * * @param x The x position of the device pixel from which to retrieve the real value * @return The real value in the complex field */ protected double absoluteRealValue(float x) { if (scaledBitmap != null) { return startReal + x / scaledBitmap.getWidth() * range; } return -1; } /** * The imaginary value in the complex field represented by a device pixel in {@code scaledBitmap}. * * @param y The y position of the device pixel from which to retrieve the imaginary value * @return The imaginary value in the complex field */ protected double absoluteImaginaryValue(float y) { if (scaledBitmap != null) { return startImg - y / scaledBitmap.getHeight() * range; } return -1; } public ProgressBar getProgressBar() { return progressBar; } /** * The {@code ProgressBar} to which the {@code FractalView} will report its progress. * If you want to detach the {@code ProgressBar} from the {@code FractalView}, pass null. * * @param progressBar Null if you don't want any {@code ProgressBar} to be linked to the * {@code FractalView}. */ public void setProgressBar(@Nullable ProgressBar progressBar) { this.progressBar = progressBar; if (progressBar != null) { progressBar.setMax(resolution); } } public int getResolution() { return resolution; } public void setResolution(int resolution) { if (!calculating) { this.resolution = resolution; progressBar.setMax(resolution); } } public int getPrecision() { return precision; } public void setPrecision(int precision) { if (!calculating) this.precision = precision; } public double getStartReal() { return startReal; } public void setStartReal(double startReal) { this.startReal = startReal; } public double getStartImg() { return startImg; } public void setStartImg(double startImg) { this.startImg = startImg; } public double getRange() { return range; } public void setRange(double range) { this.range = range; } public boolean isCalculating() { return calculating; } public void setCalculating(boolean calculating) { this.calculating = calculating; } public FractalView(Context context) { super(context); init(); } public FractalView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public FractalView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } }
Solve error when resolution % updateRows != 0
app/src/main/java/com/teinvdlugt/android/fractals/FractalView.java
Solve error when resolution % updateRows != 0
Java
mit
fe96487afd153206dd919f20555ff3a835342ab1
0
the-james-burton/sshw
/* * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.sshw.websocket; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.security.PublicKey; import net.schmizz.sshj.SSHClient; import net.schmizz.sshj.connection.channel.direct.Session; import net.schmizz.sshj.connection.channel.direct.Session.Shell; import net.schmizz.sshj.transport.verification.HostKeyVerifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.socket.WebSocketSession; public class SSHSessionImpl implements SSHSession { protected final Logger log = LoggerFactory.getLogger(getClass()); private SSHClient ssh; private Session session; private Shell shell; private BufferedReader input; private OutputStream output; private WebSocketSession socket; private SSHSessionOutput sender; private Thread thread; @Override public boolean login(String username, String password) { try { // ssh.authPublickey(System.getProperty("user.name")); log.info("new SSHClient"); ssh = new SSHClient(); log.info("verify all hosts"); ssh.addHostKeyVerifier(new HostKeyVerifier() { public boolean verify(String arg0, int arg1, PublicKey arg2) { return true; // don't bother verifying } }); log.info("connecting"); ssh.connect("127.0.0.1"); log.info("authenticating: {}", username); ssh.authPassword(username, password); log.info("starting session"); session = ssh.startSession(); log.info("allocating PTY"); session.allocateDefaultPTY(); log.info("starting shell"); shell = session.startShell(); log.info("started"); input = new BufferedReader(new InputStreamReader(shell.getInputStream())); output = shell.getOutputStream(); sender = new SSHSessionOutput(input, socket); thread = new Thread(sender); thread.start(); } catch (Exception e) { e.printStackTrace(); try { log.info("disconnect"); ssh.disconnect(); } catch (IOException e1) { e1.printStackTrace(); } return false; } return true; } @Override public BufferedReader getSSHInput() { return input; } @Override public OutputStream getSSHOutput() { return output; } @Override protected void finalize() throws Throwable { shell.close(); session.close(); ssh.disconnect(); } @Override public void setWebSocketSession(WebSocketSession session) { this.socket = session; } @Override public void logout() { try { output.write("exit".getBytes()); finalize(); } catch (Throwable e) { e.printStackTrace(); } } }
src/main/java/com/github/sshw/websocket/SSHSessionImpl.java
/* * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.sshw.websocket; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.security.PublicKey; import net.schmizz.sshj.SSHClient; import net.schmizz.sshj.connection.channel.direct.Session; import net.schmizz.sshj.connection.channel.direct.Session.Shell; import net.schmizz.sshj.transport.verification.HostKeyVerifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.socket.WebSocketSession; public class SSHSessionImpl implements SSHSession { protected final Logger log = LoggerFactory.getLogger(getClass()); private SSHClient ssh; private Session session; private Shell shell; private BufferedReader input; private OutputStream output; private WebSocketSession socket; private SSHSessionOutput sender; private Thread thread; @Override public boolean login(String username, String password) { try { // ssh.authPublickey(System.getProperty("user.name")); log.info("new SSHClient"); ssh = new SSHClient(); log.info("verify all hosts"); ssh.addHostKeyVerifier(new HostKeyVerifier() { public boolean verify(String arg0, int arg1, PublicKey arg2) { return true; // don't bother verifying } }); log.info("connecting"); ssh.connect("styletools"); log.info("authenticating: {}", username); ssh.authPassword(username, password); log.info("starting session"); session = ssh.startSession(); log.info("allocating PTY"); session.allocateDefaultPTY(); log.info("starting shell"); shell = session.startShell(); log.info("started"); input = new BufferedReader(new InputStreamReader(shell.getInputStream())); output = shell.getOutputStream(); sender = new SSHSessionOutput(input, socket); thread = new Thread(sender); thread.start(); } catch (Exception e) { e.printStackTrace(); try { log.info("disconnect"); ssh.disconnect(); } catch (IOException e1) { e1.printStackTrace(); } return false; } return true; } @Override public BufferedReader getSSHInput() { return input; } @Override public OutputStream getSSHOutput() { return output; } @Override protected void finalize() throws Throwable { shell.close(); session.close(); ssh.disconnect(); } @Override public void setWebSocketSession(WebSocketSession session) { this.socket = session; } @Override public void logout() { try { output.write("exit".getBytes()); finalize(); } catch (Throwable e) { e.printStackTrace(); } } }
Update SSHSessionImpl.java
src/main/java/com/github/sshw/websocket/SSHSessionImpl.java
Update SSHSessionImpl.java
Java
mit
1ae4da0bd0e03ffc0208e35137eaf9657b7f7901
0
mickleness/pumpernickel,mickleness/pumpernickel,mickleness/pumpernickel
/** * This software is released as part of the Pumpernickel project. * * All com.pump resources in the Pumpernickel project are distributed under the * MIT License: * https://raw.githubusercontent.com/mickleness/pumpernickel/master/License.txt * * More information about the Pumpernickel project is available here: * https://mickleness.github.io/pumpernickel/ */ package com.pump.showcase; import java.awt.AWTEvent; import java.awt.CardLayout; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Desktop; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Robot; import java.awt.Toolkit; import java.awt.event.AWTEventListener; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.HierarchyEvent; import java.awt.event.HierarchyListener; import java.awt.event.KeyEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.LinkedHashSet; import java.util.List; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicBoolean; import javax.imageio.ImageIO; import javax.swing.JButton; import javax.swing.JCheckBoxMenuItem; import javax.swing.JComponent; import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.JWindow; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.Timer; import javax.swing.UIManager; import javax.swing.border.CompoundBorder; import javax.swing.border.EmptyBorder; import javax.swing.border.LineBorder; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import javax.swing.text.html.HTMLEditorKit; import javax.swing.text.html.StyleSheet; import com.pump.desktop.DesktopApplication; import com.pump.desktop.edit.EditCommand; import com.pump.desktop.edit.EditMenuControls; import com.pump.icon.button.MinimalDuoToneCloseIcon; import com.pump.io.FileTreeIterator; import com.pump.plaf.RoundTextFieldUI; import com.pump.swing.CollapsibleContainer; import com.pump.swing.FileDialogUtils; import com.pump.swing.HelpComponent; import com.pump.swing.JFancyBox; import com.pump.swing.ListSectionContainer; import com.pump.swing.MagnificationPanel; import com.pump.swing.SectionContainer.Section; import com.pump.swing.TextFieldPrompt; import com.pump.swing.ThrobberManager; import com.pump.text.WildcardPattern; import com.pump.util.JVM; import com.pump.window.WindowDragger; import com.pump.window.WindowMenu; public class PumpernickelShowcaseApp extends JFrame { private static final long serialVersionUID = 1L; public static void main(String[] args) throws IOException { DesktopApplication.initialize("com.pump.showcase", "Showcase", "1.01", "jeremy.wood@mac.com", PumpernickelShowcaseApp.class); SwingUtilities.invokeLater(new Runnable() { public void run() { PumpernickelShowcaseApp p = new PumpernickelShowcaseApp(); p.pack(); p.setLocationRelativeTo(null); p.setVisible(true); p.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); p.loadDemos(); } }); } JTextField searchField = new JTextField(); JPanel searchFieldPanel = new JPanel(new GridBagLayout()); TextFieldPrompt searchPrompt; List<Section> masterSectionList = new ArrayList<>(); ListSectionContainer sectionContainer = new ListSectionContainer(true, null, searchFieldPanel); JMenuBar menuBar = new JMenuBar(); JMenu editMenu = createEditMenu(); JMenu helpMenu = new JMenu("Help"); JCheckBoxMenuItem magnifierItem = new JCheckBoxMenuItem("Magnifier"); JMenuItem saveScreenshotItem = new JMenuItem("Save Screenshot..."); ThrobberManager loadingThrobberManager = new ThrobberManager(); ActionListener magnifierListener = new ActionListener() { JWindow magnifierWindow; JButton closeButton = new JButton(); Timer repaintTimer; MagnificationPanel p; @Override public void actionPerformed(ActionEvent e) { if (magnifierWindow == null) { magnifierWindow = createWindow(); } magnifierWindow.setVisible(magnifierItem.isSelected()); } private JWindow createWindow() { // TODO: this is OK for now, but eventually let's: // 1. Update to a resizable dialog (the MagnificationPanel doesn't // handle resizes yet.) // 2. Support zooming in/out of the MagnificationPanel // 3. Fix MagnificationPanel.setPixelated(false), offer // checkbox/context menu to toggle JWindow w = new JWindow(PumpernickelShowcaseApp.this); // on Macs this gives the window a certain look, plus it hides // the window when the app loses focus. w.getRootPane().putClientProperty("Window.style", "small"); p = new MagnificationPanel(PumpernickelShowcaseApp.this, 40, 40, 4); // on Mac the window shadows show the boundaries well enough. // Otherwise let's paint it clearly: if (!JVM.isMac) p.setBorder(new LineBorder(Color.gray)); w.setLayout(new GridBagLayout()); w.setAlwaysOnTop(true); w.setLocationRelativeTo(PumpernickelShowcaseApp.this); new WindowDragger(p).setActive(true); w.setFocusableWindowState(false); closeButton.setIcon(new MinimalDuoToneCloseIcon(closeButton)); closeButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { magnifierItem.doClick(); } }); closeButton.setContentAreaFilled(false); closeButton.setBorderPainted(false); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.insets = new Insets(0, 0, 0, 0); c.anchor = GridBagConstraints.NORTHWEST; c.weightx = 0; c.weighty = 0; c.fill = GridBagConstraints.NONE; w.add(closeButton, c); c.insets = new Insets(0, 0, 0, 0); c.weightx = 1; c.weighty = 1; c.fill = GridBagConstraints.BOTH; w.add(p, c); w.pack(); repaintTimer = new Timer(25, new ActionListener() { public void actionPerformed(ActionEvent e) { p.refresh(); } }); repaintTimer.start(); return w; } }; private DocumentListener searchDocListener = new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { change(); } @Override public void removeUpdate(DocumentEvent e) { change(); } @Override public void changedUpdate(DocumentEvent e) { } private void change() { closeFancyBoxes(); String str = searchField.getText(); Comparator<Section> comparator = new Comparator<Section>() { @Override public int compare(Section o1, Section o2) { return o1.getName().toLowerCase() .compareTo(o2.getName().toLowerCase()); } }; Collection<Section> matches = new TreeSet<>(comparator); for (Section section : masterSectionList) { if (isMatching(section, str)) matches.add(section); } sectionContainer.getSections().setAll( matches.toArray(new Section[matches.size()])); } private boolean isMatching(Section section, String phrase) { if (phrase == null || phrase.trim().length() == 0) return true; phrase = phrase.toLowerCase(); String[] terms = phrase.split("\\s"); for (String term : terms) { if (section.getName().toLowerCase().contains(term)) return true; List<String> keywords = getKeywords(section.getBody()); for (String keyword : keywords) { if (keyword.contains(term)) return true; } if (term.contains("*") || term.contains("?") || term.contains("[")) { WildcardPattern pattern = new WildcardPattern(term); if (pattern.matches(section.getName().toLowerCase())) return true; for (String keyword : keywords) { if (pattern.matches(keyword)) return true; } } } return false; } private List<String> getKeywords(JComponent jc) { List<String> returnValue = new ArrayList<>(); if (jc instanceof LazyDemoPanel) { LazyDemoPanel ldp = (LazyDemoPanel) jc; ShowcaseDemo d = ldp.getShowcaseDemo(); if (d.getKeywords() == null) throw new NullPointerException(jc.getClass().getName()); for (String keyword : d.getKeywords()) { returnValue.add(keyword.toLowerCase()); } for (Class z : d.getClasses()) { int layer = 0; /* * Include at least 4 layers: CircularProgressBarUI -> * BasicProgressBarUI -> ProgressBarUI -> ComponentUI */ while (z != null && !z.equals(Object.class) && layer < 4) { returnValue.add(z.getSimpleName().toLowerCase()); returnValue.add(z.getName().toLowerCase()); z = z.getSuperclass(); layer++; } } } for (int a = 0; a < jc.getComponentCount(); a++) { if (jc.getComponent(a) instanceof JComponent) returnValue.addAll(getKeywords((JComponent) jc .getComponent(a))); } return returnValue; } }; ActionListener saveScreenshotActionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { createScreenshot(null); } catch (Exception e2) { e2.printStackTrace(); } } }; public PumpernickelShowcaseApp() { super("Pumpernickel Showcase"); setJMenuBar(menuBar); menuBar.add(editMenu); menuBar.add(new WindowMenu(this, magnifierItem, saveScreenshotItem)); saveScreenshotItem.addActionListener(saveScreenshotActionListener); saveScreenshotItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); // TODO: add help menu/about menu item // menuBar.add(helpMenu); magnifierItem.addActionListener(magnifierListener); getContentPane().setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.weightx = 1; c.weighty = 0; c.fill = GridBagConstraints.BOTH; c.gridy++; c.weighty = 1; getContentPane().add(sectionContainer, c); searchField.setUI(new RoundTextFieldUI()); searchField.putClientProperty("JTextField.variant", "search"); searchPrompt = new TextFieldPrompt(searchField, "Loading..."); searchField.setBorder(new CompoundBorder(new EmptyBorder(3, 3, 3, 3), searchField.getBorder())); searchField.getDocument().addDocumentListener(searchDocListener); c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.weightx = 1; c.weighty = 1; c.insets = new Insets(2, 2, 2, 2); c.fill = GridBagConstraints.BOTH; searchFieldPanel.add(searchField, c); c.gridx++; c.weightx = 0; c.fill = GridBagConstraints.NONE; searchFieldPanel.add(loadingThrobberManager.createThrobber(), c); getContentPane().setPreferredSize(new Dimension(800, 600)); try { addSection("Transition2D", "Transition2DDemo"); addSection("Transition3D", "Transition3DDemo"); addSection("BmpEncoder, BmpDecoder", "BmpComparisonDemo"); addSection("AlphaComposite", "AlphaCompositeDemo"); addSection("TextEffect", "TextEffectDemo"); addSection("AWTMonitor", "AWTMonitorDemo"); addSection("GradientTexturePaint", "GradientTexturePaintDemo"); addSection("ClickSensitivityControl", "ClickSensitivityControlDemo"); addSection("ShapeBounds", "ShapeBoundsDemo"); addSection("Clipper", "ClipperDemo"); addSection("AngleSliderUI", "AngleSliderUIDemo"); addSection("Spiral2D", "Spiral2DDemo"); addSection("DecoratedListUI, DecoratedTreeUI", "DecoratedDemo"); addSection("JThrobber", "ThrobberDemo"); addSection("JBreadCrumb", "BreadCrumbDemo"); addSection("CollapsibleContainer", "CollapsibleContainerDemo"); addSection("CustomizedToolbar", "CustomizedToolbarDemo"); addSection("JToolTip, QPopupFactory", "JToolTipDemo"); addSection("JPopover", "JPopoverDemo"); addSection("Scaling", "ScalingDemo"); // addSection("ImageQuantization", new ImageQuantizationDemo()); addSection("JColorPicker", "JColorPickerDemo"); addSection("QButtonUI", "QButtonUIDemo"); // addSection("Shapes: AreaX Tests", new AreaXTestPanel()); addSection("GraphicsWriterDebugger", "GraphicsWriterDebuggerDemo"); addSection("JPEGMetaData", "JPEGMetaDataDemo"); addSection("QPanelUI", "QPanelUIDemo"); addSection("AudioPlayer", "AudioPlayerDemo"); addSection("JavaTextComponentHighlighter", "JavaTextComponentHighlighterDemo"); addSection("XMLTextComponentHighlighter", "XMLTextComponentHighlighterDemo"); // addSection("Text: Search Controls", new TextSearchDemo()); // addSection("QuickTime: Writing Movies", new MovWriterDemo()); addSection("Highlighters, WildcardPattern", "WildcardPatternHighlighterDemo"); addSection("BoxTabbedPaneUI", "BoxTabbedPaneUIDemo"); addSection("CircularProgressBarUI", "CircularProgressBarUIDemo"); addSection("Strokes, MouseSmoothing", "StrokeMouseSmoothingDemo"); addSection("JColorWell, JPalette", "JColorWellPaletteDemo"); addSection("JEyeDropper", "JEyeDropperDemo"); addSection("JSwitchButton", "JSwitchButtonDemo"); } catch (Exception e) { e.printStackTrace(); } // Type the F1 key to take a screenshot that is automatically // file away in the resources/showcase directory. Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() { File showcaseScreenshotDir; @Override public void eventDispatched(AWTEvent event) { KeyEvent k = (KeyEvent) event; if (k.getID() == KeyEvent.KEY_RELEASED && k.getKeyCode() == KeyEvent.VK_F1) { try { File dir = getShowcaseScreenshotDirectory(); Section section = getSelectedSection(); String defaultName = getDemoName(section.getBody()); createScreenshot(new File(dir, defaultName + ".png")); } catch (Exception e) { e.printStackTrace(); } k.consume(); } } private File getShowcaseScreenshotDirectory() throws Exception { if (showcaseScreenshotDir == null) { Collection<File> candidates = new LinkedHashSet<>(); File dir = new File(System.getProperty("user.dir")); File[] resourceDirs = FileTreeIterator.findAll( new File[] { dir }, "resources"); for (File resourceDir : resourceDirs) { File showcaseDir = new File(resourceDir, "showcase"); if (showcaseDir.exists()) { candidates.add(showcaseDir); } } if (candidates.size() == 1) { showcaseScreenshotDir = candidates.iterator().next(); } else if (candidates.size() == 0) { throw new IOException( "The directory \"resources/showcase\" was not found in " + dir.getAbsolutePath()); } else { throw new IOException( "Multiple candidate target directories were found: " + candidates); } } return showcaseScreenshotDir; } }, AWTEvent.KEY_EVENT_MASK); } /** * Create a worker thread that loads all the demos. The search field is * disabled until this thread completes. */ public void loadDemos() { searchField.setEnabled(false); Thread thread = new Thread("Loading demos") { @Override public void run() { ThrobberManager.Token token = loadingThrobberManager .createToken(); try { loadSections(); } finally { loadingThrobberManager.returnToken(token); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { searchField.setEnabled(true); searchPrompt.setText("Search..."); } }); } } private void loadSections() { for (Section section : sectionContainer.getSections()) { try { final LazyDemoPanel p = (LazyDemoPanel) section .getBody().getComponent(0); final AtomicBoolean loaded = new AtomicBoolean(false); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { try { p.getShowcaseDemo(); } finally { loaded.set(true); } } }); while (!loaded.get()) { try { Thread.sleep(10); } catch (InterruptedException e) { Thread.yield(); } } } catch (Exception e) { e.printStackTrace(); } } } }; thread.start(); } /** * Take a screenshot of the currently selected demo panel. * * @param destFile * an optional target PNG file to write to. If null then the user * is prompted with a file dialog to choose the file destination. */ protected File createScreenshot(File destFile) throws Exception { Section section = getSelectedSection(); BufferedImage bi = getScreenshot(section.getBody()); if (destFile == null) { String defaultName = getDemoName(section.getBody()); destFile = FileDialogUtils.showSaveDialog( PumpernickelShowcaseApp.this, "Export as...", defaultName + ".png", "png"); } ImageIO.write(bi, "png", destFile); System.out.println("Saved screenshot as " + destFile.getAbsolutePath()); return destFile; } /** * Return the name of the showcase demo panel in the given component. */ private String getDemoName(Component c) { Class z = c.getClass(); if (z.getName().contains("pump.showcase.")) return z.getSimpleName(); if (c instanceof Container) { Container c2 = (Container) c; for (Component child : c2.getComponents()) { String n = getDemoName(child); if (n != null) return n; } } return null; } /** * Capture a screenshot based on the position of the given panel. * <p> * This uses a Robot to actually capture the real screenshot in case other * floating layers/windows are meant to be captured. */ private BufferedImage getScreenshot(JPanel panel) throws Exception { Robot robot = new Robot(); Point p = panel.getLocationOnScreen(); Rectangle screenRect = new Rectangle(p.x, p.y, panel.getWidth(), panel.getHeight()); return robot.createScreenCapture(screenRect); } /** * Return the selected Section, or throw a NullPointerException if no * selection exists. */ protected Section getSelectedSection() { Section section = sectionContainer.getSelectedSection(); if (section == null) throw new NullPointerException( "Please select a topic in the list on the left to capture a screenshot."); return section; } /** * Create an edit menu. * * Admittedly: this current implementation doesn't actually achieve very * much. It's just a standard cut/copy/paste that is automatically enabled * for text components. The real purpose of this menu is to help legitimize * this window/menubar so this app doesn't feel like it's out of place. */ private JMenu createEditMenu() { JMenu editMenu = new JMenu("Edit"); EditMenuControls editControls = new EditMenuControls(true, true, true, true); JMenuItem cutItem = new JMenuItem( editControls.getAction(EditCommand.CUT)); JMenuItem copyItem = new JMenuItem( editControls.getAction(EditCommand.COPY)); JMenuItem pasteItem = new JMenuItem( editControls.getAction(EditCommand.PASTE)); JMenuItem selectAllItem = new JMenuItem( editControls.getAction(EditCommand.SELECT_ALL)); editMenu.add(cutItem); editMenu.add(copyItem); editMenu.add(pasteItem); editMenu.add(selectAllItem); return editMenu; } private void addSection(String text, String demoClassName) { Section section = sectionContainer.addSection(text, text); masterSectionList.add(section); JPanel body = section.getBody(); body.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.weightx = 1; c.weighty = 1; c.fill = GridBagConstraints.BOTH; body.add(new LazyDemoPanel(demoClassName), c); } class LazyDemoPanel extends JPanel { private static final long serialVersionUID = 1L; CardLayout cardLayout = new CardLayout(); JPanel loadingPanel = new JPanel(); String demoClassName; ShowcaseDemo showcaseDemo; public LazyDemoPanel(String demoClassName) { super(); this.demoClassName = "com.pump.showcase." + demoClassName; setLayout(cardLayout); add(loadingPanel, "loading"); cardLayout.show(this, "loading"); // loadingPanel is never really shown to the user, // so there's no point in putting a throbber or other content in it addHierarchyListener(new HierarchyListener() { @Override public void hierarchyChanged(HierarchyEvent e) { if (loadingPanel.isShowing()) { add(createDemoPanel(), "demo"); cardLayout.show(LazyDemoPanel.this, "demo"); removeHierarchyListener(this); } } }); } ShowcaseDemo getShowcaseDemo() { if (showcaseDemo == null) { try { Class demoClass = Class.forName(demoClassName); showcaseDemo = (ShowcaseDemo) demoClass.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } return showcaseDemo; } private JComponent createDemoPanel() { ActionListener actionListener = new ActionListener() { JScrollPane scrollPane; JFancyBox box; JEditorPane textPane; @Override public void actionPerformed(ActionEvent e) { if (scrollPane == null) { textPane = createTextPane(getShowcaseDemo() .getHelpURL()); scrollPane = new JScrollPane(textPane); updatePreferredSize(); PumpernickelShowcaseApp.this .addComponentListener(new ComponentAdapter() { @Override public void componentResized( ComponentEvent e) { updatePreferredSize(); } }); try { textPane.setPage(getShowcaseDemo().getHelpURL()); box = new JFancyBox(PumpernickelShowcaseApp.this, scrollPane); } catch (IOException e2) { e2.printStackTrace(); } } box.setVisible(true); } private void updatePreferredSize() { Dimension d = PumpernickelShowcaseApp.this.getSize(); d.width = Math.max(200, d.width - 100); d.height = Math.max(200, d.height - 100); scrollPane.setMinimumSize(d); scrollPane.setPreferredSize(d); textPane.setMinimumSize(d); textPane.setPreferredSize(d); SwingUtilities.invokeLater(new Runnable() { public void run() { scrollPane.revalidate(); } }); } }; JPanel replacement = new JPanel(new GridBagLayout()); JTextArea headerTextArea = createTextArea(getShowcaseDemo() .getTitle(), 18); JTextArea descriptionTextArea = createTextArea(getShowcaseDemo() .getSummary(), 14); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.weightx = 1; c.weighty = 0; c.fill = GridBagConstraints.BOTH; c.insets = new Insets(10, 3, 3, 3); replacement.add(headerTextArea, c); c.gridx++; c.weightx = 0; JComponent jc = HelpComponent.createHelpComponent(actionListener, null, null); c.anchor = GridBagConstraints.EAST; c.fill = GridBagConstraints.NONE; c.insets = new Insets(6, 3, 3, 3); replacement.add(jc, c); jc.setVisible(getShowcaseDemo().getHelpURL() != null); c.gridx = 0; c.gridwidth = GridBagConstraints.REMAINDER; c.fill = GridBagConstraints.BOTH; c.gridy++; replacement.add(descriptionTextArea, c); c.gridy++; replacement.add(new JSeparator(), c); c.gridy++; c.weighty = 1; c.insets = new Insets(3, 3, 3, 3); replacement.add((JPanel) getShowcaseDemo(), c); return replacement; } } private JTextArea createTextArea(String str, float fontSize) { JTextArea t = new JTextArea(str); Font font = UIManager.getFont("Label.font"); if(font==null) font = t.getFont(); t.setFont(font.deriveFont(fontSize)); t.setEditable(false); t.setOpaque(false); t.setLineWrap(true); t.setWrapStyleWord(true); return t; } public JEditorPane createTextPane(URL url) { JEditorPane textPane = new JEditorPane() { private static final long serialVersionUID = 1L; public void paint(Graphics g0) { Graphics2D g = (Graphics2D) g0; // for text bullets: g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); super.paint(g); } }; textPane.setEditable(false); HTMLEditorKit kit = new HTMLEditorKit(); textPane.setEditorKit(kit); StyleSheet styleSheet = kit.getStyleSheet(); styleSheet .addRule("body { padding: 12em 12em 12em 12em; margin: 0; font-family: sans-serif; color: black; background: white; background-position: top left; background-attachment: fixed; background-repeat: no-repeat;}"); styleSheet.addRule("h1, h2, h3, h4, h5, h6 { text-align: left }"); styleSheet.addRule("h1, h2, h3 { color: #005a9c }"); styleSheet.addRule("h1 { font: 160% sans-serif }"); styleSheet.addRule("h2 { font: 140% sans-serif }"); styleSheet.addRule("h3 { font: 120% sans-serif }"); styleSheet.addRule("h4 { font: bold 100% sans-serif }"); styleSheet.addRule("h5 { font: italic 100% sans-serif }"); styleSheet.addRule("h6 { font: small-caps 100% sans-serif }"); textPane.addHyperlinkListener(new HyperlinkListener() { public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { URL url = e.getURL(); String str = e.getDescription(); if (str != null && str.startsWith("resource:")) { str = str.substring("resource:".length()); searchField.setText(str); return; } try { Desktop.getDesktop().browse(url.toURI()); } catch (IOException e1) { e1.printStackTrace(); } catch (URISyntaxException e1) { e1.printStackTrace(); } } } }); return textPane; } void closeFancyBoxes() { closeFancyBoxes(getLayeredPane()); } void closeFancyBoxes(Container container) { for (int a = 0; a < container.getComponentCount(); a++) { Component c = container.getComponent(a); if (c instanceof JFancyBox) { c.setVisible(false); } else if (c instanceof Container) { closeFancyBoxes((Container) c); } } } /** * Add a CollapsibleContainer to a panel so it fills the space and gives * equal vertical weight to non-closable sections. * * @param panel * @param collapsibleContainer * @param sections */ public static void installSections(JPanel panel, CollapsibleContainer collapsibleContainer, Section... sections) { panel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.weightx = 1; c.weighty = 1; c.fill = GridBagConstraints.BOTH; c.insets = new Insets(3, 3, 3, 3); panel.add(collapsibleContainer, c); for (Section section : sections) { section.setProperty(CollapsibleContainer.VERTICAL_WEIGHT, 1); collapsibleContainer.getHeader(section).putClientProperty( CollapsibleContainer.COLLAPSIBLE, Boolean.FALSE); } } }
src/main/java/com/pump/showcase/PumpernickelShowcaseApp.java
/** * This software is released as part of the Pumpernickel project. * * All com.pump resources in the Pumpernickel project are distributed under the * MIT License: * https://raw.githubusercontent.com/mickleness/pumpernickel/master/License.txt * * More information about the Pumpernickel project is available here: * https://mickleness.github.io/pumpernickel/ */ package com.pump.showcase; import java.awt.AWTEvent; import java.awt.CardLayout; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Desktop; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Robot; import java.awt.Toolkit; import java.awt.event.AWTEventListener; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.HierarchyEvent; import java.awt.event.HierarchyListener; import java.awt.event.KeyEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.LinkedHashSet; import java.util.List; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicBoolean; import javax.imageio.ImageIO; import javax.swing.JButton; import javax.swing.JCheckBoxMenuItem; import javax.swing.JComponent; import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.JWindow; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.Timer; import javax.swing.border.CompoundBorder; import javax.swing.border.EmptyBorder; import javax.swing.border.LineBorder; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import javax.swing.text.html.HTMLEditorKit; import javax.swing.text.html.StyleSheet; import com.pump.desktop.DesktopApplication; import com.pump.desktop.edit.EditCommand; import com.pump.desktop.edit.EditMenuControls; import com.pump.icon.button.MinimalDuoToneCloseIcon; import com.pump.io.FileTreeIterator; import com.pump.plaf.RoundTextFieldUI; import com.pump.swing.CollapsibleContainer; import com.pump.swing.FileDialogUtils; import com.pump.swing.HelpComponent; import com.pump.swing.JFancyBox; import com.pump.swing.ListSectionContainer; import com.pump.swing.MagnificationPanel; import com.pump.swing.SectionContainer.Section; import com.pump.swing.TextFieldPrompt; import com.pump.swing.ThrobberManager; import com.pump.text.WildcardPattern; import com.pump.util.JVM; import com.pump.window.WindowDragger; import com.pump.window.WindowMenu; public class PumpernickelShowcaseApp extends JFrame { private static final long serialVersionUID = 1L; public static void main(String[] args) throws IOException { DesktopApplication.initialize("com.pump.showcase", "Showcase", "1.01", "jeremy.wood@mac.com", PumpernickelShowcaseApp.class); SwingUtilities.invokeLater(new Runnable() { public void run() { PumpernickelShowcaseApp p = new PumpernickelShowcaseApp(); p.pack(); p.setLocationRelativeTo(null); p.setVisible(true); p.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); p.loadDemos(); } }); } JTextField searchField = new JTextField(); JPanel searchFieldPanel = new JPanel(new GridBagLayout()); TextFieldPrompt searchPrompt; List<Section> masterSectionList = new ArrayList<>(); ListSectionContainer sectionContainer = new ListSectionContainer(true, null, searchFieldPanel); JMenuBar menuBar = new JMenuBar(); JMenu editMenu = createEditMenu(); JMenu helpMenu = new JMenu("Help"); JCheckBoxMenuItem magnifierItem = new JCheckBoxMenuItem("Magnifier"); JMenuItem saveScreenshotItem = new JMenuItem("Save Screenshot..."); ThrobberManager loadingThrobberManager = new ThrobberManager(); ActionListener magnifierListener = new ActionListener() { JWindow magnifierWindow; JButton closeButton = new JButton(); Timer repaintTimer; MagnificationPanel p; @Override public void actionPerformed(ActionEvent e) { if (magnifierWindow == null) { magnifierWindow = createWindow(); } magnifierWindow.setVisible(magnifierItem.isSelected()); } private JWindow createWindow() { // TODO: this is OK for now, but eventually let's: // 1. Update to a resizable dialog (the MagnificationPanel doesn't // handle resizes yet.) // 2. Support zooming in/out of the MagnificationPanel // 3. Fix MagnificationPanel.setPixelated(false), offer // checkbox/context menu to toggle JWindow w = new JWindow(PumpernickelShowcaseApp.this); // on Macs this gives the window a certain look, plus it hides // the window when the app loses focus. w.getRootPane().putClientProperty("Window.style", "small"); p = new MagnificationPanel(PumpernickelShowcaseApp.this, 40, 40, 4); // on Mac the window shadows show the boundaries well enough. // Otherwise let's paint it clearly: if (!JVM.isMac) p.setBorder(new LineBorder(Color.gray)); w.setLayout(new GridBagLayout()); w.setAlwaysOnTop(true); w.setLocationRelativeTo(PumpernickelShowcaseApp.this); new WindowDragger(p).setActive(true); w.setFocusableWindowState(false); closeButton.setIcon(new MinimalDuoToneCloseIcon(closeButton)); closeButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { magnifierItem.doClick(); } }); closeButton.setContentAreaFilled(false); closeButton.setBorderPainted(false); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.insets = new Insets(0, 0, 0, 0); c.anchor = GridBagConstraints.NORTHWEST; c.weightx = 0; c.weighty = 0; c.fill = GridBagConstraints.NONE; w.add(closeButton, c); c.insets = new Insets(0, 0, 0, 0); c.weightx = 1; c.weighty = 1; c.fill = GridBagConstraints.BOTH; w.add(p, c); w.pack(); repaintTimer = new Timer(25, new ActionListener() { public void actionPerformed(ActionEvent e) { p.refresh(); } }); repaintTimer.start(); return w; } }; private DocumentListener searchDocListener = new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { change(); } @Override public void removeUpdate(DocumentEvent e) { change(); } @Override public void changedUpdate(DocumentEvent e) { } private void change() { closeFancyBoxes(); String str = searchField.getText(); Comparator<Section> comparator = new Comparator<Section>() { @Override public int compare(Section o1, Section o2) { return o1.getName().toLowerCase() .compareTo(o2.getName().toLowerCase()); } }; Collection<Section> matches = new TreeSet<>(comparator); for (Section section : masterSectionList) { if (isMatching(section, str)) matches.add(section); } sectionContainer.getSections().setAll( matches.toArray(new Section[matches.size()])); } private boolean isMatching(Section section, String phrase) { if (phrase == null || phrase.trim().length() == 0) return true; phrase = phrase.toLowerCase(); String[] terms = phrase.split("\\s"); for (String term : terms) { if (section.getName().toLowerCase().contains(term)) return true; List<String> keywords = getKeywords(section.getBody()); for (String keyword : keywords) { if (keyword.contains(term)) return true; } if (term.contains("*") || term.contains("?") || term.contains("[")) { WildcardPattern pattern = new WildcardPattern(term); if (pattern.matches(section.getName().toLowerCase())) return true; for (String keyword : keywords) { if (pattern.matches(keyword)) return true; } } } return false; } private List<String> getKeywords(JComponent jc) { List<String> returnValue = new ArrayList<>(); if (jc instanceof LazyDemoPanel) { LazyDemoPanel ldp = (LazyDemoPanel) jc; ShowcaseDemo d = ldp.getShowcaseDemo(); if (d.getKeywords() == null) throw new NullPointerException(jc.getClass().getName()); for (String keyword : d.getKeywords()) { returnValue.add(keyword.toLowerCase()); } for (Class z : d.getClasses()) { int layer = 0; /* * Include at least 4 layers: CircularProgressBarUI -> * BasicProgressBarUI -> ProgressBarUI -> ComponentUI */ while (z != null && !z.equals(Object.class) && layer < 4) { returnValue.add(z.getSimpleName().toLowerCase()); returnValue.add(z.getName().toLowerCase()); z = z.getSuperclass(); layer++; } } } for (int a = 0; a < jc.getComponentCount(); a++) { if (jc.getComponent(a) instanceof JComponent) returnValue.addAll(getKeywords((JComponent) jc .getComponent(a))); } return returnValue; } }; ActionListener saveScreenshotActionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { createScreenshot(null); } catch (Exception e2) { e2.printStackTrace(); } } }; public PumpernickelShowcaseApp() { super("Pumpernickel Showcase"); setJMenuBar(menuBar); menuBar.add(editMenu); menuBar.add(new WindowMenu(this, magnifierItem, saveScreenshotItem)); saveScreenshotItem.addActionListener(saveScreenshotActionListener); saveScreenshotItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); // TODO: add help menu/about menu item // menuBar.add(helpMenu); magnifierItem.addActionListener(magnifierListener); getContentPane().setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.weightx = 1; c.weighty = 0; c.fill = GridBagConstraints.BOTH; c.gridy++; c.weighty = 1; getContentPane().add(sectionContainer, c); searchField.setUI(new RoundTextFieldUI()); searchField.putClientProperty("JTextField.variant", "search"); searchPrompt = new TextFieldPrompt(searchField, "Loading..."); searchField.setBorder(new CompoundBorder(new EmptyBorder(3, 3, 3, 3), searchField.getBorder())); searchField.getDocument().addDocumentListener(searchDocListener); c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.weightx = 1; c.weighty = 1; c.insets = new Insets(2, 2, 2, 2); c.fill = GridBagConstraints.BOTH; searchFieldPanel.add(searchField, c); c.gridx++; c.weightx = 0; c.fill = GridBagConstraints.NONE; searchFieldPanel.add(loadingThrobberManager.createThrobber(), c); getContentPane().setPreferredSize(new Dimension(800, 600)); try { addSection("Transition2D", "Transition2DDemo"); addSection("Transition3D", "Transition3DDemo"); addSection("BmpEncoder, BmpDecoder", "BmpComparisonDemo"); addSection("AlphaComposite", "AlphaCompositeDemo"); addSection("TextEffect", "TextEffectDemo"); addSection("AWTMonitor", "AWTMonitorDemo"); addSection("GradientTexturePaint", "GradientTexturePaintDemo"); addSection("ClickSensitivityControl", "ClickSensitivityControlDemo"); addSection("ShapeBounds", "ShapeBoundsDemo"); addSection("Clipper", "ClipperDemo"); addSection("AngleSliderUI", "AngleSliderUIDemo"); addSection("Spiral2D", "Spiral2DDemo"); addSection("DecoratedListUI, DecoratedTreeUI", "DecoratedDemo"); addSection("JThrobber", "ThrobberDemo"); addSection("JBreadCrumb", "BreadCrumbDemo"); addSection("CollapsibleContainer", "CollapsibleContainerDemo"); addSection("CustomizedToolbar", "CustomizedToolbarDemo"); addSection("JToolTip, QPopupFactory", "JToolTipDemo"); addSection("JPopover", "JPopoverDemo"); addSection("Scaling", "ScalingDemo"); // addSection("ImageQuantization", new ImageQuantizationDemo()); addSection("JColorPicker", "JColorPickerDemo"); addSection("QButtonUI", "QButtonUIDemo"); // addSection("Shapes: AreaX Tests", new AreaXTestPanel()); addSection("GraphicsWriterDebugger", "GraphicsWriterDebuggerDemo"); addSection("JPEGMetaData", "JPEGMetaDataDemo"); addSection("QPanelUI", "QPanelUIDemo"); addSection("AudioPlayer", "AudioPlayerDemo"); addSection("JavaTextComponentHighlighter", "JavaTextComponentHighlighterDemo"); addSection("XMLTextComponentHighlighter", "XMLTextComponentHighlighterDemo"); // addSection("Text: Search Controls", new TextSearchDemo()); // addSection("QuickTime: Writing Movies", new MovWriterDemo()); addSection("Highlighters, WildcardPattern", "WildcardPatternHighlighterDemo"); addSection("BoxTabbedPaneUI", "BoxTabbedPaneUIDemo"); addSection("CircularProgressBarUI", "CircularProgressBarUIDemo"); addSection("Strokes, MouseSmoothing", "StrokeMouseSmoothingDemo"); addSection("JColorWell, JPalette", "JColorWellPaletteDemo"); addSection("JEyeDropper", "JEyeDropperDemo"); addSection("JSwitchButton", "JSwitchButtonDemo"); } catch (Exception e) { e.printStackTrace(); } // Type the F1 key to take a screenshot that is automatically // file away in the resources/showcase directory. Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() { File showcaseScreenshotDir; @Override public void eventDispatched(AWTEvent event) { KeyEvent k = (KeyEvent) event; if (k.getID() == KeyEvent.KEY_RELEASED && k.getKeyCode() == KeyEvent.VK_F1) { try { File dir = getShowcaseScreenshotDirectory(); Section section = getSelectedSection(); String defaultName = getDemoName(section.getBody()); createScreenshot(new File(dir, defaultName + ".png")); } catch (Exception e) { e.printStackTrace(); } k.consume(); } } private File getShowcaseScreenshotDirectory() throws Exception { if (showcaseScreenshotDir == null) { Collection<File> candidates = new LinkedHashSet<>(); File dir = new File(System.getProperty("user.dir")); File[] resourceDirs = FileTreeIterator.findAll( new File[] { dir }, "resources"); for (File resourceDir : resourceDirs) { File showcaseDir = new File(resourceDir, "showcase"); if (showcaseDir.exists()) { candidates.add(showcaseDir); } } if (candidates.size() == 1) { showcaseScreenshotDir = candidates.iterator().next(); } else if (candidates.size() == 0) { throw new IOException( "The directory \"resources/showcase\" was not found in " + dir.getAbsolutePath()); } else { throw new IOException( "Multiple candidate target directories were found: " + candidates); } } return showcaseScreenshotDir; } }, AWTEvent.KEY_EVENT_MASK); } /** * Create a worker thread that loads all the demos. The search field is * disabled until this thread completes. */ public void loadDemos() { searchField.setEnabled(false); Thread thread = new Thread("Loading demos") { @Override public void run() { ThrobberManager.Token token = loadingThrobberManager .createToken(); try { loadSections(); } finally { loadingThrobberManager.returnToken(token); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { searchField.setEnabled(true); searchPrompt.setText("Search..."); } }); } } private void loadSections() { for (Section section : sectionContainer.getSections()) { try { final LazyDemoPanel p = (LazyDemoPanel) section .getBody().getComponent(0); final AtomicBoolean loaded = new AtomicBoolean(false); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { try { p.getShowcaseDemo(); } finally { loaded.set(true); } } }); while (!loaded.get()) { try { Thread.sleep(10); } catch (InterruptedException e) { Thread.yield(); } } } catch (Exception e) { e.printStackTrace(); } } } }; thread.start(); } /** * Take a screenshot of the currently selected demo panel. * * @param destFile * an optional target PNG file to write to. If null then the user * is prompted with a file dialog to choose the file destination. */ protected File createScreenshot(File destFile) throws Exception { Section section = getSelectedSection(); BufferedImage bi = getScreenshot(section.getBody()); if (destFile == null) { String defaultName = getDemoName(section.getBody()); destFile = FileDialogUtils.showSaveDialog( PumpernickelShowcaseApp.this, "Export as...", defaultName + ".png", "png"); } ImageIO.write(bi, "png", destFile); System.out.println("Saved screenshot as " + destFile.getAbsolutePath()); return destFile; } /** * Return the name of the showcase demo panel in the given component. */ private String getDemoName(Component c) { Class z = c.getClass(); if (z.getName().contains("pump.showcase.")) return z.getSimpleName(); if (c instanceof Container) { Container c2 = (Container) c; for (Component child : c2.getComponents()) { String n = getDemoName(child); if (n != null) return n; } } return null; } /** * Capture a screenshot based on the position of the given panel. * <p> * This uses a Robot to actually capture the real screenshot in case other * floating layers/windows are meant to be captured. */ private BufferedImage getScreenshot(JPanel panel) throws Exception { Robot robot = new Robot(); Point p = panel.getLocationOnScreen(); Rectangle screenRect = new Rectangle(p.x, p.y, panel.getWidth(), panel.getHeight()); return robot.createScreenCapture(screenRect); } /** * Return the selected Section, or throw a NullPointerException if no * selection exists. */ protected Section getSelectedSection() { Section section = sectionContainer.getSelectedSection(); if (section == null) throw new NullPointerException( "Please select a topic in the list on the left to capture a screenshot."); return section; } /** * Create an edit menu. * * Admittedly: this current implementation doesn't actually achieve very * much. It's just a standard cut/copy/paste that is automatically enabled * for text components. The real purpose of this menu is to help legitimize * this window/menubar so this app doesn't feel like it's out of place. */ private JMenu createEditMenu() { JMenu editMenu = new JMenu("Edit"); EditMenuControls editControls = new EditMenuControls(true, true, true, true); JMenuItem cutItem = new JMenuItem( editControls.getAction(EditCommand.CUT)); JMenuItem copyItem = new JMenuItem( editControls.getAction(EditCommand.COPY)); JMenuItem pasteItem = new JMenuItem( editControls.getAction(EditCommand.PASTE)); JMenuItem selectAllItem = new JMenuItem( editControls.getAction(EditCommand.SELECT_ALL)); editMenu.add(cutItem); editMenu.add(copyItem); editMenu.add(pasteItem); editMenu.add(selectAllItem); return editMenu; } private void addSection(String text, String demoClassName) { Section section = sectionContainer.addSection(text, text); masterSectionList.add(section); JPanel body = section.getBody(); body.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.weightx = 1; c.weighty = 1; c.fill = GridBagConstraints.BOTH; body.add(new LazyDemoPanel(demoClassName), c); } class LazyDemoPanel extends JPanel { private static final long serialVersionUID = 1L; CardLayout cardLayout = new CardLayout(); JPanel loadingPanel = new JPanel(); String demoClassName; ShowcaseDemo showcaseDemo; public LazyDemoPanel(String demoClassName) { super(); this.demoClassName = "com.pump.showcase." + demoClassName; setLayout(cardLayout); add(loadingPanel, "loading"); cardLayout.show(this, "loading"); // loadingPanel is never really shown to the user, // so there's no point in putting a throbber or other content in it addHierarchyListener(new HierarchyListener() { @Override public void hierarchyChanged(HierarchyEvent e) { if (loadingPanel.isShowing()) { add(createDemoPanel(), "demo"); cardLayout.show(LazyDemoPanel.this, "demo"); removeHierarchyListener(this); } } }); } ShowcaseDemo getShowcaseDemo() { if (showcaseDemo == null) { try { Class demoClass = Class.forName(demoClassName); showcaseDemo = (ShowcaseDemo) demoClass.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } return showcaseDemo; } private JComponent createDemoPanel() { ActionListener actionListener = new ActionListener() { JScrollPane scrollPane; JFancyBox box; JEditorPane textPane; @Override public void actionPerformed(ActionEvent e) { if (scrollPane == null) { textPane = createTextPane(getShowcaseDemo() .getHelpURL()); scrollPane = new JScrollPane(textPane); updatePreferredSize(); PumpernickelShowcaseApp.this .addComponentListener(new ComponentAdapter() { @Override public void componentResized( ComponentEvent e) { updatePreferredSize(); } }); try { textPane.setPage(getShowcaseDemo().getHelpURL()); box = new JFancyBox(PumpernickelShowcaseApp.this, scrollPane); } catch (IOException e2) { e2.printStackTrace(); } } box.setVisible(true); } private void updatePreferredSize() { Dimension d = PumpernickelShowcaseApp.this.getSize(); d.width = Math.max(200, d.width - 100); d.height = Math.max(200, d.height - 100); scrollPane.setMinimumSize(d); scrollPane.setPreferredSize(d); textPane.setMinimumSize(d); textPane.setPreferredSize(d); SwingUtilities.invokeLater(new Runnable() { public void run() { scrollPane.revalidate(); } }); } }; JPanel replacement = new JPanel(new GridBagLayout()); JTextArea headerTextArea = createTextArea(getShowcaseDemo() .getTitle(), 18); JTextArea descriptionTextArea = createTextArea(getShowcaseDemo() .getSummary(), 14); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.weightx = 1; c.weighty = 0; c.fill = GridBagConstraints.BOTH; c.insets = new Insets(10, 3, 3, 3); replacement.add(headerTextArea, c); c.gridx++; c.weightx = 0; JComponent jc = HelpComponent.createHelpComponent(actionListener, null, null); c.anchor = GridBagConstraints.EAST; c.fill = GridBagConstraints.NONE; c.insets = new Insets(6, 3, 3, 3); replacement.add(jc, c); jc.setVisible(getShowcaseDemo().getHelpURL() != null); c.gridx = 0; c.gridwidth = GridBagConstraints.REMAINDER; c.fill = GridBagConstraints.BOTH; c.gridy++; replacement.add(descriptionTextArea, c); c.gridy++; replacement.add(new JSeparator(), c); c.gridy++; c.weighty = 1; c.insets = new Insets(3, 3, 3, 3); replacement.add((JPanel) getShowcaseDemo(), c); return replacement; } } private JTextArea createTextArea(String str, float fontSize) { JTextArea t = new JTextArea(str); t.setFont(t.getFont().deriveFont(fontSize)); t.setEditable(false); t.setOpaque(false); t.setLineWrap(true); t.setWrapStyleWord(true); return t; } public JEditorPane createTextPane(URL url) { JEditorPane textPane = new JEditorPane() { private static final long serialVersionUID = 1L; public void paint(Graphics g0) { Graphics2D g = (Graphics2D) g0; // for text bullets: g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); super.paint(g); } }; textPane.setEditable(false); HTMLEditorKit kit = new HTMLEditorKit(); textPane.setEditorKit(kit); StyleSheet styleSheet = kit.getStyleSheet(); styleSheet .addRule("body { padding: 12em 12em 12em 12em; margin: 0; font-family: sans-serif; color: black; background: white; background-position: top left; background-attachment: fixed; background-repeat: no-repeat;}"); styleSheet.addRule("h1, h2, h3, h4, h5, h6 { text-align: left }"); styleSheet.addRule("h1, h2, h3 { color: #005a9c }"); styleSheet.addRule("h1 { font: 160% sans-serif }"); styleSheet.addRule("h2 { font: 140% sans-serif }"); styleSheet.addRule("h3 { font: 120% sans-serif }"); styleSheet.addRule("h4 { font: bold 100% sans-serif }"); styleSheet.addRule("h5 { font: italic 100% sans-serif }"); styleSheet.addRule("h6 { font: small-caps 100% sans-serif }"); textPane.addHyperlinkListener(new HyperlinkListener() { public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { URL url = e.getURL(); String str = e.getDescription(); if (str != null && str.startsWith("resource:")) { str = str.substring("resource:".length()); searchField.setText(str); return; } try { Desktop.getDesktop().browse(url.toURI()); } catch (IOException e1) { e1.printStackTrace(); } catch (URISyntaxException e1) { e1.printStackTrace(); } } } }); return textPane; } void closeFancyBoxes() { closeFancyBoxes(getLayeredPane()); } void closeFancyBoxes(Container container) { for (int a = 0; a < container.getComponentCount(); a++) { Component c = container.getComponent(a); if (c instanceof JFancyBox) { c.setVisible(false); } else if (c instanceof Container) { closeFancyBoxes((Container) c); } } } /** * Add a CollapsibleContainer to a panel so it fills the space and gives * equal vertical weight to non-closable sections. * * @param panel * @param collapsibleContainer * @param sections */ public static void installSections(JPanel panel, CollapsibleContainer collapsibleContainer, Section... sections) { panel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.weightx = 1; c.weighty = 1; c.fill = GridBagConstraints.BOTH; c.insets = new Insets(3, 3, 3, 3); panel.add(collapsibleContainer, c); for (Section section : sections) { section.setProperty(CollapsibleContainer.VERTICAL_WEIGHT, 1); collapsibleContainer.getHeader(section).putClientProperty( CollapsibleContainer.COLLAPSIBLE, Boolean.FALSE); } } }
Fixing text area fonts on Windows
src/main/java/com/pump/showcase/PumpernickelShowcaseApp.java
Fixing text area fonts on Windows
Java
epl-1.0
93a02dfe1030b039e8a20ed916b223c3b1d463bb
0
dashzh/Java,dashzh/Java
package task.z06.servlet; import java.io.IOException; import java.io.PrintWriter; import java.sql.SQLException; import java.util.Base64; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.sql.DataSource; import task.z04.DataSourceManager; import task.z04.entity.AppUser; import task.z04.exception.AuthorizationException; import task.z04.exception.DBStructuralIntegrityException; import task.z06.DoubleTuple; public class AuthorizedServlet extends AbstractServlet { public static final String AUTHORIZATION_SERVLET = "authServlet"; private DoubleTuple<String, String> extractCredentials(HttpServletRequest request) { String encodedValue = request.getParameter("input-cred"); if (encodedValue == null || encodedValue.isEmpty()) return null; byte[] decodedValue = Base64.getDecoder().decode(encodedValue); String decoded = new String(decodedValue); String login = decoded.substring(0, decoded.indexOf(":")); String password = decoded.substring(decoded.indexOf(":") + 1); DoubleTuple<String, String> credentials = new DoubleTuple<String, String>(login, password); return credentials; } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html; charset=UTF-8"); HttpSession session = req.getSession(); if (session.getAttribute("dbauth") == null) { DoubleTuple<String, String> credentials = extractCredentials(req); if (credentials == null) seeOther(resp, MainServlet.MAIN_SERVLET); try { // Осуществление входа в БД DoubleTuple<DataSource, AppUser> loginData = DataSourceManager.tryLogIn(credentials.first, credentials.second); session.setAttribute("dbauth", loginData); } catch (SQLException | DBStructuralIntegrityException | AuthorizationException e) { PrintWriter writer = resp.getWriter(); e.printStackTrace(writer); } } seeOther(resp, MainServlet.MAIN_SERVLET); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) { seeOther(resp, MainServlet.MAIN_SERVLET); } @Override public void init(ServletConfig servletConfig) throws ServletException { super.init(servletConfig); } private static final long serialVersionUID = -3988422067060656591L; }
Task06/src/main/java/task/z06/servlet/AuthorizedServlet.java
package task.z06.servlet; import java.io.IOException; import java.io.PrintWriter; import java.sql.SQLException; import java.util.Base64; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.sql.DataSource; import task.z04.DataSourceManager; import task.z04.entity.AppUser; import task.z04.exception.AuthorizationException; import task.z04.exception.DBStructuralIntegrityException; import task.z06.DoubleTuple; public class AuthorizedServlet extends AbstractServlet { public static final String AUTHORIZATION_SERVLET = "authServlet"; private DoubleTuple<String, String> extractCredentials(HttpServletRequest request) { String encodedValue = request.getParameter("input-cred"); if (encodedValue == null || encodedValue.isEmpty()) return null; byte[] decodedValue = Base64.getDecoder().decode(encodedValue); String decoded = new String(decodedValue); String login = decoded.substring(0, decoded.indexOf(":")); String password = decoded.substring(decoded.indexOf(":") + 1); DoubleTuple<String, String> credentials = new DoubleTuple<String, String>(login, password); return credentials; } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html; charset=UTF-8"); HttpSession session = req.getSession(); if (session.getAttribute("dbauth") == null) { DoubleTuple<String, String> credentials = extractCredentials(req); if (credentials == null) seeOther(resp, MainServlet.MAIN_SERVLET); try { // DoubleTuple<DataSource, AppUser> loginData = DataSourceManager.tryLogIn(credentials.first, credentials.second); session.setAttribute("dbauth", loginData); } catch (SQLException | DBStructuralIntegrityException | AuthorizationException e) { PrintWriter writer = resp.getWriter(); e.printStackTrace(writer); } } seeOther(resp, MainServlet.MAIN_SERVLET); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) { seeOther(resp, MainServlet.MAIN_SERVLET); } @Override public void init(ServletConfig servletConfig) throws ServletException { super.init(servletConfig); } private static final long serialVersionUID = -3988422067060656591L; }
Update AuthorizedServlet.java
Task06/src/main/java/task/z06/servlet/AuthorizedServlet.java
Update AuthorizedServlet.java
Java
lgpl-2.1
581a2cce444c584d666ff7cba4802cd14f131a49
0
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
// // $Id: GameController.java,v 1.13 2002/05/07 00:49:24 mdb Exp $ package com.threerings.parlor.game; import java.awt.event.ActionEvent; import com.samskivert.swing.Controller; import com.threerings.presents.dobj.*; import com.threerings.crowd.client.PlaceController; import com.threerings.crowd.client.PlaceControllerDelegate; import com.threerings.crowd.data.PlaceConfig; import com.threerings.crowd.data.PlaceObject; import com.threerings.crowd.util.CrowdContext; import com.threerings.parlor.Log; import com.threerings.parlor.util.ParlorContext; /** * The game controller manages the flow and control of a game on the * client side. This class serves as the root of a hierarchy of controller * classes that aim to provide functionality shared between various * similar games. The base controller provides functionality for starting * and ending the game and for calculating ratings adjustements when a * game ends normally. It also handles the basic house keeping like * subscription to the game object and dispatch of commands and * distributed object events. */ public abstract class GameController extends PlaceController implements AttributeChangeListener, GameCodes { /** * Initializes this game controller with the game configuration that * was established during the match making process. Derived classes * may want to override this method to initialize themselves with * game-specific configuration parameters but they should be sure to * call <code>super.init</code> in such cases. * * @param ctx the client context. * @param config the configuration of the game we are intended to * control. */ public void init (CrowdContext ctx, PlaceConfig config) { // cast our references before we call super.init() so that when // super.init() calls createPlaceView(), we have our casted // references already in place _ctx = (ParlorContext)ctx; _config = (GameConfig)config; super.init(ctx, config); } /** * Adds this controller as a listener to the game object (thus derived * classes need not do so) and lets the game manager know that we are * now ready to go. */ public void willEnterPlace (PlaceObject plobj) { super.willEnterPlace(plobj); // obtain a casted reference _gobj = (GameObject)plobj; // and add ourselves as a listener _gobj.addListener(this); // finally let the game manager know that we're ready to roll MessageEvent mevt = new MessageEvent( _gobj.getOid(), PLAYER_READY_NOTIFICATION, null); _ctx.getDObjectManager().postEvent(mevt); } /** * Removes our listener registration from the game object and cleans * house. */ public void didLeavePlace (PlaceObject plobj) { super.didLeavePlace(plobj); // unlisten to the game object _gobj.removeListener(this); _gobj = null; } /** * Returns whether the game is over. */ public boolean isGameOver () { boolean gameOver = (_gobj != null) ? (_gobj.state != GameObject.IN_PLAY) : true); return (_gameOver || gameOver); } /** * Sets the client game over override. This is used in situations * where we determine that the game is over before the server has * informed us of such. */ public void setGameOver (boolean gameOver) { _gameOver = gameOver; } /** * Calls {@link #gameWillReset}, ends the current game (locally, it * does not tell the server to end the game), and waits to receive a * reset notification (which is simply an event setting the game state * to <code>IN_PLAY</code> even though it's already set to * <code>IN_PLAY</code>) from the server which will start up a new * game. Derived classes should override {@link #gameWillReset} to * perform any game-specific animations. */ public void resetGame () { // let derived classes do their thing gameWillReset(); // end the game until we receive a new board setGameOver(true); } /** * Handles basic game controller action events. Derived classes should * be sure to call <code>super.handleAction</code> for events they * don't specifically handle. */ public boolean handleAction (ActionEvent action) { return super.handleAction(action); } // documentation inherited public void attributeChanged (AttributeChangedEvent event) { // deal with game state changes if (event.getName().equals(GameObject.STATE)) { switch (event.getIntValue()) { case GameObject.IN_PLAY: gameDidStart(); break; case GameObject.GAME_OVER: gameDidEnd(); break; case GameObject.CANCELLED: gameWasCancelled(); break; default: Log.warning("Game transitioned to unknown state " + "[gobj=" + _gobj + ", state=" + event.getIntValue() + "]."); break; } } } /** * Called when the game transitions to the <code>IN_PLAY</code> * state. This happens when all of the players have arrived and the * server starts the game. */ protected void gameDidStart () { // clear out our game over flag setGameOver(false); // let our delegates do their business applyToDelegates(new DelegateOp() { public void apply (PlaceControllerDelegate delegate) { ((GameControllerDelegate)delegate).gameDidStart(); } }); } /** * Called when the game transitions to the <code>GAME_OVER</code> * state. This happens when the game reaches some end condition by * normal means (is not cancelled or aborted). */ protected void gameDidEnd () { // let our delegates do their business applyToDelegates(new DelegateOp() { public void apply (PlaceControllerDelegate delegate) { ((GameControllerDelegate)delegate).gameDidEnd(); } }); } /** * Called when the game was cancelled for some reason. */ protected void gameWasCancelled () { // let our delegates do their business applyToDelegates(new DelegateOp() { public void apply (PlaceControllerDelegate delegate) { ((GameControllerDelegate)delegate).gameWasCancelled(); } }); } /** * Called to give derived classes a chance to display animations, send * a final packet, or do any other business they care to do when the * game is about to reset. */ protected void gameWillReset () { // let our delegates do their business applyToDelegates(new DelegateOp() { public void apply (PlaceControllerDelegate delegate) { ((GameControllerDelegate)delegate).gameWillReset(); } }); } /** A reference to the active parlor context. */ protected ParlorContext _ctx; /** Our game configuration information. */ protected GameConfig _config; /** A reference to the game object for the game that we're * controlling. */ protected GameObject _gobj; /** A local flag overriding the game over state for situations where * the client knows the game is over before the server has * transitioned the game object accordingly. */ protected boolean _gameOver; }
src/java/com/threerings/parlor/game/GameController.java
// // $Id: GameController.java,v 1.12 2002/04/18 16:57:29 shaper Exp $ package com.threerings.parlor.game; import java.awt.event.ActionEvent; import com.samskivert.swing.Controller; import com.threerings.presents.dobj.*; import com.threerings.crowd.client.PlaceController; import com.threerings.crowd.client.PlaceControllerDelegate; import com.threerings.crowd.data.PlaceConfig; import com.threerings.crowd.data.PlaceObject; import com.threerings.crowd.util.CrowdContext; import com.threerings.parlor.Log; import com.threerings.parlor.util.ParlorContext; /** * The game controller manages the flow and control of a game on the * client side. This class serves as the root of a hierarchy of controller * classes that aim to provide functionality shared between various * similar games. The base controller provides functionality for starting * and ending the game and for calculating ratings adjustements when a * game ends normally. It also handles the basic house keeping like * subscription to the game object and dispatch of commands and * distributed object events. */ public abstract class GameController extends PlaceController implements AttributeChangeListener, GameCodes { /** * Initializes this game controller with the game configuration that * was established during the match making process. Derived classes * may want to override this method to initialize themselves with * game-specific configuration parameters but they should be sure to * call <code>super.init</code> in such cases. * * @param ctx the client context. * @param config the configuration of the game we are intended to * control. */ public void init (CrowdContext ctx, PlaceConfig config) { // cast our references before we call super.init() so that when // super.init() calls createPlaceView(), we have our casted // references already in place _ctx = (ParlorContext)ctx; _config = (GameConfig)config; super.init(ctx, config); } /** * Adds this controller as a listener to the game object (thus derived * classes need not do so) and lets the game manager know that we are * now ready to go. */ public void willEnterPlace (PlaceObject plobj) { super.willEnterPlace(plobj); // obtain a casted reference _gobj = (GameObject)plobj; // and add ourselves as a listener _gobj.addListener(this); // finally let the game manager know that we're ready to roll MessageEvent mevt = new MessageEvent( _gobj.getOid(), PLAYER_READY_NOTIFICATION, null); _ctx.getDObjectManager().postEvent(mevt); } /** * Removes our listener registration from the game object and cleans * house. */ public void didLeavePlace (PlaceObject plobj) { super.didLeavePlace(plobj); // unlisten to the game object _gobj.removeListener(this); _gobj = null; } /** * Returns whether the game is over. */ public boolean isGameOver () { return (_gameOver || _gobj.state != GameObject.IN_PLAY); } /** * Sets the client game over override. This is used in situations * where we determine that the game is over before the server has * informed us of such. */ public void setGameOver (boolean gameOver) { _gameOver = gameOver; } /** * Calls {@link #gameWillReset}, ends the current game (locally, it * does not tell the server to end the game), and waits to receive a * reset notification (which is simply an event setting the game state * to <code>IN_PLAY</code> even though it's already set to * <code>IN_PLAY</code>) from the server which will start up a new * game. Derived classes should override {@link #gameWillReset} to * perform any game-specific animations. */ public void resetGame () { // let derived classes do their thing gameWillReset(); // end the game until we receive a new board setGameOver(true); } /** * Handles basic game controller action events. Derived classes should * be sure to call <code>super.handleAction</code> for events they * don't specifically handle. */ public boolean handleAction (ActionEvent action) { return super.handleAction(action); } // documentation inherited public void attributeChanged (AttributeChangedEvent event) { // deal with game state changes if (event.getName().equals(GameObject.STATE)) { switch (event.getIntValue()) { case GameObject.IN_PLAY: gameDidStart(); break; case GameObject.GAME_OVER: gameDidEnd(); break; case GameObject.CANCELLED: gameWasCancelled(); break; default: Log.warning("Game transitioned to unknown state " + "[gobj=" + _gobj + ", state=" + event.getIntValue() + "]."); break; } } } /** * Called when the game transitions to the <code>IN_PLAY</code> * state. This happens when all of the players have arrived and the * server starts the game. */ protected void gameDidStart () { // clear out our game over flag setGameOver(false); // let our delegates do their business applyToDelegates(new DelegateOp() { public void apply (PlaceControllerDelegate delegate) { ((GameControllerDelegate)delegate).gameDidStart(); } }); } /** * Called when the game transitions to the <code>GAME_OVER</code> * state. This happens when the game reaches some end condition by * normal means (is not cancelled or aborted). */ protected void gameDidEnd () { // let our delegates do their business applyToDelegates(new DelegateOp() { public void apply (PlaceControllerDelegate delegate) { ((GameControllerDelegate)delegate).gameDidEnd(); } }); } /** * Called when the game was cancelled for some reason. */ protected void gameWasCancelled () { // let our delegates do their business applyToDelegates(new DelegateOp() { public void apply (PlaceControllerDelegate delegate) { ((GameControllerDelegate)delegate).gameWasCancelled(); } }); } /** * Called to give derived classes a chance to display animations, send * a final packet, or do any other business they care to do when the * game is about to reset. */ protected void gameWillReset () { // let our delegates do their business applyToDelegates(new DelegateOp() { public void apply (PlaceControllerDelegate delegate) { ((GameControllerDelegate)delegate).gameWillReset(); } }); } /** A reference to the active parlor context. */ protected ParlorContext _ctx; /** Our game configuration information. */ protected GameConfig _config; /** A reference to the game object for the game that we're * controlling. */ protected GameObject _gobj; /** A local flag overriding the game over state for situations where * the client knows the game is over before the server has * transitioned the game object accordingly. */ protected boolean _gameOver; }
Don't choke if we're asked about game over and we've already shut down and pitched our game object. git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@1344 542714f4-19e9-0310-aa3c-eee0fc999fb1
src/java/com/threerings/parlor/game/GameController.java
Don't choke if we're asked about game over and we've already shut down and pitched our game object.
Java
lgpl-2.1
62103ecaa3f8fa79b83e02f606d704dd8f24e75b
0
spotbugs/spotbugs,sewe/spotbugs,spotbugs/spotbugs,johnscancella/spotbugs,johnscancella/spotbugs,KengoTODA/spotbugs,KengoTODA/spotbugs,sewe/spotbugs,johnscancella/spotbugs,sewe/spotbugs,johnscancella/spotbugs,spotbugs/spotbugs,KengoTODA/spotbugs,spotbugs/spotbugs,spotbugs/spotbugs,KengoTODA/spotbugs,sewe/spotbugs
/* * Bytecode Analysis Framework * Copyright (C) 2003, University of Maryland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.umd.cs.daveho.ba; /** * Convert part or all of a Java type signature into something * closer to what types look like in the source code. * Both field and method signatures may be processed by this class. * For a field signature, just call parseNext() once. * For a method signature, parseNext() must be called multiple times, * and the parens around the arguments must be skipped manually * (by calling the skip() method). * * @author David Hovemeyer */ public class SignatureConverter { private String signature; /** * Constructor. * @param signature the field or method signature to convert */ public SignatureConverter(String signature) { this.signature = signature; } /** * Get the first character of the remaining part of the signature. */ public char getFirst() { return signature.charAt(0); } /** * Skip the first character of the remaining part of the signature. */ public void skip() { signature = signature.substring(1); } /** * Parse a single type out of the signature, starting at the beginning * of the remaining part of the signature. For example, if the first * character of the remaining part is "I", then this method will return * "int", and the "I" will be consumed. Arrays, reference types, * and basic types are all handled. * @return the parsed type string */ public String parseNext() { StringBuffer result = new StringBuffer(); if (signature.startsWith("[")) { int dimensions = 0; do { ++dimensions; signature = signature.substring(1); } while (signature.charAt(0) == '['); result.append(parseNext()); while (dimensions-- > 0) { result.append("[]"); } } else if (signature.startsWith("L")) { int semi = signature.indexOf(';'); if (semi < 0) throw new IllegalStateException("missing semicolon in signature " + signature); result.append(signature.substring(1, semi).replace('/', '.')); signature = signature.substring(semi + 1); } else { switch (signature.charAt(0)) { case 'B': result.append("byte"); break; case 'C': result.append("char"); break; case 'D': result.append("double"); break; case 'F': result.append("float"); break; case 'I': result.append("int"); break; case 'J': result.append("long"); break; case 'S': result.append("short"); break; case 'Z': result.append("boolean"); break; default: throw new IllegalStateException("bad signature " + signature); } skip(); } return result.toString(); } public static String convertMethodSignature(org.apache.bcel.generic.MethodGen methodGen) { return convertMethodSignature(methodGen.getClassName(), methodGen.getName(), methodGen.getSignature()); } public static String convertMethodSignature(String className, String methodName, String methodSig) { return convertMethodSignature(className, methodName, methodSig, ""); } public static String convertMethodSignature(String className, String methodName, String methodSig, String pkgName) { StringBuffer args = new StringBuffer(); SignatureConverter converter = new SignatureConverter(methodSig); converter.skip(); args.append('('); while (converter.getFirst() != ')') { if (args.length() > 1) args.append(", "); args.append(shorten(pkgName, converter.parseNext())); } converter.skip(); args.append(')'); // Ignore return type StringBuffer result = new StringBuffer(); result.append(className); result.append('.'); result.append(methodName); result.append(' '); result.append(args.toString()); return result.toString(); } public static String shorten(String pkgName, String typeName) { int index = typeName.lastIndexOf('.'); if (index >= 0 ) { String otherPkg = typeName.substring(0, index); if (otherPkg.equals(pkgName) || otherPkg.equals("java.lang")) typeName = typeName.substring(index + 1); } return typeName; } } // vim:ts=4
findbugs/src/java/edu/umd/cs/findbugs/ba/SignatureConverter.java
/* * Bytecode Analysis Framework * Copyright (C) 2003, University of Maryland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.umd.cs.daveho.ba; /** * Convert part or all of a Java type signature into something * closer to what types look like in the source code. * Both field and method signatures may be processed by this class. * For a field signature, just call parseNext() once. * For a method signature, parseNext() must be called multiple times, * and the parens around the arguments must be skipped manually * (by calling the skip() method). * * @author David Hovemeyer */ public class SignatureConverter { private String signature; /** * Constructor. * @param signature the field or method signature to convert */ public SignatureConverter(String signature) { this.signature = signature; } /** * Get the first character of the remaining part of the signature. */ public char getFirst() { return signature.charAt(0); } /** * Skip the first character of the remaining part of the signature. */ public void skip() { signature = signature.substring(1); } /** * Parse a single type out of the signature, starting at the beginning * of the remaining part of the signature. For example, if the first * character of the remaining part is "I", then this method will return * "int", and the "I" will be consumed. Arrays, reference types, * and basic types are all handled. * @return the parsed type string */ public String parseNext() { StringBuffer result = new StringBuffer(); if (signature.startsWith("[")) { int dimensions = 0; do { ++dimensions; signature = signature.substring(1); } while (signature.charAt(0) == '['); result.append(parseNext()); while (dimensions-- > 0) { result.append("[]"); } } else if (signature.startsWith("L")) { int semi = signature.indexOf(';'); if (semi < 0) throw new IllegalStateException("missing semicolon in signature " + signature); result.append(signature.substring(1, semi).replace('/', '.')); signature = signature.substring(semi + 1); } else { switch (signature.charAt(0)) { case 'B': result.append("byte"); break; case 'C': result.append("char"); break; case 'D': result.append("double"); break; case 'F': result.append("float"); break; case 'I': result.append("int"); break; case 'J': result.append("long"); break; case 'S': result.append("short"); break; case 'Z': result.append("boolean"); break; default: throw new IllegalStateException("bad signature " + signature); } skip(); } return result.toString(); } public static String convertMethodSignature(String className, String methodName, String methodSig) { return convertMethodSignature(className, methodName, methodSig, ""); } public static String convertMethodSignature(String className, String methodName, String methodSig, String pkgName) { StringBuffer args = new StringBuffer(); SignatureConverter converter = new SignatureConverter(methodSig); converter.skip(); args.append('('); while (converter.getFirst() != ')') { if (args.length() > 1) args.append(", "); args.append(shorten(pkgName, converter.parseNext())); } converter.skip(); args.append(')'); // Ignore return type StringBuffer result = new StringBuffer(); result.append(className); result.append('.'); result.append(methodName); result.append(' '); result.append(args.toString()); return result.toString(); } public static String shorten(String pkgName, String typeName) { int index = typeName.lastIndexOf('.'); if (index >= 0 ) { String otherPkg = typeName.substring(0, index); if (otherPkg.equals(pkgName) || otherPkg.equals("java.lang")) typeName = typeName.substring(index + 1); } return typeName; } } // vim:ts=4
Added convertMethodSignature(MethodGen). git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@1015 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3
findbugs/src/java/edu/umd/cs/findbugs/ba/SignatureConverter.java
Added convertMethodSignature(MethodGen).
Java
apache-2.0
8a0d05e6b38b463384d8516e2630ca2147e11765
0
palava/palava-mail-velocity
/** * palava - a java-php-bridge * Copyright (C) 2007-2010 CosmoCode GmbH * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package de.cosmocode.palava.services.mail; public class EntityEncoder { private static final EntityEncoder instance = new EntityEncoder(); private EntityEncoder() { } public String encode(String sourceString) { return sourceString == null ? "" : sourceString. replace("&", "&amp;"). replace(">", "&gt;"). replace("<", "&lt;"). replace("'", "&apos;"). replace("\"", "&quot;"). replace("%", "&#37;"); } public static EntityEncoder getInstance() { return instance; } }
src/main/java/de/cosmocode/palava/services/mail/EntityEncoder.java
/** * palava - a java-php-bridge * Copyright (C) 2007-2010 CosmoCode GmbH * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package de.cosmocode.palava.services.mail; public class EntityEncoder { private static final EntityEncoder instance = new EntityEncoder(); private EntityEncoder() { } public String encode(String sourceString) { return sourceString. replace("&", "&amp;"). replace(">", "&gt;"). replace("<", "&lt;"). replace("'", "&apos;"). replace("\"", "&quot;"). replace("%", "&#37;"); } public static EntityEncoder getInstance() { return instance; } }
added null check
src/main/java/de/cosmocode/palava/services/mail/EntityEncoder.java
added null check
Java
apache-2.0
58d8990e93d58e9770f736996ef4bbe5c832e17d
0
alexheretic/dynamics
/* * Copyright 2015 Alex Butler * * 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 alexh.weak; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.ls.DOMImplementationLS; import org.w3c.dom.ls.LSSerializer; import org.xml.sax.InputSource; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; import java.io.Reader; import java.io.StringReader; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Predicate; import java.util.stream.IntStream; import java.util.stream.Stream; import static alexh.Unchecker.uncheckedGet; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.toList; /** * Dynamic implementation for XML documents * All keys & values in an XmlDynamic unwrap to Strings, try {@link Dynamic#convert()} * to implement basic string->type conversions * <p> * As an example consider the following XML structure stored in a String 'xmlMessage' * <pre>{@code * <product> * <investment> * <info> * <current> * <name>some name</name> * </current> * </info> * </investment> * </product> * }</pre> * We can select the nested 'name' element value with * <br/>{@code new XmlDynamic(xmlMessage).get("product.investment.info.current.name", ".").asString()} * <p> * Also since XML has certain key name restrictions the pipe character '|' can be used as a splitter without declaration * <br/>ie {@code new XmlDynamic(xmlMessage).get("product|investment|info|current|name").asString()} * @see XmlDynamic#get(Object) * * @author Alex Butler */ public class XmlDynamic extends AbstractDynamic<Node> implements TypeDescriber, AvailabilityDescriber { private static final String FALLBACK_TO_STRING = "Xml[unable to serialize]"; private static final String NONE_NAMESPACE = "none"; private static final String NS_INDICATOR = "::"; private static Stream<Node> stream(NodeList nodes) { if (nodes == null) return Stream.empty(); return IntStream.range(0, nodes.getLength()).mapToObj(nodes::item); } private static Stream<Node> stream(NamedNodeMap nodeMap) { if (nodes == null) return Stream.empty(); return IntStream.range(0, nodeMap.getLength()).mapToObj(nodeMap::item); } private static Node inputSourceToNode(InputSource xml) { final XPathExpression all = uncheckedGet(() -> XPathFactory.newInstance().newXPath().compile("//*")); synchronized (XPathExpression.class) { // evaluate not thread-safe return uncheckedGet(() -> (Node) all.evaluate(xml, XPathConstants.NODE)); } } public XmlDynamic(Node inner) { super(inner); } public XmlDynamic(InputSource xml) { this(inputSourceToNode(xml)); } public XmlDynamic(Reader xml) { this(new InputSource(xml)); } public XmlDynamic(String xml) { this(new StringReader(xml)); } /** Dynamic Xml values are always {@link String}s */ @Override public boolean is(Class<?> type) { return String.class.equals(type); } /** * {@inheritDoc} * <p> * The pipe character '|' can be used as a splitter without declaration * ie {@code xmlDynamic.get("product|investment|info|current|name").asString()}. * * Multiple child elements with the same local-name effectively have [i] appended to them where i is their * index counting from top to bottom. * For example: * <pre>{@code * <product id="1234"> * <string>hello</string> * <string>hey</string> * <string>hi</string> * <string>howdy</string> * </product> * }</pre> * <br/>{@code xmlDynamic.get("product|string")} returns "hello" * <br/>{@code xmlDynamic.get("product|string[0]")} also returns "hello" * <br/>{@code xmlDynamic.get("product|string[1]")} returns "hey" * <br/>{@code xmlDynamic.get("product|string[2]")} returns "hi" * <br/>{@code xmlDynamic.get("product|string[3]")} returns "howdy" * <p> * Attributes can be accessed in exactly the same way as elements, or explicitly * <br/>{@code xmlDynamic.get("product|id").asString()} return "1234" * <br/>{@code xmlDynamic.get("product|@id").asString()} also returns "1234" * <p> * Namespaces are ignored by default, but can be used explicitly using the "::" separator * For example: * <pre>{@code * <ex:product xmlns:ex="http://example.com/example"> * <message>hello</message> * </ex:product> * }</pre> * <br/>{@code xmlDynamic.get("product|message")} returns "hello" * <br/>{@code xmlDynamic.get("http://example.com/example::product|none::message")} also returns "hello" */ @Override public Dynamic get(Object keyObject) { final String keyToString = keyObject.toString(); if (keyToString.contains("|")) return get(keyToString, "|"); if (children().allMatch(o -> false)) { if (asString().isEmpty()) return new ParentAbsence.Empty<>(this, keyObject); return new ParentAbsence.Barren<>(this, keyObject); } final String key = keyToString.endsWith("[0]") ? keyToString.substring(0, keyToString.length() - 3) : keyToString; final String[] nsKey = key.split(NS_INDICATOR); if (nsKey.length == 2) return getWithNamespace(nsKey[0], nsKey[1]); final Optional<? extends Dynamic> match; if (key.isEmpty()) match = Optional.empty(); else if (key.startsWith("@")) match = attributes().filter(attr -> attr.key.equals(key)).findAny(); else if (key.endsWith("]")) match = elements().filter(el -> el.key.equals(key)).findAny(); else { match = Stream.concat(elements().filter(el -> el.key.equals(key)), attributes().filter(attr -> attr.key.equals("@"+ key))).findFirst(); } return match.map(Dynamic.class::cast).orElse(new ChildAbsence.Missing<>(this, keyObject)); } protected Dynamic getWithNamespace(String namespace, String key) { final Optional<? extends Dynamic> match; final Predicate<Node> nodeInNamespace; if (NONE_NAMESPACE.equals(namespace)) nodeInNamespace = node -> node.getNamespaceURI() == null; else nodeInNamespace = node -> namespace.equals(node.getNamespaceURI()); if (key.isEmpty()) match = Optional.empty(); else if (key.startsWith("@")) { match = attributesWith(nodeInNamespace).filter(attr -> attr.key.equals(key)).findAny(); } else if (key.endsWith("]")) { match = elementsWith(nodeInNamespace).filter(el -> el.key.equals(key)).findAny(); } else { match = Stream.concat(elementsWith(nodeInNamespace).filter(el -> el.key.equals(key)), attributesWith(nodeInNamespace).filter(attr -> attr.key.equals("@"+ key))).findFirst(); } return match.map(Dynamic.class::cast).orElse(new ChildAbsence.Missing<>(this, namespace + NS_INDICATOR + key)); } protected Stream<Child> attributes() { return attributesWith(n -> true); } protected Stream<Child> attributesWith(Predicate<Node> predicate) { return Stream.empty(); } protected Stream<Child> elements() { return elementsWith(n -> true); } protected Stream<Child> elementsWith(Predicate<Node> predicate) { return Stream.of(inner).filter(predicate).map(n -> childElement(n, 0)); } @Override public Stream<Dynamic> children() { return Stream.concat(elements(), attributes()); } @Override public String describeAvailability() { List<String> keys = Stream.concat(elements(), attributes()) .map(child -> child.key) .collect(toList()); Map<String, Integer> keyLastIndex = new HashMap<>(); keys.forEach(key -> { if (key.endsWith("]")) { StringBuilder index = new StringBuilder(); for (int i = key.length()-2; i != -1; --i) { char c = key.charAt(i); if (c == '[') break; else index.append(c); } if (index.length() != 0) { keyLastIndex.put(key.substring(0, key.indexOf("[")), Integer.valueOf(index.toString())); } } }); keyLastIndex.forEach((multiKey, maxIndex) -> { keys.removeIf(key -> key.equals(multiKey) || key.endsWith("]") && key.substring(0, key.indexOf("[")).equals(multiKey)); keys.add(multiKey + "[0.." + maxIndex + "]"); }); return keys.toString(); } @Override protected Object keyLiteral() { return ROOT_KEY; } @Override public String describeType() { return "Xml"; } Child childElement(Node inner, int index) { return new Child(inner, this, index == 0 ? inner.getLocalName() : inner.getLocalName() + '[' + index + ']'); } @Override public int hashCode() { final String toString = fullXml(); return FALLBACK_TO_STRING.equals(toString) ? super.hashCode() : toString.hashCode(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final String otherAsString = ((XmlDynamic)o).fullXml(); return !FALLBACK_TO_STRING.equals(otherAsString) && otherAsString.equals(this.fullXml()); } protected LSSerializer serializer() { LSSerializer serializer = ((DOMImplementationLS) inner.getOwnerDocument() .getImplementation() .getFeature("LS", "3.0")) .createLSSerializer(); serializer.getDomConfig().setParameter("xml-declaration", false); return serializer; } @Override public String asObject() { return serializer().writeToString(inner); } /** @return this dynamic key->value entry as an XML string */ public String fullXml() { try { return serializer().writeToString(inner); } catch (RuntimeException ex) { return FALLBACK_TO_STRING; } } @Override public String toString() { return keyLiteral() + ":"+ describeType() + describeAvailability(); } static class Child extends XmlDynamic implements DynamicChild { private final Dynamic parent; private final String key; Child(Node inner, Dynamic parent, String key) { super(inner); this.parent = parent; this.key = requireNonNull(key); } @Override public String asObject() { return Optional.ofNullable(inner.getFirstChild()) .map(Node::getNodeValue) .orElseGet(() -> elements().map(Child::fullXml) .map(String::trim) .reduce((s1, s2) -> s1 + s2) .orElse("")); } @Override protected Stream<Child> attributesWith(Predicate<Node> predicate) { final Map<String, Integer> keyLastIndex = new HashMap<>(); return stream(inner.getAttributes()) .filter(predicate) .map(attr -> { final Integer index = Optional.ofNullable(keyLastIndex.get(attr.getLocalName())).map(i -> i + 1).orElse(0); keyLastIndex.put(attr.getLocalName(), index); return childAttribute(attr, index); }); } @Override protected Stream<Child> elementsWith(Predicate<Node> predicate) { final Map<String, Integer> keyLastIndex = new HashMap<>(); return stream(inner.getChildNodes()) .filter(node -> node.getLocalName() != null) .filter(predicate) .map(node -> { final Integer index = Optional.ofNullable(keyLastIndex.get(node.getLocalName())).map(i -> i + 1).orElse(0); keyLastIndex.put(node.getLocalName(), index); return childElement(node, index); }); } @Override public Dynamic parent() { return parent; } @Override public Object keyLiteral() { return key; } Child childAttribute(Node inner, int index) { String name = "@" + inner.getLocalName(); return new Child(inner, this, index == 0 ? name : name + '[' + index + ']'); } } }
src/main/java/alexh/weak/XmlDynamic.java
/* * Copyright 2015 Alex Butler * * 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 alexh.weak; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.ls.DOMImplementationLS; import org.w3c.dom.ls.LSSerializer; import org.xml.sax.InputSource; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; import java.io.Reader; import java.io.StringReader; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Predicate; import java.util.stream.IntStream; import java.util.stream.Stream; import static alexh.Unchecker.uncheckedGet; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.toList; /** * Dynamic implementation for XML documents * All keys & values in an XmlDynamic unwrap to Strings, try {@link Dynamic#convert()} * to implement basic string->type conversions * <p> * As an example consider the following XML structure stored in a String 'xmlMessage' * <pre>{@code * <product> * <investment> * <info> * <current> * <name>some name</name> * </current> * </info> * </investment> * </product> * }</pre> * We can select the nested 'name' element value with * <br/>{@code new XmlDynamic(xmlMessage).get("product.investment.info.current.name", ".").asString()} * <p> * Also since XML has certain key name restrictions the pipe character '|' can be used as a splitter without declaration * <br/>ie {@code new XmlDynamic(xmlMessage).get("product|investment|info|current|name").asString()} * @see XmlDynamic#get(Object) * * @author Alex Butler */ public class XmlDynamic extends AbstractDynamic<Node> implements TypeDescriber, AvailabilityDescriber { private static final String FALLBACK_TO_STRING = "Xml[unable to serialize]"; private static final String NONE_NAMESPACE = "none"; private static final String NS_INDICATOR = "::"; private static Stream<Node> stream(NodeList nodes) { return IntStream.range(0, nodes.getLength()).mapToObj(nodes::item); } private static Stream<Node> stream(NamedNodeMap nodeMap) { return IntStream.range(0, nodeMap.getLength()).mapToObj(nodeMap::item); } private static Node inputSourceToNode(InputSource xml) { final XPathExpression all = uncheckedGet(() -> XPathFactory.newInstance().newXPath().compile("//*")); synchronized (XPathExpression.class) { // evaluate not thread-safe return uncheckedGet(() -> (Node) all.evaluate(xml, XPathConstants.NODE)); } } public XmlDynamic(Node inner) { super(inner); } public XmlDynamic(InputSource xml) { this(inputSourceToNode(xml)); } public XmlDynamic(Reader xml) { this(new InputSource(xml)); } public XmlDynamic(String xml) { this(new StringReader(xml)); } /** Dynamic Xml values are always {@link String}s */ @Override public boolean is(Class<?> type) { return String.class.equals(type); } /** * {@inheritDoc} * <p> * The pipe character '|' can be used as a splitter without declaration * ie {@code xmlDynamic.get("product|investment|info|current|name").asString()}. * * Multiple child elements with the same local-name effectively have [i] appended to them where i is their * index counting from top to bottom. * For example: * <pre>{@code * <product id="1234"> * <string>hello</string> * <string>hey</string> * <string>hi</string> * <string>howdy</string> * </product> * }</pre> * <br/>{@code xmlDynamic.get("product|string")} returns "hello" * <br/>{@code xmlDynamic.get("product|string[0]")} also returns "hello" * <br/>{@code xmlDynamic.get("product|string[1]")} returns "hey" * <br/>{@code xmlDynamic.get("product|string[2]")} returns "hi" * <br/>{@code xmlDynamic.get("product|string[3]")} returns "howdy" * <p> * Attributes can be accessed in exactly the same way as elements, or explicitly * <br/>{@code xmlDynamic.get("product|id").asString()} return "1234" * <br/>{@code xmlDynamic.get("product|@id").asString()} also returns "1234" * <p> * Namespaces are ignored by default, but can be used explicitly using the "::" separator * For example: * <pre>{@code * <ex:product xmlns:ex="http://example.com/example"> * <message>hello</message> * </ex:product> * }</pre> * <br/>{@code xmlDynamic.get("product|message")} returns "hello" * <br/>{@code xmlDynamic.get("http://example.com/example::product|none::message")} also returns "hello" */ @Override public Dynamic get(Object keyObject) { final String keyToString = keyObject.toString(); if (keyToString.contains("|")) return get(keyToString, "|"); if (children().allMatch(o -> false)) { if (asString().isEmpty()) return new ParentAbsence.Empty<>(this, keyObject); return new ParentAbsence.Barren<>(this, keyObject); } final String key = keyToString.endsWith("[0]") ? keyToString.substring(0, keyToString.length() - 3) : keyToString; final String[] nsKey = key.split(NS_INDICATOR); if (nsKey.length == 2) return getWithNamespace(nsKey[0], nsKey[1]); final Optional<? extends Dynamic> match; if (key.isEmpty()) match = Optional.empty(); else if (key.startsWith("@")) match = attributes().filter(attr -> attr.key.equals(key)).findAny(); else if (key.endsWith("]")) match = elements().filter(el -> el.key.equals(key)).findAny(); else { match = Stream.concat(elements().filter(el -> el.key.equals(key)), attributes().filter(attr -> attr.key.equals("@"+ key))).findFirst(); } return match.map(Dynamic.class::cast).orElse(new ChildAbsence.Missing<>(this, keyObject)); } protected Dynamic getWithNamespace(String namespace, String key) { final Optional<? extends Dynamic> match; final Predicate<Node> nodeInNamespace; if (NONE_NAMESPACE.equals(namespace)) nodeInNamespace = node -> node.getNamespaceURI() == null; else nodeInNamespace = node -> namespace.equals(node.getNamespaceURI()); if (key.isEmpty()) match = Optional.empty(); else if (key.startsWith("@")) { match = attributesWith(nodeInNamespace).filter(attr -> attr.key.equals(key)).findAny(); } else if (key.endsWith("]")) { match = elementsWith(nodeInNamespace).filter(el -> el.key.equals(key)).findAny(); } else { match = Stream.concat(elementsWith(nodeInNamespace).filter(el -> el.key.equals(key)), attributesWith(nodeInNamespace).filter(attr -> attr.key.equals("@"+ key))).findFirst(); } return match.map(Dynamic.class::cast).orElse(new ChildAbsence.Missing<>(this, namespace + NS_INDICATOR + key)); } protected Stream<Child> attributes() { return attributesWith(n -> true); } protected Stream<Child> attributesWith(Predicate<Node> predicate) { return Stream.empty(); } protected Stream<Child> elements() { return elementsWith(n -> true); } protected Stream<Child> elementsWith(Predicate<Node> predicate) { return Stream.of(inner).filter(predicate).map(n -> childElement(n, 0)); } @Override public Stream<Dynamic> children() { return Stream.concat(elements(), attributes()); } @Override public String describeAvailability() { List<String> keys = Stream.concat(elements(), attributes()) .map(child -> child.key) .collect(toList()); Map<String, Integer> keyLastIndex = new HashMap<>(); keys.forEach(key -> { if (key.endsWith("]")) { StringBuilder index = new StringBuilder(); for (int i = key.length()-2; i != -1; --i) { char c = key.charAt(i); if (c == '[') break; else index.append(c); } if (index.length() != 0) { keyLastIndex.put(key.substring(0, key.indexOf("[")), Integer.valueOf(index.toString())); } } }); keyLastIndex.forEach((multiKey, maxIndex) -> { keys.removeIf(key -> key.equals(multiKey) || key.endsWith("]") && key.substring(0, key.indexOf("[")).equals(multiKey)); keys.add(multiKey + "[0.." + maxIndex + "]"); }); return keys.toString(); } @Override protected Object keyLiteral() { return ROOT_KEY; } @Override public String describeType() { return "Xml"; } Child childElement(Node inner, int index) { return new Child(inner, this, index == 0 ? inner.getLocalName() : inner.getLocalName() + '[' + index + ']'); } @Override public int hashCode() { final String toString = fullXml(); return FALLBACK_TO_STRING.equals(toString) ? super.hashCode() : toString.hashCode(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final String otherAsString = ((XmlDynamic)o).fullXml(); return !FALLBACK_TO_STRING.equals(otherAsString) && otherAsString.equals(this.fullXml()); } protected LSSerializer serializer() { LSSerializer serializer = ((DOMImplementationLS) inner.getOwnerDocument() .getImplementation() .getFeature("LS", "3.0")) .createLSSerializer(); serializer.getDomConfig().setParameter("xml-declaration", false); return serializer; } @Override public String asObject() { return serializer().writeToString(inner); } /** @return this dynamic key->value entry as an XML string */ public String fullXml() { try { return serializer().writeToString(inner); } catch (RuntimeException ex) { return FALLBACK_TO_STRING; } } @Override public String toString() { return keyLiteral() + ":"+ describeType() + describeAvailability(); } static class Child extends XmlDynamic implements DynamicChild { private final Dynamic parent; private final String key; Child(Node inner, Dynamic parent, String key) { super(inner); this.parent = parent; this.key = requireNonNull(key); } @Override public String asObject() { return Optional.ofNullable(inner.getFirstChild()) .map(Node::getNodeValue) .orElseGet(() -> elements().map(Child::fullXml) .map(String::trim) .reduce((s1, s2) -> s1 + s2) .orElse("")); } @Override protected Stream<Child> attributesWith(Predicate<Node> predicate) { final Map<String, Integer> keyLastIndex = new HashMap<>(); return stream(inner.getAttributes()) .filter(predicate) .map(attr -> { final Integer index = Optional.ofNullable(keyLastIndex.get(attr.getLocalName())).map(i -> i + 1).orElse(0); keyLastIndex.put(attr.getLocalName(), index); return childAttribute(attr, index); }); } @Override protected Stream<Child> elementsWith(Predicate<Node> predicate) { final Map<String, Integer> keyLastIndex = new HashMap<>(); return stream(inner.getChildNodes()) .filter(node -> node.getLocalName() != null) .filter(predicate) .map(node -> { final Integer index = Optional.ofNullable(keyLastIndex.get(node.getLocalName())).map(i -> i + 1).orElse(0); keyLastIndex.put(node.getLocalName(), index); return childElement(node, index); }); } @Override public Dynamic parent() { return parent; } @Override public Object keyLiteral() { return key; } Child childAttribute(Node inner, int index) { String name = "@" + inner.getLocalName(); return new Child(inner, this, index == 0 ? name : name + '[' + index + ']'); } } }
Update XmlDynamic.java Node API inner null handling
src/main/java/alexh/weak/XmlDynamic.java
Update XmlDynamic.java
Java
apache-2.0
ce652ff33553bcf83fc1a06fb137620e2cd96117
0
quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus
/* * Copyright 2018 Red Hat, 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 org.jboss.shamrock.maven.runner; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.lang.reflect.Constructor; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import org.eclipse.microprofile.config.Config; import org.jboss.logging.Logger; import org.jboss.shamrock.runtime.Timing; import io.smallrye.config.PropertiesConfigSource; import io.smallrye.config.SmallRyeConfigProviderResolver; /** * The main entry point for the run mojo execution */ public class RunMojoMain { private static final Logger log = Logger.getLogger(RunMojoMain.class); private static volatile boolean keepCl = false; private static volatile ClassLoader currentAppClassLoader; private static volatile URLClassLoader runtimeCl; private static File classesRoot; private static File wiringDir; private static File cacheDir; private static Closeable closeable; static volatile Throwable deploymentProblem; public static void main(String... args) throws Exception { Timing.staticInitStarted(); //the path that contains the compiled classes classesRoot = new File(args[0]); wiringDir = new File(args[1]); cacheDir = new File(args[2]); //first lets look for some config, as it is not on the current class path //and we need to load it to start undertow eagerly File config = new File(classesRoot, "META-INF/microprofile-config.properties"); if(config.exists()) { try { Config built = SmallRyeConfigProviderResolver.instance().getBuilder() .addDefaultSources() .addDiscoveredConverters() .addDiscoveredSources() .withSources(new PropertiesConfigSource(config.toURL())).build(); SmallRyeConfigProviderResolver.instance().registerConfig(built, Thread.currentThread().getContextClassLoader()); } catch (Exception e) { throw new RuntimeException(e); } } RuntimeCompilationSetup.setup(); //TODO: we can't handle an exception on startup with hot replacement, as Undertow might not have started doStart(); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { synchronized (RunMojoMain.class) { if (closeable != null) { try { closeable.close(); } catch (IOException e) { e.printStackTrace(); } } } } }, "Shamrock Shutdown Thread")); } private static synchronized void doStart() { try { if (runtimeCl == null || !keepCl) { runtimeCl = new URLClassLoader(new URL[]{classesRoot.toURL()}, ClassLoader.getSystemClassLoader()); } currentAppClassLoader = runtimeCl; ClassLoader old = Thread.currentThread().getContextClassLoader(); //we can potentially throw away this class loader, and reload the app try { Thread.currentThread().setContextClassLoader(runtimeCl); Class<?> runnerClass = runtimeCl.loadClass("org.jboss.shamrock.runner.RuntimeRunner"); Constructor ctor = runnerClass.getDeclaredConstructor(ClassLoader.class, Path.class, Path.class, Path.class, List.class); Object runner = ctor.newInstance(runtimeCl, classesRoot.toPath(), wiringDir.toPath(), cacheDir.toPath(), new ArrayList<>()); ((Runnable) runner).run(); closeable = ((Closeable) runner); deploymentProblem = null; } finally { Thread.currentThread().setContextClassLoader(old); } } catch (Throwable t) { deploymentProblem = t; log.error("Failed to start shamrock", t); } } public static synchronized void restartApp(boolean keepClassloader) { keepCl = keepClassloader; if (closeable != null) { ClassLoader old = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(runtimeCl); try { closeable.close(); } catch (IOException e) { e.printStackTrace(); } finally { Thread.currentThread().setContextClassLoader(old); } } closeable = null; doStart(); } public static ClassLoader getCurrentAppClassLoader() { return currentAppClassLoader; } }
maven/src/main/java/org/jboss/shamrock/maven/runner/RunMojoMain.java
/* * Copyright 2018 Red Hat, 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 org.jboss.shamrock.maven.runner; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.lang.reflect.Constructor; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import org.jboss.logging.Logger; import org.jboss.shamrock.runtime.Timing; /** * The main entry point for the run mojo execution */ public class RunMojoMain { private static final Logger log = Logger.getLogger(RunMojoMain.class); private static volatile boolean keepCl = false; private static volatile ClassLoader currentAppClassLoader; private static volatile URLClassLoader runtimeCl; private static File classesRoot; private static File wiringDir; private static File cacheDir; private static Closeable closeable; static volatile Throwable deploymentProblem; public static void main(String... args) throws Exception { Timing.staticInitStarted(); RuntimeCompilationSetup.setup(); //the path that contains the compiled classes classesRoot = new File(args[0]); wiringDir = new File(args[1]); cacheDir = new File(args[2]); //TODO: we can't handle an exception on startup with hot replacement, as Undertow might not have started doStart(); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { synchronized (RunMojoMain.class) { if (closeable != null) { try { closeable.close(); } catch (IOException e) { e.printStackTrace(); } } } } }, "Shamrock Shutdown Thread")); } private static synchronized void doStart() { try { if (runtimeCl == null || !keepCl) { runtimeCl = new URLClassLoader(new URL[]{classesRoot.toURL()}, ClassLoader.getSystemClassLoader()); } currentAppClassLoader = runtimeCl; ClassLoader old = Thread.currentThread().getContextClassLoader(); //we can potentially throw away this class loader, and reload the app try { Thread.currentThread().setContextClassLoader(runtimeCl); Class<?> runnerClass = runtimeCl.loadClass("org.jboss.shamrock.runner.RuntimeRunner"); Constructor ctor = runnerClass.getDeclaredConstructor(ClassLoader.class, Path.class, Path.class, Path.class, List.class); Object runner = ctor.newInstance(runtimeCl, classesRoot.toPath(), wiringDir.toPath(), cacheDir.toPath(), new ArrayList<>()); ((Runnable) runner).run(); closeable = ((Closeable) runner); deploymentProblem = null; } finally { Thread.currentThread().setContextClassLoader(old); } } catch (Throwable t) { deploymentProblem = t; log.error("Failed to start shamrock", t); } } public static synchronized void restartApp(boolean keepClassloader) { keepCl = keepClassloader; if (closeable != null) { ClassLoader old = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(runtimeCl); try { closeable.close(); } catch (IOException e) { e.printStackTrace(); } finally { Thread.currentThread().setContextClassLoader(old); } } closeable = null; doStart(); } public static ClassLoader getCurrentAppClassLoader() { return currentAppClassLoader; } }
Make shamrock:run take the port into account
maven/src/main/java/org/jboss/shamrock/maven/runner/RunMojoMain.java
Make shamrock:run take the port into account
Java
apache-2.0
9272992fc5edfae9ef806e5dd5ff926cded07cfe
0
apache/commons-codec,adrie4mac/commons-codec,apache/commons-codec,mohanaraosv/commons-codec,mohanaraosv/commons-codec,adrie4mac/commons-codec,adrie4mac/commons-codec,apache/commons-codec,mohanaraosv/commons-codec
/* * 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.codec.language.bm; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.EnumMap; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * <p> * A phoneme rule. * </p> * <p> * Rules have a pattern, left context, right context, output phoneme, set of languages for which they apply and a logical flag indicating if * all lanugages must be in play. A rule matches if: * <ul> * <li>the pattern matches at the current position</li> * <li>the string up until the beginning of the pattern matches the left context</li> * <li>the string from the end of the pattern matches the right context</li> * <li>logical is ALL and all languages are in scope; or</li> * <li>logical is any other value and at least one language is in scope</li> * </ul> * </p> * <p> * Rules are typically generated by parsing rules resources. In normal use, there will be no need for the user to explicitly construct their * own. * </p> * <p> * Rules are immutable and thread-safe. * <h2>Rules resources</h2> * <p> * Rules are typically loaded from resource files. These are UTF-8 encoded text files. They are systematically named following the pattern: * <blockquote>org/apache/commons/codec/language/bm/${NameType#getName}_${RuleType#getName}_${language}.txt</blockquote> * </p> * <p> * The format of these resources is the following: * <ul> * <li><b>Rules:</b> whitespace separated, double-quoted strings. There should be 4 columns to each row, and these will be interpreted as: * <ol> * <li>pattern</li> * <li>left context</li> * <li>right context</li> * <li>phoneme</li> * </ol> * </li> * <li><b>End-of-line comments:</b> Any occurance of '//' will cause all text following on that line to be discarded as a comment.</li> * <li><b>Multi-line comments:</b> Any line starting with '/*' will start multi-line commenting mode. This will skip all content until a * line ending in '*' and '/' is found.</li> * <li><b>Blank lines:</b> All blank lines will be skipped.</li> * </ul> * </p> * * @author Apache Software Foundation * @since 2.0 */ public class Rule { public static class Phoneme implements PhonemeExpr, Comparable<Phoneme> { private final CharSequence phonemeText; private final Languages.LanguageSet languages; public Phoneme(CharSequence phonemeText, Languages.LanguageSet languages) { this.phonemeText = phonemeText; this.languages = languages; } public Phoneme append(CharSequence str) { return new Phoneme(new AppendableCharSeqeuence(this.phonemeText, str), this.languages); } public Languages.LanguageSet getLanguages() { return this.languages; } public Iterable<Phoneme> getPhonemes() { return Collections.singleton(this); } public CharSequence getPhonemeText() { return this.phonemeText; } public Phoneme join(Phoneme right) { return new Phoneme(new AppendableCharSeqeuence(this.phonemeText, right.phonemeText), this.languages.restrictTo(right.languages)); } public int compareTo(Phoneme o) { for (int i = 0; i < phonemeText.length(); i++) { if (i >= o.phonemeText.length()) { return +1; } int c = phonemeText.charAt(i) - o.phonemeText.charAt(i); if (c != 0) { return c; } } if (phonemeText.length() < o.phonemeText.length()) { return -1; } return 0; } } public interface PhonemeExpr { Iterable<Phoneme> getPhonemes(); } public static class PhonemeList implements PhonemeExpr { private final List<Phoneme> phonemes; public PhonemeList(List<Phoneme> phonemes) { this.phonemes = phonemes; } public List<Phoneme> getPhonemes() { return this.phonemes; } } public static final String ALL = "ALL"; private static final String DOUBLE_QUOTE = "\""; private static final String HASH_INCLUDE = "#include"; private static final Map<NameType, Map<RuleType, Map<String, List<Rule>>>> RULES = new EnumMap<NameType, Map<RuleType, Map<String, List<Rule>>>>( NameType.class); static { for (NameType s : NameType.values()) { Map<RuleType, Map<String, List<Rule>>> rts = new EnumMap<RuleType, Map<String, List<Rule>>>(RuleType.class); for (RuleType rt : RuleType.values()) { Map<String, List<Rule>> rs = new HashMap<String, List<Rule>>(); Languages ls = Languages.instance(s); for (String l : ls.getLanguages()) { try { rs.put(l, parseRules(createScanner(s, rt, l), createResourceName(s, rt, l))); } catch (IllegalStateException e) { throw new IllegalStateException("Problem processing " + createResourceName(s, rt, l), e); } } if (!rt.equals(RuleType.RULES)) { rs.put("common", parseRules(createScanner(s, rt, "common"), createResourceName(s, rt, "common"))); } rts.put(rt, Collections.unmodifiableMap(rs)); } RULES.put(s, Collections.unmodifiableMap(rts)); } } private static String createResourceName(NameType nameType, RuleType rt, String lang) { return String.format("org/apache/commons/codec/language/bm/%s_%s_%s.txt", nameType.getName(), rt.getName(), lang); } private static Scanner createScanner(NameType nameType, RuleType rt, String lang) { String resName = createResourceName(nameType, rt, lang); InputStream rulesIS = Languages.class.getClassLoader().getResourceAsStream(resName); if (rulesIS == null) { throw new IllegalArgumentException("Unable to load resource: " + resName); } return new Scanner(rulesIS, ResourceConstants.ENCODING); } private static Scanner createScanner(String lang) { String resName = String.format("org/apache/commons/codec/language/bm/%s.txt", lang); InputStream rulesIS = Languages.class.getClassLoader().getResourceAsStream(resName); if (rulesIS == null) { throw new IllegalArgumentException("Unable to load resource: " + resName); } return new Scanner(rulesIS, ResourceConstants.ENCODING); } /** * Gets rules for a combination of name type, rule type and languages. * * @param nameType * the NameType to consider * @param rt * the RuleType to consider * @param langs * the set of languages to consider * @return a list of Rules that apply */ public static List<Rule> instance(NameType nameType, RuleType rt, Languages.LanguageSet langs) { return langs.isSingleton() ? instance(nameType, rt, langs.getAny()) : instance(nameType, rt, Languages.ANY); } /** * Gets rules for a combination of name type, rule type and a single language. * * @param nameType * the NameType to consider * @param rt * the RuleType to consider * @param lang * the language to consider * @return a list rules for a combination of name type, rule type and a single language. */ public static List<Rule> instance(NameType nameType, RuleType rt, String lang) { List<Rule> rules = RULES.get(nameType).get(rt).get(lang); if (rules == null) { throw new IllegalArgumentException(String.format("No rules found for %s, %s, %s.", nameType.getName(), rt.getName(), lang)); } return rules; } private static Phoneme parsePhoneme(String ph) { int open = ph.indexOf("["); if (open >= 0) { if (!ph.endsWith("]")) { throw new IllegalArgumentException("Phoneme expression contains a '[' but does not end in ']'"); } String before = ph.substring(0, open); String in = ph.substring(open + 1, ph.length() - 1); Set<String> langs = new HashSet<String>(Arrays.asList(in.split("[+]"))); return new Phoneme(before, Languages.LanguageSet.from(langs)); } else { return new Phoneme(ph, Languages.ANY_LANGUAGE); } } private static PhonemeExpr parsePhonemeExpr(String ph) { if (ph.startsWith("(")) { // we have a bracketed list of options if (!ph.endsWith(")")) { throw new IllegalArgumentException("Phoneme starts with '(' so must end with ')'"); } List<Phoneme> phs = new ArrayList<Phoneme>(); String body = ph.substring(1, ph.length() - 1); for (String part : body.split("[|]")) { phs.add(parsePhoneme(part)); } if (body.startsWith("|") || body.endsWith("|")) { phs.add(new Phoneme("", Languages.ANY_LANGUAGE)); } return new PhonemeList(phs); } else { return parsePhoneme(ph); } } private static List<Rule> parseRules(final Scanner scanner, final String location) { List<Rule> lines = new ArrayList<Rule>(); int currentLine = 0; boolean inMultilineComment = false; while (scanner.hasNextLine()) { currentLine++; String rawLine = scanner.nextLine(); String line = rawLine; if (inMultilineComment) { if (line.endsWith(ResourceConstants.EXT_CMT_END)) { inMultilineComment = false; } else { // skip } } else { if (line.startsWith(ResourceConstants.EXT_CMT_START)) { inMultilineComment = true; } else { // discard comments int cmtI = line.indexOf(ResourceConstants.CMT); if (cmtI >= 0) { line = line.substring(0, cmtI); } // trim leading-trailing whitespace line = line.trim(); if (line.length() == 0) { continue; // empty lines can be safely skipped } if (line.startsWith(HASH_INCLUDE)) { // include statement String incl = line.substring(HASH_INCLUDE.length()).trim(); if (incl.contains(" ")) { System.err.println("Warining: malformed import statement: " + rawLine); } else { lines.addAll(parseRules(createScanner(incl), location + "->" + incl)); } } else { // rule String[] parts = line.split("\\s+"); if (parts.length != 4) { System.err.println("Warning: malformed rule statement split into " + parts.length + " parts: " + rawLine); } else { try { String pat = stripQuotes(parts[0]); String lCon = stripQuotes(parts[1]); String rCon = stripQuotes(parts[2]); PhonemeExpr ph = parsePhonemeExpr(stripQuotes(parts[3])); final int cLine = currentLine; Rule r = new Rule(pat, lCon, rCon, ph) { private final int line = cLine; private final String loc = location; @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("Rule"); sb.append("{line=").append(line); sb.append(", loc='").append(loc).append('\''); sb.append('}'); return sb.toString(); } }; lines.add(r); } catch (IllegalArgumentException e) { throw new IllegalStateException("Problem parsing line " + currentLine, e); } } } } } } return lines; } private static String stripQuotes(String str) { if (str.startsWith(DOUBLE_QUOTE)) { str = str.substring(1); } if (str.endsWith(DOUBLE_QUOTE)) { str = str.substring(0, str.length() - 1); } return str; } private final RPattern lContext; private final String pattern; private final PhonemeExpr phoneme; private final RPattern rContext; /** * Creates a new rule. * * @param pattern * the pattern * @param lContext * the left context * @param rContext * the right context * @param phoneme * the resulting phoneme */ public Rule(String pattern, String lContext, String rContext, PhonemeExpr phoneme) { this.pattern = pattern; this.lContext = pattern(lContext + "$"); this.rContext = pattern("^" + rContext); this.phoneme = phoneme; } /** * Gets the left context. This is a regular expression that must match to the left of the pattern. * * @return the left context Pattern */ public RPattern getLContext() { return this.lContext; } /** * Gets the pattern. This is a string-literal that must exactly match. * * @return the pattern */ public String getPattern() { return this.pattern; } /** * Gets the phoneme. If the rule matches, this is the phoneme associated with the pattern match. * * @return the phoneme */ public PhonemeExpr getPhoneme() { return this.phoneme; } /** * Gets the right context. This is a regular expression that must match to the right of the pattern. * * @return the right context Pattern */ public RPattern getRContext() { return this.rContext; } /** * Decides if the pattern and context match the input starting at a position. * * @param input * the input String * @param i * the int position within the input * @return true if the pattern and left/right context match, false otherwise */ public boolean patternAndContextMatches(CharSequence input, int i) { if (i < 0) throw new IndexOutOfBoundsException("Can not match pattern at negative indexes"); int patternLength = this.pattern.length(); int ipl = i + patternLength; if (ipl > input.length()) { // not enough room for the pattern to match return false; } boolean patternMatches = input.subSequence(i, ipl).equals(this.pattern); boolean rContextMatches = this.rContext.matcher(input.subSequence(ipl, input.length())).find(); boolean lContextMatches = this.lContext.matcher(input.subSequence(0, i)).find(); return patternMatches && rContextMatches && lContextMatches; } /** * A minimal wrapper around the functionality of Pattern that we use, to allow for alternate implementations. */ public static interface RPattern { public RMatcher matcher(CharSequence input); } /** * A minimal wrapper around the functionality of Matcher that we use, to allow for alternate implementations. */ public static interface RMatcher { public boolean find(); } /** * Attempt to compile the regex into direct string ops, falling back to Pattern and Matcher in the worst case. * * @param regex * the regular expression to compile * @return an RPattern that will match this regex */ private static RPattern pattern(final String regex) { boolean startsWith = regex.startsWith("^"); boolean endsWith = regex.endsWith("$"); final String content = regex.substring(startsWith ? 1 : 0, endsWith ? regex.length() - 1 : regex.length()); boolean boxes = content.contains("["); if (!boxes) { if (startsWith && endsWith) { // exact match if (content.length() == 0) { // empty return new RPattern() { public RMatcher matcher(final CharSequence input) { return new RMatcher() { public boolean find() { return input.length() == 0; } }; } }; } else { return new RPattern() { public RMatcher matcher(final CharSequence input) { return new RMatcher() { public boolean find() { return input.equals(content); } }; } }; } } else if ((startsWith || endsWith) && content.length() == 0) { // matches every string return new RPattern() { public RMatcher matcher(CharSequence input) { return new RMatcher() { public boolean find() { return true; } }; } }; } else if (startsWith) { // matches from start return new RPattern() { public RMatcher matcher(final CharSequence input) { return new RMatcher() { public boolean find() { return startsWith(input, content); } }; } }; } else if (endsWith) { // matches from start return new RPattern() { public RMatcher matcher(final CharSequence input) { return new RMatcher() { public boolean find() { return endsWith(input, content); } }; } }; } } else { boolean startsWithBox = content.startsWith("["); boolean endsWithBox = content.endsWith("]"); if (startsWithBox && endsWithBox) { String boxContent = content.substring(1, content.length() - 1); if (!boxContent.contains("[")) { // box containing alternatives boolean negate = boxContent.startsWith("^"); if (negate) { boxContent = boxContent.substring(1); } final String bContent = boxContent; final boolean shouldMatch = !negate; if (startsWith && endsWith) { // exact match return new RPattern() { public RMatcher matcher(final CharSequence input) { return new RMatcher() { public boolean find() { return input.length() == 1 && (contains(bContent, input.charAt(0)) == shouldMatch); } }; } }; } else if (startsWith) { // first char return new RPattern() { public RMatcher matcher(final CharSequence input) { return new RMatcher() { public boolean find() { return input.length() > 0 && (contains(bContent, input.charAt(0)) == shouldMatch); } }; } }; } else if (endsWith) { // last char return new RPattern() { public RMatcher matcher(final CharSequence input) { return new RMatcher() { public boolean find() { return input.length() > 0 && (contains(bContent, input.charAt(input.length() - 1)) == shouldMatch); } }; } }; } } } } // System.out.println("Couldn't optimize regex: " + regex); return new RPattern() { Pattern pattern = Pattern.compile(regex); public RMatcher matcher(CharSequence input) { final Matcher matcher = pattern.matcher(input); return new RMatcher() { public boolean find() { return matcher.find(); } }; } }; } private static boolean startsWith(CharSequence input, CharSequence prefix) { if (prefix.length() > input.length()) { return false; } for (int i = 0; i < prefix.length(); i++) { if (input.charAt(i) != prefix.charAt(i)) { return false; } } return true; } private static boolean endsWith(CharSequence input, CharSequence suffix) { if (suffix.length() > input.length()) { return false; } for (int i = input.length() - 1, j = suffix.length() - 1; j >= 0; i--, j--) { if (input.charAt(i) != suffix.charAt(j)) { return false; } } return true; } private static boolean contains(CharSequence chars, char input) { for (int i = 0; i < chars.length(); i++) { if (chars.charAt(i) == input) { return true; } } return false; } private static class AppendableCharSeqeuence implements CharSequence { private final CharSequence left; private final CharSequence right; private final int length; private String contentCache = null; private AppendableCharSeqeuence(CharSequence left, CharSequence right) { this.left = left; this.right = right; this.length = left.length() + right.length(); } public int length() { return length; } public char charAt(int index) { // int lLength = left.length(); // if(index < lLength) return left.charAt(index); // else return right.charAt(index - lLength); return toString().charAt(index); } public CharSequence subSequence(int start, int end) { // int lLength = left.length(); // if(start > lLength) return right.subSequence(start - lLength, end - lLength); // else if(end <= lLength) return left.subSequence(start, end); // else { // CharSequence newLeft = left.subSequence(start, lLength); // CharSequence newRight = right.subSequence(0, end - lLength); // return new AppendableCharSeqeuence(newLeft, newRight); // } return toString().subSequence(start, end); } @Override public String toString() { if (contentCache == null) { StringBuilder sb = new StringBuilder(); buildString(sb); contentCache = sb.toString(); // System.err.println("Materialized string: " + contentCache); } return contentCache; } public void buildString(StringBuilder sb) { if (left instanceof AppendableCharSeqeuence) { ((AppendableCharSeqeuence) left).buildString(sb); } else { sb.append(left); } if (right instanceof AppendableCharSeqeuence) { ((AppendableCharSeqeuence) right).buildString(sb); } else { sb.append(right); } } } }
src/java/org/apache/commons/codec/language/bm/Rule.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.codec.language.bm; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.EnumMap; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * <p> * A phoneme rule. * </p> * <p> * Rules have a pattern, left context, right context, output phoneme, set of languages for which they apply and a logical flag indicating if * all lanugages must be in play. A rule matches if: * <ul> * <li>the pattern matches at the current position</li> * <li>the string up until the beginning of the pattern matches the left context</li> * <li>the string from the end of the pattern matches the right context</li> * <li>logical is ALL and all languages are in scope; or</li> * <li>logical is any other value and at least one language is in scope</li> * </ul> * </p> * <p> * Rules are typically generated by parsing rules resources. In normal use, there will be no need for the user to explicitly construct their * own. * </p> * <p> * Rules are immutable and thread-safe. * <h2>Rules resources</h2> * <p> * Rules are typically loaded from resource files. These are UTF-8 encoded text files. They are systematically named following the pattern: * <blockquote>org/apache/commons/codec/language/bm/${NameType#getName}_${RuleType#getName}_${language}.txt</blockquote> * </p> * <p> * The format of these resources is the following: * <ul> * <li><b>Rules:</b> whitespace separated, double-quoted strings. There should be 4 columns to each row, and these will be interpreted as: * <ol> * <li>pattern</li> * <li>left context</li> * <li>right context</li> * <li>phoneme</li> * </ol> * </li> * <li><b>End-of-line comments:</b> Any occurance of '//' will cause all text following on that line to be discarded as a comment.</li> * <li><b>Multi-line comments:</b> Any line starting with '/*' will start multi-line commenting mode. This will skip all content until a * line ending in '*' and '/' is found.</li> * <li><b>Blank lines:</b> All blank lines will be skipped.</li> * </ul> * </p> * * @author Apache Software Foundation * @since 2.0 */ public class Rule { public static class Phoneme implements PhonemeExpr, Comparable<Phoneme> { private final CharSequence phonemeText; private final Languages.LanguageSet languages; public Phoneme(CharSequence phonemeText, Languages.LanguageSet languages) { this.phonemeText = phonemeText; this.languages = languages; } public Phoneme append(CharSequence str) { return new Phoneme(new AppendableCharSeqeuence(this.phonemeText, str), this.languages); } public Languages.LanguageSet getLanguages() { return this.languages; } public Iterable<Phoneme> getPhonemes() { return Collections.singleton(this); } public CharSequence getPhonemeText() { return this.phonemeText; } public Phoneme join(Phoneme right) { return new Phoneme(new AppendableCharSeqeuence(this.phonemeText, right.phonemeText), this.languages.restrictTo(right.languages)); } public int compareTo(Phoneme o) { for (int i = 0; i < phonemeText.length(); i++) { if (i >= o.phonemeText.length()) { return +1; } int c = phonemeText.charAt(i) - o.phonemeText.charAt(i); if (c != 0) { return c; } } if (phonemeText.length() < o.phonemeText.length()) { return -1; } return 0; } } public interface PhonemeExpr { Iterable<Phoneme> getPhonemes(); } public static class PhonemeList implements PhonemeExpr { private final List<Phoneme> phonemes; public PhonemeList(List<Phoneme> phonemes) { this.phonemes = phonemes; } public List<Phoneme> getPhonemes() { return this.phonemes; } } public static final String ALL = "ALL"; private static final String DOUBLE_QUOTE = "\""; private static final String HASH_INCLUDE = "#include"; private static final Map<NameType, Map<RuleType, Map<String, List<Rule>>>> RULES = new EnumMap<NameType, Map<RuleType, Map<String, List<Rule>>>>( NameType.class); static { for (NameType s : NameType.values()) { Map<RuleType, Map<String, List<Rule>>> rts = new EnumMap<RuleType, Map<String, List<Rule>>>(RuleType.class); for (RuleType rt : RuleType.values()) { Map<String, List<Rule>> rs = new HashMap<String, List<Rule>>(); Languages ls = Languages.instance(s); for (String l : ls.getLanguages()) { try { rs.put(l, parseRules(createScanner(s, rt, l), createResourceName(s, rt, l))); } catch (IllegalStateException e) { throw new IllegalStateException("Problem processing " + createResourceName(s, rt, l), e); } } if (!rt.equals(RuleType.RULES)) { rs.put("common", parseRules(createScanner(s, rt, "common"), createResourceName(s, rt, "common"))); } rts.put(rt, Collections.unmodifiableMap(rs)); } RULES.put(s, Collections.unmodifiableMap(rts)); } } private static String createResourceName(NameType nameType, RuleType rt, String lang) { return String.format("org/apache/commons/codec/language/bm/%s_%s_%s.txt", nameType.getName(), rt.getName(), lang); } private static Scanner createScanner(NameType nameType, RuleType rt, String lang) { String resName = createResourceName(nameType, rt, lang); InputStream rulesIS = Languages.class.getClassLoader().getResourceAsStream(resName); if (rulesIS == null) { throw new IllegalArgumentException("Unable to load resource: " + resName); } return new Scanner(rulesIS, ResourceConstants.ENCODING); } private static Scanner createScanner(String lang) { String resName = String.format("org/apache/commons/codec/language/bm/%s.txt", lang); InputStream rulesIS = Languages.class.getClassLoader().getResourceAsStream(resName); if (rulesIS == null) { throw new IllegalArgumentException("Unable to load resource: " + resName); } return new Scanner(rulesIS, ResourceConstants.ENCODING); } /** * Gets rules for a combination of name type, rule type and languages. * * @param nameType * the NameType to consider * @param rt * the RuleType to consider * @param langs * the set of languages to consider * @return a list of Rules that apply */ public static List<Rule> instance(NameType nameType, RuleType rt, Languages.LanguageSet langs) { if (langs.isSingleton()) { return instance(nameType, rt, langs.getAny()); } else { return instance(nameType, rt, Languages.ANY); } } /** * Gets rules for a combination of name type, rule type and a single language. * * @param nameType * the NameType to consider * @param rt * the RuleType to consider * @param lang * the language to consider * @return a list rules for a combination of name type, rule type and a single language. */ public static List<Rule> instance(NameType nameType, RuleType rt, String lang) { List<Rule> rules = RULES.get(nameType).get(rt).get(lang); if (rules == null) { throw new IllegalArgumentException(String.format("No rules found for %s, %s, %s.", nameType.getName(), rt.getName(), lang)); } return rules; } private static Phoneme parsePhoneme(String ph) { int open = ph.indexOf("["); if (open >= 0) { if (!ph.endsWith("]")) { throw new IllegalArgumentException("Phoneme expression contains a '[' but does not end in ']'"); } String before = ph.substring(0, open); String in = ph.substring(open + 1, ph.length() - 1); Set<String> langs = new HashSet<String>(Arrays.asList(in.split("[+]"))); return new Phoneme(before, Languages.LanguageSet.from(langs)); } else { return new Phoneme(ph, Languages.ANY_LANGUAGE); } } private static PhonemeExpr parsePhonemeExpr(String ph) { if (ph.startsWith("(")) { // we have a bracketed list of options if (!ph.endsWith(")")) { throw new IllegalArgumentException("Phoneme starts with '(' so must end with ')'"); } List<Phoneme> phs = new ArrayList<Phoneme>(); String body = ph.substring(1, ph.length() - 1); for (String part : body.split("[|]")) { phs.add(parsePhoneme(part)); } if (body.startsWith("|") || body.endsWith("|")) { phs.add(new Phoneme("", Languages.ANY_LANGUAGE)); } return new PhonemeList(phs); } else { return parsePhoneme(ph); } } private static List<Rule> parseRules(final Scanner scanner, final String location) { List<Rule> lines = new ArrayList<Rule>(); int currentLine = 0; boolean inMultilineComment = false; while (scanner.hasNextLine()) { currentLine++; String rawLine = scanner.nextLine(); String line = rawLine; if (inMultilineComment) { if (line.endsWith(ResourceConstants.EXT_CMT_END)) { inMultilineComment = false; } else { // skip } } else { if (line.startsWith(ResourceConstants.EXT_CMT_START)) { inMultilineComment = true; } else { // discard comments int cmtI = line.indexOf(ResourceConstants.CMT); if (cmtI >= 0) { line = line.substring(0, cmtI); } // trim leading-trailing whitespace line = line.trim(); if (line.length() == 0) { continue; // empty lines can be safely skipped } if (line.startsWith(HASH_INCLUDE)) { // include statement String incl = line.substring(HASH_INCLUDE.length()).trim(); if (incl.contains(" ")) { System.err.println("Warining: malformed import statement: " + rawLine); } else { lines.addAll(parseRules(createScanner(incl), location + "->" + incl)); } } else { // rule String[] parts = line.split("\\s+"); if (parts.length != 4) { System.err.println("Warning: malformed rule statement split into " + parts.length + " parts: " + rawLine); } else { try { String pat = stripQuotes(parts[0]); String lCon = stripQuotes(parts[1]); String rCon = stripQuotes(parts[2]); PhonemeExpr ph = parsePhonemeExpr(stripQuotes(parts[3])); final int cLine = currentLine; Rule r = new Rule(pat, lCon, rCon, ph) { private final int line = cLine; private final String loc = location; @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("Rule"); sb.append("{line=").append(line); sb.append(", loc='").append(loc).append('\''); sb.append('}'); return sb.toString(); } }; lines.add(r); } catch (IllegalArgumentException e) { throw new IllegalStateException("Problem parsing line " + currentLine, e); } } } } } } return lines; } private static String stripQuotes(String str) { if (str.startsWith(DOUBLE_QUOTE)) { str = str.substring(1); } if (str.endsWith(DOUBLE_QUOTE)) { str = str.substring(0, str.length() - 1); } return str; } private final RPattern lContext; private final String pattern; private final PhonemeExpr phoneme; private final RPattern rContext; /** * Creates a new rule. * * @param pattern * the pattern * @param lContext * the left context * @param rContext * the right context * @param phoneme * the resulting phoneme */ public Rule(String pattern, String lContext, String rContext, PhonemeExpr phoneme) { this.pattern = pattern; this.lContext = pattern(lContext + "$"); this.rContext = pattern("^" + rContext); this.phoneme = phoneme; } /** * Gets the left context. This is a regular expression that must match to the left of the pattern. * * @return the left context Pattern */ public RPattern getLContext() { return this.lContext; } /** * Gets the pattern. This is a string-literal that must exactly match. * * @return the pattern */ public String getPattern() { return this.pattern; } /** * Gets the phoneme. If the rule matches, this is the phoneme associated with the pattern match. * * @return the phoneme */ public PhonemeExpr getPhoneme() { return this.phoneme; } /** * Gets the right context. This is a regular expression that must match to the right of the pattern. * * @return the right context Pattern */ public RPattern getRContext() { return this.rContext; } /** * Decides if the pattern and context match the input starting at a position. * * @param input * the input String * @param i * the int position within the input * @return true if the pattern and left/right context match, false otherwise */ public boolean patternAndContextMatches(CharSequence input, int i) { if (i < 0) throw new IndexOutOfBoundsException("Can not match pattern at negative indexes"); int patternLength = this.pattern.length(); int ipl = i + patternLength; if (ipl > input.length()) { // not enough room for the pattern to match return false; } boolean patternMatches = input.subSequence(i, ipl).equals(this.pattern); boolean rContextMatches = this.rContext.matcher(input.subSequence(ipl, input.length())).find(); boolean lContextMatches = this.lContext.matcher(input.subSequence(0, i)).find(); return patternMatches && rContextMatches && lContextMatches; } /** * A minimal wrapper around the functionality of Pattern that we use, to allow for alternate implementations. */ public static interface RPattern { public RMatcher matcher(CharSequence input); } /** * A minimal wrapper around the functionality of Matcher that we use, to allow for alternate implementations. */ public static interface RMatcher { public boolean find(); } /** * Attempt to compile the regex into direct string ops, falling back to Pattern and Matcher in the worst case. * * @param regex * the regular expression to compile * @return an RPattern that will match this regex */ private static RPattern pattern(final String regex) { boolean startsWith = regex.startsWith("^"); boolean endsWith = regex.endsWith("$"); final String content = regex.substring(startsWith ? 1 : 0, endsWith ? regex.length() - 1 : regex.length()); boolean boxes = content.contains("["); if (!boxes) { if (startsWith && endsWith) { // exact match if (content.length() == 0) { // empty return new RPattern() { public RMatcher matcher(final CharSequence input) { return new RMatcher() { public boolean find() { return input.length() == 0; } }; } }; } else { return new RPattern() { public RMatcher matcher(final CharSequence input) { return new RMatcher() { public boolean find() { return input.equals(content); } }; } }; } } else if ((startsWith || endsWith) && content.length() == 0) { // matches every string return new RPattern() { public RMatcher matcher(CharSequence input) { return new RMatcher() { public boolean find() { return true; } }; } }; } else if (startsWith) { // matches from start return new RPattern() { public RMatcher matcher(final CharSequence input) { return new RMatcher() { public boolean find() { return startsWith(input, content); } }; } }; } else if (endsWith) { // matches from start return new RPattern() { public RMatcher matcher(final CharSequence input) { return new RMatcher() { public boolean find() { return endsWith(input, content); } }; } }; } } else { boolean startsWithBox = content.startsWith("["); boolean endsWithBox = content.endsWith("]"); if (startsWithBox && endsWithBox) { String boxContent = content.substring(1, content.length() - 1); if (!boxContent.contains("[")) { // box containing alternatives boolean negate = boxContent.startsWith("^"); if (negate) { boxContent = boxContent.substring(1); } final String bContent = boxContent; final boolean shouldMatch = !negate; if (startsWith && endsWith) { // exact match return new RPattern() { public RMatcher matcher(final CharSequence input) { return new RMatcher() { public boolean find() { return input.length() == 1 && (contains(bContent, input.charAt(0)) == shouldMatch); } }; } }; } else if (startsWith) { // first char return new RPattern() { public RMatcher matcher(final CharSequence input) { return new RMatcher() { public boolean find() { return input.length() > 0 && (contains(bContent, input.charAt(0)) == shouldMatch); } }; } }; } else if (endsWith) { // last char return new RPattern() { public RMatcher matcher(final CharSequence input) { return new RMatcher() { public boolean find() { return input.length() > 0 && (contains(bContent, input.charAt(input.length() - 1)) == shouldMatch); } }; } }; } } } } // System.out.println("Couldn't optimize regex: " + regex); return new RPattern() { Pattern pattern = Pattern.compile(regex); public RMatcher matcher(CharSequence input) { final Matcher matcher = pattern.matcher(input); return new RMatcher() { public boolean find() { return matcher.find(); } }; } }; } private static boolean startsWith(CharSequence input, CharSequence prefix) { if (prefix.length() > input.length()) return false; for (int i = 0; i < prefix.length(); i++) { if (input.charAt(i) != prefix.charAt(i)) { return false; } } return true; } private static boolean endsWith(CharSequence input, CharSequence suffix) { if (suffix.length() > input.length()) return false; for (int i = input.length() - 1, j = suffix.length() - 1; j >= 0; i--, j--) { if (input.charAt(i) != suffix.charAt(j)) { return false; } } return true; } private static boolean contains(CharSequence chars, char input) { for (int i = 0; i < chars.length(); i++) { if (chars.charAt(i) == input) { return true; } } return false; } private static class AppendableCharSeqeuence implements CharSequence { private final CharSequence left; private final CharSequence right; private final int length; private String contentCache = null; private AppendableCharSeqeuence(CharSequence left, CharSequence right) { this.left = left; this.right = right; this.length = left.length() + right.length(); } public int length() { return length; } public char charAt(int index) { // int lLength = left.length(); // if(index < lLength) return left.charAt(index); // else return right.charAt(index - lLength); return toString().charAt(index); } public CharSequence subSequence(int start, int end) { // int lLength = left.length(); // if(start > lLength) return right.subSequence(start - lLength, end - lLength); // else if(end <= lLength) return left.subSequence(start, end); // else { // CharSequence newLeft = left.subSequence(start, lLength); // CharSequence newRight = right.subSequence(0, end - lLength); // return new AppendableCharSeqeuence(newLeft, newRight); // } return toString().subSequence(start, end); } @Override public String toString() { if (contentCache == null) { StringBuilder sb = new StringBuilder(); buildString(sb); contentCache = sb.toString(); // System.err.println("Materialized string: " + contentCache); } return contentCache; } public void buildString(StringBuilder sb) { if (left instanceof AppendableCharSeqeuence) { ((AppendableCharSeqeuence) left).buildString(sb); } else { sb.append(left); } if (right instanceof AppendableCharSeqeuence) { ((AppendableCharSeqeuence) right).buildString(sb); } else { sb.append(right); } } } }
Code clean ups. git-svn-id: cde5a1597f50f50feab6f72941f6b219c34291a1@1154431 13f79535-47bb-0310-9956-ffa450edef68
src/java/org/apache/commons/codec/language/bm/Rule.java
Code clean ups.
Java
apache-2.0
8aff873a5b38f4d906bc77c9285fc7d2583d72de
0
Zrips/Jobs
/** * Jobs Plugin for Bukkit * Copyright (C) 2011 Zak Ford <zak.j.ford@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.gamingmesh.jobs.listeners; import com.gamingmesh.jobs.CMILib.ActionBarManager; import com.gamingmesh.jobs.CMILib.CMIChatColor; import com.gamingmesh.jobs.CMILib.CMIEnchantment; import com.gamingmesh.jobs.CMILib.CMIEntityType; import com.gamingmesh.jobs.CMILib.CMIMaterial; import com.gamingmesh.jobs.CMILib.ItemManager; import com.gamingmesh.jobs.CMILib.Version; import com.gamingmesh.jobs.Jobs; import com.gamingmesh.jobs.actions.*; import com.gamingmesh.jobs.api.JobsChunkChangeEvent; import com.gamingmesh.jobs.container.*; import com.gamingmesh.jobs.hooks.HookManager; import com.gamingmesh.jobs.stuff.FurnaceBrewingHandling; import com.gamingmesh.jobs.stuff.FurnaceBrewingHandling.ownershipFeedback; import com.google.common.base.Objects; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.BrewingStand; import org.bukkit.block.Furnace; import org.bukkit.block.data.Ageable; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Damageable; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.HumanEntity; import org.bukkit.entity.Item; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.entity.Sheep; import org.bukkit.entity.Tameable; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.enchantment.EnchantItemEvent; import org.bukkit.event.entity.*; import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; import org.bukkit.event.hanging.HangingBreakByEntityEvent; import org.bukkit.event.hanging.HangingPlaceEvent; import org.bukkit.event.inventory.BrewEvent; import org.bukkit.event.inventory.CraftItemEvent; import org.bukkit.event.inventory.FurnaceSmeltEvent; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryMoveItemEvent; import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.inventory.InventoryType.SlotType; import org.bukkit.event.player.PlayerFishEvent; import org.bukkit.event.player.PlayerInteractEntityEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerShearEntityEvent; import org.bukkit.inventory.AnvilInventory; import org.bukkit.inventory.EnchantingInventory; import org.bukkit.inventory.GrindstoneInventory; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.StonecutterInventory; import org.bukkit.inventory.meta.PotionMeta; import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.metadata.MetadataValue; import org.bukkit.projectiles.ProjectileSource; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.UUID; public class JobsPaymentListener implements Listener { private Jobs plugin; public static final String furnaceOwnerMetadata = "jobsFurnaceOwner", brewingOwnerMetadata = "jobsBrewingOwner", VegyMetadata = "VegyTimer"; private final String BlockMetadata = "BlockOwner", CowMetadata = "CowTimer", entityDamageByPlayer = "JobsEntityDamagePlayer"; public JobsPaymentListener(Jobs plugin) { this.plugin = plugin; } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void villagerTradeInventoryClick(InventoryClickEvent event) { if (event.isCancelled()) return; //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(event.getWhoClicked().getWorld())) return; // If event is nothing or place, do nothing switch (event.getAction()) { case NOTHING: case PLACE_ONE: case PLACE_ALL: case PLACE_SOME: return; default: break; } if (event.getInventory().getType() != InventoryType.MERCHANT || event.getSlot() != 2 || event.getSlotType() != SlotType.RESULT) return; ItemStack resultStack = event.getClickedInventory().getItem(2); if (resultStack == null) return; if (!(event.getWhoClicked() instanceof Player)) return; Player player = (Player) event.getWhoClicked(); //Check if inventory is full and using shift click, possible money dupping fix if (player.getInventory().firstEmpty() == -1 && event.isShiftClick()) { player.sendMessage(Jobs.getLanguage().getMessage("message.crafting.fullinventory")); return; } if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; if (!event.isLeftClick() && !event.isRightClick()) return; // check if in creative if (!payIfCreative(player)) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player); if (jPlayer == null) return; if (!Jobs.getGCManager().payForEachVTradeItem) { ItemStack currentItem = event.getCurrentItem(); if (resultStack.hasItemMeta() && resultStack.getItemMeta().hasDisplayName()) { Jobs.action(jPlayer, new ItemNameActionInfo(CMIChatColor.stripColor(resultStack.getItemMeta() .getDisplayName()), ActionType.VTRADE)); } else if (currentItem != null) { Jobs.action(jPlayer, new ItemActionInfo(currentItem, ActionType.VTRADE)); } return; } // Checking how much player traded ItemStack toCraft = event.getCurrentItem(); ItemStack toStore = event.getCursor(); // Make sure we are actually traded anything if (hasItems(toCraft)) if (event.isShiftClick()) schedulePostDetection(player, toCraft.clone(), jPlayer, resultStack.clone(), ActionType.VTRADE); else { // The items are stored in the cursor. Make sure there's enough space. if (isStackSumLegal(toCraft, toStore)) { int newItemsCount = toCraft.getAmount(); while (newItemsCount >= 1) { newItemsCount--; if (resultStack.hasItemMeta() && resultStack.getItemMeta().hasDisplayName()) Jobs.action(jPlayer, new ItemNameActionInfo(CMIChatColor.stripColor(resultStack.getItemMeta().getDisplayName()), ActionType.VTRADE)); else Jobs.action(jPlayer, new ItemActionInfo(resultStack, ActionType.VTRADE)); } } } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onCowMilking(PlayerInteractEntityEvent event) { Player player = event.getPlayer(); //disabling plugin in world if (!player.isOnline() || !Jobs.getGCManager().canPerformActionInWorld(player.getWorld())) return; if (!(event.getRightClicked() instanceof LivingEntity)) return; Entity cow = event.getRightClicked(); if (cow.getType() != EntityType.COW && cow.getType() != EntityType.MUSHROOM_COW) return; ItemStack itemInHand = Jobs.getNms().getItemInMainHand(player); if ((cow.getType() == EntityType.COW && itemInHand.getType() != Material.BUCKET) || (cow.getType() == EntityType.MUSHROOM_COW && itemInHand.getType() != Material.BOWL)) { return; } // check if in creative if (!payIfCreative(player)) return; if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; // pay JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player); if (jPlayer == null) return; if (!Jobs.isPlayerHaveAction(jPlayer, ActionType.MILK)) { return; } if (Jobs.getGCManager().CowMilkingTimer > 0) { if (cow.hasMetadata(CowMetadata)) { long time = cow.getMetadata(CowMetadata).get(0).asLong(); if (System.currentTimeMillis() < time + Jobs.getGCManager().CowMilkingTimer) { long timer = ((Jobs.getGCManager().CowMilkingTimer - (System.currentTimeMillis() - time)) / 1000); jPlayer.getPlayer().sendMessage(Jobs.getLanguage().getMessage("message.cowtimer", "%time%", timer)); if (Jobs.getGCManager().CancelCowMilking) event.setCancelled(true); return; } } } Jobs.action(jPlayer, new EntityActionInfo(cow, ActionType.MILK)); Long Timer = System.currentTimeMillis(); cow.setMetadata(CowMetadata, new FixedMetadataValue(plugin, Timer)); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onEntityShear(PlayerShearEntityEvent event) { Player player = event.getPlayer(); //disabling plugin in world if (!player.isOnline() || !Jobs.getGCManager().canPerformActionInWorld(player.getWorld())) return; if (!(event.getEntity() instanceof Sheep)) return; Sheep sheep = (Sheep) event.getEntity(); // mob spawner, no payment or experience if (sheep.hasMetadata(Jobs.getPlayerManager().getMobSpawnerMetadata()) && !Jobs.getGCManager().payNearSpawner()) { sheep.removeMetadata(Jobs.getPlayerManager().getMobSpawnerMetadata(), plugin); return; } // check if in creative if (!payIfCreative(player)) return; if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; if (!payForItemDurabilityLoss(player)) return; // pay JobsPlayer jDamager = Jobs.getPlayerManager().getJobsPlayer(player); if (jDamager == null || sheep.getColor() == null) return; if (Jobs.getGCManager().payForStackedEntities && HookManager.isPluginEnabled("WildStacker") && HookManager.getWildStackerHandler().isStackedEntity(sheep)) { for (com.bgsoftware.wildstacker.api.objects.StackedEntity stacked : HookManager.getWildStackerHandler().getStackedEntities()) { if (stacked.getType() == sheep.getType()) { Jobs.action(jDamager, new CustomKillInfo(((Sheep) stacked.getLivingEntity()).getColor().name(), ActionType.SHEAR)); } } } Jobs.action(jDamager, new CustomKillInfo(sheep.getColor().name(), ActionType.SHEAR)); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onBrewEvent(BrewEvent event) { Block block = event.getBlock(); //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(block.getWorld())) return; if (!block.hasMetadata(brewingOwnerMetadata)) return; List<MetadataValue> data = block.getMetadata(brewingOwnerMetadata); if (data.isEmpty()) return; // only care about first MetadataValue value = data.get(0); String playerName = value.asString(); UUID uuid = UUID.fromString(playerName); if (uuid == null) return; JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(uuid); if (jPlayer == null || !jPlayer.isOnline()) return; Player player = jPlayer.getPlayer(); if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; ItemStack contents = event.getContents().getIngredient(); if (contents == null) return; Jobs.action(jPlayer, new ItemActionInfo(contents, ActionType.BREW)); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onBlockBreak(BlockBreakEvent event) { Block block = event.getBlock(); //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(block.getWorld())) return; Player player = event.getPlayer(); if (!player.isOnline()) return; // check if in creative if (!payIfCreative(player)) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; CMIMaterial cmat = CMIMaterial.get(block); if (cmat == CMIMaterial.FURNACE || cmat == CMIMaterial.SMOKER || cmat == CMIMaterial.BLAST_FURNACE && block.hasMetadata(furnaceOwnerMetadata)) FurnaceBrewingHandling.removeFurnace(block); else if (cmat == CMIMaterial.BREWING_STAND || cmat == CMIMaterial.LEGACY_BREWING_STAND && block.hasMetadata(brewingOwnerMetadata)) FurnaceBrewingHandling.removeBrewing(block); if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; BlockActionInfo bInfo = new BlockActionInfo(block, ActionType.BREAK); FastPayment fp = Jobs.FASTPAYMENT.get(player.getUniqueId()); if (fp != null) { if (fp.getTime() > System.currentTimeMillis() && fp.getInfo().getName().equalsIgnoreCase(bInfo.getName()) || fp.getInfo().getNameWithSub().equalsIgnoreCase(bInfo.getNameWithSub())) { Jobs.perform(fp.getPlayer(), fp.getInfo(), fp.getPayment(), fp.getJob()); return; } Jobs.FASTPAYMENT.remove(player.getUniqueId()); } if (!payForItemDurabilityLoss(player)) return; ItemStack item = Jobs.getNms().getItemInMainHand(player); if (item.getType() != Material.AIR) { // Protection for block break with silktouch if (Jobs.getGCManager().useSilkTouchProtection) { for (Enchantment one : item.getEnchantments().keySet()) { if (CMIEnchantment.get(one) == CMIEnchantment.SILK_TOUCH && Jobs.getBpManager().isInBp(block)) { return; } } } } // Prevent money duplication when breaking plant blocks Material brokenBlock = block.getRelative(BlockFace.DOWN).getType(); if (Jobs.getGCManager().preventCropResizePayment && (brokenBlock == CMIMaterial.SUGAR_CANE.getMaterial() || brokenBlock == CMIMaterial.KELP.getMaterial() || brokenBlock == CMIMaterial.CACTUS.getMaterial() || brokenBlock == CMIMaterial.BAMBOO.getMaterial())) { return; } JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player); if (jPlayer == null) return; Jobs.action(jPlayer, bInfo, block); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onBlockPlace(BlockPlaceEvent event) { // A tool should not trigger a BlockPlaceEvent (fixes stripping logs bug #940) if (CMIMaterial.get(event.getItemInHand().getType()).isTool()) return; Block block = event.getBlock(); //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(block.getWorld())) return; // check to make sure you can build if (!event.canBuild()) return; Player player = event.getPlayer(); if (!player.isOnline()) return; if (Version.isCurrentEqualOrLower(Version.v1_12_R1) && ItemManager.getItem(event.getItemInHand()).isSimilar(CMIMaterial.BONE_MEAL.newCMIItemStack())) return; // check if in creative if (!payIfCreative(player)) return; if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; // Prevent money duplication when placing plant blocks Material placedBlock = event.getBlockPlaced().getRelative(BlockFace.DOWN).getType(); if (Jobs.getGCManager().preventCropResizePayment && (placedBlock == CMIMaterial.SUGAR_CANE.getMaterial() || placedBlock == CMIMaterial.KELP.getMaterial() || placedBlock == CMIMaterial.CACTUS.getMaterial() || placedBlock == CMIMaterial.BAMBOO.getMaterial())) { return; } JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player); if (jPlayer == null) return; Jobs.action(jPlayer, new BlockActionInfo(block, ActionType.PLACE), block); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerFish(PlayerFishEvent event) { Player player = event.getPlayer(); //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(player.getWorld())) return; // check if in creative if (!payIfCreative(player)) return; if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; if (!payForItemDurabilityLoss(player)) return; if (event.getState() == PlayerFishEvent.State.CAUGHT_FISH && event.getCaught() instanceof Item) { JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player); if (jPlayer == null) return; ItemStack items = ((Item) event.getCaught()).getItemStack(); Jobs.action(jPlayer, new ItemActionInfo(items, ActionType.FISH)); } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onAnimalTame(EntityTameEvent event) { //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(event.getEntity().getWorld())) return; LivingEntity animal = event.getEntity(); // Entity being tamed must be alive if (animal.isDead()) { return; } // mob spawner, no payment or experience if (animal.hasMetadata(Jobs.getPlayerManager().getMobSpawnerMetadata()) && !Jobs.getGCManager().payNearSpawner()) { animal.removeMetadata(Jobs.getPlayerManager().getMobSpawnerMetadata(), plugin); return; } Player player = (Player) event.getOwner(); if (!player.isOnline()) return; // check if in creative if (!payIfCreative(player)) return; if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; // pay JobsPlayer jDamager = Jobs.getPlayerManager().getJobsPlayer(player); if (jDamager == null) return; if (Jobs.getGCManager().payForStackedEntities && HookManager.isPluginEnabled("WildStacker") && HookManager.getWildStackerHandler().isStackedEntity(animal)) { for (com.bgsoftware.wildstacker.api.objects.StackedEntity stacked : HookManager.getWildStackerHandler().getStackedEntities()) { if (stacked.getType() == animal.getType()) { Jobs.action(jDamager, new EntityActionInfo(stacked.getLivingEntity(), ActionType.TAME)); } } } Jobs.action(jDamager, new EntityActionInfo(animal, ActionType.TAME)); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onInventoryCraft(CraftItemEvent event) { //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(event.getWhoClicked().getWorld())) return; // If event is nothing or place, do nothing switch (event.getAction()) { case NOTHING: case PLACE_ONE: case PLACE_ALL: case PLACE_SOME: return; default: break; } if (event.getSlotType() != SlotType.RESULT) return; ItemStack resultStack = event.getRecipe().getResult(); if (!(event.getWhoClicked() instanceof Player)) return; Player player = (Player) event.getWhoClicked(); //Check if inventory is full and using shift click, possible money dupping fix if (player.getInventory().firstEmpty() == -1 && event.isShiftClick()) { player.sendMessage(Jobs.getLanguage().getMessage("message.crafting.fullinventory")); return; } if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; if (!event.isLeftClick() && !event.isRightClick()) return; // check if in creative if (!payIfCreative(player)) return; // Checking if item is been repaired, not crafted. Combining 2 items ItemStack[] sourceItems = event.getInventory().getContents(); // For dye check List<ItemStack> DyeStack = new ArrayList<>(); int y = -1; CMIMaterial first = null, second = null, third = null; boolean leather = false; boolean shulker = false; for (ItemStack s : sourceItems) { if (s == null) continue; if (CMIMaterial.isDye(s.getType())) DyeStack.add(s); CMIMaterial mat = CMIMaterial.get(s); if (mat != CMIMaterial.NONE && mat != CMIMaterial.AIR) { y++; if (y == 0) first = mat; if (y == 1) second = mat; if (y == 2) third = mat; } switch (mat) { case LEATHER_BOOTS: case LEATHER_CHESTPLATE: case LEATHER_HELMET: case LEATHER_LEGGINGS: case LEATHER_HORSE_ARMOR: leather = true; break; case SHULKER_BOX: case BLACK_SHULKER_BOX: case BLUE_SHULKER_BOX: case BROWN_SHULKER_BOX: case CYAN_SHULKER_BOX: case GRAY_SHULKER_BOX: case GREEN_SHULKER_BOX: case LIGHT_BLUE_SHULKER_BOX: case LIGHT_GRAY_SHULKER_BOX: case LIME_SHULKER_BOX: case MAGENTA_SHULKER_BOX: case ORANGE_SHULKER_BOX: case PINK_SHULKER_BOX: case PURPLE_SHULKER_BOX: case RED_SHULKER_BOX: case WHITE_SHULKER_BOX: case YELLOW_SHULKER_BOX: shulker = true; break; default: break; } } JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player); if (jPlayer == null) return; if (y == 2 && first == second && third == second) { if (Jobs.getGCManager().payForCombiningItems && third == first) { Jobs.action(jPlayer, new ItemActionInfo(event.getCurrentItem(), ActionType.REPAIR)); } else { Jobs.action(jPlayer, new ItemActionInfo(resultStack, ActionType.REPAIR)); } return; } // Check Dyes if (y >= 2 && (third != null && third.isDye() || second != null && second.isDye() || first != null && first.isDye()) && (leather || shulker)) { Jobs.action(jPlayer, new ItemActionInfo(sourceItems[0], ActionType.DYE)); for (ItemStack OneDye : DyeStack) { Jobs.action(jPlayer, new ItemActionInfo(OneDye, ActionType.DYE)); } return; } // If we need to pay only by each craft action we will skip calculation how much was crafted if (!Jobs.getGCManager().PayForEachCraft) { ItemStack currentItem = event.getCurrentItem(); // when we trying to craft tipped arrow effects if (currentItem != null && currentItem.getItemMeta() instanceof PotionMeta) { PotionMeta potion = (PotionMeta) currentItem.getItemMeta(); Jobs.action(jPlayer, new PotionItemActionInfo(currentItem, ActionType.CRAFT, potion.getBasePotionData().getType())); } else if (resultStack.hasItemMeta() && resultStack.getItemMeta().hasDisplayName()) { Jobs.action(jPlayer, new ItemNameActionInfo(CMIChatColor.stripColor(resultStack.getItemMeta() .getDisplayName()), ActionType.CRAFT)); } else if (currentItem != null) { Jobs.action(jPlayer, new ItemActionInfo(currentItem, ActionType.CRAFT)); } return; } // Checking how much player crafted ItemStack toCraft = event.getCurrentItem(); ItemStack toStore = event.getCursor(); // Make sure we are actually crafting anything if (hasItems(toCraft)) if (event.isShiftClick()) schedulePostDetection(player, toCraft.clone(), jPlayer, resultStack.clone(), ActionType.CRAFT); else { // The items are stored in the cursor. Make sure there's enough space. if (isStackSumLegal(toCraft, toStore)) { int newItemsCount = toCraft.getAmount(); while (newItemsCount >= 1) { newItemsCount--; if (resultStack.hasItemMeta() && resultStack.getItemMeta().hasDisplayName()) Jobs.action(jPlayer, new ItemNameActionInfo(CMIChatColor.stripColor(resultStack.getItemMeta().getDisplayName()), ActionType.CRAFT)); else Jobs.action(jPlayer, new ItemActionInfo(resultStack, ActionType.CRAFT)); } } } } // HACK! The API doesn't allow us to easily determine the resulting number of // crafted items, so we're forced to compare the inventory before and after. private void schedulePostDetection(final HumanEntity player, final ItemStack compareItem, final JobsPlayer jPlayer, final ItemStack resultStack, final ActionType type) { final ItemStack[] preInv = player.getInventory().getContents(); // Clone the array. The content may (was for me) be mutable. for (int i = 0; i < preInv.length; i++) { preInv[i] = preInv[i] != null ? preInv[i].clone() : null; } Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { final ItemStack[] postInv = player.getInventory().getContents(); int newItemsCount = 0; for (int i = 0; i < preInv.length; i++) { ItemStack pre = preInv[i]; ItemStack post = postInv[i]; // We're only interested in filled slots that are different if (hasSameItem(compareItem, post) && (hasSameItem(compareItem, pre) || pre == null)) { newItemsCount += post.getAmount() - (pre != null ? pre.getAmount() : 0); } } if (newItemsCount > 0) { while (newItemsCount >= 1) { newItemsCount--; Jobs.action(jPlayer, new ItemActionInfo(resultStack, type)); } } } }, 1); } private static boolean hasItems(ItemStack stack) { return stack != null && stack.getAmount() > 0; } private static boolean hasSameItem(ItemStack a, ItemStack b) { if (a == null) return b == null; else if (b == null) return false; CMIMaterial mat1 = CMIMaterial.get(a), mat2 = CMIMaterial.get(b); return mat1 == mat2 && Jobs.getNms().getDurability(a) == Jobs.getNms().getDurability(b) && Objects.equal(a.getData(), b.getData()) && Objects.equal(a.getEnchantments(), b.getEnchantments()); } private static boolean isStackSumLegal(ItemStack a, ItemStack b) { // See if we can create a new item stack with the combined elements of a and b if (a == null || b == null) return true;// Treat null as an empty stack return a.getAmount() + b.getAmount() <= a.getType().getMaxStackSize(); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onInventoryRepair(InventoryClickEvent event) { //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(event.getWhoClicked().getWorld())) return; // If event is nothing or place, do nothing switch (event.getAction()) { case NOTHING: case PLACE_ONE: case PLACE_ALL: case PLACE_SOME: return; default: break; } Inventory inv = event.getInventory(); // must be anvil inventory if (!(inv instanceof AnvilInventory) && (Version.isCurrentEqualOrHigher(Version.v1_14_R1) && !(inv instanceof GrindstoneInventory) && !(inv instanceof StonecutterInventory))) return; int slot = event.getSlot(); if (event.getSlotType() != SlotType.RESULT || (slot != 2 && slot != 1)) return; if ((Version.isCurrentEqualOrHigher(Version.v1_14_R1) && !(inv instanceof StonecutterInventory)) && slot == 1) return; if (!(event.getWhoClicked() instanceof Player)) return; Player player = (Player) event.getWhoClicked(); //Check if inventory is full and using shift click, possible money dupping fix if (player.getInventory().firstEmpty() == -1 && event.isShiftClick()) { player.sendMessage(Jobs.getLanguage().getMessage("message.crafting.fullinventory")); return; } ItemStack resultStack = event.getCurrentItem(); if (resultStack == null) return; // Checking if this is only item rename ItemStack FirstSlot = null; try { FirstSlot = inv.getItem(0); } catch (NullPointerException e) { return; } if (FirstSlot == null) return; String OriginalName = null; String NewName = null; if (FirstSlot.hasItemMeta()) OriginalName = FirstSlot.getItemMeta().getDisplayName(); if (resultStack.hasItemMeta()) NewName = resultStack.getItemMeta().getDisplayName(); if (OriginalName != null && !OriginalName.equals(NewName) && inv.getItem(1) == null && !Jobs.getGCManager().PayForRenaming) return; // Check for world permissions if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; // check if in creative if (!payIfCreative(player)) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; // Fix for possible money duplication bugs. switch (event.getClick()) { case UNKNOWN: case WINDOW_BORDER_LEFT: case WINDOW_BORDER_RIGHT: case NUMBER_KEY: return; default: break; } // Fix money dupping issue when clicking continuously in the result item, but if in the // cursor have item, then dupping the money, #438 if (event.isLeftClick() && event.getCursor().getType() != Material.AIR) return; JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player); if (jPlayer == null) return; if (Version.isCurrentEqualOrHigher(Version.v1_14_R1) && inv instanceof StonecutterInventory) { Jobs.action(jPlayer, new ItemActionInfo(resultStack, ActionType.CRAFT)); return; } if (Jobs.getGCManager().PayForEnchantingOnAnvil && inv.getItem(1) != null && inv.getItem(1).getType() == Material.ENCHANTED_BOOK) { Map<Enchantment, Integer> enchants = resultStack.getEnchantments(); for (Entry<Enchantment, Integer> oneEnchant : enchants.entrySet()) { Enchantment enchant = oneEnchant.getKey(); if (enchant == null) continue; CMIEnchantment e = CMIEnchantment.get(enchant); String enchantName = e == null ? null : e.toString(); if (enchantName == null) continue; Integer level = oneEnchant.getValue(); if (level == null) continue; Jobs.action(jPlayer, new EnchantActionInfo(enchantName, level, ActionType.ENCHANT)); } } else Jobs.action(jPlayer, new ItemActionInfo(resultStack, ActionType.REPAIR)); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onEnchantItem(EnchantItemEvent event) { if (event.isCancelled()) return; //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(event.getEnchanter().getWorld())) return; Inventory inv = event.getInventory(); if (!(inv instanceof EnchantingInventory)) return; ItemStack resultStack = ((EnchantingInventory) inv).getItem(); if (resultStack == null) return; Player player = event.getEnchanter(); if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; // check if in creative if (!payIfCreative(player)) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; if (!payForItemDurabilityLoss(player)) return; JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player); if (jPlayer == null) return; Map<Enchantment, Integer> enchants = event.getEnchantsToAdd(); for (Entry<Enchantment, Integer> oneEnchant : enchants.entrySet()) { Enchantment enchant = oneEnchant.getKey(); if (enchant == null) continue; CMIEnchantment e = CMIEnchantment.get(enchant); String enchantName = e == null ? null : e.toString(); if (enchantName == null) continue; Integer level = oneEnchant.getValue(); if (level == null) continue; Jobs.action(jPlayer, new EnchantActionInfo(enchantName, level, ActionType.ENCHANT)); } Jobs.action(jPlayer, new ItemActionInfo(resultStack, ActionType.ENCHANT)); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onInventoryMoveItemEventToFurnace(InventoryMoveItemEvent event) { if (!Jobs.getGCManager().PreventHopperFillUps) return; String type = event.getDestination().getType().toString(); if (!type.equalsIgnoreCase("FURNACE") && !type.equalsIgnoreCase("SMOKER") && !type.equalsIgnoreCase("BLAST_FURNACE")) return; if (event.getItem().getType() == Material.AIR) return; Block block = null; switch (type.toLowerCase()) { case "furnace": block = ((Furnace) event.getDestination().getHolder()).getBlock(); break; case "smoker": // This should be done in this way to have backwards compatibility block = ((org.bukkit.block.Smoker) event.getDestination().getHolder()).getBlock(); break; case "blast_furnace": // This should be done in this way to have backwards compatibility block = ((org.bukkit.block.BlastFurnace) event.getDestination().getHolder()).getBlock(); break; default: break; } if (block == null) return; //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(block.getWorld())) return; if (block.hasMetadata(furnaceOwnerMetadata)) FurnaceBrewingHandling.removeFurnace(block); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onInventoryMoveItemEventToBrewingStand(InventoryMoveItemEvent event) { if (event.getDestination().getType() != InventoryType.BREWING) return; if (!Jobs.getGCManager().PreventBrewingStandFillUps) return; if (event.getItem().getType() == Material.AIR) return; BrewingStand stand = (BrewingStand) event.getDestination().getHolder(); //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(stand.getWorld())) return; Block block = stand.getBlock(); if (block.hasMetadata(brewingOwnerMetadata)) FurnaceBrewingHandling.removeBrewing(block); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onFurnaceSmelt(FurnaceSmeltEvent event) { Block block = event.getBlock(); //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(block.getWorld())) return; if (!block.hasMetadata(furnaceOwnerMetadata)) return; List<MetadataValue> data = block.getMetadata(furnaceOwnerMetadata); if (data.isEmpty()) return; // only care about first MetadataValue value = data.get(0); String playerName = value.asString(); UUID uuid = null; try { uuid = UUID.fromString(playerName); } catch (IllegalArgumentException e) { } if (uuid == null) return; Player player = Bukkit.getPlayer(uuid); if (player == null || !player.isOnline()) return; if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player); if (jPlayer == null) return; Jobs.action(jPlayer, new ItemActionInfo(event.getResult(), ActionType.SMELT)); } @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onEntityDamageByPlayer(EntityDamageEvent event) { //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(event.getEntity().getWorld())) return; if (!Jobs.getGCManager().MonsterDamageUse) return; Entity ent = event.getEntity(); if (ent instanceof Player) return; if (!(event instanceof EntityDamageByEntityEvent)) return; EntityDamageByEntityEvent attackevent = (EntityDamageByEntityEvent) event; Entity damager = attackevent.getDamager(); if (!(damager instanceof Player)) return; double damage = event.getFinalDamage(); if (!(ent instanceof Damageable)) return; double s = ((Damageable) ent).getHealth(); if (damage > s) damage = s; if (ent.hasMetadata(entityDamageByPlayer) && !ent.getMetadata(entityDamageByPlayer).isEmpty()) damage += ent.getMetadata(entityDamageByPlayer).get(0).asDouble(); ent.setMetadata(entityDamageByPlayer, new FixedMetadataValue(plugin, damage)); } @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onEntityDamageByProjectile(EntityDamageByEntityEvent event) { //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(event.getEntity().getWorld())) return; Entity ent = event.getEntity(); Entity damager = event.getDamager(); if (ent instanceof org.bukkit.entity.EnderCrystal && damager instanceof Player) { String meta = "enderCrystalDamage"; if (ent.hasMetadata(meta)) ent.removeMetadata(meta, plugin); ent.setMetadata(meta, new FixedMetadataValue(plugin, ent)); return; } if (!(damager instanceof Projectile) || !(ent instanceof Damageable)) return; Projectile projectile = (Projectile) damager; ProjectileSource shooter = projectile.getShooter(); double damage = event.getFinalDamage(); double s = ((Damageable) ent).getHealth(); if (damage > s) damage = s; if (shooter instanceof Player) { if (ent.hasMetadata(entityDamageByPlayer) && !ent.getMetadata(entityDamageByPlayer).isEmpty()) damage += ent.getMetadata(entityDamageByPlayer).get(0).asDouble(); ent.setMetadata(entityDamageByPlayer, new FixedMetadataValue(plugin, damage)); } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onEntityDeath(EntityDeathEvent event) { //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(event.getEntity().getWorld())) return; if (!(event.getEntity().getLastDamageCause() instanceof EntityDamageByEntityEvent)) return; EntityDamageByEntityEvent e = (EntityDamageByEntityEvent) event.getEntity().getLastDamageCause(); // Entity that died must be living if (!(e.getEntity() instanceof LivingEntity)) return; LivingEntity lVictim = (LivingEntity) e.getEntity(); //extra check for Citizens 2 sentry kills if (e.getDamager() instanceof Player && e.getDamager().hasMetadata("NPC")) return; if (Jobs.getGCManager().MythicMobsEnabled && HookManager.getMythicManager() != null && HookManager.getMythicManager().isMythicMob(lVictim)) { return; } // mob spawner, no payment or experience if (lVictim.hasMetadata(Jobs.getPlayerManager().getMobSpawnerMetadata()) && !Jobs.getGCManager().payNearSpawner()) { try { // So lets remove meta in case some plugin removes entity in wrong way. lVictim.removeMetadata(Jobs.getPlayerManager().getMobSpawnerMetadata(), plugin); } catch (Exception t) { } return; } Player pDamager = null; // Checking if killer is player if (e.getDamager() instanceof Player) { pDamager = (Player) e.getDamager(); // Checking if killer is MyPet animal } else if (HookManager.getMyPetManager() != null && HookManager.getMyPetManager().isMyPet(e.getDamager(), null)) { UUID uuid = HookManager.getMyPetManager().getOwnerOfPet(e.getDamager()); if (uuid != null) pDamager = Bukkit.getPlayer(uuid); // Checking if killer is tamed animal } else if (e.getDamager() instanceof Tameable) { Tameable t = (Tameable) e.getDamager(); if (t.isTamed() && t.getOwner() instanceof Player) pDamager = (Player) t.getOwner(); } else if (e.getDamager() instanceof Projectile) { Projectile pr = (Projectile) e.getDamager(); if (pr.getShooter() instanceof Player) pDamager = (Player) pr.getShooter(); } if (pDamager == null) return; // check if in creative if (!payIfCreative(pDamager)) return; if (!Jobs.getPermissionHandler().hasWorldPermission(pDamager, pDamager.getLocation().getWorld().getName())) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && pDamager.isInsideVehicle()) return; if (!payForItemDurabilityLoss(pDamager)) return; // pay JobsPlayer jDamager = Jobs.getPlayerManager().getJobsPlayer(pDamager); if (jDamager == null) return; if (lVictim instanceof Player && !lVictim.hasMetadata("NPC")) { Player VPlayer = (Player) lVictim; if (jDamager.getName().equalsIgnoreCase(VPlayer.getName())) return; } if (Jobs.getGCManager().MonsterDamageUse && lVictim.hasMetadata(entityDamageByPlayer) && !lVictim.getMetadata(entityDamageByPlayer).isEmpty()) { double damage = lVictim.getMetadata(entityDamageByPlayer).get(0).asDouble(); double perc = (damage * 100D) / Jobs.getNms().getMaxHealth(lVictim); if (perc < Jobs.getGCManager().MonsterDamagePercentage) return; } if (Jobs.getGCManager().payForStackedEntities && HookManager.isPluginEnabled("WildStacker") && HookManager.getWildStackerHandler().isStackedEntity(lVictim)) { for (com.bgsoftware.wildstacker.api.objects.StackedEntity stacked : HookManager.getWildStackerHandler().getStackedEntities()) { if (stacked.getType() == lVictim.getType()) { Jobs.action(jDamager, new EntityActionInfo(stacked.getLivingEntity(), ActionType.KILL), e.getDamager(), stacked.getLivingEntity()); } } } Jobs.action(jDamager, new EntityActionInfo(lVictim, ActionType.KILL), e.getDamager(), lVictim); // Payment for killing player with particular job, except NPC's if (lVictim instanceof Player && !lVictim.hasMetadata("NPC")) { JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer((Player) lVictim); if (jPlayer == null) return; for (JobProgression job : jPlayer.getJobProgression()) { Jobs.action(jDamager, new CustomKillInfo(job.getJob().getName(), ActionType.CUSTOMKILL), pDamager, lVictim); } } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onCreatureSpawn(CreatureSpawnEvent event) { //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(event.getEntity().getWorld())) return; if (event.getSpawnReason() == SpawnReason.SPAWNER || event.getSpawnReason() == SpawnReason.SPAWNER_EGG) { LivingEntity creature = event.getEntity(); creature.setMetadata(Jobs.getPlayerManager().getMobSpawnerMetadata(), new FixedMetadataValue(plugin, true)); } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onHangingPlaceEvent(HangingPlaceEvent event) { //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(event.getEntity().getWorld())) return; Player player = event.getPlayer(); if (player == null || !player.isOnline()) return; // check if in creative if (!payIfCreative(player)) return; if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player); if (jPlayer == null) return; Jobs.action(jPlayer, new EntityActionInfo(event.getEntity(), ActionType.PLACE)); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onHangingBreakEvent(HangingBreakByEntityEvent event) { //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(event.getEntity().getWorld())) return; if (!(event.getRemover() instanceof Player)) return; Player player = (Player) event.getRemover(); if (!player.isOnline()) return; // check if in creative if (!payIfCreative(player)) return; if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player); if (jPlayer == null) return; Jobs.action(jPlayer, new EntityActionInfo(event.getEntity(), ActionType.BREAK)); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onArmorstandPlace(CreatureSpawnEvent event) { Entity ent = event.getEntity(); if (!ent.getType().toString().equalsIgnoreCase("ARMOR_STAND")) return; Location loc = event.getLocation(); java.util.Collection<Entity> ents = Version.isCurrentEqualOrLower(Version.v1_8_R1) || loc.getWorld() == null ? null : loc.getWorld().getNearbyEntities(loc, 4, 4, 4); if (ents == null) { return; } double dis = Double.MAX_VALUE; Player player = null; for (Entity one : ents) { if (!(one instanceof Player)) continue; Player p = (Player) one; if (!Jobs.getNms().getItemInMainHand(p).getType().toString().equalsIgnoreCase("ARMOR_STAND")) continue; double d = p.getLocation().distance(loc); if (d < dis) { dis = d; player = p; } } if (player == null || !player.isOnline()) return; // check if in creative if (!payIfCreative(player)) return; if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player); if (jPlayer == null) return; Jobs.action(jPlayer, new EntityActionInfo(ent, ActionType.PLACE)); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onArmorstandBreak(EntityDeathEvent event) { Entity ent = event.getEntity(); if (!ent.getType().toString().equalsIgnoreCase("ARMOR_STAND")) return; if (!(event.getEntity().getLastDamageCause() instanceof EntityDamageByEntityEvent)) return; EntityDamageByEntityEvent e = (EntityDamageByEntityEvent) event.getEntity().getLastDamageCause(); //extra check for Citizens 2 sentry kills if (!(e.getDamager() instanceof Player)) return; if (e.getDamager().hasMetadata("NPC")) return; Player pDamager = (Player) e.getDamager(); // check if in creative if (!payIfCreative(pDamager)) return; if (!Jobs.getPermissionHandler().hasWorldPermission(pDamager, pDamager.getLocation().getWorld().getName())) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && pDamager.isInsideVehicle()) return; // pay JobsPlayer jDamager = Jobs.getPlayerManager().getJobsPlayer(pDamager); if (jDamager == null) return; Jobs.action(jDamager, new EntityActionInfo(ent, ActionType.BREAK), e.getDamager()); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onCreatureSpawn(SlimeSplitEvent event) { //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(event.getEntity().getWorld())) return; if (!event.getEntity().hasMetadata(Jobs.getPlayerManager().getMobSpawnerMetadata())) return; EntityType type = event.getEntityType(); if (type == EntityType.SLIME && Jobs.getGCManager().PreventSlimeSplit) { event.setCancelled(true); return; } if (type == EntityType.MAGMA_CUBE && Jobs.getGCManager().PreventMagmaCubeSplit) { event.setCancelled(true); } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onCreatureBreed(CreatureSpawnEvent event) { //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(event.getEntity().getWorld())) return; if (!Jobs.getGCManager().useBreederFinder) return; SpawnReason reason = event.getSpawnReason(); if (!reason.toString().equalsIgnoreCase("BREEDING") && !reason.toString().equalsIgnoreCase("EGG")) return; LivingEntity animal = event.getEntity(); double closest = 30.0; Player player = null; for (Player i : Bukkit.getOnlinePlayers()) { if (!i.getWorld().getName().equals(animal.getWorld().getName())) continue; double dist = i.getLocation().distance(animal.getLocation()); if (closest > dist) { closest = dist; player = i; } } if (player != null && closest < 30.0) { // check if in creative if (!payIfCreative(player)) return; if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; // pay JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player); if (jPlayer == null) return; Jobs.action(jPlayer, new EntityActionInfo(animal, ActionType.BREED)); } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerEat(FoodLevelChangeEvent event) { //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(event.getEntity().getWorld())) return; if (!(event.getEntity() instanceof Player) || event.getEntity().hasMetadata("NPC") || event.getFoodLevel() <= ((Player) event.getEntity()).getFoodLevel()) return; Player player = (Player) event.getEntity(); if (!player.isOnline()) return; // check if in creative if (!payIfCreative(player)) return; if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player); if (jPlayer == null) return; // Item in hand ItemStack item = Jobs.getNms().getItemInMainHand(player); Jobs.action(jPlayer, new ItemActionInfo(item, ActionType.EAT)); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onTntExplode(EntityExplodeEvent event) { Entity e = event.getEntity(); if (!Jobs.getGCManager().canPerformActionInWorld(e)) return; EntityType type = event.getEntityType(); if (type != EntityType.PRIMED_TNT && type != EntityType.MINECART_TNT && type != CMIEntityType.ENDER_CRYSTAL.getType()) return; if (!Jobs.getGCManager().isUseTntFinder() && type != CMIEntityType.ENDER_CRYSTAL.getType()) return; double closest = 60.0; Player player = null; Location loc = e.getLocation(); for (Player i : Bukkit.getOnlinePlayers()) { if (loc.getWorld() != i.getWorld()) continue; double dist = i.getLocation().distance(loc); if (closest > dist) { closest = dist; player = i; } } if (player == null || closest == 60.0 || !player.isOnline()) return; // check if in creative if (!payIfCreative(player) || !Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player); if (jPlayer == null) return; if (!Jobs.getGCManager().isUseTntFinder() && type == CMIEntityType.ENDER_CRYSTAL.getType()) { String meta = "enderCrystalDamage"; if (type == CMIEntityType.ENDER_CRYSTAL.getType() && e.hasMetadata(meta) && !e.getMetadata(meta).isEmpty()) { Entity killed = (Entity) e.getMetadata(meta).get(0).value(); if (killed != null) { Jobs.action(jPlayer, new EntityActionInfo(killed, ActionType.KILL)); killed.removeMetadata(meta, plugin); return; } } } for (Block block : event.blockList()) { if (block == null) continue; CMIMaterial cmat = CMIMaterial.get(block); if (cmat == CMIMaterial.FURNACE || cmat == CMIMaterial.SMOKER || cmat == CMIMaterial.BLAST_FURNACE && block.hasMetadata(furnaceOwnerMetadata)) FurnaceBrewingHandling.removeFurnace(block); else if (cmat == CMIMaterial.BREWING_STAND || cmat == CMIMaterial.LEGACY_BREWING_STAND && block.hasMetadata(brewingOwnerMetadata)) FurnaceBrewingHandling.removeBrewing(block); if (Jobs.getGCManager().useBlockProtection && block.getState().hasMetadata(BlockMetadata)) return; BlockActionInfo bInfo = new BlockActionInfo(block, ActionType.TNTBREAK); Jobs.action(jPlayer, bInfo, block); } } @EventHandler(priority = EventPriority.MONITOR) public void onPlayerInteract(PlayerInteractEvent event) { Player p = event.getPlayer(); if (!Jobs.getGCManager().canPerformActionInWorld(p.getWorld())) return; final Block block = event.getClickedBlock(); if (block == null) return; CMIMaterial cmat = CMIMaterial.get(block); final JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(p); Material hand = Jobs.getNms().getItemInMainHand(p).getType(); if (Version.isCurrentEqualOrHigher(Version.v1_14_R1) && event.useInteractedBlock() != org.bukkit.event.Event.Result.DENY && event.getAction() == Action.RIGHT_CLICK_BLOCK && jPlayer != null && !p.isSneaking()) { if (cmat == CMIMaterial.COMPOSTER) { org.bukkit.block.data.Levelled level = (org.bukkit.block.data.Levelled) block.getBlockData(); if (level.getLevel() == level.getMaximumLevel()) { Jobs.action(jPlayer, new BlockActionInfo(block, ActionType.COLLECT), block); } } if (cmat == CMIMaterial.SWEET_BERRY_BUSH && hand != CMIMaterial.BONE_MEAL.getMaterial()) { Ageable age = (Ageable) block.getBlockData(); Jobs.action(jPlayer, new BlockCollectInfo(block, ActionType.COLLECT, age.getAge()), block); } } if (Version.isCurrentEqualOrHigher(Version.v1_15_R1) && event.useInteractedBlock() != org.bukkit.event.Event.Result.DENY && event.getAction() == Action.RIGHT_CLICK_BLOCK && !p.isSneaking() && jPlayer != null && (cmat == CMIMaterial.BEEHIVE || cmat == CMIMaterial.BEE_NEST)) { org.bukkit.block.data.type.Beehive beehive = (org.bukkit.block.data.type.Beehive) block.getBlockData(); if (beehive.getHoneyLevel() == beehive.getMaximumHoneyLevel() && (hand == CMIMaterial.SHEARS.getMaterial() || hand == CMIMaterial.GLASS_BOTTLE.getMaterial())) { Jobs.action(jPlayer, new BlockCollectInfo(block, ActionType.COLLECT, beehive.getHoneyLevel()), block); } } if (cmat == CMIMaterial.FURNACE || cmat == CMIMaterial.LEGACY_BURNING_FURNACE || cmat == CMIMaterial.SMOKER || cmat == CMIMaterial.BLAST_FURNACE) { ownershipFeedback done = FurnaceBrewingHandling.registerFurnaces(p, block); if (done == ownershipFeedback.tooMany) { boolean report = false; if (block.hasMetadata(furnaceOwnerMetadata)) { List<MetadataValue> data = block.getMetadata(furnaceOwnerMetadata); if (data.isEmpty()) return; // only care about first MetadataValue value = data.get(0); String uuid = value.asString(); if (!uuid.equals(p.getUniqueId().toString())) report = true; } else report = true; if (report) ActionBarManager.send(p, Jobs.getLanguage().getMessage("general.error.noFurnaceRegistration")); } else if (done == ownershipFeedback.newReg && jPlayer != null) { ActionBarManager.send(p, Jobs.getLanguage().getMessage("general.error.newFurnaceRegistration", "[current]", jPlayer.getFurnaceCount(), "[max]", jPlayer.getMaxFurnacesAllowed(cmat) == 0 ? "-" : jPlayer.getMaxFurnacesAllowed(cmat))); } } else if (cmat == CMIMaterial.BREWING_STAND || cmat == CMIMaterial.LEGACY_BREWING_STAND) { ownershipFeedback done = FurnaceBrewingHandling.registerBrewingStand(p, block); if (done == ownershipFeedback.tooMany) { boolean report = false; if (block.hasMetadata(brewingOwnerMetadata)) { List<MetadataValue> data = block.getMetadata(brewingOwnerMetadata); if (data.isEmpty()) return; // only care about first MetadataValue value = data.get(0); String uuid = value.asString(); if (!uuid.equals(p.getUniqueId().toString())) report = true; } else report = true; if (report) ActionBarManager.send(p, Jobs.getLanguage().getMessage("general.error.noBrewingRegistration")); } else if (done == ownershipFeedback.newReg && jPlayer != null) { ActionBarManager.send(p, Jobs.getLanguage().getMessage("general.error.newBrewingRegistration", "[current]", jPlayer.getBrewingStandCount(), "[max]", jPlayer.getMaxBrewingStandsAllowed() == 0 ? "-" : jPlayer.getMaxBrewingStandsAllowed())); } } else if (Version.isCurrentEqualOrHigher(Version.v1_13_R1) && block.getType().toString().startsWith("STRIPPED_") && event.getAction() == Action.RIGHT_CLICK_BLOCK) { ItemStack iih = Jobs.getNms().getItemInMainHand(p); if (iih.getType().toString().endsWith("_AXE")) { // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && p.isInsideVehicle()) return; // Prevent item durability loss if (!Jobs.getGCManager().payItemDurabilityLoss && iih.getType().getMaxDurability() - Jobs.getNms().getDurability(iih) != iih.getType().getMaxDurability()) return; Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> { if (jPlayer != null) Jobs.action(jPlayer, new BlockActionInfo(block, ActionType.STRIPLOGS), block); }, 1); } } } @EventHandler public void onExplore(JobsChunkChangeEvent event) { if (event.isCancelled()) return; Player player = event.getPlayer(); //disabling plugin in world if (player == null || !player.isOnline() || !Jobs.getGCManager().canPerformActionInWorld(player.getWorld())) return; if (!Jobs.getExplore().isExploreEnabled()) return; // check if in spectator, #330 if (player.getGameMode().toString().equals("SPECTATOR")) return; if (!Jobs.getGCManager().payExploringWhenFlying() && player.isFlying()) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; if (Jobs.getVersionCheckManager().getVersion().isEqualOrHigher(Version.v1_9_R2) && !Jobs.getGCManager().payExploringWhenGliding && player.isGliding()) return; // check if in creative if (!payIfCreative(player)) return; if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player); if (jPlayer == null) return; ExploreRespond respond = Jobs.getExplore().ChunkRespond(jPlayer.getUserId(), event.getNewChunk()); if (!respond.isNewChunk()) return; Jobs.action(jPlayer, new ExploreActionInfo(String.valueOf(respond.getCount()), ActionType.EXPLORE)); } public static boolean payIfCreative(Player player) { if (player.getGameMode() == GameMode.CREATIVE && !Jobs.getGCManager().payInCreative() && !player.hasPermission("jobs.paycreative")) return false; return true; } // Prevent item durability loss public static boolean payForItemDurabilityLoss(Player p) { if (Jobs.getGCManager().payItemDurabilityLoss) return true; ItemStack hand = Jobs.getNms().getItemInMainHand(p); CMIMaterial cmat = CMIMaterial.get(hand); HashMap<Enchantment, Integer> got = Jobs.getGCManager().whiteListedItems.get(cmat); if (got == null) return false; if (Jobs.getNms().getDurability(hand) == 0) return true; for (Entry<Enchantment, Integer> oneG : got.entrySet()) { if (!hand.getEnchantments().containsKey(oneG.getKey()) || hand.getEnchantments().get(oneG.getKey()).equals(oneG.getValue())) return false; } return true; } }
src/main/java/com/gamingmesh/jobs/listeners/JobsPaymentListener.java
/** * Jobs Plugin for Bukkit * Copyright (C) 2011 Zak Ford <zak.j.ford@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.gamingmesh.jobs.listeners; import com.gamingmesh.jobs.CMILib.ActionBarManager; import com.gamingmesh.jobs.CMILib.CMIChatColor; import com.gamingmesh.jobs.CMILib.CMIEnchantment; import com.gamingmesh.jobs.CMILib.CMIEntityType; import com.gamingmesh.jobs.CMILib.CMIMaterial; import com.gamingmesh.jobs.CMILib.ItemManager; import com.gamingmesh.jobs.CMILib.Version; import com.gamingmesh.jobs.Jobs; import com.gamingmesh.jobs.actions.*; import com.gamingmesh.jobs.api.JobsChunkChangeEvent; import com.gamingmesh.jobs.container.*; import com.gamingmesh.jobs.hooks.HookManager; import com.gamingmesh.jobs.stuff.FurnaceBrewingHandling; import com.gamingmesh.jobs.stuff.FurnaceBrewingHandling.ownershipFeedback; import com.google.common.base.Objects; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.BrewingStand; import org.bukkit.block.Furnace; import org.bukkit.block.data.Ageable; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Damageable; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.HumanEntity; import org.bukkit.entity.Item; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.entity.Sheep; import org.bukkit.entity.Tameable; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.enchantment.EnchantItemEvent; import org.bukkit.event.entity.*; import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; import org.bukkit.event.hanging.HangingBreakByEntityEvent; import org.bukkit.event.hanging.HangingPlaceEvent; import org.bukkit.event.inventory.BrewEvent; import org.bukkit.event.inventory.CraftItemEvent; import org.bukkit.event.inventory.FurnaceSmeltEvent; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryMoveItemEvent; import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.inventory.InventoryType.SlotType; import org.bukkit.event.player.PlayerFishEvent; import org.bukkit.event.player.PlayerInteractEntityEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerShearEntityEvent; import org.bukkit.inventory.AnvilInventory; import org.bukkit.inventory.EnchantingInventory; import org.bukkit.inventory.GrindstoneInventory; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.StonecutterInventory; import org.bukkit.inventory.meta.PotionMeta; import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.metadata.MetadataValue; import org.bukkit.projectiles.ProjectileSource; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.UUID; public class JobsPaymentListener implements Listener { private Jobs plugin; public static final String furnaceOwnerMetadata = "jobsFurnaceOwner", brewingOwnerMetadata = "jobsBrewingOwner", VegyMetadata = "VegyTimer"; private final String BlockMetadata = "BlockOwner", CowMetadata = "CowTimer", entityDamageByPlayer = "JobsEntityDamagePlayer"; public JobsPaymentListener(Jobs plugin) { this.plugin = plugin; } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void villagerTradeInventoryClick(InventoryClickEvent event) { if (event.isCancelled()) return; //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(event.getWhoClicked().getWorld())) return; // If event is nothing or place, do nothing switch (event.getAction()) { case NOTHING: case PLACE_ONE: case PLACE_ALL: case PLACE_SOME: return; default: break; } if (event.getInventory().getType() != InventoryType.MERCHANT || event.getSlot() != 2 || event.getSlotType() != SlotType.RESULT) return; ItemStack resultStack = event.getClickedInventory().getItem(2); if (resultStack == null) return; if (!(event.getWhoClicked() instanceof Player)) return; Player player = (Player) event.getWhoClicked(); //Check if inventory is full and using shift click, possible money dupping fix if (player.getInventory().firstEmpty() == -1 && event.isShiftClick()) { player.sendMessage(Jobs.getLanguage().getMessage("message.crafting.fullinventory")); return; } if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; if (!event.isLeftClick() && !event.isRightClick()) return; // check if in creative if (!payIfCreative(player)) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player); if (jPlayer == null) return; if (!Jobs.getGCManager().payForEachVTradeItem) { ItemStack currentItem = event.getCurrentItem(); if (resultStack.hasItemMeta() && resultStack.getItemMeta().hasDisplayName()) { Jobs.action(jPlayer, new ItemNameActionInfo(CMIChatColor.stripColor(resultStack.getItemMeta() .getDisplayName()), ActionType.VTRADE)); } else if (currentItem != null) { Jobs.action(jPlayer, new ItemActionInfo(currentItem, ActionType.VTRADE)); } return; } // Checking how much player traded ItemStack toCraft = event.getCurrentItem(); ItemStack toStore = event.getCursor(); // Make sure we are actually traded anything if (hasItems(toCraft)) if (event.isShiftClick()) schedulePostDetection(player, toCraft.clone(), jPlayer, resultStack.clone(), ActionType.VTRADE); else { // The items are stored in the cursor. Make sure there's enough space. if (isStackSumLegal(toCraft, toStore)) { int newItemsCount = toCraft.getAmount(); while (newItemsCount >= 1) { newItemsCount--; if (resultStack.hasItemMeta() && resultStack.getItemMeta().hasDisplayName()) Jobs.action(jPlayer, new ItemNameActionInfo(CMIChatColor.stripColor(resultStack.getItemMeta().getDisplayName()), ActionType.VTRADE)); else Jobs.action(jPlayer, new ItemActionInfo(resultStack, ActionType.VTRADE)); } } } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onCowMilking(PlayerInteractEntityEvent event) { Player player = event.getPlayer(); //disabling plugin in world if (!player.isOnline() || !Jobs.getGCManager().canPerformActionInWorld(player.getWorld())) return; if (!(event.getRightClicked() instanceof LivingEntity)) return; Entity cow = event.getRightClicked(); if (cow.getType() != EntityType.COW && cow.getType() != EntityType.MUSHROOM_COW) return; ItemStack itemInHand = Jobs.getNms().getItemInMainHand(player); if ((cow.getType() == EntityType.COW && itemInHand.getType() != Material.BUCKET) || (cow.getType() == EntityType.MUSHROOM_COW && itemInHand.getType() != Material.BOWL)) { return; } // check if in creative if (!payIfCreative(player)) return; if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; // pay JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player); if (jPlayer == null) return; if (!Jobs.isPlayerHaveAction(jPlayer, ActionType.MILK)) { return; } if (Jobs.getGCManager().CowMilkingTimer > 0) { if (cow.hasMetadata(CowMetadata)) { long time = cow.getMetadata(CowMetadata).get(0).asLong(); if (System.currentTimeMillis() < time + Jobs.getGCManager().CowMilkingTimer) { long timer = ((Jobs.getGCManager().CowMilkingTimer - (System.currentTimeMillis() - time)) / 1000); jPlayer.getPlayer().sendMessage(Jobs.getLanguage().getMessage("message.cowtimer", "%time%", timer)); if (Jobs.getGCManager().CancelCowMilking) event.setCancelled(true); return; } } } Jobs.action(jPlayer, new EntityActionInfo(cow, ActionType.MILK)); Long Timer = System.currentTimeMillis(); cow.setMetadata(CowMetadata, new FixedMetadataValue(plugin, Timer)); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onEntityShear(PlayerShearEntityEvent event) { Player player = event.getPlayer(); //disabling plugin in world if (!player.isOnline() || !Jobs.getGCManager().canPerformActionInWorld(player.getWorld())) return; if (!(event.getEntity() instanceof Sheep)) return; Sheep sheep = (Sheep) event.getEntity(); // mob spawner, no payment or experience if (sheep.hasMetadata(Jobs.getPlayerManager().getMobSpawnerMetadata()) && !Jobs.getGCManager().payNearSpawner()) { sheep.removeMetadata(Jobs.getPlayerManager().getMobSpawnerMetadata(), plugin); return; } // check if in creative if (!payIfCreative(player)) return; if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; if (!payForItemDurabilityLoss(player)) return; // pay JobsPlayer jDamager = Jobs.getPlayerManager().getJobsPlayer(player); if (jDamager == null || sheep.getColor() == null) return; if (Jobs.getGCManager().payForStackedEntities && HookManager.isPluginEnabled("WildStacker") && HookManager.getWildStackerHandler().isStackedEntity(sheep)) { for (com.bgsoftware.wildstacker.api.objects.StackedEntity stacked : HookManager.getWildStackerHandler().getStackedEntities()) { if (stacked.getType() == sheep.getType()) { Jobs.action(jDamager, new CustomKillInfo(((Sheep) stacked.getLivingEntity()).getColor().name(), ActionType.SHEAR)); } } } Jobs.action(jDamager, new CustomKillInfo(sheep.getColor().name(), ActionType.SHEAR)); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onBrewEvent(BrewEvent event) { Block block = event.getBlock(); //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(block.getWorld())) return; if (!block.hasMetadata(brewingOwnerMetadata)) return; List<MetadataValue> data = block.getMetadata(brewingOwnerMetadata); if (data.isEmpty()) return; // only care about first MetadataValue value = data.get(0); String playerName = value.asString(); UUID uuid = UUID.fromString(playerName); if (uuid == null) return; JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(uuid); if (jPlayer == null || !jPlayer.isOnline()) return; Player player = jPlayer.getPlayer(); if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; ItemStack contents = event.getContents().getIngredient(); if (contents == null) return; Jobs.action(jPlayer, new ItemActionInfo(contents, ActionType.BREW)); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onBlockBreak(BlockBreakEvent event) { Block block = event.getBlock(); //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(block.getWorld())) return; Player player = event.getPlayer(); if (!player.isOnline()) return; // check if in creative if (!payIfCreative(player)) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; CMIMaterial cmat = CMIMaterial.get(block); if (cmat == CMIMaterial.FURNACE || cmat == CMIMaterial.SMOKER || cmat == CMIMaterial.BLAST_FURNACE && block.hasMetadata(furnaceOwnerMetadata)) FurnaceBrewingHandling.removeFurnace(block); else if (cmat == CMIMaterial.BREWING_STAND || cmat == CMIMaterial.LEGACY_BREWING_STAND && block.hasMetadata(brewingOwnerMetadata)) FurnaceBrewingHandling.removeBrewing(block); if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; BlockActionInfo bInfo = new BlockActionInfo(block, ActionType.BREAK); FastPayment fp = Jobs.FASTPAYMENT.get(player.getUniqueId()); if (fp != null) { if (fp.getTime() > System.currentTimeMillis() && fp.getInfo().getName().equalsIgnoreCase(bInfo.getName()) || fp.getInfo().getNameWithSub().equalsIgnoreCase(bInfo.getNameWithSub())) { Jobs.perform(fp.getPlayer(), fp.getInfo(), fp.getPayment(), fp.getJob()); return; } Jobs.FASTPAYMENT.remove(player.getUniqueId()); } if (!payForItemDurabilityLoss(player)) return; ItemStack item = Jobs.getNms().getItemInMainHand(player); if (item.getType() != Material.AIR) { // Protection for block break with silktouch if (Jobs.getGCManager().useSilkTouchProtection) { for (Enchantment one : item.getEnchantments().keySet()) { if (CMIEnchantment.get(one) == CMIEnchantment.SILK_TOUCH && Jobs.getBpManager().isInBp(block)) { return; } } } } // Prevent money duplication when breaking plant blocks Material brokenBlock = block.getRelative(BlockFace.DOWN).getType(); if (Jobs.getGCManager().preventCropResizePayment && (brokenBlock == CMIMaterial.SUGAR_CANE.getMaterial() || brokenBlock == CMIMaterial.KELP.getMaterial() || brokenBlock == CMIMaterial.CACTUS.getMaterial() || brokenBlock == CMIMaterial.BAMBOO.getMaterial())) { return; } JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player); if (jPlayer == null) return; Jobs.action(jPlayer, bInfo, block); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onBlockPlace(BlockPlaceEvent event) { Block block = event.getBlock(); //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(block.getWorld())) return; // check to make sure you can build if (!event.canBuild()) return; Player player = event.getPlayer(); if (!player.isOnline()) return; if (Version.isCurrentEqualOrLower(Version.v1_12_R1) && ItemManager.getItem(event.getItemInHand()).isSimilar(CMIMaterial.BONE_MEAL.newCMIItemStack())) return; // check if in creative if (!payIfCreative(player)) return; if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; // Prevent money duplication when placing plant blocks Material placedBlock = event.getBlockPlaced().getRelative(BlockFace.DOWN).getType(); if (Jobs.getGCManager().preventCropResizePayment && (placedBlock == CMIMaterial.SUGAR_CANE.getMaterial() || placedBlock == CMIMaterial.KELP.getMaterial() || placedBlock == CMIMaterial.CACTUS.getMaterial() || placedBlock == CMIMaterial.BAMBOO.getMaterial())) { return; } JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player); if (jPlayer == null) return; Jobs.action(jPlayer, new BlockActionInfo(block, ActionType.PLACE), block); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerFish(PlayerFishEvent event) { Player player = event.getPlayer(); //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(player.getWorld())) return; // check if in creative if (!payIfCreative(player)) return; if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; if (!payForItemDurabilityLoss(player)) return; if (event.getState() == PlayerFishEvent.State.CAUGHT_FISH && event.getCaught() instanceof Item) { JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player); if (jPlayer == null) return; ItemStack items = ((Item) event.getCaught()).getItemStack(); Jobs.action(jPlayer, new ItemActionInfo(items, ActionType.FISH)); } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onAnimalTame(EntityTameEvent event) { //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(event.getEntity().getWorld())) return; LivingEntity animal = event.getEntity(); // Entity being tamed must be alive if (animal.isDead()) { return; } // mob spawner, no payment or experience if (animal.hasMetadata(Jobs.getPlayerManager().getMobSpawnerMetadata()) && !Jobs.getGCManager().payNearSpawner()) { animal.removeMetadata(Jobs.getPlayerManager().getMobSpawnerMetadata(), plugin); return; } Player player = (Player) event.getOwner(); if (!player.isOnline()) return; // check if in creative if (!payIfCreative(player)) return; if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; // pay JobsPlayer jDamager = Jobs.getPlayerManager().getJobsPlayer(player); if (jDamager == null) return; if (Jobs.getGCManager().payForStackedEntities && HookManager.isPluginEnabled("WildStacker") && HookManager.getWildStackerHandler().isStackedEntity(animal)) { for (com.bgsoftware.wildstacker.api.objects.StackedEntity stacked : HookManager.getWildStackerHandler().getStackedEntities()) { if (stacked.getType() == animal.getType()) { Jobs.action(jDamager, new EntityActionInfo(stacked.getLivingEntity(), ActionType.TAME)); } } } Jobs.action(jDamager, new EntityActionInfo(animal, ActionType.TAME)); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onInventoryCraft(CraftItemEvent event) { //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(event.getWhoClicked().getWorld())) return; // If event is nothing or place, do nothing switch (event.getAction()) { case NOTHING: case PLACE_ONE: case PLACE_ALL: case PLACE_SOME: return; default: break; } if (event.getSlotType() != SlotType.RESULT) return; ItemStack resultStack = event.getRecipe().getResult(); if (!(event.getWhoClicked() instanceof Player)) return; Player player = (Player) event.getWhoClicked(); //Check if inventory is full and using shift click, possible money dupping fix if (player.getInventory().firstEmpty() == -1 && event.isShiftClick()) { player.sendMessage(Jobs.getLanguage().getMessage("message.crafting.fullinventory")); return; } if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; if (!event.isLeftClick() && !event.isRightClick()) return; // check if in creative if (!payIfCreative(player)) return; // Checking if item is been repaired, not crafted. Combining 2 items ItemStack[] sourceItems = event.getInventory().getContents(); // For dye check List<ItemStack> DyeStack = new ArrayList<>(); int y = -1; CMIMaterial first = null, second = null, third = null; boolean leather = false; boolean shulker = false; for (ItemStack s : sourceItems) { if (s == null) continue; if (CMIMaterial.isDye(s.getType())) DyeStack.add(s); CMIMaterial mat = CMIMaterial.get(s); if (mat != CMIMaterial.NONE && mat != CMIMaterial.AIR) { y++; if (y == 0) first = mat; if (y == 1) second = mat; if (y == 2) third = mat; } switch (mat) { case LEATHER_BOOTS: case LEATHER_CHESTPLATE: case LEATHER_HELMET: case LEATHER_LEGGINGS: case LEATHER_HORSE_ARMOR: leather = true; break; case SHULKER_BOX: case BLACK_SHULKER_BOX: case BLUE_SHULKER_BOX: case BROWN_SHULKER_BOX: case CYAN_SHULKER_BOX: case GRAY_SHULKER_BOX: case GREEN_SHULKER_BOX: case LIGHT_BLUE_SHULKER_BOX: case LIGHT_GRAY_SHULKER_BOX: case LIME_SHULKER_BOX: case MAGENTA_SHULKER_BOX: case ORANGE_SHULKER_BOX: case PINK_SHULKER_BOX: case PURPLE_SHULKER_BOX: case RED_SHULKER_BOX: case WHITE_SHULKER_BOX: case YELLOW_SHULKER_BOX: shulker = true; break; default: break; } } JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player); if (jPlayer == null) return; if (y == 2 && first == second && third == second) { if (Jobs.getGCManager().payForCombiningItems && third == first) { Jobs.action(jPlayer, new ItemActionInfo(event.getCurrentItem(), ActionType.REPAIR)); } else { Jobs.action(jPlayer, new ItemActionInfo(resultStack, ActionType.REPAIR)); } return; } // Check Dyes if (y >= 2 && (third != null && third.isDye() || second != null && second.isDye() || first != null && first.isDye()) && (leather || shulker)) { Jobs.action(jPlayer, new ItemActionInfo(sourceItems[0], ActionType.DYE)); for (ItemStack OneDye : DyeStack) { Jobs.action(jPlayer, new ItemActionInfo(OneDye, ActionType.DYE)); } return; } // If we need to pay only by each craft action we will skip calculation how much was crafted if (!Jobs.getGCManager().PayForEachCraft) { ItemStack currentItem = event.getCurrentItem(); // when we trying to craft tipped arrow effects if (currentItem != null && currentItem.getItemMeta() instanceof PotionMeta) { PotionMeta potion = (PotionMeta) currentItem.getItemMeta(); Jobs.action(jPlayer, new PotionItemActionInfo(currentItem, ActionType.CRAFT, potion.getBasePotionData().getType())); } else if (resultStack.hasItemMeta() && resultStack.getItemMeta().hasDisplayName()) { Jobs.action(jPlayer, new ItemNameActionInfo(CMIChatColor.stripColor(resultStack.getItemMeta() .getDisplayName()), ActionType.CRAFT)); } else if (currentItem != null) { Jobs.action(jPlayer, new ItemActionInfo(currentItem, ActionType.CRAFT)); } return; } // Checking how much player crafted ItemStack toCraft = event.getCurrentItem(); ItemStack toStore = event.getCursor(); // Make sure we are actually crafting anything if (hasItems(toCraft)) if (event.isShiftClick()) schedulePostDetection(player, toCraft.clone(), jPlayer, resultStack.clone(), ActionType.CRAFT); else { // The items are stored in the cursor. Make sure there's enough space. if (isStackSumLegal(toCraft, toStore)) { int newItemsCount = toCraft.getAmount(); while (newItemsCount >= 1) { newItemsCount--; if (resultStack.hasItemMeta() && resultStack.getItemMeta().hasDisplayName()) Jobs.action(jPlayer, new ItemNameActionInfo(CMIChatColor.stripColor(resultStack.getItemMeta().getDisplayName()), ActionType.CRAFT)); else Jobs.action(jPlayer, new ItemActionInfo(resultStack, ActionType.CRAFT)); } } } } // HACK! The API doesn't allow us to easily determine the resulting number of // crafted items, so we're forced to compare the inventory before and after. private void schedulePostDetection(final HumanEntity player, final ItemStack compareItem, final JobsPlayer jPlayer, final ItemStack resultStack, final ActionType type) { final ItemStack[] preInv = player.getInventory().getContents(); // Clone the array. The content may (was for me) be mutable. for (int i = 0; i < preInv.length; i++) { preInv[i] = preInv[i] != null ? preInv[i].clone() : null; } Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { final ItemStack[] postInv = player.getInventory().getContents(); int newItemsCount = 0; for (int i = 0; i < preInv.length; i++) { ItemStack pre = preInv[i]; ItemStack post = postInv[i]; // We're only interested in filled slots that are different if (hasSameItem(compareItem, post) && (hasSameItem(compareItem, pre) || pre == null)) { newItemsCount += post.getAmount() - (pre != null ? pre.getAmount() : 0); } } if (newItemsCount > 0) { while (newItemsCount >= 1) { newItemsCount--; Jobs.action(jPlayer, new ItemActionInfo(resultStack, type)); } } } }, 1); } private static boolean hasItems(ItemStack stack) { return stack != null && stack.getAmount() > 0; } private static boolean hasSameItem(ItemStack a, ItemStack b) { if (a == null) return b == null; else if (b == null) return false; CMIMaterial mat1 = CMIMaterial.get(a), mat2 = CMIMaterial.get(b); return mat1 == mat2 && Jobs.getNms().getDurability(a) == Jobs.getNms().getDurability(b) && Objects.equal(a.getData(), b.getData()) && Objects.equal(a.getEnchantments(), b.getEnchantments()); } private static boolean isStackSumLegal(ItemStack a, ItemStack b) { // See if we can create a new item stack with the combined elements of a and b if (a == null || b == null) return true;// Treat null as an empty stack return a.getAmount() + b.getAmount() <= a.getType().getMaxStackSize(); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onInventoryRepair(InventoryClickEvent event) { //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(event.getWhoClicked().getWorld())) return; // If event is nothing or place, do nothing switch (event.getAction()) { case NOTHING: case PLACE_ONE: case PLACE_ALL: case PLACE_SOME: return; default: break; } Inventory inv = event.getInventory(); // must be anvil inventory if (!(inv instanceof AnvilInventory) && (Version.isCurrentEqualOrHigher(Version.v1_14_R1) && !(inv instanceof GrindstoneInventory) && !(inv instanceof StonecutterInventory))) return; int slot = event.getSlot(); if (event.getSlotType() != SlotType.RESULT || (slot != 2 && slot != 1)) return; if ((Version.isCurrentEqualOrHigher(Version.v1_14_R1) && !(inv instanceof StonecutterInventory)) && slot == 1) return; if (!(event.getWhoClicked() instanceof Player)) return; Player player = (Player) event.getWhoClicked(); //Check if inventory is full and using shift click, possible money dupping fix if (player.getInventory().firstEmpty() == -1 && event.isShiftClick()) { player.sendMessage(Jobs.getLanguage().getMessage("message.crafting.fullinventory")); return; } ItemStack resultStack = event.getCurrentItem(); if (resultStack == null) return; // Checking if this is only item rename ItemStack FirstSlot = null; try { FirstSlot = inv.getItem(0); } catch (NullPointerException e) { return; } if (FirstSlot == null) return; String OriginalName = null; String NewName = null; if (FirstSlot.hasItemMeta()) OriginalName = FirstSlot.getItemMeta().getDisplayName(); if (resultStack.hasItemMeta()) NewName = resultStack.getItemMeta().getDisplayName(); if (OriginalName != null && !OriginalName.equals(NewName) && inv.getItem(1) == null && !Jobs.getGCManager().PayForRenaming) return; // Check for world permissions if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; // check if in creative if (!payIfCreative(player)) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; // Fix for possible money duplication bugs. switch (event.getClick()) { case UNKNOWN: case WINDOW_BORDER_LEFT: case WINDOW_BORDER_RIGHT: case NUMBER_KEY: return; default: break; } // Fix money dupping issue when clicking continuously in the result item, but if in the // cursor have item, then dupping the money, #438 if (event.isLeftClick() && event.getCursor().getType() != Material.AIR) return; JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player); if (jPlayer == null) return; if (Version.isCurrentEqualOrHigher(Version.v1_14_R1) && inv instanceof StonecutterInventory) { Jobs.action(jPlayer, new ItemActionInfo(resultStack, ActionType.CRAFT)); return; } if (Jobs.getGCManager().PayForEnchantingOnAnvil && inv.getItem(1) != null && inv.getItem(1).getType() == Material.ENCHANTED_BOOK) { Map<Enchantment, Integer> enchants = resultStack.getEnchantments(); for (Entry<Enchantment, Integer> oneEnchant : enchants.entrySet()) { Enchantment enchant = oneEnchant.getKey(); if (enchant == null) continue; CMIEnchantment e = CMIEnchantment.get(enchant); String enchantName = e == null ? null : e.toString(); if (enchantName == null) continue; Integer level = oneEnchant.getValue(); if (level == null) continue; Jobs.action(jPlayer, new EnchantActionInfo(enchantName, level, ActionType.ENCHANT)); } } else Jobs.action(jPlayer, new ItemActionInfo(resultStack, ActionType.REPAIR)); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onEnchantItem(EnchantItemEvent event) { if (event.isCancelled()) return; //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(event.getEnchanter().getWorld())) return; Inventory inv = event.getInventory(); if (!(inv instanceof EnchantingInventory)) return; ItemStack resultStack = ((EnchantingInventory) inv).getItem(); if (resultStack == null) return; Player player = event.getEnchanter(); if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; // check if in creative if (!payIfCreative(player)) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; if (!payForItemDurabilityLoss(player)) return; JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player); if (jPlayer == null) return; Map<Enchantment, Integer> enchants = event.getEnchantsToAdd(); for (Entry<Enchantment, Integer> oneEnchant : enchants.entrySet()) { Enchantment enchant = oneEnchant.getKey(); if (enchant == null) continue; CMIEnchantment e = CMIEnchantment.get(enchant); String enchantName = e == null ? null : e.toString(); if (enchantName == null) continue; Integer level = oneEnchant.getValue(); if (level == null) continue; Jobs.action(jPlayer, new EnchantActionInfo(enchantName, level, ActionType.ENCHANT)); } Jobs.action(jPlayer, new ItemActionInfo(resultStack, ActionType.ENCHANT)); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onInventoryMoveItemEventToFurnace(InventoryMoveItemEvent event) { if (!Jobs.getGCManager().PreventHopperFillUps) return; String type = event.getDestination().getType().toString(); if (!type.equalsIgnoreCase("FURNACE") && !type.equalsIgnoreCase("SMOKER") && !type.equalsIgnoreCase("BLAST_FURNACE")) return; if (event.getItem().getType() == Material.AIR) return; Block block = null; switch (type.toLowerCase()) { case "furnace": block = ((Furnace) event.getDestination().getHolder()).getBlock(); break; case "smoker": // This should be done in this way to have backwards compatibility block = ((org.bukkit.block.Smoker) event.getDestination().getHolder()).getBlock(); break; case "blast_furnace": // This should be done in this way to have backwards compatibility block = ((org.bukkit.block.BlastFurnace) event.getDestination().getHolder()).getBlock(); break; default: break; } if (block == null) return; //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(block.getWorld())) return; if (block.hasMetadata(furnaceOwnerMetadata)) FurnaceBrewingHandling.removeFurnace(block); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onInventoryMoveItemEventToBrewingStand(InventoryMoveItemEvent event) { if (event.getDestination().getType() != InventoryType.BREWING) return; if (!Jobs.getGCManager().PreventBrewingStandFillUps) return; if (event.getItem().getType() == Material.AIR) return; BrewingStand stand = (BrewingStand) event.getDestination().getHolder(); //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(stand.getWorld())) return; Block block = stand.getBlock(); if (block.hasMetadata(brewingOwnerMetadata)) FurnaceBrewingHandling.removeBrewing(block); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onFurnaceSmelt(FurnaceSmeltEvent event) { Block block = event.getBlock(); //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(block.getWorld())) return; if (!block.hasMetadata(furnaceOwnerMetadata)) return; List<MetadataValue> data = block.getMetadata(furnaceOwnerMetadata); if (data.isEmpty()) return; // only care about first MetadataValue value = data.get(0); String playerName = value.asString(); UUID uuid = null; try { uuid = UUID.fromString(playerName); } catch (IllegalArgumentException e) { } if (uuid == null) return; Player player = Bukkit.getPlayer(uuid); if (player == null || !player.isOnline()) return; if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player); if (jPlayer == null) return; Jobs.action(jPlayer, new ItemActionInfo(event.getResult(), ActionType.SMELT)); } @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onEntityDamageByPlayer(EntityDamageEvent event) { //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(event.getEntity().getWorld())) return; if (!Jobs.getGCManager().MonsterDamageUse) return; Entity ent = event.getEntity(); if (ent instanceof Player) return; if (!(event instanceof EntityDamageByEntityEvent)) return; EntityDamageByEntityEvent attackevent = (EntityDamageByEntityEvent) event; Entity damager = attackevent.getDamager(); if (!(damager instanceof Player)) return; double damage = event.getFinalDamage(); if (!(ent instanceof Damageable)) return; double s = ((Damageable) ent).getHealth(); if (damage > s) damage = s; if (ent.hasMetadata(entityDamageByPlayer) && !ent.getMetadata(entityDamageByPlayer).isEmpty()) damage += ent.getMetadata(entityDamageByPlayer).get(0).asDouble(); ent.setMetadata(entityDamageByPlayer, new FixedMetadataValue(plugin, damage)); } @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onEntityDamageByProjectile(EntityDamageByEntityEvent event) { //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(event.getEntity().getWorld())) return; Entity ent = event.getEntity(); Entity damager = event.getDamager(); if (ent instanceof org.bukkit.entity.EnderCrystal && damager instanceof Player) { String meta = "enderCrystalDamage"; if (ent.hasMetadata(meta)) ent.removeMetadata(meta, plugin); ent.setMetadata(meta, new FixedMetadataValue(plugin, ent)); return; } if (!(damager instanceof Projectile) || !(ent instanceof Damageable)) return; Projectile projectile = (Projectile) damager; ProjectileSource shooter = projectile.getShooter(); double damage = event.getFinalDamage(); double s = ((Damageable) ent).getHealth(); if (damage > s) damage = s; if (shooter instanceof Player) { if (ent.hasMetadata(entityDamageByPlayer) && !ent.getMetadata(entityDamageByPlayer).isEmpty()) damage += ent.getMetadata(entityDamageByPlayer).get(0).asDouble(); ent.setMetadata(entityDamageByPlayer, new FixedMetadataValue(plugin, damage)); } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onEntityDeath(EntityDeathEvent event) { //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(event.getEntity().getWorld())) return; if (!(event.getEntity().getLastDamageCause() instanceof EntityDamageByEntityEvent)) return; EntityDamageByEntityEvent e = (EntityDamageByEntityEvent) event.getEntity().getLastDamageCause(); // Entity that died must be living if (!(e.getEntity() instanceof LivingEntity)) return; LivingEntity lVictim = (LivingEntity) e.getEntity(); //extra check for Citizens 2 sentry kills if (e.getDamager() instanceof Player && e.getDamager().hasMetadata("NPC")) return; if (Jobs.getGCManager().MythicMobsEnabled && HookManager.getMythicManager() != null && HookManager.getMythicManager().isMythicMob(lVictim)) { return; } // mob spawner, no payment or experience if (lVictim.hasMetadata(Jobs.getPlayerManager().getMobSpawnerMetadata()) && !Jobs.getGCManager().payNearSpawner()) { try { // So lets remove meta in case some plugin removes entity in wrong way. lVictim.removeMetadata(Jobs.getPlayerManager().getMobSpawnerMetadata(), plugin); } catch (Exception t) { } return; } Player pDamager = null; // Checking if killer is player if (e.getDamager() instanceof Player) { pDamager = (Player) e.getDamager(); // Checking if killer is MyPet animal } else if (HookManager.getMyPetManager() != null && HookManager.getMyPetManager().isMyPet(e.getDamager(), null)) { UUID uuid = HookManager.getMyPetManager().getOwnerOfPet(e.getDamager()); if (uuid != null) pDamager = Bukkit.getPlayer(uuid); // Checking if killer is tamed animal } else if (e.getDamager() instanceof Tameable) { Tameable t = (Tameable) e.getDamager(); if (t.isTamed() && t.getOwner() instanceof Player) pDamager = (Player) t.getOwner(); } else if (e.getDamager() instanceof Projectile) { Projectile pr = (Projectile) e.getDamager(); if (pr.getShooter() instanceof Player) pDamager = (Player) pr.getShooter(); } if (pDamager == null) return; // check if in creative if (!payIfCreative(pDamager)) return; if (!Jobs.getPermissionHandler().hasWorldPermission(pDamager, pDamager.getLocation().getWorld().getName())) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && pDamager.isInsideVehicle()) return; if (!payForItemDurabilityLoss(pDamager)) return; // pay JobsPlayer jDamager = Jobs.getPlayerManager().getJobsPlayer(pDamager); if (jDamager == null) return; if (lVictim instanceof Player && !lVictim.hasMetadata("NPC")) { Player VPlayer = (Player) lVictim; if (jDamager.getName().equalsIgnoreCase(VPlayer.getName())) return; } if (Jobs.getGCManager().MonsterDamageUse && lVictim.hasMetadata(entityDamageByPlayer) && !lVictim.getMetadata(entityDamageByPlayer).isEmpty()) { double damage = lVictim.getMetadata(entityDamageByPlayer).get(0).asDouble(); double perc = (damage * 100D) / Jobs.getNms().getMaxHealth(lVictim); if (perc < Jobs.getGCManager().MonsterDamagePercentage) return; } if (Jobs.getGCManager().payForStackedEntities && HookManager.isPluginEnabled("WildStacker") && HookManager.getWildStackerHandler().isStackedEntity(lVictim)) { for (com.bgsoftware.wildstacker.api.objects.StackedEntity stacked : HookManager.getWildStackerHandler().getStackedEntities()) { if (stacked.getType() == lVictim.getType()) { Jobs.action(jDamager, new EntityActionInfo(stacked.getLivingEntity(), ActionType.KILL), e.getDamager(), stacked.getLivingEntity()); } } } Jobs.action(jDamager, new EntityActionInfo(lVictim, ActionType.KILL), e.getDamager(), lVictim); // Payment for killing player with particular job, except NPC's if (lVictim instanceof Player && !lVictim.hasMetadata("NPC")) { JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer((Player) lVictim); if (jPlayer == null) return; for (JobProgression job : jPlayer.getJobProgression()) { Jobs.action(jDamager, new CustomKillInfo(job.getJob().getName(), ActionType.CUSTOMKILL), pDamager, lVictim); } } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onCreatureSpawn(CreatureSpawnEvent event) { //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(event.getEntity().getWorld())) return; if (event.getSpawnReason() == SpawnReason.SPAWNER || event.getSpawnReason() == SpawnReason.SPAWNER_EGG) { LivingEntity creature = event.getEntity(); creature.setMetadata(Jobs.getPlayerManager().getMobSpawnerMetadata(), new FixedMetadataValue(plugin, true)); } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onHangingPlaceEvent(HangingPlaceEvent event) { //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(event.getEntity().getWorld())) return; Player player = event.getPlayer(); if (player == null || !player.isOnline()) return; // check if in creative if (!payIfCreative(player)) return; if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player); if (jPlayer == null) return; Jobs.action(jPlayer, new EntityActionInfo(event.getEntity(), ActionType.PLACE)); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onHangingBreakEvent(HangingBreakByEntityEvent event) { //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(event.getEntity().getWorld())) return; if (!(event.getRemover() instanceof Player)) return; Player player = (Player) event.getRemover(); if (!player.isOnline()) return; // check if in creative if (!payIfCreative(player)) return; if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player); if (jPlayer == null) return; Jobs.action(jPlayer, new EntityActionInfo(event.getEntity(), ActionType.BREAK)); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onArmorstandPlace(CreatureSpawnEvent event) { Entity ent = event.getEntity(); if (!ent.getType().toString().equalsIgnoreCase("ARMOR_STAND")) return; Location loc = event.getLocation(); java.util.Collection<Entity> ents = Version.isCurrentEqualOrLower(Version.v1_8_R1) || loc.getWorld() == null ? null : loc.getWorld().getNearbyEntities(loc, 4, 4, 4); if (ents == null) { return; } double dis = Double.MAX_VALUE; Player player = null; for (Entity one : ents) { if (!(one instanceof Player)) continue; Player p = (Player) one; if (!Jobs.getNms().getItemInMainHand(p).getType().toString().equalsIgnoreCase("ARMOR_STAND")) continue; double d = p.getLocation().distance(loc); if (d < dis) { dis = d; player = p; } } if (player == null || !player.isOnline()) return; // check if in creative if (!payIfCreative(player)) return; if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player); if (jPlayer == null) return; Jobs.action(jPlayer, new EntityActionInfo(ent, ActionType.PLACE)); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onArmorstandBreak(EntityDeathEvent event) { Entity ent = event.getEntity(); if (!ent.getType().toString().equalsIgnoreCase("ARMOR_STAND")) return; if (!(event.getEntity().getLastDamageCause() instanceof EntityDamageByEntityEvent)) return; EntityDamageByEntityEvent e = (EntityDamageByEntityEvent) event.getEntity().getLastDamageCause(); //extra check for Citizens 2 sentry kills if (!(e.getDamager() instanceof Player)) return; if (e.getDamager().hasMetadata("NPC")) return; Player pDamager = (Player) e.getDamager(); // check if in creative if (!payIfCreative(pDamager)) return; if (!Jobs.getPermissionHandler().hasWorldPermission(pDamager, pDamager.getLocation().getWorld().getName())) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && pDamager.isInsideVehicle()) return; // pay JobsPlayer jDamager = Jobs.getPlayerManager().getJobsPlayer(pDamager); if (jDamager == null) return; Jobs.action(jDamager, new EntityActionInfo(ent, ActionType.BREAK), e.getDamager()); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onCreatureSpawn(SlimeSplitEvent event) { //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(event.getEntity().getWorld())) return; if (!event.getEntity().hasMetadata(Jobs.getPlayerManager().getMobSpawnerMetadata())) return; EntityType type = event.getEntityType(); if (type == EntityType.SLIME && Jobs.getGCManager().PreventSlimeSplit) { event.setCancelled(true); return; } if (type == EntityType.MAGMA_CUBE && Jobs.getGCManager().PreventMagmaCubeSplit) { event.setCancelled(true); } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onCreatureBreed(CreatureSpawnEvent event) { //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(event.getEntity().getWorld())) return; if (!Jobs.getGCManager().useBreederFinder) return; SpawnReason reason = event.getSpawnReason(); if (!reason.toString().equalsIgnoreCase("BREEDING") && !reason.toString().equalsIgnoreCase("EGG")) return; LivingEntity animal = event.getEntity(); double closest = 30.0; Player player = null; for (Player i : Bukkit.getOnlinePlayers()) { if (!i.getWorld().getName().equals(animal.getWorld().getName())) continue; double dist = i.getLocation().distance(animal.getLocation()); if (closest > dist) { closest = dist; player = i; } } if (player != null && closest < 30.0) { // check if in creative if (!payIfCreative(player)) return; if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; // pay JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player); if (jPlayer == null) return; Jobs.action(jPlayer, new EntityActionInfo(animal, ActionType.BREED)); } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerEat(FoodLevelChangeEvent event) { //disabling plugin in world if (!Jobs.getGCManager().canPerformActionInWorld(event.getEntity().getWorld())) return; if (!(event.getEntity() instanceof Player) || event.getEntity().hasMetadata("NPC") || event.getFoodLevel() <= ((Player) event.getEntity()).getFoodLevel()) return; Player player = (Player) event.getEntity(); if (!player.isOnline()) return; // check if in creative if (!payIfCreative(player)) return; if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player); if (jPlayer == null) return; // Item in hand ItemStack item = Jobs.getNms().getItemInMainHand(player); Jobs.action(jPlayer, new ItemActionInfo(item, ActionType.EAT)); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onTntExplode(EntityExplodeEvent event) { Entity e = event.getEntity(); if (!Jobs.getGCManager().canPerformActionInWorld(e)) return; EntityType type = event.getEntityType(); if (type != EntityType.PRIMED_TNT && type != EntityType.MINECART_TNT && type != CMIEntityType.ENDER_CRYSTAL.getType()) return; if (!Jobs.getGCManager().isUseTntFinder() && type != CMIEntityType.ENDER_CRYSTAL.getType()) return; double closest = 60.0; Player player = null; Location loc = e.getLocation(); for (Player i : Bukkit.getOnlinePlayers()) { if (loc.getWorld() != i.getWorld()) continue; double dist = i.getLocation().distance(loc); if (closest > dist) { closest = dist; player = i; } } if (player == null || closest == 60.0 || !player.isOnline()) return; // check if in creative if (!payIfCreative(player) || !Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player); if (jPlayer == null) return; if (!Jobs.getGCManager().isUseTntFinder() && type == CMIEntityType.ENDER_CRYSTAL.getType()) { String meta = "enderCrystalDamage"; if (type == CMIEntityType.ENDER_CRYSTAL.getType() && e.hasMetadata(meta) && !e.getMetadata(meta).isEmpty()) { Entity killed = (Entity) e.getMetadata(meta).get(0).value(); if (killed != null) { Jobs.action(jPlayer, new EntityActionInfo(killed, ActionType.KILL)); killed.removeMetadata(meta, plugin); return; } } } for (Block block : event.blockList()) { if (block == null) continue; CMIMaterial cmat = CMIMaterial.get(block); if (cmat == CMIMaterial.FURNACE || cmat == CMIMaterial.SMOKER || cmat == CMIMaterial.BLAST_FURNACE && block.hasMetadata(furnaceOwnerMetadata)) FurnaceBrewingHandling.removeFurnace(block); else if (cmat == CMIMaterial.BREWING_STAND || cmat == CMIMaterial.LEGACY_BREWING_STAND && block.hasMetadata(brewingOwnerMetadata)) FurnaceBrewingHandling.removeBrewing(block); if (Jobs.getGCManager().useBlockProtection && block.getState().hasMetadata(BlockMetadata)) return; BlockActionInfo bInfo = new BlockActionInfo(block, ActionType.TNTBREAK); Jobs.action(jPlayer, bInfo, block); } } @EventHandler(priority = EventPriority.MONITOR) public void onPlayerInteract(PlayerInteractEvent event) { Player p = event.getPlayer(); if (!Jobs.getGCManager().canPerformActionInWorld(p.getWorld())) return; final Block block = event.getClickedBlock(); if (block == null) return; CMIMaterial cmat = CMIMaterial.get(block); final JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(p); Material hand = Jobs.getNms().getItemInMainHand(p).getType(); if (Version.isCurrentEqualOrHigher(Version.v1_14_R1) && event.useInteractedBlock() != org.bukkit.event.Event.Result.DENY && event.getAction() == Action.RIGHT_CLICK_BLOCK && jPlayer != null && !p.isSneaking()) { if (cmat == CMIMaterial.COMPOSTER) { org.bukkit.block.data.Levelled level = (org.bukkit.block.data.Levelled) block.getBlockData(); if (level.getLevel() == level.getMaximumLevel()) { Jobs.action(jPlayer, new BlockActionInfo(block, ActionType.COLLECT), block); } } if (cmat == CMIMaterial.SWEET_BERRY_BUSH && hand != CMIMaterial.BONE_MEAL.getMaterial()) { Ageable age = (Ageable) block.getBlockData(); Jobs.action(jPlayer, new BlockCollectInfo(block, ActionType.COLLECT, age.getAge()), block); } } if (Version.isCurrentEqualOrHigher(Version.v1_15_R1) && event.useInteractedBlock() != org.bukkit.event.Event.Result.DENY && event.getAction() == Action.RIGHT_CLICK_BLOCK && !p.isSneaking() && jPlayer != null && (cmat == CMIMaterial.BEEHIVE || cmat == CMIMaterial.BEE_NEST)) { org.bukkit.block.data.type.Beehive beehive = (org.bukkit.block.data.type.Beehive) block.getBlockData(); if (beehive.getHoneyLevel() == beehive.getMaximumHoneyLevel() && (hand == CMIMaterial.SHEARS.getMaterial() || hand == CMIMaterial.GLASS_BOTTLE.getMaterial())) { Jobs.action(jPlayer, new BlockCollectInfo(block, ActionType.COLLECT, beehive.getHoneyLevel()), block); } } if (cmat == CMIMaterial.FURNACE || cmat == CMIMaterial.LEGACY_BURNING_FURNACE || cmat == CMIMaterial.SMOKER || cmat == CMIMaterial.BLAST_FURNACE) { ownershipFeedback done = FurnaceBrewingHandling.registerFurnaces(p, block); if (done == ownershipFeedback.tooMany) { boolean report = false; if (block.hasMetadata(furnaceOwnerMetadata)) { List<MetadataValue> data = block.getMetadata(furnaceOwnerMetadata); if (data.isEmpty()) return; // only care about first MetadataValue value = data.get(0); String uuid = value.asString(); if (!uuid.equals(p.getUniqueId().toString())) report = true; } else report = true; if (report) ActionBarManager.send(p, Jobs.getLanguage().getMessage("general.error.noFurnaceRegistration")); } else if (done == ownershipFeedback.newReg && jPlayer != null) { ActionBarManager.send(p, Jobs.getLanguage().getMessage("general.error.newFurnaceRegistration", "[current]", jPlayer.getFurnaceCount(), "[max]", jPlayer.getMaxFurnacesAllowed(cmat) == 0 ? "-" : jPlayer.getMaxFurnacesAllowed(cmat))); } } else if (cmat == CMIMaterial.BREWING_STAND || cmat == CMIMaterial.LEGACY_BREWING_STAND) { ownershipFeedback done = FurnaceBrewingHandling.registerBrewingStand(p, block); if (done == ownershipFeedback.tooMany) { boolean report = false; if (block.hasMetadata(brewingOwnerMetadata)) { List<MetadataValue> data = block.getMetadata(brewingOwnerMetadata); if (data.isEmpty()) return; // only care about first MetadataValue value = data.get(0); String uuid = value.asString(); if (!uuid.equals(p.getUniqueId().toString())) report = true; } else report = true; if (report) ActionBarManager.send(p, Jobs.getLanguage().getMessage("general.error.noBrewingRegistration")); } else if (done == ownershipFeedback.newReg && jPlayer != null) { ActionBarManager.send(p, Jobs.getLanguage().getMessage("general.error.newBrewingRegistration", "[current]", jPlayer.getBrewingStandCount(), "[max]", jPlayer.getMaxBrewingStandsAllowed() == 0 ? "-" : jPlayer.getMaxBrewingStandsAllowed())); } } else if (Version.isCurrentEqualOrHigher(Version.v1_13_R1) && block.getType().toString().startsWith("STRIPPED_") && event.getAction() == Action.RIGHT_CLICK_BLOCK) { ItemStack iih = Jobs.getNms().getItemInMainHand(p); if (iih.getType().toString().endsWith("_AXE")) { // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && p.isInsideVehicle()) return; // Prevent item durability loss if (!Jobs.getGCManager().payItemDurabilityLoss && iih.getType().getMaxDurability() - Jobs.getNms().getDurability(iih) != iih.getType().getMaxDurability()) return; Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> { if (jPlayer != null) Jobs.action(jPlayer, new BlockActionInfo(block, ActionType.STRIPLOGS), block); }, 1); } } } @EventHandler public void onExplore(JobsChunkChangeEvent event) { if (event.isCancelled()) return; Player player = event.getPlayer(); //disabling plugin in world if (player == null || !player.isOnline() || !Jobs.getGCManager().canPerformActionInWorld(player.getWorld())) return; if (!Jobs.getExplore().isExploreEnabled()) return; // check if in spectator, #330 if (player.getGameMode().toString().equals("SPECTATOR")) return; if (!Jobs.getGCManager().payExploringWhenFlying() && player.isFlying()) return; // check if player is riding if (Jobs.getGCManager().disablePaymentIfRiding && player.isInsideVehicle()) return; if (Jobs.getVersionCheckManager().getVersion().isEqualOrHigher(Version.v1_9_R2) && !Jobs.getGCManager().payExploringWhenGliding && player.isGliding()) return; // check if in creative if (!payIfCreative(player)) return; if (!Jobs.getPermissionHandler().hasWorldPermission(player, player.getLocation().getWorld().getName())) return; JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player); if (jPlayer == null) return; ExploreRespond respond = Jobs.getExplore().ChunkRespond(jPlayer.getUserId(), event.getNewChunk()); if (!respond.isNewChunk()) return; Jobs.action(jPlayer, new ExploreActionInfo(String.valueOf(respond.getCount()), ActionType.EXPLORE)); } public static boolean payIfCreative(Player player) { if (player.getGameMode() == GameMode.CREATIVE && !Jobs.getGCManager().payInCreative() && !player.hasPermission("jobs.paycreative")) return false; return true; } // Prevent item durability loss public static boolean payForItemDurabilityLoss(Player p) { if (Jobs.getGCManager().payItemDurabilityLoss) return true; ItemStack hand = Jobs.getNms().getItemInMainHand(p); CMIMaterial cmat = CMIMaterial.get(hand); HashMap<Enchantment, Integer> got = Jobs.getGCManager().whiteListedItems.get(cmat); if (got == null) return false; if (Jobs.getNms().getDurability(hand) == 0) return true; for (Entry<Enchantment, Integer> oneG : got.entrySet()) { if (!hand.getEnchantments().containsKey(oneG.getKey()) || hand.getEnchantments().get(oneG.getKey()).equals(oneG.getValue())) return false; } return true; } }
fix for #940 (stripping logs are respected as block place actions)
src/main/java/com/gamingmesh/jobs/listeners/JobsPaymentListener.java
fix for #940 (stripping logs are respected as block place actions)
Java
apache-2.0
7fa78d8397901f0e207846893bc74a6fb56efef1
0
mapsme/omim,goblinr/omim,trashkalmar/omim,ygorshenin/omim,Transtech/omim,VladiMihaylenko/omim,Zverik/omim,milchakov/omim,Transtech/omim,darina/omim,ygorshenin/omim,mpimenov/omim,matsprea/omim,bykoianko/omim,rokuz/omim,mapsme/omim,darina/omim,dobriy-eeh/omim,VladiMihaylenko/omim,VladiMihaylenko/omim,Transtech/omim,dobriy-eeh/omim,mgsergio/omim,trashkalmar/omim,ygorshenin/omim,goblinr/omim,milchakov/omim,matsprea/omim,rokuz/omim,mpimenov/omim,trashkalmar/omim,mapsme/omim,milchakov/omim,bykoianko/omim,VladiMihaylenko/omim,bykoianko/omim,darina/omim,VladiMihaylenko/omim,VladiMihaylenko/omim,mgsergio/omim,mapsme/omim,goblinr/omim,bykoianko/omim,alexzatsepin/omim,milchakov/omim,dobriy-eeh/omim,goblinr/omim,rokuz/omim,rokuz/omim,mpimenov/omim,darina/omim,mgsergio/omim,darina/omim,syershov/omim,ygorshenin/omim,bykoianko/omim,mgsergio/omim,matsprea/omim,VladiMihaylenko/omim,mapsme/omim,trashkalmar/omim,goblinr/omim,ygorshenin/omim,syershov/omim,goblinr/omim,darina/omim,syershov/omim,VladiMihaylenko/omim,dobriy-eeh/omim,Transtech/omim,dobriy-eeh/omim,Zverik/omim,darina/omim,VladiMihaylenko/omim,alexzatsepin/omim,rokuz/omim,milchakov/omim,matsprea/omim,Transtech/omim,alexzatsepin/omim,milchakov/omim,dobriy-eeh/omim,rokuz/omim,alexzatsepin/omim,mgsergio/omim,goblinr/omim,matsprea/omim,Zverik/omim,Transtech/omim,Transtech/omim,bykoianko/omim,syershov/omim,mpimenov/omim,trashkalmar/omim,milchakov/omim,syershov/omim,alexzatsepin/omim,dobriy-eeh/omim,Zverik/omim,dobriy-eeh/omim,darina/omim,Zverik/omim,VladiMihaylenko/omim,dobriy-eeh/omim,Zverik/omim,syershov/omim,Transtech/omim,ygorshenin/omim,goblinr/omim,mpimenov/omim,mpimenov/omim,trashkalmar/omim,mgsergio/omim,mapsme/omim,ygorshenin/omim,bykoianko/omim,mgsergio/omim,goblinr/omim,goblinr/omim,mpimenov/omim,milchakov/omim,mapsme/omim,trashkalmar/omim,trashkalmar/omim,mgsergio/omim,matsprea/omim,Zverik/omim,Transtech/omim,matsprea/omim,alexzatsepin/omim,syershov/omim,rokuz/omim,trashkalmar/omim,dobriy-eeh/omim,ygorshenin/omim,alexzatsepin/omim,rokuz/omim,darina/omim,alexzatsepin/omim,milchakov/omim,mpimenov/omim,goblinr/omim,mapsme/omim,milchakov/omim,bykoianko/omim,Transtech/omim,goblinr/omim,syershov/omim,Zverik/omim,matsprea/omim,Zverik/omim,ygorshenin/omim,bykoianko/omim,rokuz/omim,bykoianko/omim,mgsergio/omim,VladiMihaylenko/omim,mpimenov/omim,milchakov/omim,mapsme/omim,mapsme/omim,mgsergio/omim,bykoianko/omim,goblinr/omim,mpimenov/omim,rokuz/omim,syershov/omim,ygorshenin/omim,mpimenov/omim,darina/omim,darina/omim,mgsergio/omim,mapsme/omim,syershov/omim,alexzatsepin/omim,trashkalmar/omim,dobriy-eeh/omim,Transtech/omim,Zverik/omim,rokuz/omim,syershov/omim,Zverik/omim,ygorshenin/omim,matsprea/omim,dobriy-eeh/omim,trashkalmar/omim,alexzatsepin/omim,milchakov/omim,darina/omim,Transtech/omim,Zverik/omim,mpimenov/omim,darina/omim,mgsergio/omim,rokuz/omim,Zverik/omim,syershov/omim,mapsme/omim,syershov/omim,bykoianko/omim,rokuz/omim,VladiMihaylenko/omim,dobriy-eeh/omim,alexzatsepin/omim,alexzatsepin/omim,alexzatsepin/omim,mpimenov/omim,ygorshenin/omim,matsprea/omim,mapsme/omim,VladiMihaylenko/omim,bykoianko/omim,milchakov/omim,trashkalmar/omim
package com.mapswithme.maps.widget.placepage; import android.animation.Animator; import android.animation.ValueAnimator; import android.content.res.Resources; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.resource.drawable.GlideDrawable; import com.bumptech.glide.request.RequestListener; import com.bumptech.glide.request.target.Target; import com.mapswithme.maps.MwmApplication; import com.mapswithme.maps.R; import com.mapswithme.maps.bookmarks.data.Banner; import com.mapswithme.util.ConnectionState; import com.mapswithme.util.UiUtils; import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT; import static com.mapswithme.util.SharedPropertiesUtils.isShowcaseSwitchedOnLocal; final class BannerController implements View.OnClickListener { private static final int DURATION_DEFAULT = MwmApplication.get().getResources().getInteger(R.integer.anim_default); @Nullable private Banner mBanner; @Nullable private OnBannerClickListener mListener; @NonNull private final View mFrame; @Nullable private final ImageView mIcon; @Nullable private final TextView mTitle; @Nullable private final TextView mMessage; @Nullable private final View mAdMarker; private final float mCloseFrameHeight; private final float mCloseIconSize; private final float mOpenIconSize; private final float mMarginBase; private final float mMarginHalfPlus; @NonNull private final Resources mResources; private boolean mIsOpened = false; @Nullable private ValueAnimator mIconAnimator; BannerController(@NonNull View bannerView, @Nullable OnBannerClickListener listener) { mFrame = bannerView; mListener = listener; mResources = mFrame.getResources(); mCloseFrameHeight = mResources.getDimension(R.dimen.placepage_banner_height); mCloseIconSize = mResources.getDimension(R.dimen.placepage_banner_icon_size); mOpenIconSize = mResources.getDimension(R.dimen.placepage_banner_icon_size_full); mMarginBase = mResources.getDimension(R.dimen.margin_base); mMarginHalfPlus = mResources.getDimension(R.dimen.margin_half_plus); mIcon = (ImageView) bannerView.findViewById(R.id.iv__banner_icon); mTitle = (TextView) bannerView.findViewById(R.id.tv__banner_title); mMessage = (TextView) bannerView.findViewById(R.id.tv__banner_message); mAdMarker = bannerView.findViewById(R.id.tv__banner); } void updateData(@Nullable Banner banner) { mBanner = banner; boolean showBanner = banner != null && ConnectionState.isConnected() && isShowcaseSwitchedOnLocal(); UiUtils.showIf(showBanner, mFrame); if (!showBanner) return; loadIcon(banner); if (mTitle != null) { String title = mResources.getString(mResources.getIdentifier(banner.getTitle(), "string", mFrame.getContext().getPackageName())); if (!TextUtils.isEmpty(title)) mTitle.setText(title); } if (mMessage != null) { String message = mResources.getString(mResources.getIdentifier(banner.getMessage(), "string", mFrame.getContext().getPackageName())); if (!TextUtils.isEmpty(message)) mMessage.setText(message); } if (UiUtils.isLandscape(mFrame.getContext())) open(); } boolean isShowing() { return !UiUtils.isHidden(mFrame); } void open() { if (!isShowing() || mBanner == null || mIsOpened) return; mIsOpened = true; setFrameHeight(WRAP_CONTENT); setIconParams(mOpenIconSize, 0, mMarginBase, new Runnable() { @Override public void run() { loadIcon(mBanner); } }); UiUtils.show(mMessage, mAdMarker); if (mTitle != null) mTitle.setMaxLines(2); mFrame.setOnClickListener(this); } void close() { if (!isShowing() || mBanner == null || !mIsOpened) return; mIsOpened = false; setFrameHeight((int) mCloseFrameHeight); setIconParams(mCloseIconSize, mMarginBase, mMarginHalfPlus, new Runnable() { @Override public void run() { loadIcon(mBanner); } }); UiUtils.hide(mMessage, mAdMarker); if (mTitle != null) mTitle.setMaxLines(1); mFrame.setOnClickListener(null); } private void setFrameHeight(int height) { ViewGroup.LayoutParams lp = mFrame.getLayoutParams(); lp.height = height; mFrame.setLayoutParams(lp); } private void setIconParams(final float size, final float marginRight, final float marginTop, final @Nullable Runnable listener) { if (mIcon == null || UiUtils.isHidden(mIcon)) { if (listener != null) listener.run(); return; } if (mIconAnimator != null) mIconAnimator.cancel(); final ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) mIcon.getLayoutParams(); final float startSize = lp.height; final float startRight = lp.rightMargin; final float startTop = lp.topMargin; mIconAnimator = ValueAnimator.ofFloat(0.0f, 1.0f); if (mIconAnimator == null) { if (listener != null) listener.run(); return; } mIconAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float t = (float) animation.getAnimatedValue(); int newSize = (int) (startSize + t * (size - startSize)); lp.height = newSize; lp.width = newSize; lp.rightMargin = (int) (startRight + t * (marginRight - startRight)); lp.topMargin = (int) (startTop + t * (marginTop - startTop)); mIcon.setLayoutParams(lp); } }); mIconAnimator.addListener(new UiUtils.SimpleAnimatorListener() { @Override public void onAnimationEnd(Animator animation) { if (listener != null) listener.run(); } }); mIconAnimator.setDuration(DURATION_DEFAULT); mIconAnimator.start(); } private void loadIcon(@NonNull Banner banner) { if (mIcon == null) return; if (TextUtils.isEmpty(banner.getIconUrl())) { UiUtils.hide(mIcon); return; } Glide.with(mIcon.getContext()) .load(banner.getIconUrl()) .centerCrop() .listener(new RequestListener<String, GlideDrawable>() { @Override public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) { UiUtils.hide(mIcon); return false; } @Override public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) { UiUtils.show(mIcon); return false; } }) .into(mIcon); } @Override public void onClick(View v) { if (mListener != null && mBanner != null) mListener.onBannerClick(mBanner); } interface OnBannerClickListener { void onBannerClick(@NonNull Banner banner); } }
android/src/com/mapswithme/maps/widget/placepage/BannerController.java
package com.mapswithme.maps.widget.placepage; import android.animation.Animator; import android.animation.ValueAnimator; import android.content.res.Resources; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.resource.drawable.GlideDrawable; import com.bumptech.glide.request.RequestListener; import com.bumptech.glide.request.target.Target; import com.mapswithme.maps.MwmApplication; import com.mapswithme.maps.R; import com.mapswithme.maps.bookmarks.data.Banner; import com.mapswithme.util.ConnectionState; import com.mapswithme.util.UiUtils; import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT; import static com.mapswithme.util.SharedPropertiesUtils.isShowcaseSwitchedOnLocal; final class BannerController implements View.OnClickListener { private static final int DURATION_DEFAULT = MwmApplication.get().getResources().getInteger(R.integer.anim_default); @Nullable private Banner mBanner; @Nullable private OnBannerClickListener mListener; @NonNull private final View mFrame; @Nullable private final ImageView mIcon; @Nullable private final TextView mTitle; @Nullable private final TextView mMessage; @Nullable private final View mAdMarker; private final float mCloseFrameHeight; private final float mCloseIconSize; private final float mOpenIconSize; private final float mMarginBase; private final float mMarginHalfPlus; @NonNull private final Resources mResources; private boolean mIsOpened = false; @Nullable private ValueAnimator mIconAnimator; BannerController(@NonNull View bannerView, @Nullable OnBannerClickListener listener) { mFrame = bannerView; mListener = listener; mResources = mFrame.getResources(); mCloseFrameHeight = mResources.getDimension(R.dimen.placepage_banner_height); mCloseIconSize = mResources.getDimension(R.dimen.placepage_banner_icon_size); mOpenIconSize = mResources.getDimension(R.dimen.placepage_banner_icon_size_full); mMarginBase = mResources.getDimension(R.dimen.margin_base); mMarginHalfPlus = mResources.getDimension(R.dimen.margin_half_plus); mIcon = (ImageView) bannerView.findViewById(R.id.iv__banner_icon); mTitle = (TextView) bannerView.findViewById(R.id.tv__banner_title); mMessage = (TextView) bannerView.findViewById(R.id.tv__banner_message); mAdMarker = bannerView.findViewById(R.id.tv__banner); } void updateData(@Nullable Banner banner) { mBanner = banner; boolean showBanner = banner != null && ConnectionState.isConnected() && isShowcaseSwitchedOnLocal(); UiUtils.showIf(showBanner, mFrame); if (!showBanner) return; if (TextUtils.isEmpty(mBanner.getIconUrl())) UiUtils.hide(mIcon); else loadIcon(banner); if (mTitle != null) { String title = mResources.getString(mResources.getIdentifier(banner.getTitle(), "string", mFrame.getContext().getPackageName())); if (!TextUtils.isEmpty(title)) mTitle.setText(title); } if (mMessage != null) { String message = mResources.getString(mResources.getIdentifier(banner.getMessage(), "string", mFrame.getContext().getPackageName())); if (!TextUtils.isEmpty(message)) mMessage.setText(message); } if (UiUtils.isLandscape(mFrame.getContext())) open(); } boolean isShowing() { return !UiUtils.isHidden(mFrame); } void open() { if (!isShowing() || mBanner == null || mIsOpened) return; mIsOpened = true; setFrameHeight(WRAP_CONTENT); setIconParams(mOpenIconSize, 0, mMarginBase, new Runnable() { @Override public void run() { loadIcon(mBanner); } }); UiUtils.show(mMessage, mAdMarker); if (mTitle != null) mTitle.setMaxLines(2); mFrame.setOnClickListener(this); } void close() { if (!isShowing() || mBanner == null || !mIsOpened) return; mIsOpened = false; setFrameHeight((int) mCloseFrameHeight); setIconParams(mCloseIconSize, mMarginBase, mMarginHalfPlus, new Runnable() { @Override public void run() { loadIcon(mBanner); } }); UiUtils.hide(mMessage, mAdMarker); if (mTitle != null) mTitle.setMaxLines(1); mFrame.setOnClickListener(null); } private void setFrameHeight(int height) { ViewGroup.LayoutParams lp = mFrame.getLayoutParams(); lp.height = height; mFrame.setLayoutParams(lp); } private void setIconParams(final float size, final float marginRight, final float marginTop, final @Nullable Runnable listener) { if (mIcon == null || UiUtils.isHidden(mIcon)) { if (listener != null) listener.run(); return; } if (mIconAnimator != null) mIconAnimator.cancel(); final ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) mIcon.getLayoutParams(); final float startSize = lp.height; final float startRight = lp.rightMargin; final float startTop = lp.topMargin; mIconAnimator = ValueAnimator.ofFloat(0.0f, 1.0f); if (mIconAnimator == null) { if (listener != null) listener.run(); return; } mIconAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float t = (float) animation.getAnimatedValue(); int newSize = (int) (startSize + t * (size - startSize)); lp.height = newSize; lp.width = newSize; lp.rightMargin = (int) (startRight + t * (marginRight - startRight)); lp.topMargin = (int) (startTop + t * (marginTop - startTop)); mIcon.setLayoutParams(lp); } }); mIconAnimator.addListener(new UiUtils.SimpleAnimatorListener() { @Override public void onAnimationEnd(Animator animation) { if (listener != null) listener.run(); } }); mIconAnimator.setDuration(DURATION_DEFAULT); mIconAnimator.start(); } private void loadIcon(@NonNull Banner banner) { if (mIcon == null) return; if (TextUtils.isEmpty(banner.getIconUrl())) { UiUtils.hide(mIcon); return; } Glide.with(mIcon.getContext()) .load(banner.getIconUrl()) .centerCrop() .listener(new RequestListener<String, GlideDrawable>() { @Override public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) { UiUtils.hide(mIcon); return false; } @Override public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) { UiUtils.show(mIcon); return false; } }) .into(mIcon); } @Override public void onClick(View v) { if (mListener != null && mBanner != null) mListener.onBannerClick(mBanner); } interface OnBannerClickListener { void onBannerClick(@NonNull Banner banner); } }
[android] Review fixes.
android/src/com/mapswithme/maps/widget/placepage/BannerController.java
[android] Review fixes.
Java
apache-2.0
8734a1bcb68a9ed2d807e409c049607e473f742a
0
Altiscale/transfer-accelerator
/** * Copyright Altiscale 2014 * Author: Zoran Dimitrijevic <zoran@altiscale.com> * * TcpTunnel is a class to handle data transfer between incomming-outgoing socket pairs (tunnels) * and a threadpool that serves all these existing tunnels. * * Goal of TcpProxy is to simply tunnel all data between incoming sockets and their destination * sockets, trying to load-balance so that each destination connection transfers data with equal * rate. * * Destination ports are usually ssh-tunnels to a same service. * **/ package com.altiscale.TcpProxy; import org.apache.log4j.Logger; import java.io.*; import java.lang.Thread; import java.net.*; import java.util.ArrayList; public class TcpTunnel { // We are just a proxy. We create two pipes, proxy all data and whoever closes the // connection first our job is to simply close the other end as well. public class OneDirectionTunnel implements Runnable { private String threadName; private Thread thread; private Socket source; private Socket destination; public OneDirectionTunnel(Socket source, Socket destination) { thread = null; this.source = source; this.destination = destination; } public void run() { DataInputStream input = null; DataOutputStream output = null; try { input = new DataInputStream(source.getInputStream()); output = new DataOutputStream(destination.getOutputStream()); } catch (IOException ioe) { LOG.error("Could not open input and outpus streams."); } int cnt = 0; byte[] buffer = new byte[1024]; try { do { // Read some data. cnt = input.read(buffer); if (cnt > 0) { output.write(buffer, 0, cnt); // We don't want to buffer too much in the proxy. So, flush the output. // TODO(zoran): this might cause some performance issues. Experiment with // buffer size and maybe flush less often. output.flush(); } } while (cnt >= 0); } catch (IOException ioe) { LOG.error("IO exception catched while reading: " + ioe.getMessage()); } // Either the input stream is closed or we got an exception. Either way, close the // sockets since we're done with this tunnel. try { if (!source.isClosed()) { source.close(); } if (!destination.isClosed()) { destination.close(); } } catch (IOException ioe) { LOG.error("IO exception while closing sockets in thread [" + threadName + "]: " + ioe.getMessage()); } LOG.info("Exiting thread [" + threadName + "]"); } public Thread start(String threadName) { this.threadName = threadName; assert null == thread; // we should never call this method twice. LOG.info("Starting thread [" + threadName + "]"); thread = new Thread(this, threadName); thread.start(); return thread; } } // log4j logger. private static Logger LOG = Logger.getLogger("TcpProxy"); // Proxy who created us. We run on its threadpool. TcpProxyServer proxy; // Socket from our client to us. private Socket clientSocket; // Socket from us to our server. private Socket serverSocket; // Client-to-Server one-directional tunnel. OneDirectionTunnel clientServer; // Server-to-Client one-directional tunnel. OneDirectionTunnel serverClient; public TcpTunnel(TcpProxyServer proxy, Socket clientSocket, Socket serverSocket) { this.clientSocket = clientSocket; this.serverSocket = clientSocket; // Create two one-directional tunnels to connect both pipes. clientServer = new OneDirectionTunnel(clientSocket, serverSocket); serverClient = new OneDirectionTunnel(serverSocket, clientSocket); // Start both of them in their own threads. clientServer.start("clientServer"); serverClient.start("serverClient"); } public boolean isClosed() { return clientSocket.isClosed() && serverSocket.isClosed(); } }
src/main/java/com/altiscale/TcpProxy/TcpTunnel.java
/** * Copyright Altiscale 2014 * Author: Zoran Dimitrijevic <zoran@altiscale.com> * * TcpProxy is a class to handle data transfer between incomming-outgoing socket pairs (tunnels) * and a threadpool that serves all these existing tunnels. * * Goal of TcpProxy is to simply tunnel all data between incoming sockets and their destination * sockets, trying to load-balance so that each destination connection transfers data with equal * rate. * * Destination ports are usually ssh-tunnels to a same service. * **/ package com.altiscale.TcpProxy; import org.apache.log4j.Logger; import java.io.*; import java.lang.Thread; import java.net.*; import java.util.ArrayList; public class TcpTunnel { // We are just a proxy. We create two pipes, proxy all data and whoever closes the // connection first our job is to simply close the other end as well. public class OneDirectionTunnel implements Runnable { private String threadName; private Thread thread; private Socket source; private Socket destination; public OneDirectionTunnel(Socket source, Socket destination) { thread = null; this.source = source; this.destination = destination; } public void run() { DataInputStream input = null; DataOutputStream output = null; try { input = new DataInputStream(source.getInputStream()); output = new DataOutputStream(destination.getOutputStream()); } catch (IOException ioe) { LOG.error("Could not open input and outpus streams."); } int cnt = 0; byte[] buffer = new byte[1024]; try { do { // Read some data. cnt = input.read(buffer); if (cnt > 0) { output.write(buffer, 0, cnt); // We don't want to buffer too much in the proxy. So, flush the output. // TODO(zoran): this might cause some performance issues. Experiment with // buffer size and maybe flush less often. output.flush(); } } while (cnt >= 0); } catch (IOException ioe) { LOG.error("IO exception catched while reading: " + ioe.getMessage()); } // Either the input stream is closed or we got an exception. Either way, close the // sockets since we're done with this tunnel. try { if (!source.isClosed()) { source.close(); } if (!destination.isClosed()) { destination.close(); } } catch (IOException ioe) { LOG.error("IO exception while closing sockets in thread [" + threadName + "]: " + ioe.getMessage()); } LOG.info("Exiting thread [" + threadName + "]"); } public Thread start(String threadName) { this.threadName = threadName; assert null == thread; // we should never call this method twice. LOG.info("Starting thread [" + threadName + "]"); thread = new Thread(this, threadName); thread.start(); return thread; } } // log4j logger. private static Logger LOG = Logger.getLogger("TcpProxy"); // Proxy who created us. We run on its threadpool. TcpProxyServer proxy; // Socket from our client to us. private Socket clientSocket; // Socket from us to our server. private Socket serverSocket; // Client-to-Server one-directional tunnel. OneDirectionTunnel clientServer; // Server-to-Client one-directional tunnel. OneDirectionTunnel serverClient; public TcpTunnel(TcpProxyServer proxy, Socket clientSocket, Socket serverSocket) { this.clientSocket = clientSocket; this.serverSocket = clientSocket; // Create two one-directional tunnels to connect both pipes. clientServer = new OneDirectionTunnel(clientSocket, serverSocket); serverClient = new OneDirectionTunnel(serverSocket, clientSocket); // Start both of them in their own threads. clientServer.start("clientServer"); serverClient.start("serverClient"); } public boolean isClosed() { return clientSocket.isClosed() && serverSocket.isClosed(); } }
Fixed a typo.
src/main/java/com/altiscale/TcpProxy/TcpTunnel.java
Fixed a typo.
Java
apache-2.0
5a9aab7e9f597be95c1f64cb920673d8d4efa988
0
OmniKryptec/OmniKryptec-Engine
package de.omnikryptec.graphics.display; import de.omnikryptec.libapi.glfw.GLFWManager; import de.omnikryptec.libapi.glfw.Window; /** * A wrapper class that is responsible to update a given {@link Window} and * provide various often required functions like {@link #getDeltaTime()} or * {@link #getFPS()}. * * @author pcfreak9000 * */ public class WindowUpdater { private double swapTime = 0; private double fpstime = 0; private double deltatime = 0; private double lasttime = 0; private double frontruntime = 0; private long framecount = 0; private long fps1 = 0, fps2 = 0; private boolean fps = true; private double lastsynced; private Window<?> window; private Smoother deltaTimeSmoother; public WindowUpdater(Window<?> window) { this.window = window; this.deltaTimeSmoother = new Smoother(); } /** * Updates the window maintained by this object and the values accessable by the * functions of this class (e.g. {@link #getDeltaTime()}.<br> * The update includes swapping the buffers and polling events.<br> * <br> * This function can limit the framerate by setting this Thread to sleep. This * will happen if the frames per second (not counted) are greater than the * specified maxfps or in other words, if idle time is available. * * @param maxfps limits the FPS for values greater than 0. Otherwise does * nothing. */ public void update(int maxfps) { // TODO this is some crazy hack if (framecount == 0) { lasttime = GLFWManager.active().getTime(); fpstime = GLFWManager.active().getTime(); } double currentFrameTime = GLFWManager.active().getTime(); deltatime = (currentFrameTime - lasttime); deltaTimeSmoother.push(deltatime); frontruntime += deltatime; lasttime = currentFrameTime; if (maxfps > 0) { sync(maxfps); } double tmptime = GLFWManager.active().getTime(); window.swapBuffers(); swapTime = GLFWManager.active().getTime() - tmptime; GLFWManager.active().pollEvents(); framecount++; if (fps) { fps1++; } else { fps2++; } if (frontruntime - fpstime >= 1.0) { fpstime = frontruntime; if (fps) { fps = false; fps2 = 0; } else { fps = true; fps1 = 0; } } } /** * See {@link #update(int)}. * * @param fps maxfps, values smaller or equal to 0 confuse this function though. */ private void sync(int fps) { double target = lastsynced + (1.0 / fps); try { while ((lastsynced = GLFWManager.active().getTime()) < target) { Thread.sleep(1); } } catch (InterruptedException ex) { } } // TODO better somewhere else? public Window<?> getWindow() { return window; } /** * An instance of {@link Smoother} that can be used to retrieve a delta time * smoothed over multiple frames, in seconds. * * @return the delta time smoother * @see #getDeltaTime() */ public final Smoother getDeltaTimeSmoother() { return deltaTimeSmoother; } /** * the amount of calls to the {@link #update(int)} function since the creation * of this object. * * @return the frame count */ public long getFrameCount() { return framecount; } /** * the amount of time the maintained window was in the foreground. For a * complete time since glfw initialization, see {@link GLFWManager#getTime()}. * * @return window foreground time * @see GLFWManager#getTime() */ public double getFrontRunningTime() { return frontruntime; } /** * the counted frames per second. Counted means that the calls to * {@link #update(int)} will be counted each second, so the value of this * function will only change once every second. * * @return frames per second */ public long getFPS() { return fps ? fps2 : fps1; } /** * the measured delta time. That is the elapsed time between the last and the * last but one call to {@link #update(int)}, in seconds. For a smoothed value * over multiple updates, see {@link #getDeltaTimeSmoother()}. * * @return delta time * @see #getDeltaTimeSmoother() */ public double getDeltaTime() { return deltatime; } /** * The time spend on swapping the buffers the last time {@link #update(int)} was * called, in seconds. * * @return swap time */ public double getSwapTime() { return swapTime; } }
src/main/java/de/omnikryptec/graphics/display/WindowUpdater.java
package de.omnikryptec.graphics.display; import de.omnikryptec.libapi.glfw.GLFWManager; import de.omnikryptec.libapi.glfw.Window; /** * A wrapper class that is responsible to update a given {@link Window} and * provide various often required functions like {@link #getDeltaTime()} or * {@link #getFPS()}. * * @author pcfreak9000 * */ public class WindowUpdater { private double swapTime = 0; private double fpstime = 0; private double deltatime = 0; private double lasttime = 0; private double frontruntime = 0; private long framecount = 0; private long fps1 = 0, fps2 = 0; private boolean fps = true; private double lastsynced; private Window<?> window; private Smoother deltaTimeSmoother; public WindowUpdater(Window<?> window) { this.window = window; this.deltaTimeSmoother = new Smoother(); } /** * Updates the window maintained by this object and all the corresponding values * presented by this class. This includes swapping the buffers and polling * events.<br> * <br> * This function can limit the framerate by setting this Thread to sleep. This * will happen if the frames per second (not counted) are greater than the * specified maxfps or in other words, if idle time is available. * * @param maxfps limits the FPS for values greater than 0. Otherwise does * nothing. */ public void update(int maxfps) { // TODO this is some crazy hack if (framecount == 0) { lasttime = GLFWManager.active().getTime(); fpstime = GLFWManager.active().getTime(); } double currentFrameTime = GLFWManager.active().getTime(); deltatime = (currentFrameTime - lasttime); deltaTimeSmoother.push(deltatime); frontruntime += deltatime; lasttime = currentFrameTime; if (maxfps > 0) { sync(maxfps); } double tmptime = GLFWManager.active().getTime(); window.swapBuffers(); swapTime = GLFWManager.active().getTime() - tmptime; GLFWManager.active().pollEvents(); framecount++; if (fps) { fps1++; } else { fps2++; } if (frontruntime - fpstime >= 1.0) { fpstime = frontruntime; if (fps) { fps = false; fps2 = 0; } else { fps = true; fps1 = 0; } } } /** * See {@link #update(int)}. * * @param fps maxfps, values smaller or equal to 0 confuse this function though. */ private void sync(int fps) { double target = lastsynced + (1.0 / fps); try { while ((lastsynced = GLFWManager.active().getTime()) < target) { Thread.sleep(1); } } catch (InterruptedException ex) { } } // TODO better somewhere else? public Window<?> getWindow() { return window; } /** * An instance of {@link Smoother} that can be used to retrieve a delta time * smoothed over multiple frames, in seconds. * * @return the delta time smoother * @see #getDeltaTime() */ public final Smoother getDeltaTimeSmoother() { return deltaTimeSmoother; } /** * the amount of calls to the {@link #update(int)} function since the creation * of this object. * * @return the frame count */ public long getFrameCount() { return framecount; } /** * the amount of time the maintained window was in the foreground. For a * complete time since glfw initialization, see {@link GLFWManager#getTime()}. * * @return window foreground time * @see GLFWManager#getTime() */ public double getFrontRunningTime() { return frontruntime; } /** * the counted frames per second. Counted means that the calls to * {@link #update(int)} will be counted each second, so the value of this * function will only change once every second. * * @return frames per second */ public long getFPS() { return fps ? fps2 : fps1; } /** * the measured delta time. That is the elapsed time between the last and the * last but one call to {@link #update(int)}, in seconds. For a smoothed value * over multiple updates, see {@link #getDeltaTimeSmoother()}. * * @return delta time * @see #getDeltaTimeSmoother() */ public double getDeltaTime() { return deltatime; } /** * The time spend on swapping the buffers the last time {@link #update(int)} was * called, in seconds. * * @return swap time */ public double getSwapTime() { return swapTime; } }
another fix
src/main/java/de/omnikryptec/graphics/display/WindowUpdater.java
another fix
Java
apache-2.0
44253d988868bd6808307130c74e14f3c6a541a1
0
wyona/yanel,baszero/yanel,baszero/yanel,wyona/yanel,baszero/yanel,baszero/yanel,baszero/yanel,baszero/yanel,wyona/yanel,wyona/yanel,wyona/yanel,wyona/yanel
package org.wyona.yanel.core.source; import javax.xml.transform.Source; import javax.xml.transform.URIResolver; import javax.xml.transform.stream.StreamSource; import java.net.URL; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.BasicHttpParams; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; import org.wyona.yanel.core.Resource; /** * Resolves URIs with scheme "http" and "https". * * Syntax: * http:{path} * * e.g. * http://foo/bar.xml * */ public class HttpResolver implements URIResolver { private static final Logger log = LogManager.getLogger(HttpResolver.class); private static final String HTTP_SCHEME = "http"; private static final String HTTPS_SCHEME = "https"; //private Resource resource; private int connectionTimeout = -1; private int socketTimeout = -1; /** * @param resource Resource associated with source resolving */ public HttpResolver(Resource resource) { //this.resource = resource; } /** * @param resource Resource associated with source resolving * @param connectionTimeout Value of CONNECTION_TIMEOUT * @param socketTimeout Value of SO_TIMEOUT */ public HttpResolver(Resource resource, int connectionTimeout, int socketTimeout) { //this.resource = resource; this.connectionTimeout = connectionTimeout; this.socketTimeout = socketTimeout; } /** * @see javax.xml.transform.URIResolver#resolve(String, String) */ public Source resolve(String href, String base) throws SourceException { String httpPrefix = HTTP_SCHEME + ":"; String httpsPrefix = HTTPS_SCHEME + ":"; // INFO: Only accept URIs which start either with 'http:' or 'https:' if (href != null && (href.startsWith(httpPrefix) || href.startsWith(httpsPrefix))){ log.debug("href '" + href + "' seems to start with the correct scheme."); } else { log.error("Href '" + href + "' does neither start with prefix '" + httpPrefix + "' nor with '" + httpsPrefix + "'!"); return null; } try { java.net.URL url = new java.net.URL(href); if (log.isDebugEnabled()) log.debug("Resolve: " + url.toString()); // TODO: Make BASIC AUTH username and password configurable (similar to connection- and socket-timeout) DefaultHttpClient httpClient = getHttpClient(url, null, null, connectionTimeout, socketTimeout); HttpGet httpGet = new HttpGet(url.toString()); org.apache.http.HttpResponse response = httpClient.execute(httpGet); if (response.getStatusLine().getStatusCode() == 200) { return new StreamSource(response.getEntity().getContent()); } else { throw new Exception("Response code '" + response.getStatusLine().getStatusCode() + "'"); } } catch (java.net.SocketTimeoutException e) { String errorMsg = "Socket timeout while requesting '" + href + "' (" + e.toString() + "), whereas socket timeout is set to '" + socketTimeout + "' (Hint: Maybe it makes sense to increase this value)."; log.error(errorMsg, e); throw new SourceException(errorMsg, e); } catch (Exception e) { String errorMsg = "Could not resolve URI: " + href + ": " + e.toString(); log.error(errorMsg, e); throw new SourceException(errorMsg, e); } } /** * Get http client using SSL if necessary and basic authentication set * @param username Username for basic authentication * @param password Password for basic authentication * @param connectionTimeout Value of CONNECTION_TIMEOUT * @param socketTimeout Value of SO_TIMEOUT */ private DefaultHttpClient getHttpClient(URL url, String username, String password, int connectionTimeout, int socketTimeout) throws Exception { HttpParams httpParams = new BasicHttpParams(); if (connectionTimeout >= 0) { HttpConnectionParams.setConnectionTimeout(httpParams, connectionTimeout); } else { log.warn("No connection timeout set, hence use default value: " + HttpConnectionParams.getConnectionTimeout(httpParams)); } if (socketTimeout >= 0) { HttpConnectionParams.setSoTimeout(httpParams, socketTimeout); } else { log.warn("No socket timeout set, hence use default value: " + HttpConnectionParams.getSoTimeout(httpParams)); } DefaultHttpClient httpClient = new DefaultHttpClient(httpParams); // INFO: http://stackoverflow.com/questions/7201154/httpclient-1-4-2-explanation-needed-for-custom-ssl-context-example if (url.getProtocol().equals("https")) { httpClient.getConnectionManager().getSchemeRegistry().register(new org.apache.http.conn.scheme.Scheme("https", 443, getSSLFactory())); } else { log.warn("Unsecure connection: " + url); } if (username != null && password != null) { log.debug("Set BASIC AUTH for username '" + username + "'..."); httpClient.getCredentialsProvider().setCredentials(new org.apache.http.auth.AuthScope(url.getHost(), url.getPort()), new org.apache.http. auth.UsernamePasswordCredentials(username, password)); } else { log.debug("No BASIC AUTH credentials set."); } return httpClient; } /** * Get SSL factory */ private org.apache.http.conn.ssl.SSLSocketFactory getSSLFactory() throws Exception { // TODO: Make SSLSocketFactory configurable... // INFO: Just trust the certificate without checking/comparing a list of trusted certificates org.apache.http.conn.ssl.SSLSocketFactory factory = new org.apache.http.conn.ssl.SSLSocketFactory(new org.apache.http.conn.ssl.TrustStrategy() { public boolean isTrusted(final java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException { return true; } }, org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); //org.apache.http.conn.ssl.SSLSocketFactory factory = new org.apache.http.conn.ssl.SSLSocketFactory(getSSLContext(), new org.apache.http.conn.ssl.StrictHostnameVerifier()); return factory; } }
src/core/java/org/wyona/yanel/core/source/HttpResolver.java
package org.wyona.yanel.core.source; import javax.xml.transform.Source; import javax.xml.transform.URIResolver; import javax.xml.transform.stream.StreamSource; import java.net.URL; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.BasicHttpParams; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; import org.wyona.yanel.core.Resource; /** * Resolves URIs with scheme "http" and "https". * * Syntax: * http:{path} * * e.g. * http://foo/bar.xml * */ public class HttpResolver implements URIResolver { private static final Logger log = LogManager.getLogger(HttpResolver.class); private static final String HTTP_SCHEME = "http"; private static final String HTTPS_SCHEME = "https"; //private Resource resource; int connectionTimeout = -1; int socketTimeout = -1; /** * @param resource Resource associated with source resolving */ public HttpResolver(Resource resource) { //this.resource = resource; } /** * @param resource Resource associated with source resolving * @param connectionTimeout Value of CONNECTION_TIMEOUT * @param socketTimeout Value of SO_TIMEOUT */ public HttpResolver(Resource resource, int connectionTimeout, int socketTimeout) { //this.resource = resource; this.connectionTimeout = connectionTimeout; this.socketTimeout = socketTimeout; } /** * @see javax.xml.transform.URIResolver#resolve(String, String) */ public Source resolve(String href, String base) throws SourceException { String httpPrefix = HTTP_SCHEME + ":"; String httpsPrefix = HTTPS_SCHEME + ":"; // INFO: Only accept URIs which start either with 'http:' or 'https:' if (href != null && (href.startsWith(httpPrefix) || href.startsWith(httpsPrefix))){ log.debug("href '" + href + "' seems to start with the correct scheme."); } else { log.error("Href '" + href + "' does neither start with prefix '" + httpPrefix + "' nor with '" + httpsPrefix + "'!"); return null; } try { java.net.URL url = new java.net.URL(href); if (log.isDebugEnabled()) log.debug("Resolve: " + url.toString()); // TODO: Make BASIC AUTH username and password configurable (similar to connection- and socket-timeout) DefaultHttpClient httpClient = getHttpClient(url, null, null, connectionTimeout, socketTimeout); HttpGet httpGet = new HttpGet(url.toString()); org.apache.http.HttpResponse response = httpClient.execute(httpGet); if (response.getStatusLine().getStatusCode() == 200) { return new StreamSource(response.getEntity().getContent()); } else { throw new Exception("Response code '" + response.getStatusLine().getStatusCode() + "'"); } } catch (java.net.SocketTimeoutException e) { String errorMsg = "Socket timeout while requesting '" + href + "' (" + e.toString() + "), whereas socket timeout is set to '" + socketTimeout + "' (Hint: Maybe it makes sense to increase this value)."; log.error(errorMsg, e); throw new SourceException(errorMsg, e); } catch (Exception e) { String errorMsg = "Could not resolve URI: " + href + ": " + e.toString(); log.error(errorMsg, e); throw new SourceException(errorMsg, e); } } /** * Get http client using SSL if necessary and basic authentication set * @param username Username for basic authentication * @param password Password for basic authentication * @param connectionTimeout Value of CONNECTION_TIMEOUT * @param socketTimeout Value of SO_TIMEOUT */ private DefaultHttpClient getHttpClient(URL url, String username, String password, int connectionTimeout, int socketTimeout) throws Exception { HttpParams httpParams = new BasicHttpParams(); if (connectionTimeout >= 0) { HttpConnectionParams.setConnectionTimeout(httpParams, connectionTimeout); } else { log.warn("No connection timeout set, hence use default value: " + HttpConnectionParams.getConnectionTimeout(httpParams)); } if (socketTimeout >= 0) { HttpConnectionParams.setSoTimeout(httpParams, socketTimeout); } else { log.warn("No socket timeout set, hence use default value: " + HttpConnectionParams.getSoTimeout(httpParams)); } DefaultHttpClient httpClient = new DefaultHttpClient(httpParams); // INFO: http://stackoverflow.com/questions/7201154/httpclient-1-4-2-explanation-needed-for-custom-ssl-context-example if (url.getProtocol().equals("https")) { httpClient.getConnectionManager().getSchemeRegistry().register(new org.apache.http.conn.scheme.Scheme("https", 443, getSSLFactory())); } else { log.warn("Unsecure connection: " + url); } if (username != null && password != null) { log.debug("Set BASIC AUTH for username '" + username + "'..."); httpClient.getCredentialsProvider().setCredentials(new org.apache.http.auth.AuthScope(url.getHost(), url.getPort()), new org.apache.http. auth.UsernamePasswordCredentials(username, password)); } else { log.debug("No BASIC AUTH credentials set."); } return httpClient; } /** * Get SSL factory */ private org.apache.http.conn.ssl.SSLSocketFactory getSSLFactory() throws Exception { // TODO: Make SSLSocketFactory configurable... // INFO: Just trust the certificate without checking/comparing a list of trusted certificates org.apache.http.conn.ssl.SSLSocketFactory factory = new org.apache.http.conn.ssl.SSLSocketFactory(new org.apache.http.conn.ssl.TrustStrategy() { public boolean isTrusted(final java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException { return true; } }, org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); //org.apache.http.conn.ssl.SSLSocketFactory factory = new org.apache.http.conn.ssl.SSLSocketFactory(getSSLContext(), new org.apache.http.conn.ssl.StrictHostnameVerifier()); return factory; } }
connection and socket timeout as private variables
src/core/java/org/wyona/yanel/core/source/HttpResolver.java
connection and socket timeout as private variables
Java
apache-2.0
80a9d03d3799b8d8e394713188ff3fff371770b3
0
cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x
/* * Copyright 2002-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.orm.jdo; import javax.jdo.JDODataStoreException; import javax.jdo.JDOException; import javax.jdo.JDOFatalDataStoreException; import javax.jdo.JDOFatalUserException; import javax.jdo.JDOObjectNotFoundException; import javax.jdo.JDOOptimisticVerificationException; import javax.jdo.JDOUserException; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import javax.jdo.Query; import javax.sql.DataSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.jdbc.datasource.DataSourceUtils; import org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator; import org.springframework.jdbc.support.SQLExceptionTranslator; import org.springframework.jdbc.support.SQLStateSQLExceptionTranslator; import org.springframework.transaction.support.TransactionSynchronizationAdapter; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.util.Assert; /** * Helper class featuring methods for JDO PersistenceManager handling, * allowing for reuse of PersistenceManager instances within transactions. * Also provides support for exception translation. * * <p>Used internally by {@link JdoTemplate}, {@link JdoInterceptor} and * {@link JdoTransactionManager}. Can also be used directly in application code. * * @author Juergen Hoeller * @since 03.06.2003 * @see JdoTransactionManager * @see org.springframework.transaction.jta.JtaTransactionManager * @see org.springframework.transaction.support.TransactionSynchronizationManager */ public abstract class PersistenceManagerFactoryUtils { /** * Order value for TransactionSynchronization objects that clean up JDO * PersistenceManagers. Return DataSourceUtils.CONNECTION_SYNCHRONIZATION_ORDER - 100 * to execute PersistenceManager cleanup before JDBC Connection cleanup, if any. * @see org.springframework.jdbc.datasource.DataSourceUtils#CONNECTION_SYNCHRONIZATION_ORDER */ public static final int PERSISTENCE_MANAGER_SYNCHRONIZATION_ORDER = DataSourceUtils.CONNECTION_SYNCHRONIZATION_ORDER - 100; private static final Log logger = LogFactory.getLog(PersistenceManagerFactoryUtils.class); /** * Create an appropriate SQLExceptionTranslator for the given PersistenceManagerFactory. * <p>If a DataSource is found, creates a SQLErrorCodeSQLExceptionTranslator for the * DataSource; else, falls back to a SQLStateSQLExceptionTranslator. * @param connectionFactory the connection factory of the PersistenceManagerFactory * (may be <code>null</code>) * @return the SQLExceptionTranslator (never <code>null</code>) * @see javax.jdo.PersistenceManagerFactory#getConnectionFactory() * @see org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator * @see org.springframework.jdbc.support.SQLStateSQLExceptionTranslator */ static SQLExceptionTranslator newJdbcExceptionTranslator(Object connectionFactory) { // Check for PersistenceManagerFactory's DataSource. if (connectionFactory instanceof DataSource) { return new SQLErrorCodeSQLExceptionTranslator((DataSource) connectionFactory); } else { return new SQLStateSQLExceptionTranslator(); } } /** * Obtain a JDO PersistenceManager via the given factory. Is aware of a * corresponding PersistenceManager bound to the current thread, * for example when using JdoTransactionManager. Will create a new * PersistenceManager else, if "allowCreate" is <code>true</code>. * @param pmf PersistenceManagerFactory to create the PersistenceManager with * @param allowCreate if a non-transactional PersistenceManager should be created * when no transactional PersistenceManager can be found for the current thread * @return the PersistenceManager * @throws DataAccessResourceFailureException if the PersistenceManager couldn't be obtained * @throws IllegalStateException if no thread-bound PersistenceManager found and * "allowCreate" is <code>false</code> * @see JdoTransactionManager */ public static PersistenceManager getPersistenceManager(PersistenceManagerFactory pmf, boolean allowCreate) throws DataAccessResourceFailureException, IllegalStateException { try { return doGetPersistenceManager(pmf, allowCreate); } catch (JDOException ex) { throw new DataAccessResourceFailureException("Could not obtain JDO PersistenceManager", ex); } } /** * Obtain a JDO PersistenceManager via the given factory. Is aware of a * corresponding PersistenceManager bound to the current thread, * for example when using JdoTransactionManager. Will create a new * PersistenceManager else, if "allowCreate" is <code>true</code>. * <p>Same as <code>getPersistenceManager</code>, but throwing the original JDOException. * @param pmf PersistenceManagerFactory to create the PersistenceManager with * @param allowCreate if a non-transactional PersistenceManager should be created * when no transactional PersistenceManager can be found for the current thread * @return the PersistenceManager * @throws JDOException if the PersistenceManager couldn't be created * @throws IllegalStateException if no thread-bound PersistenceManager found and * "allowCreate" is <code>false</code> * @see #getPersistenceManager(javax.jdo.PersistenceManagerFactory, boolean) * @see JdoTransactionManager */ public static PersistenceManager doGetPersistenceManager(PersistenceManagerFactory pmf, boolean allowCreate) throws JDOException, IllegalStateException { Assert.notNull(pmf, "No PersistenceManagerFactory specified"); PersistenceManagerHolder pmHolder = (PersistenceManagerHolder) TransactionSynchronizationManager.getResource(pmf); if (pmHolder != null) { if (!pmHolder.isSynchronizedWithTransaction() && TransactionSynchronizationManager.isSynchronizationActive()) { pmHolder.setSynchronizedWithTransaction(true); TransactionSynchronizationManager.registerSynchronization( new PersistenceManagerSynchronization(pmHolder, pmf, false)); } return pmHolder.getPersistenceManager(); } if (!allowCreate && !TransactionSynchronizationManager.isSynchronizationActive()) { throw new IllegalStateException("No JDO PersistenceManager bound to thread, " + "and configuration does not allow creation of non-transactional one here"); } logger.debug("Opening JDO PersistenceManager"); PersistenceManager pm = pmf.getPersistenceManager(); if (TransactionSynchronizationManager.isSynchronizationActive()) { logger.debug("Registering transaction synchronization for JDO PersistenceManager"); // Use same PersistenceManager for further JDO actions within the transaction. // Thread object will get removed by synchronization at transaction completion. pmHolder = new PersistenceManagerHolder(pm); pmHolder.setSynchronizedWithTransaction(true); TransactionSynchronizationManager.registerSynchronization( new PersistenceManagerSynchronization(pmHolder, pmf, true)); TransactionSynchronizationManager.bindResource(pmf, pmHolder); } return pm; } /** * Return whether the given JDO PersistenceManager is transactional, that is, * bound to the current thread by Spring's transaction facilities. * @param pm the JDO PersistenceManager to check * @param pmf JDO PersistenceManagerFactory that the PersistenceManager * was created with (can be <code>null</code>) * @return whether the PersistenceManager is transactional */ public static boolean isPersistenceManagerTransactional( PersistenceManager pm, PersistenceManagerFactory pmf) { if (pmf == null) { return false; } PersistenceManagerHolder pmHolder = (PersistenceManagerHolder) TransactionSynchronizationManager.getResource(pmf); return (pmHolder != null && pm == pmHolder.getPersistenceManager()); } /** * Apply the current transaction timeout, if any, to the given JDO Query object. * @param query the JDO Query object * @param pmf JDO PersistenceManagerFactory that the Query was created for * @param jdoDialect the JdoDialect to use for applying a query timeout * (must not be <code>null</code>) * @throws JDOException if thrown by JDO methods * @see JdoDialect#applyQueryTimeout */ public static void applyTransactionTimeout( Query query, PersistenceManagerFactory pmf, JdoDialect jdoDialect) throws JDOException { Assert.notNull(query, "No Query object specified"); PersistenceManagerHolder pmHolder = (PersistenceManagerHolder) TransactionSynchronizationManager.getResource(pmf); if (pmHolder != null && pmHolder.hasTimeout()) { jdoDialect.applyQueryTimeout(query, pmHolder.getTimeToLiveInSeconds()); } } /** * Convert the given JDOException to an appropriate exception from the * <code>org.springframework.dao</code> hierarchy. * <p>The most important cases like object not found or optimistic locking * failure are covered here. For more fine-granular conversion, JdoAccessor and * JdoTransactionManager support sophisticated translation of exceptions via a * JdoDialect. * @param ex JDOException that occured * @return the corresponding DataAccessException instance * @see JdoAccessor#convertJdoAccessException * @see JdoTransactionManager#convertJdoAccessException * @see JdoDialect#translateException */ public static DataAccessException convertJdoAccessException(JDOException ex) { if (ex instanceof JDOObjectNotFoundException) { throw new JdoObjectRetrievalFailureException((JDOObjectNotFoundException) ex); } if (ex instanceof JDOOptimisticVerificationException) { throw new JdoOptimisticLockingFailureException((JDOOptimisticVerificationException) ex); } if (ex instanceof JDODataStoreException) { return new JdoResourceFailureException((JDODataStoreException) ex); } if (ex instanceof JDOFatalDataStoreException) { return new JdoResourceFailureException((JDOFatalDataStoreException) ex); } if (ex instanceof JDOUserException) { return new JdoUsageException((JDOUserException) ex); } if (ex instanceof JDOFatalUserException) { return new JdoUsageException((JDOFatalUserException) ex); } // fallback return new JdoSystemException(ex); } /** * Close the given PersistenceManager, created via the given factory, * if it is not managed externally (i.e. not bound to the thread). * @param pm PersistenceManager to close * @param pmf PersistenceManagerFactory that the PersistenceManager was created with * (can be <code>null</code>) */ public static void releasePersistenceManager(PersistenceManager pm, PersistenceManagerFactory pmf) { try { doReleasePersistenceManager(pm, pmf); } catch (JDOException ex) { logger.debug("Could not close JDO PersistenceManager", ex); } catch (Throwable ex) { logger.debug("Unexpected exception on closing JDO PersistenceManager", ex); } } /** * Actually release a PersistenceManager for the given factory. * Same as <code>releasePersistenceManager</code>, but throwing the original JDOException. * @param pm PersistenceManager to close * @param pmf PersistenceManagerFactory that the PersistenceManager was created with * (can be <code>null</code>) * @throws JDOException if thrown by JDO methods */ public static void doReleasePersistenceManager(PersistenceManager pm, PersistenceManagerFactory pmf) throws JDOException { if (pm == null) { return; } // Only release non-transactional PersistenceManagers. if (!isPersistenceManagerTransactional(pm, pmf)) { logger.debug("Closing JDO PersistenceManager"); pm.close(); } } /** * Callback for resource cleanup at the end of a non-JDO transaction * (e.g. when participating in a JtaTransactionManager transaction). * @see org.springframework.transaction.jta.JtaTransactionManager */ private static class PersistenceManagerSynchronization extends TransactionSynchronizationAdapter { private final PersistenceManagerHolder persistenceManagerHolder; private final PersistenceManagerFactory persistenceManagerFactory; private final boolean newPersistenceManager; private boolean holderActive = true; public PersistenceManagerSynchronization( PersistenceManagerHolder pmHolder, PersistenceManagerFactory pmf, boolean newPersistenceManager) { this.persistenceManagerHolder = pmHolder; this.persistenceManagerFactory = pmf; this.newPersistenceManager = newPersistenceManager; } public int getOrder() { return PERSISTENCE_MANAGER_SYNCHRONIZATION_ORDER; } public void suspend() { if (this.holderActive) { TransactionSynchronizationManager.unbindResource(this.persistenceManagerFactory); } } public void resume() { if (this.holderActive) { TransactionSynchronizationManager.bindResource( this.persistenceManagerFactory, this.persistenceManagerHolder); } } public void beforeCompletion() { if (this.newPersistenceManager) { TransactionSynchronizationManager.unbindResource(this.persistenceManagerFactory); this.holderActive = false; releasePersistenceManager( this.persistenceManagerHolder.getPersistenceManager(), this.persistenceManagerFactory); } } public void afterCompletion(int status) { this.persistenceManagerHolder.setSynchronizedWithTransaction(false); } } }
src/org/springframework/orm/jdo/PersistenceManagerFactoryUtils.java
/* * Copyright 2002-2006 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.orm.jdo; import javax.jdo.JDODataStoreException; import javax.jdo.JDOException; import javax.jdo.JDOFatalDataStoreException; import javax.jdo.JDOFatalUserException; import javax.jdo.JDOObjectNotFoundException; import javax.jdo.JDOOptimisticVerificationException; import javax.jdo.JDOUserException; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import javax.jdo.Query; import javax.sql.DataSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.jdbc.datasource.DataSourceUtils; import org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator; import org.springframework.jdbc.support.SQLExceptionTranslator; import org.springframework.jdbc.support.SQLStateSQLExceptionTranslator; import org.springframework.transaction.support.TransactionSynchronizationAdapter; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.util.Assert; /** * Helper class featuring methods for JDO PersistenceManager handling, * allowing for reuse of PersistenceManager instances within transactions. * Also provides support for exception translation. * * <p>Used by JdoTemplate, JdoInterceptor, and JdoTransactionManager. * Can also be used directly in application code, e.g. in combination * with JdoInterceptor. * * @author Juergen Hoeller * @since 03.06.2003 * @see JdoTemplate * @see JdoInterceptor * @see JdoTransactionManager */ public abstract class PersistenceManagerFactoryUtils { /** * Order value for TransactionSynchronization objects that clean up JDO * PersistenceManagers. Return DataSourceUtils.CONNECTION_SYNCHRONIZATION_ORDER - 100 * to execute PersistenceManager cleanup before JDBC Connection cleanup, if any. * @see org.springframework.jdbc.datasource.DataSourceUtils#CONNECTION_SYNCHRONIZATION_ORDER */ public static final int PERSISTENCE_MANAGER_SYNCHRONIZATION_ORDER = DataSourceUtils.CONNECTION_SYNCHRONIZATION_ORDER - 100; private static final Log logger = LogFactory.getLog(PersistenceManagerFactoryUtils.class); /** * Create an appropriate SQLExceptionTranslator for the given PersistenceManagerFactory. * <p>If a DataSource is found, creates a SQLErrorCodeSQLExceptionTranslator for the * DataSource; else, falls back to a SQLStateSQLExceptionTranslator. * @param connectionFactory the connection factory of the PersistenceManagerFactory * (may be <code>null</code>) * @return the SQLExceptionTranslator (never <code>null</code>) * @see javax.jdo.PersistenceManagerFactory#getConnectionFactory() * @see org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator * @see org.springframework.jdbc.support.SQLStateSQLExceptionTranslator */ static SQLExceptionTranslator newJdbcExceptionTranslator(Object connectionFactory) { // Check for PersistenceManagerFactory's DataSource. if (connectionFactory instanceof DataSource) { return new SQLErrorCodeSQLExceptionTranslator((DataSource) connectionFactory); } else { return new SQLStateSQLExceptionTranslator(); } } /** * Obtain a JDO PersistenceManager via the given factory. Is aware of a * corresponding PersistenceManager bound to the current thread, * for example when using JdoTransactionManager. Will create a new * PersistenceManager else, if "allowCreate" is <code>true</code>. * @param pmf PersistenceManagerFactory to create the PersistenceManager with * @param allowCreate if a non-transactional PersistenceManager should be created * when no transactional PersistenceManager can be found for the current thread * @return the PersistenceManager * @throws DataAccessResourceFailureException if the PersistenceManager couldn't be obtained * @throws IllegalStateException if no thread-bound PersistenceManager found and * "allowCreate" is <code>false</code> * @see JdoTransactionManager */ public static PersistenceManager getPersistenceManager(PersistenceManagerFactory pmf, boolean allowCreate) throws DataAccessResourceFailureException, IllegalStateException { try { return doGetPersistenceManager(pmf, allowCreate); } catch (JDOException ex) { throw new DataAccessResourceFailureException("Could not obtain JDO PersistenceManager", ex); } } /** * Obtain a JDO PersistenceManager via the given factory. Is aware of a * corresponding PersistenceManager bound to the current thread, * for example when using JdoTransactionManager. Will create a new * PersistenceManager else, if "allowCreate" is <code>true</code>. * <p>Same as <code>getPersistenceManager</code>, but throwing the original JDOException. * @param pmf PersistenceManagerFactory to create the PersistenceManager with * @param allowCreate if a non-transactional PersistenceManager should be created * when no transactional PersistenceManager can be found for the current thread * @return the PersistenceManager * @throws JDOException if the PersistenceManager couldn't be created * @throws IllegalStateException if no thread-bound PersistenceManager found and * "allowCreate" is <code>false</code> * @see #getPersistenceManager(javax.jdo.PersistenceManagerFactory, boolean) * @see JdoTransactionManager */ public static PersistenceManager doGetPersistenceManager(PersistenceManagerFactory pmf, boolean allowCreate) throws JDOException, IllegalStateException { Assert.notNull(pmf, "No PersistenceManagerFactory specified"); PersistenceManagerHolder pmHolder = (PersistenceManagerHolder) TransactionSynchronizationManager.getResource(pmf); if (pmHolder != null) { if (!pmHolder.isSynchronizedWithTransaction() && TransactionSynchronizationManager.isSynchronizationActive()) { pmHolder.setSynchronizedWithTransaction(true); TransactionSynchronizationManager.registerSynchronization( new PersistenceManagerSynchronization(pmHolder, pmf, false)); } return pmHolder.getPersistenceManager(); } if (!allowCreate && !TransactionSynchronizationManager.isSynchronizationActive()) { throw new IllegalStateException("No JDO PersistenceManager bound to thread, " + "and configuration does not allow creation of non-transactional one here"); } logger.debug("Opening JDO PersistenceManager"); PersistenceManager pm = pmf.getPersistenceManager(); if (TransactionSynchronizationManager.isSynchronizationActive()) { logger.debug("Registering transaction synchronization for JDO PersistenceManager"); // Use same PersistenceManager for further JDO actions within the transaction. // Thread object will get removed by synchronization at transaction completion. pmHolder = new PersistenceManagerHolder(pm); pmHolder.setSynchronizedWithTransaction(true); TransactionSynchronizationManager.registerSynchronization( new PersistenceManagerSynchronization(pmHolder, pmf, true)); TransactionSynchronizationManager.bindResource(pmf, pmHolder); } return pm; } /** * Return whether the given JDO PersistenceManager is transactional, that is, * bound to the current thread by Spring's transaction facilities. * @param pm the JDO PersistenceManager to check * @param pmf JDO PersistenceManagerFactory that the PersistenceManager * was created with (can be <code>null</code>) * @return whether the PersistenceManager is transactional */ public static boolean isPersistenceManagerTransactional( PersistenceManager pm, PersistenceManagerFactory pmf) { if (pmf == null) { return false; } PersistenceManagerHolder pmHolder = (PersistenceManagerHolder) TransactionSynchronizationManager.getResource(pmf); return (pmHolder != null && pm == pmHolder.getPersistenceManager()); } /** * Apply the current transaction timeout, if any, to the given JDO Query object. * @param query the JDO Query object * @param pmf JDO PersistenceManagerFactory that the Query was created for * @param jdoDialect the JdoDialect to use for applying a query timeout * (must not be <code>null</code>) * @see JdoDialect#applyQueryTimeout */ public static void applyTransactionTimeout( Query query, PersistenceManagerFactory pmf, JdoDialect jdoDialect) throws JDOException { Assert.notNull(query, "No Query object specified"); PersistenceManagerHolder pmHolder = (PersistenceManagerHolder) TransactionSynchronizationManager.getResource(pmf); if (pmHolder != null && pmHolder.hasTimeout()) { jdoDialect.applyQueryTimeout(query, pmHolder.getTimeToLiveInSeconds()); } } /** * Convert the given JDOException to an appropriate exception from the * <code>org.springframework.dao</code> hierarchy. * <p>The most important cases like object not found or optimistic locking * failure are covered here. For more fine-granular conversion, JdoAccessor and * JdoTransactionManager support sophisticated translation of exceptions via a * JdoDialect. * @param ex JDOException that occured * @return the corresponding DataAccessException instance * @see JdoAccessor#convertJdoAccessException * @see JdoTransactionManager#convertJdoAccessException * @see JdoDialect#translateException */ public static DataAccessException convertJdoAccessException(JDOException ex) { if (ex instanceof JDOObjectNotFoundException) { throw new JdoObjectRetrievalFailureException((JDOObjectNotFoundException) ex); } if (ex instanceof JDOOptimisticVerificationException) { throw new JdoOptimisticLockingFailureException((JDOOptimisticVerificationException) ex); } if (ex instanceof JDODataStoreException) { return new JdoResourceFailureException((JDODataStoreException) ex); } if (ex instanceof JDOFatalDataStoreException) { return new JdoResourceFailureException((JDOFatalDataStoreException) ex); } if (ex instanceof JDOUserException) { return new JdoUsageException((JDOUserException) ex); } if (ex instanceof JDOFatalUserException) { return new JdoUsageException((JDOFatalUserException) ex); } // fallback return new JdoSystemException(ex); } /** * Close the given PersistenceManager, created via the given factory, * if it is not managed externally (i.e. not bound to the thread). * @param pm PersistenceManager to close * @param pmf PersistenceManagerFactory that the PersistenceManager was created with * (can be <code>null</code>) */ public static void releasePersistenceManager(PersistenceManager pm, PersistenceManagerFactory pmf) { try { doReleasePersistenceManager(pm, pmf); } catch (JDOException ex) { logger.debug("Could not close JDO PersistenceManager", ex); } catch (Throwable ex) { logger.debug("Unexpected exception on closing JDO PersistenceManager", ex); } } /** * Actually release a PersistenceManager for the given factory. * Same as <code>releasePersistenceManager</code>, but throwing the original JDOException. * @param pm PersistenceManager to close * @param pmf PersistenceManagerFactory that the PersistenceManager was created with * (can be <code>null</code>) * @throws JDOException if thrown by JDO methods */ public static void doReleasePersistenceManager(PersistenceManager pm, PersistenceManagerFactory pmf) throws JDOException { if (pm == null) { return; } // Only release non-transactional PersistenceManagers. if (!isPersistenceManagerTransactional(pm, pmf)) { logger.debug("Closing JDO PersistenceManager"); pm.close(); } } /** * Callback for resource cleanup at the end of a non-JDO transaction * (e.g. when participating in a JtaTransactionManager transaction). * @see org.springframework.transaction.jta.JtaTransactionManager */ private static class PersistenceManagerSynchronization extends TransactionSynchronizationAdapter { private final PersistenceManagerHolder persistenceManagerHolder; private final PersistenceManagerFactory persistenceManagerFactory; private final boolean newPersistenceManager; private boolean holderActive = true; public PersistenceManagerSynchronization( PersistenceManagerHolder pmHolder, PersistenceManagerFactory pmf, boolean newPersistenceManager) { this.persistenceManagerHolder = pmHolder; this.persistenceManagerFactory = pmf; this.newPersistenceManager = newPersistenceManager; } public int getOrder() { return PERSISTENCE_MANAGER_SYNCHRONIZATION_ORDER; } public void suspend() { if (this.holderActive) { TransactionSynchronizationManager.unbindResource(this.persistenceManagerFactory); } } public void resume() { if (this.holderActive) { TransactionSynchronizationManager.bindResource( this.persistenceManagerFactory, this.persistenceManagerHolder); } } public void beforeCompletion() { if (this.newPersistenceManager) { TransactionSynchronizationManager.unbindResource(this.persistenceManagerFactory); this.holderActive = false; releasePersistenceManager( this.persistenceManagerHolder.getPersistenceManager(), this.persistenceManagerFactory); } } public void afterCompletion(int status) { this.persistenceManagerHolder.setSynchronizedWithTransaction(false); } } }
polishing git-svn-id: b619a0c99665f88f1afe72824344cefe9a1c8c90@14899 fd5a2b45-1f63-4059-99e9-3c7cb7fd75c8
src/org/springframework/orm/jdo/PersistenceManagerFactoryUtils.java
polishing
Java
apache-2.0
72c18a4c2b5565c15d358cb792f28b66becc9964
0
rbraeunlich/Project-TARDIS,rbraeunlich/Project-TARDIS,rbraeunlich/Project-TARDIS,rbraeunlich/Project-TARDIS
package kr.ac.kaist.se.tardis; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertThat; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.WebIntegrationTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * This test requires an installed Firefox browser on your PC! * */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = SamApplication.class) @WebIntegrationTest public class SamApplicationTests { private static final String PASSWORD = "bar"; private static final String USERNAME = "foo"; private static WebDriver webDriver; @Value("${local.server.port}") private int port; private String testUrl; @BeforeClass public static void setUpBeforeClass() { webDriver = new FirefoxDriver(); } @AfterClass public static void tearDownAfterClass() { webDriver.quit(); } @Before public void setUp() { testUrl = "https://localhost:" + port; } @Test public void succesfulLoginAfterRegistration() throws InterruptedException, Exception { webDriver.get(testUrl); // try to log in without account webDriver.findElement(By.id("loginButton")).click(); assertThat(webDriver.findElement(By.id("errorLogin")).getText(), is(notNullValue())); // create account webDriver.findElement(By.id("registerButton")).click(); webDriver.findElement(By.id("username")).sendKeys(USERNAME); webDriver.findElement(By.id("password")).sendKeys(PASSWORD); webDriver.findElement(By.id("usernameRepeated")).sendKeys(USERNAME); webDriver.findElement(By.id("passwordRepeated")).sendKeys(PASSWORD); webDriver.findElement(By.id("createButton")).click(); // create another account webDriver.findElement(By.id("registerButton")).click(); webDriver.findElement(By.id("username")).sendKeys("User1"); webDriver.findElement(By.id("password")).sendKeys("dummy"); webDriver.findElement(By.id("usernameRepeated")).sendKeys("User1"); webDriver.findElement(By.id("passwordRepeated")).sendKeys("dummy"); webDriver.findElement(By.id("createButton")).click(); // login webDriver.findElement(By.id("username")).sendKeys(USERNAME); webDriver.findElement(By.id("password")).sendKeys(PASSWORD); webDriver.findElement(By.id("loginButton")).click(); // check redirect String currentUrl = webDriver.getCurrentUrl(); assertThat(currentUrl, containsString("overview")); // create project webDriver.findElement(By.id("createProjectIcon")).click(); // first create an error webDriver.findElement(By.id("createProjectButton")).click(); // check errormessage assertThat(webDriver.findElement(By.id("errorProjectName")).getText(), is(notNullValue())); // now really create a project String projectName = "project"; webDriver.findElement(By.id("createProjectIcon")).click(); webDriver.findElement(By.id("projectname")).sendKeys(projectName); webDriver.findElement(By.id("description")).sendKeys("An example project"); webDriver.findElement(By.id("createProjectButton")).click(); // check that project is being shown webDriver.findElement(By.id(projectName)).click(); // go into Kanban Board webDriver.findElement(By.id(projectName + "Kanban")).click(); // check url currentUrl = webDriver.getCurrentUrl(); assertThat(currentUrl, containsString("kanbanboard")); assertThat(currentUrl, containsString("projectId=")); // check elements in Kanban Board new WebDriverWait(webDriver, 10L).until(ExpectedConditions.presenceOfElementLocated(By.id("projectName"))); assertThat(webDriver.findElement(By.id("projectName")).getText(), containsString(projectName)); // project setting - 1. change project name // go into project setting webDriver.findElement(By.id("projectSetting")).click(); // check url currentUrl = webDriver.getCurrentUrl(); assertThat(currentUrl, containsString("projectsettingview")); // try to rename project with 1 characters String newProjectName = "f"; webDriver.findElement(By.id("projectName")).clear(); webDriver.findElement(By.id("projectName")).sendKeys(newProjectName); webDriver.findElement(By.id("projectSettingSubmit")).click(); new WebDriverWait(webDriver, 10L).until(ExpectedConditions.presenceOfElementLocated(By.id("projectNameError"))); assertThat(webDriver.findElement(By.id("projectNameError")).getText(), containsString("Project name must contain at least three characters")); // change project name with more than 3 characters newProjectName = "new name"; webDriver.findElement(By.id("projectName")).sendKeys(newProjectName); webDriver.findElement(By.id("projectSettingSubmit")).click(); // check url currentUrl = webDriver.getCurrentUrl(); assertThat(currentUrl, containsString("kanbanboard")); Thread.sleep(50); //give it a little time to load // check new project name assertThat(webDriver.findElement(By.id("projectName")).getText(), containsString(newProjectName)); // project setting - 2. add new member // go into project setting webDriver.findElement(By.id("projectSetting")).click(); // check url currentUrl = webDriver.getCurrentUrl(); assertThat(currentUrl, containsString("projectsettingview")); // add un-exist user String newMemberName = "fake"; webDriver.findElement(By.id("newMember")).sendKeys(newMemberName); webDriver.findElement(By.id("projectSettingSubmit")).click(); new WebDriverWait(webDriver, 10L).until(ExpectedConditions.presenceOfElementLocated(By.id("newMemberError"))); assertThat(webDriver.findElement(By.id("newMemberError")).getText(), containsString("No Existing User")); // add proper user newMemberName = "User1"; webDriver.findElement(By.id("newMember")).clear(); webDriver.findElement(By.id("newMember")).sendKeys(newMemberName); webDriver.findElement(By.id("projectSettingSubmit")).click(); // check url currentUrl = webDriver.getCurrentUrl(); assertThat(currentUrl, containsString("kanbanboard")); // try to create a task webDriver.findElement(By.id("createTaskIcon")).click(); webDriver.findElement(By.id("createTaskButton")).click(); new WebDriverWait(webDriver, 10L).until(ExpectedConditions.presenceOfElementLocated(By.id("errorwrapper"))); // check error WebElement errorWrapper = webDriver.findElement(By.id("errorwrapper")); assertThat(errorWrapper.getText(), containsString("Task name must contain at least three characters")); assertThat(errorWrapper.getText(), containsString("Task must set due date")); // now really create one webDriver.findElement(By.id("createTaskIcon")).click(); String taskName = "task name"; webDriver.findElement(By.id("taskName")).sendKeys(taskName); String taskDescription = "task description"; webDriver.findElement(By.id("taskDescription")).sendKeys(taskDescription); webDriver.findElement(By.id("dueDate")).sendKeys("2016-01-01"); webDriver.findElement(By.id("createTaskButton")).click(); // check new task present new WebDriverWait(webDriver, 10L).until(ExpectedConditions.presenceOfElementLocated(By.id("ToDo"))); assertThat(webDriver.findElement(By.id("ToDo")).getText(), containsString(taskName)); assertThat(webDriver.findElement(By.id("ToDo")).getText(), containsString(taskDescription)); // HTML 5 drag and drop cannot be tested by Selenium } }
SAM/web/src/test/java/kr/ac/kaist/se/tardis/SamApplicationTests.java
package kr.ac.kaist.se.tardis; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertThat; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.WebIntegrationTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * This test requires an installed Firefox browser on your PC! * */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = SamApplication.class) @WebIntegrationTest public class SamApplicationTests { private static final String PASSWORD = "bar"; private static final String USERNAME = "foo"; private static WebDriver webDriver; @Value("${local.server.port}") private int port; private String testUrl; @BeforeClass public static void setUpBeforeClass() { webDriver = new FirefoxDriver(); } @AfterClass public static void tearDownAfterClass() { webDriver.quit(); } @Before public void setUp() { testUrl = "https://localhost:" + port; } @Test public void succesfulLoginAfterRegistration() throws InterruptedException, Exception { webDriver.get(testUrl); // try to log in without account webDriver.findElement(By.id("loginButton")).click(); assertThat(webDriver.findElement(By.id("errorLogin")).getText(), is(notNullValue())); // create account webDriver.findElement(By.id("registerButton")).click(); webDriver.findElement(By.id("username")).sendKeys(USERNAME); webDriver.findElement(By.id("password")).sendKeys(PASSWORD); webDriver.findElement(By.id("usernameRepeated")).sendKeys(USERNAME); webDriver.findElement(By.id("passwordRepeated")).sendKeys(PASSWORD); webDriver.findElement(By.id("createButton")).click(); // create another account webDriver.findElement(By.id("registerButton")).click(); webDriver.findElement(By.id("username")).sendKeys("User1"); webDriver.findElement(By.id("password")).sendKeys("dummy"); webDriver.findElement(By.id("usernameRepeated")).sendKeys("User1"); webDriver.findElement(By.id("passwordRepeated")).sendKeys("dummy"); webDriver.findElement(By.id("createButton")).click(); // login webDriver.findElement(By.id("username")).sendKeys(USERNAME); webDriver.findElement(By.id("password")).sendKeys(PASSWORD); webDriver.findElement(By.id("loginButton")).click(); // check redirect String currentUrl = webDriver.getCurrentUrl(); assertThat(currentUrl, containsString("overview")); // create project webDriver.findElement(By.id("createProjectIcon")).click(); // first create an error webDriver.findElement(By.id("createProjectButton")).click(); // check errormessage assertThat(webDriver.findElement(By.id("errorProjectName")).getText(), is(notNullValue())); // now really create a project String projectName = "project"; webDriver.findElement(By.id("createProjectIcon")).click(); webDriver.findElement(By.id("projectname")).sendKeys(projectName); webDriver.findElement(By.id("description")).sendKeys("An example project"); webDriver.findElement(By.id("createProjectButton")).click(); // check that project is being shown webDriver.findElement(By.id(projectName)).click(); // go into Kanban Board webDriver.findElement(By.id(projectName + "Kanban")).click(); // check url currentUrl = webDriver.getCurrentUrl(); assertThat(currentUrl, containsString("kanbanboard")); assertThat(currentUrl, containsString("projectId=")); // check elements in Kanban Board assertThat(webDriver.findElement(By.id("projectName")).getText(), containsString(projectName)); // project setting - 1. change project name // go into project setting webDriver.findElement(By.id("projectSetting")).click(); // check url currentUrl = webDriver.getCurrentUrl(); assertThat(currentUrl, containsString("projectsettingview")); // try to rename project with 1 characters String newProjectName = "f"; webDriver.findElement(By.id("projectName")).clear(); webDriver.findElement(By.id("projectName")).sendKeys(newProjectName); webDriver.findElement(By.id("projectSettingSubmit")).click(); Thread.sleep(50); //give it a little time to load assertThat(webDriver.findElement(By.id("projectNameError")).getText(), containsString("Project name must contain at least three characters")); // change project name with more than 3 characters newProjectName = "new name"; webDriver.findElement(By.id("projectName")).sendKeys(newProjectName); webDriver.findElement(By.id("projectSettingSubmit")).click(); // check url currentUrl = webDriver.getCurrentUrl(); assertThat(currentUrl, containsString("kanbanboard")); Thread.sleep(50); //give it a little time to load // check new project name assertThat(webDriver.findElement(By.id("projectName")).getText(), containsString(newProjectName)); // project setting - 2. add new member // go into project setting webDriver.findElement(By.id("projectSetting")).click(); // check url currentUrl = webDriver.getCurrentUrl(); assertThat(currentUrl, containsString("projectsettingview")); // add un-exist user String newMemberName = "fake"; webDriver.findElement(By.id("newMember")).sendKeys(newMemberName); webDriver.findElement(By.id("projectSettingSubmit")).click(); Thread.sleep(50); //give it a little time to load assertThat(webDriver.findElement(By.id("newMemberError")).getText(), containsString("No Existing User")); // add proper user newMemberName = "User1"; webDriver.findElement(By.id("newMember")).clear(); webDriver.findElement(By.id("newMember")).sendKeys(newMemberName); webDriver.findElement(By.id("projectSettingSubmit")).click(); // check url currentUrl = webDriver.getCurrentUrl(); assertThat(currentUrl, containsString("kanbanboard")); // try to create a task webDriver.findElement(By.id("createTaskIcon")).click(); webDriver.findElement(By.id("createTaskButton")).click(); Thread.sleep(100); //give it a little time to load // check error WebElement errorWrapper = webDriver.findElement(By.id("errorwrapper")); assertThat(errorWrapper.getText(), containsString("Task name must contain at least three characters")); assertThat(errorWrapper.getText(), containsString("Task must set due date")); // now really create one webDriver.findElement(By.id("createTaskIcon")).click(); String taskName = "task name"; webDriver.findElement(By.id("taskName")).sendKeys(taskName); String taskDescription = "task description"; webDriver.findElement(By.id("taskDescription")).sendKeys(taskDescription); webDriver.findElement(By.id("dueDate")).sendKeys("2016-01-01"); webDriver.findElement(By.id("createTaskButton")).click(); // check new task present Thread.sleep(50); //give it a little time to load assertThat(webDriver.findElement(By.id("ToDo")).getText(), containsString(taskName)); assertThat(webDriver.findElement(By.id("ToDo")).getText(), containsString(taskDescription)); // HTML 5 drag and drop cannot be tested by Selenium } }
use correct WebDriverWait in Selenium test
SAM/web/src/test/java/kr/ac/kaist/se/tardis/SamApplicationTests.java
use correct WebDriverWait in Selenium test
Java
apache-2.0
53d7abd17b0e858c360b1c10748d93760f04e6aa
0
mta452/Tehreer-Android,mta452/Tehreer-Android,mta452/Tehreer-Android
/* * Copyright (C) 2017 Muhammad Tayyab Akram * * 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.mta.tehreer.graphics; import java.util.List; public class TypeFamily { private final String familyName; private final List<Typeface> typefaces; public TypeFamily(String familyName, List<Typeface> typefaces) { this.familyName = familyName; this.typefaces = typefaces; } public String familyName() { return familyName; } public List<Typeface> typefaces() { return typefaces; } }
tehreer-android/src/main/java/com/mta/tehreer/graphics/TypeFamily.java
/* * Copyright (C) 2017 Muhammad Tayyab Akram * * 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.mta.tehreer.graphics; import java.util.Collections; import java.util.List; public class TypeFamily { final String familyName; final List<Typeface> typefaces; TypeFamily(String familyName, List<Typeface> typefaces) { this.familyName = familyName; this.typefaces = typefaces; } public String getFamilyName() { return familyName; } public List<Typeface> getTypefaces() { return Collections.unmodifiableList(typefaces); } }
[lib] Made type family class only data holder...
tehreer-android/src/main/java/com/mta/tehreer/graphics/TypeFamily.java
[lib] Made type family class only data holder...
Java
apache-2.0
ced9460cc3e0aa3d0f0789e733751c2d153fbfcd
0
davide-maestroni/jroutine,davide-maestroni/jroutine
/** * 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.bmd.wtf.fll; import com.bmd.wtf.crr.Current; import com.bmd.wtf.crr.CurrentGenerator; import com.bmd.wtf.crr.Currents; import com.bmd.wtf.flw.Bridge; import com.bmd.wtf.flw.Collector; import com.bmd.wtf.flw.Pump; import com.bmd.wtf.flw.River; import com.bmd.wtf.gts.Gate; import com.bmd.wtf.gts.GateGenerator; import com.bmd.wtf.gts.OpenGate; import com.bmd.wtf.spr.Spring; import com.bmd.wtf.spr.SpringGenerator; import com.bmd.wtf.spr.Springs; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.WeakHashMap; import java.util.concurrent.TimeUnit; /** * Here is where everything starts. * <p/> * Each waterfall instance retains a reference to its source so to be available during the building * chain. * <p/> * Created by davide on 6/4/14. * * @param <SOURCE> the waterfall source data type. * @param <IN> the input data type. * @param <OUT> the output data type. */ public class Waterfall<SOURCE, IN, OUT> extends AbstractRiver<IN> { // TODO: bridge, linq(?) // TODO: exception javadoc private static final Comparator<?> NATURAL_COMPARATOR = Collections.reverseOrder(Collections.reverseOrder()); private static final DataFall[] NO_FALL = new DataFall[0]; private static final Classification<Void> SELF_CLASSIFICATION = new Classification<Void>() {}; private static final WeakHashMap<Gate<?, ?>, Void> sGates = new WeakHashMap<Gate<?, ?>, Void>(); private static OpenGate<?> sOpenGate; private final Current mBackgroundCurrent; private final int mBackgroundPoolSize; private final Classification<?> mBridgeClassification; private final Map<Classification<?>, BridgeGate<?, ?>> mBridgeMap; private final Current mCurrent; private final CurrentGenerator mCurrentGenerator; private final DataFall<IN, OUT>[] mFalls; private final PumpGate<?> mPump; private final int mSize; private final Waterfall<SOURCE, SOURCE, ?> mSource; private Waterfall(final Waterfall<SOURCE, SOURCE, ?> source, final Map<Classification<?>, BridgeGate<?, ?>> bridgeMap, final Classification<?> bridgeClassification, final int backgroundPoolSize, final Current backgroundCurrent, final PumpGate<?> pumpGate, final int size, final Current current, final CurrentGenerator generator, final DataFall<IN, OUT>[] falls) { //noinspection unchecked mSource = (source != null) ? source : (Waterfall<SOURCE, SOURCE, ?>) this; mBridgeMap = bridgeMap; mBridgeClassification = bridgeClassification; mBackgroundPoolSize = backgroundPoolSize; mBackgroundCurrent = backgroundCurrent; mPump = pumpGate; mSize = size; mCurrent = current; mCurrentGenerator = generator; mFalls = falls; } private Waterfall(final Waterfall<SOURCE, SOURCE, ?> source, final Map<Classification<?>, BridgeGate<?, ?>> bridgeMap, final Classification<?> bridgeClassification, final int backgroundPoolSize, final Current backgroundCurrent, final PumpGate<?> pumpGate, final int size, final Current current, final CurrentGenerator generator, final Gate<IN, OUT>[] gates) { //noinspection unchecked mSource = (source != null) ? source : (Waterfall<SOURCE, SOURCE, ?>) this; mBridgeClassification = null; mBackgroundPoolSize = backgroundPoolSize; mBackgroundCurrent = backgroundCurrent; mSize = size; mCurrent = current; mCurrentGenerator = generator; final int length = gates.length; final Gate<IN, OUT> wrappedGate; if (bridgeClassification != null) { final Gate<IN, OUT> gate = gates[0]; final HashMap<Classification<?>, BridgeGate<?, ?>> fallBridgeMap = new HashMap<Classification<?>, BridgeGate<?, ?>>(bridgeMap); final BridgeGate<IN, OUT> bridgeGate = new BridgeGate<IN, OUT>(gate); mapBridge(fallBridgeMap, (SELF_CLASSIFICATION == bridgeClassification) ? Classification.ofType( gate.getClass()) : bridgeClassification, bridgeGate); mBridgeMap = fallBridgeMap; wrappedGate = bridgeGate; } else { if (size != length) { wrappedGate = new BarrageGate<IN, OUT>(gates[0]); } else { wrappedGate = null; } mBridgeMap = bridgeMap; } final DataFall[] falls = new DataFall[size]; if (size == 1) { mPump = null; } else { mPump = pumpGate; } final PumpGate<?> fallPump = mPump; for (int i = 0; i < size; ++i) { final Gate<IN, OUT> gate = (wrappedGate != null) ? wrappedGate : gates[i]; final Current fallCurrent; if (current == null) { fallCurrent = generator.create(i); } else { fallCurrent = current; } if (fallPump != null) { falls[i] = new PumpFall<SOURCE, IN, OUT>(this, fallCurrent, gate, i, fallPump); } else { falls[i] = new DataFall<IN, OUT>(this, fallCurrent, gate, i); } } //noinspection unchecked mFalls = (DataFall<IN, OUT>[]) falls; } /** * Creates and returns a new waterfall composed by a single synchronous stream. * * @return the newly created waterfall. */ public static Waterfall<Object, Object, Object> fall() { final Map<Classification<?>, BridgeGate<?, ?>> bridgeMap = Collections.emptyMap(); //noinspection unchecked return new Waterfall<Object, Object, Object>(null, bridgeMap, null, 0, null, null, 1, Currents.passThrough(), null, NO_FALL); } /** * Connects an input and an output fall through a data stream. * * @param inFall the input fall. * @param outFall the output fall. * @param <DATA> the data type. * @return the data stream running between the two falls. * @throws IllegalArgumentException if the input or the output fall are null. */ private static <DATA> DataStream<DATA> connect(final DataFall<?, DATA> inFall, final DataFall<DATA, ?> outFall) { final DataStream<DATA> stream = new DataStream<DATA>(inFall, outFall); outFall.inputStreams.add(stream); inFall.outputStreams.add(stream); return stream; } /** * Lazily creates and return a singleton open gate instance. * * @param <DATA> the data type. * @return the open gate instance. */ private static <DATA> OpenGate<DATA> openGate() { if (sOpenGate == null) { sOpenGate = new OpenGate<Object>(); } //noinspection unchecked return (OpenGate<DATA>) sOpenGate; } /** * Registers the specified gate instance by making sure it is unique among all the created * waterfalls. * * @param gate the gate to register. * @throws IllegalArgumentException if the gate is null or is already registered. */ private static void registerGate(final Gate<?, ?> gate) { if (gate == null) { throw new IllegalArgumentException("the waterfall gate cannot be null"); } if (sGates.containsKey(gate)) { throw new IllegalArgumentException("the waterfall already contains the gate: " + gate); } sGates.put(gate, null); } /** * Tells the waterfall to build a bridge on top of the next gate chained to it. * <p/> * The bridge type will be the same as the gate raw type. * * @return the newly created waterfall. */ public Waterfall<SOURCE, IN, OUT> bridge() { return bridge(SELF_CLASSIFICATION); } /** * Tells the waterfall to build a bridge of the specified type on top of the next gate chained * to it. * * @param bridgeClass the bridge class. * @return the newly created waterfall. * @throws IllegalArgumentException if the bridge class is null. */ public Waterfall<SOURCE, IN, OUT> bridge(final Class<?> bridgeClass) { return bridge(Classification.ofType(bridgeClass)); } /** * Tells the waterfall to build a bridge of the specified classification type on top of the * next gate chained to it. * * @param bridgeClassification the bridge classification. * @return the newly created waterfall. * @throws IllegalArgumentException if the bridge classification is null. */ public Waterfall<SOURCE, IN, OUT> bridge(final Classification<?> bridgeClassification) { if (bridgeClassification == null) { throw new IllegalArgumentException("the bridge classification cannot be null"); } return new Waterfall<SOURCE, IN, OUT>(mSource, mBridgeMap, bridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, mPump, mSize, mCurrent, mCurrentGenerator, mFalls); } /** * Chains the gate protected by the bridge of the specified classification type to this * waterfall. * <p/> * Note that contrary to common gate, the ones protected by a bridge can be added several times * to the same waterfall. * * @param bridgeClassification the bridge classification. * @param <NOUT> the new output data type. * @return the newly created waterfall. * @throws IllegalArgumentException if no protected gate is found. */ public <NOUT> Waterfall<SOURCE, OUT, NOUT> chain( final Classification<? extends Gate<OUT, NOUT>> bridgeClassification) { //noinspection unchecked final Gate<OUT, NOUT> gate = (Gate<OUT, NOUT>) findBestMatch(bridgeClassification); if (gate == null) { throw new IllegalArgumentException( "the waterfall does not retain any bridge of classification type " + bridgeClassification); } final DataFall<IN, OUT>[] falls = mFalls; final int size = mSize; //noinspection unchecked final Gate<OUT, NOUT>[] gates = new Gate[size]; if (size == 1) { gates[0] = gate; final Waterfall<SOURCE, OUT, NOUT> waterfall = new Waterfall<SOURCE, OUT, NOUT>(mSource, mBridgeMap, mBridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, mPump, 1, mCurrent, mCurrentGenerator, gates); final DataFall<OUT, NOUT> outFall = waterfall.mFalls[0]; for (final DataFall<IN, OUT> fall : falls) { connect(fall, outFall); } return waterfall; } final int length = falls.length; final Waterfall<SOURCE, ?, OUT> inWaterfall; if ((length != 1) && (length != size)) { inWaterfall = merge(); } else { inWaterfall = this; } Arrays.fill(gates, gate); final Waterfall<SOURCE, OUT, NOUT> waterfall = new Waterfall<SOURCE, OUT, NOUT>(inWaterfall.mSource, inWaterfall.mBridgeMap, inWaterfall.mBridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, mPump, size, inWaterfall.mCurrent, inWaterfall.mCurrentGenerator, gates); final DataFall<?, OUT>[] inFalls = inWaterfall.mFalls; final DataFall<OUT, NOUT>[] outFalls = waterfall.mFalls; if (inFalls.length == 1) { final DataFall<?, OUT> inFall = inFalls[0]; for (final DataFall<OUT, NOUT> outFall : outFalls) { connect(inFall, outFall); } } else { for (int i = 0; i < size; ++i) { connect(inFalls[i], outFalls[i]); } } return waterfall; } /** * Chains an open gate to this waterfall. * * @return the newly created waterfall. */ public Waterfall<SOURCE, OUT, OUT> chain() { final DataFall<IN, OUT>[] falls = mFalls; if (falls == NO_FALL) { //noinspection unchecked return (Waterfall<SOURCE, OUT, OUT>) start(); } final int size = mSize; final OpenGate<OUT> gate = openGate(); //noinspection unchecked final Gate<OUT, OUT>[] gates = new Gate[size]; if (size == 1) { gates[0] = gate; final Waterfall<SOURCE, OUT, OUT> waterfall = new Waterfall<SOURCE, OUT, OUT>(mSource, mBridgeMap, mBridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, mPump, 1, mCurrent, mCurrentGenerator, gates); final DataFall<OUT, OUT> outFall = waterfall.mFalls[0]; for (final DataFall<IN, OUT> fall : falls) { connect(fall, outFall); } return waterfall; } final int length = falls.length; final Waterfall<SOURCE, ?, OUT> inWaterfall; if ((length != 1) && (length != size)) { inWaterfall = merge(); } else { inWaterfall = this; } Arrays.fill(gates, gate); final Waterfall<SOURCE, OUT, OUT> waterfall = new Waterfall<SOURCE, OUT, OUT>(inWaterfall.mSource, inWaterfall.mBridgeMap, inWaterfall.mBridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, mPump, size, inWaterfall.mCurrent, inWaterfall.mCurrentGenerator, gates); final DataFall<?, OUT>[] inFalls = inWaterfall.mFalls; final DataFall<OUT, OUT>[] outFalls = waterfall.mFalls; if (inFalls.length == 1) { final DataFall<?, OUT> inFall = inFalls[0]; for (final DataFall<OUT, OUT> outFall : outFalls) { connect(inFall, outFall); } } else { for (int i = 0; i < size; ++i) { connect(inFalls[i], outFalls[i]); } } return waterfall; } /** * Chains the specified gates to this waterfall. * <p/> * Note that calling this method will have the same effect as calling first * <code>in(gates.length)</code>. * * @param gates the gate instances. * @param <NOUT> the new output data type. * @return the newly created waterfall. * @throws IllegalArgumentException if the gate collection is null, empty or contains null * instances or instances already chained to this or another * waterfall. */ public <NOUT> Waterfall<SOURCE, OUT, NOUT> chain( final Collection<? extends Gate<OUT, NOUT>> gates) { if (gates == null) { throw new IllegalArgumentException("the waterfall gate collection cannot be null"); } final int length = gates.size(); if (length == 0) { throw new IllegalArgumentException("the waterfall gate collection cannot be empty"); } final Waterfall<SOURCE, IN, OUT> waterfall; if (mSize == length) { waterfall = this; } else { waterfall = in(length); } final Iterator<? extends Gate<OUT, NOUT>> iterator = gates.iterator(); return waterfall.chain(new GateGenerator<OUT, NOUT>() { @Override public Gate<OUT, NOUT> create(final int fallNumber) { return iterator.next(); } }); } /** * Chains the specified gate to this waterfall. * <p/> * Note that in case this waterfall is composed by more then one data stream, all the data * flowing through them will be passed to the specified gate. * * @param gate the gate instance. * @param <NOUT> the new output data type. * @return the newly created waterfall. * @throws IllegalArgumentException if the gate is null or already chained to this or another * waterfall. */ public <NOUT> Waterfall<SOURCE, OUT, NOUT> chain(final Gate<OUT, NOUT> gate) { final DataFall<IN, OUT>[] falls = mFalls; if (falls == NO_FALL) { //noinspection unchecked return (Waterfall<SOURCE, OUT, NOUT>) start(gate); } final int size = mSize; //noinspection unchecked final Gate<OUT, NOUT>[] gates = new Gate[]{gate}; if (size == 1) { registerGate(gate); final Waterfall<SOURCE, OUT, NOUT> waterfall = new Waterfall<SOURCE, OUT, NOUT>(mSource, mBridgeMap, mBridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, mPump, 1, mCurrent, mCurrentGenerator, gates); final DataFall<OUT, NOUT> outFall = waterfall.mFalls[0]; for (final DataFall<IN, OUT> fall : falls) { connect(fall, outFall); } return waterfall; } final int length = falls.length; final Waterfall<SOURCE, ?, OUT> inWaterfall; if ((length != 1) && (length != size)) { inWaterfall = merge(); } else { inWaterfall = this; } registerGate(gate); final Waterfall<SOURCE, OUT, NOUT> waterfall = new Waterfall<SOURCE, OUT, NOUT>(inWaterfall.mSource, inWaterfall.mBridgeMap, inWaterfall.mBridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, mPump, size, inWaterfall.mCurrent, inWaterfall.mCurrentGenerator, gates); final DataFall<?, OUT>[] inFalls = inWaterfall.mFalls; final DataFall<OUT, NOUT>[] outFalls = waterfall.mFalls; if (inFalls.length == 1) { final DataFall<?, OUT> inFall = inFalls[0]; for (final DataFall<OUT, NOUT> outFall : outFalls) { connect(inFall, outFall); } } else { for (int i = 0; i < size; ++i) { connect(inFalls[i], outFalls[i]); } } return waterfall; } /** * Chains the gates returned by the specified generator to this waterfall. * <p/> * Note that in case this waterfall is composed by more then one data stream, each gate created * by the generator will handle a single stream. * * @param generator the gate generator. * @param <NOUT> the new output data type. * @return the newly created waterfall. * @throws IllegalArgumentException if the generator is null or returns a null gate or one * already chained to this or another waterfall. */ public <NOUT> Waterfall<SOURCE, OUT, NOUT> chain(final GateGenerator<OUT, NOUT> generator) { if (generator == null) { throw new IllegalArgumentException("the waterfall generator cannot be null"); } final DataFall<IN, OUT>[] falls = mFalls; if (falls == NO_FALL) { //noinspection unchecked return (Waterfall<SOURCE, OUT, NOUT>) start(generator); } final int size = mSize; //noinspection unchecked final Gate<OUT, NOUT>[] gates = new Gate[size]; if (size == 1) { final Gate<OUT, NOUT> gate = generator.create(0); registerGate(gate); gates[0] = gate; final Waterfall<SOURCE, OUT, NOUT> waterfall = new Waterfall<SOURCE, OUT, NOUT>(mSource, mBridgeMap, mBridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, mPump, 1, mCurrent, mCurrentGenerator, gates); final DataFall<OUT, NOUT> outFall = waterfall.mFalls[0]; for (final DataFall<IN, OUT> fall : falls) { connect(fall, outFall); } return waterfall; } if (mBridgeClassification != null) { throw new IllegalStateException("cannot make a bridge from more than one gate"); } final int length = falls.length; final Waterfall<SOURCE, ?, OUT> inWaterfall; if ((length != 1) && (length != size)) { inWaterfall = merge(); } else { inWaterfall = this; } for (int i = 0; i < size; ++i) { final Gate<OUT, NOUT> gate = generator.create(i); registerGate(gate); gates[i] = gate; } final Waterfall<SOURCE, OUT, NOUT> waterfall = new Waterfall<SOURCE, OUT, NOUT>(inWaterfall.mSource, inWaterfall.mBridgeMap, inWaterfall.mBridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, mPump, size, inWaterfall.mCurrent, inWaterfall.mCurrentGenerator, gates); final DataFall<?, OUT>[] inFalls = inWaterfall.mFalls; final DataFall<OUT, NOUT>[] outFalls = waterfall.mFalls; if (inFalls.length == 1) { final DataFall<?, OUT> inFall = inFalls[0]; for (final DataFall<OUT, NOUT> outFall : outFalls) { connect(inFall, outFall); } } else { for (int i = 0; i < size; ++i) { connect(inFalls[i], outFalls[i]); } } return waterfall; } /** * Tells the waterfall to close the bridge handling the specified gate, that is, the bridge * will not be accessible anymore to the ones requiring it. * * @param gate the gate instance. * @param <TYPE> the gate type. * @return the newly created waterfall. */ public <TYPE extends Gate<?, ?>> Waterfall<SOURCE, IN, OUT> close(final TYPE gate) { if (gate == null) { return this; } boolean isChanged = false; final HashMap<Classification<?>, BridgeGate<?, ?>> bridgeMap = new HashMap<Classification<?>, BridgeGate<?, ?>>(mBridgeMap); final Iterator<BridgeGate<?, ?>> iterator = bridgeMap.values().iterator(); while (iterator.hasNext()) { if (gate == iterator.next().gate) { iterator.remove(); isChanged = true; } } if (!isChanged) { return this; } return new Waterfall<SOURCE, IN, OUT>(mSource, bridgeMap, mBridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, mPump, mSize, mCurrent, mCurrentGenerator, mFalls); } /** * Tells the waterfall to close the bridge of the specified classification type, that is, the bridge * will not be accessible anymore to the ones requiring it. * * @param bridgeClassification the bridge classification. * @param <TYPE> the gate type. * @return the newly created waterfall. */ public <TYPE> Waterfall<SOURCE, IN, OUT> close( final Classification<TYPE> bridgeClassification) { final BridgeGate<?, ?> bridge = findBestMatch(bridgeClassification); if (bridge == null) { return this; } final HashMap<Classification<?>, BridgeGate<?, ?>> bridgeMap = new HashMap<Classification<?>, BridgeGate<?, ?>>(mBridgeMap); final Iterator<BridgeGate<?, ?>> iterator = bridgeMap.values().iterator(); while (iterator.hasNext()) { if (bridge == iterator.next()) { iterator.remove(); } } return new Waterfall<SOURCE, IN, OUT>(mSource, bridgeMap, mBridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, mPump, mSize, mCurrent, mCurrentGenerator, mFalls); } /** * Creates and returns a new data collector. * * @return the collector. * @throws IllegalStateException if this waterfall was not started. */ public Collector<OUT> collect() { if (mFalls == NO_FALL) { throw new IllegalStateException("cannot collect data from a not started waterfall"); } final CollectorGate<OUT> collectorGate = new CollectorGate<OUT>(); final BridgeGate<OUT, OUT> bridgeGate = new BridgeGate<OUT, OUT>(collectorGate); final Waterfall<SOURCE, IN, OUT> waterfall; if (mSize != 1) { waterfall = in(1); } else { waterfall = this; } waterfall.chain(bridgeGate); return new DataCollector<OUT>(bridgeGate, collectorGate); } /** * Causes the data drops flowing through this waterfall streams to be concatenated, so that all * the data coming from the stream number 0 will come before the ones coming from the stream * number 1, and so on.<br/> * The resulting waterfall will have size equal to 1. * <p/> * Note that the returned waterfall internally cache the data pushed through it and then * discharge them on the first flush. * * @return the newly created waterfall. */ public Waterfall<SOURCE, OUT, OUT> concat() { return chain(new CumulativeCacheGate<OUT, OUT>(size()) { @Override protected void onClear(final List<List<OUT>> cache, final River<OUT> upRiver, final River<OUT> downRiver) { for (final List<OUT> data : cache) { downRiver.push(data); } super.onClear(cache, upRiver, downRiver); } }).merge(); } /** * Causes the data drops flowing through this waterfall to be delayed of the specified time. * <p/> * Note that the returned waterfall internally cache the data pushed through it and then * discharge them on the first flush. * * @param delay the delay in <code>timeUnit</code> time units. * @param timeUnit the delay time unit. * @return the newly created waterfall. */ public Waterfall<SOURCE, OUT, OUT> delay(final long delay, final TimeUnit timeUnit) { return chain(new CacheGate<OUT, OUT>(size()) { @Override protected void onClear(final List<OUT> cache, final int streamNumber, final River<OUT> upRiver, final River<OUT> downRiver) { downRiver.pushAfter(delay, timeUnit, cache); super.onClear(cache, streamNumber, upRiver, downRiver); } }); } @Override public void deviate() { for (final DataFall<IN, OUT> fall : mFalls) { for (final DataStream<OUT> stream : fall.outputStreams) { stream.deviate(); } } } @Override public void deviateStream(final int streamNumber) { final DataFall<IN, OUT> fall = mFalls[streamNumber]; for (final DataStream<OUT> stream : fall.outputStreams) { stream.deviate(); } } @Override public void drain() { for (final DataFall<IN, OUT> fall : mFalls) { for (final DataStream<OUT> stream : fall.outputStreams) { stream.drain(Direction.DOWNSTREAM); } } } @Override public void drainStream(final int streamNumber) { final DataFall<IN, OUT> fall = mFalls[streamNumber]; for (final DataStream<OUT> stream : fall.outputStreams) { stream.drain(Direction.DOWNSTREAM); } } @Override public Waterfall<SOURCE, IN, OUT> exception(final Throwable throwable) { for (final DataFall<IN, OUT> fall : mFalls) { fall.raiseLevel(1); fall.inputCurrent.exception(fall, throwable); } return this; } @Override public Waterfall<SOURCE, IN, OUT> flush() { for (final DataFall<IN, OUT> fall : mFalls) { fall.inputCurrent.flush(fall, null); } return this; } @Override public Waterfall<SOURCE, IN, OUT> push(final IN... drops) { if ((drops == null) || (drops.length == 0)) { return this; } final DataFall<IN, OUT>[] falls = mFalls; for (final IN drop : drops) { for (final DataFall<IN, OUT> fall : falls) { fall.raiseLevel(1); fall.inputCurrent.push(fall, drop); } } return this; } @Override public Waterfall<SOURCE, IN, OUT> push(final Iterable<? extends IN> drops) { if (drops == null) { return this; } final DataFall<IN, OUT>[] falls = mFalls; for (final IN drop : drops) { for (final DataFall<IN, OUT> fall : falls) { fall.raiseLevel(1); fall.inputCurrent.push(fall, drop); } } return this; } @Override public Waterfall<SOURCE, IN, OUT> push(final IN drop) { for (final DataFall<IN, OUT> fall : mFalls) { fall.raiseLevel(1); fall.inputCurrent.push(fall, drop); } return this; } @Override public Waterfall<SOURCE, IN, OUT> pushAfter(final long delay, final TimeUnit timeUnit, final Iterable<? extends IN> drops) { if (drops == null) { return this; } final ArrayList<IN> list = new ArrayList<IN>(); for (final IN drop : drops) { list.add(drop); } if (!list.isEmpty()) { final int size = list.size(); for (final DataFall<IN, OUT> fall : mFalls) { fall.raiseLevel(size); fall.inputCurrent.pushAfter(fall, delay, timeUnit, list); } } return this; } @Override public Waterfall<SOURCE, IN, OUT> pushAfter(final long delay, final TimeUnit timeUnit, final IN drop) { for (final DataFall<IN, OUT> fall : mFalls) { fall.raiseLevel(1); fall.inputCurrent.pushAfter(fall, delay, timeUnit, drop); } return this; } @Override public Waterfall<SOURCE, IN, OUT> pushAfter(final long delay, final TimeUnit timeUnit, final IN... drops) { if ((drops == null) || (drops.length == 0)) { return this; } final ArrayList<IN> list = new ArrayList<IN>(Arrays.asList(drops)); for (final DataFall<IN, OUT> fall : mFalls) { fall.raiseLevel(drops.length); fall.inputCurrent.pushAfter(fall, delay, timeUnit, list); } return this; } @Override public Waterfall<SOURCE, IN, OUT> flushStream(final int streamNumber) { final DataFall<IN, OUT> fall = mFalls[streamNumber]; fall.inputCurrent.flush(fall, null); return this; } @Override public <TYPE> Bridge<TYPE> on(final Class<TYPE> bridgeClass) { return on(Classification.ofType(bridgeClass)); } @Override public <TYPE> Bridge<TYPE> on(final TYPE gate) { if (gate == null) { throw new IllegalArgumentException("the bridge gate cannot be null"); } BridgeGate<?, ?> bridge = null; final Map<Classification<?>, BridgeGate<?, ?>> bridgeMap = mBridgeMap; for (final BridgeGate<?, ?> bridgeGate : bridgeMap.values()) { if (bridgeGate.gate == gate) { bridge = bridgeGate; break; } } if (bridge == null) { throw new IllegalArgumentException("the waterfall does not retain the bridge " + gate); } return new DataBridge<TYPE>(bridge, new Classification<TYPE>() {}); } @Override public <TYPE> Bridge<TYPE> on(final Classification<TYPE> bridgeClassification) { final BridgeGate<?, ?> bridge = findBestMatch(bridgeClassification); if (bridge == null) { throw new IllegalArgumentException( "the waterfall does not retain any bridge of classification type " + bridgeClassification); } return new DataBridge<TYPE>(bridge, bridgeClassification); } @Override public Waterfall<SOURCE, IN, OUT> pushStream(final int streamNumber, final IN... drops) { if ((drops == null) || (drops.length == 0)) { return this; } final DataFall<IN, OUT> fall = mFalls[streamNumber]; fall.raiseLevel(drops.length); for (final IN drop : drops) { fall.inputCurrent.push(fall, drop); } return this; } @Override public Waterfall<SOURCE, IN, OUT> pushStream(final int streamNumber, final Iterable<? extends IN> drops) { if (drops == null) { return this; } int size = 0; for (final IN ignored : drops) { ++size; } if (size > 0) { final DataFall<IN, OUT> fall = mFalls[streamNumber]; fall.raiseLevel(size); for (final IN drop : drops) { fall.inputCurrent.push(fall, drop); } } return this; } @Override public Waterfall<SOURCE, IN, OUT> pushStream(final int streamNumber, final IN drop) { final DataFall<IN, OUT> fall = mFalls[streamNumber]; fall.raiseLevel(1); fall.inputCurrent.push(fall, drop); return this; } @Override public Waterfall<SOURCE, IN, OUT> pushStreamAfter(final int streamNumber, final long delay, final TimeUnit timeUnit, final Iterable<? extends IN> drops) { if (drops == null) { return this; } final ArrayList<IN> list = new ArrayList<IN>(); for (final IN drop : drops) { list.add(drop); } if (!list.isEmpty()) { final DataFall<IN, OUT> fall = mFalls[streamNumber]; fall.raiseLevel(list.size()); fall.inputCurrent.pushAfter(fall, delay, timeUnit, list); } return this; } @Override public Waterfall<SOURCE, IN, OUT> pushStreamAfter(final int streamNumber, final long delay, final TimeUnit timeUnit, final IN drop) { final DataFall<IN, OUT> fall = mFalls[streamNumber]; fall.raiseLevel(1); fall.inputCurrent.pushAfter(fall, delay, timeUnit, drop); return this; } @Override public Waterfall<SOURCE, IN, OUT> pushStreamAfter(final int streamNumber, final long delay, final TimeUnit timeUnit, final IN... drops) { if ((drops == null) || (drops.length == 0)) { return this; } final DataFall<IN, OUT> fall = mFalls[streamNumber]; fall.raiseLevel(drops.length); fall.inputCurrent.pushAfter(fall, delay, timeUnit, new ArrayList<IN>(Arrays.asList(drops))); return this; } @Override public int size() { return mFalls.length; } @Override public Waterfall<SOURCE, IN, OUT> streamException(final int streamNumber, final Throwable throwable) { final DataFall<IN, OUT> fall = mFalls[streamNumber]; fall.raiseLevel(1); fall.inputCurrent.exception(fall, throwable); return this; } /** * Deviates the flow of this waterfall, either downstream or upstream, by effectively * preventing any coming data to be pushed further. * * @param direction whether the waterfall must be deviated downstream or upstream. * @see #deviateStream(int, com.bmd.wtf.flw.Stream.Direction) */ public void deviate(final Direction direction) { if (direction == Direction.DOWNSTREAM) { deviate(); } else { for (final DataFall<IN, OUT> fall : mFalls) { for (final DataStream<IN> stream : fall.inputStreams) { stream.deviate(); } } } } /** * Deviates the flow of the specified waterfall stream, either downstream or upstream, by * effectively preventing any coming data to be pushed further. * * @param streamNumber the number identifying the target stream. * @param direction whether the waterfall must be deviated downstream or upstream. * @see #deviate(com.bmd.wtf.flw.Stream.Direction) */ public void deviateStream(final int streamNumber, final Direction direction) { if (direction == Direction.DOWNSTREAM) { deviateStream(streamNumber); } else { final DataFall<IN, OUT> fall = mFalls[streamNumber]; for (final DataStream<IN> stream : fall.inputStreams) { stream.deviate(); } } } /** * Uniformly distributes all the data flowing through this waterfall in the different output * streams. * * @return the newly created waterfall. */ public Waterfall<SOURCE, OUT, OUT> distribute() { final DataFall<IN, OUT>[] falls = mFalls; if (falls == NO_FALL) { //noinspection unchecked return (Waterfall<SOURCE, OUT, OUT>) start().distribute(); } final int size = mSize; if (size == 1) { return chain(); } return in(1).chainPump(new PumpGate<OUT>(size)).in(size).chain(); } /** * Distributes all the data flowing through this waterfall in the different output streams by * means of the specified pump. * * @return the newly created waterfall. * @throws IllegalArgumentException if the pump is null. */ public Waterfall<SOURCE, OUT, OUT> distribute(final Pump<OUT> pump) { if (pump == null) { throw new IllegalArgumentException("the waterfall pump cannot be null"); } final DataFall<IN, OUT>[] falls = mFalls; if (falls == NO_FALL) { //noinspection unchecked return (Waterfall<SOURCE, OUT, OUT>) start().distribute(pump); } final int size = mSize; if (size == 1) { return chain(); } return in(1).chainPump(new PumpGate<OUT>(pump, size)).in(size).chain(); } /** * Drains the waterfall, either downstream or upstream, by removing all the falls and rivers * fed only by this waterfall streams. * * @param direction whether the waterfall must be deviated downstream or upstream. * @see #drainStream(int, com.bmd.wtf.flw.Stream.Direction) */ public void drain(final Direction direction) { if (direction == Direction.DOWNSTREAM) { drain(); } else { for (final DataFall<IN, OUT> fall : mFalls) { for (final DataStream<IN> stream : fall.inputStreams) { stream.drain(direction); } } } } /** * Drains the specified waterfall stream, either downstream or upstream, by removing from all * the falls and rivers fed only by the specific stream. * * @param streamNumber the number identifying the target stream. * @param direction whether the waterfall must be deviated downstream or upstream. * @see #drain(com.bmd.wtf.flw.Stream.Direction) */ public void drainStream(final int streamNumber, final Direction direction) { if (direction == Direction.DOWNSTREAM) { drainStream(streamNumber); } else { final DataFall<IN, OUT> fall = mFalls[streamNumber]; for (final DataStream<IN> stream : fall.inputStreams) { stream.drain(direction); } } } /** * Filters the data flowing through this waterfall by retaining only the specified count of * drops, starting from the last minus the specified offset and discarding the other ones. * <p/> * Note that the returned waterfall internally cache the data pushed through it and then * discharge them on the first flush. * * @param endOffset the offset from the last data drop before a flush. * @param count the count of the element in the range. * @return the newly created waterfall. * @throws IllegalArgumentException if the offset is negative, the count is negative or equal * to zero or is greater than the offset + 1. */ public Waterfall<SOURCE, OUT, OUT> endRange(final int endOffset, final int count) { if ((endOffset < 0) || (count <= 0) || (count > (endOffset + 1))) { throw new IllegalArgumentException("invalid range indexes"); } final long maxSize = (long) endOffset + 1; final int length = Math.max(size(), 1); final long[] counts = new long[length]; //noinspection unchecked final ArrayList<OUT>[] lists = new ArrayList[length]; for (int i = 0; i < lists.length; i++) { lists[i] = new ArrayList<OUT>(); } return chain(new OpenGate<OUT>() { @Override public void onPush(final River<OUT> upRiver, final River<OUT> downRiver, final int fallNumber, final OUT drop) { ++counts[fallNumber]; final ArrayList<OUT> list = lists[fallNumber]; list.add(drop); if (list.size() > maxSize) { list.remove(0); } } @Override public void onFlush(final River<OUT> upRiver, final River<OUT> downRiver, final int fallNumber) { final long index = counts[fallNumber]; final ArrayList<OUT> list = lists[fallNumber]; if (index > (maxSize - count)) { downRiver.push(list.subList(0, count + (int) Math.min(0, index - maxSize))); } list.clear(); super.onFlush(upRiver, downRiver, fallNumber); } }); } /** * Makes this waterfall feed the specified one. After the call, all the data flowing through * this waterfall will be pushed into the target one. * * @param waterfall the waterfall to chain. * @throws IllegalArgumentException if the waterfall is null or equal to this one, or this or * the target one was not started, or if a possible closed * loop in the waterfall chain is detected. */ public void feed(final Waterfall<?, OUT, ?> waterfall) { if (waterfall == null) { throw new IllegalArgumentException("the waterfall cannot be null"); } if (this == waterfall) { throw new IllegalArgumentException("cannot feed a waterfall with itself"); } final DataFall<IN, OUT>[] falls = mFalls; if ((falls == NO_FALL) || (waterfall.mFalls == NO_FALL)) { throw new IllegalStateException("cannot feed a not started waterfall"); } final int size = waterfall.mSize; final int length = falls.length; final DataFall<OUT, ?>[] outFalls = waterfall.mFalls; for (final DataFall<OUT, ?> outFall : outFalls) { for (final DataStream<?> outputStream : outFall.outputStreams) { //noinspection unchecked if (outputStream.canReach(Arrays.asList(falls))) { throw new IllegalArgumentException( "a possible loop in the waterfall chain has been detected"); } } } if (size == 1) { final DataFall<OUT, ?> outFall = outFalls[0]; for (final DataFall<IN, OUT> fall : falls) { connect(fall, outFall); } } else { final Waterfall<SOURCE, ?, OUT> inWaterfall; if ((length != 1) && (length != size)) { inWaterfall = merge(); } else { inWaterfall = this; } final DataFall<?, OUT>[] inFalls = inWaterfall.mFalls; if (inFalls.length == 1) { final DataFall<?, OUT> inFall = inFalls[0]; for (final DataFall<OUT, ?> outFall : outFalls) { connect(inFall, outFall); } } else { for (int i = 0; i < size; ++i) { connect(inFalls[i], outFalls[i]); } } } } /** * Makes this waterfall feed the stream identified by the specified number. After the call, all * the data flowing through this waterfall will be pushed into the target stream. * * @param streamNumber the number identifying the target stream. * @param waterfall the target waterfall. * @throws IllegalArgumentException if the waterfall is null or equal to this one, or this or * the target one was not started, or if a possible closed * loop in the waterfall chain is detected. */ public void feedStream(final int streamNumber, final Waterfall<?, OUT, ?> waterfall) { if (waterfall == null) { throw new IllegalArgumentException("the waterfall cannot be null"); } if (this == waterfall) { throw new IllegalArgumentException("cannot feed a waterfall with itself"); } final DataFall<IN, OUT>[] falls = mFalls; if ((falls == NO_FALL) || (waterfall.mFalls == NO_FALL)) { throw new IllegalStateException("cannot feed a waterfall with a not started one"); } final DataFall<OUT, ?> outFall = waterfall.mFalls[streamNumber]; for (final DataStream<?> outputStream : outFall.outputStreams) { //noinspection unchecked if (outputStream.canReach(Arrays.asList(falls))) { throw new IllegalArgumentException( "a possible loop in the waterfall chain has been detected"); } } for (final DataFall<IN, OUT> fall : falls) { connect(fall, outFall); } } /** * Causes the data drops flowing through this waterfall streams to be merged into a single * collection. * * @return the newly created waterfall. */ public Waterfall<SOURCE, OUT, List<OUT>> flat() { return chain(new CacheGate<OUT, List<OUT>>(size()) { @Override protected void onClear(final List<OUT> cache, final int streamNumber, final River<OUT> upRiver, final River<List<OUT>> downRiver) { downRiver.push(new ArrayList<OUT>(cache)); super.onClear(cache, streamNumber, upRiver, downRiver); } }); } /** * Makes the waterfall streams flow through the currents returned by the specified generator. * * @param generator the current generator * @return the newly created waterfall. * @throws IllegalArgumentException if the generator is null or returns a null current. */ public Waterfall<SOURCE, IN, OUT> in(final CurrentGenerator generator) { if (generator == null) { throw new IllegalArgumentException("the waterfall current generator cannot be null"); } return new Waterfall<SOURCE, IN, OUT>(mSource, mBridgeMap, mBridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, mPump, mSize, null, generator, mFalls); } /** * Splits the waterfall in the specified number of streams. * * @param fallCount the total fall count generating the waterfall. * @return the newly created waterfall. * @throws IllegalArgumentException if the fall count is negative or 0. */ public Waterfall<SOURCE, IN, OUT> in(final int fallCount) { if (fallCount <= 0) { throw new IllegalArgumentException("the fall count cannot be negative or zero"); } return new Waterfall<SOURCE, IN, OUT>(mSource, mBridgeMap, mBridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, mPump, fallCount, mCurrent, mCurrentGenerator, mFalls); } /** * Makes the waterfall streams flow through the specified current. * * @param current the current. * @return the newly created waterfall. * @throws IllegalArgumentException if the current is null. */ public Waterfall<SOURCE, IN, OUT> in(final Current current) { if (current == null) { throw new IllegalArgumentException("the waterfall current cannot be null"); } return new Waterfall<SOURCE, IN, OUT>(mSource, mBridgeMap, mBridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, mPump, mSize, current, null, mFalls); } /** * Makes the waterfall streams flow through a background current. * <p/> * The optimum thread pool size will be automatically computed based on the available resources * and the waterfall size. * <p/> * Note also that the same background current will be retained through the waterfall. * * @param fallCount the total fall count generating the waterfall. * @return the newly created waterfall. * @throws IllegalArgumentException if the fall count is negative or 0. */ public Waterfall<SOURCE, IN, OUT> inBackground(final int fallCount) { if (fallCount <= 0) { throw new IllegalArgumentException("the fall count cannot be negative or zero"); } final int poolSize; final Current backgroundCurrent; if (mBackgroundCurrent == null) { poolSize = getBestPoolSize(); backgroundCurrent = Currents.pool(poolSize); } else { poolSize = mBackgroundPoolSize; backgroundCurrent = mBackgroundCurrent; } return new Waterfall<SOURCE, IN, OUT>(mSource, mBridgeMap, mBridgeClassification, poolSize, backgroundCurrent, mPump, fallCount, backgroundCurrent, null, mFalls); } /** * Makes the waterfall streams flow through a background current. * <p/> * The optimum thread pool size will be automatically computed based on the available resources * and the waterfall size, and the total fall count of the resulting waterfall will be * accordingly dimensioned. * <p/> * Note also that the same background current will be retained through the waterfall. * * @return the newly created waterfall. */ public Waterfall<SOURCE, IN, OUT> inBackground() { final int poolSize; final Current backgroundCurrent; if (mBackgroundCurrent == null) { poolSize = getBestPoolSize(); backgroundCurrent = Currents.pool(poolSize); } else { poolSize = mBackgroundPoolSize; backgroundCurrent = mBackgroundCurrent; } return new Waterfall<SOURCE, IN, OUT>(mSource, mBridgeMap, mBridgeClassification, poolSize, backgroundCurrent, mPump, poolSize, backgroundCurrent, null, mFalls); } /** * Causes the data drops flowing through this waterfall streams to be interleaved, so that the * first drop coming from the stream number 0 will come before the first one coming from the * stream number 1, and so on.<br/> * The resulting waterfall will have size equal to 1. * <p/> * Note that the returned waterfall internally cache the data pushed through it and then * discharge them on the first flush. * * @return the newly created waterfall. */ public Waterfall<SOURCE, OUT, OUT> interleave() { return chain(new CumulativeCacheGate<OUT, OUT>(size()) { @Override protected void onClear(final List<List<OUT>> cache, final River<OUT> upRiver, final River<OUT> downRiver) { boolean empty = false; while (!empty) { empty = true; for (final List<OUT> data : cache) { if (!data.isEmpty()) { empty = false; downRiver.push(data.remove(0)); } } } super.onClear(cache, upRiver, downRiver); } }).merge(); } /** * Makes this waterfall join the specified one, so that all the data coming from this * waterfall N streams will flow through the first N streams of the resulting waterfall, and * the ones coming from the specified waterfall streams will flow through the streams N + 1, N * + 2, ..., etc. * <p/> * TODO how to handle the bridges? * <p/> * Note that the bridges, the size and the currents of this waterfall will be retained. * * @param waterfall the waterfall to join. * @return the newly created waterfall. * @throws IllegalArgumentException if the waterfall is null. */ public Waterfall<OUT, OUT, OUT> join(final Waterfall<?, ?, OUT> waterfall) { if (waterfall == null) { throw new IllegalArgumentException("the waterfall cannot be null"); } return join(Collections.singleton(waterfall)); } /** * Makes this waterfall join the specified ones, so that all the data coming from this * waterfall N streams will flow through the first N streams of the resulting waterfall, the * ones coming from the streams of the first waterfall in the specified collection will flow * through the streams N + 1, N + 2, ..., etc., and so on. * <p/> * TODO how to handle the bridges? * <p/> * Note that the bridges, the size and the currents of this waterfall will be retained. * * @param waterfalls the collection of the waterfall to join. * @return the newly created waterfall. * @throws IllegalArgumentException if the waterfall collection is null or contains null * waterfalls. */ public Waterfall<OUT, OUT, OUT> join( final Collection<? extends Waterfall<?, ?, OUT>> waterfalls) { if (waterfalls == null) { throw new IllegalArgumentException("the waterfall collection cannot be null"); } final ArrayList<Waterfall<?, ?, OUT>> inWaterfalls = new ArrayList<Waterfall<?, ?, OUT>>(waterfalls.size() + 1); int totSize = 0; if (mFalls == NO_FALL) { totSize += 1; inWaterfalls.add(start()); } else { totSize += size(); inWaterfalls.add(this); } for (final Waterfall<?, ?, OUT> waterfall : waterfalls) { if (waterfall.mFalls == NO_FALL) { totSize += 1; inWaterfalls.add(waterfall.start()); } else { totSize += waterfall.size(); inWaterfalls.add(waterfall); } } final OpenGate<OUT> gate = openGate(); //noinspection unchecked final Gate<OUT, OUT>[] gates = new Gate[totSize]; Arrays.fill(gates, gate); final Waterfall<OUT, OUT, OUT> waterfall = new Waterfall<OUT, OUT, OUT>(null, mBridgeMap, mBridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, mPump, totSize, mCurrent, mCurrentGenerator, gates); int number = 0; final DataFall<OUT, OUT>[] outFalls = waterfall.mFalls; for (final Waterfall<?, ?, OUT> inWaterfall : inWaterfalls) { for (final DataFall<?, OUT> inFall : inWaterfall.mFalls) { connect(inFall, outFalls[number++]); } } return waterfall; } /** * Causes the data drops flowing through this waterfall streams to be merged into a single * stream.<br/> * The resulting waterfall will have size equal to 1. * * @return the newly created waterfall. */ public Waterfall<SOURCE, OUT, OUT> merge() { if (mFalls.length > 1) { return in(1).chain(); } return chain(); } /** * Creates and returns a new data collector after flushing this waterfall source. * * @return the collector. * @throws IllegalStateException if this waterfall was not started. */ public Collector<OUT> pull() { final Collector<OUT> collector = collect(); source().flush(); return collector; } /** * Creates and returns a new data collector after pushing the specified data into this * waterfall source and then flushing it. * * @param source the source data. * @return the collector. * @throws IllegalStateException if this waterfall was not started. */ public Collector<OUT> pull(final SOURCE source) { final Collector<OUT> collector = collect(); source().push(source).flush(); return collector; } /** * Creates and returns a new data collector after pushing the specified data into this * waterfall source and then flushing it. * * @param sources the source data. * @return the collector. * @throws IllegalStateException if this waterfall was not started. */ public Collector<OUT> pull(final SOURCE... sources) { final Collector<OUT> collector = collect(); source().push(sources).flush(); return collector; } /** * Creates and returns a new data collector after pushing the data returned by the specified * iterable into this waterfall source and then flushing it. * * @param sources the source data iterable. * @return the collector. * @throws IllegalStateException if this waterfall was not started. */ public Collector<OUT> pull(final Iterable<SOURCE> sources) { final Collector<OUT> collector = collect(); source().push(sources).flush(); return collector; } /** * Filters the data flowing through this waterfall by retaining only the specified count of * drops, starting from the specified offset and discarding the other ones. * <p/> * Note that the returned waterfall internally cache the data pushed through it and then * discharge them on the first flush. * * @param offset the offset from the first data drop. * @param count the count of the element in the range. * @return the newly created waterfall. * @throws IllegalArgumentException if the offset is negative, the count is negative or equal * to zero. */ public Waterfall<SOURCE, OUT, OUT> range(final int offset, final int count) { if ((offset < 0) || (count <= 0)) { throw new IllegalArgumentException("invalid range indexes"); } final long last = (long) offset + (long) count; final int length = Math.max(size(), 1); final long[] counts = new long[length]; //noinspection unchecked final ArrayList<OUT>[] lists = new ArrayList[length]; for (int i = 0; i < lists.length; i++) { lists[i] = new ArrayList<OUT>(); } return chain(new OpenGate<OUT>() { @Override public void onPush(final River<OUT> upRiver, final River<OUT> downRiver, final int fallNumber, final OUT drop) { final long index = counts[fallNumber]; if (index < last) { counts[fallNumber] = index + 1; if (index >= offset) { lists[fallNumber].add(drop); } } } @Override public void onFlush(final River<OUT> upRiver, final River<OUT> downRiver, final int fallNumber) { final ArrayList<OUT> list = lists[fallNumber]; downRiver.push(list); list.clear(); super.onFlush(upRiver, downRiver, fallNumber); } }); } /** * Causes the data drops flowing through this waterfall streams to flow down in the reverse * order. * <p/> * Note that the returned waterfall internally cache the data pushed through it and then * discharge them on the first flush. * * @return the newly created waterfall. */ public Waterfall<SOURCE, OUT, OUT> revert() { return chain(new CacheGate<OUT, OUT>(size()) { @Override protected void onClear(final List<OUT> cache, final int streamNumber, final River<OUT> upRiver, final River<OUT> downRiver) { Collections.reverse(cache); downRiver.push(cache); super.onClear(cache, streamNumber, upRiver, downRiver); } }); } /** * Causes the data drops flowing through this waterfall streams to flow down sorted in the * natural order. * <p/> * Note that the returned waterfall internally cache the data pushed through it and then * discharge them on the first flush. * * @return the newly created waterfall. */ public Waterfall<SOURCE, OUT, OUT> sort() { //noinspection unchecked return sort((Comparator<? super OUT>) NATURAL_COMPARATOR); } /** * Causes the data drops flowing through this waterfall streams to flow down sorted in the * order decided by the specified comparator. * <p/> * Note that the returned waterfall internally cache the data pushed through it and then * discharge them on the first flush. * * @param comparator the comparator. * @return the newly created waterfall. * @throws IllegalArgumentException if the comparator is null. */ public Waterfall<SOURCE, OUT, OUT> sort(final Comparator<? super OUT> comparator) { if (comparator == null) { throw new IllegalArgumentException("the data comparator cannot be null"); } return chain(new CacheGate<OUT, OUT>(size()) { @Override protected void onClear(final List<OUT> cache, final int streamNumber, final River<OUT> upRiver, final River<OUT> downRiver) { Collections.sort(cache, comparator); downRiver.push(cache); super.onClear(cache, streamNumber, upRiver, downRiver); } }); } /** * Gets the waterfall source. * * @return the source. */ public Waterfall<SOURCE, SOURCE, ?> source() { return mSource; } /** * Creates and returns a new waterfall fed by to the springs returned by the specified * generator. * <p/> * Note that the bridges, the size and the currents of this waterfall will be retained. * * @param generator the spring generator. * @param <DATA> the spring data type. * @return the newly created waterfall. * @throws IllegalArgumentException if the generator is null or returns a null spring. */ public <DATA> Waterfall<Void, Void, DATA> spring(final SpringGenerator<DATA> generator) { if (generator == null) { throw new IllegalArgumentException("the waterfall spring generator cannot be null"); } return start(new GateGenerator<Void, DATA>() { @Override public Gate<Void, DATA> create(final int fallNumber) { return new SpringGate<DATA>(generator.create(fallNumber)); } }); } /** * Creates and returns a new waterfall fed by the specified spring. * <p/> * Note that the bridges and the currents of this waterfall will be retained, while the size will * be equal to 1. * * @param spring the spring instance. * @param <DATA> the spring data type. * @return the newly created waterfall. * @throws IllegalArgumentException if the spring is null. */ public <DATA> Waterfall<Void, Void, DATA> spring(final Spring<DATA> spring) { return spring(Collections.singleton(spring)); } /** * Creates and returns a new waterfall fed by the specified springs. * <p/> * Note that the bridges and the currents of this waterfall will be retained, while the size will * be equal to the one of the specified collection. * * @param springs the spring instances. * @param <DATA> the spring data type. * @return the newly created waterfall. * @throws IllegalArgumentException if the spring collection is null or contains a null spring. */ public <DATA> Waterfall<Void, Void, DATA> spring( final Collection<? extends Spring<DATA>> springs) { if (springs == null) { throw new IllegalArgumentException("the waterfall spring collection cannot be null"); } final ArrayList<SpringGate<DATA>> gates = new ArrayList<SpringGate<DATA>>(springs.size()); for (final Spring<DATA> spring : springs) { gates.add(new SpringGate<DATA>(spring)); } return start(gates); } /** * Creates and returns a new waterfall fed by both this waterfall as a spring and the specified * one. * <p/> * Note that the bridges and the currents of this waterfall will be retained, while the size will * be equal to the one of the specified collection. * * @param spring the spring instance. * @return the newly created waterfall. * @throws IllegalArgumentException if the spring is null. */ public Waterfall<Void, Void, OUT> springWith(final Spring<OUT> spring) { if (spring == null) { throw new IllegalArgumentException("the spring cannot be null"); } return springWith(Collections.singleton(spring)); } /** * Creates and returns a new waterfall fed by this waterfall as a spring and all the specified * ones. * <p/> * Note that the bridges and the currents of this waterfall will be retained, while the size will * be equal to the one of the specified collection. * * @param springs the spring collection. * @return the newly created waterfall. * @throws IllegalArgumentException if the spring collection is null or contains a null spring. */ public Waterfall<Void, Void, OUT> springWith(final Collection<? extends Spring<OUT>> springs) { if (springs == null) { throw new IllegalArgumentException("the spring collection cannot be null"); } final ArrayList<Spring<OUT>> list = new ArrayList<Spring<OUT>>(springs.size() + 1); list.add(Springs.from(this)); list.addAll(springs); return spring(list); } /** * Creates and returns a new waterfall generating from this one. * <p/> * Note that the bridges, the size and the currents of this waterfall will be retained. * * @return the newly created waterfall. */ public Waterfall<OUT, OUT, OUT> start() { final int size = mSize; //noinspection unchecked final Gate<OUT, OUT>[] gates = new Gate[size]; Arrays.fill(gates, openGate()); final Map<Classification<?>, BridgeGate<?, ?>> bridgeMap = Collections.emptyMap(); return new Waterfall<OUT, OUT, OUT>(null, bridgeMap, mBridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, null, size, mCurrent, mCurrentGenerator, gates); } /** * Creates and returns a new waterfall generating from this one. * <p/> * Note that the bridges, the size and the currents of this waterfall will be retained. * * @param dataType the data type. * @param <DATA> the data type. * @return the newly created waterfall. * @throws IllegalArgumentException if the data type is null. */ public <DATA> Waterfall<DATA, DATA, DATA> start(final Class<DATA> dataType) { return start(Classification.ofType(dataType)); } /** * Creates and returns a new waterfall generating from this one. * <p/> * Note that the bridges, the size and the currents of this waterfall will be retained. * * @param classification the data classification. * @param <DATA> the data type. * @return the newly created waterfall. * @throws IllegalArgumentException if the data classification is null. */ public <DATA> Waterfall<DATA, DATA, DATA> start(final Classification<DATA> classification) { if (classification == null) { throw new IllegalArgumentException("the waterfall classification cannot be null"); } //noinspection unchecked return (Waterfall<DATA, DATA, DATA>) start(); } /** * Creates and returns a new waterfall chained to the gates returned by the specified * generator. * <p/> * Note that the bridges, the size and the currents of this waterfall will be retained. * * @param generator the gate generator. * @param <NIN> the new input data type. * @param <NOUT> the new output data type. * @return the newly created waterfall. * @throws IllegalArgumentException if the generator is null or returns a null gate. */ public <NIN, NOUT> Waterfall<NIN, NIN, NOUT> start(final GateGenerator<NIN, NOUT> generator) { if (generator == null) { throw new IllegalArgumentException("the waterfall gate generator cannot be null"); } final Map<Classification<?>, BridgeGate<?, ?>> bridgeMap = Collections.emptyMap(); final int size = mSize; //noinspection unchecked final Gate<NIN, NOUT>[] gates = new Gate[size]; if (size <= 1) { final Gate<NIN, NOUT> gate = generator.create(0); registerGate(gate); gates[0] = gate; return new Waterfall<NIN, NIN, NOUT>(null, bridgeMap, mBridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, null, 1, mCurrent, mCurrentGenerator, gates); } if (mBridgeClassification != null) { throw new IllegalStateException("cannot make a bridge from more than one gate"); } for (int i = 0; i < size; ++i) { final Gate<NIN, NOUT> gate = generator.create(i); registerGate(gate); gates[i] = gate; } return new Waterfall<NIN, NIN, NOUT>(null, bridgeMap, null, mBackgroundPoolSize, mBackgroundCurrent, null, size, mCurrent, mCurrentGenerator, gates); } /** * Creates and returns a new waterfall chained to the specified gates. * <p/> * Note that the bridges and the currents of this waterfall will be retained, while the size will * be equal to the one of the specified array. * * @param gates the gate instances. * @param <NIN> the new input data type. * @param <NOUT> the new output data type. * @return the newly created waterfall. * @throws IllegalArgumentException if the gate collection is null or contains a null gate. */ public <NIN, NOUT> Waterfall<NIN, NIN, NOUT> start( final Collection<? extends Gate<NIN, NOUT>> gates) { if (gates == null) { throw new IllegalArgumentException("the waterfall gate collection cannot be null"); } final int length = gates.size(); if (length == 0) { throw new IllegalArgumentException("the waterfall gate collection cannot be empty"); } final Waterfall<SOURCE, IN, OUT> waterfall; if (mSize == length) { waterfall = this; } else { waterfall = in(length); } final Iterator<? extends Gate<NIN, NOUT>> iterator = gates.iterator(); return waterfall.start(new GateGenerator<NIN, NOUT>() { @Override public Gate<NIN, NOUT> create(final int fallNumber) { return iterator.next(); } }); } /** * Creates and returns a new waterfall chained to the specified gate. * <p/> * Note that the bridges, the size and the currents of this waterfall will be retained. * * @param gate the gate instance. * @param <NIN> the new input data type. * @param <NOUT> the new output data type. * @return the newly created waterfall. * @throws IllegalArgumentException if the gate is null. */ public <NIN, NOUT> Waterfall<NIN, NIN, NOUT> start(final Gate<NIN, NOUT> gate) { registerGate(gate); final Map<Classification<?>, BridgeGate<?, ?>> bridgeMap = Collections.emptyMap(); //noinspection unchecked final Gate<NIN, NOUT>[] gates = new Gate[]{gate}; return new Waterfall<NIN, NIN, NOUT>(null, bridgeMap, mBridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, null, mSize, mCurrent, mCurrentGenerator, gates); } /** * Makes this waterfall forward an exception in case the specified timeout elapses before at * least one data drop is pushed through it. * <p/> * TODO: starts immediately * * @param timeout the timeout in <code>timeUnit</code> time units. * @param timeUnit the delay time unit. * @param exception the exception to forward. * @return the newly created waterfall. */ public Waterfall<SOURCE, OUT, OUT> throwOnTimeout(final long timeout, final TimeUnit timeUnit, final RuntimeException exception) { return chain(new TimeoutGate<OUT>(this, timeout, timeUnit, exception)); } private Waterfall<SOURCE, OUT, OUT> chainPump(final PumpGate<OUT> pumpGate) { final Waterfall<SOURCE, OUT, OUT> waterfall = chain(pumpGate); return new Waterfall<SOURCE, OUT, OUT>(waterfall.mSource, waterfall.mBridgeMap, waterfall.mBridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, pumpGate, waterfall.mSize, waterfall.mCurrent, waterfall.mCurrentGenerator, waterfall.mFalls); } private BridgeGate<?, ?> findBestMatch(final Classification<?> bridgeClassification) { final Map<Classification<?>, BridgeGate<?, ?>> bridgeMap = mBridgeMap; BridgeGate<?, ?> gate = bridgeMap.get(bridgeClassification); if (gate == null) { Classification<?> bestMatch = null; for (final Entry<Classification<?>, BridgeGate<?, ?>> entry : bridgeMap.entrySet()) { final Classification<?> type = entry.getKey(); if (bridgeClassification.isAssignableFrom(type)) { if ((bestMatch == null) || type.isAssignableFrom(bestMatch)) { gate = entry.getValue(); bestMatch = type; } } } } return gate; } private int getBestPoolSize() { final int processors = Runtime.getRuntime().availableProcessors(); if (processors < 4) { return Math.max(1, processors - 1); } return (processors / 2); } private void mapBridge(final HashMap<Classification<?>, BridgeGate<?, ?>> bridgeMap, final Classification<?> bridgeClassification, final BridgeGate<?, ?> gate) { if (!bridgeClassification.getRawType().isInstance(gate.gate)) { throw new IllegalArgumentException( "the gate does not implement the bridge classification type"); } bridgeMap.put(bridgeClassification, gate); } }
library/src/main/java/com/bmd/wtf/fll/Waterfall.java
/** * 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.bmd.wtf.fll; import com.bmd.wtf.crr.Current; import com.bmd.wtf.crr.CurrentGenerator; import com.bmd.wtf.crr.Currents; import com.bmd.wtf.flw.Bridge; import com.bmd.wtf.flw.Collector; import com.bmd.wtf.flw.Pump; import com.bmd.wtf.flw.River; import com.bmd.wtf.gts.Gate; import com.bmd.wtf.gts.GateGenerator; import com.bmd.wtf.gts.OpenGate; import com.bmd.wtf.spr.Spring; import com.bmd.wtf.spr.SpringGenerator; import com.bmd.wtf.spr.Springs; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.WeakHashMap; import java.util.concurrent.TimeUnit; /** * Here is where everything starts. * <p/> * Each waterfall instance retains a reference to its source so to be available during the building * chain. * <p/> * Created by davide on 6/4/14. * * @param <SOURCE> the waterfall source data type. * @param <IN> the input data type. * @param <OUT> the output data type. */ public class Waterfall<SOURCE, IN, OUT> extends AbstractRiver<IN> { // TODO: bridge, linq(?) // TODO: exception javadoc private static final Comparator<?> NATURAL_COMPARATOR = Collections.reverseOrder(Collections.reverseOrder()); private static final DataFall[] NO_FALL = new DataFall[0]; private static final Classification<Void> SELF_CLASSIFICATION = new Classification<Void>() {}; private static final WeakHashMap<Gate<?, ?>, Void> sGates = new WeakHashMap<Gate<?, ?>, Void>(); private static OpenGate<?> sOpenGate; private final Current mBackgroundCurrent; private final int mBackgroundPoolSize; private final Classification<?> mBridgeClassification; private final Map<Classification<?>, BridgeGate<?, ?>> mBridgeMap; private final Current mCurrent; private final CurrentGenerator mCurrentGenerator; private final DataFall<IN, OUT>[] mFalls; private final PumpGate<?> mPump; private final int mSize; private final Waterfall<SOURCE, SOURCE, ?> mSource; private Waterfall(final Waterfall<SOURCE, SOURCE, ?> source, final Map<Classification<?>, BridgeGate<?, ?>> bridgeMap, final Classification<?> bridgeClassification, final int backgroundPoolSize, final Current backgroundCurrent, final PumpGate<?> pumpGate, final int size, final Current current, final CurrentGenerator generator, final DataFall<IN, OUT>[] falls) { //noinspection unchecked mSource = (source != null) ? source : (Waterfall<SOURCE, SOURCE, ?>) this; mBridgeMap = bridgeMap; mBridgeClassification = bridgeClassification; mBackgroundPoolSize = backgroundPoolSize; mBackgroundCurrent = backgroundCurrent; mPump = pumpGate; mSize = size; mCurrent = current; mCurrentGenerator = generator; mFalls = falls; } private Waterfall(final Waterfall<SOURCE, SOURCE, ?> source, final Map<Classification<?>, BridgeGate<?, ?>> bridgeMap, final Classification<?> bridgeClassification, final int backgroundPoolSize, final Current backgroundCurrent, final PumpGate<?> pumpGate, final int size, final Current current, final CurrentGenerator generator, final Gate<IN, OUT>[] gates) { //noinspection unchecked mSource = (source != null) ? source : (Waterfall<SOURCE, SOURCE, ?>) this; mBridgeClassification = null; mBackgroundPoolSize = backgroundPoolSize; mBackgroundCurrent = backgroundCurrent; mSize = size; mCurrent = current; mCurrentGenerator = generator; final int length = gates.length; final Gate<IN, OUT> wrappedGate; if (bridgeClassification != null) { final Gate<IN, OUT> gate = gates[0]; final HashMap<Classification<?>, BridgeGate<?, ?>> fallBridgeMap = new HashMap<Classification<?>, BridgeGate<?, ?>>(bridgeMap); final BridgeGate<IN, OUT> bridgeGate = new BridgeGate<IN, OUT>(gate); mapBridge(fallBridgeMap, (SELF_CLASSIFICATION == bridgeClassification) ? Classification.ofType( gate.getClass()) : bridgeClassification, bridgeGate); mBridgeMap = fallBridgeMap; wrappedGate = bridgeGate; } else { if (size != length) { wrappedGate = new BarrageGate<IN, OUT>(gates[0]); } else { wrappedGate = null; } mBridgeMap = bridgeMap; } final DataFall[] falls = new DataFall[size]; if (size == 1) { mPump = null; } else { mPump = pumpGate; } final PumpGate<?> fallPump = mPump; for (int i = 0; i < size; ++i) { final Gate<IN, OUT> gate = (wrappedGate != null) ? wrappedGate : gates[i]; final Current fallCurrent; if (current == null) { fallCurrent = generator.create(i); } else { fallCurrent = current; } if (fallPump != null) { falls[i] = new PumpFall<SOURCE, IN, OUT>(this, fallCurrent, gate, i, fallPump); } else { falls[i] = new DataFall<IN, OUT>(this, fallCurrent, gate, i); } } //noinspection unchecked mFalls = (DataFall<IN, OUT>[]) falls; } /** * Creates and returns a new waterfall composed by a single synchronous stream. * * @return the newly created waterfall. */ public static Waterfall<Object, Object, Object> fall() { final Map<Classification<?>, BridgeGate<?, ?>> bridgeMap = Collections.emptyMap(); //noinspection unchecked return new Waterfall<Object, Object, Object>(null, bridgeMap, null, 0, null, null, 1, Currents.passThrough(), null, NO_FALL); } /** * Connects an input and an output fall through a data stream. * * @param inFall the input fall. * @param outFall the output fall. * @param <DATA> the data type. * @return the data stream running between the two falls. * @throws IllegalArgumentException if the input or the output fall are null. */ private static <DATA> DataStream<DATA> connect(final DataFall<?, DATA> inFall, final DataFall<DATA, ?> outFall) { final DataStream<DATA> stream = new DataStream<DATA>(inFall, outFall); outFall.inputStreams.add(stream); inFall.outputStreams.add(stream); return stream; } /** * Lazily creates and return a singleton open gate instance. * * @param <DATA> the data type. * @return the open gate instance. */ private static <DATA> OpenGate<DATA> openGate() { if (sOpenGate == null) { sOpenGate = new OpenGate<Object>(); } //noinspection unchecked return (OpenGate<DATA>) sOpenGate; } /** * Registers the specified gate instance by making sure it is unique among all the created * waterfalls. * * @param gate the gate to register. * @throws IllegalArgumentException if the gate is null or is already registered. */ private static void registerGate(final Gate<?, ?> gate) { if (gate == null) { throw new IllegalArgumentException("the waterfall gate cannot be null"); } if (sGates.containsKey(gate)) { throw new IllegalArgumentException("the waterfall already contains the gate: " + gate); } sGates.put(gate, null); } /** * Tells the waterfall to build a bridge above the next gate chained to it. * <p/> * The bridge type will be the same as the gate raw type. * * @return the newly created waterfall. */ public Waterfall<SOURCE, IN, OUT> bridge() { return bridge(SELF_CLASSIFICATION); } /** * Tells the waterfall to build a bridge of the specified type above the next gate chained to it. * * @param bridgeClass the bridge class. * @return the newly created waterfall. * @throws IllegalArgumentException if the bridge class is null. */ public Waterfall<SOURCE, IN, OUT> bridge(final Class<?> bridgeClass) { return bridge(Classification.ofType(bridgeClass)); } /** * Tells the waterfall to build a bridge of the specified classification type above the next * gate chained to it. * * @param bridgeClassification the bridge classification. * @return the newly created waterfall. * @throws IllegalArgumentException if the bridge classification is null. */ public Waterfall<SOURCE, IN, OUT> bridge(final Classification<?> bridgeClassification) { if (bridgeClassification == null) { throw new IllegalArgumentException("the bridge classification cannot be null"); } return new Waterfall<SOURCE, IN, OUT>(mSource, mBridgeMap, bridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, mPump, mSize, mCurrent, mCurrentGenerator, mFalls); } /** * Chains the gate protected by the bridge of the specified classification type to this * waterfall. * <p/> * Note that contrary to common gate, the ones protected by a bridge can be added several times * to the same waterfall. * * @param bridgeClassification the bridge classification. * @param <NOUT> the new output data type. * @return the newly created waterfall. * @throws IllegalArgumentException if no protected gate is found. */ public <NOUT> Waterfall<SOURCE, OUT, NOUT> chain( final Classification<? extends Gate<OUT, NOUT>> bridgeClassification) { //noinspection unchecked final Gate<OUT, NOUT> gate = (Gate<OUT, NOUT>) findBestMatch(bridgeClassification); if (gate == null) { throw new IllegalArgumentException( "the waterfall does not retain any bridge of classification type " + bridgeClassification); } final DataFall<IN, OUT>[] falls = mFalls; final int size = mSize; //noinspection unchecked final Gate<OUT, NOUT>[] gates = new Gate[size]; if (size == 1) { gates[0] = gate; final Waterfall<SOURCE, OUT, NOUT> waterfall = new Waterfall<SOURCE, OUT, NOUT>(mSource, mBridgeMap, mBridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, mPump, 1, mCurrent, mCurrentGenerator, gates); final DataFall<OUT, NOUT> outFall = waterfall.mFalls[0]; for (final DataFall<IN, OUT> fall : falls) { connect(fall, outFall); } return waterfall; } final int length = falls.length; final Waterfall<SOURCE, ?, OUT> inWaterfall; if ((length != 1) && (length != size)) { inWaterfall = merge(); } else { inWaterfall = this; } Arrays.fill(gates, gate); final Waterfall<SOURCE, OUT, NOUT> waterfall = new Waterfall<SOURCE, OUT, NOUT>(inWaterfall.mSource, inWaterfall.mBridgeMap, inWaterfall.mBridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, mPump, size, inWaterfall.mCurrent, inWaterfall.mCurrentGenerator, gates); final DataFall<?, OUT>[] inFalls = inWaterfall.mFalls; final DataFall<OUT, NOUT>[] outFalls = waterfall.mFalls; if (inFalls.length == 1) { final DataFall<?, OUT> inFall = inFalls[0]; for (final DataFall<OUT, NOUT> outFall : outFalls) { connect(inFall, outFall); } } else { for (int i = 0; i < size; ++i) { connect(inFalls[i], outFalls[i]); } } return waterfall; } /** * Chains an open gate to this waterfall. * * @return the newly created waterfall. */ public Waterfall<SOURCE, OUT, OUT> chain() { final DataFall<IN, OUT>[] falls = mFalls; if (falls == NO_FALL) { //noinspection unchecked return (Waterfall<SOURCE, OUT, OUT>) start(); } final int size = mSize; final OpenGate<OUT> gate = openGate(); //noinspection unchecked final Gate<OUT, OUT>[] gates = new Gate[size]; if (size == 1) { gates[0] = gate; final Waterfall<SOURCE, OUT, OUT> waterfall = new Waterfall<SOURCE, OUT, OUT>(mSource, mBridgeMap, mBridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, mPump, 1, mCurrent, mCurrentGenerator, gates); final DataFall<OUT, OUT> outFall = waterfall.mFalls[0]; for (final DataFall<IN, OUT> fall : falls) { connect(fall, outFall); } return waterfall; } final int length = falls.length; final Waterfall<SOURCE, ?, OUT> inWaterfall; if ((length != 1) && (length != size)) { inWaterfall = merge(); } else { inWaterfall = this; } Arrays.fill(gates, gate); final Waterfall<SOURCE, OUT, OUT> waterfall = new Waterfall<SOURCE, OUT, OUT>(inWaterfall.mSource, inWaterfall.mBridgeMap, inWaterfall.mBridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, mPump, size, inWaterfall.mCurrent, inWaterfall.mCurrentGenerator, gates); final DataFall<?, OUT>[] inFalls = inWaterfall.mFalls; final DataFall<OUT, OUT>[] outFalls = waterfall.mFalls; if (inFalls.length == 1) { final DataFall<?, OUT> inFall = inFalls[0]; for (final DataFall<OUT, OUT> outFall : outFalls) { connect(inFall, outFall); } } else { for (int i = 0; i < size; ++i) { connect(inFalls[i], outFalls[i]); } } return waterfall; } /** * Chains the specified gates to this waterfall. * <p/> * Note that calling this method will have the same effect as calling first * <code>in(gates.length)</code>. * * @param gates the gate instances. * @param <NOUT> the new output data type. * @return the newly created waterfall. * @throws IllegalArgumentException if the gate collection is null, empty or contains null * instances or instances already chained to this or another * waterfall. */ public <NOUT> Waterfall<SOURCE, OUT, NOUT> chain( final Collection<? extends Gate<OUT, NOUT>> gates) { if (gates == null) { throw new IllegalArgumentException("the waterfall gate collection cannot be null"); } final int length = gates.size(); if (length == 0) { throw new IllegalArgumentException("the waterfall gate collection cannot be empty"); } final Waterfall<SOURCE, IN, OUT> waterfall; if (mSize == length) { waterfall = this; } else { waterfall = in(length); } final Iterator<? extends Gate<OUT, NOUT>> iterator = gates.iterator(); return waterfall.chain(new GateGenerator<OUT, NOUT>() { @Override public Gate<OUT, NOUT> create(final int fallNumber) { return iterator.next(); } }); } /** * Chains the specified gate to this waterfall. * <p/> * Note that in case this waterfall is composed by more then one data stream, all the data * flowing through them will be passed to the specified gate. * * @param gate the gate instance. * @param <NOUT> the new output data type. * @return the newly created waterfall. * @throws IllegalArgumentException if the gate is null or already chained to this or another * waterfall. */ public <NOUT> Waterfall<SOURCE, OUT, NOUT> chain(final Gate<OUT, NOUT> gate) { final DataFall<IN, OUT>[] falls = mFalls; if (falls == NO_FALL) { //noinspection unchecked return (Waterfall<SOURCE, OUT, NOUT>) start(gate); } final int size = mSize; //noinspection unchecked final Gate<OUT, NOUT>[] gates = new Gate[]{gate}; if (size == 1) { registerGate(gate); final Waterfall<SOURCE, OUT, NOUT> waterfall = new Waterfall<SOURCE, OUT, NOUT>(mSource, mBridgeMap, mBridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, mPump, 1, mCurrent, mCurrentGenerator, gates); final DataFall<OUT, NOUT> outFall = waterfall.mFalls[0]; for (final DataFall<IN, OUT> fall : falls) { connect(fall, outFall); } return waterfall; } final int length = falls.length; final Waterfall<SOURCE, ?, OUT> inWaterfall; if ((length != 1) && (length != size)) { inWaterfall = merge(); } else { inWaterfall = this; } registerGate(gate); final Waterfall<SOURCE, OUT, NOUT> waterfall = new Waterfall<SOURCE, OUT, NOUT>(inWaterfall.mSource, inWaterfall.mBridgeMap, inWaterfall.mBridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, mPump, size, inWaterfall.mCurrent, inWaterfall.mCurrentGenerator, gates); final DataFall<?, OUT>[] inFalls = inWaterfall.mFalls; final DataFall<OUT, NOUT>[] outFalls = waterfall.mFalls; if (inFalls.length == 1) { final DataFall<?, OUT> inFall = inFalls[0]; for (final DataFall<OUT, NOUT> outFall : outFalls) { connect(inFall, outFall); } } else { for (int i = 0; i < size; ++i) { connect(inFalls[i], outFalls[i]); } } return waterfall; } /** * Chains the gates returned by the specified generator to this waterfall. * <p/> * Note that in case this waterfall is composed by more then one data stream, each gate created * by the generator will handle a single stream. * * @param generator the gate generator. * @param <NOUT> the new output data type. * @return the newly created waterfall. * @throws IllegalArgumentException if the generator is null or returns a null gate or one * already chained to this or another waterfall. */ public <NOUT> Waterfall<SOURCE, OUT, NOUT> chain(final GateGenerator<OUT, NOUT> generator) { if (generator == null) { throw new IllegalArgumentException("the waterfall generator cannot be null"); } final DataFall<IN, OUT>[] falls = mFalls; if (falls == NO_FALL) { //noinspection unchecked return (Waterfall<SOURCE, OUT, NOUT>) start(generator); } final int size = mSize; //noinspection unchecked final Gate<OUT, NOUT>[] gates = new Gate[size]; if (size == 1) { final Gate<OUT, NOUT> gate = generator.create(0); registerGate(gate); gates[0] = gate; final Waterfall<SOURCE, OUT, NOUT> waterfall = new Waterfall<SOURCE, OUT, NOUT>(mSource, mBridgeMap, mBridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, mPump, 1, mCurrent, mCurrentGenerator, gates); final DataFall<OUT, NOUT> outFall = waterfall.mFalls[0]; for (final DataFall<IN, OUT> fall : falls) { connect(fall, outFall); } return waterfall; } if (mBridgeClassification != null) { throw new IllegalStateException("cannot make a bridge from more than one gate"); } final int length = falls.length; final Waterfall<SOURCE, ?, OUT> inWaterfall; if ((length != 1) && (length != size)) { inWaterfall = merge(); } else { inWaterfall = this; } for (int i = 0; i < size; ++i) { final Gate<OUT, NOUT> gate = generator.create(i); registerGate(gate); gates[i] = gate; } final Waterfall<SOURCE, OUT, NOUT> waterfall = new Waterfall<SOURCE, OUT, NOUT>(inWaterfall.mSource, inWaterfall.mBridgeMap, inWaterfall.mBridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, mPump, size, inWaterfall.mCurrent, inWaterfall.mCurrentGenerator, gates); final DataFall<?, OUT>[] inFalls = inWaterfall.mFalls; final DataFall<OUT, NOUT>[] outFalls = waterfall.mFalls; if (inFalls.length == 1) { final DataFall<?, OUT> inFall = inFalls[0]; for (final DataFall<OUT, NOUT> outFall : outFalls) { connect(inFall, outFall); } } else { for (int i = 0; i < size; ++i) { connect(inFalls[i], outFalls[i]); } } return waterfall; } /** * Tells the waterfall to close the bridge handling the specified gate, that is, the bridge * will not be accessible anymore to the ones requiring it. * * @param gate the gate instance. * @param <TYPE> the gate type. * @return the newly created waterfall. */ public <TYPE extends Gate<?, ?>> Waterfall<SOURCE, IN, OUT> close(final TYPE gate) { if (gate == null) { return this; } boolean isChanged = false; final HashMap<Classification<?>, BridgeGate<?, ?>> bridgeMap = new HashMap<Classification<?>, BridgeGate<?, ?>>(mBridgeMap); final Iterator<BridgeGate<?, ?>> iterator = bridgeMap.values().iterator(); while (iterator.hasNext()) { if (gate == iterator.next().gate) { iterator.remove(); isChanged = true; } } if (!isChanged) { return this; } return new Waterfall<SOURCE, IN, OUT>(mSource, bridgeMap, mBridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, mPump, mSize, mCurrent, mCurrentGenerator, mFalls); } /** * Tells the waterfall to close the bridge of the specified classification type, that is, the bridge * will not be accessible anymore to the ones requiring it. * * @param bridgeClassification the bridge classification. * @param <TYPE> the gate type. * @return the newly created waterfall. */ public <TYPE> Waterfall<SOURCE, IN, OUT> close( final Classification<TYPE> bridgeClassification) { final BridgeGate<?, ?> bridge = findBestMatch(bridgeClassification); if (bridge == null) { return this; } final HashMap<Classification<?>, BridgeGate<?, ?>> bridgeMap = new HashMap<Classification<?>, BridgeGate<?, ?>>(mBridgeMap); final Iterator<BridgeGate<?, ?>> iterator = bridgeMap.values().iterator(); while (iterator.hasNext()) { if (bridge == iterator.next()) { iterator.remove(); } } return new Waterfall<SOURCE, IN, OUT>(mSource, bridgeMap, mBridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, mPump, mSize, mCurrent, mCurrentGenerator, mFalls); } /** * Creates and returns a new data collector. * * @return the collector. * @throws IllegalStateException if this waterfall was not started. */ public Collector<OUT> collect() { if (mFalls == NO_FALL) { throw new IllegalStateException("cannot collect data from a not started waterfall"); } final CollectorGate<OUT> collectorGate = new CollectorGate<OUT>(); final BridgeGate<OUT, OUT> bridgeGate = new BridgeGate<OUT, OUT>(collectorGate); final Waterfall<SOURCE, IN, OUT> waterfall; if (mSize != 1) { waterfall = in(1); } else { waterfall = this; } waterfall.chain(bridgeGate); return new DataCollector<OUT>(bridgeGate, collectorGate); } /** * Causes the data drops flowing through this waterfall streams to be concatenated, so that all * the data coming from the stream number 0 will come before the ones coming from the stream * number 1, and so on.<br/> * The resulting waterfall will have size equal to 1. * <p/> * Note that the returned waterfall internally cache the data pushed through it and then * discharge them on the first flush. * * @return the newly created waterfall. */ public Waterfall<SOURCE, OUT, OUT> concat() { return chain(new CumulativeCacheGate<OUT, OUT>(size()) { @Override protected void onClear(final List<List<OUT>> cache, final River<OUT> upRiver, final River<OUT> downRiver) { for (final List<OUT> data : cache) { downRiver.push(data); } super.onClear(cache, upRiver, downRiver); } }).merge(); } /** * Causes the data drops flowing through this waterfall to be delayed of the specified time. * <p/> * Note that the returned waterfall internally cache the data pushed through it and then * discharge them on the first flush. * * @param delay the delay in <code>timeUnit</code> time units. * @param timeUnit the delay time unit. * @return the newly created waterfall. */ public Waterfall<SOURCE, OUT, OUT> delay(final long delay, final TimeUnit timeUnit) { return chain(new CacheGate<OUT, OUT>(size()) { @Override protected void onClear(final List<OUT> cache, final int streamNumber, final River<OUT> upRiver, final River<OUT> downRiver) { downRiver.pushAfter(delay, timeUnit, cache); super.onClear(cache, streamNumber, upRiver, downRiver); } }); } @Override public void deviate() { for (final DataFall<IN, OUT> fall : mFalls) { for (final DataStream<OUT> stream : fall.outputStreams) { stream.deviate(); } } } @Override public void deviateStream(final int streamNumber) { final DataFall<IN, OUT> fall = mFalls[streamNumber]; for (final DataStream<OUT> stream : fall.outputStreams) { stream.deviate(); } } @Override public void drain() { for (final DataFall<IN, OUT> fall : mFalls) { for (final DataStream<OUT> stream : fall.outputStreams) { stream.drain(Direction.DOWNSTREAM); } } } @Override public void drainStream(final int streamNumber) { final DataFall<IN, OUT> fall = mFalls[streamNumber]; for (final DataStream<OUT> stream : fall.outputStreams) { stream.drain(Direction.DOWNSTREAM); } } @Override public Waterfall<SOURCE, IN, OUT> exception(final Throwable throwable) { for (final DataFall<IN, OUT> fall : mFalls) { fall.raiseLevel(1); fall.inputCurrent.exception(fall, throwable); } return this; } @Override public Waterfall<SOURCE, IN, OUT> flush() { for (final DataFall<IN, OUT> fall : mFalls) { fall.inputCurrent.flush(fall, null); } return this; } @Override public Waterfall<SOURCE, IN, OUT> push(final IN... drops) { if ((drops == null) || (drops.length == 0)) { return this; } final DataFall<IN, OUT>[] falls = mFalls; for (final IN drop : drops) { for (final DataFall<IN, OUT> fall : falls) { fall.raiseLevel(1); fall.inputCurrent.push(fall, drop); } } return this; } @Override public Waterfall<SOURCE, IN, OUT> push(final Iterable<? extends IN> drops) { if (drops == null) { return this; } final DataFall<IN, OUT>[] falls = mFalls; for (final IN drop : drops) { for (final DataFall<IN, OUT> fall : falls) { fall.raiseLevel(1); fall.inputCurrent.push(fall, drop); } } return this; } @Override public Waterfall<SOURCE, IN, OUT> push(final IN drop) { for (final DataFall<IN, OUT> fall : mFalls) { fall.raiseLevel(1); fall.inputCurrent.push(fall, drop); } return this; } @Override public Waterfall<SOURCE, IN, OUT> pushAfter(final long delay, final TimeUnit timeUnit, final Iterable<? extends IN> drops) { if (drops == null) { return this; } final ArrayList<IN> list = new ArrayList<IN>(); for (final IN drop : drops) { list.add(drop); } if (!list.isEmpty()) { final int size = list.size(); for (final DataFall<IN, OUT> fall : mFalls) { fall.raiseLevel(size); fall.inputCurrent.pushAfter(fall, delay, timeUnit, list); } } return this; } @Override public Waterfall<SOURCE, IN, OUT> pushAfter(final long delay, final TimeUnit timeUnit, final IN drop) { for (final DataFall<IN, OUT> fall : mFalls) { fall.raiseLevel(1); fall.inputCurrent.pushAfter(fall, delay, timeUnit, drop); } return this; } @Override public Waterfall<SOURCE, IN, OUT> pushAfter(final long delay, final TimeUnit timeUnit, final IN... drops) { if ((drops == null) || (drops.length == 0)) { return this; } final ArrayList<IN> list = new ArrayList<IN>(Arrays.asList(drops)); for (final DataFall<IN, OUT> fall : mFalls) { fall.raiseLevel(drops.length); fall.inputCurrent.pushAfter(fall, delay, timeUnit, list); } return this; } @Override public Waterfall<SOURCE, IN, OUT> flushStream(final int streamNumber) { final DataFall<IN, OUT> fall = mFalls[streamNumber]; fall.inputCurrent.flush(fall, null); return this; } @Override public <TYPE> Bridge<TYPE> on(final Class<TYPE> bridgeClass) { return on(Classification.ofType(bridgeClass)); } @Override public <TYPE> Bridge<TYPE> on(final TYPE gate) { if (gate == null) { throw new IllegalArgumentException("the bridge gate cannot be null"); } BridgeGate<?, ?> bridge = null; final Map<Classification<?>, BridgeGate<?, ?>> bridgeMap = mBridgeMap; for (final BridgeGate<?, ?> bridgeGate : bridgeMap.values()) { if (bridgeGate.gate == gate) { bridge = bridgeGate; break; } } if (bridge == null) { throw new IllegalArgumentException("the waterfall does not retain the bridge " + gate); } return new DataBridge<TYPE>(bridge, new Classification<TYPE>() {}); } @Override public <TYPE> Bridge<TYPE> on(final Classification<TYPE> bridgeClassification) { final BridgeGate<?, ?> bridge = findBestMatch(bridgeClassification); if (bridge == null) { throw new IllegalArgumentException( "the waterfall does not retain any bridge of classification type " + bridgeClassification); } return new DataBridge<TYPE>(bridge, bridgeClassification); } @Override public Waterfall<SOURCE, IN, OUT> pushStream(final int streamNumber, final IN... drops) { if ((drops == null) || (drops.length == 0)) { return this; } final DataFall<IN, OUT> fall = mFalls[streamNumber]; fall.raiseLevel(drops.length); for (final IN drop : drops) { fall.inputCurrent.push(fall, drop); } return this; } @Override public Waterfall<SOURCE, IN, OUT> pushStream(final int streamNumber, final Iterable<? extends IN> drops) { if (drops == null) { return this; } int size = 0; for (final IN ignored : drops) { ++size; } if (size > 0) { final DataFall<IN, OUT> fall = mFalls[streamNumber]; fall.raiseLevel(size); for (final IN drop : drops) { fall.inputCurrent.push(fall, drop); } } return this; } @Override public Waterfall<SOURCE, IN, OUT> pushStream(final int streamNumber, final IN drop) { final DataFall<IN, OUT> fall = mFalls[streamNumber]; fall.raiseLevel(1); fall.inputCurrent.push(fall, drop); return this; } @Override public Waterfall<SOURCE, IN, OUT> pushStreamAfter(final int streamNumber, final long delay, final TimeUnit timeUnit, final Iterable<? extends IN> drops) { if (drops == null) { return this; } final ArrayList<IN> list = new ArrayList<IN>(); for (final IN drop : drops) { list.add(drop); } if (!list.isEmpty()) { final DataFall<IN, OUT> fall = mFalls[streamNumber]; fall.raiseLevel(list.size()); fall.inputCurrent.pushAfter(fall, delay, timeUnit, list); } return this; } @Override public Waterfall<SOURCE, IN, OUT> pushStreamAfter(final int streamNumber, final long delay, final TimeUnit timeUnit, final IN drop) { final DataFall<IN, OUT> fall = mFalls[streamNumber]; fall.raiseLevel(1); fall.inputCurrent.pushAfter(fall, delay, timeUnit, drop); return this; } @Override public Waterfall<SOURCE, IN, OUT> pushStreamAfter(final int streamNumber, final long delay, final TimeUnit timeUnit, final IN... drops) { if ((drops == null) || (drops.length == 0)) { return this; } final DataFall<IN, OUT> fall = mFalls[streamNumber]; fall.raiseLevel(drops.length); fall.inputCurrent.pushAfter(fall, delay, timeUnit, new ArrayList<IN>(Arrays.asList(drops))); return this; } @Override public int size() { return mFalls.length; } @Override public Waterfall<SOURCE, IN, OUT> streamException(final int streamNumber, final Throwable throwable) { final DataFall<IN, OUT> fall = mFalls[streamNumber]; fall.raiseLevel(1); fall.inputCurrent.exception(fall, throwable); return this; } /** * Deviates the flow of this waterfall, either downstream or upstream, by effectively * preventing any coming data to be pushed further. * * @param direction whether the waterfall must be deviated downstream or upstream. * @see #deviateStream(int, com.bmd.wtf.flw.Stream.Direction) */ public void deviate(final Direction direction) { if (direction == Direction.DOWNSTREAM) { deviate(); } else { for (final DataFall<IN, OUT> fall : mFalls) { for (final DataStream<IN> stream : fall.inputStreams) { stream.deviate(); } } } } /** * Deviates the flow of the specified waterfall stream, either downstream or upstream, by * effectively preventing any coming data to be pushed further. * * @param streamNumber the number identifying the target stream. * @param direction whether the waterfall must be deviated downstream or upstream. * @see #deviate(com.bmd.wtf.flw.Stream.Direction) */ public void deviateStream(final int streamNumber, final Direction direction) { if (direction == Direction.DOWNSTREAM) { deviateStream(streamNumber); } else { final DataFall<IN, OUT> fall = mFalls[streamNumber]; for (final DataStream<IN> stream : fall.inputStreams) { stream.deviate(); } } } /** * Uniformly distributes all the data flowing through this waterfall in the different output * streams. * * @return the newly created waterfall. */ public Waterfall<SOURCE, OUT, OUT> distribute() { final DataFall<IN, OUT>[] falls = mFalls; if (falls == NO_FALL) { //noinspection unchecked return (Waterfall<SOURCE, OUT, OUT>) start().distribute(); } final int size = mSize; if (size == 1) { return chain(); } return in(1).chainPump(new PumpGate<OUT>(size)).in(size).chain(); } /** * Distributes all the data flowing through this waterfall in the different output streams by * means of the specified pump. * * @return the newly created waterfall. * @throws IllegalArgumentException if the pump is null. */ public Waterfall<SOURCE, OUT, OUT> distribute(final Pump<OUT> pump) { if (pump == null) { throw new IllegalArgumentException("the waterfall pump cannot be null"); } final DataFall<IN, OUT>[] falls = mFalls; if (falls == NO_FALL) { //noinspection unchecked return (Waterfall<SOURCE, OUT, OUT>) start().distribute(pump); } final int size = mSize; if (size == 1) { return chain(); } return in(1).chainPump(new PumpGate<OUT>(pump, size)).in(size).chain(); } /** * Drains the waterfall, either downstream or upstream, by removing all the falls and rivers * fed only by this waterfall streams. * * @param direction whether the waterfall must be deviated downstream or upstream. * @see #drainStream(int, com.bmd.wtf.flw.Stream.Direction) */ public void drain(final Direction direction) { if (direction == Direction.DOWNSTREAM) { drain(); } else { for (final DataFall<IN, OUT> fall : mFalls) { for (final DataStream<IN> stream : fall.inputStreams) { stream.drain(direction); } } } } /** * Drains the specified waterfall stream, either downstream or upstream, by removing from all * the falls and rivers fed only by the specific stream. * * @param streamNumber the number identifying the target stream. * @param direction whether the waterfall must be deviated downstream or upstream. * @see #drain(com.bmd.wtf.flw.Stream.Direction) */ public void drainStream(final int streamNumber, final Direction direction) { if (direction == Direction.DOWNSTREAM) { drainStream(streamNumber); } else { final DataFall<IN, OUT> fall = mFalls[streamNumber]; for (final DataStream<IN> stream : fall.inputStreams) { stream.drain(direction); } } } /** * Filters the data flowing through this waterfall by retaining only the specified count of * drops, starting from the last minus the specified offset and discarding the other ones. * <p/> * Note that the returned waterfall internally cache the data pushed through it and then * discharge them on the first flush. * * @param endOffset the offset from the last data drop before a flush. * @param count the count of the element in the range. * @return the newly created waterfall. * @throws IllegalArgumentException if the offset is negative, the count is negative or equal * to zero or is greater than the offset + 1. */ public Waterfall<SOURCE, OUT, OUT> endRange(final int endOffset, final int count) { if ((endOffset < 0) || (count <= 0) || (count > (endOffset + 1))) { throw new IllegalArgumentException("invalid range indexes"); } final long maxSize = (long) endOffset + 1; final int length = Math.max(size(), 1); final long[] counts = new long[length]; //noinspection unchecked final ArrayList<OUT>[] lists = new ArrayList[length]; for (int i = 0; i < lists.length; i++) { lists[i] = new ArrayList<OUT>(); } return chain(new OpenGate<OUT>() { @Override public void onPush(final River<OUT> upRiver, final River<OUT> downRiver, final int fallNumber, final OUT drop) { ++counts[fallNumber]; final ArrayList<OUT> list = lists[fallNumber]; list.add(drop); if (list.size() > maxSize) { list.remove(0); } } @Override public void onFlush(final River<OUT> upRiver, final River<OUT> downRiver, final int fallNumber) { final long index = counts[fallNumber]; final ArrayList<OUT> list = lists[fallNumber]; if (index > (maxSize - count)) { downRiver.push(list.subList(0, count + (int) Math.min(0, index - maxSize))); } list.clear(); super.onFlush(upRiver, downRiver, fallNumber); } }); } /** * Makes this waterfall feed the specified one. After the call, all the data flowing through * this waterfall will be pushed into the target one. * * @param waterfall the waterfall to chain. * @throws IllegalArgumentException if the waterfall is null or equal to this one, or this or * the target one was not started, or if a possible closed * loop in the waterfall chain is detected. */ public void feed(final Waterfall<?, OUT, ?> waterfall) { if (waterfall == null) { throw new IllegalArgumentException("the waterfall cannot be null"); } if (this == waterfall) { throw new IllegalArgumentException("cannot feed a waterfall with itself"); } final DataFall<IN, OUT>[] falls = mFalls; if ((falls == NO_FALL) || (waterfall.mFalls == NO_FALL)) { throw new IllegalStateException("cannot feed a not started waterfall"); } final int size = waterfall.mSize; final int length = falls.length; final DataFall<OUT, ?>[] outFalls = waterfall.mFalls; for (final DataFall<OUT, ?> outFall : outFalls) { for (final DataStream<?> outputStream : outFall.outputStreams) { //noinspection unchecked if (outputStream.canReach(Arrays.asList(falls))) { throw new IllegalArgumentException( "a possible loop in the waterfall chain has been detected"); } } } if (size == 1) { final DataFall<OUT, ?> outFall = outFalls[0]; for (final DataFall<IN, OUT> fall : falls) { connect(fall, outFall); } } else { final Waterfall<SOURCE, ?, OUT> inWaterfall; if ((length != 1) && (length != size)) { inWaterfall = merge(); } else { inWaterfall = this; } final DataFall<?, OUT>[] inFalls = inWaterfall.mFalls; if (inFalls.length == 1) { final DataFall<?, OUT> inFall = inFalls[0]; for (final DataFall<OUT, ?> outFall : outFalls) { connect(inFall, outFall); } } else { for (int i = 0; i < size; ++i) { connect(inFalls[i], outFalls[i]); } } } } /** * Makes this waterfall feed the stream identified by the specified number. After the call, all * the data flowing through this waterfall will be pushed into the target stream. * * @param streamNumber the number identifying the target stream. * @param waterfall the target waterfall. * @throws IllegalArgumentException if the waterfall is null or equal to this one, or this or * the target one was not started, or if a possible closed * loop in the waterfall chain is detected. */ public void feedStream(final int streamNumber, final Waterfall<?, OUT, ?> waterfall) { if (waterfall == null) { throw new IllegalArgumentException("the waterfall cannot be null"); } if (this == waterfall) { throw new IllegalArgumentException("cannot feed a waterfall with itself"); } final DataFall<IN, OUT>[] falls = mFalls; if ((falls == NO_FALL) || (waterfall.mFalls == NO_FALL)) { throw new IllegalStateException("cannot feed a waterfall with a not started one"); } final DataFall<OUT, ?> outFall = waterfall.mFalls[streamNumber]; for (final DataStream<?> outputStream : outFall.outputStreams) { //noinspection unchecked if (outputStream.canReach(Arrays.asList(falls))) { throw new IllegalArgumentException( "a possible loop in the waterfall chain has been detected"); } } for (final DataFall<IN, OUT> fall : falls) { connect(fall, outFall); } } /** * Causes the data drops flowing through this waterfall streams to be merged into a single * collection. * * @return the newly created waterfall. */ public Waterfall<SOURCE, OUT, List<OUT>> flat() { return chain(new CacheGate<OUT, List<OUT>>(size()) { @Override protected void onClear(final List<OUT> cache, final int streamNumber, final River<OUT> upRiver, final River<List<OUT>> downRiver) { downRiver.push(new ArrayList<OUT>(cache)); super.onClear(cache, streamNumber, upRiver, downRiver); } }); } /** * Makes the waterfall streams flow through the currents returned by the specified generator. * * @param generator the current generator * @return the newly created waterfall. * @throws IllegalArgumentException if the generator is null or returns a null current. */ public Waterfall<SOURCE, IN, OUT> in(final CurrentGenerator generator) { if (generator == null) { throw new IllegalArgumentException("the waterfall current generator cannot be null"); } return new Waterfall<SOURCE, IN, OUT>(mSource, mBridgeMap, mBridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, mPump, mSize, null, generator, mFalls); } /** * Splits the waterfall in the specified number of streams. * * @param fallCount the total fall count generating the waterfall. * @return the newly created waterfall. * @throws IllegalArgumentException if the fall count is negative or 0. */ public Waterfall<SOURCE, IN, OUT> in(final int fallCount) { if (fallCount <= 0) { throw new IllegalArgumentException("the fall count cannot be negative or zero"); } return new Waterfall<SOURCE, IN, OUT>(mSource, mBridgeMap, mBridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, mPump, fallCount, mCurrent, mCurrentGenerator, mFalls); } /** * Makes the waterfall streams flow through the specified current. * * @param current the current. * @return the newly created waterfall. * @throws IllegalArgumentException if the current is null. */ public Waterfall<SOURCE, IN, OUT> in(final Current current) { if (current == null) { throw new IllegalArgumentException("the waterfall current cannot be null"); } return new Waterfall<SOURCE, IN, OUT>(mSource, mBridgeMap, mBridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, mPump, mSize, current, null, mFalls); } /** * Makes the waterfall streams flow through a background current. * <p/> * The optimum thread pool size will be automatically computed based on the available resources * and the waterfall size. * <p/> * Note also that the same background current will be retained through the waterfall. * * @param fallCount the total fall count generating the waterfall. * @return the newly created waterfall. * @throws IllegalArgumentException if the fall count is negative or 0. */ public Waterfall<SOURCE, IN, OUT> inBackground(final int fallCount) { if (fallCount <= 0) { throw new IllegalArgumentException("the fall count cannot be negative or zero"); } final int poolSize; final Current backgroundCurrent; if (mBackgroundCurrent == null) { poolSize = getBestPoolSize(); backgroundCurrent = Currents.pool(poolSize); } else { poolSize = mBackgroundPoolSize; backgroundCurrent = mBackgroundCurrent; } return new Waterfall<SOURCE, IN, OUT>(mSource, mBridgeMap, mBridgeClassification, poolSize, backgroundCurrent, mPump, fallCount, backgroundCurrent, null, mFalls); } /** * Makes the waterfall streams flow through a background current. * <p/> * The optimum thread pool size will be automatically computed based on the available resources * and the waterfall size, and the total fall count of the resulting waterfall will be * accordingly dimensioned. * <p/> * Note also that the same background current will be retained through the waterfall. * * @return the newly created waterfall. */ public Waterfall<SOURCE, IN, OUT> inBackground() { final int poolSize; final Current backgroundCurrent; if (mBackgroundCurrent == null) { poolSize = getBestPoolSize(); backgroundCurrent = Currents.pool(poolSize); } else { poolSize = mBackgroundPoolSize; backgroundCurrent = mBackgroundCurrent; } return new Waterfall<SOURCE, IN, OUT>(mSource, mBridgeMap, mBridgeClassification, poolSize, backgroundCurrent, mPump, poolSize, backgroundCurrent, null, mFalls); } /** * Causes the data drops flowing through this waterfall streams to be interleaved, so that the * first drop coming from the stream number 0 will come before the first one coming from the * stream number 1, and so on.<br/> * The resulting waterfall will have size equal to 1. * <p/> * Note that the returned waterfall internally cache the data pushed through it and then * discharge them on the first flush. * * @return the newly created waterfall. */ public Waterfall<SOURCE, OUT, OUT> interleave() { return chain(new CumulativeCacheGate<OUT, OUT>(size()) { @Override protected void onClear(final List<List<OUT>> cache, final River<OUT> upRiver, final River<OUT> downRiver) { boolean empty = false; while (!empty) { empty = true; for (final List<OUT> data : cache) { if (!data.isEmpty()) { empty = false; downRiver.push(data.remove(0)); } } } super.onClear(cache, upRiver, downRiver); } }).merge(); } /** * Makes this waterfall join the specified one, so that all the data coming from this * waterfall N streams will flow through the first N streams of the resulting waterfall, and * the ones coming from the specified waterfall streams will flow through the streams N + 1, N * + 2, ..., etc. * <p/> * TODO how to handle the bridges? * <p/> * Note that the bridges, the size and the currents of this waterfall will be retained. * * @param waterfall the waterfall to join. * @return the newly created waterfall. * @throws IllegalArgumentException if the waterfall is null. */ public Waterfall<OUT, OUT, OUT> join(final Waterfall<?, ?, OUT> waterfall) { if (waterfall == null) { throw new IllegalArgumentException("the waterfall cannot be null"); } return join(Collections.singleton(waterfall)); } /** * Makes this waterfall join the specified ones, so that all the data coming from this * waterfall N streams will flow through the first N streams of the resulting waterfall, the * ones coming from the streams of the first waterfall in the specified collection will flow * through the streams N + 1, N + 2, ..., etc., and so on. * <p/> * TODO how to handle the bridges? * <p/> * Note that the bridges, the size and the currents of this waterfall will be retained. * * @param waterfalls the collection of the waterfall to join. * @return the newly created waterfall. * @throws IllegalArgumentException if the waterfall collection is null or contains null * waterfalls. */ public Waterfall<OUT, OUT, OUT> join( final Collection<? extends Waterfall<?, ?, OUT>> waterfalls) { if (waterfalls == null) { throw new IllegalArgumentException("the waterfall collection cannot be null"); } final ArrayList<Waterfall<?, ?, OUT>> inWaterfalls = new ArrayList<Waterfall<?, ?, OUT>>(waterfalls.size() + 1); int totSize = 0; if (mFalls == NO_FALL) { totSize += 1; inWaterfalls.add(start()); } else { totSize += size(); inWaterfalls.add(this); } for (final Waterfall<?, ?, OUT> waterfall : waterfalls) { if (waterfall.mFalls == NO_FALL) { totSize += 1; inWaterfalls.add(waterfall.start()); } else { totSize += waterfall.size(); inWaterfalls.add(waterfall); } } final OpenGate<OUT> gate = openGate(); //noinspection unchecked final Gate<OUT, OUT>[] gates = new Gate[totSize]; Arrays.fill(gates, gate); final Waterfall<OUT, OUT, OUT> waterfall = new Waterfall<OUT, OUT, OUT>(null, mBridgeMap, mBridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, mPump, totSize, mCurrent, mCurrentGenerator, gates); int number = 0; final DataFall<OUT, OUT>[] outFalls = waterfall.mFalls; for (final Waterfall<?, ?, OUT> inWaterfall : inWaterfalls) { for (final DataFall<?, OUT> inFall : inWaterfall.mFalls) { connect(inFall, outFalls[number++]); } } return waterfall; } /** * Causes the data drops flowing through this waterfall streams to be merged into a single * stream.<br/> * The resulting waterfall will have size equal to 1. * * @return the newly created waterfall. */ public Waterfall<SOURCE, OUT, OUT> merge() { if (mFalls.length > 1) { return in(1).chain(); } return chain(); } /** * Creates and returns a new data collector after flushing this waterfall source. * * @return the collector. * @throws IllegalStateException if this waterfall was not started. */ public Collector<OUT> pull() { final Collector<OUT> collector = collect(); source().flush(); return collector; } /** * Creates and returns a new data collector after pushing the specified data into this * waterfall source and then flushing it. * * @param source the source data. * @return the collector. * @throws IllegalStateException if this waterfall was not started. */ public Collector<OUT> pull(final SOURCE source) { final Collector<OUT> collector = collect(); source().push(source).flush(); return collector; } /** * Creates and returns a new data collector after pushing the specified data into this * waterfall source and then flushing it. * * @param sources the source data. * @return the collector. * @throws IllegalStateException if this waterfall was not started. */ public Collector<OUT> pull(final SOURCE... sources) { final Collector<OUT> collector = collect(); source().push(sources).flush(); return collector; } /** * Creates and returns a new data collector after pushing the data returned by the specified * iterable into this waterfall source and then flushing it. * * @param sources the source data iterable. * @return the collector. * @throws IllegalStateException if this waterfall was not started. */ public Collector<OUT> pull(final Iterable<SOURCE> sources) { final Collector<OUT> collector = collect(); source().push(sources).flush(); return collector; } /** * Filters the data flowing through this waterfall by retaining only the specified count of * drops, starting from the specified offset and discarding the other ones. * <p/> * Note that the returned waterfall internally cache the data pushed through it and then * discharge them on the first flush. * * @param offset the offset from the first data drop. * @param count the count of the element in the range. * @return the newly created waterfall. * @throws IllegalArgumentException if the offset is negative, the count is negative or equal * to zero. */ public Waterfall<SOURCE, OUT, OUT> range(final int offset, final int count) { if ((offset < 0) || (count <= 0)) { throw new IllegalArgumentException("invalid range indexes"); } final long last = (long) offset + (long) count; final int length = Math.max(size(), 1); final long[] counts = new long[length]; //noinspection unchecked final ArrayList<OUT>[] lists = new ArrayList[length]; for (int i = 0; i < lists.length; i++) { lists[i] = new ArrayList<OUT>(); } return chain(new OpenGate<OUT>() { @Override public void onPush(final River<OUT> upRiver, final River<OUT> downRiver, final int fallNumber, final OUT drop) { final long index = counts[fallNumber]; if (index < last) { counts[fallNumber] = index + 1; if (index >= offset) { lists[fallNumber].add(drop); } } } @Override public void onFlush(final River<OUT> upRiver, final River<OUT> downRiver, final int fallNumber) { final ArrayList<OUT> list = lists[fallNumber]; downRiver.push(list); list.clear(); super.onFlush(upRiver, downRiver, fallNumber); } }); } /** * Causes the data drops flowing through this waterfall streams to flow down in the reverse * order. * <p/> * Note that the returned waterfall internally cache the data pushed through it and then * discharge them on the first flush. * * @return the newly created waterfall. */ public Waterfall<SOURCE, OUT, OUT> revert() { return chain(new CacheGate<OUT, OUT>(size()) { @Override protected void onClear(final List<OUT> cache, final int streamNumber, final River<OUT> upRiver, final River<OUT> downRiver) { Collections.reverse(cache); downRiver.push(cache); super.onClear(cache, streamNumber, upRiver, downRiver); } }); } /** * Causes the data drops flowing through this waterfall streams to flow down sorted in the * natural order. * <p/> * Note that the returned waterfall internally cache the data pushed through it and then * discharge them on the first flush. * * @return the newly created waterfall. */ public Waterfall<SOURCE, OUT, OUT> sort() { //noinspection unchecked return sort((Comparator<? super OUT>) NATURAL_COMPARATOR); } /** * Causes the data drops flowing through this waterfall streams to flow down sorted in the * order decided by the specified comparator. * <p/> * Note that the returned waterfall internally cache the data pushed through it and then * discharge them on the first flush. * * @param comparator the comparator. * @return the newly created waterfall. * @throws IllegalArgumentException if the comparator is null. */ public Waterfall<SOURCE, OUT, OUT> sort(final Comparator<? super OUT> comparator) { if (comparator == null) { throw new IllegalArgumentException("the data comparator cannot be null"); } return chain(new CacheGate<OUT, OUT>(size()) { @Override protected void onClear(final List<OUT> cache, final int streamNumber, final River<OUT> upRiver, final River<OUT> downRiver) { Collections.sort(cache, comparator); downRiver.push(cache); super.onClear(cache, streamNumber, upRiver, downRiver); } }); } /** * Gets the waterfall source. * * @return the source. */ public Waterfall<SOURCE, SOURCE, ?> source() { return mSource; } /** * Creates and returns a new waterfall fed by to the springs returned by the specified * generator. * <p/> * Note that the bridges, the size and the currents of this waterfall will be retained. * * @param generator the spring generator. * @param <DATA> the spring data type. * @return the newly created waterfall. * @throws IllegalArgumentException if the generator is null or returns a null spring. */ public <DATA> Waterfall<Void, Void, DATA> spring(final SpringGenerator<DATA> generator) { if (generator == null) { throw new IllegalArgumentException("the waterfall spring generator cannot be null"); } return start(new GateGenerator<Void, DATA>() { @Override public Gate<Void, DATA> create(final int fallNumber) { return new SpringGate<DATA>(generator.create(fallNumber)); } }); } /** * Creates and returns a new waterfall fed by the specified spring. * <p/> * Note that the bridges and the currents of this waterfall will be retained, while the size will * be equal to 1. * * @param spring the spring instance. * @param <DATA> the spring data type. * @return the newly created waterfall. * @throws IllegalArgumentException if the spring is null. */ public <DATA> Waterfall<Void, Void, DATA> spring(final Spring<DATA> spring) { return spring(Collections.singleton(spring)); } /** * Creates and returns a new waterfall fed by the specified springs. * <p/> * Note that the bridges and the currents of this waterfall will be retained, while the size will * be equal to the one of the specified collection. * * @param springs the spring instances. * @param <DATA> the spring data type. * @return the newly created waterfall. * @throws IllegalArgumentException if the spring collection is null or contains a null spring. */ public <DATA> Waterfall<Void, Void, DATA> spring( final Collection<? extends Spring<DATA>> springs) { if (springs == null) { throw new IllegalArgumentException("the waterfall spring collection cannot be null"); } final ArrayList<SpringGate<DATA>> gates = new ArrayList<SpringGate<DATA>>(springs.size()); for (final Spring<DATA> spring : springs) { gates.add(new SpringGate<DATA>(spring)); } return start(gates); } /** * Creates and returns a new waterfall fed by both this waterfall as a spring and the specified * one. * <p/> * Note that the bridges and the currents of this waterfall will be retained, while the size will * be equal to the one of the specified collection. * * @param spring the spring instance. * @return the newly created waterfall. * @throws IllegalArgumentException if the spring is null. */ public Waterfall<Void, Void, OUT> springWith(final Spring<OUT> spring) { if (spring == null) { throw new IllegalArgumentException("the spring cannot be null"); } return springWith(Collections.singleton(spring)); } /** * Creates and returns a new waterfall fed by this waterfall as a spring and all the specified * ones. * <p/> * Note that the bridges and the currents of this waterfall will be retained, while the size will * be equal to the one of the specified collection. * * @param springs the spring collection. * @return the newly created waterfall. * @throws IllegalArgumentException if the spring collection is null or contains a null spring. */ public Waterfall<Void, Void, OUT> springWith(final Collection<? extends Spring<OUT>> springs) { if (springs == null) { throw new IllegalArgumentException("the spring collection cannot be null"); } final ArrayList<Spring<OUT>> list = new ArrayList<Spring<OUT>>(springs.size() + 1); list.add(Springs.from(this)); list.addAll(springs); return spring(list); } /** * Creates and returns a new waterfall generating from this one. * <p/> * Note that the bridges, the size and the currents of this waterfall will be retained. * * @return the newly created waterfall. */ public Waterfall<OUT, OUT, OUT> start() { final int size = mSize; //noinspection unchecked final Gate<OUT, OUT>[] gates = new Gate[size]; Arrays.fill(gates, openGate()); final Map<Classification<?>, BridgeGate<?, ?>> bridgeMap = Collections.emptyMap(); return new Waterfall<OUT, OUT, OUT>(null, bridgeMap, mBridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, null, size, mCurrent, mCurrentGenerator, gates); } /** * Creates and returns a new waterfall generating from this one. * <p/> * Note that the bridges, the size and the currents of this waterfall will be retained. * * @param dataType the data type. * @param <DATA> the data type. * @return the newly created waterfall. * @throws IllegalArgumentException if the data type is null. */ public <DATA> Waterfall<DATA, DATA, DATA> start(final Class<DATA> dataType) { return start(Classification.ofType(dataType)); } /** * Creates and returns a new waterfall generating from this one. * <p/> * Note that the bridges, the size and the currents of this waterfall will be retained. * * @param classification the data classification. * @param <DATA> the data type. * @return the newly created waterfall. * @throws IllegalArgumentException if the data classification is null. */ public <DATA> Waterfall<DATA, DATA, DATA> start(final Classification<DATA> classification) { if (classification == null) { throw new IllegalArgumentException("the waterfall classification cannot be null"); } //noinspection unchecked return (Waterfall<DATA, DATA, DATA>) start(); } /** * Creates and returns a new waterfall chained to the gates returned by the specified * generator. * <p/> * Note that the bridges, the size and the currents of this waterfall will be retained. * * @param generator the gate generator. * @param <NIN> the new input data type. * @param <NOUT> the new output data type. * @return the newly created waterfall. * @throws IllegalArgumentException if the generator is null or returns a null gate. */ public <NIN, NOUT> Waterfall<NIN, NIN, NOUT> start(final GateGenerator<NIN, NOUT> generator) { if (generator == null) { throw new IllegalArgumentException("the waterfall gate generator cannot be null"); } final Map<Classification<?>, BridgeGate<?, ?>> bridgeMap = Collections.emptyMap(); final int size = mSize; //noinspection unchecked final Gate<NIN, NOUT>[] gates = new Gate[size]; if (size <= 1) { final Gate<NIN, NOUT> gate = generator.create(0); registerGate(gate); gates[0] = gate; return new Waterfall<NIN, NIN, NOUT>(null, bridgeMap, mBridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, null, 1, mCurrent, mCurrentGenerator, gates); } if (mBridgeClassification != null) { throw new IllegalStateException("cannot make a bridge from more than one gate"); } for (int i = 0; i < size; ++i) { final Gate<NIN, NOUT> gate = generator.create(i); registerGate(gate); gates[i] = gate; } return new Waterfall<NIN, NIN, NOUT>(null, bridgeMap, null, mBackgroundPoolSize, mBackgroundCurrent, null, size, mCurrent, mCurrentGenerator, gates); } /** * Creates and returns a new waterfall chained to the specified gates. * <p/> * Note that the bridges and the currents of this waterfall will be retained, while the size will * be equal to the one of the specified array. * * @param gates the gate instances. * @param <NIN> the new input data type. * @param <NOUT> the new output data type. * @return the newly created waterfall. * @throws IllegalArgumentException if the gate collection is null or contains a null gate. */ public <NIN, NOUT> Waterfall<NIN, NIN, NOUT> start( final Collection<? extends Gate<NIN, NOUT>> gates) { if (gates == null) { throw new IllegalArgumentException("the waterfall gate collection cannot be null"); } final int length = gates.size(); if (length == 0) { throw new IllegalArgumentException("the waterfall gate collection cannot be empty"); } final Waterfall<SOURCE, IN, OUT> waterfall; if (mSize == length) { waterfall = this; } else { waterfall = in(length); } final Iterator<? extends Gate<NIN, NOUT>> iterator = gates.iterator(); return waterfall.start(new GateGenerator<NIN, NOUT>() { @Override public Gate<NIN, NOUT> create(final int fallNumber) { return iterator.next(); } }); } /** * Creates and returns a new waterfall chained to the specified gate. * <p/> * Note that the bridges, the size and the currents of this waterfall will be retained. * * @param gate the gate instance. * @param <NIN> the new input data type. * @param <NOUT> the new output data type. * @return the newly created waterfall. * @throws IllegalArgumentException if the gate is null. */ public <NIN, NOUT> Waterfall<NIN, NIN, NOUT> start(final Gate<NIN, NOUT> gate) { registerGate(gate); final Map<Classification<?>, BridgeGate<?, ?>> bridgeMap = Collections.emptyMap(); //noinspection unchecked final Gate<NIN, NOUT>[] gates = new Gate[]{gate}; return new Waterfall<NIN, NIN, NOUT>(null, bridgeMap, mBridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, null, mSize, mCurrent, mCurrentGenerator, gates); } /** * Makes this waterfall forward an exception in case the specified timeout elapses before at * least one data drop is pushed through it. * <p/> * TODO: starts immediately * * @param timeout the timeout in <code>timeUnit</code> time units. * @param timeUnit the delay time unit. * @param exception the exception to forward. * @return the newly created waterfall. */ public Waterfall<SOURCE, OUT, OUT> throwOnTimeout(final long timeout, final TimeUnit timeUnit, final RuntimeException exception) { return chain(new TimeoutGate<OUT>(this, timeout, timeUnit, exception)); } private Waterfall<SOURCE, OUT, OUT> chainPump(final PumpGate<OUT> pumpGate) { final Waterfall<SOURCE, OUT, OUT> waterfall = chain(pumpGate); return new Waterfall<SOURCE, OUT, OUT>(waterfall.mSource, waterfall.mBridgeMap, waterfall.mBridgeClassification, mBackgroundPoolSize, mBackgroundCurrent, pumpGate, waterfall.mSize, waterfall.mCurrent, waterfall.mCurrentGenerator, waterfall.mFalls); } private BridgeGate<?, ?> findBestMatch(final Classification<?> bridgeClassification) { final Map<Classification<?>, BridgeGate<?, ?>> bridgeMap = mBridgeMap; BridgeGate<?, ?> gate = bridgeMap.get(bridgeClassification); if (gate == null) { Classification<?> bestMatch = null; for (final Entry<Classification<?>, BridgeGate<?, ?>> entry : bridgeMap.entrySet()) { final Classification<?> type = entry.getKey(); if (bridgeClassification.isAssignableFrom(type)) { if ((bestMatch == null) || type.isAssignableFrom(bestMatch)) { gate = entry.getValue(); bestMatch = type; } } } } return gate; } private int getBestPoolSize() { final int processors = Runtime.getRuntime().availableProcessors(); if (processors < 4) { return Math.max(1, processors - 1); } return (processors / 2); } private void mapBridge(final HashMap<Classification<?>, BridgeGate<?, ?>> bridgeMap, final Classification<?> bridgeClassification, final BridgeGate<?, ?> gate) { if (!bridgeClassification.getRawType().isInstance(gate.gate)) { throw new IllegalArgumentException( "the gate does not implement the bridge classification type"); } bridgeMap.put(bridgeClassification, gate); } }
Documentation
library/src/main/java/com/bmd/wtf/fll/Waterfall.java
Documentation
Java
apache-2.0
03403045dd5d56cf0162a3a32e65c0b16a671688
0
Neeeo/incubator-weex,namedlock/weex,miomin/incubator-weex,Hanks10100/weex,leoward/incubator-weex,Neeeo/incubator-weex,HomHomLin/weex,Tancy/weex,miomin/incubator-weex,bigconvience/weex,acton393/weex,houfeng0923/weex,misakuo/incubator-weex,bigconvience/weex,alibaba/weex,boboning/weex,MrRaindrop/weex,houfeng0923/weex,weexteam/incubator-weex,miomin/incubator-weex,acton393/incubator-weex,zhangquan/weex,zhangquan/weex,Neeeo/incubator-weex,kfeagle/weex,yuguitao/incubator-weex,xiayun200825/weex,Tancy/weex,boboning/weex,acton393/incubator-weex,alibaba/weex,yuguitao/incubator-weex,leoward/incubator-weex,lzyzsd/weex,weexteam/incubator-weex,lvscar/weex,lzyzsd/weex,weexteam/incubator-weex,Hanks10100/weex,erha19/incubator-weex,Hanks10100/incubator-weex,Hanks10100/incubator-weex,KalicyZhou/incubator-weex,lvscar/weex,Tancy/weex,zhangquan/weex,LeeJay0226/weex,Neeeo/incubator-weex,cxfeng1/incubator-weex,HomHomLin/weex,dianwodaMobile/DWeex,acton393/incubator-weex,HomHomLin/weex,misakuo/incubator-weex,weexteam/incubator-weex,LeeJay0226/weex,erha19/incubator-weex,miomin/incubator-weex,dianwodaMobile/DWeex,miomin/incubator-weex,houfeng0923/weex,lvscar/weex,boboning/weex,MrRaindrop/weex,alibaba/weex,Hanks10100/incubator-weex,Tancy/weex,KalicyZhou/incubator-weex,erha19/incubator-weex,kfeagle/weex,xiayun200825/weex,zzyhappyzzy/weex,yuguitao/incubator-weex,cxfeng1/incubator-weex,zzyhappyzzy/weex,zzyhappyzzy/weex,acton393/weex,misakuo/incubator-weex,MrRaindrop/incubator-weex,LeeJay0226/weex,boboning/weex,cxfeng1/incubator-weex,namedlock/weex,MrRaindrop/incubator-weex,MrRaindrop/weex,acton393/weex,MrRaindrop/weex,Hanks10100/incubator-weex,boboning/weex,cxfeng1/incubator-weex,namedlock/weex,lvscar/weex,cxfeng1/weex,MrRaindrop/incubator-weex,acton393/incubator-weex,kfeagle/weex,KalicyZhou/incubator-weex,cxfeng1/weex,LeeJay0226/weex,HomHomLin/weex,zhangquan/weex,HomHomLin/weex,zzyhappyzzy/weex,misakuo/incubator-weex,weexteam/incubator-weex,leoward/incubator-weex,cxfeng1/weex,HomHomLin/weex,cxfeng1/weex,MrRaindrop/incubator-weex,boboning/weex,zhangquan/weex,miomin/incubator-weex,zzyhappyzzy/weex,lzyzsd/weex,Hanks10100/weex,erha19/incubator-weex,MrRaindrop/weex,MrRaindrop/weex,miomin/incubator-weex,lzyzsd/weex,lzyzsd/weex,LeeJay0226/weex,dianwodaMobile/DWeex,kfeagle/weex,bigconvience/weex,Hanks10100/weex,acton393/weex,lvscar/weex,erha19/incubator-weex,erha19/incubator-weex,KalicyZhou/incubator-weex,bigconvience/weex,Hanks10100/weex,cxfeng1/weex,miomin/incubator-weex,yuguitao/incubator-weex,lvscar/weex,leoward/incubator-weex,zhangquan/weex,Neeeo/incubator-weex,acton393/weex,erha19/incubator-weex,xiayun200825/weex,acton393/incubator-weex,bigconvience/weex,dianwodaMobile/DWeex,Tancy/weex,dianwodaMobile/DWeex,Neeeo/incubator-weex,cxfeng1/weex,MrRaindrop/incubator-weex,alibaba/weex,misakuo/incubator-weex,misakuo/incubator-weex,kfeagle/weex,cxfeng1/incubator-weex,alibaba/weex,acton393/incubator-weex,kfeagle/weex,MrRaindrop/incubator-weex,Hanks10100/weex,Hanks10100/incubator-weex,leoward/incubator-weex,xiayun200825/weex,KalicyZhou/incubator-weex,cxfeng1/incubator-weex,LeeJay0226/weex,xiayun200825/weex,Hanks10100/incubator-weex,KalicyZhou/incubator-weex,bigconvience/weex,acton393/weex,yuguitao/incubator-weex,leoward/incubator-weex,zzyhappyzzy/weex,alibaba/weex,Tancy/weex,houfeng0923/weex,acton393/incubator-weex,lzyzsd/weex,xiayun200825/weex,alibaba/weex,Hanks10100/incubator-weex,houfeng0923/weex,yuguitao/incubator-weex,houfeng0923/weex,namedlock/weex,dianwodaMobile/DWeex,Hanks10100/incubator-weex,namedlock/weex,acton393/incubator-weex,erha19/incubator-weex,namedlock/weex,weexteam/incubator-weex
/** * * Apache License * Version 2.0, January 2004 * http://www.apache.org/licenses/ * * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION * * 1. Definitions. * * "License" shall mean the terms and conditions for use, reproduction, * and distribution as defined by Sections 1 through 9 of this document. * * "Licensor" shall mean the copyright owner or entity authorized by * the copyright owner that is granting the License. * * "Legal Entity" shall mean the union of the acting entity and all * other entities that control, are controlled by, or are under common * control with that entity. For the purposes of this definition, * "control" means (i) the power, direct or indirect, to cause the * direction or management of such entity, whether by contract or * otherwise, or (ii) ownership of fifty percent (50%) or more of the * outstanding shares, or (iii) beneficial ownership of such entity. * * "You" (or "Your") shall mean an individual or Legal Entity * exercising permissions granted by this License. * * "Source" form shall mean the preferred form for making modifications, * including but not limited to software source code, documentation * source, and configuration files. * * "Object" form shall mean any form resulting from mechanical * transformation or translation of a Source form, including but * not limited to compiled object code, generated documentation, * and conversions to other media types. * * "Work" shall mean the work of authorship, whether in Source or * Object form, made available under the License, as indicated by a * copyright notice that is included in or attached to the work * (an example is provided in the Appendix below). * * "Derivative Works" shall mean any work, whether in Source or Object * form, that is based on (or derived from) the Work and for which the * editorial revisions, annotations, elaborations, or other modifications * represent, as a whole, an original work of authorship. For the purposes * of this License, Derivative Works shall not include works that remain * separable from, or merely link (or bind by name) to the interfaces of, * the Work and Derivative Works thereof. * * "Contribution" shall mean any work of authorship, including * the original version of the Work and any modifications or additions * to that Work or Derivative Works thereof, that is intentionally * submitted to Licensor for inclusion in the Work by the copyright owner * or by an individual or Legal Entity authorized to submit on behalf of * the copyright owner. For the purposes of this definition, "submitted" * means any form of electronic, verbal, or written communication sent * to the Licensor or its representatives, including but not limited to * communication on electronic mailing lists, source code control systems, * and issue tracking systems that are managed by, or on behalf of, the * Licensor for the purpose of discussing and improving the Work, but * excluding communication that is conspicuously marked or otherwise * designated in writing by the copyright owner as "Not a Contribution." * * "Contributor" shall mean Licensor and any individual or Legal Entity * on behalf of whom a Contribution has been received by Licensor and * subsequently incorporated within the Work. * * 2. Grant of Copyright License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * copyright license to reproduce, prepare Derivative Works of, * publicly display, publicly perform, sublicense, and distribute the * Work and such Derivative Works in Source or Object form. * * 3. Grant of Patent License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * (except as stated in this section) patent license to make, have made, * use, offer to sell, sell, import, and otherwise transfer the Work, * where such license applies only to those patent claims licensable * by such Contributor that are necessarily infringed by their * Contribution(s) alone or by combination of their Contribution(s) * with the Work to which such Contribution(s) was submitted. If You * institute patent litigation against any entity (including a * cross-claim or counterclaim in a lawsuit) alleging that the Work * or a Contribution incorporated within the Work constitutes direct * or contributory patent infringement, then any patent licenses * granted to You under this License for that Work shall terminate * as of the date such litigation is filed. * * 4. Redistribution. You may reproduce and distribute copies of the * Work or Derivative Works thereof in any medium, with or without * modifications, and in Source or Object form, provided that You * meet the following conditions: * * (a) You must give any other recipients of the Work or * Derivative Works a copy of this License; and * * (b) You must cause any modified files to carry prominent notices * stating that You changed the files; and * * (c) You must retain, in the Source form of any Derivative Works * that You distribute, all copyright, patent, trademark, and * attribution notices from the Source form of the Work, * excluding those notices that do not pertain to any part of * the Derivative Works; and * * (d) If the Work includes a "NOTICE" text file as part of its * distribution, then any Derivative Works that You distribute must * include a readable copy of the attribution notices contained * within such NOTICE file, excluding those notices that do not * pertain to any part of the Derivative Works, in at least one * of the following places: within a NOTICE text file distributed * as part of the Derivative Works; within the Source form or * documentation, if provided along with the Derivative Works; or, * within a display generated by the Derivative Works, if and * wherever such third-party notices normally appear. The contents * of the NOTICE file are for informational purposes only and * do not modify the License. You may add Your own attribution * notices within Derivative Works that You distribute, alongside * or as an addendum to the NOTICE text from the Work, provided * that such additional attribution notices cannot be construed * as modifying the License. * * You may add Your own copyright statement to Your modifications and * may provide additional or different license terms and conditions * for use, reproduction, or distribution of Your modifications, or * for any such Derivative Works as a whole, provided Your use, * reproduction, and distribution of the Work otherwise complies with * the conditions stated in this License. * * 5. Submission of Contributions. Unless You explicitly state otherwise, * any Contribution intentionally submitted for inclusion in the Work * by You to the Licensor shall be under the terms and conditions of * this License, without any additional terms or conditions. * Notwithstanding the above, nothing herein shall supersede or modify * the terms of any separate license agreement you may have executed * with Licensor regarding such Contributions. * * 6. Trademarks. This License does not grant permission to use the trade * names, trademarks, service marks, or product names of the Licensor, * except as required for reasonable and customary use in describing the * origin of the Work and reproducing the content of the NOTICE file. * * 7. Disclaimer of Warranty. Unless required by applicable law or * agreed to in writing, Licensor provides the Work (and each * Contributor provides its Contributions) on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied, including, without limitation, any warranties or conditions * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A * PARTICULAR PURPOSE. You are solely responsible for determining the * appropriateness of using or redistributing the Work and assume any * risks associated with Your exercise of permissions under this License. * * 8. Limitation of Liability. In no event and under no legal theory, * whether in tort (including negligence), contract, or otherwise, * unless required by applicable law (such as deliberate and grossly * negligent acts) or agreed to in writing, shall any Contributor be * liable to You for damages, including any direct, indirect, special, * incidental, or consequential damages of any character arising as a * result of this License or out of the use or inability to use the * Work (including but not limited to damages for loss of goodwill, * work stoppage, computer failure or malfunction, or any and all * other commercial damages or losses), even if such Contributor * has been advised of the possibility of such damages. * * 9. Accepting Warranty or Additional Liability. While redistributing * the Work or Derivative Works thereof, You may choose to offer, * and charge a fee for, acceptance of support, warranty, indemnity, * or other liability obligations and/or rights consistent with this * License. However, in accepting such obligations, You may act only * on Your own behalf and on Your sole responsibility, not on behalf * of any other Contributor, and only if You agree to indemnify, * defend, and hold each Contributor harmless for any liability * incurred by, or claims asserted against, such Contributor by reason * of your accepting any such warranty or additional liability. * * END OF TERMS AND CONDITIONS * * APPENDIX: How to apply the Apache License to your work. * * To apply the Apache License to your work, attach the following * boilerplate notice, with the fields enclosed by brackets "[]" * replaced with your own identifying information. (Don't include * the brackets!) The text should be enclosed in the appropriate * comment syntax for the file format. We also recommend that a * file or class name and description of purpose be included on the * same "printed page" as the copyright notice for easier * identification within third-party archives. * * Copyright 2016 Alibaba Group * * 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.taobao.weex; import android.content.Context; import android.net.Uri; import android.text.TextUtils; import android.view.View; import android.view.ViewGroup; import android.widget.ScrollView; import com.taobao.weex.adapter.DefaultWXHttpAdapter; import com.taobao.weex.adapter.IWXHttpAdapter; import com.taobao.weex.adapter.IWXImgLoaderAdapter; import com.taobao.weex.adapter.IWXUserTrackAdapter; import com.taobao.weex.common.WXErrorCode; import com.taobao.weex.common.WXPerformance; import com.taobao.weex.common.WXRefreshData; import com.taobao.weex.common.WXRenderStrategy; import com.taobao.weex.common.WXRequest; import com.taobao.weex.common.WXResponse; import com.taobao.weex.http.WXHttpUtil; import com.taobao.weex.ui.WXRecycleImageManager; import com.taobao.weex.ui.component.WXComponent; import com.taobao.weex.ui.view.WXScrollView; import com.taobao.weex.ui.view.WXScrollView.WXScrollViewListener; import com.taobao.weex.utils.WXConst; import com.taobao.weex.utils.WXFileUtils; import com.taobao.weex.utils.WXJsonUtils; import com.taobao.weex.utils.WXLogUtils; import com.taobao.weex.utils.WXReflectionUtils; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentLinkedQueue; /** * Each instance of WXSDKInstance represents an running weex instance. * It can be a pure weex view, or mixed with native view */ public class WXSDKInstance implements IWXActivityStateListener { public boolean mEnd = false; // adapters protected IWXUserTrackAdapter mUserTrackAdapter; protected IWXHttpAdapter mWXHttpAdapter; private IWXRenderListener mRenderListener; private Context mContext; private volatile String mInstanceId; public WXComponent getRootCom() { return mRootCom; } private WXComponent mRootCom; private boolean mRendered; private WXRefreshData mLastRefreshData; /** * Render strategy. */ private WXRenderStrategy mRenderStrategy = WXRenderStrategy.APPEND_ASYNC; /** * Width of weex's root container. */ private int mGodViewWidth = -1; /** * Height of weex's root container. */ private int mGodViewHeight = -1; /** * Render start time */ private long mRenderStartTime; /** * Refresh start time */ private long mRefreshStartTime; private WXRecycleImageManager mRecycleImageManager; private ConcurrentLinkedQueue<IWXActivityStateListener> mActivityStateListeners; private WXPerformance mWXPerformance; private ScrollView mScrollView; private WXScrollViewListener mWXScrollViewListener; private ViewGroup rootView; public WXSDKInstance(Context context) { init(context); } public void init(Context context) { mContext = context; mActivityStateListeners = new ConcurrentLinkedQueue<>(); mRecycleImageManager = new WXRecycleImageManager(this); mWXPerformance = new WXPerformance(); mWXPerformance.WXSDKVersion = WXEnvironment.WXSDK_VERSION; mWXPerformance.JSLibInitTime = WXEnvironment.sJSLibInitTime; mUserTrackAdapter=WXSDKManager.getInstance().getIWXUserTrackAdapter(); mWXHttpAdapter=WXSDKManager.getInstance().getIWXHttpAdapter(); } public void setBizType(String bizType) { if (!TextUtils.isEmpty(bizType)) { mWXPerformance.bizType = bizType; } } public ScrollView getScrollView() { return mScrollView; } public void setRootScrollView(ScrollView scrollView) { mScrollView = scrollView; if (mWXScrollViewListener != null) { ((WXScrollView) mScrollView).addScrollViewListener(mWXScrollViewListener); } } public void registerScrollViewListener(WXScrollViewListener scrollViewListener) { mWXScrollViewListener = scrollViewListener; } public WXScrollViewListener getScrollViewListener() { return mWXScrollViewListener; } @Deprecated public void setIWXUserTrackAdapter(IWXUserTrackAdapter adapter) { } /** * Render template asynchronously, use {@link WXRenderStrategy#APPEND_ASYNC} as render strategy * @param template bundle js * @param options os iphone/android/ipad * weexversion Weex version(like 1.0.0) * appversion App version(like 1.0.0) * devid Device id(like Aqh9z8dRJNBhmS9drLG5BKCmXhecHUXIZoXOctKwFebH) * sysversion Device system version(like 5.4.4、7.0.4, should be used with os) * sysmodel Device model(like iOS:"MGA82J/A", android:"MI NOTE LTE") * Time UNIX timestamp, UTC+08:00 * TTID(Optional) * MarkertId * Appname(Optional) tm,tb,qa * Bundleurl(Optional) template url * @param jsonInitData Initial data for rendering */ public void render(String template, Map<String, Object> options, String jsonInitData) { render(template, options, jsonInitData, WXRenderStrategy.APPEND_ASYNC); } /** * Render template asynchronously * @param template bundle js * @param options os iphone/android/ipad * weexversion Weex version(like 1.0.0) * appversion App version(like 1.0.0) * devid Device id(like Aqh9z8dRJNBhmS9drLG5BKCmXhecHUXIZoXOctKwFebH) * sysversion Device system version(like 5.4.4、7.0.4, should be used with os) * sysmodel Device model(like iOS:"MGA82J/A", android:"MI NOTE LTE") * Time UNIX timestamp, UTC+08:00 * TTID(Optional) * MarkertId * Appname(Optional) tm,tb,qa * Bundleurl(Optional) template url * @param jsonInitData Initial data for rendering * @param flag RenderStrategy {@link WXRenderStrategy} */ public void render(String template, Map<String, Object> options, String jsonInitData, WXRenderStrategy flag) { render(WXPerformance.DEFAULT, template, options, jsonInitData, -1, -1, flag); } /** * Render template asynchronously * * @param pageName, used for performance log. * @param template bundle js * @param options os iphone/android/ipad * weexversion Weex version(like 1.0.0) * appversion App version(like 1.0.0) * devid Device id(like Aqh9z8dRJNBhmS9drLG5BKCmXhecHUXIZoXOctKwFebH) * sysversion Device system version(like 5.4.4、7.0.4, should be used with os) * sysmodel Device model(like iOS:"MGA82J/A", android:"MI NOTE LTE") * Time UNIX timestamp, UTC+08:00 * TTID(Optional) * MarkertId * Appname(Optional) tm,tb,qa * Bundleurl(Optional) template url * @param jsonInitData Initial data for rendering * @param width Width of weex's root container, the default is match_parent * @param height Height of weex's root container, the default is match_parent * @param flag RenderStrategy {@link WXRenderStrategy} */ public void render(String pageName, String template, Map<String, Object> options, String jsonInitData, int width, int height, WXRenderStrategy flag) { if (mRendered || TextUtils.isEmpty(template)) { return; } if(options==null){ options=new HashMap<>(); } if(WXEnvironment.sDynamicMode && !TextUtils.isEmpty(WXEnvironment.sDynamicUrl) && options!=null && options.get("dynamicMode")==null){ options.put("dynamicMode","true"); renderByUrl(pageName,WXEnvironment.sDynamicUrl,options,jsonInitData,width,height,flag); return; } mWXPerformance.pageName = pageName; mWXPerformance.JSTemplateSize = template.length() / 1024; mRenderStartTime = System.currentTimeMillis(); mRenderStrategy = flag; mGodViewWidth = width; mGodViewHeight = height; mInstanceId = WXSDKManager.getInstance().generateInstanceId(); WXSDKManager.getInstance().createInstance(this, template, options, jsonInitData); mRendered = true; } /** * Render template asynchronously, use {@link WXRenderStrategy#APPEND_ASYNC} as render strategy * @param template bundle js * @param width default match_parent * @param height default match_parent */ public void render(String template, int width, int height) { render(WXPerformance.DEFAULT, template, null, null, width, height, mRenderStrategy); } public void renderByUrl(final String pageName, final String url, Map<String, Object> options, final String jsonInitData, final int width, final int height, final WXRenderStrategy flag) { if (options == null) { options = new HashMap<String, Object>(); } if (!options.containsKey("bundleUrl")) { options.put("bundleUrl", url); } Uri uri=Uri.parse(url); if(uri!=null && uri.getScheme().equals("file")){ render(pageName, WXFileUtils.loadFileContent(assembleFilePath(uri), mContext),options,jsonInitData,width,height,flag); return; } IWXHttpAdapter adapter=WXSDKManager.getInstance().getIWXHttpAdapter(); if (adapter == null) { adapter = new DefaultWXHttpAdapter(); } WXRequest wxRequest = new WXRequest(); wxRequest.url = url; if (wxRequest.paramMap == null) { wxRequest.paramMap = new HashMap<String, Object>(); } wxRequest.paramMap.put("user-agent", WXHttpUtil.assembleUserAgent()); adapter.sendRequest(wxRequest, new WXHttpListener(pageName, options, jsonInitData, width, height, flag, System.currentTimeMillis())); mWXHttpAdapter = adapter; } private String assembleFilePath(Uri uri) { if(uri!=null && uri.getPath()!=null){ return uri.getPath().replaceFirst("/",""); } return ""; } /** * Refresh instance asynchronously. * @param data the new data */ public void refreshInstance(Map<String, Object> data) { if (data == null) { return; } refreshInstance(WXJsonUtils.fromObjectToJSONString(data)); } /** * Refresh instance asynchronously. * @param jsonData the new data */ public void refreshInstance(String jsonData) { if (jsonData == null) { return; } mRefreshStartTime = System.currentTimeMillis(); //cancel last refresh message if (mLastRefreshData != null) { mLastRefreshData.isDirty = true; } mLastRefreshData = new WXRefreshData(jsonData, false); WXSDKManager.getInstance().refreshInstance(mInstanceId, mLastRefreshData); } public WXRenderStrategy getRenderStrategy() { return mRenderStrategy; } public String getInstanceId() { return mInstanceId; } public Context getContext() { return mContext; } public int getWeexHeight() { return mGodViewHeight; } public int getWeexWidth() { return mGodViewWidth; } public WXRecycleImageManager getRecycleImageManager() { return mRecycleImageManager; } public IWXImgLoaderAdapter getImgLoaderAdapter() { return WXSDKManager.getInstance().getIWXImgLoaderAdapter(); } @Deprecated public void setImgLoaderAdapter(IWXImgLoaderAdapter adapter) { } public IWXHttpAdapter getWXHttpAdapter() { return WXSDKManager.getInstance().getIWXHttpAdapter(); } public void reloadImages() { if (mScrollView == null) { return; } if (mRecycleImageManager != null && mRecycleImageManager.isRecycleImage()) { WXSDKManager.getInstance().postOnUiThread(new Runnable() { @Override public void run() { if (mRecycleImageManager != null) { mRecycleImageManager.loadImage(); } } }, 250); } } /******************************** * begin register listener ********************************************************/ public void registerRenderListener(IWXRenderListener listener) { mRenderListener = listener; } public void registerActivityStateListener(IWXActivityStateListener listener) { if (listener == null) { return; } if (!mActivityStateListeners.contains(listener)) { mActivityStateListeners.add(listener); } } /******************************** * end register listener ********************************************************/ // WAActivityStateListener////////////////////////////////////////////////////////////////////////////////// @Override public void onActivityCreate() { for (IWXActivityStateListener listener : mActivityStateListeners) { listener.onActivityCreate(); } } @Override public void onActivityStart() { for (IWXActivityStateListener listener : mActivityStateListeners) { listener.onActivityStart(); } } @Override public void onActivityPause() { for (IWXActivityStateListener listener : mActivityStateListeners) { listener.onActivityPause(); } } @Override public void onActivityResume() { for (IWXActivityStateListener listener : mActivityStateListeners) { listener.onActivityResume(); } } @Override public void onActivityStop() { for (IWXActivityStateListener listener : mActivityStateListeners) { listener.onActivityStop(); } } @Override public void onActivityDestroy() { for (IWXActivityStateListener listener : mActivityStateListeners) { listener.onActivityDestroy(); } destroy(); } @Override public boolean onActivityBack() { for (IWXActivityStateListener listener : mActivityStateListeners) { boolean isIntercept = listener.onActivityBack(); if (isIntercept) { return true; } } return false; } public void onViewCreated(final WXComponent component) { if (mRenderListener != null && mContext != null) { runOnUiThread(new Runnable() { @Override public void run() { if (mRenderListener != null && mContext != null) { mRootCom = component; mRenderListener.onViewCreated(WXSDKInstance.this, component.getView()); } } }); } } public void runOnUiThread(Runnable action) { WXSDKManager.getInstance().postOnUiThread(action, 0); } public void onRenderSuccess(final int width, final int height) { long time = System.currentTimeMillis() - mRenderStartTime; WXLogUtils.renderPerformanceLog("onRenderSuccess", time); mWXPerformance.totalTime = time; WXLogUtils.d(WXLogUtils.WEEX_PERF_TAG, "mComponentNum:" + WXComponent.mComponentNum); WXComponent.mComponentNum = 0; if (mRenderListener != null && mContext != null) { runOnUiThread(new Runnable() { @Override public void run() { if (mRenderListener != null && mContext != null) { mRenderListener.onRenderSuccess(WXSDKInstance.this, width, height); if (WXEnvironment.isApkDebugable()) { WXLogUtils.d(WXLogUtils.WEEX_PERF_TAG, mWXPerformance.toString()); } if (mUserTrackAdapter != null) { mUserTrackAdapter.commit(mContext, null, WXConst.LOAD, mWXPerformance, null); } } } }); } } public void onRefreshSuccess(final int width, final int height) { WXLogUtils.renderPerformanceLog("onRefreshSuccess", (System.currentTimeMillis() - mRefreshStartTime)); if (mRenderListener != null && mContext != null) { runOnUiThread(new Runnable() { @Override public void run() { if (mRenderListener != null && mContext != null) { mRenderListener.onRefreshSuccess(WXSDKInstance.this, width, height); } } }); } } public void onRenderError(final String errCode, final String msg) { if (mRenderListener != null && mContext != null) { runOnUiThread(new Runnable() { @Override public void run() { if (mRenderListener != null && mContext != null) { mRenderListener.onException(WXSDKInstance.this, errCode, msg); } } }); } } public void onJSException(final String errCode, final String function, final String exception) { if (mRenderListener != null && mContext != null) { runOnUiThread(new Runnable() { @Override public void run() { if (mRenderListener != null && mContext != null) { StringBuilder builder = new StringBuilder(); builder.append(function); builder.append(exception); mRenderListener.onException(WXSDKInstance.this, errCode, builder.toString()); } } }); } } public void firstScreenRenderFinished(long endTime) { mEnd = true; long time = endTime - mRenderStartTime; mWXPerformance.screenRenderTime = time; WXLogUtils.renderPerformanceLog("firstScreenRenderFinished", time); } public void createInstanceFinished(long time) { if (time > 0) { mWXPerformance.communicateTime = time; } } /** * UserTrack Log */ public void commitUTStab(final String type, final WXErrorCode errorCode) { if (errorCode == WXErrorCode.WX_SUCCESS) { return; } runOnUiThread(new Runnable() { @Override public void run() { if (mUserTrackAdapter == null || TextUtils.isEmpty(type)) { return; } // Log for commit if (errorCode.getErrorCode() == null && errorCode.getErrorMsg() == null) { mUserTrackAdapter.commit(mContext, null, type, null, null); return; } WXPerformance perf = new WXPerformance(); perf.errCode = errorCode.getErrorCode(); perf.errMsg = errorCode.getErrorMsg(); if (WXEnvironment.isApkDebugable()) { WXLogUtils.d(perf.toString()); } mUserTrackAdapter.commit(mContext, null, type, perf, null); } }); } private void destroyView(View rootView) { try { if (rootView instanceof ViewGroup) { ViewGroup cViewGroup = ((ViewGroup) rootView); for (int index = 0; index < cViewGroup.getChildCount(); index++) { destroyView(cViewGroup.getChildAt(index)); } cViewGroup.removeViews(0, ((ViewGroup) rootView).getChildCount()); // Ensure that the viewgroup's status to be normal WXReflectionUtils.setValue(rootView, "mChildrenCount", 0); } } catch (Exception e) { WXLogUtils.e("WXSDKInstance destroyView Exception: " + WXLogUtils.getStackTrace(e)); } } public void destroy() { WXSDKManager.getInstance().destroyInstance(mInstanceId); if (mRecycleImageManager != null) { mRecycleImageManager.destroy(); mRecycleImageManager = null; } if (mRootCom != null && mRootCom.getView() != null) { mRootCom.destroy(); destroyView(mRootCom.getView()); mRootCom = null; } if (mActivityStateListeners != null) { mActivityStateListeners.clear(); mActivityStateListeners = null; } mContext = null; mRenderListener = null; } public ViewGroup getRootView() { return rootView; } public void setRootView(ViewGroup rootView) { this.rootView = rootView; } /** * load bundle js listener */ class WXHttpListener implements IWXHttpAdapter.OnHttpListener { private String pageName; private Map<String, Object> options; private String jsonInitData; private int width; private int height; private WXRenderStrategy flag; private long startRequestTime; private WXHttpListener(String pageName, Map<String, Object> options, String jsonInitData, int width, int height, WXRenderStrategy flag, long startRequestTime) { this.pageName = pageName; this.options = options; this.jsonInitData = jsonInitData; this.width = width; this.height = height; this.flag = flag; this.startRequestTime = startRequestTime; } @Override public void onHttpStart() { } @Override public void onHttpUploadProgress(int uploadProgress) { } @Override public void onHttpResponseProgress(int responseProgress) { } @Override public void onHttpFinish(WXResponse response) { mWXPerformance.networkTime = System.currentTimeMillis() - startRequestTime; WXLogUtils.renderPerformanceLog("networkTime", mWXPerformance.networkTime); if (TextUtils.equals("200", response.statusCode)) { String template = new String(response.originalData); render(pageName, template, options, jsonInitData, width, height, flag); } else if (TextUtils.equals(WXRenderErrorCode.WX_USER_INTERCEPT_ERROR, response.statusCode)) { WXLogUtils.d("user intercept"); onRenderError(WXRenderErrorCode.WX_USER_INTERCEPT_ERROR,response.errorMsg); } else { onRenderError(WXRenderErrorCode.WX_NETWORK_ERROR, response.errorMsg); } } } }
android/sdk/src/main/java/com/taobao/weex/WXSDKInstance.java
/** * * Apache License * Version 2.0, January 2004 * http://www.apache.org/licenses/ * * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION * * 1. Definitions. * * "License" shall mean the terms and conditions for use, reproduction, * and distribution as defined by Sections 1 through 9 of this document. * * "Licensor" shall mean the copyright owner or entity authorized by * the copyright owner that is granting the License. * * "Legal Entity" shall mean the union of the acting entity and all * other entities that control, are controlled by, or are under common * control with that entity. For the purposes of this definition, * "control" means (i) the power, direct or indirect, to cause the * direction or management of such entity, whether by contract or * otherwise, or (ii) ownership of fifty percent (50%) or more of the * outstanding shares, or (iii) beneficial ownership of such entity. * * "You" (or "Your") shall mean an individual or Legal Entity * exercising permissions granted by this License. * * "Source" form shall mean the preferred form for making modifications, * including but not limited to software source code, documentation * source, and configuration files. * * "Object" form shall mean any form resulting from mechanical * transformation or translation of a Source form, including but * not limited to compiled object code, generated documentation, * and conversions to other media types. * * "Work" shall mean the work of authorship, whether in Source or * Object form, made available under the License, as indicated by a * copyright notice that is included in or attached to the work * (an example is provided in the Appendix below). * * "Derivative Works" shall mean any work, whether in Source or Object * form, that is based on (or derived from) the Work and for which the * editorial revisions, annotations, elaborations, or other modifications * represent, as a whole, an original work of authorship. For the purposes * of this License, Derivative Works shall not include works that remain * separable from, or merely link (or bind by name) to the interfaces of, * the Work and Derivative Works thereof. * * "Contribution" shall mean any work of authorship, including * the original version of the Work and any modifications or additions * to that Work or Derivative Works thereof, that is intentionally * submitted to Licensor for inclusion in the Work by the copyright owner * or by an individual or Legal Entity authorized to submit on behalf of * the copyright owner. For the purposes of this definition, "submitted" * means any form of electronic, verbal, or written communication sent * to the Licensor or its representatives, including but not limited to * communication on electronic mailing lists, source code control systems, * and issue tracking systems that are managed by, or on behalf of, the * Licensor for the purpose of discussing and improving the Work, but * excluding communication that is conspicuously marked or otherwise * designated in writing by the copyright owner as "Not a Contribution." * * "Contributor" shall mean Licensor and any individual or Legal Entity * on behalf of whom a Contribution has been received by Licensor and * subsequently incorporated within the Work. * * 2. Grant of Copyright License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * copyright license to reproduce, prepare Derivative Works of, * publicly display, publicly perform, sublicense, and distribute the * Work and such Derivative Works in Source or Object form. * * 3. Grant of Patent License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * (except as stated in this section) patent license to make, have made, * use, offer to sell, sell, import, and otherwise transfer the Work, * where such license applies only to those patent claims licensable * by such Contributor that are necessarily infringed by their * Contribution(s) alone or by combination of their Contribution(s) * with the Work to which such Contribution(s) was submitted. If You * institute patent litigation against any entity (including a * cross-claim or counterclaim in a lawsuit) alleging that the Work * or a Contribution incorporated within the Work constitutes direct * or contributory patent infringement, then any patent licenses * granted to You under this License for that Work shall terminate * as of the date such litigation is filed. * * 4. Redistribution. You may reproduce and distribute copies of the * Work or Derivative Works thereof in any medium, with or without * modifications, and in Source or Object form, provided that You * meet the following conditions: * * (a) You must give any other recipients of the Work or * Derivative Works a copy of this License; and * * (b) You must cause any modified files to carry prominent notices * stating that You changed the files; and * * (c) You must retain, in the Source form of any Derivative Works * that You distribute, all copyright, patent, trademark, and * attribution notices from the Source form of the Work, * excluding those notices that do not pertain to any part of * the Derivative Works; and * * (d) If the Work includes a "NOTICE" text file as part of its * distribution, then any Derivative Works that You distribute must * include a readable copy of the attribution notices contained * within such NOTICE file, excluding those notices that do not * pertain to any part of the Derivative Works, in at least one * of the following places: within a NOTICE text file distributed * as part of the Derivative Works; within the Source form or * documentation, if provided along with the Derivative Works; or, * within a display generated by the Derivative Works, if and * wherever such third-party notices normally appear. The contents * of the NOTICE file are for informational purposes only and * do not modify the License. You may add Your own attribution * notices within Derivative Works that You distribute, alongside * or as an addendum to the NOTICE text from the Work, provided * that such additional attribution notices cannot be construed * as modifying the License. * * You may add Your own copyright statement to Your modifications and * may provide additional or different license terms and conditions * for use, reproduction, or distribution of Your modifications, or * for any such Derivative Works as a whole, provided Your use, * reproduction, and distribution of the Work otherwise complies with * the conditions stated in this License. * * 5. Submission of Contributions. Unless You explicitly state otherwise, * any Contribution intentionally submitted for inclusion in the Work * by You to the Licensor shall be under the terms and conditions of * this License, without any additional terms or conditions. * Notwithstanding the above, nothing herein shall supersede or modify * the terms of any separate license agreement you may have executed * with Licensor regarding such Contributions. * * 6. Trademarks. This License does not grant permission to use the trade * names, trademarks, service marks, or product names of the Licensor, * except as required for reasonable and customary use in describing the * origin of the Work and reproducing the content of the NOTICE file. * * 7. Disclaimer of Warranty. Unless required by applicable law or * agreed to in writing, Licensor provides the Work (and each * Contributor provides its Contributions) on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied, including, without limitation, any warranties or conditions * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A * PARTICULAR PURPOSE. You are solely responsible for determining the * appropriateness of using or redistributing the Work and assume any * risks associated with Your exercise of permissions under this License. * * 8. Limitation of Liability. In no event and under no legal theory, * whether in tort (including negligence), contract, or otherwise, * unless required by applicable law (such as deliberate and grossly * negligent acts) or agreed to in writing, shall any Contributor be * liable to You for damages, including any direct, indirect, special, * incidental, or consequential damages of any character arising as a * result of this License or out of the use or inability to use the * Work (including but not limited to damages for loss of goodwill, * work stoppage, computer failure or malfunction, or any and all * other commercial damages or losses), even if such Contributor * has been advised of the possibility of such damages. * * 9. Accepting Warranty or Additional Liability. While redistributing * the Work or Derivative Works thereof, You may choose to offer, * and charge a fee for, acceptance of support, warranty, indemnity, * or other liability obligations and/or rights consistent with this * License. However, in accepting such obligations, You may act only * on Your own behalf and on Your sole responsibility, not on behalf * of any other Contributor, and only if You agree to indemnify, * defend, and hold each Contributor harmless for any liability * incurred by, or claims asserted against, such Contributor by reason * of your accepting any such warranty or additional liability. * * END OF TERMS AND CONDITIONS * * APPENDIX: How to apply the Apache License to your work. * * To apply the Apache License to your work, attach the following * boilerplate notice, with the fields enclosed by brackets "[]" * replaced with your own identifying information. (Don't include * the brackets!) The text should be enclosed in the appropriate * comment syntax for the file format. We also recommend that a * file or class name and description of purpose be included on the * same "printed page" as the copyright notice for easier * identification within third-party archives. * * Copyright 2016 Alibaba Group * * 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.taobao.weex; import android.content.Context; import android.text.TextUtils; import android.view.View; import android.view.ViewGroup; import android.widget.ScrollView; import com.taobao.weex.adapter.DefaultWXHttpAdapter; import com.taobao.weex.adapter.IWXHttpAdapter; import com.taobao.weex.adapter.IWXImgLoaderAdapter; import com.taobao.weex.adapter.IWXUserTrackAdapter; import com.taobao.weex.common.WXErrorCode; import com.taobao.weex.common.WXPerformance; import com.taobao.weex.common.WXRefreshData; import com.taobao.weex.common.WXRenderStrategy; import com.taobao.weex.common.WXRequest; import com.taobao.weex.common.WXResponse; import com.taobao.weex.http.WXHttpUtil; import com.taobao.weex.ui.WXRecycleImageManager; import com.taobao.weex.ui.component.WXComponent; import com.taobao.weex.ui.view.WXScrollView; import com.taobao.weex.ui.view.WXScrollView.WXScrollViewListener; import com.taobao.weex.utils.WXConst; import com.taobao.weex.utils.WXJsonUtils; import com.taobao.weex.utils.WXLogUtils; import com.taobao.weex.utils.WXReflectionUtils; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentLinkedQueue; /** * Each instance of WXSDKInstance represents an running weex instance. * It can be a pure weex view, or mixed with native view */ public class WXSDKInstance implements IWXActivityStateListener { public boolean mEnd = false; // adapters protected IWXUserTrackAdapter mUserTrackAdapter; protected IWXHttpAdapter mWXHttpAdapter; private IWXRenderListener mRenderListener; private Context mContext; private volatile String mInstanceId; public WXComponent getRootCom() { return mRootCom; } private WXComponent mRootCom; private boolean mRendered; private WXRefreshData mLastRefreshData; /** * Render strategy. */ private WXRenderStrategy mRenderStrategy = WXRenderStrategy.APPEND_ASYNC; /** * Width of weex's root container. */ private int mGodViewWidth = -1; /** * Height of weex's root container. */ private int mGodViewHeight = -1; /** * Render start time */ private long mRenderStartTime; /** * Refresh start time */ private long mRefreshStartTime; private WXRecycleImageManager mRecycleImageManager; private ConcurrentLinkedQueue<IWXActivityStateListener> mActivityStateListeners; private WXPerformance mWXPerformance; private ScrollView mScrollView; private WXScrollViewListener mWXScrollViewListener; private ViewGroup rootView; public WXSDKInstance(Context context) { init(context); } public void init(Context context) { mContext = context; mActivityStateListeners = new ConcurrentLinkedQueue<>(); mRecycleImageManager = new WXRecycleImageManager(this); mWXPerformance = new WXPerformance(); mWXPerformance.WXSDKVersion = WXEnvironment.WXSDK_VERSION; mWXPerformance.JSLibInitTime = WXEnvironment.sJSLibInitTime; mUserTrackAdapter=WXSDKManager.getInstance().getIWXUserTrackAdapter(); mWXHttpAdapter=WXSDKManager.getInstance().getIWXHttpAdapter(); } public void setBizType(String bizType) { if (!TextUtils.isEmpty(bizType)) { mWXPerformance.bizType = bizType; } } public ScrollView getScrollView() { return mScrollView; } public void setRootScrollView(ScrollView scrollView) { mScrollView = scrollView; if (mWXScrollViewListener != null) { ((WXScrollView) mScrollView).addScrollViewListener(mWXScrollViewListener); } } public void registerScrollViewListener(WXScrollViewListener scrollViewListener) { mWXScrollViewListener = scrollViewListener; } public WXScrollViewListener getScrollViewListener() { return mWXScrollViewListener; } @Deprecated public void setIWXUserTrackAdapter(IWXUserTrackAdapter adapter) { } /** * Render template asynchronously, use {@link WXRenderStrategy#APPEND_ASYNC} as render strategy * @param template bundle js * @param options os iphone/android/ipad * weexversion Weex version(like 1.0.0) * appversion App version(like 1.0.0) * devid Device id(like Aqh9z8dRJNBhmS9drLG5BKCmXhecHUXIZoXOctKwFebH) * sysversion Device system version(like 5.4.4、7.0.4, should be used with os) * sysmodel Device model(like iOS:"MGA82J/A", android:"MI NOTE LTE") * Time UNIX timestamp, UTC+08:00 * TTID(Optional) * MarkertId * Appname(Optional) tm,tb,qa * Bundleurl(Optional) template url * @param jsonInitData Initial data for rendering */ public void render(String template, Map<String, Object> options, String jsonInitData) { render(template, options, jsonInitData, WXRenderStrategy.APPEND_ASYNC); } /** * Render template asynchronously * @param template bundle js * @param options os iphone/android/ipad * weexversion Weex version(like 1.0.0) * appversion App version(like 1.0.0) * devid Device id(like Aqh9z8dRJNBhmS9drLG5BKCmXhecHUXIZoXOctKwFebH) * sysversion Device system version(like 5.4.4、7.0.4, should be used with os) * sysmodel Device model(like iOS:"MGA82J/A", android:"MI NOTE LTE") * Time UNIX timestamp, UTC+08:00 * TTID(Optional) * MarkertId * Appname(Optional) tm,tb,qa * Bundleurl(Optional) template url * @param jsonInitData Initial data for rendering * @param flag RenderStrategy {@link WXRenderStrategy} */ public void render(String template, Map<String, Object> options, String jsonInitData, WXRenderStrategy flag) { render(WXPerformance.DEFAULT, template, options, jsonInitData, -1, -1, flag); } /** * Render template asynchronously * * @param pageName, used for performance log. * @param template bundle js * @param options os iphone/android/ipad * weexversion Weex version(like 1.0.0) * appversion App version(like 1.0.0) * devid Device id(like Aqh9z8dRJNBhmS9drLG5BKCmXhecHUXIZoXOctKwFebH) * sysversion Device system version(like 5.4.4、7.0.4, should be used with os) * sysmodel Device model(like iOS:"MGA82J/A", android:"MI NOTE LTE") * Time UNIX timestamp, UTC+08:00 * TTID(Optional) * MarkertId * Appname(Optional) tm,tb,qa * Bundleurl(Optional) template url * @param jsonInitData Initial data for rendering * @param width Width of weex's root container, the default is match_parent * @param height Height of weex's root container, the default is match_parent * @param flag RenderStrategy {@link WXRenderStrategy} */ public void render(String pageName, String template, Map<String, Object> options, String jsonInitData, int width, int height, WXRenderStrategy flag) { if (mRendered || TextUtils.isEmpty(template)) { return; } if(options==null){ options=new HashMap<>(); } if(WXEnvironment.sDynamicMode && !TextUtils.isEmpty(WXEnvironment.sDynamicUrl) && options!=null && options.get("dynamicMode")==null){ options.put("dynamicMode","true"); renderByUrl(pageName,WXEnvironment.sDynamicUrl,options,jsonInitData,width,height,flag); return; } mWXPerformance.pageName = pageName; mWXPerformance.JSTemplateSize = template.length() / 1024; mRenderStartTime = System.currentTimeMillis(); mRenderStrategy = flag; mGodViewWidth = width; mGodViewHeight = height; mInstanceId = WXSDKManager.getInstance().generateInstanceId(); WXSDKManager.getInstance().createInstance(this, template, options, jsonInitData); mRendered = true; } /** * Render template asynchronously, use {@link WXRenderStrategy#APPEND_ASYNC} as render strategy * @param template bundle js * @param width default match_parent * @param height default match_parent */ public void render(String template, int width, int height) { render(WXPerformance.DEFAULT, template, null, null, width, height, mRenderStrategy); } public void renderByUrl(final String pageName, final String url, Map<String, Object> options, final String jsonInitData, final int width, final int height, final WXRenderStrategy flag) { IWXHttpAdapter adapter=WXSDKManager.getInstance().getIWXHttpAdapter(); if (adapter == null) { adapter = new DefaultWXHttpAdapter(); } WXRequest wxRequest = new WXRequest(); wxRequest.url = url; if (wxRequest.paramMap == null) { wxRequest.paramMap = new HashMap<String, Object>(); } wxRequest.paramMap.put("user-agent", WXHttpUtil.assembleUserAgent()); if (options == null) { options = new HashMap<String, Object>(); } if (!options.containsKey("bundleUrl")) { options.put("bundleUrl", url); } adapter.sendRequest(wxRequest, new WXHttpListener(pageName, options, jsonInitData, width, height, flag, System.currentTimeMillis())); mWXHttpAdapter = adapter; } /** * Refresh instance asynchronously. * @param data the new data */ public void refreshInstance(Map<String, Object> data) { if (data == null) { return; } refreshInstance(WXJsonUtils.fromObjectToJSONString(data)); } /** * Refresh instance asynchronously. * @param jsonData the new data */ public void refreshInstance(String jsonData) { if (jsonData == null) { return; } mRefreshStartTime = System.currentTimeMillis(); //cancel last refresh message if (mLastRefreshData != null) { mLastRefreshData.isDirty = true; } mLastRefreshData = new WXRefreshData(jsonData, false); WXSDKManager.getInstance().refreshInstance(mInstanceId, mLastRefreshData); } public WXRenderStrategy getRenderStrategy() { return mRenderStrategy; } public String getInstanceId() { return mInstanceId; } public Context getContext() { return mContext; } public int getWeexHeight() { return mGodViewHeight; } public int getWeexWidth() { return mGodViewWidth; } public WXRecycleImageManager getRecycleImageManager() { return mRecycleImageManager; } public IWXImgLoaderAdapter getImgLoaderAdapter() { return WXSDKManager.getInstance().getIWXImgLoaderAdapter(); } @Deprecated public void setImgLoaderAdapter(IWXImgLoaderAdapter adapter) { } public IWXHttpAdapter getWXHttpAdapter() { return WXSDKManager.getInstance().getIWXHttpAdapter(); } public void reloadImages() { if (mScrollView == null) { return; } if (mRecycleImageManager != null && mRecycleImageManager.isRecycleImage()) { WXSDKManager.getInstance().postOnUiThread(new Runnable() { @Override public void run() { if (mRecycleImageManager != null) { mRecycleImageManager.loadImage(); } } }, 250); } } /******************************** * begin register listener ********************************************************/ public void registerRenderListener(IWXRenderListener listener) { mRenderListener = listener; } public void registerActivityStateListener(IWXActivityStateListener listener) { if (listener == null) { return; } if (!mActivityStateListeners.contains(listener)) { mActivityStateListeners.add(listener); } } /******************************** * end register listener ********************************************************/ // WAActivityStateListener////////////////////////////////////////////////////////////////////////////////// @Override public void onActivityCreate() { for (IWXActivityStateListener listener : mActivityStateListeners) { listener.onActivityCreate(); } } @Override public void onActivityStart() { for (IWXActivityStateListener listener : mActivityStateListeners) { listener.onActivityStart(); } } @Override public void onActivityPause() { for (IWXActivityStateListener listener : mActivityStateListeners) { listener.onActivityPause(); } } @Override public void onActivityResume() { for (IWXActivityStateListener listener : mActivityStateListeners) { listener.onActivityResume(); } } @Override public void onActivityStop() { for (IWXActivityStateListener listener : mActivityStateListeners) { listener.onActivityStop(); } } @Override public void onActivityDestroy() { for (IWXActivityStateListener listener : mActivityStateListeners) { listener.onActivityDestroy(); } destroy(); } @Override public boolean onActivityBack() { for (IWXActivityStateListener listener : mActivityStateListeners) { boolean isIntercept = listener.onActivityBack(); if (isIntercept) { return true; } } return false; } public void onViewCreated(final WXComponent component) { if (mRenderListener != null && mContext != null) { runOnUiThread(new Runnable() { @Override public void run() { if (mRenderListener != null && mContext != null) { mRootCom = component; mRenderListener.onViewCreated(WXSDKInstance.this, component.getView()); } } }); } } public void runOnUiThread(Runnable action) { WXSDKManager.getInstance().postOnUiThread(action, 0); } public void onRenderSuccess(final int width, final int height) { long time = System.currentTimeMillis() - mRenderStartTime; WXLogUtils.renderPerformanceLog("onRenderSuccess", time); mWXPerformance.totalTime = time; WXLogUtils.d(WXLogUtils.WEEX_PERF_TAG, "mComponentNum:" + WXComponent.mComponentNum); WXComponent.mComponentNum = 0; if (mRenderListener != null && mContext != null) { runOnUiThread(new Runnable() { @Override public void run() { if (mRenderListener != null && mContext != null) { mRenderListener.onRenderSuccess(WXSDKInstance.this, width, height); if (WXEnvironment.isApkDebugable()) { WXLogUtils.d(WXLogUtils.WEEX_PERF_TAG, mWXPerformance.toString()); } if (mUserTrackAdapter != null) { mUserTrackAdapter.commit(mContext, null, WXConst.LOAD, mWXPerformance, null); } } } }); } } public void onRefreshSuccess(final int width, final int height) { WXLogUtils.renderPerformanceLog("onRefreshSuccess", (System.currentTimeMillis() - mRefreshStartTime)); if (mRenderListener != null && mContext != null) { runOnUiThread(new Runnable() { @Override public void run() { if (mRenderListener != null && mContext != null) { mRenderListener.onRefreshSuccess(WXSDKInstance.this, width, height); } } }); } } public void onRenderError(final String errCode, final String msg) { if (mRenderListener != null && mContext != null) { runOnUiThread(new Runnable() { @Override public void run() { if (mRenderListener != null && mContext != null) { mRenderListener.onException(WXSDKInstance.this, errCode, msg); } } }); } } public void onJSException(final String errCode, final String function, final String exception) { if (mRenderListener != null && mContext != null) { runOnUiThread(new Runnable() { @Override public void run() { if (mRenderListener != null && mContext != null) { StringBuilder builder = new StringBuilder(); builder.append(function); builder.append(exception); mRenderListener.onException(WXSDKInstance.this, errCode, builder.toString()); } } }); } } public void firstScreenRenderFinished(long endTime) { mEnd = true; long time = endTime - mRenderStartTime; mWXPerformance.screenRenderTime = time; WXLogUtils.renderPerformanceLog("firstScreenRenderFinished", time); } public void createInstanceFinished(long time) { if (time > 0) { mWXPerformance.communicateTime = time; } } /** * UserTrack Log */ public void commitUTStab(final String type, final WXErrorCode errorCode) { if (errorCode == WXErrorCode.WX_SUCCESS) { return; } runOnUiThread(new Runnable() { @Override public void run() { if (mUserTrackAdapter == null || TextUtils.isEmpty(type)) { return; } // Log for commit if (errorCode.getErrorCode() == null && errorCode.getErrorMsg() == null) { mUserTrackAdapter.commit(mContext, null, type, null, null); return; } WXPerformance perf = new WXPerformance(); perf.errCode = errorCode.getErrorCode(); perf.errMsg = errorCode.getErrorMsg(); if (WXEnvironment.isApkDebugable()) { WXLogUtils.d(perf.toString()); } mUserTrackAdapter.commit(mContext, null, type, perf, null); } }); } private void destroyView(View rootView) { try { if (rootView instanceof ViewGroup) { ViewGroup cViewGroup = ((ViewGroup) rootView); for (int index = 0; index < cViewGroup.getChildCount(); index++) { destroyView(cViewGroup.getChildAt(index)); } cViewGroup.removeViews(0, ((ViewGroup) rootView).getChildCount()); // Ensure that the viewgroup's status to be normal WXReflectionUtils.setValue(rootView, "mChildrenCount", 0); } } catch (Exception e) { WXLogUtils.e("WXSDKInstance destroyView Exception: " + WXLogUtils.getStackTrace(e)); } } public void destroy() { WXSDKManager.getInstance().destroyInstance(mInstanceId); if (mRecycleImageManager != null) { mRecycleImageManager.destroy(); mRecycleImageManager = null; } if (mRootCom != null && mRootCom.getView() != null) { mRootCom.destroy(); destroyView(mRootCom.getView()); mRootCom = null; } if (mActivityStateListeners != null) { mActivityStateListeners.clear(); mActivityStateListeners = null; } mContext = null; mRenderListener = null; } public ViewGroup getRootView() { return rootView; } public void setRootView(ViewGroup rootView) { this.rootView = rootView; } /** * load bundle js listener */ class WXHttpListener implements IWXHttpAdapter.OnHttpListener { private String pageName; private Map<String, Object> options; private String jsonInitData; private int width; private int height; private WXRenderStrategy flag; private long startRequestTime; private WXHttpListener(String pageName, Map<String, Object> options, String jsonInitData, int width, int height, WXRenderStrategy flag, long startRequestTime) { this.pageName = pageName; this.options = options; this.jsonInitData = jsonInitData; this.width = width; this.height = height; this.flag = flag; this.startRequestTime = startRequestTime; } @Override public void onHttpStart() { } @Override public void onHttpUploadProgress(int uploadProgress) { } @Override public void onHttpResponseProgress(int responseProgress) { } @Override public void onHttpFinish(WXResponse response) { mWXPerformance.networkTime = System.currentTimeMillis() - startRequestTime; WXLogUtils.renderPerformanceLog("networkTime", mWXPerformance.networkTime); if (TextUtils.equals("200", response.statusCode)) { String template = new String(response.originalData); render(pageName, template, options, jsonInitData, width, height, flag); } else if (TextUtils.equals(WXRenderErrorCode.WX_USER_INTERCEPT_ERROR, response.statusCode)) { WXLogUtils.d("user intercept"); onRenderError(WXRenderErrorCode.WX_USER_INTERCEPT_ERROR,response.errorMsg); } else { onRenderError(WXRenderErrorCode.WX_NETWORK_ERROR, response.errorMsg); } } } }
* [android] update WXSDKInstance.java
android/sdk/src/main/java/com/taobao/weex/WXSDKInstance.java
* [android] update WXSDKInstance.java
Java
apache-2.0
2780031fe84315e45059d14071b89954204f8eac
0
Bananeweizen/cgeo,samueltardieu/cgeo,ThibaultR/cgeo,Bananeweizen/cgeo,ThibaultR/cgeo,cgeo/cgeo,marco-dev/c-geo-opensource,mucek4/cgeo,cgeo/cgeo,superspindel/cgeo,kumy/cgeo,tobiasge/cgeo,rsudev/c-geo-opensource,tobiasge/cgeo,auricgoldfinger/cgeo,ThibaultR/cgeo,pstorch/cgeo,S-Bartfast/cgeo,matej116/cgeo,pstorch/cgeo,madankb/cgeo,madankb/cgeo,schwabe/cgeo,xiaoyanit/cgeo,Huertix/cgeo,schwabe/cgeo,KublaikhanGeek/cgeo,mucek4/cgeo,yummy222/cgeo,pstorch/cgeo,brok85/cgeo,lewurm/cgeo,matej116/cgeo,S-Bartfast/cgeo,yummy222/cgeo,Huertix/cgeo,SammysHP/cgeo,superspindel/cgeo,yummy222/cgeo,schwabe/cgeo,kumy/cgeo,Huertix/cgeo,cgeo/cgeo,superspindel/cgeo,mucek4/cgeo,kumy/cgeo,xiaoyanit/cgeo,lewurm/cgeo,KublaikhanGeek/cgeo,vishwakulkarni/cgeo,brok85/cgeo,SammysHP/cgeo,auricgoldfinger/cgeo,cgeo/cgeo,SammysHP/cgeo,matej116/cgeo,brok85/cgeo,rsudev/c-geo-opensource,samueltardieu/cgeo,samueltardieu/cgeo,vishwakulkarni/cgeo,KublaikhanGeek/cgeo,madankb/cgeo,auricgoldfinger/cgeo,Bananeweizen/cgeo,S-Bartfast/cgeo,vishwakulkarni/cgeo,marco-dev/c-geo-opensource,marco-dev/c-geo-opensource,rsudev/c-geo-opensource,schwabe/cgeo,lewurm/cgeo,tobiasge/cgeo,xiaoyanit/cgeo
package cgeo.geocaching.network; import cgeo.geocaching.CgeoApplication; import cgeo.geocaching.R; import cgeo.geocaching.compatibility.Compatibility; import cgeo.geocaching.connector.ConnectorFactory; import cgeo.geocaching.files.LocalStorage; import cgeo.geocaching.list.StoredList; import cgeo.geocaching.utils.CancellableHandler; import cgeo.geocaching.utils.FileUtils; import cgeo.geocaching.utils.ImageUtils; import cgeo.geocaching.utils.ImageUtils.ContainerDrawable; import cgeo.geocaching.utils.Log; import cgeo.geocaching.utils.RxUtils; import cgeo.geocaching.utils.RxUtils.ObservableCache; import ch.boye.httpclientandroidlib.HttpResponse; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; import rx.Observable; import rx.Observable.OnSubscribe; import rx.Subscriber; import rx.functions.Action0; import rx.functions.Func0; import rx.functions.Func1; import rx.subjects.PublishSubject; import rx.subscriptions.CompositeSubscription; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Point; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.text.Html; import android.widget.TextView; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Date; /** * All-purpose image getter that can also be used as a ImageGetter interface when displaying caches. */ public class HtmlImage implements Html.ImageGetter { private static final String[] BLOCKED = new String[] { "gccounter.de", "gccounter.com", "cachercounter/?", "gccounter/imgcount.php", "flagcounter.com", "compteur-blog.net", "counter.digits.com", "andyhoppe", "besucherzaehler-homepage.de", "hitwebcounter.com", "kostenloser-counter.eu", "trendcounter.com", "hit-counter-download.com", "gcwetterau.de/counter" }; public static final String SHARED = "shared"; final private String geocode; /** * on error: return large error image, if {@code true}, otherwise empty 1x1 image */ final private boolean returnErrorImage; final private int listId; final private boolean onlySave; final private int maxWidth; final private int maxHeight; final private Resources resources; protected final TextView view; final private ObservableCache<String, BitmapDrawable> observableCache = new ObservableCache<>(new Func1<String, Observable<BitmapDrawable>>() { @Override public Observable<BitmapDrawable> call(final String url) { return fetchDrawableUncached(url); } }); // Background loading final private PublishSubject<Observable<String>> loading = PublishSubject.create(); final private Observable<String> waitForEnd = Observable.merge(loading).cache(); final private CompositeSubscription subscription = new CompositeSubscription(waitForEnd.subscribe()); /** * Create a new HtmlImage object with different behaviours depending on <tt>onlySave</tt> and <tt>view</tt> values. * There are the three possible use cases: * <ul> * <li>If onlySave is true, {@link #getDrawable(String)} will return <tt>null</tt> immediately and will queue the image retrieval * and saving in the loading subject. Downloads will start in parallel when the blocking * {@link #waitForEndObservable(cgeo.geocaching.utils.CancellableHandler)} method is called, and they can be cancelled through the given handler.</li> * <li>If <tt>onlySave</tt> is <tt>false</tt> and the instance is called through {@link #fetchDrawable(String)}, then an observable for the * given URL will be returned. This observable will emit the local copy of the image if it is present * regardless of its freshness, then if needed an updated fresher copy after retrieving it from the network.</li> * <li>If <tt>onlySave</tt> is <tt>false</tt> and the instance is used as an {@link Html.ImageGetter}, only the final version of the * image will be returned, unless a view has been provided. If it has, then a dummy drawable is returned * and is updated when the image is available, possibly several times if we had a stale copy of the image * and then got a new one from the network.</li> * </ul> * * @param geocode the geocode of the item for which we are requesting the image * @param returnErrorImage set to <tt>true</tt> if an error image should be returned in case of a problem, * <tt>false</tt> to get a transparent 1x1 image instead * @param listId the list this cache belongs to, used to determine if an older image for the offline case can be used or not * @param onlySave if set to <tt>true</tt>, {@link #getDrawable(String)} will only fetch and store the image, not return it * @param view if non-null, {@link #getDrawable(String)} will return an initially empty drawable which will be redrawn when * the image is ready through an invalidation of the given view */ public HtmlImage(final String geocode, final boolean returnErrorImage, final int listId, final boolean onlySave, final TextView view) { this.geocode = geocode; this.returnErrorImage = returnErrorImage; this.listId = listId; this.onlySave = onlySave; this.view = view; final Point displaySize = Compatibility.getDisplaySize(); this.maxWidth = displaySize.x - 25; this.maxHeight = displaySize.y - 25; this.resources = CgeoApplication.getInstance().getResources(); } /** * Create a new HtmlImage object with different behaviours depending on <tt>onlySave</tt> value. No view object * will be tied to this HtmlImage. * * For documentation, see {@link #HtmlImage(String, boolean, int, boolean, TextView)}. */ public HtmlImage(final String geocode, final boolean returnErrorImage, final int listId, final boolean onlySave) { this(geocode, returnErrorImage, listId, onlySave, null); } /** * Retrieve and optionally display an image. * See {@link #HtmlImage(String, boolean, int, boolean, TextView)} for the various behaviours. * * @param url * the URL to fetch from cache or network * @return a drawable containing the image, or <tt>null</tt> if <tt>onlySave</tt> is <tt>true</tt> */ @Nullable @Override public BitmapDrawable getDrawable(final String url) { final Observable<BitmapDrawable> drawable = fetchDrawable(url); if (onlySave) { loading.onNext(drawable.map(new Func1<BitmapDrawable, String>() { @Override public String call(final BitmapDrawable bitmapDrawable) { return url; } })); return null; } return view == null ? drawable.toBlocking().lastOrDefault(null) : getContainerDrawable(drawable); } protected BitmapDrawable getContainerDrawable(final Observable<BitmapDrawable> drawable) { return new ContainerDrawable(view, drawable); } public Observable<BitmapDrawable> fetchDrawable(final String url) { return observableCache.get(url); } // Caches are loaded from disk on a computation scheduler to avoid using more threads than cores while decoding // the image. Downloads happen on downloadScheduler, in parallel with image decoding. private Observable<BitmapDrawable> fetchDrawableUncached(final String url) { if (StringUtils.isBlank(url) || ImageUtils.containsPattern(url, BLOCKED)) { return Observable.just(ImageUtils.getTransparent1x1Drawable(resources)); } // Explicit local file URLs are loaded from the filesystem regardless of their age. The IO part is short // enough to make the whole operation on the computation scheduler. if (FileUtils.isFileUrl(url)) { return Observable.defer(new Func0<Observable<BitmapDrawable>>() { @Override public Observable<BitmapDrawable> call() { final Bitmap bitmap = loadCachedImage(FileUtils.urlToFile(url), true).left; return bitmap != null ? Observable.just(ImageUtils.scaleBitmapToFitDisplay(bitmap)) : Observable.<BitmapDrawable>empty(); } }).subscribeOn(RxUtils.computationScheduler); } final boolean shared = url.contains("/images/icons/icon_"); final String pseudoGeocode = shared ? SHARED : geocode; return Observable.create(new OnSubscribe<BitmapDrawable>() { @Override public void call(final Subscriber<? super BitmapDrawable> subscriber) { subscription.add(subscriber); subscriber.add(RxUtils.computationScheduler.createWorker().schedule(new Action0() { @Override public void call() { final ImmutablePair<BitmapDrawable, Boolean> loaded = loadFromDisk(); final BitmapDrawable bitmap = loaded.left; if (loaded.right) { subscriber.onNext(bitmap); subscriber.onCompleted(); return; } if (bitmap != null && !onlySave) { subscriber.onNext(bitmap); } RxUtils.networkScheduler.createWorker().schedule(new Action0() { @Override public void call() { downloadAndSave(subscriber); } }); } })); } private ImmutablePair<BitmapDrawable, Boolean> loadFromDisk() { final ImmutablePair<Bitmap, Boolean> loadResult = loadImageFromStorage(url, pseudoGeocode, shared); return scaleImage(loadResult); } private void downloadAndSave(final Subscriber<? super BitmapDrawable> subscriber) { final File file = LocalStorage.getStorageFile(pseudoGeocode, url, true, true); if (url.startsWith("data:image/")) { if (url.contains(";base64,")) { ImageUtils.decodeBase64ToFile(StringUtils.substringAfter(url, ";base64,"), file); } else { Log.e("HtmlImage.getDrawable: unable to decode non-base64 inline image"); subscriber.onCompleted(); return; } } else if (subscriber.isUnsubscribed() || downloadOrRefreshCopy(url, file)) { // The existing copy was fresh enough or we were unsubscribed earlier. subscriber.onCompleted(); return; } if (onlySave) { subscriber.onCompleted(); return; } RxUtils.computationScheduler.createWorker().schedule(new Action0() { @Override public void call() { final ImmutablePair<BitmapDrawable, Boolean> loaded = loadFromDisk(); final BitmapDrawable image = loaded.left; if (image != null) { subscriber.onNext(image); } else { subscriber.onNext(returnErrorImage ? new BitmapDrawable(resources, BitmapFactory.decodeResource(resources, R.drawable.image_not_loaded)) : ImageUtils.getTransparent1x1Drawable(resources)); } subscriber.onCompleted(); } }); } }); } @SuppressWarnings("static-method") protected ImmutablePair<BitmapDrawable, Boolean> scaleImage(final ImmutablePair<Bitmap, Boolean> loadResult) { final Bitmap bitmap = loadResult.left; return ImmutablePair.of(bitmap != null ? ImageUtils.scaleBitmapToFitDisplay(bitmap) : null, loadResult.right); } public Observable<String> waitForEndObservable(@Nullable final CancellableHandler handler) { if (handler != null) { handler.unsubscribeIfCancelled(subscription); } loading.onCompleted(); return waitForEnd; } /** * Download or refresh the copy of <code>url</code> in <code>file</code>. * * @param url the url of the document * @param file the file to save the document in * @return <code>true</code> if the existing file was up-to-date, <code>false</code> otherwise */ private boolean downloadOrRefreshCopy(final String url, final File file) { final String absoluteURL = makeAbsoluteURL(url); if (absoluteURL != null) { try { final HttpResponse httpResponse = Network.getRequest(absoluteURL, null, file); if (httpResponse != null) { final int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode == 200) { LocalStorage.saveEntityToFile(httpResponse, file); } else if (statusCode == 304) { if (!file.setLastModified(System.currentTimeMillis())) { makeFreshCopy(file); } return true; } } } catch (final Exception e) { Log.e("HtmlImage.downloadOrRefreshCopy", e); } } return false; } /** * Make a fresh copy of the file to reset its timestamp. On some storage, it is impossible * to modify the modified time after the fact, in which case a brand new file must be * created if we want to be able to use the time as validity hint. * * See Android issue 1699. * * @param file the file to refresh */ private static void makeFreshCopy(final File file) { final File tempFile = new File(file.getParentFile(), file.getName() + "-temp"); if (file.renameTo(tempFile)) { LocalStorage.copy(tempFile, file); FileUtils.deleteIgnoringFailure(tempFile); } else { Log.e("Could not reset timestamp of file " + file.getAbsolutePath()); } } /** * Load an image from primary or secondary storage. * * @param url the image URL * @param pseudoGeocode the geocode or the shared name * @param forceKeep keep the image if it is there, without checking its freshness * @return A pair whose first element is the bitmap if available, and the second one is <code>true</code> if the image is present and fresh enough. */ @NonNull private ImmutablePair<Bitmap, Boolean> loadImageFromStorage(final String url, final String pseudoGeocode, final boolean forceKeep) { try { final File file = LocalStorage.getStorageFile(pseudoGeocode, url, true, false); final ImmutablePair<Bitmap, Boolean> image = loadCachedImage(file, forceKeep); if (image.right || image.left != null) { return image; } final File fileSec = LocalStorage.getStorageSecFile(pseudoGeocode, url, true); return loadCachedImage(fileSec, forceKeep); } catch (final Exception e) { Log.w("HtmlImage.loadImageFromStorage", e); } return ImmutablePair.of((Bitmap) null, false); } @Nullable private String makeAbsoluteURL(final String url) { // Check if uri is absolute or not, if not attach the connector hostname // FIXME: that should also include the scheme if (Uri.parse(url).isAbsolute()) { return url; } final String host = ConnectorFactory.getConnector(geocode).getHost(); if (StringUtils.isNotEmpty(host)) { final StringBuilder builder = new StringBuilder("http://"); builder.append(host); if (!StringUtils.startsWith(url, "/")) { // FIXME: explain why the result URL would be valid if the path does not start with // a '/', or signal an error. builder.append('/'); } builder.append(url); return builder.toString(); } return null; } /** * Load a previously saved image. * * @param file the file on disk * @param forceKeep keep the image if it is there, without checking its freshness * @return a pair with <code>true</code> in the second component if the image was there and is fresh enough or <code>false</code> otherwise, * and the image (possibly <code>null</code> if the second component is <code>false</code> and the image * could not be loaded, or if the second component is <code>true</code> and <code>onlySave</code> is also * <code>true</code>) */ @NonNull private ImmutablePair<Bitmap, Boolean> loadCachedImage(final File file, final boolean forceKeep) { if (file.exists()) { final boolean freshEnough = listId >= StoredList.STANDARD_LIST_ID || file.lastModified() > (new Date().getTime() - (24 * 60 * 60 * 1000)) || forceKeep; if (freshEnough && onlySave) { return ImmutablePair.of((Bitmap) null, true); } final BitmapFactory.Options bfOptions = new BitmapFactory.Options(); bfOptions.inTempStorage = new byte[16 * 1024]; bfOptions.inPreferredConfig = Bitmap.Config.RGB_565; setSampleSize(file, bfOptions); final Bitmap image = BitmapFactory.decodeFile(file.getPath(), bfOptions); if (image == null) { Log.e("Cannot decode bitmap from " + file.getPath()); return ImmutablePair.of((Bitmap) null, false); } return ImmutablePair.of(image, freshEnough); } return ImmutablePair.of((Bitmap) null, false); } private void setSampleSize(final File file, final BitmapFactory.Options bfOptions) { //Decode image size only final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BufferedInputStream stream = null; try { stream = new BufferedInputStream(new FileInputStream(file)); BitmapFactory.decodeStream(stream, null, options); } catch (final FileNotFoundException e) { Log.e("HtmlImage.setSampleSize", e); } finally { IOUtils.closeQuietly(stream); } int scale = 1; if (options.outHeight > maxHeight || options.outWidth > maxWidth) { scale = Math.max(options.outHeight / maxHeight, options.outWidth / maxWidth); } bfOptions.inSampleSize = scale; } }
main/src/cgeo/geocaching/network/HtmlImage.java
package cgeo.geocaching.network; import cgeo.geocaching.CgeoApplication; import cgeo.geocaching.R; import cgeo.geocaching.compatibility.Compatibility; import cgeo.geocaching.connector.ConnectorFactory; import cgeo.geocaching.files.LocalStorage; import cgeo.geocaching.list.StoredList; import cgeo.geocaching.utils.CancellableHandler; import cgeo.geocaching.utils.FileUtils; import cgeo.geocaching.utils.ImageUtils; import cgeo.geocaching.utils.ImageUtils.ContainerDrawable; import cgeo.geocaching.utils.Log; import cgeo.geocaching.utils.RxUtils; import cgeo.geocaching.utils.RxUtils.ObservableCache; import ch.boye.httpclientandroidlib.HttpResponse; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; import rx.Observable; import rx.Observable.OnSubscribe; import rx.Subscriber; import rx.functions.Action0; import rx.functions.Func0; import rx.functions.Func1; import rx.subjects.PublishSubject; import rx.subscriptions.CompositeSubscription; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Point; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.text.Html; import android.widget.TextView; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Date; /** * All-purpose image getter that can also be used as a ImageGetter interface when displaying caches. */ public class HtmlImage implements Html.ImageGetter { private static final String[] BLOCKED = new String[] { "gccounter.de", "gccounter.com", "cachercounter/?", "gccounter/imgcount.php", "flagcounter.com", "compteur-blog.net", "counter.digits.com", "andyhoppe", "besucherzaehler-homepage.de", "hitwebcounter.com", "kostenloser-counter.eu", "trendcounter.com", "hit-counter-download.com", "gcwetterau.de/counter" }; public static final String SHARED = "shared"; final private String geocode; /** * on error: return large error image, if {@code true}, otherwise empty 1x1 image */ final private boolean returnErrorImage; final private int listId; final private boolean onlySave; final private int maxWidth; final private int maxHeight; final private Resources resources; protected final TextView view; final private ObservableCache<String, BitmapDrawable> observableCache = new ObservableCache<>(new Func1<String, Observable<BitmapDrawable>>() { @Override public Observable<BitmapDrawable> call(final String url) { return fetchDrawableUncached(url); } }); // Background loading final private PublishSubject<Observable<String>> loading = PublishSubject.create(); final private Observable<String> waitForEnd = Observable.merge(loading).cache(); final private CompositeSubscription subscription = new CompositeSubscription(waitForEnd.subscribe()); /** * Create a new HtmlImage object with different behaviours depending on <tt>onlySave</tt> and <tt>view</tt> values. * There are the three possible use cases: * <ul> * <li>If onlySave is true, {@link #getDrawable(String)} will return <tt>null</tt> immediately and will queue the image retrieval * and saving in the loading subject. Downloads will start in parallel when the blocking * {@link #waitForEndObservable(cgeo.geocaching.utils.CancellableHandler)} method is called, and they can be cancelled through the given handler.</li> * <li>If <tt>onlySave</tt> is <tt>false</tt> and the instance is called through {@link #fetchDrawable(String)}, then an observable for the * given URL will be returned. This observable will emit the local copy of the image if it is present * regardless of its freshness, then if needed an updated fresher copy after retrieving it from the network.</li> * <li>If <tt>onlySave</tt> is <tt>false</tt> and the instance is used as an {@link Html.ImageGetter}, only the final version of the * image will be returned, unless a view has been provided. If it has, then a dummy drawable is returned * and is updated when the image is available, possibly several times if we had a stale copy of the image * and then got a new one from the network.</li> * </ul> * * @param geocode the geocode of the item for which we are requesting the image * @param returnErrorImage set to <tt>true</tt> if an error image should be returned in case of a problem, * <tt>false</tt> to get a transparent 1x1 image instead * @param listId the list this cache belongs to, used to determine if an older image for the offline case can be used or not * @param onlySave if set to <tt>true</tt>, {@link #getDrawable(String)} will only fetch and store the image, not return it * @param view if non-null, {@link #getDrawable(String)} will return an initially empty drawable which will be redrawn when * the image is ready through an invalidation of the given view */ public HtmlImage(final String geocode, final boolean returnErrorImage, final int listId, final boolean onlySave, final TextView view) { this.geocode = geocode; this.returnErrorImage = returnErrorImage; this.listId = listId; this.onlySave = onlySave; this.view = view; final Point displaySize = Compatibility.getDisplaySize(); this.maxWidth = displaySize.x - 25; this.maxHeight = displaySize.y - 25; this.resources = CgeoApplication.getInstance().getResources(); } /** * Create a new HtmlImage object with different behaviours depending on <tt>onlySave</tt> value. No view object * will be tied to this HtmlImage. * * For documentation, see {@link #HtmlImage(String, boolean, int, boolean, TextView)}. */ public HtmlImage(final String geocode, final boolean returnErrorImage, final int listId, final boolean onlySave) { this(geocode, returnErrorImage, listId, onlySave, null); } /** * Retrieve and optionally display an image. * See {@link #HtmlImage(String, boolean, int, boolean, TextView)} for the various behaviours. * * @param url * the URL to fetch from cache or network * @return a drawable containing the image, or <tt>null</tt> if <tt>onlySave</tt> is <tt>true</tt> */ @Nullable @Override public BitmapDrawable getDrawable(final String url) { final Observable<BitmapDrawable> drawable = fetchDrawable(url); if (onlySave) { loading.onNext(drawable.map(new Func1<BitmapDrawable, String>() { @Override public String call(final BitmapDrawable bitmapDrawable) { return url; } })); return null; } return view == null ? drawable.toBlocking().lastOrDefault(null) : getContainerDrawable(drawable); } protected BitmapDrawable getContainerDrawable(final Observable<BitmapDrawable> drawable) { return new ContainerDrawable(view, drawable); } public Observable<BitmapDrawable> fetchDrawable(final String url) { return observableCache.get(url); } // Caches are loaded from disk on a computation scheduler to avoid using more threads than cores while decoding // the image. Downloads happen on downloadScheduler, in parallel with image decoding. private Observable<BitmapDrawable> fetchDrawableUncached(final String url) { if (StringUtils.isBlank(url) || ImageUtils.containsPattern(url, BLOCKED)) { return Observable.just(ImageUtils.getTransparent1x1Drawable(resources)); } // Explicit local file URLs are loaded from the filesystem regardless of their age. The IO part is short // enough to make the whole operation on the computation scheduler. if (FileUtils.isFileUrl(url)) { return Observable.defer(new Func0<Observable<BitmapDrawable>>() { @Override public Observable<BitmapDrawable> call() { final Bitmap bitmap = loadCachedImage(FileUtils.urlToFile(url), true).left; return bitmap != null ? Observable.just(ImageUtils.scaleBitmapToFitDisplay(bitmap)) : Observable.<BitmapDrawable>empty(); } }).subscribeOn(RxUtils.computationScheduler); } final boolean shared = url.contains("/images/icons/icon_"); final String pseudoGeocode = shared ? SHARED : geocode; return Observable.create(new OnSubscribe<BitmapDrawable>() { @Override public void call(final Subscriber<? super BitmapDrawable> subscriber) { subscription.add(subscriber); subscriber.add(RxUtils.computationScheduler.createWorker().schedule(new Action0() { @Override public void call() { final ImmutablePair<BitmapDrawable, Boolean> loaded = loadFromDisk(); final BitmapDrawable bitmap = loaded.left; if (loaded.right) { subscriber.onNext(bitmap); subscriber.onCompleted(); return; } if (bitmap != null && !onlySave) { subscriber.onNext(bitmap); } RxUtils.networkScheduler.createWorker().schedule(new Action0() { @Override public void call() { downloadAndSave(subscriber); } }); } })); } private ImmutablePair<BitmapDrawable, Boolean> loadFromDisk() { final ImmutablePair<Bitmap, Boolean> loadResult = loadImageFromStorage(url, pseudoGeocode, shared); return scaleImage(loadResult); } private void downloadAndSave(final Subscriber<? super BitmapDrawable> subscriber) { final File file = LocalStorage.getStorageFile(pseudoGeocode, url, true, true); if (url.startsWith("data:image/")) { if (url.contains(";base64,")) { ImageUtils.decodeBase64ToFile(StringUtils.substringAfter(url, ";base64,"), file); } else { Log.e("HtmlImage.getDrawable: unable to decode non-base64 inline image"); subscriber.onCompleted(); return; } } else if (subscriber.isUnsubscribed() || downloadOrRefreshCopy(url, file)) { // The existing copy was fresh enough or we were unsubscribed earlier. subscriber.onCompleted(); return; } if (onlySave) { Log.d("onlySave, returning"); subscriber.onCompleted(); return; } RxUtils.computationScheduler.createWorker().schedule(new Action0() { @Override public void call() { final ImmutablePair<BitmapDrawable, Boolean> loaded = loadFromDisk(); final BitmapDrawable image = loaded.left; if (image != null) { subscriber.onNext(image); } else { subscriber.onNext(returnErrorImage ? new BitmapDrawable(resources, BitmapFactory.decodeResource(resources, R.drawable.image_not_loaded)) : ImageUtils.getTransparent1x1Drawable(resources)); } subscriber.onCompleted(); } }); } }); } @SuppressWarnings("static-method") protected ImmutablePair<BitmapDrawable, Boolean> scaleImage(final ImmutablePair<Bitmap, Boolean> loadResult) { final Bitmap bitmap = loadResult.left; return ImmutablePair.of(bitmap != null ? ImageUtils.scaleBitmapToFitDisplay(bitmap) : null, loadResult.right); } public Observable<String> waitForEndObservable(@Nullable final CancellableHandler handler) { if (handler != null) { handler.unsubscribeIfCancelled(subscription); } loading.onCompleted(); return waitForEnd; } /** * Download or refresh the copy of <code>url</code> in <code>file</code>. * * @param url the url of the document * @param file the file to save the document in * @return <code>true</code> if the existing file was up-to-date, <code>false</code> otherwise */ private boolean downloadOrRefreshCopy(final String url, final File file) { final String absoluteURL = makeAbsoluteURL(url); if (absoluteURL != null) { try { final HttpResponse httpResponse = Network.getRequest(absoluteURL, null, file); if (httpResponse != null) { final int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode == 200) { LocalStorage.saveEntityToFile(httpResponse, file); } else if (statusCode == 304) { if (!file.setLastModified(System.currentTimeMillis())) { makeFreshCopy(file); } return true; } } } catch (final Exception e) { Log.e("HtmlImage.downloadOrRefreshCopy", e); } } return false; } /** * Make a fresh copy of the file to reset its timestamp. On some storage, it is impossible * to modify the modified time after the fact, in which case a brand new file must be * created if we want to be able to use the time as validity hint. * * See Android issue 1699. * * @param file the file to refresh */ private static void makeFreshCopy(final File file) { final File tempFile = new File(file.getParentFile(), file.getName() + "-temp"); if (file.renameTo(tempFile)) { LocalStorage.copy(tempFile, file); FileUtils.deleteIgnoringFailure(tempFile); } else { Log.e("Could not reset timestamp of file " + file.getAbsolutePath()); } } /** * Load an image from primary or secondary storage. * * @param url the image URL * @param pseudoGeocode the geocode or the shared name * @param forceKeep keep the image if it is there, without checking its freshness * @return A pair whose first element is the bitmap if available, and the second one is <code>true</code> if the image is present and fresh enough. */ @NonNull private ImmutablePair<Bitmap, Boolean> loadImageFromStorage(final String url, final String pseudoGeocode, final boolean forceKeep) { try { final File file = LocalStorage.getStorageFile(pseudoGeocode, url, true, false); final ImmutablePair<Bitmap, Boolean> image = loadCachedImage(file, forceKeep); if (image.right || image.left != null) { return image; } final File fileSec = LocalStorage.getStorageSecFile(pseudoGeocode, url, true); return loadCachedImage(fileSec, forceKeep); } catch (final Exception e) { Log.w("HtmlImage.loadImageFromStorage", e); } return ImmutablePair.of((Bitmap) null, false); } @Nullable private String makeAbsoluteURL(final String url) { // Check if uri is absolute or not, if not attach the connector hostname // FIXME: that should also include the scheme if (Uri.parse(url).isAbsolute()) { return url; } final String host = ConnectorFactory.getConnector(geocode).getHost(); if (StringUtils.isNotEmpty(host)) { final StringBuilder builder = new StringBuilder("http://"); builder.append(host); if (!StringUtils.startsWith(url, "/")) { // FIXME: explain why the result URL would be valid if the path does not start with // a '/', or signal an error. builder.append('/'); } builder.append(url); return builder.toString(); } return null; } /** * Load a previously saved image. * * @param file the file on disk * @param forceKeep keep the image if it is there, without checking its freshness * @return a pair with <code>true</code> in the second component if the image was there and is fresh enough or <code>false</code> otherwise, * and the image (possibly <code>null</code> if the second component is <code>false</code> and the image * could not be loaded, or if the second component is <code>true</code> and <code>onlySave</code> is also * <code>true</code>) */ @NonNull private ImmutablePair<Bitmap, Boolean> loadCachedImage(final File file, final boolean forceKeep) { if (file.exists()) { final boolean freshEnough = listId >= StoredList.STANDARD_LIST_ID || file.lastModified() > (new Date().getTime() - (24 * 60 * 60 * 1000)) || forceKeep; if (freshEnough && onlySave) { return ImmutablePair.of((Bitmap) null, true); } final BitmapFactory.Options bfOptions = new BitmapFactory.Options(); bfOptions.inTempStorage = new byte[16 * 1024]; bfOptions.inPreferredConfig = Bitmap.Config.RGB_565; setSampleSize(file, bfOptions); final Bitmap image = BitmapFactory.decodeFile(file.getPath(), bfOptions); if (image == null) { Log.e("Cannot decode bitmap from " + file.getPath()); return ImmutablePair.of((Bitmap) null, false); } return ImmutablePair.of(image, freshEnough); } return ImmutablePair.of((Bitmap) null, false); } private void setSampleSize(final File file, final BitmapFactory.Options bfOptions) { //Decode image size only final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BufferedInputStream stream = null; try { stream = new BufferedInputStream(new FileInputStream(file)); BitmapFactory.decodeStream(stream, null, options); } catch (final FileNotFoundException e) { Log.e("HtmlImage.setSampleSize", e); } finally { IOUtils.closeQuietly(stream); } int scale = 1; if (options.outHeight > maxHeight || options.outWidth > maxWidth) { scale = Math.max(options.outHeight / maxHeight, options.outWidth / maxWidth); } bfOptions.inSampleSize = scale; } }
Remove extra debugging information
main/src/cgeo/geocaching/network/HtmlImage.java
Remove extra debugging information
Java
apache-2.0
8aa551ce52c307bfe842a2206a6a7e6c4db83347
0
orekyuu/intellij-community,joewalnes/idea-community,alphafoobar/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,supersven/intellij-community,da1z/intellij-community,fnouama/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,fnouama/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,izonder/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,adedayo/intellij-community,signed/intellij-community,da1z/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,ibinti/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,kdwink/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,kool79/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,vladmm/intellij-community,ernestp/consulo,kool79/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,ernestp/consulo,adedayo/intellij-community,jagguli/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,caot/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,diorcety/intellij-community,kool79/intellij-community,wreckJ/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,xfournet/intellij-community,asedunov/intellij-community,fitermay/intellij-community,jexp/idea2,vvv1559/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,signed/intellij-community,amith01994/intellij-community,amith01994/intellij-community,clumsy/intellij-community,signed/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,slisson/intellij-community,caot/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,joewalnes/idea-community,consulo/consulo,akosyakov/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,caot/intellij-community,signed/intellij-community,jexp/idea2,suncycheng/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,dslomov/intellij-community,clumsy/intellij-community,robovm/robovm-studio,diorcety/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,kool79/intellij-community,joewalnes/idea-community,ftomassetti/intellij-community,hurricup/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,holmes/intellij-community,ryano144/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,vladmm/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,blademainer/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,caot/intellij-community,youdonghai/intellij-community,caot/intellij-community,dslomov/intellij-community,fnouama/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,caot/intellij-community,holmes/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,jexp/idea2,fitermay/intellij-community,ibinti/intellij-community,izonder/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,hurricup/intellij-community,da1z/intellij-community,petteyg/intellij-community,xfournet/intellij-community,ibinti/intellij-community,jagguli/intellij-community,asedunov/intellij-community,semonte/intellij-community,da1z/intellij-community,jagguli/intellij-community,ernestp/consulo,ahb0327/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,amith01994/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,allotria/intellij-community,vvv1559/intellij-community,semonte/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,asedunov/intellij-community,kdwink/intellij-community,jagguli/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,amith01994/intellij-community,signed/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,xfournet/intellij-community,diorcety/intellij-community,izonder/intellij-community,blademainer/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,signed/intellij-community,kdwink/intellij-community,apixandru/intellij-community,ryano144/intellij-community,amith01994/intellij-community,xfournet/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,joewalnes/idea-community,supersven/intellij-community,petteyg/intellij-community,asedunov/intellij-community,semonte/intellij-community,caot/intellij-community,slisson/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,ernestp/consulo,adedayo/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,kool79/intellij-community,jagguli/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,jexp/idea2,izonder/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,ryano144/intellij-community,semonte/intellij-community,retomerz/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,samthor/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,supersven/intellij-community,retomerz/intellij-community,ibinti/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,jagguli/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,samthor/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,supersven/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,fitermay/intellij-community,joewalnes/idea-community,gnuhub/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,retomerz/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,allotria/intellij-community,consulo/consulo,blademainer/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,joewalnes/idea-community,samthor/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,jexp/idea2,robovm/robovm-studio,retomerz/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,caot/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,hurricup/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,vladmm/intellij-community,dslomov/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,pwoodworth/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,semonte/intellij-community,suncycheng/intellij-community,joewalnes/idea-community,tmpgit/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,ibinti/intellij-community,izonder/intellij-community,holmes/intellij-community,samthor/intellij-community,vladmm/intellij-community,retomerz/intellij-community,allotria/intellij-community,semonte/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,xfournet/intellij-community,allotria/intellij-community,amith01994/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,dslomov/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,holmes/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,kdwink/intellij-community,holmes/intellij-community,ernestp/consulo,ryano144/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,consulo/consulo,michaelgallacher/intellij-community,tmpgit/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,dslomov/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,consulo/consulo,ahb0327/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,jagguli/intellij-community,adedayo/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,vvv1559/intellij-community,allotria/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,robovm/robovm-studio,retomerz/intellij-community,nicolargo/intellij-community,semonte/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,alphafoobar/intellij-community,jexp/idea2,signed/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,diorcety/intellij-community,clumsy/intellij-community,fitermay/intellij-community,samthor/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,caot/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,joewalnes/idea-community,suncycheng/intellij-community,allotria/intellij-community,petteyg/intellij-community,jagguli/intellij-community,holmes/intellij-community,ibinti/intellij-community,robovm/robovm-studio,signed/intellij-community,joewalnes/idea-community,apixandru/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,jexp/idea2,tmpgit/intellij-community,kdwink/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,orekyuu/intellij-community,da1z/intellij-community,ahb0327/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,jexp/idea2,asedunov/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,ernestp/consulo,supersven/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,izonder/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,diorcety/intellij-community,slisson/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,signed/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,hurricup/intellij-community,samthor/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,caot/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,ibinti/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,diorcety/intellij-community,semonte/intellij-community,ahb0327/intellij-community,da1z/intellij-community,diorcety/intellij-community,caot/intellij-community,amith01994/intellij-community,consulo/consulo,muntasirsyed/intellij-community,retomerz/intellij-community,consulo/consulo,ryano144/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,izonder/intellij-community,blademainer/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,hurricup/intellij-community,xfournet/intellij-community,da1z/intellij-community,dslomov/intellij-community,xfournet/intellij-community,retomerz/intellij-community,fitermay/intellij-community,samthor/intellij-community,petteyg/intellij-community,da1z/intellij-community
/* * Copyright (c) 2000-2004 by JetBrains s.r.o. All Rights Reserved. * Use is subject to license terms. */ package com.intellij.ide.dnd; import com.intellij.openapi.application.Application; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Pair; import com.intellij.ui.awt.RelativeRectangle; import com.intellij.util.ui.GeometryUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.*; import java.awt.dnd.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.lang.ref.WeakReference; public class DnDManagerImpl extends DnDManager implements DnDEvent.DropTargetHighlightingType { private static final Logger LOG = Logger.getInstance("com.intellij.ide.dnd.DnDManager"); static final @NonNls String SOURCE_KEY = "DnD Source"; static final @NonNls String TARGET_KEY = "DnD Target"; public static final Key<Pair<Image, Point>> DRAGGED_IMAGE_KEY = new Key<Pair<Image, Point>>("draggedImage"); private DnDEventImpl myCurrentEvent; private DnDEvent myLastHighlightedEvent; private static DnDTarget NULL_TARGET = new NullTarget(); private WeakReference<DnDTarget> myLastProcessedTarget = new WeakReference<DnDTarget>(NULL_TARGET); private DragSourceContext myCurrentDragContext; private Component myLastProcessedOverComponent; private Point myLastProcessedPoint; private String myLastMessage; private DnDEvent myLastProcessedEvent; private DragGestureListener myDragGestureListener = new MyDragGestureListnener(); private DropTargetListener myDropTargetListener = new MyDropTargetListener(); private static final Image EMPTY_IMAGE = new BufferedImage(1, 1, Transparency.TRANSLUCENT); private Timer myTooltipTimer = new Timer(ToolTipManager.sharedInstance().getInitialDelay(), new ActionListener() { public void actionPerformed(ActionEvent e) { onTimer(); } }); private Runnable myHightlighterShowRequest; private Rectangle myLastHighlightedRec; private int myLastProcessedAction; private Application myApp; public DnDManagerImpl(final Application app) { myApp = app; myTooltipTimer.start(); } public void registerSource(@NotNull final AdvancedDnDSource source) { if (!getApplication().isHeadlessEnvironment()) { final JComponent c = source.getComponent(); registerSource(source, c); final DnDEnabler enabler = new DnDEnabler(source, source); c.putClientProperty(DnDEnabler.KEY, enabler); } } public void registerSource(DnDSource source, JComponent component) { if (!getApplication().isHeadlessEnvironment()) { component.putClientProperty(SOURCE_KEY, source); final DragSource defaultDragSource = DragSource.getDefaultDragSource(); defaultDragSource.createDefaultDragGestureRecognizer(component, DnDConstants.ACTION_COPY_OR_MOVE, myDragGestureListener); } } public void unregisterSource(AdvancedDnDSource source) { final JComponent c = source.getComponent(); if (c != null) { final DnDEnabler enabler = (DnDEnabler)c.getClientProperty(DnDEnabler.KEY); if (enabler != null) { Disposer.dispose(enabler); c.putClientProperty(DnDEnabler.KEY, null); } } unregisterSource(source, c); } public void unregisterSource(DnDSource source, JComponent component) { component.putClientProperty(SOURCE_KEY, null); cleanup(); } private void cleanup() { Runnable cleanup = new Runnable() { public void run() { myLastProcessedOverComponent = null; myCurrentDragContext = null; myCurrentEvent = null; } }; if (myApp.isDispatchThread()) { cleanup.run(); } else { SwingUtilities.invokeLater(cleanup); } } public void registerTarget(DnDTarget target, JComponent component) { if (!getApplication().isHeadlessEnvironment()) { component.putClientProperty(TARGET_KEY, target); new DropTarget(component, DnDConstants.ACTION_COPY_OR_MOVE, myDropTargetListener); } } public void unregisterTarget(DnDTarget target, JComponent component) { component.putClientProperty(TARGET_KEY, null); cleanup(); } private void updateCurrentEvent(Component aComponentOverDragging, Point aPoint, int nativeAction) { LOG.debug("updateCurrentEvent: " + aComponentOverDragging); if (myCurrentDragContext == null) return; if (myCurrentEvent == null) return; myCurrentEvent.updateAction(getDnDActionForPlatformAction(nativeAction)); myCurrentEvent.setPoint(aPoint); myCurrentEvent.setHandlerComponent(aComponentOverDragging); boolean samePoint = myCurrentEvent.getPoint().equals(myLastProcessedPoint); boolean sameComponent = myCurrentEvent.getCurrentOverComponent().equals(myLastProcessedOverComponent); boolean sameAction = (nativeAction == myLastProcessedAction); LOG.debug("updateCurrentEvent: point:" + aPoint); LOG.debug("updateCurrentEvent: action:" + nativeAction); if (samePoint && sameComponent && sameAction) { return; } DnDTarget target = getTarget(aComponentOverDragging); DnDTarget immediateTarget = target; Component eachParent = aComponentOverDragging; final Pair<Image, Point> pair = myCurrentEvent.getUserData(DRAGGED_IMAGE_KEY); if (pair != null) { target.updateDraggedImage(pair.first, aPoint, pair.second); } LOG.debug("updateCurrentEvent: action:" + nativeAction); while (true) { boolean canGoToParent = update(target); if (myCurrentEvent.isDropPossible()) { if (myCurrentEvent.wasDelegated()) { target = myCurrentEvent.getDelegatedTarget(); } break; } if (!canGoToParent) { break; } eachParent = findAllowedParentComponent(eachParent); if (eachParent == null) { break; } target = getTarget(eachParent); } LOG.debug("updateCurrentEvent: target:" + target); LOG.debug("updateCurrentEvent: immediateTarget:" + immediateTarget); if (!myCurrentEvent.isDropPossible() && !immediateTarget.equals(target)) { update(immediateTarget); } updateCursor(); final Container current = (Container)myCurrentEvent.getCurrentOverComponent(); final Point point = myCurrentEvent.getPointOn(getLayeredPane(current)); Rectangle inPlaceRect = new Rectangle(point.x - 5, point.y - 5, 5, 5); if (!myCurrentEvent.equals(myLastProcessedEvent)) { hideCurrentHighlighter(); } boolean sameTarget = getLastProcessedTarget() != null && getLastProcessedTarget().equals(target); if (sameTarget) { if (myCurrentEvent.isDropPossible()) { if (!myLastProcessedPoint.equals(myCurrentEvent.getPoint())) { if (!Highlighters.isVisibleExcept(TEXT | ERROR_TEXT)) { hideCurrentHighlighter(); restartTimer(); queueTooltip(myCurrentEvent, getLayeredPane(current), inPlaceRect); } } } else { if (myLastProcessedPoint == null || myCurrentEvent == null || !myLastProcessedPoint.equals(myCurrentEvent.getPoint())) { hideCurrentHighlighter(); restartTimer(); queueTooltip(myCurrentEvent, getLayeredPane(current), inPlaceRect); } } } else { hideCurrentHighlighter(); getLastProcessedTarget().cleanUpOnLeave(); myCurrentEvent.clearDropHandler(); restartTimer(); if (!myCurrentEvent.isDropPossible()) { queueTooltip(myCurrentEvent, getLayeredPane(current), inPlaceRect); } } myLastProcessedTarget = new WeakReference<DnDTarget>(target); myLastProcessedPoint = myCurrentEvent.getPoint(); myLastProcessedOverComponent = myCurrentEvent.getCurrentOverComponent(); myLastProcessedAction = myCurrentEvent.getAction().getActionId(); myLastProcessedEvent = (DnDEvent)myCurrentEvent.clone(); } private void updateCursor() { Cursor cursor; if (myCurrentEvent.isDropPossible()) { cursor = myCurrentEvent.getCursor(); if (cursor == null) { cursor = myCurrentEvent.getAction().getCursor(); } } else { cursor = myCurrentEvent.getAction().getRejectCursor(); } myCurrentDragContext.setCursor(cursor); } private void restartTimer() { myTooltipTimer.restart(); } private boolean update(DnDTarget target) { LOG.debug("update target:" + target); myCurrentEvent.clearDelegatedTarget(); final boolean canGoToParent = target.update(myCurrentEvent); String message; if (isMessageProvided(myCurrentEvent)) { message = myCurrentEvent.getExpectedDropResult(); } else { message = ""; } //final WindowManager wm = WindowManager.getInstance(); //final StatusBar statusBar = wm.getStatusBar(target.getProject()); //statusBar.setInfo(message); if (myLastMessage != null && !myLastMessage.equals(message)) { hideCurrentHighlighter(); } myLastMessage = message; return canGoToParent; } private static Component findAllowedParentComponent(Component aComponentOverDragging) { Component eachParent = aComponentOverDragging; while (true) { eachParent = eachParent.getParent(); if (eachParent == null) { return null; } final DnDTarget target = getTarget(eachParent); if (target != NULL_TARGET) { return eachParent; } } } private static DnDSource getSource(Component component) { if (component instanceof JComponent) { return (DnDSource)((JComponent)component).getClientProperty(SOURCE_KEY); } return null; } private static DnDTarget getTarget(Component component) { if (component instanceof JComponent) { DnDTarget target = (DnDTarget)((JComponent)component).getClientProperty(TARGET_KEY); if (target != null) return target; } return NULL_TARGET; } void showHighlighter(final Component aComponent, final int aType, final DnDEvent aEvent) { final Rectangle bounds = aComponent.getBounds(); final Container parent = aComponent.getParent(); showHighlighter(parent, aEvent, bounds, aType); } void showHighlighter(final RelativeRectangle rectangle, final int aType, final DnDEvent aEvent) { final JLayeredPane layeredPane = getLayeredPane(rectangle.getPoint().getComponent()); final Rectangle bounds = rectangle.getRectangleOn(layeredPane); showHighlighter(layeredPane, aEvent, bounds, aType); } void showHighlighter(JLayeredPane layeredPane, final RelativeRectangle rectangle, final int aType, final DnDEvent event) { final Rectangle bounds = rectangle.getRectangleOn(layeredPane); showHighlighter(layeredPane, event, bounds, aType); } private boolean isEventBeingHighlighted(DnDEvent event) { return event.equals(getLastHighlightedEvent()); } private void showHighlighter(final Component parent, final DnDEvent aEvent, final Rectangle bounds, final int aType) { final JLayeredPane layeredPane = getLayeredPane(parent); if (layeredPane == null) { return; } if (isEventBeingHighlighted(aEvent)) { if (GeometryUtil.isWithin(myLastHighlightedRec, aEvent.getPointOn(layeredPane))) { return; } } final Rectangle rectangle = SwingUtilities.convertRectangle(parent, bounds, layeredPane); setLastHighlightedEvent((DnDEvent)((DnDEventImpl)aEvent).clone(), rectangle); Highlighters.hide(); Highlighters.show(aType, layeredPane, rectangle, aEvent); if (isMessageProvided(aEvent)) { queueTooltip(aEvent, layeredPane, rectangle); } else { Highlighters.hide(TEXT | ERROR_TEXT); } } private void queueTooltip(final DnDEvent aEvent, final JLayeredPane aLayeredPane, final Rectangle aRectangle) { myHightlighterShowRequest = new Runnable() { public void run() { if (myCurrentEvent != aEvent) return; Highlighters.hide(TEXT | ERROR_TEXT); if (aEvent.isDropPossible()) { Highlighters.show(TEXT, aLayeredPane, aRectangle, aEvent); } else { Highlighters.show(ERROR_TEXT, aLayeredPane, aRectangle, aEvent); } } }; } private static boolean isMessageProvided(final DnDEvent aEvent) { return aEvent.getExpectedDropResult() != null && aEvent.getExpectedDropResult().trim().length() > 0; } void hideCurrentHighlighter() { Highlighters.hide(); myHightlighterShowRequest = null; setLastHighlightedEvent(null, null); } private void onTimer() { if (myHightlighterShowRequest != null) { myHightlighterShowRequest.run(); myHightlighterShowRequest = null; } } private static JLayeredPane getLayeredPane(Component aComponent) { if (aComponent == null) return null; if (aComponent instanceof JLayeredPane) { return (JLayeredPane)aComponent; } if (aComponent instanceof JFrame) { return ((JFrame)aComponent).getRootPane().getLayeredPane(); } if (aComponent instanceof JDialog) { return ((JDialog)aComponent).getRootPane().getLayeredPane(); } final Window window = SwingUtilities.getWindowAncestor(aComponent); if (window instanceof JFrame) { return ((JFrame) window).getRootPane().getLayeredPane(); } else if (window instanceof JDialog) { return ((JDialog) window).getRootPane().getLayeredPane(); } return null; } private DnDTarget getLastProcessedTarget() { return myLastProcessedTarget.get(); } private static class NullTarget implements DnDTarget { public boolean update(DnDEvent aEvent) { aEvent.setDropPossible(false, "You cannot drop anything here"); return false; } public void drop(DnDEvent aEvent) { } public void cleanUpOnLeave() { } public void updateDraggedImage(Image image, Point dropPoint, Point imageOffset) { } } DnDEvent getCurrentEvent() { return myCurrentEvent; } private DnDEvent getLastHighlightedEvent() { return myLastHighlightedEvent; } private void setLastHighlightedEvent(DnDEvent lastHighlightedEvent, Rectangle aRectangle) { myLastHighlightedEvent = lastHighlightedEvent; myLastHighlightedRec = aRectangle; } private void resetCurrentEvent(@NonNls String s) { myCurrentEvent = null; LOG.debug("Reset Current Event: " + s); } private class MyDragGestureListnener implements DragGestureListener { public void dragGestureRecognized(DragGestureEvent dge) { final DnDSource source = getSource(dge.getComponent()); if (source == null) return; DnDAction action = getDnDActionForPlatformAction(dge.getDragAction()); if (source.canStartDragging(action, dge.getDragOrigin())) { if (myCurrentEvent == null) { // Actually, under Linux it is possible to get 2 or more dragGestureRecognized calls for single drag // operation. To reproduce: // 1. Do D-n-D in Styles tree // 2. Make an attempt to do D-n-D in Services tree // 3. Do D-n-D in Styles tree again. LOG.debug("Starting dragging for " + action); hideCurrentHighlighter(); final DnDDragStartBean dnDDragStartBean = source.startDragging(action, dge.getDragOrigin()); myCurrentEvent = new DnDEventImpl(DnDManagerImpl.this, action, dnDDragStartBean.getAttachedObject(), dnDDragStartBean.getPoint()); myCurrentEvent.setOrgPoint(dge.getDragOrigin()); Pair<Image, Point> pair = source.createDraggedImage(action, dge.getDragOrigin()); if (pair == null) { pair = new Pair<Image, Point>(EMPTY_IMAGE, new Point(0, 0)); } if (!DragSource.isDragImageSupported()) { // not all of the platforms supports image dragging (mswin doesn't, for example). myCurrentEvent.putUserData(DRAGGED_IMAGE_KEY, pair); } // mac osx fix: it will draw a border with size of the dragged component if there is no image provided. dge.startDrag(DragSource.DefaultCopyDrop, pair.first, pair.second, myCurrentEvent, new MyDragSourceListener(source)); // check if source is also a target // DnDTarget target = getTarget(dge.getComponent()); // if( target != null ) { // target.update(myCurrentEvent); // } } } } } private static DnDAction getDnDActionForPlatformAction(int platformAction) { DnDAction action = null; switch (platformAction) { case DnDConstants.ACTION_COPY: action = DnDAction.COPY; break; case DnDConstants.ACTION_MOVE: action = DnDAction.MOVE; break; case DnDConstants.ACTION_LINK: action = DnDAction.LINK; break; default: break; } return action; } private class MyDragSourceListener implements DragSourceListener { private final DnDSource mySource; public MyDragSourceListener(final DnDSource source) { mySource = source; } public void dragEnter(DragSourceDragEvent dsde) { LOG.debug("dragEnter:" + dsde.getDragSourceContext().getComponent()); myCurrentDragContext = dsde.getDragSourceContext(); } public void dragOver(DragSourceDragEvent dsde) { LOG.debug("dragOver:" + dsde.getDragSourceContext().getComponent()); myCurrentDragContext = dsde.getDragSourceContext(); } public void dropActionChanged(DragSourceDragEvent dsde) { mySource.dropActionChanged(dsde.getGestureModifiers()); } public void dragDropEnd(DragSourceDropEvent dsde) { mySource.dragDropEnd(); final DnDTarget target = getLastProcessedTarget(); if (target != null) { target.cleanUpOnLeave(); } resetCurrentEvent("dragDropEnd:" + dsde.getDragSourceContext().getComponent()); Highlighters.hide(TEXT | ERROR_TEXT); } public void dragExit(DragSourceEvent dse) { LOG.debug("Stop dragging1"); onDragExit(); } } private class MyDropTargetListener implements DropTargetListener { public void drop(final DropTargetDropEvent dtde) { try { final Component component = dtde.getDropTargetContext().getComponent(); updateCurrentEvent(component, dtde.getLocation(), dtde.getDropAction()); final DnDEventImpl event = myCurrentEvent; if (event != null && event.isDropPossible()) { dtde.acceptDrop(dtde.getDropAction()); // do not wrap this into WriteAction! doDrop(component); if (event.shouldRemoveHighlightings()) { hideCurrentHighlighter(); } dtde.dropComplete(true); } else { dtde.rejectDrop(); } } catch (Throwable e) { LOG.error(e); dtde.rejectDrop(); } finally { resetCurrentEvent("Stop dragging2"); } } private void doDrop(Component component) { if (myCurrentEvent.canHandleDrop()) { myCurrentEvent.handleDrop(); } else { getTarget(component).drop(myCurrentEvent); } } public void dragOver(DropTargetDragEvent dtde) { updateCurrentEvent(dtde.getDropTargetContext().getComponent(), dtde.getLocation(), dtde.getDropAction()); } public void dragExit(DropTargetEvent dte) { onDragExit(); } public void dragEnter(DropTargetDragEvent dtde) { } public void dropActionChanged(DropTargetDragEvent dtde) { updateCurrentEvent(dtde.getDropTargetContext().getComponent(), dtde.getLocation(), dtde.getDropAction()); } } private void onDragExit() { if (myCurrentDragContext != null) { myCurrentDragContext.setCursor(null); } final DnDTarget target = getLastProcessedTarget(); if (target != null) { target.cleanUpOnLeave(); } hideCurrentHighlighter(); myHightlighterShowRequest = null; } private Application getApplication() { return myApp; } }
source/com/intellij/ide/dnd/DnDManagerImpl.java
/* * Copyright (c) 2000-2004 by JetBrains s.r.o. All Rights Reserved. * Use is subject to license terms. */ package com.intellij.ide.dnd; import com.intellij.openapi.application.Application; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Pair; import com.intellij.ui.awt.RelativeRectangle; import com.intellij.util.ui.GeometryUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.*; import java.awt.dnd.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.lang.ref.WeakReference; public class DnDManagerImpl extends DnDManager implements DnDEvent.DropTargetHighlightingType { private static final Logger LOG = Logger.getInstance("com.intellij.ide.dnd.DnDManager"); static final @NonNls String SOURCE_KEY = "DnD Source"; static final @NonNls String TARGET_KEY = "DnD Target"; public static final Key<Pair<Image, Point>> DRAGGED_IMAGE_KEY = new Key<Pair<Image, Point>>("draggedImage"); private DnDEventImpl myCurrentEvent; private DnDEvent myLastHighlightedEvent; private static DnDTarget NULL_TARGET = new NullTarget(); private WeakReference<DnDTarget> myLastProcessedTarget = new WeakReference<DnDTarget>(NULL_TARGET); private DragSourceContext myCurrentDragContext; private Component myLastProcessedOverComponent; private Point myLastProcessedPoint; private String myLastMessage; private DnDEvent myLastProcessedEvent; private DragGestureListener myDragGestureListener = new MyDragGestureListnener(); private DropTargetListener myDropTargetListener = new MyDropTargetListener(); private static final Image EMPTY_IMAGE = new BufferedImage(1, 1, Transparency.TRANSLUCENT); private Timer myTooltipTimer = new Timer(ToolTipManager.sharedInstance().getInitialDelay(), new ActionListener() { public void actionPerformed(ActionEvent e) { onTimer(); } }); private Runnable myHightlighterShowRequest; private Rectangle myLastHighlightedRec; private int myLastProcessedAction; private Application myApp; public DnDManagerImpl(final Application app) { myApp = app; myTooltipTimer.start(); } public void registerSource(@NotNull final AdvancedDnDSource source) { if (!getApplication().isHeadlessEnvironment()) { final JComponent c = source.getComponent(); registerSource(source, c); final DnDEnabler enabler = new DnDEnabler(source, source); c.putClientProperty(DnDEnabler.KEY, enabler); } } public void registerSource(DnDSource source, JComponent component) { if (!getApplication().isHeadlessEnvironment()) { component.putClientProperty(SOURCE_KEY, source); final DragSource defaultDragSource = DragSource.getDefaultDragSource(); defaultDragSource.createDefaultDragGestureRecognizer(component, DnDConstants.ACTION_COPY_OR_MOVE, myDragGestureListener); } } public void unregisterSource(AdvancedDnDSource source) { final JComponent c = source.getComponent(); if (c != null) { final DnDEnabler enabler = (DnDEnabler)c.getClientProperty(DnDEnabler.KEY); if (enabler != null) { Disposer.dispose(enabler); c.putClientProperty(DnDEnabler.KEY, null); } } unregisterSource(source, c); } public void unregisterSource(DnDSource source, JComponent component) { component.putClientProperty(SOURCE_KEY, null); cleanup(); } private void cleanup() { Runnable cleanup = new Runnable() { public void run() { myLastProcessedOverComponent = null; myCurrentDragContext = null; myCurrentEvent = null; } }; if (myApp.isDispatchThread()) { cleanup.run(); } else { SwingUtilities.invokeLater(cleanup); } } public void registerTarget(DnDTarget target, JComponent component) { if (!getApplication().isHeadlessEnvironment()) { component.putClientProperty(TARGET_KEY, target); new DropTarget(component, DnDConstants.ACTION_COPY_OR_MOVE, myDropTargetListener); } } public void unregisterTarget(DnDTarget target, JComponent component) { component.putClientProperty(TARGET_KEY, null); cleanup(); } private void updateCurrentEvent(Component aComponentOverDragging, Point aPoint, int nativeAction) { LOG.debug("updateCurrentEvent: " + aComponentOverDragging); if (myCurrentDragContext == null) return; myCurrentEvent.updateAction(getDnDActionForPlatformAction(nativeAction)); myCurrentEvent.setPoint(aPoint); myCurrentEvent.setHandlerComponent(aComponentOverDragging); boolean samePoint = myCurrentEvent.getPoint().equals(myLastProcessedPoint); boolean sameComponent = myCurrentEvent.getCurrentOverComponent().equals(myLastProcessedOverComponent); boolean sameAction = (nativeAction == myLastProcessedAction); LOG.debug("updateCurrentEvent: point:" + aPoint); LOG.debug("updateCurrentEvent: action:" + nativeAction); if (samePoint && sameComponent && sameAction) { return; } DnDTarget target = getTarget(aComponentOverDragging); DnDTarget immediateTarget = target; Component eachParent = aComponentOverDragging; final Pair<Image, Point> pair = myCurrentEvent.getUserData(DRAGGED_IMAGE_KEY); if (pair != null) { target.updateDraggedImage(pair.first, aPoint, pair.second); } LOG.debug("updateCurrentEvent: action:" + nativeAction); while (true) { boolean canGoToParent = update(target); if (myCurrentEvent.isDropPossible()) { if (myCurrentEvent.wasDelegated()) { target = myCurrentEvent.getDelegatedTarget(); } break; } if (!canGoToParent) { break; } eachParent = findAllowedParentComponent(eachParent); if (eachParent == null) { break; } target = getTarget(eachParent); } LOG.debug("updateCurrentEvent: target:" + target); LOG.debug("updateCurrentEvent: immediateTarget:" + immediateTarget); if (!myCurrentEvent.isDropPossible() && !immediateTarget.equals(target)) { update(immediateTarget); } updateCursor(); final Container current = (Container)myCurrentEvent.getCurrentOverComponent(); final Point point = myCurrentEvent.getPointOn(getLayeredPane(current)); Rectangle inPlaceRect = new Rectangle(point.x - 5, point.y - 5, 5, 5); if (!myCurrentEvent.equals(myLastProcessedEvent)) { hideCurrentHighlighter(); } boolean sameTarget = getLastProcessedTarget() != null && getLastProcessedTarget().equals(target); if (sameTarget) { if (myCurrentEvent.isDropPossible()) { if (!myLastProcessedPoint.equals(myCurrentEvent.getPoint())) { if (!Highlighters.isVisibleExcept(TEXT | ERROR_TEXT)) { hideCurrentHighlighter(); restartTimer(); queueTooltip(myCurrentEvent, getLayeredPane(current), inPlaceRect); } } } else { if (myLastProcessedPoint == null || myCurrentEvent == null || !myLastProcessedPoint.equals(myCurrentEvent.getPoint())) { hideCurrentHighlighter(); restartTimer(); queueTooltip(myCurrentEvent, getLayeredPane(current), inPlaceRect); } } } else { hideCurrentHighlighter(); getLastProcessedTarget().cleanUpOnLeave(); myCurrentEvent.clearDropHandler(); restartTimer(); if (!myCurrentEvent.isDropPossible()) { queueTooltip(myCurrentEvent, getLayeredPane(current), inPlaceRect); } } myLastProcessedTarget = new WeakReference<DnDTarget>(target); myLastProcessedPoint = myCurrentEvent.getPoint(); myLastProcessedOverComponent = myCurrentEvent.getCurrentOverComponent(); myLastProcessedAction = myCurrentEvent.getAction().getActionId(); myLastProcessedEvent = (DnDEvent)myCurrentEvent.clone(); } private void updateCursor() { Cursor cursor; if (myCurrentEvent.isDropPossible()) { cursor = myCurrentEvent.getCursor(); if (cursor == null) { cursor = myCurrentEvent.getAction().getCursor(); } } else { cursor = myCurrentEvent.getAction().getRejectCursor(); } myCurrentDragContext.setCursor(cursor); } private void restartTimer() { myTooltipTimer.restart(); } private boolean update(DnDTarget target) { LOG.debug("update target:" + target); myCurrentEvent.clearDelegatedTarget(); final boolean canGoToParent = target.update(myCurrentEvent); String message; if (isMessageProvided(myCurrentEvent)) { message = myCurrentEvent.getExpectedDropResult(); } else { message = ""; } //final WindowManager wm = WindowManager.getInstance(); //final StatusBar statusBar = wm.getStatusBar(target.getProject()); //statusBar.setInfo(message); if (myLastMessage != null && !myLastMessage.equals(message)) { hideCurrentHighlighter(); } myLastMessage = message; return canGoToParent; } private static Component findAllowedParentComponent(Component aComponentOverDragging) { Component eachParent = aComponentOverDragging; while (true) { eachParent = eachParent.getParent(); if (eachParent == null) { return null; } final DnDTarget target = getTarget(eachParent); if (target != NULL_TARGET) { return eachParent; } } } private static DnDSource getSource(Component component) { if (component instanceof JComponent) { return (DnDSource)((JComponent)component).getClientProperty(SOURCE_KEY); } return null; } private static DnDTarget getTarget(Component component) { if (component instanceof JComponent) { DnDTarget target = (DnDTarget)((JComponent)component).getClientProperty(TARGET_KEY); if (target != null) return target; } return NULL_TARGET; } void showHighlighter(final Component aComponent, final int aType, final DnDEvent aEvent) { final Rectangle bounds = aComponent.getBounds(); final Container parent = aComponent.getParent(); showHighlighter(parent, aEvent, bounds, aType); } void showHighlighter(final RelativeRectangle rectangle, final int aType, final DnDEvent aEvent) { final JLayeredPane layeredPane = getLayeredPane(rectangle.getPoint().getComponent()); final Rectangle bounds = rectangle.getRectangleOn(layeredPane); showHighlighter(layeredPane, aEvent, bounds, aType); } void showHighlighter(JLayeredPane layeredPane, final RelativeRectangle rectangle, final int aType, final DnDEvent event) { final Rectangle bounds = rectangle.getRectangleOn(layeredPane); showHighlighter(layeredPane, event, bounds, aType); } private boolean isEventBeingHighlighted(DnDEvent event) { return event.equals(getLastHighlightedEvent()); } private void showHighlighter(final Component parent, final DnDEvent aEvent, final Rectangle bounds, final int aType) { final JLayeredPane layeredPane = getLayeredPane(parent); if (layeredPane == null) { return; } if (isEventBeingHighlighted(aEvent)) { if (GeometryUtil.isWithin(myLastHighlightedRec, aEvent.getPointOn(layeredPane))) { return; } } final Rectangle rectangle = SwingUtilities.convertRectangle(parent, bounds, layeredPane); setLastHighlightedEvent((DnDEvent)((DnDEventImpl)aEvent).clone(), rectangle); Highlighters.hide(); Highlighters.show(aType, layeredPane, rectangle, aEvent); if (isMessageProvided(aEvent)) { queueTooltip(aEvent, layeredPane, rectangle); } else { Highlighters.hide(TEXT | ERROR_TEXT); } } private void queueTooltip(final DnDEvent aEvent, final JLayeredPane aLayeredPane, final Rectangle aRectangle) { myHightlighterShowRequest = new Runnable() { public void run() { if (myCurrentEvent != aEvent) return; Highlighters.hide(TEXT | ERROR_TEXT); if (aEvent.isDropPossible()) { Highlighters.show(TEXT, aLayeredPane, aRectangle, aEvent); } else { Highlighters.show(ERROR_TEXT, aLayeredPane, aRectangle, aEvent); } } }; } private static boolean isMessageProvided(final DnDEvent aEvent) { return aEvent.getExpectedDropResult() != null && aEvent.getExpectedDropResult().trim().length() > 0; } void hideCurrentHighlighter() { Highlighters.hide(); myHightlighterShowRequest = null; setLastHighlightedEvent(null, null); } private void onTimer() { if (myHightlighterShowRequest != null) { myHightlighterShowRequest.run(); myHightlighterShowRequest = null; } } private static JLayeredPane getLayeredPane(Component aComponent) { if (aComponent == null) return null; if (aComponent instanceof JLayeredPane) { return (JLayeredPane)aComponent; } if (aComponent instanceof JFrame) { return ((JFrame)aComponent).getRootPane().getLayeredPane(); } if (aComponent instanceof JDialog) { return ((JDialog)aComponent).getRootPane().getLayeredPane(); } final Window window = SwingUtilities.getWindowAncestor(aComponent); if (window instanceof JFrame) { return ((JFrame) window).getRootPane().getLayeredPane(); } else if (window instanceof JDialog) { return ((JDialog) window).getRootPane().getLayeredPane(); } return null; } private DnDTarget getLastProcessedTarget() { return myLastProcessedTarget.get(); } private static class NullTarget implements DnDTarget { public boolean update(DnDEvent aEvent) { aEvent.setDropPossible(false, "You cannot drop anything here"); return false; } public void drop(DnDEvent aEvent) { } public void cleanUpOnLeave() { } public void updateDraggedImage(Image image, Point dropPoint, Point imageOffset) { } } DnDEvent getCurrentEvent() { return myCurrentEvent; } private DnDEvent getLastHighlightedEvent() { return myLastHighlightedEvent; } private void setLastHighlightedEvent(DnDEvent lastHighlightedEvent, Rectangle aRectangle) { myLastHighlightedEvent = lastHighlightedEvent; myLastHighlightedRec = aRectangle; } private void resetCurrentEvent(@NonNls String s) { myCurrentEvent = null; LOG.debug("Reset Current Event: " + s); } private class MyDragGestureListnener implements DragGestureListener { public void dragGestureRecognized(DragGestureEvent dge) { final DnDSource source = getSource(dge.getComponent()); if (source == null) return; DnDAction action = getDnDActionForPlatformAction(dge.getDragAction()); if (source.canStartDragging(action, dge.getDragOrigin())) { if (myCurrentEvent == null) { // Actually, under Linux it is possible to get 2 or more dragGestureRecognized calls for single drag // operation. To reproduce: // 1. Do D-n-D in Styles tree // 2. Make an attempt to do D-n-D in Services tree // 3. Do D-n-D in Styles tree again. LOG.debug("Starting dragging for " + action); hideCurrentHighlighter(); final DnDDragStartBean dnDDragStartBean = source.startDragging(action, dge.getDragOrigin()); myCurrentEvent = new DnDEventImpl(DnDManagerImpl.this, action, dnDDragStartBean.getAttachedObject(), dnDDragStartBean.getPoint()); myCurrentEvent.setOrgPoint(dge.getDragOrigin()); Pair<Image, Point> pair = source.createDraggedImage(action, dge.getDragOrigin()); if (pair == null) { pair = new Pair<Image, Point>(EMPTY_IMAGE, new Point(0, 0)); } if (!DragSource.isDragImageSupported()) { // not all of the platforms supports image dragging (mswin doesn't, for example). myCurrentEvent.putUserData(DRAGGED_IMAGE_KEY, pair); } // mac osx fix: it will draw a border with size of the dragged component if there is no image provided. dge.startDrag(DragSource.DefaultCopyDrop, pair.first, pair.second, myCurrentEvent, new MyDragSourceListener(source)); // check if source is also a target // DnDTarget target = getTarget(dge.getComponent()); // if( target != null ) { // target.update(myCurrentEvent); // } } } } } private static DnDAction getDnDActionForPlatformAction(int platformAction) { DnDAction action = null; switch (platformAction) { case DnDConstants.ACTION_COPY: action = DnDAction.COPY; break; case DnDConstants.ACTION_MOVE: action = DnDAction.MOVE; break; case DnDConstants.ACTION_LINK: action = DnDAction.LINK; break; default: break; } return action; } private class MyDragSourceListener implements DragSourceListener { private final DnDSource mySource; public MyDragSourceListener(final DnDSource source) { mySource = source; } public void dragEnter(DragSourceDragEvent dsde) { LOG.debug("dragEnter:" + dsde.getDragSourceContext().getComponent()); myCurrentDragContext = dsde.getDragSourceContext(); } public void dragOver(DragSourceDragEvent dsde) { LOG.debug("dragOver:" + dsde.getDragSourceContext().getComponent()); myCurrentDragContext = dsde.getDragSourceContext(); } public void dropActionChanged(DragSourceDragEvent dsde) { mySource.dropActionChanged(dsde.getGestureModifiers()); } public void dragDropEnd(DragSourceDropEvent dsde) { mySource.dragDropEnd(); final DnDTarget target = getLastProcessedTarget(); if (target != null) { target.cleanUpOnLeave(); } resetCurrentEvent("dragDropEnd:" + dsde.getDragSourceContext().getComponent()); Highlighters.hide(TEXT | ERROR_TEXT); } public void dragExit(DragSourceEvent dse) { LOG.debug("Stop dragging1"); onDragExit(); } } private class MyDropTargetListener implements DropTargetListener { public void drop(final DropTargetDropEvent dtde) { try { final Component component = dtde.getDropTargetContext().getComponent(); updateCurrentEvent(component, dtde.getLocation(), dtde.getDropAction()); final DnDEventImpl event = myCurrentEvent; if (event != null && event.isDropPossible()) { dtde.acceptDrop(dtde.getDropAction()); // do not wrap this into WriteAction! doDrop(component); if (event.shouldRemoveHighlightings()) { hideCurrentHighlighter(); } dtde.dropComplete(true); } else { dtde.rejectDrop(); } } catch (Throwable e) { LOG.error(e); dtde.rejectDrop(); } finally { resetCurrentEvent("Stop dragging2"); } } private void doDrop(Component component) { if (myCurrentEvent.canHandleDrop()) { myCurrentEvent.handleDrop(); } else { getTarget(component).drop(myCurrentEvent); } } public void dragOver(DropTargetDragEvent dtde) { updateCurrentEvent(dtde.getDropTargetContext().getComponent(), dtde.getLocation(), dtde.getDropAction()); } public void dragExit(DropTargetEvent dte) { onDragExit(); } public void dragEnter(DropTargetDragEvent dtde) { } public void dropActionChanged(DropTargetDragEvent dtde) { updateCurrentEvent(dtde.getDropTargetContext().getComponent(), dtde.getLocation(), dtde.getDropAction()); } } private void onDragExit() { if (myCurrentDragContext != null) { myCurrentDragContext.setCursor(null); } final DnDTarget target = getLastProcessedTarget(); if (target != null) { target.cleanUpOnLeave(); } hideCurrentHighlighter(); myHightlighterShowRequest = null; } private Application getApplication() { return myApp; } }
NPE in DnDManager (worked for years but strangely failed at max)
source/com/intellij/ide/dnd/DnDManagerImpl.java
NPE in DnDManager (worked for years but strangely failed at max)
Java
apache-2.0
1a524b4ab96e297bd54174b3d780de72e81c7069
0
HaiJiaoXinHeng/server-1,hongsudt/server,HaiJiaoXinHeng/server-1,HaiJiaoXinHeng/server-1,hongsudt/server,hongsudt/server
package edu.ucla.cens.awserver.domain; /** * The default user implementation. * * @author selsky */ public class UserImpl implements User { private int _id; private String _userName; private int _campaignId; private boolean _loggedIn; public UserImpl() { } /** * Copy constructor. */ public UserImpl(User user) { if(null == user) { throw new IllegalArgumentException("a null user is not allowed"); } _id = user.getId(); _userName = user.getUserName(); _campaignId = user.getCampaignId(); _loggedIn = user.isLoggedIn(); } public int getId() { return _id; } public void setId(int id) { _id = id; } public int getCampaignId() { return _campaignId; } public void setCampaignId(int id) { _campaignId = id; } public String getUserName() { return _userName; } public void setUserName(String userName) { _userName = userName; } public boolean isLoggedIn() { return _loggedIn; } public void setLoggedIn(boolean loggedIn) { _loggedIn = loggedIn; } @Override public String toString() { return "UserImpl [_campaignId=" + _campaignId + ", _id=" + _id + ", _loggedIn=" + _loggedIn + ", _userName=" + _userName + "]"; } }
src/edu/ucla/cens/awserver/domain/UserImpl.java
package edu.ucla.cens.awserver.domain; /** * The default user implementation. * * @author selsky */ public class UserImpl implements User { private int _id; private String _userName; private int _campaignId; private boolean _loggedIn; public int getId() { return _id; } public void setId(int id) { _id = id; } public int getCampaignId() { return _campaignId; } public void setCampaignId(int id) { _campaignId = id; } public String getUserName() { return _userName; } public void setUserName(String userName) { _userName = userName; } public boolean isLoggedIn() { return _loggedIn; } public void setLoggedIn(boolean loggedIn) { _loggedIn = loggedIn; } }
added copy constructor and toString()
src/edu/ucla/cens/awserver/domain/UserImpl.java
added copy constructor and toString()
Java
apache-2.0
55494f7ef0c99e33895016ce474c32406d74087b
0
sarvex/MINA,sarvex/MINA
/* * 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.mina.filter.support; import java.nio.ByteBuffer; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngineResult; import javax.net.ssl.SSLException; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLSession; import org.apache.mina.common.IoSession; import org.apache.mina.common.WriteFuture; import org.apache.mina.common.IoFilter.NextFilter; import org.apache.mina.common.IoFilter.WriteRequest; import org.apache.mina.common.support.DefaultWriteFuture; import org.apache.mina.filter.SSLFilter; import org.apache.mina.util.SessionLog; import edu.emory.mathcs.backport.java.util.LinkedList; import edu.emory.mathcs.backport.java.util.Queue; import edu.emory.mathcs.backport.java.util.concurrent.ConcurrentLinkedQueue; /** * A helper class using the SSLEngine API to decrypt/encrypt data. * <p> * Each connection has a SSLEngine that is used through the lifetime of the connection. * We allocate byte buffers for use as the outbound and inbound network buffers. * These buffers handle all of the intermediary data for the SSL connection. To make things easy, * we'll require outNetBuffer be completely flushed before trying to wrap any more data. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev$, $Date$ */ public class SSLHandler { private final SSLFilter parent; private final SSLContext ctx; private final IoSession session; private final Queue preHandshakeEventQueue = new LinkedList(); private final Queue filterWriteEventQueue = new ConcurrentLinkedQueue(); private final Queue messageReceivedEventQueue = new ConcurrentLinkedQueue(); private SSLEngine sslEngine; /** * Encrypted data from the net */ private ByteBuffer inNetBuffer; /** * Encrypted data to be written to the net */ private ByteBuffer outNetBuffer; /** * Applicaton cleartext data to be read by application */ private ByteBuffer appBuffer; /** * Empty buffer used during initial handshake and close operations */ private final ByteBuffer hsBB = ByteBuffer.allocate(0); /** * Handshake status */ private SSLEngineResult.HandshakeStatus handshakeStatus; private boolean initialHandshakeComplete; /** * Handshake complete? */ private boolean handshakeComplete; private boolean writingEncryptedData; /** * Constuctor. * * @param sslc * @throws SSLException */ public SSLHandler(SSLFilter parent, SSLContext sslc, IoSession session) throws SSLException { this.parent = parent; this.session = session; ctx = sslc; init(); } public void init() throws SSLException { if (sslEngine != null) { return; } sslEngine = ctx.createSSLEngine(); sslEngine.setUseClientMode(parent.isUseClientMode()); if (parent.isWantClientAuth()) { sslEngine.setWantClientAuth(true); } if (parent.isNeedClientAuth()) { sslEngine.setNeedClientAuth(true); } if (parent.getEnabledCipherSuites() != null) { sslEngine.setEnabledCipherSuites(parent.getEnabledCipherSuites()); } if (parent.getEnabledProtocols() != null) { sslEngine.setEnabledProtocols(parent.getEnabledProtocols()); } sslEngine.beginHandshake(); handshakeStatus = sslEngine.getHandshakeStatus();//SSLEngineResult.HandshakeStatus.NEED_UNWRAP; handshakeComplete = false; initialHandshakeComplete = false; SSLByteBufferPool.initiate(sslEngine); appBuffer = SSLByteBufferPool.getApplicationBuffer(); inNetBuffer = SSLByteBufferPool.getPacketBuffer(); outNetBuffer = SSLByteBufferPool.getPacketBuffer(); outNetBuffer.position(0); outNetBuffer.limit(0); writingEncryptedData = false; } /** * Release allocated ByteBuffers. */ public void destroy() { if (sslEngine == null) { return; } // Close inbound and flush all remaining data if available. try { sslEngine.closeInbound(); } catch (SSLException e) { SessionLog.debug(session, "Unexpected exception from SSLEngine.closeInbound().", e); } try { do { outNetBuffer.clear(); } while (sslEngine.wrap(hsBB, outNetBuffer).bytesProduced() > 0); } catch (SSLException e) { SessionLog.debug(session, "Unexpected exception from SSLEngine.wrap().", e); } sslEngine.closeOutbound(); sslEngine = null; SSLByteBufferPool.release(appBuffer); SSLByteBufferPool.release(inNetBuffer); SSLByteBufferPool.release(outNetBuffer); preHandshakeEventQueue.clear(); } public SSLFilter getParent() { return parent; } public IoSession getSession() { return session; } /** * Check we are writing encrypted data. */ public boolean isWritingEncryptedData() { return writingEncryptedData; } /** * Check if handshake is completed. */ public boolean isHandshakeComplete() { return handshakeComplete; } public boolean isInboundDone() { return sslEngine == null || sslEngine.isInboundDone(); } public boolean isOutboundDone() { return sslEngine == null || sslEngine.isOutboundDone(); } /** * Check if there is any need to complete handshake. */ public boolean needToCompleteHandshake() { return handshakeStatus == SSLEngineResult.HandshakeStatus.NEED_WRAP && !isInboundDone(); } public void schedulePreHandshakeWriteRequest(NextFilter nextFilter, WriteRequest writeRequest) { preHandshakeEventQueue.offer(new Event(EventType.FILTER_WRITE, nextFilter, writeRequest)); } public void flushPreHandshakeEvents() throws SSLException { Event scheduledWrite; while ((scheduledWrite = (Event) preHandshakeEventQueue.poll()) != null) { if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " Flushing buffered write request: " + scheduledWrite.data); } parent.filterWrite(scheduledWrite.nextFilter, session, (WriteRequest) scheduledWrite.data); } } public void scheduleFilterWrite(NextFilter nextFilter, WriteRequest writeRequest) { filterWriteEventQueue.offer(new Event(EventType.FILTER_WRITE, nextFilter, writeRequest)); } public void scheduleMessageReceived(NextFilter nextFilter, Object message) { messageReceivedEventQueue.offer(new Event(EventType.RECEIVED, nextFilter, message)); } public void flushScheduledEvents() { // Fire events only when no lock is hold for this handler. if (Thread.holdsLock(this)) { return; } Event e; // We need synchronization here inevitably because filterWrite can be // called simultaneously and cause 'bad record MAC' integrity error. synchronized (this) { while ((e = (Event) filterWriteEventQueue.poll()) != null) { e.nextFilter.filterWrite(session, (WriteRequest) e.data); } } while ((e = (Event) messageReceivedEventQueue.poll()) != null) { e.nextFilter.messageReceived(session, e.data); } } /** * Call when data read from net. Will perform inial hanshake or decrypt provided * Buffer. * Decrytpted data reurned by getAppBuffer(), if any. * * @param buf buffer to decrypt * @throws SSLException on errors */ public void messageReceived(NextFilter nextFilter, ByteBuffer buf) throws SSLException { if (buf.limit() > inNetBuffer.remaining()) { // We have to expand inNetBuffer inNetBuffer = SSLByteBufferPool.expandBuffer(inNetBuffer, inNetBuffer.capacity() + buf.limit() * 2); // We also expand app. buffer (twice the size of in net. buffer) appBuffer = SSLByteBufferPool.expandBuffer(appBuffer, inNetBuffer .capacity() * 2); if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " expanded inNetBuffer:" + inNetBuffer); SessionLog.debug(session, " expanded appBuffer:" + appBuffer); } } // append buf to inNetBuffer inNetBuffer.put(buf); if (!handshakeComplete) { handshake(nextFilter); } else { decrypt(nextFilter); } if (isInboundDone()) { // Rewind the MINA buffer if not all data is processed and inbound is finished. buf.position(buf.position() - inNetBuffer.position()); inNetBuffer.clear(); } } /** * Get decrypted application data. * * @return buffer with data */ public ByteBuffer getAppBuffer() { return appBuffer; } /** * Get encrypted data to be sent. * * @return buffer with data */ public ByteBuffer getOutNetBuffer() { return outNetBuffer; } /** * Encrypt provided buffer. Encytpted data reurned by getOutNetBuffer(). * * @param src data to encrypt * @throws SSLException on errors */ public void encrypt(ByteBuffer src) throws SSLException { if (!handshakeComplete) { throw new IllegalStateException(); } // The data buffer is (must be) empty, we can reuse the entire // buffer. outNetBuffer.clear(); SSLEngineResult result; // Loop until there is no more data in src while (src.hasRemaining()) { if (src.remaining() > (outNetBuffer.capacity() - outNetBuffer .position()) / 2) { // We have to expand outNetBuffer // Note: there is no way to know the exact size required, but enrypted data // shouln't need to be larger than twice the source data size? outNetBuffer = SSLByteBufferPool.expandBuffer(outNetBuffer, src .capacity() * 2); if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " expanded outNetBuffer:" + outNetBuffer); } } result = sslEngine.wrap(src, outNetBuffer); if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " Wrap res:" + result); } if (result.getStatus() == SSLEngineResult.Status.OK) { if (result.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_TASK) { doTasks(); } } else { throw new SSLException("SSLEngine error during encrypt: " + result.getStatus() + " src: " + src + "outNetBuffer: " + outNetBuffer); } } outNetBuffer.flip(); } /** * Start SSL shutdown process. * * @return <tt>true</tt> if shutdown process is started. * <tt>false</tt> if shutdown process is already finished. * * @throws SSLException on errors */ public boolean closeOutbound() throws SSLException { if (sslEngine == null || sslEngine.isOutboundDone()) { return false; } sslEngine.closeOutbound(); // By RFC 2616, we can "fire and forget" our close_notify // message, so that's what we'll do here. outNetBuffer.clear(); SSLEngineResult result = sslEngine.wrap(hsBB, outNetBuffer); if (result.getStatus() != SSLEngineResult.Status.CLOSED) { throw new SSLException("Improper close state: " + result); } outNetBuffer.flip(); return true; } /** * Decrypt in net buffer. Result is stored in app buffer. * * @throws SSLException */ private void decrypt(NextFilter nextFilter) throws SSLException { if (!handshakeComplete) { throw new IllegalStateException(); } unwrap(nextFilter); } /** * @param status * @throws SSLException */ private void checkStatus(SSLEngineResult res) throws SSLException { SSLEngineResult.Status status = res.getStatus(); /* * The status may be: * OK - Normal operation * OVERFLOW - Should never happen since the application buffer is * sized to hold the maximum packet size. * UNDERFLOW - Need to read more data from the socket. It's normal. * CLOSED - The other peer closed the socket. Also normal. */ if (status != SSLEngineResult.Status.OK && status != SSLEngineResult.Status.CLOSED && status != SSLEngineResult.Status.BUFFER_UNDERFLOW) { throw new SSLException("SSLEngine error during decrypt: " + status + " inNetBuffer: " + inNetBuffer + "appBuffer: " + appBuffer); } } /** * Perform any handshaking processing. */ public void handshake(NextFilter nextFilter) throws SSLException { if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " doHandshake()"); } for (;;) { if (handshakeStatus == SSLEngineResult.HandshakeStatus.FINISHED) { session.setAttribute(SSLFilter.SSL_SESSION, sslEngine .getSession()); if (SessionLog.isDebugEnabled(session)) { SSLSession sslSession = sslEngine.getSession(); SessionLog.debug(session, " handshakeStatus=FINISHED"); SessionLog.debug(session, " sslSession CipherSuite used " + sslSession.getCipherSuite()); } handshakeComplete = true; if (!initialHandshakeComplete && session.containsAttribute(SSLFilter.USE_NOTIFICATION)) { // SESSION_SECURED is fired only when it's the first handshake. // (i.e. renegotiation shouldn't trigger SESSION_SECURED.) initialHandshakeComplete = true; scheduleMessageReceived(nextFilter, SSLFilter.SESSION_SECURED); } break; } else if (handshakeStatus == SSLEngineResult.HandshakeStatus.NEED_TASK) { if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " handshakeStatus=NEED_TASK"); } handshakeStatus = doTasks(); } else if (handshakeStatus == SSLEngineResult.HandshakeStatus.NEED_UNWRAP) { // we need more data read if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " handshakeStatus=NEED_UNWRAP"); } SSLEngineResult.Status status = unwrapHandshake(nextFilter); if (status == SSLEngineResult.Status.BUFFER_UNDERFLOW && handshakeStatus != SSLEngineResult.HandshakeStatus.FINISHED || isInboundDone()) { // We need more data or the session is closed break; } } else if (handshakeStatus == SSLEngineResult.HandshakeStatus.NEED_WRAP) { if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " handshakeStatus=NEED_WRAP"); } // First make sure that the out buffer is completely empty. Since we // cannot call wrap with data left on the buffer if (outNetBuffer.hasRemaining()) { if (SessionLog.isDebugEnabled(session)) { SessionLog .debug(session, " Still data in out buffer!"); } break; } outNetBuffer.clear(); SSLEngineResult result = sslEngine.wrap(hsBB, outNetBuffer); if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " Wrap res:" + result); } outNetBuffer.flip(); handshakeStatus = result.getHandshakeStatus(); writeNetBuffer(nextFilter); } else { throw new IllegalStateException("Invalid Handshaking State" + handshakeStatus); } } } public WriteFuture writeNetBuffer(NextFilter nextFilter) throws SSLException { // Check if any net data needed to be writen if (!getOutNetBuffer().hasRemaining()) { // no; bail out return DefaultWriteFuture.newNotWrittenFuture(session); } WriteFuture writeFuture = null; // write net data // set flag that we are writing encrypted data // (used in SSLFilter.filterWrite()) writingEncryptedData = true; try { if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " write outNetBuffer: " + getOutNetBuffer()); } org.apache.mina.common.ByteBuffer writeBuffer = copy(getOutNetBuffer()); if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " session write: " + writeBuffer); } //debug("outNetBuffer (after copy): {0}", sslHandler.getOutNetBuffer()); writeFuture = new DefaultWriteFuture(session); parent.filterWrite(nextFilter, session, new WriteRequest( writeBuffer, writeFuture)); // loop while more writes required to complete handshake while (needToCompleteHandshake()) { try { handshake(nextFilter); } catch (SSLException ssle) { SSLException newSSLE = new SSLHandshakeException( "SSL handshake failed."); newSSLE.initCause(ssle); throw newSSLE; } if (getOutNetBuffer().hasRemaining()) { if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " write outNetBuffer2: " + getOutNetBuffer()); } org.apache.mina.common.ByteBuffer writeBuffer2 = copy(getOutNetBuffer()); writeFuture = new DefaultWriteFuture(session); parent.filterWrite(nextFilter, session, new WriteRequest( writeBuffer2, writeFuture)); } } } finally { writingEncryptedData = false; } if (writeFuture != null) { return writeFuture; } else { return DefaultWriteFuture.newNotWrittenFuture(session); } } private void unwrap(NextFilter nextFilter) throws SSLException { if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " unwrap()"); } // Prepare the net data for reading. inNetBuffer.flip(); SSLEngineResult res = unwrap0(); // prepare to be written again inNetBuffer.compact(); checkStatus(res); renegotiateIfNeeded(nextFilter, res); } private SSLEngineResult.Status unwrapHandshake(NextFilter nextFilter) throws SSLException { if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " unwrapHandshake()"); } // Prepare the net data for reading. inNetBuffer.flip(); SSLEngineResult res = unwrap0(); handshakeStatus = res.getHandshakeStatus(); checkStatus(res); // If handshake finished, no data was produced, and the status is still ok, // try to unwrap more if (handshakeStatus == SSLEngineResult.HandshakeStatus.FINISHED && res.getStatus() == SSLEngineResult.Status.OK && inNetBuffer.hasRemaining()) { res = unwrap0(); // prepare to be written again inNetBuffer.compact(); renegotiateIfNeeded(nextFilter, res); } else { // prepare to be written again inNetBuffer.compact(); } return res.getStatus(); } private void renegotiateIfNeeded(NextFilter nextFilter, SSLEngineResult res) throws SSLException { if (res.getStatus() != SSLEngineResult.Status.CLOSED && res.getStatus() != SSLEngineResult.Status.BUFFER_UNDERFLOW && res.getHandshakeStatus() != SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) { // Renegotiation required. SessionLog.debug(session, " Renegotiating..."); handshakeComplete = false; handshakeStatus = res.getHandshakeStatus(); handshake(nextFilter); } } private SSLEngineResult unwrap0() throws SSLException { SSLEngineResult res; do { if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " inNetBuffer: " + inNetBuffer); SessionLog.debug(session, " appBuffer: " + appBuffer); } res = sslEngine.unwrap(inNetBuffer, appBuffer); if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " Unwrap res:" + res); } } while (res.getStatus() == SSLEngineResult.Status.OK && (handshakeComplete && res.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING || res.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_UNWRAP)); return res; } /** * Do all the outstanding handshake tasks in the current Thread. */ private SSLEngineResult.HandshakeStatus doTasks() { if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " doTasks()"); } /* * We could run this in a separate thread, but I don't see the need * for this when used from SSLFilter. Use thread filters in MINA instead? */ Runnable runnable; while ((runnable = sslEngine.getDelegatedTask()) != null) { if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " doTask: " + runnable); } runnable.run(); } if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " doTasks(): " + sslEngine.getHandshakeStatus()); } return sslEngine.getHandshakeStatus(); } /** * Creates a new Mina byte buffer that is a deep copy of the remaining bytes * in the given buffer (between index buf.position() and buf.limit()) * * @param src the buffer to copy * @return the new buffer, ready to read from */ public static org.apache.mina.common.ByteBuffer copy(java.nio.ByteBuffer src) { org.apache.mina.common.ByteBuffer copy = org.apache.mina.common.ByteBuffer .allocate(src.remaining()); copy.put(src); copy.flip(); return copy; } private static class EventType { public static final EventType RECEIVED = new EventType("RECEIVED"); public static final EventType FILTER_WRITE = new EventType( "FILTER_WRITE"); private final String value; private EventType(String value) { this.value = value; } public String toString() { return value; } } private static class Event { private final EventType type; private final NextFilter nextFilter; private final Object data; Event(EventType type, NextFilter nextFilter, Object data) { this.type = type; this.nextFilter = nextFilter; this.data = data; } public Object getData() { return data; } public NextFilter getNextFilter() { return nextFilter; } public EventType getType() { return type; } } }
filter-ssl/src/main/java/org/apache/mina/filter/support/SSLHandler.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.mina.filter.support; import java.nio.ByteBuffer; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngineResult; import javax.net.ssl.SSLException; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLSession; import org.apache.mina.common.IoSession; import org.apache.mina.common.WriteFuture; import org.apache.mina.common.IoFilter.NextFilter; import org.apache.mina.common.IoFilter.WriteRequest; import org.apache.mina.common.support.DefaultWriteFuture; import org.apache.mina.filter.SSLFilter; import org.apache.mina.util.SessionLog; import edu.emory.mathcs.backport.java.util.LinkedList; import edu.emory.mathcs.backport.java.util.Queue; import edu.emory.mathcs.backport.java.util.concurrent.ConcurrentLinkedQueue; /** * A helper class using the SSLEngine API to decrypt/encrypt data. * <p> * Each connection has a SSLEngine that is used through the lifetime of the connection. * We allocate byte buffers for use as the outbound and inbound network buffers. * These buffers handle all of the intermediary data for the SSL connection. To make things easy, * we'll require outNetBuffer be completely flushed before trying to wrap any more data. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev$, $Date$ */ public class SSLHandler { private final SSLFilter parent; private final SSLContext ctx; private final IoSession session; private final Queue preHandshakeEventQueue = new LinkedList(); private final Queue filterWriteEventQueue = new ConcurrentLinkedQueue(); private final Queue messageReceivedEventQueue = new ConcurrentLinkedQueue(); private SSLEngine sslEngine; /** * Encrypted data from the net */ private ByteBuffer inNetBuffer; /** * Encrypted data to be written to the net */ private ByteBuffer outNetBuffer; /** * Applicaton cleartext data to be read by application */ private ByteBuffer appBuffer; /** * Empty buffer used during initial handshake and close operations */ private final ByteBuffer hsBB = ByteBuffer.allocate(0); /** * Handshake status */ private SSLEngineResult.HandshakeStatus handshakeStatus; private boolean initialHandshakeComplete; /** * Handshake complete? */ private boolean handshakeComplete; private boolean writingEncryptedData; /** * Constuctor. * * @param sslc * @throws SSLException */ public SSLHandler(SSLFilter parent, SSLContext sslc, IoSession session) throws SSLException { this.parent = parent; this.session = session; this.ctx = sslc; init(); } public void init() throws SSLException { if (sslEngine != null) { return; } sslEngine = ctx.createSSLEngine(); sslEngine.setUseClientMode(parent.isUseClientMode()); if (parent.isWantClientAuth()) { sslEngine.setWantClientAuth(true); } if (parent.isNeedClientAuth()) { sslEngine.setNeedClientAuth(true); } if (parent.getEnabledCipherSuites() != null) { sslEngine.setEnabledCipherSuites(parent.getEnabledCipherSuites()); } if (parent.getEnabledProtocols() != null) { sslEngine.setEnabledProtocols(parent.getEnabledProtocols()); } sslEngine.beginHandshake(); handshakeStatus = sslEngine.getHandshakeStatus();//SSLEngineResult.HandshakeStatus.NEED_UNWRAP; handshakeComplete = false; initialHandshakeComplete = false; SSLByteBufferPool.initiate(sslEngine); appBuffer = SSLByteBufferPool.getApplicationBuffer(); inNetBuffer = SSLByteBufferPool.getPacketBuffer(); outNetBuffer = SSLByteBufferPool.getPacketBuffer(); outNetBuffer.position(0); outNetBuffer.limit(0); writingEncryptedData = false; } /** * Release allocated ByteBuffers. */ public void destroy() { if (sslEngine == null) { return; } // Close inbound and flush all remaining data if available. try { sslEngine.closeInbound(); } catch (SSLException e) { SessionLog.debug(session, "Unexpected exception from SSLEngine.closeInbound().", e); } try { do { outNetBuffer.clear(); } while (sslEngine.wrap(hsBB, outNetBuffer).bytesProduced() > 0); } catch (SSLException e) { SessionLog.debug(session, "Unexpected exception from SSLEngine.wrap().", e); } sslEngine.closeOutbound(); sslEngine = null; SSLByteBufferPool.release(appBuffer); SSLByteBufferPool.release(inNetBuffer); SSLByteBufferPool.release(outNetBuffer); preHandshakeEventQueue.clear(); } public SSLFilter getParent() { return parent; } public IoSession getSession() { return session; } /** * Check we are writing encrypted data. */ public boolean isWritingEncryptedData() { return writingEncryptedData; } /** * Check if handshake is completed. */ public boolean isHandshakeComplete() { return handshakeComplete; } public boolean isInboundDone() { return sslEngine == null || sslEngine.isInboundDone(); } public boolean isOutboundDone() { return sslEngine == null || sslEngine.isOutboundDone(); } /** * Check if there is any need to complete handshake. */ public boolean needToCompleteHandshake() { return (handshakeStatus == SSLEngineResult.HandshakeStatus.NEED_WRAP && !isInboundDone()); } public void schedulePreHandshakeWriteRequest(NextFilter nextFilter, WriteRequest writeRequest) { preHandshakeEventQueue.offer(new Event(EventType.FILTER_WRITE, nextFilter, writeRequest)); } public void flushPreHandshakeEvents() throws SSLException { Event scheduledWrite; while ((scheduledWrite = (Event) preHandshakeEventQueue.poll()) != null) { if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " Flushing buffered write request: " + scheduledWrite.data); } parent.filterWrite(scheduledWrite.nextFilter, session, (WriteRequest) scheduledWrite.data); } } public void scheduleFilterWrite(NextFilter nextFilter, WriteRequest writeRequest) { filterWriteEventQueue.offer(new Event(EventType.FILTER_WRITE, nextFilter, writeRequest)); } public void scheduleMessageReceived(NextFilter nextFilter, Object message) { messageReceivedEventQueue.offer(new Event(EventType.RECEIVED, nextFilter, message)); } public void flushScheduledEvents() { // Fire events only when no lock is hold for this handler. if (Thread.holdsLock(this)) { return; } Event e; // We need synchronization here inevitably because filterWrite can be // called simultaneously and cause 'bad record MAC' integrity error. synchronized (this) { while ((e = (Event) filterWriteEventQueue.poll()) != null) { e.nextFilter.filterWrite(session, (WriteRequest) e.data); } } while ((e = (Event) messageReceivedEventQueue.poll()) != null) { e.nextFilter.messageReceived(session, e.data); } } /** * Call when data read from net. Will perform inial hanshake or decrypt provided * Buffer. * Decrytpted data reurned by getAppBuffer(), if any. * * @param buf buffer to decrypt * @throws SSLException on errors */ public void messageReceived(NextFilter nextFilter, ByteBuffer buf) throws SSLException { if (buf.limit() > inNetBuffer.remaining()) { // We have to expand inNetBuffer inNetBuffer = SSLByteBufferPool.expandBuffer(inNetBuffer, inNetBuffer.capacity() + (buf.limit() * 2)); // We also expand app. buffer (twice the size of in net. buffer) appBuffer = SSLByteBufferPool.expandBuffer(appBuffer, inNetBuffer .capacity() * 2); if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " expanded inNetBuffer:" + inNetBuffer); SessionLog.debug(session, " expanded appBuffer:" + appBuffer); } } // append buf to inNetBuffer inNetBuffer.put(buf); if (!handshakeComplete) { handshake(nextFilter); } else { decrypt(nextFilter); } if (isInboundDone()) { // Rewind the MINA buffer if not all data is processed and inbound is finished. buf.position(buf.position() - inNetBuffer.position()); inNetBuffer.clear(); } } /** * Get decrypted application data. * * @return buffer with data */ public ByteBuffer getAppBuffer() { return appBuffer; } /** * Get encrypted data to be sent. * * @return buffer with data */ public ByteBuffer getOutNetBuffer() { return outNetBuffer; } /** * Encrypt provided buffer. Encytpted data reurned by getOutNetBuffer(). * * @param src data to encrypt * @throws SSLException on errors */ public void encrypt(ByteBuffer src) throws SSLException { if (!handshakeComplete) { throw new IllegalStateException(); } // The data buffer is (must be) empty, we can reuse the entire // buffer. outNetBuffer.clear(); SSLEngineResult result; // Loop until there is no more data in src while (src.hasRemaining()) { if (src.remaining() > ((outNetBuffer.capacity() - outNetBuffer .position()) / 2)) { // We have to expand outNetBuffer // Note: there is no way to know the exact size required, but enrypted data // shouln't need to be larger than twice the source data size? outNetBuffer = SSLByteBufferPool.expandBuffer(outNetBuffer, src .capacity() * 2); if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " expanded outNetBuffer:" + outNetBuffer); } } result = sslEngine.wrap(src, outNetBuffer); if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " Wrap res:" + result); } if (result.getStatus() == SSLEngineResult.Status.OK) { if (result.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_TASK) { doTasks(); } } else { throw new SSLException("SSLEngine error during encrypt: " + result.getStatus() + " src: " + src + "outNetBuffer: " + outNetBuffer); } } outNetBuffer.flip(); } /** * Start SSL shutdown process. * * @return <tt>true</tt> if shutdown process is started. * <tt>false</tt> if shutdown process is already finished. * * @throws SSLException on errors */ public boolean closeOutbound() throws SSLException { if (sslEngine == null || sslEngine.isOutboundDone()) { return false; } sslEngine.closeOutbound(); // By RFC 2616, we can "fire and forget" our close_notify // message, so that's what we'll do here. outNetBuffer.clear(); SSLEngineResult result = sslEngine.wrap(hsBB, outNetBuffer); if (result.getStatus() != SSLEngineResult.Status.CLOSED) { throw new SSLException("Improper close state: " + result); } outNetBuffer.flip(); return true; } /** * Decrypt in net buffer. Result is stored in app buffer. * * @throws SSLException */ private void decrypt(NextFilter nextFilter) throws SSLException { if (!handshakeComplete) { throw new IllegalStateException(); } unwrap(nextFilter); } /** * @param status * @throws SSLException */ private void checkStatus(SSLEngineResult res) throws SSLException { SSLEngineResult.Status status = res.getStatus(); /* * The status may be: * OK - Normal operation * OVERFLOW - Should never happen since the application buffer is * sized to hold the maximum packet size. * UNDERFLOW - Need to read more data from the socket. It's normal. * CLOSED - The other peer closed the socket. Also normal. */ if (status != SSLEngineResult.Status.OK && status != SSLEngineResult.Status.CLOSED && status != SSLEngineResult.Status.BUFFER_UNDERFLOW) { throw new SSLException("SSLEngine error during decrypt: " + status + " inNetBuffer: " + inNetBuffer + "appBuffer: " + appBuffer); } } /** * Perform any handshaking processing. */ public void handshake(NextFilter nextFilter) throws SSLException { if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " doHandshake()"); } for (;;) { if (handshakeStatus == SSLEngineResult.HandshakeStatus.FINISHED) { session.setAttribute(SSLFilter.SSL_SESSION, sslEngine .getSession()); if (SessionLog.isDebugEnabled(session)) { SSLSession sslSession = sslEngine.getSession(); SessionLog.debug(session, " handshakeStatus=FINISHED"); SessionLog.debug(session, " sslSession CipherSuite used " + sslSession.getCipherSuite()); } handshakeComplete = true; if (!initialHandshakeComplete && session.containsAttribute(SSLFilter.USE_NOTIFICATION)) { // SESSION_SECURED is fired only when it's the first handshake. // (i.e. renegotiation shouldn't trigger SESSION_SECURED.) initialHandshakeComplete = true; scheduleMessageReceived(nextFilter, SSLFilter.SESSION_SECURED); } break; } else if (handshakeStatus == SSLEngineResult.HandshakeStatus.NEED_TASK) { if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " handshakeStatus=NEED_TASK"); } handshakeStatus = doTasks(); } else if (handshakeStatus == SSLEngineResult.HandshakeStatus.NEED_UNWRAP) { // we need more data read if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " handshakeStatus=NEED_UNWRAP"); } SSLEngineResult.Status status = unwrapHandshake(nextFilter); if (status == SSLEngineResult.Status.BUFFER_UNDERFLOW || isInboundDone()) { // We need more data or the session is closed break; } } else if (handshakeStatus == SSLEngineResult.HandshakeStatus.NEED_WRAP) { if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " handshakeStatus=NEED_WRAP"); } // First make sure that the out buffer is completely empty. Since we // cannot call wrap with data left on the buffer if (outNetBuffer.hasRemaining()) { if (SessionLog.isDebugEnabled(session)) { SessionLog .debug(session, " Still data in out buffer!"); } break; } outNetBuffer.clear(); SSLEngineResult result = sslEngine.wrap(hsBB, outNetBuffer); if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " Wrap res:" + result); } outNetBuffer.flip(); handshakeStatus = result.getHandshakeStatus(); writeNetBuffer(nextFilter); } else { throw new IllegalStateException("Invalid Handshaking State" + handshakeStatus); } } } public WriteFuture writeNetBuffer(NextFilter nextFilter) throws SSLException { // Check if any net data needed to be writen if (!getOutNetBuffer().hasRemaining()) { // no; bail out return DefaultWriteFuture.newNotWrittenFuture(session); } WriteFuture writeFuture = null; // write net data // set flag that we are writing encrypted data // (used in SSLFilter.filterWrite()) writingEncryptedData = true; try { if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " write outNetBuffer: " + getOutNetBuffer()); } org.apache.mina.common.ByteBuffer writeBuffer = copy(getOutNetBuffer()); if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " session write: " + writeBuffer); } //debug("outNetBuffer (after copy): {0}", sslHandler.getOutNetBuffer()); writeFuture = new DefaultWriteFuture(session); parent.filterWrite(nextFilter, session, new WriteRequest( writeBuffer, writeFuture)); // loop while more writes required to complete handshake while (needToCompleteHandshake()) { try { handshake(nextFilter); } catch (SSLException ssle) { SSLException newSSLE = new SSLHandshakeException( "SSL handshake failed."); newSSLE.initCause(ssle); throw newSSLE; } if (getOutNetBuffer().hasRemaining()) { if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " write outNetBuffer2: " + getOutNetBuffer()); } org.apache.mina.common.ByteBuffer writeBuffer2 = copy(getOutNetBuffer()); writeFuture = new DefaultWriteFuture(session); parent.filterWrite(nextFilter, session, new WriteRequest( writeBuffer2, writeFuture)); } } } finally { writingEncryptedData = false; } if (writeFuture != null) { return writeFuture; } else { return DefaultWriteFuture.newNotWrittenFuture(session); } } private void unwrap(NextFilter nextFilter) throws SSLException { if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " unwrap()"); } // Prepare the net data for reading. inNetBuffer.flip(); SSLEngineResult res = unwrap0(); // prepare to be written again inNetBuffer.compact(); checkStatus(res); renegotiateIfNeeded(nextFilter, res); } private SSLEngineResult.Status unwrapHandshake(NextFilter nextFilter) throws SSLException { if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " unwrapHandshake()"); } // Prepare the net data for reading. inNetBuffer.flip(); SSLEngineResult res = unwrap0(); handshakeStatus = res.getHandshakeStatus(); checkStatus(res); // If handshake finished, no data was produced, and the status is still ok, // try to unwrap more if (handshakeStatus == SSLEngineResult.HandshakeStatus.FINISHED && res.getStatus() == SSLEngineResult.Status.OK && inNetBuffer.hasRemaining()) { res = unwrap0(); // prepare to be written again inNetBuffer.compact(); renegotiateIfNeeded(nextFilter, res); } else { // prepare to be written again inNetBuffer.compact(); } return res.getStatus(); } private void renegotiateIfNeeded(NextFilter nextFilter, SSLEngineResult res) throws SSLException { if (res.getStatus() != SSLEngineResult.Status.CLOSED && res.getStatus() != SSLEngineResult.Status.BUFFER_UNDERFLOW && res.getHandshakeStatus() != SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) { // Renegotiation required. SessionLog.debug(session, " Renegotiating..."); handshakeComplete = false; handshakeStatus = res.getHandshakeStatus(); handshake(nextFilter); } } private SSLEngineResult unwrap0() throws SSLException { SSLEngineResult res; do { if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " inNetBuffer: " + inNetBuffer); SessionLog.debug(session, " appBuffer: " + appBuffer); } res = sslEngine.unwrap(inNetBuffer, appBuffer); if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " Unwrap res:" + res); } } while (res.getStatus() == SSLEngineResult.Status.OK && (handshakeComplete && res.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING || res.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_UNWRAP)); return res; } /** * Do all the outstanding handshake tasks in the current Thread. */ private SSLEngineResult.HandshakeStatus doTasks() { if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " doTasks()"); } /* * We could run this in a separate thread, but I don't see the need * for this when used from SSLFilter. Use thread filters in MINA instead? */ Runnable runnable; while ((runnable = sslEngine.getDelegatedTask()) != null) { if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " doTask: " + runnable); } runnable.run(); } if (SessionLog.isDebugEnabled(session)) { SessionLog.debug(session, " doTasks(): " + sslEngine.getHandshakeStatus()); } return sslEngine.getHandshakeStatus(); } /** * Creates a new Mina byte buffer that is a deep copy of the remaining bytes * in the given buffer (between index buf.position() and buf.limit()) * * @param src the buffer to copy * @return the new buffer, ready to read from */ public static org.apache.mina.common.ByteBuffer copy(java.nio.ByteBuffer src) { org.apache.mina.common.ByteBuffer copy = org.apache.mina.common.ByteBuffer .allocate(src.remaining()); copy.put(src); copy.flip(); return copy; } private static class EventType { public static final EventType RECEIVED = new EventType("RECEIVED"); public static final EventType FILTER_WRITE = new EventType( "FILTER_WRITE"); private final String value; private EventType(String value) { this.value = value; } public String toString() { return value; } } private static class Event { private final EventType type; private final NextFilter nextFilter; private final Object data; Event(EventType type, NextFilter nextFilter, Object data) { this.type = type; this.nextFilter = nextFilter; this.data = data; } public Object getData() { return data; } public NextFilter getNextFilter() { return nextFilter; } public EventType getType() { return type; } } }
Resolved issue: DIRMINA-580 (Session Idle times out when SSL is enabled) * Applied the best patch suggested by Janardhanan git-svn-id: 947f4930c5627d17225bfea29b780d1478372630@656102 13f79535-47bb-0310-9956-ffa450edef68
filter-ssl/src/main/java/org/apache/mina/filter/support/SSLHandler.java
Resolved issue: DIRMINA-580 (Session Idle times out when SSL is enabled) * Applied the best patch suggested by Janardhanan
Java
apache-2.0
1ac44ad90f50c7a51c77b179fac5440135d58df6
0
unofficial/npr-android-app
// Copyright 2009 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 org.npr.android.news; import android.content.Intent; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.ExpandableListView; import android.widget.ImageView; import android.widget.SimpleExpandableListAdapter; import android.widget.TextView; import android.widget.ExpandableListView.OnChildClickListener; import org.npr.android.util.Tracker; import org.npr.android.util.Tracker.StationDetailsMeasurement; import org.npr.api.Station; import org.npr.api.Station.AudioStream; import org.npr.api.Station.Listenable; import org.npr.api.Station.Podcast; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; public class StationDetailsActivity extends BackAndForthActivity implements OnChildClickListener { private String stationId; private Station station; private ImageView imageView; private ImageView iconView; private Drawable imageDrawable; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 0: if (imageDrawable != null) { iconView.setVisibility(View.GONE); imageView.setImageDrawable(imageDrawable); imageView.setVisibility(View.VISIBLE); } break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); stationId = getIntent().getStringExtra(Constants.EXTRA_STATION_ID); station = StationListActivity.getStationFromCache(stationId); if (station == null) { finish(); } setContentView(R.layout.station_details); TextView miscText = (TextView) findViewById(R.id.StationMiscText); TextView taglineText = (TextView) findViewById(R.id.StationTaglineText); miscText.setText(new StringBuilder().append(station.getFrequency()).append( " ").append(station.getBand()).append(", ").append( station.getMarketCity())); taglineText.setText(station.getTagline()); iconView = (ImageView) findViewById(R.id.StationDetailsIcon); imageView = (ImageView) findViewById(R.id.StationDetailsImage); final String image = station.getImage(); if (image != null) { Thread imageInitThread = new Thread(new Runnable() { public void run() { imageDrawable = DownloadDrawable.createFromUrl(image); handler.sendEmptyMessage(0); } }); imageInitThread.start(); } constructList(); } @SuppressWarnings("unchecked") private void constructList() { int[] topLevel = new int[] { R.string.msg_station_streams, R.string.msg_station_podcasts }; List<AudioStream> streams = station.getAudioStreams(); List<Podcast> podcasts = station.getPodcasts(); int groupLayout = android.R.layout.simple_expandable_list_item_1; int childLayout = android.R.layout.simple_expandable_list_item_2; String[] groupFrom = new String[]{"title"}; int[] groupTo = new int[]{ android.R.id.text1 }; List<Map<String, String>> groupData = new ArrayList<Map<String, String>>(); String[] childFrom = new String[]{"title", "num"}; int[] childTo = groupTo; List<List<Map<String, String>>> childData = new ArrayList<List<Map<String, String>>>(); List<Map<String, String>> children = new ArrayList<Map<String, String>>(); // Streams if (streams.size() > 0) { Map<String, String> group1 = new HashMap<String, String>(); group1.put(groupFrom[0], String.format("%s (%d)", getString(topLevel[0]), streams.size())); groupData.add(group1); for (Iterator<AudioStream> it = streams.iterator(); it.hasNext();) { AudioStream stream = it.next(); int i = ((ListIterator) it).previousIndex(); Map<String, String> curChildMap = new HashMap<String, String>(); children.add(curChildMap); curChildMap.put(childFrom[0], stream.getTitle()); curChildMap.put(childFrom[1], "" + i); } childData.add(children); } // Podcasts if (podcasts.size() > 0) { Map<String, String> group2 = new HashMap<String, String>(); group2.put(groupFrom[0], String.format("%s (%d)", getString(topLevel[1]), podcasts.size())); groupData.add(group2); children = new ArrayList<Map<String, String>>(); for (Iterator<Podcast> it = podcasts.iterator(); it.hasNext(); ) { Podcast podcast = it.next(); int i = ((ListIterator) it).previousIndex(); Map<String, String> curChildMap = new HashMap<String, String>(); children.add(curChildMap); curChildMap.put(childFrom[0], podcast.getTitle()); curChildMap.put(childFrom[1], "" + i); } childData.add(children); } SimpleExpandableListAdapter listAdapter = new SimpleExpandableListAdapter( this, groupData, groupLayout, groupFrom, groupTo, childData, childLayout, childFrom, childTo); ExpandableListView list = (ExpandableListView) findViewById(R.id.ExpandableListView01); list.setAdapter(listAdapter); list.setOnChildClickListener(this); // Expand first group if present and it has something to show if (listAdapter.getGroupCount() > 0) { if (listAdapter.getChildrenCount(0) > 0) { list.expandGroup(0); } } } @Override public CharSequence getMainTitle() { return station.getName(); } @SuppressWarnings("unchecked") @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { Map<String, String> map = (Map<String, String>) parent.getExpandableListAdapter().getChild( groupPosition, childPosition); int num = Integer.parseInt(map.get("num")); Listenable l; Intent i; switch(groupPosition) { case 0: l = station.getAudioStreams().get(num); i = new Intent(ListenActivity.class.getName()).putExtra( ListenActivity.EXTRA_CONTENT_URL, l.getUrl()).putExtra( ListenActivity.EXTRA_CONTENT_TITLE, l.getTitle()).putExtra( ListenActivity.EXTRA_PLAY_IMMEDIATELY, true).putExtra( ListenActivity.EXTRA_STREAM, true); sendBroadcast(i); break; case 1: l = station.getPodcasts().get(num); i = new Intent(this, PodcastActivity.class).putExtra( PodcastActivity.EXTRA_PODCAST_TITLE, l.getTitle()).putExtra( PodcastActivity.EXTRA_PODCAST_URL, l.getUrl()); startActivity(i); break; } return true; } @Override public void trackNow() { StringBuilder pageName = new StringBuilder("Stations").append(Tracker.PAGE_NAME_SEPARATOR); pageName.append(getMainTitle()); Tracker.instance(getApplication()).trackPage( new StationDetailsMeasurement(pageName.toString(), "Stations", stationId)); } }
src/org/npr/android/news/StationDetailsActivity.java
// Copyright 2009 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 org.npr.android.news; import android.content.Intent; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.ExpandableListView; import android.widget.ImageView; import android.widget.SimpleExpandableListAdapter; import android.widget.TextView; import android.widget.ExpandableListView.OnChildClickListener; import org.npr.android.util.Tracker; import org.npr.android.util.Tracker.StationDetailsMeasurement; import org.npr.api.Station; import org.npr.api.Station.AudioStream; import org.npr.api.Station.Listenable; import org.npr.api.Station.Podcast; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; public class StationDetailsActivity extends BackAndForthActivity implements OnChildClickListener { private String stationId; private Station station; private ImageView imageView; private ImageView iconView; private Drawable imageDrawable; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 0: if (imageDrawable != null) { iconView.setVisibility(View.GONE); imageView.setImageDrawable(imageDrawable); imageView.setVisibility(View.VISIBLE); } break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); stationId = getIntent().getStringExtra(Constants.EXTRA_STATION_ID); station = StationListActivity.getStationFromCache(stationId); if (station == null) { finish(); } setContentView(R.layout.station_details); TextView miscText = (TextView) findViewById(R.id.StationMiscText); TextView taglineText = (TextView) findViewById(R.id.StationTaglineText); miscText.setText(new StringBuilder().append(station.getFrequency()).append( " ").append(station.getBand()).append(", ").append( station.getMarketCity())); taglineText.setText(station.getTagline()); iconView = (ImageView) findViewById(R.id.StationDetailsIcon); imageView = (ImageView) findViewById(R.id.StationDetailsImage); final String image = station.getImage(); if (image != null) { Thread imageInitThread = new Thread(new Runnable() { public void run() { imageDrawable = DownloadDrawable.createFromUrl(image); handler.sendEmptyMessage(0); } }); imageInitThread.start(); } constructList(); } @SuppressWarnings("unchecked") private void constructList() { int[] topLevel = new int[] { R.string.msg_station_streams, R.string.msg_station_podcasts }; List<AudioStream> streams = station.getAudioStreams(); List<Podcast> podcasts = station.getPodcasts(); int groupLayout = android.R.layout.simple_expandable_list_item_1; int childLayout = android.R.layout.simple_expandable_list_item_2; String[] groupFrom = new String[]{"title"}; int[] groupTo = new int[]{ android.R.id.text1 }; List<Map<String, String>> groupData = new ArrayList<Map<String, String>>(); String[] childFrom = new String[]{"title", "num"}; int[] childTo = groupTo; List<List<Map<String, String>>> childData = new ArrayList<List<Map<String, String>>>(); List<Map<String, String>> children = new ArrayList<Map<String, String>>(); // Streams if (streams.size() > 0) { Map<String, String> group1 = new HashMap<String, String>(); group1.put(groupFrom[0], String.format("%s (%d)", getString(topLevel[0]), streams.size())); groupData.add(group1); for (Iterator<AudioStream> it = streams.iterator(); it.hasNext();) { AudioStream stream = it.next(); int i = ((ListIterator) it).previousIndex(); Map<String, String> curChildMap = new HashMap<String, String>(); children.add(curChildMap); curChildMap.put(childFrom[0], stream.getTitle()); curChildMap.put(childFrom[1], "" + i); } childData.add(children); } // Podcasts if (podcasts.size() > 0) { Map<String, String> group2 = new HashMap<String, String>(); group2.put(groupFrom[0], String.format("%s (%d)", getString(topLevel[1]), podcasts.size())); groupData.add(group2); children = new ArrayList<Map<String, String>>(); for (Iterator<Podcast> it = podcasts.iterator(); it.hasNext(); ) { Podcast podcast = it.next(); int i = ((ListIterator) it).previousIndex(); Map<String, String> curChildMap = new HashMap<String, String>(); children.add(curChildMap); curChildMap.put(childFrom[0], podcast.getTitle()); curChildMap.put(childFrom[1], "" + i); } childData.add(children); } SimpleExpandableListAdapter listAdapter = new SimpleExpandableListAdapter( this, groupData, groupLayout, groupFrom, groupTo, childData, childLayout, childFrom, childTo); ExpandableListView list = (ExpandableListView) findViewById(R.id.ExpandableListView01); list.setAdapter(listAdapter); list.setOnChildClickListener(this); // Expand first header list.expandGroup(0); } @Override public CharSequence getMainTitle() { return station.getName(); } @SuppressWarnings("unchecked") @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { Map<String, String> map = (Map<String, String>) parent.getExpandableListAdapter().getChild( groupPosition, childPosition); int num = Integer.parseInt(map.get("num")); Listenable l; Intent i; switch(groupPosition) { case 0: l = station.getAudioStreams().get(num); i = new Intent(ListenActivity.class.getName()).putExtra( ListenActivity.EXTRA_CONTENT_URL, l.getUrl()).putExtra( ListenActivity.EXTRA_CONTENT_TITLE, l.getTitle()).putExtra( ListenActivity.EXTRA_PLAY_IMMEDIATELY, true).putExtra( ListenActivity.EXTRA_STREAM, true); sendBroadcast(i); break; case 1: l = station.getPodcasts().get(num); i = new Intent(this, PodcastActivity.class).putExtra( PodcastActivity.EXTRA_PODCAST_TITLE, l.getTitle()).putExtra( PodcastActivity.EXTRA_PODCAST_URL, l.getUrl()); startActivity(i); break; } return true; } @Override public void trackNow() { StringBuilder pageName = new StringBuilder("Stations").append(Tracker.PAGE_NAME_SEPARATOR); pageName.append(getMainTitle()); Tracker.instance(getApplication()).trackPage( new StationDetailsMeasurement(pageName.toString(), "Stations", stationId)); } }
Fix crash when station has no podcasts or streams (#1708041) git-svn-id: db726465513d871f9b26a5f354abfdea998d0c60@74 0a442a4a-40cc-11de-998b-8fedbbe774c7
src/org/npr/android/news/StationDetailsActivity.java
Fix crash when station has no podcasts or streams (#1708041)
Java
apache-2.0
e8561d6fb12e1929699d7906a61038a3477db32f
0
JetBrains/xodus,JetBrains/xodus,JetBrains/xodus
/** * Copyright 2010 - 2021 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 jetbrains.exodus.env; import jetbrains.exodus.ConfigSettingChangeListener; import jetbrains.exodus.ExodusException; import jetbrains.exodus.InvalidSettingException; import jetbrains.exodus.backup.BackupStrategy; import jetbrains.exodus.core.dataStructures.ObjectCacheBase; import jetbrains.exodus.core.dataStructures.Pair; import jetbrains.exodus.core.execution.SharedTimer; import jetbrains.exodus.crypto.StreamCipherProvider; import jetbrains.exodus.debug.StackTrace; import jetbrains.exodus.debug.TxnProfiler; import jetbrains.exodus.entitystore.MetaServer; import jetbrains.exodus.env.management.DatabaseProfiler; import jetbrains.exodus.env.management.EnvironmentConfigWithOperations; import jetbrains.exodus.gc.GarbageCollector; import jetbrains.exodus.gc.UtilizationProfile; import jetbrains.exodus.io.DataReaderWriterProvider; import jetbrains.exodus.io.RemoveBlockType; import jetbrains.exodus.io.StorageTypeNotAllowedException; import jetbrains.exodus.log.DataIterator; import jetbrains.exodus.log.Log; import jetbrains.exodus.log.LogConfig; import jetbrains.exodus.log.LogTip; import jetbrains.exodus.tree.ExpiredLoggableCollection; import jetbrains.exodus.tree.TreeMetaInfo; import jetbrains.exodus.tree.btree.BTree; import jetbrains.exodus.tree.btree.BTreeBalancePolicy; import jetbrains.exodus.util.DeferredIO; import jetbrains.exodus.util.IOUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.management.InstanceAlreadyExistsException; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.ReentrantReadWriteLock; import static jetbrains.exodus.env.EnvironmentStatistics.Type.*; public class EnvironmentImpl implements Environment { public static final int META_TREE_ID = 1; private static final Logger logger = LoggerFactory.getLogger(EnvironmentImpl.class); private static final String ENVIRONMENT_PROPERTIES_FILE = "exodus.properties"; @NotNull private final Log log; @NotNull private final EnvironmentConfig ec; private BTreeBalancePolicy balancePolicy; private MetaTreeImpl metaTree; private final AtomicInteger structureId; @NotNull private final TransactionSet txns; private final LinkedList<RunnableWithTxnRoot> txnSafeTasks; @Nullable private StoreGetCache storeGetCache; private final EnvironmentSettingsListener envSettingsListener; private final GarbageCollector gc; final Object commitLock = new Object(); private final ReentrantReadWriteLock.ReadLock metaReadLock; final ReentrantReadWriteLock.WriteLock metaWriteLock; private final ReentrantTransactionDispatcher txnDispatcher; @NotNull private final EnvironmentStatistics statistics; @Nullable private final TxnProfiler txnProfiler; @Nullable private final jetbrains.exodus.env.management.EnvironmentConfig configMBean; @Nullable private final jetbrains.exodus.env.management.EnvironmentStatistics statisticsMBean; @Nullable private final DatabaseProfiler profilerMBean; /** * Throwable caught during commit after which rollback of highAddress failed. * Generally, it should ne null, otherwise environment is inoperative: * no transaction can be started or committed in that state. Once environment became inoperative, * it will remain inoperative forever. */ volatile Throwable throwableOnCommit; private Throwable throwableOnClose; @Nullable private final StuckTransactionMonitor stuckTxnMonitor; @Nullable private final StreamCipherProvider streamCipherProvider; @Nullable private final byte[] cipherKey; private final long cipherBasicIV; @SuppressWarnings({"ThisEscapedInObjectConstruction"}) EnvironmentImpl(@NotNull final Log log, @NotNull final EnvironmentConfig ec) { this.log = log; this.ec = ec; final String logLocation = log.getLocation(); applyEnvironmentSettings(logLocation, ec); checkStorageType(logLocation, ec); final DataReaderWriterProvider readerWriterProvider = log.getConfig().getReaderWriterProvider(); readerWriterProvider.onEnvironmentCreated(this); final Pair<MetaTreeImpl, Integer> meta; synchronized (commitLock) { meta = MetaTreeImpl.create(this); } metaTree = meta.getFirst(); structureId = new AtomicInteger(meta.getSecond()); txns = new TransactionSet(); txnSafeTasks = new LinkedList<>(); invalidateStoreGetCache(); envSettingsListener = new EnvironmentSettingsListener(); ec.addChangedSettingsListener(envSettingsListener); gc = new GarbageCollector(this); ReentrantReadWriteLock metaLock = new ReentrantReadWriteLock(); metaReadLock = metaLock.readLock(); metaWriteLock = metaLock.writeLock(); txnDispatcher = new ReentrantTransactionDispatcher(ec.getEnvMaxParallelTxns()); statistics = new EnvironmentStatistics(this); txnProfiler = ec.getProfilerEnabled() ? new TxnProfiler() : null; final jetbrains.exodus.env.management.EnvironmentConfig configMBean = ec.isManagementEnabled() ? createConfigMBean(this) : null; if (configMBean != null) { this.configMBean = configMBean; // if we don't gather statistics then we should not expose corresponding managed bean statisticsMBean = ec.getEnvGatherStatistics() ? new jetbrains.exodus.env.management.EnvironmentStatistics(this) : null; profilerMBean = txnProfiler == null ? null : new DatabaseProfiler(this); } else { this.configMBean = null; statisticsMBean = null; profilerMBean = null; } throwableOnCommit = null; throwableOnClose = null; stuckTxnMonitor = (transactionTimeout() > 0 || transactionExpirationTimeout() > 0) ? new StuckTransactionMonitor(this) : null; final LogConfig logConfig = log.getConfig(); streamCipherProvider = logConfig.getCipherProvider(); cipherKey = logConfig.getCipherKey(); cipherBasicIV = logConfig.getCipherBasicIV(); loggerInfo("Exodus environment created: " + logLocation); } @Override public long getCreated() { return log.getCreated(); } @Override @NotNull public String getLocation() { return log.getLocation(); } @Override public @NotNull BitmapImpl openBitmap(@NotNull String name, @NotNull final StoreConfig config, @NotNull Transaction transaction) { if (config.duplicates) { throw new ExodusException("Bitmap can't be opened atop of the store with duplicates"); } final StoreImpl store = openStore(name.concat("#bitmap"), config, transaction); return new BitmapImpl(store); } @Override @NotNull public EnvironmentConfig getEnvironmentConfig() { return ec; } @Override @NotNull public EnvironmentStatistics getStatistics() { return statistics; } public GarbageCollector getGC() { return gc; } @Nullable public TxnProfiler getTxnProfiler() { return txnProfiler; } @Override @NotNull public StoreImpl openStore(@NotNull final String name, @NotNull final StoreConfig config, @NotNull final Transaction transaction) { final TransactionBase txn = (TransactionBase) transaction; return openStoreImpl(name, config, txn, txn.getTreeMetaInfo(name)); } @Override @Nullable public StoreImpl openStore(@NotNull final String name, @NotNull final StoreConfig config, @NotNull final Transaction transaction, final boolean creationRequired) { final TransactionBase txn = (TransactionBase) transaction; final TreeMetaInfo metaInfo = txn.getTreeMetaInfo(name); if (metaInfo == null && !creationRequired) { return null; } return openStoreImpl(name, config, txn, metaInfo); } @Override @NotNull public TransactionBase beginTransaction() { return beginTransaction(null, false, false); } @Override @NotNull public TransactionBase beginTransaction(final Runnable beginHook) { return beginTransaction(beginHook, false, false); } @NotNull @Override public Transaction beginExclusiveTransaction() { return beginTransaction(null, true, false); } @NotNull @Override public Transaction beginExclusiveTransaction(Runnable beginHook) { return beginTransaction(beginHook, true, false); } @NotNull @Override public Transaction beginReadonlyTransaction() { return beginReadonlyTransaction(null); } @NotNull @Override public TransactionBase beginReadonlyTransaction(final Runnable beginHook) { checkIsOperative(); return new ReadonlyTransaction(this, false, beginHook); } @NotNull public ReadWriteTransaction beginGCTransaction() { if (ec.getEnvIsReadonly()) { throw new ReadonlyTransactionException("Can't start GC transaction on read-only Environment"); } return new ReadWriteTransaction(this, null, ec.getGcUseExclusiveTransaction(), true) { @Override boolean isGCTransaction() { return true; } }; } public ReadonlyTransaction beginTransactionAt(final long highAddress) { checkIsOperative(); return new ReadonlyTransaction(this, highAddress); } @Override public void executeInTransaction(@NotNull final TransactionalExecutable executable) { executeInTransaction(executable, beginTransaction()); } @Override public void executeInExclusiveTransaction(@NotNull final TransactionalExecutable executable) { executeInTransaction(executable, beginExclusiveTransaction()); } @Override public void executeInReadonlyTransaction(@NotNull TransactionalExecutable executable) { final Transaction txn = beginReadonlyTransaction(); try { executable.execute(txn); } finally { abortIfNotFinished(txn); } } @Override public <T> T computeInTransaction(@NotNull TransactionalComputable<T> computable) { return computeInTransaction(computable, beginTransaction()); } @Override public <T> T computeInExclusiveTransaction(@NotNull TransactionalComputable<T> computable) { return computeInTransaction(computable, beginExclusiveTransaction()); } @Override public <T> T computeInReadonlyTransaction(@NotNull TransactionalComputable<T> computable) { final Transaction txn = beginReadonlyTransaction(); try { return computable.compute(txn); } finally { abortIfNotFinished(txn); } } @Override public void executeTransactionSafeTask(@NotNull final Runnable task) { final long newestTxnRoot = txns.getNewestTxnRootAddress(); if (newestTxnRoot == Long.MIN_VALUE) { task.run(); } else { synchronized (txnSafeTasks) { txnSafeTasks.addLast(new RunnableWithTxnRoot(task, newestTxnRoot)); } } } public int getStuckTransactionCount() { return stuckTxnMonitor == null ? 0 : stuckTxnMonitor.getStuckTxnCount(); } @Override @Nullable public StreamCipherProvider getCipherProvider() { return streamCipherProvider; } @Override @Nullable public byte[] getCipherKey() { return cipherKey; } @Override public long getCipherBasicIV() { return cipherBasicIV; } @Override public void clear() { final Thread currentThread = Thread.currentThread(); if (txnDispatcher.getThreadPermits(currentThread) != 0) { throw new ExodusException("Environment.clear() can't proceed if there is a transaction in current thread"); } runAllTransactionSafeTasks(); synchronized (txnSafeTasks) { txnSafeTasks.clear(); } suspendGC(); try { final int permits = txnDispatcher.acquireExclusiveTransaction(currentThread);// wait for and stop all writing transactions try { synchronized (commitLock) { metaWriteLock.lock(); try { gc.clear(); log.clear(); invalidateStoreGetCache(); throwableOnCommit = null; final Pair<MetaTreeImpl, Integer> meta = MetaTreeImpl.create(this); metaTree = meta.getFirst(); structureId.set(meta.getSecond()); } finally { metaWriteLock.unlock(); } } } finally { txnDispatcher.releaseTransaction(currentThread, permits); } } finally { resumeGC(); } } @Override public void close() { // if this is already closed do nothing synchronized (commitLock) { if (!isOpen()) { return; } } final MetaServer metaServer = getEnvironmentConfig().getMetaServer(); if (metaServer != null) { metaServer.stop(this); } if (configMBean != null) { configMBean.unregister(); } if (statisticsMBean != null) { statisticsMBean.unregister(); } if (profilerMBean != null) { profilerMBean.unregister(); } runAllTransactionSafeTasks(); // in order to avoid deadlock, do not finish gc inside lock // it is safe to invoke gc.finish() several times gc.finish(); final float logCacheHitRate; final float storeGetCacheHitRate; synchronized (commitLock) { // concurrent close() detected if (throwableOnClose != null) { throw new EnvironmentClosedException(throwableOnClose); // add combined stack trace information } final boolean closeForcedly = ec.getEnvCloseForcedly(); checkInactive(closeForcedly); try { if (!closeForcedly && !ec.getEnvIsReadonly() && ec.isGcEnabled()) { executeInTransaction(txn -> gc.getUtilizationProfile().forceSave(txn)); } ec.removeChangedSettingsListener(envSettingsListener); logCacheHitRate = log.getCacheHitRate(); log.close(); } finally { log.release(); } if (storeGetCache == null) { storeGetCacheHitRate = 0; } else { storeGetCacheHitRate = storeGetCache.hitRate(); storeGetCache.close(); } if (txnProfiler != null) { txnProfiler.dump(); } throwableOnClose = new EnvironmentClosedException(); throwableOnCommit = throwableOnClose; } loggerDebug("Store get cache hit rate: " + ObjectCacheBase.formatHitRate(storeGetCacheHitRate)); loggerDebug("Exodus log cache hit rate: " + ObjectCacheBase.formatHitRate(logCacheHitRate)); } @Override public boolean isOpen() { return throwableOnClose == null; } @NotNull @Override public BackupStrategy getBackupStrategy() { return new EnvironmentBackupStrategyImpl(this); } @Override public void truncateStore(@NotNull final String storeName, @NotNull final Transaction txn) { final ReadWriteTransaction t = throwIfReadonly(txn, "Can't truncate a store in read-only transaction"); StoreImpl store = openStore(storeName, StoreConfig.USE_EXISTING, t, false); if (store == null) { throw new ExodusException("Attempt to truncate unknown store '" + storeName + '\''); } t.storeRemoved(store); final TreeMetaInfo metaInfoCloned = store.getMetaInfo().clone(allocateStructureId()); store = new StoreImpl(this, storeName, metaInfoCloned); t.storeCreated(store); } @Override public void removeStore(@NotNull final String storeName, @NotNull final Transaction txn) { final ReadWriteTransaction t = throwIfReadonly(txn, "Can't remove a store in read-only transaction"); final StoreImpl store = openStore(storeName, StoreConfig.USE_EXISTING, t, false); if (store == null) { throw new ExodusException("Attempt to remove unknown store '" + storeName + '\''); } t.storeRemoved(store); } public long getAllStoreCount() { metaReadLock.lock(); try { return metaTree.getAllStoreCount(); } finally { metaReadLock.unlock(); } } @Override @NotNull public List<String> getAllStoreNames(@NotNull final Transaction txn) { checkIfTransactionCreatedAgainstThis(txn); return ((TransactionBase) txn).getAllStoreNames(); } public boolean storeExists(@NotNull final String storeName, @NotNull final Transaction txn) { return ((TransactionBase) txn).getTreeMetaInfo(storeName) != null; } @NotNull public Log getLog() { return log; } @Override public void gc() { gc.wake(true); } @Override public void suspendGC() { gc.suspend(); } @Override public void resumeGC() { gc.resume(); } @Override public void executeBeforeGc(Runnable action) { gc.addBeforeGcAction(action); } public BTreeBalancePolicy getBTreeBalancePolicy() { // we don't care of possible race condition here if (balancePolicy == null) { balancePolicy = new BTreeBalancePolicy(ec.getTreeMaxPageSize(), ec.getTreeDupMaxPageSize()); } return balancePolicy; } /** * Flushes Log's data writer exclusively in commit lock. This guarantees that the data writer is in committed state. * Also performs syncing cached by OS data to storage device. */ public void flushAndSync() { synchronized (commitLock) { if (isOpen()) { getLog().sync(); } } } public void removeFiles(final long[] files, @NotNull final RemoveBlockType rbt) { synchronized (commitLock) { log.beginWrite(); try { log.forgetFiles(files); log.endWrite(); } catch (Throwable t) { log.abortWrite(); throw ExodusException.toExodusException(t, "Failed to forget files in log"); } } for (long file : files) { log.removeFile(file, rbt); } } public float getStoreGetCacheHitRate() { return storeGetCache == null ? 0 : storeGetCache.hitRate(); } protected StoreImpl createStore(@NotNull final String name, @NotNull final TreeMetaInfo metaInfo) { return new StoreImpl(this, name, metaInfo); } protected void finishTransaction(@NotNull final TransactionBase txn) { if (!txn.isReadonly()) { releaseTransaction(txn); } txns.remove(txn); txn.setIsFinished(); final long duration = System.currentTimeMillis() - txn.getCreated(); if (txn.isReadonly()) { statistics.getStatisticsItem(READONLY_TRANSACTIONS).incTotal(); statistics.getStatisticsItem(READONLY_TRANSACTIONS_DURATION).addTotal(duration); } else if (txn.isGCTransaction()) { statistics.getStatisticsItem(GC_TRANSACTIONS).incTotal(); statistics.getStatisticsItem(GC_TRANSACTIONS_DURATION).addTotal(duration); } else { statistics.getStatisticsItem(TRANSACTIONS).incTotal(); statistics.getStatisticsItem(TRANSACTIONS_DURATION).addTotal(duration); } runTransactionSafeTasks(); } @NotNull protected TransactionBase beginTransaction(Runnable beginHook, boolean exclusive, boolean cloneMeta) { checkIsOperative(); return ec.getEnvIsReadonly() && ec.getEnvFailFastInReadonly() ? new ReadonlyTransaction(this, exclusive, beginHook) : new ReadWriteTransaction(this, beginHook, exclusive, cloneMeta); } @Nullable StoreGetCache getStoreGetCache() { return storeGetCache; } long getDiskUsage() { return log.getDiskUsage(); } void acquireTransaction(@NotNull final TransactionBase txn) { checkIfTransactionCreatedAgainstThis(txn); txnDispatcher.acquireTransaction(throwIfReadonly( txn, "TxnDispatcher can't acquire permits for read-only transaction"), this); } void releaseTransaction(@NotNull final TransactionBase txn) { checkIfTransactionCreatedAgainstThis(txn); txnDispatcher.releaseTransaction(throwIfReadonly( txn, "TxnDispatcher can't release permits for read-only transaction")); } void downgradeTransaction(@NotNull final TransactionBase txn) { txnDispatcher.downgradeTransaction(throwIfReadonly( txn, "TxnDispatcher can't downgrade read-only transaction")); } boolean shouldTransactionBeExclusive(@NotNull final ReadWriteTransaction txn) { final int replayCount = txn.getReplayCount(); return replayCount >= ec.getEnvTxnReplayMaxCount() || System.currentTimeMillis() - txn.getCreated() >= ec.getEnvTxnReplayTimeout(); } /** * @return timeout for a transaction in milliseconds, or 0 if no timeout is configured */ int transactionTimeout() { return ec.getEnvMonitorTxnsTimeout(); } /** * @return expiration timeout for a transaction in milliseconds, or 0 if no timeout is configured */ int transactionExpirationTimeout() { return ec.getEnvMonitorTxnsExpirationTimeout(); } /** * Tries to load meta tree located at specified rootAddress. * * @param rootAddress tree root address. * @return tree instance or null if the address is not valid. */ @Nullable BTree loadMetaTree(final long rootAddress, final LogTip logTip) { if (rootAddress < 0 || rootAddress >= logTip.highAddress) return null; return new BTree(log, getBTreeBalancePolicy(), rootAddress, false, META_TREE_ID) { @NotNull @Override public DataIterator getDataIterator(long address) { return new DataIterator(log, address); } }; } boolean commitTransaction(@NotNull final ReadWriteTransaction txn) { if (flushTransaction(txn, false)) { finishTransaction(txn); return true; } return false; } boolean flushTransaction(@NotNull final ReadWriteTransaction txn, final boolean forceCommit) { checkIfTransactionCreatedAgainstThis(txn); if (!forceCommit && txn.isIdempotent()) { return true; } final ExpiredLoggableCollection expiredLoggables; final long initialHighAddress; final long resultingHighAddress; final boolean isGcTransaction = txn.isGCTransaction(); boolean wasUpSaved = false; final UtilizationProfile up = gc.getUtilizationProfile(); if (!isGcTransaction && up.isDirty()) { up.save(txn); wasUpSaved = true; } synchronized (commitLock) { if (ec.getEnvIsReadonly()) { throw new ReadonlyTransactionException(); } checkIsOperative(); if (!txn.checkVersion(metaTree.root)) { // meta lock not needed 'cause write can only occur in another commit lock return false; } if (wasUpSaved) { up.setDirty(false); } final LogTip logTip = log.beginWrite(); initialHighAddress = logTip.highAddress; boolean writeConfirmed = false; try { final MetaTreeImpl.Proto[] tree = new MetaTreeImpl.Proto[1]; expiredLoggables = txn.doCommit(tree); // there is a temptation to postpone I/O in order to reduce number of writes to storage device, // but it's quite difficult to resolve all possible inconsistencies afterwards, // so think twice before removing the following line log.flush(); final MetaTreeImpl.Proto proto = tree[0]; metaWriteLock.lock(); try { final LogTip updatedTip = log.endWrite(); writeConfirmed = true; resultingHighAddress = updatedTip.approvedHighAddress; txn.setMetaTree(metaTree = MetaTreeImpl.create(this, updatedTip, proto)); txn.executeCommitHook(); } finally { metaWriteLock.unlock(); } // update txn profiler within commitLock updateTxnProfiler(txn, initialHighAddress, resultingHighAddress); } catch (Throwable t) { // pokemon exception handling to decrease try/catch block overhead loggerError("Failed to flush transaction", t); if (writeConfirmed) { throwableOnCommit = t; // inoperative on failing to read meta tree throw ExodusException.toExodusException(t, "Failed to read meta tree"); } try { log.revertWrite(logTip); } catch (Throwable th) { throwableOnCommit = t; // inoperative on failing to update high address loggerError("Failed to rollback high address", th); throw ExodusException.toExodusException(th, "Failed to rollback high address"); } throw ExodusException.toExodusException(t, "Failed to flush transaction"); } } gc.fetchExpiredLoggables(expiredLoggables); // update statistics statistics.getStatisticsItem(BYTES_WRITTEN).setTotal(resultingHighAddress); if (isGcTransaction) { statistics.getStatisticsItem(BYTES_MOVED_BY_GC).addTotal(resultingHighAddress - initialHighAddress); } statistics.getStatisticsItem(FLUSHED_TRANSACTIONS).incTotal(); return true; } MetaTreeImpl holdNewestSnapshotBy(@NotNull final TransactionBase txn) { return holdNewestSnapshotBy(txn, true); } MetaTreeImpl holdNewestSnapshotBy(@NotNull final TransactionBase txn, final boolean acquireTxn) { if (acquireTxn) { acquireTransaction(txn); } final Runnable beginHook = txn.getBeginHook(); metaReadLock.lock(); try { if (beginHook != null) { beginHook.run(); } return metaTree; } finally { metaReadLock.unlock(); } } public MetaTree getMetaTree() { metaReadLock.lock(); try { return metaTree; } finally { metaReadLock.unlock(); } } MetaTreeImpl getMetaTreeInternal() { return metaTree; } // unsafe void setMetaTreeInternal(MetaTreeImpl metaTree) { this.metaTree = metaTree; } /** * Opens or creates store just like openStore() with the same parameters does, but gets parameters * that are not annotated. This allows to pass, e.g., nullable transaction. * * @param name store name * @param config store configuration * @param txn transaction, should not null if store doesn't exists * @param metaInfo target meta information * @return store object */ @SuppressWarnings({"AssignmentToMethodParameter"}) @NotNull StoreImpl openStoreImpl(@NotNull final String name, @NotNull StoreConfig config, @NotNull final TransactionBase txn, @Nullable TreeMetaInfo metaInfo) { checkIfTransactionCreatedAgainstThis(txn); if (config.useExisting) { // this parameter requires to recalculate if (metaInfo == null) { throw new ExodusException("Can't restore meta information for store " + name); } else { config = TreeMetaInfo.toConfig(metaInfo); } } final StoreImpl result; if (metaInfo == null) { if (txn.isReadonly() && ec.getEnvReadonlyEmptyStores()) { return createTemporaryEmptyStore(name); } final int structureId = allocateStructureId(); metaInfo = TreeMetaInfo.load(this, config.duplicates, config.prefixing, structureId); result = createStore(name, metaInfo); final ReadWriteTransaction tx = throwIfReadonly(txn, "Can't create a store in read-only transaction"); tx.getMutableTree(result); tx.storeCreated(result); } else { final boolean hasDuplicates = metaInfo.hasDuplicates(); if (hasDuplicates != config.duplicates) { throw new ExodusException("Attempt to open store '" + name + "' with duplicates = " + config.duplicates + " while it was created with duplicates =" + hasDuplicates); } if (metaInfo.isKeyPrefixing() != config.prefixing) { if (!config.prefixing) { throw new ExodusException("Attempt to open store '" + name + "' with prefixing = false while it was created with prefixing = true"); } // if we're trying to open existing store with prefixing which actually wasn't created as store // with prefixing due to lack of the PatriciaTree feature, then open store with existing config metaInfo = TreeMetaInfo.load(this, hasDuplicates, false, metaInfo.getStructureId()); } result = createStore(name, metaInfo); // XD-774: if the store was just removed in the same txn forget the removal if (txn instanceof ReadWriteTransaction) { ((ReadWriteTransaction) txn).storeOpened(result); } } return result; } int getLastStructureId() { return structureId.get(); } void registerTransaction(@NotNull final TransactionBase txn) { checkIfTransactionCreatedAgainstThis(txn); // N.B! due to TransactionImpl.revert(), there can appear a txn which is already in the transaction set // any implementation of transaction set should process this well txns.add(txn); } boolean isRegistered(@NotNull final ReadWriteTransaction txn) { checkIfTransactionCreatedAgainstThis(txn); return txns.contains(txn); } int activeTransactions() { return txns.size(); } void runTransactionSafeTasks() { if (throwableOnCommit == null) { List<Runnable> tasksToRun = null; final long oldestTxnRoot = txns.getOldestTxnRootAddress(); synchronized (txnSafeTasks) { while (true) { if (!txnSafeTasks.isEmpty()) { final RunnableWithTxnRoot r = txnSafeTasks.getFirst(); if (r.txnRoot < oldestTxnRoot) { txnSafeTasks.removeFirst(); if (tasksToRun == null) { tasksToRun = new ArrayList<>(4); } tasksToRun.add(r.runnable); continue; } } break; } } if (tasksToRun != null) { for (final Runnable task : tasksToRun) { task.run(); } } } } void forEachActiveTransaction(@NotNull final TransactionalExecutable executable) { txns.forEach(executable); } void setHighAddress(final long highAddress) { synchronized (commitLock) { log.setHighAddress(log.getTip(), highAddress); final Pair<MetaTreeImpl, Integer> meta = MetaTreeImpl.create(this); metaWriteLock.lock(); try { metaTree = meta.getFirst(); } finally { metaWriteLock.unlock(); } } } // for tests only boolean awaitUpdate(final long fromAddress, long timeout) { final int delta = 20; try { while (timeout > 0) { if (log.getHighAddress() > fromAddress) { return true; } Thread.sleep(delta); timeout -= delta; } } catch (InterruptedException ignore) { Thread.currentThread().interrupt(); } return false; } protected StoreImpl createTemporaryEmptyStore(String name) { return new TemporaryEmptyStore(this, name); } static boolean isUtilizationProfile(@NotNull final String storeName) { return GarbageCollector.isUtilizationProfile(storeName); } static ReadWriteTransaction throwIfReadonly(@NotNull final Transaction txn, @NotNull final String exceptionMessage) { if (txn.isReadonly()) { throw new ReadonlyTransactionException(exceptionMessage); } return (ReadWriteTransaction) txn; } static void loggerError(@NotNull final String errorMessage) { loggerError(errorMessage, null); } static void loggerError(@NotNull final String errorMessage, @Nullable final Throwable t) { if (t == null) { logger.error(errorMessage); } else { logger.error(errorMessage, t); } } static void loggerInfo(@NotNull final String message) { if (logger.isInfoEnabled()) { logger.info(message); } } static void loggerDebug(@NotNull final String message) { loggerDebug(message, null); } static void loggerDebug(@NotNull final String message, @Nullable final Throwable t) { if (logger.isDebugEnabled()) { if (t == null) { logger.debug(message); } else { logger.debug(message, t); } } } private void runAllTransactionSafeTasks() { if (throwableOnCommit == null) { synchronized (txnSafeTasks) { for (final RunnableWithTxnRoot r : txnSafeTasks) { r.runnable.run(); } } DeferredIO.getJobProcessor().waitForJobs(100); } } private void checkIfTransactionCreatedAgainstThis(@NotNull final Transaction txn) { if (txn.getEnvironment() != this) { throw new ExodusException("Transaction is created against another Environment"); } } private void checkInactive(boolean exceptionSafe) { int txnCount = txns.size(); if (!exceptionSafe && txnCount > 0) { SharedTimer.ensureIdle(); txnCount = txns.size(); } if (txnCount > 0) { final String errorString = "Environment[" + getLocation() + "] is active: " + txnCount + " transaction(s) not finished"; if (!exceptionSafe) { loggerError(errorString); } else { loggerInfo(errorString); } if (!exceptionSafe) { reportAliveTransactions(false); } else if (logger.isDebugEnabled()) { reportAliveTransactions(true); } } if (!exceptionSafe) { if (txnCount > 0) { throw new ExodusException("Finish all transactions before closing database environment"); } } } private void reportAliveTransactions(final boolean debug) { if (transactionTimeout() == 0) { String stacksUnavailable = "Transactions stack traces are not available, " + "set '" + EnvironmentConfig.ENV_MONITOR_TXNS_TIMEOUT + " > 0'"; if (debug) { loggerDebug(stacksUnavailable); } else { loggerError(stacksUnavailable); } } else { forEachActiveTransaction(txn -> { final StackTrace trace = ((TransactionBase) txn).getTrace(); if (debug) { loggerDebug("Alive transaction:\n" + trace); } else { loggerError("Alive transaction:\n" + trace); } }); } } private void checkIsOperative() { final Throwable t = throwableOnCommit; if (t != null) { if (t instanceof EnvironmentClosedException) { throw new ExodusException("Environment is inoperative", t); } throw ExodusException.toExodusException(t, "Environment is inoperative"); } } private int allocateStructureId() { /** * <TRICK> * Allocates structure id so that 256 doesn't factor it. This ensures that corresponding byte iterable * will never end with zero byte, and any such id can be used as a key in meta tree without collision * with a string key (store name). String keys (according to StringBinding) do always end with zero byte. * </TRICK> */ while (true) { final int result = structureId.incrementAndGet(); if ((result & 0xff) != 0) { return result; } } } private void invalidateStoreGetCache() { final int storeGetCacheSize = ec.getEnvStoreGetCacheSize(); storeGetCache = storeGetCacheSize == 0 ? null : new StoreGetCache(storeGetCacheSize, ec.getEnvStoreGetCacheMinTreeSize(), ec.getEnvStoreGetCacheMaxValueSize()); } private void updateTxnProfiler(TransactionBase txn, long initialHighAddress, long resultingHighAddress) { if (txnProfiler != null) { final long writtenBytes = resultingHighAddress - initialHighAddress; if (txn.isGCTransaction()) { txnProfiler.incGcTransaction(); txnProfiler.addGcMovedBytes(writtenBytes); } else if (txn.isReadonly()) { txnProfiler.addReadonlyTxn(txn); } else { txnProfiler.addTxn(txn, writtenBytes); } } } private static void applyEnvironmentSettings(@NotNull final String location, @NotNull final EnvironmentConfig ec) { final File propsFile = new File(location, ENVIRONMENT_PROPERTIES_FILE); if (propsFile.exists() && propsFile.isFile()) { try { try (InputStream propsStream = new FileInputStream(propsFile)) { final Properties envProps = new Properties(); envProps.load(propsStream); for (final Map.Entry<Object, Object> entry : envProps.entrySet()) { ec.setSetting(entry.getKey().toString(), entry.getValue()); } } } catch (IOException e) { throw ExodusException.toExodusException(e); } } } private static void checkStorageType(@NotNull final String location, @NotNull final EnvironmentConfig ec) { if (ec.getLogDataReaderWriterProvider().equals(DataReaderWriterProvider.DEFAULT_READER_WRITER_PROVIDER)) { final File databaseDir = new File(location); if (!ec.isLogAllowRemovable() && IOUtil.isRemovableFile(databaseDir)) { throw new StorageTypeNotAllowedException("Database on removable storage is not allowed"); } if (!ec.isLogAllowRemote() && IOUtil.isRemoteFile(databaseDir)) { throw new StorageTypeNotAllowedException("Database on remote storage is not allowed"); } if (!ec.isLogAllowRamDisk() && IOUtil.isRamDiskFile(databaseDir)) { throw new StorageTypeNotAllowedException("Database on RAM disk is not allowed"); } } } @Nullable private static jetbrains.exodus.env.management.EnvironmentConfig createConfigMBean(@NotNull final EnvironmentImpl e) { try { return e.ec.getManagementOperationsRestricted() ? new jetbrains.exodus.env.management.EnvironmentConfig(e) : new EnvironmentConfigWithOperations(e); } catch (RuntimeException ex) { if (ex.getCause() instanceof InstanceAlreadyExistsException) { return null; } throw ex; } } private static void executeInTransaction(@NotNull final TransactionalExecutable executable, @NotNull final Transaction txn) { try { while (true) { executable.execute(txn); if (txn.isReadonly() || // txn can be read-only if Environment is in read-only mode txn.isFinished() || // txn can be finished if, e.g., it was aborted within executable txn.flush()) { break; } txn.revert(); } } finally { abortIfNotFinished(txn); } } private static <T> T computeInTransaction(@NotNull final TransactionalComputable<T> computable, @NotNull final Transaction txn) { try { while (true) { final T result = computable.compute(txn); if (txn.isReadonly() || // txn can be read-only if Environment is in read-only mode txn.isFinished() || // txn can be finished if, e.g., it was aborted within computable txn.flush()) { return result; } txn.revert(); } } finally { abortIfNotFinished(txn); } } private static void abortIfNotFinished(@NotNull final Transaction txn) { if (!txn.isFinished()) { txn.abort(); } } private class EnvironmentSettingsListener implements ConfigSettingChangeListener { @Override public void beforeSettingChanged(@NotNull String key, @NotNull Object value, @NotNull Map<String, Object> context) { if (key.equals(EnvironmentConfig.ENV_IS_READONLY)) { if (log.getConfig().isReadonlyReaderWriterProvider()) { throw new InvalidSettingException("Can't modify read-only state in run time since DataReaderWriterProvider is read-only"); } if (Boolean.TRUE.equals(value)) { suspendGC(); final TransactionBase txn = beginTransaction(); try { if (!txn.isReadonly()) { gc.getUtilizationProfile().forceSave(txn); txn.setCommitHook(() -> { EnvironmentConfig.suppressConfigChangeListenersForThread(); ec.setEnvIsReadonly(true); EnvironmentConfig.resumeConfigChangeListenersForThread(); }); ((ReadWriteTransaction) txn).forceFlush(); } } finally { txn.abort(); } } } } @Override public void afterSettingChanged(@NotNull String key, @NotNull Object value, @NotNull Map<String, Object> context) { if (key.equals(EnvironmentConfig.ENV_STOREGET_CACHE_SIZE) || key.equals(EnvironmentConfig.ENV_STOREGET_CACHE_MIN_TREE_SIZE) || key.equals(EnvironmentConfig.ENV_STOREGET_CACHE_MAX_VALUE_SIZE)) { invalidateStoreGetCache(); } else if (key.equals(EnvironmentConfig.LOG_SYNC_PERIOD)) { log.getConfig().setSyncPeriod(ec.getLogSyncPeriod()); } else if (key.equals(EnvironmentConfig.LOG_DURABLE_WRITE)) { log.getConfig().setDurableWrite(ec.getLogDurableWrite()); } else if (key.equals(EnvironmentConfig.ENV_IS_READONLY) && !ec.getEnvIsReadonly()) { resumeGC(); } else if (key.equals(EnvironmentConfig.GC_UTILIZATION_FROM_SCRATCH) && ec.getGcUtilizationFromScratch()) { gc.getUtilizationProfile().computeUtilizationFromScratch(); } else if (key.equals(EnvironmentConfig.GC_UTILIZATION_FROM_FILE)) { gc.getUtilizationProfile().loadUtilizationFromFile((String) value); } else if (key.equals(EnvironmentConfig.TREE_MAX_PAGE_SIZE)) { balancePolicy = null; } else if (key.equals(EnvironmentConfig.TREE_DUP_MAX_PAGE_SIZE)) { balancePolicy = null; } else if (key.equals(EnvironmentConfig.LOG_CACHE_READ_AHEAD_MULTIPLE)) { log.getConfig().setCacheReadAheadMultiple(ec.getLogCacheReadAheadMultiple()); } } } private static class RunnableWithTxnRoot { private final Runnable runnable; private final long txnRoot; private RunnableWithTxnRoot(Runnable runnable, long txnRoot) { this.runnable = runnable; this.txnRoot = txnRoot; } } }
environment/src/main/java/jetbrains/exodus/env/EnvironmentImpl.java
/** * Copyright 2010 - 2021 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 jetbrains.exodus.env; import jetbrains.exodus.ConfigSettingChangeListener; import jetbrains.exodus.ExodusException; import jetbrains.exodus.InvalidSettingException; import jetbrains.exodus.backup.BackupStrategy; import jetbrains.exodus.core.dataStructures.ObjectCacheBase; import jetbrains.exodus.core.dataStructures.Pair; import jetbrains.exodus.core.execution.SharedTimer; import jetbrains.exodus.crypto.StreamCipherProvider; import jetbrains.exodus.debug.StackTrace; import jetbrains.exodus.debug.TxnProfiler; import jetbrains.exodus.entitystore.MetaServer; import jetbrains.exodus.env.management.DatabaseProfiler; import jetbrains.exodus.env.management.EnvironmentConfigWithOperations; import jetbrains.exodus.gc.GarbageCollector; import jetbrains.exodus.gc.UtilizationProfile; import jetbrains.exodus.io.DataReaderWriterProvider; import jetbrains.exodus.io.RemoveBlockType; import jetbrains.exodus.io.StorageTypeNotAllowedException; import jetbrains.exodus.log.DataIterator; import jetbrains.exodus.log.Log; import jetbrains.exodus.log.LogConfig; import jetbrains.exodus.log.LogTip; import jetbrains.exodus.tree.ExpiredLoggableCollection; import jetbrains.exodus.tree.TreeMetaInfo; import jetbrains.exodus.tree.btree.BTree; import jetbrains.exodus.tree.btree.BTreeBalancePolicy; import jetbrains.exodus.util.DeferredIO; import jetbrains.exodus.util.IOUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.management.InstanceAlreadyExistsException; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.ReentrantReadWriteLock; import static jetbrains.exodus.env.EnvironmentStatistics.Type.*; public class EnvironmentImpl implements Environment { public static final int META_TREE_ID = 1; private static final Logger logger = LoggerFactory.getLogger(EnvironmentImpl.class); private static final String ENVIRONMENT_PROPERTIES_FILE = "exodus.properties"; @NotNull private final Log log; @NotNull private final EnvironmentConfig ec; private BTreeBalancePolicy balancePolicy; private MetaTreeImpl metaTree; private final AtomicInteger structureId; @NotNull private final TransactionSet txns; private final LinkedList<RunnableWithTxnRoot> txnSafeTasks; @Nullable private StoreGetCache storeGetCache; private final EnvironmentSettingsListener envSettingsListener; private final GarbageCollector gc; final Object commitLock = new Object(); private final ReentrantReadWriteLock.ReadLock metaReadLock; final ReentrantReadWriteLock.WriteLock metaWriteLock; private final ReentrantTransactionDispatcher txnDispatcher; @NotNull private final EnvironmentStatistics statistics; @Nullable private final TxnProfiler txnProfiler; @Nullable private final jetbrains.exodus.env.management.EnvironmentConfig configMBean; @Nullable private final jetbrains.exodus.env.management.EnvironmentStatistics statisticsMBean; @Nullable private final DatabaseProfiler profilerMBean; /** * Throwable caught during commit after which rollback of highAddress failed. * Generally, it should ne null, otherwise environment is inoperative: * no transaction can be started or committed in that state. Once environment became inoperative, * it will remain inoperative forever. */ volatile Throwable throwableOnCommit; private Throwable throwableOnClose; @Nullable private final StuckTransactionMonitor stuckTxnMonitor; @Nullable private final StreamCipherProvider streamCipherProvider; @Nullable private final byte[] cipherKey; private final long cipherBasicIV; @SuppressWarnings({"ThisEscapedInObjectConstruction"}) EnvironmentImpl(@NotNull final Log log, @NotNull final EnvironmentConfig ec) { this.log = log; this.ec = ec; final String logLocation = log.getLocation(); applyEnvironmentSettings(logLocation, ec); checkStorageType(logLocation, ec); final DataReaderWriterProvider readerWriterProvider = log.getConfig().getReaderWriterProvider(); readerWriterProvider.onEnvironmentCreated(this); final Pair<MetaTreeImpl, Integer> meta; synchronized (commitLock) { meta = MetaTreeImpl.create(this); } metaTree = meta.getFirst(); structureId = new AtomicInteger(meta.getSecond()); txns = new TransactionSet(); txnSafeTasks = new LinkedList<>(); invalidateStoreGetCache(); envSettingsListener = new EnvironmentSettingsListener(); ec.addChangedSettingsListener(envSettingsListener); gc = new GarbageCollector(this); ReentrantReadWriteLock metaLock = new ReentrantReadWriteLock(); metaReadLock = metaLock.readLock(); metaWriteLock = metaLock.writeLock(); txnDispatcher = new ReentrantTransactionDispatcher(ec.getEnvMaxParallelTxns()); statistics = new EnvironmentStatistics(this); txnProfiler = ec.getProfilerEnabled() ? new TxnProfiler() : null; final jetbrains.exodus.env.management.EnvironmentConfig configMBean = ec.isManagementEnabled() ? createConfigMBean(this) : null; if (configMBean != null) { this.configMBean = configMBean; // if we don't gather statistics then we should not expose corresponding managed bean statisticsMBean = ec.getEnvGatherStatistics() ? new jetbrains.exodus.env.management.EnvironmentStatistics(this) : null; profilerMBean = txnProfiler == null ? null : new DatabaseProfiler(this); } else { this.configMBean = null; statisticsMBean = null; profilerMBean = null; } throwableOnCommit = null; throwableOnClose = null; stuckTxnMonitor = (transactionTimeout() > 0 || transactionExpirationTimeout() > 0) ? new StuckTransactionMonitor(this) : null; final LogConfig logConfig = log.getConfig(); streamCipherProvider = logConfig.getCipherProvider(); cipherKey = logConfig.getCipherKey(); cipherBasicIV = logConfig.getCipherBasicIV(); loggerInfo("Exodus environment created: " + logLocation); } @Override public long getCreated() { return log.getCreated(); } @Override @NotNull public String getLocation() { return log.getLocation(); } @Override public @NotNull BitmapImpl openBitmap(@NotNull String name, @NotNull final StoreConfig config, @NotNull Transaction transaction) { if (config == StoreConfig.WITH_DUPLICATES || config == StoreConfig.WITH_DUPLICATES_WITH_PREFIXING) { throw new ExodusException("Bitmap can't be opened on the store with duplicates"); } final StoreImpl store = openStore(name.concat("#bitmap"), config, transaction); return new BitmapImpl(store); } @Override @NotNull public EnvironmentConfig getEnvironmentConfig() { return ec; } @Override @NotNull public EnvironmentStatistics getStatistics() { return statistics; } public GarbageCollector getGC() { return gc; } @Nullable public TxnProfiler getTxnProfiler() { return txnProfiler; } @Override @NotNull public StoreImpl openStore(@NotNull final String name, @NotNull final StoreConfig config, @NotNull final Transaction transaction) { final TransactionBase txn = (TransactionBase) transaction; return openStoreImpl(name, config, txn, txn.getTreeMetaInfo(name)); } @Override @Nullable public StoreImpl openStore(@NotNull final String name, @NotNull final StoreConfig config, @NotNull final Transaction transaction, final boolean creationRequired) { final TransactionBase txn = (TransactionBase) transaction; final TreeMetaInfo metaInfo = txn.getTreeMetaInfo(name); if (metaInfo == null && !creationRequired) { return null; } return openStoreImpl(name, config, txn, metaInfo); } @Override @NotNull public TransactionBase beginTransaction() { return beginTransaction(null, false, false); } @Override @NotNull public TransactionBase beginTransaction(final Runnable beginHook) { return beginTransaction(beginHook, false, false); } @NotNull @Override public Transaction beginExclusiveTransaction() { return beginTransaction(null, true, false); } @NotNull @Override public Transaction beginExclusiveTransaction(Runnable beginHook) { return beginTransaction(beginHook, true, false); } @NotNull @Override public Transaction beginReadonlyTransaction() { return beginReadonlyTransaction(null); } @NotNull @Override public TransactionBase beginReadonlyTransaction(final Runnable beginHook) { checkIsOperative(); return new ReadonlyTransaction(this, false, beginHook); } @NotNull public ReadWriteTransaction beginGCTransaction() { if (ec.getEnvIsReadonly()) { throw new ReadonlyTransactionException("Can't start GC transaction on read-only Environment"); } return new ReadWriteTransaction(this, null, ec.getGcUseExclusiveTransaction(), true) { @Override boolean isGCTransaction() { return true; } }; } public ReadonlyTransaction beginTransactionAt(final long highAddress) { checkIsOperative(); return new ReadonlyTransaction(this, highAddress); } @Override public void executeInTransaction(@NotNull final TransactionalExecutable executable) { executeInTransaction(executable, beginTransaction()); } @Override public void executeInExclusiveTransaction(@NotNull final TransactionalExecutable executable) { executeInTransaction(executable, beginExclusiveTransaction()); } @Override public void executeInReadonlyTransaction(@NotNull TransactionalExecutable executable) { final Transaction txn = beginReadonlyTransaction(); try { executable.execute(txn); } finally { abortIfNotFinished(txn); } } @Override public <T> T computeInTransaction(@NotNull TransactionalComputable<T> computable) { return computeInTransaction(computable, beginTransaction()); } @Override public <T> T computeInExclusiveTransaction(@NotNull TransactionalComputable<T> computable) { return computeInTransaction(computable, beginExclusiveTransaction()); } @Override public <T> T computeInReadonlyTransaction(@NotNull TransactionalComputable<T> computable) { final Transaction txn = beginReadonlyTransaction(); try { return computable.compute(txn); } finally { abortIfNotFinished(txn); } } @Override public void executeTransactionSafeTask(@NotNull final Runnable task) { final long newestTxnRoot = txns.getNewestTxnRootAddress(); if (newestTxnRoot == Long.MIN_VALUE) { task.run(); } else { synchronized (txnSafeTasks) { txnSafeTasks.addLast(new RunnableWithTxnRoot(task, newestTxnRoot)); } } } public int getStuckTransactionCount() { return stuckTxnMonitor == null ? 0 : stuckTxnMonitor.getStuckTxnCount(); } @Override @Nullable public StreamCipherProvider getCipherProvider() { return streamCipherProvider; } @Override @Nullable public byte[] getCipherKey() { return cipherKey; } @Override public long getCipherBasicIV() { return cipherBasicIV; } @Override public void clear() { final Thread currentThread = Thread.currentThread(); if (txnDispatcher.getThreadPermits(currentThread) != 0) { throw new ExodusException("Environment.clear() can't proceed if there is a transaction in current thread"); } runAllTransactionSafeTasks(); synchronized (txnSafeTasks) { txnSafeTasks.clear(); } suspendGC(); try { final int permits = txnDispatcher.acquireExclusiveTransaction(currentThread);// wait for and stop all writing transactions try { synchronized (commitLock) { metaWriteLock.lock(); try { gc.clear(); log.clear(); invalidateStoreGetCache(); throwableOnCommit = null; final Pair<MetaTreeImpl, Integer> meta = MetaTreeImpl.create(this); metaTree = meta.getFirst(); structureId.set(meta.getSecond()); } finally { metaWriteLock.unlock(); } } } finally { txnDispatcher.releaseTransaction(currentThread, permits); } } finally { resumeGC(); } } @Override public void close() { // if this is already closed do nothing synchronized (commitLock) { if (!isOpen()) { return; } } final MetaServer metaServer = getEnvironmentConfig().getMetaServer(); if (metaServer != null) { metaServer.stop(this); } if (configMBean != null) { configMBean.unregister(); } if (statisticsMBean != null) { statisticsMBean.unregister(); } if (profilerMBean != null) { profilerMBean.unregister(); } runAllTransactionSafeTasks(); // in order to avoid deadlock, do not finish gc inside lock // it is safe to invoke gc.finish() several times gc.finish(); final float logCacheHitRate; final float storeGetCacheHitRate; synchronized (commitLock) { // concurrent close() detected if (throwableOnClose != null) { throw new EnvironmentClosedException(throwableOnClose); // add combined stack trace information } final boolean closeForcedly = ec.getEnvCloseForcedly(); checkInactive(closeForcedly); try { if (!closeForcedly && !ec.getEnvIsReadonly() && ec.isGcEnabled()) { executeInTransaction(txn -> gc.getUtilizationProfile().forceSave(txn)); } ec.removeChangedSettingsListener(envSettingsListener); logCacheHitRate = log.getCacheHitRate(); log.close(); } finally { log.release(); } if (storeGetCache == null) { storeGetCacheHitRate = 0; } else { storeGetCacheHitRate = storeGetCache.hitRate(); storeGetCache.close(); } if (txnProfiler != null) { txnProfiler.dump(); } throwableOnClose = new EnvironmentClosedException(); throwableOnCommit = throwableOnClose; } loggerDebug("Store get cache hit rate: " + ObjectCacheBase.formatHitRate(storeGetCacheHitRate)); loggerDebug("Exodus log cache hit rate: " + ObjectCacheBase.formatHitRate(logCacheHitRate)); } @Override public boolean isOpen() { return throwableOnClose == null; } @NotNull @Override public BackupStrategy getBackupStrategy() { return new EnvironmentBackupStrategyImpl(this); } @Override public void truncateStore(@NotNull final String storeName, @NotNull final Transaction txn) { final ReadWriteTransaction t = throwIfReadonly(txn, "Can't truncate a store in read-only transaction"); StoreImpl store = openStore(storeName, StoreConfig.USE_EXISTING, t, false); if (store == null) { throw new ExodusException("Attempt to truncate unknown store '" + storeName + '\''); } t.storeRemoved(store); final TreeMetaInfo metaInfoCloned = store.getMetaInfo().clone(allocateStructureId()); store = new StoreImpl(this, storeName, metaInfoCloned); t.storeCreated(store); } @Override public void removeStore(@NotNull final String storeName, @NotNull final Transaction txn) { final ReadWriteTransaction t = throwIfReadonly(txn, "Can't remove a store in read-only transaction"); final StoreImpl store = openStore(storeName, StoreConfig.USE_EXISTING, t, false); if (store == null) { throw new ExodusException("Attempt to remove unknown store '" + storeName + '\''); } t.storeRemoved(store); } public long getAllStoreCount() { metaReadLock.lock(); try { return metaTree.getAllStoreCount(); } finally { metaReadLock.unlock(); } } @Override @NotNull public List<String> getAllStoreNames(@NotNull final Transaction txn) { checkIfTransactionCreatedAgainstThis(txn); return ((TransactionBase) txn).getAllStoreNames(); } public boolean storeExists(@NotNull final String storeName, @NotNull final Transaction txn) { return ((TransactionBase) txn).getTreeMetaInfo(storeName) != null; } @NotNull public Log getLog() { return log; } @Override public void gc() { gc.wake(true); } @Override public void suspendGC() { gc.suspend(); } @Override public void resumeGC() { gc.resume(); } @Override public void executeBeforeGc(Runnable action) { gc.addBeforeGcAction(action); } public BTreeBalancePolicy getBTreeBalancePolicy() { // we don't care of possible race condition here if (balancePolicy == null) { balancePolicy = new BTreeBalancePolicy(ec.getTreeMaxPageSize(), ec.getTreeDupMaxPageSize()); } return balancePolicy; } /** * Flushes Log's data writer exclusively in commit lock. This guarantees that the data writer is in committed state. * Also performs syncing cached by OS data to storage device. */ public void flushAndSync() { synchronized (commitLock) { if (isOpen()) { getLog().sync(); } } } public void removeFiles(final long[] files, @NotNull final RemoveBlockType rbt) { synchronized (commitLock) { log.beginWrite(); try { log.forgetFiles(files); log.endWrite(); } catch (Throwable t) { log.abortWrite(); throw ExodusException.toExodusException(t, "Failed to forget files in log"); } } for (long file : files) { log.removeFile(file, rbt); } } public float getStoreGetCacheHitRate() { return storeGetCache == null ? 0 : storeGetCache.hitRate(); } protected StoreImpl createStore(@NotNull final String name, @NotNull final TreeMetaInfo metaInfo) { return new StoreImpl(this, name, metaInfo); } protected void finishTransaction(@NotNull final TransactionBase txn) { if (!txn.isReadonly()) { releaseTransaction(txn); } txns.remove(txn); txn.setIsFinished(); final long duration = System.currentTimeMillis() - txn.getCreated(); if (txn.isReadonly()) { statistics.getStatisticsItem(READONLY_TRANSACTIONS).incTotal(); statistics.getStatisticsItem(READONLY_TRANSACTIONS_DURATION).addTotal(duration); } else if (txn.isGCTransaction()) { statistics.getStatisticsItem(GC_TRANSACTIONS).incTotal(); statistics.getStatisticsItem(GC_TRANSACTIONS_DURATION).addTotal(duration); } else { statistics.getStatisticsItem(TRANSACTIONS).incTotal(); statistics.getStatisticsItem(TRANSACTIONS_DURATION).addTotal(duration); } runTransactionSafeTasks(); } @NotNull protected TransactionBase beginTransaction(Runnable beginHook, boolean exclusive, boolean cloneMeta) { checkIsOperative(); return ec.getEnvIsReadonly() && ec.getEnvFailFastInReadonly() ? new ReadonlyTransaction(this, exclusive, beginHook) : new ReadWriteTransaction(this, beginHook, exclusive, cloneMeta); } @Nullable StoreGetCache getStoreGetCache() { return storeGetCache; } long getDiskUsage() { return log.getDiskUsage(); } void acquireTransaction(@NotNull final TransactionBase txn) { checkIfTransactionCreatedAgainstThis(txn); txnDispatcher.acquireTransaction(throwIfReadonly( txn, "TxnDispatcher can't acquire permits for read-only transaction"), this); } void releaseTransaction(@NotNull final TransactionBase txn) { checkIfTransactionCreatedAgainstThis(txn); txnDispatcher.releaseTransaction(throwIfReadonly( txn, "TxnDispatcher can't release permits for read-only transaction")); } void downgradeTransaction(@NotNull final TransactionBase txn) { txnDispatcher.downgradeTransaction(throwIfReadonly( txn, "TxnDispatcher can't downgrade read-only transaction")); } boolean shouldTransactionBeExclusive(@NotNull final ReadWriteTransaction txn) { final int replayCount = txn.getReplayCount(); return replayCount >= ec.getEnvTxnReplayMaxCount() || System.currentTimeMillis() - txn.getCreated() >= ec.getEnvTxnReplayTimeout(); } /** * @return timeout for a transaction in milliseconds, or 0 if no timeout is configured */ int transactionTimeout() { return ec.getEnvMonitorTxnsTimeout(); } /** * @return expiration timeout for a transaction in milliseconds, or 0 if no timeout is configured */ int transactionExpirationTimeout() { return ec.getEnvMonitorTxnsExpirationTimeout(); } /** * Tries to load meta tree located at specified rootAddress. * * @param rootAddress tree root address. * @return tree instance or null if the address is not valid. */ @Nullable BTree loadMetaTree(final long rootAddress, final LogTip logTip) { if (rootAddress < 0 || rootAddress >= logTip.highAddress) return null; return new BTree(log, getBTreeBalancePolicy(), rootAddress, false, META_TREE_ID) { @NotNull @Override public DataIterator getDataIterator(long address) { return new DataIterator(log, address); } }; } boolean commitTransaction(@NotNull final ReadWriteTransaction txn) { if (flushTransaction(txn, false)) { finishTransaction(txn); return true; } return false; } boolean flushTransaction(@NotNull final ReadWriteTransaction txn, final boolean forceCommit) { checkIfTransactionCreatedAgainstThis(txn); if (!forceCommit && txn.isIdempotent()) { return true; } final ExpiredLoggableCollection expiredLoggables; final long initialHighAddress; final long resultingHighAddress; final boolean isGcTransaction = txn.isGCTransaction(); boolean wasUpSaved = false; final UtilizationProfile up = gc.getUtilizationProfile(); if (!isGcTransaction && up.isDirty()) { up.save(txn); wasUpSaved = true; } synchronized (commitLock) { if (ec.getEnvIsReadonly()) { throw new ReadonlyTransactionException(); } checkIsOperative(); if (!txn.checkVersion(metaTree.root)) { // meta lock not needed 'cause write can only occur in another commit lock return false; } if (wasUpSaved) { up.setDirty(false); } final LogTip logTip = log.beginWrite(); initialHighAddress = logTip.highAddress; boolean writeConfirmed = false; try { final MetaTreeImpl.Proto[] tree = new MetaTreeImpl.Proto[1]; expiredLoggables = txn.doCommit(tree); // there is a temptation to postpone I/O in order to reduce number of writes to storage device, // but it's quite difficult to resolve all possible inconsistencies afterwards, // so think twice before removing the following line log.flush(); final MetaTreeImpl.Proto proto = tree[0]; metaWriteLock.lock(); try { final LogTip updatedTip = log.endWrite(); writeConfirmed = true; resultingHighAddress = updatedTip.approvedHighAddress; txn.setMetaTree(metaTree = MetaTreeImpl.create(this, updatedTip, proto)); txn.executeCommitHook(); } finally { metaWriteLock.unlock(); } // update txn profiler within commitLock updateTxnProfiler(txn, initialHighAddress, resultingHighAddress); } catch (Throwable t) { // pokemon exception handling to decrease try/catch block overhead loggerError("Failed to flush transaction", t); if (writeConfirmed) { throwableOnCommit = t; // inoperative on failing to read meta tree throw ExodusException.toExodusException(t, "Failed to read meta tree"); } try { log.revertWrite(logTip); } catch (Throwable th) { throwableOnCommit = t; // inoperative on failing to update high address loggerError("Failed to rollback high address", th); throw ExodusException.toExodusException(th, "Failed to rollback high address"); } throw ExodusException.toExodusException(t, "Failed to flush transaction"); } } gc.fetchExpiredLoggables(expiredLoggables); // update statistics statistics.getStatisticsItem(BYTES_WRITTEN).setTotal(resultingHighAddress); if (isGcTransaction) { statistics.getStatisticsItem(BYTES_MOVED_BY_GC).addTotal(resultingHighAddress - initialHighAddress); } statistics.getStatisticsItem(FLUSHED_TRANSACTIONS).incTotal(); return true; } MetaTreeImpl holdNewestSnapshotBy(@NotNull final TransactionBase txn) { return holdNewestSnapshotBy(txn, true); } MetaTreeImpl holdNewestSnapshotBy(@NotNull final TransactionBase txn, final boolean acquireTxn) { if (acquireTxn) { acquireTransaction(txn); } final Runnable beginHook = txn.getBeginHook(); metaReadLock.lock(); try { if (beginHook != null) { beginHook.run(); } return metaTree; } finally { metaReadLock.unlock(); } } public MetaTree getMetaTree() { metaReadLock.lock(); try { return metaTree; } finally { metaReadLock.unlock(); } } MetaTreeImpl getMetaTreeInternal() { return metaTree; } // unsafe void setMetaTreeInternal(MetaTreeImpl metaTree) { this.metaTree = metaTree; } /** * Opens or creates store just like openStore() with the same parameters does, but gets parameters * that are not annotated. This allows to pass, e.g., nullable transaction. * * @param name store name * @param config store configuration * @param txn transaction, should not null if store doesn't exists * @param metaInfo target meta information * @return store object */ @SuppressWarnings({"AssignmentToMethodParameter"}) @NotNull StoreImpl openStoreImpl(@NotNull final String name, @NotNull StoreConfig config, @NotNull final TransactionBase txn, @Nullable TreeMetaInfo metaInfo) { checkIfTransactionCreatedAgainstThis(txn); if (config.useExisting) { // this parameter requires to recalculate if (metaInfo == null) { throw new ExodusException("Can't restore meta information for store " + name); } else { config = TreeMetaInfo.toConfig(metaInfo); } } final StoreImpl result; if (metaInfo == null) { if (txn.isReadonly() && ec.getEnvReadonlyEmptyStores()) { return createTemporaryEmptyStore(name); } final int structureId = allocateStructureId(); metaInfo = TreeMetaInfo.load(this, config.duplicates, config.prefixing, structureId); result = createStore(name, metaInfo); final ReadWriteTransaction tx = throwIfReadonly(txn, "Can't create a store in read-only transaction"); tx.getMutableTree(result); tx.storeCreated(result); } else { final boolean hasDuplicates = metaInfo.hasDuplicates(); if (hasDuplicates != config.duplicates) { throw new ExodusException("Attempt to open store '" + name + "' with duplicates = " + config.duplicates + " while it was created with duplicates =" + hasDuplicates); } if (metaInfo.isKeyPrefixing() != config.prefixing) { if (!config.prefixing) { throw new ExodusException("Attempt to open store '" + name + "' with prefixing = false while it was created with prefixing = true"); } // if we're trying to open existing store with prefixing which actually wasn't created as store // with prefixing due to lack of the PatriciaTree feature, then open store with existing config metaInfo = TreeMetaInfo.load(this, hasDuplicates, false, metaInfo.getStructureId()); } result = createStore(name, metaInfo); // XD-774: if the store was just removed in the same txn forget the removal if (txn instanceof ReadWriteTransaction) { ((ReadWriteTransaction) txn).storeOpened(result); } } return result; } int getLastStructureId() { return structureId.get(); } void registerTransaction(@NotNull final TransactionBase txn) { checkIfTransactionCreatedAgainstThis(txn); // N.B! due to TransactionImpl.revert(), there can appear a txn which is already in the transaction set // any implementation of transaction set should process this well txns.add(txn); } boolean isRegistered(@NotNull final ReadWriteTransaction txn) { checkIfTransactionCreatedAgainstThis(txn); return txns.contains(txn); } int activeTransactions() { return txns.size(); } void runTransactionSafeTasks() { if (throwableOnCommit == null) { List<Runnable> tasksToRun = null; final long oldestTxnRoot = txns.getOldestTxnRootAddress(); synchronized (txnSafeTasks) { while (true) { if (!txnSafeTasks.isEmpty()) { final RunnableWithTxnRoot r = txnSafeTasks.getFirst(); if (r.txnRoot < oldestTxnRoot) { txnSafeTasks.removeFirst(); if (tasksToRun == null) { tasksToRun = new ArrayList<>(4); } tasksToRun.add(r.runnable); continue; } } break; } } if (tasksToRun != null) { for (final Runnable task : tasksToRun) { task.run(); } } } } void forEachActiveTransaction(@NotNull final TransactionalExecutable executable) { txns.forEach(executable); } void setHighAddress(final long highAddress) { synchronized (commitLock) { log.setHighAddress(log.getTip(), highAddress); final Pair<MetaTreeImpl, Integer> meta = MetaTreeImpl.create(this); metaWriteLock.lock(); try { metaTree = meta.getFirst(); } finally { metaWriteLock.unlock(); } } } // for tests only boolean awaitUpdate(final long fromAddress, long timeout) { final int delta = 20; try { while (timeout > 0) { if (log.getHighAddress() > fromAddress) { return true; } Thread.sleep(delta); timeout -= delta; } } catch (InterruptedException ignore) { Thread.currentThread().interrupt(); } return false; } protected StoreImpl createTemporaryEmptyStore(String name) { return new TemporaryEmptyStore(this, name); } static boolean isUtilizationProfile(@NotNull final String storeName) { return GarbageCollector.isUtilizationProfile(storeName); } static ReadWriteTransaction throwIfReadonly(@NotNull final Transaction txn, @NotNull final String exceptionMessage) { if (txn.isReadonly()) { throw new ReadonlyTransactionException(exceptionMessage); } return (ReadWriteTransaction) txn; } static void loggerError(@NotNull final String errorMessage) { loggerError(errorMessage, null); } static void loggerError(@NotNull final String errorMessage, @Nullable final Throwable t) { if (t == null) { logger.error(errorMessage); } else { logger.error(errorMessage, t); } } static void loggerInfo(@NotNull final String message) { if (logger.isInfoEnabled()) { logger.info(message); } } static void loggerDebug(@NotNull final String message) { loggerDebug(message, null); } static void loggerDebug(@NotNull final String message, @Nullable final Throwable t) { if (logger.isDebugEnabled()) { if (t == null) { logger.debug(message); } else { logger.debug(message, t); } } } private void runAllTransactionSafeTasks() { if (throwableOnCommit == null) { synchronized (txnSafeTasks) { for (final RunnableWithTxnRoot r : txnSafeTasks) { r.runnable.run(); } } DeferredIO.getJobProcessor().waitForJobs(100); } } private void checkIfTransactionCreatedAgainstThis(@NotNull final Transaction txn) { if (txn.getEnvironment() != this) { throw new ExodusException("Transaction is created against another Environment"); } } private void checkInactive(boolean exceptionSafe) { int txnCount = txns.size(); if (!exceptionSafe && txnCount > 0) { SharedTimer.ensureIdle(); txnCount = txns.size(); } if (txnCount > 0) { final String errorString = "Environment[" + getLocation() + "] is active: " + txnCount + " transaction(s) not finished"; if (!exceptionSafe) { loggerError(errorString); } else { loggerInfo(errorString); } if (!exceptionSafe) { reportAliveTransactions(false); } else if (logger.isDebugEnabled()) { reportAliveTransactions(true); } } if (!exceptionSafe) { if (txnCount > 0) { throw new ExodusException("Finish all transactions before closing database environment"); } } } private void reportAliveTransactions(final boolean debug) { if (transactionTimeout() == 0) { String stacksUnavailable = "Transactions stack traces are not available, " + "set '" + EnvironmentConfig.ENV_MONITOR_TXNS_TIMEOUT + " > 0'"; if (debug) { loggerDebug(stacksUnavailable); } else { loggerError(stacksUnavailable); } } else { forEachActiveTransaction(txn -> { final StackTrace trace = ((TransactionBase) txn).getTrace(); if (debug) { loggerDebug("Alive transaction:\n" + trace); } else { loggerError("Alive transaction:\n" + trace); } }); } } private void checkIsOperative() { final Throwable t = throwableOnCommit; if (t != null) { if (t instanceof EnvironmentClosedException) { throw new ExodusException("Environment is inoperative", t); } throw ExodusException.toExodusException(t, "Environment is inoperative"); } } private int allocateStructureId() { /** * <TRICK> * Allocates structure id so that 256 doesn't factor it. This ensures that corresponding byte iterable * will never end with zero byte, and any such id can be used as a key in meta tree without collision * with a string key (store name). String keys (according to StringBinding) do always end with zero byte. * </TRICK> */ while (true) { final int result = structureId.incrementAndGet(); if ((result & 0xff) != 0) { return result; } } } private void invalidateStoreGetCache() { final int storeGetCacheSize = ec.getEnvStoreGetCacheSize(); storeGetCache = storeGetCacheSize == 0 ? null : new StoreGetCache(storeGetCacheSize, ec.getEnvStoreGetCacheMinTreeSize(), ec.getEnvStoreGetCacheMaxValueSize()); } private void updateTxnProfiler(TransactionBase txn, long initialHighAddress, long resultingHighAddress) { if (txnProfiler != null) { final long writtenBytes = resultingHighAddress - initialHighAddress; if (txn.isGCTransaction()) { txnProfiler.incGcTransaction(); txnProfiler.addGcMovedBytes(writtenBytes); } else if (txn.isReadonly()) { txnProfiler.addReadonlyTxn(txn); } else { txnProfiler.addTxn(txn, writtenBytes); } } } private static void applyEnvironmentSettings(@NotNull final String location, @NotNull final EnvironmentConfig ec) { final File propsFile = new File(location, ENVIRONMENT_PROPERTIES_FILE); if (propsFile.exists() && propsFile.isFile()) { try { try (InputStream propsStream = new FileInputStream(propsFile)) { final Properties envProps = new Properties(); envProps.load(propsStream); for (final Map.Entry<Object, Object> entry : envProps.entrySet()) { ec.setSetting(entry.getKey().toString(), entry.getValue()); } } } catch (IOException e) { throw ExodusException.toExodusException(e); } } } private static void checkStorageType(@NotNull final String location, @NotNull final EnvironmentConfig ec) { if (ec.getLogDataReaderWriterProvider().equals(DataReaderWriterProvider.DEFAULT_READER_WRITER_PROVIDER)) { final File databaseDir = new File(location); if (!ec.isLogAllowRemovable() && IOUtil.isRemovableFile(databaseDir)) { throw new StorageTypeNotAllowedException("Database on removable storage is not allowed"); } if (!ec.isLogAllowRemote() && IOUtil.isRemoteFile(databaseDir)) { throw new StorageTypeNotAllowedException("Database on remote storage is not allowed"); } if (!ec.isLogAllowRamDisk() && IOUtil.isRamDiskFile(databaseDir)) { throw new StorageTypeNotAllowedException("Database on RAM disk is not allowed"); } } } @Nullable private static jetbrains.exodus.env.management.EnvironmentConfig createConfigMBean(@NotNull final EnvironmentImpl e) { try { return e.ec.getManagementOperationsRestricted() ? new jetbrains.exodus.env.management.EnvironmentConfig(e) : new EnvironmentConfigWithOperations(e); } catch (RuntimeException ex) { if (ex.getCause() instanceof InstanceAlreadyExistsException) { return null; } throw ex; } } private static void executeInTransaction(@NotNull final TransactionalExecutable executable, @NotNull final Transaction txn) { try { while (true) { executable.execute(txn); if (txn.isReadonly() || // txn can be read-only if Environment is in read-only mode txn.isFinished() || // txn can be finished if, e.g., it was aborted within executable txn.flush()) { break; } txn.revert(); } } finally { abortIfNotFinished(txn); } } private static <T> T computeInTransaction(@NotNull final TransactionalComputable<T> computable, @NotNull final Transaction txn) { try { while (true) { final T result = computable.compute(txn); if (txn.isReadonly() || // txn can be read-only if Environment is in read-only mode txn.isFinished() || // txn can be finished if, e.g., it was aborted within computable txn.flush()) { return result; } txn.revert(); } } finally { abortIfNotFinished(txn); } } private static void abortIfNotFinished(@NotNull final Transaction txn) { if (!txn.isFinished()) { txn.abort(); } } private class EnvironmentSettingsListener implements ConfigSettingChangeListener { @Override public void beforeSettingChanged(@NotNull String key, @NotNull Object value, @NotNull Map<String, Object> context) { if (key.equals(EnvironmentConfig.ENV_IS_READONLY)) { if (log.getConfig().isReadonlyReaderWriterProvider()) { throw new InvalidSettingException("Can't modify read-only state in run time since DataReaderWriterProvider is read-only"); } if (Boolean.TRUE.equals(value)) { suspendGC(); final TransactionBase txn = beginTransaction(); try { if (!txn.isReadonly()) { gc.getUtilizationProfile().forceSave(txn); txn.setCommitHook(() -> { EnvironmentConfig.suppressConfigChangeListenersForThread(); ec.setEnvIsReadonly(true); EnvironmentConfig.resumeConfigChangeListenersForThread(); }); ((ReadWriteTransaction) txn).forceFlush(); } } finally { txn.abort(); } } } } @Override public void afterSettingChanged(@NotNull String key, @NotNull Object value, @NotNull Map<String, Object> context) { if (key.equals(EnvironmentConfig.ENV_STOREGET_CACHE_SIZE) || key.equals(EnvironmentConfig.ENV_STOREGET_CACHE_MIN_TREE_SIZE) || key.equals(EnvironmentConfig.ENV_STOREGET_CACHE_MAX_VALUE_SIZE)) { invalidateStoreGetCache(); } else if (key.equals(EnvironmentConfig.LOG_SYNC_PERIOD)) { log.getConfig().setSyncPeriod(ec.getLogSyncPeriod()); } else if (key.equals(EnvironmentConfig.LOG_DURABLE_WRITE)) { log.getConfig().setDurableWrite(ec.getLogDurableWrite()); } else if (key.equals(EnvironmentConfig.ENV_IS_READONLY) && !ec.getEnvIsReadonly()) { resumeGC(); } else if (key.equals(EnvironmentConfig.GC_UTILIZATION_FROM_SCRATCH) && ec.getGcUtilizationFromScratch()) { gc.getUtilizationProfile().computeUtilizationFromScratch(); } else if (key.equals(EnvironmentConfig.GC_UTILIZATION_FROM_FILE)) { gc.getUtilizationProfile().loadUtilizationFromFile((String) value); } else if (key.equals(EnvironmentConfig.TREE_MAX_PAGE_SIZE)) { balancePolicy = null; } else if (key.equals(EnvironmentConfig.TREE_DUP_MAX_PAGE_SIZE)) { balancePolicy = null; } else if (key.equals(EnvironmentConfig.LOG_CACHE_READ_AHEAD_MULTIPLE)) { log.getConfig().setCacheReadAheadMultiple(ec.getLogCacheReadAheadMultiple()); } } } private static class RunnableWithTxnRoot { private final Runnable runnable; private final long txnRoot; private RunnableWithTxnRoot(Runnable runnable, long txnRoot) { this.runnable = runnable; this.txnRoot = txnRoot; } } }
a piece of cake
environment/src/main/java/jetbrains/exodus/env/EnvironmentImpl.java
a piece of cake
Java
apache-2.0
7106c74ec208cf43f1416166ff04bd8d5b870730
0
trejkaz/derby,trejkaz/derby,apache/derby,apache/derby,apache/derby,apache/derby,trejkaz/derby
/* Derby - Class org.apache.derby.jdbc.EmbedPooledConnection Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.derby.jdbc; import org.apache.derby.iapi.services.sanity.SanityManager; import org.apache.derby.iapi.reference.Property; import org.apache.derby.iapi.error.ExceptionSeverity; import org.apache.derby.iapi.reference.JDBC30Translation; import org.apache.derby.iapi.sql.conn.LanguageConnectionContext; /* import impl class */ import org.apache.derby.impl.jdbc.Util; import org.apache.derby.impl.jdbc.EmbedConnection; import org.apache.derby.iapi.jdbc.BrokeredConnection; import org.apache.derby.iapi.jdbc.BrokeredConnectionControl; import org.apache.derby.iapi.jdbc.EngineConnection; import org.apache.derby.impl.jdbc.EmbedPreparedStatement; import org.apache.derby.impl.jdbc.EmbedCallableStatement; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.sql.PreparedStatement; import java.sql.CallableStatement; import java.util.Vector; import java.util.Enumeration; /* -- New jdbc 20 extension types --- */ import javax.sql.DataSource; import javax.sql.PooledConnection; import javax.sql.ConnectionEventListener; import javax.sql.ConnectionEvent; /** A PooledConnection object is a connection object that provides hooks for connection pool management. <P>This is Derby's implementation of a PooledConnection for use in the following environments: <UL> <LI> JDBC 3.0 - Java 2 - JDK 1.4, J2SE 5.0 <LI> JDBC 2.0 - Java 2 - JDK 1.2,1.3 </UL> */ class EmbedPooledConnection implements javax.sql.PooledConnection, BrokeredConnectionControl { /** Static counter for connection ids */ private static int idCounter = 0; /** The id for this connection. */ private int connectionId; /** the connection string */ private String connString; private Vector eventListener; // who wants to know I am closed or error EmbedConnection realConnection; int defaultIsolationLevel; private boolean defaultReadOnly; BrokeredConnection currentConnectionHandle; // set up once by the data source final ReferenceableDataSource dataSource; private final String username; private final String password; /** True if the password was passed in on the connection request, false if it came from the data source property. */ private final boolean requestPassword; protected boolean isActive; private synchronized int nextId() { return idCounter++; } EmbedPooledConnection(ReferenceableDataSource ds, String u, String p, boolean requestPassword) throws SQLException { connectionId = nextId(); dataSource = ds; username = u; password = p; this.requestPassword = requestPassword; isActive = true; // open the connection up front in order to do authentication openRealConnection(); } String getUsername() { if (username == null || username.equals("")) return Property.DEFAULT_USER_NAME; else return username; } String getPassword() { if (password == null) return ""; else return password; } /** Create an object handle for a database connection. @return a Connection object @exception SQLException - if a database-access error occurs. */ public synchronized Connection getConnection() throws SQLException { checkActive(); // need to do this in case the connection is forcibly removed without // first being closed. closeCurrentConnectionHandle(); // RealConnection is not null if the app server yanks a local // connection from one client and give it to another. In this case, // the real connection is ready to be used. Otherwise, set it up if (realConnection == null) { // first time we establish a connection openRealConnection(); } else { resetRealConnection(); } // now make a brokered connection wrapper and give this to the user // we reuse the EmbedConnection(ie realConnection). Connection c = getNewCurrentConnectionHandle(); return c; } final void openRealConnection() throws SQLException { // first time we establish a connection Connection rc = dataSource.getConnection(username, password, requestPassword); this.realConnection = (EmbedConnection) rc; defaultIsolationLevel = rc.getTransactionIsolation(); defaultReadOnly = rc.isReadOnly(); if (currentConnectionHandle != null) realConnection.setApplicationConnection(currentConnectionHandle); } final Connection getNewCurrentConnectionHandle() { Connection applicationConnection = currentConnectionHandle = ((org.apache.derby.jdbc.Driver20) (realConnection.getLocalDriver())).newBrokeredConnection(this); realConnection.setApplicationConnection(applicationConnection); return applicationConnection; } /** In this case the Listeners are *not* notified. JDBC 3.0 spec section 11.4 */ private void closeCurrentConnectionHandle() throws SQLException { if (currentConnectionHandle != null) { Vector tmpEventListener = eventListener; eventListener = null; try { currentConnectionHandle.close(); } finally { eventListener = tmpEventListener; } currentConnectionHandle = null; } } void resetRealConnection() throws SQLException { // ensure any outstanding changes from the previous // user are rolledback. realConnection.rollback(); // clear any warnings that are left over realConnection.clearWarnings(); // need to reset transaction isolation, autocommit, readonly, holdability states if (realConnection.getTransactionIsolation() != defaultIsolationLevel) { realConnection.setTransactionIsolation(defaultIsolationLevel); } if (!realConnection.getAutoCommit()) realConnection.setAutoCommit(true); if (realConnection.isReadOnly() != defaultReadOnly) realConnection.setReadOnly(defaultReadOnly); if (realConnection.getHoldability() != JDBC30Translation.HOLD_CURSORS_OVER_COMMIT) realConnection.setHoldability(JDBC30Translation.HOLD_CURSORS_OVER_COMMIT); // reset any remaining state of the connection realConnection.resetFromPool(); if (SanityManager.DEBUG) { SanityManager.ASSERT(realConnection.transactionIsIdle(), "real connection should have been idle at this point"); } } /** Close the Pooled connection. @exception SQLException - if a database-access error occurs. */ public synchronized void close() throws SQLException { if (!isActive) return; closeCurrentConnectionHandle(); try { if (realConnection != null) { if (!realConnection.isClosed()) realConnection.close(); } } finally { realConnection = null; // make sure I am not accessed again. isActive = false; eventListener = null; } } /** Add an event listener. */ public final synchronized void addConnectionEventListener(ConnectionEventListener listener) { if (!isActive) return; if (listener == null) return; if (eventListener == null) eventListener = new Vector(); eventListener.addElement(listener); } /** Remove an event listener. */ public final synchronized void removeConnectionEventListener(ConnectionEventListener listener) { if (listener == null) return; if (eventListener != null) eventListener.removeElement(listener); } /* * class specific method */ // called by ConnectionHandle when it needs to forward things to the // underlying connection public synchronized EngineConnection getRealConnection() throws SQLException { checkActive(); return realConnection; } /** * @return The underlying language connection. */ public synchronized LanguageConnectionContext getLanguageConnection() throws SQLException { checkActive(); return realConnection.getLanguageConnection(); } // my conneciton handle has caught an error (actually, the real connection // has already handled the error, we just need to nofity the listener an // error is about to be thrown to the app). public synchronized void notifyError(SQLException exception) { // only report fatal error to the connection pool manager if (exception.getErrorCode() < ExceptionSeverity.SESSION_SEVERITY) return; // tell my listeners an exception is about to be thrown if (eventListener != null && eventListener.size() > 0) { ConnectionEvent errorEvent = new ConnectionEvent(this, exception); for (Enumeration e = eventListener.elements(); e.hasMoreElements(); ) { ConnectionEventListener l = (ConnectionEventListener)e.nextElement(); l.connectionErrorOccurred(errorEvent); } } } final void checkActive() throws SQLException { if (!isActive) throw Util.noCurrentConnection(); } /* ** BrokeredConnectionControl api */ /** Returns true if isolation level has been set using either JDBC api or SQL */ public boolean isIsolationLevelSetUsingSQLorJDBC() throws SQLException { if (realConnection != null) return realConnection.getLanguageConnection().isIsolationLevelSetUsingSQLorJDBC(); else return false; } /** Reset the isolation level flag used to keep state in BrokeredConnection. It will get set to true when isolation level is set using JDBC/SQL. It will get reset to false at the start and the end of a global transaction. */ public void resetIsolationLevelFlag() throws SQLException { realConnection.getLanguageConnection().resetIsolationLevelFlagUsedForSQLandJDBC(); } /** Notify the control class that a SQLException was thrown during a call on one of the brokered connection's methods. */ public void notifyException(SQLException sqle) { this.notifyError(sqle); } /** Allow control over setting auto commit mode. */ public void checkAutoCommit(boolean autoCommit) throws SQLException { } /** Are held cursors allowed. */ public int checkHoldCursors(int holdability, boolean downgrade) throws SQLException { return holdability; } /** Allow control over creating a Savepoint (JDBC 3.0) */ public void checkSavepoint() throws SQLException { } /** Allow control over calling rollback. */ public void checkRollback() throws SQLException { } /** Allow control over calling commit. */ public void checkCommit() throws SQLException { } /** Close called on BrokeredConnection. If this call returns true then getRealConnection().close() will be called. Notify listners that connection is closed. Don't close the underlying real connection as it is pooled. */ public synchronized boolean closingConnection() throws SQLException { //DERBY-2142-Null out the connection handle BEFORE notifying listeners. //At time of the callback the PooledConnection must be //disassociated from its previous logical connection. //If not there is a risk that the Pooled //Connection could be returned to the pool, ready for pickup by a //new thread. This new thread then might obtain a java.sql.Connection //whose reference might get assigned to the currentConnectionHandle //field, meanwhile the previous thread completes the close making //the newly assigned currentConnectionHandle null, resulting in an NPE. currentConnectionHandle = null; // tell my listeners I am closed if (eventListener != null && eventListener.size() > 0) { ConnectionEvent closeEvent = new ConnectionEvent(this); for (Enumeration e = eventListener.elements(); e.hasMoreElements(); ) { ConnectionEventListener l = (ConnectionEventListener)e.nextElement(); l.connectionClosed(closeEvent); } } return false; } /** No need to wrap statements for PooledConnections. */ public Statement wrapStatement(Statement s) throws SQLException { return s; } /** * Call the setBrokeredConnectionControl method inside the * EmbedPreparedStatement class to set the BrokeredConnectionControl * variable to this instance of EmbedPooledConnection * This will then be used to call the onStatementErrorOccurred * and onStatementClose events when the corresponding events * occur on the PreparedStatement * * @param ps PreparedStatment to be wrapped * @param sql String * @param generatedKeys Object * @return returns the wrapped PreparedStatement * @throws java.sql.SQLException */ public PreparedStatement wrapStatement(PreparedStatement ps, String sql, Object generatedKeys) throws SQLException { /* */ EmbedPreparedStatement ps_ = (EmbedPreparedStatement)ps; ps_.setBrokeredConnectionControl(this); return (PreparedStatement)ps_; } /** * Call the setBrokeredConnectionControl method inside the * EmbedCallableStatement class to set the BrokeredConnectionControl * variable to this instance of EmbedPooledConnection * This will then be used to call the onStatementErrorOccurred * and onStatementClose events when the corresponding events * occur on the CallableStatement * * @param cs CallableStatment to be wrapped * @param sql String * @return returns the wrapped CallableStatement * @throws java.sql.SQLException */ public CallableStatement wrapStatement(CallableStatement cs, String sql) throws SQLException { EmbedCallableStatement cs_ = (EmbedCallableStatement)cs; cs_.setBrokeredConnectionControl(this); return (CallableStatement)cs_; } /** * Get the string representation of this pooled connection. * * A pooled connection is assigned a separate id from a physical * connection. When a container calls PooledConnection.toString(), * it gets the string representation of this id. This is useful for * developers implementing connection pools when they are trying to * debug pooled connections. * * @return a string representation of the uniquie id for this pooled * connection. * */ public String toString() { if ( connString == null ) { String physicalConnString = isActive ? realConnection.toString() : "<none>"; connString = this.getClass().getName() + "@" + this.hashCode() + " " + "(ID = " + connectionId + "), " + "Physical Connection = " + physicalConnString; } return connString; } /*-----------------------------------------------------------------*/ /* * These methods are from the BrokeredConnectionControl interface. * These methods are needed to provide StatementEvent support for * derby. * They are actually implemented in EmbedPooledConnection40 but have * a dummy implementation here so that the compilation wont fail when they * are compiled with jdk1.4 */ /** * Dummy implementation for the actual methods found in * org.apache.derby.jdbc.EmbedPooledConnection40 * @param statement PreparedStatement */ public void onStatementClose(PreparedStatement statement) { } /** * Dummy implementation for the actual methods found in * org.apache.derby.jdbc.EmbedPooledConnection40 * @param statement PreparedStatement * @param sqle SQLException */ public void onStatementErrorOccurred(PreparedStatement statement, SQLException sqle) { } }
java/engine/org/apache/derby/jdbc/EmbedPooledConnection.java
/* Derby - Class org.apache.derby.jdbc.EmbedPooledConnection Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.derby.jdbc; import org.apache.derby.iapi.services.sanity.SanityManager; import org.apache.derby.iapi.reference.Property; import org.apache.derby.iapi.error.ExceptionSeverity; import org.apache.derby.iapi.reference.JDBC30Translation; import org.apache.derby.iapi.sql.conn.LanguageConnectionContext; /* import impl class */ import org.apache.derby.impl.jdbc.Util; import org.apache.derby.impl.jdbc.EmbedConnection; import org.apache.derby.iapi.jdbc.BrokeredConnection; import org.apache.derby.iapi.jdbc.BrokeredConnectionControl; import org.apache.derby.iapi.jdbc.EngineConnection; import org.apache.derby.impl.jdbc.EmbedPreparedStatement; import org.apache.derby.impl.jdbc.EmbedCallableStatement; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.sql.PreparedStatement; import java.sql.CallableStatement; import java.util.Vector; import java.util.Enumeration; /* -- New jdbc 20 extension types --- */ import javax.sql.DataSource; import javax.sql.PooledConnection; import javax.sql.ConnectionEventListener; import javax.sql.ConnectionEvent; /** A PooledConnection object is a connection object that provides hooks for connection pool management. <P>This is Derby's implementation of a PooledConnection for use in the following environments: <UL> <LI> JDBC 3.0 - Java 2 - JDK 1.4, J2SE 5.0 <LI> JDBC 2.0 - Java 2 - JDK 1.2,1.3 </UL> */ class EmbedPooledConnection implements javax.sql.PooledConnection, BrokeredConnectionControl { /** Static counter for connection ids */ private static int idCounter = 0; /** The id for this connection. */ private int connectionId; /** the connection string */ private String connString; private Vector eventListener; // who wants to know I am closed or error EmbedConnection realConnection; int defaultIsolationLevel; private boolean defaultReadOnly; BrokeredConnection currentConnectionHandle; // set up once by the data source final ReferenceableDataSource dataSource; private final String username; private final String password; /** True if the password was passed in on the connection request, false if it came from the data source property. */ private final boolean requestPassword; protected boolean isActive; private synchronized int nextId() { return idCounter++; } EmbedPooledConnection(ReferenceableDataSource ds, String u, String p, boolean requestPassword) throws SQLException { connectionId = nextId(); dataSource = ds; username = u; password = p; this.requestPassword = requestPassword; isActive = true; // open the connection up front in order to do authentication openRealConnection(); } String getUsername() { if (username == null || username.equals("")) return Property.DEFAULT_USER_NAME; else return username; } String getPassword() { if (password == null) return ""; else return password; } /** Create an object handle for a database connection. @return a Connection object @exception SQLException - if a database-access error occurs. */ public synchronized Connection getConnection() throws SQLException { checkActive(); // need to do this in case the connection is forcibly removed without // first being closed. closeCurrentConnectionHandle(); // RealConnection is not null if the app server yanks a local // connection from one client and give it to another. In this case, // the real connection is ready to be used. Otherwise, set it up if (realConnection == null) { // first time we establish a connection openRealConnection(); } else { resetRealConnection(); } // now make a brokered connection wrapper and give this to the user // we reuse the EmbedConnection(ie realConnection). Connection c = getNewCurrentConnectionHandle(); return c; } final void openRealConnection() throws SQLException { // first time we establish a connection Connection rc = dataSource.getConnection(username, password, requestPassword); this.realConnection = (EmbedConnection) rc; defaultIsolationLevel = rc.getTransactionIsolation(); defaultReadOnly = rc.isReadOnly(); if (currentConnectionHandle != null) realConnection.setApplicationConnection(currentConnectionHandle); } final Connection getNewCurrentConnectionHandle() { Connection applicationConnection = currentConnectionHandle = ((org.apache.derby.jdbc.Driver20) (realConnection.getLocalDriver())).newBrokeredConnection(this); realConnection.setApplicationConnection(applicationConnection); return applicationConnection; } /** In this case the Listeners are *not* notified. JDBC 3.0 spec section 11.4 */ private void closeCurrentConnectionHandle() throws SQLException { if (currentConnectionHandle != null) { Vector tmpEventListener = eventListener; eventListener = null; try { currentConnectionHandle.close(); } finally { eventListener = tmpEventListener; } currentConnectionHandle = null; } } void resetRealConnection() throws SQLException { // ensure any outstanding changes from the previous // user are rolledback. realConnection.rollback(); // clear any warnings that are left over realConnection.clearWarnings(); // need to reset transaction isolation, autocommit, readonly, holdability states if (realConnection.getTransactionIsolation() != defaultIsolationLevel) { realConnection.setTransactionIsolation(defaultIsolationLevel); } if (!realConnection.getAutoCommit()) realConnection.setAutoCommit(true); if (realConnection.isReadOnly() != defaultReadOnly) realConnection.setReadOnly(defaultReadOnly); if (realConnection.getHoldability() != JDBC30Translation.HOLD_CURSORS_OVER_COMMIT) realConnection.setHoldability(JDBC30Translation.HOLD_CURSORS_OVER_COMMIT); // reset any remaining state of the connection realConnection.resetFromPool(); if (SanityManager.DEBUG) { SanityManager.ASSERT(realConnection.transactionIsIdle(), "real connection should have been idle at this point"); } } /** Close the Pooled connection. @exception SQLException - if a database-access error occurs. */ public synchronized void close() throws SQLException { if (!isActive) return; closeCurrentConnectionHandle(); try { if (realConnection != null) { if (!realConnection.isClosed()) realConnection.close(); } } finally { realConnection = null; // make sure I am not accessed again. isActive = false; eventListener = null; } } /** Add an event listener. */ public final synchronized void addConnectionEventListener(ConnectionEventListener listener) { if (!isActive) return; if (listener == null) return; if (eventListener == null) eventListener = new Vector(); eventListener.addElement(listener); } /** Remove an event listener. */ public final synchronized void removeConnectionEventListener(ConnectionEventListener listener) { if (listener == null) return; if (eventListener != null) eventListener.removeElement(listener); } /* * class specific method */ // called by ConnectionHandle when it needs to forward things to the // underlying connection public synchronized EngineConnection getRealConnection() throws SQLException { checkActive(); return realConnection; } /** * @return The underlying language connection. */ public synchronized LanguageConnectionContext getLanguageConnection() throws SQLException { checkActive(); return realConnection.getLanguageConnection(); } // my conneciton handle has caught an error (actually, the real connection // has already handled the error, we just need to nofity the listener an // error is about to be thrown to the app). public synchronized void notifyError(SQLException exception) { // only report fatal error to the connection pool manager if (exception.getErrorCode() < ExceptionSeverity.SESSION_SEVERITY) return; // tell my listeners an exception is about to be thrown if (eventListener != null && eventListener.size() > 0) { ConnectionEvent errorEvent = new ConnectionEvent(this, exception); for (Enumeration e = eventListener.elements(); e.hasMoreElements(); ) { ConnectionEventListener l = (ConnectionEventListener)e.nextElement(); l.connectionErrorOccurred(errorEvent); } } } final void checkActive() throws SQLException { if (!isActive) throw Util.noCurrentConnection(); } /* ** BrokeredConnectionControl api */ /** Returns true if isolation level has been set using either JDBC api or SQL */ public boolean isIsolationLevelSetUsingSQLorJDBC() throws SQLException { if (realConnection != null) return realConnection.getLanguageConnection().isIsolationLevelSetUsingSQLorJDBC(); else return false; } /** Reset the isolation level flag used to keep state in BrokeredConnection. It will get set to true when isolation level is set using JDBC/SQL. It will get reset to false at the start and the end of a global transaction. */ public void resetIsolationLevelFlag() throws SQLException { realConnection.getLanguageConnection().resetIsolationLevelFlagUsedForSQLandJDBC(); } /** Notify the control class that a SQLException was thrown during a call on one of the brokered connection's methods. */ public void notifyException(SQLException sqle) { this.notifyError(sqle); } /** Allow control over setting auto commit mode. */ public void checkAutoCommit(boolean autoCommit) throws SQLException { } /** Are held cursors allowed. */ public int checkHoldCursors(int holdability, boolean downgrade) throws SQLException { return holdability; } /** Allow control over creating a Savepoint (JDBC 3.0) */ public void checkSavepoint() throws SQLException { } /** Allow control over calling rollback. */ public void checkRollback() throws SQLException { } /** Allow control over calling commit. */ public void checkCommit() throws SQLException { } /** Close called on BrokeredConnection. If this call returns true then getRealConnection().close() will be called. Notify listners that connection is closed. Don't close the underlying real connection as it is pooled. */ public synchronized boolean closingConnection() throws SQLException { //DERBY-2142 - Null out the connection handle BEFORE notifying listeners. currentConnectionHandle = null; // tell my listeners I am closed if (eventListener != null && eventListener.size() > 0) { ConnectionEvent closeEvent = new ConnectionEvent(this); for (Enumeration e = eventListener.elements(); e.hasMoreElements(); ) { ConnectionEventListener l = (ConnectionEventListener)e.nextElement(); l.connectionClosed(closeEvent); } } return false; } /** No need to wrap statements for PooledConnections. */ public Statement wrapStatement(Statement s) throws SQLException { return s; } /** * Call the setBrokeredConnectionControl method inside the * EmbedPreparedStatement class to set the BrokeredConnectionControl * variable to this instance of EmbedPooledConnection * This will then be used to call the onStatementErrorOccurred * and onStatementClose events when the corresponding events * occur on the PreparedStatement * * @param ps PreparedStatment to be wrapped * @param sql String * @param generatedKeys Object * @return returns the wrapped PreparedStatement * @throws java.sql.SQLException */ public PreparedStatement wrapStatement(PreparedStatement ps, String sql, Object generatedKeys) throws SQLException { /* */ EmbedPreparedStatement ps_ = (EmbedPreparedStatement)ps; ps_.setBrokeredConnectionControl(this); return (PreparedStatement)ps_; } /** * Call the setBrokeredConnectionControl method inside the * EmbedCallableStatement class to set the BrokeredConnectionControl * variable to this instance of EmbedPooledConnection * This will then be used to call the onStatementErrorOccurred * and onStatementClose events when the corresponding events * occur on the CallableStatement * * @param cs CallableStatment to be wrapped * @param sql String * @return returns the wrapped CallableStatement * @throws java.sql.SQLException */ public CallableStatement wrapStatement(CallableStatement cs, String sql) throws SQLException { EmbedCallableStatement cs_ = (EmbedCallableStatement)cs; cs_.setBrokeredConnectionControl(this); return (CallableStatement)cs_; } /** * Get the string representation of this pooled connection. * * A pooled connection is assigned a separate id from a physical * connection. When a container calls PooledConnection.toString(), * it gets the string representation of this id. This is useful for * developers implementing connection pools when they are trying to * debug pooled connections. * * @return a string representation of the uniquie id for this pooled * connection. * */ public String toString() { if ( connString == null ) { String physicalConnString = isActive ? realConnection.toString() : "<none>"; connString = this.getClass().getName() + "@" + this.hashCode() + " " + "(ID = " + connectionId + "), " + "Physical Connection = " + physicalConnString; } return connString; } /*-----------------------------------------------------------------*/ /* * These methods are from the BrokeredConnectionControl interface. * These methods are needed to provide StatementEvent support for * derby. * They are actually implemented in EmbedPooledConnection40 but have * a dummy implementation here so that the compilation wont fail when they * are compiled with jdk1.4 */ /** * Dummy implementation for the actual methods found in * org.apache.derby.jdbc.EmbedPooledConnection40 * @param statement PreparedStatement */ public void onStatementClose(PreparedStatement statement) { } /** * Dummy implementation for the actual methods found in * org.apache.derby.jdbc.EmbedPooledConnection40 * @param statement PreparedStatement * @param sqle SQLException */ public void onStatementErrorOccurred(PreparedStatement statement, SQLException sqle) { } }
DERBY-2142 NullPointerException while using XAConnection/PooledConnection in a heavily contended multithreaded scenario Update code comments. git-svn-id: 2c06e9c5008124d912b69f0b82df29d4867c0ce2@616575 13f79535-47bb-0310-9956-ffa450edef68
java/engine/org/apache/derby/jdbc/EmbedPooledConnection.java
DERBY-2142 NullPointerException while using XAConnection/PooledConnection in a heavily contended multithreaded scenario
Java
bsd-2-clause
96edf827727ead71b59a647273023eafaf8a9122
0
TheFakeMontyOnTheRun/nehe-ndk-gles20,TheFakeMontyOnTheRun/nehe-ndk-gles20,TheFakeMontyOnTheRun/nehe-ndk-gles20
/* * Copyright (C) 2007 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 br.odb.nehe.lesson06; import android.app.Activity; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.util.Log; import android.view.WindowManager; import java.io.File; public class GL2JNIActivity extends Activity { GL2JNIView mView; boolean running = false; static AssetManager assets; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); assets = getAssets(); GL2JNILib.onCreate( assets ); Bitmap bitmap = BitmapFactory.decodeResource( getResources(), R.mipmap.ic_launcher ); GL2JNILib.setTexture(bitmap); mView = new GL2JNIView(getApplication()); setContentView(mView); } @Override protected void onPause() { super.onPause(); running = false; mView.onPause(); } @Override protected void onResume() { super.onResume(); mView.onResume(); new Thread(new Runnable() { @Override public void run() { running = true; while( running ) { try { Thread.sleep( 20 ); } catch (InterruptedException e) { e.printStackTrace(); } GL2JNILib.tick(); } } }).start(); } @Override protected void onDestroy() { GL2JNILib.onDestroy(); super.onDestroy(); } }
lesson06/app/src/main/java/br/odb/nehe/lesson06/GL2JNIActivity.java
/* * Copyright (C) 2007 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 br.odb.nehe.lesson06; import android.app.Activity; import android.content.res.AssetManager; import android.os.Bundle; import android.util.Log; import android.view.WindowManager; import java.io.File; public class GL2JNIActivity extends Activity { GL2JNIView mView; boolean running = false; static AssetManager assets; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); assets = getAssets(); GL2JNILib.onCreate( assets ); mView = new GL2JNIView(getApplication()); setContentView(mView); } @Override protected void onPause() { super.onPause(); running = false; mView.onPause(); } @Override protected void onResume() { super.onResume(); mView.onResume(); new Thread(new Runnable() { @Override public void run() { running = true; while( running ) { try { Thread.sleep( 20 ); } catch (InterruptedException e) { e.printStackTrace(); } GL2JNILib.tick(); } } }).start(); } @Override protected void onDestroy() { GL2JNILib.onDestroy(); super.onDestroy(); } }
Create and set texture from Java, to Lesson 06 The native side now will copy this into the texturing unit.
lesson06/app/src/main/java/br/odb/nehe/lesson06/GL2JNIActivity.java
Create and set texture from Java, to Lesson 06
Java
bsd-3-clause
e8be297a94f0aaabfb4d0052f9d45ba85b8deb75
0
Beachbot330/Beachbot2013Java,Beachbot330/Beachbot2014Java,Beachbot330/Beachbot2013Java
// RobotBuilder Version: 0.0.2 // // This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in th future. package org.usfirst.frc330.Beachbot2013Java.subsystems; import org.usfirst.frc330.Beachbot2013Java.RobotMap; import org.usfirst.frc330.Beachbot2013Java.commands.*; import edu.wpi.first.wpilibj.*; import edu.wpi.first.wpilibj.CounterBase.EncodingType; import edu.wpi.first.wpilibj.Encoder.PIDSourceParameter; import edu.wpi.first.wpilibj.command.Subsystem; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import org.usfirst.frc330.Beachbot2013Java.Robot; /** * */ public class ShooterLow extends Subsystem { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS DoubleSolenoid shooterLoadSolenoid = RobotMap.shooterLowShooterLoadSolenoid; SpeedController shooterLowController = RobotMap.shooterLowShooterLowController; Encoder shooterLowEncoder = RobotMap.shooterLowShooterLowEncoder; // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS // Put methods for controlling this subsystem // here. Call these from Commands. public void initDefaultCommand() { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND // Set the default command for a subsystem here. //setDefaultCommand(new MySpecialCommand()); } public void shoot(double voltage) { SmartDashboard.putNumber("voltageLow", voltage); shooterLowController.set(voltage); } public void armLoadShooterOn() { shooterLoadSolenoid.set(DoubleSolenoid.Value.kForward); } public void armLoadShooterOff() { shooterLoadSolenoid.set(DoubleSolenoid.Value.kReverse); } public double launchFrisbeeSolenoidOffTime() { return Preferences.getInstance().getDouble("solenoidOffTime", 0.5); } public double getSpeed() { return shooterLowEncoder.getRate(); } public void ShooterLowMotorToggle(double voltage) { if ( voltage == 0 ) Robot.shooterLow.shoot(voltage); else Robot.shooterLow.shoot(0); } }
src/org/usfirst/frc330/Beachbot2013Java/subsystems/ShooterLow.java
// RobotBuilder Version: 0.0.2 // // This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in th future. package org.usfirst.frc330.Beachbot2013Java.subsystems; import org.usfirst.frc330.Beachbot2013Java.RobotMap; import org.usfirst.frc330.Beachbot2013Java.commands.*; import edu.wpi.first.wpilibj.*; import edu.wpi.first.wpilibj.CounterBase.EncodingType; import edu.wpi.first.wpilibj.Encoder.PIDSourceParameter; import edu.wpi.first.wpilibj.command.Subsystem; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** * */ public class ShooterLow extends Subsystem { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS DoubleSolenoid shooterLoadSolenoid = RobotMap.shooterLowShooterLoadSolenoid; SpeedController shooterLowController = RobotMap.shooterLowShooterLowController; Encoder shooterLowEncoder = RobotMap.shooterLowShooterLowEncoder; // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS // Put methods for controlling this subsystem // here. Call these from Commands. public void initDefaultCommand() { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND // Set the default command for a subsystem here. //setDefaultCommand(new MySpecialCommand()); } public void shoot(double voltage) { SmartDashboard.putNumber("voltageLow", voltage); shooterLowController.set(voltage); } public void armLoadShooterOn() { shooterLoadSolenoid.set(DoubleSolenoid.Value.kForward); } public void armLoadShooterOff() { shooterLoadSolenoid.set(DoubleSolenoid.Value.kReverse); } public double launchFrisbeeSolenoidOffTime() { return Preferences.getInstance().getDouble("solenoidOffTime", 0.5); } public double getSpeed() { return shooterLowEncoder.getRate(); } }
Added a toggle for shooter low
src/org/usfirst/frc330/Beachbot2013Java/subsystems/ShooterLow.java
Added a toggle for shooter low
Java
mit
bdf81ad7d2c3b22438441eb3d7cbee38dd71cc53
0
keceli/RMG-Java,faribas/RMG-Java,rwest/RMG-Java,connie/RMG-Java,KEHANG/RMG-Java,nyee/RMG-Java,KEHANG/RMG-Java,rwest/RMG-Java,faribas/RMG-Java,nyee/RMG-Java,ReactionMechanismGenerator/RMG-Java,ReactionMechanismGenerator/RMG-Java,enochd/RMG-Java,keceli/RMG-Java,keceli/RMG-Java,jwallen/RMG-Java,keceli/RMG-Java,nyee/RMG-Java,faribas/RMG-Java,rwest/RMG-Java,jwallen/RMG-Java,nyee/RMG-Java,enochd/RMG-Java,enochd/RMG-Java,connie/RMG-Java,enochd/RMG-Java,keceli/RMG-Java,ReactionMechanismGenerator/RMG-Java,KEHANG/RMG-Java,jwallen/RMG-Java,KEHANG/RMG-Java,connie/RMG-Java,jwallen/RMG-Java,enochd/RMG-Java,KEHANG/RMG-Java,nyee/RMG-Java,ReactionMechanismGenerator/RMG-Java,connie/RMG-Java,keceli/RMG-Java,rwest/RMG-Java,jwallen/RMG-Java,nyee/RMG-Java,ReactionMechanismGenerator/RMG-Java,faribas/RMG-Java,jwallen/RMG-Java,enochd/RMG-Java,rwest/RMG-Java,connie/RMG-Java,KEHANG/RMG-Java
//////////////////////////////////////////////////////////////////////////////// // // RMG - Reaction Mechanism Generator // // Copyright (c) 2002-2011 Prof. William H. Green (whgreen@mit.edu) and the // RMG Team (rmg_dev@mit.edu) // // 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 jing.rxnSys; import java.io.*; import jing.mathTool.UncertainDouble; import jing.param.Pressure; import jing.param.Temperature; import jing.rxn.*; import jing.chem.*; import java.util.*; import jing.chemUtil.*; import jing.chemParser.*; /** * This is a new class called SeedMechanism. SeedMechanism is the same class * as the old PrimaryKineticLibrary, just with a new (and more appropriate) * name. RMG will automatically include every species and reaction contained * in a Seed Mechanism. Furthermore, the user has the option to pass multiple * Seed Mechanisms to RMG. In the event of a duplicate species/reaction, RMG * will use the first instance it finds (i.e. the order of the Seed Mechanisms * listed in the condition.txt file is important). * * MRH 9-Jun-2009 */ /* * Comments from old PrimaryKineticLibrary: * * This is the primary reaction set that any reaction system has to include * into its model. For example, in combustion system, we build a primary small * molecule reaction set, and every combustion/oxidation system should include * such a primary reaction library. The reaction / rates are basically from Leeds * methane oxidation mechanism. */ public class SeedMechanism { protected String name; protected LinkedHashSet reactionSet = new LinkedHashSet(); protected HashMap speciesSet = new HashMap(); private boolean generateReactions = false; public LinkedList allPdepNetworks = new LinkedList(); // Constructors public SeedMechanism(String p_mechName, String p_directoryPath, boolean p_generateReactions, boolean p_fromRestart) throws IOException { name = p_mechName; generateReactions = p_generateReactions; if ( p_directoryPath == null) throw new NullPointerException("RMG does not recognize Seed Mechanism directory path: Value is null"); try { read(p_directoryPath,p_fromRestart,p_mechName); } catch (IOException e) { throw new IOException("Error in reading Seed Mechanism: " + p_mechName + '\n' + e.getMessage()); } } public SeedMechanism() { } public void appendSeedMechanism(String new_mechName, String new_directoryPath, boolean p_generateReactions, boolean p_fromRestart) throws IOException { if (p_generateReactions) setGenerateReactions(p_generateReactions); setName(name + "/" + new_mechName); try { read(new_directoryPath,p_fromRestart,new_mechName); } catch (IOException e) { throw new IOException("Error in reading Seed Mechanism: " + new_mechName + '\n' + e.getMessage()); } } public LinkedHashSet getSpeciesSet() { return new LinkedHashSet(speciesSet.values()); } public void read(String p_directoryName, boolean p_fromRestart, String seedMechName) throws IOException { Logger.info("Reading seed mechanism from directory " + p_directoryName); HashMap localSpecies = null; LinkedHashSet localReactions = null; try { if (!p_directoryName.endsWith("/")) p_directoryName = p_directoryName + "/"; if (!p_fromRestart) { String speciesFile = p_directoryName + "species.txt"; String reactionFile = p_directoryName + "reactions.txt"; String pdepreactionFile = p_directoryName + "pdepreactions.txt"; speciesSet.putAll(readSpecies(speciesFile,seedMechName,"Seed Mechanism: ")); reactionSet.addAll(readReactions(reactionFile,seedMechName,speciesSet,"Seed Mechanism: ",true)); reactionSet.addAll(readPdepReactions(pdepreactionFile,seedMechName,speciesSet,"Seed Mechanism: ",true)); } else { String speciesFile = p_directoryName + "coreSpecies.txt"; String pdepreactionFile = p_directoryName + "pdepreactions.txt"; speciesSet.putAll(readSpecies(speciesFile,seedMechName,"Seed Mechanism: ")); reactionSet.addAll(readPdepReactions(pdepreactionFile,seedMechName,speciesSet,"Seed Mechanism: ",true)); } return; } catch (Exception e) { throw new IOException("RMG cannot read entire Seed Mechanism: " + p_directoryName + "\n" + e.getMessage()); } } public LinkedHashSet readReactions(String p_reactionFileName, String p_name, HashMap allSpecies, String source, boolean pkl) throws IOException { LinkedHashSet localReactions = new LinkedHashSet(); try { FileReader in = new FileReader(p_reactionFileName); BufferedReader data = new BufferedReader(in); double[] multipliers = parseReactionRateUnits(data); double A_multiplier = multipliers[0]; double E_multiplier = multipliers[1]; String line = ChemParser.readMeaningfulLine(data, true); read: while (line != null) { Reaction r; try { r = ChemParser.parseArrheniusReaction(allSpecies, line, A_multiplier, E_multiplier); r.setKineticsSource(source+ p_name,0); r.setKineticsComments(" ",0); if (pkl) { r.setIsFromPrimaryKineticLibrary(true); (r.getKinetics())[0].setFromPrimaryKineticLibrary(true); } } catch (InvalidReactionFormatException e) { throw new InvalidReactionFormatException(line + ": " + e.getMessage()); } if (r == null) throw new InvalidReactionFormatException(line); localReactions = updateReactionList(r,localReactions,true); line = ChemParser.readMeaningfulLine(data, true); } in.close(); return localReactions; } catch (Exception e) { Logger.error("RMG did not read the following " + source + p_name + " file: " + p_reactionFileName + " because " + e.getMessage() ); Logger.logStackTrace(e); return null; } } public HashMap readSpecies(String p_speciesFileName, String p_name, String source) throws IOException { HashMap localSpecies = new HashMap(); try { FileReader in = new FileReader(p_speciesFileName); BufferedReader data = new BufferedReader(in); // step 1: read in structure String line = ChemParser.readMeaningfulLine(data, true); read: while (line != null) { // GJB allow unreactive species StringTokenizer st = new StringTokenizer(line); String name = st.nextToken().trim(); boolean IsReactive = true; if (st.hasMoreTokens()) { String reactive = st.nextToken().trim(); if ( reactive.equalsIgnoreCase("unreactive") ) IsReactive = false; } Graph graph; try { graph = ChemParser.readChemGraph(data); if (graph == null) throw new IOException("Graph was null"); } catch (IOException e) { throw new InvalidChemGraphException("Cannot read species '" + name + "': " + e.getMessage()); } ChemGraph cg = ChemGraph.make(graph); Species spe = Species.make(name, cg); // GJB: Turn off reactivity if necessary, but don't let code turn it on // again if was already set as unreactive from input file if(IsReactive==false) spe.setReactivity(IsReactive); localSpecies.put(name, spe); line = ChemParser.readMeaningfulLine(data, true); } in.close(); return localSpecies; } catch (Exception e) { throw new IOException("RMG cannot read the \"species.txt\" file in the " + source + p_name + "\n" + e.getMessage()); } } public LinkedHashSet readPdepReactions(String pdepFileName, String p_name, HashMap allSpecies, String source, boolean pkl) throws IOException { LinkedHashSet localReactions = new LinkedHashSet(); LinkedList pdepNetworks = getPDepNetworks(); try { FileReader in = new FileReader(pdepFileName); BufferedReader data = new BufferedReader(in); double[] multipliers = parseReactionRateUnits(data); double A_multiplier = multipliers[0]; double E_multiplier = multipliers[1]; String nextLine = ChemParser.readMeaningfulLine(data, true); read: while (nextLine != null) { Reaction r; try { r = ChemParser.parseArrheniusReaction(allSpecies, nextLine, A_multiplier, E_multiplier); } catch (InvalidReactionFormatException e) { throw new InvalidReactionFormatException(nextLine + ": " + e.getMessage()); } if (r == null) throw new InvalidReactionFormatException(nextLine); /* * Read the next line and determine what to do based on the * presence/absence of keywords */ nextLine = ChemParser.readMeaningfulLine(data, true); boolean continueToReadRxn = true; // Initialize all of the possible pdep variables HashMap thirdBodyList = new HashMap(); UncertainDouble uA = new UncertainDouble(0.0, 0.0, "Adder"); UncertainDouble un = new UncertainDouble(0.0, 0.0, "Adder"); UncertainDouble uE = new UncertainDouble(0.0, 0.0, "Adder"); ArrheniusKinetics low = new ArrheniusKinetics(uA, un, uE, "", 0, "", ""); double a = 0.0; double T3star = 0.0; double Tstar = 0.0; double T2star = 0.0; boolean troe7 = false; int numPLOGs = 0; PDepArrheniusKinetics pdepkineticsPLOG = new PDepArrheniusKinetics(numPLOGs); /* * When reading in the auxillary information for the pdep reactions, * let's not assume the order is fixed (i.e. third-bodies and * their efficiencies, then lindemann, then troe) * The order of the if statement is important as the "troe" and * "low" lines will also contain a "/"; thus, the elseif contains * "/" needs to be last. */ /* * Additions by MRH on 26JUL2010: * Allowing RMG to read-in PLOG and CHEB formatting */ while (continueToReadRxn) { if (nextLine == null) { continueToReadRxn = false; } else if (nextLine.toLowerCase().contains("troe")) { // read in troe parameters StringTokenizer st = new StringTokenizer(nextLine, "/"); String temp = st.nextToken().trim(); // TROE String troeString = st.nextToken().trim(); // List of troe parameters st = new StringTokenizer(troeString); int n = st.countTokens(); if (n != 3 && n != 4) throw new InvalidKineticsFormatException("Troe parameter number = "+n + " for reaction: " + r.toString()); a = Double.parseDouble(st.nextToken().trim()); T3star = Double.parseDouble(st.nextToken().trim()); Tstar = Double.parseDouble(st.nextToken().trim()); if (st.hasMoreTokens()) { troe7 = true; T2star = Double.parseDouble(st.nextToken().trim()); } nextLine = ChemParser.readMeaningfulLine(data, true); } else if (nextLine.toLowerCase().contains("low")) { // read in lindemann parameters StringTokenizer st = new StringTokenizer(nextLine, "/"); String temp = st.nextToken().trim(); // LOW String lowString = st.nextToken().trim(); // Modified Arrhenius parameters /* * MRH 17Feb2010: * The units of the k_zero (LOW) Arrhenius parameters are different from the units of * k_inf Arrhenius parameters by a factor of cm3/mol, hence the getReactantNumber()+1 */ low = ChemParser.parseSimpleArrheniusKinetics(lowString, A_multiplier, E_multiplier, r.getReactantNumber()+1); nextLine = ChemParser.readMeaningfulLine(data, true); } else if (nextLine.contains("CHEB")) { // Read in the Tmin/Tmax and Pmin/Pmax information StringTokenizer st_cheb = new StringTokenizer(nextLine,"/"); String nextToken = st_cheb.nextToken(); // Should be TCHEB or PCHEB StringTokenizer st_minmax = new StringTokenizer(st_cheb.nextToken()); double Tmin = 0.0; double Tmax = 0.0; double Pmin = 0.0; double Pmax = 0.0; if (nextToken.trim().equals("TCHEB")) { Tmin = Double.parseDouble(st_minmax.nextToken()); Tmax = Double.parseDouble(st_minmax.nextToken()); } else { Pmin = Double.parseDouble(st_minmax.nextToken()); Pmax = Double.parseDouble(st_minmax.nextToken()); } nextToken = st_cheb.nextToken(); // Should be PCHEB or TCHEB st_minmax = new StringTokenizer(st_cheb.nextToken()); if (nextToken.trim().equals("TCHEB")) { Tmin = Double.parseDouble(st_minmax.nextToken()); Tmax = Double.parseDouble(st_minmax.nextToken()); } else { Pmin = Double.parseDouble(st_minmax.nextToken()); Pmax = Double.parseDouble(st_minmax.nextToken()); } // Read in the N/M values (number of polynomials in the Temp and Press domain) nextLine = ChemParser.readMeaningfulLine(data, true); st_cheb = new StringTokenizer(nextLine,"/"); nextToken = st_cheb.nextToken(); // Should be CHEB st_minmax = new StringTokenizer(st_cheb.nextToken()); int numN = Integer.parseInt(st_minmax.nextToken()); int numM = Integer.parseInt(st_minmax.nextToken()); // Read in the coefficients nextLine = ChemParser.readMeaningfulLine(data, true); double[] unorderedChebyCoeffs = new double[numN*numM]; int chebyCoeffCounter = 0; while (nextLine != null && nextLine.contains("CHEB")) { st_cheb = new StringTokenizer(nextLine,"/"); nextToken = st_cheb.nextToken(); // Should be CHEB st_minmax = new StringTokenizer(st_cheb.nextToken()); while (st_minmax.hasMoreTokens()) { unorderedChebyCoeffs[chebyCoeffCounter] = Double.parseDouble(st_minmax.nextToken()); ++chebyCoeffCounter; } nextLine = ChemParser.readMeaningfulLine(data, true); } // Order the chebyshev coefficients double[][] chebyCoeffs = new double[numN][numM]; for (int numRows=0; numRows<numN; numRows++) { for (int numCols=0; numCols<numM; numCols++) { chebyCoeffs[numRows][numCols] = unorderedChebyCoeffs[numM*numRows+numCols]; } } // Make the ChebyshevPolynomials, PDepReaction, and add to list of PDepReactions ChebyshevPolynomials coeffs = new ChebyshevPolynomials( numN,new Temperature(Tmin,"K"),new Temperature(Tmax,"K"), numM,new Pressure(Pmin,"bar"),new Pressure(Pmax,"bar"), chebyCoeffs); PDepIsomer reactants = new PDepIsomer(r.getStructure().getReactantList()); PDepIsomer products = new PDepIsomer(r.getStructure().getProductList()); PDepRateConstant pdepRC = new PDepRateConstant(coeffs); PDepReaction pdeprxn = new PDepReaction(reactants,products,pdepRC); allPdepNetworks.add(pdeprxn); continueToReadRxn = false; } else if (nextLine.contains("PLOG")) { while (nextLine != null && nextLine.contains("PLOG")) { // Increase the PLOG counter ++numPLOGs; // Store the previous PLOG information in temporary arrays Pressure[] previousPressures = new Pressure[numPLOGs]; ArrheniusKinetics[] previousKinetics = new ArrheniusKinetics[numPLOGs]; for (int previousNumPLOG=0; previousNumPLOG<numPLOGs-1; ++previousNumPLOG) { previousPressures[previousNumPLOG] = pdepkineticsPLOG.getPressure(previousNumPLOG); previousKinetics[previousNumPLOG] = pdepkineticsPLOG.getKinetics(previousNumPLOG); } // Read in the new PLOG information, and add this to the temporary array PDepArrheniusKinetics newpdepkinetics = parsePLOGline(nextLine); previousPressures[numPLOGs-1] = newpdepkinetics.getPressure(0); previousKinetics[numPLOGs-1] = newpdepkinetics.getKinetics(0); // Re-initialize pdepkinetics and populate with stored information pdepkineticsPLOG = new PDepArrheniusKinetics(numPLOGs); pdepkineticsPLOG.setPressures(previousPressures); pdepkineticsPLOG.setRateCoefficients(previousKinetics); // Read the next line nextLine = ChemParser.readMeaningfulLine(data, true); } // Make the PDepReaction PDepIsomer reactants = new PDepIsomer(r.getStructure().getReactantList()); PDepIsomer products = new PDepIsomer(r.getStructure().getProductList()); PDepRateConstant pdepRC = new PDepRateConstant(pdepkineticsPLOG); PDepReaction pdeprxn = new PDepReaction(reactants,products,pdepRC); // Add to the list of PDepReactions allPdepNetworks.add(pdeprxn); // Re-initialize the pdepkinetics variable numPLOGs = 0; pdepkineticsPLOG = new PDepArrheniusKinetics(numPLOGs); continueToReadRxn = false; } else if (nextLine.contains("/")) { // read in third body colliders + efficiencies thirdBodyList.putAll(ChemParser.parseThirdBodyList(nextLine,allSpecies)); nextLine = ChemParser.readMeaningfulLine(data, true); } else { // the nextLine is a "new" reaction, hence we need to exit the while loop continueToReadRxn = false; } } /* * Make the pdep reaction, according to which parameters * are present */ if ((a==0.0) && (T3star==0.0) && (Tstar==0.0)) { // Not a troe reaction if (low.getAValue() == 0.0) { // thirdbody reaction ThirdBodyReaction tbr = ThirdBodyReaction.make(r,thirdBodyList); tbr.setKineticsSource(source+ p_name,0); tbr.setKineticsComments(" ",0); if (pkl) { tbr.setIsFromPrimaryKineticLibrary(true); (tbr.getKinetics())[0].setFromPrimaryKineticLibrary(true); } localReactions.add(tbr); Reaction reverse = tbr.getReverseReaction(); if (reverse != null) localReactions.add(reverse); } else { // lindemann reaction LindemannReaction tbr = LindemannReaction.make(r,thirdBodyList,low); tbr.setKineticsSource(source+ p_name,0); tbr.setKineticsComments(" ",0); if (pkl) { tbr.setIsFromPrimaryKineticLibrary(true); (tbr.getKinetics())[0].setFromPrimaryKineticLibrary(true); } localReactions.add(tbr); Reaction reverse = tbr.getReverseReaction(); if (reverse != null) localReactions.add(reverse); } } else { // troe reaction TROEReaction tbr = TROEReaction.make(r,thirdBodyList, low, a, T3star, Tstar, troe7, T2star); tbr.setKineticsSource(source+ p_name,0); tbr.setKineticsComments(" ",0); if (pkl) { tbr.setIsFromPrimaryKineticLibrary(true); (tbr.getKinetics())[0].setFromPrimaryKineticLibrary(true); } localReactions.add(tbr); Reaction reverse = tbr.getReverseReaction(); if (reverse != null) localReactions.add(reverse); } } in.close(); return localReactions; } catch (Exception e) { /* * 25Jun2009-MRH: When reading the Primary Kinetic Library, we should not require the user to supply * troe reactions. In the instance that no "troeReactions.txt" file exists, inform * user of this but continue simulation. */ System.err.println("RMG could not find, or read in its entirety, the pressure-dependent reactions file (pdepreactions.txt)" + "\n\tin the " + source + p_name + "\n" + e.getMessage()); return null; } } public int size() { return speciesSet.size(); } public String getName() { return name; } public void setName(String p_name) { name = p_name; } public LinkedHashSet getReactionSet() { return reactionSet; } public boolean shouldGenerateReactions() { return generateReactions; } public void setGenerateReactions(boolean generateReactions) { this.generateReactions = generateReactions; } public double[] parseReactionRateUnits(BufferedReader data) { double[] multipliers = new double[2]; String line = ChemParser.readMeaningfulLine(data, true); if (line.startsWith("Unit")) { line = ChemParser.readMeaningfulLine(data, true); unit: while(!(line.startsWith("Reaction"))) { if (line.startsWith("A")) { StringTokenizer st = new StringTokenizer(line); String temp = st.nextToken(); String unit = st.nextToken().trim(); if (unit.compareToIgnoreCase("mol/cm3/s") == 0) { multipliers[0] = 1; } else if (unit.compareToIgnoreCase("mol/liter/s") == 0) { multipliers[0] = 1e-3; } else if (unit.compareToIgnoreCase("molecule/cm3/s") == 0) { multipliers[0] = 6.022e23; } } else if (line.startsWith("E")) { StringTokenizer st = new StringTokenizer(line); String temp = st.nextToken(); String unit = st.nextToken().trim(); if (unit.compareToIgnoreCase("kcal/mol") == 0) { multipliers[1] = 1; } else if (unit.compareToIgnoreCase("cal/mol") == 0) { multipliers[1] = 1e-3; } else if (unit.compareToIgnoreCase("kJ/mol") == 0) { multipliers[1] = 1/4.186; } else if (unit.compareToIgnoreCase("J/mol") == 0) { multipliers[1] = 1/4186; } else if (unit.compareToIgnoreCase("Kelvin") == 0) { multipliers[1] = 1.987e-3; } } line = ChemParser.readMeaningfulLine(data, true); } } return multipliers; } public LinkedHashSet updateReactionList(Reaction r, LinkedHashSet listOfRxns, boolean generateReverse) { Iterator allRxnsIter = listOfRxns.iterator(); boolean foundRxn = false; while (allRxnsIter.hasNext()) { Reaction old = (Reaction)allRxnsIter.next(); if (old.equals(r)) { old.addAdditionalKinetics(r.getKinetics()[0],1); foundRxn = true; break; } } if (!foundRxn) { listOfRxns.add(r); if (generateReverse) { Reaction reverse = r.getReverseReaction(); if (reverse != null) { listOfRxns.add(reverse); } } } return listOfRxns; } public PDepArrheniusKinetics parsePLOGline(String line) { PDepRateConstant pdepk = new PDepRateConstant(); // Delimit the PLOG line by "/" StringTokenizer st_slash = new StringTokenizer(line,"/"); String dummyString = st_slash.nextToken(); // Delimit the data of the PLOG line by whitespace StringTokenizer st = new StringTokenizer(st_slash.nextToken()); // If reading a chemkin plog line, pressure MUST be in atmospheres Pressure p = new Pressure(Double.parseDouble(st.nextToken().trim()),"atm"); UncertainDouble dA = new UncertainDouble(Double.parseDouble(st.nextToken().trim()),0.0,"A"); UncertainDouble dn = new UncertainDouble(Double.parseDouble(st.nextToken().trim()),0.0,"A"); double Ea = Double.parseDouble(st.nextToken().trim()); // If reading a chemkin plog line, Ea MUST be in cal/mol Ea = Ea / 1000; UncertainDouble dE = new UncertainDouble(Ea,0.0,"A"); ArrheniusKinetics k = new ArrheniusKinetics(dA, dn, dE, "", 1, "", ""); PDepArrheniusKinetics pdepAK = new PDepArrheniusKinetics(1); pdepAK.setKinetics(0, p, k); return pdepAK; } public LinkedList getPDepNetworks() { return allPdepNetworks; } }
source/RMG/jing/rxnSys/SeedMechanism.java
//////////////////////////////////////////////////////////////////////////////// // // RMG - Reaction Mechanism Generator // // Copyright (c) 2002-2011 Prof. William H. Green (whgreen@mit.edu) and the // RMG Team (rmg_dev@mit.edu) // // 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 jing.rxnSys; import java.io.*; import jing.mathTool.UncertainDouble; import jing.param.Pressure; import jing.param.Temperature; import jing.rxn.*; import jing.chem.*; import java.util.*; import jing.chemUtil.*; import jing.chemParser.*; /** * This is a new class called SeedMechanism. SeedMechanism is the same class * as the old PrimaryKineticLibrary, just with a new (and more appropriate) * name. RMG will automatically include every species and reaction contained * in a Seed Mechanism. Furthermore, the user has the option to pass multiple * Seed Mechanisms to RMG. In the event of a duplicate species/reaction, RMG * will use the first instance it finds (i.e. the order of the Seed Mechanisms * listed in the condition.txt file is important). * * MRH 9-Jun-2009 */ /* * Comments from old PrimaryKineticLibrary: * * This is the primary reaction set that any reaction system has to include * into its model. For example, in combustion system, we build a primary small * molecule reaction set, and every combustion/oxidation system should include * such a primary reaction library. The reaction / rates are basically from Leeds * methane oxidation mechanism. */ public class SeedMechanism { protected String name; protected LinkedHashSet reactionSet = new LinkedHashSet(); protected HashMap speciesSet = new HashMap(); private boolean generateReactions = false; public LinkedList allPdepNetworks = new LinkedList(); // Constructors public SeedMechanism(String p_mechName, String p_directoryPath, boolean p_generateReactions, boolean p_fromRestart) throws IOException { name = p_mechName; generateReactions = p_generateReactions; if ( p_directoryPath == null) throw new NullPointerException("RMG does not recognize Seed Mechanism directory path: Value is null"); try { read(p_directoryPath,p_fromRestart,p_mechName); } catch (IOException e) { throw new IOException("Error in reading Seed Mechanism: " + p_mechName + '\n' + e.getMessage()); } } public SeedMechanism() { } public void appendSeedMechanism(String new_mechName, String new_directoryPath, boolean p_generateReactions, boolean p_fromRestart) throws IOException { if (p_generateReactions) setGenerateReactions(p_generateReactions); setName(name + "/" + new_mechName); try { read(new_directoryPath,p_fromRestart,new_mechName); } catch (IOException e) { throw new IOException("Error in reading Seed Mechanism: " + new_mechName + '\n' + e.getMessage()); } } public LinkedHashSet getSpeciesSet() { return new LinkedHashSet(speciesSet.values()); } public void read(String p_directoryName, boolean p_fromRestart, String seedMechName) throws IOException { Logger.info("Reading seed mechanism from directory " + p_directoryName); HashMap localSpecies = null; LinkedHashSet localReactions = null; try { if (!p_directoryName.endsWith("/")) p_directoryName = p_directoryName + "/"; if (!p_fromRestart) { String speciesFile = p_directoryName + "species.txt"; String reactionFile = p_directoryName + "reactions.txt"; String pdepreactionFile = p_directoryName + "pdepreactions.txt"; speciesSet.putAll(readSpecies(speciesFile,seedMechName,"Seed Mechanism: ")); reactionSet.addAll(readReactions(reactionFile,seedMechName,speciesSet,"Seed Mechanism: ",true)); reactionSet.addAll(readPdepReactions(pdepreactionFile,seedMechName,speciesSet,"Seed Mechanism: ",true)); } else { String speciesFile = p_directoryName + "coreSpecies.txt"; String pdepreactionFile = p_directoryName + "pdepreactions.txt"; speciesSet.putAll(readSpecies(speciesFile,seedMechName,"Seed Mechanism: ")); reactionSet.addAll(readPdepReactions(pdepreactionFile,seedMechName,speciesSet,"Seed Mechanism: ",true)); } return; } catch (Exception e) { throw new IOException("RMG cannot read entire Seed Mechanism: " + p_directoryName + "\n" + e.getMessage()); } } public LinkedHashSet readReactions(String p_reactionFileName, String p_name, HashMap allSpecies, String source, boolean pkl) throws IOException { LinkedHashSet localReactions = new LinkedHashSet(); try { FileReader in = new FileReader(p_reactionFileName); BufferedReader data = new BufferedReader(in); double[] multipliers = parseReactionRateUnits(data); double A_multiplier = multipliers[0]; double E_multiplier = multipliers[1]; String line = ChemParser.readMeaningfulLine(data, true); read: while (line != null) { Reaction r; try { r = ChemParser.parseArrheniusReaction(allSpecies, line, A_multiplier, E_multiplier); r.setKineticsSource(source+ p_name,0); r.setKineticsComments(" ",0); if (pkl) { r.setIsFromPrimaryKineticLibrary(true); (r.getKinetics())[0].setFromPrimaryKineticLibrary(true); } } catch (InvalidReactionFormatException e) { throw new InvalidReactionFormatException(line + ": " + e.getMessage()); } if (r == null) throw new InvalidReactionFormatException(line); localReactions = updateReactionList(r,localReactions,true); line = ChemParser.readMeaningfulLine(data, true); } in.close(); return localReactions; } catch (Exception e) { Logger.error("RMG did not read the following " + source + p_name + " file: " + p_reactionFileName + " because " + e.getMessage() ); Logger.logStackTrace(e); return null; } } public HashMap readSpecies(String p_speciesFileName, String p_name, String source) throws IOException { HashMap localSpecies = new HashMap(); try { FileReader in = new FileReader(p_speciesFileName); BufferedReader data = new BufferedReader(in); // step 1: read in structure String line = ChemParser.readMeaningfulLine(data, true); read: while (line != null) { // GJB allow unreactive species StringTokenizer st = new StringTokenizer(line); String name = st.nextToken().trim(); boolean IsReactive = true; if (st.hasMoreTokens()) { String reactive = st.nextToken().trim(); if ( reactive.equalsIgnoreCase("unreactive") ) IsReactive = false; } Graph graph; try { graph = ChemParser.readChemGraph(data); if (graph == null) throw new IOException("Graph was null"); } catch (IOException e) { throw new InvalidChemGraphException("Cannot read species '" + name + "': " + e.getMessage()); } ChemGraph cg = ChemGraph.make(graph); Species spe = Species.make(name, cg); // GJB: Turn off reactivity if necessary, but don't let code turn it on // again if was already set as unreactive from input file if(IsReactive==false) spe.setReactivity(IsReactive); localSpecies.put(name, spe); line = ChemParser.readMeaningfulLine(data, true); } in.close(); return localSpecies; } catch (Exception e) { throw new IOException("RMG cannot read the \"species.txt\" file in the " + source + p_name + "\n" + e.getMessage()); } } public LinkedHashSet readPdepReactions(String pdepFileName, String p_name, HashMap allSpecies, String source, boolean pkl) throws IOException { LinkedHashSet localReactions = new LinkedHashSet(); LinkedList pdepNetworks = getPDepNetworks(); try { FileReader in = new FileReader(pdepFileName); BufferedReader data = new BufferedReader(in); double[] multipliers = parseReactionRateUnits(data); double A_multiplier = multipliers[0]; double E_multiplier = multipliers[1]; String nextLine = ChemParser.readMeaningfulLine(data, true); read: while (nextLine != null) { Reaction r; try { r = ChemParser.parseArrheniusReaction(allSpecies, nextLine, A_multiplier, E_multiplier); } catch (InvalidReactionFormatException e) { throw new InvalidReactionFormatException(nextLine + ": " + e.getMessage()); } if (r == null) throw new InvalidReactionFormatException(nextLine); /* * Read the next line and determine what to do based on the * presence/absence of keywords */ nextLine = ChemParser.readMeaningfulLine(data, true); boolean continueToReadRxn = true; // Initialize all of the possible pdep variables HashMap thirdBodyList = new HashMap(); UncertainDouble uA = new UncertainDouble(0.0, 0.0, "Adder"); UncertainDouble un = new UncertainDouble(0.0, 0.0, "Adder"); UncertainDouble uE = new UncertainDouble(0.0, 0.0, "Adder"); ArrheniusKinetics low = new ArrheniusKinetics(uA, un, uE, "", 0, "", ""); double a = 0.0; double T3star = 0.0; double Tstar = 0.0; double T2star = 0.0; boolean troe7 = false; int numPLOGs = 0; PDepArrheniusKinetics pdepkineticsPLOG = new PDepArrheniusKinetics(numPLOGs); /* * When reading in the auxillary information for the pdep reactions, * let's not assume the order is fixed (i.e. third-bodies and * their efficiencies, then lindemann, then troe) * The order of the if statement is important as the "troe" and * "low" lines will also contain a "/"; thus, the elseif contains * "/" needs to be last. */ /* * Additions by MRH on 26JUL2010: * Allowing RMG to read-in PLOG and CHEB formatting */ while (continueToReadRxn) { if (nextLine == null) { continueToReadRxn = false; } else if (nextLine.toLowerCase().contains("troe")) { // read in troe parameters StringTokenizer st = new StringTokenizer(nextLine, "/"); String temp = st.nextToken().trim(); // TROE String troeString = st.nextToken().trim(); // List of troe parameters st = new StringTokenizer(troeString); int n = st.countTokens(); if (n != 3 && n != 4) throw new InvalidKineticsFormatException("Troe parameter number = "+n + " for reaction: " + r.toString()); a = Double.parseDouble(st.nextToken().trim()); T3star = Double.parseDouble(st.nextToken().trim()); Tstar = Double.parseDouble(st.nextToken().trim()); if (st.hasMoreTokens()) { troe7 = true; T2star = Double.parseDouble(st.nextToken().trim()); } nextLine = ChemParser.readMeaningfulLine(data, true); } else if (nextLine.toLowerCase().contains("low")) { // read in lindemann parameters StringTokenizer st = new StringTokenizer(nextLine, "/"); String temp = st.nextToken().trim(); // LOW String lowString = st.nextToken().trim(); // Modified Arrhenius parameters /* * MRH 17Feb2010: * The units of the k_zero (LOW) Arrhenius parameters are different from the units of * k_inf Arrhenius parameters by a factor of cm3/mol, hence the getReactantNumber()+1 */ low = ChemParser.parseSimpleArrheniusKinetics(lowString, A_multiplier, E_multiplier, r.getReactantNumber()+1); nextLine = ChemParser.readMeaningfulLine(data, true); } else if (nextLine.contains("CHEB")) { // Read in the Tmin/Tmax and Pmin/Pmax information StringTokenizer st_cheb = new StringTokenizer(nextLine,"/"); String nextToken = st_cheb.nextToken(); // Should be TCHEB or PCHEB StringTokenizer st_minmax = new StringTokenizer(st_cheb.nextToken()); double Tmin = 0.0; double Tmax = 0.0; double Pmin = 0.0; double Pmax = 0.0; if (nextToken.trim().equals("TCHEB")) { Tmin = Double.parseDouble(st_minmax.nextToken()); Tmax = Double.parseDouble(st_minmax.nextToken()); } else { Pmin = Double.parseDouble(st_minmax.nextToken()); Pmax = Double.parseDouble(st_minmax.nextToken()); } nextToken = st_cheb.nextToken(); // Should be PCHEB or TCHEB st_minmax = new StringTokenizer(st_cheb.nextToken()); if (nextToken.trim().equals("TCHEB")) { Tmin = Double.parseDouble(st_minmax.nextToken()); Tmax = Double.parseDouble(st_minmax.nextToken()); } else { Pmin = Double.parseDouble(st_minmax.nextToken()); Pmax = Double.parseDouble(st_minmax.nextToken()); } // Read in the N/M values (number of polynomials in the Temp and Press domain) nextLine = ChemParser.readMeaningfulLine(data, true); st_cheb = new StringTokenizer(nextLine,"/"); nextToken = st_cheb.nextToken(); // Should be CHEB st_minmax = new StringTokenizer(st_cheb.nextToken()); int numN = Integer.parseInt(st_minmax.nextToken()); int numM = Integer.parseInt(st_minmax.nextToken()); // Read in the coefficients nextLine = ChemParser.readMeaningfulLine(data, true); double[] unorderedChebyCoeffs = new double[numN*numM]; int chebyCoeffCounter = 0; while (nextLine != null && nextLine.contains("CHEB")) { st_cheb = new StringTokenizer(nextLine,"/"); nextToken = st_cheb.nextToken(); // Should be CHEB st_minmax = new StringTokenizer(st_cheb.nextToken()); while (st_minmax.hasMoreTokens()) { unorderedChebyCoeffs[chebyCoeffCounter] = Double.parseDouble(st_minmax.nextToken()); ++chebyCoeffCounter; } nextLine = ChemParser.readMeaningfulLine(data, true); } // Order the chebyshev coefficients double[][] chebyCoeffs = new double[numN][numM]; for (int numRows=0; numRows<numN; numRows++) { for (int numCols=0; numCols<numM; numCols++) { chebyCoeffs[numRows][numCols] = unorderedChebyCoeffs[numM*numRows+numCols]; } } // Make the ChebyshevPolynomials, PDepReaction, and add to list of PDepReactions ChebyshevPolynomials coeffs = new ChebyshevPolynomials( numN,new Temperature(Tmin,"K"),new Temperature(Tmax,"K"), numM,new Pressure(Pmin,"bar"),new Pressure(Pmax,"bar"), chebyCoeffs); PDepIsomer reactants = new PDepIsomer(r.getStructure().getReactantList()); PDepIsomer products = new PDepIsomer(r.getStructure().getProductList()); PDepRateConstant pdepRC = new PDepRateConstant(coeffs); PDepReaction pdeprxn = new PDepReaction(reactants,products,pdepRC); allPdepNetworks.add(pdeprxn); continueToReadRxn = false; } else if (nextLine.contains("PLOG")) { while (nextLine != null && nextLine.contains("PLOG")) { // Increase the PLOG counter ++numPLOGs; // Store the previous PLOG information in temporary arrays Pressure[] previousPressures = new Pressure[numPLOGs]; ArrheniusKinetics[] previousKinetics = new ArrheniusKinetics[numPLOGs]; for (int previousNumPLOG=0; previousNumPLOG<numPLOGs-1; ++previousNumPLOG) { previousPressures[previousNumPLOG] = pdepkineticsPLOG.getPressure(previousNumPLOG); previousKinetics[previousNumPLOG] = pdepkineticsPLOG.getKinetics(previousNumPLOG); } // Read in the new PLOG information, and add this to the temporary array PDepArrheniusKinetics newpdepkinetics = parsePLOGline(nextLine); previousPressures[numPLOGs-1] = newpdepkinetics.getPressure(0); previousKinetics[numPLOGs-1] = newpdepkinetics.getKinetics(0); // Re-initialize pdepkinetics and populate with stored information pdepkineticsPLOG = new PDepArrheniusKinetics(numPLOGs); pdepkineticsPLOG.setPressures(previousPressures); pdepkineticsPLOG.setRateCoefficients(previousKinetics); // Read the next line nextLine = ChemParser.readMeaningfulLine(data, true); } // Make the PDepReaction PDepIsomer reactants = new PDepIsomer(r.getStructure().getReactantList()); PDepIsomer products = new PDepIsomer(r.getStructure().getProductList()); PDepRateConstant pdepRC = new PDepRateConstant(pdepkineticsPLOG); PDepReaction pdeprxn = new PDepReaction(reactants,products,pdepRC); // Add to the list of PDepReactions allPdepNetworks.add(pdeprxn); // Re-initialize the pdepkinetics variable numPLOGs = 0; pdepkineticsPLOG = new PDepArrheniusKinetics(numPLOGs); continueToReadRxn = false; } else if (nextLine.contains("/")) { // read in third body colliders + efficiencies thirdBodyList.putAll(ChemParser.parseThirdBodyList(nextLine,allSpecies)); nextLine = ChemParser.readMeaningfulLine(data, true); } else { // the nextLine is a "new" reaction, hence we need to exit the while loop continueToReadRxn = false; } } /* * Make the pdep reaction, according to which parameters * are present */ if ((a==0.0) && (T3star==0.0) && (Tstar==0.0)) { // Not a troe reaction if (low.getAValue() == 0.0) { // thirdbody reaction ThirdBodyReaction tbr = ThirdBodyReaction.make(r,thirdBodyList); tbr.setKineticsSource(source+ p_name,0); tbr.setKineticsComments(" ",0); if (pkl) { tbr.setIsFromPrimaryKineticLibrary(true); (tbr.getKinetics())[0].setFromPrimaryKineticLibrary(true); } localReactions.add(tbr); Reaction reverse = tbr.getReverseReaction(); if (reverse != null) localReactions.add(reverse); } else { // lindemann reaction LindemannReaction tbr = LindemannReaction.make(r,thirdBodyList,low); tbr.setKineticsSource(source+ p_name,0); tbr.setKineticsComments(" ",0); if (pkl) { tbr.setIsFromPrimaryKineticLibrary(true); (tbr.getKinetics())[0].setFromPrimaryKineticLibrary(true); } localReactions.add(tbr); Reaction reverse = tbr.getReverseReaction(); if (reverse != null) localReactions.add(reverse); } } else { // troe reaction TROEReaction tbr = TROEReaction.make(r,thirdBodyList, low, a, T3star, Tstar, troe7, T2star); tbr.setKineticsSource(source+ p_name,0); tbr.setKineticsComments(" ",0); if (pkl) { tbr.setIsFromPrimaryKineticLibrary(true); (tbr.getKinetics())[0].setFromPrimaryKineticLibrary(true); } localReactions.add(tbr); Reaction reverse = tbr.getReverseReaction(); if (reverse != null) localReactions.add(reverse); } } in.close(); return localReactions; } catch (Exception e) { /* * 25Jun2009-MRH: When reading the Primary Kinetic Library, we should not require the user to supply * troe reactions. In the instance that no "troeReactions.txt" file exists, inform * user of this but continue simulation. */ System.err.println("RMG could not find, or read in its entirety, the pressure-dependent reactions file (pdepreactions.txt)" + "\n\tin the " + source + p_name + "\n" + e.getMessage()); return null; } } public int size() { return speciesSet.size(); } public String getName() { return name; } public void setName(String p_name) { name = p_name; } public LinkedHashSet getReactionSet() { return reactionSet; } public boolean shouldGenerateReactions() { return generateReactions; } public void setGenerateReactions(boolean generateReactions) { this.generateReactions = generateReactions; } public double[] parseReactionRateUnits(BufferedReader data) { double[] multipliers = new double[2]; String line = ChemParser.readMeaningfulLine(data, true); if (line.startsWith("Unit")) { line = ChemParser.readMeaningfulLine(data, true); unit: while(!(line.startsWith("Reaction"))) { if (line.startsWith("A")) { StringTokenizer st = new StringTokenizer(line); String temp = st.nextToken(); String unit = st.nextToken().trim(); if (unit.compareToIgnoreCase("mol/cm3/s") == 0) { multipliers[0] = 1; } else if (unit.compareToIgnoreCase("mol/liter/s") == 0) { multipliers[0] = 1e-3; } else if (unit.compareToIgnoreCase("molecule/cm3/s") == 0) { multipliers[0] = 6.022e23; } } else if (line.startsWith("E")) { StringTokenizer st = new StringTokenizer(line); String temp = st.nextToken(); String unit = st.nextToken().trim(); if (unit.compareToIgnoreCase("kcal/mol") == 0) { multipliers[1] = 1; } else if (unit.compareToIgnoreCase("cal/mol") == 0) { multipliers[1] = 1e-3; } else if (unit.compareToIgnoreCase("kJ/mol") == 0) { multipliers[1] = 1/4.186; } else if (unit.compareToIgnoreCase("J/mol") == 0) { multipliers[1] = 1/4186; } else if (unit.compareToIgnoreCase("Kelvin") == 0) { multipliers[1] = 1.987e-3; } } line = ChemParser.readMeaningfulLine(data, true); } } return multipliers; } public LinkedHashSet updateReactionList(Reaction r, LinkedHashSet listOfRxns, boolean generateReverse) { Iterator allRxnsIter = listOfRxns.iterator(); boolean foundRxn = false; while (allRxnsIter.hasNext()) { Reaction old = (Reaction)allRxnsIter.next(); if (old.equals(r)) { old.addAdditionalKinetics(r.getKinetics()[0],1); foundRxn = true; break; } } if (!foundRxn) { listOfRxns.add(r); if (generateReverse) { Reaction reverse = r.getReverseReaction(); if (reverse != null) { listOfRxns.add(reverse); } } } return listOfRxns; } public PDepArrheniusKinetics parsePLOGline(String line) { PDepRateConstant pdepk = new PDepRateConstant(); // Delimit the PLOG line by "/" StringTokenizer st_slash = new StringTokenizer(line,"/"); String dummyString = st_slash.nextToken(); // Delimit the data of the PLOG line by whitespace StringTokenizer st = new StringTokenizer(st_slash.nextToken()); // If reading a chemkin plog line, pressure MUST be in atmospheres Pressure p = new Pressure(Double.parseDouble(st.nextToken().trim()),"atm"); UncertainDouble dA = new UncertainDouble(Double.parseDouble(st.nextToken().trim()),0.0,"A"); UncertainDouble dn = new UncertainDouble(Double.parseDouble(st.nextToken().trim()),0.0,"A"); double Ea = Double.parseDouble(st.nextToken().trim()); // If reading a chemkin plog line, Ea MUST be in cal/mol Ea = Ea / 1000; UncertainDouble dE = new UncertainDouble(Ea,0.0,"A"); ArrheniusKinetics k = new ArrheniusKinetics(dA, dn, dE, "", 1, "", ""); PDepArrheniusKinetics pdepAK = new PDepArrheniusKinetics(1); pdepAK.setKinetics(0, p, k); return pdepAK; } public LinkedList getPDepNetworks() { return allPdepNetworks; } }
Automatically change indentation in SeedMechanism.java (needed re-doing)
source/RMG/jing/rxnSys/SeedMechanism.java
Automatically change indentation in SeedMechanism.java
Java
mit
e6afbad388c0e0e5feacbaba76c22aac479724ae
0
sdl/Testy,sdl/Testy,sdl/Testy,sdl/Testy
package com.sdl.selenium.extjs6.grid; import com.sdl.selenium.web.SearchType; import com.sdl.selenium.web.WebLocator; import com.sdl.selenium.web.table.Table; import com.sdl.selenium.web.utils.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Grid extends Table implements Scrollable { private static final Logger LOGGER = LoggerFactory.getLogger(Grid.class); public Grid() { setClassName("Grid"); setBaseCls("x-grid"); setTag("*"); WebLocator header = new WebLocator().setClasses("x-title").setRoot("//"); setTemplateTitle(new WebLocator(header)); } public Grid(WebLocator container) { this(); setContainer(container); } /** * <pre>{@code * Grid grid = new Grid().setHeaders("Company", "Price", "Change"); * }</pre> * * @param headers grid's headers in order * @param <T> element which extended the Grid * @return this Grid */ public <T extends Table> T setHeaders(final String... headers) { List<WebLocator> list = new ArrayList<>(); for (int i = 0; i < headers.length; i++) { WebLocator headerEL = new WebLocator(this).setTag("*[" + (i + 1) + "]").setClasses("x-column-header"). setText(headers[i], SearchType.DEEP_CHILD_NODE_OR_SELF, SearchType.EQUALS); list.add(headerEL); } setChildNodes(list.toArray(new WebLocator[list.size()])); return (T) this; } @Override public Row getRow(int rowIndex) { return new Row(this, rowIndex).setInfoMessage("-Row"); } @Override public Row getRow(String searchElement) { return new Row(this, searchElement, SearchType.EQUALS).setInfoMessage("-Row"); } @Override public Row getRow(String searchElement, SearchType... searchTypes) { return new Row(this, searchElement, searchTypes).setInfoMessage("-Row"); } public Row getRow(Cell... byCells) { return new Row(this, byCells).setInfoMessage("-Row"); } public Row getRow(int indexRow, Cell... byCells) { return new Row(this, indexRow, byCells).setInfoMessage("-Row"); } @Override public Cell getCell(int rowIndex, int columnIndex) { Row row = getRow(rowIndex); return new Cell(row, columnIndex).setInfoMessage("cell - Table"); } @Override public Cell getCell(String searchElement, SearchType... searchTypes) { Row row = new Row(this); return new Cell(row).setText(searchElement, searchTypes); } public Cell getCell(int rowIndex, int columnIndex, String text) { Row row = getRow(rowIndex); return new Cell(row, columnIndex, text, SearchType.EQUALS); } public Cell getCell(String searchElement, String columnText, SearchType... searchTypes) { Row row = getRow(searchElement, SearchType.CONTAINS); return new Cell(row).setText(columnText, searchTypes); } @Override public Cell getCell(String searchElement, int columnIndex, SearchType... searchTypes) { return new Cell(new Row(this, searchElement, searchTypes), columnIndex); } public Cell getCell(int columnIndex, Cell... byCells) { return new Cell(getRow(byCells), columnIndex); } public Cell getCell(int columnIndex, String text, Cell... byCells) { return new Cell(getRow(byCells), columnIndex, text, SearchType.EQUALS); } public boolean waitToActivate(int seconds) { String info = toString(); int count = 0; boolean hasMask; while ((hasMask = hasMask()) && (count < seconds)) { count++; LOGGER.info("waitToActivate:" + (seconds - count) + " seconds; " + info); Utils.sleep(900); } return !hasMask; } private boolean hasMask() { WebLocator mask = new WebLocator(this).setClasses("x-mask").setElPathSuffix("style", "not(contains(@style, 'display: none'))").setAttribute("aria-hidden", "false").setInfoMessage("Mask"); return mask.waitToRender(500, false); } @Override public boolean waitToPopulate(int seconds) { Row row = getRow(1).setVisibility(true).setRoot("//..//").setInfoMessage("first Row"); WebLocator body = new WebLocator(this).setClasses("x-grid-header-ct"); // TODO see if must add for all rows row.setContainer(body); return row.waitToRender(seconds * 1000L); } public List<String> getHeaders() { List<String> headers = new ArrayList<>(); WebLocator header = new WebLocator(this).setClasses("x-grid-header-ct"); String headerText = header.getText(); if (headerText == null || "".equals(headerText)) { headerText = header.getText(true); } Collections.addAll(headers, headerText.trim().split("\n")); return headers; } @Override public List<List<String>> getCellsText(int... excludedColumns) { Row rowsEl = new Row(this); Row rowEl = new Row(this, 1); Cell columnsEl = new Cell(rowEl); int rows = rowsEl.size(); int columns = columnsEl.size(); List<Integer> columnsList = getColumns(columns, excludedColumns); if (rows <= 0) { return null; } else { List<List<String>> listOfList = new ArrayList<>(); boolean canRead = true; String id = ""; do { for (int i = 1; i <= rows; ++i) { if (canRead) { List<String> list = new ArrayList<>(); for (int j : columnsList) { list.add(this.getCell(i, j).getText(true)); } listOfList.add(list); } else { String currentId = new Row(this, i).getAttributeId(); if (!"".equals(id) && id.equals(currentId)) { canRead = true; } } } if (isScrollBottom()) { break; } id = new Row(this, rows).getAttributeId(); scrollPageDownInTree(); canRead = false; } while (true); return listOfList; } } }
src/main/java/com/sdl/selenium/extjs6/grid/Grid.java
package com.sdl.selenium.extjs6.grid; import com.sdl.selenium.web.SearchType; import com.sdl.selenium.web.WebLocator; import com.sdl.selenium.web.table.Table; import com.sdl.selenium.web.utils.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Grid extends Table implements Scrollable { private static final Logger LOGGER = LoggerFactory.getLogger(Grid.class); public Grid() { setClassName("Grid"); setBaseCls("x-grid"); setTag("*"); WebLocator header = new WebLocator().setClasses("x-title").setRoot("//"); setTemplateTitle(new WebLocator(header)); } public Grid(WebLocator container) { this(); setContainer(container); } /** * <pre>{@code * Grid grid = new Grid().setHeaders("Company", "Price", "Change"); * }</pre> * * @param headers grid's headers in order * @param <T> element which extended the Grid * @return this Grid */ public <T extends Table> T setHeaders(final String... headers) { List<WebLocator> list = new ArrayList<>(); for (int i = 0; i < headers.length; i++) { WebLocator headerEL = new WebLocator(this).setTag("*[" + (i + 1) + "]").setClasses("x-column-header"). setText(headers[i], SearchType.DEEP_CHILD_NODE_OR_SELF, SearchType.EQUALS); list.add(headerEL); } setChildNodes(list.toArray(new WebLocator[list.size()])); return (T) this; } @Override public Row getRow(int rowIndex) { return new Row(this, rowIndex).setInfoMessage("-Row"); } @Override public Row getRow(String searchElement) { return new Row(this, searchElement, SearchType.EQUALS).setInfoMessage("-Row"); } @Override public Row getRow(String searchElement, SearchType... searchTypes) { return new Row(this, searchElement, searchTypes).setInfoMessage("-Row"); } public Row getRow(Cell... byCells) { return new Row(this, byCells).setInfoMessage("-Row"); } public Row getRow(int indexRow, Cell... byCells) { return new Row(this, indexRow, byCells).setInfoMessage("-Row"); } @Override public Cell getCell(int rowIndex, int columnIndex) { Row row = getRow(rowIndex); return new Cell(row, columnIndex).setInfoMessage("cell - Table"); } @Override public Cell getCell(String searchElement, SearchType... searchTypes) { Row row = new Row(this); return new Cell(row).setText(searchElement, searchTypes); } public Cell getCell(int rowIndex, int columnIndex, String text) { Row row = getRow(rowIndex); return new Cell(row, columnIndex, text, SearchType.EQUALS); } public Cell getCell(String searchElement, String columnText, SearchType... searchTypes) { Row row = getRow(searchElement, SearchType.CONTAINS); return new Cell(row).setText(columnText, searchTypes); } @Override public Cell getCell(String searchElement, int columnIndex, SearchType... searchTypes) { return new Cell(new Row(this, searchElement, searchTypes), columnIndex); } public Cell getCell(int columnIndex, Cell... byCells) { return new Cell(getRow(byCells), columnIndex); } public Cell getCell(int columnIndex, String text, Cell... byCells) { return new Cell(getRow(byCells), columnIndex, text, SearchType.EQUALS); } public boolean waitToActivate(int seconds) { String info = toString(); int count = 0; boolean hasMask; while ((hasMask = hasMask()) && (count < seconds)) { count++; LOGGER.info("waitToActivate:" + (seconds - count) + " seconds; " + info); Utils.sleep(900); } return !hasMask; } private boolean hasMask() { WebLocator mask = new WebLocator(this).setClasses("x-mask").setElPathSuffix("style", "not(contains(@style, 'display: none'))").setAttribute("aria-hidden", "false").setInfoMessage("Mask"); return mask.waitToRender(500, false); } @Override public boolean waitToPopulate(int seconds) { Row row = getRow(1).setVisibility(true).setRoot("//..//").setInfoMessage("first Row"); WebLocator body = new WebLocator(this).setClasses("x-grid-header-ct"); // TODO see if must add for all rows row.setContainer(body); return row.waitToRender(seconds * 1000L); } public List<String> getHeaders() { List<String> headers = new ArrayList<>(); WebLocator header = new WebLocator(this).setClasses("x-grid-header-ct"); String headerText = header.getText(); if (headerText == null || "".equals(headerText)) { headerText = header.getText(true); } Collections.addAll(headers, headerText.trim().split("\n")); return headers; } @Override public List<List<String>> getCellsText(int... excludedColumns) { Row rowsEl = new Row(this); Row rowEl = new Row(this, 1); Cell columnsEl = new Cell(rowEl); int rows = rowsEl.size(); int columns = columnsEl.size(); List<Integer> columnsList = getColumns(columns, excludedColumns); if (rows <= 0) { return null; } else { List<List<String>> listOfList = new ArrayList<>(); for (int i = 1; i <= rows; ++i) { List<String> list = new ArrayList<>(); for (int j : columnsList) { list.add(this.getCell(i, j).getText(true)); } listOfList.add(list); } return listOfList; } } }
improvement getCellsText(int... excludedColumns) in Grid
src/main/java/com/sdl/selenium/extjs6/grid/Grid.java
improvement getCellsText(int... excludedColumns) in Grid
Java
mit
0b3e09407f65ae52da1312dea03dc2cfad274d1c
0
zalando/nakadi,zalando/nakadi
package org.zalando.nakadi.domain; public class PartitionBaseStatisticsImpl implements PartitionBaseStatistics { private final Timeline timeline; private final String partition; public PartitionBaseStatisticsImpl(final Timeline timeline, final String partition) { this.timeline = timeline; this.partition = partition; } @Override public Timeline getTimeline() { return timeline; } @Override public String getTopic() { return timeline.getTopic(); } @Override public String getPartition() { return partition; } }
src/main/java/org/zalando/nakadi/domain/PartitionBaseStatisticsImpl.java
package org.zalando.nakadi.domain; public class PartitionBaseStatisticsImpl implements PartitionBaseStatistics { private Timeline timeline; private String partition; public PartitionBaseStatisticsImpl(final Timeline timeline, final String partition) { this.timeline = timeline; this.partition = partition; } @Override public Timeline getTimeline() { return timeline; } @Override public String getTopic() { return timeline.getTopic(); } @Override public String getPartition() { return partition; } }
ARUHA-769: Added final
src/main/java/org/zalando/nakadi/domain/PartitionBaseStatisticsImpl.java
ARUHA-769: Added final
Java
mit
db8a2f8c19bb06f162de70eb2609d41a0fc70239
0
mobilejazz/mobilejazz-android-utilities
package cat.mobilejazz.utilities; public class ObjectUtils { public static boolean equals(Object a, Object b) { if (a == null) { return b == null; } else { return a.equals(b); } } public static int hashCode(Object a) { if (a == null) { return 0; } else { return a.hashCode(); } } }
src/cat/mobilejazz/utilities/ObjectUtils.java
package cat.mobilejazz.utilities; public class ObjectUtils { public static boolean equals(Object a, Object b) { if (a == null) { return b == null; } else { return a.equals(b); } } }
added a hashCode method that can deal with null objects
src/cat/mobilejazz/utilities/ObjectUtils.java
added a hashCode method that can deal with null objects
Java
mit
57fc9b7fb5dde8ce01e1176b567dc607e2a338ea
0
SolarCactus/ARKCraft-Code,LewisMcReu/ARKCraft-Code,tterrag1098/ARKCraft-Code
package com.arkcraft.mod.core.entity.passive; import net.minecraft.entity.EntityAgeable; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.EntityAIFollowOwner; import net.minecraft.entity.ai.EntityAIFollowParent; import net.minecraft.entity.ai.EntityAILookIdle; import net.minecraft.entity.ai.EntityAIMate; import net.minecraft.entity.ai.EntityAISwimming; import net.minecraft.entity.ai.EntityAITempt; import net.minecraft.entity.ai.EntityAIWander; import net.minecraft.entity.ai.EntityAIWatchClosest; import net.minecraft.entity.passive.EntityTameable; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.pathfinding.PathNavigateGround; import net.minecraft.world.World; import com.arkcraft.mod.core.GlobalAdditions; public class EntityBrontosaurus extends EntityTameable { public EntityBrontosaurus(World w) { super(w); this.setSize(4.5F, 4.5F); ((PathNavigateGround)this.getNavigator()).func_179690_a(true); this.tasks.taskEntries.clear(); int p = 0; this.tasks.addTask(++p, new EntityAISwimming(this)); this.tasks.addTask(++p, new EntityAIWander(this, 1.0D)); this.tasks.addTask(++p, new EntityAILookIdle(this)); this.tasks.addTask(++p, new EntityAIMate(this, 1.0D)); this.tasks.addTask(++p, new EntityAITempt(this, 1.0D, GlobalAdditions.narcoBerry, false)); this.tasks.addTask(++p, new EntityAIFollowParent(this, 1.1D)); this.tasks.addTask(++p, new EntityAIWander(this, 1.0D)); this.tasks.addTask(++p, new EntityAIFollowOwner(this, 1.0D, 8.0F, 5.0F)); this.tasks.addTask(++p, new EntityAIWatchClosest(this, EntityPlayer.class, 6.0F)); } @Override protected void applyEntityAttributes() { super.applyEntityAttributes(); this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(30.0D); this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.23000000417232513D); } @Override public EntityAgeable createChild(EntityAgeable ageable) { return new EntityBrontosaurus(this.worldObj); } @Override public void setTamed(boolean tamed) { super.setTamed(tamed); if (tamed) { this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(40.0D); this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.23000000417232513D); //zombie move speed } } @Override protected boolean canDespawn() { return !this.isTamed() && this.ticksExisted > 2400; } }
src/main/java/com/arkcraft/mod/core/entity/passive/EntityBrontosaurus.java
package com.arkcraft.mod.core.entity.passive; import net.minecraft.entity.EntityAgeable; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.EntityAIFollowOwner; import net.minecraft.entity.ai.EntityAIFollowParent; import net.minecraft.entity.ai.EntityAILookIdle; import net.minecraft.entity.ai.EntityAIMate; import net.minecraft.entity.ai.EntityAISwimming; import net.minecraft.entity.ai.EntityAITempt; import net.minecraft.entity.ai.EntityAIWander; import net.minecraft.entity.ai.EntityAIWatchClosest; import net.minecraft.entity.passive.EntityTameable; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.pathfinding.PathNavigateGround; import net.minecraft.world.World; import com.arkcraft.mod.core.GlobalAdditions; public class EntityBrontosaurus extends EntityTameable { public EntityBrontosaurus(World w) { super(w); this.setSize(4.5F, 4.5F); ((PathNavigateGround)this.getNavigator()).func_179690_a(true); this.tasks.taskEntries.clear(); int p = 0; this.tasks.addTask(++p, new EntityAISwimming(this)); this.tasks.addTask(++p, new EntityAIWander(this, 1.0D)); this.tasks.addTask(++p, new EntityAILookIdle(this)); this.tasks.addTask(++p, new EntityAIMate(this, 1.0D)); this.tasks.addTask(++p, new EntityAITempt(this, 1.0D, GlobalAdditions.narcoBerry, false)); this.tasks.addTask(++p, new EntityAIFollowParent(this, 1.1D)); this.tasks.addTask(++p, new EntityAIWander(this, 1.0D)); this.tasks.addTask(++p, new EntityAIFollowOwner(this, 1.0D, 8.0F, 5.0F)); this.tasks.addTask(++p, new EntityAIWatchClosest(this, EntityPlayer.class, 6.0F)); } @Override protected void applyEntityAttributes() { super.applyEntityAttributes(); this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(30.0D); this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.7D); } @Override public EntityAgeable createChild(EntityAgeable ageable) { return new EntityBrontosaurus(this.worldObj); } @Override public void setTamed(boolean tamed) { super.setTamed(tamed); if (tamed) { this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(10.0D); this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.23000000417232513D); //zombie move speed } } @Override protected boolean canDespawn() { return !this.isTamed() && this.ticksExisted > 2400; } }
Did some stuff w/ the brontosaurus
src/main/java/com/arkcraft/mod/core/entity/passive/EntityBrontosaurus.java
Did some stuff w/ the brontosaurus
Java
epl-1.0
3894b22f97c84674b8349dcc5c7a6272496cf136
0
DavidGutknecht/elexis-3-base,DavidGutknecht/elexis-3-base,DavidGutknecht/elexis-3-base,DavidGutknecht/elexis-3-base,DavidGutknecht/elexis-3-base
/******************************************************************************* * Copyright (c) 2007-2015, D. Lutz and Elexis. * 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: * D. Lutz - initial API and implementation * Gerry Weirich - adapted for 2.1 * Niklaus Giger - small improvements, split into 20 classes * * Sponsors: * Dr. Peter Schönbucher, Luzern ******************************************************************************/ package org.iatrix.widgets; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Hashtable; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.TraverseEvent; import org.eclipse.swt.events.TraverseListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Text; import org.iatrix.Iatrix; import org.iatrix.actions.IatrixEventHelper; import org.iatrix.data.Problem; import org.iatrix.util.Constants; import org.iatrix.util.DateComparator; import org.iatrix.util.NumberComparator; import org.iatrix.util.StatusComparator; import org.iatrix.views.JournalView; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ch.elexis.core.data.activator.CoreHub; import ch.elexis.core.ui.UiDesk; import ch.elexis.data.Konsultation; import ch.elexis.data.Patient; import ch.elexis.data.PersistentObject; import ch.elexis.data.Prescription; import ch.elexis.icpc.Episode; import ch.rgw.tools.StringTool; import ch.rgw.tools.TimeTool; import de.kupzog.ktable.KTable; import de.kupzog.ktable.KTableCellEditor; import de.kupzog.ktable.KTableCellRenderer; import de.kupzog.ktable.KTableModel; import de.kupzog.ktable.renderers.FixedCellRenderer; public class ProblemsTableModel implements KTableModel { private Patient actPatient; private static Logger log = LoggerFactory.getLogger(ProblemsTableModel.class); private MyKTable problemsKTable; private Color highlightColor; private ProblemsTableColorProvider problemsTableColorProvider = new ProblemsTableColorProvider(); private Object[] problems = null; private final Hashtable<Integer, Integer> colWidths = new Hashtable<>(); private final Hashtable<Integer, Integer> rowHeights = new Hashtable<>(); private final KTableCellRenderer fixedRenderer = new FixedCellRenderer(FixedCellRenderer.STYLE_PUSH | FixedCellRenderer.INDICATION_SORT | FixedCellRenderer.INDICATION_FOCUS | FixedCellRenderer.INDICATION_CLICKED); private final KTableCellRenderer textRenderer = new ProblemsTableTextCellRenderer(); private final KTableCellRenderer imageRenderer = new ProblemsTableImageCellRenderer(); private final KTableCellRenderer therapyRenderer = new ProblemsTableTherapyCellRenderer(); private static final DateComparator DATE_COMPARATOR = new DateComparator(); private static final NumberComparator NUMBER_COMPARATOR = new NumberComparator(); private static final StatusComparator STATUS_COMPARATOR = new StatusComparator(); private static Comparator<Problem> comparator = new DateComparator(); private boolean highlightSelection = false; private boolean highlightRow = false; public void refresh(){ // problemsKTable.updateScrollbarVisibility(); problemsKTable.redraw(); } /** * Base class for our cell editors Especially, we need to take care of heartbeat management */ abstract class BaseCellEditor extends KTableCellEditor { @Override public void open(KTable table, int col, int row, Rectangle rect){ org.iatrix.util.Heartbeat.getInstance().setHeartbeatProblemEnabled(false); super.open(table, col, row, rect); } @Override public void close(boolean save){ super.close(save); org.iatrix.util.Heartbeat.getInstance().setHeartbeatProblemEnabled(true); } } /** * Replacement for KTableCellEditorText2 We don't want to have the editor vertically centered * * @author danlutz * */ public class MyKTableCellEditorText2 extends BaseCellEditor { protected Text m_Text; protected KeyAdapter keyListener = new KeyAdapter() { @Override public void keyPressed(KeyEvent e){ try { onKeyPressed(e); } catch (Exception ex) { ex.printStackTrace(); // Do nothing } } }; protected TraverseListener travListener = new TraverseListener() { @Override public void keyTraversed(TraverseEvent e){ onTraverse(e); } }; @Override public void open(KTable table, int col, int row, Rectangle rect){ super.open(table, col, row, rect); m_Text.setText(m_Model.getContentAt(m_Col, m_Row).toString()); m_Text.selectAll(); m_Text.setVisible(true); m_Text.setFocus(); } @Override public void close(boolean save){ if (save) m_Model.setContentAt(m_Col, m_Row, m_Text.getText()); m_Text.removeKeyListener(keyListener); m_Text.removeTraverseListener(travListener); super.close(save); m_Text = null; } @Override protected Control createControl(){ m_Text = new Text(m_Table, SWT.NONE); m_Text.addKeyListener(keyListener); m_Text.addTraverseListener(travListener); return m_Text; } /** * Implement In-Textfield navigation with the keys... * * @see de.kupzog.ktable.KTableCellEditor#onTraverse(org.eclipse.swt.events.TraverseEvent) */ @Override protected void onTraverse(TraverseEvent e){ if (e.keyCode == SWT.ARROW_LEFT) { // handel the event within the text widget! } else if (e.keyCode == SWT.ARROW_RIGHT) { // handle the event within the text widget! } else super.onTraverse(e); } @Override protected void onKeyPressed(KeyEvent e){ if ((e.character == '\r') && ((e.stateMask & SWT.SHIFT) == 0)) { close(true); // move one row below! // if (m_Row<m_Model.getRowCount()) // m_Table.setSelection(m_Col, m_Row+1, true); } else super.onKeyPressed(e); } /* * (non-Javadoc) * * @see de.kupzog.ktable.KTableCellEditor#setContent(java.lang.Object) */ @Override public void setContent(Object content){ m_Text.setText(content.toString()); m_Text.setSelection(content.toString().length()); } } public class KTableDiagnosisCellEditor extends BaseCellEditor { private Combo combo; private final KeyAdapter keyListener = new KeyAdapter() { @Override public void keyPressed(KeyEvent e){ try { onKeyPressed(e); } catch (Exception ex) { // Do nothing } } }; private final TraverseListener travListener = new TraverseListener() { @Override public void keyTraversed(TraverseEvent e){ onTraverse(e); } }; @Override public void open(KTable table, int col, int row, Rectangle rect){ super.open(table, col, row, rect); String text = ""; Object obj = m_Model.getContentAt(m_Col, m_Row); if (obj instanceof Problem) { text = "test"; } combo.setText(text); combo.setVisible(true); combo.setFocus(); } @Override public void close(boolean save){ if (save) m_Model.setContentAt(m_Col, m_Row, combo.getText()); combo.removeKeyListener(keyListener); combo.removeTraverseListener(travListener); combo = null; super.close(save); } @Override protected Control createControl(){ combo = new Combo(m_Table, SWT.DROP_DOWN); combo.addKeyListener(keyListener); combo.addTraverseListener(travListener); return combo; } /** * Implement In-Textfield navigation with the keys... * * @see de.kupzog.ktable.KTableCellEditor#onTraverse(org.eclipse.swt.events.TraverseEvent) */ @Override protected void onTraverse(TraverseEvent e){ if (e.keyCode == SWT.ARROW_LEFT) { // handel the event within the text widget! } else if (e.keyCode == SWT.ARROW_RIGHT) { // handle the event within the text widget! } else super.onTraverse(e); } /* * overridden from superclass */ @Override public void setBounds(Rectangle rect){ super.setBounds(new Rectangle(rect.x, rect.y, rect.width, rect.height)); } /* * (non-Javadoc) * * @see de.kupzog.ktable.KTableCellEditor#setContent(java.lang.Object) */ @Override public void setContent(Object content){ combo.setText(content.toString()); } } public class KTableTherapyCellEditor extends BaseCellEditor { private Text m_Text; private final KeyAdapter keyListener = new KeyAdapter() { @Override public void keyPressed(KeyEvent e){ try { onKeyPressed(e); } catch (Exception ex) { // Do nothing } } }; private final TraverseListener travListener = new TraverseListener() { @Override public void keyTraversed(TraverseEvent e){ onTraverse(e); } }; @Override public void open(KTable table, int col, int row, Rectangle rect){ super.open(table, col, row, rect); String text = ""; Object obj = m_Model.getContentAt(m_Col, m_Row); if (obj instanceof Problem) { Problem problem = (Problem) obj; text = problem.getProcedere(); } m_Text.setText(PersistentObject.checkNull(text)); m_Text.selectAll(); m_Text.setVisible(true); m_Text.setFocus(); } @Override public void close(boolean save){ if (save) m_Model.setContentAt(m_Col, m_Row, m_Text.getText()); m_Text.removeKeyListener(keyListener); m_Text.removeTraverseListener(travListener); m_Text = null; super.close(save); } @Override protected Control createControl(){ m_Text = new Text(m_Table, SWT.MULTI | SWT.V_SCROLL); m_Text.addKeyListener(keyListener); m_Text.addTraverseListener(travListener); return m_Text; } /** * Implement In-Textfield navigation with the keys... * * @see de.kupzog.ktable.KTableCellEditor#onTraverse(org.eclipse.swt.events.TraverseEvent) */ @Override protected void onTraverse(TraverseEvent e){ if (e.keyCode == SWT.ARROW_LEFT) { // handel the event within the text widget! } else if (e.keyCode == SWT.ARROW_RIGHT) { // handle the event within the text widget! } else super.onTraverse(e); } /* * overridden from superclass */ @Override public void setBounds(Rectangle rect){ super.setBounds(new Rectangle(rect.x, rect.y, rect.width, rect.height)); } /* * (non-Javadoc) * * @see de.kupzog.ktable.KTableCellEditor#setContent(java.lang.Object) */ @Override public void setContent(Object content){ m_Text.setText(content.toString()); m_Text.setSelection(content.toString().length()); } } class ProblemsTableImageCellRenderer extends ProblemsTableCellRendererBase { private final Display display; public ProblemsTableImageCellRenderer(){ display = Display.getCurrent(); } @Override public int getOptimalWidth(GC gc, int col, int row, Object content, boolean fixed, KTableModel model){ if (content instanceof Image) { Image image = (Image) content; return image.getBounds().width; } else { return 0; } } @Override public void drawCell(GC gc, Rectangle rect, int col, int row, Object content, boolean focus, boolean fixed, boolean clicked, KTableModel model){ Color backColor; Color borderColor; Image image = null; if (content instanceof Image) { image = (Image) content; } if (isSelected(row) && ((ProblemsTableModel) model).isHighlightRow()) { backColor = highlightColor; } else if (focus && ((ProblemsTableModel) model).isHighlightSelection()) { backColor = highlightColor; } else { backColor = display.getSystemColor(SWT.COLOR_LIST_BACKGROUND); } borderColor = display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND); gc.setForeground(borderColor); gc.drawLine(rect.x, rect.y + rect.height, rect.x + rect.width, rect.y + rect.height); gc.setForeground(borderColor); gc.drawLine(rect.x + rect.width, rect.y, rect.x + rect.width, rect.y + rect.height); gc.setBackground(backColor); gc.fillRectangle(rect); if (image != null) { // center image Rectangle imageBounds = image.getBounds(); int imageWidth = imageBounds.width; int imageHeight = imageBounds.height; int xOffset = (rect.width - imageWidth) / 2; int yOffset = (rect.height - imageHeight) / 2; Rectangle oldClipping = gc.getClipping(); gc.setClipping(rect); gc.drawImage(image, rect.x + xOffset, rect.y + yOffset); gc.setClipping(oldClipping); } if (focus) { gc.drawFocus(rect.x, rect.y, rect.width, rect.height); } } } abstract class ProblemsTableCellRendererBase implements KTableCellRenderer { protected Problem getSelectedProblem(){ Point[] selection = problemsKTable.getCellSelection(); if (selection == null || selection.length == 0) { return null; } else { int rowIndex = selection[0].y - getFixedHeaderRowCount(); Problem problem = getProblem(rowIndex); return problem; } } protected boolean isSelected(int row){ if (problemsKTable.isRowSelectMode()) { int[] selectedRows = problemsKTable.getRowSelection(); if (selectedRows != null) { for (int r : selectedRows) { if (r == row) { return true; } } } } else { Point[] selectedCells = problemsKTable.getCellSelection(); if (selectedCells != null) { for (Point cell : selectedCells) { if (cell.y == row) { return true; } } } } return false; } } class ProblemsTableTextCellRenderer extends ProblemsTableCellRendererBase { private final Display display; public ProblemsTableTextCellRenderer(){ display = Display.getCurrent(); } @Override public int getOptimalWidth(GC gc, int col, int row, Object content, boolean fixed, KTableModel model){ if (content instanceof String) { String text = (String) content; return gc.textExtent(text).x + 8; } else { return 0; } } @Override public void drawCell(GC gc, Rectangle rect, int col, int row, Object content, boolean focus, boolean fixed, boolean clicked, KTableModel model){ Color textColor; Color backColor; Color borderColor; String text; if (content instanceof String) { text = (String) content; } else { text = ""; } if (focus) { textColor = display.getSystemColor(SWT.COLOR_BLUE); } else { textColor = problemsTableColorProvider.getForegroundColor(col, row); } if (isSelected(row) && ((ProblemsTableModel) model).isHighlightRow()) { backColor = highlightColor; } else if (focus && ((ProblemsTableModel) model).isHighlightSelection()) { backColor = highlightColor; } else { backColor = display.getSystemColor(SWT.COLOR_LIST_BACKGROUND); } borderColor = display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND); gc.setForeground(borderColor); gc.drawLine(rect.x, rect.y + rect.height, rect.x + rect.width, rect.y + rect.height); gc.setForeground(borderColor); gc.drawLine(rect.x + rect.width, rect.y, rect.x + rect.width, rect.y + rect.height); gc.setBackground(backColor); gc.setForeground(textColor); gc.fillRectangle(rect); Rectangle oldClipping = gc.getClipping(); gc.setClipping(rect); gc.drawText((text), rect.x + 3, rect.y); gc.setClipping(oldClipping); if (focus) { gc.drawFocus(rect.x, rect.y, rect.width, rect.height); } } } /** * Renderer for Therapy cell. Shows the procedere of the problem. If there are prescriptions, * they are shown above the procedere, separated by a line. * * @author danlutz */ class ProblemsTableTherapyCellRenderer extends ProblemsTableCellRendererBase { private static final int MARGIN = 8; private static final int PADDING = 3; private final Display display; public ProblemsTableTherapyCellRenderer(){ display = Display.getCurrent(); } private boolean hasPrescriptions(Problem problem){ List<Prescription> prescriptions = problem.getPrescriptions(); return (prescriptions.size() > 0); } private boolean hasProcedere(Problem problem){ if (!StringTool.isNothing(PersistentObject.checkNull(problem.getProcedere()))) { return true; } else { return false; } } private String getPrescriptionsText(Problem problem){ String prescriptions = PersistentObject.checkNull(problem.getPrescriptionsAsText()); String lineSeparator = System.getProperty("line.separator"); String prescriptionsText = prescriptions.replaceAll(Problem.TEXT_SEPARATOR, lineSeparator); return prescriptionsText; } private String getProcedereText(Problem problem){ return PersistentObject.checkNull(problem.getProcedere()); } public int getOptimalHeight(GC gc, Problem problem){ int height = 0; int prescriptionsHeight = 0; if (hasPrescriptions(problem)) { String prescriptionsText = getPrescriptionsText(problem); prescriptionsHeight = gc.textExtent(prescriptionsText).y; } int procedereHeight = 0; if (hasProcedere(problem)) { String procedereText = getProcedereText(problem); procedereHeight = gc.textExtent(procedereText).y; } if (prescriptionsHeight > 0 && procedereHeight > 0) { height = prescriptionsHeight + PADDING + procedereHeight; } else if (prescriptionsHeight > 0) { height = prescriptionsHeight; } else if (procedereHeight > 0) { height = procedereHeight; } if (height == 0) { // default height height = gc.textExtent("").y; } return height; } @Override public int getOptimalWidth(GC gc, int col, int row, Object content, boolean fixed, KTableModel model){ if (content instanceof Problem) { Problem problem = (Problem) content; String prescriptionsText = getPrescriptionsText(problem); String procedereText = getProcedereText(problem); int width1 = gc.textExtent(prescriptionsText).x; int width2 = gc.textExtent(procedereText).x; int width = Math.max(width1, width2); return width + MARGIN; } else { return 0; } } @Override public void drawCell(GC gc, Rectangle rect, int col, int row, Object content, boolean focus, boolean fixed, boolean clicked, KTableModel model){ Color textColor; Color backColor; Color borderColor; String prescriptionsText = ""; String procedereText = ""; boolean hasPrescriptions = false; boolean hasProcedere = false; if (content instanceof Problem) { Problem problem = (Problem) content; prescriptionsText = getPrescriptionsText(problem); procedereText = getProcedereText(problem); hasPrescriptions = hasPrescriptions(problem); hasProcedere = hasProcedere(problem); } if (focus) { textColor = display.getSystemColor(SWT.COLOR_BLUE); } else { textColor = problemsTableColorProvider.getForegroundColor(col, row); } if (isSelected(row) && ((ProblemsTableModel) model).isHighlightRow()) { backColor = highlightColor; } else if (focus && ((ProblemsTableModel) model).isHighlightSelection()) { backColor = highlightColor; } else { backColor = display.getSystemColor(SWT.COLOR_LIST_BACKGROUND); } borderColor = display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND); gc.setForeground(borderColor); gc.drawLine(rect.x, rect.y + rect.height, rect.x + rect.width, rect.y + rect.height); gc.setForeground(borderColor); gc.drawLine(rect.x + rect.width, rect.y, rect.x + rect.width, rect.y + rect.height); gc.setBackground(backColor); gc.setForeground(textColor); gc.fillRectangle(rect); Rectangle oldClipping = gc.getClipping(); gc.setClipping(rect); if (hasPrescriptions && hasProcedere) { // draw prescriptions and procedre, separated by a line int prescriptionsHeight = gc.textExtent(prescriptionsText).y; gc.setForeground(borderColor); gc.drawLine(rect.x, rect.y + prescriptionsHeight + 1, rect.x + rect.width, rect.y + prescriptionsHeight + 1); gc.setBackground(backColor); gc.setForeground(textColor); gc.drawText(prescriptionsText, rect.x + 3, rect.y); gc.drawText(procedereText, rect.x + 3, rect.y + prescriptionsHeight + PADDING); } else { String text; if (hasPrescriptions) { // prescriptions only text = prescriptionsText; } else if (hasProcedere) { // procedere only text = procedereText; } else { // nothing text = ""; } gc.setBackground(backColor); gc.setForeground(textColor); gc.drawText(text, rect.x + 3, rect.y); } gc.setClipping(oldClipping); if (focus) { gc.drawFocus(rect.x, rect.y, rect.width, rect.height); } } } /* * Heartbeat activation management The heartbeat events are only processed if these variables * are set to true. They may be set to false if heartbeat processing would distrub, e. g. in * case of editing a problem or the consultation text. */ private boolean heartbeatProblemEnabled = true; private Konsultation actKons; public void heartbeatProblem(){ log.debug("heartbeatProblem enabled " + heartbeatProblemEnabled); if (heartbeatProblemEnabled) { // backup selection boolean isRowSelectMode = problemsKTable.isRowSelectMode(); Problem selectedProblem = null; int currentColumn = -1; if (isRowSelectMode) { // full row selection // not supported } else { // single cell selection Point[] cells = problemsKTable.getCellSelection(); if (cells != null && cells.length > 0) { int row = cells[0].y; int rowIndex = row - getFixedHeaderRowCount(); selectedProblem = getProblem(rowIndex); currentColumn = cells[0].x; } } // restore selection if (selectedProblem != null) { if (isRowSelectMode) { // full row selection // not supported } else { // single cell selection int rowIndex = getIndexOf(selectedProblem); if (rowIndex >= 0) { // problem found, i. e. still in list int row = rowIndex + getFixedHeaderRowCount(); if (currentColumn == -1) { currentColumn = getFixedHeaderColumnCount(); } problemsKTable.setSelection(currentColumn, row, true); } } } } } public Problem getProblem(int index){ Problem problem = null; if (problems != null) { if (index >= 0 && index < problems.length) { Object element = problems[index]; if (element instanceof Problem) { problem = (Problem) element; } } } return problem; } /** * Finds the index of the given problem (array index, not row) * * @param problem * @return the index, or -1 if not found */ public int getIndexOf(Problem problem){ if (problems != null) { for (int i = 0; i < problems.length; i++) { Object element = problems[i]; if (element instanceof Problem) { Problem p = (Problem) element; if (p.getId().equals(problem.getId())) { return i; } } } } return -1; } /** * Returns the KTable index corresponding to our model index (mapping) * * @param rowIndex * the index of a problem * @return the problem's index as a KTable index */ public int modelIndexToTableIndex(int rowIndex){ return rowIndex + getFixedHeaderRowCount(); } /** * Returns the model index corresponding to the KTable index (mapping) * * @param row * the KTable index of a problem * @return the problem's index of the model */ public int tableIndexToRowIndex(int row){ return row - getFixedHeaderRowCount(); } @Override public Point belongsToCell(int col, int row){ return new Point(col, row); } @Override public KTableCellEditor getCellEditor(int col, int row){ if (row < getFixedHeaderRowCount() || col < getFixedHeaderColumnCount()) { return null; } int colIndex = col - getFixedHeaderColumnCount(); if (colIndex == Constants.BEZEICHNUNG || colIndex == Constants.NUMMER || colIndex == Constants.DATUM) { return new MyKTableCellEditorText2(); } else if (colIndex == Constants.THERAPIE) { return new KTableTherapyCellEditor(); } else { return null; } } @Override public KTableCellRenderer getCellRenderer(int col, int row){ if (row < getFixedHeaderRowCount() || col < getFixedHeaderColumnCount()) { return fixedRenderer; } int colIndex = col - getFixedHeaderColumnCount(); if (colIndex == Constants.STATUS) { return imageRenderer; } if (colIndex == Constants.THERAPIE) { return therapyRenderer; } return textRenderer; } @Override public int getColumnCount(){ return getFixedHeaderColumnCount() + Constants.COLUMN_TEXT.length; } @Override public int getRowCount(){ loadElements(); return getFixedHeaderRowCount() + problems.length; } @Override public int getFixedHeaderColumnCount(){ return 1; } @Override public int getFixedSelectableColumnCount(){ return 0; } @Override public int getFixedHeaderRowCount(){ return 1; } @Override public int getFixedSelectableRowCount(){ return 0; } private int getInitialColumnWidth(int col){ if (col < getFixedHeaderColumnCount()) { return 20; } int colIndex = col - getFixedHeaderColumnCount(); if (colIndex >= 0 && colIndex < Constants.COLUMN_TEXT.length) { int width = CoreHub.localCfg.get(Constants.COLUMN_CFG_KEY[colIndex], Constants.DEFAULT_COLUMN_WIDTH[colIndex]); return width; } else { // invalid column return 0; } } @Override public int getColumnWidth(int col){ Integer width = colWidths.get(new Integer(col)); if (width == null) { width = new Integer(getInitialColumnWidth(col)); colWidths.put(new Integer(col), width); } return width.intValue(); } private int getHeaderRowHeight(){ // TODO return 22; } @Override public int getRowHeightMinimum(){ // TODO return 10; } @Override public int getRowHeight(int row){ Integer height = rowHeights.get(new Integer(row)); if (height == null) { height = new Integer(getOptimalRowHeight(row)); rowHeights.put(new Integer(row), height); } return height.intValue(); } private int getOptimalRowHeight(int row){ if (row < getFixedHeaderRowCount()) { return getHeaderRowHeight(); } else { int height = 0; GC gc = new GC(problemsKTable); for (int i = 0; i < Constants.COLUMN_TEXT.length; i++) { int col = i + getFixedHeaderColumnCount(); int currentHeight = 0; Object obj = getContentAt(col, row); if (obj instanceof String) { String text = (String) obj; currentHeight = gc.textExtent(text).y; } else if (obj instanceof Image) { Image image = (Image) obj; currentHeight = image.getBounds().height; } else if (obj instanceof Problem && i == Constants.THERAPIE) { Problem problem = (Problem) obj; ProblemsTableTherapyCellRenderer cellRenderer = (ProblemsTableTherapyCellRenderer) getCellRenderer(col, row); currentHeight = cellRenderer.getOptimalHeight(gc, problem); } if (currentHeight > height) { height = currentHeight; } } gc.dispose(); return height; } } @Override public void setColumnWidth(int col, int width){ colWidths.put(new Integer(col), new Integer(width)); // store new column with in localCfg int colIndex = col - getFixedHeaderColumnCount(); if (colIndex >= 0 && colIndex < Constants.COLUMN_TEXT.length) { CoreHub.localCfg.set(Constants.COLUMN_CFG_KEY[colIndex], width); } } @Override public void setRowHeight(int row, int height){ rowHeights.put(new Integer(row), new Integer(height)); } private void loadElements(){ if (problems == null) { List<Object> elements = new ArrayList<>(); if (actPatient != null) { List<Problem> problems = Problem.getProblemsOfPatient(actPatient); if (comparator != null) { Collections.sort(problems, comparator); } elements.addAll(problems); // add dummy element elements.add(new DummyProblem()); } problems = elements.toArray(); } } private void addElement(Object element){ Object[] newProblems = new Object[problems.length + 1]; System.arraycopy(problems, 0, newProblems, 0, problems.length); newProblems[newProblems.length - 1] = element; } public void reload(){ // force elements to be reloaded problems = null; // force heights to be re-calculated rowHeights.clear(); } private Object getHeaderContentAt(int col){ int colIndex = col - getFixedHeaderColumnCount(); if (colIndex >= 0 && colIndex < Constants.COLUMN_TEXT.length) { return Constants.COLUMN_TEXT[colIndex]; } else { return ""; } } @Override public Object getContentAt(int col, int row){ if (row < getFixedHeaderRowCount()) { // header return getHeaderContentAt(col); } // rows // load problems if required loadElements(); int colIndex = col - getFixedHeaderColumnCount(); int rowIndex = row - getFixedHeaderRowCount(); // consider header row if (rowIndex >= 0 && rowIndex < problems.length) { Object element = problems[rowIndex]; if (element instanceof Problem) { Problem problem = (Problem) element; String text; String lineSeparator; switch (colIndex) { case Constants.BEZEICHNUNG: return problem.getTitle(); case Constants.NUMMER: return problem.getNumber(); case Constants.DATUM: return problem.getStartDate(); case Constants.DIAGNOSEN: String diagnosen = problem.getDiagnosenAsText(); lineSeparator = System.getProperty("line.separator"); text = diagnosen.replaceAll(Problem.TEXT_SEPARATOR, lineSeparator); return text; /* * case GESETZ: return problem.getGesetz(); */ /* * case RECHNUNGSDATEN: return "not yet implemented"; */ case Constants.THERAPIE: /* * String prescriptions = problem.getPrescriptionsAsText(); lineSeparator = * System.getProperty("line.separator"); text = * prescriptions.replaceAll(Problem.TEXT_SEPARATOR, lineSeparator); return * text; */ return problem; /* * case PROCEDERE: return problem.getProcedere(); */ case Constants.STATUS: if (problem.getStatus() == Episode.ACTIVE) { return UiDesk.getImage(Iatrix.IMG_ACTIVE); } else { return UiDesk.getImage(Iatrix.IMG_INACTIVE); } default: return ""; } } else { // DummyProblem if (col < getFixedHeaderColumnCount()) { return "*"; } else { return ""; } } } else { // row index out of bound return ""; } } @Override public String getTooltipAt(int col, int row){ if (col < Constants.TOOLTIP_TEXT.length) return Constants.TOOLTIP_TEXT[col]; else return "Tooltip für col " + col; } @Override public boolean isColumnResizable(int col){ return true; } @Override public boolean isRowResizable(int row){ return true; } @Override public void setContentAt(int col, int row, Object value){ // don't do anything if there are no problems if (problems == null) { return; } // only accept String values if (!(value instanceof String)) { return; } String text = (String) value; int colIndex = col - getFixedHeaderColumnCount(); int rowIndex = row - getFixedHeaderRowCount(); if (rowIndex >= 0 && rowIndex < problems.length) { boolean isNew = false; Problem problem; if (problems[rowIndex] instanceof Problem) { problem = (Problem) problems[rowIndex]; } else { // replace dummy object with real object if (actPatient == null) { // shuldn't happen; silently ignore return; } problem = new Problem(actPatient, ""); String currentDate = new TimeTool().toString(TimeTool.DATE_ISO); problem.setStartDate(currentDate); IatrixEventHelper.fireSelectionEventProblem(problem); problems[rowIndex] = problem; addElement(new DummyProblem()); isNew = true; } switch (colIndex) { case Constants.BEZEICHNUNG: problem.setTitle(text); break; case Constants.NUMMER: problem.setNumber(text); break; case Constants.DATUM: problem.setStartDate(text); break; case Constants.THERAPIE: problem.setProcedere(text); break; } if (isNew) { reload(); refresh(); problemsKTable.refresh(); } JournalView.updateAllKonsAreas(actKons.getFall().getPatient(), actKons, IJournalArea.KonsActions.EVENT_UPDATE); } } public void setComparator(int col, int row){ if (row < getFixedHeaderRowCount()) { int colIndex = col - getFixedHeaderColumnCount(); switch (colIndex) { case Constants.DATUM: comparator = DATE_COMPARATOR; break; case Constants.NUMMER: comparator = NUMBER_COMPARATOR; break; case Constants.STATUS: comparator = STATUS_COMPARATOR; break; } } } public void setHighlightSelection(boolean highlight, boolean row){ this.highlightSelection = highlight; this.highlightRow = row; } public boolean isHighlightSelection(){ return highlightSelection; } public boolean isHighlightRow(){ return highlightSelection && highlightRow; } class ProblemsTableColorProvider { public Color getForegroundColor(int col, int row){ int rowIndex = row - getFixedHeaderRowCount(); Problem problem = getProblem(rowIndex); if (problem != null && problem.getStatus() == Episode.ACTIVE) { return Display.getCurrent().getSystemColor(SWT.COLOR_BLACK); } else { return Display.getCurrent().getSystemColor(SWT.COLOR_GRAY); } } } public KTable getProblemsKTable(){ return problemsKTable; } public void setProblemsKTable(MyKTable problemsKTable2){ problemsKTable = problemsKTable2; } static class DummyProblem {} public void setKons(Patient newPatient, Konsultation newKons) { actKons = newKons; actPatient = newPatient; } }
org.iatrix/src/org/iatrix/widgets/ProblemsTableModel.java
/******************************************************************************* * Copyright (c) 2007-2015, D. Lutz and Elexis. * 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: * D. Lutz - initial API and implementation * Gerry Weirich - adapted for 2.1 * Niklaus Giger - small improvements, split into 20 classes * * Sponsors: * Dr. Peter Schönbucher, Luzern ******************************************************************************/ package org.iatrix.widgets; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Hashtable; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.TraverseEvent; import org.eclipse.swt.events.TraverseListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Text; import org.iatrix.Iatrix; import org.iatrix.actions.IatrixEventHelper; import org.iatrix.data.Problem; import org.iatrix.util.Constants; import org.iatrix.util.DateComparator; import org.iatrix.util.NumberComparator; import org.iatrix.util.StatusComparator; import org.iatrix.views.JournalView; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ch.elexis.core.data.activator.CoreHub; import ch.elexis.core.ui.UiDesk; import ch.elexis.data.Konsultation; import ch.elexis.data.Patient; import ch.elexis.data.PersistentObject; import ch.elexis.data.Prescription; import ch.elexis.icpc.Episode; import ch.rgw.tools.StringTool; import ch.rgw.tools.TimeTool; import de.kupzog.ktable.KTable; import de.kupzog.ktable.KTableCellEditor; import de.kupzog.ktable.KTableCellRenderer; import de.kupzog.ktable.KTableModel; import de.kupzog.ktable.renderers.FixedCellRenderer; public class ProblemsTableModel implements KTableModel { private Patient actPatient; private static Logger log = LoggerFactory.getLogger(ProblemsTableModel.class); private MyKTable problemsKTable; private Color highlightColor; private ProblemsTableColorProvider problemsTableColorProvider = new ProblemsTableColorProvider(); private Object[] problems = null; private final Hashtable<Integer, Integer> colWidths = new Hashtable<>(); private final Hashtable<Integer, Integer> rowHeights = new Hashtable<>(); private final KTableCellRenderer fixedRenderer = new FixedCellRenderer(FixedCellRenderer.STYLE_PUSH | FixedCellRenderer.INDICATION_SORT | FixedCellRenderer.INDICATION_FOCUS | FixedCellRenderer.INDICATION_CLICKED); private final KTableCellRenderer textRenderer = new ProblemsTableTextCellRenderer(); private final KTableCellRenderer imageRenderer = new ProblemsTableImageCellRenderer(); private final KTableCellRenderer therapyRenderer = new ProblemsTableTherapyCellRenderer(); private static final DateComparator DATE_COMPARATOR = new DateComparator(); private static final NumberComparator NUMBER_COMPARATOR = new NumberComparator(); private static final StatusComparator STATUS_COMPARATOR = new StatusComparator(); private static Comparator<Problem> comparator = new DateComparator(); private boolean highlightSelection = false; private boolean highlightRow = false; public void refresh(){ // problemsKTable.updateScrollbarVisibility(); problemsKTable.redraw(); } /** * Base class for our cell editors Especially, we need to take care of heartbeat management */ abstract class BaseCellEditor extends KTableCellEditor { @Override public void open(KTable table, int col, int row, Rectangle rect){ org.iatrix.util.Heartbeat.getInstance().setHeartbeatProblemEnabled(false); super.open(table, col, row, rect); } @Override public void close(boolean save){ super.close(save); org.iatrix.util.Heartbeat.getInstance().setHeartbeatProblemEnabled(true); } } /** * Replacement for KTableCellEditorText2 We don't want to have the editor vertically centered * * @author danlutz * */ public class MyKTableCellEditorText2 extends BaseCellEditor { protected Text m_Text; protected KeyAdapter keyListener = new KeyAdapter() { @Override public void keyPressed(KeyEvent e){ try { onKeyPressed(e); } catch (Exception ex) { ex.printStackTrace(); // Do nothing } } }; protected TraverseListener travListener = new TraverseListener() { @Override public void keyTraversed(TraverseEvent e){ onTraverse(e); } }; @Override public void open(KTable table, int col, int row, Rectangle rect){ super.open(table, col, row, rect); m_Text.setText(m_Model.getContentAt(m_Col, m_Row).toString()); m_Text.selectAll(); m_Text.setVisible(true); m_Text.setFocus(); } @Override public void close(boolean save){ if (save) m_Model.setContentAt(m_Col, m_Row, m_Text.getText()); m_Text.removeKeyListener(keyListener); m_Text.removeTraverseListener(travListener); super.close(save); m_Text = null; } @Override protected Control createControl(){ m_Text = new Text(m_Table, SWT.NONE); m_Text.addKeyListener(keyListener); m_Text.addTraverseListener(travListener); return m_Text; } /** * Implement In-Textfield navigation with the keys... * * @see de.kupzog.ktable.KTableCellEditor#onTraverse(org.eclipse.swt.events.TraverseEvent) */ @Override protected void onTraverse(TraverseEvent e){ if (e.keyCode == SWT.ARROW_LEFT) { // handel the event within the text widget! } else if (e.keyCode == SWT.ARROW_RIGHT) { // handle the event within the text widget! } else super.onTraverse(e); } @Override protected void onKeyPressed(KeyEvent e){ if ((e.character == '\r') && ((e.stateMask & SWT.SHIFT) == 0)) { close(true); // move one row below! // if (m_Row<m_Model.getRowCount()) // m_Table.setSelection(m_Col, m_Row+1, true); } else super.onKeyPressed(e); } /* * (non-Javadoc) * * @see de.kupzog.ktable.KTableCellEditor#setContent(java.lang.Object) */ @Override public void setContent(Object content){ m_Text.setText(content.toString()); m_Text.setSelection(content.toString().length()); } } public class KTableDiagnosisCellEditor extends BaseCellEditor { private Combo combo; private final KeyAdapter keyListener = new KeyAdapter() { @Override public void keyPressed(KeyEvent e){ try { onKeyPressed(e); } catch (Exception ex) { // Do nothing } } }; private final TraverseListener travListener = new TraverseListener() { @Override public void keyTraversed(TraverseEvent e){ onTraverse(e); } }; @Override public void open(KTable table, int col, int row, Rectangle rect){ super.open(table, col, row, rect); String text = ""; Object obj = m_Model.getContentAt(m_Col, m_Row); if (obj instanceof Problem) { text = "test"; } combo.setText(text); combo.setVisible(true); combo.setFocus(); } @Override public void close(boolean save){ if (save) m_Model.setContentAt(m_Col, m_Row, combo.getText()); combo.removeKeyListener(keyListener); combo.removeTraverseListener(travListener); combo = null; super.close(save); } @Override protected Control createControl(){ combo = new Combo(m_Table, SWT.DROP_DOWN); combo.addKeyListener(keyListener); combo.addTraverseListener(travListener); return combo; } /** * Implement In-Textfield navigation with the keys... * * @see de.kupzog.ktable.KTableCellEditor#onTraverse(org.eclipse.swt.events.TraverseEvent) */ @Override protected void onTraverse(TraverseEvent e){ if (e.keyCode == SWT.ARROW_LEFT) { // handel the event within the text widget! } else if (e.keyCode == SWT.ARROW_RIGHT) { // handle the event within the text widget! } else super.onTraverse(e); } /* * overridden from superclass */ @Override public void setBounds(Rectangle rect){ super.setBounds(new Rectangle(rect.x, rect.y, rect.width, rect.height)); } /* * (non-Javadoc) * * @see de.kupzog.ktable.KTableCellEditor#setContent(java.lang.Object) */ @Override public void setContent(Object content){ combo.setText(content.toString()); } } public class KTableTherapyCellEditor extends BaseCellEditor { private Text m_Text; private final KeyAdapter keyListener = new KeyAdapter() { @Override public void keyPressed(KeyEvent e){ try { onKeyPressed(e); } catch (Exception ex) { // Do nothing } } }; private final TraverseListener travListener = new TraverseListener() { @Override public void keyTraversed(TraverseEvent e){ onTraverse(e); } }; @Override public void open(KTable table, int col, int row, Rectangle rect){ super.open(table, col, row, rect); String text = ""; Object obj = m_Model.getContentAt(m_Col, m_Row); if (obj instanceof Problem) { Problem problem = (Problem) obj; text = problem.getProcedere(); } m_Text.setText(PersistentObject.checkNull(text)); m_Text.selectAll(); m_Text.setVisible(true); m_Text.setFocus(); } @Override public void close(boolean save){ if (save) m_Model.setContentAt(m_Col, m_Row, m_Text.getText()); m_Text.removeKeyListener(keyListener); m_Text.removeTraverseListener(travListener); m_Text = null; super.close(save); } @Override protected Control createControl(){ m_Text = new Text(m_Table, SWT.MULTI | SWT.V_SCROLL); m_Text.addKeyListener(keyListener); m_Text.addTraverseListener(travListener); return m_Text; } /** * Implement In-Textfield navigation with the keys... * * @see de.kupzog.ktable.KTableCellEditor#onTraverse(org.eclipse.swt.events.TraverseEvent) */ @Override protected void onTraverse(TraverseEvent e){ if (e.keyCode == SWT.ARROW_LEFT) { // handel the event within the text widget! } else if (e.keyCode == SWT.ARROW_RIGHT) { // handle the event within the text widget! } else super.onTraverse(e); } /* * overridden from superclass */ @Override public void setBounds(Rectangle rect){ super.setBounds(new Rectangle(rect.x, rect.y, rect.width, rect.height)); } /* * (non-Javadoc) * * @see de.kupzog.ktable.KTableCellEditor#setContent(java.lang.Object) */ @Override public void setContent(Object content){ m_Text.setText(content.toString()); m_Text.setSelection(content.toString().length()); } } class ProblemsTableImageCellRenderer extends ProblemsTableCellRendererBase { private final Display display; public ProblemsTableImageCellRenderer(){ display = Display.getCurrent(); } @Override public int getOptimalWidth(GC gc, int col, int row, Object content, boolean fixed, KTableModel model){ if (content instanceof Image) { Image image = (Image) content; return image.getBounds().width; } else { return 0; } } @Override public void drawCell(GC gc, Rectangle rect, int col, int row, Object content, boolean focus, boolean fixed, boolean clicked, KTableModel model){ Color backColor; Color borderColor; Image image = null; if (content instanceof Image) { image = (Image) content; } if (isSelected(row) && ((ProblemsTableModel) model).isHighlightRow()) { backColor = highlightColor; } else if (focus && ((ProblemsTableModel) model).isHighlightSelection()) { backColor = highlightColor; } else { backColor = display.getSystemColor(SWT.COLOR_LIST_BACKGROUND); } borderColor = display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND); gc.setForeground(borderColor); gc.drawLine(rect.x, rect.y + rect.height, rect.x + rect.width, rect.y + rect.height); gc.setForeground(borderColor); gc.drawLine(rect.x + rect.width, rect.y, rect.x + rect.width, rect.y + rect.height); gc.setBackground(backColor); gc.fillRectangle(rect); if (image != null) { // center image Rectangle imageBounds = image.getBounds(); int imageWidth = imageBounds.width; int imageHeight = imageBounds.height; int xOffset = (rect.width - imageWidth) / 2; int yOffset = (rect.height - imageHeight) / 2; Rectangle oldClipping = gc.getClipping(); gc.setClipping(rect); gc.drawImage(image, rect.x + xOffset, rect.y + yOffset); gc.setClipping(oldClipping); } if (focus) { gc.drawFocus(rect.x, rect.y, rect.width, rect.height); } } } abstract class ProblemsTableCellRendererBase implements KTableCellRenderer { protected Problem getSelectedProblem(){ Point[] selection = problemsKTable.getCellSelection(); if (selection == null || selection.length == 0) { return null; } else { int rowIndex = selection[0].y - getFixedHeaderRowCount(); Problem problem = getProblem(rowIndex); return problem; } } protected boolean isSelected(int row){ if (problemsKTable.isRowSelectMode()) { int[] selectedRows = problemsKTable.getRowSelection(); if (selectedRows != null) { for (int r : selectedRows) { if (r == row) { return true; } } } } else { Point[] selectedCells = problemsKTable.getCellSelection(); if (selectedCells != null) { for (Point cell : selectedCells) { if (cell.y == row) { return true; } } } } return false; } } class ProblemsTableTextCellRenderer extends ProblemsTableCellRendererBase { private final Display display; public ProblemsTableTextCellRenderer(){ display = Display.getCurrent(); } @Override public int getOptimalWidth(GC gc, int col, int row, Object content, boolean fixed, KTableModel model){ if (content instanceof String) { String text = (String) content; return gc.textExtent(text).x + 8; } else { return 0; } } @Override public void drawCell(GC gc, Rectangle rect, int col, int row, Object content, boolean focus, boolean fixed, boolean clicked, KTableModel model){ Color textColor; Color backColor; Color borderColor; String text; if (content instanceof String) { text = (String) content; } else { text = ""; } if (focus) { textColor = display.getSystemColor(SWT.COLOR_BLUE); } else { textColor = problemsTableColorProvider.getForegroundColor(col, row); } if (isSelected(row) && ((ProblemsTableModel) model).isHighlightRow()) { backColor = highlightColor; } else if (focus && ((ProblemsTableModel) model).isHighlightSelection()) { backColor = highlightColor; } else { backColor = display.getSystemColor(SWT.COLOR_LIST_BACKGROUND); } borderColor = display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND); gc.setForeground(borderColor); gc.drawLine(rect.x, rect.y + rect.height, rect.x + rect.width, rect.y + rect.height); gc.setForeground(borderColor); gc.drawLine(rect.x + rect.width, rect.y, rect.x + rect.width, rect.y + rect.height); gc.setBackground(backColor); gc.setForeground(textColor); gc.fillRectangle(rect); Rectangle oldClipping = gc.getClipping(); gc.setClipping(rect); gc.drawText((text), rect.x + 3, rect.y); gc.setClipping(oldClipping); if (focus) { gc.drawFocus(rect.x, rect.y, rect.width, rect.height); } } } /** * Renderer for Therapy cell. Shows the procedere of the problem. If there are prescriptions, * they are shown above the procedere, separated by a line. * * @author danlutz */ class ProblemsTableTherapyCellRenderer extends ProblemsTableCellRendererBase { private static final int MARGIN = 8; private static final int PADDING = 3; private final Display display; public ProblemsTableTherapyCellRenderer(){ display = Display.getCurrent(); } private boolean hasPrescriptions(Problem problem){ List<Prescription> prescriptions = problem.getPrescriptions(); return (prescriptions.size() > 0); } private boolean hasProcedere(Problem problem){ if (!StringTool.isNothing(PersistentObject.checkNull(problem.getProcedere()))) { return true; } else { return false; } } private String getPrescriptionsText(Problem problem){ String prescriptions = PersistentObject.checkNull(problem.getPrescriptionsAsText()); String lineSeparator = System.getProperty("line.separator"); String prescriptionsText = prescriptions.replaceAll(Problem.TEXT_SEPARATOR, lineSeparator); return prescriptionsText; } private String getProcedereText(Problem problem){ return PersistentObject.checkNull(problem.getProcedere()); } public int getOptimalHeight(GC gc, Problem problem){ int height = 0; int prescriptionsHeight = 0; if (hasPrescriptions(problem)) { String prescriptionsText = getPrescriptionsText(problem); prescriptionsHeight = gc.textExtent(prescriptionsText).y; } int procedereHeight = 0; if (hasProcedere(problem)) { String procedereText = getProcedereText(problem); procedereHeight = gc.textExtent(procedereText).y; } if (prescriptionsHeight > 0 && procedereHeight > 0) { height = prescriptionsHeight + PADDING + procedereHeight; } else if (prescriptionsHeight > 0) { height = prescriptionsHeight; } else if (procedereHeight > 0) { height = procedereHeight; } if (height == 0) { // default height height = gc.textExtent("").y; } return height; } @Override public int getOptimalWidth(GC gc, int col, int row, Object content, boolean fixed, KTableModel model){ if (content instanceof Problem) { Problem problem = (Problem) content; String prescriptionsText = getPrescriptionsText(problem); String procedereText = getProcedereText(problem); int width1 = gc.textExtent(prescriptionsText).x; int width2 = gc.textExtent(procedereText).x; int width = Math.max(width1, width2); return width + MARGIN; } else { return 0; } } @Override public void drawCell(GC gc, Rectangle rect, int col, int row, Object content, boolean focus, boolean fixed, boolean clicked, KTableModel model){ Color textColor; Color backColor; Color borderColor; String prescriptionsText = ""; String procedereText = ""; boolean hasPrescriptions = false; boolean hasProcedere = false; if (content instanceof Problem) { Problem problem = (Problem) content; prescriptionsText = getPrescriptionsText(problem); procedereText = getProcedereText(problem); hasPrescriptions = hasPrescriptions(problem); hasProcedere = hasProcedere(problem); } if (focus) { textColor = display.getSystemColor(SWT.COLOR_BLUE); } else { textColor = problemsTableColorProvider.getForegroundColor(col, row); } if (isSelected(row) && ((ProblemsTableModel) model).isHighlightRow()) { backColor = highlightColor; } else if (focus && ((ProblemsTableModel) model).isHighlightSelection()) { backColor = highlightColor; } else { backColor = display.getSystemColor(SWT.COLOR_LIST_BACKGROUND); } borderColor = display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND); gc.setForeground(borderColor); gc.drawLine(rect.x, rect.y + rect.height, rect.x + rect.width, rect.y + rect.height); gc.setForeground(borderColor); gc.drawLine(rect.x + rect.width, rect.y, rect.x + rect.width, rect.y + rect.height); gc.setBackground(backColor); gc.setForeground(textColor); gc.fillRectangle(rect); Rectangle oldClipping = gc.getClipping(); gc.setClipping(rect); if (hasPrescriptions && hasProcedere) { // draw prescriptions and procedre, separated by a line int prescriptionsHeight = gc.textExtent(prescriptionsText).y; gc.setForeground(borderColor); gc.drawLine(rect.x, rect.y + prescriptionsHeight + 1, rect.x + rect.width, rect.y + prescriptionsHeight + 1); gc.setBackground(backColor); gc.setForeground(textColor); gc.drawText(prescriptionsText, rect.x + 3, rect.y); gc.drawText(procedereText, rect.x + 3, rect.y + prescriptionsHeight + PADDING); } else { String text; if (hasPrescriptions) { // prescriptions only text = prescriptionsText; } else if (hasProcedere) { // procedere only text = procedereText; } else { // nothing text = ""; } gc.setBackground(backColor); gc.setForeground(textColor); gc.drawText(text, rect.x + 3, rect.y); } gc.setClipping(oldClipping); if (focus) { gc.drawFocus(rect.x, rect.y, rect.width, rect.height); } } } /* * Heartbeat activation management The heartbeat events are only processed if these variables * are set to true. They may be set to false if heartbeat processing would distrub, e. g. in * case of editing a problem or the consultation text. */ private boolean heartbeatProblemEnabled = true; private Konsultation actKons; public void heartbeatProblem(){ log.debug("heartbeatProblem enabled " + heartbeatProblemEnabled); if (heartbeatProblemEnabled) { // backup selection boolean isRowSelectMode = problemsKTable.isRowSelectMode(); Problem selectedProblem = null; int currentColumn = -1; if (isRowSelectMode) { // full row selection // not supported } else { // single cell selection Point[] cells = problemsKTable.getCellSelection(); if (cells != null && cells.length > 0) { int row = cells[0].y; int rowIndex = row - getFixedHeaderRowCount(); selectedProblem = getProblem(rowIndex); currentColumn = cells[0].x; } } // restore selection if (selectedProblem != null) { if (isRowSelectMode) { // full row selection // not supported } else { // single cell selection int rowIndex = getIndexOf(selectedProblem); if (rowIndex >= 0) { // problem found, i. e. still in list int row = rowIndex + getFixedHeaderRowCount(); if (currentColumn == -1) { currentColumn = getFixedHeaderColumnCount(); } problemsKTable.setSelection(currentColumn, row, true); } } } } } public Problem getProblem(int index){ Problem problem = null; if (problems != null) { if (index >= 0 && index < problems.length) { Object element = problems[index]; if (element instanceof Problem) { problem = (Problem) element; } } } return problem; } /** * Finds the index of the given problem (array index, not row) * * @param problem * @return the index, or -1 if not found */ public int getIndexOf(Problem problem){ if (problems != null) { for (int i = 0; i < problems.length; i++) { Object element = problems[i]; if (element instanceof Problem) { Problem p = (Problem) element; if (p.getId().equals(problem.getId())) { return i; } } } } return -1; } /** * Returns the KTable index corresponding to our model index (mapping) * * @param rowIndex * the index of a problem * @return the problem's index as a KTable index */ public int modelIndexToTableIndex(int rowIndex){ return rowIndex + getFixedHeaderRowCount(); } /** * Returns the model index corresponding to the KTable index (mapping) * * @param row * the KTable index of a problem * @return the problem's index of the model */ public int tableIndexToRowIndex(int row){ return row - getFixedHeaderRowCount(); } @Override public Point belongsToCell(int col, int row){ return new Point(col, row); } @Override public KTableCellEditor getCellEditor(int col, int row){ if (row < getFixedHeaderRowCount() || col < getFixedHeaderColumnCount()) { return null; } int colIndex = col - getFixedHeaderColumnCount(); if (colIndex == Constants.BEZEICHNUNG || colIndex == Constants.NUMMER || colIndex == Constants.DATUM) { return new MyKTableCellEditorText2(); } else if (colIndex == Constants.THERAPIE) { return new KTableTherapyCellEditor(); } else { return null; } } @Override public KTableCellRenderer getCellRenderer(int col, int row){ if (row < getFixedHeaderRowCount() || col < getFixedHeaderColumnCount()) { return fixedRenderer; } int colIndex = col - getFixedHeaderColumnCount(); if (colIndex == Constants.STATUS) { return imageRenderer; } if (colIndex == Constants.THERAPIE) { return therapyRenderer; } return textRenderer; } @Override public int getColumnCount(){ return getFixedHeaderColumnCount() + Constants.COLUMN_TEXT.length; } @Override public int getRowCount(){ loadElements(); return getFixedHeaderRowCount() + problems.length; } @Override public int getFixedHeaderColumnCount(){ return 1; } @Override public int getFixedSelectableColumnCount(){ return 0; } @Override public int getFixedHeaderRowCount(){ return 1; } @Override public int getFixedSelectableRowCount(){ return 0; } private int getInitialColumnWidth(int col){ if (col < getFixedHeaderColumnCount()) { return 20; } int colIndex = col - getFixedHeaderColumnCount(); if (colIndex >= 0 && colIndex < Constants.COLUMN_TEXT.length) { int width = CoreHub.localCfg.get(Constants.COLUMN_CFG_KEY[colIndex], Constants.DEFAULT_COLUMN_WIDTH[colIndex]); return width; } else { // invalid column return 0; } } @Override public int getColumnWidth(int col){ Integer width = colWidths.get(new Integer(col)); if (width == null) { width = new Integer(getInitialColumnWidth(col)); colWidths.put(new Integer(col), width); } return width.intValue(); } private int getHeaderRowHeight(){ // TODO return 22; } @Override public int getRowHeightMinimum(){ // TODO return 10; } @Override public int getRowHeight(int row){ Integer height = rowHeights.get(new Integer(row)); if (height == null) { height = new Integer(getOptimalRowHeight(row)); rowHeights.put(new Integer(row), height); } return height.intValue(); } private int getOptimalRowHeight(int row){ if (row < getFixedHeaderRowCount()) { return getHeaderRowHeight(); } else { int height = 0; GC gc = new GC(problemsKTable); for (int i = 0; i < Constants.COLUMN_TEXT.length; i++) { int col = i + getFixedHeaderColumnCount(); int currentHeight = 0; Object obj = getContentAt(col, row); if (obj instanceof String) { String text = (String) obj; currentHeight = gc.textExtent(text).y; } else if (obj instanceof Image) { Image image = (Image) obj; currentHeight = image.getBounds().height; } else if (obj instanceof Problem && i == Constants.THERAPIE) { Problem problem = (Problem) obj; ProblemsTableTherapyCellRenderer cellRenderer = (ProblemsTableTherapyCellRenderer) getCellRenderer(col, row); currentHeight = cellRenderer.getOptimalHeight(gc, problem); } if (currentHeight > height) { height = currentHeight; } } gc.dispose(); return height; } } @Override public void setColumnWidth(int col, int width){ colWidths.put(new Integer(col), new Integer(width)); // store new column with in localCfg int colIndex = col - getFixedHeaderColumnCount(); if (colIndex >= 0 && colIndex < Constants.COLUMN_TEXT.length) { CoreHub.localCfg.set(Constants.COLUMN_CFG_KEY[colIndex], width); } } @Override public void setRowHeight(int row, int height){ rowHeights.put(new Integer(row), new Integer(height)); } private void loadElements(){ if (problems == null) { List<Object> elements = new ArrayList<>(); if (actPatient != null) { List<Problem> problems = Problem.getProblemsOfPatient(actPatient); if (comparator != null) { Collections.sort(problems, comparator); } elements.addAll(problems); // add dummy element elements.add(new DummyProblem()); } problems = elements.toArray(); } } private void addElement(Object element){ Object[] newProblems = new Object[problems.length + 1]; System.arraycopy(problems, 0, newProblems, 0, problems.length); newProblems[newProblems.length - 1] = element; } public void reload(){ // force elements to be reloaded problems = null; // force heights to be re-calculated rowHeights.clear(); } private Object getHeaderContentAt(int col){ int colIndex = col - getFixedHeaderColumnCount(); if (colIndex >= 0 && colIndex < Constants.COLUMN_TEXT.length) { return Constants.COLUMN_TEXT[colIndex]; } else { return ""; } } @Override public Object getContentAt(int col, int row){ if (row < getFixedHeaderRowCount()) { // header return getHeaderContentAt(col); } // rows // load problems if required loadElements(); int colIndex = col - getFixedHeaderColumnCount(); int rowIndex = row - getFixedHeaderRowCount(); // consider header row if (rowIndex >= 0 && rowIndex < problems.length) { Object element = problems[rowIndex]; if (element instanceof Problem) { Problem problem = (Problem) element; String text; String lineSeparator; switch (colIndex) { case Constants.BEZEICHNUNG: return problem.getTitle(); case Constants.NUMMER: return problem.getNumber(); case Constants.DATUM: return problem.getStartDate(); case Constants.DIAGNOSEN: String diagnosen = problem.getDiagnosenAsText(); lineSeparator = System.getProperty("line.separator"); text = diagnosen.replaceAll(Problem.TEXT_SEPARATOR, lineSeparator); return text; /* * case GESETZ: return problem.getGesetz(); */ /* * case RECHNUNGSDATEN: return "not yet implemented"; */ case Constants.THERAPIE: /* * String prescriptions = problem.getPrescriptionsAsText(); lineSeparator = * System.getProperty("line.separator"); text = * prescriptions.replaceAll(Problem.TEXT_SEPARATOR, lineSeparator); return * text; */ return problem; /* * case PROCEDERE: return problem.getProcedere(); */ case Constants.STATUS: if (problem.getStatus() == Episode.ACTIVE) { return UiDesk.getImage(Iatrix.IMG_ACTIVE); } else { return UiDesk.getImage(Iatrix.IMG_INACTIVE); } default: return ""; } } else { // DummyProblem if (col < getFixedHeaderColumnCount()) { return "*"; } else { return ""; } } } else { // row index out of bound return ""; } } @Override public String getTooltipAt(int col, int row){ if (col < Constants.TOOLTIP_TEXT.length) return Constants.TOOLTIP_TEXT[col]; else return "Tooltip für col " + col; } @Override public boolean isColumnResizable(int col){ return true; } @Override public boolean isRowResizable(int row){ return true; } @Override public void setContentAt(int col, int row, Object value){ // don't do anything if there are no problems if (problems == null) { return; } // only accept String values if (!(value instanceof String)) { return; } String text = (String) value; int colIndex = col - getFixedHeaderColumnCount(); int rowIndex = row - getFixedHeaderRowCount(); if (rowIndex >= 0 && rowIndex < problems.length) { boolean isNew = false; Problem problem; if (problems[rowIndex] instanceof Problem) { problem = (Problem) problems[rowIndex]; } else { // replace dummy object with real object if (actPatient == null) { // shuldn't happen; silently ignore return; } problem = new Problem(actPatient, ""); String currentDate = new TimeTool().toString(TimeTool.DATE_ISO); problem.setStartDate(currentDate); IatrixEventHelper.fireSelectionEventProblem(problem); problems[rowIndex] = problem; addElement(new DummyProblem()); isNew = true; } switch (colIndex) { case Constants.BEZEICHNUNG: problem.setTitle(text); break; case Constants.NUMMER: problem.setNumber(text); break; case Constants.DATUM: problem.setStartDate(text); break; case Constants.THERAPIE: problem.setProcedere(text); break; } if (isNew) { reload(); refresh(); problemsKTable.refresh(); } JournalView.updateAllKonsAreas(null, actKons, IJournalArea.KonsActions.EVENT_UPDATE); } } public void setComparator(int col, int row){ if (row < getFixedHeaderRowCount()) { int colIndex = col - getFixedHeaderColumnCount(); switch (colIndex) { case Constants.DATUM: comparator = DATE_COMPARATOR; break; case Constants.NUMMER: comparator = NUMBER_COMPARATOR; break; case Constants.STATUS: comparator = STATUS_COMPARATOR; break; } } } public void setHighlightSelection(boolean highlight, boolean row){ this.highlightSelection = highlight; this.highlightRow = row; } public boolean isHighlightSelection(){ return highlightSelection; } public boolean isHighlightRow(){ return highlightSelection && highlightRow; } class ProblemsTableColorProvider { public Color getForegroundColor(int col, int row){ int rowIndex = row - getFixedHeaderRowCount(); Problem problem = getProblem(rowIndex); if (problem != null && problem.getStatus() == Episode.ACTIVE) { return Display.getCurrent().getSystemColor(SWT.COLOR_BLACK); } else { return Display.getCurrent().getSystemColor(SWT.COLOR_GRAY); } } } public KTable getProblemsKTable(){ return problemsKTable; } public void setProblemsKTable(MyKTable problemsKTable2){ problemsKTable = problemsKTable2; } static class DummyProblem {} public void setKons(Patient newPatient, Konsultation newKons) { actKons = newKons; actPatient = newPatient; } }
[9598] Updating a problem refreshed patient correctly
org.iatrix/src/org/iatrix/widgets/ProblemsTableModel.java
[9598] Updating a problem refreshed patient correctly
Java
lgpl-2.1
fda60d06a5b9d2481b30d1a88a2580004cee2d78
0
MenoData/Time4J
package net.time4j.range; import net.time4j.ClockUnit; import net.time4j.Duration; import net.time4j.PlainDate; import net.time4j.PlainTime; import net.time4j.PlainTimestamp; import net.time4j.Weekday; import net.time4j.tz.olson.EUROPE; import net.time4j.tz.olson.PACIFIC; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static net.time4j.Weekday.*; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; @RunWith(JUnit4.class) public class DayPartitionTest { @Test public void simpleCase1() { DayPartitionRule rule = new DayPartitionBuilder((date) -> !date.equals(PlainDate.of(2016, 9, 2))) .addExclusion(Collections.singleton(PlainDate.of(2016, 8, 27))) .addWeekdayRule(MONDAY, ClockInterval.between(PlainTime.of(9, 0), PlainTime.of(12, 30))) .addWeekdayRule(MONDAY, ClockInterval.between(PlainTime.of(14, 0), PlainTime.of(16, 0))) .addWeekdayRule(TUESDAY, ClockInterval.between(PlainTime.of(9, 0), PlainTime.of(12, 30))) .addWeekdayRule(TUESDAY, ClockInterval.between(PlainTime.of(14, 0), PlainTime.of(19, 0))) .addWeekdayRule(WEDNESDAY, ClockInterval.between(PlainTime.of(9, 0), PlainTime.of(12, 30))) .addWeekdayRule(THURSDAY, ClockInterval.between(PlainTime.of(9, 0), PlainTime.of(12, 30))) .addWeekdayRule(THURSDAY, ClockInterval.between(PlainTime.of(14, 0), PlainTime.of(19, 0))) .addWeekdayRule(FRIDAY, ClockInterval.between(PlainTime.of(9, 0), PlainTime.of(12, 30))) .addWeekdayRule(SATURDAY, ClockInterval.between(PlainTime.of(10, 0), PlainTime.of(12, 0))) .addSpecialRule( PlainDate.of(2016, 9, 6), ClockInterval.between(PlainTime.of(9, 15), PlainTime.of(12, 45))) .build(); List<TimestampInterval> intervals = DateInterval.between(PlainDate.of(2016, 8, 25), PlainDate.of(2016, 9, 7)) .streamPartitioned(rule) .parallel() .collect(Collectors.toList()); List<ChronoInterval<PlainTimestamp>> expected = new ArrayList<>(); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 25, 9, 0), PlainTimestamp.of(2016, 8, 25, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 25, 14, 0), PlainTimestamp.of(2016, 8, 25, 19, 0))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 26, 9, 0), PlainTimestamp.of(2016, 8, 26, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 29, 9, 0), PlainTimestamp.of(2016, 8, 29, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 29, 14, 0), PlainTimestamp.of(2016, 8, 29, 16, 0))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 30, 9, 0), PlainTimestamp.of(2016, 8, 30, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 30, 14, 0), PlainTimestamp.of(2016, 8, 30, 19, 0))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 31, 9, 0), PlainTimestamp.of(2016, 8, 31, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 9, 1, 9, 0), PlainTimestamp.of(2016, 9, 1, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 9, 1, 14, 0), PlainTimestamp.of(2016, 9, 1, 19, 0))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 9, 3, 10, 0), PlainTimestamp.of(2016, 9, 3, 12, 0))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 9, 5, 9, 0), PlainTimestamp.of(2016, 9, 5, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 9, 5, 14, 0), PlainTimestamp.of(2016, 9, 5, 16, 0))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 9, 6, 9, 15), PlainTimestamp.of(2016, 9, 6, 12, 45))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 9, 7, 9, 0), PlainTimestamp.of(2016, 9, 7, 12, 30))); assertThat(intervals, is(expected)); assertThat(rule.matches(PlainTimestamp.of(2016, 9, 7, 12, 15)), is(true)); assertThat(rule.matches(PlainTimestamp.of(2016, 9, 7, 12, 30)), is(false)); } @Test public void simpleCase2() { DayPartitionRule rule = new DayPartitionBuilder((date) -> !date.equals(PlainDate.of(2016, 9, 2))) .addExclusion(Collections.singleton(PlainDate.of(2016, 8, 27))) .addWeekdayRule( SpanOfWeekdays.betweenMondayAndFriday(), ClockInterval.between(PlainTime.of(9, 0), PlainTime.of(12, 30))) .addWeekdayRule(MONDAY, ClockInterval.between(PlainTime.of(14, 0), PlainTime.of(16, 0))) .addWeekdayRule(TUESDAY, ClockInterval.between(PlainTime.of(14, 0), PlainTime.of(19, 0))) .addWeekdayRule(THURSDAY, ClockInterval.between(PlainTime.of(14, 0), PlainTime.of(19, 0))) .addWeekdayRule(SATURDAY, ClockInterval.between(PlainTime.of(10, 0), PlainTime.of(12, 0))) .addSpecialRule( PlainDate.of(2016, 9, 6), ClockInterval.between(PlainTime.of(9, 15), PlainTime.of(12, 45))) .build(); List<TimestampInterval> intervals = DateInterval.between(PlainDate.of(2016, 8, 25), PlainDate.of(2016, 9, 7)) .streamPartitioned(rule) .parallel() .collect(Collectors.toList()); List<ChronoInterval<PlainTimestamp>> expected = new ArrayList<>(); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 25, 9, 0), PlainTimestamp.of(2016, 8, 25, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 25, 14, 0), PlainTimestamp.of(2016, 8, 25, 19, 0))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 26, 9, 0), PlainTimestamp.of(2016, 8, 26, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 29, 9, 0), PlainTimestamp.of(2016, 8, 29, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 29, 14, 0), PlainTimestamp.of(2016, 8, 29, 16, 0))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 30, 9, 0), PlainTimestamp.of(2016, 8, 30, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 30, 14, 0), PlainTimestamp.of(2016, 8, 30, 19, 0))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 31, 9, 0), PlainTimestamp.of(2016, 8, 31, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 9, 1, 9, 0), PlainTimestamp.of(2016, 9, 1, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 9, 1, 14, 0), PlainTimestamp.of(2016, 9, 1, 19, 0))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 9, 3, 10, 0), PlainTimestamp.of(2016, 9, 3, 12, 0))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 9, 5, 9, 0), PlainTimestamp.of(2016, 9, 5, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 9, 5, 14, 0), PlainTimestamp.of(2016, 9, 5, 16, 0))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 9, 6, 9, 15), PlainTimestamp.of(2016, 9, 6, 12, 45))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 9, 7, 9, 0), PlainTimestamp.of(2016, 9, 7, 12, 30))); assertThat(intervals, is(expected)); assertThat(rule.matches(PlainTimestamp.of(2016, 9, 7, 12, 15)), is(true)); assertThat(rule.matches(PlainTimestamp.of(2016, 9, 7, 12, 30)), is(false)); } @Test public void dailyRule() { DayPartitionRule rule = new DayPartitionBuilder() .addDailyRule(ClockInterval.between(PlainTime.of(9, 0), PlainTime.of(12, 30))) .build(); List<TimestampInterval> intervals = DateInterval.between(PlainDate.of(2016, 8, 24), PlainDate.of(2016, 8, 31)) .streamPartitioned(rule) .parallel() .collect(Collectors.toList()); List<ChronoInterval<PlainTimestamp>> expected = new ArrayList<>(); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 24, 9, 0), PlainTimestamp.of(2016, 8, 24, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 25, 9, 0), PlainTimestamp.of(2016, 8, 25, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 26, 9, 0), PlainTimestamp.of(2016, 8, 26, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 27, 9, 0), PlainTimestamp.of(2016, 8, 27, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 28, 9, 0), PlainTimestamp.of(2016, 8, 28, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 29, 9, 0), PlainTimestamp.of(2016, 8, 29, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 30, 9, 0), PlainTimestamp.of(2016, 8, 30, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 31, 9, 0), PlainTimestamp.of(2016, 8, 31, 12, 30))); assertThat(intervals, is(expected)); assertThat(rule.matches(PlainTimestamp.of(2016, 8, 31, 12, 15)), is(true)); assertThat(rule.matches(PlainTimestamp.of(2016, 8, 31, 12, 30)), is(false)); } @Test public void euCaseWithFullIntervalInGap() { DayPartitionRule rule = new DayPartitionBuilder() .addWeekdayRule(MONDAY, ClockInterval.between(PlainTime.of(9, 0), PlainTime.of(12, 30))) .addWeekdayRule(SUNDAY, ClockInterval.between(PlainTime.of(2, 10), PlainTime.of(2, 20))) .addWeekdayRule(SUNDAY, ClockInterval.between(PlainTime.of(2, 30), PlainTime.of(3, 0))) .addWeekdayRule(SATURDAY, ClockInterval.between(PlainTime.of(10, 0), PlainTime.of(12, 0))) .build(); List<MomentInterval> intervals = DateInterval.between(PlainDate.of(2016, 3, 26), PlainDate.of(2016, 3, 28)) .streamPartitioned(rule, EUROPE.BERLIN) .collect(Collectors.toList()); List<MomentInterval> expected = new ArrayList<>(); expected.add( MomentInterval.between( PlainTimestamp.of(2016, 3, 26, 10, 0).inTimezone(EUROPE.BERLIN), PlainTimestamp.of(2016, 3, 26, 12, 0).inTimezone(EUROPE.BERLIN))); expected.add( MomentInterval.between( PlainTimestamp.of(2016, 3, 28, 9, 0).inTimezone(EUROPE.BERLIN), PlainTimestamp.of(2016, 3, 28, 12, 30).inTimezone(EUROPE.BERLIN))); assertThat(intervals, is(expected)); } @Test public void euCaseWithPartialIntervalInGap() { DayPartitionRule rule = new DayPartitionBuilder() .addWeekdayRule(MONDAY, ClockInterval.between(PlainTime.of(9, 0), PlainTime.of(12, 30))) .addWeekdayRule(SUNDAY, ClockInterval.between(PlainTime.of(1, 10), PlainTime.of(2, 20))) .addWeekdayRule(SUNDAY, ClockInterval.between(PlainTime.of(2, 30), PlainTime.of(3, 15))) .addWeekdayRule(SATURDAY, ClockInterval.between(PlainTime.of(10, 0), PlainTime.of(12, 0))) .build(); List<MomentInterval> intervals = DateInterval.between(PlainDate.of(2016, 3, 26), PlainDate.of(2016, 3, 28)) .streamPartitioned(rule, EUROPE.BERLIN) .collect(Collectors.toList()); List<MomentInterval> expected = new ArrayList<>(); expected.add( MomentInterval.between( PlainTimestamp.of(2016, 3, 26, 10, 0).inTimezone(EUROPE.BERLIN), PlainTimestamp.of(2016, 3, 26, 12, 0).inTimezone(EUROPE.BERLIN))); expected.add( MomentInterval.between( PlainTimestamp.of(2016, 3, 27, 1, 10).inTimezone(EUROPE.BERLIN), PlainTimestamp.of(2016, 3, 27, 3, 0).inTimezone(EUROPE.BERLIN))); expected.add( MomentInterval.between( PlainTimestamp.of(2016, 3, 27, 3, 0).inTimezone(EUROPE.BERLIN), PlainTimestamp.of(2016, 3, 27, 3, 15).inTimezone(EUROPE.BERLIN))); expected.add( MomentInterval.between( PlainTimestamp.of(2016, 3, 28, 9, 0).inTimezone(EUROPE.BERLIN), PlainTimestamp.of(2016, 3, 28, 12, 30).inTimezone(EUROPE.BERLIN))); assertThat(intervals, is(expected)); } @Test public void samoaCase() { DayPartitionRule rule = new DayPartitionBuilder() .addWeekdayRule(THURSDAY, ClockInterval.between(PlainTime.of(9, 0), PlainTime.of(12, 30))) .addWeekdayRule(THURSDAY, ClockInterval.between(PlainTime.of(14, 0), PlainTime.of(19, 0))) .addWeekdayRule(FRIDAY, ClockInterval.between(PlainTime.of(9, 0), PlainTime.of(12, 30))) .addWeekdayRule(SATURDAY, ClockInterval.between(PlainTime.of(10, 0), PlainTime.of(12, 0))) .build(); List<MomentInterval> intervals = DateInterval.between(PlainDate.of(2011, 12, 29), PlainDate.of(2011, 12, 31)) .streamPartitioned(rule, PACIFIC.APIA) .collect(Collectors.toList()); List<MomentInterval> expected = new ArrayList<>(); expected.add( MomentInterval.between( PlainTimestamp.of(2011, 12, 29, 9, 0).inTimezone(PACIFIC.APIA), PlainTimestamp.of(2011, 12, 29, 12, 30).inTimezone(PACIFIC.APIA))); expected.add( MomentInterval.between( PlainTimestamp.of(2011, 12, 29, 14, 0).inTimezone(PACIFIC.APIA), PlainTimestamp.of(2011, 12, 29, 19, 0).inTimezone(PACIFIC.APIA))); expected.add( MomentInterval.between( PlainTimestamp.of(2011, 12, 31, 10, 0).inTimezone(PACIFIC.APIA), PlainTimestamp.of(2011, 12, 31, 12, 0).inTimezone(PACIFIC.APIA))); assertThat(intervals, is(expected)); } @Test public void timestampPartitionsOnSingleDay() { DayPartitionRule rule = new DayPartitionBuilder() .addWeekdayRule(THURSDAY, ClockInterval.between(PlainTime.of(9, 0), PlainTime.of(12, 30))) .addWeekdayRule(THURSDAY, ClockInterval.between(PlainTime.of(14, 0), PlainTime.of(19, 0))) .addWeekdayRule(FRIDAY, ClockInterval.between(PlainTime.of(9, 0), PlainTime.of(12, 30))) .addWeekdayRule(SATURDAY, ClockInterval.between(PlainTime.of(10, 0), PlainTime.of(12, 0))) .build(); List<TimestampInterval> intervals = TimestampInterval.between(PlainTimestamp.of(2018, 10, 25, 9, 15), PlainTimestamp.of(2018, 10, 25, 15, 30)) .streamPartitioned(rule) .collect(Collectors.toList()); List<ChronoInterval<PlainTimestamp>> expected = new ArrayList<>(); expected.add( TimestampInterval.between(PlainTimestamp.of(2018, 10, 25, 9, 15), PlainTimestamp.of(2018, 10, 25, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2018, 10, 25, 14, 0), PlainTimestamp.of(2018, 10, 25, 15, 30))); assertThat(intervals, is(expected)); } @Test public void timestampPartitionsOnTwoDays() { DayPartitionRule rule = new DayPartitionBuilder() .addWeekdayRule(THURSDAY, ClockInterval.between(PlainTime.of(9, 0), PlainTime.of(12, 30))) .addWeekdayRule(THURSDAY, ClockInterval.between(PlainTime.of(14, 0), PlainTime.of(19, 0))) .addWeekdayRule(FRIDAY, ClockInterval.between(PlainTime.of(9, 0), PlainTime.of(12, 30))) .addWeekdayRule(SATURDAY, ClockInterval.between(PlainTime.of(10, 0), PlainTime.of(12, 0))) .build(); List<TimestampInterval> intervals = TimestampInterval.between(PlainTimestamp.of(2018, 10, 25, 9, 15), PlainTimestamp.of(2018, 10, 26, 15, 30)) .streamPartitioned(rule) .collect(Collectors.toList()); List<ChronoInterval<PlainTimestamp>> expected = new ArrayList<>(); expected.add( TimestampInterval.between(PlainTimestamp.of(2018, 10, 25, 9, 15), PlainTimestamp.of(2018, 10, 25, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2018, 10, 25, 14, 0), PlainTimestamp.of(2018, 10, 25, 19, 0))); expected.add( TimestampInterval.between(PlainTimestamp.of(2018, 10, 26, 9, 0), PlainTimestamp.of(2018, 10, 26, 12, 30))); assertThat(intervals, is(expected)); } @Test public void timestampPartitionsOnThreeDays() { DayPartitionRule rule = new DayPartitionBuilder() .addWeekdayRule(THURSDAY, ClockInterval.between(PlainTime.of(9, 0), PlainTime.of(12, 30))) .addWeekdayRule(THURSDAY, ClockInterval.between(PlainTime.of(14, 0), PlainTime.of(19, 0))) .addWeekdayRule(FRIDAY, ClockInterval.between(PlainTime.of(9, 0), PlainTime.of(12, 30))) .addWeekdayRule(SATURDAY, ClockInterval.between(PlainTime.of(10, 0), PlainTime.of(12, 0))) .build(); List<TimestampInterval> intervals = TimestampInterval.between(PlainTimestamp.of(2018, 10, 25, 9, 15), PlainTimestamp.of(2018, 10, 27, 11, 30)) .streamPartitioned(rule) .collect(Collectors.toList()); List<ChronoInterval<PlainTimestamp>> expected = new ArrayList<>(); expected.add( TimestampInterval.between(PlainTimestamp.of(2018, 10, 25, 9, 15), PlainTimestamp.of(2018, 10, 25, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2018, 10, 25, 14, 0), PlainTimestamp.of(2018, 10, 25, 19, 0))); expected.add( TimestampInterval.between(PlainTimestamp.of(2018, 10, 26, 9, 0), PlainTimestamp.of(2018, 10, 26, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2018, 10, 27, 10, 0), PlainTimestamp.of(2018, 10, 27, 11, 30))); assertThat(intervals, is(expected)); } @Test public void overlapOfPartitions() { DayPartitionRule rule = new DayPartitionBuilder() .addWeekdayRule( Weekday.MONDAY, ClockInterval.between(PlainTime.of(8, 0), PlainTime.of(10, 0))) .addWeekdayRule( Weekday.TUESDAY, ClockInterval.between(PlainTime.of(10, 0), PlainTime.of(15, 0))) .build(); Map<Integer, TimestampInterval> events = new HashMap<>(); events.put( 1, TimestampInterval.between( PlainTimestamp.of(2018, 1, 1, 8, 0), PlainTimestamp.of(2018, 1, 1, 9, 0))); events.put( 2, TimestampInterval.between( PlainTimestamp.of(2018, 1, 1, 10, 0), PlainTimestamp.of(2018, 1, 1, 12, 0))); events.put( 3, TimestampInterval.between( PlainTimestamp.of(2018, 1, 2, 10, 0), PlainTimestamp.of(2018, 1, 2, 12, 0))); events.forEach( (id, interval) -> System.out.println( "Event: " + id + " => " + Duration.formatter(ClockUnit.class, "#h:mm").format( interval .streamPartitioned(rule) .map(i -> i.getDuration(ClockUnit.HOURS, ClockUnit.MINUTES)) .collect(Duration.summingUp()) .with(Duration.STD_CLOCK_PERIOD) ) ) ); // output: // Event: 1 => 1:00 // Event: 2 => 0:00 // Event: 3 => 2:00 } }
base/src/test/java/net/time4j/range/DayPartitionTest.java
package net.time4j.range; import net.time4j.PlainDate; import net.time4j.PlainTime; import net.time4j.PlainTimestamp; import net.time4j.tz.olson.EUROPE; import net.time4j.tz.olson.PACIFIC; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import static net.time4j.Weekday.*; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; @RunWith(JUnit4.class) public class DayPartitionTest { @Test public void simpleCase1() { DayPartitionRule rule = new DayPartitionBuilder((date) -> !date.equals(PlainDate.of(2016, 9, 2))) .addExclusion(Collections.singleton(PlainDate.of(2016, 8, 27))) .addWeekdayRule(MONDAY, ClockInterval.between(PlainTime.of(9, 0), PlainTime.of(12, 30))) .addWeekdayRule(MONDAY, ClockInterval.between(PlainTime.of(14, 0), PlainTime.of(16, 0))) .addWeekdayRule(TUESDAY, ClockInterval.between(PlainTime.of(9, 0), PlainTime.of(12, 30))) .addWeekdayRule(TUESDAY, ClockInterval.between(PlainTime.of(14, 0), PlainTime.of(19, 0))) .addWeekdayRule(WEDNESDAY, ClockInterval.between(PlainTime.of(9, 0), PlainTime.of(12, 30))) .addWeekdayRule(THURSDAY, ClockInterval.between(PlainTime.of(9, 0), PlainTime.of(12, 30))) .addWeekdayRule(THURSDAY, ClockInterval.between(PlainTime.of(14, 0), PlainTime.of(19, 0))) .addWeekdayRule(FRIDAY, ClockInterval.between(PlainTime.of(9, 0), PlainTime.of(12, 30))) .addWeekdayRule(SATURDAY, ClockInterval.between(PlainTime.of(10, 0), PlainTime.of(12, 0))) .addSpecialRule( PlainDate.of(2016, 9, 6), ClockInterval.between(PlainTime.of(9, 15), PlainTime.of(12, 45))) .build(); List<TimestampInterval> intervals = DateInterval.between(PlainDate.of(2016, 8, 25), PlainDate.of(2016, 9, 7)) .streamPartitioned(rule) .parallel() .collect(Collectors.toList()); List<ChronoInterval<PlainTimestamp>> expected = new ArrayList<>(); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 25, 9, 0), PlainTimestamp.of(2016, 8, 25, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 25, 14, 0), PlainTimestamp.of(2016, 8, 25, 19, 0))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 26, 9, 0), PlainTimestamp.of(2016, 8, 26, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 29, 9, 0), PlainTimestamp.of(2016, 8, 29, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 29, 14, 0), PlainTimestamp.of(2016, 8, 29, 16, 0))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 30, 9, 0), PlainTimestamp.of(2016, 8, 30, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 30, 14, 0), PlainTimestamp.of(2016, 8, 30, 19, 0))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 31, 9, 0), PlainTimestamp.of(2016, 8, 31, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 9, 1, 9, 0), PlainTimestamp.of(2016, 9, 1, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 9, 1, 14, 0), PlainTimestamp.of(2016, 9, 1, 19, 0))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 9, 3, 10, 0), PlainTimestamp.of(2016, 9, 3, 12, 0))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 9, 5, 9, 0), PlainTimestamp.of(2016, 9, 5, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 9, 5, 14, 0), PlainTimestamp.of(2016, 9, 5, 16, 0))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 9, 6, 9, 15), PlainTimestamp.of(2016, 9, 6, 12, 45))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 9, 7, 9, 0), PlainTimestamp.of(2016, 9, 7, 12, 30))); assertThat(intervals, is(expected)); assertThat(rule.matches(PlainTimestamp.of(2016, 9, 7, 12, 15)), is(true)); assertThat(rule.matches(PlainTimestamp.of(2016, 9, 7, 12, 30)), is(false)); } @Test public void simpleCase2() { DayPartitionRule rule = new DayPartitionBuilder((date) -> !date.equals(PlainDate.of(2016, 9, 2))) .addExclusion(Collections.singleton(PlainDate.of(2016, 8, 27))) .addWeekdayRule( SpanOfWeekdays.betweenMondayAndFriday(), ClockInterval.between(PlainTime.of(9, 0), PlainTime.of(12, 30))) .addWeekdayRule(MONDAY, ClockInterval.between(PlainTime.of(14, 0), PlainTime.of(16, 0))) .addWeekdayRule(TUESDAY, ClockInterval.between(PlainTime.of(14, 0), PlainTime.of(19, 0))) .addWeekdayRule(THURSDAY, ClockInterval.between(PlainTime.of(14, 0), PlainTime.of(19, 0))) .addWeekdayRule(SATURDAY, ClockInterval.between(PlainTime.of(10, 0), PlainTime.of(12, 0))) .addSpecialRule( PlainDate.of(2016, 9, 6), ClockInterval.between(PlainTime.of(9, 15), PlainTime.of(12, 45))) .build(); List<TimestampInterval> intervals = DateInterval.between(PlainDate.of(2016, 8, 25), PlainDate.of(2016, 9, 7)) .streamPartitioned(rule) .parallel() .collect(Collectors.toList()); List<ChronoInterval<PlainTimestamp>> expected = new ArrayList<>(); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 25, 9, 0), PlainTimestamp.of(2016, 8, 25, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 25, 14, 0), PlainTimestamp.of(2016, 8, 25, 19, 0))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 26, 9, 0), PlainTimestamp.of(2016, 8, 26, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 29, 9, 0), PlainTimestamp.of(2016, 8, 29, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 29, 14, 0), PlainTimestamp.of(2016, 8, 29, 16, 0))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 30, 9, 0), PlainTimestamp.of(2016, 8, 30, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 30, 14, 0), PlainTimestamp.of(2016, 8, 30, 19, 0))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 31, 9, 0), PlainTimestamp.of(2016, 8, 31, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 9, 1, 9, 0), PlainTimestamp.of(2016, 9, 1, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 9, 1, 14, 0), PlainTimestamp.of(2016, 9, 1, 19, 0))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 9, 3, 10, 0), PlainTimestamp.of(2016, 9, 3, 12, 0))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 9, 5, 9, 0), PlainTimestamp.of(2016, 9, 5, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 9, 5, 14, 0), PlainTimestamp.of(2016, 9, 5, 16, 0))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 9, 6, 9, 15), PlainTimestamp.of(2016, 9, 6, 12, 45))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 9, 7, 9, 0), PlainTimestamp.of(2016, 9, 7, 12, 30))); assertThat(intervals, is(expected)); assertThat(rule.matches(PlainTimestamp.of(2016, 9, 7, 12, 15)), is(true)); assertThat(rule.matches(PlainTimestamp.of(2016, 9, 7, 12, 30)), is(false)); } @Test public void dailyRule() { DayPartitionRule rule = new DayPartitionBuilder() .addDailyRule(ClockInterval.between(PlainTime.of(9, 0), PlainTime.of(12, 30))) .build(); List<TimestampInterval> intervals = DateInterval.between(PlainDate.of(2016, 8, 24), PlainDate.of(2016, 8, 31)) .streamPartitioned(rule) .parallel() .collect(Collectors.toList()); List<ChronoInterval<PlainTimestamp>> expected = new ArrayList<>(); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 24, 9, 0), PlainTimestamp.of(2016, 8, 24, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 25, 9, 0), PlainTimestamp.of(2016, 8, 25, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 26, 9, 0), PlainTimestamp.of(2016, 8, 26, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 27, 9, 0), PlainTimestamp.of(2016, 8, 27, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 28, 9, 0), PlainTimestamp.of(2016, 8, 28, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 29, 9, 0), PlainTimestamp.of(2016, 8, 29, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 30, 9, 0), PlainTimestamp.of(2016, 8, 30, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2016, 8, 31, 9, 0), PlainTimestamp.of(2016, 8, 31, 12, 30))); assertThat(intervals, is(expected)); assertThat(rule.matches(PlainTimestamp.of(2016, 8, 31, 12, 15)), is(true)); assertThat(rule.matches(PlainTimestamp.of(2016, 8, 31, 12, 30)), is(false)); } @Test public void euCaseWithFullIntervalInGap() { DayPartitionRule rule = new DayPartitionBuilder() .addWeekdayRule(MONDAY, ClockInterval.between(PlainTime.of(9, 0), PlainTime.of(12, 30))) .addWeekdayRule(SUNDAY, ClockInterval.between(PlainTime.of(2, 10), PlainTime.of(2, 20))) .addWeekdayRule(SUNDAY, ClockInterval.between(PlainTime.of(2, 30), PlainTime.of(3, 0))) .addWeekdayRule(SATURDAY, ClockInterval.between(PlainTime.of(10, 0), PlainTime.of(12, 0))) .build(); List<MomentInterval> intervals = DateInterval.between(PlainDate.of(2016, 3, 26), PlainDate.of(2016, 3, 28)) .streamPartitioned(rule, EUROPE.BERLIN) .collect(Collectors.toList()); List<MomentInterval> expected = new ArrayList<>(); expected.add( MomentInterval.between( PlainTimestamp.of(2016, 3, 26, 10, 0).inTimezone(EUROPE.BERLIN), PlainTimestamp.of(2016, 3, 26, 12, 0).inTimezone(EUROPE.BERLIN))); expected.add( MomentInterval.between( PlainTimestamp.of(2016, 3, 28, 9, 0).inTimezone(EUROPE.BERLIN), PlainTimestamp.of(2016, 3, 28, 12, 30).inTimezone(EUROPE.BERLIN))); assertThat(intervals, is(expected)); } @Test public void euCaseWithPartialIntervalInGap() { DayPartitionRule rule = new DayPartitionBuilder() .addWeekdayRule(MONDAY, ClockInterval.between(PlainTime.of(9, 0), PlainTime.of(12, 30))) .addWeekdayRule(SUNDAY, ClockInterval.between(PlainTime.of(1, 10), PlainTime.of(2, 20))) .addWeekdayRule(SUNDAY, ClockInterval.between(PlainTime.of(2, 30), PlainTime.of(3, 15))) .addWeekdayRule(SATURDAY, ClockInterval.between(PlainTime.of(10, 0), PlainTime.of(12, 0))) .build(); List<MomentInterval> intervals = DateInterval.between(PlainDate.of(2016, 3, 26), PlainDate.of(2016, 3, 28)) .streamPartitioned(rule, EUROPE.BERLIN) .collect(Collectors.toList()); List<MomentInterval> expected = new ArrayList<>(); expected.add( MomentInterval.between( PlainTimestamp.of(2016, 3, 26, 10, 0).inTimezone(EUROPE.BERLIN), PlainTimestamp.of(2016, 3, 26, 12, 0).inTimezone(EUROPE.BERLIN))); expected.add( MomentInterval.between( PlainTimestamp.of(2016, 3, 27, 1, 10).inTimezone(EUROPE.BERLIN), PlainTimestamp.of(2016, 3, 27, 3, 0).inTimezone(EUROPE.BERLIN))); expected.add( MomentInterval.between( PlainTimestamp.of(2016, 3, 27, 3, 0).inTimezone(EUROPE.BERLIN), PlainTimestamp.of(2016, 3, 27, 3, 15).inTimezone(EUROPE.BERLIN))); expected.add( MomentInterval.between( PlainTimestamp.of(2016, 3, 28, 9, 0).inTimezone(EUROPE.BERLIN), PlainTimestamp.of(2016, 3, 28, 12, 30).inTimezone(EUROPE.BERLIN))); assertThat(intervals, is(expected)); } @Test public void samoaCase() { DayPartitionRule rule = new DayPartitionBuilder() .addWeekdayRule(THURSDAY, ClockInterval.between(PlainTime.of(9, 0), PlainTime.of(12, 30))) .addWeekdayRule(THURSDAY, ClockInterval.between(PlainTime.of(14, 0), PlainTime.of(19, 0))) .addWeekdayRule(FRIDAY, ClockInterval.between(PlainTime.of(9, 0), PlainTime.of(12, 30))) .addWeekdayRule(SATURDAY, ClockInterval.between(PlainTime.of(10, 0), PlainTime.of(12, 0))) .build(); List<MomentInterval> intervals = DateInterval.between(PlainDate.of(2011, 12, 29), PlainDate.of(2011, 12, 31)) .streamPartitioned(rule, PACIFIC.APIA) .collect(Collectors.toList()); List<MomentInterval> expected = new ArrayList<>(); expected.add( MomentInterval.between( PlainTimestamp.of(2011, 12, 29, 9, 0).inTimezone(PACIFIC.APIA), PlainTimestamp.of(2011, 12, 29, 12, 30).inTimezone(PACIFIC.APIA))); expected.add( MomentInterval.between( PlainTimestamp.of(2011, 12, 29, 14, 0).inTimezone(PACIFIC.APIA), PlainTimestamp.of(2011, 12, 29, 19, 0).inTimezone(PACIFIC.APIA))); expected.add( MomentInterval.between( PlainTimestamp.of(2011, 12, 31, 10, 0).inTimezone(PACIFIC.APIA), PlainTimestamp.of(2011, 12, 31, 12, 0).inTimezone(PACIFIC.APIA))); assertThat(intervals, is(expected)); } @Test public void timestampPartitionsOnSingleDay() { DayPartitionRule rule = new DayPartitionBuilder() .addWeekdayRule(THURSDAY, ClockInterval.between(PlainTime.of(9, 0), PlainTime.of(12, 30))) .addWeekdayRule(THURSDAY, ClockInterval.between(PlainTime.of(14, 0), PlainTime.of(19, 0))) .addWeekdayRule(FRIDAY, ClockInterval.between(PlainTime.of(9, 0), PlainTime.of(12, 30))) .addWeekdayRule(SATURDAY, ClockInterval.between(PlainTime.of(10, 0), PlainTime.of(12, 0))) .build(); List<TimestampInterval> intervals = TimestampInterval.between(PlainTimestamp.of(2018, 10, 25, 9, 15), PlainTimestamp.of(2018, 10, 25, 15, 30)) .streamPartitioned(rule) .collect(Collectors.toList()); List<ChronoInterval<PlainTimestamp>> expected = new ArrayList<>(); expected.add( TimestampInterval.between(PlainTimestamp.of(2018, 10, 25, 9, 15), PlainTimestamp.of(2018, 10, 25, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2018, 10, 25, 14, 0), PlainTimestamp.of(2018, 10, 25, 15, 30))); assertThat(intervals, is(expected)); } @Test public void timestampPartitionsOnTwoDays() { DayPartitionRule rule = new DayPartitionBuilder() .addWeekdayRule(THURSDAY, ClockInterval.between(PlainTime.of(9, 0), PlainTime.of(12, 30))) .addWeekdayRule(THURSDAY, ClockInterval.between(PlainTime.of(14, 0), PlainTime.of(19, 0))) .addWeekdayRule(FRIDAY, ClockInterval.between(PlainTime.of(9, 0), PlainTime.of(12, 30))) .addWeekdayRule(SATURDAY, ClockInterval.between(PlainTime.of(10, 0), PlainTime.of(12, 0))) .build(); List<TimestampInterval> intervals = TimestampInterval.between(PlainTimestamp.of(2018, 10, 25, 9, 15), PlainTimestamp.of(2018, 10, 26, 15, 30)) .streamPartitioned(rule) .collect(Collectors.toList()); List<ChronoInterval<PlainTimestamp>> expected = new ArrayList<>(); expected.add( TimestampInterval.between(PlainTimestamp.of(2018, 10, 25, 9, 15), PlainTimestamp.of(2018, 10, 25, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2018, 10, 25, 14, 0), PlainTimestamp.of(2018, 10, 25, 19, 0))); expected.add( TimestampInterval.between(PlainTimestamp.of(2018, 10, 26, 9, 0), PlainTimestamp.of(2018, 10, 26, 12, 30))); assertThat(intervals, is(expected)); } @Test public void timestampPartitionsOnThreeDays() { DayPartitionRule rule = new DayPartitionBuilder() .addWeekdayRule(THURSDAY, ClockInterval.between(PlainTime.of(9, 0), PlainTime.of(12, 30))) .addWeekdayRule(THURSDAY, ClockInterval.between(PlainTime.of(14, 0), PlainTime.of(19, 0))) .addWeekdayRule(FRIDAY, ClockInterval.between(PlainTime.of(9, 0), PlainTime.of(12, 30))) .addWeekdayRule(SATURDAY, ClockInterval.between(PlainTime.of(10, 0), PlainTime.of(12, 0))) .build(); List<TimestampInterval> intervals = TimestampInterval.between(PlainTimestamp.of(2018, 10, 25, 9, 15), PlainTimestamp.of(2018, 10, 27, 11, 30)) .streamPartitioned(rule) .collect(Collectors.toList()); List<ChronoInterval<PlainTimestamp>> expected = new ArrayList<>(); expected.add( TimestampInterval.between(PlainTimestamp.of(2018, 10, 25, 9, 15), PlainTimestamp.of(2018, 10, 25, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2018, 10, 25, 14, 0), PlainTimestamp.of(2018, 10, 25, 19, 0))); expected.add( TimestampInterval.between(PlainTimestamp.of(2018, 10, 26, 9, 0), PlainTimestamp.of(2018, 10, 26, 12, 30))); expected.add( TimestampInterval.between(PlainTimestamp.of(2018, 10, 27, 10, 0), PlainTimestamp.of(2018, 10, 27, 11, 30))); assertThat(intervals, is(expected)); } }
extra test for timestamp interval partitions
base/src/test/java/net/time4j/range/DayPartitionTest.java
extra test for timestamp interval partitions
Java
lgpl-2.1
7fff05b7792c6b3e31621a3f0ab8a5832ecda716
0
rblasch/fb-contrib,mebigfatguy/fb-contrib,ThrawnCA/fb-contrib,rblasch/fb-contrib,ThrawnCA/fb-contrib,ThrawnCA/fb-contrib,ThrawnCA/fb-contrib,mebigfatguy/fb-contrib,rblasch/fb-contrib,rblasch/fb-contrib,mebigfatguy/fb-contrib
/* * fb-contrib - Auxiliary detectors for Java programs * Copyright (C) 2005-2016 Dave Brosius * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.mebigfatguy.fbcontrib.detect; import java.util.BitSet; import java.util.Iterator; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.Method; import com.mebigfatguy.fbcontrib.utils.BugType; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.Detector; import edu.umd.cs.findbugs.ba.BasicBlock; import edu.umd.cs.findbugs.ba.CFG; import edu.umd.cs.findbugs.ba.CFGBuilderException; import edu.umd.cs.findbugs.ba.ClassContext; import edu.umd.cs.findbugs.ba.Edge; import edu.umd.cs.findbugs.ba.EdgeTypes; import edu.umd.cs.findbugs.visitclass.PreorderVisitor; /** * Calculates the McCabe Cyclomatic Complexity measure and reports methods that have an excessive value. This report value can be set with system property * 'fb-contrib.cc.limit'. */ public class CyclomaticComplexity extends PreorderVisitor implements Detector { public static final String LIMIT_PROPERTY = "fb-contrib.cc.limit"; private BugReporter bugReporter; private ClassContext classContext; private int reportLimit = 50; /** * constructs a CC detector given the reporter to report bugs on * * @param bugReporter * the sync of bug reports */ public CyclomaticComplexity(final BugReporter bugReporter) { this.bugReporter = bugReporter; Integer limit = Integer.getInteger(LIMIT_PROPERTY); if (limit != null) { reportLimit = limit.intValue(); } } /** * overrides the visitor to store the class context * * @param context * the context object for the currently parsed class */ @Override public void visitClassContext(final ClassContext context) { try { classContext = context; classContext.getJavaClass().accept(this); } finally { classContext = null; } } /** * implement the detector with null implementation */ @Override public void report() { // not used, required by the Detector interface } /** * overrides the visitor to navigate the basic block list to count branches * * @param obj * the method of the currently parsed method */ @Override public void visitMethod(final Method obj) { try { if (obj.isSynthetic()) { return; } Code code = obj.getCode(); if (code == null) { return; } // There really is no valid relationship between reportLimit and // code // length, but it is good enough. If the method is small, don't // bother if (code.getCode().length < (2 * reportLimit)) { return; } BitSet exceptionNodeTargets = new BitSet(); CFG cfg = classContext.getCFG(obj); int branches = 0; Iterator<BasicBlock> bbi = cfg.blockIterator(); while (bbi.hasNext()) { BasicBlock bb = bbi.next(); Iterator<Edge> iei = cfg.outgoingEdgeIterator(bb); while (iei.hasNext()) { Edge e = iei.next(); int edgeType = e.getType(); if ((edgeType != EdgeTypes.FALL_THROUGH_EDGE) && (edgeType != EdgeTypes.RETURN_EDGE) && (edgeType != EdgeTypes.UNKNOWN_EDGE)) { if ((edgeType == EdgeTypes.UNHANDLED_EXCEPTION_EDGE) || (edgeType == EdgeTypes.HANDLED_EXCEPTION_EDGE)) { int nodeTarget = e.getTarget().getLabel(); if (!exceptionNodeTargets.get(nodeTarget)) { exceptionNodeTargets.set(nodeTarget); branches++; } } else { branches++; } } } } if (branches > reportLimit) { int priority = (branches > (reportLimit * 2) ? HIGH_PRIORITY : NORMAL_PRIORITY); BugInstance bug = new BugInstance(this, BugType.CC_CYCLOMATIC_COMPLEXITY.name(), priority).addClass(this).addMethod(this) .addSourceLine(classContext, this, 0).addInt(branches); bugReporter.reportBug(bug); } } catch (CFGBuilderException cbe) { bugReporter.logError("Failure examining basic blocks for method " + classContext.getJavaClass().getClassName() + '.' + obj.getName() + " in Cyclomatic Complexity detector", cbe); } } }
src/com/mebigfatguy/fbcontrib/detect/CyclomaticComplexity.java
/* * fb-contrib - Auxiliary detectors for Java programs * Copyright (C) 2005-2016 Dave Brosius * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.mebigfatguy.fbcontrib.detect; import java.util.BitSet; import java.util.Iterator; import org.apache.bcel.Constants; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.Method; import com.mebigfatguy.fbcontrib.utils.BugType; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.Detector; import edu.umd.cs.findbugs.ba.BasicBlock; import edu.umd.cs.findbugs.ba.CFG; import edu.umd.cs.findbugs.ba.CFGBuilderException; import edu.umd.cs.findbugs.ba.ClassContext; import edu.umd.cs.findbugs.ba.Edge; import edu.umd.cs.findbugs.ba.EdgeTypes; import edu.umd.cs.findbugs.visitclass.PreorderVisitor; /** * Calculates the McCabe Cyclomatic Complexity measure and reports methods that * have an excessive value. This report value can be set with system property * 'fb-contrib.cc.limit'. */ public class CyclomaticComplexity extends PreorderVisitor implements Detector { public static final String LIMIT_PROPERTY = "fb-contrib.cc.limit"; private BugReporter bugReporter; private ClassContext classContext; private int reportLimit = 50; /** * constructs a CC detector given the reporter to report bugs on * * @param bugReporter * the sync of bug reports */ public CyclomaticComplexity(final BugReporter bugReporter) { this.bugReporter = bugReporter; Integer limit = Integer.getInteger(LIMIT_PROPERTY); if (limit != null) { reportLimit = limit.intValue(); } } /** * overrides the visitor to store the class context * * @param context * the context object for the currently parsed class */ @Override public void visitClassContext(final ClassContext context) { try { classContext = context; classContext.getJavaClass().accept(this); } finally { classContext = null; } } /** * implement the detector with null implementation */ @Override public void report() { // not used, required by the Detector interface } /** * overrides the visitor to navigate the basic block list to count branches * * @param obj * the method of the currently parsed method */ @Override public void visitMethod(final Method obj) { try { if ((obj.getAccessFlags() & Constants.ACC_SYNTHETIC) != 0) { return; } Code code = obj.getCode(); if (code == null) { return; } // There really is no valid relationship between reportLimit and // code // length, but it is good enough. If the method is small, don't // bother if (code.getCode().length < (2 * reportLimit)) { return; } BitSet exceptionNodeTargets = new BitSet(); CFG cfg = classContext.getCFG(obj); int branches = 0; Iterator<BasicBlock> bbi = cfg.blockIterator(); while (bbi.hasNext()) { BasicBlock bb = bbi.next(); Iterator<Edge> iei = cfg.outgoingEdgeIterator(bb); while (iei.hasNext()) { Edge e = iei.next(); int edgeType = e.getType(); if ((edgeType != EdgeTypes.FALL_THROUGH_EDGE) && (edgeType != EdgeTypes.RETURN_EDGE) && (edgeType != EdgeTypes.UNKNOWN_EDGE)) { if ((edgeType == EdgeTypes.UNHANDLED_EXCEPTION_EDGE) || (edgeType == EdgeTypes.HANDLED_EXCEPTION_EDGE)) { int nodeTarget = e.getTarget().getLabel(); if (!exceptionNodeTargets.get(nodeTarget)) { exceptionNodeTargets.set(nodeTarget); branches++; } } else { branches++; } } } } if (branches > reportLimit) { int priority = (branches > (reportLimit * 2) ? HIGH_PRIORITY : NORMAL_PRIORITY); BugInstance bug = new BugInstance(this, BugType.CC_CYCLOMATIC_COMPLEXITY.name(), priority).addClass(this).addMethod(this) .addSourceLine(classContext, this, 0).addInt(branches); bugReporter.reportBug(bug); } } catch (CFGBuilderException cbe) { bugReporter.logError("Failure examining basic blocks for method " + classContext.getJavaClass().getClassName() + '.' + obj.getName() + " in Cyclomatic Complexity detector", cbe); } } }
simplify
src/com/mebigfatguy/fbcontrib/detect/CyclomaticComplexity.java
simplify
Java
lgpl-2.1
99c7b5316665e0846c360bf82a3895755d2cb70f
0
jagazee/teiid-8.7,jagazee/teiid-8.7,kenweezy/teiid,kenweezy/teiid,kenweezy/teiid
/* * JBoss, Home of Professional Open Source. * See the COPYRIGHT.txt file distributed with this work for information * regarding copyright ownership. Some portions may be licensed * to Red Hat, Inc. under one or more contributor license agreements. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. */ package com.metamatrix.dqp.service; import java.util.Collection; import com.metamatrix.api.exception.MetaMatrixComponentException; import com.metamatrix.common.application.ApplicationService; import com.metamatrix.core.CoreConstants; import com.metamatrix.query.eval.SecurityFunctionEvaluator; /** * This service provides a means to check whether a connection is authorized to access * various data resources. */ public interface AuthorizationService extends ApplicationService, SecurityFunctionEvaluator { public static final int ACTION_READ = 0; public static final int ACTION_CREATE = 1; public static final int ACTION_UPDATE = 2; public static final int ACTION_DELETE = 3; public static final int CONTEXT_QUERY = 0; public static final int CONTEXT_INSERT = 1; public static final int CONTEXT_UPDATE = 2; public static final int CONTEXT_DELETE = 3; public static final int CONTEXT_PROCEDURE = 4; public static final String DEFAULT_WSDL_USERNAME = CoreConstants.DEFAULT_ANON_USERNAME; /** * Determine which of a set of resources a connection does not have permission to * perform the specified action. * @param connectionID Connection ID identifying the connection (and thus the user credentials) * @param action Action connection wishes to perform * @param resources Resources the connection wishes to perform the action on, Collection of String * @param context Auditing context * @return Collection Subset of resources * @throws MetaMatrixComponentException If an error occurs in the service while checking resources */ Collection getInaccessibleResources(String connectionID, int action, Collection resources, int context) throws MetaMatrixComponentException; /** * Determine whether entitlements checking is enabled on the server. * @return <code>true</code> iff server-side entitlements checking is enabled. */ boolean checkingEntitlements(); }
engine/src/main/java/com/metamatrix/dqp/service/AuthorizationService.java
/* * JBoss, Home of Professional Open Source. * See the COPYRIGHT.txt file distributed with this work for information * regarding copyright ownership. Some portions may be licensed * to Red Hat, Inc. under one or more contributor license agreements. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. */ package com.metamatrix.dqp.service; import java.util.Collection; import com.metamatrix.api.exception.MetaMatrixComponentException; import com.metamatrix.common.application.ApplicationService; import com.metamatrix.query.eval.SecurityFunctionEvaluator; /** * This service provides a means to check whether a connection is authorized to access * various data resources. */ public interface AuthorizationService extends ApplicationService, SecurityFunctionEvaluator { public static final int ACTION_READ = 0; public static final int ACTION_CREATE = 1; public static final int ACTION_UPDATE = 2; public static final int ACTION_DELETE = 3; public static final int CONTEXT_QUERY = 0; public static final int CONTEXT_INSERT = 1; public static final int CONTEXT_UPDATE = 2; public static final int CONTEXT_DELETE = 3; public static final int CONTEXT_PROCEDURE = 4; public static final String DEFAULT_WSDL_USERNAME = CoreCon /** * Determine which of a set of resources a connection does not have permission to * perform the specified action. * @param connectionID Connection ID identifying the connection (and thus the user credentials) * @param action Action connection wishes to perform * @param resources Resources the connection wishes to perform the action on, Collection of String * @param context Auditing context * @return Collection Subset of resources * @throws MetaMatrixComponentException If an error occurs in the service while checking resources */ Collection getInaccessibleResources(String connectionID, int action, Collection resources, int context) throws MetaMatrixComponentException; /** * Determine whether entitlements checking is enabled on the server. * @return <code>true</code> iff server-side entitlements checking is enabled. */ boolean checkingEntitlements(); }
TEIID-422 - Fix for compile error.
engine/src/main/java/com/metamatrix/dqp/service/AuthorizationService.java
TEIID-422 - Fix for compile error.
Java
lgpl-2.1
c77e51209478d5cf3a3d122dee18862008184edb
0
OpenTSDB/opentsdb,andyflury/opentsdb,MadDogTechnology/opentsdb,eswdd/opentsdb,OpenTSDB/opentsdb,johann8384/opentsdb,eswdd/opentsdb,johann8384/opentsdb,ShefronYudy/opentsdb,alienth/opentsdb,OpenTSDB/opentsdb,MadDogTechnology/opentsdb,ShefronYudy/opentsdb,alienth/opentsdb,andyflury/opentsdb,MadDogTechnology/opentsdb
// This file is part of OpenTSDB. // Copyright (C) 2010-2012 The OpenTSDB Authors. // // This program is free software: you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 2.1 of the License, or (at your // option) any later version. This program is distributed in the hope that it // will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser // General Public License for more details. You should have received a copy // of the GNU Lesser General Public License along with this program. If not, // see <http://www.gnu.org/licenses/>. package net.opentsdb.uid; import java.nio.charset.Charset; import java.util.Arrays; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import com.stumbleupon.async.Callback; import com.stumbleupon.async.Deferred; import javax.xml.bind.DatatypeConverter; import net.opentsdb.core.TSDB; import net.opentsdb.meta.UIDMeta; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.hbase.async.AtomicIncrementRequest; import org.hbase.async.Bytes; import org.hbase.async.DeleteRequest; import org.hbase.async.GetRequest; import org.hbase.async.HBaseClient; import org.hbase.async.HBaseException; import org.hbase.async.KeyValue; import org.hbase.async.PutRequest; import org.hbase.async.Scanner; /** * Represents a table of Unique IDs, manages the lookup and creation of IDs. * <p> * Don't attempt to use {@code equals()} or {@code hashCode()} on * this class. * @see UniqueIdInterface */ @SuppressWarnings("deprecation") // Dunno why even with this, compiler warns. public final class UniqueId implements UniqueIdInterface { private static final Logger LOG = LoggerFactory.getLogger(UniqueId.class); /** Enumerator for different types of UIDS @since 2.0 */ public enum UniqueIdType { METRIC, TAGK, TAGV } /** Charset used to convert Strings to byte arrays and back. */ private static final Charset CHARSET = Charset.forName("ISO-8859-1"); /** The single column family used by this class. */ private static final byte[] ID_FAMILY = toBytes("id"); /** The single column family used by this class. */ private static final byte[] NAME_FAMILY = toBytes("name"); /** Row key of the special row used to track the max ID already assigned. */ private static final byte[] MAXID_ROW = { 0 }; /** How many time do we try to assign an ID before giving up. */ private static final short MAX_ATTEMPTS_ASSIGN_ID = 3; /** How many time do we try to apply an edit before giving up. */ private static final short MAX_ATTEMPTS_PUT = 6; /** Initial delay in ms for exponential backoff to retry failed RPCs. */ private static final short INITIAL_EXP_BACKOFF_DELAY = 800; /** Maximum number of results to return in suggest(). */ private static final short MAX_SUGGESTIONS = 25; /** HBase client to use. */ private final HBaseClient client; /** Table where IDs are stored. */ private final byte[] table; /** The kind of UniqueId, used as the column qualifier. */ private final byte[] kind; /** The type of UID represented by this cache */ private final UniqueIdType type; /** Number of bytes on which each ID is encoded. */ private final short id_width; /** Cache for forward mappings (name to ID). */ private final ConcurrentHashMap<String, byte[]> name_cache = new ConcurrentHashMap<String, byte[]>(); /** Cache for backward mappings (ID to name). * The ID in the key is a byte[] converted to a String to be Comparable. */ private final ConcurrentHashMap<String, String> id_cache = new ConcurrentHashMap<String, String>(); /** Number of times we avoided reading from HBase thanks to the cache. */ private volatile int cache_hits; /** Number of times we had to read from HBase and populate the cache. */ private volatile int cache_misses; /** Whether or not to generate new UIDMetas */ private TSDB tsdb; /** * Constructor. * @param client The HBase client to use. * @param table The name of the HBase table to use. * @param kind The kind of Unique ID this instance will deal with. * @param width The number of bytes on which Unique IDs should be encoded. * @throws IllegalArgumentException if width is negative or too small/large * or if kind is an empty string. */ public UniqueId(final HBaseClient client, final byte[] table, final String kind, final int width) { this.client = client; this.table = table; if (kind.isEmpty()) { throw new IllegalArgumentException("Empty string as 'kind' argument!"); } this.kind = toBytes(kind); type = stringToUniqueIdType(kind); if (width < 1 || width > 8) { throw new IllegalArgumentException("Invalid width: " + width); } this.id_width = (short) width; } /** The number of times we avoided reading from HBase thanks to the cache. */ public int cacheHits() { return cache_hits; } /** The number of times we had to read from HBase and populate the cache. */ public int cacheMisses() { return cache_misses; } /** Returns the number of elements stored in the internal cache. */ public int cacheSize() { return name_cache.size() + id_cache.size(); } public String kind() { return fromBytes(kind); } public short width() { return id_width; } /** @param Whether or not to track new UIDMeta objects */ public void setTSDB(final TSDB tsdb) { this.tsdb = tsdb; } /** The largest possible ID given the number of bytes the IDs are represented on. */ public long maxPossibleId() { return (1 << id_width * Byte.SIZE) - 1; } /** * Causes this instance to discard all its in-memory caches. * @since 1.1 */ public void dropCaches() { name_cache.clear(); id_cache.clear(); } /** * Finds the name associated with a given ID. * <p> * <strong>This method is blocking.</strong> Its use within OpenTSDB itself * is discouraged, please use {@link #getNameAsync} instead. * @param id The ID associated with that name. * @see #getId(String) * @see #getOrCreateId(String) * @throws NoSuchUniqueId if the given ID is not assigned. * @throws HBaseException if there is a problem communicating with HBase. * @throws IllegalArgumentException if the ID given in argument is encoded * on the wrong number of bytes. */ public String getName(final byte[] id) throws NoSuchUniqueId, HBaseException { try { return getNameAsync(id).joinUninterruptibly(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException("Should never be here", e); } } /** * Finds the name associated with a given ID. * * @param id The ID associated with that name. * @see #getId(String) * @see #getOrCreateIdAsync(String) * @throws NoSuchUniqueId if the given ID is not assigned. * @throws HBaseException if there is a problem communicating with HBase. * @throws IllegalArgumentException if the ID given in argument is encoded * on the wrong number of bytes. * @since 1.1 */ public Deferred<String> getNameAsync(final byte[] id) { if (id.length != id_width) { throw new IllegalArgumentException("Wrong id.length = " + id.length + " which is != " + id_width + " required for '" + kind() + '\''); } final String name = getNameFromCache(id); if (name != null) { cache_hits++; return Deferred.fromResult(name); } cache_misses++; class GetNameCB implements Callback<String, String> { public String call(final String name) { if (name == null) { throw new NoSuchUniqueId(kind(), id); } addNameToCache(id, name); addIdToCache(name, id); return name; } } return getNameFromHBase(id).addCallback(new GetNameCB()); } private String getNameFromCache(final byte[] id) { return id_cache.get(fromBytes(id)); } private Deferred<String> getNameFromHBase(final byte[] id) { class NameFromHBaseCB implements Callback<String, byte[]> { public String call(final byte[] name) { return name == null ? null : fromBytes(name); } } return hbaseGet(id, NAME_FAMILY).addCallback(new NameFromHBaseCB()); } private void addNameToCache(final byte[] id, final String name) { final String key = fromBytes(id); String found = id_cache.get(key); if (found == null) { found = id_cache.putIfAbsent(key, name); } if (found != null && !found.equals(name)) { throw new IllegalStateException("id=" + Arrays.toString(id) + " => name=" + name + ", already mapped to " + found); } } public byte[] getId(final String name) throws NoSuchUniqueName, HBaseException { try { return getIdAsync(name).joinUninterruptibly(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException("Should never be here", e); } } public Deferred<byte[]> getIdAsync(final String name) { final byte[] id = getIdFromCache(name); if (id != null) { cache_hits++; return Deferred.fromResult(id); } cache_misses++; class GetIdCB implements Callback<byte[], byte[]> { public byte[] call(final byte[] id) { if (id == null) { throw new NoSuchUniqueName(kind(), name); } if (id.length != id_width) { throw new IllegalStateException("Found id.length = " + id.length + " which is != " + id_width + " required for '" + kind() + '\''); } addIdToCache(name, id); addNameToCache(id, name); return id; } } Deferred<byte[]> d = getIdFromHBase(name).addCallback(new GetIdCB()); return d; } private byte[] getIdFromCache(final String name) { return name_cache.get(name); } private Deferred<byte[]> getIdFromHBase(final String name) { return hbaseGet(toBytes(name), ID_FAMILY); } private void addIdToCache(final String name, final byte[] id) { byte[] found = name_cache.get(name); if (found == null) { found = name_cache.putIfAbsent(name, // Must make a defensive copy to be immune // to any changes the caller may do on the // array later on. Arrays.copyOf(id, id.length)); } if (found != null && !Arrays.equals(found, id)) { throw new IllegalStateException("name=" + name + " => id=" + Arrays.toString(id) + ", already mapped to " + Arrays.toString(found)); } } /** * Implements the process to allocate a new UID. * This callback is re-used multiple times in a four step process: * 1. Allocate a new UID via atomic increment. * 2. Create the reverse mapping (ID to name). * 3. Create the forward mapping (name to ID). * 4. Return the new UID to the caller. */ private final class UniqueIdAllocator implements Callback<Object, Object> { private final String name; // What we're trying to allocate an ID for. private short attempt = MAX_ATTEMPTS_ASSIGN_ID; // Give up when zero. private HBaseException hbe = null; // Last exception caught. private long id = -1; // The ID we'll grab with an atomic increment. private byte row[]; // The same ID, as a byte array. private static final byte ALLOCATE_UID = 0; private static final byte CREATE_REVERSE_MAPPING = 1; private static final byte CREATE_FORWARD_MAPPING = 2; private static final byte DONE = 3; private byte state = ALLOCATE_UID; // Current state of the process. UniqueIdAllocator(final String name) { this.name = name; } @SuppressWarnings("unchecked") Deferred<byte[]> tryAllocate() { attempt--; state = ALLOCATE_UID; return (Deferred<byte[]>) call(null); } @SuppressWarnings("unchecked") public Object call(final Object arg) { if (attempt == 0) { if (hbe == null) { throw new IllegalStateException("Should never happen!"); } LOG.error("Failed to assign an ID for kind='" + kind() + "' name='" + name + "'", hbe); throw hbe; } if (arg instanceof Exception) { final String msg = ("Failed attempt #" + (MAX_ATTEMPTS_ASSIGN_ID - attempt) + " to assign an UID for " + kind() + ':' + name + " at step #" + state); if (arg instanceof HBaseException) { LOG.error(msg, (Exception) arg); hbe = (HBaseException) arg; return tryAllocate(); // Retry from the beginning. } else { LOG.error("WTF? Unexpected exception! " + msg, (Exception) arg); return arg; // Unexpected exception, let it bubble up. } } final Deferred d; switch (state) { case ALLOCATE_UID: d = allocateUid(); break; case CREATE_REVERSE_MAPPING: d = createReverseMapping(arg); break; case CREATE_FORWARD_MAPPING: d = createForwardMapping(arg); break; case DONE: return done(arg); default: throw new AssertionError("Should never be here!"); } return d.addBoth(this); } private Deferred<Long> allocateUid() { LOG.info("Creating an ID for kind='" + kind() + "' name='" + name + '\''); state = CREATE_REVERSE_MAPPING; return client.atomicIncrement(new AtomicIncrementRequest(table, MAXID_ROW, ID_FAMILY, kind)); } /** * Create the reverse mapping. * We do this before the forward one so that if we die before creating * the forward mapping we don't run the risk of "publishing" a * partially assigned ID. The reverse mapping on its own is harmless * but the forward mapping without reverse mapping is bad as it would * point to an ID that cannot be resolved. */ private Deferred<Boolean> createReverseMapping(final Object arg) { if (!(arg instanceof Long)) { throw new IllegalStateException("Expected a Long but got " + arg); } id = (Long) arg; if (id <= 0) { throw new IllegalStateException("Got a negative ID from HBase: " + id); } LOG.info("Got ID=" + id + " for kind='" + kind() + "' name='" + name + "'"); row = Bytes.fromLong(id); // row.length should actually be 8. if (row.length < id_width) { throw new IllegalStateException("OMG, row.length = " + row.length + " which is less than " + id_width + " for id=" + id + " row=" + Arrays.toString(row)); } // Verify that we're going to drop bytes that are 0. for (int i = 0; i < row.length - id_width; i++) { if (row[i] != 0) { final String message = "All Unique IDs for " + kind() + " on " + id_width + " bytes are already assigned!"; LOG.error("OMG " + message); throw new IllegalStateException(message); } } // Shrink the ID on the requested number of bytes. row = Arrays.copyOfRange(row, row.length - id_width, row.length); state = CREATE_FORWARD_MAPPING; // We are CAS'ing the KV into existence -- the second argument is how // we tell HBase we want to atomically create the KV, so that if there // is already a KV in this cell, we'll fail. Technically we could do // just a `put' here, as we have a freshly allocated UID, so there is // not reason why a KV should already exist for this UID, but just to // err on the safe side and catch really weird corruption cases, we do // a CAS instead to create the KV. return client.compareAndSet(reverseMapping(), HBaseClient.EMPTY_ARRAY); } private PutRequest reverseMapping() { return new PutRequest(table, row, NAME_FAMILY, kind, toBytes(name)); } private Deferred<?> createForwardMapping(final Object arg) { if (!(arg instanceof Boolean)) { throw new IllegalStateException("Expected a Boolean but got " + arg); } if (!((Boolean) arg)) { // Previous CAS failed. Something is really messed up. LOG.error("WTF! Failed to CAS reverse mapping: " + reverseMapping() + " -- run an fsck against the UID table!"); return tryAllocate(); // Try again from the beginning. } state = DONE; return client.compareAndSet(forwardMapping(), HBaseClient.EMPTY_ARRAY); } private PutRequest forwardMapping() { return new PutRequest(table, toBytes(name), ID_FAMILY, kind, row); } private Deferred<byte[]> done(final Object arg) { if (!(arg instanceof Boolean)) { throw new IllegalStateException("Expected a Boolean but got " + arg); } if (!((Boolean) arg)) { // Previous CAS failed. We lost a race. LOG.warn("Race condition: tried to assign ID " + id + " to " + kind() + ":" + name + ", but CAS failed on " + forwardMapping() + ", which indicates this UID must have" + " been allocated concurrently by another TSD. So ID " + id + " was leaked."); // If two TSDs attempted to allocate a UID for the same name at the // same time, they would both have allocated a UID, and created a // reverse mapping, and upon getting here, only one of them would // manage to CAS this KV into existence. The one that loses the // race will retry and discover the UID assigned by the winner TSD, // and a UID will have been wasted in the process. No big deal. return getIdAsync(name); } cacheMapping(name, row); if (tsdb != null && tsdb.getConfig().enable_realtime_uid()) { final UIDMeta meta = new UIDMeta(type, row, name); meta.storeNew(tsdb); LOG.info("Wrote UIDMeta for: " + name); tsdb.indexUIDMeta(meta); } return Deferred.fromResult(row); } } /** Adds the bidirectional mapping in the cache. */ private void cacheMapping(final String name, final byte[] id) { addIdToCache(name, id); addNameToCache(id, name); } /** * Finds the ID associated with a given name or creates it. * <p> * <strong>This method is blocking.</strong> Its use within OpenTSDB itself * is discouraged, please use {@link #getOrCreateIdAsync} instead. * <p> * The length of the byte array is fixed in advance by the implementation. * * @param name The name to lookup in the table or to assign an ID to. * @throws HBaseException if there is a problem communicating with HBase. * @throws IllegalStateException if all possible IDs are already assigned. * @throws IllegalStateException if the ID found in HBase is encoded on the * wrong number of bytes. */ public byte[] getOrCreateId(final String name) throws HBaseException { try { return getOrCreateIdAsync(name).joinUninterruptibly(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException("Should never be here", e); } } /** * Finds the ID associated with a given name or creates it. * <p> * The length of the byte array is fixed in advance by the implementation. * * @param name The name to lookup in the table or to assign an ID to. * @throws HBaseException if there is a problem communicating with HBase. * @throws IllegalStateException if all possible IDs are already assigned. * @throws IllegalStateException if the ID found in HBase is encoded on the * wrong number of bytes. * @since 1.2 */ public Deferred<byte[]> getOrCreateIdAsync(final String name) { // Look in the cache first. final byte[] id = getIdFromCache(name); if (id != null) { cache_hits++; return Deferred.fromResult(id); } // Not found in our cache, so look in HBase instead. class HandleNoSuchUniqueNameCB implements Callback<Object, Exception> { public Object call(final Exception e) { if (e instanceof NoSuchUniqueName) { return new UniqueIdAllocator(name).tryAllocate(); } return e; // Other unexpected exception, let it bubble up. } } // Kick off the HBase lookup, and if we don't find it there either, start // the process to allocate a UID. return getIdAsync(name).addErrback(new HandleNoSuchUniqueNameCB()); } /** * Attempts to find suggestions of names given a search term. * <p> * <strong>This method is blocking.</strong> Its use within OpenTSDB itself * is discouraged, please use {@link #suggestAsync} instead. * @param search The search term (possibly empty). * @param max_results The number of results to return. Must be 1 or greater * @return A list of known valid names that have UIDs that sort of match * the search term. If the search term is empty, returns the first few * terms. * @throws HBaseException if there was a problem getting suggestions from * HBase. */ public List<String> suggest(final String search) throws HBaseException { return suggest(search, MAX_SUGGESTIONS); } /** * Attempts to find suggestions of names given a search term. * @param search The search term (possibly empty). * @param max_results The number of results to return. Must be 1 or greater * @return A list of known valid names that have UIDs that sort of match * the search term. If the search term is empty, returns the first few * terms. * @throws HBaseException if there was a problem getting suggestions from * HBase. * @throws IllegalArgumentException if the count was less than 1 * @since 2.0 */ public List<String> suggest(final String search, final int max_results) throws HBaseException { if (max_results < 1) { throw new IllegalArgumentException("Count must be greater than 0"); } try { return suggestAsync(search, max_results).joinUninterruptibly(); } catch (HBaseException e) { throw e; } catch (Exception e) { // Should never happen. final String msg = "Unexpected exception caught by " + this + ".suggest(" + search + ')'; LOG.error(msg, e); throw new RuntimeException(msg, e); // Should never happen. } } /** * Attempts to find suggestions of names given a search term. * @param search The search term (possibly empty). * @return A list of known valid names that have UIDs that sort of match * the search term. If the search term is empty, returns the first few * terms. * @throws HBaseException if there was a problem getting suggestions from * HBase. * @since 1.1 */ public Deferred<List<String>> suggestAsync(final String search, final int max_results) { return new SuggestCB(search, max_results).search(); } /** * Helper callback to asynchronously scan HBase for suggestions. */ private final class SuggestCB implements Callback<Object, ArrayList<ArrayList<KeyValue>>> { private final LinkedList<String> suggestions = new LinkedList<String>(); private final Scanner scanner; private final int max_results; SuggestCB(final String search, final int max_results) { this.max_results = max_results; this.scanner = getSuggestScanner(search, max_results); } @SuppressWarnings("unchecked") Deferred<List<String>> search() { return (Deferred) scanner.nextRows().addCallback(this); } public Object call(final ArrayList<ArrayList<KeyValue>> rows) { if (rows == null) { // We're done scanning. return suggestions; } for (final ArrayList<KeyValue> row : rows) { if (row.size() != 1) { LOG.error("WTF shouldn't happen! Scanner " + scanner + " returned" + " a row that doesn't have exactly 1 KeyValue: " + row); if (row.isEmpty()) { continue; } } final byte[] key = row.get(0).key(); final String name = fromBytes(key); final byte[] id = row.get(0).value(); final byte[] cached_id = name_cache.get(name); if (cached_id == null) { cacheMapping(name, id); } else if (!Arrays.equals(id, cached_id)) { throw new IllegalStateException("WTF? For kind=" + kind() + " name=" + name + ", we have id=" + Arrays.toString(cached_id) + " in cache, but just scanned id=" + Arrays.toString(id)); } suggestions.add(name); if ((short) suggestions.size() > max_results) { // We have enough. return suggestions; } row.clear(); // free() } return search(); // Get more suggestions. } } /** * Reassigns the UID to a different name (non-atomic). * <p> * Whatever was the UID of {@code oldname} will be given to {@code newname}. * {@code oldname} will no longer be assigned a UID. * <p> * Beware that the assignment change is <b>not atommic</b>. If two threads * or processes attempt to rename the same UID differently, the result is * unspecified and might even be inconsistent. This API is only here for * administrative purposes, not for normal programmatic interactions. * @param oldname The old name to rename. * @param newname The new name. * @throws NoSuchUniqueName if {@code oldname} wasn't assigned. * @throws IllegalArgumentException if {@code newname} was already assigned. * @throws HBaseException if there was a problem with HBase while trying to * update the mapping. */ public void rename(final String oldname, final String newname) { final byte[] row = getId(oldname); { byte[] id = null; try { id = getId(newname); } catch (NoSuchUniqueName e) { // OK, we don't want the new name to be assigned. } if (id != null) { throw new IllegalArgumentException("When trying rename(\"" + oldname + "\", \"" + newname + "\") on " + this + ": new name already" + " assigned ID=" + Arrays.toString(id)); } } final byte[] newnameb = toBytes(newname); // Update the reverse mapping first, so that if we die before updating // the forward mapping we don't run the risk of "publishing" a // partially assigned ID. The reverse mapping on its own is harmless // but the forward mapping without reverse mapping is bad. try { final PutRequest reverse_mapping = new PutRequest( table, row, NAME_FAMILY, kind, newnameb); hbasePutWithRetry(reverse_mapping, MAX_ATTEMPTS_PUT, INITIAL_EXP_BACKOFF_DELAY); } catch (HBaseException e) { LOG.error("When trying rename(\"" + oldname + "\", \"" + newname + "\") on " + this + ": Failed to update reverse" + " mapping for ID=" + Arrays.toString(row), e); throw e; } // Now create the new forward mapping. try { final PutRequest forward_mapping = new PutRequest( table, newnameb, ID_FAMILY, kind, row); hbasePutWithRetry(forward_mapping, MAX_ATTEMPTS_PUT, INITIAL_EXP_BACKOFF_DELAY); } catch (HBaseException e) { LOG.error("When trying rename(\"" + oldname + "\", \"" + newname + "\") on " + this + ": Failed to create the" + " new forward mapping with ID=" + Arrays.toString(row), e); throw e; } // Update cache. addIdToCache(newname, row); // add new name -> ID id_cache.put(fromBytes(row), newname); // update ID -> new name name_cache.remove(oldname); // remove old name -> ID // Delete the old forward mapping. try { final DeleteRequest old_forward_mapping = new DeleteRequest( table, toBytes(oldname), ID_FAMILY, kind); client.delete(old_forward_mapping).joinUninterruptibly(); } catch (HBaseException e) { LOG.error("When trying rename(\"" + oldname + "\", \"" + newname + "\") on " + this + ": Failed to remove the" + " old forward mapping for ID=" + Arrays.toString(row), e); throw e; } catch (Exception e) { final String msg = "Unexpected exception when trying rename(\"" + oldname + "\", \"" + newname + "\") on " + this + ": Failed to remove the" + " old forward mapping for ID=" + Arrays.toString(row); LOG.error("WTF? " + msg, e); throw new RuntimeException(msg, e); } // Success! } /** The start row to scan on empty search strings. `!' = first ASCII char. */ private static final byte[] START_ROW = new byte[] { '!' }; /** The end row to scan on empty search strings. `~' = last ASCII char. */ private static final byte[] END_ROW = new byte[] { '~' }; /** * Creates a scanner that scans the right range of rows for suggestions. * @param search The string to start searching at * @param max_results The max number of results to return */ private Scanner getSuggestScanner(final String search, final int max_results) { final byte[] start_row; final byte[] end_row; if (search.isEmpty()) { start_row = START_ROW; end_row = END_ROW; } else { start_row = toBytes(search); end_row = Arrays.copyOf(start_row, start_row.length); end_row[start_row.length - 1]++; } final Scanner scanner = client.newScanner(table); scanner.setStartKey(start_row); scanner.setStopKey(end_row); scanner.setFamily(ID_FAMILY); scanner.setQualifier(kind); scanner.setMaxNumRows(max_results <= 4096 ? max_results : 4096); return scanner; } /** Returns the cell of the specified row key, using family:kind. */ private Deferred<byte[]> hbaseGet(final byte[] key, final byte[] family) { final GetRequest get = new GetRequest(table, key); get.family(family).qualifier(kind); class GetCB implements Callback<byte[], ArrayList<KeyValue>> { public byte[] call(final ArrayList<KeyValue> row) { if (row == null || row.isEmpty()) { return null; } return row.get(0).value(); } } return client.get(get).addCallback(new GetCB()); } /** * Attempts to run the PutRequest given in argument, retrying if needed. * * Puts are synchronized. * * @param put The PutRequest to execute. * @param attempts The maximum number of attempts. * @param wait The initial amount of time in ms to sleep for after a * failure. This amount is doubled after each failed attempt. * @throws HBaseException if all the attempts have failed. This exception * will be the exception of the last attempt. */ private void hbasePutWithRetry(final PutRequest put, short attempts, short wait) throws HBaseException { put.setBufferable(false); // TODO(tsuna): Remove once this code is async. while (attempts-- > 0) { try { client.put(put).joinUninterruptibly(); return; } catch (HBaseException e) { if (attempts > 0) { LOG.error("Put failed, attempts left=" + attempts + " (retrying in " + wait + " ms), put=" + put, e); try { Thread.sleep(wait); } catch (InterruptedException ie) { throw new RuntimeException("interrupted", ie); } wait *= 2; } else { throw e; } } catch (Exception e) { LOG.error("WTF? Unexpected exception type, put=" + put, e); } } throw new IllegalStateException("This code should never be reached!"); } private static byte[] toBytes(final String s) { return s.getBytes(CHARSET); } private static String fromBytes(final byte[] b) { return new String(b, CHARSET); } /** Returns a human readable string representation of the object. */ public String toString() { return "UniqueId(" + fromBytes(table) + ", " + kind() + ", " + id_width + ")"; } /** * Converts a byte array to a hex encoded, upper case string with padding * @param uid The ID to convert * @return the UID as a hex string * @throws NullPointerException if the ID was null * @since 2.0 */ public static String uidToString(final byte[] uid) { return DatatypeConverter.printHexBinary(uid); } /** * Converts a hex string to a byte array * If the {@code uid} is less than {@code uid_length * 2} characters wide, it * will be padded with 0s to conform to the spec. E.g. if the tagk width is 3 * and the given {@code uid} string is "1", the string will be padded to * "000001" and then converted to a byte array to reach 3 bytes. * All {@code uid}s are padded to 1 byte. If given "1", and {@code uid_length} * is 0, the uid will be padded to "01" then converted. * @param uid The UID to convert * @param uid_length An optional length, in bytes, that the UID must conform * to. Set to 0 if not used. * @return The UID as a byte array * @throws NullPointerException if the ID was null * @throws IllegalArgumentException if the string is not valid hex * @since 2.0 */ public static byte[] stringToUid(final String uid) { return stringToUid(uid, (short)0); } /** * Attempts to convert the given string to a type enumerator * @param type The string to convert * @return a valid UniqueIdType if matched * @throws IllegalArgumentException if the string did not match a type * @since 2.0 */ public static UniqueIdType stringToUniqueIdType(final String type) { if (type.toLowerCase().equals("metric") || type.toLowerCase().equals("metrics")) { return UniqueIdType.METRIC; } else if (type.toLowerCase().equals("tagk")) { return UniqueIdType.TAGK; } else if (type.toLowerCase().equals("tagv")) { return UniqueIdType.TAGV; } else { throw new IllegalArgumentException("Invalid type requested: " + type); } } /** * Converts a hex string to a byte array * If the {@code uid} is less than {@code uid_length * 2} characters wide, it * will be padded with 0s to conform to the spec. E.g. if the tagk width is 3 * and the given {@code uid} string is "1", the string will be padded to * "000001" and then converted to a byte array to reach 3 bytes. * All {@code uid}s are padded to 1 byte. If given "1", and {@code uid_length} * is 0, the uid will be padded to "01" then converted. * @param uid The UID to convert * @param uid_length An optional length, in bytes, that the UID must conform * to. Set to 0 if not used. * @return The UID as a byte array * @throws NullPointerException if the ID was null * @throws IllegalArgumentException if the string is not valid hex * @since 2.0 */ public static byte[] stringToUid(final String uid, final short uid_length) { if (uid == null || uid.isEmpty()) { throw new IllegalArgumentException("UID was empty"); } String id = uid; if (uid_length > 0) { while (id.length() < uid_length * 2) { id = "0" + id; } } else { if (id.length() % 2 > 0) { id = "0" + id; } } return DatatypeConverter.parseHexBinary(id); } /** * Extracts the TSUID from a storage row key that includes the timestamp. * @param row_key The row key to process * @param metric_width The width of the metric * @param timestamp_width The width of the timestamp * @return The TSUID * @throws ArrayIndexOutOfBoundsException if the row_key is invalid */ public static byte[] getTSUIDFromKey(final byte[] row_key, final short metric_width, final short timestamp_width) { int idx = 0; final byte[] tsuid = new byte[row_key.length - timestamp_width]; for (int i = 0; i < row_key.length; i++) { if (i < metric_width || i >= (metric_width + timestamp_width)) { tsuid[idx] = row_key[i]; idx++; } } return tsuid; } /** * Extracts a list of tagk/tagv pairs from a tsuid * @param tsuid The tsuid to parse * @param metric_width The width of the metric tag in bytes * @param tagk_width The width of tagks in bytes * @param tagv_width The width of tagvs in bytes * @return A list of tagk/tagv pairs alternating with tagk, tagv, tagk, tagv * @throws IllegalArgumentException if the TSUID is malformed */ public static List<byte[]> getTagPairsFromTSUID(final String tsuid, final short metric_width, final short tagk_width, final short tagv_width) { if (tsuid == null || tsuid.isEmpty()) { throw new IllegalArgumentException("Missing TSUID"); } if (tsuid.length() <= metric_width * 2) { throw new IllegalArgumentException( "TSUID is too short, may be missing tags"); } final List<byte[]> tags = new ArrayList<byte[]>(); final int pair_width = (tagk_width * 2) + (tagv_width * 2); // start after the metric then iterate over each tagk/tagv pair for (int i = metric_width * 2; i < tsuid.length(); i+= pair_width) { if (i + pair_width > tsuid.length()){ throw new IllegalArgumentException( "The TSUID appears to be malformed, improper tag width"); } String tag = tsuid.substring(i, i + (tagk_width * 2)); tags.add(UniqueId.stringToUid(tag)); tag = tsuid.substring(i + (tagk_width * 2), i + pair_width); tags.add(UniqueId.stringToUid(tag)); } return tags; } /** * Returns a map of max UIDs from storage for the given list of UID types * @param tsdb The TSDB to which we belong * @param kinds A list of qualifiers to fetch * @return A map with the "kind" as the key and the maximum assigned UID as * the value * @since 2.0 */ public static Deferred<Map<String, Long>> getUsedUIDs(final TSDB tsdb, final byte[][] kinds) { /** * Returns a map with 0 if the max ID row hasn't been initialized yet, * otherwise the map has actual data */ final class GetCB implements Callback<Map<String, Long>, ArrayList<KeyValue>> { @Override public Map<String, Long> call(final ArrayList<KeyValue> row) throws Exception { final Map<String, Long> results = new HashMap<String, Long>(3); if (row == null || row.isEmpty()) { // it could be the case that this is the first time the TSD has run // and the user hasn't put any metrics in, so log and return 0s LOG.info("Could not find the UID assignment row"); for (final byte[] kind : kinds) { results.put(new String(kind, CHARSET), 0L); } return results; } for (final KeyValue column : row) { results.put(new String(column.qualifier(), CHARSET), Bytes.getLong(column.value())); } return results; } } final GetRequest get = new GetRequest(tsdb.uidTable(), MAXID_ROW); get.family(ID_FAMILY); get.qualifiers(kinds); return tsdb.getClient().get(get).addCallback(new GetCB()); } }
src/uid/UniqueId.java
// This file is part of OpenTSDB. // Copyright (C) 2010-2012 The OpenTSDB Authors. // // This program is free software: you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 2.1 of the License, or (at your // option) any later version. This program is distributed in the hope that it // will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser // General Public License for more details. You should have received a copy // of the GNU Lesser General Public License along with this program. If not, // see <http://www.gnu.org/licenses/>. package net.opentsdb.uid; import java.nio.charset.Charset; import java.util.Arrays; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import com.stumbleupon.async.Callback; import com.stumbleupon.async.Deferred; import javax.xml.bind.DatatypeConverter; import net.opentsdb.core.TSDB; import net.opentsdb.meta.UIDMeta; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.hbase.async.AtomicIncrementRequest; import org.hbase.async.Bytes; import org.hbase.async.DeleteRequest; import org.hbase.async.GetRequest; import org.hbase.async.HBaseClient; import org.hbase.async.HBaseException; import org.hbase.async.KeyValue; import org.hbase.async.PutRequest; import org.hbase.async.Scanner; /** * Represents a table of Unique IDs, manages the lookup and creation of IDs. * <p> * Don't attempt to use {@code equals()} or {@code hashCode()} on * this class. * @see UniqueIdInterface */ @SuppressWarnings("deprecation") // Dunno why even with this, compiler warns. public final class UniqueId implements UniqueIdInterface { private static final Logger LOG = LoggerFactory.getLogger(UniqueId.class); /** Enumerator for different types of UIDS @since 2.0 */ public enum UniqueIdType { METRIC, TAGK, TAGV } /** Charset used to convert Strings to byte arrays and back. */ private static final Charset CHARSET = Charset.forName("ISO-8859-1"); /** The single column family used by this class. */ private static final byte[] ID_FAMILY = toBytes("id"); /** The single column family used by this class. */ private static final byte[] NAME_FAMILY = toBytes("name"); /** Row key of the special row used to track the max ID already assigned. */ private static final byte[] MAXID_ROW = { 0 }; /** How many time do we try to assign an ID before giving up. */ private static final short MAX_ATTEMPTS_ASSIGN_ID = 3; /** How many time do we try to apply an edit before giving up. */ private static final short MAX_ATTEMPTS_PUT = 6; /** Initial delay in ms for exponential backoff to retry failed RPCs. */ private static final short INITIAL_EXP_BACKOFF_DELAY = 800; /** Maximum number of results to return in suggest(). */ private static final short MAX_SUGGESTIONS = 25; /** HBase client to use. */ private final HBaseClient client; /** Table where IDs are stored. */ private final byte[] table; /** The kind of UniqueId, used as the column qualifier. */ private final byte[] kind; /** The type of UID represented by this cache */ private final UniqueIdType type; /** Number of bytes on which each ID is encoded. */ private final short id_width; /** Cache for forward mappings (name to ID). */ private final ConcurrentHashMap<String, byte[]> name_cache = new ConcurrentHashMap<String, byte[]>(); /** Cache for backward mappings (ID to name). * The ID in the key is a byte[] converted to a String to be Comparable. */ private final ConcurrentHashMap<String, String> id_cache = new ConcurrentHashMap<String, String>(); /** Number of times we avoided reading from HBase thanks to the cache. */ private volatile int cache_hits; /** Number of times we had to read from HBase and populate the cache. */ private volatile int cache_misses; /** Whether or not to generate new UIDMetas */ private TSDB tsdb; /** * Constructor. * @param client The HBase client to use. * @param table The name of the HBase table to use. * @param kind The kind of Unique ID this instance will deal with. * @param width The number of bytes on which Unique IDs should be encoded. * @throws IllegalArgumentException if width is negative or too small/large * or if kind is an empty string. */ public UniqueId(final HBaseClient client, final byte[] table, final String kind, final int width) { this.client = client; this.table = table; if (kind.isEmpty()) { throw new IllegalArgumentException("Empty string as 'kind' argument!"); } this.kind = toBytes(kind); type = stringToUniqueIdType(kind); if (width < 1 || width > 8) { throw new IllegalArgumentException("Invalid width: " + width); } this.id_width = (short) width; } /** The number of times we avoided reading from HBase thanks to the cache. */ public int cacheHits() { return cache_hits; } /** The number of times we had to read from HBase and populate the cache. */ public int cacheMisses() { return cache_misses; } /** Returns the number of elements stored in the internal cache. */ public int cacheSize() { return name_cache.size() + id_cache.size(); } public String kind() { return fromBytes(kind); } public short width() { return id_width; } /** @param Whether or not to track new UIDMeta objects */ public void setTSDB(final TSDB tsdb) { this.tsdb = tsdb; } /** The largest possible ID given the number of bytes the IDs are represented on. */ public long maxPossibleId() { return (1 << id_width * Byte.SIZE) - 1; } /** * Causes this instance to discard all its in-memory caches. * @since 1.1 */ public void dropCaches() { name_cache.clear(); id_cache.clear(); } /** * Finds the name associated with a given ID. * <p> * <strong>This method is blocking.</strong> Its use within OpenTSDB itself * is discouraged, please use {@link #getNameAsync} instead. * @param id The ID associated with that name. * @see #getId(String) * @see #getOrCreateId(String) * @throws NoSuchUniqueId if the given ID is not assigned. * @throws HBaseException if there is a problem communicating with HBase. * @throws IllegalArgumentException if the ID given in argument is encoded * on the wrong number of bytes. */ public String getName(final byte[] id) throws NoSuchUniqueId, HBaseException { try { return getNameAsync(id).joinUninterruptibly(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException("Should never be here", e); } } /** * Finds the name associated with a given ID. * * @param id The ID associated with that name. * @see #getId(String) * @see #getOrCreateIdAsync(String) * @throws NoSuchUniqueId if the given ID is not assigned. * @throws HBaseException if there is a problem communicating with HBase. * @throws IllegalArgumentException if the ID given in argument is encoded * on the wrong number of bytes. * @since 1.1 */ public Deferred<String> getNameAsync(final byte[] id) { if (id.length != id_width) { throw new IllegalArgumentException("Wrong id.length = " + id.length + " which is != " + id_width + " required for '" + kind() + '\''); } final String name = getNameFromCache(id); if (name != null) { cache_hits++; return Deferred.fromResult(name); } cache_misses++; class GetNameCB implements Callback<String, String> { public String call(final String name) { if (name == null) { throw new NoSuchUniqueId(kind(), id); } addNameToCache(id, name); addIdToCache(name, id); return name; } } return getNameFromHBase(id).addCallback(new GetNameCB()); } private String getNameFromCache(final byte[] id) { return id_cache.get(fromBytes(id)); } private Deferred<String> getNameFromHBase(final byte[] id) { class NameFromHBaseCB implements Callback<String, byte[]> { public String call(final byte[] name) { return name == null ? null : fromBytes(name); } } return hbaseGet(id, NAME_FAMILY).addCallback(new NameFromHBaseCB()); } private void addNameToCache(final byte[] id, final String name) { final String key = fromBytes(id); String found = id_cache.get(key); if (found == null) { found = id_cache.putIfAbsent(key, name); } if (found != null && !found.equals(name)) { throw new IllegalStateException("id=" + Arrays.toString(id) + " => name=" + name + ", already mapped to " + found); } } public byte[] getId(final String name) throws NoSuchUniqueName, HBaseException { try { return getIdAsync(name).joinUninterruptibly(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException("Should never be here", e); } } public Deferred<byte[]> getIdAsync(final String name) { final byte[] id = getIdFromCache(name); if (id != null) { cache_hits++; return Deferred.fromResult(id); } cache_misses++; class GetIdCB implements Callback<byte[], byte[]> { public byte[] call(final byte[] id) { if (id == null) { throw new NoSuchUniqueName(kind(), name); } if (id.length != id_width) { throw new IllegalStateException("Found id.length = " + id.length + " which is != " + id_width + " required for '" + kind() + '\''); } addIdToCache(name, id); addNameToCache(id, name); return id; } } Deferred<byte[]> d = getIdFromHBase(name).addCallback(new GetIdCB()); return d; } private byte[] getIdFromCache(final String name) { return name_cache.get(name); } private Deferred<byte[]> getIdFromHBase(final String name) { return hbaseGet(toBytes(name), ID_FAMILY); } private void addIdToCache(final String name, final byte[] id) { byte[] found = name_cache.get(name); if (found == null) { found = name_cache.putIfAbsent(name, // Must make a defensive copy to be immune // to any changes the caller may do on the // array later on. Arrays.copyOf(id, id.length)); } if (found != null && !Arrays.equals(found, id)) { throw new IllegalStateException("name=" + name + " => id=" + Arrays.toString(id) + ", already mapped to " + Arrays.toString(found)); } } /** * Implements the process to allocate a new UID. * This callback is re-used multiple times in a four step process: * 1. Allocate a new UID via atomic increment. * 2. Create the reverse mapping (ID to name). * 3. Create the forward mapping (name to ID). * 4. Return the new UID to the caller. */ private final class UniqueIdAllocator implements Callback<Object, Object> { private final String name; // What we're trying to allocate an ID for. private short attempt = MAX_ATTEMPTS_ASSIGN_ID; // Give up when zero. private HBaseException hbe = null; // Last exception caught. private long id = -1; // The ID we'll grab with an atomic increment. private byte row[]; // The same ID, as a byte array. private static final byte ALLOCATE_UID = 0; private static final byte CREATE_REVERSE_MAPPING = 1; private static final byte CREATE_FORWARD_MAPPING = 2; private static final byte DONE = 3; private byte state = ALLOCATE_UID; // Current state of the process. UniqueIdAllocator(final String name) { this.name = name; } @SuppressWarnings("unchecked") Deferred<byte[]> tryAllocate() { attempt--; state = ALLOCATE_UID; return (Deferred<byte[]>) call(null); } @SuppressWarnings("unchecked") public Object call(final Object arg) { if (attempt == 0) { if (hbe == null) { throw new IllegalStateException("Should never happen!"); } LOG.error("Failed to assign an ID for kind='" + kind() + "' name='" + name + "'", hbe); throw hbe; } if (arg instanceof Exception) { final String msg = ("Failed attempt #" + (MAX_ATTEMPTS_ASSIGN_ID - attempt) + " to assign an UID for " + kind() + ':' + name + " at step #" + state); if (arg instanceof HBaseException) { LOG.error(msg, (Exception) arg); hbe = (HBaseException) arg; return tryAllocate(); // Retry from the beginning. } else { LOG.error("WTF? Unexpected exception! " + msg, (Exception) arg); return arg; // Unexpected exception, let it bubble up. } } final Deferred d; switch (state) { case ALLOCATE_UID: d = allocateUid(); break; case CREATE_REVERSE_MAPPING: d = createReverseMapping(arg); break; case CREATE_FORWARD_MAPPING: d = createForwardMapping(arg); break; case DONE: return done(arg); default: throw new AssertionError("Should never be here!"); } return d.addBoth(this); } private Deferred<Long> allocateUid() { LOG.info("Creating an ID for kind='" + kind() + "' name='" + name + '\''); state = CREATE_REVERSE_MAPPING; return client.atomicIncrement(new AtomicIncrementRequest(table, MAXID_ROW, ID_FAMILY, kind)); } /** * Create the reverse mapping. * We do this before the forward one so that if we die before creating * the forward mapping we don't run the risk of "publishing" a * partially assigned ID. The reverse mapping on its own is harmless * but the forward mapping without reverse mapping is bad as it would * point to an ID that cannot be resolved. */ private Deferred<Boolean> createReverseMapping(final Object arg) { if (!(arg instanceof Long)) { throw new IllegalStateException("Expected a Long but got " + arg); } id = (Long) arg; if (id <= 0) { throw new IllegalStateException("Got a negative ID from HBase: " + id); } LOG.info("Got ID=" + id + " for kind='" + kind() + "' name='" + name + "'"); row = Bytes.fromLong(id); // row.length should actually be 8. if (row.length < id_width) { throw new IllegalStateException("OMG, row.length = " + row.length + " which is less than " + id_width + " for id=" + id + " row=" + Arrays.toString(row)); } // Verify that we're going to drop bytes that are 0. for (int i = 0; i < row.length - id_width; i++) { if (row[i] != 0) { final String message = "All Unique IDs for " + kind() + " on " + id_width + " bytes are already assigned!"; LOG.error("OMG " + message); throw new IllegalStateException(message); } } // Shrink the ID on the requested number of bytes. row = Arrays.copyOfRange(row, row.length - id_width, row.length); state = CREATE_FORWARD_MAPPING; // We are CAS'ing the KV into existence -- the second argument is how // we tell HBase we want to atomically create the KV, so that if there // is already a KV in this cell, we'll fail. Technically we could do // just a `put' here, as we have a freshly allocated UID, so there is // not reason why a KV should already exist for this UID, but just to // err on the safe side and catch really weird corruption cases, we do // a CAS instead to create the KV. return client.compareAndSet(reverseMapping(), HBaseClient.EMPTY_ARRAY); } private PutRequest reverseMapping() { return new PutRequest(table, row, NAME_FAMILY, kind, toBytes(name)); } private Deferred<?> createForwardMapping(final Object arg) { if (!(arg instanceof Boolean)) { throw new IllegalStateException("Expected a Boolean but got " + arg); } if (!((Boolean) arg)) { // Previous CAS failed. Something is really messed up. LOG.error("WTF! Failed to CAS reverse mapping: " + reverseMapping() + " -- run an fsck against the UID table!"); return tryAllocate(); // Try again from the beginning. } state = DONE; return client.compareAndSet(forwardMapping(), HBaseClient.EMPTY_ARRAY); } private PutRequest forwardMapping() { return new PutRequest(table, toBytes(name), ID_FAMILY, kind, row); } private Deferred<byte[]> done(final Object arg) { if (!(arg instanceof Boolean)) { throw new IllegalStateException("Expected a Boolean but got " + arg); } if (!((Boolean) arg)) { // Previous CAS failed. We lost a race. LOG.warn("Race condition: tried to assign ID " + id + " to " + kind() + ":" + name + ", but CAS failed on " + forwardMapping() + ", which indicates this UID must have" + " been allocated concurrently by another TSD. So ID " + id + " was leaked."); // If two TSDs attempted to allocate a UID for the same name at the // same time, they would both have allocated a UID, and created a // reverse mapping, and upon getting here, only one of them would // manage to CAS this KV into existence. The one that loses the // race will retry and discover the UID assigned by the winner TSD, // and a UID will have been wasted in the process. No big deal. return getIdAsync(name); } addIdToCache(name, row); addNameToCache(row, name); if (tsdb != null && tsdb.getConfig().enable_realtime_uid()) { final UIDMeta meta = new UIDMeta(type, row, name); meta.storeNew(tsdb); LOG.info("Wrote UIDMeta for: " + name); tsdb.indexUIDMeta(meta); } return Deferred.fromResult(row); } } /** * Finds the ID associated with a given name or creates it. * <p> * <strong>This method is blocking.</strong> Its use within OpenTSDB itself * is discouraged, please use {@link #getOrCreateIdAsync} instead. * <p> * The length of the byte array is fixed in advance by the implementation. * * @param name The name to lookup in the table or to assign an ID to. * @throws HBaseException if there is a problem communicating with HBase. * @throws IllegalStateException if all possible IDs are already assigned. * @throws IllegalStateException if the ID found in HBase is encoded on the * wrong number of bytes. */ public byte[] getOrCreateId(final String name) throws HBaseException { try { return getOrCreateIdAsync(name).joinUninterruptibly(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException("Should never be here", e); } } /** * Finds the ID associated with a given name or creates it. * <p> * The length of the byte array is fixed in advance by the implementation. * * @param name The name to lookup in the table or to assign an ID to. * @throws HBaseException if there is a problem communicating with HBase. * @throws IllegalStateException if all possible IDs are already assigned. * @throws IllegalStateException if the ID found in HBase is encoded on the * wrong number of bytes. * @since 1.2 */ public Deferred<byte[]> getOrCreateIdAsync(final String name) { // Look in the cache first. final byte[] id = getIdFromCache(name); if (id != null) { cache_hits++; return Deferred.fromResult(id); } // Not found in our cache, so look in HBase instead. class HandleNoSuchUniqueNameCB implements Callback<Object, Exception> { public Object call(final Exception e) { if (e instanceof NoSuchUniqueName) { return new UniqueIdAllocator(name).tryAllocate(); } return e; // Other unexpected exception, let it bubble up. } } // Kick off the HBase lookup, and if we don't find it there either, start // the process to allocate a UID. return getIdAsync(name).addErrback(new HandleNoSuchUniqueNameCB()); } /** * Attempts to find suggestions of names given a search term. * <p> * <strong>This method is blocking.</strong> Its use within OpenTSDB itself * is discouraged, please use {@link #suggestAsync} instead. * @param search The search term (possibly empty). * @param max_results The number of results to return. Must be 1 or greater * @return A list of known valid names that have UIDs that sort of match * the search term. If the search term is empty, returns the first few * terms. * @throws HBaseException if there was a problem getting suggestions from * HBase. */ public List<String> suggest(final String search) throws HBaseException { return suggest(search, MAX_SUGGESTIONS); } /** * Attempts to find suggestions of names given a search term. * @param search The search term (possibly empty). * @param max_results The number of results to return. Must be 1 or greater * @return A list of known valid names that have UIDs that sort of match * the search term. If the search term is empty, returns the first few * terms. * @throws HBaseException if there was a problem getting suggestions from * HBase. * @throws IllegalArgumentException if the count was less than 1 * @since 2.0 */ public List<String> suggest(final String search, final int max_results) throws HBaseException { if (max_results < 1) { throw new IllegalArgumentException("Count must be greater than 0"); } try { return suggestAsync(search, max_results).joinUninterruptibly(); } catch (HBaseException e) { throw e; } catch (Exception e) { // Should never happen. final String msg = "Unexpected exception caught by " + this + ".suggest(" + search + ')'; LOG.error(msg, e); throw new RuntimeException(msg, e); // Should never happen. } } /** * Attempts to find suggestions of names given a search term. * @param search The search term (possibly empty). * @return A list of known valid names that have UIDs that sort of match * the search term. If the search term is empty, returns the first few * terms. * @throws HBaseException if there was a problem getting suggestions from * HBase. * @since 1.1 */ public Deferred<List<String>> suggestAsync(final String search, final int max_results) { return new SuggestCB(search, max_results).search(); } /** * Helper callback to asynchronously scan HBase for suggestions. */ private final class SuggestCB implements Callback<Object, ArrayList<ArrayList<KeyValue>>> { private final LinkedList<String> suggestions = new LinkedList<String>(); private final Scanner scanner; private final int max_results; SuggestCB(final String search, final int max_results) { this.max_results = max_results; this.scanner = getSuggestScanner(search, max_results); } @SuppressWarnings("unchecked") Deferred<List<String>> search() { return (Deferred) scanner.nextRows().addCallback(this); } public Object call(final ArrayList<ArrayList<KeyValue>> rows) { if (rows == null) { // We're done scanning. return suggestions; } for (final ArrayList<KeyValue> row : rows) { if (row.size() != 1) { LOG.error("WTF shouldn't happen! Scanner " + scanner + " returned" + " a row that doesn't have exactly 1 KeyValue: " + row); if (row.isEmpty()) { continue; } } final byte[] key = row.get(0).key(); final String name = fromBytes(key); final byte[] id = row.get(0).value(); final byte[] cached_id = name_cache.get(name); if (cached_id == null) { addIdToCache(name, id); addNameToCache(id, name); } else if (!Arrays.equals(id, cached_id)) { throw new IllegalStateException("WTF? For kind=" + kind() + " name=" + name + ", we have id=" + Arrays.toString(cached_id) + " in cache, but just scanned id=" + Arrays.toString(id)); } suggestions.add(name); if ((short) suggestions.size() > max_results) { // We have enough. return suggestions; } row.clear(); // free() } return search(); // Get more suggestions. } } /** * Reassigns the UID to a different name (non-atomic). * <p> * Whatever was the UID of {@code oldname} will be given to {@code newname}. * {@code oldname} will no longer be assigned a UID. * <p> * Beware that the assignment change is <b>not atommic</b>. If two threads * or processes attempt to rename the same UID differently, the result is * unspecified and might even be inconsistent. This API is only here for * administrative purposes, not for normal programmatic interactions. * @param oldname The old name to rename. * @param newname The new name. * @throws NoSuchUniqueName if {@code oldname} wasn't assigned. * @throws IllegalArgumentException if {@code newname} was already assigned. * @throws HBaseException if there was a problem with HBase while trying to * update the mapping. */ public void rename(final String oldname, final String newname) { final byte[] row = getId(oldname); { byte[] id = null; try { id = getId(newname); } catch (NoSuchUniqueName e) { // OK, we don't want the new name to be assigned. } if (id != null) { throw new IllegalArgumentException("When trying rename(\"" + oldname + "\", \"" + newname + "\") on " + this + ": new name already" + " assigned ID=" + Arrays.toString(id)); } } final byte[] newnameb = toBytes(newname); // Update the reverse mapping first, so that if we die before updating // the forward mapping we don't run the risk of "publishing" a // partially assigned ID. The reverse mapping on its own is harmless // but the forward mapping without reverse mapping is bad. try { final PutRequest reverse_mapping = new PutRequest( table, row, NAME_FAMILY, kind, newnameb); hbasePutWithRetry(reverse_mapping, MAX_ATTEMPTS_PUT, INITIAL_EXP_BACKOFF_DELAY); } catch (HBaseException e) { LOG.error("When trying rename(\"" + oldname + "\", \"" + newname + "\") on " + this + ": Failed to update reverse" + " mapping for ID=" + Arrays.toString(row), e); throw e; } // Now create the new forward mapping. try { final PutRequest forward_mapping = new PutRequest( table, newnameb, ID_FAMILY, kind, row); hbasePutWithRetry(forward_mapping, MAX_ATTEMPTS_PUT, INITIAL_EXP_BACKOFF_DELAY); } catch (HBaseException e) { LOG.error("When trying rename(\"" + oldname + "\", \"" + newname + "\") on " + this + ": Failed to create the" + " new forward mapping with ID=" + Arrays.toString(row), e); throw e; } // Update cache. addIdToCache(newname, row); // add new name -> ID id_cache.put(fromBytes(row), newname); // update ID -> new name name_cache.remove(oldname); // remove old name -> ID // Delete the old forward mapping. try { final DeleteRequest old_forward_mapping = new DeleteRequest( table, toBytes(oldname), ID_FAMILY, kind); client.delete(old_forward_mapping).joinUninterruptibly(); } catch (HBaseException e) { LOG.error("When trying rename(\"" + oldname + "\", \"" + newname + "\") on " + this + ": Failed to remove the" + " old forward mapping for ID=" + Arrays.toString(row), e); throw e; } catch (Exception e) { final String msg = "Unexpected exception when trying rename(\"" + oldname + "\", \"" + newname + "\") on " + this + ": Failed to remove the" + " old forward mapping for ID=" + Arrays.toString(row); LOG.error("WTF? " + msg, e); throw new RuntimeException(msg, e); } // Success! } /** The start row to scan on empty search strings. `!' = first ASCII char. */ private static final byte[] START_ROW = new byte[] { '!' }; /** The end row to scan on empty search strings. `~' = last ASCII char. */ private static final byte[] END_ROW = new byte[] { '~' }; /** * Creates a scanner that scans the right range of rows for suggestions. * @param search The string to start searching at * @param max_results The max number of results to return */ private Scanner getSuggestScanner(final String search, final int max_results) { final byte[] start_row; final byte[] end_row; if (search.isEmpty()) { start_row = START_ROW; end_row = END_ROW; } else { start_row = toBytes(search); end_row = Arrays.copyOf(start_row, start_row.length); end_row[start_row.length - 1]++; } final Scanner scanner = client.newScanner(table); scanner.setStartKey(start_row); scanner.setStopKey(end_row); scanner.setFamily(ID_FAMILY); scanner.setQualifier(kind); scanner.setMaxNumRows(max_results <= 4096 ? max_results : 4096); return scanner; } /** Returns the cell of the specified row key, using family:kind. */ private Deferred<byte[]> hbaseGet(final byte[] key, final byte[] family) { final GetRequest get = new GetRequest(table, key); get.family(family).qualifier(kind); class GetCB implements Callback<byte[], ArrayList<KeyValue>> { public byte[] call(final ArrayList<KeyValue> row) { if (row == null || row.isEmpty()) { return null; } return row.get(0).value(); } } return client.get(get).addCallback(new GetCB()); } /** * Attempts to run the PutRequest given in argument, retrying if needed. * * Puts are synchronized. * * @param put The PutRequest to execute. * @param attempts The maximum number of attempts. * @param wait The initial amount of time in ms to sleep for after a * failure. This amount is doubled after each failed attempt. * @throws HBaseException if all the attempts have failed. This exception * will be the exception of the last attempt. */ private void hbasePutWithRetry(final PutRequest put, short attempts, short wait) throws HBaseException { put.setBufferable(false); // TODO(tsuna): Remove once this code is async. while (attempts-- > 0) { try { client.put(put).joinUninterruptibly(); return; } catch (HBaseException e) { if (attempts > 0) { LOG.error("Put failed, attempts left=" + attempts + " (retrying in " + wait + " ms), put=" + put, e); try { Thread.sleep(wait); } catch (InterruptedException ie) { throw new RuntimeException("interrupted", ie); } wait *= 2; } else { throw e; } } catch (Exception e) { LOG.error("WTF? Unexpected exception type, put=" + put, e); } } throw new IllegalStateException("This code should never be reached!"); } private static byte[] toBytes(final String s) { return s.getBytes(CHARSET); } private static String fromBytes(final byte[] b) { return new String(b, CHARSET); } /** Returns a human readable string representation of the object. */ public String toString() { return "UniqueId(" + fromBytes(table) + ", " + kind() + ", " + id_width + ")"; } /** * Converts a byte array to a hex encoded, upper case string with padding * @param uid The ID to convert * @return the UID as a hex string * @throws NullPointerException if the ID was null * @since 2.0 */ public static String uidToString(final byte[] uid) { return DatatypeConverter.printHexBinary(uid); } /** * Converts a hex string to a byte array * If the {@code uid} is less than {@code uid_length * 2} characters wide, it * will be padded with 0s to conform to the spec. E.g. if the tagk width is 3 * and the given {@code uid} string is "1", the string will be padded to * "000001" and then converted to a byte array to reach 3 bytes. * All {@code uid}s are padded to 1 byte. If given "1", and {@code uid_length} * is 0, the uid will be padded to "01" then converted. * @param uid The UID to convert * @param uid_length An optional length, in bytes, that the UID must conform * to. Set to 0 if not used. * @return The UID as a byte array * @throws NullPointerException if the ID was null * @throws IllegalArgumentException if the string is not valid hex * @since 2.0 */ public static byte[] stringToUid(final String uid) { return stringToUid(uid, (short)0); } /** * Attempts to convert the given string to a type enumerator * @param type The string to convert * @return a valid UniqueIdType if matched * @throws IllegalArgumentException if the string did not match a type * @since 2.0 */ public static UniqueIdType stringToUniqueIdType(final String type) { if (type.toLowerCase().equals("metric") || type.toLowerCase().equals("metrics")) { return UniqueIdType.METRIC; } else if (type.toLowerCase().equals("tagk")) { return UniqueIdType.TAGK; } else if (type.toLowerCase().equals("tagv")) { return UniqueIdType.TAGV; } else { throw new IllegalArgumentException("Invalid type requested: " + type); } } /** * Converts a hex string to a byte array * If the {@code uid} is less than {@code uid_length * 2} characters wide, it * will be padded with 0s to conform to the spec. E.g. if the tagk width is 3 * and the given {@code uid} string is "1", the string will be padded to * "000001" and then converted to a byte array to reach 3 bytes. * All {@code uid}s are padded to 1 byte. If given "1", and {@code uid_length} * is 0, the uid will be padded to "01" then converted. * @param uid The UID to convert * @param uid_length An optional length, in bytes, that the UID must conform * to. Set to 0 if not used. * @return The UID as a byte array * @throws NullPointerException if the ID was null * @throws IllegalArgumentException if the string is not valid hex * @since 2.0 */ public static byte[] stringToUid(final String uid, final short uid_length) { if (uid == null || uid.isEmpty()) { throw new IllegalArgumentException("UID was empty"); } String id = uid; if (uid_length > 0) { while (id.length() < uid_length * 2) { id = "0" + id; } } else { if (id.length() % 2 > 0) { id = "0" + id; } } return DatatypeConverter.parseHexBinary(id); } /** * Extracts the TSUID from a storage row key that includes the timestamp. * @param row_key The row key to process * @param metric_width The width of the metric * @param timestamp_width The width of the timestamp * @return The TSUID * @throws ArrayIndexOutOfBoundsException if the row_key is invalid */ public static byte[] getTSUIDFromKey(final byte[] row_key, final short metric_width, final short timestamp_width) { int idx = 0; final byte[] tsuid = new byte[row_key.length - timestamp_width]; for (int i = 0; i < row_key.length; i++) { if (i < metric_width || i >= (metric_width + timestamp_width)) { tsuid[idx] = row_key[i]; idx++; } } return tsuid; } /** * Extracts a list of tagk/tagv pairs from a tsuid * @param tsuid The tsuid to parse * @param metric_width The width of the metric tag in bytes * @param tagk_width The width of tagks in bytes * @param tagv_width The width of tagvs in bytes * @return A list of tagk/tagv pairs alternating with tagk, tagv, tagk, tagv * @throws IllegalArgumentException if the TSUID is malformed */ public static List<byte[]> getTagPairsFromTSUID(final String tsuid, final short metric_width, final short tagk_width, final short tagv_width) { if (tsuid == null || tsuid.isEmpty()) { throw new IllegalArgumentException("Missing TSUID"); } if (tsuid.length() <= metric_width * 2) { throw new IllegalArgumentException( "TSUID is too short, may be missing tags"); } final List<byte[]> tags = new ArrayList<byte[]>(); final int pair_width = (tagk_width * 2) + (tagv_width * 2); // start after the metric then iterate over each tagk/tagv pair for (int i = metric_width * 2; i < tsuid.length(); i+= pair_width) { if (i + pair_width > tsuid.length()){ throw new IllegalArgumentException( "The TSUID appears to be malformed, improper tag width"); } String tag = tsuid.substring(i, i + (tagk_width * 2)); tags.add(UniqueId.stringToUid(tag)); tag = tsuid.substring(i + (tagk_width * 2), i + pair_width); tags.add(UniqueId.stringToUid(tag)); } return tags; } /** * Returns a map of max UIDs from storage for the given list of UID types * @param tsdb The TSDB to which we belong * @param kinds A list of qualifiers to fetch * @return A map with the "kind" as the key and the maximum assigned UID as * the value * @since 2.0 */ public static Deferred<Map<String, Long>> getUsedUIDs(final TSDB tsdb, final byte[][] kinds) { /** * Returns a map with 0 if the max ID row hasn't been initialized yet, * otherwise the map has actual data */ final class GetCB implements Callback<Map<String, Long>, ArrayList<KeyValue>> { @Override public Map<String, Long> call(final ArrayList<KeyValue> row) throws Exception { final Map<String, Long> results = new HashMap<String, Long>(3); if (row == null || row.isEmpty()) { // it could be the case that this is the first time the TSD has run // and the user hasn't put any metrics in, so log and return 0s LOG.info("Could not find the UID assignment row"); for (final byte[] kind : kinds) { results.put(new String(kind, CHARSET), 0L); } return results; } for (final KeyValue column : row) { results.put(new String(column.qualifier(), CHARSET), Bytes.getLong(column.value())); } return results; } } final GetRequest get = new GetRequest(tsdb.uidTable(), MAXID_ROW); get.family(ID_FAMILY); get.qualifiers(kinds); return tsdb.getClient().get(get).addCallback(new GetCB()); } }
Factor out a bit of UniqueId code. Signed-off-by: Chris Larsen <83037b211e1d109d6858769a113e269c3139ffd3@euphoriaaudio.com>
src/uid/UniqueId.java
Factor out a bit of UniqueId code.
Java
apache-2.0
24b4f5238276f3a7a06c08778d0d945903acbbf9
0
arnost-starosta/midpoint,rpudil/midpoint,gureronder/midpoint,gureronder/midpoint,PetrGasparik/midpoint,Pardus-Engerek/engerek,arnost-starosta/midpoint,rpudil/midpoint,sabriarabacioglu/engerek,arnost-starosta/midpoint,PetrGasparik/midpoint,sabriarabacioglu/engerek,arnost-starosta/midpoint,sabriarabacioglu/engerek,rpudil/midpoint,gureronder/midpoint,Pardus-Engerek/engerek,PetrGasparik/midpoint,PetrGasparik/midpoint,gureronder/midpoint,rpudil/midpoint,Pardus-Engerek/engerek,Pardus-Engerek/engerek,arnost-starosta/midpoint
/* * Copyright (c) 2012 Evolveum * * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the License). You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1 or * CDDLv1.0.txt file in the source code distribution. * See the License for the specific language governing * permission and limitations under the License. * * If applicable, add the following below the CDDL Header, * with the fields enclosed by brackets [] replaced by * your own identifying information: * * Portions Copyrighted 2012 [name of copyright owner] */ package com.evolveum.midpoint.common; import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.holder.XPathHolder; import com.evolveum.midpoint.util.DOMUtil; import com.evolveum.midpoint.util.JAXBUtil; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.xml.ns._public.common.common_1.ObjectType; import com.evolveum.midpoint.xml.ns._public.common.common_1.QueryType; import com.evolveum.midpoint.xml.ns._public.common.common_1.ResourceType; import org.apache.commons.lang.Validate; import org.w3c.dom.Document; import org.w3c.dom.Element; import javax.xml.bind.JAXBException; import javax.xml.namespace.QName; import java.util.ArrayList; import java.util.List; /** * @author semancik */ public class QueryUtil { @Deprecated public static Element createTypeFilter(Document doc, String uri) { Validate.notNull(doc); Validate.notNull(uri); Validate.notEmpty(uri); Element type = doc.createElementNS(SchemaConstants.C_FILTER_TYPE.getNamespaceURI(), SchemaConstants.C_FILTER_TYPE.getLocalPart()); type.setAttributeNS(SchemaConstants.C_FILTER_TYPE_URI.getNamespaceURI(), SchemaConstants.C_FILTER_TYPE_URI.getLocalPart(), uri); return type; } /** * Creates "equal" filter segment for multi-valued properties based on DOM representation. * * @param doc * @param xpath property container xpath. may be null. * @param values * @return "equal" filter segment (as DOM) * @throws JAXBException */ public static Element createEqualFilter(Document doc, XPathHolder xpath, List<? extends Object> values, PrismContext prismContext) throws SchemaException { Validate.notNull(doc); Validate.notNull(values); Validate.notEmpty(values); Element equal = doc.createElementNS(SchemaConstants.C_FILTER_EQUAL.getNamespaceURI(), SchemaConstants.C_FILTER_EQUAL.getLocalPart()); Element value = doc.createElementNS(SchemaConstants.C_FILTER_VALUE.getNamespaceURI(), SchemaConstants.C_FILTER_VALUE.getLocalPart()); for (Object val : values) { Element domElement; try { domElement = prismContext.getPrismJaxbProcessor().toDomElement(val, doc); // domElement = JAXBUtil.toDomElement(val); } catch (JAXBException e) { throw new SchemaException("Unexpected JAXB problem while creating search filer for value " + val, e); } value.appendChild(doc.importNode(domElement, true)); } if (xpath != null) { Element path = xpath.toElement(SchemaConstants.C_FILTER_PATH, doc); equal.appendChild(doc.importNode(path, true)); } equal.appendChild(doc.importNode(value, true)); return equal; } /** * Creates "equal" filter segment for single-valued properties based on DOM representation. * * @param doc * @param xpath property container xpath. may be null. * @param value * @return "equal" filter segment (as DOM) * @throws JAXBException */ public static Element createEqualFilter(Document doc, XPathHolder xpath, Object object) throws SchemaException { Validate.notNull(doc); Validate.notNull(object); //todo this was bad recursion // List<Object> values = new ArrayList<Object>(); // values.add(value); // return createEqualFilter(doc, xpath, values); //todo bad quick fix HACK Element equal = doc.createElementNS(SchemaConstants.C_FILTER_EQUAL.getNamespaceURI(), SchemaConstants.C_FILTER_EQUAL.getLocalPart()); Element value = doc.createElementNS(SchemaConstants.C_FILTER_VALUE.getNamespaceURI(), SchemaConstants.C_FILTER_VALUE.getLocalPart()); Element domElement=doc.createElementNS(SchemaConstants.C_FILTER_VALUE.getNamespaceURI(), "fixMe"); domElement.setTextContent(object.toString()); value.appendChild(doc.importNode(domElement, true)); if (xpath != null) { Element path = xpath.toElement(SchemaConstants.C_FILTER_PATH, doc); equal.appendChild(doc.importNode(path, true)); } equal.appendChild(doc.importNode(value, true)); return equal; } /** * Creates "equal" filter segment for single-valued properties with string content. * * @param doc * @param xpath property container xpath. may be null. * @param value * @return "equal" filter segment (as DOM) * @throws JAXBException */ public static Element createEqualFilter(Document doc, XPathHolder xpath, QName properyName, String value) throws SchemaException { Validate.notNull(doc); Validate.notNull(properyName); Validate.notNull(value); Element element = doc.createElementNS(properyName.getNamespaceURI(), properyName.getLocalPart()); element.setTextContent(value); List<Element> values = new ArrayList<Element>(); values.add(element); return createEqualFilter(doc, xpath, values); } /** * Creates "equal" filter segment for single-valued properties with QName content. * * @param doc * @param xpath property container xpath. may be null. * @param value * @return "equal" filter segment (as DOM) * @throws JAXBException */ public static Element createEqualFilter(Document doc, XPathHolder xpath, QName properyName, QName value) throws SchemaException { Validate.notNull(doc); Validate.notNull(properyName); Validate.notNull(value); Element element = doc.createElementNS(properyName.getNamespaceURI(), properyName.getLocalPart()); DOMUtil.setQNameValue(element, value); List<Element> values = new ArrayList<Element>(); values.add(element); return createEqualFilter(doc, xpath, values); } /** * Creates "equal" filter for object reference. * * @param doc * @param xpath property container xpath. may be null. * @param propertyName name of the reference property (e.g. "resourceRef") * @param oid OID of the referenced object * @return "equal" filter segment (as DOM) * @throws JAXBException */ public static Element createEqualRefFilter(Document doc, XPathHolder xpath, QName propertyName, String oid) throws SchemaException { Element value = doc.createElementNS(propertyName.getNamespaceURI(), propertyName.getLocalPart()); value.setAttributeNS(SchemaConstants.C_OID_ATTRIBUTE.getNamespaceURI(), SchemaConstants.C_OID_ATTRIBUTE.getLocalPart(), oid); return createEqualFilter(doc, xpath, value); } public static Element createAndFilter(Document doc, Element... conditions) { Validate.notNull(doc); Validate.notNull(conditions); Element and = doc.createElementNS(SchemaConstants.C_FILTER_AND.getNamespaceURI(), SchemaConstants.C_FILTER_AND.getLocalPart()); for (Element condition : conditions) { Validate.notNull(condition); and.appendChild(condition); } return and; } // public static Element createAndFilter(Document doc, Element el1, Element el2) { // Validate.notNull(doc); // Validate.notNull(el1); // Validate.notNull(el2); // // Element and = doc.createElementNS(SchemaConstants.C_FILTER_AND.getNamespaceURI(), SchemaConstants.C_FILTER_AND.getLocalPart()); // and.appendChild(el1); // and.appendChild(el2); // return and; // } // // public static Element createAndFilter(Document doc, Element el1, Element el2, Element el3) { // Validate.notNull(doc); // Validate.notNull(el1); // Validate.notNull(el2); // Validate.notNull(el3); // // Element and = doc.createElementNS(SchemaConstants.C_FILTER_AND.getNamespaceURI(), SchemaConstants.C_FILTER_AND.getLocalPart()); // and.appendChild(el1); // and.appendChild(el2); // and.appendChild(el3); // return and; // } public static QueryType createNameQuery(String name) throws SchemaException { Document doc = DOMUtil.getDocument(); Element filter = QueryUtil.createEqualFilter(doc, null, SchemaConstants.C_NAME, name); QueryType query = new QueryType(); query.setFilter(filter); return query; } public static QueryType createNameQuery(ObjectType object) throws SchemaException { return createNameQuery(object.getName()); } @Deprecated public static <T extends ObjectType> Element createNameAndClassFilter(Class<T> type, String name) throws SchemaException { Document doc = DOMUtil.getDocument(); return QueryUtil.createEqualFilter(doc, null, SchemaConstants.C_NAME, name); } public static QueryType createQuery(Element filter) { QueryType query = new QueryType(); query.setFilter(filter); return query; } /** * Returns query that returns all objects. */ public static QueryType createAllObjectsQuery() { // Create empty filter. This returns all objects of a type given as an argument to searchObjects. return new QueryType(); } public static QueryType createResourceAndAccountQuery(ResourceType resource, QName objectClass, String accountType) throws SchemaException { Document doc = DOMUtil.getDocument(); Element filter = QueryUtil.createAndFilter(doc, // TODO: The account type is hardcoded now, it should determined // from the schema later, or maybe we can make it entirely // generic (use ResourceObjectShadowType instead). QueryUtil.createEqualRefFilter(doc, null, SchemaConstants.I_RESOURCE_REF, resource.getOid()), QueryUtil.createEqualFilter(doc, null, SchemaConstants.I_OBJECT_CLASS, objectClass) ); QueryType query = new QueryType(); query.setFilter(filter); return query; } public static String dump(QueryType query) { StringBuilder sb = new StringBuilder("Query("); sb.append(query.getDescription()).append("):\n"); sb.append(DOMUtil.serializeDOMToString(query.getFilter())); return sb.toString(); } }
infra/common/src/main/java/com/evolveum/midpoint/common/QueryUtil.java
/* * Copyright (c) 2012 Evolveum * * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the License). You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1 or * CDDLv1.0.txt file in the source code distribution. * See the License for the specific language governing * permission and limitations under the License. * * If applicable, add the following below the CDDL Header, * with the fields enclosed by brackets [] replaced by * your own identifying information: * * Portions Copyrighted 2012 [name of copyright owner] */ package com.evolveum.midpoint.common; import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.holder.XPathHolder; import com.evolveum.midpoint.util.DOMUtil; import com.evolveum.midpoint.util.JAXBUtil; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.xml.ns._public.common.common_1.ObjectType; import com.evolveum.midpoint.xml.ns._public.common.common_1.QueryType; import com.evolveum.midpoint.xml.ns._public.common.common_1.ResourceType; import org.apache.commons.lang.Validate; import org.w3c.dom.Document; import org.w3c.dom.Element; import javax.xml.bind.JAXBException; import javax.xml.namespace.QName; import java.util.ArrayList; import java.util.List; /** * @author semancik */ public class QueryUtil { @Deprecated public static Element createTypeFilter(Document doc, String uri) { Validate.notNull(doc); Validate.notNull(uri); Validate.notEmpty(uri); Element type = doc.createElementNS(SchemaConstants.C_FILTER_TYPE.getNamespaceURI(), SchemaConstants.C_FILTER_TYPE.getLocalPart()); type.setAttributeNS(SchemaConstants.C_FILTER_TYPE_URI.getNamespaceURI(), SchemaConstants.C_FILTER_TYPE_URI.getLocalPart(), uri); return type; } /** * Creates "equal" filter segment for multi-valued properties based on DOM representation. * * @param doc * @param xpath property container xpath. may be null. * @param values * @return "equal" filter segment (as DOM) * @throws JAXBException */ public static Element createEqualFilter(Document doc, XPathHolder xpath, List<? extends Object> values, PrismContext prismContext) throws SchemaException { Validate.notNull(doc); Validate.notNull(values); Validate.notEmpty(values); Element equal = doc.createElementNS(SchemaConstants.C_FILTER_EQUAL.getNamespaceURI(), SchemaConstants.C_FILTER_EQUAL.getLocalPart()); Element value = doc.createElementNS(SchemaConstants.C_FILTER_VALUE.getNamespaceURI(), SchemaConstants.C_FILTER_VALUE.getLocalPart()); for (Object val : values) { Element domElement; try { domElement = prismContext.getPrismJaxbProcessor().toDomElement(val, doc); // domElement = JAXBUtil.toDomElement(val); } catch (JAXBException e) { throw new SchemaException("Unexpected JAXB problem while creating search filer for value " + val, e); } value.appendChild(doc.importNode(domElement, true)); } if (xpath != null) { Element path = xpath.toElement(SchemaConstants.C_FILTER_PATH, doc); equal.appendChild(doc.importNode(path, true)); } equal.appendChild(doc.importNode(value, true)); return equal; } /** * Creates "equal" filter segment for single-valued properties based on DOM representation. * * @param doc * @param xpath property container xpath. may be null. * @param value * @return "equal" filter segment (as DOM) * @throws JAXBException */ public static Element createEqualFilter(Document doc, XPathHolder xpath, Object value) throws SchemaException { Validate.notNull(doc); Validate.notNull(value); List<Object> values = new ArrayList<Object>(); values.add(value); return createEqualFilter(doc, xpath, values); } /** * Creates "equal" filter segment for single-valued properties with string content. * * @param doc * @param xpath property container xpath. may be null. * @param value * @return "equal" filter segment (as DOM) * @throws JAXBException */ public static Element createEqualFilter(Document doc, XPathHolder xpath, QName properyName, String value) throws SchemaException { Validate.notNull(doc); Validate.notNull(properyName); Validate.notNull(value); Element element = doc.createElementNS(properyName.getNamespaceURI(), properyName.getLocalPart()); element.setTextContent(value); List<Element> values = new ArrayList<Element>(); values.add(element); return createEqualFilter(doc, xpath, values); } /** * Creates "equal" filter segment for single-valued properties with QName content. * * @param doc * @param xpath property container xpath. may be null. * @param value * @return "equal" filter segment (as DOM) * @throws JAXBException */ public static Element createEqualFilter(Document doc, XPathHolder xpath, QName properyName, QName value) throws SchemaException { Validate.notNull(doc); Validate.notNull(properyName); Validate.notNull(value); Element element = doc.createElementNS(properyName.getNamespaceURI(), properyName.getLocalPart()); DOMUtil.setQNameValue(element, value); List<Element> values = new ArrayList<Element>(); values.add(element); return createEqualFilter(doc, xpath, values); } /** * Creates "equal" filter for object reference. * * @param doc * @param xpath property container xpath. may be null. * @param propertyName name of the reference property (e.g. "resourceRef") * @param oid OID of the referenced object * @return "equal" filter segment (as DOM) * @throws JAXBException */ public static Element createEqualRefFilter(Document doc, XPathHolder xpath, QName propertyName, String oid) throws SchemaException { Element value = doc.createElementNS(propertyName.getNamespaceURI(), propertyName.getLocalPart()); value.setAttributeNS(SchemaConstants.C_OID_ATTRIBUTE.getNamespaceURI(), SchemaConstants.C_OID_ATTRIBUTE.getLocalPart(), oid); return createEqualFilter(doc, xpath, value); } public static Element createAndFilter(Document doc, Element... conditions) { Validate.notNull(doc); Validate.notNull(conditions); Element and = doc.createElementNS(SchemaConstants.C_FILTER_AND.getNamespaceURI(), SchemaConstants.C_FILTER_AND.getLocalPart()); for (Element condition : conditions) { Validate.notNull(condition); and.appendChild(condition); } return and; } // public static Element createAndFilter(Document doc, Element el1, Element el2) { // Validate.notNull(doc); // Validate.notNull(el1); // Validate.notNull(el2); // // Element and = doc.createElementNS(SchemaConstants.C_FILTER_AND.getNamespaceURI(), SchemaConstants.C_FILTER_AND.getLocalPart()); // and.appendChild(el1); // and.appendChild(el2); // return and; // } // // public static Element createAndFilter(Document doc, Element el1, Element el2, Element el3) { // Validate.notNull(doc); // Validate.notNull(el1); // Validate.notNull(el2); // Validate.notNull(el3); // // Element and = doc.createElementNS(SchemaConstants.C_FILTER_AND.getNamespaceURI(), SchemaConstants.C_FILTER_AND.getLocalPart()); // and.appendChild(el1); // and.appendChild(el2); // and.appendChild(el3); // return and; // } public static QueryType createNameQuery(String name) throws SchemaException { Document doc = DOMUtil.getDocument(); Element filter = QueryUtil.createEqualFilter(doc, null, SchemaConstants.C_NAME, name); QueryType query = new QueryType(); query.setFilter(filter); return query; } public static QueryType createNameQuery(ObjectType object) throws SchemaException { return createNameQuery(object.getName()); } @Deprecated public static <T extends ObjectType> Element createNameAndClassFilter(Class<T> type, String name) throws SchemaException { Document doc = DOMUtil.getDocument(); return QueryUtil.createEqualFilter(doc, null, SchemaConstants.C_NAME, name); } public static QueryType createQuery(Element filter) { QueryType query = new QueryType(); query.setFilter(filter); return query; } /** * Returns query that returns all objects. */ public static QueryType createAllObjectsQuery() { // Create empty filter. This returns all objects of a type given as an argument to searchObjects. return new QueryType(); } public static QueryType createResourceAndAccountQuery(ResourceType resource, QName objectClass, String accountType) throws SchemaException { Document doc = DOMUtil.getDocument(); Element filter = QueryUtil.createAndFilter(doc, // TODO: The account type is hardcoded now, it should determined // from the schema later, or maybe we can make it entirely // generic (use ResourceObjectShadowType instead). QueryUtil.createEqualRefFilter(doc, null, SchemaConstants.I_RESOURCE_REF, resource.getOid()), QueryUtil.createEqualFilter(doc, null, SchemaConstants.I_OBJECT_CLASS, objectClass) ); QueryType query = new QueryType(); query.setFilter(filter); return query; } public static String dump(QueryType query) { StringBuilder sb = new StringBuilder("Query("); sb.append(query.getDescription()).append("):\n"); sb.append(DOMUtil.serializeDOMToString(query.getFilter())); return sb.toString(); } }
QUICK HACK to fix recursion, didn't know what to do with it (was causing stack overflow exception)
infra/common/src/main/java/com/evolveum/midpoint/common/QueryUtil.java
QUICK HACK to fix recursion, didn't know what to do with it (was causing stack overflow exception)
Java
apache-2.0
30e240118cd6b1df2596d7a5126b4630ec0482b9
0
nathbenjwolf/FFA,nathbenjwolf/FFA
package battle; import javax.swing.*; import javax.swing.Timer; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import java.awt.geom.GeneralPath; import java.awt.image.BufferedImage; import java.util.*; import java.util.List; import java.util.Set; import ability.Ability; import character.Character; import mapElement.MapCell; import mapElement.MapElement; import utils.Orientation; import utils.Orientation.Direction; import utils.PathFinding; /** * Created by Nathan on 11/14/2015. */ public class Board extends JPanel implements ActionListener, MouseMotionListener { // Size constants public static int cellSize = 80; static int gridLineThickness = 2; public static int cellYThickness = cellSize / 3; public static int cellXThickness = cellSize / 5; public static int backgroundXPadding = cellSize / 3; public static int backgroundYPadding = cellSize / 5; static int realCellSize = cellSize - gridLineThickness; static int healthBarXPadding = (int) ((double)cellSize * 0.15); static int healthBarYPadding = (int) ((double)cellSize * 0.05); static int healthBarWidth = (int) ((double)cellSize * 0.7); static int healthBarHeight = (int) ((double)cellSize * 0.1); public int boardDesiredWidth; public int boardDesiredHeight; // Animation timer constants static int animationTimerDelay = 100; public static int animationTotalTicks = 1000; static int tilePulseFrames = 10; // Shading Constants static float tileThicknessAlpha = 0.5F; static float gridLineAlpha = 0.3F; // Move Cell Constants static Color moveCellColorFill = new Color(1F, 0.55F, 0F, 0.5F); static Color moveCellColorBorder = new Color(1F, 0.55F, 0F, 1F); // Ability Cell Constants static Color abilityRangeCellColorFill = new Color(1F, 0.55F, 0.0F, 0.3F); static Color abilityRangeCellColorBorder = new Color(1F, 0.55F, 0.0F, 1F); static Color abilityTargetCellColorFill = new Color(0.0F, 0.25F, 0.25F, 0.5F); static Color abilityTargetCellColorBorder = new Color(0.0F, 0.25F, 0.25F, 1F); // Orientation Cell Constants static Color orientationCellColorFill = new Color(0.0F, 0.0F, 0.1F, 0.5F); static Color orientationCellColorBorder = new Color(0.0F, 0.0F, 0.1F, 1F); int numXCells; int numYCells; MapCell[][] map; Set<Cell> moveCells = new HashSet<>(); Set<Cell> abilityTargetCells = new HashSet<>(); Set<Cell> abilityRangeCells = new HashSet<>(); Set<Cell> orientationCells = new HashSet<>(); Cell mouseHoverCell; private List<Character> team1; private List<Character> team2; private List<Character> allCharacters; private Map<Character, Cell> characterLocations = new HashMap<>(); private Timer animationTimer; private int animationTick; public Board(List<Character> team1, List<Character> team2, String groundMap, String objectMap) { this.team1 = team1; this.team2 = team2; this.allCharacters = new ArrayList<>(); this.allCharacters.addAll(team1); this.allCharacters.addAll(team2); this.map = MapParser.decodeMap(groundMap, objectMap); this.numXCells = this.map.length; this.numYCells = this.map[0].length; this.boardDesiredWidth = cellSize*numXCells + backgroundXPadding*2; this.boardDesiredHeight = cellSize*numYCells + cellYThickness + backgroundYPadding*2; //TODO: Temporary code till character placement code exists //Team 1 for(int i = 0; i < team1.size(); i++) { team1.get(i).cell = new Cell(0,i+3); team1.get(i).direction = Direction.RIGHT; } //Team 1 for(int i = 0; i < team2.size(); i++) { team2.get(i).cell = new Cell(numXCells-1,i+3); team2.get(i).direction = Direction.LEFT; } // Setup animation timer animationTick = 0; animationTimer = new Timer(animationTimerDelay, this); animationTimer.setInitialDelay(animationTimerDelay); animationTimer.start(); // Mouse detector addMouseMotionListener(this); } public void paintComponent(Graphics g) { drawBackground(g); drawGround(g); drawCellIndicators(g); drawObjects(g); } private void drawBackground(Graphics g) { // TEMOPRARY: need background image stuff g.setColor(new Color(255,0,0)); g.fillRect(0, 0, getWidth(), getHeight()); } private void drawGround(Graphics g) { for(int y=0; y<map[0].length; y++) { for(int x=map.length-1; x>=0; x--) { Cell cell = new Cell(x,y); drawGroundCell(g, cell); } } } private void drawCellIndicators(Graphics g) { drawMoveCells(g); drawAbilityCells(g); drawOrientationCells(g); } private void drawObjects(Graphics g) { for(int x=0; x<map.length; x++) { for(int y=0; y<map[0].length; y++) { Cell cell = new Cell(x,y); Cell TLPixel = cellToTLPixel(cell); // TEMPORARY TLPixel.y -= (cellSize/3); Cell BRPixel = cellToBRPixel(cell); // TEMPORARY BRPixel.y -= (cellSize/3); // Draw Cell Object drawObjectCell(g, cell); // Draw Character drawCellCharacter(g, cell); } } } private void drawGroundCell(Graphics g, Cell cell) { Cell TLPixel = cellToTLPixel(cell); Cell BRPixel = cellToBRPixel(cell); if(map[cell.x][cell.y].isPresent() && map[cell.x][cell.y].ground != null) { BufferedImage img = map[cell.x][cell.y].ground.getImage(animationTick); g.drawImage(img, TLPixel.x, TLPixel.y, BRPixel.x + 1, BRPixel.y + 1, // Extra +1 because drawImage -1 0, 0, img.getWidth(), img.getHeight(), null); drawCellGrid(g, cell); drawGroundCellThickness(g, cell, img); } } private void drawGroundCellThickness(Graphics g, Cell cell, BufferedImage img) { // Y-axis thickness Cell TLPixel = cellToTLYThicknessPixel(cell); Cell BRPixel = cellToBRYThicknessPixel(cell); Shape s = getYCellThicknessShape(cell); drawCellThickness(g, img, s, TLPixel, BRPixel); // X-axis thickness TLPixel = cellToTLXThicknessPixel(cell); BRPixel = cellToBRXThicknessPixel(cell); s = getXCellThicknessShape(cell); drawCellThickness(g, img, s, TLPixel, BRPixel); } private void drawCellThickness(Graphics g, BufferedImage img, Shape s, Cell TLPixel, Cell BRPixel) { Graphics2D g2 = (Graphics2D) g; g2.setClip(s); g2.drawImage(img, TLPixel.x, TLPixel.y, BRPixel.x + 1, BRPixel.y + 1, 0, 0, img.getWidth(), img.getHeight(), null); g2.setColor(new Color(0, 0, 0, tileThicknessAlpha)); g2.fill(s); g2.setColor(new Color(0, 0, 0, gridLineAlpha)); Stroke oldStroke = g2.getStroke(); g2.setStroke(new BasicStroke(gridLineThickness*2)); g2.draw(s); g2.setClip(null); g2.setStroke(oldStroke); } private Shape getXCellThicknessShape(Cell cell) { Cell TLPixel = cellToTLPixel(cell); GeneralPath path = new GeneralPath(); path.moveTo(TLPixel.x,TLPixel.y); TLPixel.x -= cellXThickness; TLPixel.y += cellYThickness; path.lineTo(TLPixel.x,TLPixel.y); TLPixel.y += cellSize; path.lineTo(TLPixel.x,TLPixel.y); TLPixel.x += cellXThickness; TLPixel.y -= cellYThickness; path.lineTo(TLPixel.x,TLPixel.y); path.closePath(); return path; } private Shape getYCellThicknessShape(Cell cell) { // Grab 1 cell lower top left pixel Cell adjustedCell = new Cell(cell); adjustedCell.y += 1; Cell TLPixel = cellToTLPixel(adjustedCell); GeneralPath path = new GeneralPath(); path.moveTo(TLPixel.x,TLPixel.y); TLPixel.x -= cellXThickness; TLPixel.y += cellYThickness; path.lineTo(TLPixel.x,TLPixel.y); TLPixel.x += cellSize; path.lineTo(TLPixel.x,TLPixel.y); TLPixel.x += cellXThickness; TLPixel.y -= cellYThickness; path.lineTo(TLPixel.x,TLPixel.y); path.closePath(); return path; } private void drawMoveCells(Graphics g) { if(moveCells.size() == 0) { return; } Color fillColor = getPulseColor(moveCellColorFill); Color borderColor = getPulseColor(moveCellColorBorder); for(Cell cell: moveCells) { drawCell(g, cell, fillColor); drawCellBorder(g, cell, borderColor); } } private void drawAbilityCells(Graphics g) { for(Cell cell: abilityRangeCells) { drawCell(g, cell, abilityRangeCellColorFill); drawCellBorder(g, cell, abilityRangeCellColorBorder); } Color fillColor = getPulseColor(abilityTargetCellColorFill); Color borderColor = getPulseColor(abilityTargetCellColorBorder); for(Cell cell: abilityTargetCells) { drawCell(g, cell, fillColor); drawCellBorder(g, cell, borderColor); } } private void drawOrientationCells(Graphics g) { Color fillColor = getPulseColor(orientationCellColorFill); Color borderColor = getPulseColor(orientationCellColorBorder); for(Cell cell: orientationCells) { drawCell(g, cell, fillColor); drawCellBorder(g, cell, borderColor); } } private Color getPulseColor(Color color) { return new Color((float)color.getRed()/255F, (float)color.getGreen()/255F, (float)color.getBlue()/255F, ((float)color.getAlpha()/255F)*getPulseFrame()); } private void drawObjectCell(Graphics g, Cell cell) { if(map[cell.x][cell.y].isPresent()) { Cell TLPixel = cellToTLPixel(cell); // TEMPORARY TLPixel.y -= (cellSize/2); Cell BRPixel = cellToBRPixel(cell); // TEMPORARY BRPixel.y -= (cellSize/4); if(map[cell.x][cell.y].isPresent() && map[cell.x][cell.y].object != null) { BufferedImage img = map[cell.x][cell.y].object.getImage(animationTick); g.drawImage(img, TLPixel.x, TLPixel.y, BRPixel.x + 1, BRPixel.y + 1, // Extra +1 because drawImage -1 0, 0, img.getWidth(), img.getHeight(), null); } } } private void drawCellCharacter(Graphics g, Cell cell) { Cell TLPixel = cellToTLPixel(cell); // TEMPORARY TLPixel.y -= (cellSize/3); Cell BRPixel = cellToBRPixel(cell); // TEMPORARY BRPixel.y -= (cellSize/3); for(Character character: allCharacters) { if(character.cell.equals(cell)) { BufferedImage img = character.getImage(); g.drawImage(img, TLPixel.x, TLPixel.y, BRPixel.x + 1, BRPixel.y + 1, // Extra +1 because drawImage -1 0, 0, img.getWidth(), img.getHeight(), null); if(mouseHoverCell != null && mouseHoverCell.equals(character.cell)) { drawHealthBar(g, character); } } } } private void drawCharacters(Graphics g, List<Character> characters) { for(Character character : characters) { Cell TLPixel = cellToTLPixel(character.cell); // TEMPORARY TLPixel.y -= (cellSize/3); Cell BRPixel = cellToBRPixel(character.cell); // TEMPORARY BRPixel.y -= (cellSize/3); // Character image BufferedImage img = character.getImage(); g.drawImage(img, TLPixel.x, TLPixel.y, BRPixel.x+1, BRPixel.y+1, // Extra +1 because drawImage -1 0, 0, img.getWidth(), img.getHeight(), null); // Health bar //drawHealthBar(g, character); } } private void drawHealthBar(Graphics g, Character character) { Cell TLPixel = cellToTLPixel(character.cell); TLPixel.x += healthBarXPadding; TLPixel.y -= (cellSize/3); TLPixel.y += healthBarYPadding; // Health bar border g.setColor(Color.WHITE); g.drawRect(TLPixel.x, TLPixel.y, healthBarWidth, healthBarHeight); // Health bar contents g.setColor(Color.RED); int healthWidth = (int)((double)(healthBarWidth-1) * ((double)character.currentHealth/(double)character.totalHealth)); g.fillRect(TLPixel.x+1, TLPixel.y+1, healthWidth, healthBarHeight-1); } private void drawCell(Graphics g, Cell cell, Color color) { g.setColor(color); Cell topLeftPixel = cellToTLPixel(cell); g.fillRect(topLeftPixel.x, topLeftPixel.y, cellSize, cellSize); } private void drawCellBorder(Graphics g, Cell cell, Color color) { g.setColor(color); Cell topLeftPixel = cellToTLPixel(cell); // Old way of drawing (should remove once decided) // g.fillRect(topLeftPixel.x, topLeftPixel.y, cellSize, gridLineThickness); // g.fillRect(topLeftPixel.x, topLeftPixel.y, gridLineThickness, cellSize); // g.fillRect(topLeftPixel.x, topLeftPixel.y+cellSize-gridLineThickness, cellSize, gridLineThickness); // g.fillRect(topLeftPixel.x+cellSize-gridLineThickness, topLeftPixel.y, gridLineThickness, cellSize); Graphics2D g2 = (Graphics2D) g; Stroke oldStroke = g2.getStroke(); g2.setStroke(new BasicStroke(gridLineThickness)); g2.drawRect(topLeftPixel.x+gridLineThickness, topLeftPixel.y+gridLineThickness, cellSize-(gridLineThickness*2), cellSize-(gridLineThickness*2)); g2.setStroke(oldStroke); } private void drawCellGrid(Graphics g, Cell cell) { g.setColor(new Color(0, 0, 0, gridLineAlpha)); Cell topLeftPixel = cellToTLPixel(cell); Graphics2D g2 = (Graphics2D) g; Stroke oldStroke = g2.getStroke(); g2.setStroke(new BasicStroke(gridLineThickness)); g2.drawRect(topLeftPixel.x+1, topLeftPixel.y+1, cellSize-gridLineThickness, cellSize-gridLineThickness); g2.setStroke(oldStroke); } private float getPulseFrame() { // Pulse between 50% and 100% return (((float)animationTick%tilePulseFrames)+tilePulseFrames)/(tilePulseFrames*2); } @Override public void actionPerformed(ActionEvent e) { if(animationTick+1 >= animationTotalTicks) { animationTick = 0; } else { animationTick++; } repaint(); } public void showMoveCells(Character character) { moveCells.clear(); moveCells = character.getMovementCells(map, getTeam(character), getEnemyTeam(character)); repaint(); } public void clearMoveCells() { moveCells.clear(); repaint(); } private boolean isMoveableCell(Cell cell) { return moveCells.contains(cell); } public boolean moveCharacter(Character character, Cell cell) { if(isMoveableCell(cell)) { character.moveCharacter(new Cell(cell)); clearMoveCells(); return true; } else { return false; } } public void showAbilityCells(Character character, Ability ability) { abilityTargetCells.clear(); abilityRangeCells.clear(); List<Set<Cell>> abilityCells = ability.getAttackCells(map, getTeam(character), getEnemyTeam(character), character); abilityTargetCells = abilityCells.get(0); abilityRangeCells = abilityCells.get(1); repaint(); } public void clearAbilityCells() { abilityTargetCells.clear(); abilityRangeCells.clear(); repaint(); } private boolean isAbilityCell(Cell cell) { return abilityTargetCells.contains(cell); } public boolean useAbility(Character character, Ability ability, Cell cell) { if(isAbilityCell(cell)) { ability.useAbility(map, getTeam(character), getEnemyTeam(character), character, cell); updateCharacterStatus(); clearAbilityCells(); return true; } else { return false; } } public void showOrientationCells(Character character) { orientationCells.clear(); orientationCells = PathFinding.findRadialCells(map, character.cell, 1); orientationCells.remove(character.cell); repaint(); } public boolean isOrientaionCell(Cell cell) { return orientationCells.contains(cell); } public boolean orientCharacter(Character character, Cell cell) { if(isOrientaionCell(cell)) { character.setOrientation(Orientation.getDirection(character.cell, cell)); clearOrientationCells(); return true; } else { return false; } } public void clearOrientationCells() { orientationCells.clear(); repaint(); } private void updateCharacterStatus() { // Check for dead characters on both teams List<Character> deadCharacters = new ArrayList<>(); for(Character character : allCharacters) { if(character.isDead()) { deadCharacters.add(character); } } for(Character deadCharacter : deadCharacters) { team1.remove(deadCharacter); team2.remove(deadCharacter); allCharacters.remove(deadCharacter); } } private Character getCharacterOnCell(Cell cell) { for(Character character : allCharacters) { if(character.cell.equals(cell)) { return character; } } return null; } private Character getTeamOnCell(List<Character> team, Cell cell) { for(Character character : team) { if(character.cell.equals(cell)) { return character; } } return null; } private List<Character> getTeam(Character character) { return team1.contains(character) ? team1 : team2; } private List<Character> getEnemyTeam(Character character) { return team2.contains(character) ? team1 : team2; } private Set<Cell> getTeamLocations(Character character) { List<Character> team = getTeam(character); Set<Cell> teamLocations = new HashSet<>(); for(Character teammate : team) { teamLocations.add(teammate.cell); } return teamLocations; } private Set<Cell> getEnemyLocations(Character character) { List<Character> team = getEnemyTeam(character); Set<Cell> teamLocations = new HashSet<>(); for(Character teammate : team) { teamLocations.add(teammate.cell); } return teamLocations; } public Cell cellToTLPixel(Cell cell) { return new Cell(cell.x*cellSize + backgroundXPadding, cell.y*cellSize + backgroundYPadding); } public Cell cellToBRPixel(Cell cell) { return new Cell((cell.x+1)*cellSize-1 + backgroundXPadding, (cell.y+1)*cellSize-1 + backgroundYPadding); } public Cell cellToTLYThicknessPixel(Cell cell) { cell = new Cell(cell.x, cell.y+1); Cell TLPixel = cellToTLPixel(cell); TLPixel.x -= cellXThickness; return TLPixel; } public Cell cellToBRYThicknessPixel(Cell cell) { Cell BRPixel = cellToBRPixel(cell); BRPixel.y += cellYThickness + 1; // cellToBRPixel removes an extra pixel for inclusive conditions return BRPixel; } public Cell cellToTLXThicknessPixel(Cell cell) { Cell TLPixel = cellToTLPixel(cell); TLPixel.x -= cellXThickness; return TLPixel; } public Cell cellToBRXThicknessPixel(Cell cell) { cell = new Cell(cell.x, cell.y+1); Cell BRPixel = cellToTLPixel(cell); BRPixel.y += cellYThickness; return BRPixel; } public boolean isBoardPixel(int x, int y) { return x >= backgroundXPadding && x < numXCells*cellSize + backgroundXPadding && y >= backgroundYPadding && y < numYCells*cellSize + backgroundYPadding; } public Cell pixelToCell(int x, int y) { if(isBoardPixel(x,y)) { return new Cell((x - backgroundXPadding) / cellSize, (y - backgroundYPadding) / cellSize); } return null; } @Override public void mouseDragged(MouseEvent e) { System.out.println("Dragged"); System.out.println("x: " + e.getPoint().x + " y: " + e.getPoint().y); } @Override public void mouseMoved(MouseEvent e) { System.out.println("Moved"); System.out.println("x: " + e.getPoint().x + " y: " + e.getPoint().y); mouseHoverCell = pixelToCell(e.getPoint().x, e.getPoint().y); repaint(); } }
src/battle/Board.java
package battle; import javax.swing.*; import javax.swing.Timer; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.geom.GeneralPath; import java.awt.image.BufferedImage; import java.util.*; import java.util.List; import java.util.Set; import ability.Ability; import character.Character; import mapElement.MapCell; import mapElement.MapElement; import utils.Orientation; import utils.Orientation.Direction; import utils.PathFinding; /** * Created by Nathan on 11/14/2015. */ public class Board extends JPanel implements ActionListener { // Size constants public static int cellSize = 80; static int gridLineThickness = 2; public static int cellYThickness = cellSize / 3; public static int cellXThickness = cellSize / 5; public static int backgroundXPadding = cellSize / 3; public static int backgroundYPadding = cellSize / 5; static int realCellSize = cellSize - gridLineThickness; static int healthBarPadding = (int) ((double)Board.realCellSize * 0.05); static int healthBarWidth = (int) ((double)Board.realCellSize * 0.7); static int healthBarHeight = (int) ((double)Board.realCellSize * 0.1); public int boardDesiredWidth; public int boardDesiredHeight; // Animation timer constants static int animationTimerDelay = 100; public static int animationTotalTicks = 1000; static int tilePulseFrames = 10; // Shading Constants static float tileThicknessAlpha = 0.5F; static float gridLineAlpha = 0.3F; // Move Cell Constants static Color moveCellColorFill = new Color(1F, 0.55F, 0F, 0.5F); static Color moveCellColorBorder = new Color(1F, 0.55F, 0F, 1F); // Ability Cell Constants static Color abilityRangeCellColorFill = new Color(1F, 0.55F, 0.0F, 0.3F); static Color abilityRangeCellColorBorder = new Color(1F, 0.55F, 0.0F, 1F); static Color abilityTargetCellColorFill = new Color(0.0F, 0.25F, 0.25F, 0.5F); static Color abilityTargetCellColorBorder = new Color(0.0F, 0.25F, 0.25F, 1F); // Orientation Cell Constants static Color orientationCellColorFill = new Color(0.0F, 0.0F, 0.1F, 0.5F); static Color orientationCellColorBorder = new Color(0.0F, 0.0F, 0.1F, 1F); int numXCells; int numYCells; MapCell[][] map; Set<Cell> moveCells = new HashSet<>(); Set<Cell> abilityTargetCells = new HashSet<>(); Set<Cell> abilityRangeCells = new HashSet<>(); Set<Cell> orientationCells = new HashSet<>(); private List<Character> team1; private List<Character> team2; private List<Character> allCharacters; private Map<Character, Cell> characterLocations = new HashMap<>(); private Timer animationTimer; private int animationTick; public Board(List<Character> team1, List<Character> team2, String groundMap, String objectMap) { this.team1 = team1; this.team2 = team2; this.allCharacters = new ArrayList<>(); this.allCharacters.addAll(team1); this.allCharacters.addAll(team2); this.map = MapParser.decodeMap(groundMap, objectMap); this.numXCells = this.map.length; this.numYCells = this.map[0].length; this.boardDesiredWidth = cellSize*numXCells + backgroundXPadding*2; this.boardDesiredHeight = cellSize*numYCells + cellYThickness + backgroundYPadding*2; //TODO: Temporary code till character placement code exists //Team 1 for(int i = 0; i < team1.size(); i++) { team1.get(i).cell = new Cell(0,i+3); team1.get(i).direction = Direction.RIGHT; } //Team 1 for(int i = 0; i < team2.size(); i++) { team2.get(i).cell = new Cell(numXCells-1,i+3); team2.get(i).direction = Direction.LEFT; } // Setup animation timer animationTick = 0; animationTimer = new Timer(animationTimerDelay, this); animationTimer.setInitialDelay(animationTimerDelay); animationTimer.start(); } public void paintComponent(Graphics g) { drawBackground(g); drawGround(g); drawCellIndicators(g); drawObjects(g); } private void drawBackground(Graphics g) { // TEMOPRARY: need background image stuff g.setColor(new Color(255,0,0)); g.fillRect(0, 0, getWidth(), getHeight()); } private void drawGround(Graphics g) { for(int y=0; y<map[0].length; y++) { for(int x=map.length-1; x>=0; x--) { Cell cell = new Cell(x,y); drawGroundCell(g, cell); } } } private void drawCellIndicators(Graphics g) { drawMoveCells(g); drawAbilityCells(g); drawOrientationCells(g); } private void drawObjects(Graphics g) { for(int x=0; x<map.length; x++) { for(int y=0; y<map[0].length; y++) { Cell cell = new Cell(x,y); Cell TLPixel = cellToTLPixel(cell); // TEMPORARY TLPixel.y -= (cellSize/3); Cell BRPixel = cellToBRPixel(cell); // TEMPORARY BRPixel.y -= (cellSize/3); // Draw Cell Object drawObjectCell(g, cell); // Draw Character drawCellCharacter(g, cell); } } } private void drawGroundCell(Graphics g, Cell cell) { Cell TLPixel = cellToTLPixel(cell); Cell BRPixel = cellToBRPixel(cell); if(map[cell.x][cell.y].isPresent() && map[cell.x][cell.y].ground != null) { BufferedImage img = map[cell.x][cell.y].ground.getImage(animationTick); g.drawImage(img, TLPixel.x, TLPixel.y, BRPixel.x + 1, BRPixel.y + 1, // Extra +1 because drawImage -1 0, 0, img.getWidth(), img.getHeight(), null); drawCellGrid(g, cell); drawGroundCellThickness(g, cell, img); } } private void drawGroundCellThickness(Graphics g, Cell cell, BufferedImage img) { // Y-axis thickness Cell TLPixel = cellToTLYThicknessPixel(cell); Cell BRPixel = cellToBRYThicknessPixel(cell); Shape s = getYCellThicknessShape(cell); drawCellThickness(g, img, s, TLPixel, BRPixel); // X-axis thickness TLPixel = cellToTLXThicknessPixel(cell); BRPixel = cellToBRXThicknessPixel(cell); s = getXCellThicknessShape(cell); drawCellThickness(g, img, s, TLPixel, BRPixel); } private void drawCellThickness(Graphics g, BufferedImage img, Shape s, Cell TLPixel, Cell BRPixel) { Graphics2D g2 = (Graphics2D) g; g2.setClip(s); g2.drawImage(img, TLPixel.x, TLPixel.y, BRPixel.x + 1, BRPixel.y + 1, 0, 0, img.getWidth(), img.getHeight(), null); g2.setColor(new Color(0, 0, 0, tileThicknessAlpha)); g2.fill(s); g2.setColor(new Color(0, 0, 0, gridLineAlpha)); g2.setStroke(new BasicStroke(gridLineThickness*2)); g2.draw(s); g2.setClip(null); } private Shape getXCellThicknessShape(Cell cell) { Cell TLPixel = cellToTLPixel(cell); GeneralPath path = new GeneralPath(); path.moveTo(TLPixel.x,TLPixel.y); TLPixel.x -= cellXThickness; TLPixel.y += cellYThickness; path.lineTo(TLPixel.x,TLPixel.y); TLPixel.y += cellSize; path.lineTo(TLPixel.x,TLPixel.y); TLPixel.x += cellXThickness; TLPixel.y -= cellYThickness; path.lineTo(TLPixel.x,TLPixel.y); path.closePath(); return path; } private Shape getYCellThicknessShape(Cell cell) { // Grab 1 cell lower top left pixel Cell adjustedCell = new Cell(cell); adjustedCell.y += 1; Cell TLPixel = cellToTLPixel(adjustedCell); GeneralPath path = new GeneralPath(); path.moveTo(TLPixel.x,TLPixel.y); TLPixel.x -= cellXThickness; TLPixel.y += cellYThickness; path.lineTo(TLPixel.x,TLPixel.y); TLPixel.x += cellSize; path.lineTo(TLPixel.x,TLPixel.y); TLPixel.x += cellXThickness; TLPixel.y -= cellYThickness; path.lineTo(TLPixel.x,TLPixel.y); path.closePath(); return path; } private void drawMoveCells(Graphics g) { if(moveCells.size() == 0) { return; } Color fillColor = getPulseColor(moveCellColorFill); Color borderColor = getPulseColor(moveCellColorBorder); for(Cell cell: moveCells) { drawCell(g, cell, fillColor); drawCellBorder(g, cell, borderColor); } } private void drawAbilityCells(Graphics g) { for(Cell cell: abilityRangeCells) { drawCell(g, cell, abilityRangeCellColorFill); drawCellBorder(g, cell, abilityRangeCellColorBorder); } Color fillColor = getPulseColor(abilityTargetCellColorFill); Color borderColor = getPulseColor(abilityTargetCellColorBorder); for(Cell cell: abilityTargetCells) { drawCell(g, cell, fillColor); drawCellBorder(g, cell, borderColor); } } private void drawOrientationCells(Graphics g) { Color fillColor = getPulseColor(orientationCellColorFill); Color borderColor = getPulseColor(orientationCellColorBorder); for(Cell cell: orientationCells) { drawCell(g, cell, fillColor); drawCellBorder(g, cell, borderColor); } } private Color getPulseColor(Color color) { return new Color((float)color.getRed()/255F, (float)color.getGreen()/255F, (float)color.getBlue()/255F, ((float)color.getAlpha()/255F)*getPulseFrame()); } private void drawObjectCell(Graphics g, Cell cell) { if(map[cell.x][cell.y].isPresent()) { Cell TLPixel = cellToTLPixel(cell); // TEMPORARY TLPixel.y -= (cellSize/2); Cell BRPixel = cellToBRPixel(cell); // TEMPORARY BRPixel.y -= (cellSize/4); if(map[cell.x][cell.y].isPresent() && map[cell.x][cell.y].object != null) { BufferedImage img = map[cell.x][cell.y].object.getImage(animationTick); g.drawImage(img, TLPixel.x, TLPixel.y, BRPixel.x + 1, BRPixel.y + 1, // Extra +1 because drawImage -1 0, 0, img.getWidth(), img.getHeight(), null); } } } private void drawCellCharacter(Graphics g, Cell cell) { Cell TLPixel = cellToTLPixel(cell); // TEMPORARY TLPixel.y -= (cellSize/3); Cell BRPixel = cellToBRPixel(cell); // TEMPORARY BRPixel.y -= (cellSize/3); for(Character character: allCharacters) { if(character.cell.equals(cell)) { BufferedImage img = character.getImage(); g.drawImage(img, TLPixel.x, TLPixel.y, BRPixel.x + 1, BRPixel.y + 1, // Extra +1 because drawImage -1 0, 0, img.getWidth(), img.getHeight(), null); } } } private void drawCharacters(Graphics g, List<Character> characters) { for(Character character : characters) { Cell TLPixel = cellToTLPixel(character.cell); // TEMPORARY TLPixel.y -= (cellSize/3); Cell BRPixel = cellToBRPixel(character.cell); // TEMPORARY BRPixel.y -= (cellSize/3); // Character image BufferedImage img = character.getImage(); g.drawImage(img, TLPixel.x, TLPixel.y, BRPixel.x+1, BRPixel.y+1, // Extra +1 because drawImage -1 0, 0, img.getWidth(), img.getHeight(), null); // Health bar //drawHealthBar(g, character); } } private void drawHealthBar(Graphics g, Character character) { Cell TLPixel = cellToTLPixel(character.cell); TLPixel.x += healthBarPadding; TLPixel.y -= (cellSize/3); TLPixel.y += healthBarPadding; // Health bar border g.setColor(Color.WHITE); g.drawRect(TLPixel.x, TLPixel.y, healthBarWidth, healthBarHeight); // Health bar contents g.setColor(Color.RED); int healthWidth = (int)((double)(healthBarWidth-1) * ((double)character.currentHealth/(double)character.totalHealth)); g.fillRect(TLPixel.x+1, TLPixel.y+1, healthWidth, healthBarHeight-1); } private void drawCell(Graphics g, Cell cell, Color color) { g.setColor(color); Cell topLeftPixel = cellToTLPixel(cell); g.fillRect(topLeftPixel.x, topLeftPixel.y, cellSize, cellSize); } private void drawCellBorder(Graphics g, Cell cell, Color color) { g.setColor(color); Cell topLeftPixel = cellToTLPixel(cell); // Old way of drawing (should remove once decided) // g.fillRect(topLeftPixel.x, topLeftPixel.y, cellSize, gridLineThickness); // g.fillRect(topLeftPixel.x, topLeftPixel.y, gridLineThickness, cellSize); // g.fillRect(topLeftPixel.x, topLeftPixel.y+cellSize-gridLineThickness, cellSize, gridLineThickness); // g.fillRect(topLeftPixel.x+cellSize-gridLineThickness, topLeftPixel.y, gridLineThickness, cellSize); Graphics2D g2 = (Graphics2D) g; Stroke oldStroke = g2.getStroke(); g2.setStroke(new BasicStroke(gridLineThickness)); g2.drawRect(topLeftPixel.x+gridLineThickness, topLeftPixel.y+gridLineThickness, cellSize-(gridLineThickness*2), cellSize-(gridLineThickness*2)); g2.setStroke(oldStroke); } private void drawCellGrid(Graphics g, Cell cell) { g.setColor(new Color(0, 0, 0, gridLineAlpha)); Cell topLeftPixel = cellToTLPixel(cell); Graphics2D g2 = (Graphics2D) g; Stroke oldStroke = g2.getStroke(); g2.setStroke(new BasicStroke(gridLineThickness)); g2.drawRect(topLeftPixel.x+1, topLeftPixel.y+1, cellSize-gridLineThickness, cellSize-gridLineThickness); g2.setStroke(oldStroke); } private float getPulseFrame() { // Pulse between 50% and 100% return (((float)animationTick%tilePulseFrames)+tilePulseFrames)/(tilePulseFrames*2); } @Override public void actionPerformed(ActionEvent e) { if(animationTick+1 >= animationTotalTicks) { animationTick = 0; } else { animationTick++; } repaint(); } public void showMoveCells(Character character) { moveCells.clear(); moveCells = character.getMovementCells(map, getTeam(character), getEnemyTeam(character)); repaint(); } public void clearMoveCells() { moveCells.clear(); repaint(); } private boolean isMoveableCell(Cell cell) { return moveCells.contains(cell); } public boolean moveCharacter(Character character, Cell cell) { if(isMoveableCell(cell)) { character.moveCharacter(new Cell(cell)); clearMoveCells(); return true; } else { return false; } } public void showAbilityCells(Character character, Ability ability) { abilityTargetCells.clear(); abilityRangeCells.clear(); List<Set<Cell>> abilityCells = ability.getAttackCells(map, getTeam(character), getEnemyTeam(character), character); abilityTargetCells = abilityCells.get(0); abilityRangeCells = abilityCells.get(1); repaint(); } public void clearAbilityCells() { abilityTargetCells.clear(); abilityRangeCells.clear(); repaint(); } private boolean isAbilityCell(Cell cell) { return abilityTargetCells.contains(cell); } public boolean useAbility(Character character, Ability ability, Cell cell) { if(isAbilityCell(cell)) { ability.useAbility(map, getTeam(character), getEnemyTeam(character), character, cell); updateCharacterStatus(); clearAbilityCells(); return true; } else { return false; } } public void showOrientationCells(Character character) { orientationCells.clear(); orientationCells = PathFinding.findRadialCells(map, character.cell, 1); orientationCells.remove(character.cell); repaint(); } public boolean isOrientaionCell(Cell cell) { return orientationCells.contains(cell); } public boolean orientCharacter(Character character, Cell cell) { if(isOrientaionCell(cell)) { character.setOrientation(Orientation.getDirection(character.cell, cell)); clearOrientationCells(); return true; } else { return false; } } public void clearOrientationCells() { orientationCells.clear(); repaint(); } private void updateCharacterStatus() { // Check for dead characters on both teams List<Character> deadCharacters = new ArrayList<>(); for(Character character : allCharacters) { if(character.isDead()) { deadCharacters.add(character); } } for(Character deadCharacter : deadCharacters) { team1.remove(deadCharacter); team2.remove(deadCharacter); allCharacters.remove(deadCharacter); } } private Character getCharacterOnCell(Cell cell) { for(Character character : allCharacters) { if(character.cell.equals(cell)) { return character; } } return null; } private Character getTeamOnCell(List<Character> team, Cell cell) { for(Character character : team) { if(character.cell.equals(cell)) { return character; } } return null; } private List<Character> getTeam(Character character) { return team1.contains(character) ? team1 : team2; } private List<Character> getEnemyTeam(Character character) { return team2.contains(character) ? team1 : team2; } private Set<Cell> getTeamLocations(Character character) { List<Character> team = getTeam(character); Set<Cell> teamLocations = new HashSet<>(); for(Character teammate : team) { teamLocations.add(teammate.cell); } return teamLocations; } private Set<Cell> getEnemyLocations(Character character) { List<Character> team = getEnemyTeam(character); Set<Cell> teamLocations = new HashSet<>(); for(Character teammate : team) { teamLocations.add(teammate.cell); } return teamLocations; } public Cell cellToTLPixel(Cell cell) { return new Cell(cell.x*cellSize + backgroundXPadding, cell.y*cellSize + backgroundYPadding); } public Cell cellToBRPixel(Cell cell) { return new Cell((cell.x+1)*cellSize-1 + backgroundXPadding, (cell.y+1)*cellSize-1 + backgroundYPadding); } public Cell cellToTLYThicknessPixel(Cell cell) { cell = new Cell(cell.x, cell.y+1); Cell TLPixel = cellToTLPixel(cell); TLPixel.x -= cellXThickness; return TLPixel; } public Cell cellToBRYThicknessPixel(Cell cell) { Cell BRPixel = cellToBRPixel(cell); BRPixel.y += cellYThickness + 1; // cellToBRPixel removes an extra pixel for inclusive conditions return BRPixel; } public Cell cellToTLXThicknessPixel(Cell cell) { Cell TLPixel = cellToTLPixel(cell); TLPixel.x -= cellXThickness; return TLPixel; } public Cell cellToBRXThicknessPixel(Cell cell) { cell = new Cell(cell.x, cell.y+1); Cell BRPixel = cellToTLPixel(cell); BRPixel.y += cellYThickness; return BRPixel; } public boolean isBoardPixel(int x, int y) { return x >= backgroundXPadding && x < numXCells*cellSize + backgroundXPadding && y >= backgroundYPadding && y < numYCells*cellSize + backgroundYPadding; } public Cell pixelToCell(int x, int y) { if(isBoardPixel(x,y)) { return new Cell((x - backgroundXPadding) / cellSize, (y - backgroundYPadding) / cellSize); } return null; } }
Added health bar hover
src/battle/Board.java
Added health bar hover
Java
apache-2.0
b0bf9bf0c341792891bc801e26ab7b39654af864
0
diorcety/intellij-community,akosyakov/intellij-community,izonder/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,blademainer/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,jexp/idea2,FHannes/intellij-community,diorcety/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,hurricup/intellij-community,fitermay/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,fitermay/intellij-community,fitermay/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,holmes/intellij-community,holmes/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,caot/intellij-community,TangHao1987/intellij-community,joewalnes/idea-community,semonte/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,izonder/intellij-community,fitermay/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,ernestp/consulo,apixandru/intellij-community,semonte/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,signed/intellij-community,semonte/intellij-community,supersven/intellij-community,semonte/intellij-community,semonte/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,Lekanich/intellij-community,joewalnes/idea-community,muntasirsyed/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,allotria/intellij-community,apixandru/intellij-community,da1z/intellij-community,tmpgit/intellij-community,samthor/intellij-community,samthor/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,TangHao1987/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,samthor/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,vladmm/intellij-community,ernestp/consulo,Distrotech/intellij-community,consulo/consulo,ibinti/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,caot/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,signed/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,TangHao1987/intellij-community,caot/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,diorcety/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,dslomov/intellij-community,ernestp/consulo,TangHao1987/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,jexp/idea2,supersven/intellij-community,semonte/intellij-community,slisson/intellij-community,apixandru/intellij-community,consulo/consulo,gnuhub/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,allotria/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,jagguli/intellij-community,da1z/intellij-community,robovm/robovm-studio,amith01994/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,joewalnes/idea-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,xfournet/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,caot/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,vladmm/intellij-community,kool79/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,kdwink/intellij-community,jexp/idea2,wreckJ/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,blademainer/intellij-community,ibinti/intellij-community,izonder/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,FHannes/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,da1z/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,samthor/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,jagguli/intellij-community,retomerz/intellij-community,adedayo/intellij-community,fnouama/intellij-community,petteyg/intellij-community,consulo/consulo,blademainer/intellij-community,orekyuu/intellij-community,slisson/intellij-community,FHannes/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,jexp/idea2,mglukhikh/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,semonte/intellij-community,ernestp/consulo,suncycheng/intellij-community,xfournet/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,supersven/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,holmes/intellij-community,consulo/consulo,ol-loginov/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,allotria/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,asedunov/intellij-community,fnouama/intellij-community,supersven/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,joewalnes/idea-community,apixandru/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,holmes/intellij-community,semonte/intellij-community,asedunov/intellij-community,consulo/consulo,Distrotech/intellij-community,FHannes/intellij-community,supersven/intellij-community,slisson/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,da1z/intellij-community,caot/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,da1z/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,signed/intellij-community,jagguli/intellij-community,joewalnes/idea-community,wreckJ/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,diorcety/intellij-community,kdwink/intellij-community,dslomov/intellij-community,slisson/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,blademainer/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,samthor/intellij-community,orekyuu/intellij-community,kool79/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,blademainer/intellij-community,jexp/idea2,FHannes/intellij-community,allotria/intellij-community,joewalnes/idea-community,akosyakov/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,ibinti/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,signed/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,jexp/idea2,suncycheng/intellij-community,robovm/robovm-studio,clumsy/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,vvv1559/intellij-community,izonder/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,apixandru/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,allotria/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,FHannes/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,signed/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,apixandru/intellij-community,hurricup/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,izonder/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,caot/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,petteyg/intellij-community,jagguli/intellij-community,fnouama/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,ryano144/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,holmes/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,holmes/intellij-community,caot/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,diorcety/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,signed/intellij-community,xfournet/intellij-community,fnouama/intellij-community,samthor/intellij-community,signed/intellij-community,signed/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,fnouama/intellij-community,ernestp/consulo,retomerz/intellij-community,holmes/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,ernestp/consulo,petteyg/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,jexp/idea2,ibinti/intellij-community,dslomov/intellij-community,blademainer/intellij-community,dslomov/intellij-community,signed/intellij-community,wreckJ/intellij-community,semonte/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,allotria/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,kdwink/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,caot/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,supersven/intellij-community,ryano144/intellij-community,diorcety/intellij-community,fitermay/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,robovm/robovm-studio,robovm/robovm-studio,signed/intellij-community,kool79/intellij-community,allotria/intellij-community,clumsy/intellij-community,semonte/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,joewalnes/idea-community,vvv1559/intellij-community,holmes/intellij-community,samthor/intellij-community,xfournet/intellij-community,consulo/consulo,fengbaicanhe/intellij-community,caot/intellij-community,samthor/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,allotria/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,supersven/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,da1z/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,joewalnes/idea-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,caot/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,ibinti/intellij-community,petteyg/intellij-community,kdwink/intellij-community,vladmm/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,apixandru/intellij-community,petteyg/intellij-community,petteyg/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,caot/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,jexp/idea2,fengbaicanhe/intellij-community,hurricup/intellij-community,kool79/intellij-community,fitermay/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,joewalnes/idea-community,ivan-fedorov/intellij-community,fnouama/intellij-community,ibinti/intellij-community,signed/intellij-community
/* * Created by IntelliJ IDEA. * User: max * Date: Oct 22, 2001 * Time: 8:21:36 PM * To change template for new class use * Code Style | Class Templates options (Tools | IDE Options). */ package com.intellij.codeInspection.reference; import com.intellij.ExtensionPoints; import com.intellij.analysis.AnalysisScope; import com.intellij.codeInspection.InspectionsBundle; import com.intellij.codeInspection.ex.GlobalInspectionContextImpl; import com.intellij.codeInspection.lang.InspectionExtensionsFactory; import com.intellij.codeInspection.lang.RefManagerExtension; import com.intellij.lang.Language; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.PathMacroManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectUtil; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Key; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.util.concurrency.JBReentrantReadWriteLock; import com.intellij.util.concurrency.LockFactory; import gnu.trove.THashMap; import org.jdom.Element; import org.jetbrains.annotations.Nullable; import java.util.*; public class RefManagerImpl extends RefManager { private int myLastUsedMask = 256 * 256 * 256 * 4; private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.reference.RefManager"); private final Project myProject; private AnalysisScope myScope; private RefProject myRefProject; private THashMap<PsiAnchor, RefElement> myRefTable; private THashMap<Module, RefModule> myModules; private final ProjectIterator myProjectIterator; private boolean myDeclarationsFound; private boolean myIsInProcess = false; private List<RefGraphAnnotator> myGraphAnnotators = new ArrayList<RefGraphAnnotator>(); private GlobalInspectionContextImpl myContext; private Map<Key, RefManagerExtension> myExtensions = new HashMap<Key, RefManagerExtension>(); private HashMap<Language, RefManagerExtension> myLanguageExtensions = new HashMap<Language, RefManagerExtension>(); private JBReentrantReadWriteLock myLock = LockFactory.createReadWriteLock(); public RefManagerImpl(Project project, AnalysisScope scope, GlobalInspectionContextImpl context) { myDeclarationsFound = false; myProject = project; myScope = scope; myContext = context; myRefProject = new RefProjectImpl(this); myRefTable = new THashMap<PsiAnchor, RefElement>(); myProjectIterator = new ProjectIterator(); for (InspectionExtensionsFactory factory : Extensions.getExtensions(InspectionExtensionsFactory.EP_NAME)) { final RefManagerExtension extension = factory.createRefManagerExtension(this); myExtensions.put(extension.getID(), extension); myLanguageExtensions.put(extension.getLanguage(), extension); } } public void iterate(RefVisitor visitor) { myLock.readLock().lock(); try { final THashMap<PsiAnchor, RefElement> refTable = getRefTable(); for (RefElement refElement : refTable.values()) { refElement.accept(visitor); } if (myModules != null) { for (RefModule refModule : myModules.values()) { refModule.accept(visitor); } } for (RefManagerExtension extension : myExtensions.values()) { extension.iterate(visitor); } } finally { myLock.readLock().unlock(); } } public void cleanup() { myScope = null; myRefProject = null; myRefTable = null; myModules = null; myContext = null; myGraphAnnotators.clear(); for (RefManagerExtension extension : myExtensions.values()) { extension.cleanup(); } } public AnalysisScope getScope() { return myScope; } public void fireNodeInitialized(RefElement refElement) { for (RefGraphAnnotator annotator : myGraphAnnotators) { annotator.onInitialize(refElement); } } public void fireNodeMarkedReferenced(RefElement refWhat, RefElement refFrom, boolean referencedFromClassInitializer, final boolean forReading, final boolean forWriting) { for (RefGraphAnnotator annotator : myGraphAnnotators) { annotator.onMarkReferenced(refWhat, refFrom, referencedFromClassInitializer, forReading, forWriting); } } public void fireBuildReferences(RefElement refElement) { for (RefGraphAnnotator annotator : myGraphAnnotators) { annotator.onReferencesBuild(refElement); } } public void registerGraphAnnotator(RefGraphAnnotator annotator) { myGraphAnnotators.add(annotator); } public int getLastUsedMask() { myLastUsedMask *= 2; return myLastUsedMask; } public <T> T getExtension(final Key<T> key) { return (T)myExtensions.get(key); } public String getType(final RefEntity ref) { for (RefManagerExtension extension : myExtensions.values()) { final String type = extension.getType(ref); if (type != null) return type; } if (ref instanceof RefFile) { return SmartRefElementPointer.FILE; } else if (ref instanceof RefModule) { return SmartRefElementPointer.MODULE; } else if (ref instanceof RefProject) { return SmartRefElementPointer.PROJECT; } else if (ref instanceof RefDirectory) { return SmartRefElementPointer.DIR; } return null; } public RefEntity getRefinedElement(RefEntity ref) { for (RefManagerExtension extension : myExtensions.values()) { ref = extension.getRefinedElement(ref); } return ref; } public Element export(RefEntity refEntity, final Element element, final int actualLine) { refEntity = getRefinedElement(refEntity); Element problem = new Element("problem"); if (refEntity instanceof RefElement) { final RefElement refElement = (RefElement)refEntity; PsiElement psiElement = refElement.getElement(); PsiFile psiFile = psiElement.getContainingFile(); Element fileElement = new Element("file"); Element lineElement = new Element("line"); final VirtualFile virtualFile = psiFile.getVirtualFile(); LOG.assertTrue(virtualFile != null); fileElement.addContent(virtualFile.getUrl()); if (actualLine == -1) { final Document document = PsiDocumentManager.getInstance(refElement.getRefManager().getProject()).getDocument(psiFile); LOG.assertTrue(document != null); lineElement.addContent(String.valueOf(document.getLineNumber(psiElement.getTextOffset()) + 1)); } else { lineElement.addContent(String.valueOf(actualLine)); } problem.addContent(fileElement); problem.addContent(lineElement); appendModule(problem, refElement.getModule()); } else if (refEntity instanceof RefModule) { final RefModule refModule = (RefModule)refEntity; final VirtualFile moduleFile = refModule.getModule().getModuleFile(); final Element fileElement = new Element("file"); fileElement.addContent(moduleFile != null ? moduleFile.getUrl() : refEntity.getName()); problem.addContent(fileElement); appendModule(problem, refModule); } for (RefManagerExtension extension : myExtensions.values()) { extension.export(refEntity, problem); } new SmartRefElementPointerImpl(refEntity, true).writeExternal(problem); element.addContent(problem); return problem; } @Nullable public String getGroupName(final RefElement entity) { for (RefManagerExtension extension : myExtensions.values()) { final String groupName = extension.getGroupName(entity); if (groupName != null) return groupName; } return null; } private static void appendModule(final Element problem, final RefModule refModule) { if (refModule != null) { Element moduleElement = new Element("module"); moduleElement.addContent(refModule.getName()); problem.addContent(moduleElement); } } public void findAllDeclarations() { if (!myDeclarationsFound) { long before = System.currentTimeMillis(); getScope().accept(myProjectIterator); myDeclarationsFound = true; LOG.info("Total duration of processing project usages:" + (System.currentTimeMillis() - before)); } } public boolean isDeclarationsFound() { return myDeclarationsFound; } public void inspectionReadActionStarted() { myIsInProcess = true; } public void inspectionReadActionFinished() { myIsInProcess = false; } public boolean isInProcess() { return myIsInProcess; } public Project getProject() { return myProject; } public RefProject getRefProject() { return myRefProject; } public THashMap<PsiAnchor, RefElement> getRefTable() { return myRefTable; } public void removeReference(RefElement refElem) { myLock.writeLock().lock(); try { final THashMap<PsiAnchor, RefElement> refTable = getRefTable(); final PsiElement element = refElem.getElement(); final RefManagerExtension extension = element != null ? getExtension(element.getLanguage()) : null; if (extension != null) { extension.removeReference(refElem); } if (refTable.remove(PsiAnchor.create(element)) != null) return; //PsiElement may have been invalidated and new one returned by getElement() is different so we need to do this stuff. for (PsiAnchor psiElement : refTable.keySet()) { if (refTable.get(psiElement) == refElem) { refTable.remove(psiElement); return; } } } finally { myLock.writeLock().unlock(); } } public void initializeAnnotators() { final Object[] graphAnnotators = Extensions.getRootArea().getExtensionPoint(ExtensionPoints.INSPECTIONS_GRAPH_ANNOTATOR).getExtensions(); for (Object annotator : graphAnnotators) { registerGraphAnnotator((RefGraphAnnotator)annotator); } for (RefGraphAnnotator graphAnnotator : myGraphAnnotators) { if (graphAnnotator instanceof RefGraphAnnotatorEx) { ((RefGraphAnnotatorEx)graphAnnotator).initialize(this); } } } private class ProjectIterator extends PsiElementVisitor { @Override public void visitElement(PsiElement element) { final RefManagerExtension extension = getExtension(element.getLanguage()); if (extension != null) { extension.visitElement(element); } for (PsiElement aChildren : element.getChildren()) { aChildren.accept(this); } } @Override public void visitFile(PsiFile file) { final VirtualFile virtualFile = file.getVirtualFile(); if (virtualFile != null) { myContext .incrementJobDoneAmount(GlobalInspectionContextImpl.BUILD_GRAPH, ProjectUtil.calcRelativeToProjectPath(virtualFile, myProject)); } final FileViewProvider viewProvider = file.getViewProvider(); final Set<Language> relevantLanguages = viewProvider.getLanguages(); for (Language language : relevantLanguages) { visitElement(viewProvider.getPsi(language)); } } } @Nullable public RefElement getReference(final PsiElement elem) { if (elem != null && (elem instanceof PsiDirectory || belongsToScope(elem))) { if (!elem.isValid()) return null; RefElement ref = getFromRefTable(elem); if (ref == null) { if (!isValidPointForReference()) { //LOG.assertTrue(true, "References may become invalid after process is finished"); return null; } final RefElementImpl refElement = ApplicationManager.getApplication().runReadAction(new Computable<RefElementImpl>() { @Nullable public RefElementImpl compute() { final RefManagerExtension extension = getExtension(elem.getLanguage()); if (extension != null) { final RefElement refElement = extension.createRefElement(elem); if (refElement != null) return (RefElementImpl)refElement; } if (elem instanceof PsiFile) { return new RefFileImpl((PsiFile)elem, RefManagerImpl.this); } else if (elem instanceof PsiDirectory) { return new RefDirectoryImpl((PsiDirectory)elem, RefManagerImpl.this); } else { return null; } } }); if (refElement == null) return null; putToRefTable(elem, refElement); ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { refElement.initialize(); } }); return refElement; } return ref; } return null; } private RefManagerExtension getExtension(final Language language) { return myLanguageExtensions.get(language); } public @Nullable RefEntity getReference(final String type, final String fqName) { for (RefManagerExtension extension : myExtensions.values()) { final RefEntity refEntity = extension.getReference(type, fqName); if (refEntity != null) return refEntity; } if (SmartRefElementPointer.FILE.equals(type)) { return RefFileImpl.fileFromExternalName(this, fqName); } else if (SmartRefElementPointer.MODULE.equals(type)) { return RefModuleImpl.moduleFromName(this, fqName); } else if (SmartRefElementPointer.PROJECT.equals(type)) { return getRefProject(); } else if (SmartRefElementPointer.DIR.equals(type)) { final VirtualFile vFile = LocalFileSystem.getInstance().findFileByPath(PathMacroManager.getInstance(getProject()).expandPath(fqName)); if (vFile != null) { final PsiDirectory dir = PsiManager.getInstance(getProject()).findDirectory(vFile); return getReference(dir); } } return null; } protected RefElement getFromRefTable(final PsiElement element) { myLock.readLock().lock(); try { return getRefTable().get(PsiAnchor.create(element)); } finally { myLock.readLock().unlock(); } } protected void putToRefTable(final PsiElement element, final RefElement ref) { myLock.writeLock().lock(); try { getRefTable().put(PsiAnchor.create(element), ref); } finally { myLock.writeLock().unlock(); } } public RefModule getRefModule(Module module) { if (module == null) { return null; } if (myModules == null) { myModules = new THashMap<Module, RefModule>(); } RefModule refModule = myModules.get(module); if (refModule == null) { refModule = new RefModuleImpl(module, this); myModules.put(module, refModule); } return refModule; } public boolean belongsToScope(final PsiElement psiElement) { if (psiElement == null) return false; if (psiElement instanceof PsiCompiledElement) return false; final PsiFile containingFile = ApplicationManager.getApplication().runReadAction(new Computable<PsiFile>() { public PsiFile compute() { return psiElement.getContainingFile(); } }); if (containingFile == null) { return false; } for (RefManagerExtension extension : myExtensions.values()) { if (!extension.belongsToScope(psiElement)) return false; } final Boolean inProject = ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() { public Boolean compute() { return psiElement != null && psiElement.isValid() && psiElement.getManager().isInProject(psiElement); } }); return inProject.booleanValue() && (getScope() == null || getScope().contains(psiElement)); } public String getQualifiedName(RefEntity refEntity) { if (refEntity == null || refEntity instanceof RefElementImpl && !refEntity.isValid()) { return InspectionsBundle.message("inspection.reference.invalid"); } return refEntity.getQualifiedName(); } public void removeRefElement(RefElement refElement, List<RefElement> deletedRefs) { List<RefEntity> children = refElement.getChildren(); if (children != null) { RefElement[] refElements = children.toArray(new RefElement[children.size()]); for (RefElement refChild : refElements) { removeRefElement(refChild, deletedRefs); } } ((RefManagerImpl)refElement.getRefManager()).removeReference(refElement); ((RefElementImpl)refElement).referenceRemoved(); if (!deletedRefs.contains(refElement)) deletedRefs.add(refElement); } protected boolean isValidPointForReference() { return myIsInProcess || ApplicationManager.getApplication().isUnitTestMode(); } }
lang-impl/src/com/intellij/codeInspection/reference/RefManagerImpl.java
/* * Created by IntelliJ IDEA. * User: max * Date: Oct 22, 2001 * Time: 8:21:36 PM * To change template for new class use * Code Style | Class Templates options (Tools | IDE Options). */ package com.intellij.codeInspection.reference; import com.intellij.ExtensionPoints; import com.intellij.analysis.AnalysisScope; import com.intellij.codeInspection.InspectionsBundle; import com.intellij.codeInspection.ex.GlobalInspectionContextImpl; import com.intellij.codeInspection.lang.InspectionExtensionsFactory; import com.intellij.codeInspection.lang.RefManagerExtension; import com.intellij.lang.Language; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.PathMacroManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectUtil; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Key; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.util.concurrency.JBReentrantReadWriteLock; import com.intellij.util.concurrency.LockFactory; import gnu.trove.THashMap; import org.jdom.Element; import org.jetbrains.annotations.Nullable; import java.util.*; public class RefManagerImpl extends RefManager { private int myLastUsedMask = 256 * 256 * 256 * 4; private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.reference.RefManager"); private final Project myProject; private AnalysisScope myScope; private RefProject myRefProject; private THashMap<PsiAnchor, RefElement> myRefTable; private THashMap<Module, RefModule> myModules; private final ProjectIterator myProjectIterator; private boolean myDeclarationsFound; private boolean myIsInProcess = false; private List<RefGraphAnnotator> myGraphAnnotators = new ArrayList<RefGraphAnnotator>(); private GlobalInspectionContextImpl myContext; private Map<Key, RefManagerExtension> myExtensions = new HashMap<Key, RefManagerExtension>(); private HashMap<Language, RefManagerExtension> myLanguageExtensions = new HashMap<Language, RefManagerExtension>(); private JBReentrantReadWriteLock myLock = LockFactory.createReadWriteLock(); public RefManagerImpl(Project project, AnalysisScope scope, GlobalInspectionContextImpl context) { myDeclarationsFound = false; myProject = project; myScope = scope; myContext = context; myRefProject = new RefProjectImpl(this); myRefTable = new THashMap<PsiAnchor, RefElement>(); myProjectIterator = new ProjectIterator(); for (InspectionExtensionsFactory factory : Extensions.getExtensions(InspectionExtensionsFactory.EP_NAME)) { final RefManagerExtension extension = factory.createRefManagerExtension(this); myExtensions.put(extension.getID(), extension); myLanguageExtensions.put(extension.getLanguage(), extension); } } public void iterate(RefVisitor visitor) { myLock.readLock().lock(); try { final THashMap<PsiAnchor, RefElement> refTable = getRefTable(); for (RefElement refElement : refTable.values()) { refElement.accept(visitor); } if (myModules != null) { for (RefModule refModule : myModules.values()) { refModule.accept(visitor); } } for (RefManagerExtension extension : myExtensions.values()) { extension.iterate(visitor); } } finally { myLock.readLock().unlock(); } } public void cleanup() { myScope = null; myRefProject = null; myRefTable = null; myModules = null; myContext = null; myGraphAnnotators.clear(); for (RefManagerExtension extension : myExtensions.values()) { extension.cleanup(); } } public AnalysisScope getScope() { return myScope; } public void fireNodeInitialized(RefElement refElement) { for (RefGraphAnnotator annotator : myGraphAnnotators) { annotator.onInitialize(refElement); } } public void fireNodeMarkedReferenced(RefElement refWhat, RefElement refFrom, boolean referencedFromClassInitializer, final boolean forReading, final boolean forWriting) { for (RefGraphAnnotator annotator : myGraphAnnotators) { annotator.onMarkReferenced(refWhat, refFrom, referencedFromClassInitializer, forReading, forWriting); } } public void fireBuildReferences(RefElement refElement) { for (RefGraphAnnotator annotator : myGraphAnnotators) { annotator.onReferencesBuild(refElement); } } public void registerGraphAnnotator(RefGraphAnnotator annotator) { myGraphAnnotators.add(annotator); } public int getLastUsedMask() { myLastUsedMask *= 2; return myLastUsedMask; } public <T> T getExtension(final Key<T> key) { return (T)myExtensions.get(key); } public String getType(final RefEntity ref) { for (RefManagerExtension extension : myExtensions.values()) { final String type = extension.getType(ref); if (type != null) return type; } if (ref instanceof RefFile) { return SmartRefElementPointer.FILE; } else if (ref instanceof RefModule) { return SmartRefElementPointer.MODULE; } else if (ref instanceof RefProject) { return SmartRefElementPointer.PROJECT; } else if (ref instanceof RefDirectory) { return SmartRefElementPointer.DIR; } return null; } public RefEntity getRefinedElement(RefEntity ref) { for (RefManagerExtension extension : myExtensions.values()) { ref = extension.getRefinedElement(ref); } return ref; } public Element export(RefEntity refEntity, final Element element, final int actualLine) { refEntity = getRefinedElement(refEntity); Element problem = new Element("problem"); if (refEntity instanceof RefElement) { final RefElement refElement = (RefElement)refEntity; PsiElement psiElement = refElement.getElement(); PsiFile psiFile = psiElement.getContainingFile(); Element fileElement = new Element("file"); Element lineElement = new Element("line"); final VirtualFile virtualFile = psiFile.getVirtualFile(); LOG.assertTrue(virtualFile != null); fileElement.addContent(virtualFile.getUrl()); if (actualLine == -1) { final Document document = PsiDocumentManager.getInstance(refElement.getRefManager().getProject()).getDocument(psiFile); LOG.assertTrue(document != null); lineElement.addContent(String.valueOf(document.getLineNumber(psiElement.getTextOffset()) + 1)); } else { lineElement.addContent(String.valueOf(actualLine)); } problem.addContent(fileElement); problem.addContent(lineElement); appendModule(problem, refElement.getModule()); } else if (refEntity instanceof RefModule) { final RefModule refModule = (RefModule)refEntity; final VirtualFile moduleFile = refModule.getModule().getModuleFile(); final Element fileElement = new Element("file"); fileElement.addContent(moduleFile != null ? moduleFile.getUrl() : refEntity.getName()); problem.addContent(fileElement); appendModule(problem, refModule); } for (RefManagerExtension extension : myExtensions.values()) { extension.export(refEntity, problem); } new SmartRefElementPointerImpl(refEntity, true).writeExternal(problem); element.addContent(problem); return problem; } @Nullable public String getGroupName(final RefElement entity) { for (RefManagerExtension extension : myExtensions.values()) { final String groupName = extension.getGroupName(entity); if (groupName != null) return groupName; } return null; } private static void appendModule(final Element problem, final RefModule refModule) { if (refModule != null) { Element moduleElement = new Element("module"); moduleElement.addContent(refModule.getName()); problem.addContent(moduleElement); } } public void findAllDeclarations() { if (!myDeclarationsFound) { long before = System.currentTimeMillis(); getScope().accept(myProjectIterator); myDeclarationsFound = true; LOG.info("Total duration of processing project usages:" + (System.currentTimeMillis() - before)); } } public boolean isDeclarationsFound() { return myDeclarationsFound; } public void inspectionReadActionStarted() { myIsInProcess = true; } public void inspectionReadActionFinished() { myIsInProcess = false; } public boolean isInProcess() { return myIsInProcess; } public Project getProject() { return myProject; } public RefProject getRefProject() { return myRefProject; } public THashMap<PsiAnchor, RefElement> getRefTable() { return myRefTable; } public void removeReference(RefElement refElem) { myLock.writeLock().lock(); try { final THashMap<PsiAnchor, RefElement> refTable = getRefTable(); final PsiElement element = refElem.getElement(); final RefManagerExtension extension = element != null ? getExtension(element.getLanguage()) : null; if (extension != null) { extension.removeReference(refElem); } if (refTable.remove(PsiAnchor.create(element)) != null) return; //PsiElement may have been invalidated and new one returned by getElement() is different so we need to do this stuff. for (PsiAnchor psiElement : refTable.keySet()) { if (refTable.get(psiElement) == refElem) { refTable.remove(psiElement); return; } } } finally { myLock.writeLock().unlock(); } } public void initializeAnnotators() { final Object[] graphAnnotators = Extensions.getRootArea().getExtensionPoint(ExtensionPoints.INSPECTIONS_GRAPH_ANNOTATOR).getExtensions(); for (Object annotator : graphAnnotators) { registerGraphAnnotator((RefGraphAnnotator)annotator); } for (RefGraphAnnotator graphAnnotator : myGraphAnnotators) { if (graphAnnotator instanceof RefGraphAnnotatorEx) { ((RefGraphAnnotatorEx)graphAnnotator).initialize(this); } } } private class ProjectIterator extends PsiElementVisitor { @Override public void visitElement(PsiElement element) { final RefManagerExtension extension = getExtension(element.getLanguage()); if (extension != null) { extension.visitElement(element); } for (PsiElement aChildren : element.getChildren()) { aChildren.accept(this); } } @Override public void visitFile(PsiFile file) { final VirtualFile virtualFile = file.getVirtualFile(); if (virtualFile != null) { myContext .incrementJobDoneAmount(GlobalInspectionContextImpl.BUILD_GRAPH, ProjectUtil.calcRelativeToProjectPath(virtualFile, myProject)); } final FileViewProvider viewProvider = file.getViewProvider(); final Set<Language> relevantLanguages = viewProvider.getLanguages(); for (Language language : relevantLanguages) { visitElement(viewProvider.getPsi(language)); } } } @Nullable public RefElement getReference(final PsiElement elem) { if (elem instanceof PsiDirectory) { return new RefDirectoryImpl((PsiDirectory)elem, this); } if (elem != null && belongsToScope(elem)) { if (!elem.isValid()) return null; RefElement ref = getFromRefTable(elem); if (ref == null) { if (!isValidPointForReference()) { //LOG.assertTrue(true, "References may become invalid after process is finished"); return null; } final RefElementImpl refElement = ApplicationManager.getApplication().runReadAction(new Computable<RefElementImpl>() { @Nullable public RefElementImpl compute() { final RefManagerExtension extension = getExtension(elem.getLanguage()); if (extension != null) { final RefElement refElement = extension.createRefElement(elem); if (refElement != null) return (RefElementImpl)refElement; } if (elem instanceof PsiFile) { return new RefFileImpl((PsiFile)elem, RefManagerImpl.this); } else { return null; } } }); if (refElement == null) return null; putToRefTable(elem, refElement); ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { refElement.initialize(); } }); return refElement; } return ref; } return null; } private RefManagerExtension getExtension(final Language language) { return myLanguageExtensions.get(language); } public @Nullable RefEntity getReference(final String type, final String fqName) { for (RefManagerExtension extension : myExtensions.values()) { final RefEntity refEntity = extension.getReference(type, fqName); if (refEntity != null) return refEntity; } if (SmartRefElementPointer.FILE.equals(type)) { return RefFileImpl.fileFromExternalName(this, fqName); } else if (SmartRefElementPointer.MODULE.equals(type)) { return RefModuleImpl.moduleFromName(this, fqName); } else if (SmartRefElementPointer.PROJECT.equals(type)) { return getRefProject(); } else if (SmartRefElementPointer.DIR.equals(type)) { final VirtualFile vFile = LocalFileSystem.getInstance().findFileByPath(PathMacroManager.getInstance(getProject()).expandPath(fqName)); if (vFile != null) { final PsiDirectory dir = PsiManager.getInstance(getProject()).findDirectory(vFile); return getReference(dir); } } return null; } protected RefElement getFromRefTable(final PsiElement element) { myLock.readLock().lock(); try { return getRefTable().get(PsiAnchor.create(element)); } finally { myLock.readLock().unlock(); } } protected void putToRefTable(final PsiElement element, final RefElement ref) { myLock.writeLock().lock(); try { getRefTable().put(PsiAnchor.create(element), ref); } finally { myLock.writeLock().unlock(); } } public RefModule getRefModule(Module module) { if (module == null) { return null; } if (myModules == null) { myModules = new THashMap<Module, RefModule>(); } RefModule refModule = myModules.get(module); if (refModule == null) { refModule = new RefModuleImpl(module, this); myModules.put(module, refModule); } return refModule; } public boolean belongsToScope(final PsiElement psiElement) { if (psiElement == null) return false; if (psiElement instanceof PsiCompiledElement) return false; final PsiFile containingFile = ApplicationManager.getApplication().runReadAction(new Computable<PsiFile>() { public PsiFile compute() { return psiElement.getContainingFile(); } }); if (containingFile == null) { return false; } for (RefManagerExtension extension : myExtensions.values()) { if (!extension.belongsToScope(psiElement)) return false; } final Boolean inProject = ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() { public Boolean compute() { return psiElement != null && psiElement.isValid() && psiElement.getManager().isInProject(psiElement); } }); return inProject.booleanValue() && (getScope() == null || getScope().contains(psiElement)); } public String getQualifiedName(RefEntity refEntity) { if (refEntity == null || refEntity instanceof RefElementImpl && !refEntity.isValid()) { return InspectionsBundle.message("inspection.reference.invalid"); } return refEntity.getQualifiedName(); } public void removeRefElement(RefElement refElement, List<RefElement> deletedRefs) { List<RefEntity> children = refElement.getChildren(); if (children != null) { RefElement[] refElements = children.toArray(new RefElement[children.size()]); for (RefElement refChild : refElements) { removeRefElement(refChild, deletedRefs); } } ((RefManagerImpl)refElement.getRefManager()).removeReference(refElement); ((RefElementImpl)refElement).referenceRemoved(); if (!deletedRefs.contains(refElement)) deletedRefs.add(refElement); } protected boolean isValidPointForReference() { return myIsInProcess || ApplicationManager.getApplication().isUnitTestMode(); } }
RefDirectory merge fixed
lang-impl/src/com/intellij/codeInspection/reference/RefManagerImpl.java
RefDirectory merge fixed
Java
apache-2.0
2510a4b431c0a17ab738651766ce3457b46168a8
0
SpineEventEngine/core-java,SpineEventEngine/core-java,SpineEventEngine/core-java
/* * Copyright 2020, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.server.model; import com.google.common.collect.ImmutableList; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.function.Predicate; import static com.google.common.base.Preconditions.checkNotNull; import static io.spine.util.Exceptions.newIllegalArgumentException; import static java.lang.reflect.Modifier.isPrivate; import static java.lang.reflect.Modifier.isProtected; import static java.lang.reflect.Modifier.isPublic; /** * The predicate for {@linkplain Modifier access modifiers} of {@linkplain Method methods}. */ public final class AccessModifier implements Predicate<Method> { public static final AccessModifier PUBLIC = new AccessModifier(Modifier::isPublic, "public"); public static final AccessModifier PROTECTED = new AccessModifier(Modifier::isProtected, "protected"); public static final AccessModifier PACKAGE_PRIVATE = new AccessModifier(methodModifier -> !(isPublic(methodModifier) || isProtected(methodModifier) || isPrivate(methodModifier)), "package-private"); public static final AccessModifier PRIVATE = new AccessModifier(Modifier::isPrivate, "private"); /** * The predicate which works with the {@linkplain Method#getModifiers() raw representation } * of method's access modifiers. */ private final Predicate<Integer> checkingMethod; /** * The name of the access modifier. * * <p>Serves for pretty printing. */ private final String name; private AccessModifier(Predicate<Integer> checkingMethod, String name) { this.checkingMethod = checkingMethod; this.name = name; } /** * Obtains the access modifier of the given method. * * @param method * the method to analyze * @return the access modifier of the given method */ static AccessModifier fromMethod(Method method) { checkNotNull(method); AccessModifier matchedModifier = ImmutableList .of(PRIVATE, PACKAGE_PRIVATE, PROTECTED, PUBLIC) .stream() .filter(modifier -> modifier.test(method)) .findFirst() .orElseThrow(() -> newIllegalArgumentException( "Could not determine the access level of the method `%s`.", method )); return matchedModifier; } /** * Checks whether the method is of the modifier determined by {@code this} instance. * * @param method * the method to check * @return {@code true} if the method is declared with the expected modifier, * {@code false} otherwise. */ @Override public boolean test(Method method) { return checkingMethod.test(method.getModifiers()); } @Override public String toString() { return name; } }
server/src/main/java/io/spine/server/model/AccessModifier.java
/* * Copyright 2020, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.server.model; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.function.Predicate; import static com.google.common.base.Preconditions.checkNotNull; import static io.spine.util.Exceptions.newIllegalArgumentException; import static java.lang.reflect.Modifier.isPrivate; import static java.lang.reflect.Modifier.isProtected; import static java.lang.reflect.Modifier.isPublic; /** * The predicate for {@linkplain Modifier access modifiers} of {@linkplain Method methods}. */ public final class AccessModifier implements Predicate<Method> { public static final AccessModifier PUBLIC = new AccessModifier(Modifier::isPublic, "public"); public static final AccessModifier PROTECTED = new AccessModifier(Modifier::isProtected, "protected"); public static final AccessModifier PACKAGE_PRIVATE = new AccessModifier(methodModifier -> !(isPublic(methodModifier) || isProtected(methodModifier) || isPrivate(methodModifier)), "package-private"); public static final AccessModifier PRIVATE = new AccessModifier(Modifier::isPrivate, "private"); /** * The predicate which works with the {@linkplain Method#getModifiers() raw representation } * of method's access modifiers. */ private final Predicate<Integer> checkingMethod; /** * The name of the access modifier. * * <p>Serves for pretty printing. */ private final String name; private AccessModifier(Predicate<Integer> checkingMethod, String name) { this.checkingMethod = checkingMethod; this.name = name; } /** * Obtains the access modifier of the given method. * * @param method * the method to analyze * @return the access modifier of the given method */ static AccessModifier fromMethod(Method method) { checkNotNull(method); AccessModifier matchedModifier = ImmutableList .of(PRIVATE, PACKAGE_PRIVATE, PROTECTED, PUBLIC) .stream() .filter(modifier -> modifier.test(method)) .findFirst() .orElseThrow(() -> newIllegalArgumentException( "Could not determine the access level of method %s.", method )); return matchedModifier; } /** * Composes a string representation of several access modifiers. * * @param modifiers * the modifiers to compose into a {@code String} * @return the string with modifier-as-strings */ static String asString(Iterable<AccessModifier> modifiers) { return Joiner.on(", ") .join(modifiers); } /** * Checks whether the method is of the modifier determined by {@code this} instance. * * @param method * the method to check * @return {@code true} if the method is declared with the expected modifier, * {@code false} otherwise. */ @Override public boolean test(Method method) { return checkingMethod.test(method.getModifiers()); } @Override public String toString() { return name; } }
Remove unused method
server/src/main/java/io/spine/server/model/AccessModifier.java
Remove unused method
Java
apache-2.0
ca8d2e88661742790029bf31972a42640d3e12b8
0
pinterest/secor,HenryCaiHaiying/secor,pinterest/secor,HenryCaiHaiying/secor
package com.pinterest.secor.common; import io.confluent.kafka.schemaregistry.client.CachedSchemaRegistryClient; import io.confluent.kafka.serializers.KafkaAvroDecoder; import org.apache.avro.Schema; import org.apache.avro.generic.GenericRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; public class SecorSchemaRegistryClient { private static final Logger LOG = LoggerFactory.getLogger(SecorSchemaRegistryClient.class); private KafkaAvroDecoder decoder; private static Map<String, Schema> schemas; public SecorSchemaRegistryClient(SecorConfig config) { try { LOG.info("Initializing schema registry {}", config.getSchemaRegistryUrl()); Properties props = new Properties(); props.put("schema.registry.url", config.getSchemaRegistryUrl()); CachedSchemaRegistryClient schemaRegistryClient = new CachedSchemaRegistryClient(config.getSchemaRegistryUrl(), 30); decoder = new KafkaAvroDecoder(schemaRegistryClient); schemas = new ConcurrentHashMap<>(); } catch (Exception e){ LOG.error("Error initalizing schema registry", e); throw new RuntimeException(e); } } public GenericRecord decodeMessage(String topic, byte[] message) { GenericRecord record = (GenericRecord) decoder.fromBytes(message); Schema schema = record.getSchema(); schemas.putIfAbsent(topic, schema); return record; } public Schema getSchema(String topic) { try { return schemas.get(topic); } catch (Exception e) { throw new RuntimeException(e); } } }
src/main/java/com/pinterest/secor/common/SecorSchemaRegistryClient.java
package com.pinterest.secor.common; import io.confluent.kafka.schemaregistry.client.CachedSchemaRegistryClient; import io.confluent.kafka.serializers.KafkaAvroDecoder; import org.apache.avro.Schema; import org.apache.avro.generic.GenericRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; public class SecorSchemaRegistryClient { private static final Logger LOG = LoggerFactory.getLogger(SecorSchemaRegistryClient.class); private static Object mutex = new Object(); private KafkaAvroDecoder decoder; private static Map<String, Schema> schemas; private static volatile SecorSchemaRegistryClient instance = null; public SecorSchemaRegistryClient(SecorConfig config) { try { LOG.info("Initializing schema registry {}", config.getSchemaRegistryUrl()); Properties props = new Properties(); props.put("schema.registry.url", config.getSchemaRegistryUrl()); CachedSchemaRegistryClient schemaRegistryClient = new CachedSchemaRegistryClient(config.getSchemaRegistryUrl(), 30); decoder = new KafkaAvroDecoder(schemaRegistryClient); schemas = new ConcurrentHashMap<>(); } catch (Exception e){ LOG.error("Error initalizing schema registry", e); throw new RuntimeException(e); } } public GenericRecord decodeMessage(String topic, byte[] message) { GenericRecord record = (GenericRecord) decoder.fromBytes(message); Schema schema = record.getSchema(); schemas.putIfAbsent(topic, schema); return record; } public Schema getSchema(String topic) { try { return schemas.get(topic); } catch (Exception e) { throw new RuntimeException(e); } } // public static GenericRecord decodeMessage(Message message) { // GenericRecord record = (GenericRecord) decoder.fromBytes(message.getPayload()); // schemas.put(message.getTopic(), record.getSchema()); // return record; // } }
remove unused fields and method
src/main/java/com/pinterest/secor/common/SecorSchemaRegistryClient.java
remove unused fields and method
Java
apache-2.0
af869800c8835630f3dad15525d32c429fe3d4a0
0
Kwangseob/graphhopper,joh12041/graphhopper,joh12041/graphhopper,prembasumatary/graphhopper,PGWelch/graphhopper,komoot/graphhopper,zzottel/graphhopper,bendavidson/graphhopper,seeebiii/graphhopper,msoftware/graphhopper,zzottel/graphhopper,jansoe/graphhopper,hguerrero/graphhopper,devemux86/graphhopper,don-philipe/graphhopper,routexl/graphhopper,mmalfertheiner/graphhopper,don-philipe/graphhopper,CEPFU/graphhopper,prembasumatary/graphhopper,cecemel/graphhopper,devemux86/graphhopper,hguerrero/graphhopper,tlatt/graphhopper,boldtrn/graphhopper,mmalfertheiner/graphhopper,don-philipe/graphhopper,kod3r/graphhopper,jansoe/graphhopper,cecemel/graphhopper,komoot/graphhopper,seeebiii/graphhopper,bendavidson/graphhopper,msoftware/graphhopper,cecemel/graphhopper,CEPFU/graphhopper,tobias74/graphhopper,cecemel/graphhopper,zzottel/graphhopper,HelgeKrueger/graphhopper,ammagamma/graphhopper,Ranjan101/graphhopper,engaric/graphhopper,kod3r/graphhopper,jansoe/graphhopper,prembasumatary/graphhopper,joh12041/graphhopper,kalvish/graphhopper,piemapping/graphhopper,bendavidson/graphhopper,ammagamma/graphhopper,CEPFU/graphhopper,msoftware/graphhopper,tobias74/graphhopper,ratrun/graphhopper,kod3r/graphhopper,PGWelch/graphhopper,joh12041/graphhopper,devemux86/graphhopper,zzottel/graphhopper,engaric/graphhopper,PGWelch/graphhopper,tobias74/graphhopper,heisenpai/GraphHopper,fbonzon/graphhopper,Ranjan101/graphhopper,tobias74/graphhopper,hguerrero/graphhopper,don-philipe/graphhopper,msoftware/graphhopper,CEPFU/graphhopper,fbonzon/graphhopper,prembasumatary/graphhopper,ammagamma/graphhopper,mmalfertheiner/graphhopper,tlatt/graphhopper,Ranjan101/graphhopper,boldtrn/graphhopper,graphhopper/graphhopper,piemapping/graphhopper,piemapping/graphhopper,kalvish/graphhopper,hguerrero/graphhopper,fbonzon/graphhopper,heisenpai/GraphHopper,engaric/graphhopper,graphhopper/graphhopper,tlatt/graphhopper,engaric/graphhopper,PGWelch/graphhopper,seeebiii/graphhopper,piemapping/graphhopper,graphhopper/graphhopper,kalvish/graphhopper,jansoe/graphhopper,routexl/graphhopper,seeebiii/graphhopper,HelgeKrueger/graphhopper,kalvish/graphhopper,bendavidson/graphhopper,routexl/graphhopper,komoot/graphhopper,Kwangseob/graphhopper,heisenpai/GraphHopper,ratrun/graphhopper,graphhopper/graphhopper,routexl/graphhopper,heisenpai/GraphHopper,Kwangseob/graphhopper,komoot/graphhopper,boldtrn/graphhopper,boldtrn/graphhopper,Kwangseob/graphhopper,kod3r/graphhopper,Ranjan101/graphhopper,mmalfertheiner/graphhopper,ratrun/graphhopper,HelgeKrueger/graphhopper,fbonzon/graphhopper,tlatt/graphhopper,ammagamma/graphhopper,ratrun/graphhopper,devemux86/graphhopper,HelgeKrueger/graphhopper
/* * Licensed to GraphHopper and Peter Karich under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * GraphHopper licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.graphhopper.http; import com.graphhopper.GHRequest; import com.graphhopper.GraphHopper; import com.graphhopper.GHResponse; import com.graphhopper.routing.util.FlagEncoder; import com.graphhopper.routing.util.WeightingMap; import com.graphhopper.util.*; import com.graphhopper.util.Helper; import com.graphhopper.util.shapes.BBox; import com.graphhopper.util.shapes.GHPoint; import java.io.IOException; import java.io.StringWriter; import java.util.*; import java.util.Map.Entry; import javax.inject.Inject; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import static javax.servlet.http.HttpServletResponse.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.json.JSONObject; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * Servlet to use GraphHopper in a remote application (mobile or browser). Attention: If type is * json it returns the points in GeoJson format (longitude,latitude) unlike the format "lat,lon" * used otherwise. * <p/> * @author Peter Karich */ public class GraphHopperServlet extends GHBaseServlet { @Inject private GraphHopper hopper; @Override public void doGet( HttpServletRequest req, HttpServletResponse res ) throws ServletException, IOException { try { writePath(req, res); } catch (IllegalArgumentException ex) { writeError(res, SC_BAD_REQUEST, ex.getMessage()); } catch (Exception ex) { logger.error("Error while executing request: " + req.getQueryString(), ex); writeError(res, SC_INTERNAL_SERVER_ERROR, "Problem occured:" + ex.getMessage()); } } void writePath( HttpServletRequest httpReq, HttpServletResponse res ) throws Exception { List<GHPoint> infoPoints = getPoints(httpReq, "point"); // we can reduce the path length based on the maximum differences to the original coordinates double minPathPrecision = getDoubleParam(httpReq, "way_point_max_distance", 1d); boolean writeGPX = "gpx".equalsIgnoreCase(getParam(httpReq, "type", "json")); boolean enableInstructions = writeGPX || getBooleanParam(httpReq, "instructions", true); boolean calcPoints = getBooleanParam(httpReq, "calc_points", true); boolean enableElevation = getBooleanParam(httpReq, "elevation", false); boolean pointsEncoded = getBooleanParam(httpReq, "points_encoded", true); String vehicleStr = getParam(httpReq, "vehicle", "car"); String weighting = getParam(httpReq, "weighting", "fastest"); String algoStr = getParam(httpReq, "algorithm", ""); String localeStr = getParam(httpReq, "locale", "en"); StopWatch sw = new StopWatch().start(); GHResponse ghRsp; if (!hopper.getEncodingManager().supports(vehicleStr)) { ghRsp = new GHResponse().addError(new IllegalArgumentException("Vehicle not supported: " + vehicleStr)); } else if (enableElevation && !hopper.hasElevation()) { ghRsp = new GHResponse().addError(new IllegalArgumentException("Elevation not supported!")); } else { FlagEncoder algoVehicle = hopper.getEncodingManager().getEncoder(vehicleStr); GHRequest request = new GHRequest(infoPoints); initHints(request, httpReq.getParameterMap()); request.setVehicle(algoVehicle.toString()). setWeighting(weighting). setAlgorithm(algoStr). setLocale(localeStr). getHints(). put("calcPoints", calcPoints). put("instructions", enableInstructions). put("wayPointMaxDistance", minPathPrecision); ghRsp = hopper.route(request); } float took = sw.stop().getSeconds(); String infoStr = httpReq.getRemoteAddr() + " " + httpReq.getLocale() + " " + httpReq.getHeader("User-Agent"); String logStr = httpReq.getQueryString() + " " + infoStr + " " + infoPoints + ", took:" + took + ", " + algoStr + ", " + weighting + ", " + vehicleStr; if (ghRsp.hasErrors()) logger.error(logStr + ", errors:" + ghRsp.getErrors()); else logger.info(logStr + ", distance: " + ghRsp.getDistance() + ", time:" + Math.round(ghRsp.getTime() / 60000f) + "min, points:" + ghRsp.getPoints().getSize() + ", debug - " + ghRsp.getDebugInfo()); if (writeGPX) { writeResponse(res, createGPXString(httpReq, res, ghRsp)); } else { Map<String, Object> map = createJson(ghRsp, calcPoints, pointsEncoded, enableElevation, enableInstructions); Object infoMap = map.get("info"); if (infoMap != null) ((Map) infoMap).put("took", Math.round(took * 1000)); writeJson(httpReq, res, new JSONObject(map)); } } protected String createGPXString( HttpServletRequest req, HttpServletResponse res, GHResponse rsp ) throws Exception { boolean includeElevation = getBooleanParam(req, "elevation", false); res.setCharacterEncoding("UTF-8"); res.setContentType("application/xml"); String trackName = getParam(req, "track", "GraphHopper Track"); res.setHeader("Content-Disposition", "attachment;filename=" + "GraphHopper.gpx"); long time = getLongParam(req, "millis", System.currentTimeMillis()); if (rsp.hasErrors()) return errorsToXML(rsp.getErrors()); else return rsp.getInstructions().createGPX(trackName, time, includeElevation); } String errorsToXML( List<Throwable> list ) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.newDocument(); Element gpxElement = doc.createElement("gpx"); gpxElement.setAttribute("creator", "GraphHopper"); gpxElement.setAttribute("version", "1.1"); doc.appendChild(gpxElement); Element mdElement = doc.createElement("metadata"); gpxElement.appendChild(mdElement); Element errorsElement = doc.createElement("extensions"); mdElement.appendChild(errorsElement); for (Throwable t : list) { Element error = doc.createElement("error"); errorsElement.appendChild(error); error.setAttribute("message", t.getMessage()); error.setAttribute("details", t.getClass().getName()); } TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); return writer.toString(); } protected Map<String, Object> createJson( GHResponse rsp, boolean calcPoints, boolean pointsEncoded, boolean includeElevation, boolean enableInstructions ) { Map<String, Object> json = new HashMap<String, Object>(); Map<String, Object> jsonInfo = new HashMap<String, Object>(); json.put("info", jsonInfo); jsonInfo.put("copyrights", Arrays.asList("GraphHopper", "OpenStreetMap contributors")); if (rsp.hasErrors()) { List<Map<String, String>> list = new ArrayList<Map<String, String>>(); for (Throwable t : rsp.getErrors()) { Map<String, String> map = new HashMap<String, String>(); map.put("message", t.getMessage()); map.put("details", t.getClass().getName()); list.add(map); } jsonInfo.put("errors", list); } else { Map<String, Object> jsonPath = new HashMap<String, Object>(); jsonPath.put("distance", Helper.round(rsp.getDistance(), 3)); jsonPath.put("weight", Helper.round6(rsp.getDistance())); jsonPath.put("time", rsp.getTime()); if (calcPoints) { jsonPath.put("points_encoded", pointsEncoded); PointList points = rsp.getPoints(); if (points.getSize() >= 2) { BBox maxBounds = hopper.getGraph().getBounds(); BBox maxBounds2D = new BBox(maxBounds.minLon, maxBounds.maxLon, maxBounds.minLat, maxBounds.maxLat); jsonPath.put("bbox", rsp.calcRouteBBox(maxBounds2D).toGeoJson()); } jsonPath.put("points", createPoints(points, pointsEncoded, includeElevation)); if (enableInstructions) { InstructionList instructions = rsp.getInstructions(); jsonPath.put("instructions", instructions.createJson()); } } json.put("paths", Collections.singletonList(jsonPath)); } return json; } protected Object createPoints( PointList points, boolean pointsEncoded, boolean includeElevation ) { if (pointsEncoded) return WebHelper.encodePolyline(points, includeElevation); Map<String, Object> jsonPoints = new HashMap<String, Object>(); jsonPoints.put("type", "LineString"); jsonPoints.put("coordinates", points.toGeoJson(includeElevation)); return jsonPoints; } protected List<GHPoint> getPoints( HttpServletRequest req, String key ) { String[] pointsAsStr = getParams(req, key); final List<GHPoint> infoPoints = new ArrayList<GHPoint>(pointsAsStr.length); for (String str : pointsAsStr) { String[] fromStrs = str.split(","); if (fromStrs.length == 2) { GHPoint point = GHPoint.parse(str); if (point != null) { infoPoints.add(point); } } } return infoPoints; } protected void initHints( GHRequest request, Map<String, String[]> parameterMap ) { WeightingMap m = request.getHints(); for (Entry<String, String[]> e : parameterMap.entrySet()) { if (e.getValue().length == 1) m.put(e.getKey(), e.getValue()[0]); } } }
web/src/main/java/com/graphhopper/http/GraphHopperServlet.java
/* * Licensed to GraphHopper and Peter Karich under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * GraphHopper licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.graphhopper.http; import com.graphhopper.GHRequest; import com.graphhopper.GraphHopper; import com.graphhopper.GHResponse; import com.graphhopper.routing.util.FlagEncoder; import com.graphhopper.routing.util.WeightingMap; import com.graphhopper.util.*; import com.graphhopper.util.Helper; import com.graphhopper.util.shapes.BBox; import com.graphhopper.util.shapes.GHPoint; import java.io.IOException; import java.io.StringWriter; import java.util.*; import java.util.Map.Entry; import javax.inject.Inject; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import static javax.servlet.http.HttpServletResponse.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.json.JSONObject; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * Servlet to use GraphHopper in a remote application (mobile or browser). Attention: If type is * json it returns the points in GeoJson format (longitude,latitude) unlike the format "lat,lon" * used otherwise. * <p/> * @author Peter Karich */ public class GraphHopperServlet extends GHBaseServlet { @Inject private GraphHopper hopper; @Override public void doGet( HttpServletRequest req, HttpServletResponse res ) throws ServletException, IOException { try { writePath(req, res); } catch (IllegalArgumentException ex) { writeError(res, SC_BAD_REQUEST, ex.getMessage()); } catch (Exception ex) { logger.error("Error while executing request: " + req.getQueryString(), ex); writeError(res, SC_INTERNAL_SERVER_ERROR, "Problem occured:" + ex.getMessage()); } } void writePath( HttpServletRequest httpReq, HttpServletResponse res ) throws Exception { List<GHPoint> infoPoints = getPoints(httpReq, "point"); // we can reduce the path length based on the maximum differences to the original coordinates double minPathPrecision = getDoubleParam(httpReq, "way_point_max_distance", 1d); boolean writeGPX = "gpx".equalsIgnoreCase(getParam(httpReq, "type", "json")); boolean enableInstructions = writeGPX || getBooleanParam(httpReq, "instructions", true); boolean calcPoints = getBooleanParam(httpReq, "calc_points", true); boolean elevation = getBooleanParam(httpReq, "elevation", false); String vehicleStr = getParam(httpReq, "vehicle", "car"); String weighting = getParam(httpReq, "weighting", "fastest"); String algoStr = getParam(httpReq, "algorithm", ""); String localeStr = getParam(httpReq, "locale", "en"); StopWatch sw = new StopWatch().start(); GHResponse ghRsp; if (!hopper.getEncodingManager().supports(vehicleStr)) { ghRsp = new GHResponse().addError(new IllegalArgumentException("Vehicle not supported: " + vehicleStr)); } else if (elevation && !hopper.hasElevation()) { ghRsp = new GHResponse().addError(new IllegalArgumentException("Elevation not supported!")); } else { FlagEncoder algoVehicle = hopper.getEncodingManager().getEncoder(vehicleStr); GHRequest request = new GHRequest(infoPoints); initHints(request, httpReq.getParameterMap()); request.setVehicle(algoVehicle.toString()). setWeighting(weighting). setAlgorithm(algoStr). setLocale(localeStr). getHints(). put("calcPoints", calcPoints). put("instructions", enableInstructions). put("wayPointMaxDistance", minPathPrecision); ghRsp = hopper.route(request); } float took = sw.stop().getSeconds(); String infoStr = httpReq.getRemoteAddr() + " " + httpReq.getLocale() + " " + httpReq.getHeader("User-Agent"); String logStr = httpReq.getQueryString() + " " + infoStr + " " + infoPoints + ", took:" + took + ", " + algoStr + ", " + weighting + ", " + vehicleStr; if (ghRsp.hasErrors()) logger.error(logStr + ", errors:" + ghRsp.getErrors()); else logger.info(logStr + ", distance: " + ghRsp.getDistance() + ", time:" + Math.round(ghRsp.getTime() / 60000f) + "min, points:" + ghRsp.getPoints().getSize() + ", debug - " + ghRsp.getDebugInfo()); if (writeGPX) writeResponse(res, createGPXString(httpReq, res, ghRsp)); else writeJson(httpReq, res, new JSONObject(createJson(httpReq, ghRsp, took))); } protected String createGPXString( HttpServletRequest req, HttpServletResponse res, GHResponse rsp ) throws Exception { boolean includeElevation = getBooleanParam(req, "elevation", false); res.setCharacterEncoding("UTF-8"); res.setContentType("application/xml"); String trackName = getParam(req, "track", "GraphHopper Track"); res.setHeader("Content-Disposition", "attachment;filename=" + "GraphHopper.gpx"); long time = getLongParam(req, "millis", System.currentTimeMillis()); if (rsp.hasErrors()) return errorsToXML(rsp.getErrors()); else return rsp.getInstructions().createGPX(trackName, time, includeElevation); } String errorsToXML( List<Throwable> list ) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.newDocument(); Element gpxElement = doc.createElement("gpx"); gpxElement.setAttribute("creator", "GraphHopper"); gpxElement.setAttribute("version", "1.1"); doc.appendChild(gpxElement); Element mdElement = doc.createElement("metadata"); gpxElement.appendChild(mdElement); Element errorsElement = doc.createElement("extensions"); mdElement.appendChild(errorsElement); for (Throwable t : list) { Element error = doc.createElement("error"); errorsElement.appendChild(error); error.setAttribute("message", t.getMessage()); error.setAttribute("details", t.getClass().getName()); } TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); return writer.toString(); } protected Map<String, Object> createJson( HttpServletRequest req, GHResponse rsp, float took ) { boolean enableInstructions = getBooleanParam(req, "instructions", true); boolean pointsEncoded = getBooleanParam(req, "points_encoded", true); boolean calcPoints = getBooleanParam(req, "calc_points", true); boolean includeElevation = getBooleanParam(req, "elevation", false); Map<String, Object> json = new HashMap<String, Object>(); Map<String, Object> jsonInfo = new HashMap<String, Object>(); json.put("info", jsonInfo); jsonInfo.put("copyrights", Arrays.asList("GraphHopper", "OpenStreetMap contributors")); if (rsp.hasErrors()) { List<Map<String, String>> list = new ArrayList<Map<String, String>>(); for (Throwable t : rsp.getErrors()) { Map<String, String> map = new HashMap<String, String>(); map.put("message", t.getMessage()); map.put("details", t.getClass().getName()); list.add(map); } jsonInfo.put("errors", list); } else { jsonInfo.put("took", Math.round(took * 1000)); Map<String, Object> jsonPath = new HashMap<String, Object>(); jsonPath.put("distance", Helper.round(rsp.getDistance(), 3)); jsonPath.put("weight", Helper.round6(rsp.getDistance())); jsonPath.put("time", rsp.getTime()); if (calcPoints) { jsonPath.put("points_encoded", pointsEncoded); PointList points = rsp.getPoints(); if (points.getSize() >= 2) { BBox maxBounds = hopper.getGraph().getBounds(); BBox maxBounds2D = new BBox(maxBounds.minLon, maxBounds.maxLon, maxBounds.minLat, maxBounds.maxLat); jsonPath.put("bbox", rsp.calcRouteBBox(maxBounds2D).toGeoJson()); } jsonPath.put("points", createPoints(points, pointsEncoded, includeElevation)); if (enableInstructions) { InstructionList instructions = rsp.getInstructions(); jsonPath.put("instructions", instructions.createJson()); } } json.put("paths", Collections.singletonList(jsonPath)); } return json; } protected Object createPoints( PointList points, boolean pointsEncoded, boolean includeElevation ) { if (pointsEncoded) return WebHelper.encodePolyline(points, includeElevation); Map<String, Object> jsonPoints = new HashMap<String, Object>(); jsonPoints.put("type", "LineString"); jsonPoints.put("coordinates", points.toGeoJson(includeElevation)); return jsonPoints; } protected List<GHPoint> getPoints( HttpServletRequest req, String key ) throws IOException { String[] pointsAsStr = getParams(req, key); final List<GHPoint> infoPoints = new ArrayList<GHPoint>(pointsAsStr.length); for (String str : pointsAsStr) { String[] fromStrs = str.split(","); if (fromStrs.length == 2) { GHPoint point = GHPoint.parse(str); if (point != null) { infoPoints.add(point); } } } return infoPoints; } protected void initHints( GHRequest request, Map<String, String[]> parameterMap ) { WeightingMap m = request.getHints(); for (Entry<String, String[]> e : parameterMap.entrySet()) { if (e.getValue().length == 1) m.put(e.getKey(), e.getValue()[0]); } } }
minor refactoring for json creation
web/src/main/java/com/graphhopper/http/GraphHopperServlet.java
minor refactoring for json creation
Java
apache-2.0
236166a3e658c82925ece1d429ff60370c939c52
0
AWildBeard/Terasology,kaen/Terasology,MovingBlocks/Terasology,DPirate/Terasology,kartikey0303/Terasology,MovingBlocks/Terasology,MovingBlocks/Terasology,kaen/Terasology,dannyzhou98/Terasology,Nanoware/Terasology,dannyzhou98/Terasology,mertserezli/Terasology,Halamix2/Terasology,Nanoware/Terasology,Malanius/Terasology,DPirate/Terasology,Halamix2/Terasology,AWildBeard/Terasology,Vizaxo/Terasology,kartikey0303/Terasology,Vizaxo/Terasology,Nanoware/Terasology,mertserezli/Terasology,Malanius/Terasology
/* * Copyright 2016 MovingBlocks * * 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.terasology.rendering.dag.nodes; import org.terasology.assets.ResourceUrn; import org.terasology.config.Config; import org.terasology.config.RenderingConfig; import org.terasology.monitoring.PerformanceMonitor; import org.terasology.registry.In; import org.terasology.rendering.dag.ConditionDependentNode; import org.terasology.rendering.dag.stateChanges.BindFBO; import org.terasology.rendering.dag.stateChanges.EnableMaterial; import org.terasology.rendering.opengl.FBO; import org.terasology.rendering.opengl.FBOConfig; import org.terasology.rendering.opengl.fbms.DisplayResolutionDependentFBOs; import org.terasology.rendering.world.WorldRenderer; import static org.lwjgl.opengl.GL11.GL_COLOR_BUFFER_BIT; import static org.lwjgl.opengl.GL11.GL_DEPTH_BUFFER_BIT; import static org.lwjgl.opengl.GL11.glClear; import static org.terasology.rendering.opengl.OpenGLUtils.bindDisplay; import static org.terasology.rendering.opengl.OpenGLUtils.renderFullscreenQuad; import static org.terasology.rendering.opengl.ScalingFactors.FULL_SCALE; /** * TODO: Add diagram of this node */ public class OutlineNode extends ConditionDependentNode { public static final ResourceUrn OUTLINE = new ResourceUrn("engine:outline"); @In private DisplayResolutionDependentFBOs displayResolutionDependentFBOs; @In private WorldRenderer worldRenderer; @In private Config config; private RenderingConfig renderingConfig; @Override public void initialise() { renderingConfig = config.getRendering(); renderingConfig.subscribe(renderingConfig.OUTLINE, this); requiresCondition(() -> renderingConfig.isOutline()); requiresFBO(new FBOConfig(OUTLINE, FULL_SCALE, FBO.Type.DEFAULT), displayResolutionDependentFBOs); addDesiredStateChange(new EnableMaterial("engine:prog.sobel")); // TODO: verify inputs: shouldn't there be a texture binding here? addDesiredStateChange(new BindFBO(OUTLINE, displayResolutionDependentFBOs)); } /** * Enabled by the "outline" option in the render settings, this method generates * landscape/objects outlines and stores them into a buffer in its own FBO. The * stored image is eventually combined with others. * <p> * The outlines visually separate a given object (including the landscape) or parts of it * from sufficiently distant objects it overlaps. It is effectively a depth-based edge * detection technique and internally uses a Sobel operator. * <p> * For further information see: http://en.wikipedia.org/wiki/Sobel_operator */ @Override public void process() { PerformanceMonitor.startActivity("rendering/outline"); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // TODO: verify this is necessary renderFullscreenQuad(); bindDisplay(); // TODO: verify this is necessary PerformanceMonitor.endActivity(); } }
engine/src/main/java/org/terasology/rendering/dag/nodes/OutlineNode.java
/* * Copyright 2016 MovingBlocks * * 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.terasology.rendering.dag.nodes; import org.terasology.assets.ResourceUrn; import org.terasology.config.Config; import org.terasology.config.RenderingConfig; import org.terasology.monitoring.PerformanceMonitor; import org.terasology.registry.In; import org.terasology.rendering.assets.material.Material; import org.terasology.rendering.dag.AbstractNode; import static org.terasology.rendering.opengl.DefaultDynamicFBOs.READ_ONLY_GBUFFER; import org.terasology.rendering.opengl.FBO; import org.terasology.rendering.opengl.FBOConfig; import static org.terasology.rendering.opengl.ScalingFactors.FULL_SCALE; import org.terasology.rendering.opengl.fbms.DisplayResolutionDependentFBOs; import org.terasology.rendering.world.WorldRenderer; import static org.lwjgl.opengl.GL11.GL_COLOR_BUFFER_BIT; import static org.lwjgl.opengl.GL11.GL_DEPTH_BUFFER_BIT; import static org.lwjgl.opengl.GL11.glClear; import static org.terasology.rendering.opengl.OpenGLUtils.bindDisplay; import static org.terasology.rendering.opengl.OpenGLUtils.renderFullscreenQuad; import static org.terasology.rendering.opengl.OpenGLUtils.setViewportToSizeOf; /** * TODO: Add diagram of this node */ public class OutlineNode extends AbstractNode { public static final ResourceUrn OUTLINE = new ResourceUrn("engine:outline"); @In private DisplayResolutionDependentFBOs displayResolutionDependentFBOs; @In private WorldRenderer worldRenderer; @In private Config config; private RenderingConfig renderingConfig; private Material outline; private FBO outlineFBO; @Override public void initialise() { renderingConfig = config.getRendering(); outline = worldRenderer.getMaterial("engine:prog.sobel"); requiresFBO(new FBOConfig(OUTLINE, FULL_SCALE, FBO.Type.DEFAULT), displayResolutionDependentFBOs); } /** * Enabled by the "outline" option in the render settings, this method generates * landscape/objects outlines and stores them into a buffer in its own FBO. The * stored image is eventually combined with others. * <p> * The outlines visually separate a given object (including the landscape) or parts of it * from sufficiently distant objects it overlaps. It is effectively a depth-based edge * detection technique and internally uses a Sobel operator. * <p> * For further information see: http://en.wikipedia.org/wiki/Sobel_operator */ @Override public void process() { if (renderingConfig.isOutline()) { // TODO: define state changes after this check is eliminated PerformanceMonitor.startActivity("rendering/outline"); outlineFBO = displayResolutionDependentFBOs.get(OUTLINE); outline.enable(); // TODO: verify inputs: shouldn't there be a texture binding here? outlineFBO.bind(); setViewportToSizeOf(outlineFBO); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // TODO: verify this is necessary renderFullscreenQuad(); bindDisplay(); // TODO: verify this is necessary setViewportToSizeOf(READ_ONLY_GBUFFER); // TODO: verify this is necessary PerformanceMonitor.endActivity(); } } }
Add desiredStateChanges to PrePostCompositeNode
engine/src/main/java/org/terasology/rendering/dag/nodes/OutlineNode.java
Add desiredStateChanges to PrePostCompositeNode
Java
apache-2.0
e3b4ddd5aa64bdf485496841572454106f971881
0
kangkangSS/coolweather
package com.coolweather.app.db; import java.util.ArrayList; import java.util.List; import com.coolweather.app.model.City; import com.coolweather.app.model.County; import com.coolweather.app.model.Province; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; public class CoolWeatherDB { public static final String DB_NAME="cool_weather"; public static final int VERSION=1; public static CoolWeatherDB coolWeatherDB; private SQLiteDatabase db; private CoolWeatherDB(Context context) { // TODO ԶɵĹ캯 CoolWeatherOpenHelper dbHelper=new CoolWeatherOpenHelper(context, DB_NAME, null, VERSION); db=dbHelper.getWritableDatabase(); } public synchronized static CoolWeatherDB getInstance(Context context){ if(coolWeatherDB==null){ coolWeatherDB=new CoolWeatherDB(context); } return coolWeatherDB; } public void saveProvice(Province province){ if(province!=null){ ContentValues value=new ContentValues(); value.put("province_name", province.getProvinceName()); value.put("province_code",province.getProvinceCode()); db.insert("Province", null, value); } } public List<Province> loadProvince(){ List<Province> list=new ArrayList<Province>(); Cursor cursor=db.query("Province", null, null, null, null, null, null); if(cursor.moveToFirst()){ do{ Province province=new Province(); province.setId(cursor.getInt(cursor.getColumnIndex("id"))); province.setProvinceCode(cursor.getString(cursor.getColumnIndex("province_code"))); province.setProvinceName(cursor.getString(cursor.getColumnIndex("province_name"))); list.add(province); }while(cursor.moveToNext()); } if(cursor!=null){ cursor.close(); } return list; } public void saveCity(City city){ if(city!=null){ ContentValues value=new ContentValues(); value.put("city_name", city.getCityName()); value.put("city_code",city.getCityCode()); value.put("province_id", city.getProvinceId()); db.insert("City", null, value); } } public List<City> loadCity(int provinceId){ List<City> list=new ArrayList<City>(); Cursor cursor=db.query("City", null, "province_id=?", new String[] {String.valueOf(provinceId)}, null, null, null); if(cursor.moveToFirst()){ do{ City city=new City(); city.setId(cursor.getInt(cursor.getColumnIndex("id"))); city.setCityCode(cursor.getString(cursor.getColumnIndex("city_code"))); city.setCityName(cursor.getString(cursor.getColumnIndex("city_name"))); city.setProvinceId(provinceId); list.add(city); }while(cursor.moveToNext()); } if(cursor!=null){ cursor.close(); } return list; } public void saveCounty(County county){ if(county!=null){ ContentValues value=new ContentValues(); value.put("county_name", county.getCountyName()); value.put("county_code",county.getCountyCode()); value.put("city_id", county.getCityId()); db.insert("County", null, value); } } public List<County> loadCounty(int cityId){ List<County> list=new ArrayList<County>(); Cursor cursor=db.query("County", null, "city_id=?", new String[] {String.valueOf(cityId)}, null, null, null); if(cursor.moveToFirst()){ do{ County county=new County(); county.setId(cursor.getInt(cursor.getColumnIndex("id"))); county.setCountyCode(cursor.getString(cursor.getColumnIndex("county_code"))); county.setCountyName(cursor.getString(cursor.getColumnIndex("county_name"))); county.setCityId(cityId); list.add(county); }while(cursor.moveToNext()); } if(cursor!=null){ cursor.close(); } return list; } }
src/com/coolweather/app/db/CoolWeatherDB.java
package com.coolweather.app.db; import java.util.ArrayList; import java.util.List; import com.coolweather.app.model.City; import com.coolweather.app.model.County; import com.coolweather.app.model.Province; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; public class CoolWeatherDB { public static final String DB_NAME="cool_weather"; public static final int VERSION=1; public static CoolWeatherDB coolWeatherDB; private SQLiteDatabase db; private CoolWeatherDB(Context context) { // TODO ԶɵĹ캯 CoolWeatherOpenHelper dbHelper=new CoolWeatherOpenHelper(context, DB_NAME, null, VERSION); db=dbHelper.getWritableDatabase(); } public synchronized static CoolWeatherDB getInstance(Context context){ if(coolWeatherDB==null){ coolWeatherDB=new CoolWeatherDB(context); } return coolWeatherDB; } public void saveProvice(Province province){ if(province!=null){ ContentValues value=new ContentValues(); value.put("province_name", province.getProvinceName()); value.put("province_code",province.getProvinceCode()); db.insert("Province", null, value); } } public List<Province> loadProvince(){ List<Province> list=new ArrayList<Province>(); Cursor cursor=db.query("Province", null, null, null, null, null, null); if(cursor.moveToFirst()){ do{ Province province=new Province(); province.setId(cursor.getColumnIndex("id")); province.setProvinceCode(cursor.getString(cursor.getColumnIndex("province_code"))); province.setProvinceName(cursor.getString(cursor.getColumnIndex("province_name"))); list.add(province); }while(cursor.moveToNext()); } if(cursor!=null){ cursor.close(); } return list; } public void saveCity(City city){ if(city!=null){ ContentValues value=new ContentValues(); value.put("city_name", city.getCityName()); value.put("city_code",city.getCityCode()); value.put("province_id", city.getProvinceId()); db.insert("City", null, value); } } public List<City> loadCity(int provinceId){ List<City> list=new ArrayList<City>(); Cursor cursor=db.query("City", null, "province_id=?", new String[] {String.valueOf(provinceId)}, null, null, null); if(cursor.moveToFirst()){ do{ City city=new City(); city.setId(cursor.getColumnIndex("id")); city.setCityCode(cursor.getString(cursor.getColumnIndex("city_code"))); city.setCityName(cursor.getString(cursor.getColumnIndex("city_name"))); city.setProvinceId(provinceId); list.add(city); }while(cursor.moveToNext()); } if(cursor!=null){ cursor.close(); } return list; } public void saveCounty(County county){ if(county!=null){ ContentValues value=new ContentValues(); value.put("county_name", county.getCountyName()); value.put("county_code",county.getCountyCode()); value.put("city_id", county.getCityId()); db.insert("County", null, value); } } public List<County> loadCounty(int cityId){ List<County> list=new ArrayList<County>(); Cursor cursor=db.query("County", null, "city_id=?", new String[] {String.valueOf(cityId)}, null, null, null); if(cursor.moveToFirst()){ do{ County county=new County(); county.setId(cursor.getColumnIndex("id")); county.setCountyCode(cursor.getString(cursor.getColumnIndex("county_code"))); county.setCountyName(cursor.getString(cursor.getColumnIndex("county_name"))); county.setCityId(cityId); list.add(county); }while(cursor.moveToNext()); } if(cursor!=null){ cursor.close(); } return list; } }
数据库修改正常
src/com/coolweather/app/db/CoolWeatherDB.java
数据库修改正常
Java
apache-2.0
ac56e152018e56ae729c55f4313e56e967fcdf99
0
opendatakit/androidcommon
/* * Copyright (C) 2012-2013 University of Washington * * 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.opendatakit.common.android.utilities; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileFilter; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.Map; import org.apache.commons.lang3.CharEncoding; import org.opendatakit.common.android.utilities.StaticStateManipulator.IStaticFieldManipulator; import android.util.Log; /** * Logger that emits logs to the LOGGING_PATH and recycles them as needed. * Useful to separate out ODK log entries from the overall logging stream, * especially on heavily logged 4.x systems. * * @author mitchellsundt@gmail.com */ public class WebLogger { private static final long MILLISECONDS_DAY = 86400000L; private static final long FLUSH_INTERVAL = 12000L; // 5 times a minute private static final int ASSERT = 1; private static final int VERBOSE = 2; private static final int DEBUG = 3; private static final int INFO = 4; private static final int WARN = 5; private static final int ERROR = 6; private static final int SUCCESS = 7; private static final int TIP = 8; private static final int LOG_INFO_LEVEL = 1; private static long lastStaleScan = 0L; private static Map<String, WebLogger> loggers = new HashMap<String, WebLogger>(); static { // register a state-reset manipulator for 'loggers' field. StaticStateManipulator.get().register(99, new IStaticFieldManipulator() { @Override public void reset() { for ( WebLogger l : loggers.values() ) { l.close(); } loggers.clear(); } }); } /** * Instance variables */ // appName under which to write log private final String appName; // dateStamp (filename) of opened stream private String dateStamp = null; // opened stream private OutputStreamWriter logFile = null; // the last time we flushed our output stream private long lastFlush = 0L; private static class ThreadLogger extends ThreadLocal<String> { @Override protected String initialValue() { return null; } } private static ThreadLogger contextLogger = new ThreadLogger(); public static WebLogger getContextLogger() { String appNameOfThread = contextLogger.get(); if ( appNameOfThread != null ) { return getLogger(appNameOfThread); } return null; } public synchronized static WebLogger getLogger(String appName) { WebLogger logger = loggers.get(appName); if (logger == null) { logger = new WebLogger(appName); loggers.put(appName, logger); } contextLogger.set(appName); long now = System.currentTimeMillis(); if (lastStaleScan + MILLISECONDS_DAY < now) { try { // ensure we have the directories created... ODKFileUtils.verifyExternalStorageAvailability(); ODKFileUtils.assertDirectoryStructure(appName); // scan for stale logs... String loggingPath = ODKFileUtils.getLoggingFolder(appName); final long distantPast = now - 30L * MILLISECONDS_DAY; // thirty days // ago... File loggingDirectory = new File(loggingPath); loggingDirectory.mkdirs(); File[] stale = loggingDirectory.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return (pathname.lastModified() < distantPast); } }); if (stale != null) { for (File f : stale) { f.delete(); } } } catch (Exception e) { // no exceptions are claimed, but since we can mount/unmount // the SDCard, there might be an external storage unavailable // exception that would otherwise percolate up. e.printStackTrace(); } finally { // whether or not we failed, record that we did the scan. lastStaleScan = now; } } return logger; } private WebLogger(String appName) { this.appName = appName; } private synchronized void close() { if ( logFile != null ) { OutputStreamWriter writer = logFile; logFile = null; try { writer.flush(); writer.close(); } catch ( IOException e ) { Log.e("WebLogger", "Unable to flush and close " + appName + " WebLogger"); } } } private synchronized void log(String logMsg) throws IOException { String curDateStamp = (new SimpleDateFormat("yyyy-MM-dd_HH", Locale.ENGLISH)).format(new Date()); if ( logFile == null || dateStamp == null || !curDateStamp.equals(dateStamp) ) { // the file we should log to has changed. // or has not yet been opened. if ( logFile != null ) { // close existing writer... OutputStreamWriter writer = logFile; logFile = null; try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } // ensure we have the directories created... ODKFileUtils.verifyExternalStorageAvailability(); ODKFileUtils.assertDirectoryStructure(appName); String loggingPath = ODKFileUtils.getLoggingFolder(appName); File loggingDirectory = new File(loggingPath); if (!loggingDirectory.exists()) { if (!loggingDirectory.mkdirs()) { Log.e("WebLogger", "Unable to create logging directory"); return; } } if (!loggingDirectory.isDirectory()) { Log.e("WebLogger", "Logging Directory exists but is not a directory!"); return; } File f = new File(loggingDirectory, curDateStamp + ".log"); try { FileOutputStream fo = new FileOutputStream(f, true); logFile = new OutputStreamWriter(new BufferedOutputStream(fo), CharEncoding.UTF_8); dateStamp = curDateStamp; // if we see a lot of these being logged, we have a problem logFile.write("---- starting ----\n"); } catch (Exception e) { e.printStackTrace(); Log.e("WebLogger", "Unexpected exception while opening logging file: " + e.toString()); try { if ( logFile != null ) { logFile.close(); } } catch (Exception ex) { // ignore } logFile = null; return; } } if ( logFile != null ) { logFile.write(logMsg + "\n"); } if ( lastFlush + WebLogger.FLUSH_INTERVAL < System.currentTimeMillis() ) { // log when we are explicitly flushing, just to have a record of that in the log logFile.write("---- flushing ----\n"); logFile.flush(); lastFlush = System.currentTimeMillis(); } } public void log(int severity, String t, String logMsg) { try { // do logcat logging... if ( severity == ERROR ) { Log.e(t, logMsg); } else if ( severity == WARN ) { Log.w(t, logMsg); } else if ( LOG_INFO_LEVEL >= severity ) { Log.i(t, logMsg); } else { Log.d(t, logMsg); } // and compose the log to the file... switch (severity) { case ASSERT: logMsg = "A/" + t + ": " + logMsg; break; case DEBUG: logMsg = "D/" + t + ": " + logMsg; break; case ERROR: logMsg = "E/" + t + ": " + logMsg; break; case INFO: logMsg = "I/" + t + ": " + logMsg; break; case SUCCESS: logMsg = "S/" + t + ": " + logMsg; break; case VERBOSE: logMsg = "V/" + t + ": " + logMsg; break; case TIP: logMsg = "T/" + t + ": " + logMsg; break; case WARN: logMsg = "W/" + t + ": " + logMsg; break; default: Log.d(t, logMsg); logMsg = "?/" + t + ": " + logMsg; break; } log(logMsg); } catch (IOException e) { e.printStackTrace(); } } public void a(String t, String logMsg) { log(ASSERT, t, logMsg); } public void t(String t, String logMsg) { log(TIP, t, logMsg); } public void v(String t, String logMsg) { log(VERBOSE, t, logMsg); } public void d(String t, String logMsg) { log(DEBUG, t, logMsg); } public void i(String t, String logMsg) { log(INFO, t, logMsg); } public void w(String t, String logMsg) { log(WARN, t, logMsg); } public void e(String t, String logMsg) { log(ERROR, t, logMsg); } public void printStackTrace(Throwable e) { e.printStackTrace(); ByteArrayOutputStream ba = new ByteArrayOutputStream(); PrintStream w; try { w = new PrintStream(ba, false, "UTF-8"); e.printStackTrace(w); w.flush(); w.close(); log(ba.toString("UTF-8")); } catch (UnsupportedEncodingException e1) { // error if it ever occurs throw new IllegalStateException("unable to specify UTF-8 Charset!"); } catch (IOException e1) { e1.printStackTrace(); } } public void s(String t, String logMsg) { log(SUCCESS, t, logMsg); } }
androidcommon/src/org/opendatakit/common/android/utilities/WebLogger.java
/* * Copyright (C) 2012-2013 University of Washington * * 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.opendatakit.common.android.utilities; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileFilter; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.Map; import org.apache.commons.lang3.CharEncoding; import org.opendatakit.common.android.utilities.StaticStateManipulator.IStaticFieldManipulator; import android.util.Log; /** * Logger that emits logs to the LOGGING_PATH and recycles them as needed. * Useful to separate out ODK log entries from the overall logging stream, * especially on heavily logged 4.x systems. * * @author mitchellsundt@gmail.com */ public class WebLogger { private static final long MILLISECONDS_DAY = 86400000L; private static final long FLUSH_INTERVAL = 12000L; // 5 times a minute private static final int ASSERT = 1; private static final int VERBOSE = 2; private static final int DEBUG = 3; private static final int INFO = 4; private static final int WARN = 5; private static final int ERROR = 6; private static final int SUCCESS = 7; private static final int TIP = 8; private static final int LOG_INFO_LEVEL = 1; private static long lastStaleScan = 0L; private static Map<String, WebLogger> loggers = new HashMap<String, WebLogger>(); static { // register a state-reset manipulator for 'loggers' field. StaticStateManipulator.get().register(99, new IStaticFieldManipulator() { @Override public void reset() { for ( WebLogger l : loggers.values() ) { l.close(); } loggers.clear(); } }); } /** * Instance variables */ // appName under which to write log private final String appName; // dateStamp (filename) of opened stream private String dateStamp = null; // opened stream private OutputStreamWriter logFile = null; // the last time we flushed our output stream private long lastFlush = 0L; private static class ThreadLogger extends ThreadLocal<String> { @Override protected String initialValue() { return null; } } private static ThreadLogger contextLogger = new ThreadLogger(); public static WebLogger getContextLogger() { String appNameOfThread = contextLogger.get(); if ( appNameOfThread != null ) { return getLogger(appNameOfThread); } return null; } public synchronized static WebLogger getLogger(String appName) { WebLogger logger = loggers.get(appName); if (logger == null) { logger = new WebLogger(appName); loggers.put(appName, logger); } contextLogger.set(appName); long now = System.currentTimeMillis(); if (lastStaleScan + MILLISECONDS_DAY < now) { try { // scan for stale logs... String loggingPath = ODKFileUtils.getLoggingFolder(appName); final long distantPast = now - 30L * MILLISECONDS_DAY; // thirty days // ago... File loggingDirectory = new File(loggingPath); loggingDirectory.mkdirs(); File[] stale = loggingDirectory.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return (pathname.lastModified() < distantPast); } }); if (stale != null) { for (File f : stale) { f.delete(); } } } catch (Exception e) { // no exceptions are claimed, but since we can mount/unmount // the SDCard, there might be an external storage unavailable // exception that would otherwise percolate up. e.printStackTrace(); } finally { // whether or not we failed, record that we did the scan. lastStaleScan = now; } } return logger; } private WebLogger(String appName) { this.appName = appName; } private synchronized void close() { if ( logFile != null ) { OutputStreamWriter writer = logFile; logFile = null; try { writer.flush(); writer.close(); } catch ( IOException e ) { Log.e("WebLogger", "Unable to flush and close " + appName + " WebLogger"); } } } private synchronized void log(String logMsg) throws IOException { String curDateStamp = (new SimpleDateFormat("yyyy-MM-dd_HH", Locale.ENGLISH)).format(new Date()); if ( logFile == null || dateStamp == null || !curDateStamp.equals(dateStamp) ) { // the file we should log to has changed. // or has not yet been opened. if ( logFile != null ) { // close existing writer... OutputStreamWriter writer = logFile; logFile = null; try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } String loggingPath = ODKFileUtils.getLoggingFolder(appName); File loggingDirectory = new File(loggingPath); if (!loggingDirectory.exists()) { if (!loggingDirectory.mkdirs()) { Log.e("WebLogger", "Unable to create logging directory"); return; } } if (!loggingDirectory.isDirectory()) { Log.e("WebLogger", "Logging Directory exists but is not a directory!"); return; } File f = new File(loggingDirectory, curDateStamp + ".log"); try { FileOutputStream fo = new FileOutputStream(f, true); logFile = new OutputStreamWriter(new BufferedOutputStream(fo), CharEncoding.UTF_8); dateStamp = curDateStamp; // if we see a lot of these being logged, we have a problem logFile.write("---- starting ----\n"); } catch (Exception e) { e.printStackTrace(); Log.e("WebLogger", "Unexpected exception while opening logging file: " + e.toString()); try { if ( logFile != null ) { logFile.close(); } } catch (Exception ex) { // ignore } logFile = null; return; } } if ( logFile != null ) { logFile.write(logMsg + "\n"); } if ( lastFlush + WebLogger.FLUSH_INTERVAL < System.currentTimeMillis() ) { // log when we are explicitly flushing, just to have a record of that in the log logFile.write("---- flushing ----\n"); logFile.flush(); lastFlush = System.currentTimeMillis(); } } public void log(int severity, String t, String logMsg) { try { // do logcat logging... if ( severity == ERROR ) { Log.e(t, logMsg); } else if ( severity == WARN ) { Log.w(t, logMsg); } else if ( LOG_INFO_LEVEL >= severity ) { Log.i(t, logMsg); } else { Log.d(t, logMsg); } // and compose the log to the file... switch (severity) { case ASSERT: logMsg = "A/" + t + ": " + logMsg; break; case DEBUG: logMsg = "D/" + t + ": " + logMsg; break; case ERROR: logMsg = "E/" + t + ": " + logMsg; break; case INFO: logMsg = "I/" + t + ": " + logMsg; break; case SUCCESS: logMsg = "S/" + t + ": " + logMsg; break; case VERBOSE: logMsg = "V/" + t + ": " + logMsg; break; case TIP: logMsg = "T/" + t + ": " + logMsg; break; case WARN: logMsg = "W/" + t + ": " + logMsg; break; default: Log.d(t, logMsg); logMsg = "?/" + t + ": " + logMsg; break; } log(logMsg); } catch (IOException e) { e.printStackTrace(); } } public void a(String t, String logMsg) { log(ASSERT, t, logMsg); } public void t(String t, String logMsg) { log(TIP, t, logMsg); } public void v(String t, String logMsg) { log(VERBOSE, t, logMsg); } public void d(String t, String logMsg) { log(DEBUG, t, logMsg); } public void i(String t, String logMsg) { log(INFO, t, logMsg); } public void w(String t, String logMsg) { log(WARN, t, logMsg); } public void e(String t, String logMsg) { log(ERROR, t, logMsg); } public void printStackTrace(Throwable e) { e.printStackTrace(); ByteArrayOutputStream ba = new ByteArrayOutputStream(); PrintStream w; try { w = new PrintStream(ba, false, "UTF-8"); e.printStackTrace(w); w.flush(); w.close(); log(ba.toString("UTF-8")); } catch (UnsupportedEncodingException e1) { // error if it ever occurs throw new IllegalStateException("unable to specify UTF-8 Charset!"); } catch (IOException e1) { e1.printStackTrace(); } } public void s(String t, String logMsg) { log(SUCCESS, t, logMsg); } }
Ensure the directory structures are created before logging (fixes a startup crash)
androidcommon/src/org/opendatakit/common/android/utilities/WebLogger.java
Ensure the directory structures are created before logging (fixes a startup crash)
Java
apache-2.0
b3998cdc52b15e225435807809f177be1aa4a63c
0
marverenic/Jockey,marverenic/Jockey
package com.marverenic.music.data.store; import android.content.Context; import android.support.annotation.Nullable; import com.marverenic.music.R; import com.marverenic.music.instances.AutoPlaylist; import com.marverenic.music.instances.Playlist; import com.marverenic.music.instances.Song; import java.util.ArrayList; import java.util.Collections; import java.util.List; import rx.Observable; import rx.subjects.BehaviorSubject; public class LocalPlaylistStore implements PlaylistStore { private Context mContext; private BehaviorSubject<List<Playlist>> mPlaylists; public LocalPlaylistStore(Context context) { mContext = context; } @Override public Observable<List<Playlist>> getPlaylists() { if (mPlaylists == null) { mPlaylists = BehaviorSubject.create(); MediaStoreUtil.getPermission(mContext).subscribe(granted -> { if (granted) { mPlaylists.onNext(getAllPlaylists()); } else { mPlaylists.onNext(Collections.emptyList()); } }); } return mPlaylists; } private List<Playlist> getAllPlaylists() { return MediaStoreUtil.getAllPlaylists(mContext); } @Override public Observable<List<Song>> getSongs(Playlist playlist) { return Observable.just(MediaStoreUtil.getPlaylistSongs(mContext, playlist)); } @Override public Observable<List<Playlist>> searchForPlaylists(String query) { return Observable.just(MediaStoreUtil.searchForPlaylists(mContext, query)); } @Override public String verifyPlaylistName(String playlistName) { if (playlistName == null || playlistName.trim().isEmpty()) { return mContext.getString(R.string.error_hint_empty_playlist); } if (MediaStoreUtil.findPlaylistByName(mContext, playlistName) != null) { return mContext.getString(R.string.error_hint_duplicate_playlist); } return null; } @Override public Playlist makePlaylist(String name) { return makePlaylist(name, null); } @Override public AutoPlaylist makePlaylist(AutoPlaylist model) { // TODO implement AutoPlaylists return null; } @Override public Playlist makePlaylist(String name, @Nullable List<Song> songs) { Playlist created = MediaStoreUtil.createPlaylist(mContext, name, songs); if (mPlaylists != null && mPlaylists.getValue() != null) { List<Playlist> updated = new ArrayList<>(mPlaylists.getValue()); updated.add(created); Collections.sort(updated); mPlaylists.onNext(updated); } return created; } @Override public void removePlaylist(Playlist playlist) { MediaStoreUtil.deletePlaylist(mContext, playlist); if (mPlaylists != null && mPlaylists.getValue() != null) { List<Playlist> updated = new ArrayList<>(mPlaylists.getValue()); updated.remove(playlist); mPlaylists.onNext(updated); } } @Override public void editPlaylist(Playlist playlist, List<Song> newSongs) { MediaStoreUtil.editPlaylist(mContext, playlist, newSongs); } @Override public void editPlaylist(AutoPlaylist replacementModel) { // TODO implement AutoPlaylists } @Override public void addToPlaylist(Playlist playlist, Song song) { MediaStoreUtil.appendToPlaylist(mContext, playlist, song); } @Override public void addToPlaylist(Playlist playlist, List<Song> songs) { MediaStoreUtil.appendToPlaylist(mContext, playlist, songs); } }
app/src/main/java/com/marverenic/music/data/store/LocalPlaylistStore.java
package com.marverenic.music.data.store; import android.content.Context; import android.support.annotation.Nullable; import com.jakewharton.rxrelay.BehaviorRelay; import com.marverenic.music.R; import com.marverenic.music.instances.AutoPlaylist; import com.marverenic.music.instances.Playlist; import com.marverenic.music.instances.Song; import java.util.ArrayList; import java.util.Collections; import java.util.List; import rx.Observable; public class LocalPlaylistStore implements PlaylistStore { private Context mContext; private BehaviorRelay<List<Playlist>> mPlaylists; public LocalPlaylistStore(Context context) { mContext = context; } @Override public Observable<List<Playlist>> getPlaylists() { if (mPlaylists == null) { mPlaylists = BehaviorRelay.create(); MediaStoreUtil.getPermission(mContext).map(granted -> { if (granted) { return MediaStoreUtil.getAllPlaylists(mContext); } else { return Collections.<Playlist>emptyList(); } }).subscribe(mPlaylists); } return mPlaylists; } @Override public Observable<List<Song>> getSongs(Playlist playlist) { return Observable.just(MediaStoreUtil.getPlaylistSongs(mContext, playlist)); } @Override public Observable<List<Playlist>> searchForPlaylists(String query) { return Observable.just(MediaStoreUtil.searchForPlaylists(mContext, query)); } @Override public String verifyPlaylistName(String playlistName) { if (playlistName == null || playlistName.trim().isEmpty()) { return mContext.getString(R.string.error_hint_empty_playlist); } if (MediaStoreUtil.findPlaylistByName(mContext, playlistName) != null) { return mContext.getString(R.string.error_hint_duplicate_playlist); } return null; } @Override public Playlist makePlaylist(String name) { return makePlaylist(name, null); } @Override public AutoPlaylist makePlaylist(AutoPlaylist model) { // TODO implement AutoPlaylists return null; } @Override public Playlist makePlaylist(String name, @Nullable List<Song> songs) { Playlist created = MediaStoreUtil.createPlaylist(mContext, name, songs); if (mPlaylists != null && mPlaylists.getValue() != null) { List<Playlist> updated = new ArrayList<>(mPlaylists.getValue()); updated.add(created); Collections.sort(updated); mPlaylists.call(updated); } return created; } @Override public void removePlaylist(Playlist playlist) { MediaStoreUtil.deletePlaylist(mContext, playlist); if (mPlaylists != null && mPlaylists.getValue() != null) { List<Playlist> updated = new ArrayList<>(mPlaylists.getValue()); updated.remove(playlist); mPlaylists.call(updated); } } @Override public void editPlaylist(Playlist playlist, List<Song> newSongs) { MediaStoreUtil.editPlaylist(mContext, playlist, newSongs); } @Override public void editPlaylist(AutoPlaylist replacementModel) { // TODO implement AutoPlaylists } @Override public void addToPlaylist(Playlist playlist, Song song) { MediaStoreUtil.appendToPlaylist(mContext, playlist, song); } @Override public void addToPlaylist(Playlist playlist, List<Song> songs) { MediaStoreUtil.appendToPlaylist(mContext, playlist, songs); } }
Use a BehaviorSubject instead of a BehaviorRelay
app/src/main/java/com/marverenic/music/data/store/LocalPlaylistStore.java
Use a BehaviorSubject instead of a BehaviorRelay
Java
apache-2.0
00f2bdb852a7e0ded29494b909f0c65d1c7c7dc8
0
facebook/litho,facebook/litho,facebook/litho,facebook/litho,facebook/litho,facebook/litho
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.litho.widget; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PixelFormat; import android.graphics.RadialGradient; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Shader; import android.graphics.drawable.Drawable; public class CardShadowDrawable extends Drawable { static final float SHADOW_MULTIPLIER = 1.5f; private int mShadowStartColor; private int mShadowEndColor; private final Paint mEdgeShadowPaint; private final Path mCornerShadowTopPath = new Path(); private final Path mCornerShadowBottomPath = new Path(); private final Paint mCornerShadowPaint; private float mCornerRadius; private float mShadowSize; private float mRawShadowSize; private boolean mHideTopShadow; private boolean mHideBottomShadow; private boolean mDirty = true; CardShadowDrawable() { mCornerShadowPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG); mCornerShadowPaint.setStyle(Paint.Style.FILL); mEdgeShadowPaint = new Paint(mCornerShadowPaint); mEdgeShadowPaint.setAntiAlias(false); } @Override public void setAlpha(int alpha) { mCornerShadowPaint.setAlpha(alpha); mEdgeShadowPaint.setAlpha(alpha); } public static int getShadowHorizontal(float shadowSize) { return (int) Math.ceil(toEven(shadowSize)); } public static int getShadowTop(float shadowSize) { return (int) Math.ceil(toEven(shadowSize) / 2); } public static int getShadowRight(float shadowSize) { return (int) Math.ceil(toEven(shadowSize)); } public static int getShadowBottom(float shadowSize) { return (int) Math.ceil(toEven(shadowSize) * SHADOW_MULTIPLIER); } @Override public void setColorFilter(ColorFilter cf) { mCornerShadowPaint.setColorFilter(cf); mEdgeShadowPaint.setColorFilter(cf); } @Override public int getOpacity() { return PixelFormat.TRANSLUCENT; } @Override public void draw(Canvas canvas) { if (mDirty) { buildShadow(); mDirty = false; } final Rect bounds = getBounds(); drawShadowCorners(canvas, bounds); drawShadowEdges(canvas, bounds); } void setShadowStartColor(int shadowStartColor) { if (mShadowStartColor == shadowStartColor) { return; } mShadowStartColor = shadowStartColor; mDirty = true; invalidateSelf(); } void setShadowEndColor(int shadowEndColor) { if (mShadowEndColor == shadowEndColor) { return; } mShadowEndColor = shadowEndColor; mDirty = true; invalidateSelf(); } void setCornerRadius(float radius) { radius = (int) (radius + .5f); if (mCornerRadius == radius) { return; } mCornerRadius = radius; mDirty = true; invalidateSelf(); } void setShadowSize(float shadowSize) { if (shadowSize < 0) { throw new IllegalArgumentException("invalid shadow size"); } shadowSize = toEven(shadowSize); if (mRawShadowSize == shadowSize) { return; } mRawShadowSize = shadowSize; mShadowSize = (int) (shadowSize * SHADOW_MULTIPLIER + .5f); mDirty = true; invalidateSelf(); } void setHideTopShadow(boolean hideTopShadow) { mHideTopShadow = hideTopShadow; } void setHideBottomShadow(boolean hideBottomShadow) { mHideBottomShadow = hideBottomShadow; } private void buildShadow() { final int shadowHorizontal = getShadowHorizontal(mRawShadowSize); final int shadowTop = getShadowTop(mRawShadowSize); final int shadowBottom = getShadowBottom(mRawShadowSize); final float shadowCornerRadius = shadowHorizontal + mCornerRadius; mCornerShadowPaint.setShader( new RadialGradient( shadowCornerRadius, shadowCornerRadius, shadowCornerRadius, new int[] {mShadowStartColor, mShadowStartColor, mShadowEndColor}, new float[] {0f, .2f, 1f}, Shader.TileMode.CLAMP)); final RectF topInnerBounds = new RectF( shadowHorizontal, shadowTop, shadowHorizontal + 2 * mCornerRadius, shadowTop + 2 * mCornerRadius); final RectF topOuterBounds = new RectF(0, 0, 2 * mCornerRadius, 2 * mCornerRadius); mCornerShadowTopPath.reset(); mCornerShadowTopPath.setFillType(Path.FillType.EVEN_ODD); mCornerShadowTopPath.moveTo(shadowHorizontal + mCornerRadius, shadowTop); mCornerShadowTopPath.arcTo(topInnerBounds, 270f, -90f, true); mCornerShadowTopPath.rLineTo(-shadowHorizontal, 0); mCornerShadowTopPath.lineTo(0, mCornerRadius); mCornerShadowTopPath.arcTo(topOuterBounds, 180f, 90f, true); mCornerShadowTopPath.lineTo(shadowHorizontal + mCornerRadius, 0); mCornerShadowTopPath.rLineTo(0, shadowTop); mCornerShadowTopPath.close(); final RectF bottomInnerBounds = new RectF( getShadowHorizontal(mRawShadowSize), getShadowBottom(mRawShadowSize), getShadowHorizontal(mRawShadowSize) + 2 * mCornerRadius, getShadowBottom(mRawShadowSize) + 2 * mCornerRadius); final RectF bottomOuterBounds = new RectF(0, 0, 2 * mCornerRadius, 2 * mCornerRadius); mCornerShadowBottomPath.reset(); mCornerShadowBottomPath.setFillType(Path.FillType.EVEN_ODD); mCornerShadowBottomPath.moveTo(shadowHorizontal + mCornerRadius, shadowBottom); mCornerShadowBottomPath.arcTo(bottomInnerBounds, 270f, -90f, true); mCornerShadowBottomPath.rLineTo(-shadowHorizontal, 0); mCornerShadowBottomPath.lineTo(0, mCornerRadius); mCornerShadowBottomPath.arcTo(bottomOuterBounds, 180f, 90f, true); mCornerShadowBottomPath.lineTo(shadowHorizontal + mCornerRadius, 0); mCornerShadowBottomPath.rLineTo(0, shadowBottom); mCornerShadowBottomPath.close(); // We offset the content (shadowSize / 2) pixels up to make it more realistic. // This is why edge shadow shader has some extra space. When drawing bottom edge // shadow, we use that extra space. mEdgeShadowPaint.setShader( new LinearGradient( 0, shadowCornerRadius, 0, 0, new int[] {mShadowStartColor, mShadowStartColor, mShadowEndColor}, new float[] {0f, .2f, 1f}, Shader.TileMode.CLAMP)); mEdgeShadowPaint.setAntiAlias(false); } private void drawShadowCorners(Canvas canvas, Rect bounds) { int saved = canvas.save(); if (!mHideTopShadow) { // left-top canvas.translate(bounds.left, bounds.top); canvas.drawPath(mCornerShadowTopPath, mCornerShadowPaint); canvas.restoreToCount(saved); // right-top saved = canvas.save(); canvas.translate(bounds.right, bounds.top); canvas.scale(-1f, 1f); canvas.drawPath(mCornerShadowTopPath, mCornerShadowPaint); canvas.restoreToCount(saved); } if (!mHideBottomShadow) { // right-bottom saved = canvas.save(); canvas.translate(bounds.right, bounds.bottom); canvas.scale(-1f, -1f); canvas.drawPath(mCornerShadowBottomPath, mCornerShadowPaint); canvas.restoreToCount(saved); // left-bottom saved = canvas.save(); canvas.translate(bounds.left, bounds.bottom); canvas.scale(1f, -1f); canvas.drawPath(mCornerShadowBottomPath, mCornerShadowPaint); canvas.restoreToCount(saved); } } private void drawShadowEdges(Canvas canvas, Rect bounds) { final int paddingLeft = getShadowHorizontal(mRawShadowSize); final int paddingTop = getShadowTop(mRawShadowSize); final int paddingRight = getShadowRight(mRawShadowSize); final int paddingBottom = getShadowBottom(mRawShadowSize); int saved = canvas.save(); if (!mHideTopShadow) { // top canvas.translate(bounds.left, bounds.top); canvas.drawRect( paddingLeft + mCornerRadius, 0, bounds.width() - mCornerRadius - paddingRight, paddingTop, mEdgeShadowPaint); canvas.restoreToCount(saved); } if (!mHideBottomShadow) { // bottom saved = canvas.save(); canvas.translate(bounds.right, bounds.bottom); canvas.rotate(180f); canvas.drawRect( paddingRight + mCornerRadius, 0, bounds.width() - mCornerRadius - paddingLeft, paddingBottom, mEdgeShadowPaint); canvas.restoreToCount(saved); } // left saved = canvas.save(); canvas.translate(bounds.left, bounds.bottom); canvas.rotate(270f); canvas.drawRect( mHideBottomShadow ? 0 : (paddingBottom + mCornerRadius), 0, bounds.height() - (mHideTopShadow ? 0 : mCornerRadius + paddingTop), paddingLeft, mEdgeShadowPaint); canvas.restoreToCount(saved); // right saved = canvas.save(); canvas.translate(bounds.right, bounds.top); canvas.rotate(90f); canvas.drawRect( mHideTopShadow ? 0 : (paddingTop + mCornerRadius), 0, bounds.height() - (mHideBottomShadow ? 0 : mCornerRadius + paddingBottom), paddingRight, mEdgeShadowPaint); canvas.restoreToCount(saved); } private static int toEven(float value) { final int i = (int) (value + .5f); if (i % 2 == 1) { return i - 1; } return i; } }
litho-widget/src/main/java/com/facebook/litho/widget/CardShadowDrawable.java
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.litho.widget; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PixelFormat; import android.graphics.RadialGradient; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Shader; import android.graphics.drawable.Drawable; public class CardShadowDrawable extends Drawable { static final float SHADOW_MULTIPLIER = 1.5f; private int mShadowStartColor; private int mShadowEndColor; private final Paint mEdgeShadowPaint; private final Path mCornerShadowTopPath = new Path(); private final Path mCornerShadowBottomPath = new Path(); private final Paint mCornerShadowPaint; private float mCornerRadius; private float mShadowSize; private float mRawShadowSize; private boolean mHideTopShadow; private boolean mHideBottomShadow; private boolean mDirty = true; CardShadowDrawable() { mCornerShadowPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG); mCornerShadowPaint.setStyle(Paint.Style.FILL); mEdgeShadowPaint = new Paint(mCornerShadowPaint); mEdgeShadowPaint.setAntiAlias(false); } @Override public void setAlpha(int alpha) { mCornerShadowPaint.setAlpha(alpha); mEdgeShadowPaint.setAlpha(alpha); } public static int getShadowHorizontal(float shadowSize) { return (int) Math.ceil(shadowSize); } public static int getShadowTop(float shadowSize) { return (int) Math.ceil(shadowSize / 2); } public static int getShadowRight(float shadowSize) { return (int) Math.ceil(shadowSize); } public static int getShadowBottom(float shadowSize) { return (int) Math.ceil(shadowSize * SHADOW_MULTIPLIER); } @Override public void setColorFilter(ColorFilter cf) { mCornerShadowPaint.setColorFilter(cf); mEdgeShadowPaint.setColorFilter(cf); } @Override public int getOpacity() { return PixelFormat.TRANSLUCENT; } @Override public void draw(Canvas canvas) { if (mDirty) { buildShadow(); mDirty = false; } final Rect bounds = getBounds(); drawShadowCorners(canvas, bounds); drawShadowEdges(canvas, bounds); } void setShadowStartColor(int shadowStartColor) { if (mShadowStartColor == shadowStartColor) { return; } mShadowStartColor = shadowStartColor; mDirty = true; invalidateSelf(); } void setShadowEndColor(int shadowEndColor) { if (mShadowEndColor == shadowEndColor) { return; } mShadowEndColor = shadowEndColor; mDirty = true; invalidateSelf(); } void setCornerRadius(float radius) { radius = (int) (radius + .5f); if (mCornerRadius == radius) { return; } mCornerRadius = radius; mDirty = true; invalidateSelf(); } void setShadowSize(float shadowSize) { if (shadowSize < 0) { throw new IllegalArgumentException("invalid shadow size"); } shadowSize = toEven(shadowSize); if (mRawShadowSize == shadowSize) { return; } mRawShadowSize = shadowSize; mShadowSize = (int) (shadowSize * SHADOW_MULTIPLIER + .5f); mDirty = true; invalidateSelf(); } void setHideTopShadow(boolean hideTopShadow) { mHideTopShadow = hideTopShadow; } void setHideBottomShadow(boolean hideBottomShadow) { mHideBottomShadow = hideBottomShadow; } private void buildShadow() { final int shadowHorizontal = getShadowHorizontal(mRawShadowSize); final int shadowTop = getShadowTop(mRawShadowSize); final int shadowBottom = getShadowBottom(mRawShadowSize); final float shadowCornerRadius = shadowHorizontal + mCornerRadius; mCornerShadowPaint.setShader( new RadialGradient( shadowCornerRadius, shadowCornerRadius, shadowCornerRadius, new int[] {mShadowStartColor, mShadowStartColor, mShadowEndColor}, new float[] {0f, .2f, 1f}, Shader.TileMode.CLAMP)); final RectF topInnerBounds = new RectF( shadowHorizontal, shadowTop, shadowHorizontal + 2 * mCornerRadius, shadowTop + 2 * mCornerRadius); final RectF topOuterBounds = new RectF(0, 0, 2 * mCornerRadius, 2 * mCornerRadius); mCornerShadowTopPath.reset(); mCornerShadowTopPath.setFillType(Path.FillType.EVEN_ODD); mCornerShadowTopPath.moveTo(shadowHorizontal + mCornerRadius, shadowTop); mCornerShadowTopPath.arcTo(topInnerBounds, 270f, -90f, true); mCornerShadowTopPath.rLineTo(-shadowHorizontal, 0); mCornerShadowTopPath.lineTo(0, mCornerRadius); mCornerShadowTopPath.arcTo(topOuterBounds, 180f, 90f, true); mCornerShadowTopPath.lineTo(shadowHorizontal + mCornerRadius, 0); mCornerShadowTopPath.rLineTo(0, shadowTop); mCornerShadowTopPath.close(); final RectF bottomInnerBounds = new RectF( getShadowHorizontal(mRawShadowSize), getShadowBottom(mRawShadowSize), getShadowHorizontal(mRawShadowSize) + 2 * mCornerRadius, getShadowBottom(mRawShadowSize) + 2 * mCornerRadius); final RectF bottomOuterBounds = new RectF(0, 0, 2 * mCornerRadius, 2 * mCornerRadius); mCornerShadowBottomPath.reset(); mCornerShadowBottomPath.setFillType(Path.FillType.EVEN_ODD); mCornerShadowBottomPath.moveTo(shadowHorizontal + mCornerRadius, shadowBottom); mCornerShadowBottomPath.arcTo(bottomInnerBounds, 270f, -90f, true); mCornerShadowBottomPath.rLineTo(-shadowHorizontal, 0); mCornerShadowBottomPath.lineTo(0, mCornerRadius); mCornerShadowBottomPath.arcTo(bottomOuterBounds, 180f, 90f, true); mCornerShadowBottomPath.lineTo(shadowHorizontal + mCornerRadius, 0); mCornerShadowBottomPath.rLineTo(0, shadowBottom); mCornerShadowBottomPath.close(); // We offset the content (shadowSize / 2) pixels up to make it more realistic. // This is why edge shadow shader has some extra space. When drawing bottom edge // shadow, we use that extra space. mEdgeShadowPaint.setShader( new LinearGradient( 0, shadowCornerRadius, 0, 0, new int[] {mShadowStartColor, mShadowStartColor, mShadowEndColor}, new float[] {0f, .2f, 1f}, Shader.TileMode.CLAMP)); mEdgeShadowPaint.setAntiAlias(false); } private void drawShadowCorners(Canvas canvas, Rect bounds) { int saved = canvas.save(); if (!mHideTopShadow) { // left-top canvas.translate(bounds.left, bounds.top); canvas.drawPath(mCornerShadowTopPath, mCornerShadowPaint); canvas.restoreToCount(saved); // right-top saved = canvas.save(); canvas.translate(bounds.right, bounds.top); canvas.scale(-1f, 1f); canvas.drawPath(mCornerShadowTopPath, mCornerShadowPaint); canvas.restoreToCount(saved); } if (!mHideBottomShadow) { // right-bottom saved = canvas.save(); canvas.translate(bounds.right, bounds.bottom); canvas.scale(-1f, -1f); canvas.drawPath(mCornerShadowBottomPath, mCornerShadowPaint); canvas.restoreToCount(saved); // left-bottom saved = canvas.save(); canvas.translate(bounds.left, bounds.bottom); canvas.scale(1f, -1f); canvas.drawPath(mCornerShadowBottomPath, mCornerShadowPaint); canvas.restoreToCount(saved); } } private void drawShadowEdges(Canvas canvas, Rect bounds) { final int paddingLeft = getShadowHorizontal(mRawShadowSize); final int paddingTop = getShadowTop(mRawShadowSize); final int paddingRight = getShadowRight(mRawShadowSize); final int paddingBottom = getShadowBottom(mRawShadowSize); int saved = canvas.save(); if (!mHideTopShadow) { // top canvas.translate(bounds.left, bounds.top); canvas.drawRect( paddingLeft + mCornerRadius, 0, bounds.width() - mCornerRadius - paddingRight, paddingTop, mEdgeShadowPaint); canvas.restoreToCount(saved); } if (!mHideBottomShadow) { // bottom saved = canvas.save(); canvas.translate(bounds.right, bounds.bottom); canvas.rotate(180f); canvas.drawRect( paddingRight + mCornerRadius, 0, bounds.width() - mCornerRadius - paddingLeft, paddingBottom, mEdgeShadowPaint); canvas.restoreToCount(saved); } // left saved = canvas.save(); canvas.translate(bounds.left, bounds.bottom); canvas.rotate(270f); canvas.drawRect( mHideBottomShadow ? 0 : (paddingBottom + mCornerRadius), 0, bounds.height() - (mHideTopShadow ? 0 : mCornerRadius + paddingTop), paddingLeft, mEdgeShadowPaint); canvas.restoreToCount(saved); // right saved = canvas.save(); canvas.translate(bounds.right, bounds.top); canvas.rotate(90f); canvas.drawRect( mHideTopShadow ? 0 : (paddingTop + mCornerRadius), 0, bounds.height() - (mHideBottomShadow ? 0 : mCornerRadius + paddingBottom), paddingRight, mEdgeShadowPaint); canvas.restoreToCount(saved); } private static int toEven(float value) { final int i = (int) (value + .5f); if (i % 2 == 1) { return i - 1; } return i; } }
Remove white space between content and shadows Summary: On some devices, we were seeing white space at the bottom and right sides of CardSpecs that have white clipping colors and non-white backgrounds in the card's content. The cause for this is that the shadow and clipping calculations are sometimes based off of different shadow sizes. - CardSpec takes in an `elevation` prop, and calculates the shadow sizes to pass into CardClipSpec directly from the shadow calculation static methods (such as `getShadowBottom()`). - However, a different shadow size is being saved in CardShadowDrawable. CardSpec passes its `elevation` to CardShadowSpec, which passes it to CardShadowDrawable. But CardShadowDrawable rounds the shadow size to the nearest even integer before saving it (https://fburl.com/diffusion/455ktwek). This means that if the `elevation` value is not even, the shadow sizes used by the clipping and shadow components will be different. This diff changes the static method used by card clipping to be the same as the shadow calculation. Concrete example: - On Pixel: CardSpec's elevation is 11px, CardShadowDrawable's is 10px. The white space appears. - On Pixel 2 XL: CardSpec's elevation is 14px, CardShadowDrawable's is 14px. The white space does not appear. ----- I suspect this bug wasn't noticed/prioritized before because most CardSpecs have a white content background, so the white space at the bottom is not differentiable. ----- Here is how the CardSpec previously looked on the Pixel device. You can see white space at the bottom and sides of the card: | Solid non-white content background | Image as content background | White content background (no issues) | | https://pxl.cl/10kZq | https://pxl.cl/10kZt | https://pxl.cl/10kZv | ----- See T58728684 for more details. Reviewed By: astreet Differential Revision: D19867346 fbshipit-source-id: e22c3c35895d5a0605d9bf25a676e017502614be
litho-widget/src/main/java/com/facebook/litho/widget/CardShadowDrawable.java
Remove white space between content and shadows
Java
apache-2.0
50583ea46695692bb6d8437037397a111e036fac
0
sbrossie/killbill,killbill/killbill,killbill/killbill,marksimu/killbill,sbrossie/killbill,marksimu/killbill,marksimu/killbill,killbill/killbill,killbill/killbill,andrenpaes/killbill,killbill/killbill,andrenpaes/killbill,andrenpaes/killbill,andrenpaes/killbill,sbrossie/killbill,sbrossie/killbill,sbrossie/killbill,marksimu/killbill,andrenpaes/killbill,marksimu/killbill
/* * Copyright 2010-2013 Ning, Inc. * Copyright 2014-2016 Groupon, Inc * Copyright 2014-2016 The Billing Project, LLC * * The Billing 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 org.killbill.billing.payment.api; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.UUID; import javax.annotation.Nullable; import org.joda.time.LocalDate; import org.killbill.billing.ErrorCode; import org.killbill.billing.account.api.Account; import org.killbill.billing.catalog.api.Currency; import org.killbill.billing.control.plugin.api.PaymentControlApiException; import org.killbill.billing.invoice.api.Invoice; import org.killbill.billing.invoice.api.InvoiceApiException; import org.killbill.billing.invoice.api.InvoiceItem; import org.killbill.billing.osgi.api.OSGIServiceDescriptor; import org.killbill.billing.payment.MockRecurringInvoiceItem; import org.killbill.billing.payment.PaymentTestSuiteWithEmbeddedDB; import org.killbill.billing.payment.dao.PaymentAttemptModelDao; import org.killbill.billing.payment.dao.PaymentSqlDao; import org.killbill.billing.payment.invoice.InvoicePaymentControlPluginApi; import org.killbill.billing.payment.plugin.api.PaymentPluginApiException; import org.killbill.billing.payment.plugin.api.PaymentPluginStatus; import org.killbill.billing.payment.provider.ExternalPaymentProviderPlugin; import org.killbill.billing.payment.provider.MockPaymentControlProviderPlugin; import org.killbill.billing.payment.provider.MockPaymentProviderPlugin; import org.killbill.billing.util.entity.Pagination; import org.killbill.bus.api.PersistentBus.EventBusException; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.google.common.collect.ImmutableList; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; public class TestPaymentApi extends PaymentTestSuiteWithEmbeddedDB { private MockPaymentProviderPlugin mockPaymentProviderPlugin; private MockPaymentControlProviderPlugin mockPaymentControlProviderPlugin; final PaymentOptions INVOICE_PAYMENT = new PaymentOptions() { @Override public boolean isExternalPayment() { return false; } @Override public List<String> getPaymentControlPluginNames() { return ImmutableList.<String>of(InvoicePaymentControlPluginApi.PLUGIN_NAME); } }; final PaymentOptions CONTROL_PLUGIN_OPTIONS = new PaymentOptions() { @Override public boolean isExternalPayment() { return true; } @Override public List<String> getPaymentControlPluginNames() { return Arrays.asList(MockPaymentControlProviderPlugin.PLUGIN_NAME); } }; private Account account; @BeforeClass(groups = "slow") protected void beforeClass() throws Exception { super.beforeClass(); mockPaymentProviderPlugin = (MockPaymentProviderPlugin) registry.getServiceForName(MockPaymentProviderPlugin.PLUGIN_NAME); } @BeforeMethod(groups = "slow") public void beforeMethod() throws Exception { super.beforeMethod(); mockPaymentProviderPlugin.clear(); account = testHelper.createTestAccount("bobo@gmail.com", true); mockPaymentControlProviderPlugin = new MockPaymentControlProviderPlugin(); controlPluginRegistry.registerService(new OSGIServiceDescriptor() { @Override public String getPluginSymbolicName() { return null; } @Override public String getPluginName() { return MockPaymentControlProviderPlugin.PLUGIN_NAME; } @Override public String getRegistrationName() { return MockPaymentControlProviderPlugin.PLUGIN_NAME; } }, mockPaymentControlProviderPlugin); } @Test(groups = "slow") public void testUniqueExternalPaymentMethod() throws PaymentApiException { paymentApi.addPaymentMethod(account, "thisonewillwork", ExternalPaymentProviderPlugin.PLUGIN_NAME, true, null, ImmutableList.<PluginProperty>of(), callContext); try { paymentApi.addPaymentMethod(account, "thisonewillnotwork", ExternalPaymentProviderPlugin.PLUGIN_NAME, true, null, ImmutableList.<PluginProperty>of(), callContext); } catch (PaymentApiException e) { assertEquals(e.getCode(), ErrorCode.PAYMENT_EXTERNAL_PAYMENT_METHOD_ALREADY_EXISTS.getCode()); } } @Test(groups = "slow") public void testAddRemovePaymentMethod() throws Exception { final Long baseNbRecords = paymentApi.getPaymentMethods(0L, 1000L, false, ImmutableList.<PluginProperty>of(), callContext).getMaxNbRecords(); Assert.assertEquals(baseNbRecords, (Long) 1L); final Account account = testHelper.createTestAccount(UUID.randomUUID().toString(), true); final UUID paymentMethodId = account.getPaymentMethodId(); checkPaymentMethodPagination(paymentMethodId, baseNbRecords + 1, false); paymentApi.deletePaymentMethod(account, paymentMethodId, true, ImmutableList.<PluginProperty>of(), callContext); checkPaymentMethodPagination(paymentMethodId, baseNbRecords, true); } @Test(groups = "slow") public void testCreateSuccessPurchase() throws PaymentApiException { final BigDecimal requestedAmount = BigDecimal.TEN; final String paymentExternalKey = "bwwrr"; final String transactionExternalKey = "krapaut"; final Payment payment = paymentApi.createPurchase(account, account.getPaymentMethodId(), null, requestedAmount, Currency.AED, paymentExternalKey, transactionExternalKey, ImmutableList.<PluginProperty>of(), callContext); assertEquals(payment.getExternalKey(), paymentExternalKey); assertEquals(payment.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment.getAccountId(), account.getId()); assertEquals(payment.getAuthAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getPurchasedAmount().compareTo(requestedAmount), 0); assertEquals(payment.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCurrency(), Currency.AED); assertEquals(payment.getTransactions().size(), 1); assertEquals(payment.getTransactions().get(0).getExternalKey(), transactionExternalKey); assertEquals(payment.getTransactions().get(0).getPaymentId(), payment.getId()); assertEquals(payment.getTransactions().get(0).getAmount().compareTo(requestedAmount), 0); assertEquals(payment.getTransactions().get(0).getCurrency(), Currency.AED); assertEquals(payment.getTransactions().get(0).getProcessedAmount().compareTo(requestedAmount), 0); assertEquals(payment.getTransactions().get(0).getProcessedCurrency(), Currency.AED); assertEquals(payment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment.getTransactions().get(0).getTransactionType(), TransactionType.PURCHASE); assertNotNull(payment.getTransactions().get(0).getGatewayErrorMsg()); assertNotNull(payment.getTransactions().get(0).getGatewayErrorCode()); } @Test(groups = "slow") public void testCreateFailedPurchase() throws PaymentApiException { final BigDecimal requestedAmount = BigDecimal.TEN; final String paymentExternalKey = "ohhhh"; final String transactionExternalKey = "naaahhh"; mockPaymentProviderPlugin.makeNextPaymentFailWithError(); final Payment payment = paymentApi.createPurchase(account, account.getPaymentMethodId(), null, requestedAmount, Currency.AED, paymentExternalKey, transactionExternalKey, ImmutableList.<PluginProperty>of(), callContext); assertEquals(payment.getExternalKey(), paymentExternalKey); assertEquals(payment.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment.getAccountId(), account.getId()); assertEquals(payment.getAuthAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCurrency(), Currency.AED); assertEquals(payment.getTransactions().size(), 1); assertEquals(payment.getTransactions().get(0).getExternalKey(), transactionExternalKey); assertEquals(payment.getTransactions().get(0).getPaymentId(), payment.getId()); assertEquals(payment.getTransactions().get(0).getAmount().compareTo(requestedAmount), 0); assertEquals(payment.getTransactions().get(0).getCurrency(), Currency.AED); assertEquals(payment.getTransactions().get(0).getProcessedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getTransactions().get(0).getProcessedCurrency(), Currency.AED); assertEquals(payment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.PAYMENT_FAILURE); assertEquals(payment.getTransactions().get(0).getTransactionType(), TransactionType.PURCHASE); assertNotNull(payment.getTransactions().get(0).getGatewayErrorMsg()); assertNotNull(payment.getTransactions().get(0).getGatewayErrorCode()); final Payment payment2 = paymentApi.createPurchase(account, account.getPaymentMethodId(), null, requestedAmount, Currency.AED, paymentExternalKey, transactionExternalKey, ImmutableList.<PluginProperty>of(), callContext); assertEquals(payment2.getExternalKey(), paymentExternalKey); assertEquals(payment2.getTransactions().get(0).getExternalKey(), transactionExternalKey); assertEquals(payment2.getTransactions().get(0).getTransactionStatus(), TransactionStatus.PAYMENT_FAILURE); assertEquals(payment2.getTransactions().get(0).getTransactionType(), TransactionType.PURCHASE); assertEquals(payment2.getTransactions().get(1).getExternalKey(), transactionExternalKey); assertEquals(payment2.getTransactions().get(1).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment2.getTransactions().get(1).getTransactionType(), TransactionType.PURCHASE); } @Test(groups = "slow") public void testCreateCancelledPurchase() throws PaymentApiException { final BigDecimal requestedAmount = BigDecimal.TEN; final String paymentExternalKey = "hgh3"; final String transactionExternalKey = "hgh3sss"; mockPaymentProviderPlugin.makeNextPaymentFailWithCancellation(); final Payment payment = paymentApi.createPurchase(account, account.getPaymentMethodId(), null, requestedAmount, Currency.AED, paymentExternalKey, transactionExternalKey, ImmutableList.<PluginProperty>of(), callContext); assertEquals(payment.getExternalKey(), paymentExternalKey); assertEquals(payment.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment.getAccountId(), account.getId()); assertEquals(payment.getAuthAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCurrency(), Currency.AED); assertEquals(payment.getTransactions().size(), 1); assertEquals(payment.getTransactions().get(0).getExternalKey(), transactionExternalKey); assertEquals(payment.getTransactions().get(0).getPaymentId(), payment.getId()); assertEquals(payment.getTransactions().get(0).getAmount().compareTo(requestedAmount), 0); assertEquals(payment.getTransactions().get(0).getCurrency(), Currency.AED); assertEquals(payment.getTransactions().get(0).getProcessedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getTransactions().get(0).getProcessedCurrency(), Currency.AED); assertEquals(payment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.PLUGIN_FAILURE); assertEquals(payment.getTransactions().get(0).getTransactionType(), TransactionType.PURCHASE); assertNotNull(payment.getTransactions().get(0).getGatewayErrorMsg()); assertNotNull(payment.getTransactions().get(0).getGatewayErrorCode()); final Payment payment2 = paymentApi.createPurchase(account, account.getPaymentMethodId(), null, requestedAmount, Currency.AED, paymentExternalKey, transactionExternalKey, ImmutableList.<PluginProperty>of(), callContext); assertEquals(payment2.getExternalKey(), paymentExternalKey); assertEquals(payment2.getTransactions().get(0).getExternalKey(), transactionExternalKey); assertEquals(payment2.getTransactions().get(0).getTransactionStatus(), TransactionStatus.PLUGIN_FAILURE); assertEquals(payment2.getTransactions().get(0).getTransactionType(), TransactionType.PURCHASE); assertEquals(payment2.getTransactions().get(1).getExternalKey(), transactionExternalKey); assertEquals(payment2.getTransactions().get(1).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment2.getTransactions().get(1).getTransactionType(), TransactionType.PURCHASE); } @Test(groups = "slow") public void testCreatePurchasePaymentPluginException() { mockPaymentProviderPlugin.makeNextPaymentFailWithException(); final BigDecimal requestedAmount = BigDecimal.TEN; final String paymentExternalKey = "pay external key"; final String transactionExternalKey = "txn external key"; try { paymentApi.createPurchase(account, account.getPaymentMethodId(), null, requestedAmount, Currency.AED, paymentExternalKey, transactionExternalKey, ImmutableList.<PluginProperty>of(), callContext); fail(); } catch (PaymentApiException e) { assertTrue(e.getCause() instanceof PaymentPluginApiException); } } @Test(groups = "slow") public void testCreatePurchaseWithControlPaymentPluginException() throws Exception { mockPaymentProviderPlugin.makeNextPaymentFailWithException(); final BigDecimal requestedAmount = BigDecimal.TEN; final String paymentExternalKey = "pay controle external key";; final String transactionExternalKey = "txn control external key"; try { paymentApi.createPurchaseWithPaymentControl( account, account.getPaymentMethodId(), null, requestedAmount, Currency.AED, paymentExternalKey, transactionExternalKey, ImmutableList.<PluginProperty>of(), CONTROL_PLUGIN_OPTIONS, callContext); fail(); } catch (PaymentApiException e) { assertTrue(e.getCause() instanceof PaymentPluginApiException); } } @Test(groups = "slow") public void testCreatePurchaseWithControlPluginException() throws Exception { mockPaymentControlProviderPlugin.throwsException(new PaymentControlApiException()); final BigDecimal requestedAmount = BigDecimal.TEN; final String paymentExternalKey = "pay controle external key";; final String transactionExternalKey = "txn control external key"; try { paymentApi.createPurchaseWithPaymentControl( account, account.getPaymentMethodId(), null, requestedAmount, Currency.AED, paymentExternalKey, transactionExternalKey, ImmutableList.<PluginProperty>of(), CONTROL_PLUGIN_OPTIONS, callContext); fail(); } catch (PaymentApiException e) { assertTrue(e.getCause() instanceof PaymentControlApiException); } } @Test(groups = "slow") public void testCreatePurchaseWithControlPluginRuntimeException() throws Exception { mockPaymentControlProviderPlugin.throwsException(new IllegalStateException()); final BigDecimal requestedAmount = BigDecimal.TEN; final String paymentExternalKey = "pay controle external key";; final String transactionExternalKey = "txn control external key"; try { paymentApi.createPurchaseWithPaymentControl( account, account.getPaymentMethodId(), null, requestedAmount, Currency.AED, paymentExternalKey, transactionExternalKey, ImmutableList.<PluginProperty>of(), CONTROL_PLUGIN_OPTIONS, callContext); fail(); } catch (PaymentApiException e) { assertTrue(e.getCause() instanceof IllegalStateException); } } @Test(groups = "slow") public void testCreateSuccessAuthVoid() throws PaymentApiException { final BigDecimal authAmount = BigDecimal.TEN; final String paymentExternalKey = UUID.randomUUID().toString(); final String transactionExternalKey = UUID.randomUUID().toString(); final String transactionExternalKey2 = UUID.randomUUID().toString(); final Payment payment = paymentApi.createAuthorization(account, account.getPaymentMethodId(), null, authAmount, Currency.AED, paymentExternalKey, transactionExternalKey, ImmutableList.<PluginProperty>of(), callContext); assertEquals(payment.getExternalKey(), paymentExternalKey); assertEquals(payment.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment.getAccountId(), account.getId()); assertEquals(payment.getAuthAmount().compareTo(authAmount), 0); assertEquals(payment.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCurrency(), Currency.AED); assertFalse(payment.isAuthVoided()); assertEquals(payment.getTransactions().size(), 1); assertEquals(payment.getTransactions().get(0).getExternalKey(), transactionExternalKey); assertEquals(payment.getTransactions().get(0).getPaymentId(), payment.getId()); assertEquals(payment.getTransactions().get(0).getAmount().compareTo(authAmount), 0); assertEquals(payment.getTransactions().get(0).getCurrency(), Currency.AED); assertEquals(payment.getTransactions().get(0).getProcessedAmount().compareTo(authAmount), 0); assertEquals(payment.getTransactions().get(0).getProcessedCurrency(), Currency.AED); assertEquals(payment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment.getTransactions().get(0).getTransactionType(), TransactionType.AUTHORIZE); assertNotNull(payment.getTransactions().get(0).getGatewayErrorMsg()); assertNotNull(payment.getTransactions().get(0).getGatewayErrorCode()); // Void the authorization final Payment payment2 = paymentApi.createVoid(account, payment.getId(), transactionExternalKey2, ImmutableList.<PluginProperty>of(), callContext); assertEquals(payment2.getExternalKey(), paymentExternalKey); assertEquals(payment2.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment2.getAccountId(), account.getId()); assertEquals(payment2.getAuthAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment2.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment2.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment2.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment2.getCurrency(), Currency.AED); assertTrue(payment2.isAuthVoided()); assertEquals(payment2.getTransactions().size(), 2); assertEquals(payment2.getTransactions().get(1).getExternalKey(), transactionExternalKey2); assertEquals(payment2.getTransactions().get(1).getPaymentId(), payment.getId()); assertNull(payment2.getTransactions().get(1).getAmount()); assertNull(payment2.getTransactions().get(1).getCurrency()); assertNull(payment2.getTransactions().get(1).getProcessedAmount()); assertNull(payment2.getTransactions().get(1).getProcessedCurrency()); assertEquals(payment2.getTransactions().get(1).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment2.getTransactions().get(1).getTransactionType(), TransactionType.VOID); assertNotNull(payment2.getTransactions().get(1).getGatewayErrorMsg()); assertNotNull(payment2.getTransactions().get(1).getGatewayErrorCode()); } @Test(groups = "slow") public void testCreateSuccessAuthCaptureVoidCapture() throws PaymentApiException { final BigDecimal authAmount = BigDecimal.TEN; final BigDecimal captureAmount = BigDecimal.ONE; final String paymentExternalKey = UUID.randomUUID().toString(); final String transactionExternalKey = UUID.randomUUID().toString(); final String transactionExternalKey2 = UUID.randomUUID().toString(); final String transactionExternalKey3 = UUID.randomUUID().toString(); final String transactionExternalKey4 = UUID.randomUUID().toString(); final Payment payment = paymentApi.createAuthorization(account, account.getPaymentMethodId(), null, authAmount, Currency.AED, paymentExternalKey, transactionExternalKey, ImmutableList.<PluginProperty>of(), callContext); assertEquals(payment.getExternalKey(), paymentExternalKey); assertEquals(payment.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment.getAccountId(), account.getId()); assertEquals(payment.getAuthAmount().compareTo(authAmount), 0); assertEquals(payment.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCurrency(), Currency.AED); assertFalse(payment.isAuthVoided()); assertEquals(payment.getTransactions().size(), 1); assertEquals(payment.getTransactions().get(0).getExternalKey(), transactionExternalKey); assertEquals(payment.getTransactions().get(0).getPaymentId(), payment.getId()); assertEquals(payment.getTransactions().get(0).getAmount().compareTo(authAmount), 0); assertEquals(payment.getTransactions().get(0).getCurrency(), Currency.AED); assertEquals(payment.getTransactions().get(0).getProcessedAmount().compareTo(authAmount), 0); assertEquals(payment.getTransactions().get(0).getProcessedCurrency(), Currency.AED); assertEquals(payment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment.getTransactions().get(0).getTransactionType(), TransactionType.AUTHORIZE); assertNotNull(payment.getTransactions().get(0).getGatewayErrorMsg()); assertNotNull(payment.getTransactions().get(0).getGatewayErrorCode()); final Payment payment2 = paymentApi.createCapture(account, payment.getId(), captureAmount, Currency.AED, transactionExternalKey2, ImmutableList.<PluginProperty>of(), callContext); assertEquals(payment2.getExternalKey(), paymentExternalKey); assertEquals(payment2.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment2.getAccountId(), account.getId()); assertEquals(payment2.getAuthAmount().compareTo(authAmount), 0); assertEquals(payment2.getCapturedAmount().compareTo(captureAmount), 0); assertEquals(payment2.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment2.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment2.getCurrency(), Currency.AED); assertFalse(payment2.isAuthVoided()); assertEquals(payment2.getTransactions().size(), 2); assertEquals(payment2.getTransactions().get(1).getExternalKey(), transactionExternalKey2); assertEquals(payment2.getTransactions().get(1).getPaymentId(), payment.getId()); assertEquals(payment2.getTransactions().get(1).getAmount().compareTo(captureAmount), 0); assertEquals(payment2.getTransactions().get(1).getCurrency(), Currency.AED); assertEquals(payment2.getTransactions().get(1).getProcessedAmount().compareTo(captureAmount), 0); assertEquals(payment2.getTransactions().get(1).getProcessedCurrency(), Currency.AED); assertEquals(payment2.getTransactions().get(1).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment2.getTransactions().get(1).getTransactionType(), TransactionType.CAPTURE); assertNotNull(payment2.getTransactions().get(1).getGatewayErrorMsg()); assertNotNull(payment2.getTransactions().get(1).getGatewayErrorCode()); // Void the capture final Payment payment3 = paymentApi.createVoid(account, payment.getId(), transactionExternalKey3, ImmutableList.<PluginProperty>of(), callContext); assertEquals(payment3.getExternalKey(), paymentExternalKey); assertEquals(payment3.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment3.getAccountId(), account.getId()); assertEquals(payment3.getAuthAmount().compareTo(authAmount), 0); assertEquals(payment3.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment3.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment3.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment3.getCurrency(), Currency.AED); assertFalse(payment3.isAuthVoided()); assertEquals(payment3.getTransactions().size(), 3); assertEquals(payment3.getTransactions().get(2).getExternalKey(), transactionExternalKey3); assertEquals(payment3.getTransactions().get(2).getPaymentId(), payment.getId()); assertNull(payment3.getTransactions().get(2).getAmount()); assertNull(payment3.getTransactions().get(2).getCurrency()); assertNull(payment3.getTransactions().get(2).getProcessedAmount()); assertNull(payment3.getTransactions().get(2).getProcessedCurrency()); assertEquals(payment3.getTransactions().get(2).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment3.getTransactions().get(2).getTransactionType(), TransactionType.VOID); assertNotNull(payment3.getTransactions().get(2).getGatewayErrorMsg()); assertNotNull(payment3.getTransactions().get(2).getGatewayErrorCode()); // Capture again final Payment payment4 = paymentApi.createCapture(account, payment.getId(), captureAmount, Currency.AED, transactionExternalKey4, ImmutableList.<PluginProperty>of(), callContext); assertEquals(payment4.getExternalKey(), paymentExternalKey); assertEquals(payment4.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment4.getAccountId(), account.getId()); assertEquals(payment4.getAuthAmount().compareTo(authAmount), 0); assertEquals(payment4.getCapturedAmount().compareTo(captureAmount), 0); assertEquals(payment4.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment4.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment4.getCurrency(), Currency.AED); assertFalse(payment4.isAuthVoided()); assertEquals(payment4.getTransactions().size(), 4); assertEquals(payment4.getTransactions().get(3).getExternalKey(), transactionExternalKey4); assertEquals(payment4.getTransactions().get(3).getPaymentId(), payment.getId()); assertEquals(payment4.getTransactions().get(3).getAmount().compareTo(captureAmount), 0); assertEquals(payment4.getTransactions().get(3).getCurrency(), Currency.AED); assertEquals(payment4.getTransactions().get(3).getProcessedAmount().compareTo(captureAmount), 0); assertEquals(payment4.getTransactions().get(3).getProcessedCurrency(), Currency.AED); assertEquals(payment4.getTransactions().get(3).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment4.getTransactions().get(3).getTransactionType(), TransactionType.CAPTURE); assertNotNull(payment4.getTransactions().get(3).getGatewayErrorMsg()); assertNotNull(payment4.getTransactions().get(3).getGatewayErrorCode()); } @Test(groups = "slow") public void testCreateSuccessAuthCaptureVoidVoid() throws PaymentApiException { final BigDecimal authAmount = BigDecimal.TEN; final BigDecimal captureAmount = BigDecimal.ONE; final String paymentExternalKey = UUID.randomUUID().toString(); final String transactionExternalKey = UUID.randomUUID().toString(); final String transactionExternalKey2 = UUID.randomUUID().toString(); final String transactionExternalKey3 = UUID.randomUUID().toString(); final String transactionExternalKey4 = UUID.randomUUID().toString(); final Payment payment = paymentApi.createAuthorization(account, account.getPaymentMethodId(), null, authAmount, Currency.AED, paymentExternalKey, transactionExternalKey, ImmutableList.<PluginProperty>of(), callContext); assertEquals(payment.getExternalKey(), paymentExternalKey); assertEquals(payment.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment.getAccountId(), account.getId()); assertEquals(payment.getAuthAmount().compareTo(authAmount), 0); assertEquals(payment.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCurrency(), Currency.AED); assertFalse(payment.isAuthVoided()); assertEquals(payment.getTransactions().size(), 1); assertEquals(payment.getTransactions().get(0).getExternalKey(), transactionExternalKey); assertEquals(payment.getTransactions().get(0).getPaymentId(), payment.getId()); assertEquals(payment.getTransactions().get(0).getAmount().compareTo(authAmount), 0); assertEquals(payment.getTransactions().get(0).getCurrency(), Currency.AED); assertEquals(payment.getTransactions().get(0).getProcessedAmount().compareTo(authAmount), 0); assertEquals(payment.getTransactions().get(0).getProcessedCurrency(), Currency.AED); assertEquals(payment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment.getTransactions().get(0).getTransactionType(), TransactionType.AUTHORIZE); assertNotNull(payment.getTransactions().get(0).getGatewayErrorMsg()); assertNotNull(payment.getTransactions().get(0).getGatewayErrorCode()); final Payment payment2 = paymentApi.createCapture(account, payment.getId(), captureAmount, Currency.AED, transactionExternalKey2, ImmutableList.<PluginProperty>of(), callContext); assertEquals(payment2.getExternalKey(), paymentExternalKey); assertEquals(payment2.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment2.getAccountId(), account.getId()); assertEquals(payment2.getAuthAmount().compareTo(authAmount), 0); assertEquals(payment2.getCapturedAmount().compareTo(captureAmount), 0); assertEquals(payment2.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment2.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment2.getCurrency(), Currency.AED); assertFalse(payment2.isAuthVoided()); assertEquals(payment2.getTransactions().size(), 2); assertEquals(payment2.getTransactions().get(1).getExternalKey(), transactionExternalKey2); assertEquals(payment2.getTransactions().get(1).getPaymentId(), payment.getId()); assertEquals(payment2.getTransactions().get(1).getAmount().compareTo(captureAmount), 0); assertEquals(payment2.getTransactions().get(1).getCurrency(), Currency.AED); assertEquals(payment2.getTransactions().get(1).getProcessedAmount().compareTo(captureAmount), 0); assertEquals(payment2.getTransactions().get(1).getProcessedCurrency(), Currency.AED); assertEquals(payment2.getTransactions().get(1).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment2.getTransactions().get(1).getTransactionType(), TransactionType.CAPTURE); assertNotNull(payment2.getTransactions().get(1).getGatewayErrorMsg()); assertNotNull(payment2.getTransactions().get(1).getGatewayErrorCode()); // Void the capture final Payment payment3 = paymentApi.createVoid(account, payment.getId(), transactionExternalKey3, ImmutableList.<PluginProperty>of(), callContext); assertEquals(payment3.getExternalKey(), paymentExternalKey); assertEquals(payment3.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment3.getAccountId(), account.getId()); assertEquals(payment3.getAuthAmount().compareTo(authAmount), 0); assertEquals(payment3.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment3.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment3.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment3.getCurrency(), Currency.AED); assertFalse(payment3.isAuthVoided()); assertEquals(payment3.getTransactions().size(), 3); assertEquals(payment3.getTransactions().get(2).getExternalKey(), transactionExternalKey3); assertEquals(payment3.getTransactions().get(2).getPaymentId(), payment.getId()); assertNull(payment3.getTransactions().get(2).getAmount()); assertNull(payment3.getTransactions().get(2).getCurrency()); assertNull(payment3.getTransactions().get(2).getProcessedAmount()); assertNull(payment3.getTransactions().get(2).getProcessedCurrency()); assertEquals(payment3.getTransactions().get(2).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment3.getTransactions().get(2).getTransactionType(), TransactionType.VOID); assertNotNull(payment3.getTransactions().get(2).getGatewayErrorMsg()); assertNotNull(payment3.getTransactions().get(2).getGatewayErrorCode()); // Void the authorization final Payment payment4 = paymentApi.createVoid(account, payment.getId(), transactionExternalKey4, ImmutableList.<PluginProperty>of(), callContext); assertEquals(payment4.getExternalKey(), paymentExternalKey); assertEquals(payment4.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment4.getAccountId(), account.getId()); assertEquals(payment4.getAuthAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment4.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment4.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment4.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment4.getCurrency(), Currency.AED); assertTrue(payment4.isAuthVoided()); assertEquals(payment4.getTransactions().size(), 4); assertEquals(payment4.getTransactions().get(3).getExternalKey(), transactionExternalKey4); assertEquals(payment4.getTransactions().get(3).getPaymentId(), payment.getId()); assertNull(payment4.getTransactions().get(3).getAmount()); assertNull(payment4.getTransactions().get(3).getCurrency()); assertNull(payment4.getTransactions().get(3).getProcessedAmount()); assertNull(payment4.getTransactions().get(3).getProcessedCurrency()); assertEquals(payment4.getTransactions().get(3).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment4.getTransactions().get(3).getTransactionType(), TransactionType.VOID); assertNotNull(payment4.getTransactions().get(3).getGatewayErrorMsg()); assertNotNull(payment4.getTransactions().get(3).getGatewayErrorCode()); } @Test(groups = "slow") public void testCreateSuccessAuthMultipleCaptureAndRefund() throws PaymentApiException { final BigDecimal authAmount = BigDecimal.TEN; final BigDecimal captureAmount = BigDecimal.ONE; final String paymentExternalKey = "courou"; final String transactionExternalKey = "sioux"; final String transactionExternalKey2 = "sioux2"; final String transactionExternalKey3 = "sioux3"; final String transactionExternalKey4 = "sioux4"; final Payment payment = paymentApi.createAuthorization(account, account.getPaymentMethodId(), null, authAmount, Currency.USD, paymentExternalKey, transactionExternalKey, ImmutableList.<PluginProperty>of(), callContext); paymentApi.createCapture(account, payment.getId(), captureAmount, Currency.USD, transactionExternalKey2, ImmutableList.<PluginProperty>of(), callContext); final Payment payment3 = paymentApi.createCapture(account, payment.getId(), captureAmount, Currency.USD, transactionExternalKey3, ImmutableList.<PluginProperty>of(), callContext); assertEquals(payment3.getExternalKey(), paymentExternalKey); assertEquals(payment3.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment3.getAccountId(), account.getId()); assertEquals(payment3.getAuthAmount().compareTo(authAmount), 0); assertEquals(payment3.getCapturedAmount().compareTo(captureAmount.add(captureAmount)), 0); assertEquals(payment3.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment3.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment3.getCurrency(), Currency.USD); assertEquals(payment3.getTransactions().size(), 3); final Payment payment4 = paymentApi.createRefund(account, payment3.getId(), payment3.getCapturedAmount(), Currency.USD, transactionExternalKey4, ImmutableList.<PluginProperty>of(), callContext); assertEquals(payment4.getAuthAmount().compareTo(authAmount), 0); assertEquals(payment4.getCapturedAmount().compareTo(captureAmount.add(captureAmount)), 0); assertEquals(payment4.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment4.getRefundedAmount().compareTo(payment3.getCapturedAmount()), 0); assertEquals(payment4.getTransactions().size(), 4); assertEquals(payment4.getTransactions().get(3).getExternalKey(), transactionExternalKey4); assertEquals(payment4.getTransactions().get(3).getPaymentId(), payment.getId()); assertEquals(payment4.getTransactions().get(3).getAmount().compareTo(payment3.getCapturedAmount()), 0); assertEquals(payment4.getTransactions().get(3).getCurrency(), Currency.USD); assertEquals(payment4.getTransactions().get(3).getProcessedAmount().compareTo(payment3.getCapturedAmount()), 0); assertEquals(payment4.getTransactions().get(3).getProcessedCurrency(), Currency.USD); assertEquals(payment4.getTransactions().get(3).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment4.getTransactions().get(3).getTransactionType(), TransactionType.REFUND); assertNotNull(payment4.getTransactions().get(3).getGatewayErrorMsg()); assertNotNull(payment4.getTransactions().get(3).getGatewayErrorCode()); } @Test(groups = "slow") public void testCreateSuccessPurchaseWithPaymentControl() throws PaymentApiException, InvoiceApiException, EventBusException { final BigDecimal requestedAmount = BigDecimal.TEN; final UUID subscriptionId = UUID.randomUUID(); final UUID bundleId = UUID.randomUUID(); final LocalDate now = clock.getUTCToday(); final Invoice invoice = testHelper.createTestInvoice(account, now, Currency.USD); final String paymentExternalKey = invoice.getId().toString(); final String transactionExternalKey = "brrrrrr"; invoice.addInvoiceItem(new MockRecurringInvoiceItem(invoice.getId(), account.getId(), subscriptionId, bundleId, "test plan", "test phase", null, now, now.plusMonths(1), requestedAmount, new BigDecimal("1.0"), Currency.USD)); final Payment payment = paymentApi.createPurchaseWithPaymentControl(account, account.getPaymentMethodId(), null, requestedAmount, Currency.USD, paymentExternalKey, transactionExternalKey, createPropertiesForInvoice(invoice), INVOICE_PAYMENT, callContext); assertEquals(payment.getExternalKey(), paymentExternalKey); assertEquals(payment.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment.getAccountId(), account.getId()); assertEquals(payment.getAuthAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getPurchasedAmount().compareTo(requestedAmount), 0); assertEquals(payment.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCurrency(), Currency.USD); assertEquals(payment.getTransactions().size(), 1); assertEquals(payment.getTransactions().get(0).getExternalKey(), transactionExternalKey); assertEquals(payment.getTransactions().get(0).getPaymentId(), payment.getId()); assertEquals(payment.getTransactions().get(0).getAmount().compareTo(requestedAmount), 0); assertEquals(payment.getTransactions().get(0).getCurrency(), Currency.USD); assertEquals(payment.getTransactions().get(0).getProcessedAmount().compareTo(requestedAmount), 0); assertEquals(payment.getTransactions().get(0).getProcessedCurrency(), Currency.USD); assertEquals(payment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment.getTransactions().get(0).getTransactionType(), TransactionType.PURCHASE); assertNotNull(payment.getTransactions().get(0).getGatewayErrorMsg()); assertNotNull(payment.getTransactions().get(0).getGatewayErrorCode()); // Not stricly an API test but interesting to verify that we indeed went through the attempt logic final List<PaymentAttemptModelDao> attempts = paymentDao.getPaymentAttempts(payment.getExternalKey(), internalCallContext); assertEquals(attempts.size(), 1); } @Test(groups = "slow") public void testCreateFailedPurchaseWithPaymentControl() throws PaymentApiException, InvoiceApiException, EventBusException { final BigDecimal requestedAmount = BigDecimal.TEN; final UUID subscriptionId = UUID.randomUUID(); final UUID bundleId = UUID.randomUUID(); final LocalDate now = clock.getUTCToday(); final Invoice invoice = testHelper.createTestInvoice(account, now, Currency.USD); final String paymentExternalKey = invoice.getId().toString(); final String transactionExternalKey = "brrrrrr"; mockPaymentProviderPlugin.makeNextPaymentFailWithError(); invoice.addInvoiceItem(new MockRecurringInvoiceItem(invoice.getId(), account.getId(), subscriptionId, bundleId, "test plan", "test phase", null, now, now.plusMonths(1), requestedAmount, new BigDecimal("1.0"), Currency.USD)); try { paymentApi.createPurchaseWithPaymentControl(account, account.getPaymentMethodId(), null, requestedAmount, Currency.USD, paymentExternalKey, transactionExternalKey, createPropertiesForInvoice(invoice), INVOICE_PAYMENT, callContext); } catch (final PaymentApiException expected) { assertTrue(true); } final List<Payment> accountPayments = paymentApi.getAccountPayments(account.getId(), false, ImmutableList.<PluginProperty>of(), callContext); assertEquals(accountPayments.size(), 1); final Payment payment = accountPayments.get(0); assertEquals(payment.getExternalKey(), paymentExternalKey); assertEquals(payment.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment.getAccountId(), account.getId()); assertEquals(payment.getAuthAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCurrency(), Currency.USD); assertEquals(payment.getTransactions().size(), 1); assertEquals(payment.getTransactions().get(0).getExternalKey(), transactionExternalKey); assertEquals(payment.getTransactions().get(0).getPaymentId(), payment.getId()); assertEquals(payment.getTransactions().get(0).getAmount().compareTo(requestedAmount), 0); assertEquals(payment.getTransactions().get(0).getCurrency(), Currency.USD); assertEquals(payment.getTransactions().get(0).getProcessedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getTransactions().get(0).getProcessedCurrency(), Currency.USD); assertEquals(payment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.PAYMENT_FAILURE); assertEquals(payment.getTransactions().get(0).getTransactionType(), TransactionType.PURCHASE); } @Test(groups = "slow") public void testCreateCancelledPurchaseWithPaymentControl() throws PaymentApiException, InvoiceApiException, EventBusException { final BigDecimal requestedAmount = BigDecimal.TEN; final UUID subscriptionId = UUID.randomUUID(); final UUID bundleId = UUID.randomUUID(); final LocalDate now = clock.getUTCToday(); final Invoice invoice = testHelper.createTestInvoice(account, now, Currency.USD); final String paymentExternalKey = invoice.getId().toString(); final String transactionExternalKey = "hgjhgjgjhg33"; mockPaymentProviderPlugin.makeNextPaymentFailWithCancellation(); invoice.addInvoiceItem(new MockRecurringInvoiceItem(invoice.getId(), account.getId(), subscriptionId, bundleId, "test plan", "test phase", null, now, now.plusMonths(1), requestedAmount, new BigDecimal("1.0"), Currency.USD)); try { paymentApi.createPurchaseWithPaymentControl(account, account.getPaymentMethodId(), null, requestedAmount, Currency.USD, paymentExternalKey, transactionExternalKey, createPropertiesForInvoice(invoice), INVOICE_PAYMENT, callContext); } catch (final PaymentApiException expected) { assertTrue(true); } final List<Payment> accountPayments = paymentApi.getAccountPayments(account.getId(), false, ImmutableList.<PluginProperty>of(), callContext); assertEquals(accountPayments.size(), 1); final Payment payment = accountPayments.get(0); assertEquals(payment.getExternalKey(), paymentExternalKey); assertEquals(payment.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment.getAccountId(), account.getId()); assertEquals(payment.getAuthAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCurrency(), Currency.USD); assertEquals(payment.getTransactions().size(), 1); assertEquals(payment.getTransactions().get(0).getExternalKey(), transactionExternalKey); assertEquals(payment.getTransactions().get(0).getPaymentId(), payment.getId()); assertEquals(payment.getTransactions().get(0).getAmount().compareTo(requestedAmount), 0); assertEquals(payment.getTransactions().get(0).getCurrency(), Currency.USD); assertEquals(payment.getTransactions().get(0).getProcessedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getTransactions().get(0).getProcessedCurrency(), Currency.USD); assertEquals(payment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.PLUGIN_FAILURE); assertEquals(payment.getTransactions().get(0).getTransactionType(), TransactionType.PURCHASE); // Make sure we can retry and that works paymentApi.createPurchaseWithPaymentControl(account, account.getPaymentMethodId(), null, requestedAmount, Currency.USD, paymentExternalKey, transactionExternalKey, createPropertiesForInvoice(invoice), INVOICE_PAYMENT, callContext); final List<Payment> accountPayments2 = paymentApi.getAccountPayments(account.getId(), false, ImmutableList.<PluginProperty>of(), callContext); assertEquals(accountPayments2.size(), 1); final Payment payment2 = accountPayments2.get(0); assertEquals(payment2.getTransactions().size(), 2); assertEquals(payment2.getTransactions().get(0).getExternalKey(), transactionExternalKey); assertEquals(payment2.getTransactions().get(0).getTransactionStatus(), TransactionStatus.PLUGIN_FAILURE); assertEquals(payment2.getTransactions().get(0).getTransactionType(), TransactionType.PURCHASE); assertEquals(payment2.getTransactions().get(1).getExternalKey(), transactionExternalKey); assertEquals(payment2.getTransactions().get(1).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment2.getTransactions().get(1).getTransactionType(), TransactionType.PURCHASE); } @Test(groups = "slow") public void testCreateAbortedPurchaseWithPaymentControl() throws InvoiceApiException, EventBusException { final BigDecimal requestedAmount = BigDecimal.TEN; final UUID subscriptionId = UUID.randomUUID(); final UUID bundleId = UUID.randomUUID(); final LocalDate now = clock.getUTCToday(); final Invoice invoice = testHelper.createTestInvoice(account, now, Currency.USD); final String paymentExternalKey = invoice.getId().toString(); final String transactionExternalKey = "brrrrrr"; invoice.addInvoiceItem(new MockRecurringInvoiceItem(invoice.getId(), account.getId(), subscriptionId, bundleId, "test plan", "test phase", null, now, now.plusMonths(1), BigDecimal.ONE, new BigDecimal("1.0"), Currency.USD)); try { paymentApi.createPurchaseWithPaymentControl(account, account.getPaymentMethodId(), null, requestedAmount, Currency.USD, paymentExternalKey, transactionExternalKey, createPropertiesForInvoice(invoice), INVOICE_PAYMENT, callContext); Assert.fail("Unexpected success"); } catch (final PaymentApiException e) { } } @Test(groups = "slow") public void testCreateSuccessRefundWithPaymentControl() throws PaymentApiException, InvoiceApiException, EventBusException { final BigDecimal requestedAmount = BigDecimal.TEN; final UUID subscriptionId = UUID.randomUUID(); final UUID bundleId = UUID.randomUUID(); final LocalDate now = clock.getUTCToday(); final Invoice invoice = testHelper.createTestInvoice(account, now, Currency.USD); final String paymentExternalKey = invoice.getId().toString(); final String transactionExternalKey = "sacrebleu"; final String transactionExternalKey2 = "maisenfin"; final InvoiceItem invoiceItem = new MockRecurringInvoiceItem(invoice.getId(), account.getId(), subscriptionId, bundleId, "test plan", "test phase", null, now, now.plusMonths(1), requestedAmount, new BigDecimal("1.0"), Currency.USD); invoice.addInvoiceItem(invoiceItem); final Payment payment = paymentApi.createPurchaseWithPaymentControl(account, account.getPaymentMethodId(), null, requestedAmount, Currency.USD, paymentExternalKey, transactionExternalKey, createPropertiesForInvoice(invoice), INVOICE_PAYMENT, callContext); final List<PluginProperty> refundProperties = ImmutableList.<PluginProperty>of(); final Payment payment2 = paymentApi.createRefundWithPaymentControl(account, payment.getId(), requestedAmount, Currency.USD, transactionExternalKey2, refundProperties, INVOICE_PAYMENT, callContext); assertEquals(payment2.getTransactions().size(), 2); assertEquals(payment2.getExternalKey(), paymentExternalKey); assertEquals(payment2.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment2.getAccountId(), account.getId()); assertEquals(payment2.getAuthAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment2.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment2.getPurchasedAmount().compareTo(requestedAmount), 0); assertEquals(payment2.getRefundedAmount().compareTo(requestedAmount), 0); assertEquals(payment2.getCurrency(), Currency.USD); } @Test(groups = "slow") public void testCreateAbortedRefundWithPaymentControl() throws PaymentApiException, InvoiceApiException, EventBusException { final BigDecimal requestedAmount = BigDecimal.ONE; final UUID subscriptionId = UUID.randomUUID(); final UUID bundleId = UUID.randomUUID(); final LocalDate now = clock.getUTCToday(); final Invoice invoice = testHelper.createTestInvoice(account, now, Currency.USD); final String paymentExternalKey = invoice.getId().toString(); final String transactionExternalKey = "payment"; final String transactionExternalKey2 = "refund"; final InvoiceItem invoiceItem = new MockRecurringInvoiceItem(invoice.getId(), account.getId(), subscriptionId, bundleId, "test plan", "test phase", null, now, now.plusMonths(1), requestedAmount, new BigDecimal("1.0"), Currency.USD); invoice.addInvoiceItem(invoiceItem); final Payment payment = paymentApi.createPurchaseWithPaymentControl(account, account.getPaymentMethodId(), null, requestedAmount, Currency.USD, paymentExternalKey, transactionExternalKey, createPropertiesForInvoice(invoice), INVOICE_PAYMENT, callContext); final List<PluginProperty> refundProperties = ImmutableList.<PluginProperty>of(); try { paymentApi.createRefundWithPaymentControl(account, payment.getId(), BigDecimal.TEN, Currency.USD, transactionExternalKey2, refundProperties, INVOICE_PAYMENT, callContext); } catch (final PaymentApiException e) { assertTrue(e.getCause() instanceof PaymentControlApiException); } } @Test(groups = "slow") public void testCreateSuccessRefundPaymentControlWithItemAdjustments() throws PaymentApiException, InvoiceApiException, EventBusException { final BigDecimal requestedAmount = BigDecimal.TEN; final UUID subscriptionId = UUID.randomUUID(); final UUID bundleId = UUID.randomUUID(); final LocalDate now = clock.getUTCToday(); final Invoice invoice = testHelper.createTestInvoice(account, now, Currency.USD); final String paymentExternalKey = invoice.getId().toString(); final String transactionExternalKey = "hopla"; final String transactionExternalKey2 = "chouette"; final InvoiceItem invoiceItem = new MockRecurringInvoiceItem(invoice.getId(), account.getId(), subscriptionId, bundleId, "test plan", "test phase", null, now, now.plusMonths(1), requestedAmount, new BigDecimal("1.0"), Currency.USD); invoice.addInvoiceItem(invoiceItem); final Payment payment = paymentApi.createPurchaseWithPaymentControl(account, account.getPaymentMethodId(), null, requestedAmount, Currency.USD, paymentExternalKey, transactionExternalKey, createPropertiesForInvoice(invoice), INVOICE_PAYMENT, callContext); final List<PluginProperty> refundProperties = new ArrayList<PluginProperty>(); final HashMap<UUID, BigDecimal> uuidBigDecimalHashMap = new HashMap<UUID, BigDecimal>(); uuidBigDecimalHashMap.put(invoiceItem.getId(), null); final PluginProperty refundIdsProp = new PluginProperty(InvoicePaymentControlPluginApi.PROP_IPCD_REFUND_IDS_WITH_AMOUNT_KEY, uuidBigDecimalHashMap, false); refundProperties.add(refundIdsProp); final Payment payment2 = paymentApi.createRefundWithPaymentControl(account, payment.getId(), null, Currency.USD, transactionExternalKey2, refundProperties, INVOICE_PAYMENT, callContext); assertEquals(payment2.getTransactions().size(), 2); assertEquals(payment2.getExternalKey(), paymentExternalKey); assertEquals(payment2.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment2.getAccountId(), account.getId()); assertEquals(payment2.getAuthAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment2.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment2.getPurchasedAmount().compareTo(requestedAmount), 0); assertEquals(payment2.getRefundedAmount().compareTo(requestedAmount), 0); assertEquals(payment2.getCurrency(), Currency.USD); } @Test(groups = "slow", description = "https://github.com/killbill/killbill/issues/477") public void testCreateChargeback() throws PaymentApiException { // API change in 0.17 final DefaultPaymentApi paymentApi = (DefaultPaymentApi) this.paymentApi; final BigDecimal requestedAmount = BigDecimal.TEN; final Currency currency = Currency.AED; final String paymentExternalKey = UUID.randomUUID().toString(); final String purchaseTransactionExternalKey = UUID.randomUUID().toString(); final String chargebackTransactionExternalKey = UUID.randomUUID().toString(); final ImmutableList<PluginProperty> properties = ImmutableList.<PluginProperty>of(); final Payment payment = paymentApi.createPurchase(account, account.getPaymentMethodId(), null, requestedAmount, currency, paymentExternalKey, purchaseTransactionExternalKey, properties, callContext); assertEquals(payment.getExternalKey(), paymentExternalKey); assertEquals(payment.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment.getAccountId(), account.getId()); assertEquals(payment.getAuthAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getPurchasedAmount().compareTo(requestedAmount), 0); assertEquals(payment.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCurrency(), currency); assertEquals(payment.getTransactions().size(), 1); assertEquals(payment.getTransactions().get(0).getExternalKey(), purchaseTransactionExternalKey); assertEquals(payment.getTransactions().get(0).getPaymentId(), payment.getId()); assertEquals(payment.getTransactions().get(0).getAmount().compareTo(requestedAmount), 0); assertEquals(payment.getTransactions().get(0).getCurrency(), currency); assertEquals(payment.getTransactions().get(0).getProcessedAmount().compareTo(requestedAmount), 0); assertEquals(payment.getTransactions().get(0).getProcessedCurrency(), currency); assertEquals(payment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment.getTransactions().get(0).getTransactionType(), TransactionType.PURCHASE); assertEquals(payment.getTransactions().get(0).getGatewayErrorMsg(), ""); assertEquals(payment.getTransactions().get(0).getGatewayErrorCode(), ""); assertEquals(paymentDao.getPayment(payment.getId(), internalCallContext).getStateName(), "PURCHASE_SUCCESS"); assertEquals(paymentDao.getPayment(payment.getId(), internalCallContext).getLastSuccessStateName(), "PURCHASE_SUCCESS"); // First chargeback final Payment payment2 = paymentApi.createChargeback(account, payment.getId(), requestedAmount, currency, chargebackTransactionExternalKey, callContext); assertEquals(payment2.getExternalKey(), paymentExternalKey); assertEquals(payment2.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment2.getAccountId(), account.getId()); assertEquals(payment2.getAuthAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment2.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); // Purchase amount zero-ed out assertEquals(payment2.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment2.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment2.getCurrency(), currency); assertEquals(payment2.getTransactions().size(), 2); assertEquals(payment2.getTransactions().get(1).getExternalKey(), chargebackTransactionExternalKey); assertEquals(payment2.getTransactions().get(1).getPaymentId(), payment.getId()); assertEquals(payment2.getTransactions().get(1).getAmount().compareTo(requestedAmount), 0); assertEquals(payment2.getTransactions().get(1).getCurrency(), currency); assertEquals(payment2.getTransactions().get(1).getProcessedAmount().compareTo(requestedAmount), 0); assertEquals(payment2.getTransactions().get(1).getProcessedCurrency(), currency); assertEquals(payment2.getTransactions().get(1).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment2.getTransactions().get(1).getTransactionType(), TransactionType.CHARGEBACK); assertNull(payment2.getTransactions().get(1).getGatewayErrorMsg()); assertNull(payment2.getTransactions().get(1).getGatewayErrorCode()); assertEquals(paymentDao.getPayment(payment.getId(), internalCallContext).getStateName(), "CHARGEBACK_SUCCESS"); assertEquals(paymentDao.getPayment(payment.getId(), internalCallContext).getLastSuccessStateName(), "CHARGEBACK_SUCCESS"); try { paymentApi.createRefund(account, payment.getId(), requestedAmount, currency, UUID.randomUUID().toString(), properties, callContext); Assert.fail("Refunds are no longer permitted after a chargeback"); } catch (final PaymentApiException e) { assertEquals(e.getCode(), ErrorCode.PAYMENT_INVALID_OPERATION.getCode()); } // First reversal final Payment payment3 = paymentApi.createChargebackReversal(account, payment.getId(), chargebackTransactionExternalKey, callContext); assertEquals(payment3.getExternalKey(), paymentExternalKey); assertEquals(payment3.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment3.getAccountId(), account.getId()); assertEquals(payment3.getAuthAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment3.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); // Actual purchase amount assertEquals(payment3.getPurchasedAmount().compareTo(requestedAmount), 0); assertEquals(payment3.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment3.getCurrency(), currency); assertEquals(payment3.getTransactions().size(), 3); assertEquals(payment3.getTransactions().get(2).getExternalKey(), chargebackTransactionExternalKey); assertEquals(payment3.getTransactions().get(2).getPaymentId(), payment.getId()); assertNull(payment3.getTransactions().get(2).getAmount()); assertNull(payment3.getTransactions().get(2).getCurrency()); assertEquals(payment3.getTransactions().get(2).getProcessedAmount().compareTo(BigDecimal.ZERO), 0); assertNull(payment3.getTransactions().get(2).getProcessedCurrency()); assertEquals(payment3.getTransactions().get(2).getTransactionStatus(), TransactionStatus.PAYMENT_FAILURE); assertEquals(payment3.getTransactions().get(2).getTransactionType(), TransactionType.CHARGEBACK); assertNull(payment3.getTransactions().get(2).getGatewayErrorMsg()); assertNull(payment3.getTransactions().get(2).getGatewayErrorCode()); assertEquals(paymentDao.getPayment(payment.getId(), internalCallContext).getStateName(), "CHARGEBACK_FAILED"); assertEquals(paymentDao.getPayment(payment.getId(), internalCallContext).getLastSuccessStateName(), "CHARGEBACK_FAILED"); // Attempt a refund final BigDecimal refundAmount = BigDecimal.ONE; final String refundTransactionExternalKey = UUID.randomUUID().toString(); final Payment payment4 = paymentApi.createRefund(account, payment.getId(), refundAmount, currency, refundTransactionExternalKey, properties, callContext); assertEquals(payment4.getExternalKey(), paymentExternalKey); assertEquals(payment4.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment4.getAccountId(), account.getId()); assertEquals(payment4.getAuthAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment4.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); // Actual purchase amount assertEquals(payment4.getPurchasedAmount().compareTo(requestedAmount), 0); assertEquals(payment4.getRefundedAmount().compareTo(refundAmount), 0); assertEquals(payment4.getCurrency(), currency); assertEquals(payment4.getTransactions().size(), 4); assertEquals(payment4.getTransactions().get(3).getExternalKey(), refundTransactionExternalKey); assertEquals(payment4.getTransactions().get(3).getPaymentId(), payment.getId()); assertEquals(payment4.getTransactions().get(3).getAmount().compareTo(refundAmount), 0); assertEquals(payment4.getTransactions().get(3).getCurrency(), currency); assertEquals(payment4.getTransactions().get(3).getProcessedAmount().compareTo(refundAmount), 0); assertEquals(payment4.getTransactions().get(3).getProcessedCurrency(), currency); assertEquals(payment4.getTransactions().get(3).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment4.getTransactions().get(3).getTransactionType(), TransactionType.REFUND); assertEquals(payment4.getTransactions().get(3).getGatewayErrorMsg(), ""); assertEquals(payment4.getTransactions().get(3).getGatewayErrorCode(), ""); assertEquals(paymentDao.getPayment(payment.getId(), internalCallContext).getStateName(), "REFUND_SUCCESS"); assertEquals(paymentDao.getPayment(payment.getId(), internalCallContext).getLastSuccessStateName(), "REFUND_SUCCESS"); // Second chargeback final BigDecimal secondChargebackAmount = requestedAmount.add(refundAmount.negate()); final Payment payment5 = paymentApi.createChargeback(account, payment.getId(), secondChargebackAmount, currency, chargebackTransactionExternalKey, callContext); assertEquals(payment5.getExternalKey(), paymentExternalKey); assertEquals(payment5.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment5.getAccountId(), account.getId()); assertEquals(payment5.getAuthAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment5.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); // Purchase amount zero-ed out assertEquals(payment5.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment5.getRefundedAmount().compareTo(refundAmount), 0); assertEquals(payment5.getCurrency(), currency); assertEquals(payment5.getTransactions().size(), 5); assertEquals(payment5.getTransactions().get(4).getExternalKey(), chargebackTransactionExternalKey); assertEquals(payment5.getTransactions().get(4).getPaymentId(), payment.getId()); assertEquals(payment5.getTransactions().get(4).getAmount().compareTo(secondChargebackAmount), 0); assertEquals(payment5.getTransactions().get(4).getCurrency(), currency); assertEquals(payment5.getTransactions().get(4).getProcessedAmount().compareTo(secondChargebackAmount), 0); assertEquals(payment5.getTransactions().get(4).getProcessedCurrency(), currency); assertEquals(payment5.getTransactions().get(4).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment5.getTransactions().get(4).getTransactionType(), TransactionType.CHARGEBACK); assertNull(payment5.getTransactions().get(4).getGatewayErrorMsg()); assertNull(payment5.getTransactions().get(4).getGatewayErrorCode()); assertEquals(paymentDao.getPayment(payment.getId(), internalCallContext).getStateName(), "CHARGEBACK_SUCCESS"); assertEquals(paymentDao.getPayment(payment.getId(), internalCallContext).getLastSuccessStateName(), "CHARGEBACK_SUCCESS"); try { paymentApi.createRefund(account, payment.getId(), refundAmount, currency, UUID.randomUUID().toString(), properties, callContext); Assert.fail("Refunds are no longer permitted after a chargeback"); } catch (final PaymentApiException e) { assertEquals(e.getCode(), ErrorCode.PAYMENT_INVALID_OPERATION.getCode()); } // Second reversal final Payment payment6 = paymentApi.createChargebackReversal(account, payment.getId(), chargebackTransactionExternalKey, callContext); assertEquals(payment6.getExternalKey(), paymentExternalKey); assertEquals(payment6.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment6.getAccountId(), account.getId()); assertEquals(payment6.getAuthAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment6.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); // Actual purchase amount assertEquals(payment6.getPurchasedAmount().compareTo(requestedAmount), 0); assertEquals(payment6.getRefundedAmount().compareTo(refundAmount), 0); assertEquals(payment6.getCurrency(), currency); assertEquals(payment6.getTransactions().size(), 6); assertEquals(payment6.getTransactions().get(5).getExternalKey(), chargebackTransactionExternalKey); assertEquals(payment6.getTransactions().get(5).getPaymentId(), payment.getId()); assertNull(payment6.getTransactions().get(5).getAmount()); assertNull(payment6.getTransactions().get(5).getCurrency()); assertEquals(payment6.getTransactions().get(5).getProcessedAmount().compareTo(BigDecimal.ZERO), 0); assertNull(payment6.getTransactions().get(5).getProcessedCurrency()); assertEquals(payment6.getTransactions().get(5).getTransactionStatus(), TransactionStatus.PAYMENT_FAILURE); assertEquals(payment6.getTransactions().get(5).getTransactionType(), TransactionType.CHARGEBACK); assertNull(payment6.getTransactions().get(5).getGatewayErrorMsg()); assertNull(payment6.getTransactions().get(5).getGatewayErrorCode()); assertEquals(paymentDao.getPayment(payment.getId(), internalCallContext).getStateName(), "CHARGEBACK_FAILED"); assertEquals(paymentDao.getPayment(payment.getId(), internalCallContext).getLastSuccessStateName(), "CHARGEBACK_FAILED"); } @Test(groups = "slow") public void testCreateChargebackReversalBeforeChargeback() throws PaymentApiException { // API change in 0.17 final DefaultPaymentApi paymentApi = (DefaultPaymentApi) this.paymentApi; final BigDecimal requestedAmount = BigDecimal.TEN; final Currency currency = Currency.AED; final String paymentExternalKey = UUID.randomUUID().toString(); final String purchaseTransactionExternalKey = UUID.randomUUID().toString(); final String chargebackTransactionExternalKey = UUID.randomUUID().toString(); final ImmutableList<PluginProperty> properties = ImmutableList.<PluginProperty>of(); final Payment payment = paymentApi.createPurchase(account, account.getPaymentMethodId(), null, requestedAmount, currency, paymentExternalKey, purchaseTransactionExternalKey, properties, callContext); assertEquals(payment.getExternalKey(), paymentExternalKey); assertEquals(payment.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment.getAccountId(), account.getId()); assertEquals(payment.getAuthAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getPurchasedAmount().compareTo(requestedAmount), 0); assertEquals(payment.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCurrency(), currency); assertEquals(payment.getTransactions().size(), 1); assertEquals(payment.getTransactions().get(0).getExternalKey(), purchaseTransactionExternalKey); assertEquals(payment.getTransactions().get(0).getPaymentId(), payment.getId()); assertEquals(payment.getTransactions().get(0).getAmount().compareTo(requestedAmount), 0); assertEquals(payment.getTransactions().get(0).getCurrency(), currency); assertEquals(payment.getTransactions().get(0).getProcessedAmount().compareTo(requestedAmount), 0); assertEquals(payment.getTransactions().get(0).getProcessedCurrency(), currency); assertEquals(payment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment.getTransactions().get(0).getTransactionType(), TransactionType.PURCHASE); assertEquals(payment.getTransactions().get(0).getGatewayErrorMsg(), ""); assertEquals(payment.getTransactions().get(0).getGatewayErrorCode(), ""); assertEquals(paymentDao.getPayment(payment.getId(), internalCallContext).getStateName(), "PURCHASE_SUCCESS"); assertEquals(paymentDao.getPayment(payment.getId(), internalCallContext).getLastSuccessStateName(), "PURCHASE_SUCCESS"); try { paymentApi.createChargebackReversal(account, payment.getId(), chargebackTransactionExternalKey, callContext); Assert.fail("Chargeback reversals are not permitted before a chargeback"); } catch (final PaymentApiException e) { assertEquals(e.getCode(), ErrorCode.PAYMENT_NO_SUCH_SUCCESS_PAYMENT.getCode()); } assertEquals(paymentApi.getPayment(payment.getId(), false, ImmutableList.<PluginProperty>of(), callContext).getTransactions().size(), 1); assertEquals(paymentDao.getPayment(payment.getId(), internalCallContext).getStateName(), "PURCHASE_SUCCESS"); assertEquals(paymentDao.getPayment(payment.getId(), internalCallContext).getLastSuccessStateName(), "PURCHASE_SUCCESS"); } @Test(groups = "slow") public void testNotifyPendingTransactionOfStateChanged() throws PaymentApiException { final BigDecimal authAmount = BigDecimal.TEN; final String paymentExternalKey = "rouge"; final String transactionExternalKey = "vert"; final Payment initialPayment = createPayment(TransactionType.AUTHORIZE, null, paymentExternalKey, transactionExternalKey, authAmount, PaymentPluginStatus.PENDING); final Payment payment = paymentApi.notifyPendingTransactionOfStateChanged(account, initialPayment.getTransactions().get(0).getId(), true, callContext); assertEquals(payment.getExternalKey(), paymentExternalKey); assertEquals(payment.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment.getAccountId(), account.getId()); assertEquals(payment.getAuthAmount().compareTo(authAmount), 0); assertEquals(payment.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCurrency(), Currency.USD); assertEquals(payment.getTransactions().size(), 1); assertEquals(payment.getTransactions().get(0).getExternalKey(), transactionExternalKey); assertEquals(payment.getTransactions().get(0).getPaymentId(), payment.getId()); assertEquals(payment.getTransactions().get(0).getAmount().compareTo(authAmount), 0); assertEquals(payment.getTransactions().get(0).getCurrency(), Currency.USD); assertEquals(payment.getTransactions().get(0).getProcessedAmount().compareTo(authAmount), 0); assertEquals(payment.getTransactions().get(0).getProcessedCurrency(), Currency.USD); assertEquals(payment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment.getTransactions().get(0).getTransactionType(), TransactionType.AUTHORIZE); assertNull(payment.getTransactions().get(0).getGatewayErrorMsg()); assertNull(payment.getTransactions().get(0).getGatewayErrorCode()); } @Test(groups = "slow") public void testSimpleAuthCaptureWithInvalidPaymentId() throws Exception { final BigDecimal requestedAmount = new BigDecimal("80.0091"); final Payment initialPayment = paymentApi.createAuthorization(account, account.getPaymentMethodId(), null, requestedAmount, account.getCurrency(), UUID.randomUUID().toString(), UUID.randomUUID().toString(), ImmutableList.<PluginProperty>of(), callContext); try { paymentApi.createCapture(account, UUID.randomUUID(), requestedAmount, account.getCurrency(), UUID.randomUUID().toString(), ImmutableList.<PluginProperty>of(), callContext); Assert.fail("Expected capture to fail..."); } catch (final PaymentApiException e) { Assert.assertEquals(e.getCode(), ErrorCode.PAYMENT_NO_SUCH_PAYMENT.getCode()); final Payment latestPayment = paymentApi.getPayment(initialPayment.getId(), true, ImmutableList.<PluginProperty>of(), callContext); assertEquals(latestPayment, initialPayment); } } @Test(groups = "slow") public void testSimpleAuthCaptureWithInvalidCurrency() throws Exception { final BigDecimal requestedAmount = new BigDecimal("80.0091"); final Payment initialPayment = paymentApi.createAuthorization(account, account.getPaymentMethodId(), null, requestedAmount, account.getCurrency(), UUID.randomUUID().toString(), UUID.randomUUID().toString(), ImmutableList.<PluginProperty>of(), callContext); try { paymentApi.createCapture(account, initialPayment.getId(), requestedAmount, Currency.AMD, UUID.randomUUID().toString(), ImmutableList.<PluginProperty>of(), callContext); Assert.fail("Expected capture to fail..."); } catch (final PaymentApiException e) { Assert.assertEquals(e.getCode(), ErrorCode.PAYMENT_INVALID_PARAMETER.getCode()); final Payment latestPayment = paymentApi.getPayment(initialPayment.getId(), true, ImmutableList.<PluginProperty>of(), callContext); assertEquals(latestPayment, initialPayment); } } @Test(groups = "slow") public void testInvalidTransitionAfterFailure() throws PaymentApiException { final BigDecimal requestedAmount = BigDecimal.TEN; final String paymentExternalKey = "krapo"; final String transactionExternalKey = "grenouye"; final Payment payment = paymentApi.createAuthorization(account, account.getPaymentMethodId(), null, requestedAmount, Currency.EUR, paymentExternalKey, transactionExternalKey, ImmutableList.<PluginProperty>of(), callContext); // Hack the Database to make it look like it was a failure paymentDao.updatePaymentAndTransactionOnCompletion(account.getId(), null, payment.getId(), TransactionType.AUTHORIZE, "AUTH_ERRORED", null, payment.getTransactions().get(0).getId(), TransactionStatus.PLUGIN_FAILURE, null, null, null, null, internalCallContext); final PaymentSqlDao paymentSqlDao = dbi.onDemand(PaymentSqlDao.class); paymentSqlDao.updateLastSuccessPaymentStateName(payment.getId().toString(), "AUTH_ERRORED", null, internalCallContext); try { paymentApi.createCapture(account, payment.getId(), requestedAmount, Currency.EUR, "tetard", ImmutableList.<PluginProperty>of(), callContext); Assert.fail("Unexpected success"); } catch (final PaymentApiException e) { Assert.assertEquals(e.getCode(), ErrorCode.PAYMENT_INVALID_OPERATION.getCode()); } } @Test(groups = "slow") public void testApiWithPendingPaymentTransaction() throws Exception { for (final TransactionType transactionType : ImmutableList.<TransactionType>of(TransactionType.AUTHORIZE, TransactionType.PURCHASE, TransactionType.CREDIT)) { testApiWithPendingPaymentTransaction(transactionType, BigDecimal.TEN, BigDecimal.TEN); testApiWithPendingPaymentTransaction(transactionType, BigDecimal.TEN, BigDecimal.ONE); // See https://github.com/killbill/killbill/issues/372 testApiWithPendingPaymentTransaction(transactionType, BigDecimal.TEN, null); } } @Test(groups = "slow") public void testApiWithPendingRefundPaymentTransaction() throws Exception { final String paymentExternalKey = UUID.randomUUID().toString(); final String paymentTransactionExternalKey = UUID.randomUUID().toString(); final String refundTransactionExternalKey = UUID.randomUUID().toString(); final BigDecimal requestedAmount = BigDecimal.TEN; final BigDecimal refundAmount = BigDecimal.ONE; final Iterable<PluginProperty> pendingPluginProperties = ImmutableList.<PluginProperty>of(new PluginProperty(MockPaymentProviderPlugin.PLUGIN_PROPERTY_PAYMENT_PLUGIN_STATUS_OVERRIDE, TransactionStatus.PENDING.toString(), false)); final Payment payment = createPayment(TransactionType.PURCHASE, null, paymentExternalKey, paymentTransactionExternalKey, requestedAmount, PaymentPluginStatus.PROCESSED); assertNotNull(payment); Assert.assertEquals(payment.getExternalKey(), paymentExternalKey); Assert.assertEquals(payment.getTransactions().size(), 1); Assert.assertEquals(payment.getTransactions().get(0).getAmount().compareTo(requestedAmount), 0); Assert.assertEquals(payment.getTransactions().get(0).getProcessedAmount().compareTo(requestedAmount), 0); Assert.assertEquals(payment.getTransactions().get(0).getCurrency(), account.getCurrency()); Assert.assertEquals(payment.getTransactions().get(0).getExternalKey(), paymentTransactionExternalKey); Assert.assertEquals(payment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.SUCCESS); final Payment pendingRefund = paymentApi.createRefund(account, payment.getId(), requestedAmount, account.getCurrency(), refundTransactionExternalKey, pendingPluginProperties, callContext); verifyRefund(pendingRefund, paymentExternalKey, paymentTransactionExternalKey, refundTransactionExternalKey, requestedAmount, requestedAmount, TransactionStatus.PENDING); // Test Janitor path (regression test for https://github.com/killbill/killbill/issues/363) verifyPaymentViaGetPath(pendingRefund); // See https://github.com/killbill/killbill/issues/372 final Payment pendingRefund2 = paymentApi.createRefund(account, payment.getId(), null, null, refundTransactionExternalKey, pendingPluginProperties, callContext); verifyRefund(pendingRefund2, paymentExternalKey, paymentTransactionExternalKey, refundTransactionExternalKey, requestedAmount, requestedAmount, TransactionStatus.PENDING); verifyPaymentViaGetPath(pendingRefund2); // Note: we change the refund amount final Payment pendingRefund3 = paymentApi.createRefund(account, payment.getId(), refundAmount, account.getCurrency(), refundTransactionExternalKey, pendingPluginProperties, callContext); verifyRefund(pendingRefund3, paymentExternalKey, paymentTransactionExternalKey, refundTransactionExternalKey, requestedAmount, refundAmount, TransactionStatus.PENDING); verifyPaymentViaGetPath(pendingRefund3); // Pass null, we revert back to the original refund amount final Payment pendingRefund4 = paymentApi.createRefund(account, payment.getId(), null, null, refundTransactionExternalKey, ImmutableList.<PluginProperty>of(), callContext); verifyRefund(pendingRefund4, paymentExternalKey, paymentTransactionExternalKey, refundTransactionExternalKey, requestedAmount, requestedAmount, TransactionStatus.SUCCESS); verifyPaymentViaGetPath(pendingRefund4); } @Test(groups = "slow") public void testCompletionOfUnknownAuthorization() throws Exception { final String paymentExternalKey = UUID.randomUUID().toString(); final String paymentTransactionExternalKey = UUID.randomUUID().toString(); final BigDecimal requestedAmount = BigDecimal.TEN; final Payment pendingPayment = createPayment(TransactionType.AUTHORIZE, null, paymentExternalKey, paymentTransactionExternalKey, requestedAmount, PaymentPluginStatus.UNDEFINED); assertNotNull(pendingPayment); Assert.assertEquals(pendingPayment.getTransactions().size(), 1); Assert.assertEquals(pendingPayment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.UNKNOWN); try { // Attempt to complete the payment createPayment(TransactionType.AUTHORIZE, pendingPayment.getId(), paymentExternalKey, paymentTransactionExternalKey, requestedAmount, PaymentPluginStatus.PROCESSED); Assert.fail(); } catch (final PaymentApiException e) { Assert.assertEquals(e.getCode(), ErrorCode.PAYMENT_INVALID_OPERATION.getCode()); } } @Test(groups = "slow") public void testCompletionOfUnknownCapture() throws Exception { final String paymentExternalKey = UUID.randomUUID().toString(); final BigDecimal requestedAmount = BigDecimal.TEN; final Payment authorization = createPayment(TransactionType.AUTHORIZE, null, paymentExternalKey, UUID.randomUUID().toString(), requestedAmount, PaymentPluginStatus.PROCESSED); assertNotNull(authorization); Assert.assertEquals(authorization.getTransactions().size(), 1); Assert.assertEquals(authorization.getTransactions().get(0).getTransactionStatus(), TransactionStatus.SUCCESS); final String paymentTransactionExternalKey = UUID.randomUUID().toString(); final Payment pendingPayment = createPayment(TransactionType.CAPTURE, authorization.getId(), paymentExternalKey, paymentTransactionExternalKey, requestedAmount, PaymentPluginStatus.UNDEFINED); Assert.assertEquals(pendingPayment.getTransactions().size(), 2); Assert.assertEquals(pendingPayment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.SUCCESS); Assert.assertEquals(pendingPayment.getTransactions().get(1).getTransactionStatus(), TransactionStatus.UNKNOWN); try { // Attempt to complete the payment createPayment(TransactionType.CAPTURE, authorization.getId(), paymentExternalKey, paymentTransactionExternalKey, requestedAmount, PaymentPluginStatus.PROCESSED); Assert.fail(); } catch (final PaymentApiException e) { Assert.assertEquals(e.getCode(), ErrorCode.PAYMENT_INVALID_OPERATION.getCode()); } } @Test(groups = "slow") public void testCreatePurchaseWithTimeout() throws Exception { final BigDecimal requestedAmount = BigDecimal.TEN; final String paymentExternalKey = "ohhhh"; final String transactionExternalKey = "naaahhh"; mockPaymentProviderPlugin.makePluginWaitSomeMilliseconds((int) (paymentConfig.getPaymentPluginTimeout().getMillis() + 100)); try { paymentApi.createPurchase(account, account.getPaymentMethodId(), null, requestedAmount, Currency.AED, paymentExternalKey, transactionExternalKey, ImmutableList.<PluginProperty>of(), callContext); fail(); } catch (PaymentApiException e) { assertEquals(e.getCode(), ErrorCode.PAYMENT_PLUGIN_TIMEOUT.getCode()); } } @Test(groups = "slow") public void testCreatePurchaseWithControlTimeout() throws Exception { final BigDecimal requestedAmount = BigDecimal.ONE; final String paymentExternalKey = "111111"; final String transactionExternalKey = "11111"; mockPaymentProviderPlugin.makePluginWaitSomeMilliseconds((int) (paymentConfig.getPaymentPluginTimeout().getMillis() + 100)); try { paymentApi.createPurchaseWithPaymentControl( account, account.getPaymentMethodId(), null, requestedAmount, Currency.AED, paymentExternalKey, transactionExternalKey, ImmutableList.<PluginProperty>of(), CONTROL_PLUGIN_OPTIONS, callContext); fail(); } catch (PaymentApiException e) { assertEquals(e.getCode(), ErrorCode.PAYMENT_PLUGIN_TIMEOUT.getCode()); } } @Test(groups = "slow") public void testSanityAcrossTransactionTypes() throws PaymentApiException { final BigDecimal requestedAmount = BigDecimal.TEN; final String paymentExternalKey = "ahhhhhhhh"; final String transactionExternalKey = "okkkkkkk"; final Payment pendingPayment = createPayment(TransactionType.AUTHORIZE, null, paymentExternalKey, transactionExternalKey, requestedAmount, PaymentPluginStatus.PENDING); assertNotNull(pendingPayment); Assert.assertEquals(pendingPayment.getExternalKey(), paymentExternalKey); Assert.assertEquals(pendingPayment.getTransactions().size(), 1); Assert.assertEquals(pendingPayment.getTransactions().get(0).getAmount().compareTo(requestedAmount), 0); Assert.assertEquals(pendingPayment.getTransactions().get(0).getProcessedAmount().compareTo(requestedAmount), 0); Assert.assertEquals(pendingPayment.getTransactions().get(0).getCurrency(), account.getCurrency()); Assert.assertEquals(pendingPayment.getTransactions().get(0).getExternalKey(), transactionExternalKey); Assert.assertEquals(pendingPayment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.PENDING); try { createPayment(TransactionType.PURCHASE, null, paymentExternalKey, transactionExternalKey, requestedAmount, PaymentPluginStatus.PENDING); Assert.fail("PURCHASE transaction with same key should have failed"); } catch (final PaymentApiException expected) { Assert.assertEquals(expected.getCode(), ErrorCode.PAYMENT_INVALID_OPERATION.getCode()); } } @Test(groups = "slow") public void testSuccessfulInitialTransactionToSameTransaction() throws Exception { final BigDecimal requestedAmount = BigDecimal.TEN; for (final TransactionType transactionType : ImmutableList.<TransactionType>of(TransactionType.AUTHORIZE, TransactionType.PURCHASE, TransactionType.CREDIT)) { final String paymentExternalKey = UUID.randomUUID().toString(); final String keyA = UUID.randomUUID().toString(); final Payment processedPayment = createPayment(transactionType, null, paymentExternalKey, keyA, requestedAmount, PaymentPluginStatus.PROCESSED); assertNotNull(processedPayment); Assert.assertEquals(processedPayment.getTransactions().size(), 1); Assert.assertEquals(processedPayment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.SUCCESS); // Attempt to create another {AUTH, PURCHASE, CREDIT} with different key => KB state machine should make the request fail as we don't allow // multiple SUCCESS {AUTH, PURCHASE, CREDIT} final String keyB = UUID.randomUUID().toString(); try { createPayment(transactionType, processedPayment.getId(), paymentExternalKey, keyB, requestedAmount, PaymentPluginStatus.PROCESSED); Assert.fail("Retrying initial successful transaction (AUTHORIZE, PURCHASE, CREDIT) with same different key should fail"); } catch (final PaymentApiException e) { } // Attempt to create another {AUTH, PURCHASE, CREDIT} with same key => key constraint should make the request fail try { createPayment(transactionType, processedPayment.getId(), paymentExternalKey, keyA, requestedAmount, PaymentPluginStatus.PROCESSED); Assert.fail("Retrying initial successful transaction (AUTHORIZE, PURCHASE, CREDIT) with same transaction key should fail"); } catch (final PaymentApiException e) { } } } @Test(groups = "slow") public void testPendingInitialTransactionToSameTransaction() throws Exception { final BigDecimal requestedAmount = BigDecimal.TEN; for (final TransactionType transactionType : ImmutableList.<TransactionType>of(TransactionType.AUTHORIZE, TransactionType.PURCHASE, TransactionType.CREDIT)) { final String paymentExternalKey = UUID.randomUUID().toString(); final String keyA = UUID.randomUUID().toString(); final Payment pendingPayment = createPayment(transactionType, null, paymentExternalKey, keyA, requestedAmount, PaymentPluginStatus.PENDING); assertNotNull(pendingPayment); Assert.assertEquals(pendingPayment.getTransactions().size(), 1); Assert.assertEquals(pendingPayment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.PENDING); // Attempt to create another {AUTH, PURCHASE, CREDIT} with different key => KB state machine should make the request fail as we don't allow // multiple SUCCESS {AUTH, PURCHASE, CREDIT} final String keyB = UUID.randomUUID().toString(); try { createPayment(transactionType, pendingPayment.getId(), paymentExternalKey, keyB, requestedAmount, PaymentPluginStatus.PROCESSED); Assert.fail("Retrying initial successful transaction (AUTHORIZE, PURCHASE, CREDIT) with same different key should fail"); } catch (final PaymentApiException e) { } // Attempt to create another {AUTH, PURCHASE, CREDIT} with same key => That should work because we are completing the payment final Payment completedPayment = createPayment(transactionType, pendingPayment.getId(), paymentExternalKey, keyA, requestedAmount, PaymentPluginStatus.PROCESSED); assertNotNull(completedPayment); Assert.assertEquals(completedPayment.getId(), pendingPayment.getId()); Assert.assertEquals(completedPayment.getTransactions().size(), 1); } } @Test(groups = "slow") public void testFailedInitialTransactionToSameTransactionWithSameKey() throws Exception { final BigDecimal requestedAmount = BigDecimal.TEN; for (final TransactionType transactionType : ImmutableList.<TransactionType>of(TransactionType.AUTHORIZE, TransactionType.PURCHASE, TransactionType.CREDIT)) { final String paymentExternalKey = UUID.randomUUID().toString(); final String keyA = UUID.randomUUID().toString(); final Payment errorPayment = createPayment(transactionType, null, paymentExternalKey, keyA, requestedAmount, PaymentPluginStatus.ERROR); assertNotNull(errorPayment); Assert.assertEquals(errorPayment.getTransactions().size(), 1); Assert.assertEquals(errorPayment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.PAYMENT_FAILURE); // Attempt to create another {AUTH, PURCHASE, CREDIT} with same key => That should work because we are completing the payment final Payment successfulPayment = createPayment(transactionType, errorPayment.getId(), paymentExternalKey, keyA, requestedAmount, PaymentPluginStatus.PROCESSED); assertNotNull(successfulPayment); Assert.assertEquals(successfulPayment.getId(), errorPayment.getId()); Assert.assertEquals(successfulPayment.getTransactions().size(), 2); } } @Test(groups = "slow") public void testFailedInitialTransactionToSameTransactionWithDifferentKey() throws Exception { final BigDecimal requestedAmount = BigDecimal.TEN; for (final TransactionType transactionType : ImmutableList.<TransactionType>of(TransactionType.AUTHORIZE, TransactionType.PURCHASE, TransactionType.CREDIT)) { final String paymentExternalKey = UUID.randomUUID().toString(); final String keyA = UUID.randomUUID().toString(); final Payment errorPayment = createPayment(transactionType, null, paymentExternalKey, keyA, requestedAmount, PaymentPluginStatus.ERROR); assertNotNull(errorPayment); Assert.assertEquals(errorPayment.getTransactions().size(), 1); Assert.assertEquals(errorPayment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.PAYMENT_FAILURE); // Attempt to create another {AUTH, PURCHASE, CREDIT} with different key => KB state machine should make the request fail as we don't allow // multiple SUCCESS {AUTH, PURCHASE, CREDIT} final String keyB = UUID.randomUUID().toString(); final Payment successfulPayment = createPayment(transactionType, errorPayment.getId(), paymentExternalKey, keyB, requestedAmount, PaymentPluginStatus.PROCESSED); assertNotNull(successfulPayment); Assert.assertEquals(successfulPayment.getId(), errorPayment.getId()); Assert.assertEquals(successfulPayment.getTransactions().size(), 2); } } private void verifyRefund(final Payment refund, final String paymentExternalKey, final String paymentTransactionExternalKey, final String refundTransactionExternalKey, final BigDecimal requestedAmount, final BigDecimal refundAmount, final TransactionStatus transactionStatus) { Assert.assertEquals(refund.getExternalKey(), paymentExternalKey); Assert.assertEquals(refund.getTransactions().size(), 2); Assert.assertEquals(refund.getTransactions().get(0).getAmount().compareTo(requestedAmount), 0); Assert.assertEquals(refund.getTransactions().get(0).getProcessedAmount().compareTo(requestedAmount), 0); Assert.assertEquals(refund.getTransactions().get(0).getCurrency(), account.getCurrency()); Assert.assertEquals(refund.getTransactions().get(0).getExternalKey(), paymentTransactionExternalKey); Assert.assertEquals(refund.getTransactions().get(0).getTransactionStatus(), TransactionStatus.SUCCESS); Assert.assertEquals(refund.getTransactions().get(1).getAmount().compareTo(requestedAmount), 0); Assert.assertEquals(refund.getTransactions().get(1).getProcessedAmount().compareTo(refundAmount), 0); Assert.assertEquals(refund.getTransactions().get(1).getCurrency(), account.getCurrency()); Assert.assertEquals(refund.getTransactions().get(1).getExternalKey(), refundTransactionExternalKey); Assert.assertEquals(refund.getTransactions().get(1).getTransactionStatus(), transactionStatus); } private Payment testApiWithPendingPaymentTransaction(final TransactionType transactionType, final BigDecimal requestedAmount, @Nullable final BigDecimal pendingAmount) throws PaymentApiException { final String paymentExternalKey = UUID.randomUUID().toString(); final String paymentTransactionExternalKey = UUID.randomUUID().toString(); final Payment pendingPayment = createPayment(transactionType, null, paymentExternalKey, paymentTransactionExternalKey, requestedAmount, PaymentPluginStatus.PENDING); assertNotNull(pendingPayment); Assert.assertEquals(pendingPayment.getExternalKey(), paymentExternalKey); Assert.assertEquals(pendingPayment.getTransactions().size(), 1); Assert.assertEquals(pendingPayment.getTransactions().get(0).getAmount().compareTo(requestedAmount), 0); Assert.assertEquals(pendingPayment.getTransactions().get(0).getProcessedAmount().compareTo(requestedAmount), 0); Assert.assertEquals(pendingPayment.getTransactions().get(0).getCurrency(), account.getCurrency()); Assert.assertEquals(pendingPayment.getTransactions().get(0).getExternalKey(), paymentTransactionExternalKey); Assert.assertEquals(pendingPayment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.PENDING); // Test Janitor path (regression test for https://github.com/killbill/killbill/issues/363) verifyPaymentViaGetPath(pendingPayment); final Payment pendingPayment2 = createPayment(transactionType, pendingPayment.getId(), paymentExternalKey, paymentTransactionExternalKey, pendingAmount, PaymentPluginStatus.PENDING); assertNotNull(pendingPayment2); Assert.assertEquals(pendingPayment2.getExternalKey(), paymentExternalKey); Assert.assertEquals(pendingPayment2.getTransactions().size(), 1); Assert.assertEquals(pendingPayment2.getTransactions().get(0).getAmount().compareTo(requestedAmount), 0); Assert.assertEquals(pendingPayment2.getTransactions().get(0).getProcessedAmount().compareTo(pendingAmount == null ? requestedAmount : pendingAmount), 0); Assert.assertEquals(pendingPayment2.getTransactions().get(0).getCurrency(), account.getCurrency()); Assert.assertEquals(pendingPayment2.getTransactions().get(0).getExternalKey(), paymentTransactionExternalKey); Assert.assertEquals(pendingPayment2.getTransactions().get(0).getTransactionStatus(), TransactionStatus.PENDING); verifyPaymentViaGetPath(pendingPayment2); final Payment completedPayment = createPayment(transactionType, pendingPayment.getId(), paymentExternalKey, paymentTransactionExternalKey, pendingAmount, PaymentPluginStatus.PROCESSED); assertNotNull(completedPayment); Assert.assertEquals(completedPayment.getExternalKey(), paymentExternalKey); Assert.assertEquals(completedPayment.getTransactions().size(), 1); Assert.assertEquals(completedPayment.getTransactions().get(0).getAmount().compareTo(requestedAmount), 0); Assert.assertEquals(completedPayment.getTransactions().get(0).getProcessedAmount().compareTo(pendingAmount == null ? requestedAmount : pendingAmount), 0); Assert.assertEquals(completedPayment.getTransactions().get(0).getCurrency(), account.getCurrency()); Assert.assertEquals(completedPayment.getTransactions().get(0).getExternalKey(), paymentTransactionExternalKey); Assert.assertEquals(completedPayment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.SUCCESS); verifyPaymentViaGetPath(completedPayment); return completedPayment; } private void verifyPaymentViaGetPath(final Payment payment) throws PaymentApiException { // We can't use Assert.assertEquals because the updateDate may have been updated by the Janitor final Payment refreshedPayment = paymentApi.getPayment(payment.getId(), true, ImmutableList.<PluginProperty>of(), callContext); Assert.assertEquals(refreshedPayment.getAccountId(), payment.getAccountId()); Assert.assertEquals(refreshedPayment.getTransactions().size(), payment.getTransactions().size()); Assert.assertEquals(refreshedPayment.getExternalKey(), payment.getExternalKey()); Assert.assertEquals(refreshedPayment.getPaymentMethodId(), payment.getPaymentMethodId()); Assert.assertEquals(refreshedPayment.getAccountId(), payment.getAccountId()); Assert.assertEquals(refreshedPayment.getAuthAmount().compareTo(payment.getAuthAmount()), 0); Assert.assertEquals(refreshedPayment.getCapturedAmount().compareTo(payment.getCapturedAmount()), 0); Assert.assertEquals(refreshedPayment.getPurchasedAmount().compareTo(payment.getPurchasedAmount()), 0); Assert.assertEquals(refreshedPayment.getRefundedAmount().compareTo(payment.getRefundedAmount()), 0); Assert.assertEquals(refreshedPayment.getCurrency(), payment.getCurrency()); for (int i = 0; i < refreshedPayment.getTransactions().size(); i++) { final PaymentTransaction refreshedPaymentTransaction = refreshedPayment.getTransactions().get(i); final PaymentTransaction paymentTransaction = payment.getTransactions().get(i); Assert.assertEquals(refreshedPaymentTransaction.getAmount().compareTo(paymentTransaction.getAmount()), 0); Assert.assertEquals(refreshedPaymentTransaction.getProcessedAmount().compareTo(paymentTransaction.getProcessedAmount()), 0); Assert.assertEquals(refreshedPaymentTransaction.getCurrency(), paymentTransaction.getCurrency()); Assert.assertEquals(refreshedPaymentTransaction.getExternalKey(), paymentTransaction.getExternalKey()); Assert.assertEquals(refreshedPaymentTransaction.getTransactionStatus(), paymentTransaction.getTransactionStatus()); } } private Payment createPayment(final TransactionType transactionType, @Nullable final UUID paymentId, @Nullable final String paymentExternalKey, @Nullable final String paymentTransactionExternalKey, @Nullable final BigDecimal amount, final PaymentPluginStatus paymentPluginStatus) throws PaymentApiException { final Iterable<PluginProperty> pluginProperties = ImmutableList.<PluginProperty>of(new PluginProperty(MockPaymentProviderPlugin.PLUGIN_PROPERTY_PAYMENT_PLUGIN_STATUS_OVERRIDE, paymentPluginStatus.toString(), false)); switch (transactionType) { case AUTHORIZE: return paymentApi.createAuthorization(account, account.getPaymentMethodId(), paymentId, amount, amount == null ? null : account.getCurrency(), paymentExternalKey, paymentTransactionExternalKey, pluginProperties, callContext); case PURCHASE: return paymentApi.createPurchase(account, account.getPaymentMethodId(), paymentId, amount, amount == null ? null : account.getCurrency(), paymentExternalKey, paymentTransactionExternalKey, pluginProperties, callContext); case CREDIT: return paymentApi.createCredit(account, account.getPaymentMethodId(), paymentId, amount, amount == null ? null : account.getCurrency(), paymentExternalKey, paymentTransactionExternalKey, pluginProperties, callContext); case CAPTURE: return paymentApi.createCapture(account, paymentId, amount, amount == null ? null : account.getCurrency(), paymentTransactionExternalKey, pluginProperties, callContext); default: Assert.fail(); return null; } } private List<PluginProperty> createPropertiesForInvoice(final Invoice invoice) { final List<PluginProperty> result = new ArrayList<PluginProperty>(); result.add(new PluginProperty(InvoicePaymentControlPluginApi.PROP_IPCD_INVOICE_ID, invoice.getId().toString(), false)); return result; } // Search by a key supported by the search in MockPaymentProviderPlugin private void checkPaymentMethodPagination(final UUID paymentMethodId, final Long maxNbRecords, final boolean deleted) throws PaymentApiException { final Pagination<PaymentMethod> foundPaymentMethods = paymentApi.searchPaymentMethods(paymentMethodId.toString(), 0L, maxNbRecords + 1, false, ImmutableList.<PluginProperty>of(), callContext); Assert.assertEquals(foundPaymentMethods.iterator().hasNext(), !deleted); Assert.assertEquals(foundPaymentMethods.getMaxNbRecords(), maxNbRecords); Assert.assertEquals(foundPaymentMethods.getTotalNbRecords(), (Long) (!deleted ? 1L : 0L)); final Pagination<PaymentMethod> foundPaymentMethodsWithPluginInfo = paymentApi.searchPaymentMethods(paymentMethodId.toString(), 0L, maxNbRecords + 1, true, ImmutableList.<PluginProperty>of(), callContext); Assert.assertEquals(foundPaymentMethodsWithPluginInfo.iterator().hasNext(), !deleted); Assert.assertEquals(foundPaymentMethodsWithPluginInfo.getMaxNbRecords(), maxNbRecords); Assert.assertEquals(foundPaymentMethodsWithPluginInfo.getTotalNbRecords(), (Long) (!deleted ? 1L : 0L)); final Pagination<PaymentMethod> foundPaymentMethods2 = paymentApi.searchPaymentMethods(paymentMethodId.toString(), 0L, maxNbRecords + 1, MockPaymentProviderPlugin.PLUGIN_NAME, false, ImmutableList.<PluginProperty>of(), callContext); Assert.assertEquals(foundPaymentMethods2.iterator().hasNext(), !deleted); Assert.assertEquals(foundPaymentMethods2.getMaxNbRecords(), maxNbRecords); Assert.assertEquals(foundPaymentMethods2.getTotalNbRecords(), (Long) (!deleted ? 1L : 0L)); final Pagination<PaymentMethod> foundPaymentMethods2WithPluginInfo = paymentApi.searchPaymentMethods(paymentMethodId.toString(), 0L, maxNbRecords + 1, MockPaymentProviderPlugin.PLUGIN_NAME, true, ImmutableList.<PluginProperty>of(), callContext); Assert.assertEquals(foundPaymentMethods2WithPluginInfo.iterator().hasNext(), !deleted); Assert.assertEquals(foundPaymentMethods2WithPluginInfo.getMaxNbRecords(), maxNbRecords); Assert.assertEquals(foundPaymentMethods2WithPluginInfo.getTotalNbRecords(), (Long) (!deleted ? 1L : 0L)); final Pagination<PaymentMethod> gotPaymentMethods = paymentApi.getPaymentMethods(0L, maxNbRecords + 1L, false, ImmutableList.<PluginProperty>of(), callContext); Assert.assertEquals(gotPaymentMethods.iterator().hasNext(), maxNbRecords > 0); Assert.assertEquals(gotPaymentMethods.getMaxNbRecords(), maxNbRecords); Assert.assertEquals(gotPaymentMethods.getTotalNbRecords(), maxNbRecords); final Pagination<PaymentMethod> gotPaymentMethodsWithPluginInfo = paymentApi.getPaymentMethods(0L, maxNbRecords + 1L, true, ImmutableList.<PluginProperty>of(), callContext); Assert.assertEquals(gotPaymentMethodsWithPluginInfo.iterator().hasNext(), maxNbRecords > 0); Assert.assertEquals(gotPaymentMethodsWithPluginInfo.getMaxNbRecords(), maxNbRecords); Assert.assertEquals(gotPaymentMethodsWithPluginInfo.getTotalNbRecords(), maxNbRecords); final Pagination<PaymentMethod> gotPaymentMethods2 = paymentApi.getPaymentMethods(0L, maxNbRecords + 1L, MockPaymentProviderPlugin.PLUGIN_NAME, false, ImmutableList.<PluginProperty>of(), callContext); Assert.assertEquals(gotPaymentMethods2.iterator().hasNext(), maxNbRecords > 0); Assert.assertEquals(gotPaymentMethods2.getMaxNbRecords(), maxNbRecords); Assert.assertEquals(gotPaymentMethods2.getTotalNbRecords(), maxNbRecords); final Pagination<PaymentMethod> gotPaymentMethods2WithPluginInfo = paymentApi.getPaymentMethods(0L, maxNbRecords + 1L, MockPaymentProviderPlugin.PLUGIN_NAME, true, ImmutableList.<PluginProperty>of(), callContext); Assert.assertEquals(gotPaymentMethods2WithPluginInfo.iterator().hasNext(), maxNbRecords > 0); Assert.assertEquals(gotPaymentMethods2WithPluginInfo.getMaxNbRecords(), maxNbRecords); Assert.assertEquals(gotPaymentMethods2WithPluginInfo.getTotalNbRecords(), maxNbRecords); } }
payment/src/test/java/org/killbill/billing/payment/api/TestPaymentApi.java
/* * Copyright 2010-2013 Ning, Inc. * Copyright 2014-2016 Groupon, Inc * Copyright 2014-2016 The Billing Project, LLC * * The Billing 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 org.killbill.billing.payment.api; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.UUID; import javax.annotation.Nullable; import org.joda.time.LocalDate; import org.killbill.billing.ErrorCode; import org.killbill.billing.account.api.Account; import org.killbill.billing.catalog.api.Currency; import org.killbill.billing.control.plugin.api.PaymentControlApiException; import org.killbill.billing.invoice.api.Invoice; import org.killbill.billing.invoice.api.InvoiceApiException; import org.killbill.billing.invoice.api.InvoiceItem; import org.killbill.billing.osgi.api.OSGIServiceDescriptor; import org.killbill.billing.payment.MockRecurringInvoiceItem; import org.killbill.billing.payment.PaymentTestSuiteWithEmbeddedDB; import org.killbill.billing.payment.dao.PaymentAttemptModelDao; import org.killbill.billing.payment.dao.PaymentSqlDao; import org.killbill.billing.payment.invoice.InvoicePaymentControlPluginApi; import org.killbill.billing.payment.plugin.api.PaymentPluginApiException; import org.killbill.billing.payment.plugin.api.PaymentPluginStatus; import org.killbill.billing.payment.provider.ExternalPaymentProviderPlugin; import org.killbill.billing.payment.provider.MockPaymentControlProviderPlugin; import org.killbill.billing.payment.provider.MockPaymentProviderPlugin; import org.killbill.billing.util.entity.Pagination; import org.killbill.bus.api.PersistentBus.EventBusException; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.google.common.collect.ImmutableList; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; public class TestPaymentApi extends PaymentTestSuiteWithEmbeddedDB { private MockPaymentProviderPlugin mockPaymentProviderPlugin; private MockPaymentControlProviderPlugin mockPaymentControlProviderPlugin; final PaymentOptions INVOICE_PAYMENT = new PaymentOptions() { @Override public boolean isExternalPayment() { return false; } @Override public List<String> getPaymentControlPluginNames() { return ImmutableList.<String>of(InvoicePaymentControlPluginApi.PLUGIN_NAME); } }; final PaymentOptions CONTROL_PLUGIN_OPTIONS = new PaymentOptions() { @Override public boolean isExternalPayment() { return true; } @Override public List<String> getPaymentControlPluginNames() { return Arrays.asList(MockPaymentControlProviderPlugin.PLUGIN_NAME); } }; private Account account; @BeforeClass(groups = "slow") protected void beforeClass() throws Exception { super.beforeClass(); mockPaymentProviderPlugin = (MockPaymentProviderPlugin) registry.getServiceForName(MockPaymentProviderPlugin.PLUGIN_NAME); } @BeforeMethod(groups = "slow") public void beforeMethod() throws Exception { super.beforeMethod(); mockPaymentProviderPlugin.clear(); account = testHelper.createTestAccount("bobo@gmail.com", true); mockPaymentControlProviderPlugin = new MockPaymentControlProviderPlugin(); controlPluginRegistry.registerService(new OSGIServiceDescriptor() { @Override public String getPluginSymbolicName() { return null; } @Override public String getPluginName() { return MockPaymentControlProviderPlugin.PLUGIN_NAME; } @Override public String getRegistrationName() { return MockPaymentControlProviderPlugin.PLUGIN_NAME; } }, mockPaymentControlProviderPlugin); } @Test(groups = "slow") public void testUniqueExternalPaymentMethod() throws PaymentApiException { paymentApi.addPaymentMethod(account, "thisonewillwork", ExternalPaymentProviderPlugin.PLUGIN_NAME, true, null, ImmutableList.<PluginProperty>of(), callContext); try { paymentApi.addPaymentMethod(account, "thisonewillnotwork", ExternalPaymentProviderPlugin.PLUGIN_NAME, true, null, ImmutableList.<PluginProperty>of(), callContext); } catch (PaymentApiException e) { assertEquals(e.getCode(), ErrorCode.PAYMENT_EXTERNAL_PAYMENT_METHOD_ALREADY_EXISTS.getCode()); } } @Test(groups = "slow") public void testAddRemovePaymentMethod() throws Exception { final Long baseNbRecords = paymentApi.getPaymentMethods(0L, 1000L, false, ImmutableList.<PluginProperty>of(), callContext).getMaxNbRecords(); Assert.assertEquals(baseNbRecords, (Long) 1L); final Account account = testHelper.createTestAccount(UUID.randomUUID().toString(), true); final UUID paymentMethodId = account.getPaymentMethodId(); checkPaymentMethodPagination(paymentMethodId, baseNbRecords + 1, false); paymentApi.deletePaymentMethod(account, paymentMethodId, true, ImmutableList.<PluginProperty>of(), callContext); checkPaymentMethodPagination(paymentMethodId, baseNbRecords, true); } @Test(groups = "slow") public void testCreateSuccessPurchase() throws PaymentApiException { final BigDecimal requestedAmount = BigDecimal.TEN; final String paymentExternalKey = "bwwrr"; final String transactionExternalKey = "krapaut"; final Payment payment = paymentApi.createPurchase(account, account.getPaymentMethodId(), null, requestedAmount, Currency.AED, paymentExternalKey, transactionExternalKey, ImmutableList.<PluginProperty>of(), callContext); assertEquals(payment.getExternalKey(), paymentExternalKey); assertEquals(payment.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment.getAccountId(), account.getId()); assertEquals(payment.getAuthAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getPurchasedAmount().compareTo(requestedAmount), 0); assertEquals(payment.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCurrency(), Currency.AED); assertEquals(payment.getTransactions().size(), 1); assertEquals(payment.getTransactions().get(0).getExternalKey(), transactionExternalKey); assertEquals(payment.getTransactions().get(0).getPaymentId(), payment.getId()); assertEquals(payment.getTransactions().get(0).getAmount().compareTo(requestedAmount), 0); assertEquals(payment.getTransactions().get(0).getCurrency(), Currency.AED); assertEquals(payment.getTransactions().get(0).getProcessedAmount().compareTo(requestedAmount), 0); assertEquals(payment.getTransactions().get(0).getProcessedCurrency(), Currency.AED); assertEquals(payment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment.getTransactions().get(0).getTransactionType(), TransactionType.PURCHASE); assertNotNull(payment.getTransactions().get(0).getGatewayErrorMsg()); assertNotNull(payment.getTransactions().get(0).getGatewayErrorCode()); } @Test(groups = "slow") public void testCreateFailedPurchase() throws PaymentApiException { final BigDecimal requestedAmount = BigDecimal.TEN; final String paymentExternalKey = "ohhhh"; final String transactionExternalKey = "naaahhh"; mockPaymentProviderPlugin.makeNextPaymentFailWithError(); final Payment payment = paymentApi.createPurchase(account, account.getPaymentMethodId(), null, requestedAmount, Currency.AED, paymentExternalKey, transactionExternalKey, ImmutableList.<PluginProperty>of(), callContext); assertEquals(payment.getExternalKey(), paymentExternalKey); assertEquals(payment.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment.getAccountId(), account.getId()); assertEquals(payment.getAuthAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCurrency(), Currency.AED); assertEquals(payment.getTransactions().size(), 1); assertEquals(payment.getTransactions().get(0).getExternalKey(), transactionExternalKey); assertEquals(payment.getTransactions().get(0).getPaymentId(), payment.getId()); assertEquals(payment.getTransactions().get(0).getAmount().compareTo(requestedAmount), 0); assertEquals(payment.getTransactions().get(0).getCurrency(), Currency.AED); assertEquals(payment.getTransactions().get(0).getProcessedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getTransactions().get(0).getProcessedCurrency(), Currency.AED); assertEquals(payment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.PAYMENT_FAILURE); assertEquals(payment.getTransactions().get(0).getTransactionType(), TransactionType.PURCHASE); assertNotNull(payment.getTransactions().get(0).getGatewayErrorMsg()); assertNotNull(payment.getTransactions().get(0).getGatewayErrorCode()); final Payment payment2 = paymentApi.createPurchase(account, account.getPaymentMethodId(), null, requestedAmount, Currency.AED, paymentExternalKey, transactionExternalKey, ImmutableList.<PluginProperty>of(), callContext); assertEquals(payment2.getExternalKey(), paymentExternalKey); assertEquals(payment2.getTransactions().get(0).getExternalKey(), transactionExternalKey); assertEquals(payment2.getTransactions().get(0).getTransactionStatus(), TransactionStatus.PAYMENT_FAILURE); assertEquals(payment2.getTransactions().get(0).getTransactionType(), TransactionType.PURCHASE); assertEquals(payment2.getTransactions().get(1).getExternalKey(), transactionExternalKey); assertEquals(payment2.getTransactions().get(1).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment2.getTransactions().get(1).getTransactionType(), TransactionType.PURCHASE); } @Test(groups = "slow") public void testCreateCancelledPurchase() throws PaymentApiException { final BigDecimal requestedAmount = BigDecimal.TEN; final String paymentExternalKey = "hgh3"; final String transactionExternalKey = "hgh3sss"; mockPaymentProviderPlugin.makeNextPaymentFailWithCancellation(); final Payment payment = paymentApi.createPurchase(account, account.getPaymentMethodId(), null, requestedAmount, Currency.AED, paymentExternalKey, transactionExternalKey, ImmutableList.<PluginProperty>of(), callContext); assertEquals(payment.getExternalKey(), paymentExternalKey); assertEquals(payment.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment.getAccountId(), account.getId()); assertEquals(payment.getAuthAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCurrency(), Currency.AED); assertEquals(payment.getTransactions().size(), 1); assertEquals(payment.getTransactions().get(0).getExternalKey(), transactionExternalKey); assertEquals(payment.getTransactions().get(0).getPaymentId(), payment.getId()); assertEquals(payment.getTransactions().get(0).getAmount().compareTo(requestedAmount), 0); assertEquals(payment.getTransactions().get(0).getCurrency(), Currency.AED); assertEquals(payment.getTransactions().get(0).getProcessedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getTransactions().get(0).getProcessedCurrency(), Currency.AED); assertEquals(payment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.PLUGIN_FAILURE); assertEquals(payment.getTransactions().get(0).getTransactionType(), TransactionType.PURCHASE); assertNotNull(payment.getTransactions().get(0).getGatewayErrorMsg()); assertNotNull(payment.getTransactions().get(0).getGatewayErrorCode()); final Payment payment2 = paymentApi.createPurchase(account, account.getPaymentMethodId(), null, requestedAmount, Currency.AED, paymentExternalKey, transactionExternalKey, ImmutableList.<PluginProperty>of(), callContext); assertEquals(payment2.getExternalKey(), paymentExternalKey); assertEquals(payment2.getTransactions().get(0).getExternalKey(), transactionExternalKey); assertEquals(payment2.getTransactions().get(0).getTransactionStatus(), TransactionStatus.PLUGIN_FAILURE); assertEquals(payment2.getTransactions().get(0).getTransactionType(), TransactionType.PURCHASE); assertEquals(payment2.getTransactions().get(1).getExternalKey(), transactionExternalKey); assertEquals(payment2.getTransactions().get(1).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment2.getTransactions().get(1).getTransactionType(), TransactionType.PURCHASE); } @Test(groups = "slow") public void testCreatePurchasePaymentPluginException() { mockPaymentProviderPlugin.makeNextPaymentFailWithException(); final BigDecimal requestedAmount = BigDecimal.TEN; final String paymentExternalKey = "pay external key"; final String transactionExternalKey = "txn external key"; try { paymentApi.createPurchase(account, account.getPaymentMethodId(), null, requestedAmount, Currency.AED, paymentExternalKey, transactionExternalKey, ImmutableList.<PluginProperty>of(), callContext); fail(); } catch (PaymentApiException e) { assertTrue(e.getCause() instanceof PaymentPluginApiException); } } @Test(groups = "slow") public void testCreatePurchaseWithControlPaymentPluginException() throws Exception { mockPaymentProviderPlugin.makeNextPaymentFailWithException(); final BigDecimal requestedAmount = BigDecimal.TEN; final String paymentExternalKey = "pay controle external key";; final String transactionExternalKey = "txn control external key"; try { paymentApi.createPurchaseWithPaymentControl( account, account.getPaymentMethodId(), null, requestedAmount, Currency.AED, paymentExternalKey, transactionExternalKey, ImmutableList.<PluginProperty>of(), CONTROL_PLUGIN_OPTIONS, callContext); fail(); } catch (PaymentApiException e) { assertTrue(e.getCause() instanceof PaymentPluginApiException); } } @Test(groups = "slow") public void testCreatePurchaseWithControlPluginException() throws Exception { mockPaymentControlProviderPlugin.throwsException(new PaymentControlApiException()); final BigDecimal requestedAmount = BigDecimal.TEN; final String paymentExternalKey = "pay controle external key";; final String transactionExternalKey = "txn control external key"; try { paymentApi.createPurchaseWithPaymentControl( account, account.getPaymentMethodId(), null, requestedAmount, Currency.AED, paymentExternalKey, transactionExternalKey, ImmutableList.<PluginProperty>of(), CONTROL_PLUGIN_OPTIONS, callContext); fail(); } catch (PaymentApiException e) { assertTrue(e.getCause() instanceof PaymentControlApiException); } } @Test(groups = "slow") public void testCreatePurchaseWithControlPluginRuntimeException() throws Exception { mockPaymentControlProviderPlugin.throwsException(new IllegalStateException()); final BigDecimal requestedAmount = BigDecimal.TEN; final String paymentExternalKey = "pay controle external key";; final String transactionExternalKey = "txn control external key"; try { paymentApi.createPurchaseWithPaymentControl( account, account.getPaymentMethodId(), null, requestedAmount, Currency.AED, paymentExternalKey, transactionExternalKey, ImmutableList.<PluginProperty>of(), CONTROL_PLUGIN_OPTIONS, callContext); fail(); } catch (PaymentApiException e) { assertTrue(e.getCause() instanceof IllegalStateException); } } @Test(groups = "slow") public void testCreateSuccessAuthVoid() throws PaymentApiException { final BigDecimal authAmount = BigDecimal.TEN; final String paymentExternalKey = UUID.randomUUID().toString(); final String transactionExternalKey = UUID.randomUUID().toString(); final String transactionExternalKey2 = UUID.randomUUID().toString(); final Payment payment = paymentApi.createAuthorization(account, account.getPaymentMethodId(), null, authAmount, Currency.AED, paymentExternalKey, transactionExternalKey, ImmutableList.<PluginProperty>of(), callContext); assertEquals(payment.getExternalKey(), paymentExternalKey); assertEquals(payment.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment.getAccountId(), account.getId()); assertEquals(payment.getAuthAmount().compareTo(authAmount), 0); assertEquals(payment.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCurrency(), Currency.AED); assertFalse(payment.isAuthVoided()); assertEquals(payment.getTransactions().size(), 1); assertEquals(payment.getTransactions().get(0).getExternalKey(), transactionExternalKey); assertEquals(payment.getTransactions().get(0).getPaymentId(), payment.getId()); assertEquals(payment.getTransactions().get(0).getAmount().compareTo(authAmount), 0); assertEquals(payment.getTransactions().get(0).getCurrency(), Currency.AED); assertEquals(payment.getTransactions().get(0).getProcessedAmount().compareTo(authAmount), 0); assertEquals(payment.getTransactions().get(0).getProcessedCurrency(), Currency.AED); assertEquals(payment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment.getTransactions().get(0).getTransactionType(), TransactionType.AUTHORIZE); assertNotNull(payment.getTransactions().get(0).getGatewayErrorMsg()); assertNotNull(payment.getTransactions().get(0).getGatewayErrorCode()); // Void the authorization final Payment payment2 = paymentApi.createVoid(account, payment.getId(), transactionExternalKey2, ImmutableList.<PluginProperty>of(), callContext); assertEquals(payment2.getExternalKey(), paymentExternalKey); assertEquals(payment2.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment2.getAccountId(), account.getId()); assertEquals(payment2.getAuthAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment2.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment2.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment2.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment2.getCurrency(), Currency.AED); assertTrue(payment2.isAuthVoided()); assertEquals(payment2.getTransactions().size(), 2); assertEquals(payment2.getTransactions().get(1).getExternalKey(), transactionExternalKey2); assertEquals(payment2.getTransactions().get(1).getPaymentId(), payment.getId()); assertNull(payment2.getTransactions().get(1).getAmount()); assertNull(payment2.getTransactions().get(1).getCurrency()); assertNull(payment2.getTransactions().get(1).getProcessedAmount()); assertNull(payment2.getTransactions().get(1).getProcessedCurrency()); assertEquals(payment2.getTransactions().get(1).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment2.getTransactions().get(1).getTransactionType(), TransactionType.VOID); assertNotNull(payment2.getTransactions().get(1).getGatewayErrorMsg()); assertNotNull(payment2.getTransactions().get(1).getGatewayErrorCode()); } @Test(groups = "slow") public void testCreateSuccessAuthCaptureVoidCapture() throws PaymentApiException { final BigDecimal authAmount = BigDecimal.TEN; final BigDecimal captureAmount = BigDecimal.ONE; final String paymentExternalKey = UUID.randomUUID().toString(); final String transactionExternalKey = UUID.randomUUID().toString(); final String transactionExternalKey2 = UUID.randomUUID().toString(); final String transactionExternalKey3 = UUID.randomUUID().toString(); final String transactionExternalKey4 = UUID.randomUUID().toString(); final Payment payment = paymentApi.createAuthorization(account, account.getPaymentMethodId(), null, authAmount, Currency.AED, paymentExternalKey, transactionExternalKey, ImmutableList.<PluginProperty>of(), callContext); assertEquals(payment.getExternalKey(), paymentExternalKey); assertEquals(payment.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment.getAccountId(), account.getId()); assertEquals(payment.getAuthAmount().compareTo(authAmount), 0); assertEquals(payment.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCurrency(), Currency.AED); assertFalse(payment.isAuthVoided()); assertEquals(payment.getTransactions().size(), 1); assertEquals(payment.getTransactions().get(0).getExternalKey(), transactionExternalKey); assertEquals(payment.getTransactions().get(0).getPaymentId(), payment.getId()); assertEquals(payment.getTransactions().get(0).getAmount().compareTo(authAmount), 0); assertEquals(payment.getTransactions().get(0).getCurrency(), Currency.AED); assertEquals(payment.getTransactions().get(0).getProcessedAmount().compareTo(authAmount), 0); assertEquals(payment.getTransactions().get(0).getProcessedCurrency(), Currency.AED); assertEquals(payment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment.getTransactions().get(0).getTransactionType(), TransactionType.AUTHORIZE); assertNotNull(payment.getTransactions().get(0).getGatewayErrorMsg()); assertNotNull(payment.getTransactions().get(0).getGatewayErrorCode()); final Payment payment2 = paymentApi.createCapture(account, payment.getId(), captureAmount, Currency.AED, transactionExternalKey2, ImmutableList.<PluginProperty>of(), callContext); assertEquals(payment2.getExternalKey(), paymentExternalKey); assertEquals(payment2.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment2.getAccountId(), account.getId()); assertEquals(payment2.getAuthAmount().compareTo(authAmount), 0); assertEquals(payment2.getCapturedAmount().compareTo(captureAmount), 0); assertEquals(payment2.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment2.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment2.getCurrency(), Currency.AED); assertFalse(payment2.isAuthVoided()); assertEquals(payment2.getTransactions().size(), 2); assertEquals(payment2.getTransactions().get(1).getExternalKey(), transactionExternalKey2); assertEquals(payment2.getTransactions().get(1).getPaymentId(), payment.getId()); assertEquals(payment2.getTransactions().get(1).getAmount().compareTo(captureAmount), 0); assertEquals(payment2.getTransactions().get(1).getCurrency(), Currency.AED); assertEquals(payment2.getTransactions().get(1).getProcessedAmount().compareTo(captureAmount), 0); assertEquals(payment2.getTransactions().get(1).getProcessedCurrency(), Currency.AED); assertEquals(payment2.getTransactions().get(1).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment2.getTransactions().get(1).getTransactionType(), TransactionType.CAPTURE); assertNotNull(payment2.getTransactions().get(1).getGatewayErrorMsg()); assertNotNull(payment2.getTransactions().get(1).getGatewayErrorCode()); // Void the capture final Payment payment3 = paymentApi.createVoid(account, payment.getId(), transactionExternalKey3, ImmutableList.<PluginProperty>of(), callContext); assertEquals(payment3.getExternalKey(), paymentExternalKey); assertEquals(payment3.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment3.getAccountId(), account.getId()); assertEquals(payment3.getAuthAmount().compareTo(authAmount), 0); assertEquals(payment3.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment3.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment3.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment3.getCurrency(), Currency.AED); assertFalse(payment3.isAuthVoided()); assertEquals(payment3.getTransactions().size(), 3); assertEquals(payment3.getTransactions().get(2).getExternalKey(), transactionExternalKey3); assertEquals(payment3.getTransactions().get(2).getPaymentId(), payment.getId()); assertNull(payment3.getTransactions().get(2).getAmount()); assertNull(payment3.getTransactions().get(2).getCurrency()); assertNull(payment3.getTransactions().get(2).getProcessedAmount()); assertNull(payment3.getTransactions().get(2).getProcessedCurrency()); assertEquals(payment3.getTransactions().get(2).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment3.getTransactions().get(2).getTransactionType(), TransactionType.VOID); assertNotNull(payment3.getTransactions().get(2).getGatewayErrorMsg()); assertNotNull(payment3.getTransactions().get(2).getGatewayErrorCode()); // Capture again final Payment payment4 = paymentApi.createCapture(account, payment.getId(), captureAmount, Currency.AED, transactionExternalKey4, ImmutableList.<PluginProperty>of(), callContext); assertEquals(payment4.getExternalKey(), paymentExternalKey); assertEquals(payment4.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment4.getAccountId(), account.getId()); assertEquals(payment4.getAuthAmount().compareTo(authAmount), 0); assertEquals(payment4.getCapturedAmount().compareTo(captureAmount), 0); assertEquals(payment4.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment4.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment4.getCurrency(), Currency.AED); assertFalse(payment4.isAuthVoided()); assertEquals(payment4.getTransactions().size(), 4); assertEquals(payment4.getTransactions().get(3).getExternalKey(), transactionExternalKey4); assertEquals(payment4.getTransactions().get(3).getPaymentId(), payment.getId()); assertEquals(payment4.getTransactions().get(3).getAmount().compareTo(captureAmount), 0); assertEquals(payment4.getTransactions().get(3).getCurrency(), Currency.AED); assertEquals(payment4.getTransactions().get(3).getProcessedAmount().compareTo(captureAmount), 0); assertEquals(payment4.getTransactions().get(3).getProcessedCurrency(), Currency.AED); assertEquals(payment4.getTransactions().get(3).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment4.getTransactions().get(3).getTransactionType(), TransactionType.CAPTURE); assertNotNull(payment4.getTransactions().get(3).getGatewayErrorMsg()); assertNotNull(payment4.getTransactions().get(3).getGatewayErrorCode()); } @Test(groups = "slow") public void testCreateSuccessAuthCaptureVoidVoid() throws PaymentApiException { final BigDecimal authAmount = BigDecimal.TEN; final BigDecimal captureAmount = BigDecimal.ONE; final String paymentExternalKey = UUID.randomUUID().toString(); final String transactionExternalKey = UUID.randomUUID().toString(); final String transactionExternalKey2 = UUID.randomUUID().toString(); final String transactionExternalKey3 = UUID.randomUUID().toString(); final String transactionExternalKey4 = UUID.randomUUID().toString(); final Payment payment = paymentApi.createAuthorization(account, account.getPaymentMethodId(), null, authAmount, Currency.AED, paymentExternalKey, transactionExternalKey, ImmutableList.<PluginProperty>of(), callContext); assertEquals(payment.getExternalKey(), paymentExternalKey); assertEquals(payment.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment.getAccountId(), account.getId()); assertEquals(payment.getAuthAmount().compareTo(authAmount), 0); assertEquals(payment.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCurrency(), Currency.AED); assertFalse(payment.isAuthVoided()); assertEquals(payment.getTransactions().size(), 1); assertEquals(payment.getTransactions().get(0).getExternalKey(), transactionExternalKey); assertEquals(payment.getTransactions().get(0).getPaymentId(), payment.getId()); assertEquals(payment.getTransactions().get(0).getAmount().compareTo(authAmount), 0); assertEquals(payment.getTransactions().get(0).getCurrency(), Currency.AED); assertEquals(payment.getTransactions().get(0).getProcessedAmount().compareTo(authAmount), 0); assertEquals(payment.getTransactions().get(0).getProcessedCurrency(), Currency.AED); assertEquals(payment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment.getTransactions().get(0).getTransactionType(), TransactionType.AUTHORIZE); assertNotNull(payment.getTransactions().get(0).getGatewayErrorMsg()); assertNotNull(payment.getTransactions().get(0).getGatewayErrorCode()); final Payment payment2 = paymentApi.createCapture(account, payment.getId(), captureAmount, Currency.AED, transactionExternalKey2, ImmutableList.<PluginProperty>of(), callContext); assertEquals(payment2.getExternalKey(), paymentExternalKey); assertEquals(payment2.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment2.getAccountId(), account.getId()); assertEquals(payment2.getAuthAmount().compareTo(authAmount), 0); assertEquals(payment2.getCapturedAmount().compareTo(captureAmount), 0); assertEquals(payment2.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment2.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment2.getCurrency(), Currency.AED); assertFalse(payment2.isAuthVoided()); assertEquals(payment2.getTransactions().size(), 2); assertEquals(payment2.getTransactions().get(1).getExternalKey(), transactionExternalKey2); assertEquals(payment2.getTransactions().get(1).getPaymentId(), payment.getId()); assertEquals(payment2.getTransactions().get(1).getAmount().compareTo(captureAmount), 0); assertEquals(payment2.getTransactions().get(1).getCurrency(), Currency.AED); assertEquals(payment2.getTransactions().get(1).getProcessedAmount().compareTo(captureAmount), 0); assertEquals(payment2.getTransactions().get(1).getProcessedCurrency(), Currency.AED); assertEquals(payment2.getTransactions().get(1).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment2.getTransactions().get(1).getTransactionType(), TransactionType.CAPTURE); assertNotNull(payment2.getTransactions().get(1).getGatewayErrorMsg()); assertNotNull(payment2.getTransactions().get(1).getGatewayErrorCode()); // Void the capture final Payment payment3 = paymentApi.createVoid(account, payment.getId(), transactionExternalKey3, ImmutableList.<PluginProperty>of(), callContext); assertEquals(payment3.getExternalKey(), paymentExternalKey); assertEquals(payment3.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment3.getAccountId(), account.getId()); assertEquals(payment3.getAuthAmount().compareTo(authAmount), 0); assertEquals(payment3.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment3.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment3.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment3.getCurrency(), Currency.AED); assertFalse(payment3.isAuthVoided()); assertEquals(payment3.getTransactions().size(), 3); assertEquals(payment3.getTransactions().get(2).getExternalKey(), transactionExternalKey3); assertEquals(payment3.getTransactions().get(2).getPaymentId(), payment.getId()); assertNull(payment3.getTransactions().get(2).getAmount()); assertNull(payment3.getTransactions().get(2).getCurrency()); assertNull(payment3.getTransactions().get(2).getProcessedAmount()); assertNull(payment3.getTransactions().get(2).getProcessedCurrency()); assertEquals(payment3.getTransactions().get(2).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment3.getTransactions().get(2).getTransactionType(), TransactionType.VOID); assertNotNull(payment3.getTransactions().get(2).getGatewayErrorMsg()); assertNotNull(payment3.getTransactions().get(2).getGatewayErrorCode()); // Void the authorization final Payment payment4 = paymentApi.createVoid(account, payment.getId(), transactionExternalKey4, ImmutableList.<PluginProperty>of(), callContext); assertEquals(payment4.getExternalKey(), paymentExternalKey); assertEquals(payment4.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment4.getAccountId(), account.getId()); assertEquals(payment4.getAuthAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment4.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment4.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment4.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment4.getCurrency(), Currency.AED); assertTrue(payment4.isAuthVoided()); assertEquals(payment4.getTransactions().size(), 4); assertEquals(payment4.getTransactions().get(3).getExternalKey(), transactionExternalKey4); assertEquals(payment4.getTransactions().get(3).getPaymentId(), payment.getId()); assertNull(payment4.getTransactions().get(3).getAmount()); assertNull(payment4.getTransactions().get(3).getCurrency()); assertNull(payment4.getTransactions().get(3).getProcessedAmount()); assertNull(payment4.getTransactions().get(3).getProcessedCurrency()); assertEquals(payment4.getTransactions().get(3).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment4.getTransactions().get(3).getTransactionType(), TransactionType.VOID); assertNotNull(payment4.getTransactions().get(3).getGatewayErrorMsg()); assertNotNull(payment4.getTransactions().get(3).getGatewayErrorCode()); } @Test(groups = "slow") public void testCreateSuccessAuthMultipleCaptureAndRefund() throws PaymentApiException { final BigDecimal authAmount = BigDecimal.TEN; final BigDecimal captureAmount = BigDecimal.ONE; final String paymentExternalKey = "courou"; final String transactionExternalKey = "sioux"; final String transactionExternalKey2 = "sioux2"; final String transactionExternalKey3 = "sioux3"; final String transactionExternalKey4 = "sioux4"; final Payment payment = paymentApi.createAuthorization(account, account.getPaymentMethodId(), null, authAmount, Currency.USD, paymentExternalKey, transactionExternalKey, ImmutableList.<PluginProperty>of(), callContext); paymentApi.createCapture(account, payment.getId(), captureAmount, Currency.USD, transactionExternalKey2, ImmutableList.<PluginProperty>of(), callContext); final Payment payment3 = paymentApi.createCapture(account, payment.getId(), captureAmount, Currency.USD, transactionExternalKey3, ImmutableList.<PluginProperty>of(), callContext); assertEquals(payment3.getExternalKey(), paymentExternalKey); assertEquals(payment3.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment3.getAccountId(), account.getId()); assertEquals(payment3.getAuthAmount().compareTo(authAmount), 0); assertEquals(payment3.getCapturedAmount().compareTo(captureAmount.add(captureAmount)), 0); assertEquals(payment3.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment3.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment3.getCurrency(), Currency.USD); assertEquals(payment3.getTransactions().size(), 3); final Payment payment4 = paymentApi.createRefund(account, payment3.getId(), payment3.getCapturedAmount(), Currency.USD, transactionExternalKey4, ImmutableList.<PluginProperty>of(), callContext); assertEquals(payment4.getAuthAmount().compareTo(authAmount), 0); assertEquals(payment4.getCapturedAmount().compareTo(captureAmount.add(captureAmount)), 0); assertEquals(payment4.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment4.getRefundedAmount().compareTo(payment3.getCapturedAmount()), 0); assertEquals(payment4.getTransactions().size(), 4); assertEquals(payment4.getTransactions().get(3).getExternalKey(), transactionExternalKey4); assertEquals(payment4.getTransactions().get(3).getPaymentId(), payment.getId()); assertEquals(payment4.getTransactions().get(3).getAmount().compareTo(payment3.getCapturedAmount()), 0); assertEquals(payment4.getTransactions().get(3).getCurrency(), Currency.USD); assertEquals(payment4.getTransactions().get(3).getProcessedAmount().compareTo(payment3.getCapturedAmount()), 0); assertEquals(payment4.getTransactions().get(3).getProcessedCurrency(), Currency.USD); assertEquals(payment4.getTransactions().get(3).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment4.getTransactions().get(3).getTransactionType(), TransactionType.REFUND); assertNotNull(payment4.getTransactions().get(3).getGatewayErrorMsg()); assertNotNull(payment4.getTransactions().get(3).getGatewayErrorCode()); } @Test(groups = "slow") public void testCreateSuccessPurchaseWithPaymentControl() throws PaymentApiException, InvoiceApiException, EventBusException { final BigDecimal requestedAmount = BigDecimal.TEN; final UUID subscriptionId = UUID.randomUUID(); final UUID bundleId = UUID.randomUUID(); final LocalDate now = clock.getUTCToday(); final Invoice invoice = testHelper.createTestInvoice(account, now, Currency.USD); final String paymentExternalKey = invoice.getId().toString(); final String transactionExternalKey = "brrrrrr"; invoice.addInvoiceItem(new MockRecurringInvoiceItem(invoice.getId(), account.getId(), subscriptionId, bundleId, "test plan", "test phase", null, now, now.plusMonths(1), requestedAmount, new BigDecimal("1.0"), Currency.USD)); final Payment payment = paymentApi.createPurchaseWithPaymentControl(account, account.getPaymentMethodId(), null, requestedAmount, Currency.USD, paymentExternalKey, transactionExternalKey, createPropertiesForInvoice(invoice), INVOICE_PAYMENT, callContext); assertEquals(payment.getExternalKey(), paymentExternalKey); assertEquals(payment.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment.getAccountId(), account.getId()); assertEquals(payment.getAuthAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getPurchasedAmount().compareTo(requestedAmount), 0); assertEquals(payment.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCurrency(), Currency.USD); assertEquals(payment.getTransactions().size(), 1); assertEquals(payment.getTransactions().get(0).getExternalKey(), transactionExternalKey); assertEquals(payment.getTransactions().get(0).getPaymentId(), payment.getId()); assertEquals(payment.getTransactions().get(0).getAmount().compareTo(requestedAmount), 0); assertEquals(payment.getTransactions().get(0).getCurrency(), Currency.USD); assertEquals(payment.getTransactions().get(0).getProcessedAmount().compareTo(requestedAmount), 0); assertEquals(payment.getTransactions().get(0).getProcessedCurrency(), Currency.USD); assertEquals(payment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment.getTransactions().get(0).getTransactionType(), TransactionType.PURCHASE); assertNotNull(payment.getTransactions().get(0).getGatewayErrorMsg()); assertNotNull(payment.getTransactions().get(0).getGatewayErrorCode()); // Not stricly an API test but interesting to verify that we indeed went through the attempt logic final List<PaymentAttemptModelDao> attempts = paymentDao.getPaymentAttempts(payment.getExternalKey(), internalCallContext); assertEquals(attempts.size(), 1); } @Test(groups = "slow") public void testCreateFailedPurchaseWithPaymentControl() throws PaymentApiException, InvoiceApiException, EventBusException { final BigDecimal requestedAmount = BigDecimal.TEN; final UUID subscriptionId = UUID.randomUUID(); final UUID bundleId = UUID.randomUUID(); final LocalDate now = clock.getUTCToday(); final Invoice invoice = testHelper.createTestInvoice(account, now, Currency.USD); final String paymentExternalKey = invoice.getId().toString(); final String transactionExternalKey = "brrrrrr"; mockPaymentProviderPlugin.makeNextPaymentFailWithError(); invoice.addInvoiceItem(new MockRecurringInvoiceItem(invoice.getId(), account.getId(), subscriptionId, bundleId, "test plan", "test phase", null, now, now.plusMonths(1), requestedAmount, new BigDecimal("1.0"), Currency.USD)); try { paymentApi.createPurchaseWithPaymentControl(account, account.getPaymentMethodId(), null, requestedAmount, Currency.USD, paymentExternalKey, transactionExternalKey, createPropertiesForInvoice(invoice), INVOICE_PAYMENT, callContext); } catch (final PaymentApiException expected) { assertTrue(true); } final List<Payment> accountPayments = paymentApi.getAccountPayments(account.getId(), false, ImmutableList.<PluginProperty>of(), callContext); assertEquals(accountPayments.size(), 1); final Payment payment = accountPayments.get(0); assertEquals(payment.getExternalKey(), paymentExternalKey); assertEquals(payment.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment.getAccountId(), account.getId()); assertEquals(payment.getAuthAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCurrency(), Currency.USD); assertEquals(payment.getTransactions().size(), 1); assertEquals(payment.getTransactions().get(0).getExternalKey(), transactionExternalKey); assertEquals(payment.getTransactions().get(0).getPaymentId(), payment.getId()); assertEquals(payment.getTransactions().get(0).getAmount().compareTo(requestedAmount), 0); assertEquals(payment.getTransactions().get(0).getCurrency(), Currency.USD); assertEquals(payment.getTransactions().get(0).getProcessedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getTransactions().get(0).getProcessedCurrency(), Currency.USD); assertEquals(payment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.PAYMENT_FAILURE); assertEquals(payment.getTransactions().get(0).getTransactionType(), TransactionType.PURCHASE); } @Test(groups = "slow") public void testCreateCancelledPurchaseWithPaymentControl() throws PaymentApiException, InvoiceApiException, EventBusException { final BigDecimal requestedAmount = BigDecimal.TEN; final UUID subscriptionId = UUID.randomUUID(); final UUID bundleId = UUID.randomUUID(); final LocalDate now = clock.getUTCToday(); final Invoice invoice = testHelper.createTestInvoice(account, now, Currency.USD); final String paymentExternalKey = invoice.getId().toString(); final String transactionExternalKey = "hgjhgjgjhg33"; mockPaymentProviderPlugin.makeNextPaymentFailWithCancellation(); invoice.addInvoiceItem(new MockRecurringInvoiceItem(invoice.getId(), account.getId(), subscriptionId, bundleId, "test plan", "test phase", null, now, now.plusMonths(1), requestedAmount, new BigDecimal("1.0"), Currency.USD)); try { paymentApi.createPurchaseWithPaymentControl(account, account.getPaymentMethodId(), null, requestedAmount, Currency.USD, paymentExternalKey, transactionExternalKey, createPropertiesForInvoice(invoice), INVOICE_PAYMENT, callContext); } catch (final PaymentApiException expected) { assertTrue(true); } final List<Payment> accountPayments = paymentApi.getAccountPayments(account.getId(), false, ImmutableList.<PluginProperty>of(), callContext); assertEquals(accountPayments.size(), 1); final Payment payment = accountPayments.get(0); assertEquals(payment.getExternalKey(), paymentExternalKey); assertEquals(payment.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment.getAccountId(), account.getId()); assertEquals(payment.getAuthAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCurrency(), Currency.USD); assertEquals(payment.getTransactions().size(), 1); assertEquals(payment.getTransactions().get(0).getExternalKey(), transactionExternalKey); assertEquals(payment.getTransactions().get(0).getPaymentId(), payment.getId()); assertEquals(payment.getTransactions().get(0).getAmount().compareTo(requestedAmount), 0); assertEquals(payment.getTransactions().get(0).getCurrency(), Currency.USD); assertEquals(payment.getTransactions().get(0).getProcessedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getTransactions().get(0).getProcessedCurrency(), Currency.USD); assertEquals(payment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.PLUGIN_FAILURE); assertEquals(payment.getTransactions().get(0).getTransactionType(), TransactionType.PURCHASE); // Make sure we can retry and that works paymentApi.createPurchaseWithPaymentControl(account, account.getPaymentMethodId(), null, requestedAmount, Currency.USD, paymentExternalKey, transactionExternalKey, createPropertiesForInvoice(invoice), INVOICE_PAYMENT, callContext); final List<Payment> accountPayments2 = paymentApi.getAccountPayments(account.getId(), false, ImmutableList.<PluginProperty>of(), callContext); assertEquals(accountPayments2.size(), 1); final Payment payment2 = accountPayments2.get(0); assertEquals(payment2.getTransactions().size(), 2); assertEquals(payment2.getTransactions().get(0).getExternalKey(), transactionExternalKey); assertEquals(payment2.getTransactions().get(0).getTransactionStatus(), TransactionStatus.PLUGIN_FAILURE); assertEquals(payment2.getTransactions().get(0).getTransactionType(), TransactionType.PURCHASE); assertEquals(payment2.getTransactions().get(1).getExternalKey(), transactionExternalKey); assertEquals(payment2.getTransactions().get(1).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment2.getTransactions().get(1).getTransactionType(), TransactionType.PURCHASE); } @Test(groups = "slow") public void testCreateAbortedPurchaseWithPaymentControl() throws InvoiceApiException, EventBusException { final BigDecimal requestedAmount = BigDecimal.TEN; final UUID subscriptionId = UUID.randomUUID(); final UUID bundleId = UUID.randomUUID(); final LocalDate now = clock.getUTCToday(); final Invoice invoice = testHelper.createTestInvoice(account, now, Currency.USD); final String paymentExternalKey = invoice.getId().toString(); final String transactionExternalKey = "brrrrrr"; invoice.addInvoiceItem(new MockRecurringInvoiceItem(invoice.getId(), account.getId(), subscriptionId, bundleId, "test plan", "test phase", null, now, now.plusMonths(1), BigDecimal.ONE, new BigDecimal("1.0"), Currency.USD)); try { paymentApi.createPurchaseWithPaymentControl(account, account.getPaymentMethodId(), null, requestedAmount, Currency.USD, paymentExternalKey, transactionExternalKey, createPropertiesForInvoice(invoice), INVOICE_PAYMENT, callContext); Assert.fail("Unexpected success"); } catch (final PaymentApiException e) { } } @Test(groups = "slow") public void testCreateSuccessRefundWithPaymentControl() throws PaymentApiException, InvoiceApiException, EventBusException { final BigDecimal requestedAmount = BigDecimal.TEN; final UUID subscriptionId = UUID.randomUUID(); final UUID bundleId = UUID.randomUUID(); final LocalDate now = clock.getUTCToday(); final Invoice invoice = testHelper.createTestInvoice(account, now, Currency.USD); final String paymentExternalKey = invoice.getId().toString(); final String transactionExternalKey = "sacrebleu"; final String transactionExternalKey2 = "maisenfin"; final InvoiceItem invoiceItem = new MockRecurringInvoiceItem(invoice.getId(), account.getId(), subscriptionId, bundleId, "test plan", "test phase", null, now, now.plusMonths(1), requestedAmount, new BigDecimal("1.0"), Currency.USD); invoice.addInvoiceItem(invoiceItem); final Payment payment = paymentApi.createPurchaseWithPaymentControl(account, account.getPaymentMethodId(), null, requestedAmount, Currency.USD, paymentExternalKey, transactionExternalKey, createPropertiesForInvoice(invoice), INVOICE_PAYMENT, callContext); final List<PluginProperty> refundProperties = ImmutableList.<PluginProperty>of(); final Payment payment2 = paymentApi.createRefundWithPaymentControl(account, payment.getId(), requestedAmount, Currency.USD, transactionExternalKey2, refundProperties, INVOICE_PAYMENT, callContext); assertEquals(payment2.getTransactions().size(), 2); assertEquals(payment2.getExternalKey(), paymentExternalKey); assertEquals(payment2.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment2.getAccountId(), account.getId()); assertEquals(payment2.getAuthAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment2.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment2.getPurchasedAmount().compareTo(requestedAmount), 0); assertEquals(payment2.getRefundedAmount().compareTo(requestedAmount), 0); assertEquals(payment2.getCurrency(), Currency.USD); } @Test(groups = "slow") public void testCreateAbortedRefundWithPaymentControl() throws PaymentApiException, InvoiceApiException, EventBusException { final BigDecimal requestedAmount = BigDecimal.ONE; final UUID subscriptionId = UUID.randomUUID(); final UUID bundleId = UUID.randomUUID(); final LocalDate now = clock.getUTCToday(); final Invoice invoice = testHelper.createTestInvoice(account, now, Currency.USD); final String paymentExternalKey = invoice.getId().toString(); final String transactionExternalKey = "payment"; final String transactionExternalKey2 = "refund"; final InvoiceItem invoiceItem = new MockRecurringInvoiceItem(invoice.getId(), account.getId(), subscriptionId, bundleId, "test plan", "test phase", null, now, now.plusMonths(1), requestedAmount, new BigDecimal("1.0"), Currency.USD); invoice.addInvoiceItem(invoiceItem); final Payment payment = paymentApi.createPurchaseWithPaymentControl(account, account.getPaymentMethodId(), null, requestedAmount, Currency.USD, paymentExternalKey, transactionExternalKey, createPropertiesForInvoice(invoice), INVOICE_PAYMENT, callContext); final List<PluginProperty> refundProperties = ImmutableList.<PluginProperty>of(); try { paymentApi.createRefundWithPaymentControl(account, payment.getId(), BigDecimal.TEN, Currency.USD, transactionExternalKey2, refundProperties, INVOICE_PAYMENT, callContext); } catch (final PaymentApiException e) { assertTrue(e.getCause() instanceof PaymentControlApiException); } } @Test(groups = "slow") public void testCreateSuccessRefundPaymentControlWithItemAdjustments() throws PaymentApiException, InvoiceApiException, EventBusException { final BigDecimal requestedAmount = BigDecimal.TEN; final UUID subscriptionId = UUID.randomUUID(); final UUID bundleId = UUID.randomUUID(); final LocalDate now = clock.getUTCToday(); final Invoice invoice = testHelper.createTestInvoice(account, now, Currency.USD); final String paymentExternalKey = invoice.getId().toString(); final String transactionExternalKey = "hopla"; final String transactionExternalKey2 = "chouette"; final InvoiceItem invoiceItem = new MockRecurringInvoiceItem(invoice.getId(), account.getId(), subscriptionId, bundleId, "test plan", "test phase", null, now, now.plusMonths(1), requestedAmount, new BigDecimal("1.0"), Currency.USD); invoice.addInvoiceItem(invoiceItem); final Payment payment = paymentApi.createPurchaseWithPaymentControl(account, account.getPaymentMethodId(), null, requestedAmount, Currency.USD, paymentExternalKey, transactionExternalKey, createPropertiesForInvoice(invoice), INVOICE_PAYMENT, callContext); final List<PluginProperty> refundProperties = new ArrayList<PluginProperty>(); final HashMap<UUID, BigDecimal> uuidBigDecimalHashMap = new HashMap<UUID, BigDecimal>(); uuidBigDecimalHashMap.put(invoiceItem.getId(), null); final PluginProperty refundIdsProp = new PluginProperty(InvoicePaymentControlPluginApi.PROP_IPCD_REFUND_IDS_WITH_AMOUNT_KEY, uuidBigDecimalHashMap, false); refundProperties.add(refundIdsProp); final Payment payment2 = paymentApi.createRefundWithPaymentControl(account, payment.getId(), null, Currency.USD, transactionExternalKey2, refundProperties, INVOICE_PAYMENT, callContext); assertEquals(payment2.getTransactions().size(), 2); assertEquals(payment2.getExternalKey(), paymentExternalKey); assertEquals(payment2.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment2.getAccountId(), account.getId()); assertEquals(payment2.getAuthAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment2.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment2.getPurchasedAmount().compareTo(requestedAmount), 0); assertEquals(payment2.getRefundedAmount().compareTo(requestedAmount), 0); assertEquals(payment2.getCurrency(), Currency.USD); } @Test(groups = "slow", description = "https://github.com/killbill/killbill/issues/477") public void testCreateChargeback() throws PaymentApiException { // API change in 0.17 final DefaultPaymentApi paymentApi = (DefaultPaymentApi) this.paymentApi; final BigDecimal requestedAmount = BigDecimal.TEN; final Currency currency = Currency.AED; final String paymentExternalKey = UUID.randomUUID().toString(); final String purchaseTransactionExternalKey = UUID.randomUUID().toString(); final String chargebackTransactionExternalKey = UUID.randomUUID().toString(); final ImmutableList<PluginProperty> properties = ImmutableList.<PluginProperty>of(); final Payment payment = paymentApi.createPurchase(account, account.getPaymentMethodId(), null, requestedAmount, currency, paymentExternalKey, purchaseTransactionExternalKey, properties, callContext); assertEquals(payment.getExternalKey(), paymentExternalKey); assertEquals(payment.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment.getAccountId(), account.getId()); assertEquals(payment.getAuthAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getPurchasedAmount().compareTo(requestedAmount), 0); assertEquals(payment.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCurrency(), currency); assertEquals(payment.getTransactions().size(), 1); assertEquals(payment.getTransactions().get(0).getExternalKey(), purchaseTransactionExternalKey); assertEquals(payment.getTransactions().get(0).getPaymentId(), payment.getId()); assertEquals(payment.getTransactions().get(0).getAmount().compareTo(requestedAmount), 0); assertEquals(payment.getTransactions().get(0).getCurrency(), currency); assertEquals(payment.getTransactions().get(0).getProcessedAmount().compareTo(requestedAmount), 0); assertEquals(payment.getTransactions().get(0).getProcessedCurrency(), currency); assertEquals(payment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment.getTransactions().get(0).getTransactionType(), TransactionType.PURCHASE); assertEquals(payment.getTransactions().get(0).getGatewayErrorMsg(), ""); assertEquals(payment.getTransactions().get(0).getGatewayErrorCode(), ""); assertEquals(paymentDao.getPayment(payment.getId(), internalCallContext).getStateName(), "PURCHASE_SUCCESS"); assertEquals(paymentDao.getPayment(payment.getId(), internalCallContext).getLastSuccessStateName(), "PURCHASE_SUCCESS"); // First chargeback final Payment payment2 = paymentApi.createChargeback(account, payment.getId(), requestedAmount, currency, chargebackTransactionExternalKey, callContext); assertEquals(payment2.getExternalKey(), paymentExternalKey); assertEquals(payment2.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment2.getAccountId(), account.getId()); assertEquals(payment2.getAuthAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment2.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); // Purchase amount zero-ed out assertEquals(payment2.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment2.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment2.getCurrency(), currency); assertEquals(payment2.getTransactions().size(), 2); assertEquals(payment2.getTransactions().get(1).getExternalKey(), chargebackTransactionExternalKey); assertEquals(payment2.getTransactions().get(1).getPaymentId(), payment.getId()); assertEquals(payment2.getTransactions().get(1).getAmount().compareTo(requestedAmount), 0); assertEquals(payment2.getTransactions().get(1).getCurrency(), currency); assertEquals(payment2.getTransactions().get(1).getProcessedAmount().compareTo(requestedAmount), 0); assertEquals(payment2.getTransactions().get(1).getProcessedCurrency(), currency); assertEquals(payment2.getTransactions().get(1).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment2.getTransactions().get(1).getTransactionType(), TransactionType.CHARGEBACK); assertNull(payment2.getTransactions().get(1).getGatewayErrorMsg()); assertNull(payment2.getTransactions().get(1).getGatewayErrorCode()); assertEquals(paymentDao.getPayment(payment.getId(), internalCallContext).getStateName(), "CHARGEBACK_SUCCESS"); assertEquals(paymentDao.getPayment(payment.getId(), internalCallContext).getLastSuccessStateName(), "CHARGEBACK_SUCCESS"); try { paymentApi.createRefund(account, payment.getId(), requestedAmount, currency, UUID.randomUUID().toString(), properties, callContext); Assert.fail("Refunds are no longer permitted after a chargeback"); } catch (final PaymentApiException e) { assertEquals(e.getCode(), ErrorCode.PAYMENT_INVALID_OPERATION.getCode()); } // First reversal final Payment payment3 = paymentApi.createChargebackReversal(account, payment.getId(), chargebackTransactionExternalKey, callContext); assertEquals(payment3.getExternalKey(), paymentExternalKey); assertEquals(payment3.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment3.getAccountId(), account.getId()); assertEquals(payment3.getAuthAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment3.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); // Actual purchase amount assertEquals(payment3.getPurchasedAmount().compareTo(requestedAmount), 0); assertEquals(payment3.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment3.getCurrency(), currency); assertEquals(payment3.getTransactions().size(), 3); assertEquals(payment3.getTransactions().get(2).getExternalKey(), chargebackTransactionExternalKey); assertEquals(payment3.getTransactions().get(2).getPaymentId(), payment.getId()); assertNull(payment3.getTransactions().get(2).getAmount()); assertNull(payment3.getTransactions().get(2).getCurrency()); assertEquals(payment3.getTransactions().get(2).getProcessedAmount().compareTo(BigDecimal.ZERO), 0); assertNull(payment3.getTransactions().get(2).getProcessedCurrency()); assertEquals(payment3.getTransactions().get(2).getTransactionStatus(), TransactionStatus.PAYMENT_FAILURE); assertEquals(payment3.getTransactions().get(2).getTransactionType(), TransactionType.CHARGEBACK); assertNull(payment3.getTransactions().get(2).getGatewayErrorMsg()); assertNull(payment3.getTransactions().get(2).getGatewayErrorCode()); assertEquals(paymentDao.getPayment(payment.getId(), internalCallContext).getStateName(), "CHARGEBACK_FAILED"); assertEquals(paymentDao.getPayment(payment.getId(), internalCallContext).getLastSuccessStateName(), "CHARGEBACK_FAILED"); // Attempt a refund final BigDecimal refundAmount = BigDecimal.ONE; final String refundTransactionExternalKey = UUID.randomUUID().toString(); final Payment payment4 = paymentApi.createRefund(account, payment.getId(), refundAmount, currency, refundTransactionExternalKey, properties, callContext); assertEquals(payment4.getExternalKey(), paymentExternalKey); assertEquals(payment4.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment4.getAccountId(), account.getId()); assertEquals(payment4.getAuthAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment4.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); // Actual purchase amount assertEquals(payment4.getPurchasedAmount().compareTo(requestedAmount), 0); assertEquals(payment4.getRefundedAmount().compareTo(refundAmount), 0); assertEquals(payment4.getCurrency(), currency); assertEquals(payment4.getTransactions().size(), 4); assertEquals(payment4.getTransactions().get(3).getExternalKey(), refundTransactionExternalKey); assertEquals(payment4.getTransactions().get(3).getPaymentId(), payment.getId()); assertEquals(payment4.getTransactions().get(3).getAmount().compareTo(refundAmount), 0); assertEquals(payment4.getTransactions().get(3).getCurrency(), currency); assertEquals(payment4.getTransactions().get(3).getProcessedAmount().compareTo(refundAmount), 0); assertEquals(payment4.getTransactions().get(3).getProcessedCurrency(), currency); assertEquals(payment4.getTransactions().get(3).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment4.getTransactions().get(3).getTransactionType(), TransactionType.REFUND); assertEquals(payment4.getTransactions().get(3).getGatewayErrorMsg(), ""); assertEquals(payment4.getTransactions().get(3).getGatewayErrorCode(), ""); assertEquals(paymentDao.getPayment(payment.getId(), internalCallContext).getStateName(), "REFUND_SUCCESS"); assertEquals(paymentDao.getPayment(payment.getId(), internalCallContext).getLastSuccessStateName(), "REFUND_SUCCESS"); // Second chargeback final BigDecimal secondChargebackAmount = requestedAmount.add(refundAmount.negate()); final Payment payment5 = paymentApi.createChargeback(account, payment.getId(), secondChargebackAmount, currency, chargebackTransactionExternalKey, callContext); assertEquals(payment5.getExternalKey(), paymentExternalKey); assertEquals(payment5.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment5.getAccountId(), account.getId()); assertEquals(payment5.getAuthAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment5.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); // Purchase amount zero-ed out assertEquals(payment5.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment5.getRefundedAmount().compareTo(refundAmount), 0); assertEquals(payment5.getCurrency(), currency); assertEquals(payment5.getTransactions().size(), 5); assertEquals(payment5.getTransactions().get(4).getExternalKey(), chargebackTransactionExternalKey); assertEquals(payment5.getTransactions().get(4).getPaymentId(), payment.getId()); assertEquals(payment5.getTransactions().get(4).getAmount().compareTo(secondChargebackAmount), 0); assertEquals(payment5.getTransactions().get(4).getCurrency(), currency); assertEquals(payment5.getTransactions().get(4).getProcessedAmount().compareTo(secondChargebackAmount), 0); assertEquals(payment5.getTransactions().get(4).getProcessedCurrency(), currency); assertEquals(payment5.getTransactions().get(4).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment5.getTransactions().get(4).getTransactionType(), TransactionType.CHARGEBACK); assertNull(payment5.getTransactions().get(4).getGatewayErrorMsg()); assertNull(payment5.getTransactions().get(4).getGatewayErrorCode()); assertEquals(paymentDao.getPayment(payment.getId(), internalCallContext).getStateName(), "CHARGEBACK_SUCCESS"); assertEquals(paymentDao.getPayment(payment.getId(), internalCallContext).getLastSuccessStateName(), "CHARGEBACK_SUCCESS"); try { paymentApi.createRefund(account, payment.getId(), refundAmount, currency, UUID.randomUUID().toString(), properties, callContext); Assert.fail("Refunds are no longer permitted after a chargeback"); } catch (final PaymentApiException e) { assertEquals(e.getCode(), ErrorCode.PAYMENT_INVALID_OPERATION.getCode()); } // Second reversal final Payment payment6 = paymentApi.createChargebackReversal(account, payment.getId(), chargebackTransactionExternalKey, callContext); assertEquals(payment6.getExternalKey(), paymentExternalKey); assertEquals(payment6.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment6.getAccountId(), account.getId()); assertEquals(payment6.getAuthAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment6.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); // Actual purchase amount assertEquals(payment6.getPurchasedAmount().compareTo(requestedAmount), 0); assertEquals(payment6.getRefundedAmount().compareTo(refundAmount), 0); assertEquals(payment6.getCurrency(), currency); assertEquals(payment6.getTransactions().size(), 6); assertEquals(payment6.getTransactions().get(5).getExternalKey(), chargebackTransactionExternalKey); assertEquals(payment6.getTransactions().get(5).getPaymentId(), payment.getId()); assertNull(payment6.getTransactions().get(5).getAmount()); assertNull(payment6.getTransactions().get(5).getCurrency()); assertEquals(payment6.getTransactions().get(5).getProcessedAmount().compareTo(BigDecimal.ZERO), 0); assertNull(payment6.getTransactions().get(5).getProcessedCurrency()); assertEquals(payment6.getTransactions().get(5).getTransactionStatus(), TransactionStatus.PAYMENT_FAILURE); assertEquals(payment6.getTransactions().get(5).getTransactionType(), TransactionType.CHARGEBACK); assertNull(payment6.getTransactions().get(5).getGatewayErrorMsg()); assertNull(payment6.getTransactions().get(5).getGatewayErrorCode()); assertEquals(paymentDao.getPayment(payment.getId(), internalCallContext).getStateName(), "CHARGEBACK_FAILED"); assertEquals(paymentDao.getPayment(payment.getId(), internalCallContext).getLastSuccessStateName(), "CHARGEBACK_FAILED"); } @Test(groups = "slow") public void testCreateChargebackReversalBeforeChargeback() throws PaymentApiException { // API change in 0.17 final DefaultPaymentApi paymentApi = (DefaultPaymentApi) this.paymentApi; final BigDecimal requestedAmount = BigDecimal.TEN; final Currency currency = Currency.AED; final String paymentExternalKey = UUID.randomUUID().toString(); final String purchaseTransactionExternalKey = UUID.randomUUID().toString(); final String chargebackTransactionExternalKey = UUID.randomUUID().toString(); final ImmutableList<PluginProperty> properties = ImmutableList.<PluginProperty>of(); final Payment payment = paymentApi.createPurchase(account, account.getPaymentMethodId(), null, requestedAmount, currency, paymentExternalKey, purchaseTransactionExternalKey, properties, callContext); assertEquals(payment.getExternalKey(), paymentExternalKey); assertEquals(payment.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment.getAccountId(), account.getId()); assertEquals(payment.getAuthAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getPurchasedAmount().compareTo(requestedAmount), 0); assertEquals(payment.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCurrency(), currency); assertEquals(payment.getTransactions().size(), 1); assertEquals(payment.getTransactions().get(0).getExternalKey(), purchaseTransactionExternalKey); assertEquals(payment.getTransactions().get(0).getPaymentId(), payment.getId()); assertEquals(payment.getTransactions().get(0).getAmount().compareTo(requestedAmount), 0); assertEquals(payment.getTransactions().get(0).getCurrency(), currency); assertEquals(payment.getTransactions().get(0).getProcessedAmount().compareTo(requestedAmount), 0); assertEquals(payment.getTransactions().get(0).getProcessedCurrency(), currency); assertEquals(payment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment.getTransactions().get(0).getTransactionType(), TransactionType.PURCHASE); assertEquals(payment.getTransactions().get(0).getGatewayErrorMsg(), ""); assertEquals(payment.getTransactions().get(0).getGatewayErrorCode(), ""); assertEquals(paymentDao.getPayment(payment.getId(), internalCallContext).getStateName(), "PURCHASE_SUCCESS"); assertEquals(paymentDao.getPayment(payment.getId(), internalCallContext).getLastSuccessStateName(), "PURCHASE_SUCCESS"); try { paymentApi.createChargebackReversal(account, payment.getId(), chargebackTransactionExternalKey, callContext); Assert.fail("Chargeback reversals are not permitted before a chargeback"); } catch (final PaymentApiException e) { assertEquals(e.getCode(), ErrorCode.PAYMENT_NO_SUCH_SUCCESS_PAYMENT.getCode()); } assertEquals(paymentApi.getPayment(payment.getId(), false, ImmutableList.<PluginProperty>of(), callContext).getTransactions().size(), 1); assertEquals(paymentDao.getPayment(payment.getId(), internalCallContext).getStateName(), "PURCHASE_SUCCESS"); assertEquals(paymentDao.getPayment(payment.getId(), internalCallContext).getLastSuccessStateName(), "PURCHASE_SUCCESS"); } @Test(groups = "slow") public void testNotifyPendingTransactionOfStateChanged() throws PaymentApiException { final BigDecimal authAmount = BigDecimal.TEN; final String paymentExternalKey = "rouge"; final String transactionExternalKey = "vert"; final Payment initialPayment = createPayment(TransactionType.AUTHORIZE, null, paymentExternalKey, transactionExternalKey, authAmount, PaymentPluginStatus.PENDING); final Payment payment = paymentApi.notifyPendingTransactionOfStateChanged(account, initialPayment.getTransactions().get(0).getId(), true, callContext); assertEquals(payment.getExternalKey(), paymentExternalKey); assertEquals(payment.getPaymentMethodId(), account.getPaymentMethodId()); assertEquals(payment.getAccountId(), account.getId()); assertEquals(payment.getAuthAmount().compareTo(authAmount), 0); assertEquals(payment.getCapturedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getPurchasedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getRefundedAmount().compareTo(BigDecimal.ZERO), 0); assertEquals(payment.getCurrency(), Currency.USD); assertEquals(payment.getTransactions().size(), 1); assertEquals(payment.getTransactions().get(0).getExternalKey(), transactionExternalKey); assertEquals(payment.getTransactions().get(0).getPaymentId(), payment.getId()); assertEquals(payment.getTransactions().get(0).getAmount().compareTo(authAmount), 0); assertEquals(payment.getTransactions().get(0).getCurrency(), Currency.USD); assertEquals(payment.getTransactions().get(0).getProcessedAmount().compareTo(authAmount), 0); assertEquals(payment.getTransactions().get(0).getProcessedCurrency(), Currency.USD); assertEquals(payment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.SUCCESS); assertEquals(payment.getTransactions().get(0).getTransactionType(), TransactionType.AUTHORIZE); assertNull(payment.getTransactions().get(0).getGatewayErrorMsg()); assertNull(payment.getTransactions().get(0).getGatewayErrorCode()); } @Test(groups = "slow") public void testSimpleAuthCaptureWithInvalidPaymentId() throws Exception { final BigDecimal requestedAmount = new BigDecimal("80.0091"); final Payment initialPayment = paymentApi.createAuthorization(account, account.getPaymentMethodId(), null, requestedAmount, account.getCurrency(), UUID.randomUUID().toString(), UUID.randomUUID().toString(), ImmutableList.<PluginProperty>of(), callContext); try { paymentApi.createCapture(account, UUID.randomUUID(), requestedAmount, account.getCurrency(), UUID.randomUUID().toString(), ImmutableList.<PluginProperty>of(), callContext); Assert.fail("Expected capture to fail..."); } catch (final PaymentApiException e) { Assert.assertEquals(e.getCode(), ErrorCode.PAYMENT_NO_SUCH_PAYMENT.getCode()); final Payment latestPayment = paymentApi.getPayment(initialPayment.getId(), true, ImmutableList.<PluginProperty>of(), callContext); assertEquals(latestPayment, initialPayment); } } @Test(groups = "slow") public void testSimpleAuthCaptureWithInvalidCurrency() throws Exception { final BigDecimal requestedAmount = new BigDecimal("80.0091"); final Payment initialPayment = paymentApi.createAuthorization(account, account.getPaymentMethodId(), null, requestedAmount, account.getCurrency(), UUID.randomUUID().toString(), UUID.randomUUID().toString(), ImmutableList.<PluginProperty>of(), callContext); try { paymentApi.createCapture(account, initialPayment.getId(), requestedAmount, Currency.AMD, UUID.randomUUID().toString(), ImmutableList.<PluginProperty>of(), callContext); Assert.fail("Expected capture to fail..."); } catch (final PaymentApiException e) { Assert.assertEquals(e.getCode(), ErrorCode.PAYMENT_INVALID_PARAMETER.getCode()); final Payment latestPayment = paymentApi.getPayment(initialPayment.getId(), true, ImmutableList.<PluginProperty>of(), callContext); assertEquals(latestPayment, initialPayment); } } @Test(groups = "slow") public void testInvalidTransitionAfterFailure() throws PaymentApiException { final BigDecimal requestedAmount = BigDecimal.TEN; final String paymentExternalKey = "krapo"; final String transactionExternalKey = "grenouye"; final Payment payment = paymentApi.createAuthorization(account, account.getPaymentMethodId(), null, requestedAmount, Currency.EUR, paymentExternalKey, transactionExternalKey, ImmutableList.<PluginProperty>of(), callContext); // Hack the Database to make it look like it was a failure paymentDao.updatePaymentAndTransactionOnCompletion(account.getId(), null, payment.getId(), TransactionType.AUTHORIZE, "AUTH_ERRORED", null, payment.getTransactions().get(0).getId(), TransactionStatus.PLUGIN_FAILURE, null, null, null, null, internalCallContext); final PaymentSqlDao paymentSqlDao = dbi.onDemand(PaymentSqlDao.class); paymentSqlDao.updateLastSuccessPaymentStateName(payment.getId().toString(), "AUTH_ERRORED", null, internalCallContext); try { paymentApi.createCapture(account, payment.getId(), requestedAmount, Currency.EUR, "tetard", ImmutableList.<PluginProperty>of(), callContext); Assert.fail("Unexpected success"); } catch (final PaymentApiException e) { Assert.assertEquals(e.getCode(), ErrorCode.PAYMENT_INVALID_OPERATION.getCode()); } } @Test(groups = "slow") public void testApiWithPendingPaymentTransaction() throws Exception { for (final TransactionType transactionType : ImmutableList.<TransactionType>of(TransactionType.AUTHORIZE, TransactionType.PURCHASE, TransactionType.CREDIT)) { testApiWithPendingPaymentTransaction(transactionType, BigDecimal.TEN, BigDecimal.TEN); testApiWithPendingPaymentTransaction(transactionType, BigDecimal.TEN, BigDecimal.ONE); // See https://github.com/killbill/killbill/issues/372 testApiWithPendingPaymentTransaction(transactionType, BigDecimal.TEN, null); } } @Test(groups = "slow") public void testApiWithPendingRefundPaymentTransaction() throws Exception { final String paymentExternalKey = UUID.randomUUID().toString(); final String paymentTransactionExternalKey = UUID.randomUUID().toString(); final String refundTransactionExternalKey = UUID.randomUUID().toString(); final BigDecimal requestedAmount = BigDecimal.TEN; final BigDecimal refundAmount = BigDecimal.ONE; final Iterable<PluginProperty> pendingPluginProperties = ImmutableList.<PluginProperty>of(new PluginProperty(MockPaymentProviderPlugin.PLUGIN_PROPERTY_PAYMENT_PLUGIN_STATUS_OVERRIDE, TransactionStatus.PENDING.toString(), false)); final Payment payment = createPayment(TransactionType.PURCHASE, null, paymentExternalKey, paymentTransactionExternalKey, requestedAmount, PaymentPluginStatus.PROCESSED); assertNotNull(payment); Assert.assertEquals(payment.getExternalKey(), paymentExternalKey); Assert.assertEquals(payment.getTransactions().size(), 1); Assert.assertEquals(payment.getTransactions().get(0).getAmount().compareTo(requestedAmount), 0); Assert.assertEquals(payment.getTransactions().get(0).getProcessedAmount().compareTo(requestedAmount), 0); Assert.assertEquals(payment.getTransactions().get(0).getCurrency(), account.getCurrency()); Assert.assertEquals(payment.getTransactions().get(0).getExternalKey(), paymentTransactionExternalKey); Assert.assertEquals(payment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.SUCCESS); final Payment pendingRefund = paymentApi.createRefund(account, payment.getId(), requestedAmount, account.getCurrency(), refundTransactionExternalKey, pendingPluginProperties, callContext); verifyRefund(pendingRefund, paymentExternalKey, paymentTransactionExternalKey, refundTransactionExternalKey, requestedAmount, requestedAmount, TransactionStatus.PENDING); // Test Janitor path (regression test for https://github.com/killbill/killbill/issues/363) verifyPaymentViaGetPath(pendingRefund); // See https://github.com/killbill/killbill/issues/372 final Payment pendingRefund2 = paymentApi.createRefund(account, payment.getId(), null, null, refundTransactionExternalKey, pendingPluginProperties, callContext); verifyRefund(pendingRefund2, paymentExternalKey, paymentTransactionExternalKey, refundTransactionExternalKey, requestedAmount, requestedAmount, TransactionStatus.PENDING); verifyPaymentViaGetPath(pendingRefund2); // Note: we change the refund amount final Payment pendingRefund3 = paymentApi.createRefund(account, payment.getId(), refundAmount, account.getCurrency(), refundTransactionExternalKey, pendingPluginProperties, callContext); verifyRefund(pendingRefund3, paymentExternalKey, paymentTransactionExternalKey, refundTransactionExternalKey, requestedAmount, refundAmount, TransactionStatus.PENDING); verifyPaymentViaGetPath(pendingRefund3); // Pass null, we revert back to the original refund amount final Payment pendingRefund4 = paymentApi.createRefund(account, payment.getId(), null, null, refundTransactionExternalKey, ImmutableList.<PluginProperty>of(), callContext); verifyRefund(pendingRefund4, paymentExternalKey, paymentTransactionExternalKey, refundTransactionExternalKey, requestedAmount, requestedAmount, TransactionStatus.SUCCESS); verifyPaymentViaGetPath(pendingRefund4); } @Test(groups = "slow") public void testCreatePurchaseWithTimeout() throws Exception { final BigDecimal requestedAmount = BigDecimal.TEN; final String paymentExternalKey = "ohhhh"; final String transactionExternalKey = "naaahhh"; mockPaymentProviderPlugin.makePluginWaitSomeMilliseconds((int) (paymentConfig.getPaymentPluginTimeout().getMillis() + 100)); try { paymentApi.createPurchase(account, account.getPaymentMethodId(), null, requestedAmount, Currency.AED, paymentExternalKey, transactionExternalKey, ImmutableList.<PluginProperty>of(), callContext); fail(); } catch (PaymentApiException e) { assertEquals(e.getCode(), ErrorCode.PAYMENT_PLUGIN_TIMEOUT.getCode()); } } @Test(groups = "slow") public void testCreatePurchaseWithControlTimeout() throws Exception { final BigDecimal requestedAmount = BigDecimal.ONE; final String paymentExternalKey = "111111"; final String transactionExternalKey = "11111"; mockPaymentProviderPlugin.makePluginWaitSomeMilliseconds((int) (paymentConfig.getPaymentPluginTimeout().getMillis() + 100)); try { paymentApi.createPurchaseWithPaymentControl( account, account.getPaymentMethodId(), null, requestedAmount, Currency.AED, paymentExternalKey, transactionExternalKey, ImmutableList.<PluginProperty>of(), CONTROL_PLUGIN_OPTIONS, callContext); fail(); } catch (PaymentApiException e) { assertEquals(e.getCode(), ErrorCode.PAYMENT_PLUGIN_TIMEOUT.getCode()); } } @Test(groups = "slow") public void testSanityAcrossTransactionTypes() throws PaymentApiException { final BigDecimal requestedAmount = BigDecimal.TEN; final String paymentExternalKey = "ahhhhhhhh"; final String transactionExternalKey = "okkkkkkk"; final Payment pendingPayment = createPayment(TransactionType.AUTHORIZE, null, paymentExternalKey, transactionExternalKey, requestedAmount, PaymentPluginStatus.PENDING); assertNotNull(pendingPayment); Assert.assertEquals(pendingPayment.getExternalKey(), paymentExternalKey); Assert.assertEquals(pendingPayment.getTransactions().size(), 1); Assert.assertEquals(pendingPayment.getTransactions().get(0).getAmount().compareTo(requestedAmount), 0); Assert.assertEquals(pendingPayment.getTransactions().get(0).getProcessedAmount().compareTo(requestedAmount), 0); Assert.assertEquals(pendingPayment.getTransactions().get(0).getCurrency(), account.getCurrency()); Assert.assertEquals(pendingPayment.getTransactions().get(0).getExternalKey(), transactionExternalKey); Assert.assertEquals(pendingPayment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.PENDING); try { createPayment(TransactionType.PURCHASE, null, paymentExternalKey, transactionExternalKey, requestedAmount, PaymentPluginStatus.PENDING); Assert.fail("PURCHASE transaction with same key should have failed"); } catch (final PaymentApiException expected) { Assert.assertEquals(expected.getCode(), ErrorCode.PAYMENT_INVALID_OPERATION.getCode()); } } @Test(groups = "slow") public void testSuccessfulInitialTransactionToSameTransaction() throws Exception { final BigDecimal requestedAmount = BigDecimal.TEN; for (final TransactionType transactionType : ImmutableList.<TransactionType>of(TransactionType.AUTHORIZE, TransactionType.PURCHASE, TransactionType.CREDIT)) { final String paymentExternalKey = UUID.randomUUID().toString(); final String keyA = UUID.randomUUID().toString(); final Payment processedPayment = createPayment(transactionType, null, paymentExternalKey, keyA, requestedAmount, PaymentPluginStatus.PROCESSED); assertNotNull(processedPayment); Assert.assertEquals(processedPayment.getTransactions().size(), 1); Assert.assertEquals(processedPayment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.SUCCESS); // Attempt to create another {AUTH, PURCHASE, CREDIT} with different key => KB state machine should make the request fail as we don't allow // multiple SUCCESS {AUTH, PURCHASE, CREDIT} final String keyB = UUID.randomUUID().toString(); try { createPayment(transactionType, processedPayment.getId(), paymentExternalKey, keyB, requestedAmount, PaymentPluginStatus.PROCESSED); Assert.fail("Retrying initial successful transaction (AUTHORIZE, PURCHASE, CREDIT) with same different key should fail"); } catch (final PaymentApiException e) { } // Attempt to create another {AUTH, PURCHASE, CREDIT} with same key => key constraint should make the request fail try { createPayment(transactionType, processedPayment.getId(), paymentExternalKey, keyA, requestedAmount, PaymentPluginStatus.PROCESSED); Assert.fail("Retrying initial successful transaction (AUTHORIZE, PURCHASE, CREDIT) with same transaction key should fail"); } catch (final PaymentApiException e) { } } } @Test(groups = "slow") public void testPendingInitialTransactionToSameTransaction() throws Exception { final BigDecimal requestedAmount = BigDecimal.TEN; for (final TransactionType transactionType : ImmutableList.<TransactionType>of(TransactionType.AUTHORIZE, TransactionType.PURCHASE, TransactionType.CREDIT)) { final String paymentExternalKey = UUID.randomUUID().toString(); final String keyA = UUID.randomUUID().toString(); final Payment pendingPayment = createPayment(transactionType, null, paymentExternalKey, keyA, requestedAmount, PaymentPluginStatus.PENDING); assertNotNull(pendingPayment); Assert.assertEquals(pendingPayment.getTransactions().size(), 1); Assert.assertEquals(pendingPayment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.PENDING); // Attempt to create another {AUTH, PURCHASE, CREDIT} with different key => KB state machine should make the request fail as we don't allow // multiple SUCCESS {AUTH, PURCHASE, CREDIT} final String keyB = UUID.randomUUID().toString(); try { createPayment(transactionType, pendingPayment.getId(), paymentExternalKey, keyB, requestedAmount, PaymentPluginStatus.PROCESSED); Assert.fail("Retrying initial successful transaction (AUTHORIZE, PURCHASE, CREDIT) with same different key should fail"); } catch (final PaymentApiException e) { } // Attempt to create another {AUTH, PURCHASE, CREDIT} with same key => That should work because we are completing the payment final Payment completedPayment = createPayment(transactionType, pendingPayment.getId(), paymentExternalKey, keyA, requestedAmount, PaymentPluginStatus.PROCESSED); assertNotNull(completedPayment); Assert.assertEquals(completedPayment.getId(), pendingPayment.getId()); Assert.assertEquals(completedPayment.getTransactions().size(), 1); } } @Test(groups = "slow") public void testFailedInitialTransactionToSameTransactionWithSameKey() throws Exception { final BigDecimal requestedAmount = BigDecimal.TEN; for (final TransactionType transactionType : ImmutableList.<TransactionType>of(TransactionType.AUTHORIZE, TransactionType.PURCHASE, TransactionType.CREDIT)) { final String paymentExternalKey = UUID.randomUUID().toString(); final String keyA = UUID.randomUUID().toString(); final Payment errorPayment = createPayment(transactionType, null, paymentExternalKey, keyA, requestedAmount, PaymentPluginStatus.ERROR); assertNotNull(errorPayment); Assert.assertEquals(errorPayment.getTransactions().size(), 1); Assert.assertEquals(errorPayment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.PAYMENT_FAILURE); // Attempt to create another {AUTH, PURCHASE, CREDIT} with same key => That should work because we are completing the payment final Payment successfulPayment = createPayment(transactionType, errorPayment.getId(), paymentExternalKey, keyA, requestedAmount, PaymentPluginStatus.PROCESSED); assertNotNull(successfulPayment); Assert.assertEquals(successfulPayment.getId(), errorPayment.getId()); Assert.assertEquals(successfulPayment.getTransactions().size(), 2); } } @Test(groups = "slow") public void testFailedInitialTransactionToSameTransactionWithDifferentKey() throws Exception { final BigDecimal requestedAmount = BigDecimal.TEN; for (final TransactionType transactionType : ImmutableList.<TransactionType>of(TransactionType.AUTHORIZE, TransactionType.PURCHASE, TransactionType.CREDIT)) { final String paymentExternalKey = UUID.randomUUID().toString(); final String keyA = UUID.randomUUID().toString(); final Payment errorPayment = createPayment(transactionType, null, paymentExternalKey, keyA, requestedAmount, PaymentPluginStatus.ERROR); assertNotNull(errorPayment); Assert.assertEquals(errorPayment.getTransactions().size(), 1); Assert.assertEquals(errorPayment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.PAYMENT_FAILURE); // Attempt to create another {AUTH, PURCHASE, CREDIT} with different key => KB state machine should make the request fail as we don't allow // multiple SUCCESS {AUTH, PURCHASE, CREDIT} final String keyB = UUID.randomUUID().toString(); final Payment successfulPayment = createPayment(transactionType, errorPayment.getId(), paymentExternalKey, keyB, requestedAmount, PaymentPluginStatus.PROCESSED); assertNotNull(successfulPayment); Assert.assertEquals(successfulPayment.getId(), errorPayment.getId()); Assert.assertEquals(successfulPayment.getTransactions().size(), 2); } } private void verifyRefund(final Payment refund, final String paymentExternalKey, final String paymentTransactionExternalKey, final String refundTransactionExternalKey, final BigDecimal requestedAmount, final BigDecimal refundAmount, final TransactionStatus transactionStatus) { Assert.assertEquals(refund.getExternalKey(), paymentExternalKey); Assert.assertEquals(refund.getTransactions().size(), 2); Assert.assertEquals(refund.getTransactions().get(0).getAmount().compareTo(requestedAmount), 0); Assert.assertEquals(refund.getTransactions().get(0).getProcessedAmount().compareTo(requestedAmount), 0); Assert.assertEquals(refund.getTransactions().get(0).getCurrency(), account.getCurrency()); Assert.assertEquals(refund.getTransactions().get(0).getExternalKey(), paymentTransactionExternalKey); Assert.assertEquals(refund.getTransactions().get(0).getTransactionStatus(), TransactionStatus.SUCCESS); Assert.assertEquals(refund.getTransactions().get(1).getAmount().compareTo(requestedAmount), 0); Assert.assertEquals(refund.getTransactions().get(1).getProcessedAmount().compareTo(refundAmount), 0); Assert.assertEquals(refund.getTransactions().get(1).getCurrency(), account.getCurrency()); Assert.assertEquals(refund.getTransactions().get(1).getExternalKey(), refundTransactionExternalKey); Assert.assertEquals(refund.getTransactions().get(1).getTransactionStatus(), transactionStatus); } private Payment testApiWithPendingPaymentTransaction(final TransactionType transactionType, final BigDecimal requestedAmount, @Nullable final BigDecimal pendingAmount) throws PaymentApiException { final String paymentExternalKey = UUID.randomUUID().toString(); final String paymentTransactionExternalKey = UUID.randomUUID().toString(); final Payment pendingPayment = createPayment(transactionType, null, paymentExternalKey, paymentTransactionExternalKey, requestedAmount, PaymentPluginStatus.PENDING); assertNotNull(pendingPayment); Assert.assertEquals(pendingPayment.getExternalKey(), paymentExternalKey); Assert.assertEquals(pendingPayment.getTransactions().size(), 1); Assert.assertEquals(pendingPayment.getTransactions().get(0).getAmount().compareTo(requestedAmount), 0); Assert.assertEquals(pendingPayment.getTransactions().get(0).getProcessedAmount().compareTo(requestedAmount), 0); Assert.assertEquals(pendingPayment.getTransactions().get(0).getCurrency(), account.getCurrency()); Assert.assertEquals(pendingPayment.getTransactions().get(0).getExternalKey(), paymentTransactionExternalKey); Assert.assertEquals(pendingPayment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.PENDING); // Test Janitor path (regression test for https://github.com/killbill/killbill/issues/363) verifyPaymentViaGetPath(pendingPayment); final Payment pendingPayment2 = createPayment(transactionType, pendingPayment.getId(), paymentExternalKey, paymentTransactionExternalKey, pendingAmount, PaymentPluginStatus.PENDING); assertNotNull(pendingPayment2); Assert.assertEquals(pendingPayment2.getExternalKey(), paymentExternalKey); Assert.assertEquals(pendingPayment2.getTransactions().size(), 1); Assert.assertEquals(pendingPayment2.getTransactions().get(0).getAmount().compareTo(requestedAmount), 0); Assert.assertEquals(pendingPayment2.getTransactions().get(0).getProcessedAmount().compareTo(pendingAmount == null ? requestedAmount : pendingAmount), 0); Assert.assertEquals(pendingPayment2.getTransactions().get(0).getCurrency(), account.getCurrency()); Assert.assertEquals(pendingPayment2.getTransactions().get(0).getExternalKey(), paymentTransactionExternalKey); Assert.assertEquals(pendingPayment2.getTransactions().get(0).getTransactionStatus(), TransactionStatus.PENDING); verifyPaymentViaGetPath(pendingPayment2); final Payment completedPayment = createPayment(transactionType, pendingPayment.getId(), paymentExternalKey, paymentTransactionExternalKey, pendingAmount, PaymentPluginStatus.PROCESSED); assertNotNull(completedPayment); Assert.assertEquals(completedPayment.getExternalKey(), paymentExternalKey); Assert.assertEquals(completedPayment.getTransactions().size(), 1); Assert.assertEquals(completedPayment.getTransactions().get(0).getAmount().compareTo(requestedAmount), 0); Assert.assertEquals(completedPayment.getTransactions().get(0).getProcessedAmount().compareTo(pendingAmount == null ? requestedAmount : pendingAmount), 0); Assert.assertEquals(completedPayment.getTransactions().get(0).getCurrency(), account.getCurrency()); Assert.assertEquals(completedPayment.getTransactions().get(0).getExternalKey(), paymentTransactionExternalKey); Assert.assertEquals(completedPayment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.SUCCESS); verifyPaymentViaGetPath(completedPayment); return completedPayment; } private void verifyPaymentViaGetPath(final Payment payment) throws PaymentApiException { // We can't use Assert.assertEquals because the updateDate may have been updated by the Janitor final Payment refreshedPayment = paymentApi.getPayment(payment.getId(), true, ImmutableList.<PluginProperty>of(), callContext); Assert.assertEquals(refreshedPayment.getAccountId(), payment.getAccountId()); Assert.assertEquals(refreshedPayment.getTransactions().size(), payment.getTransactions().size()); Assert.assertEquals(refreshedPayment.getExternalKey(), payment.getExternalKey()); Assert.assertEquals(refreshedPayment.getPaymentMethodId(), payment.getPaymentMethodId()); Assert.assertEquals(refreshedPayment.getAccountId(), payment.getAccountId()); Assert.assertEquals(refreshedPayment.getAuthAmount().compareTo(payment.getAuthAmount()), 0); Assert.assertEquals(refreshedPayment.getCapturedAmount().compareTo(payment.getCapturedAmount()), 0); Assert.assertEquals(refreshedPayment.getPurchasedAmount().compareTo(payment.getPurchasedAmount()), 0); Assert.assertEquals(refreshedPayment.getRefundedAmount().compareTo(payment.getRefundedAmount()), 0); Assert.assertEquals(refreshedPayment.getCurrency(), payment.getCurrency()); for (int i = 0; i < refreshedPayment.getTransactions().size(); i++) { final PaymentTransaction refreshedPaymentTransaction = refreshedPayment.getTransactions().get(i); final PaymentTransaction paymentTransaction = payment.getTransactions().get(i); Assert.assertEquals(refreshedPaymentTransaction.getAmount().compareTo(paymentTransaction.getAmount()), 0); Assert.assertEquals(refreshedPaymentTransaction.getProcessedAmount().compareTo(paymentTransaction.getProcessedAmount()), 0); Assert.assertEquals(refreshedPaymentTransaction.getCurrency(), paymentTransaction.getCurrency()); Assert.assertEquals(refreshedPaymentTransaction.getExternalKey(), paymentTransaction.getExternalKey()); Assert.assertEquals(refreshedPaymentTransaction.getTransactionStatus(), paymentTransaction.getTransactionStatus()); } } private Payment createPayment(final TransactionType transactionType, @Nullable final UUID paymentId, @Nullable final String paymentExternalKey, @Nullable final String paymentTransactionExternalKey, @Nullable final BigDecimal amount, final PaymentPluginStatus paymentPluginStatus) throws PaymentApiException { final Iterable<PluginProperty> pluginProperties = ImmutableList.<PluginProperty>of(new PluginProperty(MockPaymentProviderPlugin.PLUGIN_PROPERTY_PAYMENT_PLUGIN_STATUS_OVERRIDE, paymentPluginStatus.toString(), false)); switch (transactionType) { case AUTHORIZE: return paymentApi.createAuthorization(account, account.getPaymentMethodId(), paymentId, amount, amount == null ? null : account.getCurrency(), paymentExternalKey, paymentTransactionExternalKey, pluginProperties, callContext); case PURCHASE: return paymentApi.createPurchase(account, account.getPaymentMethodId(), paymentId, amount, amount == null ? null : account.getCurrency(), paymentExternalKey, paymentTransactionExternalKey, pluginProperties, callContext); case CREDIT: return paymentApi.createCredit(account, account.getPaymentMethodId(), paymentId, amount, amount == null ? null : account.getCurrency(), paymentExternalKey, paymentTransactionExternalKey, pluginProperties, callContext); default: Assert.fail(); return null; } } private List<PluginProperty> createPropertiesForInvoice(final Invoice invoice) { final List<PluginProperty> result = new ArrayList<PluginProperty>(); result.add(new PluginProperty(InvoicePaymentControlPluginApi.PROP_IPCD_INVOICE_ID, invoice.getId().toString(), false)); return result; } // Search by a key supported by the search in MockPaymentProviderPlugin private void checkPaymentMethodPagination(final UUID paymentMethodId, final Long maxNbRecords, final boolean deleted) throws PaymentApiException { final Pagination<PaymentMethod> foundPaymentMethods = paymentApi.searchPaymentMethods(paymentMethodId.toString(), 0L, maxNbRecords + 1, false, ImmutableList.<PluginProperty>of(), callContext); Assert.assertEquals(foundPaymentMethods.iterator().hasNext(), !deleted); Assert.assertEquals(foundPaymentMethods.getMaxNbRecords(), maxNbRecords); Assert.assertEquals(foundPaymentMethods.getTotalNbRecords(), (Long) (!deleted ? 1L : 0L)); final Pagination<PaymentMethod> foundPaymentMethodsWithPluginInfo = paymentApi.searchPaymentMethods(paymentMethodId.toString(), 0L, maxNbRecords + 1, true, ImmutableList.<PluginProperty>of(), callContext); Assert.assertEquals(foundPaymentMethodsWithPluginInfo.iterator().hasNext(), !deleted); Assert.assertEquals(foundPaymentMethodsWithPluginInfo.getMaxNbRecords(), maxNbRecords); Assert.assertEquals(foundPaymentMethodsWithPluginInfo.getTotalNbRecords(), (Long) (!deleted ? 1L : 0L)); final Pagination<PaymentMethod> foundPaymentMethods2 = paymentApi.searchPaymentMethods(paymentMethodId.toString(), 0L, maxNbRecords + 1, MockPaymentProviderPlugin.PLUGIN_NAME, false, ImmutableList.<PluginProperty>of(), callContext); Assert.assertEquals(foundPaymentMethods2.iterator().hasNext(), !deleted); Assert.assertEquals(foundPaymentMethods2.getMaxNbRecords(), maxNbRecords); Assert.assertEquals(foundPaymentMethods2.getTotalNbRecords(), (Long) (!deleted ? 1L : 0L)); final Pagination<PaymentMethod> foundPaymentMethods2WithPluginInfo = paymentApi.searchPaymentMethods(paymentMethodId.toString(), 0L, maxNbRecords + 1, MockPaymentProviderPlugin.PLUGIN_NAME, true, ImmutableList.<PluginProperty>of(), callContext); Assert.assertEquals(foundPaymentMethods2WithPluginInfo.iterator().hasNext(), !deleted); Assert.assertEquals(foundPaymentMethods2WithPluginInfo.getMaxNbRecords(), maxNbRecords); Assert.assertEquals(foundPaymentMethods2WithPluginInfo.getTotalNbRecords(), (Long) (!deleted ? 1L : 0L)); final Pagination<PaymentMethod> gotPaymentMethods = paymentApi.getPaymentMethods(0L, maxNbRecords + 1L, false, ImmutableList.<PluginProperty>of(), callContext); Assert.assertEquals(gotPaymentMethods.iterator().hasNext(), maxNbRecords > 0); Assert.assertEquals(gotPaymentMethods.getMaxNbRecords(), maxNbRecords); Assert.assertEquals(gotPaymentMethods.getTotalNbRecords(), maxNbRecords); final Pagination<PaymentMethod> gotPaymentMethodsWithPluginInfo = paymentApi.getPaymentMethods(0L, maxNbRecords + 1L, true, ImmutableList.<PluginProperty>of(), callContext); Assert.assertEquals(gotPaymentMethodsWithPluginInfo.iterator().hasNext(), maxNbRecords > 0); Assert.assertEquals(gotPaymentMethodsWithPluginInfo.getMaxNbRecords(), maxNbRecords); Assert.assertEquals(gotPaymentMethodsWithPluginInfo.getTotalNbRecords(), maxNbRecords); final Pagination<PaymentMethod> gotPaymentMethods2 = paymentApi.getPaymentMethods(0L, maxNbRecords + 1L, MockPaymentProviderPlugin.PLUGIN_NAME, false, ImmutableList.<PluginProperty>of(), callContext); Assert.assertEquals(gotPaymentMethods2.iterator().hasNext(), maxNbRecords > 0); Assert.assertEquals(gotPaymentMethods2.getMaxNbRecords(), maxNbRecords); Assert.assertEquals(gotPaymentMethods2.getTotalNbRecords(), maxNbRecords); final Pagination<PaymentMethod> gotPaymentMethods2WithPluginInfo = paymentApi.getPaymentMethods(0L, maxNbRecords + 1L, MockPaymentProviderPlugin.PLUGIN_NAME, true, ImmutableList.<PluginProperty>of(), callContext); Assert.assertEquals(gotPaymentMethods2WithPluginInfo.iterator().hasNext(), maxNbRecords > 0); Assert.assertEquals(gotPaymentMethods2WithPluginInfo.getMaxNbRecords(), maxNbRecords); Assert.assertEquals(gotPaymentMethods2WithPluginInfo.getTotalNbRecords(), maxNbRecords); } }
payment: add completion tests of UNKNOWN transactions outside of control layer Signed-off-by: Pierre-Alexandre Meyer <ff019a5748a52b5641624af88a54a2f0e46a9fb5@mouraf.org>
payment/src/test/java/org/killbill/billing/payment/api/TestPaymentApi.java
payment: add completion tests of UNKNOWN transactions outside of control layer
Java
apache-2.0
097c085dfd6c04848c4fe1a53153da17080766e6
0
nate-rcl/irplus,nate-rcl/irplus
/** Copyright 2008 University of Rochester 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 edu.ur.hibernate.ir.institution.db; import java.sql.SQLException; import java.util.Date; import java.util.LinkedList; import java.util.List; import org.apache.log4j.Logger; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.Restrictions; import org.springframework.orm.hibernate3.HibernateCallback; import edu.ur.hibernate.HbCrudDAO; import edu.ur.hibernate.HbHelper; import edu.ur.ir.institution.InstitutionalCollection; import edu.ur.ir.institution.InstitutionalItem; import edu.ur.ir.institution.InstitutionalItemDAO; import edu.ur.ir.item.ContentTypeCount; import edu.ur.order.OrderType; /** * Implementation of relational storage for an institutional item. * * @author Nathan Sarr * */ public class HbInstitutionalItemDAO implements InstitutionalItemDAO { /** eclipse generated id */ private static final long serialVersionUID = -828719967486672639L; /** Get the logger for this class */ private static final Logger log = Logger.getLogger(HbInstitutionalItemDAO.class); /** Helper for persisting information using hibernate. */ private final HbCrudDAO<InstitutionalItem> hbCrudDAO; /** * Default Constructor */ public HbInstitutionalItemDAO() { hbCrudDAO = new HbCrudDAO<InstitutionalItem>(InstitutionalItem.class); } /** * Set the session factory. * * @param sessionFactory */ public void setSessionFactory(SessionFactory sessionFactory) { hbCrudDAO.setSessionFactory(sessionFactory); } /** * Return all institutional items. * * @see edu.ur.dao.CrudDAO#getAll() */ @SuppressWarnings("unchecked") public List getAll() { return hbCrudDAO.getAll(); } /** * Get an institutional item by it's id. * * @see edu.ur.dao.CrudDAO#getById(java.lang.Long, boolean) */ public InstitutionalItem getById(Long id, boolean lock) { return hbCrudDAO.getById(id, lock); } /** * Add an institutional item to relational storage. * * @see edu.ur.dao.CrudDAO#makePersistent(java.lang.Object) */ public void makePersistent(InstitutionalItem entity) { hbCrudDAO.makePersistent(entity); } /** * Remove an institutional item from relational storage. * * @see edu.ur.dao.CrudDAO#makeTransient(java.lang.Object) */ public void makeTransient(InstitutionalItem entity) { hbCrudDAO.makeTransient(entity); } /** * Find if the item version is already published to this collection. * * @param institutional item id * @param institutionalCollectionId Id of the institutional collection * @param itemVersionId Id of the item version * * @return True if item is published to the collection else false */ public boolean isItemPublishedToCollection(Long institutionalCollectionId, Long genericItemId) { if (getInstitutionalItem(institutionalCollectionId, genericItemId) != null) { return true; } else { return false; } } /** * Get an institutional item by collection id and generic item id. * * @param collectionId - id of the collection * @param genericItemId - the generic item id. * * @return the institutional item */ public InstitutionalItem getInstitutionalItem(Long collectionId, Long genericItemId) { Query q = hbCrudDAO.getSessionFactory().getCurrentSession().getNamedQuery("isItemPublishedToThisCollection"); q.setParameter("collectionId", collectionId); q.setParameter("itemId", genericItemId); return (InstitutionalItem)q.uniqueResult(); } /** * Get the institutional items for given collection Ids * * @param itemIds - List of item ids * * @return List of items ids */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getInstitutionalItems(final List<Long> itemIds) { List<InstitutionalItem> foundItems = new LinkedList<InstitutionalItem>(); if( itemIds.size() > 0 ) { foundItems = (List<InstitutionalItem>) hbCrudDAO.getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Criteria criteria = session.createCriteria(hbCrudDAO.getClazz()); criteria.add(Restrictions.in("id",itemIds)); return criteria.list(); } }); } return foundItems; } /** * Get a list of items for a specified repository by name. * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param repositoryId - id of the collection to get items * @param orderType - The order to sort by (ascending/descending) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getRepositoryItemsByName(final int rowStart, final int maxResults, final Long repositoryId, final OrderType orderType) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if (orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getRepositoryItemsByNameOrderDesc"); } else { q = session.getNamedQuery("getRepositoryItemsByNameOrderAsc"); } q.setLong("repositoryId", repositoryId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setCacheable(false); q.setReadOnly(true); q.setFetchSize(maxResults); return q.list(); } /** * Get a list of items for a specified repository by first character of the name * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param repositoryId - id of the repository to get items * @param firstChar - first character that the name should have * @param orderType - The order to sort by (asc/desc) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getRepositoryItemsByChar(final int rowStart, final int maxResults, final Long repositoryId, final char firstChar, final OrderType orderType) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if (orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getRepositoryItemsByCharOrderDesc"); } else { q = session.getNamedQuery("getRepositoryItemsByCharOrderAsc"); } q.setLong("repositoryId", repositoryId); q.setCharacter("firstChar", Character.toLowerCase(firstChar)); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } /** * Get a list of items for a specified repository by between the that have titles * that start between the specified characters * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param repositoryId - id of the repository to get items * @param firstChar - first character in range that the first letter of the name can have * @param lastChar - last character in range that the first letter of the name can have * @param orderType - The order to sort by (asc/desc) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getRepositoryItemsBetweenChar(final int rowStart, final int maxResults, final Long repositoryId, final char firstChar, final char lastChar, final OrderType orderType) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if (orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getRepositoryItemsByCharRangeOrderDesc"); } else { q = session.getNamedQuery("getRepositoryItemsByCharRangeOrderAsc"); } q.setLong("repositoryId", repositoryId); q.setCharacter("firstChar", Character.toLowerCase(firstChar)); q.setCharacter("lastChar", Character.toLowerCase(lastChar)); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } /** * @see edu.ur.ir.institution.InstitutionalItemDAO#getCollectionItemsByName(int, int, edu.ur.ir.institution.InstitutionalCollection, java.lang.String) */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getCollectionItemsByName(final int rowStart, final int maxResults, final InstitutionalCollection collection, final OrderType orderType) { if(collection != null ) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if (orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session .getNamedQuery("getInstitutionalCollectionItemsByNameOrderDesc"); } else { q = session .getNamedQuery("getInstitutionalCollectionItemsByNameOrderAsc"); } q.setLong("leftVal", collection.getLeftValue()); q.setLong("rightVal", collection.getRightValue()); q.setLong("rootId", collection.getTreeRoot().getId()); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } else { return new LinkedList<InstitutionalItem>(); } } /** * Return a count of all items in the system. * * @see edu.ur.dao.CountableDAO#getCount() */ public Long getCount() { return (Long)HbHelper.getUnique(hbCrudDAO.getHibernateTemplate().findByNamedQuery("institutionalItemCount")); } /** * Get a count of institutional items in the repository. * * @param repositoryId - id of the repository * @return */ public Long getCount(Long repositoryId) { return (Long)HbHelper.getUnique(hbCrudDAO.getHibernateTemplate().findByNamedQuery("institutionalItemCountForRepository", repositoryId)); } /** * Get a count of institutional items in the repository with a name * that starts with the specified first character. * * @param repositoryId - id of the repository * @param nameFirstChar - first character of the name * * @return the count found */ public Long getCount(Long repositoryId, char nameFirstChar) { Object[] values = new Object[]{repositoryId, Character.valueOf(Character.toLowerCase(nameFirstChar))}; return (Long)HbHelper.getUnique(hbCrudDAO.getHibernateTemplate().findByNamedQuery("institutionalItemCountForRepositoryByChar", values)); } /** * Get a count of institutional items in the repository with a name * that starts with the specified first character in the given range. * * @param repositoryId - id of the repository * @param nameFirstCharRange - first character of the name start of range * @param nameLastCharRange- first character of the name end of range * * @return the count found */ public Long getCount(Long repositoryId, char nameFirstCharRange, char namelastCharRange) { Object[] values = new Object[]{repositoryId, Character.valueOf(Character.toLowerCase(nameFirstCharRange)), Character.valueOf(Character.toLowerCase(namelastCharRange))}; return (Long)HbHelper.getUnique(hbCrudDAO.getHibernateTemplate().findByNamedQuery("institutionalItemCountForRepositoryByCharRange", values)); } /** * Get a count of institutional items in a collection and its children. * * @param collectionId - id of the collection * @return */ public Long getCountForCollectionAndChildren(InstitutionalCollection collection) { Long[] ids = new Long[] {collection.getLeftValue(), collection.getRightValue(), collection.getTreeRoot().getId()}; return (Long)HbHelper.getUnique(hbCrudDAO.getHibernateTemplate().findByNamedQuery("institutionalItemCountForCollectionAndchildren", ids)); } /** * Get a count of institutional items in a collection. * * @param collectionId - id of the collection * @return */ public Long getCount(InstitutionalCollection collection) { return (Long)HbHelper.getUnique(hbCrudDAO.getHibernateTemplate().findByNamedQuery("institutionalItemCountForCollection", collection.getId())); } public Long getCountByGenericItem(Long genericItemId) { return (Long)HbHelper.getUnique(hbCrudDAO.getHibernateTemplate().findByNamedQuery("institutionalItemCountForGenericItem", genericItemId)); } /** * Get all institutional items that contain any of the generic item ids in the given list. * * @param genericItemIds - list of generic item ids * @return list of institutional items found. */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getInstitutionalItemsByGenericItemIds(List<Long> genericItemIds) { //getInstitutionalItemsForGenericItemIds Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = session.getNamedQuery("getInstitutionalItemsForGenericItemIds"); q.setParameterList("itemIds", genericItemIds); return q.list(); } /** * @see edu.ur.ir.institution.InstitutionalItemDAO#getCollectionItemsBetweenChar(int, int, edu.ur.ir.institution.InstitutionalCollection, char, char, java.lang.String) */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getCollectionItemsBetweenChar( final int rowStart, final int maxResults, final InstitutionalCollection collection, final char firstChar, final char lastChar, final OrderType orderType) { Query q = null; if(collection != null ) { if (orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = hbCrudDAO.getSessionFactory().getCurrentSession() .getNamedQuery("getCollectionItemsByCharRangeOrderDesc"); } else { q = hbCrudDAO.getSessionFactory().getCurrentSession() .getNamedQuery("getCollectionItemsByCharRangeOrderAsc"); } q.setLong("leftVal", collection.getLeftValue()); q.setLong("rightVal", collection.getRightValue()); q.setLong("rootId", collection.getTreeRoot().getId()); q.setCharacter("firstChar", Character.toLowerCase(firstChar)); q.setCharacter("lastChar", Character.toLowerCase(lastChar)); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } else { return new LinkedList<InstitutionalItem>(); } } /** * * @see edu.ur.ir.institution.InstitutionalItemDAO#getCollectionItemsByChar(int, int, edu.ur.ir.institution.InstitutionalCollection, char, java.lang.String) */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getCollectionItemsByChar(final int rowStart, final int maxResults, final InstitutionalCollection collection, final char firstChar, final OrderType orderType) { if( collection != null ) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if (orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session .getNamedQuery("getInstitutionalCollectionItemsByCharOrderDesc"); } else { q = session .getNamedQuery("getInstitutionalCollectionItemsByCharOrderAsc"); } q.setLong("leftVal", collection.getLeftValue()); q.setLong("rightVal", collection.getRightValue()); q.setLong("rootId", collection.getTreeRoot().getId()); q.setCharacter("firstChar", Character.toLowerCase(firstChar)); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } else { return new LinkedList<InstitutionalItem>(); } } /** * @see edu.ur.ir.institution.InstitutionalItemDAO#getCount(edu.ur.ir.institution.InstitutionalCollection, char) */ public Long getCount(InstitutionalCollection collection, char nameFirstChar) { if( collection != null ) { Object[] values = new Object[]{ collection.getLeftValue(), collection.getRightValue(), collection.getTreeRoot().getId(), Character.valueOf(Character.toLowerCase(nameFirstChar))}; return (Long)HbHelper.getUnique(hbCrudDAO.getHibernateTemplate().findByNamedQuery("institutionalItemCountForCollectionByChar", values)); } else { return 0l; } } /** * @see edu.ur.ir.institution.InstitutionalItemDAO#getCount(edu.ur.ir.institution.InstitutionalCollection, char, char) */ public Long getCount(InstitutionalCollection collection, char nameFirstCharRange, char namelastCharRange) { if( collection != null ) { Object[] values = new Object[]{ collection.getLeftValue(), collection.getRightValue(), collection.getTreeRoot().getId(), Character.valueOf(Character.toLowerCase(nameFirstCharRange)), Character.valueOf(Character.toLowerCase(namelastCharRange))}; return (Long)HbHelper.getUnique(hbCrudDAO.getHibernateTemplate().findByNamedQuery("institutionalItemCountForCollectionByCharRange", values)); } else { return 0l; } } /** * Get a count of distinct institutional items in the repository. * * @return */ public Long getDistinctInstitutionalItemCount() { return (Long)HbHelper.getUnique(hbCrudDAO.getHibernateTemplate().findByNamedQuery("distinctInstitutionalItemCount")); } /** * Get a institutional collections the generic item exists in * * @return */ @SuppressWarnings("unchecked") public List<InstitutionalCollection> getInstitutionalCollectionsForGenericItem(Long itemId) { return (List<InstitutionalCollection>) hbCrudDAO.getHibernateTemplate().findByNamedQuery("getCollectionsForGenericItem", itemId); } /** * get the publication count for given name id. * * @see edu.ur.ir.institution.InstitutionalItemDAO#getPublicationCountByPersonName(List) */ public Long getPublicationCountByPersonName(List<Long> personNameIds) { Query q = hbCrudDAO.getHibernateTemplate().getSessionFactory().getCurrentSession().getNamedQuery("getPublicationCountByPersonNameId"); q.setParameterList("personNameIds", personNameIds); Long count = (Long)q.uniqueResult(); return count; } /** * Get Institutional item by given version id * * @see edu.ur.ir.institution.InstitutionalItemDAO#getInstitutionalItemByVersionId(Long) */ public InstitutionalItem getInstitutionalItemByVersionId(Long institutionalVerisonId) { return (InstitutionalItem) HbHelper.getUnique(hbCrudDAO.getHibernateTemplate().findByNamedQuery("getInstitutionalItemByVersionId", institutionalVerisonId)); } /** * Get a institutional items where the generic item is the latest version * * @return */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getInstitutionalItemsForGenericItemId(Long itemId) { return (List<InstitutionalItem>) hbCrudDAO.getHibernateTemplate().findByNamedQuery("getInstitutionalItemsForGenericItemId", itemId); } /** * @see edu.ur.ir.institution.InstitutionalItemDAO#getItems(int, int, edu.ur.ir.institution.InstitutionalCollection, java.util.Date, java.util.Date) */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getItemsOrderByDate(final int rowStart, final int maxResults, final InstitutionalCollection collection, final OrderType orderType) { if( collection != null ) { List<InstitutionalItem> foundItems = (List<InstitutionalItem>) hbCrudDAO.getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getInstitutionalCollectionItemsByAcceptedDateDesc"); } else { q = session.getNamedQuery("getInstitutionalCollectionItemsByAcceptedDateAsc"); } q.setLong(0, collection.getId()); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } }); return foundItems; } else { return new LinkedList<InstitutionalItem>(); } } /** * @see edu.ur.ir.institution.InstitutionalItemDAO#getItems(edu.ur.ir.institution.InstitutionalCollection, java.util.Date, java.util.Date) */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getItems(final InstitutionalCollection collection, final Date startDate, final Date endDate) { if(collection != null && startDate != null && endDate != null ) { log.debug("Trying dates " + startDate + " and " + endDate); List<InstitutionalItem> foundItems = (List<InstitutionalItem>) hbCrudDAO.getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Query q = null; q = session.getNamedQuery("getInstitutionalCollectionItemsByAcceptedDateRange"); q.setLong(0, collection.getId()); q.setTimestamp(1, startDate); q.setTimestamp(2, endDate); return q.list(); } }); return foundItems; } else { return new LinkedList<InstitutionalItem>(); } } /** * Get the list of collection items by id. * * @see edu.ur.ir.institution.InstitutionalItemDAO#getCollectionItemsById(int, int, edu.ur.ir.institution.InstitutionalCollection, edu.ur.order.OrderType) */ @SuppressWarnings("unchecked") public List<Long> getCollectionItemsIds(final int rowStart, final int maxResults, final InstitutionalCollection collection, final OrderType orderType) { if( collection != null ) { List<Long> foundIds = (List<Long>) hbCrudDAO.getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getInstitutionalCollectionItemIdsOrderDesc"); } else { q = session.getNamedQuery("getInstitutionalCollectionItemIdsOrderAsc"); } q.setLong(0, collection.getLeftValue()); q.setLong(1, collection.getRightValue()); q.setLong(2, collection.getTreeRoot().getId()); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } }); return foundIds; } else { return new LinkedList<Long>(); } } /** * Get a list of items for a specified repository by between the that have titles * that start between the specified characters * * NOTE: This search includes all items in child collections * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param collection - the institutional collection * @param contentTypeId - content type id the items must have * @param firstChar - first character in range that the first letter of the name can have * @param lastChar - last character in range that the first letter of the name can have * @param orderType - The order to sort by (asc/desc) * * @return list of items matching the specified criteria * * @see edu.ur.ir.institution.InstitutionalItemDAO#getCollectionItemsBetweenChar(int, int, edu.ur.ir.institution.InstitutionalCollection, java.lang.Long, char, char, edu.ur.order.OrderType) */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getCollectionItemsBetweenChar(int rowStart, int maxResults, InstitutionalCollection collection, Long contentTypeId, char firstChar, char lastChar, OrderType orderType) { if( collection != null ) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getCollectionItemsContentTypeByCharRangeOrderDesc"); } else { q = session.getNamedQuery("getCollectionItemsContentTypeByCharRangeOrderAsc"); } q.setParameter("leftVal", collection.getLeftValue()); q.setParameter("rightVal", collection.getRightValue()); q.setParameter("rootId", collection.getTreeRoot().getId()); q.setParameter("firstChar", Character.valueOf(Character.toLowerCase(firstChar))); q.setParameter("lastChar", Character.valueOf(Character.toLowerCase(lastChar))); q.setParameter("contentTypeId", contentTypeId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } else { return new LinkedList<InstitutionalItem>(); } } /** * Get a list of items for a specified collection by first character of the name * * NOTE: This search includes all items in child collections * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param institutional collection - the institutional collection * @param contentTypeId - id of the content type * @param firstChar - first character that the name should have * @param orderType - The order to sort by (asc/desc) * * @return List of institutional items * * @see edu.ur.ir.institution.InstitutionalItemDAO#getCollectionItemsByChar(int, int, edu.ur.ir.institution.InstitutionalCollection, java.lang.Long, char, edu.ur.order.OrderType) */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getCollectionItemsByChar(int rowStart, int maxResults, InstitutionalCollection collection, Long contentTypeId, char firstChar, OrderType orderType) { if(collection != null ) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getInstitutionalCollectionItemsContentTypeByCharOrderDesc"); } else { q = session.getNamedQuery("getInstitutionalCollectionItemsContentTypeByCharOrderAsc"); } q.setParameter("leftVal", collection.getLeftValue()); q.setParameter("rightVal", collection.getRightValue()); q.setParameter("rootId", collection.getTreeRoot().getId()); q.setParameter("firstChar", Character.valueOf(Character.toLowerCase(firstChar))); q.setParameter("contentTypeId", contentTypeId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } else { return new LinkedList<InstitutionalItem>(); } } /** * Get the list of items for the specified collection with the given * content type id. This includes items in child collections * * @param rowStart - Start row to fetch the data from * @param maxResults - maximum number of results to return * @param collection - the collection to get items * @param contentTypeId - id of the content type * @param orderType - The order to sort by (ascending/descending) * * @return List of institutional items * * @see edu.ur.ir.institution.InstitutionalItemDAO#getCollectionItemsByName(int, int, edu.ur.ir.institution.InstitutionalCollection, java.lang.Long, edu.ur.order.OrderType) */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getCollectionItemsByName(int rowStart, int maxResults, InstitutionalCollection collection, Long contentTypeId, OrderType orderType) { if( collection != null ) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getInstitutionalCollectionItemsContentTypeByNameOrderDesc"); } else { q = session.getNamedQuery("getInstitutionalCollectionItemsContentTypeByNameOrderAsc"); } q.setParameter("leftVal", collection.getLeftValue()); q.setParameter("rightVal", collection.getRightValue()); q.setParameter("rootId", collection.getTreeRoot().getId()); q.setParameter("contentTypeId", contentTypeId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } else { return new LinkedList<InstitutionalItem>(); } } /** * Get a count of institutional items with the given content type id. * * @param repositoryId - id of the repository * @param contentTypeId - content type * * @return the count of institutional items with the content type in the specified * repository. */ public Long getCount(Long repositoryId, Long contentTypeId) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = session.getNamedQuery("getRepositoryItemsContentTypeCount"); q.setParameter("repositoryId", repositoryId); q.setParameter("contentTypeId", contentTypeId); return (Long)q.uniqueResult(); } /** * Get a count of institutional items with the specified repository id * has a name starting with the first character and the specified content type id. * * @param repositoryId - id of the repository * @param nameFirstChar - name of the first character * @param contentTypeId - specified content type id * * @return the count of items with the specified criteria */ public Long getCount(Long repositoryId, char firstChar, Long contentTypeId) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = session.getNamedQuery("institutionalItemCountContentTypeForRepositoryByChar"); q.setParameter("repositoryId", repositoryId); q.setParameter("contentTypeId", contentTypeId); q.setParameter("char", Character.valueOf(Character.toLowerCase(firstChar))); return (Long)q.uniqueResult(); } /** * Get a count of all items within the specified repository with a name * first character starting between the given character range and the content type id. * * @param repositoryId - id of the repository * @param nameFirstCharRange - starting character range * @param namelastCharRange - ending character range * @param contentTypeId - id of the content type * * @return the count of items */ public Long getCount(Long repositoryId, char nameFirstCharRange, char namelastCharRange, Long contentTypeId) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = session.getNamedQuery("institutionalItemCountForRepositoryContentTypeByCharRange"); q.setParameter("repositoryId", repositoryId); q.setParameter("contentTypeId", contentTypeId); q.setParameter("firstChar", Character.valueOf(Character.toLowerCase(nameFirstCharRange))); q.setParameter("lastChar", Character.valueOf(Character.toLowerCase(namelastCharRange))); return (Long)q.uniqueResult(); } /** * Get a count of all items within the specified collection, has the specified first character * and a given content type id. This includes a count of items within sub collections. * * @param collection - collection items must be within sub collections * @param nameFirstChar - name starts with the specified first character * @param contentTypeId - id of the content type * * @return count of items */ public Long getCount(InstitutionalCollection collection, char nameFirstChar, Long contentTypeId) { if( collection != null ) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = session.getNamedQuery("institutionalItemCountForCollectionContentTypeByChar"); q.setParameter("leftVal", collection.getLeftValue()); q.setParameter("rightVal", collection.getRightValue()); q.setParameter("contentTypeId", contentTypeId); q.setParameter("rootId", collection.getTreeRoot().getId()); q.setParameter("firstChar", Character.valueOf(Character.toLowerCase(nameFirstChar))); return (Long)q.uniqueResult(); } else { return 0l; } } /** Get a count of all institutional items in the specified collection with * specified first character in the given character range with the given content type id- THIS INCLUDES items in child collections * * @param institutional collection - parent collection * @param nameFirstCharRange - first character in range * @param nameLastCharRange - last character in the range * * @return count of titles found that have a first character in the specified range */ public Long getCount(InstitutionalCollection collection, char nameFirstCharRange, char nameLastCharRange, Long contentTypeId) { if(collection != null) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = session.getNamedQuery("institutionalItemCountForCollectionContentTypeByCharRange"); q.setParameter("leftVal", collection.getLeftValue()); q.setParameter("rightVal", collection.getRightValue()); q.setParameter("contentTypeId", contentTypeId); q.setParameter("rootId", collection.getTreeRoot().getId()); q.setParameter("firstChar", Character.valueOf(Character.toLowerCase(nameFirstCharRange))); q.setParameter("lastChar", Character.valueOf(Character.toLowerCase(nameLastCharRange))); return (Long)q.uniqueResult(); } else { return 0l; } } /** * Get a count of institutional items in a collection and its children with * the specified content type. * * @param collection - collection to start counting from * @param contentTypeId - id of the content type * * @return Items within the specified collection and its sub collection */ public Long getCount(InstitutionalCollection collection, Long contentTypeId) { if( collection != null ) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = session.getNamedQuery("getInstitutionalCollectionItemsContentTypeCount"); q.setParameter("leftVal", collection.getLeftValue()); q.setParameter("rightVal", collection.getRightValue()); q.setParameter("contentTypeId", contentTypeId); q.setParameter("rootId", collection.getTreeRoot().getId()); return (Long)q.uniqueResult(); } else { return 0l; } } /** * Get a list of items for a specified repository by between the that have titles * that start between the specified characters with the given content type id * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param repositoryId - id of the repository to get items * @param firstChar - first character in range that the first letter of the name can have * @param lastChar - last character in range that the first letter of the name can have * @param contentTypeId - id of the content type * @param orderType - The order to sort by (asc/desc) * * @return List of institutional items * @see edu.ur.ir.institution.InstitutionalItemDAO#getRepositoryItemsBetweenChar(int, int, java.lang.Long, char, char, java.lang.Long, edu.ur.order.OrderType) */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getRepositoryItemsBetweenChar(int rowStart, int maxResults, Long repositoryId, char firstChar, char lastChar, Long contentTypeId, OrderType orderType) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getRepositoryItemsContentTypeByCharRangeOrderDesc"); } else { q = session.getNamedQuery("getRepositoryItemsContentTypeByCharRangeOrderAsc"); } q.setParameter("repositoryId", repositoryId); q.setParameter("firstChar",Character.valueOf(Character.toLowerCase(firstChar))); q.setParameter("lastChar", Character.valueOf(Character.toLowerCase(lastChar))); q.setParameter("contentTypeId", contentTypeId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } /** * Get a list of items for a specified repository by first character of the name and * the given content type id * * @param rowStart - Start row to fetch the data from * @param maxResults - maximum number of results to fetch * @param repositoryId - id of the repository to get items * @param contentTypeId - id of the content type * @param firstChar - first character that the name should have * @param orderType - The order to sort by (asc/desc) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getRepositoryItemsByChar(int rowStart, int maxResults, Long repositoryId, Long contentTypeId, char firstChar, OrderType orderType) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getRepositoryItemsContentTypeByCharOrderDesc"); } else { q = session.getNamedQuery("getRepositoryItemsContentTypeByCharOrderAsc"); } q.setParameter("repositoryId", repositoryId); q.setParameter("char", Character.valueOf(Character.toLowerCase(firstChar))); q.setParameter("contentTypeId", contentTypeId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } /** * Get a list of items for a specified repository with the given content type id. * * @param rowStart - Start row to fetch the data from * @param rowEnd - End row to get data * @param repositoryId - id of the repository to get items * @param contentTypeId - id of the content type * @param propertyName - The property to sort on * @param orderType - The order to sort by (ascending/descending) * * @return List of institutional items * @see edu.ur.ir.institution.InstitutionalItemDAO#getRepositoryItemsOrderByName(int, int, java.lang.Long, java.lang.Long, edu.ur.order.OrderType) */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getRepositoryItemsOrderByName(int rowStart, int maxResults, Long repositoryId, Long contentTypeId, OrderType orderType) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getRepositoryItemsContentTypeByNameOrderDesc"); } else { q = session.getNamedQuery("getRepositoryItemsContentTypeByNameOrderAsc"); } q.setParameter("repositoryId", repositoryId); q.setParameter("contentTypeId", contentTypeId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } /** * Get a list of of repository content types with counts for the number * of items within the repository. This will return only those * items that have a count greater than 0. * * @return - list of content type counts * @see edu.ur.ir.institution.InstitutionalItemDAO#getRepositoryContentTypeCount() */ @SuppressWarnings("unchecked") public List<ContentTypeCount> getRepositoryContentTypeCount(Long repositoryId) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = session.getNamedQuery("getRepositoryItemsSumByContentType"); q.setParameter("repositoryId", repositoryId); return q.list(); } /** * Get a list of of repository content types with counts for the number * of items within the repository. * * @param collection - institutional collection * @return - list of content type counts * * @see edu.ur.ir.institution.InstitutionalItemService#getRepositoryContentTypeCount() */ @SuppressWarnings("unchecked") public List<ContentTypeCount> getCollectionContentTypeCount(InstitutionalCollection collection) { if( collection != null ) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = session.getNamedQuery("getCollectionItemsSumByContentType"); q.setParameter("leftVal", collection.getLeftValue()); q.setParameter("rightVal", collection.getRightValue()); q.setParameter("rootId", collection.getTreeRoot().getId()); return q.list(); } else { return new LinkedList<ContentTypeCount>(); } } /** * Get a list of items for a specified repository by between the that have titles * that start between the specified characters * * NOTE: This search includes all items in child collections * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param collection - the institutional collection * @param firstChar - first character in range that the first letter of the name can have * @param lastChar - last character in range that the first letter of the name can have * @param orderType - The order to sort by (asc/desc) * * @return list of items matching the specified criteria * * @see edu.ur.ir.institution.InstitutionalItemDAO#getCollectionItemsBetweenChar(int, int, edu.ur.ir.institution.InstitutionalCollection, java.lang.Long, char, char, edu.ur.order.OrderType) */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getCollectionItemsBetweenCharPublicationDateOrder( int rowStart, int maxResults, InstitutionalCollection collection, char firstChar, char lastChar, OrderType orderType) { if( collection != null) { Query q = null; if (orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = hbCrudDAO.getSessionFactory().getCurrentSession() .getNamedQuery("getInstitutionalCollectionItemsByCharRangePublicationDateOrderDesc"); } else { q = hbCrudDAO.getSessionFactory().getCurrentSession() .getNamedQuery("getInstitutionalCollectionItemsByCharRangePublicationDateOrderAsc"); } q.setLong("leftVal", collection.getLeftValue()); q.setLong("rightVal", collection.getRightValue()); q.setLong("rootId", collection.getTreeRoot().getId()); q.setCharacter("firstChar", Character.toLowerCase(firstChar)); q.setCharacter("lastChar", Character.toLowerCase(lastChar)); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } else { return new LinkedList<InstitutionalItem>(); } } /** * Get a list of items for a specified repository by between the that have titles * that start between the specified characters * * NOTE: This search includes all items in child collections * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param collection - the institutional collection * @param contentTypeId - content type id the items must have * @param firstChar - first character in range that the first letter of the name can have * @param lastChar - last character in range that the first letter of the name can have * @param orderType - The order to sort by (asc/desc) * * @return list of items matching the specified criteria * * @see edu.ur.ir.institution.InstitutionalItemDAO#getCollectionItemsBetweenChar(int, int, edu.ur.ir.institution.InstitutionalCollection, java.lang.Long, char, char, edu.ur.order.OrderType) */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getCollectionItemsBetweenCharPublicationDateOrder( int rowStart, int maxResults, InstitutionalCollection collection, Long contentTypeId, char firstChar, char lastChar, OrderType orderType) { if( collection != null ) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getCollectionItemsContentTypeByCharRangePublicationDateOrderDesc"); } else { q = session.getNamedQuery("getCollectionItemsContentTypeByCharRangePublicationDateOrderAsc"); } q.setParameter("leftVal", collection.getLeftValue()); q.setParameter("rightVal", collection.getRightValue()); q.setParameter("rootId", collection.getTreeRoot().getId()); q.setParameter("firstChar", Character.valueOf(Character.toLowerCase(firstChar))); q.setParameter("lastChar", Character.valueOf(Character.toLowerCase(lastChar))); q.setParameter("contentTypeId", contentTypeId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } else { return new LinkedList<InstitutionalItem>(); } } /** * Get a list of items for a specified collection by first character of the name * * NOTE: This search includes all items in child collections * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param institutional collection - the institutional collection * @param firstChar - first character that the name should have * @param orderType - The order to sort by (asc/desc) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getCollectionItemsByCharPublicationDateOrder( int rowStart, int maxResults, InstitutionalCollection collection, char firstChar, OrderType orderType) { if( collection != null ) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if (orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session .getNamedQuery("getInstitutionalCollectionItemsByCharPublicationDateOrderDesc"); } else { q = session .getNamedQuery("getInstitutionalCollectionItemsByCharPublicationDateOrderAsc"); } q.setLong("leftVal", collection.getLeftValue()); q.setLong("rightVal", collection.getRightValue()); q.setLong("rootId", collection.getTreeRoot().getId()); q.setCharacter("firstChar", Character.toLowerCase(firstChar)); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } else { return new LinkedList<InstitutionalItem>(); } } /** * Get a list of items for a specified collection by first character of the name * * NOTE: This search includes all items in child collections * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param institutional collection - the institutional collection * @param contentTypeId - id of the content type * @param firstChar - first character that the name should have * @param orderType - The order to sort by (asc/desc) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getCollectionItemsByCharPublicationDateOrder( int rowStart, int maxResults, InstitutionalCollection collection, Long contentTypeId, char firstChar, OrderType orderType) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( collection != null ) { if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getInstitutionalCollectionItemsContentTypeByCharPublicationDateOrderDesc"); } else { q = session.getNamedQuery("getInstitutionalCollectionItemsContentTypeByCharPublicationDateOrderAsc"); } q.setParameter("leftVal", collection.getLeftValue()); q.setParameter("rightVal", collection.getRightValue()); q.setParameter("rootId", collection.getTreeRoot().getId()); q.setParameter("firstChar", Character.valueOf(Character.toLowerCase(firstChar))); q.setParameter("contentTypeId", contentTypeId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } else { return new LinkedList<InstitutionalItem>(); } } /** * Get the list of items for the specified collection. * This includes items in child collections * * @param rowStart - Start row to fetch the data from * @param maxResults - maximum number of results to return * @param collection - the collection to get items * @param orderType - The order to sort by (ascending/descending) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getCollectionItemsPublicationDateOrder( int rowStart, int maxResults, InstitutionalCollection collection, OrderType orderType) { if(collection != null ) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if (orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session .getNamedQuery("getInstitutionalCollectionItemsPublicationDateOrderDesc"); } else { q = session .getNamedQuery("getInstitutionalCollectionItemsPublicationDateOrderAsc"); } q.setLong("leftVal", collection.getLeftValue()); q.setLong("rightVal", collection.getRightValue()); q.setLong("rootId", collection.getTreeRoot().getId()); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } else { return new LinkedList<InstitutionalItem>(); } } /** * Get the list of items for the specified collection with the given * content type id. This includes items in child collections * * @param rowStart - Start row to fetch the data from * @param maxResults - maximum number of results to return * @param collection - the collection to get items * @param contentTypeId - id of the content type * @param orderType - The order to sort by (ascending/descending) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getCollectionItemsPublicationDateOrder( int rowStart, int maxResults, InstitutionalCollection collection, Long contentTypeId, OrderType orderType) { if( collection != null ) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if (orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session .getNamedQuery("getInstitutionalCollectionItemsContentTypeByPublicationDateOrderDesc"); } else { q = session .getNamedQuery("getInstitutionalCollectionItemsContentTypeByPublicationDateOrderAsc"); } q.setLong("leftVal", collection.getLeftValue()); q.setLong("rightVal", collection.getRightValue()); q.setLong("rootId", collection.getTreeRoot().getId()); q.setLong("contentTypeId", contentTypeId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } else { return new LinkedList<InstitutionalItem>(); } } /** * Get a list of items for a specified repository by between the that have titles * that start between the specified characters * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param repositoryId - id of the repository to get items * @param firstChar - first character in range that the first letter of the name can have * @param lastChar - last character in range that the first letter of the name can have * @param orderType - The order to sort by (asc/desc) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getRepositoryItemsBetweenCharPublicationDateOrder( int rowStart, int maxResults, Long repositoryId, char firstChar, char lastChar, OrderType orderType) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if (orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getRepositoryItemsByCharRangePublicationDateOrderDesc"); } else { q = session.getNamedQuery("getRepositoryItemsByCharRangePublicationDateOrderAsc"); } q.setLong("repositoryId", repositoryId); q.setCharacter("firstChar", Character.toLowerCase(firstChar)); q.setCharacter("lastChar", Character.toLowerCase(lastChar)); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } /** * Get a list of items for a specified repository by between the that have titles * that start between the specified characters with the given content type id * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param repositoryId - id of the repository to get items * @param firstChar - first character in range that the first letter of the name can have * @param lastChar - last character in range that the first letter of the name can have * @param contentTypeId - id of the content type * @param orderType - The order to sort by (asc/desc) * * @return List of institutional items * @see edu.ur.ir.institution.InstitutionalItemDAO#getRepositoryItemsBetweenChar(int, int, java.lang.Long, char, char, java.lang.Long, edu.ur.order.OrderType) */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getRepositoryItemsBetweenCharPublicationDateOrder( int rowStart, int maxResults, Long repositoryId, char firstChar, char lastChar, Long contentTypeId, OrderType orderType) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getRepositoryItemsContentTypeByCharRangeOrderDesc"); } else { q = session.getNamedQuery("getRepositoryItemsContentTypeByCharRangeOrderAsc"); } q.setParameter("repositoryId", repositoryId); q.setParameter("firstChar",Character.valueOf(Character.toLowerCase(firstChar))); q.setParameter("lastChar", Character.valueOf(Character.toLowerCase(lastChar))); q.setParameter("contentTypeId", contentTypeId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } /** * Get a list of items for a specified repository by first character of the name and * the given content type id * * @param rowStart - Start row to fetch the data from * @param maxResults - maximum number of results to fetch * @param repositoryId - id of the repository to get items * @param contentTypeId - id of the content type * @param firstChar - first character that the name should have * @param orderType - The order to sort by (asc/desc) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getRepositoryItemsByCharPublicationDateOrder( int rowStart, int maxResults, Long repositoryId, Long contentTypeId, char firstChar, OrderType orderType) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getRepositoryItemsContentTypeByCharPublicationDateOrderDesc"); } else { q = session.getNamedQuery("getRepositoryItemsContentTypeByCharPublicationDateOrderAsc"); } q.setParameter("repositoryId", repositoryId); q.setParameter("char", Character.valueOf(Character.toLowerCase(firstChar))); q.setParameter("contentTypeId", contentTypeId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } /** * Get a list of items for a specified repository by between the that have titles * that start between the specified characters * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param repositoryId - id of the repository to get items * @param firstChar - first character in range that the first letter of the name can have * @param lastChar - last character in range that the first letter of the name can have * @param orderType - The order to sort by (asc/desc) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getRepositoryItemsByCharPublicationDateOrder( int rowStart, int maxResults, Long repositoryId, char firstChar, OrderType orderType) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if (orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getRepositoryItemsByCharPublicationDateOrderDesc"); } else { q = session.getNamedQuery("getRepositoryItemsByCharPublicationDateOrderAsc"); } q.setLong("repositoryId", repositoryId); q.setCharacter("firstChar", Character.toLowerCase(firstChar)); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } /** * Get a list of items for a specified repository by publication date. * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param repositoryId - id of the collection to get items * @param orderType - The order to sort by (ascending/descending) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getRepositoryItemsPublicationDateOrder( int rowStart, int maxResults, Long repositoryId, OrderType orderType) { Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = hbCrudDAO.getSessionFactory().getCurrentSession().getNamedQuery("getRepositoryItemsByPublicationDateOrderDesc"); } else { q = hbCrudDAO.getSessionFactory().getCurrentSession().getNamedQuery("getRepositoryItemsByPublicationDateOrderAsc"); } q.setLong("repositoryId", repositoryId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setCacheable(false); q.setReadOnly(true); q.setFetchSize(maxResults); return (List<InstitutionalItem>)q.list(); } /** * Get a list of items for a specified repository by publication date. * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param repositoryId - id of the collection to get items * @param contentTypeId - id of the content type * @param orderType - The order to sort by (ascending/descending) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getRepositoryItemsPublicationDateOrder( int rowStart, int maxResults, Long repositoryId, Long contentTypeId, OrderType orderType) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getRepositoryItemsContentTypeByPublicationDateOrderDesc"); } else { q = session.getNamedQuery("getRepositoryItemsContentTypeByPublicationDateOrderAsc"); } q.setParameter("repositoryId", repositoryId); q.setParameter("contentTypeId", contentTypeId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } /** * Get the list of items for the specified collection with the given * content type id. This includes items in child collections * * @param rowStart - Start row to fetch the data from * @param maxResults - maximum number of results to return * @param collection - the collection to get items * @param orderType - The order to sort by (ascending/descending) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getCollectionItemsFirstAvailableOrder( int rowStart, int maxResults, InstitutionalCollection collection, OrderType orderType) { if(collection != null ) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if (orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session .getNamedQuery("getInstitutionalCollectionItemsFirstAvailableOrderDesc"); } else { q = session .getNamedQuery("getInstitutionalCollectionItemsFirstAvailableOrderAsc"); } q.setLong("leftVal", collection.getLeftValue()); q.setLong("rightVal", collection.getRightValue()); q.setLong("rootId", collection.getTreeRoot().getId()); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } else { return new LinkedList<InstitutionalItem>(); } } /** * Get the list of items for the specified collection with the given * content type id. This includes items in child collections * * @param rowStart - Start row to fetch the data from * @param maxResults - maximum number of results to return * @param collection - the collection to get items * @param contentTypeId - id of the content type * @param orderType - The order to sort by (ascending/descending) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getCollectionItemsFirstAvailableOrder( int rowStart, int maxResults, InstitutionalCollection collection, Long contentTypeId, OrderType orderType) { if(collection != null ) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if (orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session .getNamedQuery("getInstitutionalCollectionItemsContentTypeByFirstAvailableOrderDesc"); } else { q = session .getNamedQuery("getInstitutionalCollectionItemsContentTypeByFirstAvailableOrderAsc"); } q.setLong("leftVal", collection.getLeftValue()); q.setLong("rightVal", collection.getRightValue()); q.setLong("rootId", collection.getTreeRoot().getId()); q.setLong("contentTypeId", contentTypeId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } else { return new LinkedList<InstitutionalItem>(); } } /** * Get a list of items for a specified repository by between the that have titles * that start between the specified characters * * NOTE: This search includes all items in child collections * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param collection - the institutional collection * @param firstChar - first character in range that the first letter of the name can have * @param lastChar - last character in range that the first letter of the name can have * @param orderType - The order to sort by (asc/desc) * * @return list of items matching the specified criteria * * @see edu.ur.ir.institution.InstitutionalItemDAO#getCollectionItemsBetweenChar(int, int, edu.ur.ir.institution.InstitutionalCollection, java.lang.Long, char, char, edu.ur.order.OrderType) */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getCollectionItemsBetweenCharFirstAvailableOrder( int rowStart, int maxResults, InstitutionalCollection collection, char firstChar, char lastChar, OrderType orderType) { if( collection != null ) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getInstitutionalCollectionItemsByCharRangeFirstAvailableOrderDesc"); } else { q = session.getNamedQuery("getInstitutionalCollectionItemsByCharRangeFirstAvailableOrderAsc"); } q.setParameter("leftVal", collection.getLeftValue()); q.setParameter("rightVal", collection.getRightValue()); q.setParameter("rootId", collection.getTreeRoot().getId()); q.setParameter("firstChar", Character.valueOf(Character.toLowerCase(firstChar))); q.setParameter("lastChar", Character.valueOf(Character.toLowerCase(lastChar))); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } else { return new LinkedList<InstitutionalItem>(); } } /** * Get a list of items for a specified repository by between the that have titles * that start between the specified characters * * NOTE: This search includes all items in child collections * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param collection - the institutional collection * @param contentTypeId - id of the content type * @param firstChar - first character in range that the first letter of the name can have * @param lastChar - last character in range that the first letter of the name can have * @param orderType - The order to sort by (asc/desc) * * @return list of items matching the specified criteria * * @see edu.ur.ir.institution.InstitutionalItemDAO#getCollectionItemsBetweenChar(int, int, edu.ur.ir.institution.InstitutionalCollection, java.lang.Long, char, char, edu.ur.order.OrderType) */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getCollectionItemsBetweenCharFirstAvailableOrder( int rowStart, int maxResults, InstitutionalCollection collection, Long contentTypeId, char firstChar, char lastChar, OrderType orderType) { if( collection != null ) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getInstitutionalCollectionItemsContentTypeByCharRangeFirstAvailableOrderDesc"); } else { q = session.getNamedQuery("getInstitutionalCollectionItemsContentTypeByCharRangeFirstAvailableOrderAsc"); } q.setParameter("leftVal", collection.getLeftValue()); q.setParameter("rightVal", collection.getRightValue()); q.setParameter("rootId", collection.getTreeRoot().getId()); q.setParameter("firstChar", Character.valueOf(Character.toLowerCase(firstChar))); q.setParameter("lastChar", Character.valueOf(Character.toLowerCase(lastChar))); q.setParameter("contentTypeId", contentTypeId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } else { return new LinkedList<InstitutionalItem>(); } } /** * Get a list of items for a specified collection by first character of the name * * NOTE: This search includes all items in child collections * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param institutional collection - the institutional collection * @param firstChar - first character that the name should have * @param orderType - The order to sort by (asc/desc) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getCollectionItemsByCharFirstAvailableOrder( int rowStart, int maxResults, InstitutionalCollection collection, char firstChar, OrderType orderType) { if(collection != null ) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getInstitutionalCollectionItemsByCharFirstAvailableOrderDesc"); } else { q = session.getNamedQuery("getInstitutionalCollectionItemsByCharFirstAvailableOrderAsc"); } q.setParameter("leftVal", collection.getLeftValue()); q.setParameter("rightVal", collection.getRightValue()); q.setParameter("rootId", collection.getTreeRoot().getId()); q.setParameter("firstChar", Character.valueOf(Character.toLowerCase(firstChar))); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } else { return new LinkedList<InstitutionalItem>(); } } /** * Get a list of items for a specified collection by first character of the name * * NOTE: This search includes all items in child collections * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param institutional collection - the institutional collection * @param contentTypeId - id of the content type * @param firstChar - first character that the name should have * @param orderType - The order to sort by (asc/desc) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getCollectionItemsByCharFirstAvailableOrder( int rowStart, int maxResults, InstitutionalCollection collection, Long contentTypeId, char firstChar, OrderType orderType) { if( collection != null ) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getInstitutionalCollectionItemsContentTypeByCharFirstAvailableOrderDesc"); } else { q = session.getNamedQuery("getInstitutionalCollectionItemsContentTypeByCharFirstAvailableOrderAsc"); } q.setParameter("leftVal", collection.getLeftValue()); q.setParameter("rightVal", collection.getRightValue()); q.setParameter("rootId", collection.getTreeRoot().getId()); q.setParameter("firstChar", Character.valueOf(Character.toLowerCase(firstChar))); q.setParameter("contentTypeId", contentTypeId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } else { return new LinkedList<InstitutionalItem>(); } } /** * Get a list of items for a specified repository by publication date. * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param repositoryId - id of the collection to get items * @param contentTypeId - id of the content type * @param orderType - The order to sort by (ascending/descending) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getRepositoryItemsFirstAvailableOrder( int rowStart, int maxResults, Long repositoryId, Long contentTypeId, OrderType orderType) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getRepositoryItemsContentTypeByFirstAvailableOrderDesc"); } else { q = session.getNamedQuery("getRepositoryItemsContentTypeByFirstAvailableOrderAsc"); } q.setParameter("repositoryId", repositoryId); q.setParameter("contentTypeId", contentTypeId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } /** * Get a list of items for a specified repository by publication date. * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param repositoryId - id of the collection to get items * @param orderType - The order to sort by (ascending/descending) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getRepositoryItemsFirstAvailableOrder( int rowStart, int maxResults, Long repositoryId, OrderType orderType) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getRepositoryItemsByFirstAvailableOrderDesc"); } else { q = session.getNamedQuery("getRepositoryItemsByFirstAvailableOrderAsc"); } q.setParameter("repositoryId", repositoryId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } /** * Get a list of items for a specified repository by between the that have titles * that start between the specified characters with the given content type id * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param repositoryId - id of the repository to get items * @param firstChar - first character in range that the first letter of the name can have * @param lastChar - last character in range that the first letter of the name can have * @param orderType - The order to sort by (asc/desc) * * @return List of institutional items * @see edu.ur.ir.institution.InstitutionalItemDAO#getRepositoryItemsBetweenChar(int, int, java.lang.Long, char, char, java.lang.Long, edu.ur.order.OrderType) */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getRepositoryItemsBetweenCharFirstAvailableOrder( int rowStart, int maxResults, Long repositoryId, char firstChar, char lastChar, OrderType orderType) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getRepositoryItemsByCharRangeFirstAvailableOrderDesc"); } else { q = session.getNamedQuery("getRepositoryItemsByCharRangeFirstAvailableOrderAsc"); } q.setParameter("repositoryId", repositoryId); q.setParameter("firstChar",Character.valueOf(Character.toLowerCase(firstChar))); q.setParameter("lastChar", Character.valueOf(Character.toLowerCase(lastChar))); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } /** * Get a list of items for a specified repository by between the that have titles * that start between the specified characters with the given content type id * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param repositoryId - id of the repository to get items * @param firstChar - first character in range that the first letter of the name can have * @param lastChar - last character in range that the first letter of the name can have * @param contentTypeId - id of the content type * @param orderType - The order to sort by (asc/desc) * * @return List of institutional items * @see edu.ur.ir.institution.InstitutionalItemDAO#getRepositoryItemsBetweenChar(int, int, java.lang.Long, char, char, java.lang.Long, edu.ur.order.OrderType) */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getRepositoryItemsBetweenCharFirstAvailableOrder( int rowStart, int maxResults, Long repositoryId, char firstChar, char lastChar, Long contentTypeId, OrderType orderType) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getRepositoryItemsContentTypeByCharRangeFirstAvailableOrderDesc"); } else { q = session.getNamedQuery("getRepositoryItemsContentTypeByCharRangeFirstAvailableOrderAsc"); } q.setParameter("repositoryId", repositoryId); q.setParameter("firstChar",Character.valueOf(Character.toLowerCase(firstChar))); q.setParameter("lastChar", Character.valueOf(Character.toLowerCase(lastChar))); q.setParameter("contentTypeId", contentTypeId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } /** * Get a list of items for a specified repository by first character of the name and * the given content type id * * @param rowStart - Start row to fetch the data from * @param maxResults - maximum number of results to fetch * @param repositoryId - id of the repository to get items * @param firstChar - first character that the name should have * @param orderType - The order to sort by (asc/desc) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getRepositoryItemsByCharFirstAvailableOrder( int rowStart, int maxResults, Long repositoryId, char firstChar, OrderType orderType) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getRepositoryItemsByCharFirstAvailableOrderDesc"); } else { q = session.getNamedQuery("getRepositoryItemsByCharFirstAvailableOrderAsc"); } q.setParameter("repositoryId", repositoryId); q.setParameter("firstChar", Character.valueOf(Character.toLowerCase(firstChar))); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } /** * Get a list of items for a specified repository by first character of the name and * the given content type id * * @param rowStart - Start row to fetch the data from * @param maxResults - maximum number of results to fetch * @param repositoryId - id of the repository to get items * @param contentTypeId - id of the content type * @param firstChar - first character that the name should have * @param orderType - The order to sort by (asc/desc) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getRepositoryItemsByCharFirstAvailableOrder( int rowStart, int maxResults, Long repositoryId, Long contentTypeId, char firstChar, OrderType orderType) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getRepositoryItemsContentTypeByCharFirstAvailableOrderDesc"); } else { q = session.getNamedQuery("getRepositoryItemsContentTypeByCharFirstAvailableOrderAsc"); } q.setParameter("repositoryId", repositoryId); q.setParameter("char", Character.valueOf(Character.toLowerCase(firstChar))); q.setParameter("contentTypeId", contentTypeId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } }
ir_hibernate/src/edu/ur/hibernate/ir/institution/db/HbInstitutionalItemDAO.java
/** Copyright 2008 University of Rochester 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 edu.ur.hibernate.ir.institution.db; import java.sql.SQLException; import java.util.Date; import java.util.LinkedList; import java.util.List; import org.apache.log4j.Logger; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.Restrictions; import org.springframework.orm.hibernate3.HibernateCallback; import edu.ur.hibernate.HbCrudDAO; import edu.ur.hibernate.HbHelper; import edu.ur.ir.institution.InstitutionalCollection; import edu.ur.ir.institution.InstitutionalItem; import edu.ur.ir.institution.InstitutionalItemDAO; import edu.ur.ir.item.ContentTypeCount; import edu.ur.order.OrderType; /** * Implementation of relational storage for an institutional item. * * @author Nathan Sarr * */ public class HbInstitutionalItemDAO implements InstitutionalItemDAO { /** eclipse generated id */ private static final long serialVersionUID = -828719967486672639L; /** Get the logger for this class */ private static final Logger log = Logger.getLogger(HbInstitutionalItemDAO.class); /** Helper for persisting information using hibernate. */ private final HbCrudDAO<InstitutionalItem> hbCrudDAO; /** * Default Constructor */ public HbInstitutionalItemDAO() { hbCrudDAO = new HbCrudDAO<InstitutionalItem>(InstitutionalItem.class); } /** * Set the session factory. * * @param sessionFactory */ public void setSessionFactory(SessionFactory sessionFactory) { hbCrudDAO.setSessionFactory(sessionFactory); } /** * Return all institutional items. * * @see edu.ur.dao.CrudDAO#getAll() */ @SuppressWarnings("unchecked") public List getAll() { return hbCrudDAO.getAll(); } /** * Get an institutional item by it's id. * * @see edu.ur.dao.CrudDAO#getById(java.lang.Long, boolean) */ public InstitutionalItem getById(Long id, boolean lock) { return hbCrudDAO.getById(id, lock); } /** * Add an institutional item to relational storage. * * @see edu.ur.dao.CrudDAO#makePersistent(java.lang.Object) */ public void makePersistent(InstitutionalItem entity) { hbCrudDAO.makePersistent(entity); } /** * Remove an institutional item from relational storage. * * @see edu.ur.dao.CrudDAO#makeTransient(java.lang.Object) */ public void makeTransient(InstitutionalItem entity) { hbCrudDAO.makeTransient(entity); } /** * Find if the item version is already published to this collection. * * @param institutional item id * @param institutionalCollectionId Id of the institutional collection * @param itemVersionId Id of the item version * * @return True if item is published to the collection else false */ public boolean isItemPublishedToCollection(Long institutionalCollectionId, Long genericItemId) { if (getInstitutionalItem(institutionalCollectionId, genericItemId) != null) { return true; } else { return false; } } /** * Get an institutional item by collection id and generic item id. * * @param collectionId - id of the collection * @param genericItemId - the generic item id. * * @return the institutional item */ public InstitutionalItem getInstitutionalItem(Long collectionId, Long genericItemId) { Query q = hbCrudDAO.getSessionFactory().getCurrentSession().getNamedQuery("isItemPublishedToThisCollection"); q.setParameter("collectionId", collectionId); q.setParameter("itemId", genericItemId); return (InstitutionalItem)q.uniqueResult(); } /** * Get the institutional items for given collection Ids * * @param itemIds - List of item ids * * @return List of items ids */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getInstitutionalItems(final List<Long> itemIds) { List<InstitutionalItem> foundItems = new LinkedList<InstitutionalItem>(); if( itemIds.size() > 0 ) { foundItems = (List<InstitutionalItem>) hbCrudDAO.getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Criteria criteria = session.createCriteria(hbCrudDAO.getClazz()); criteria.add(Restrictions.in("id",itemIds)); return criteria.list(); } }); } return foundItems; } /** * Get a list of items for a specified repository by name. * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param repositoryId - id of the collection to get items * @param orderType - The order to sort by (ascending/descending) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getRepositoryItemsByName(final int rowStart, final int maxResults, final Long repositoryId, final OrderType orderType) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if (orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getRepositoryItemsByNameOrderDesc"); } else { q = session.getNamedQuery("getRepositoryItemsByNameOrderAsc"); } q.setLong("repositoryId", repositoryId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setCacheable(false); q.setReadOnly(true); q.setFetchSize(maxResults); return q.list(); } /** * Get a list of items for a specified repository by first character of the name * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param repositoryId - id of the repository to get items * @param firstChar - first character that the name should have * @param orderType - The order to sort by (asc/desc) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getRepositoryItemsByChar(final int rowStart, final int maxResults, final Long repositoryId, final char firstChar, final OrderType orderType) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if (orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getRepositoryItemsByCharOrderDesc"); } else { q = session.getNamedQuery("getRepositoryItemsByCharOrderAsc"); } q.setLong("repositoryId", repositoryId); q.setCharacter("firstChar", Character.toLowerCase(firstChar)); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } /** * Get a list of items for a specified repository by between the that have titles * that start between the specified characters * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param repositoryId - id of the repository to get items * @param firstChar - first character in range that the first letter of the name can have * @param lastChar - last character in range that the first letter of the name can have * @param orderType - The order to sort by (asc/desc) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getRepositoryItemsBetweenChar(final int rowStart, final int maxResults, final Long repositoryId, final char firstChar, final char lastChar, final OrderType orderType) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if (orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getRepositoryItemsByCharRangeOrderDesc"); } else { q = session.getNamedQuery("getRepositoryItemsByCharRangeOrderAsc"); } q.setLong("repositoryId", repositoryId); q.setCharacter("firstChar", Character.toLowerCase(firstChar)); q.setCharacter("lastChar", Character.toLowerCase(lastChar)); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } /** * @see edu.ur.ir.institution.InstitutionalItemDAO#getCollectionItemsByName(int, int, edu.ur.ir.institution.InstitutionalCollection, java.lang.String) */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getCollectionItemsByName(final int rowStart, final int maxResults, final InstitutionalCollection collection, final OrderType orderType) { if(collection != null ) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if (orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session .getNamedQuery("getInstitutionalCollectionItemsByNameOrderDesc"); } else { q = session .getNamedQuery("getInstitutionalCollectionItemsByNameOrderAsc"); } q.setLong("leftVal", collection.getLeftValue()); q.setLong("rightVal", collection.getRightValue()); q.setLong("rootId", collection.getTreeRoot().getId()); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } else { return new LinkedList<InstitutionalItem>(); } } /** * Return a count of all items in the system. * * @see edu.ur.dao.CountableDAO#getCount() */ public Long getCount() { return (Long)HbHelper.getUnique(hbCrudDAO.getHibernateTemplate().findByNamedQuery("institutionalItemCount")); } /** * Get a count of institutional items in the repository. * * @param repositoryId - id of the repository * @return */ public Long getCount(Long repositoryId) { return (Long)HbHelper.getUnique(hbCrudDAO.getHibernateTemplate().findByNamedQuery("institutionalItemCountForRepository", repositoryId)); } /** * Get a count of institutional items in the repository with a name * that starts with the specified first character. * * @param repositoryId - id of the repository * @param nameFirstChar - first character of the name * * @return the count found */ public Long getCount(Long repositoryId, char nameFirstChar) { Object[] values = new Object[]{repositoryId, Character.valueOf(Character.toLowerCase(nameFirstChar))}; return (Long)HbHelper.getUnique(hbCrudDAO.getHibernateTemplate().findByNamedQuery("institutionalItemCountForRepositoryByChar", values)); } /** * Get a count of institutional items in the repository with a name * that starts with the specified first character in the given range. * * @param repositoryId - id of the repository * @param nameFirstCharRange - first character of the name start of range * @param nameLastCharRange- first character of the name end of range * * @return the count found */ public Long getCount(Long repositoryId, char nameFirstCharRange, char namelastCharRange) { Object[] values = new Object[]{repositoryId, Character.valueOf(Character.toLowerCase(nameFirstCharRange)), Character.valueOf(Character.toLowerCase(namelastCharRange))}; return (Long)HbHelper.getUnique(hbCrudDAO.getHibernateTemplate().findByNamedQuery("institutionalItemCountForRepositoryByCharRange", values)); } /** * Get a count of institutional items in a collection and its children. * * @param collectionId - id of the collection * @return */ public Long getCountForCollectionAndChildren(InstitutionalCollection collection) { Long[] ids = new Long[] {collection.getLeftValue(), collection.getRightValue(), collection.getTreeRoot().getId()}; return (Long)HbHelper.getUnique(hbCrudDAO.getHibernateTemplate().findByNamedQuery("institutionalItemCountForCollectionAndchildren", ids)); } /** * Get a count of institutional items in a collection. * * @param collectionId - id of the collection * @return */ public Long getCount(InstitutionalCollection collection) { return (Long)HbHelper.getUnique(hbCrudDAO.getHibernateTemplate().findByNamedQuery("institutionalItemCountForCollection", collection.getId())); } public Long getCountByGenericItem(Long genericItemId) { return (Long)HbHelper.getUnique(hbCrudDAO.getHibernateTemplate().findByNamedQuery("institutionalItemCountForGenericItem", genericItemId)); } /** * Get all institutional items that contain any of the generic item ids in the given list. * * @param genericItemIds - list of generic item ids * @return list of institutional items found. */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getInstitutionalItemsByGenericItemIds(List<Long> genericItemIds) { //getInstitutionalItemsForGenericItemIds Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = session.getNamedQuery("getInstitutionalItemsForGenericItemIds"); q.setParameterList("itemIds", genericItemIds); return q.list(); } /** * @see edu.ur.ir.institution.InstitutionalItemDAO#getCollectionItemsBetweenChar(int, int, edu.ur.ir.institution.InstitutionalCollection, char, char, java.lang.String) */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getCollectionItemsBetweenChar( final int rowStart, final int maxResults, final InstitutionalCollection collection, final char firstChar, final char lastChar, final OrderType orderType) { Query q = null; if(collection != null ) { if (orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = hbCrudDAO.getSessionFactory().getCurrentSession() .getNamedQuery("getCollectionItemsByCharRangeOrderDesc"); } else { q = hbCrudDAO.getSessionFactory().getCurrentSession() .getNamedQuery("getCollectionItemsByCharRangeOrderAsc"); } q.setLong("leftVal", collection.getLeftValue()); q.setLong("rightVal", collection.getRightValue()); q.setLong("rootId", collection.getTreeRoot().getId()); q.setCharacter("firstChar", Character.toLowerCase(firstChar)); q.setCharacter("lastChar", Character.toLowerCase(lastChar)); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } else { return new LinkedList<InstitutionalItem>(); } } /** * * @see edu.ur.ir.institution.InstitutionalItemDAO#getCollectionItemsByChar(int, int, edu.ur.ir.institution.InstitutionalCollection, char, java.lang.String) */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getCollectionItemsByChar(final int rowStart, final int maxResults, final InstitutionalCollection collection, final char firstChar, final OrderType orderType) { if( collection != null ) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if (orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session .getNamedQuery("getInstitutionalCollectionItemsByCharOrderDesc"); } else { q = session .getNamedQuery("getInstitutionalCollectionItemsByCharOrderAsc"); } q.setLong("leftVal", collection.getLeftValue()); q.setLong("rightVal", collection.getRightValue()); q.setLong("rootId", collection.getTreeRoot().getId()); q.setCharacter("firstChar", Character.toLowerCase(firstChar)); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } else { return new LinkedList<InstitutionalItem>(); } } /** * @see edu.ur.ir.institution.InstitutionalItemDAO#getCount(edu.ur.ir.institution.InstitutionalCollection, char) */ public Long getCount(InstitutionalCollection collection, char nameFirstChar) { if( collection != null ) { Object[] values = new Object[]{ collection.getLeftValue(), collection.getRightValue(), collection.getTreeRoot().getId(), Character.valueOf(Character.toLowerCase(nameFirstChar))}; return (Long)HbHelper.getUnique(hbCrudDAO.getHibernateTemplate().findByNamedQuery("institutionalItemCountForCollectionByChar", values)); } else { return 0; } } /** * @see edu.ur.ir.institution.InstitutionalItemDAO#getCount(edu.ur.ir.institution.InstitutionalCollection, char, char) */ public Long getCount(InstitutionalCollection collection, char nameFirstCharRange, char namelastCharRange) { if( collection != null ) { Object[] values = new Object[]{ collection.getLeftValue(), collection.getRightValue(), collection.getTreeRoot().getId(), Character.valueOf(Character.toLowerCase(nameFirstCharRange)), Character.valueOf(Character.toLowerCase(namelastCharRange))}; return (Long)HbHelper.getUnique(hbCrudDAO.getHibernateTemplate().findByNamedQuery("institutionalItemCountForCollectionByCharRange", values)); } else { return 0l; } } /** * Get a count of distinct institutional items in the repository. * * @return */ public Long getDistinctInstitutionalItemCount() { return (Long)HbHelper.getUnique(hbCrudDAO.getHibernateTemplate().findByNamedQuery("distinctInstitutionalItemCount")); } /** * Get a institutional collections the generic item exists in * * @return */ @SuppressWarnings("unchecked") public List<InstitutionalCollection> getInstitutionalCollectionsForGenericItem(Long itemId) { return (List<InstitutionalCollection>) hbCrudDAO.getHibernateTemplate().findByNamedQuery("getCollectionsForGenericItem", itemId); } /** * get the publication count for given name id. * * @see edu.ur.ir.institution.InstitutionalItemDAO#getPublicationCountByPersonName(List) */ public Long getPublicationCountByPersonName(List<Long> personNameIds) { Query q = hbCrudDAO.getHibernateTemplate().getSessionFactory().getCurrentSession().getNamedQuery("getPublicationCountByPersonNameId"); q.setParameterList("personNameIds", personNameIds); Long count = (Long)q.uniqueResult(); return count; } /** * Get Institutional item by given version id * * @see edu.ur.ir.institution.InstitutionalItemDAO#getInstitutionalItemByVersionId(Long) */ public InstitutionalItem getInstitutionalItemByVersionId(Long institutionalVerisonId) { return (InstitutionalItem) HbHelper.getUnique(hbCrudDAO.getHibernateTemplate().findByNamedQuery("getInstitutionalItemByVersionId", institutionalVerisonId)); } /** * Get a institutional items where the generic item is the latest version * * @return */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getInstitutionalItemsForGenericItemId(Long itemId) { return (List<InstitutionalItem>) hbCrudDAO.getHibernateTemplate().findByNamedQuery("getInstitutionalItemsForGenericItemId", itemId); } /** * @see edu.ur.ir.institution.InstitutionalItemDAO#getItems(int, int, edu.ur.ir.institution.InstitutionalCollection, java.util.Date, java.util.Date) */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getItemsOrderByDate(final int rowStart, final int maxResults, final InstitutionalCollection collection, final OrderType orderType) { if( collection != null ) { List<InstitutionalItem> foundItems = (List<InstitutionalItem>) hbCrudDAO.getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getInstitutionalCollectionItemsByAcceptedDateDesc"); } else { q = session.getNamedQuery("getInstitutionalCollectionItemsByAcceptedDateAsc"); } q.setLong(0, collection.getId()); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } }); return foundItems; } else { return new LinkedList<InstitutionalItem>(); } } /** * @see edu.ur.ir.institution.InstitutionalItemDAO#getItems(edu.ur.ir.institution.InstitutionalCollection, java.util.Date, java.util.Date) */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getItems(final InstitutionalCollection collection, final Date startDate, final Date endDate) { if(collection != null && startDate != null && endDate != null ) { log.debug("Trying dates " + startDate + " and " + endDate); List<InstitutionalItem> foundItems = (List<InstitutionalItem>) hbCrudDAO.getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Query q = null; q = session.getNamedQuery("getInstitutionalCollectionItemsByAcceptedDateRange"); q.setLong(0, collection.getId()); q.setTimestamp(1, startDate); q.setTimestamp(2, endDate); return q.list(); } }); return foundItems; } else { return new LinkedList<InstitutionalItem>(); } } /** * Get the list of collection items by id. * * @see edu.ur.ir.institution.InstitutionalItemDAO#getCollectionItemsById(int, int, edu.ur.ir.institution.InstitutionalCollection, edu.ur.order.OrderType) */ @SuppressWarnings("unchecked") public List<Long> getCollectionItemsIds(final int rowStart, final int maxResults, final InstitutionalCollection collection, final OrderType orderType) { if( collection != null ) { List<Long> foundIds = (List<Long>) hbCrudDAO.getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getInstitutionalCollectionItemIdsOrderDesc"); } else { q = session.getNamedQuery("getInstitutionalCollectionItemIdsOrderAsc"); } q.setLong(0, collection.getLeftValue()); q.setLong(1, collection.getRightValue()); q.setLong(2, collection.getTreeRoot().getId()); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } }); return foundIds; } else { return new LinkedList<Long>(); } } /** * Get a list of items for a specified repository by between the that have titles * that start between the specified characters * * NOTE: This search includes all items in child collections * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param collection - the institutional collection * @param contentTypeId - content type id the items must have * @param firstChar - first character in range that the first letter of the name can have * @param lastChar - last character in range that the first letter of the name can have * @param orderType - The order to sort by (asc/desc) * * @return list of items matching the specified criteria * * @see edu.ur.ir.institution.InstitutionalItemDAO#getCollectionItemsBetweenChar(int, int, edu.ur.ir.institution.InstitutionalCollection, java.lang.Long, char, char, edu.ur.order.OrderType) */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getCollectionItemsBetweenChar(int rowStart, int maxResults, InstitutionalCollection collection, Long contentTypeId, char firstChar, char lastChar, OrderType orderType) { if( collection != null ) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getCollectionItemsContentTypeByCharRangeOrderDesc"); } else { q = session.getNamedQuery("getCollectionItemsContentTypeByCharRangeOrderAsc"); } q.setParameter("leftVal", collection.getLeftValue()); q.setParameter("rightVal", collection.getRightValue()); q.setParameter("rootId", collection.getTreeRoot().getId()); q.setParameter("firstChar", Character.valueOf(Character.toLowerCase(firstChar))); q.setParameter("lastChar", Character.valueOf(Character.toLowerCase(lastChar))); q.setParameter("contentTypeId", contentTypeId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } else { return new LinkedList<InstitutionalItem>(); } } /** * Get a list of items for a specified collection by first character of the name * * NOTE: This search includes all items in child collections * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param institutional collection - the institutional collection * @param contentTypeId - id of the content type * @param firstChar - first character that the name should have * @param orderType - The order to sort by (asc/desc) * * @return List of institutional items * * @see edu.ur.ir.institution.InstitutionalItemDAO#getCollectionItemsByChar(int, int, edu.ur.ir.institution.InstitutionalCollection, java.lang.Long, char, edu.ur.order.OrderType) */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getCollectionItemsByChar(int rowStart, int maxResults, InstitutionalCollection collection, Long contentTypeId, char firstChar, OrderType orderType) { if(collection != null ) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getInstitutionalCollectionItemsContentTypeByCharOrderDesc"); } else { q = session.getNamedQuery("getInstitutionalCollectionItemsContentTypeByCharOrderAsc"); } q.setParameter("leftVal", collection.getLeftValue()); q.setParameter("rightVal", collection.getRightValue()); q.setParameter("rootId", collection.getTreeRoot().getId()); q.setParameter("firstChar", Character.valueOf(Character.toLowerCase(firstChar))); q.setParameter("contentTypeId", contentTypeId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } else { return new LinkedList<InstitutionalItem>(); } } /** * Get the list of items for the specified collection with the given * content type id. This includes items in child collections * * @param rowStart - Start row to fetch the data from * @param maxResults - maximum number of results to return * @param collection - the collection to get items * @param contentTypeId - id of the content type * @param orderType - The order to sort by (ascending/descending) * * @return List of institutional items * * @see edu.ur.ir.institution.InstitutionalItemDAO#getCollectionItemsByName(int, int, edu.ur.ir.institution.InstitutionalCollection, java.lang.Long, edu.ur.order.OrderType) */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getCollectionItemsByName(int rowStart, int maxResults, InstitutionalCollection collection, Long contentTypeId, OrderType orderType) { if( collection != null ) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getInstitutionalCollectionItemsContentTypeByNameOrderDesc"); } else { q = session.getNamedQuery("getInstitutionalCollectionItemsContentTypeByNameOrderAsc"); } q.setParameter("leftVal", collection.getLeftValue()); q.setParameter("rightVal", collection.getRightValue()); q.setParameter("rootId", collection.getTreeRoot().getId()); q.setParameter("contentTypeId", contentTypeId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } else { return new LinkedList<InstitutionalItem>(); } } /** * Get a count of institutional items with the given content type id. * * @param repositoryId - id of the repository * @param contentTypeId - content type * * @return the count of institutional items with the content type in the specified * repository. */ public Long getCount(Long repositoryId, Long contentTypeId) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = session.getNamedQuery("getRepositoryItemsContentTypeCount"); q.setParameter("repositoryId", repositoryId); q.setParameter("contentTypeId", contentTypeId); return (Long)q.uniqueResult(); } /** * Get a count of institutional items with the specified repository id * has a name starting with the first character and the specified content type id. * * @param repositoryId - id of the repository * @param nameFirstChar - name of the first character * @param contentTypeId - specified content type id * * @return the count of items with the specified criteria */ public Long getCount(Long repositoryId, char firstChar, Long contentTypeId) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = session.getNamedQuery("institutionalItemCountContentTypeForRepositoryByChar"); q.setParameter("repositoryId", repositoryId); q.setParameter("contentTypeId", contentTypeId); q.setParameter("char", Character.valueOf(Character.toLowerCase(firstChar))); return (Long)q.uniqueResult(); } /** * Get a count of all items within the specified repository with a name * first character starting between the given character range and the content type id. * * @param repositoryId - id of the repository * @param nameFirstCharRange - starting character range * @param namelastCharRange - ending character range * @param contentTypeId - id of the content type * * @return the count of items */ public Long getCount(Long repositoryId, char nameFirstCharRange, char namelastCharRange, Long contentTypeId) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = session.getNamedQuery("institutionalItemCountForRepositoryContentTypeByCharRange"); q.setParameter("repositoryId", repositoryId); q.setParameter("contentTypeId", contentTypeId); q.setParameter("firstChar", Character.valueOf(Character.toLowerCase(nameFirstCharRange))); q.setParameter("lastChar", Character.valueOf(Character.toLowerCase(namelastCharRange))); return (Long)q.uniqueResult(); } /** * Get a count of all items within the specified collection, has the specified first character * and a given content type id. This includes a count of items within sub collections. * * @param collection - collection items must be within sub collections * @param nameFirstChar - name starts with the specified first character * @param contentTypeId - id of the content type * * @return count of items */ public Long getCount(InstitutionalCollection collection, char nameFirstChar, Long contentTypeId) { if( collection != null ) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = session.getNamedQuery("institutionalItemCountForCollectionContentTypeByChar"); q.setParameter("leftVal", collection.getLeftValue()); q.setParameter("rightVal", collection.getRightValue()); q.setParameter("contentTypeId", contentTypeId); q.setParameter("rootId", collection.getTreeRoot().getId()); q.setParameter("firstChar", Character.valueOf(Character.toLowerCase(nameFirstChar))); return (Long)q.uniqueResult(); } else { return 0l; } } /** Get a count of all institutional items in the specified collection with * specified first character in the given character range with the given content type id- THIS INCLUDES items in child collections * * @param institutional collection - parent collection * @param nameFirstCharRange - first character in range * @param nameLastCharRange - last character in the range * * @return count of titles found that have a first character in the specified range */ public Long getCount(InstitutionalCollection collection, char nameFirstCharRange, char nameLastCharRange, Long contentTypeId) { if(collection != null) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = session.getNamedQuery("institutionalItemCountForCollectionContentTypeByCharRange"); q.setParameter("leftVal", collection.getLeftValue()); q.setParameter("rightVal", collection.getRightValue()); q.setParameter("contentTypeId", contentTypeId); q.setParameter("rootId", collection.getTreeRoot().getId()); q.setParameter("firstChar", Character.valueOf(Character.toLowerCase(nameFirstCharRange))); q.setParameter("lastChar", Character.valueOf(Character.toLowerCase(nameLastCharRange))); return (Long)q.uniqueResult(); } else { return 0l; } } /** * Get a count of institutional items in a collection and its children with * the specified content type. * * @param collection - collection to start counting from * @param contentTypeId - id of the content type * * @return Items within the specified collection and its sub collection */ public Long getCount(InstitutionalCollection collection, Long contentTypeId) { if( collection != null ) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = session.getNamedQuery("getInstitutionalCollectionItemsContentTypeCount"); q.setParameter("leftVal", collection.getLeftValue()); q.setParameter("rightVal", collection.getRightValue()); q.setParameter("contentTypeId", contentTypeId); q.setParameter("rootId", collection.getTreeRoot().getId()); return (Long)q.uniqueResult(); } else { return 0l; } } /** * Get a list of items for a specified repository by between the that have titles * that start between the specified characters with the given content type id * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param repositoryId - id of the repository to get items * @param firstChar - first character in range that the first letter of the name can have * @param lastChar - last character in range that the first letter of the name can have * @param contentTypeId - id of the content type * @param orderType - The order to sort by (asc/desc) * * @return List of institutional items * @see edu.ur.ir.institution.InstitutionalItemDAO#getRepositoryItemsBetweenChar(int, int, java.lang.Long, char, char, java.lang.Long, edu.ur.order.OrderType) */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getRepositoryItemsBetweenChar(int rowStart, int maxResults, Long repositoryId, char firstChar, char lastChar, Long contentTypeId, OrderType orderType) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getRepositoryItemsContentTypeByCharRangeOrderDesc"); } else { q = session.getNamedQuery("getRepositoryItemsContentTypeByCharRangeOrderAsc"); } q.setParameter("repositoryId", repositoryId); q.setParameter("firstChar",Character.valueOf(Character.toLowerCase(firstChar))); q.setParameter("lastChar", Character.valueOf(Character.toLowerCase(lastChar))); q.setParameter("contentTypeId", contentTypeId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } /** * Get a list of items for a specified repository by first character of the name and * the given content type id * * @param rowStart - Start row to fetch the data from * @param maxResults - maximum number of results to fetch * @param repositoryId - id of the repository to get items * @param contentTypeId - id of the content type * @param firstChar - first character that the name should have * @param orderType - The order to sort by (asc/desc) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getRepositoryItemsByChar(int rowStart, int maxResults, Long repositoryId, Long contentTypeId, char firstChar, OrderType orderType) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getRepositoryItemsContentTypeByCharOrderDesc"); } else { q = session.getNamedQuery("getRepositoryItemsContentTypeByCharOrderAsc"); } q.setParameter("repositoryId", repositoryId); q.setParameter("char", Character.valueOf(Character.toLowerCase(firstChar))); q.setParameter("contentTypeId", contentTypeId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } /** * Get a list of items for a specified repository with the given content type id. * * @param rowStart - Start row to fetch the data from * @param rowEnd - End row to get data * @param repositoryId - id of the repository to get items * @param contentTypeId - id of the content type * @param propertyName - The property to sort on * @param orderType - The order to sort by (ascending/descending) * * @return List of institutional items * @see edu.ur.ir.institution.InstitutionalItemDAO#getRepositoryItemsOrderByName(int, int, java.lang.Long, java.lang.Long, edu.ur.order.OrderType) */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getRepositoryItemsOrderByName(int rowStart, int maxResults, Long repositoryId, Long contentTypeId, OrderType orderType) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getRepositoryItemsContentTypeByNameOrderDesc"); } else { q = session.getNamedQuery("getRepositoryItemsContentTypeByNameOrderAsc"); } q.setParameter("repositoryId", repositoryId); q.setParameter("contentTypeId", contentTypeId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } /** * Get a list of of repository content types with counts for the number * of items within the repository. This will return only those * items that have a count greater than 0. * * @return - list of content type counts * @see edu.ur.ir.institution.InstitutionalItemDAO#getRepositoryContentTypeCount() */ @SuppressWarnings("unchecked") public List<ContentTypeCount> getRepositoryContentTypeCount(Long repositoryId) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = session.getNamedQuery("getRepositoryItemsSumByContentType"); q.setParameter("repositoryId", repositoryId); return q.list(); } /** * Get a list of of repository content types with counts for the number * of items within the repository. * * @param collection - institutional collection * @return - list of content type counts * * @see edu.ur.ir.institution.InstitutionalItemService#getRepositoryContentTypeCount() */ @SuppressWarnings("unchecked") public List<ContentTypeCount> getCollectionContentTypeCount(InstitutionalCollection collection) { if( collection != null ) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = session.getNamedQuery("getCollectionItemsSumByContentType"); q.setParameter("leftVal", collection.getLeftValue()); q.setParameter("rightVal", collection.getRightValue()); q.setParameter("rootId", collection.getTreeRoot().getId()); return q.list(); } else { return new LinkedList<ContentTypeCount>(); } } /** * Get a list of items for a specified repository by between the that have titles * that start between the specified characters * * NOTE: This search includes all items in child collections * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param collection - the institutional collection * @param firstChar - first character in range that the first letter of the name can have * @param lastChar - last character in range that the first letter of the name can have * @param orderType - The order to sort by (asc/desc) * * @return list of items matching the specified criteria * * @see edu.ur.ir.institution.InstitutionalItemDAO#getCollectionItemsBetweenChar(int, int, edu.ur.ir.institution.InstitutionalCollection, java.lang.Long, char, char, edu.ur.order.OrderType) */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getCollectionItemsBetweenCharPublicationDateOrder( int rowStart, int maxResults, InstitutionalCollection collection, char firstChar, char lastChar, OrderType orderType) { if( collection != null) { Query q = null; if (orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = hbCrudDAO.getSessionFactory().getCurrentSession() .getNamedQuery("getInstitutionalCollectionItemsByCharRangePublicationDateOrderDesc"); } else { q = hbCrudDAO.getSessionFactory().getCurrentSession() .getNamedQuery("getInstitutionalCollectionItemsByCharRangePublicationDateOrderAsc"); } q.setLong("leftVal", collection.getLeftValue()); q.setLong("rightVal", collection.getRightValue()); q.setLong("rootId", collection.getTreeRoot().getId()); q.setCharacter("firstChar", Character.toLowerCase(firstChar)); q.setCharacter("lastChar", Character.toLowerCase(lastChar)); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } else { return new LinkedList<InstitutionalItem>(); } } /** * Get a list of items for a specified repository by between the that have titles * that start between the specified characters * * NOTE: This search includes all items in child collections * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param collection - the institutional collection * @param contentTypeId - content type id the items must have * @param firstChar - first character in range that the first letter of the name can have * @param lastChar - last character in range that the first letter of the name can have * @param orderType - The order to sort by (asc/desc) * * @return list of items matching the specified criteria * * @see edu.ur.ir.institution.InstitutionalItemDAO#getCollectionItemsBetweenChar(int, int, edu.ur.ir.institution.InstitutionalCollection, java.lang.Long, char, char, edu.ur.order.OrderType) */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getCollectionItemsBetweenCharPublicationDateOrder( int rowStart, int maxResults, InstitutionalCollection collection, Long contentTypeId, char firstChar, char lastChar, OrderType orderType) { if( collection != null ) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getCollectionItemsContentTypeByCharRangePublicationDateOrderDesc"); } else { q = session.getNamedQuery("getCollectionItemsContentTypeByCharRangePublicationDateOrderAsc"); } q.setParameter("leftVal", collection.getLeftValue()); q.setParameter("rightVal", collection.getRightValue()); q.setParameter("rootId", collection.getTreeRoot().getId()); q.setParameter("firstChar", Character.valueOf(Character.toLowerCase(firstChar))); q.setParameter("lastChar", Character.valueOf(Character.toLowerCase(lastChar))); q.setParameter("contentTypeId", contentTypeId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } else { return new LinkedList<InstitutionalItem>(); } } /** * Get a list of items for a specified collection by first character of the name * * NOTE: This search includes all items in child collections * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param institutional collection - the institutional collection * @param firstChar - first character that the name should have * @param orderType - The order to sort by (asc/desc) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getCollectionItemsByCharPublicationDateOrder( int rowStart, int maxResults, InstitutionalCollection collection, char firstChar, OrderType orderType) { if( collection != null ) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if (orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session .getNamedQuery("getInstitutionalCollectionItemsByCharPublicationDateOrderDesc"); } else { q = session .getNamedQuery("getInstitutionalCollectionItemsByCharPublicationDateOrderAsc"); } q.setLong("leftVal", collection.getLeftValue()); q.setLong("rightVal", collection.getRightValue()); q.setLong("rootId", collection.getTreeRoot().getId()); q.setCharacter("firstChar", Character.toLowerCase(firstChar)); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } else { return new LinkedList<InstitutionalItem>(); } } /** * Get a list of items for a specified collection by first character of the name * * NOTE: This search includes all items in child collections * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param institutional collection - the institutional collection * @param contentTypeId - id of the content type * @param firstChar - first character that the name should have * @param orderType - The order to sort by (asc/desc) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getCollectionItemsByCharPublicationDateOrder( int rowStart, int maxResults, InstitutionalCollection collection, Long contentTypeId, char firstChar, OrderType orderType) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( collection != null ) { if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getInstitutionalCollectionItemsContentTypeByCharPublicationDateOrderDesc"); } else { q = session.getNamedQuery("getInstitutionalCollectionItemsContentTypeByCharPublicationDateOrderAsc"); } q.setParameter("leftVal", collection.getLeftValue()); q.setParameter("rightVal", collection.getRightValue()); q.setParameter("rootId", collection.getTreeRoot().getId()); q.setParameter("firstChar", Character.valueOf(Character.toLowerCase(firstChar))); q.setParameter("contentTypeId", contentTypeId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } else { return new LinkedList<InstitutionalItem>(); } } /** * Get the list of items for the specified collection. * This includes items in child collections * * @param rowStart - Start row to fetch the data from * @param maxResults - maximum number of results to return * @param collection - the collection to get items * @param orderType - The order to sort by (ascending/descending) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getCollectionItemsPublicationDateOrder( int rowStart, int maxResults, InstitutionalCollection collection, OrderType orderType) { if(collection != null ) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if (orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session .getNamedQuery("getInstitutionalCollectionItemsPublicationDateOrderDesc"); } else { q = session .getNamedQuery("getInstitutionalCollectionItemsPublicationDateOrderAsc"); } q.setLong("leftVal", collection.getLeftValue()); q.setLong("rightVal", collection.getRightValue()); q.setLong("rootId", collection.getTreeRoot().getId()); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } else { return new LinkedList<InstitutionalItem>(); } } /** * Get the list of items for the specified collection with the given * content type id. This includes items in child collections * * @param rowStart - Start row to fetch the data from * @param maxResults - maximum number of results to return * @param collection - the collection to get items * @param contentTypeId - id of the content type * @param orderType - The order to sort by (ascending/descending) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getCollectionItemsPublicationDateOrder( int rowStart, int maxResults, InstitutionalCollection collection, Long contentTypeId, OrderType orderType) { if( collection != null ) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if (orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session .getNamedQuery("getInstitutionalCollectionItemsContentTypeByPublicationDateOrderDesc"); } else { q = session .getNamedQuery("getInstitutionalCollectionItemsContentTypeByPublicationDateOrderAsc"); } q.setLong("leftVal", collection.getLeftValue()); q.setLong("rightVal", collection.getRightValue()); q.setLong("rootId", collection.getTreeRoot().getId()); q.setLong("contentTypeId", contentTypeId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } else { return new LinkedList<InstitutionalItem>(); } } /** * Get a list of items for a specified repository by between the that have titles * that start between the specified characters * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param repositoryId - id of the repository to get items * @param firstChar - first character in range that the first letter of the name can have * @param lastChar - last character in range that the first letter of the name can have * @param orderType - The order to sort by (asc/desc) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getRepositoryItemsBetweenCharPublicationDateOrder( int rowStart, int maxResults, Long repositoryId, char firstChar, char lastChar, OrderType orderType) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if (orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getRepositoryItemsByCharRangePublicationDateOrderDesc"); } else { q = session.getNamedQuery("getRepositoryItemsByCharRangePublicationDateOrderAsc"); } q.setLong("repositoryId", repositoryId); q.setCharacter("firstChar", Character.toLowerCase(firstChar)); q.setCharacter("lastChar", Character.toLowerCase(lastChar)); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } /** * Get a list of items for a specified repository by between the that have titles * that start between the specified characters with the given content type id * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param repositoryId - id of the repository to get items * @param firstChar - first character in range that the first letter of the name can have * @param lastChar - last character in range that the first letter of the name can have * @param contentTypeId - id of the content type * @param orderType - The order to sort by (asc/desc) * * @return List of institutional items * @see edu.ur.ir.institution.InstitutionalItemDAO#getRepositoryItemsBetweenChar(int, int, java.lang.Long, char, char, java.lang.Long, edu.ur.order.OrderType) */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getRepositoryItemsBetweenCharPublicationDateOrder( int rowStart, int maxResults, Long repositoryId, char firstChar, char lastChar, Long contentTypeId, OrderType orderType) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getRepositoryItemsContentTypeByCharRangeOrderDesc"); } else { q = session.getNamedQuery("getRepositoryItemsContentTypeByCharRangeOrderAsc"); } q.setParameter("repositoryId", repositoryId); q.setParameter("firstChar",Character.valueOf(Character.toLowerCase(firstChar))); q.setParameter("lastChar", Character.valueOf(Character.toLowerCase(lastChar))); q.setParameter("contentTypeId", contentTypeId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } /** * Get a list of items for a specified repository by first character of the name and * the given content type id * * @param rowStart - Start row to fetch the data from * @param maxResults - maximum number of results to fetch * @param repositoryId - id of the repository to get items * @param contentTypeId - id of the content type * @param firstChar - first character that the name should have * @param orderType - The order to sort by (asc/desc) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getRepositoryItemsByCharPublicationDateOrder( int rowStart, int maxResults, Long repositoryId, Long contentTypeId, char firstChar, OrderType orderType) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getRepositoryItemsContentTypeByCharPublicationDateOrderDesc"); } else { q = session.getNamedQuery("getRepositoryItemsContentTypeByCharPublicationDateOrderAsc"); } q.setParameter("repositoryId", repositoryId); q.setParameter("char", Character.valueOf(Character.toLowerCase(firstChar))); q.setParameter("contentTypeId", contentTypeId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } /** * Get a list of items for a specified repository by between the that have titles * that start between the specified characters * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param repositoryId - id of the repository to get items * @param firstChar - first character in range that the first letter of the name can have * @param lastChar - last character in range that the first letter of the name can have * @param orderType - The order to sort by (asc/desc) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getRepositoryItemsByCharPublicationDateOrder( int rowStart, int maxResults, Long repositoryId, char firstChar, OrderType orderType) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if (orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getRepositoryItemsByCharPublicationDateOrderDesc"); } else { q = session.getNamedQuery("getRepositoryItemsByCharPublicationDateOrderAsc"); } q.setLong("repositoryId", repositoryId); q.setCharacter("firstChar", Character.toLowerCase(firstChar)); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } /** * Get a list of items for a specified repository by publication date. * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param repositoryId - id of the collection to get items * @param orderType - The order to sort by (ascending/descending) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getRepositoryItemsPublicationDateOrder( int rowStart, int maxResults, Long repositoryId, OrderType orderType) { Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = hbCrudDAO.getSessionFactory().getCurrentSession().getNamedQuery("getRepositoryItemsByPublicationDateOrderDesc"); } else { q = hbCrudDAO.getSessionFactory().getCurrentSession().getNamedQuery("getRepositoryItemsByPublicationDateOrderAsc"); } q.setLong("repositoryId", repositoryId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setCacheable(false); q.setReadOnly(true); q.setFetchSize(maxResults); return (List<InstitutionalItem>)q.list(); } /** * Get a list of items for a specified repository by publication date. * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param repositoryId - id of the collection to get items * @param contentTypeId - id of the content type * @param orderType - The order to sort by (ascending/descending) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getRepositoryItemsPublicationDateOrder( int rowStart, int maxResults, Long repositoryId, Long contentTypeId, OrderType orderType) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getRepositoryItemsContentTypeByPublicationDateOrderDesc"); } else { q = session.getNamedQuery("getRepositoryItemsContentTypeByPublicationDateOrderAsc"); } q.setParameter("repositoryId", repositoryId); q.setParameter("contentTypeId", contentTypeId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } /** * Get the list of items for the specified collection with the given * content type id. This includes items in child collections * * @param rowStart - Start row to fetch the data from * @param maxResults - maximum number of results to return * @param collection - the collection to get items * @param orderType - The order to sort by (ascending/descending) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getCollectionItemsFirstAvailableOrder( int rowStart, int maxResults, InstitutionalCollection collection, OrderType orderType) { if(collection != null ) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if (orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session .getNamedQuery("getInstitutionalCollectionItemsFirstAvailableOrderDesc"); } else { q = session .getNamedQuery("getInstitutionalCollectionItemsFirstAvailableOrderAsc"); } q.setLong("leftVal", collection.getLeftValue()); q.setLong("rightVal", collection.getRightValue()); q.setLong("rootId", collection.getTreeRoot().getId()); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } else { return new LinkedList<InstitutionalItem>(); } } /** * Get the list of items for the specified collection with the given * content type id. This includes items in child collections * * @param rowStart - Start row to fetch the data from * @param maxResults - maximum number of results to return * @param collection - the collection to get items * @param contentTypeId - id of the content type * @param orderType - The order to sort by (ascending/descending) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getCollectionItemsFirstAvailableOrder( int rowStart, int maxResults, InstitutionalCollection collection, Long contentTypeId, OrderType orderType) { if(collection != null ) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if (orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session .getNamedQuery("getInstitutionalCollectionItemsContentTypeByFirstAvailableOrderDesc"); } else { q = session .getNamedQuery("getInstitutionalCollectionItemsContentTypeByFirstAvailableOrderAsc"); } q.setLong("leftVal", collection.getLeftValue()); q.setLong("rightVal", collection.getRightValue()); q.setLong("rootId", collection.getTreeRoot().getId()); q.setLong("contentTypeId", contentTypeId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } else { return new LinkedList<InstitutionalItem>(); } } /** * Get a list of items for a specified repository by between the that have titles * that start between the specified characters * * NOTE: This search includes all items in child collections * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param collection - the institutional collection * @param firstChar - first character in range that the first letter of the name can have * @param lastChar - last character in range that the first letter of the name can have * @param orderType - The order to sort by (asc/desc) * * @return list of items matching the specified criteria * * @see edu.ur.ir.institution.InstitutionalItemDAO#getCollectionItemsBetweenChar(int, int, edu.ur.ir.institution.InstitutionalCollection, java.lang.Long, char, char, edu.ur.order.OrderType) */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getCollectionItemsBetweenCharFirstAvailableOrder( int rowStart, int maxResults, InstitutionalCollection collection, char firstChar, char lastChar, OrderType orderType) { if( collection != null ) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getInstitutionalCollectionItemsByCharRangeFirstAvailableOrderDesc"); } else { q = session.getNamedQuery("getInstitutionalCollectionItemsByCharRangeFirstAvailableOrderAsc"); } q.setParameter("leftVal", collection.getLeftValue()); q.setParameter("rightVal", collection.getRightValue()); q.setParameter("rootId", collection.getTreeRoot().getId()); q.setParameter("firstChar", Character.valueOf(Character.toLowerCase(firstChar))); q.setParameter("lastChar", Character.valueOf(Character.toLowerCase(lastChar))); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } else { return new LinkedList<InstitutionalItem>(); } } /** * Get a list of items for a specified repository by between the that have titles * that start between the specified characters * * NOTE: This search includes all items in child collections * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param collection - the institutional collection * @param contentTypeId - id of the content type * @param firstChar - first character in range that the first letter of the name can have * @param lastChar - last character in range that the first letter of the name can have * @param orderType - The order to sort by (asc/desc) * * @return list of items matching the specified criteria * * @see edu.ur.ir.institution.InstitutionalItemDAO#getCollectionItemsBetweenChar(int, int, edu.ur.ir.institution.InstitutionalCollection, java.lang.Long, char, char, edu.ur.order.OrderType) */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getCollectionItemsBetweenCharFirstAvailableOrder( int rowStart, int maxResults, InstitutionalCollection collection, Long contentTypeId, char firstChar, char lastChar, OrderType orderType) { if( collection != null ) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getInstitutionalCollectionItemsContentTypeByCharRangeFirstAvailableOrderDesc"); } else { q = session.getNamedQuery("getInstitutionalCollectionItemsContentTypeByCharRangeFirstAvailableOrderAsc"); } q.setParameter("leftVal", collection.getLeftValue()); q.setParameter("rightVal", collection.getRightValue()); q.setParameter("rootId", collection.getTreeRoot().getId()); q.setParameter("firstChar", Character.valueOf(Character.toLowerCase(firstChar))); q.setParameter("lastChar", Character.valueOf(Character.toLowerCase(lastChar))); q.setParameter("contentTypeId", contentTypeId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } else { return new LinkedList<InstitutionalItem>(); } } /** * Get a list of items for a specified collection by first character of the name * * NOTE: This search includes all items in child collections * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param institutional collection - the institutional collection * @param firstChar - first character that the name should have * @param orderType - The order to sort by (asc/desc) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getCollectionItemsByCharFirstAvailableOrder( int rowStart, int maxResults, InstitutionalCollection collection, char firstChar, OrderType orderType) { if(collection != null ) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getInstitutionalCollectionItemsByCharFirstAvailableOrderDesc"); } else { q = session.getNamedQuery("getInstitutionalCollectionItemsByCharFirstAvailableOrderAsc"); } q.setParameter("leftVal", collection.getLeftValue()); q.setParameter("rightVal", collection.getRightValue()); q.setParameter("rootId", collection.getTreeRoot().getId()); q.setParameter("firstChar", Character.valueOf(Character.toLowerCase(firstChar))); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } else { return new LinkedList<InstitutionalItem>(); } } /** * Get a list of items for a specified collection by first character of the name * * NOTE: This search includes all items in child collections * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param institutional collection - the institutional collection * @param contentTypeId - id of the content type * @param firstChar - first character that the name should have * @param orderType - The order to sort by (asc/desc) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getCollectionItemsByCharFirstAvailableOrder( int rowStart, int maxResults, InstitutionalCollection collection, Long contentTypeId, char firstChar, OrderType orderType) { if( collection != null ) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getInstitutionalCollectionItemsContentTypeByCharFirstAvailableOrderDesc"); } else { q = session.getNamedQuery("getInstitutionalCollectionItemsContentTypeByCharFirstAvailableOrderAsc"); } q.setParameter("leftVal", collection.getLeftValue()); q.setParameter("rightVal", collection.getRightValue()); q.setParameter("rootId", collection.getTreeRoot().getId()); q.setParameter("firstChar", Character.valueOf(Character.toLowerCase(firstChar))); q.setParameter("contentTypeId", contentTypeId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } else { return new LinkedList<InstitutionalItem>(); } } /** * Get a list of items for a specified repository by publication date. * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param repositoryId - id of the collection to get items * @param contentTypeId - id of the content type * @param orderType - The order to sort by (ascending/descending) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getRepositoryItemsFirstAvailableOrder( int rowStart, int maxResults, Long repositoryId, Long contentTypeId, OrderType orderType) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getRepositoryItemsContentTypeByFirstAvailableOrderDesc"); } else { q = session.getNamedQuery("getRepositoryItemsContentTypeByFirstAvailableOrderAsc"); } q.setParameter("repositoryId", repositoryId); q.setParameter("contentTypeId", contentTypeId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } /** * Get a list of items for a specified repository by publication date. * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param repositoryId - id of the collection to get items * @param orderType - The order to sort by (ascending/descending) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getRepositoryItemsFirstAvailableOrder( int rowStart, int maxResults, Long repositoryId, OrderType orderType) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getRepositoryItemsByFirstAvailableOrderDesc"); } else { q = session.getNamedQuery("getRepositoryItemsByFirstAvailableOrderAsc"); } q.setParameter("repositoryId", repositoryId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } /** * Get a list of items for a specified repository by between the that have titles * that start between the specified characters with the given content type id * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param repositoryId - id of the repository to get items * @param firstChar - first character in range that the first letter of the name can have * @param lastChar - last character in range that the first letter of the name can have * @param orderType - The order to sort by (asc/desc) * * @return List of institutional items * @see edu.ur.ir.institution.InstitutionalItemDAO#getRepositoryItemsBetweenChar(int, int, java.lang.Long, char, char, java.lang.Long, edu.ur.order.OrderType) */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getRepositoryItemsBetweenCharFirstAvailableOrder( int rowStart, int maxResults, Long repositoryId, char firstChar, char lastChar, OrderType orderType) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getRepositoryItemsByCharRangeFirstAvailableOrderDesc"); } else { q = session.getNamedQuery("getRepositoryItemsByCharRangeFirstAvailableOrderAsc"); } q.setParameter("repositoryId", repositoryId); q.setParameter("firstChar",Character.valueOf(Character.toLowerCase(firstChar))); q.setParameter("lastChar", Character.valueOf(Character.toLowerCase(lastChar))); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } /** * Get a list of items for a specified repository by between the that have titles * that start between the specified characters with the given content type id * * @param rowStart - Start row to fetch the data from * @param maxResulsts - maximum number of results to fetch * @param repositoryId - id of the repository to get items * @param firstChar - first character in range that the first letter of the name can have * @param lastChar - last character in range that the first letter of the name can have * @param contentTypeId - id of the content type * @param orderType - The order to sort by (asc/desc) * * @return List of institutional items * @see edu.ur.ir.institution.InstitutionalItemDAO#getRepositoryItemsBetweenChar(int, int, java.lang.Long, char, char, java.lang.Long, edu.ur.order.OrderType) */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getRepositoryItemsBetweenCharFirstAvailableOrder( int rowStart, int maxResults, Long repositoryId, char firstChar, char lastChar, Long contentTypeId, OrderType orderType) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getRepositoryItemsContentTypeByCharRangeFirstAvailableOrderDesc"); } else { q = session.getNamedQuery("getRepositoryItemsContentTypeByCharRangeFirstAvailableOrderAsc"); } q.setParameter("repositoryId", repositoryId); q.setParameter("firstChar",Character.valueOf(Character.toLowerCase(firstChar))); q.setParameter("lastChar", Character.valueOf(Character.toLowerCase(lastChar))); q.setParameter("contentTypeId", contentTypeId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } /** * Get a list of items for a specified repository by first character of the name and * the given content type id * * @param rowStart - Start row to fetch the data from * @param maxResults - maximum number of results to fetch * @param repositoryId - id of the repository to get items * @param firstChar - first character that the name should have * @param orderType - The order to sort by (asc/desc) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getRepositoryItemsByCharFirstAvailableOrder( int rowStart, int maxResults, Long repositoryId, char firstChar, OrderType orderType) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getRepositoryItemsByCharFirstAvailableOrderDesc"); } else { q = session.getNamedQuery("getRepositoryItemsByCharFirstAvailableOrderAsc"); } q.setParameter("repositoryId", repositoryId); q.setParameter("firstChar", Character.valueOf(Character.toLowerCase(firstChar))); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } /** * Get a list of items for a specified repository by first character of the name and * the given content type id * * @param rowStart - Start row to fetch the data from * @param maxResults - maximum number of results to fetch * @param repositoryId - id of the repository to get items * @param contentTypeId - id of the content type * @param firstChar - first character that the name should have * @param orderType - The order to sort by (asc/desc) * * @return List of institutional items */ @SuppressWarnings("unchecked") public List<InstitutionalItem> getRepositoryItemsByCharFirstAvailableOrder( int rowStart, int maxResults, Long repositoryId, Long contentTypeId, char firstChar, OrderType orderType) { Session session = hbCrudDAO.getSessionFactory().getCurrentSession(); Query q = null; if( orderType != null && orderType.equals(OrderType.DESCENDING_ORDER)) { q = session.getNamedQuery("getRepositoryItemsContentTypeByCharFirstAvailableOrderDesc"); } else { q = session.getNamedQuery("getRepositoryItemsContentTypeByCharFirstAvailableOrderAsc"); } q.setParameter("repositoryId", repositoryId); q.setParameter("char", Character.valueOf(Character.toLowerCase(firstChar))); q.setParameter("contentTypeId", contentTypeId); q.setFirstResult(rowStart); q.setMaxResults(maxResults); q.setFetchSize(maxResults); return q.list(); } }
make sure a long is returned
ir_hibernate/src/edu/ur/hibernate/ir/institution/db/HbInstitutionalItemDAO.java
make sure a long is returned
Java
apache-2.0
6406c193c19d921ab361a6a397c6a3434304cd81
0
ontop/ontop,ConstantB/ontop-spatial,eschwert/ontop,eschwert/ontop,ontop/ontop,ConstantB/ontop-spatial,srapisarda/ontop,srapisarda/ontop,eschwert/ontop,ontop/ontop,ConstantB/ontop-spatial,srapisarda/ontop,ontop/ontop,ontop/ontop,srapisarda/ontop,ConstantB/ontop-spatial,eschwert/ontop
package it.unibz.krdb.obda.reformulation.tests; import static org.junit.Assert.*; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.LinkedList; import java.util.List; import it.unibz.krdb.obda.io.ModelIOManager; import it.unibz.krdb.obda.model.OBDADataFactory; import it.unibz.krdb.obda.model.OBDAModel; import it.unibz.krdb.obda.model.impl.OBDADataFactoryImpl; import it.unibz.krdb.obda.owlrefplatform.core.QuestConstants; import it.unibz.krdb.obda.owlrefplatform.core.QuestPreferences; import it.unibz.krdb.obda.owlrefplatform.owlapi3.QuestOWL; import it.unibz.krdb.obda.owlrefplatform.owlapi3.QuestOWLFactory; import org.junit.Test; import org.semanticweb.owlapi.apibinding.OWLManager; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyManager; import org.semanticweb.owlapi.reasoner.SimpleConfiguration; import org.semanticweb.owlapi.util.SimpleIRIMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class NPDTest { Logger log = LoggerFactory.getLogger(this.getClass()); @Test public void test_load_NPD() throws Exception { File ontDir = new File("src/test/resources/npd-v2"); String path = ontDir.getAbsolutePath() + "/"; String prfx = "file://" + path; OWLOntologyManager manager = OWLManager.createOWLOntologyManager(); manager.addIRIMapper(new SimpleIRIMapper( IRI.create("http://sws.ifi.uio.no/vocab/version/20130919/npd-bfo"), IRI.create(prfx + "npd-bfo.owl"))); manager.addIRIMapper(new SimpleIRIMapper( IRI.create("http://sws.ifi.uio.no/vocab/version/20130919/npd-db"), IRI.create(prfx + "npd-db"))); manager.addIRIMapper(new SimpleIRIMapper( IRI.create("http://sws.ifi.uio.no/vocab/version/20130919/npd-facility"), IRI.create(prfx + "npd-facility.owl"))); manager.addIRIMapper(new SimpleIRIMapper( IRI.create("http://sws.ifi.uio.no/vocab/version/20130919/npd-geology"), IRI.create(prfx + "npd-geology.owl"))); manager.addIRIMapper(new SimpleIRIMapper( IRI.create("http://sws.ifi.uio.no/vocab/version/20130919/npd-geometry"), IRI.create(prfx + "npd-geometry.owl"))); manager.addIRIMapper(new SimpleIRIMapper( IRI.create("http://sws.ifi.uio.no/vocab/version/20130919/npd-org"), IRI.create(prfx + "npd-org.owl"))); manager.addIRIMapper(new SimpleIRIMapper( IRI.create("http://sws.ifi.uio.no/vocab/version/20130919/npd-prod"), IRI.create(prfx + "npd-prod.owl"))); manager.addIRIMapper(new SimpleIRIMapper( IRI.create("http://sws.ifi.uio.no/vocab/version/20130919/npd-seismic"), IRI.create(prfx + "npd-seismic.owl"))); manager.addIRIMapper(new SimpleIRIMapper( IRI.create("http://sws.ifi.uio.no/vocab/version/20130919/npd-well"), IRI.create(prfx + "npd-well.owl"))); manager.addIRIMapper(new SimpleIRIMapper( IRI.create("http://sws.ifi.uio.no/vocab/version/20130919/npd"), IRI.create(prfx + "npd.owl"))); manager.addIRIMapper(new SimpleIRIMapper( IRI.create("http://sws.ifi.uio.no/vocab/version/20130919/sql"), IRI.create(prfx + "sql.owl"))); manager.addIRIMapper(new SimpleIRIMapper( IRI.create("http://sws.ifi.uio.no/vocab/version/20130919/npd-isc-2012"), IRI.create(prfx + "npd-isc-2012.owl"))); manager.addIRIMapper(new SimpleIRIMapper( IRI.create("http://www.opengis.net/ont/geosparql"), IRI.create(prfx + "geosparql_vocab_all.xml"))); manager.addIRIMapper(new SimpleIRIMapper( IRI.create("http://www.opengis.net/ont/gml"), IRI.create(prfx + "gml_32_geometries.xml"))); manager.addIRIMapper(new SimpleIRIMapper( IRI.create("http://www.opengis.net/ont/sf"), IRI.create(prfx + "gml_32_geometries.xml"))); manager.addIRIMapper(new SimpleIRIMapper( IRI.create("http://purl.org/dc/elements/1.1/"), IRI.create(prfx + "dc.xml"))); manager.addIRIMapper(new SimpleIRIMapper( IRI.create("http://www.w3.org/2004/02/skos/core"), IRI.create(prfx + "skos.xml"))); manager.addIRIMapper(new SimpleIRIMapper( IRI.create("http://www.ifomis.org/bfo/owl"), IRI.create(prfx + "bfo-1.1.owl"))); OWLOntology owlOnto = manager.loadOntologyFromOntologyDocument(new File(path + "npd-v2.owl")); /* Ontology onto = OWLAPI3TranslatorUtility.translateImportsClosure(owlOnto); // - 2 to account for top and bot System.out.println("Class names: " + (onto.getVocabulary().getClasses().size() - 2)); System.out.println("Object Property names: " + (onto.getVocabulary().getObjectProperties().size() - 2)); System.out.println("Data Property names: " + (onto.getVocabulary().getDataProperties().size() - 2)); */ OBDADataFactory fac = OBDADataFactoryImpl.getInstance(); OBDAModel obdaModel = fac.getOBDAModel(); ModelIOManager ioManager = new ModelIOManager(obdaModel); ioManager.load(path + "npd.obda"); QuestPreferences pref = new QuestPreferences(); //pref.setCurrentValueOf(QuestPreferences.DBTYPE, QuestConstants.SEMANTIC_INDEX); pref.setCurrentValueOf(QuestPreferences.ABOX_MODE, QuestConstants.VIRTUAL); pref.setCurrentValueOf(QuestPreferences.REFORMULATION_TECHNIQUE, QuestConstants.TW); pref.setCurrentValueOf(QuestPreferences.REWRITE, QuestConstants.TRUE); pref.setCurrentValueOf(QuestPreferences.PRINT_KEYS, QuestConstants.TRUE); QuestOWLFactory factory = new QuestOWLFactory(); factory.setOBDAController(obdaModel); factory.setPreferenceHolder(pref); setupDatabase(); QuestOWL reasoner = factory.createReasoner(owlOnto, new SimpleConfiguration()); } public void setupDatabase() throws SQLException, IOException { // String driver = "org.h2.Driver"; String url = "jdbc:h2:mem:npdv"; String username = "sa"; String password = ""; Connection conn = DriverManager.getConnection(url, username, password); Statement st = conn.createStatement(); int i = 0; FileReader reader = new FileReader("src/test/resources/npd-v2/npd-schema.sql"); StringBuilder bf = new StringBuilder(); try (BufferedReader in = new BufferedReader(reader)) { for (String line = in.readLine(); line != null; line = in.readLine()) { bf.append(line + "\n"); if (line.startsWith("--")) { //System.out.println("EXECUTING " + i++ + ":\n" + bf.toString()); st.executeUpdate(bf.toString()); conn.commit(); bf = new StringBuilder(); } } } DatabaseMetaData md = conn.getMetaData(); try (ResultSet rsTables = md.getTables(null, null, null, new String[] { "TABLE", "VIEW" })) { int tbl = 0; while (rsTables.next()) { final String tblName = rsTables.getString("TABLE_NAME"); tbl++; //System.out.println("Table " + tbl + ": " + tblName); } assertEquals(tbl, 70); } List<String> pk = new LinkedList<String>(); try (ResultSet rsPrimaryKeys = md.getPrimaryKeys(null, null, "FIELD_DESCRIPTION")) { while (rsPrimaryKeys.next()) { String colName = rsPrimaryKeys.getString("COLUMN_NAME"); String pkName = rsPrimaryKeys.getString("PK_NAME"); if (pkName != null) { pk.add(colName); } } } System.out.println(pk); try (ResultSet rsIndexes = md.getIndexInfo(null, null, "WELLBORE_CORE", true, true)) { while (rsIndexes.next()) { String colName = rsIndexes.getString("COLUMN_NAME"); String indName = rsIndexes.getString("INDEX_NAME"); boolean nonUnique = rsIndexes.getBoolean("NON_UNIQUE"); //System.out.println(indName + " " +colName + " " + nonUnique); } } System.out.println("Database schema created successfully"); } }
quest-owlapi3/src/test/java/it/unibz/krdb/obda/reformulation/tests/NPDTest.java
package it.unibz.krdb.obda.reformulation.tests; import static org.junit.Assert.*; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.LinkedList; import java.util.List; import it.unibz.krdb.obda.io.ModelIOManager; import it.unibz.krdb.obda.model.OBDADataFactory; import it.unibz.krdb.obda.model.OBDAModel; import it.unibz.krdb.obda.model.impl.OBDADataFactoryImpl; import it.unibz.krdb.obda.owlrefplatform.core.QuestConstants; import it.unibz.krdb.obda.owlrefplatform.core.QuestPreferences; import it.unibz.krdb.obda.owlrefplatform.owlapi3.QuestOWL; import it.unibz.krdb.obda.owlrefplatform.owlapi3.QuestOWLFactory; import org.junit.Test; import org.semanticweb.owlapi.apibinding.OWLManager; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyManager; import org.semanticweb.owlapi.reasoner.SimpleConfiguration; import org.semanticweb.owlapi.util.SimpleIRIMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class NPDTest { Logger log = LoggerFactory.getLogger(this.getClass()); @Test public void test_load_NPD() throws Exception { File ontDir = new File("src/test/resources/npd-v2"); String path = ontDir.getAbsolutePath() + "/"; String prfx = "file://" + path; OWLOntologyManager manager = OWLManager.createOWLOntologyManager(); manager.addIRIMapper(new SimpleIRIMapper( IRI.create("http://sws.ifi.uio.no/vocab/version/20130919/npd-bfo"), IRI.create(prfx + "npd-bfo.owl"))); manager.addIRIMapper(new SimpleIRIMapper( IRI.create("http://sws.ifi.uio.no/vocab/version/20130919/npd-db"), IRI.create(prfx + "npd-db"))); manager.addIRIMapper(new SimpleIRIMapper( IRI.create("http://sws.ifi.uio.no/vocab/version/20130919/npd-facility"), IRI.create(prfx + "npd-facility.owl"))); manager.addIRIMapper(new SimpleIRIMapper( IRI.create("http://sws.ifi.uio.no/vocab/version/20130919/npd-geology"), IRI.create(prfx + "npd-geology.owl"))); manager.addIRIMapper(new SimpleIRIMapper( IRI.create("http://sws.ifi.uio.no/vocab/version/20130919/npd-geometry"), IRI.create(prfx + "npd-geometry.owl"))); manager.addIRIMapper(new SimpleIRIMapper( IRI.create("http://sws.ifi.uio.no/vocab/version/20130919/npd-org"), IRI.create(prfx + "npd-org.owl"))); manager.addIRIMapper(new SimpleIRIMapper( IRI.create("http://sws.ifi.uio.no/vocab/version/20130919/npd-prod"), IRI.create(prfx + "npd-prod.owl"))); manager.addIRIMapper(new SimpleIRIMapper( IRI.create("http://sws.ifi.uio.no/vocab/version/20130919/npd-seismic"), IRI.create(prfx + "npd-seismic.owl"))); manager.addIRIMapper(new SimpleIRIMapper( IRI.create("http://sws.ifi.uio.no/vocab/version/20130919/npd-well"), IRI.create(prfx + "npd-well.owl"))); manager.addIRIMapper(new SimpleIRIMapper( IRI.create("http://sws.ifi.uio.no/vocab/version/20130919/npd"), IRI.create(prfx + "npd.owl"))); manager.addIRIMapper(new SimpleIRIMapper( IRI.create("http://sws.ifi.uio.no/vocab/version/20130919/sql"), IRI.create(prfx + "sql.owl"))); manager.addIRIMapper(new SimpleIRIMapper( IRI.create("http://sws.ifi.uio.no/vocab/version/20130919/npd-isc-2012"), IRI.create(prfx + "npd-isc-2012.owl"))); manager.addIRIMapper(new SimpleIRIMapper( IRI.create("http://www.opengis.net/ont/geosparql"), IRI.create(prfx + "geosparql_vocab_all.xml"))); manager.addIRIMapper(new SimpleIRIMapper( IRI.create("http://www.opengis.net/ont/gml"), IRI.create(prfx + "gml_32_geometries.xml"))); manager.addIRIMapper(new SimpleIRIMapper( IRI.create("http://www.opengis.net/ont/sf"), IRI.create(prfx + "gml_32_geometries.xml"))); manager.addIRIMapper(new SimpleIRIMapper( IRI.create("http://purl.org/dc/elements/1.1/"), IRI.create(prfx + "dc.xml"))); manager.addIRIMapper(new SimpleIRIMapper( IRI.create("http://www.w3.org/2004/02/skos/core"), IRI.create(prfx + "skos.xml"))); manager.addIRIMapper(new SimpleIRIMapper( IRI.create("http://www.ifomis.org/bfo/owl"), IRI.create(prfx + "bfo-1.1.owl"))); OWLOntology owlOnto = manager.loadOntologyFromOntologyDocument(new File(path + "npd-v2.owl")); /* Ontology onto = OWLAPI3TranslatorUtility.translateImportsClosure(owlOnto); // - 2 to account for top and bot System.out.println("Class names: " + (onto.getVocabulary().getClasses().size() - 2)); System.out.println("Object Property names: " + (onto.getVocabulary().getObjectProperties().size() - 2)); System.out.println("Data Property names: " + (onto.getVocabulary().getDataProperties().size() - 2)); */ OBDADataFactory fac = OBDADataFactoryImpl.getInstance(); OBDAModel obdaModel = fac.getOBDAModel(); ModelIOManager ioManager = new ModelIOManager(obdaModel); ioManager.load(path + "npd.obda"); QuestPreferences pref = new QuestPreferences(); //pref.setCurrentValueOf(QuestPreferences.DBTYPE, QuestConstants.SEMANTIC_INDEX); pref.setCurrentValueOf(QuestPreferences.ABOX_MODE, QuestConstants.VIRTUAL); pref.setCurrentValueOf(QuestPreferences.REFORMULATION_TECHNIQUE, QuestConstants.TW); pref.setCurrentValueOf(QuestPreferences.REWRITE, QuestConstants.TRUE); pref.setCurrentValueOf(QuestPreferences.PRINT_KEYS, QuestConstants.TRUE); QuestOWLFactory factory = new QuestOWLFactory(); factory.setOBDAController(obdaModel); factory.setPreferenceHolder(pref); setupDatabase(); QuestOWL reasoner = factory.createReasoner(owlOnto, new SimpleConfiguration()); } public void setupDatabase() throws SQLException, IOException { // String driver = "org.h2.Driver"; String url = "jdbc:h2:mem:npdv"; String username = "sa"; String password = ""; Connection conn = DriverManager.getConnection(url, username, password); Statement st = conn.createStatement(); int i = 0; FileReader reader = new FileReader("src/test/resources/npd-v2/npd-schema.sql"); StringBuilder bf = new StringBuilder(); try (BufferedReader in = new BufferedReader(reader)) { for (String line = in.readLine(); line != null; line = in.readLine()) { bf.append(line + "\n"); if (line.startsWith("--")) { //System.out.println("EXECUTING " + i++ + ":\n" + bf.toString()); st.executeUpdate(bf.toString()); conn.commit(); bf = new StringBuilder(); } } } DatabaseMetaData md = conn.getMetaData(); try (ResultSet rsTables = md.getTables(null, null, null, new String[] { "TABLE", "VIEW" })) { int tbl = 0; while (rsTables.next()) { final String tblName = rsTables.getString("TABLE_NAME"); //System.out.println("Table " + ++tbl + ": " + tblName); } assertEquals(tbl, 70); } List<String> pk = new LinkedList<String>(); try (ResultSet rsPrimaryKeys = md.getPrimaryKeys(null, null, "FIELD_DESCRIPTION")) { while (rsPrimaryKeys.next()) { String colName = rsPrimaryKeys.getString("COLUMN_NAME"); String pkName = rsPrimaryKeys.getString("PK_NAME"); if (pkName != null) { pk.add(colName); } } } System.out.println(pk); try (ResultSet rsIndexes = md.getIndexInfo(null, null, "WELLBORE_CORE", true, true)) { while (rsIndexes.next()) { String colName = rsIndexes.getString("COLUMN_NAME"); String indName = rsIndexes.getString("INDEX_NAME"); boolean nonUnique = rsIndexes.getBoolean("NON_UNIQUE"); //System.out.println(indName + " " +colName + " " + nonUnique); } } System.out.println("Database schema created successfully"); } }
test fix
quest-owlapi3/src/test/java/it/unibz/krdb/obda/reformulation/tests/NPDTest.java
test fix
Java
bsd-2-clause
7c192b572a45baa0eafae2222ab2bbf9d9d960d8
0
scifio/scifio
/* * #%L * OME Bio-Formats package for reading and converting biological file formats. * %% * Copyright (C) 2005 - 2013 Open Microscopy Environment: * - Board of Regents of the University of Wisconsin-Madison * - Glencoe Software, Inc. * - University of Dundee * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ package loci.formats.in; import java.io.IOException; import java.util.Vector; import loci.common.DataTools; import loci.common.Location; import loci.common.RandomAccessInputStream; import loci.common.services.DependencyException; import loci.common.services.ServiceException; import loci.common.services.ServiceFactory; import loci.formats.CoreMetadata; import loci.formats.FormatException; import loci.formats.FormatReader; import loci.formats.FormatTools; import loci.formats.MetadataTools; import loci.formats.MissingLibraryException; import loci.formats.meta.MetadataStore; import loci.formats.services.NetCDFService; import loci.formats.services.NetCDFServiceImpl; import ome.xml.model.primitives.Color; import ome.xml.model.primitives.PositiveFloat; /** * Reader for Bitplane Imaris 5.5 (HDF) files. * * <dl><dt><b>Source code:</b></dt> * <dd><a href="http://trac.openmicroscopy.org.uk/ome/browser/bioformats.git/components/bio-formats/src/loci/formats/in/ImarisHDFReader.java">Trac</a>, * <a href="http://git.openmicroscopy.org/?p=bioformats.git;a=blob;f=components/bio-formats/src/loci/formats/in/ImarisHDFReader.java;hb=HEAD">Gitweb</a></dd></dl> */ public class ImarisHDFReader extends FormatReader { // -- Constants -- public static final String HDF_MAGIC_STRING = "HDF"; private static final String[] DELIMITERS = {" ", "-", "."}; // -- Fields -- private double pixelSizeX, pixelSizeY, pixelSizeZ; private double minX, minY, minZ, maxX, maxY, maxZ; private int seriesCount; private NetCDFService netcdf; // channel parameters private Vector<String> emWave, exWave, channelMin, channelMax; private Vector<String> gain, pinhole, channelName, microscopyMode; private Vector<double[]> colors; private int lastChannel = 0; // -- Constructor -- /** Constructs a new Imaris HDF reader. */ public ImarisHDFReader() { super("Bitplane Imaris 5.5 (HDF)", "ims"); suffixSufficient = false; domains = new String[] {FormatTools.UNKNOWN_DOMAIN}; } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */ public boolean isThisType(RandomAccessInputStream stream) throws IOException { final int blockLen = 8; if (!FormatTools.validStream(stream, blockLen, false)) return false; return stream.readString(blockLen).indexOf(HDF_MAGIC_STRING) >= 0; } /* @see loci.formats.IFormatReader#get8BitLookupTable() */ public byte[][] get8BitLookupTable() { FormatTools.assertId(currentId, true, 1); if (getPixelType() != FormatTools.UINT8 || !isIndexed()) return null; if (lastChannel < 0 || lastChannel >= colors.size()) { return null; } double[] color = colors.get(lastChannel); byte[][] lut = new byte[3][256]; for (int c=0; c<lut.length; c++) { double max = color[c] * 255; for (int p=0; p<lut[c].length; p++) { lut[c][p] = (byte) ((p / 255.0) * max); } } return lut; } /* @see loci.formats.IFormatReaderget16BitLookupTable() */ public short[][] get16BitLookupTable() { FormatTools.assertId(currentId, true, 1); if (getPixelType() != FormatTools.UINT16 || !isIndexed()) return null; if (lastChannel < 0 || lastChannel >= colors.size()) { return null; } double[] color = colors.get(lastChannel); short[][] lut = new short[3][65536]; for (int c=0; c<lut.length; c++) { double max = color[c] * 65535; for (int p=0; p<lut[c].length; p++) { lut[c][p] = (short) ((p / 65535.0) * max); } } return lut; } /** * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int) */ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h); lastChannel = getZCTCoords(no)[1]; // pixel data is stored in XYZ blocks Object image = getImageData(no, y, h); boolean big = !isLittleEndian(); int bpp = FormatTools.getBytesPerPixel(getPixelType()); for (int row=0; row<h; row++) { int base = row * w * bpp; if (image instanceof byte[][]) { byte[][] data = (byte[][]) image; byte[] rowData = data[row]; System.arraycopy(rowData, x, buf, row*w, w); } else if (image instanceof short[][]) { short[][] data = (short[][]) image; short[] rowData = data[row]; for (int i=0; i<w; i++) { DataTools.unpackBytes(rowData[i + x], buf, base + 2*i, 2, big); } } else if (image instanceof int[][]) { int[][] data = (int[][]) image; int[] rowData = data[row]; for (int i=0; i<w; i++) { DataTools.unpackBytes(rowData[i + x], buf, base + i*4, 4, big); } } else if (image instanceof float[][]) { float[][] data = (float[][]) image; float[] rowData = data[row]; for (int i=0; i<w; i++) { int v = Float.floatToIntBits(rowData[i + x]); DataTools.unpackBytes(v, buf, base + i*4, 4, big); } } else if (image instanceof double[][]) { double[][] data = (double[][]) image; double[] rowData = data[row]; for (int i=0; i<w; i++) { long v = Double.doubleToLongBits(rowData[i + x]); DataTools.unpackBytes(v, buf, base + i * 8, 8, big); } } } return buf; } /* @see loci.formats.IFormatReader#close(boolean) */ public void close(boolean fileOnly) throws IOException { super.close(fileOnly); if (!fileOnly) { seriesCount = 0; pixelSizeX = pixelSizeY = pixelSizeZ = 0; minX = minY = minZ = maxX = maxY = maxZ = 0; if (netcdf != null) netcdf.close(); netcdf = null; emWave = exWave = channelMin = channelMax = null; gain = pinhole = channelName = microscopyMode = null; colors = null; lastChannel = 0; } } // -- Internal FormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { super.initFile(id); try { ServiceFactory factory = new ServiceFactory(); netcdf = factory.getInstance(NetCDFService.class); netcdf.setFile(id); } catch (DependencyException e) { throw new MissingLibraryException(NetCDFServiceImpl.NO_NETCDF_MSG, e); } pixelSizeX = pixelSizeY = pixelSizeZ = 1; emWave = new Vector<String>(); exWave = new Vector<String>(); channelMin = new Vector<String>(); channelMax = new Vector<String>(); gain = new Vector<String>(); pinhole = new Vector<String>(); channelName = new Vector<String>(); microscopyMode = new Vector<String>(); colors = new Vector<double[]>(); seriesCount = 0; // read all of the metadata key/value pairs parseAttributes(); CoreMetadata ms0 = core.get(0); if (seriesCount > 1) { for (int i=1; i<seriesCount; i++) { core.add(new CoreMetadata()); } ms0.resolutionCount = seriesCount; for (int i=1; i<seriesCount; i++) { CoreMetadata ms = core.get(i); String groupPath = "/DataSet/ResolutionLevel_" + i + "/TimePoint_0/Channel_0"; ms.sizeX = Integer.parseInt(netcdf.getAttributeValue(groupPath + "/ImageSizeX")); ms.sizeY = Integer.parseInt(netcdf.getAttributeValue(groupPath + "/ImageSizeY")); ms.sizeZ = Integer.parseInt(netcdf.getAttributeValue(groupPath + "/ImageSizeZ")); ms.imageCount = ms.sizeZ * getSizeC() * getSizeT(); ms.sizeC = getSizeC(); ms.sizeT = getSizeT(); ms.thumbnail = true; } } ms0.imageCount = getSizeZ() * getSizeC() * getSizeT(); ms0.thumbnail = false; ms0.dimensionOrder = "XYZCT"; // determine pixel type - this isn't stored in the metadata, so we need // to check the pixels themselves int type = -1; Object pix = getImageData(0, 0, 1); if (pix instanceof byte[][]) type = FormatTools.UINT8; else if (pix instanceof short[][]) type = FormatTools.UINT16; else if (pix instanceof int[][]) type = FormatTools.UINT32; else if (pix instanceof float[][]) type = FormatTools.FLOAT; else if (pix instanceof double[][]) type = FormatTools.DOUBLE; else { throw new FormatException("Unknown pixel type: " + pix); } for (int i=0; i<core.size(); i++) { CoreMetadata ms = core.get(i); ms.pixelType = type; ms.dimensionOrder = "XYZCT"; ms.rgb = false; ms.thumbSizeX = 128; ms.thumbSizeY = 128; ms.orderCertain = true; ms.littleEndian = true; ms.interleaved = false; ms.indexed = colors.size() >= getSizeC(); } MetadataStore store = makeFilterMetadata(); MetadataTools.populatePixels(store, this); String imageName = new Location(getCurrentFile()).getName(); for (int s=0; s<getSeriesCount(); s++) { store.setImageName(imageName + " Resolution Level " + (s + 1), s); } if (getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM) { return; } int cIndex = 0; for (int s=0; s<getSeriesCount(); s++) { setSeries(s); double px = pixelSizeX, py = pixelSizeY, pz = pixelSizeZ; if (px == 1) px = (maxX - minX) / getSizeX(); if (py == 1) py = (maxY - minY) / getSizeY(); if (pz == 1) pz = (maxZ - minZ) / getSizeZ(); if (px > 0) { store.setPixelsPhysicalSizeX(new PositiveFloat(px), s); } else { LOGGER.warn("Expected positive value for PhysicalSizeX; got {}", px); } if (py > 0) { store.setPixelsPhysicalSizeY(new PositiveFloat(py), s); } else { LOGGER.warn("Expected positive value for PhysicalSizeY; got {}", py); } if (pz > 0) { store.setPixelsPhysicalSizeZ(new PositiveFloat(pz), s); } else { LOGGER.warn("Expected positive value for PhysicalSizeZ; got {}", pz); } for (int i=0; i<getSizeC(); i++, cIndex++) { Float gainValue = null; Integer pinholeValue = null, emWaveValue = null, exWaveValue; if (cIndex < gain.size()) { try { gainValue = new Float(gain.get(cIndex)); } catch (NumberFormatException e) { } } if (cIndex < pinhole.size()) { try { pinholeValue = new Integer(pinhole.get(cIndex)); } catch (NumberFormatException e) { } } if (cIndex < emWave.size()) { try { emWaveValue = new Integer(emWave.get(cIndex)); } catch (NumberFormatException e) { } } if (cIndex < exWave.size()) { try { exWaveValue = new Integer(exWave.get(cIndex)); } catch (NumberFormatException e) { } } // CHECK /* store.setLogicalChannelName((String) channelName.get(cIndex), s, i); store.setDetectorSettingsGain(gainValue, s, i); store.setLogicalChannelPinholeSize(pinholeValue, s, i); store.setLogicalChannelMode((String) microscopyMode.get(cIndex), s, i); store.setLogicalChannelEmWave(emWaveValue, s, i); store.setLogicalChannelExWave(exWaveValue, s, i); */ Double minValue = null, maxValue = null; if (cIndex < channelMin.size()) { try { minValue = new Double(channelMin.get(cIndex)); } catch (NumberFormatException e) { } } if (cIndex < channelMax.size()) { try { maxValue = new Double(channelMax.get(cIndex)); } catch (NumberFormatException e) { } } if (i < colors.size()) { double[] color = colors.get(i); Color realColor = new Color( (int) (color[0] * 255), (int) (color[1] * 255), (int) (color[2] * 255), 255); store.setChannelColor(realColor, s, i); } } } setSeries(0); } // -- Helper methods -- private Object getImageData(int no, int y, int height) throws FormatException { int[] zct = getZCTCoords(no); String path = "/DataSet/ResolutionLevel_" + getCoreIndex() + "/TimePoint_" + zct[2] + "/Channel_" + zct[1] + "/Data"; Object image = null; // the width and height cannot be 1, because then netCDF will give us a // singleton instead of an array if (height == 1) { height++; } int[] dimensions = new int[] {1, height, getSizeX()}; int[] indices = new int[] {zct[0], y, 0}; try { image = netcdf.getArray(path, indices, dimensions); } catch (ServiceException e) { throw new FormatException(e); } return image; } private void parseAttributes() { Vector<String> attributes = netcdf.getAttributeList(); CoreMetadata ms0 = core.get(0); for (String attr : attributes) { String name = attr.substring(attr.lastIndexOf("/") + 1); String value = netcdf.getAttributeValue(attr); if (value == null) continue; value = value.trim(); if (name.equals("X") || name.equals("ImageSizeX")) { try { ms0.sizeX = Integer.parseInt(value); } catch (NumberFormatException e) { LOGGER.trace("Failed to parse '" + name + "'", e); } } else if (name.equals("Y") || name.equals("ImageSizeY")) { try { ms0.sizeY = Integer.parseInt(value); } catch (NumberFormatException e) { LOGGER.trace("Failed to parse '" + name + "'", e); } } else if (name.equals("Z") || name.equals("ImageSizeZ")) { try { ms0.sizeZ = Integer.parseInt(value); } catch (NumberFormatException e) { LOGGER.trace("Failed to parse '" + name + "'", e); } } else if (name.equals("FileTimePoints")) { ms0.sizeT = Integer.parseInt(value); } else if (name.equals("RecordingEntrySampleSpacing")) { pixelSizeX = Double.parseDouble(value); } else if (name.equals("RecordingEntryLineSpacing")) { pixelSizeY = Double.parseDouble(value); } else if (name.equals("RecordingEntryPlaneSpacing")) { pixelSizeZ = Double.parseDouble(value); } else if (name.equals("ExtMax0")) maxX = Double.parseDouble(value); else if (name.equals("ExtMax1")) maxY = Double.parseDouble(value); else if (name.equals("ExtMax2")) maxZ = Double.parseDouble(value); else if (name.equals("ExtMin0")) minX = Double.parseDouble(value); else if (name.equals("ExtMin1")) minY = Double.parseDouble(value); else if (name.equals("ExtMin2")) minZ = Double.parseDouble(value); if (attr.startsWith("/DataSet/ResolutionLevel_")) { int slash = attr.indexOf("/", 25); int n = Integer.parseInt(attr.substring(25, slash == -1 ? attr.length() : slash)); if (n == seriesCount) seriesCount++; } if (attr.startsWith("/DataSetInfo/Channel_")) { String originalValue = value; for (String d : DELIMITERS) { if (value.indexOf(d) != -1) { value = value.substring(value.indexOf(d) + 1); } } int underscore = attr.indexOf("_") + 1; int cIndex = Integer.parseInt(attr.substring(underscore, attr.indexOf("/", underscore))); if (cIndex == getSizeC()) ms0.sizeC++; if (name.equals("Gain")) gain.add(value); else if (name.equals("LSMEmissionWavelength")) emWave.add(value); else if (name.equals("LSMExcitationWavelength")) exWave.add(value); else if (name.equals("Max")) channelMax.add(value); else if (name.equals("Min")) channelMin.add(value); else if (name.equals("Pinhole")) pinhole.add(value); else if (name.equals("Name")) channelName.add(value); else if (name.equals("MicroscopyMode")) microscopyMode.add(value); else if (name.equals("Color")) { double[] color = new double[3]; String[] intensity = originalValue.split(" "); for (int i=0; i<intensity.length; i++) { color[i] = Double.parseDouble(intensity[i]); } colors.add(color); } } if (value != null) addGlobalMeta(name, value); } } }
components/bio-formats/src/loci/formats/in/ImarisHDFReader.java
/* * #%L * OME Bio-Formats package for reading and converting biological file formats. * %% * Copyright (C) 2005 - 2013 Open Microscopy Environment: * - Board of Regents of the University of Wisconsin-Madison * - Glencoe Software, Inc. * - University of Dundee * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ package loci.formats.in; import java.io.IOException; import java.util.Vector; import loci.common.DataTools; import loci.common.Location; import loci.common.RandomAccessInputStream; import loci.common.services.DependencyException; import loci.common.services.ServiceException; import loci.common.services.ServiceFactory; import loci.formats.CoreMetadata; import loci.formats.FormatException; import loci.formats.FormatReader; import loci.formats.FormatTools; import loci.formats.MetadataTools; import loci.formats.MissingLibraryException; import loci.formats.meta.MetadataStore; import loci.formats.services.NetCDFService; import loci.formats.services.NetCDFServiceImpl; import ome.xml.model.primitives.Color; import ome.xml.model.primitives.PositiveFloat; /** * Reader for Bitplane Imaris 5.5 (HDF) files. * * <dl><dt><b>Source code:</b></dt> * <dd><a href="http://trac.openmicroscopy.org.uk/ome/browser/bioformats.git/components/bio-formats/src/loci/formats/in/ImarisHDFReader.java">Trac</a>, * <a href="http://git.openmicroscopy.org/?p=bioformats.git;a=blob;f=components/bio-formats/src/loci/formats/in/ImarisHDFReader.java;hb=HEAD">Gitweb</a></dd></dl> */ public class ImarisHDFReader extends FormatReader { // -- Constants -- public static final String HDF_MAGIC_STRING = "HDF"; private static final String[] DELIMITERS = {" ", "-", "."}; // -- Fields -- private double pixelSizeX, pixelSizeY, pixelSizeZ; private double minX, minY, minZ, maxX, maxY, maxZ; private int seriesCount; private NetCDFService netcdf; // channel parameters private Vector<String> emWave, exWave, channelMin, channelMax; private Vector<String> gain, pinhole, channelName, microscopyMode; private Vector<double[]> colors; private int lastChannel = 0; // -- Constructor -- /** Constructs a new Imaris HDF reader. */ public ImarisHDFReader() { super("Bitplane Imaris 5.5 (HDF)", "ims"); suffixSufficient = false; domains = new String[] {FormatTools.UNKNOWN_DOMAIN}; } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#getOptimalTileHeight() */ public int getOptimalTileHeight() { FormatTools.assertId(currentId, true, 1); return getSizeY(); } /* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */ public boolean isThisType(RandomAccessInputStream stream) throws IOException { final int blockLen = 8; if (!FormatTools.validStream(stream, blockLen, false)) return false; return stream.readString(blockLen).indexOf(HDF_MAGIC_STRING) >= 0; } /* @see loci.formats.IFormatReader#get8BitLookupTable() */ public byte[][] get8BitLookupTable() { FormatTools.assertId(currentId, true, 1); if (getPixelType() != FormatTools.UINT8 || !isIndexed()) return null; if (lastChannel < 0 || lastChannel >= colors.size()) { return null; } double[] color = colors.get(lastChannel); byte[][] lut = new byte[3][256]; for (int c=0; c<lut.length; c++) { double max = color[c] * 255; for (int p=0; p<lut[c].length; p++) { lut[c][p] = (byte) ((p / 255.0) * max); } } return lut; } /* @see loci.formats.IFormatReaderget16BitLookupTable() */ public short[][] get16BitLookupTable() { FormatTools.assertId(currentId, true, 1); if (getPixelType() != FormatTools.UINT16 || !isIndexed()) return null; if (lastChannel < 0 || lastChannel >= colors.size()) { return null; } double[] color = colors.get(lastChannel); short[][] lut = new short[3][65536]; for (int c=0; c<lut.length; c++) { double max = color[c] * 65535; for (int p=0; p<lut[c].length; p++) { lut[c][p] = (short) ((p / 65535.0) * max); } } return lut; } /** * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int) */ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h); lastChannel = getZCTCoords(no)[1]; // pixel data is stored in XYZ blocks Object image = getImageData(no, y, h); boolean big = !isLittleEndian(); int bpp = FormatTools.getBytesPerPixel(getPixelType()); for (int row=0; row<h; row++) { int base = row * w * bpp; if (image instanceof byte[][]) { byte[][] data = (byte[][]) image; byte[] rowData = data[row]; System.arraycopy(rowData, x, buf, row*w, w); } else if (image instanceof short[][]) { short[][] data = (short[][]) image; short[] rowData = data[row]; for (int i=0; i<w; i++) { DataTools.unpackBytes(rowData[i + x], buf, base + 2*i, 2, big); } } else if (image instanceof int[][]) { int[][] data = (int[][]) image; int[] rowData = data[row]; for (int i=0; i<w; i++) { DataTools.unpackBytes(rowData[i + x], buf, base + i*4, 4, big); } } else if (image instanceof float[][]) { float[][] data = (float[][]) image; float[] rowData = data[row]; for (int i=0; i<w; i++) { int v = Float.floatToIntBits(rowData[i + x]); DataTools.unpackBytes(v, buf, base + i*4, 4, big); } } else if (image instanceof double[][]) { double[][] data = (double[][]) image; double[] rowData = data[row]; for (int i=0; i<w; i++) { long v = Double.doubleToLongBits(rowData[i + x]); DataTools.unpackBytes(v, buf, base + i * 8, 8, big); } } } return buf; } /* @see loci.formats.IFormatReader#close(boolean) */ public void close(boolean fileOnly) throws IOException { super.close(fileOnly); if (!fileOnly) { seriesCount = 0; pixelSizeX = pixelSizeY = pixelSizeZ = 0; minX = minY = minZ = maxX = maxY = maxZ = 0; if (netcdf != null) netcdf.close(); netcdf = null; emWave = exWave = channelMin = channelMax = null; gain = pinhole = channelName = microscopyMode = null; colors = null; lastChannel = 0; } } // -- Internal FormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { super.initFile(id); try { ServiceFactory factory = new ServiceFactory(); netcdf = factory.getInstance(NetCDFService.class); netcdf.setFile(id); } catch (DependencyException e) { throw new MissingLibraryException(NetCDFServiceImpl.NO_NETCDF_MSG, e); } pixelSizeX = pixelSizeY = pixelSizeZ = 1; emWave = new Vector<String>(); exWave = new Vector<String>(); channelMin = new Vector<String>(); channelMax = new Vector<String>(); gain = new Vector<String>(); pinhole = new Vector<String>(); channelName = new Vector<String>(); microscopyMode = new Vector<String>(); colors = new Vector<double[]>(); seriesCount = 0; // read all of the metadata key/value pairs parseAttributes(); CoreMetadata ms0 = core.get(0); if (seriesCount > 1) { for (int i=1; i<seriesCount; i++) { core.add(new CoreMetadata()); } ms0.resolutionCount = seriesCount; for (int i=1; i<seriesCount; i++) { CoreMetadata ms = core.get(i); String groupPath = "/DataSet/ResolutionLevel_" + i + "/TimePoint_0/Channel_0"; ms.sizeX = Integer.parseInt(netcdf.getAttributeValue(groupPath + "/ImageSizeX")); ms.sizeY = Integer.parseInt(netcdf.getAttributeValue(groupPath + "/ImageSizeY")); ms.sizeZ = Integer.parseInt(netcdf.getAttributeValue(groupPath + "/ImageSizeZ")); ms.imageCount = ms.sizeZ * getSizeC() * getSizeT(); ms.sizeC = getSizeC(); ms.sizeT = getSizeT(); ms.thumbnail = true; } } ms0.imageCount = getSizeZ() * getSizeC() * getSizeT(); ms0.thumbnail = false; ms0.dimensionOrder = "XYZCT"; // determine pixel type - this isn't stored in the metadata, so we need // to check the pixels themselves int type = -1; Object pix = getImageData(0, 0, 1); if (pix instanceof byte[][]) type = FormatTools.UINT8; else if (pix instanceof short[][]) type = FormatTools.UINT16; else if (pix instanceof int[][]) type = FormatTools.UINT32; else if (pix instanceof float[][]) type = FormatTools.FLOAT; else if (pix instanceof double[][]) type = FormatTools.DOUBLE; else { throw new FormatException("Unknown pixel type: " + pix); } for (int i=0; i<core.size(); i++) { CoreMetadata ms = core.get(i); ms.pixelType = type; ms.dimensionOrder = "XYZCT"; ms.rgb = false; ms.thumbSizeX = 128; ms.thumbSizeY = 128; ms.orderCertain = true; ms.littleEndian = true; ms.interleaved = false; ms.indexed = colors.size() >= getSizeC(); } MetadataStore store = makeFilterMetadata(); MetadataTools.populatePixels(store, this); String imageName = new Location(getCurrentFile()).getName(); for (int s=0; s<getSeriesCount(); s++) { store.setImageName(imageName + " Resolution Level " + (s + 1), s); } if (getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM) { return; } int cIndex = 0; for (int s=0; s<getSeriesCount(); s++) { setSeries(s); double px = pixelSizeX, py = pixelSizeY, pz = pixelSizeZ; if (px == 1) px = (maxX - minX) / getSizeX(); if (py == 1) py = (maxY - minY) / getSizeY(); if (pz == 1) pz = (maxZ - minZ) / getSizeZ(); if (px > 0) { store.setPixelsPhysicalSizeX(new PositiveFloat(px), s); } else { LOGGER.warn("Expected positive value for PhysicalSizeX; got {}", px); } if (py > 0) { store.setPixelsPhysicalSizeY(new PositiveFloat(py), s); } else { LOGGER.warn("Expected positive value for PhysicalSizeY; got {}", py); } if (pz > 0) { store.setPixelsPhysicalSizeZ(new PositiveFloat(pz), s); } else { LOGGER.warn("Expected positive value for PhysicalSizeZ; got {}", pz); } for (int i=0; i<getSizeC(); i++, cIndex++) { Float gainValue = null; Integer pinholeValue = null, emWaveValue = null, exWaveValue; if (cIndex < gain.size()) { try { gainValue = new Float(gain.get(cIndex)); } catch (NumberFormatException e) { } } if (cIndex < pinhole.size()) { try { pinholeValue = new Integer(pinhole.get(cIndex)); } catch (NumberFormatException e) { } } if (cIndex < emWave.size()) { try { emWaveValue = new Integer(emWave.get(cIndex)); } catch (NumberFormatException e) { } } if (cIndex < exWave.size()) { try { exWaveValue = new Integer(exWave.get(cIndex)); } catch (NumberFormatException e) { } } // CHECK /* store.setLogicalChannelName((String) channelName.get(cIndex), s, i); store.setDetectorSettingsGain(gainValue, s, i); store.setLogicalChannelPinholeSize(pinholeValue, s, i); store.setLogicalChannelMode((String) microscopyMode.get(cIndex), s, i); store.setLogicalChannelEmWave(emWaveValue, s, i); store.setLogicalChannelExWave(exWaveValue, s, i); */ Double minValue = null, maxValue = null; if (cIndex < channelMin.size()) { try { minValue = new Double(channelMin.get(cIndex)); } catch (NumberFormatException e) { } } if (cIndex < channelMax.size()) { try { maxValue = new Double(channelMax.get(cIndex)); } catch (NumberFormatException e) { } } if (i < colors.size()) { double[] color = colors.get(i); Color realColor = new Color( (int) (color[0] * 255), (int) (color[1] * 255), (int) (color[2] * 255), 255); store.setChannelColor(realColor, s, i); } } } setSeries(0); } // -- Helper methods -- private Object getImageData(int no, int y, int height) throws FormatException { int[] zct = getZCTCoords(no); String path = "/DataSet/ResolutionLevel_" + getCoreIndex() + "/TimePoint_" + zct[2] + "/Channel_" + zct[1] + "/Data"; Object image = null; // the width and height cannot be 1, because then netCDF will give us a // singleton instead of an array if (height == 1) { height++; } int[] dimensions = new int[] {1, height, getSizeX()}; int[] indices = new int[] {zct[0], y, 0}; try { image = netcdf.getArray(path, indices, dimensions); } catch (ServiceException e) { throw new FormatException(e); } return image; } private void parseAttributes() { Vector<String> attributes = netcdf.getAttributeList(); CoreMetadata ms0 = core.get(0); for (String attr : attributes) { String name = attr.substring(attr.lastIndexOf("/") + 1); String value = netcdf.getAttributeValue(attr); if (value == null) continue; value = value.trim(); if (name.equals("X") || name.equals("ImageSizeX")) { try { ms0.sizeX = Integer.parseInt(value); } catch (NumberFormatException e) { LOGGER.trace("Failed to parse '" + name + "'", e); } } else if (name.equals("Y") || name.equals("ImageSizeY")) { try { ms0.sizeY = Integer.parseInt(value); } catch (NumberFormatException e) { LOGGER.trace("Failed to parse '" + name + "'", e); } } else if (name.equals("Z") || name.equals("ImageSizeZ")) { try { ms0.sizeZ = Integer.parseInt(value); } catch (NumberFormatException e) { LOGGER.trace("Failed to parse '" + name + "'", e); } } else if (name.equals("FileTimePoints")) { ms0.sizeT = Integer.parseInt(value); } else if (name.equals("RecordingEntrySampleSpacing")) { pixelSizeX = Double.parseDouble(value); } else if (name.equals("RecordingEntryLineSpacing")) { pixelSizeY = Double.parseDouble(value); } else if (name.equals("RecordingEntryPlaneSpacing")) { pixelSizeZ = Double.parseDouble(value); } else if (name.equals("ExtMax0")) maxX = Double.parseDouble(value); else if (name.equals("ExtMax1")) maxY = Double.parseDouble(value); else if (name.equals("ExtMax2")) maxZ = Double.parseDouble(value); else if (name.equals("ExtMin0")) minX = Double.parseDouble(value); else if (name.equals("ExtMin1")) minY = Double.parseDouble(value); else if (name.equals("ExtMin2")) minZ = Double.parseDouble(value); if (attr.startsWith("/DataSet/ResolutionLevel_")) { int slash = attr.indexOf("/", 25); int n = Integer.parseInt(attr.substring(25, slash == -1 ? attr.length() : slash)); if (n == seriesCount) seriesCount++; } if (attr.startsWith("/DataSetInfo/Channel_")) { String originalValue = value; for (String d : DELIMITERS) { if (value.indexOf(d) != -1) { value = value.substring(value.indexOf(d) + 1); } } int underscore = attr.indexOf("_") + 1; int cIndex = Integer.parseInt(attr.substring(underscore, attr.indexOf("/", underscore))); if (cIndex == getSizeC()) ms0.sizeC++; if (name.equals("Gain")) gain.add(value); else if (name.equals("LSMEmissionWavelength")) emWave.add(value); else if (name.equals("LSMExcitationWavelength")) exWave.add(value); else if (name.equals("Max")) channelMax.add(value); else if (name.equals("Min")) channelMin.add(value); else if (name.equals("Pinhole")) pinhole.add(value); else if (name.equals("Name")) channelName.add(value); else if (name.equals("MicroscopyMode")) microscopyMode.add(value); else if (name.equals("Color")) { double[] color = new double[3]; String[] intensity = originalValue.split(" "); for (int i=0; i<intensity.length; i++) { color[i] = Double.parseDouble(intensity[i]); } colors.add(color); } } if (value != null) addGlobalMeta(name, value); } } }
Imaris HDF: fix optimal tile height Fixes ticket #10272.
components/bio-formats/src/loci/formats/in/ImarisHDFReader.java
Imaris HDF: fix optimal tile height
Java
bsd-2-clause
0056ad11cb96cb39337bca6177296597d118f5ff
0
octavianiLocator/g3m,octavianiLocator/g3m,AeroGlass/g3m,AeroGlass/g3m,AeroGlass/g3m,AeroGlass/g3m,AeroGlass/g3m,octavianiLocator/g3m,octavianiLocator/g3m,octavianiLocator/g3m,octavianiLocator/g3m,AeroGlass/g3m
package org.glob3.mobile.generated; public class NonOverlappingMark { private float _springLengthInPixels; // MutableVector2F _widgetScreenPosition; // MutableVector2F _anchorScreenPosition; private Vector3D _cartesianPos; private Geodetic3D _geoPosition ; private MutableVector2F _speed = new MutableVector2F(); private MutableVector2F _force = new MutableVector2F(); private MarkWidget _widget; private MarkWidget _anchorWidget; private GLState _springGLState; private IFloatBuffer _springVertices; private ViewportExtentGLFeature _springViewportExtentGLFeature; private final float _springK; private final float _maxSpringLength; private final float _minSpringLength; private final float _electricCharge; private final float _anchorElectricCharge; private final float _resistanceFactor; private String _id; private NonOverlappingMarkTouchListener _touchListener; public NonOverlappingMark(IImageBuilder imageBuilderWidget, IImageBuilder imageBuilderAnchor, Geodetic3D position, NonOverlappingMarkTouchListener touchListener, float springLengthInPixels, float springK, float minSpringLength, float maxSpringLength, float electricCharge, float anchorElectricCharge) { this(imageBuilderWidget, imageBuilderAnchor, position, touchListener, springLengthInPixels, springK, minSpringLength, maxSpringLength, electricCharge, anchorElectricCharge, 0.95f); } public NonOverlappingMark(IImageBuilder imageBuilderWidget, IImageBuilder imageBuilderAnchor, Geodetic3D position, NonOverlappingMarkTouchListener touchListener, float springLengthInPixels, float springK, float minSpringLength, float maxSpringLength, float electricCharge) { this(imageBuilderWidget, imageBuilderAnchor, position, touchListener, springLengthInPixels, springK, minSpringLength, maxSpringLength, electricCharge, 2000.0f, 0.95f); } public NonOverlappingMark(IImageBuilder imageBuilderWidget, IImageBuilder imageBuilderAnchor, Geodetic3D position, NonOverlappingMarkTouchListener touchListener, float springLengthInPixels, float springK, float minSpringLength, float maxSpringLength) { this(imageBuilderWidget, imageBuilderAnchor, position, touchListener, springLengthInPixels, springK, minSpringLength, maxSpringLength, 3000.0f, 2000.0f, 0.95f); } public NonOverlappingMark(IImageBuilder imageBuilderWidget, IImageBuilder imageBuilderAnchor, Geodetic3D position, NonOverlappingMarkTouchListener touchListener, float springLengthInPixels, float springK, float minSpringLength) { this(imageBuilderWidget, imageBuilderAnchor, position, touchListener, springLengthInPixels, springK, minSpringLength, 0.0f, 3000.0f, 2000.0f, 0.95f); } public NonOverlappingMark(IImageBuilder imageBuilderWidget, IImageBuilder imageBuilderAnchor, Geodetic3D position, NonOverlappingMarkTouchListener touchListener, float springLengthInPixels, float springK) { this(imageBuilderWidget, imageBuilderAnchor, position, touchListener, springLengthInPixels, springK, 0.0f, 0.0f, 3000.0f, 2000.0f, 0.95f); } public NonOverlappingMark(IImageBuilder imageBuilderWidget, IImageBuilder imageBuilderAnchor, Geodetic3D position, NonOverlappingMarkTouchListener touchListener, float springLengthInPixels) { this(imageBuilderWidget, imageBuilderAnchor, position, touchListener, springLengthInPixels, 70.0f, 0.0f, 0.0f, 3000.0f, 2000.0f, 0.95f); } public NonOverlappingMark(IImageBuilder imageBuilderWidget, IImageBuilder imageBuilderAnchor, Geodetic3D position, NonOverlappingMarkTouchListener touchListener) { this(imageBuilderWidget, imageBuilderAnchor, position, touchListener, 100.0f, 70.0f, 0.0f, 0.0f, 3000.0f, 2000.0f, 0.95f); } public NonOverlappingMark(IImageBuilder imageBuilderWidget, IImageBuilder imageBuilderAnchor, Geodetic3D position) { this(imageBuilderWidget, imageBuilderAnchor, position, null, 100.0f, 70.0f, 0.0f, 0.0f, 3000.0f, 2000.0f, 0.95f); } public NonOverlappingMark(IImageBuilder imageBuilderWidget, IImageBuilder imageBuilderAnchor, Geodetic3D position, NonOverlappingMarkTouchListener touchListener, float springLengthInPixels, float springK, float minSpringLength, float maxSpringLength, float electricCharge, float anchorElectricCharge, float resistanceFactor) //_widgetScreenPosition(MutableVector2F::nan()), //_anchorScreenPosition(MutableVector2F::nan()), { _cartesianPos = null; _speed = new MutableVector2F(MutableVector2F.zero()); _force = new MutableVector2F(MutableVector2F.zero()); _geoPosition = new Geodetic3D(position); _springLengthInPixels = springLengthInPixels; _springK = springK; _minSpringLength = minSpringLength > 0 ? minSpringLength : (springLengthInPixels * 0.25f); _maxSpringLength = maxSpringLength > 0 ? maxSpringLength : (springLengthInPixels * 1.25f); _electricCharge = electricCharge; _anchorElectricCharge = anchorElectricCharge; _resistanceFactor = resistanceFactor; _touchListener = touchListener; _springGLState = null; _springVertices = null; _springViewportExtentGLFeature = null; _widget = new MarkWidget(imageBuilderWidget); _anchorWidget = new MarkWidget(imageBuilderAnchor); } public final void setID(String id) { _id = id; } public final String getID() { return _id; } public void dispose() { if (_touchListener != null) _touchListener.dispose(); if (_widget != null) _widget.dispose(); if (_anchorWidget != null) _anchorWidget.dispose(); if (_cartesianPos != null) _cartesianPos.dispose(); if (_springGLState != null) { _springGLState._release(); } } public final Vector3D getCartesianPosition(Planet planet) { //C++ TO JAVA CONVERTER TODO TASK: There is no preprocessor in Java: //#warning toCartesian without garbage if (_cartesianPos == null) { _cartesianPos = new Vector3D(planet.toCartesian(_geoPosition)); } return _cartesianPos; } public final void computeAnchorScreenPos(Camera camera, Planet planet) { Vector2F sp = new Vector2F(camera.point2Pixel(getCartesianPosition(planet))); // _anchorScreenPosition.put(sp._x, sp._y); // if (_widgetScreenPosition.isNan()) { // _widgetScreenPosition.put(sp._x, sp._y + 0.01f); // } _anchorWidget.setScreenPos(sp._x, sp._y); if (_widget.getScreenPos().isNan()) { _widget.setScreenPos(sp._x, sp._y + 0.01f); } } public final Vector2F getScreenPos() { return _widget.getScreenPos(); } public final Vector2F getAnchorScreenPos() { return _anchorWidget.getScreenPos(); } public final void renderWidget(G3MRenderContext rc, GLState glState) { if (_widget.isReady()) { _widget.render(rc, glState); } else { _widget.init(rc); } } public final void renderAnchorWidget(G3MRenderContext rc, GLState glState) { if (_anchorWidget.isReady()) { _anchorWidget.render(rc, glState); } else { _anchorWidget.init(rc); } } public final void renderSpringWidget(G3MRenderContext rc, GLState glState) { final Vector2F sp = getScreenPos(); final Vector2F asp = getAnchorScreenPos(); if (_springGLState == null) { _springGLState = new GLState(); _springGLState.addGLFeature(new FlatColorGLFeature(Color.black()), false); _springVertices = rc.getFactory().createFloatBuffer(2 * 2); _springVertices.rawPut(0, sp._x); _springVertices.rawPut(1, -sp._y); _springVertices.rawPut(2, asp._x); _springVertices.rawPut(3, -asp._y); _springGLState.addGLFeature(new Geometry2DGLFeature(_springVertices, 2, 0, true, 0, 3.0f, true, 2.0f, Vector2F.zero()), false); // translation - pointSize - needsPointSize - lineWidth - stride - normalized - index - arrayElementSize - buffer _springViewportExtentGLFeature = new ViewportExtentGLFeature(rc.getCurrentCamera()); _springGLState.addGLFeature(_springViewportExtentGLFeature, false); } else { _springVertices.put(0, sp._x); _springVertices.put(1, -sp._y); _springVertices.put(2, asp._x); _springVertices.put(3, -asp._y); } rc.getGL().drawArrays(GLPrimitive.lines(), 0, 2, _springGLState, rc.getGPUProgramManager()); // count - first } public final void applyCoulombsLaw(NonOverlappingMark that) { Vector2F d = getScreenPos().sub(that.getScreenPos()); double distance = d.length() + 0.001; Vector2F direction = d.div((float)distance); float strength = (float)(this._electricCharge * that._electricCharge / (distance * distance)); Vector2F force = direction.times(strength); this.applyForce(force._x, force._y); that.applyForce(-force._x, -force._y); } public final void applyCoulombsLawFromAnchor(NonOverlappingMark that) { Vector2F dAnchor = getScreenPos().sub(that.getAnchorScreenPos()); double distanceAnchor = dAnchor.length() + 0.001; Vector2F directionAnchor = dAnchor.div((float)distanceAnchor); float strengthAnchor = (float)(this._electricCharge * that._anchorElectricCharge / (distanceAnchor * distanceAnchor)); this.applyForce(directionAnchor._x * strengthAnchor, directionAnchor._y * strengthAnchor); } public final void applyHookesLaw() { Vector2F d = getScreenPos().sub(getAnchorScreenPos()); double mod = d.length(); double displacement = _springLengthInPixels - mod; Vector2F direction = d.div((float)mod); float force = (float)(_springK * displacement); applyForce(direction._x * force, direction._y * force); } public final void applyForce(float x, float y) { _force.add(x, y); } public final void updatePositionWithCurrentForce(float timeInSeconds, int viewportWidth, int viewportHeight, float viewportMargin) { _speed.add(_force._x * timeInSeconds, _force._y * timeInSeconds); _speed.times(_resistanceFactor); //Force has been applied and must be reset //C++ TO JAVA CONVERTER TODO TASK: There is no preprocessor in Java: //#warning It's needed? _force.set(0, 0); //Update position Vector2F widgetPosition = _widget.getScreenPos(); final float newX = widgetPosition._x + (_speed._x * timeInSeconds); final float newY = widgetPosition._y + (_speed._y * timeInSeconds); Vector2F anchorPosition = _anchorWidget.getScreenPos(); // Vector2F spring = Vector2F(newX,newY).sub(anchorPosition).clampLength(_minSpringLength, _maxSpringLength); Vector2F spring = new Vector2F(newX - anchorPosition._x, newY - anchorPosition._y).clampLength(_minSpringLength, _maxSpringLength); _widget.setAndClampScreenPos(anchorPosition._x + spring._x, anchorPosition._y + spring._y, viewportWidth, viewportHeight, viewportMargin); } public final void onResizeViewportEvent(int width, int height) { _widget.onResizeViewportEvent(width, height); _anchorWidget.onResizeViewportEvent(width, height); if (_springViewportExtentGLFeature != null) { _springViewportExtentGLFeature.changeExtent(width, height); } } public final void resetWidgetPositionVelocityAndForce() { _widget.resetPosition(); // _widgetScreenPosition.put(NANF, NANF); _speed.set(0, 0); _force.set(0, 0); } public final int getWidth() { return _widget.getWidth(); } public final int getHeight() { return _widget.getHeight(); } public final boolean onTouchEvent(Vector2F touchedPixel) { if (_touchListener != null) { return _touchListener.touchedMark(this, touchedPixel); } return false; } }
Commons/G3MSharedSDK/src/org/glob3/mobile/generated/NonOverlappingMark.java
package org.glob3.mobile.generated; public class NonOverlappingMark { private float _springLengthInPixels; // MutableVector2F _widgetScreenPosition; // MutableVector2F _anchorScreenPosition; private Vector3D _cartesianPos; private Geodetic3D _geoPosition ; private MutableVector2F _speed = new MutableVector2F(); private MutableVector2F _force = new MutableVector2F(); private MarkWidget _widget; private MarkWidget _anchorWidget; private GLState _springGLState; private IFloatBuffer _springVertices; private ViewportExtentGLFeature _springViewportExtentGLFeature; private final float _springK; private final float _maxSpringLength; private final float _minSpringLength; private final float _electricCharge; private final float _anchorElectricCharge; private final float _resistanceFactor; private String _id; private NonOverlappingMarkTouchListener _touchListener; public NonOverlappingMark(IImageBuilder imageBuilderWidget, IImageBuilder imageBuilderAnchor, Geodetic3D position, NonOverlappingMarkTouchListener touchListener, float springLengthInPixels, float springK, float minSpringLength, float maxSpringLength, float electricCharge, float anchorElectricCharge) { this(imageBuilderWidget, imageBuilderAnchor, position, touchListener, springLengthInPixels, springK, minSpringLength, maxSpringLength, electricCharge, anchorElectricCharge, 0.95f); } public NonOverlappingMark(IImageBuilder imageBuilderWidget, IImageBuilder imageBuilderAnchor, Geodetic3D position, NonOverlappingMarkTouchListener touchListener, float springLengthInPixels, float springK, float minSpringLength, float maxSpringLength, float electricCharge) { this(imageBuilderWidget, imageBuilderAnchor, position, touchListener, springLengthInPixels, springK, minSpringLength, maxSpringLength, electricCharge, 2000.0f, 0.95f); } public NonOverlappingMark(IImageBuilder imageBuilderWidget, IImageBuilder imageBuilderAnchor, Geodetic3D position, NonOverlappingMarkTouchListener touchListener, float springLengthInPixels, float springK, float minSpringLength, float maxSpringLength) { this(imageBuilderWidget, imageBuilderAnchor, position, touchListener, springLengthInPixels, springK, minSpringLength, maxSpringLength, 3000.0f, 2000.0f, 0.95f); } public NonOverlappingMark(IImageBuilder imageBuilderWidget, IImageBuilder imageBuilderAnchor, Geodetic3D position, NonOverlappingMarkTouchListener touchListener, float springLengthInPixels, float springK, float minSpringLength) { this(imageBuilderWidget, imageBuilderAnchor, position, touchListener, springLengthInPixels, springK, minSpringLength, 0.0f, 3000.0f, 2000.0f, 0.95f); } public NonOverlappingMark(IImageBuilder imageBuilderWidget, IImageBuilder imageBuilderAnchor, Geodetic3D position, NonOverlappingMarkTouchListener touchListener, float springLengthInPixels, float springK) { this(imageBuilderWidget, imageBuilderAnchor, position, touchListener, springLengthInPixels, springK, 0.0f, 0.0f, 3000.0f, 2000.0f, 0.95f); } public NonOverlappingMark(IImageBuilder imageBuilderWidget, IImageBuilder imageBuilderAnchor, Geodetic3D position, NonOverlappingMarkTouchListener touchListener, float springLengthInPixels) { this(imageBuilderWidget, imageBuilderAnchor, position, touchListener, springLengthInPixels, 70.0f, 0.0f, 0.0f, 3000.0f, 2000.0f, 0.95f); } public NonOverlappingMark(IImageBuilder imageBuilderWidget, IImageBuilder imageBuilderAnchor, Geodetic3D position, NonOverlappingMarkTouchListener touchListener) { this(imageBuilderWidget, imageBuilderAnchor, position, touchListener, 100.0f, 70.0f, 0.0f, 0.0f, 3000.0f, 2000.0f, 0.95f); } public NonOverlappingMark(IImageBuilder imageBuilderWidget, IImageBuilder imageBuilderAnchor, Geodetic3D position) { this(imageBuilderWidget, imageBuilderAnchor, position, null, 100.0f, 70.0f, 0.0f, 0.0f, 3000.0f, 2000.0f, 0.95f); } public NonOverlappingMark(IImageBuilder imageBuilderWidget, IImageBuilder imageBuilderAnchor, Geodetic3D position, NonOverlappingMarkTouchListener touchListener, float springLengthInPixels, float springK, float minSpringLength, float maxSpringLength, float electricCharge, float anchorElectricCharge, float resistanceFactor) //_widgetScreenPosition(MutableVector2F::nan()), //_anchorScreenPosition(MutableVector2F::nan()), { _cartesianPos = null; _speed = new MutableVector2F(MutableVector2F.zero()); _force = new MutableVector2F(MutableVector2F.zero()); _geoPosition = new Geodetic3D(position); _springLengthInPixels = springLengthInPixels; _springK = springK; _minSpringLength = minSpringLength > 0 ? minSpringLength : (springLengthInPixels * 0.25f); _maxSpringLength = maxSpringLength > 0 ? maxSpringLength : (springLengthInPixels * 1.25f); _electricCharge = electricCharge; _anchorElectricCharge = anchorElectricCharge; _resistanceFactor = resistanceFactor; _touchListener = touchListener; _springGLState = null; _springVertices = null; _springViewportExtentGLFeature = null; _widget = new MarkWidget(imageBuilderWidget); _anchorWidget = new MarkWidget(imageBuilderAnchor); } public final void setID(String id) { _id = id; } public final String getID() { return _id; } public void dispose() { if (_touchListener != null) _touchListener.dispose(); if (_widget != null) _widget.dispose(); if (_anchorWidget != null) _anchorWidget.dispose(); if (_cartesianPos != null) _cartesianPos.dispose(); if (_springGLState != null) { _springGLState._release(); } } public final Vector3D getCartesianPosition(Planet planet) { //C++ TO JAVA CONVERTER TODO TASK: There is no preprocessor in Java: //#warning toCartesian without garbage if (_cartesianPos == null) { _cartesianPos = new Vector3D(planet.toCartesian(_geoPosition)); } return _cartesianPos; } public final void computeAnchorScreenPos(Camera camera, Planet planet) { Vector2F sp = new Vector2F(camera.point2Pixel(getCartesianPosition(planet))); // _anchorScreenPosition.put(sp._x, sp._y); // if (_widgetScreenPosition.isNan()) { // _widgetScreenPosition.put(sp._x, sp._y + 0.01f); // } _anchorWidget.setScreenPos(sp._x, sp._y); if (_widget.getScreenPos().isNan()) { _widget.setScreenPos(sp._x, sp._y + 0.01f); } } public final Vector2F getScreenPos() { return _widget.getScreenPos(); } public final Vector2F getAnchorScreenPos() { return _anchorWidget.getScreenPos(); } public final void renderWidget(G3MRenderContext rc, GLState glState) { if (_widget.isReady()) { _widget.render(rc, glState); } else { _widget.init(rc); } } public final void renderAnchorWidget(G3MRenderContext rc, GLState glState) { if (_anchorWidget.isReady()) { _anchorWidget.render(rc, glState); } else { _anchorWidget.init(rc); } } public final void renderSpringWidget(G3MRenderContext rc, GLState glState) { //C++ TO JAVA CONVERTER TODO TASK: There is no preprocessor in Java: //#warning Diego at work if (_springGLState == null) { _springGLState = new GLState(); _springGLState.addGLFeature(new FlatColorGLFeature(Color.black()), false); // _springGLState->clearGLFeatureGroup(NO_GROUP); _springVertices = rc.getFactory().createFloatBuffer(2 * 2); final Vector2F sp = getScreenPos(); final Vector2F asp = getAnchorScreenPos(); _springVertices.rawPut(0, sp._x); _springVertices.rawPut(1, -sp._y); _springVertices.rawPut(2, asp._x); _springVertices.rawPut(3, -asp._y); _springGLState.addGLFeature(new Geometry2DGLFeature(_springVertices, 2, 0, true, 0, 3.0f, true, 2.0f, Vector2F.zero()), false); // translation - pointSize - needsPointSize - lineWidth - stride - normalized - index - arrayElementSize - buffer _springViewportExtentGLFeature = new ViewportExtentGLFeature(rc.getCurrentCamera()); _springGLState.addGLFeature(_springViewportExtentGLFeature, false); } else { final Vector2F sp = getScreenPos(); final Vector2F asp = getAnchorScreenPos(); _springVertices.put(0, sp._x); _springVertices.put(1, -sp._y); _springVertices.put(2, asp._x); _springVertices.put(3, -asp._y); } rc.getGL().drawArrays(GLPrimitive.lines(), 0, 2, _springGLState, rc.getGPUProgramManager()); // count - first } public final void applyCoulombsLaw(NonOverlappingMark that) { Vector2F d = getScreenPos().sub(that.getScreenPos()); double distance = d.length() + 0.001; Vector2F direction = d.div((float)distance); float strength = (float)(this._electricCharge * that._electricCharge / (distance * distance)); Vector2F force = direction.times(strength); this.applyForce(force._x, force._y); that.applyForce(-force._x, -force._y); } public final void applyCoulombsLawFromAnchor(NonOverlappingMark that) { Vector2F dAnchor = getScreenPos().sub(that.getAnchorScreenPos()); double distanceAnchor = dAnchor.length() + 0.001; Vector2F directionAnchor = dAnchor.div((float)distanceAnchor); float strengthAnchor = (float)(this._electricCharge * that._anchorElectricCharge / (distanceAnchor * distanceAnchor)); this.applyForce(directionAnchor._x * strengthAnchor, directionAnchor._y * strengthAnchor); } public final void applyHookesLaw() { Vector2F d = getScreenPos().sub(getAnchorScreenPos()); double mod = d.length(); double displacement = _springLengthInPixels - mod; Vector2F direction = d.div((float)mod); float force = (float)(_springK * displacement); applyForce(direction._x * force, direction._y * force); } public final void applyForce(float x, float y) { _force.add(x, y); } public final void updatePositionWithCurrentForce(float timeInSeconds, int viewportWidth, int viewportHeight, float viewportMargin) { _speed.add(_force._x * timeInSeconds, _force._y * timeInSeconds); _speed.times(_resistanceFactor); //Force has been applied and must be reset //C++ TO JAVA CONVERTER TODO TASK: There is no preprocessor in Java: //#warning It's needed? _force.set(0, 0); //Update position Vector2F widgetPosition = _widget.getScreenPos(); final float newX = widgetPosition._x + (_speed._x * timeInSeconds); final float newY = widgetPosition._y + (_speed._y * timeInSeconds); Vector2F anchorPosition = _anchorWidget.getScreenPos(); // Vector2F spring = Vector2F(newX,newY).sub(anchorPosition).clampLength(_minSpringLength, _maxSpringLength); Vector2F spring = new Vector2F(newX - anchorPosition._x, newY - anchorPosition._y).clampLength(_minSpringLength, _maxSpringLength); _widget.setAndClampScreenPos(anchorPosition._x + spring._x, anchorPosition._y + spring._y, viewportWidth, viewportHeight, viewportMargin); } public final void onResizeViewportEvent(int width, int height) { _widget.onResizeViewportEvent(width, height); _anchorWidget.onResizeViewportEvent(width, height); if (_springViewportExtentGLFeature != null) { _springViewportExtentGLFeature.changeExtent(width, height); } } public final void resetWidgetPositionVelocityAndForce() { _widget.resetPosition(); // _widgetScreenPosition.put(NANF, NANF); _speed.set(0, 0); _force.set(0, 0); } public final int getWidth() { return _widget.getWidth(); } public final int getHeight() { return _widget.getHeight(); } public final boolean onTouchEvent(Vector2F touchedPixel) { if (_touchListener != null) { return _touchListener.touchedMark(this, touchedPixel); } return false; } }
Generated
Commons/G3MSharedSDK/src/org/glob3/mobile/generated/NonOverlappingMark.java
Generated
Java
bsd-3-clause
fe5a39fef599a81734922438c16fc3838c8e44e4
0
gabrielsr/bomberman-libgdx
package br.unb.unbomber.systems; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.logging.Level; import br.unb.bomberman.ui.screens.ScreenDimensions; import br.unb.unbomber.component.CellPlacement; import br.unb.unbomber.component.Draw; import br.unb.unbomber.component.Movable; import br.unb.unbomber.components.Transform; import br.unb.unbomber.components.Visual; import br.unb.unbomber.core.BaseSystem; import br.unb.unbomber.core.Component; import br.unb.unbomber.core.Entity; import br.unb.unbomber.core.EntityManager; import br.unb.unbomber.gridphysics.Vector2D; import br.unb.unbomber.ui.skin.LoadTexture; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.utils.Array; public class RenderSystem extends BaseSystem { private OrthographicCamera cam; private Array<Entity> renderQueue; private Comparator<Entity> comparator; SpriteBatch batch; private ScreenDimensions screenDimensions = new ScreenDimensions(); public RenderSystem(EntityManager entityManager) { super(entityManager); } public RenderSystem(EntityManager entityManager, SpriteBatch batch) { super(entityManager); this.batch = batch; comparator = new Comparator<Entity>() { @Override public int compare(Entity entityA, Entity entityB) { return (int)Math.signum(getY(entityB) - getY(entityA)); } private int getY(Entity entityA) { CellPlacement placement = (CellPlacement)getEntityManager().getComponent(CellPlacement.class, entityA.getEntityId()); return placement.getCellY(); } }; this.batch = batch; } @Override public void start() { cam = new OrthographicCamera(); cam.setToOrtho(false, screenDimensions.getScreenWidth(), screenDimensions.getScreenHeight()); } @Override public void update() { LoadTexture.load(getEntityManager()); List<Component> renderQueue = new ArrayList<Component>(); renderQueue.addAll(getEntityManager().getComponents(Visual.class)); //renderQueue.sort(comparator); cam.update(); batch.setProjectionMatrix(cam.combined); for (Component visComponent : renderQueue) { Visual vis = (Visual) visComponent; if (vis.getRegion() == null) { continue; } CellPlacement cellPlacement = (CellPlacement) getEntityManager().getComponent(CellPlacement.class, vis.getEntityId()); if(cellPlacement==null){ Draw draw = (Draw) getEntityManager().getComponent(Draw.class, vis.getEntityId()); LOGGER.log(Level.SEVERE, "trying to draw a "+ draw.getType() +"\n But it has not a placement"); continue; } Vector2D<Float> screenPosition; float width = vis.getRegion().getRegionWidth(); float height = vis.getRegion().getRegionHeight(); Movable movable = (Movable) getEntityManager().getComponent(Movable.class, vis.getEntityId()); Vector2D<Float> gridPosition = cellPlacement.centerPosition(); if(movable!=null){ gridPosition = gridPosition.add(movable.getCellPosition().sub(new Vector2D<Float>(0.5f, 0.5f))); } /** screen position */ screenPosition = gridPositionToScreenPosition(gridPosition); Vector2D<Float> repositeTheCenter = new Vector2D<Float>(-0.5f * width, -0.5f * height); screenPosition = screenPosition.add(repositeTheCenter); /** Transformations for the game */ Vector2D<Float> gameTransSum = new Vector2D<Float>(vis.getTransform().dx, vis.getTransform().dy); screenPosition = screenPosition.add(gameTransSum); Transform t = vis.getTransform(); float originX = width * 0.5f; float originY = height * 0.5f; // batch.draw(vis.getRegion(), // screenPosition.getX(), // screenPosition.getY()); batch.draw(vis.getRegion(), screenPosition.getX(), screenPosition.getY(), originX, originY, width, height, t.scalex, t.scaley, MathUtils.radiansToDegrees * t.rotation); } renderQueue.clear(); } public void processEntity(Entity entity) { renderQueue.add(entity); } public OrthographicCamera getCamera() { return cam; } public Visual getVisual(Entity entity){ Visual visual = (Visual)getEntityManager().getComponent(Visual.class, entity.getEntityId()); return visual; } /** * Method that convert a cell placement from grid reference to screen position. * * GridRef -> Up-Down, Left-Right, 1 cell mesure 1.0f u.m. * ScreenRef -> Down-Up, Left-Right, 1 cell 32 pix * * Do linear transformation: * * - get the center of the cell * - rebase to the screen origin (left, down) * - scale to the configured num pix / cell * @param cellPlacement * @return */ public Vector2D<Float> gridPositionToScreenPosition(Vector2D<Float> gridRef ){ //(0,-1) - invert y axe Vector2D<Float> orient = new Vector2D<Float>(1.0f, -1.0f); Vector2D<Float> moveUp = new Vector2D<Float>(0.0f, (float)(screenDimensions.getScreenHeight() - screenDimensions.getHudHeight()) ); float scale = screenDimensions.getCellSize(); return gridRef.mult(orient)//.add(bringToTheBorder) .mult(scale) .add(moveUp); } }
core/src/main/java/br/unb/unbomber/systems/RenderSystem.java
package br.unb.unbomber.systems; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import br.unb.bomberman.ui.screens.ScreenDimensions; import br.unb.unbomber.component.CellPlacement; import br.unb.unbomber.component.Draw; import br.unb.unbomber.component.Movable; import br.unb.unbomber.components.Transform; import br.unb.unbomber.components.Visual; import br.unb.unbomber.core.BaseSystem; import br.unb.unbomber.core.Component; import br.unb.unbomber.core.Entity; import br.unb.unbomber.core.EntityManager; import br.unb.unbomber.gridphysics.Vector2D; import br.unb.unbomber.ui.skin.LoadTexture; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.utils.Array; public class RenderSystem extends BaseSystem { private OrthographicCamera cam; private Array<Entity> renderQueue; private Comparator<Entity> comparator; SpriteBatch batch; private ScreenDimensions screenDimensions; public RenderSystem(EntityManager entityManager) { super(entityManager); screenDimensions = new ScreenDimensions(); } public RenderSystem(EntityManager entityManager, SpriteBatch batch) { super(entityManager); this.batch = batch; comparator = new Comparator<Entity>() { @Override public int compare(Entity entityA, Entity entityB) { return (int)Math.signum(getY(entityB) - getY(entityA)); } private int getY(Entity entityA) { CellPlacement placement = (CellPlacement)getEntityManager().getComponent(CellPlacement.class, entityA.getEntityId()); return placement.getCellY(); } }; this.batch = batch; } @Override public void start() { cam = new OrthographicCamera(); cam.setToOrtho(false, screenDimensions.getScreenWidth(), screenDimensions.getScreenHeight()); } @Override public void update() { LoadTexture.load(getEntityManager()); List<Component> renderQueue = new ArrayList<Component>(); renderQueue.addAll(getEntityManager().getComponents(Visual.class)); //renderQueue.sort(comparator); cam.update(); batch.setProjectionMatrix(cam.combined); for (Component visComponent : renderQueue) { Visual vis = (Visual) visComponent; if (vis.getRegion() == null) { continue; } CellPlacement cellPlacement = (CellPlacement) getEntityManager().getComponent(CellPlacement.class, vis.getEntityId()); if(cellPlacement==null){ Draw draw = (Draw) getEntityManager().getComponent(Draw.class, vis.getEntityId()); //LOGGER.log(Level.SEVERE, "trying to draw a "+ draw.getType() +"\n But it has not a placement"); continue; } Vector2D<Float> screenPosition; float width = vis.getRegion().getRegionWidth(); float height = vis.getRegion().getRegionHeight(); Movable movable = (Movable) getEntityManager().getComponent(Movable.class, vis.getEntityId()); screenPosition = gridPositionToScreenPosition(cellPlacement.centerPosition()); Vector2D<Float> repositeTheCenter = new Vector2D<Float>(-0.5f * width, +0.5f * height); screenPosition.add(repositeTheCenter); /** Transformations for the game */ Vector2D<Float> gameTransSum = new Vector2D<Float>(vis.getTransform().dx, vis.getTransform().dy); screenPosition.add(gameTransSum); if(movable!=null){ screenPosition.add(movable.getCellPosition().sub(cellPlacement.centerPosition())); } Transform t = vis.getTransform(); float originX = width * 0.5f; float originY = height * 0.5f; // batch.draw(vis.getRegion(), // screenPosition.getX(), // screenPosition.getY()); batch.draw(vis.getRegion(), screenPosition.getX(), screenPosition.getY(), originX, originY, width, height, t.scalex, t.scaley, MathUtils.radiansToDegrees * t.rotation); } renderQueue.clear(); } public void processEntity(Entity entity) { renderQueue.add(entity); } public OrthographicCamera getCamera() { return cam; } public Visual getVisual(Entity entity){ Visual visual = (Visual)getEntityManager().getComponent(Visual.class, entity.getEntityId()); return visual; } /** * Method that convert a cell placement from grid reference to screen position. * * GridRef -> Up-Down, Left-Right, 1 cell mesure 1.0f u.m. * ScreenRef -> Down-Up, Left-Right, 1 cell 32 pix * * Do linear transformation: * * - get the center of the cell * - rebase to the screen origin (left, down) * - scale to the configured num pix / cell * @param cellPlacement * @return */ public Vector2D<Float> gridPositionToScreenPosition(Vector2D<Float> gridRef ){ //(0,-1) - invert y axe Vector2D<Float> orient = new Vector2D<Float>(1.0f, -1.0f); Vector2D<Float> moveUp = new Vector2D<Float>(0.0f, (float)(screenDimensions.getScreenHeight() - screenDimensions.getHudHeight()) ); float scale = screenDimensions.getCellSize(); return gridRef.mult(orient)//.add(bringToTheBorder) .mult(scale) .add(moveUp); } }
Fixign RenderSystem
core/src/main/java/br/unb/unbomber/systems/RenderSystem.java
Fixign RenderSystem
Java
mit
86c44630b1033aea0251a88c028d3467117de0d9
0
DemigodsRPG/Demigods3
package com.censoredsoftware.demigods.engine.player; import com.censoredsoftware.censoredlib.data.inventory.CEnderInventory; import com.censoredsoftware.censoredlib.data.inventory.CInventory; import com.censoredsoftware.censoredlib.data.inventory.CItemStack; import com.censoredsoftware.censoredlib.data.player.Notification; import com.censoredsoftware.censoredlib.language.Symbol; import com.censoredsoftware.demigods.engine.Demigods; import com.censoredsoftware.demigods.engine.ability.Ability; import com.censoredsoftware.demigods.engine.battle.Participant; import com.censoredsoftware.demigods.engine.data.DataManager; import com.censoredsoftware.demigods.engine.data.util.CItemStacks; import com.censoredsoftware.demigods.engine.data.util.CLocations; import com.censoredsoftware.demigods.engine.deity.Alliance; import com.censoredsoftware.demigods.engine.deity.Deity; import com.censoredsoftware.demigods.engine.listener.DemigodsChatEvent; import com.censoredsoftware.demigods.engine.structure.Structure; import com.censoredsoftware.demigods.engine.structure.StructureData; import com.censoredsoftware.demigods.engine.util.Configs; import com.censoredsoftware.demigods.engine.util.Messages; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.*; import org.bukkit.*; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.serialization.ConfigurationSerializable; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.potion.PotionEffect; import org.bukkit.scheduler.BukkitRunnable; import java.util.*; public class DCharacter implements Participant, ConfigurationSerializable { private UUID id; private String name; private String mojangAccount; private boolean alive; private double health; private Integer hunger; private Float experience; private Integer level; private Integer killCount; private UUID location; private UUID bedSpawn; private GameMode gameMode; private String deity; private Set<String> minorDeities; private boolean active; private boolean usable; private UUID meta; private UUID inventory, enderInventory; private Set<String> potionEffects; private Set<String> deaths; private static boolean LEVEL_SEPERATE_SKILLS = Demigods.mythos().levelSeperateSkills(); public DCharacter() { deaths = Sets.newHashSet(); potionEffects = Sets.newHashSet(); minorDeities = Sets.newHashSet(); } public DCharacter(UUID id, ConfigurationSection conf) { this.id = id; name = conf.getString("name"); mojangAccount = conf.getString("mojangAccount"); if(conf.isBoolean("alive")) alive = conf.getBoolean("alive"); health = conf.getDouble("health"); hunger = conf.getInt("hunger"); experience = Float.valueOf(conf.getString("experience")); level = conf.getInt("level"); killCount = conf.getInt("killCount"); if(conf.isString("location")) { location = UUID.fromString(conf.getString("location")); try { CLocations.load(location); } catch(Throwable errored) { location = null; } } if(conf.getString("bedSpawn") != null) { bedSpawn = UUID.fromString(conf.getString("bedSpawn")); try { CLocations.load(bedSpawn); } catch(Throwable errored) { bedSpawn = null; } } if(conf.getString("gameMode") != null) gameMode = GameMode.SURVIVAL; deity = conf.getString("deity"); active = conf.getBoolean("active"); usable = conf.getBoolean("usable"); meta = UUID.fromString(conf.getString("meta")); if(conf.isList("minorDeities")) minorDeities = Sets.newHashSet(conf.getStringList("minorDeities")); if(conf.isString("inventory")) inventory = UUID.fromString(conf.getString("inventory")); if(conf.isString("enderInventory")) enderInventory = UUID.fromString(conf.getString("enderInventory")); if(conf.isList("deaths")) deaths = Sets.newHashSet(conf.getStringList("deaths")); if(conf.isList("potionEffects")) potionEffects = Sets.newHashSet(conf.getStringList("potionEffects")); } @Override public Map<String, Object> serialize() { Map<String, Object> map = Maps.newHashMap(); try { map.put("name", name); map.put("mojangAccount", mojangAccount); map.put("alive", alive); map.put("health", health); map.put("hunger", hunger); map.put("experience", experience); map.put("level", level); map.put("killCount", killCount); if(location != null) map.put("location", location.toString()); if(bedSpawn != null) map.put("bedSpawn", bedSpawn.toString()); if(gameMode != null) map.put("gameMode", gameMode.name()); map.put("deity", deity); if(minorDeities != null) map.put("minorDeities", Lists.newArrayList(minorDeities)); map.put("active", active); map.put("usable", usable); map.put("meta", meta.toString()); if(inventory != null) map.put("inventory", inventory.toString()); if(enderInventory != null) map.put("enderInventory", enderInventory.toString()); if(deaths != null) map.put("deaths", Lists.newArrayList(deaths)); if(potionEffects != null) map.put("potionEffects", Lists.newArrayList(potionEffects)); } catch(Throwable ignored) {} return map; } void generateId() { id = UUID.randomUUID(); } void setName(String name) { this.name = name; } void setDeity(Deity deity) { this.deity = deity.getName(); } public void setMinorDeities(Set<String> set) { this.minorDeities = set; } public void addMinorDeity(Deity deity) { this.minorDeities.add(deity.getName()); } public void removeMinorDeity(Deity deity) { this.minorDeities.remove(deity.getName()); } void setMojangAccount(DPlayer player) { this.mojangAccount = player.getMojangAccount(); } public void setActive(boolean option) { this.active = option; Util.save(this); } public void saveInventory() { this.inventory = Util.createInventory(this).getId(); this.enderInventory = Util.createEnderInventory(this).getId(); Util.save(this); } public void setAlive(boolean alive) { this.alive = alive; Util.save(this); } public void setHealth(double health) { this.health = health; } public void setHunger(int hunger) { this.hunger = hunger; } public void setLevel(int level) { this.level = level; } public void setExperience(float exp) { this.experience = exp; } public void setLocation(Location location) { this.location = CLocations.create(location).getId(); } public void setBedSpawn(Location location) { this.bedSpawn = CLocations.create(location).getId(); } public void setGameMode(GameMode gameMode) { this.gameMode = gameMode; } public void setMeta(Meta meta) { this.meta = meta.getId(); } public void setUsable(boolean usable) { this.usable = usable; } public void setPotionEffects(Collection<PotionEffect> potions) { if(potions != null) { if(potionEffects == null) potionEffects = Sets.newHashSet(); for(PotionEffect potion : potions) potionEffects.add((new DSavedPotion(potion)).getId().toString()); } } public Set<PotionEffect> getPotionEffects() { if(potionEffects == null) potionEffects = Sets.newHashSet(); Set<PotionEffect> set = new HashSet<PotionEffect>(); for(String stringId : potionEffects) { try { PotionEffect potion = Util.getSavedPotion(UUID.fromString(stringId)).toPotionEffect(); if(potion != null) { DataManager.savedPotions.remove(UUID.fromString(stringId)); set.add(potion); } } catch(Exception ignored) {} } potionEffects.clear(); return set; } public Collection<DSavedPotion> getRawPotionEffects() { if(potionEffects == null) potionEffects = Sets.newHashSet(); return Collections2.transform(potionEffects, new Function<String, DSavedPotion>() { @Override public DSavedPotion apply(String s) { try { return DataManager.savedPotions.get(UUID.fromString(s)); } catch(Exception ignored) {} return null; } }); } public CInventory getInventory() { if(Util.getInventory(inventory) == null) inventory = Util.createEmptyInventory().getId(); return Util.getInventory(inventory); } public CEnderInventory getEnderInventory() { if(Util.getEnderInventory(enderInventory) == null) enderInventory = Util.createEnderInventory(this).getId(); return Util.getEnderInventory(enderInventory); } public Meta getMeta() { return Util.loadMeta(meta); } public OfflinePlayer getOfflinePlayer() { return Bukkit.getOfflinePlayer(getPlayerName()); } public String getName() { return name; } public boolean isActive() { return active; } public Location getLocation() { if(location == null) return null; return CLocations.load(location).toLocation(); } public Location getBedSpawn() { if(bedSpawn == null) return null; return CLocations.load(bedSpawn).toLocation(); } public GameMode getGameMode() { return gameMode; } public Location getCurrentLocation() { if(getOfflinePlayer().isOnline()) return getOfflinePlayer().getPlayer().getLocation(); return getLocation(); } @Override public DCharacter getRelatedCharacter() { return this; } @Override public LivingEntity getEntity() { return getOfflinePlayer().getPlayer(); } public String getMojangAccount() { return mojangAccount; } public String getPlayerName() { return DPlayer.Util.getPlayer(mojangAccount).getPlayerName(); } public Integer getLevel() { return level; } public boolean isAlive() { return alive; } public Double getHealth() { return health; } public Double getMaxHealth() { return getDeity().getMaxHealth(); } public Integer getHunger() { return hunger; } public Float getExperience() { return experience; } public boolean isDeity(String deityName) { return getDeity().getName().equalsIgnoreCase(deityName); } public Deity getDeity() { return Deity.Util.getDeity(this.deity); } public Collection<Deity> getMinorDeities() { return Collections2.transform(minorDeities, new Function<String, Deity>() { @Override public Deity apply(String deity) { return Deity.Util.getDeity(deity); } }); } public Alliance getAlliance() { return getDeity().getAlliance(); } public int getKillCount() { return killCount; } public void setKillCount(int amount) { killCount = amount; Util.save(this); } public void addKill() { killCount += 1; Util.save(this); } public int getDeathCount() { return deaths.size(); } public void addDeath() { if(deaths == null) deaths = Sets.newHashSet(); deaths.add(new DDeath(this).getId().toString()); Util.save(this); } public void addDeath(DCharacter attacker) { deaths.add(new DDeath(this, attacker).getId().toString()); Util.save(this); } public Collection<DDeath> getDeaths() { if(deaths == null) deaths = Sets.newHashSet(); return Collections2.transform(deaths, new Function<String, DDeath>() { @Override public DDeath apply(String s) { try { return DDeath.Util.load(UUID.fromString(s)); } catch(Exception ignored) {} return null; } }); } public Collection<StructureData> getOwnedStructures() { return StructureData.Util.findAll(new Predicate<StructureData>() { @Override public boolean apply(StructureData data) { return data.getOwner().equals(getId()); } }); } public Collection<StructureData> getOwnedStructures(final String type) { return StructureData.Util.findAll(new Predicate<StructureData>() { @Override public boolean apply(StructureData data) { return data.getTypeName().equals(type) && data.getOwner().equals(getId()); } }); } public int getFavorRegen() { int favorRegenSkill = getMeta().getSkill(Skill.Type.FAVOR_REGEN) != null ? 4 * getMeta().getSkill(Skill.Type.FAVOR_REGEN).getLevel() : 0; int regenRate = (int) Math.ceil(Configs.getSettingDouble("multipliers.favor") * (getDeity().getFavorRegen() + favorRegenSkill)); if(regenRate < 30) regenRate = 30; return regenRate; } public void setCanPvp(boolean pvp) { DPlayer.Util.getPlayer(getOfflinePlayer()).setCanPvp(pvp); } @Override public boolean canPvp() { return DPlayer.Util.getPlayer(getMojangAccount()).canPvp(); } public boolean isUsable() { return usable; } public void updateUseable() { usable = Deity.Util.getDeity(this.deity) != null && Deity.Util.getDeity(this.deity).getFlags().contains(Deity.Flag.PLAYABLE); } public UUID getId() { return id; } public Collection<DPet> getPets() { return DPet.Util.findByOwner(id); } public void remove() { // Define the DPlayer DPlayer dPlayer = DPlayer.Util.getPlayer(getOfflinePlayer()); // Switch the player to mortal if(getOfflinePlayer().isOnline() && dPlayer.getCurrent().getName().equalsIgnoreCase(getName())) dPlayer.setToMortal(); // Remove the data if(dPlayer.getCurrent().getName().equalsIgnoreCase(getName())) dPlayer.resetCurrent(); for(StructureData structureSave : Structure.Util.getStructureWithFlag(Structure.Flag.DELETE_WITH_OWNER)) if(structureSave.hasOwner() && structureSave.getOwner().equals(getId())) structureSave.remove(); for(DSavedPotion potion : getRawPotionEffects()) DataManager.savedPotions.remove(potion.getId()); Util.deleteInventory(getInventory().getId()); Util.deleteEnderInventory(getEnderInventory().getId()); Util.deleteMeta(getMeta().getId()); Util.delete(getId()); } public void sendAllianceMessage(String message) { DemigodsChatEvent chatEvent = new DemigodsChatEvent(message, DCharacter.Util.getOnlineCharactersWithAlliance(getAlliance())); Bukkit.getPluginManager().callEvent(chatEvent); if(!chatEvent.isCancelled()) for(Player player : chatEvent.getRecipients()) player.sendMessage(message); } public void chatWithAlliance(String message) { sendAllianceMessage(" " + ChatColor.GRAY + getAlliance() + "s " + ChatColor.DARK_GRAY + "" + Symbol.BLACK_FLAG + " " + getDeity().getColor() + name + ChatColor.GRAY + ": " + ChatColor.RESET + message); Messages.info("[" + getAlliance() + "]" + name + ": " + message); } public void applyToPlayer(final Player player) { // Define variables DPlayer playerSave = DPlayer.Util.getPlayer(player); // Set character to active setActive(true); if(playerSave.getMortalInventory() != null) { playerSave.setMortalName(player.getDisplayName()); playerSave.setMortalListName(player.getPlayerListName()); } // Update their inventory if(playerSave.getCharacters().size() == 1) saveInventory(); else player.getEnderChest().clear(); getInventory().setToPlayer(player); getEnderInventory().setToPlayer(player); // Update health, experience, and name player.setDisplayName(getDeity().getColor() + getName()); player.setPlayerListName(getDeity().getColor() + getName()); player.setMaxHealth(getMaxHealth()); player.setHealth(getHealth() >= getMaxHealth() ? getMaxHealth() : getHealth()); player.setFoodLevel(getHunger()); player.setExp(getExperience()); player.setLevel(getLevel()); for(PotionEffect potion : player.getActivePotionEffects()) player.removePotionEffect(potion.getType()); Set<PotionEffect> potionEffects = getPotionEffects(); if(!potionEffects.isEmpty()) player.addPotionEffects(potionEffects); Bukkit.getScheduler().scheduleSyncDelayedTask(Demigods.PLUGIN, new BukkitRunnable() { @Override public void run() { if(getBedSpawn() != null) player.setBedSpawnLocation(getBedSpawn()); } }, 1); if(gameMode != null) player.setGameMode(gameMode); // Set player display name player.setDisplayName(getDeity().getColor() + getName()); player.setPlayerListName(getDeity().getColor() + getName()); // Re-own pets DPet.Util.reownPets(player, this); // Add to their team Demigods.BOARD.getTeam(getAlliance().getName()).removePlayer(getOfflinePlayer()); } public static class Inventory extends CInventory { public Inventory() { super(); } public Inventory(UUID id, ConfigurationSection conf) { super(id, conf); } protected CItemStack create(ItemStack itemStack) { return CItemStacks.create(itemStack); } protected CItemStack load(UUID itemStack) { return CItemStacks.load(itemStack); } protected void delete() { DataManager.inventories.remove(getId()); } } public static class EnderInventory extends CEnderInventory { public EnderInventory() { super(); } public EnderInventory(UUID id, ConfigurationSection conf) { super(id, conf); } protected CItemStack create(ItemStack itemStack) { return CItemStacks.create(itemStack); } protected CItemStack load(UUID itemStack) { return CItemStacks.load(itemStack); } protected void delete() { DataManager.enderInventories.remove(this.getId()); } } public static class Meta implements ConfigurationSerializable { private UUID id; private UUID character; private int favor; private int maxFavor; private int skillPoints; private Set<String> notifications; private Map<String, Object> binds; private Map<String, Object> skillData; private Map<String, Object> warps; private Map<String, Object> invites; public Meta() {} public Meta(UUID id, ConfigurationSection conf) { this.id = id; favor = conf.getInt("favor"); maxFavor = conf.getInt("maxFavor"); skillPoints = conf.getInt("skillPoints"); notifications = Sets.newHashSet(conf.getStringList("notifications")); character = UUID.fromString(conf.getString("character")); if(conf.getConfigurationSection("skillData") != null) skillData = conf.getConfigurationSection("skillData").getValues(false); if(conf.getConfigurationSection("binds") != null) binds = conf.getConfigurationSection("binds").getValues(false); if(conf.getConfigurationSection("warps") != null) warps = conf.getConfigurationSection("warps").getValues(false); if(conf.getConfigurationSection("invites") != null) invites = conf.getConfigurationSection("invites").getValues(false); } @Override public Map<String, Object> serialize() { Map<String, Object> map = Maps.newHashMap(); map.put("character", character.toString()); map.put("favor", favor); map.put("maxFavor", maxFavor); map.put("skillPoints", skillPoints); map.put("notifications", Lists.newArrayList(notifications)); map.put("binds", binds); map.put("skillData", skillData); map.put("warps", warps); map.put("invites", invites); return map; } public void generateId() { id = UUID.randomUUID(); } void setCharacter(DCharacter character) { this.character = character.getId(); } void initialize() { notifications = Sets.newHashSet(); warps = Maps.newHashMap(); invites = Maps.newHashMap(); skillData = Maps.newHashMap(); binds = Maps.newHashMap(); } public UUID getId() { return id; } public DCharacter getCharacter() { return DCharacter.Util.load(character); } public void setSkillPoints(int skillPoints) { this.skillPoints = skillPoints; } public int getSkillPoints() { return skillPoints; } public void addSkillPoints(int skillPoints) { setSkillPoints(getSkillPoints() + skillPoints); } public void subtractSkillPoints(int skillPoints) { setSkillPoints(getSkillPoints() - skillPoints); } public void addNotification(Notification notification) { getNotifications().add(notification.getId().toString()); Util.saveMeta(this); } public void removeNotification(Notification notification) { getNotifications().remove(notification.getId().toString()); Util.saveMeta(this); } public Set<String> getNotifications() { if(this.notifications == null) this.notifications = Sets.newHashSet(); return this.notifications; } public void clearNotifications() { notifications.clear(); } public boolean hasNotifications() { return !notifications.isEmpty(); } public void addWarp(String name, Location location) { warps.put(name.toLowerCase(), CLocations.create(location).getId().toString()); Util.saveMeta(this); } public void removeWarp(String name) { getWarps().remove(name.toLowerCase()); Util.saveMeta(this); } public Map<String, Object> getWarps() { if(this.warps == null) this.warps = Maps.newHashMap(); return this.warps; } public void clearWarps() { getWarps().clear(); } public boolean hasWarps() { return !this.warps.isEmpty(); } public void addInvite(String name, Location location) { getInvites().put(name.toLowerCase(), CLocations.create(location).getId().toString()); Util.saveMeta(this); } public void removeInvite(String name) { getInvites().remove(name.toLowerCase()); Util.saveMeta(this); } public Map<String, Object> getInvites() { if(this.invites == null) this.invites = Maps.newHashMap(); return this.invites; } public void clearInvites() { invites.clear(); } public boolean hasInvites() { return !this.invites.isEmpty(); } public void resetSkills() { getRawSkills().clear(); for(Skill.Type type : Skill.Type.values()) if(type.isDefault()) addSkill(Skill.Util.createSkill(getCharacter(), type)); } public void cleanSkills() { List<String> toRemove = Lists.newArrayList(); // Locate obselete skills for(String skillName : getRawSkills().keySet()) { try { // Attempt to find the value of the skillname Skill.Type.valueOf(skillName.toUpperCase()); } catch(Exception ignored) { // There was an error. Catch it and remove the skill. toRemove.add(skillName); } } // Remove the obsolete skills for(String skillName : toRemove) getRawSkills().remove(skillName); } public void addSkill(Skill skill) { if(!getRawSkills().containsKey(skill.getType().toString())) getRawSkills().put(skill.getType().toString(), skill.getId().toString()); Util.saveMeta(this); } public Skill getSkill(Skill.Type type) { if(getRawSkills().containsKey(type.toString())) return Skill.Util.loadSkill(UUID.fromString(getRawSkills().get(type.toString()).toString())); return null; } public Map<String, Object> getRawSkills() { if(skillData == null) skillData = Maps.newHashMap(); return skillData; } public Collection<Skill> getSkills() { return Collections2.transform(getRawSkills().values(), new Function<Object, Skill>() { @Override public Skill apply(Object obj) { return Skill.Util.loadSkill(UUID.fromString(obj.toString())); } }); } public boolean checkBound(String abilityName, Material material) { return getBinds().containsKey(abilityName) && binds.get(abilityName).equals(material.name()); } public boolean isBound(Ability ability) { return getBinds().containsKey(ability.getName()); } public boolean isBound(Material material) { return getBinds().containsValue(material.name()); } public void setBind(Ability ability, Material material) { getBinds().put(ability.getName(), material.name()); } public Map<String, Object> getBinds() { if(binds == null) binds = Maps.newHashMap(); return this.binds; } public void removeBind(Ability ability) { getBinds().remove(ability.getName()); } public void removeBind(Material material) { if(getBinds().containsValue(material.name())) { String toRemove = null; for(Map.Entry<String, Object> entry : getBinds().entrySet()) { toRemove = entry.getValue().equals(material.name()) ? entry.getKey() : null; } getBinds().remove(toRemove); } } public int getIndividualSkillCap() { int total = 0; for(Skill skill : getSkills()) total += skill.getLevel(); return getOverallSkillCap() - total; } public int getOverallSkillCap() { // This is done this way so it can easily be manipulated later return Configs.getSettingInt("caps.skills"); } public int getAscensions() { if(LEVEL_SEPERATE_SKILLS) { double total = 0.0; for(Skill skill : getSkills()) total += skill.getLevel(); return (int) Math.ceil(total / getSkills().size()); } return (int) Math.ceil(getSkillPoints() / 500); // TODO Balance this. } public Integer getFavor() { return favor; } public void setFavor(int amount) { favor = amount; Util.saveMeta(this); } public void addFavor(int amount) { if((favor + amount) > maxFavor) favor = maxFavor; else favor += amount; Util.saveMeta(this); } public void subtractFavor(int amount) { if((favor - amount) < 0) favor = 0; else favor -= amount; Util.saveMeta(this); } public Integer getMaxFavor() { return maxFavor; } public void addMaxFavor(int amount) { if((maxFavor + amount) > Configs.getSettingInt("caps.favor")) maxFavor = Configs.getSettingInt("caps.favor"); else maxFavor += amount; Util.saveMeta(this); } public void setMaxFavor(int amount) { if(amount < 0) maxFavor = 0; if(amount > Configs.getSettingInt("caps.favor")) maxFavor = Configs.getSettingInt("caps.favor"); else maxFavor = amount; Util.saveMeta(this); } public void subtractMaxFavor(int amount) { setMaxFavor(getMaxFavor() - amount); } } public static class Util { public static void save(DCharacter character) { DataManager.characters.put(character.getId(), character); } public static void saveMeta(Meta meta) { DataManager.characterMetas.put(meta.getId(), meta); } public static void saveInventory(Inventory inventory) { DataManager.inventories.put(inventory.getId(), inventory); } public static void saveInventory(EnderInventory inventory) { DataManager.enderInventories.put(inventory.getId(), inventory); } public static void delete(UUID id) { DataManager.characters.remove(id); } public static void deleteMeta(UUID id) { DataManager.characterMetas.remove(id); } public static void deleteInventory(UUID id) { DataManager.inventories.remove(id); } public static void deleteEnderInventory(UUID id) { DataManager.enderInventories.remove(id); } public static void create(DPlayer player, String chosenDeity, String chosenName, boolean switchCharacter) { // Switch to new character if(switchCharacter) player.switchCharacter(create(player, chosenName, chosenDeity)); } public static DCharacter create(DPlayer player, String charName, String charDeity) { if(getCharacterByName(charName) == null) { // Create the DCharacter return create(player, charName, Deity.Util.getDeity(charDeity)); } return null; } private static DCharacter create(final DPlayer player, final String charName, final Deity deity) { DCharacter character = new DCharacter(); character.generateId(); character.setAlive(true); character.setMojangAccount(player); character.setName(charName); character.setDeity(deity); character.setMinorDeities(new HashSet<String>(0)); character.setUsable(true); character.setHealth(deity.getMaxHealth()); character.setHunger(20); character.setExperience(0); character.setLevel(0); character.setKillCount(0); character.setLocation(player.getOfflinePlayer().getPlayer().getLocation()); character.setMeta(Util.createMeta(character)); save(character); return character; } public static CInventory createInventory(DCharacter character) { PlayerInventory inventory = character.getOfflinePlayer().getPlayer().getInventory(); Inventory charInventory = new Inventory(); charInventory.generateId(); if(inventory.getHelmet() != null) charInventory.setHelmet(inventory.getHelmet()); if(inventory.getChestplate() != null) charInventory.setChestplate(inventory.getChestplate()); if(inventory.getLeggings() != null) charInventory.setLeggings(inventory.getLeggings()); if(inventory.getBoots() != null) charInventory.setBoots(inventory.getBoots()); charInventory.setItems(inventory); saveInventory(charInventory); return charInventory; } public static CInventory createEmptyInventory() { Inventory charInventory = new Inventory(); charInventory.generateId(); charInventory.setHelmet(new ItemStack(Material.AIR)); charInventory.setChestplate(new ItemStack(Material.AIR)); charInventory.setLeggings(new ItemStack(Material.AIR)); charInventory.setBoots(new ItemStack(Material.AIR)); saveInventory(charInventory); return charInventory; } public static CEnderInventory createEnderInventory(DCharacter character) { org.bukkit.inventory.Inventory inventory = character.getOfflinePlayer().getPlayer().getEnderChest(); EnderInventory enderInventory = new EnderInventory(); enderInventory.generateId(); enderInventory.setItems(inventory); saveInventory(enderInventory); return enderInventory; } public static CEnderInventory createEmptyEnderInventory() { EnderInventory enderInventory = new EnderInventory(); enderInventory.generateId(); saveInventory(enderInventory); return enderInventory; } public static Meta createMeta(DCharacter character) { Meta charMeta = new Meta(); charMeta.initialize(); charMeta.setCharacter(character); charMeta.generateId(); charMeta.setFavor(Configs.getSettingInt("character.defaults.favor")); charMeta.setMaxFavor(Configs.getSettingInt("character.defaults.max_favor")); charMeta.resetSkills(); saveMeta(charMeta); return charMeta; } public static Set<DCharacter> loadAll() { return Sets.newHashSet(DataManager.characters.values()); } public static DCharacter load(UUID id) { return DataManager.characters.get(id); } public static Meta loadMeta(UUID id) { return DataManager.characterMetas.get(id); } public static Inventory getInventory(UUID id) { try { return DataManager.inventories.get(id); } catch(Exception ignored) {} return null; } public static EnderInventory getEnderInventory(UUID id) { try { return DataManager.enderInventories.get(id); } catch(Exception ignored) {} return null; } public static DSavedPotion getSavedPotion(UUID id) { try { return DataManager.savedPotions.get(id); } catch(Exception ignored) {} return null; } public static void updateUsableCharacters() { for(DCharacter character : loadAll()) character.updateUseable(); } public static DCharacter getCharacterByName(final String name) { try { return Iterators.find(loadAll().iterator(), new Predicate<DCharacter>() { @Override public boolean apply(DCharacter loaded) { return loaded.getName().equalsIgnoreCase(name); } }); } catch(Exception ignored) {} return null; } public static boolean charExists(String name) { return getCharacterByName(name) != null; } public static boolean isCooledDown(DCharacter player, String ability, boolean sendMsg) { if(DataManager.hasKeyTemp(player.getName(), ability + "_cooldown") && Long.parseLong(DataManager.getValueTemp(player.getName(), ability + "_cooldown").toString()) > System.currentTimeMillis()) { if(sendMsg) player.getOfflinePlayer().getPlayer().sendMessage(ChatColor.RED + ability + " has not cooled down!"); return false; } else return true; } public static void setCoolDown(DCharacter player, String ability, long cooldown) { DataManager.saveTemp(player.getName(), ability + "_cooldown", cooldown); } public static long getCoolDown(DCharacter player, String ability) { return Long.parseLong(DataManager.getValueTemp(player.getName(), ability + "_cooldown").toString()); } public static Set<DCharacter> getAllActive() { return Sets.filter(loadAll(), new Predicate<DCharacter>() { @Override public boolean apply(DCharacter character) { return character.isUsable() && character.isActive(); } }); } public static Set<DCharacter> getAllUsable() { return Sets.filter(loadAll(), new Predicate<DCharacter>() { @Override public boolean apply(DCharacter character) { return character.isUsable(); } }); } /** * Returns true if <code>char1</code> is allied with <code>char2</code> based * on their current alliances. * * @param char1 the first character to check. * @param char2 the second character to check. * @return boolean */ public static boolean areAllied(DCharacter char1, DCharacter char2) { return char1.getAlliance().getName().equalsIgnoreCase(char2.getAlliance().getName()); } public static Collection<DCharacter> getOnlineCharactersWithDeity(final String deity) { return getCharactersWithPredicate(new Predicate<DCharacter>() { @Override public boolean apply(DCharacter character) { return character.isActive() && character.getOfflinePlayer().isOnline() && character.getDeity().getName().equalsIgnoreCase(deity); } }); } public static Collection<DCharacter> getOnlineCharactersWithAbility(final String abilityName) { return getCharactersWithPredicate(new Predicate<DCharacter>() { @Override public boolean apply(DCharacter character) { if(character.isActive() && character.getOfflinePlayer().isOnline()) { for(Ability abilityToCheck : character.getDeity().getAbilities()) if(abilityToCheck.getName().equalsIgnoreCase(abilityName)) return true; } return false; } }); } public static Collection<DCharacter> getOnlineCharactersWithAlliance(final Alliance alliance) { return getCharactersWithPredicate(new Predicate<DCharacter>() { @Override public boolean apply(DCharacter character) { return character.isActive() && character.getOfflinePlayer().isOnline() && character.getAlliance().equals(alliance); } }); } public static Collection<DCharacter> getOnlineCharactersWithoutAlliance(final Alliance alliance) { return getCharactersWithPredicate(new Predicate<DCharacter>() { @Override public boolean apply(DCharacter character) { return character.isActive() && character.getOfflinePlayer().isOnline() && !character.getAlliance().equals(alliance); } }); } public static Collection<DCharacter> getOnlineCharactersBelowAscension(final int ascension) { return getCharactersWithPredicate(new Predicate<DCharacter>() { @Override public boolean apply(DCharacter character) { return character.isActive() && character.getOfflinePlayer().isOnline() && character.getMeta().getAscensions() < ascension; } }); } public static Collection<DCharacter> getOnlineCharacters() { return getCharactersWithPredicate(new Predicate<DCharacter>() { @Override public boolean apply(DCharacter character) { return character.isActive() && character.getOfflinePlayer().isOnline(); } }); } public static Collection<DCharacter> getCharactersWithPredicate(Predicate<DCharacter> predicate) { return Collections2.filter(getAllUsable(), predicate); } /** * Updates favor for all online characters. */ public static void updateFavor() { for(Player player : Bukkit.getOnlinePlayers()) { DCharacter character = DPlayer.Util.getPlayer(player).getCurrent(); if(character != null) character.getMeta().addFavor(character.getFavorRegen()); } } } }
Demigods-Engine/src/main/java/com/censoredsoftware/demigods/engine/player/DCharacter.java
package com.censoredsoftware.demigods.engine.player; import com.censoredsoftware.censoredlib.data.inventory.CEnderInventory; import com.censoredsoftware.censoredlib.data.inventory.CInventory; import com.censoredsoftware.censoredlib.data.inventory.CItemStack; import com.censoredsoftware.censoredlib.data.player.Notification; import com.censoredsoftware.censoredlib.language.Symbol; import com.censoredsoftware.demigods.engine.Demigods; import com.censoredsoftware.demigods.engine.ability.Ability; import com.censoredsoftware.demigods.engine.battle.Participant; import com.censoredsoftware.demigods.engine.data.DataManager; import com.censoredsoftware.demigods.engine.data.util.CItemStacks; import com.censoredsoftware.demigods.engine.data.util.CLocations; import com.censoredsoftware.demigods.engine.deity.Alliance; import com.censoredsoftware.demigods.engine.deity.Deity; import com.censoredsoftware.demigods.engine.listener.DemigodsChatEvent; import com.censoredsoftware.demigods.engine.structure.Structure; import com.censoredsoftware.demigods.engine.structure.StructureData; import com.censoredsoftware.demigods.engine.util.Configs; import com.censoredsoftware.demigods.engine.util.Messages; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.*; import org.bukkit.*; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.serialization.ConfigurationSerializable; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.potion.PotionEffect; import org.bukkit.scheduler.BukkitRunnable; import java.util.*; public class DCharacter implements Participant, ConfigurationSerializable { private UUID id; private String name; private String mojangAccount; private boolean alive; private double health; private Integer hunger; private Float experience; private Integer level; private Integer killCount; private UUID location; private UUID bedSpawn; private GameMode gameMode; private String deity; private Set<String> minorDeities; private boolean active; private boolean usable; private UUID meta; private UUID inventory, enderInventory; private Set<String> potionEffects; private Set<String> deaths; private static boolean LEVEL_SEPERATE_SKILLS = Demigods.mythos().levelSeperateSkills(); public DCharacter() { deaths = Sets.newHashSet(); potionEffects = Sets.newHashSet(); minorDeities = Sets.newHashSet(); } public DCharacter(UUID id, ConfigurationSection conf) { this.id = id; name = conf.getString("name"); mojangAccount = conf.getString("mojangAccount"); if(conf.isBoolean("alive")) alive = conf.getBoolean("alive"); health = conf.getDouble("health"); hunger = conf.getInt("hunger"); experience = Float.valueOf(conf.getString("experience")); level = conf.getInt("level"); killCount = conf.getInt("killCount"); if(conf.isString("location")) { location = UUID.fromString(conf.getString("location")); try { CLocations.load(location); } catch(Throwable errored) { location = null; } } if(conf.getString("bedSpawn") != null) { bedSpawn = UUID.fromString(conf.getString("bedSpawn")); try { CLocations.load(bedSpawn); } catch(Throwable errored) { bedSpawn = null; } } if(conf.getString("gameMode") != null) gameMode = GameMode.SURVIVAL; deity = conf.getString("deity"); active = conf.getBoolean("active"); usable = conf.getBoolean("usable"); meta = UUID.fromString(conf.getString("meta")); if(conf.isList("minorDeities")) minorDeities = Sets.newHashSet(conf.getStringList("minorDeities")); if(conf.isString("inventory")) inventory = UUID.fromString(conf.getString("inventory")); if(conf.isString("enderInventory")) enderInventory = UUID.fromString(conf.getString("enderInventory")); if(conf.isList("deaths")) deaths = Sets.newHashSet(conf.getStringList("deaths")); if(conf.isList("potionEffects")) potionEffects = Sets.newHashSet(conf.getStringList("potionEffects")); } @Override public Map<String, Object> serialize() { Map<String, Object> map = Maps.newHashMap(); try { map.put("name", name); map.put("mojangAccount", mojangAccount); map.put("alive", alive); map.put("health", health); map.put("hunger", hunger); map.put("experience", experience); map.put("level", level); map.put("killCount", killCount); if(location != null) map.put("location", location.toString()); if(bedSpawn != null) map.put("bedSpawn", bedSpawn.toString()); if(gameMode != null) map.put("gameMode", gameMode.name()); map.put("deity", deity); if(minorDeities != null) map.put("minorDeities", Lists.newArrayList(minorDeities)); map.put("active", active); map.put("usable", usable); map.put("meta", meta.toString()); if(inventory != null) map.put("inventory", inventory.toString()); if(enderInventory != null) map.put("enderInventory", enderInventory.toString()); if(deaths != null) map.put("deaths", Lists.newArrayList(deaths)); if(potionEffects != null) map.put("potionEffects", Lists.newArrayList(potionEffects)); } catch(Throwable ignored) {} return map; } void generateId() { id = UUID.randomUUID(); } void setName(String name) { this.name = name; } void setDeity(Deity deity) { this.deity = deity.getName(); } public void setMinorDeities(Set<String> set) { this.minorDeities = set; } public void addMinorDeity(Deity deity) { this.minorDeities.add(deity.getName()); } public void removeMinorDeity(Deity deity) { this.minorDeities.remove(deity.getName()); } void setMojangAccount(DPlayer player) { this.mojangAccount = player.getMojangAccount(); } public void setActive(boolean option) { this.active = option; Util.save(this); } public void saveInventory() { this.inventory = Util.createInventory(this).getId(); this.enderInventory = Util.createEnderInventory(this).getId(); Util.save(this); } public void setAlive(boolean alive) { this.alive = alive; Util.save(this); } public void setHealth(double health) { this.health = health; } public void setHunger(int hunger) { this.hunger = hunger; } public void setLevel(int level) { this.level = level; } public void setExperience(float exp) { this.experience = exp; } public void setLocation(Location location) { this.location = CLocations.create(location).getId(); } public void setBedSpawn(Location location) { this.bedSpawn = CLocations.create(location).getId(); } public void setGameMode(GameMode gameMode) { this.gameMode = gameMode; } public void setMeta(Meta meta) { this.meta = meta.getId(); } public void setUsable(boolean usable) { this.usable = usable; } public void setPotionEffects(Collection<PotionEffect> potions) { if(potions != null) { if(potionEffects == null) potionEffects = Sets.newHashSet(); for(PotionEffect potion : potions) potionEffects.add((new DSavedPotion(potion)).getId().toString()); } } public Set<PotionEffect> getPotionEffects() { if(potionEffects == null) potionEffects = Sets.newHashSet(); Set<PotionEffect> set = new HashSet<PotionEffect>(); for(String stringId : potionEffects) { try { PotionEffect potion = Util.getSavedPotion(UUID.fromString(stringId)).toPotionEffect(); if(potion != null) { DataManager.savedPotions.remove(UUID.fromString(stringId)); set.add(potion); } } catch(Exception ignored) {} } potionEffects.clear(); return set; } public Collection<DSavedPotion> getRawPotionEffects() { if(potionEffects == null) potionEffects = Sets.newHashSet(); return Collections2.transform(potionEffects, new Function<String, DSavedPotion>() { @Override public DSavedPotion apply(String s) { try { return DataManager.savedPotions.get(UUID.fromString(s)); } catch(Exception ignored) {} return null; } }); } public CInventory getInventory() { if(Util.getInventory(inventory) == null) inventory = Util.createEmptyInventory().getId(); return Util.getInventory(inventory); } public CEnderInventory getEnderInventory() { if(Util.getEnderInventory(enderInventory) == null) enderInventory = Util.createEnderInventory(this).getId(); return Util.getEnderInventory(enderInventory); } public Meta getMeta() { return Util.loadMeta(meta); } public OfflinePlayer getOfflinePlayer() { return Bukkit.getOfflinePlayer(getPlayerName()); } public String getName() { return name; } public boolean isActive() { return active; } public Location getLocation() { if(location == null) return null; return CLocations.load(location).toLocation(); } public Location getBedSpawn() { if(bedSpawn == null) return null; return CLocations.load(bedSpawn).toLocation(); } public GameMode getGameMode() { return gameMode; } public Location getCurrentLocation() { if(getOfflinePlayer().isOnline()) return getOfflinePlayer().getPlayer().getLocation(); return getLocation(); } @Override public DCharacter getRelatedCharacter() { return this; } @Override public LivingEntity getEntity() { return getOfflinePlayer().getPlayer(); } public String getMojangAccount() { return mojangAccount; } public String getPlayerName() { return DPlayer.Util.getPlayer(mojangAccount).getPlayerName(); } public Integer getLevel() { return level; } public boolean isAlive() { return alive; } public Double getHealth() { return health; } public Double getMaxHealth() { return getDeity().getMaxHealth(); } public Integer getHunger() { return hunger; } public Float getExperience() { return experience; } public boolean isDeity(String deityName) { return getDeity().getName().equalsIgnoreCase(deityName); } public Deity getDeity() { return Deity.Util.getDeity(this.deity); } public Collection<Deity> getMinorDeities() { return Collections2.transform(minorDeities, new Function<String, Deity>() { @Override public Deity apply(String deity) { return Deity.Util.getDeity(deity); } }); } public Alliance getAlliance() { return getDeity().getAlliance(); } public int getKillCount() { return killCount; } public void setKillCount(int amount) { killCount = amount; Util.save(this); } public void addKill() { killCount += 1; Util.save(this); } public int getDeathCount() { return deaths.size(); } public void addDeath() { if(deaths == null) deaths = Sets.newHashSet(); deaths.add(new DDeath(this).getId().toString()); Util.save(this); } public void addDeath(DCharacter attacker) { deaths.add(new DDeath(this, attacker).getId().toString()); Util.save(this); } public Collection<DDeath> getDeaths() { if(deaths == null) deaths = Sets.newHashSet(); return Collections2.transform(deaths, new Function<String, DDeath>() { @Override public DDeath apply(String s) { try { return DDeath.Util.load(UUID.fromString(s)); } catch(Exception ignored) {} return null; } }); } public Collection<StructureData> getOwnedStructures() { return StructureData.Util.findAll(new Predicate<StructureData>() { @Override public boolean apply(StructureData data) { return data.getOwner().equals(getId()); } }); } public Collection<StructureData> getOwnedStructures(final String type) { return StructureData.Util.findAll(new Predicate<StructureData>() { @Override public boolean apply(StructureData data) { return data.getTypeName().equals(type) && data.getOwner().equals(getId()); } }); } public int getFavorRegen() { int favorRegenSkill = getMeta().getSkill(Skill.Type.FAVOR_REGEN) != null ? 4 * getMeta().getSkill(Skill.Type.FAVOR_REGEN).getLevel() : 0; int regenRate = (int) Math.ceil(Configs.getSettingDouble("multipliers.favor") * (getDeity().getFavorRegen() + favorRegenSkill)); if(regenRate < 30) regenRate = 30; return regenRate; } public void setCanPvp(boolean pvp) { DPlayer.Util.getPlayer(getOfflinePlayer()).setCanPvp(pvp); } @Override public boolean canPvp() { return DPlayer.Util.getPlayer(getMojangAccount()).canPvp(); } public boolean isUsable() { return usable; } public void updateUseable() { usable = Deity.Util.getDeity(this.deity) != null && Deity.Util.getDeity(this.deity).getFlags().contains(Deity.Flag.PLAYABLE); } public UUID getId() { return id; } public Collection<DPet> getPets() { return DPet.Util.findByOwner(id); } public void remove() { // Define the DPlayer DPlayer dPlayer = DPlayer.Util.getPlayer(getOfflinePlayer()); // Switch the player to mortal if(getOfflinePlayer().isOnline() && dPlayer.getCurrent().getName().equalsIgnoreCase(getName())) dPlayer.setToMortal(); // Remove the data if(dPlayer.getCurrent().getName().equalsIgnoreCase(getName())) dPlayer.resetCurrent(); for(StructureData structureSave : Structure.Util.getStructureWithFlag(Structure.Flag.DELETE_WITH_OWNER)) if(structureSave.hasOwner() && structureSave.getOwner().equals(getId())) structureSave.remove(); for(DSavedPotion potion : getRawPotionEffects()) DataManager.savedPotions.remove(potion.getId()); Util.deleteInventory(getInventory().getId()); Util.deleteEnderInventory(getEnderInventory().getId()); Util.deleteMeta(getMeta().getId()); Util.delete(getId()); } public void sendAllianceMessage(String message) { DemigodsChatEvent chatEvent = new DemigodsChatEvent(message, DCharacter.Util.getOnlineCharactersWithAlliance(getAlliance())); Bukkit.getPluginManager().callEvent(chatEvent); if(!chatEvent.isCancelled()) for(Player player : chatEvent.getRecipients()) player.sendMessage(message); } public void chatWithAlliance(String message) { sendAllianceMessage(" " + ChatColor.GRAY + getAlliance() + "s " + ChatColor.DARK_GRAY + "" + Symbol.BLACK_FLAG + " " + getDeity().getColor() + name + ChatColor.GRAY + ": " + ChatColor.RESET + message); Messages.info("[" + getAlliance() + "]" + name + ": " + message); } public void applyToPlayer(final Player player) { // Define variables DPlayer playerSave = DPlayer.Util.getPlayer(player); // Set character to active setActive(true); if(playerSave.getMortalInventory() != null) { playerSave.setMortalName(player.getDisplayName()); playerSave.setMortalListName(player.getPlayerListName()); } // Update their inventory if(playerSave.getCharacters().size() == 1) saveInventory(); else player.getEnderChest().clear(); getInventory().setToPlayer(player); getEnderInventory().setToPlayer(player); // Update health, experience, and name player.setDisplayName(getDeity().getColor() + getName()); player.setPlayerListName(getDeity().getColor() + getName()); player.setMaxHealth(getMaxHealth()); player.setHealth(getHealth() >= getMaxHealth() ? getMaxHealth() : getHealth()); player.setFoodLevel(getHunger()); player.setExp(getExperience()); player.setLevel(getLevel()); for(PotionEffect potion : player.getActivePotionEffects()) player.removePotionEffect(potion.getType()); if(getPotionEffects() != null) player.addPotionEffects(getPotionEffects()); Bukkit.getScheduler().scheduleSyncDelayedTask(Demigods.PLUGIN, new BukkitRunnable() { @Override public void run() { if(getBedSpawn() != null) player.setBedSpawnLocation(getBedSpawn()); } }, 1); if(gameMode != null) player.setGameMode(gameMode); // Set player display name player.setDisplayName(getDeity().getColor() + getName()); player.setPlayerListName(getDeity().getColor() + getName()); // Re-own pets DPet.Util.reownPets(player, this); // Add to their team Demigods.BOARD.getTeam(getAlliance().getName()).removePlayer(getOfflinePlayer()); } public static class Inventory extends CInventory { public Inventory() { super(); } public Inventory(UUID id, ConfigurationSection conf) { super(id, conf); } protected CItemStack create(ItemStack itemStack) { return CItemStacks.create(itemStack); } protected CItemStack load(UUID itemStack) { return CItemStacks.load(itemStack); } protected void delete() { DataManager.inventories.remove(getId()); } } public static class EnderInventory extends CEnderInventory { public EnderInventory() { super(); } public EnderInventory(UUID id, ConfigurationSection conf) { super(id, conf); } protected CItemStack create(ItemStack itemStack) { return CItemStacks.create(itemStack); } protected CItemStack load(UUID itemStack) { return CItemStacks.load(itemStack); } protected void delete() { DataManager.enderInventories.remove(this.getId()); } } public static class Meta implements ConfigurationSerializable { private UUID id; private UUID character; private int favor; private int maxFavor; private int skillPoints; private Set<String> notifications; private Map<String, Object> binds; private Map<String, Object> skillData; private Map<String, Object> warps; private Map<String, Object> invites; public Meta() {} public Meta(UUID id, ConfigurationSection conf) { this.id = id; favor = conf.getInt("favor"); maxFavor = conf.getInt("maxFavor"); skillPoints = conf.getInt("skillPoints"); notifications = Sets.newHashSet(conf.getStringList("notifications")); character = UUID.fromString(conf.getString("character")); if(conf.getConfigurationSection("skillData") != null) skillData = conf.getConfigurationSection("skillData").getValues(false); if(conf.getConfigurationSection("binds") != null) binds = conf.getConfigurationSection("binds").getValues(false); if(conf.getConfigurationSection("warps") != null) warps = conf.getConfigurationSection("warps").getValues(false); if(conf.getConfigurationSection("invites") != null) invites = conf.getConfigurationSection("invites").getValues(false); } @Override public Map<String, Object> serialize() { Map<String, Object> map = Maps.newHashMap(); map.put("character", character.toString()); map.put("favor", favor); map.put("maxFavor", maxFavor); map.put("skillPoints", skillPoints); map.put("notifications", Lists.newArrayList(notifications)); map.put("binds", binds); map.put("skillData", skillData); map.put("warps", warps); map.put("invites", invites); return map; } public void generateId() { id = UUID.randomUUID(); } void setCharacter(DCharacter character) { this.character = character.getId(); } void initialize() { notifications = Sets.newHashSet(); warps = Maps.newHashMap(); invites = Maps.newHashMap(); skillData = Maps.newHashMap(); binds = Maps.newHashMap(); } public UUID getId() { return id; } public DCharacter getCharacter() { return DCharacter.Util.load(character); } public void setSkillPoints(int skillPoints) { this.skillPoints = skillPoints; } public int getSkillPoints() { return skillPoints; } public void addSkillPoints(int skillPoints) { setSkillPoints(getSkillPoints() + skillPoints); } public void subtractSkillPoints(int skillPoints) { setSkillPoints(getSkillPoints() - skillPoints); } public void addNotification(Notification notification) { getNotifications().add(notification.getId().toString()); Util.saveMeta(this); } public void removeNotification(Notification notification) { getNotifications().remove(notification.getId().toString()); Util.saveMeta(this); } public Set<String> getNotifications() { if(this.notifications == null) this.notifications = Sets.newHashSet(); return this.notifications; } public void clearNotifications() { notifications.clear(); } public boolean hasNotifications() { return !notifications.isEmpty(); } public void addWarp(String name, Location location) { warps.put(name.toLowerCase(), CLocations.create(location).getId().toString()); Util.saveMeta(this); } public void removeWarp(String name) { getWarps().remove(name.toLowerCase()); Util.saveMeta(this); } public Map<String, Object> getWarps() { if(this.warps == null) this.warps = Maps.newHashMap(); return this.warps; } public void clearWarps() { getWarps().clear(); } public boolean hasWarps() { return !this.warps.isEmpty(); } public void addInvite(String name, Location location) { getInvites().put(name.toLowerCase(), CLocations.create(location).getId().toString()); Util.saveMeta(this); } public void removeInvite(String name) { getInvites().remove(name.toLowerCase()); Util.saveMeta(this); } public Map<String, Object> getInvites() { if(this.invites == null) this.invites = Maps.newHashMap(); return this.invites; } public void clearInvites() { invites.clear(); } public boolean hasInvites() { return !this.invites.isEmpty(); } public void resetSkills() { getRawSkills().clear(); for(Skill.Type type : Skill.Type.values()) if(type.isDefault()) addSkill(Skill.Util.createSkill(getCharacter(), type)); } public void cleanSkills() { List<String> toRemove = Lists.newArrayList(); // Locate obselete skills for(String skillName : getRawSkills().keySet()) { try { // Attempt to find the value of the skillname Skill.Type.valueOf(skillName.toUpperCase()); } catch(Exception ignored) { // There was an error. Catch it and remove the skill. toRemove.add(skillName); } } // Remove the obsolete skills for(String skillName : toRemove) getRawSkills().remove(skillName); } public void addSkill(Skill skill) { if(!getRawSkills().containsKey(skill.getType().toString())) getRawSkills().put(skill.getType().toString(), skill.getId().toString()); Util.saveMeta(this); } public Skill getSkill(Skill.Type type) { if(getRawSkills().containsKey(type.toString())) return Skill.Util.loadSkill(UUID.fromString(getRawSkills().get(type.toString()).toString())); return null; } public Map<String, Object> getRawSkills() { if(skillData == null) skillData = Maps.newHashMap(); return skillData; } public Collection<Skill> getSkills() { return Collections2.transform(getRawSkills().values(), new Function<Object, Skill>() { @Override public Skill apply(Object obj) { return Skill.Util.loadSkill(UUID.fromString(obj.toString())); } }); } public boolean checkBound(String abilityName, Material material) { return getBinds().containsKey(abilityName) && binds.get(abilityName).equals(material.name()); } public boolean isBound(Ability ability) { return getBinds().containsKey(ability.getName()); } public boolean isBound(Material material) { return getBinds().containsValue(material.name()); } public void setBind(Ability ability, Material material) { getBinds().put(ability.getName(), material.name()); } public Map<String, Object> getBinds() { if(binds == null) binds = Maps.newHashMap(); return this.binds; } public void removeBind(Ability ability) { getBinds().remove(ability.getName()); } public void removeBind(Material material) { if(getBinds().containsValue(material.name())) { String toRemove = null; for(Map.Entry<String, Object> entry : getBinds().entrySet()) { toRemove = entry.getValue().equals(material.name()) ? entry.getKey() : null; } getBinds().remove(toRemove); } } public int getIndividualSkillCap() { int total = 0; for(Skill skill : getSkills()) total += skill.getLevel(); return getOverallSkillCap() - total; } public int getOverallSkillCap() { // This is done this way so it can easily be manipulated later return Configs.getSettingInt("caps.skills"); } public int getAscensions() { if(LEVEL_SEPERATE_SKILLS) { double total = 0.0; for(Skill skill : getSkills()) total += skill.getLevel(); return (int) Math.ceil(total / getSkills().size()); } return (int) Math.ceil(getSkillPoints() / 500); // TODO Balance this. } public Integer getFavor() { return favor; } public void setFavor(int amount) { favor = amount; Util.saveMeta(this); } public void addFavor(int amount) { if((favor + amount) > maxFavor) favor = maxFavor; else favor += amount; Util.saveMeta(this); } public void subtractFavor(int amount) { if((favor - amount) < 0) favor = 0; else favor -= amount; Util.saveMeta(this); } public Integer getMaxFavor() { return maxFavor; } public void addMaxFavor(int amount) { if((maxFavor + amount) > Configs.getSettingInt("caps.favor")) maxFavor = Configs.getSettingInt("caps.favor"); else maxFavor += amount; Util.saveMeta(this); } public void setMaxFavor(int amount) { if(amount < 0) maxFavor = 0; if(amount > Configs.getSettingInt("caps.favor")) maxFavor = Configs.getSettingInt("caps.favor"); else maxFavor = amount; Util.saveMeta(this); } public void subtractMaxFavor(int amount) { setMaxFavor(getMaxFavor() - amount); } } public static class Util { public static void save(DCharacter character) { DataManager.characters.put(character.getId(), character); } public static void saveMeta(Meta meta) { DataManager.characterMetas.put(meta.getId(), meta); } public static void saveInventory(Inventory inventory) { DataManager.inventories.put(inventory.getId(), inventory); } public static void saveInventory(EnderInventory inventory) { DataManager.enderInventories.put(inventory.getId(), inventory); } public static void delete(UUID id) { DataManager.characters.remove(id); } public static void deleteMeta(UUID id) { DataManager.characterMetas.remove(id); } public static void deleteInventory(UUID id) { DataManager.inventories.remove(id); } public static void deleteEnderInventory(UUID id) { DataManager.enderInventories.remove(id); } public static void create(DPlayer player, String chosenDeity, String chosenName, boolean switchCharacter) { // Switch to new character if(switchCharacter) player.switchCharacter(create(player, chosenName, chosenDeity)); } public static DCharacter create(DPlayer player, String charName, String charDeity) { if(getCharacterByName(charName) == null) { // Create the DCharacter return create(player, charName, Deity.Util.getDeity(charDeity)); } return null; } private static DCharacter create(final DPlayer player, final String charName, final Deity deity) { DCharacter character = new DCharacter(); character.generateId(); character.setAlive(true); character.setMojangAccount(player); character.setName(charName); character.setDeity(deity); character.setMinorDeities(new HashSet<String>(0)); character.setUsable(true); character.setHealth(deity.getMaxHealth()); character.setHunger(20); character.setExperience(0); character.setLevel(0); character.setKillCount(0); character.setLocation(player.getOfflinePlayer().getPlayer().getLocation()); character.setMeta(Util.createMeta(character)); save(character); return character; } public static CInventory createInventory(DCharacter character) { PlayerInventory inventory = character.getOfflinePlayer().getPlayer().getInventory(); Inventory charInventory = new Inventory(); charInventory.generateId(); if(inventory.getHelmet() != null) charInventory.setHelmet(inventory.getHelmet()); if(inventory.getChestplate() != null) charInventory.setChestplate(inventory.getChestplate()); if(inventory.getLeggings() != null) charInventory.setLeggings(inventory.getLeggings()); if(inventory.getBoots() != null) charInventory.setBoots(inventory.getBoots()); charInventory.setItems(inventory); saveInventory(charInventory); return charInventory; } public static CInventory createEmptyInventory() { Inventory charInventory = new Inventory(); charInventory.generateId(); charInventory.setHelmet(new ItemStack(Material.AIR)); charInventory.setChestplate(new ItemStack(Material.AIR)); charInventory.setLeggings(new ItemStack(Material.AIR)); charInventory.setBoots(new ItemStack(Material.AIR)); saveInventory(charInventory); return charInventory; } public static CEnderInventory createEnderInventory(DCharacter character) { org.bukkit.inventory.Inventory inventory = character.getOfflinePlayer().getPlayer().getEnderChest(); EnderInventory enderInventory = new EnderInventory(); enderInventory.generateId(); enderInventory.setItems(inventory); saveInventory(enderInventory); return enderInventory; } public static CEnderInventory createEmptyEnderInventory() { EnderInventory enderInventory = new EnderInventory(); enderInventory.generateId(); saveInventory(enderInventory); return enderInventory; } public static Meta createMeta(DCharacter character) { Meta charMeta = new Meta(); charMeta.initialize(); charMeta.setCharacter(character); charMeta.generateId(); charMeta.setFavor(Configs.getSettingInt("character.defaults.favor")); charMeta.setMaxFavor(Configs.getSettingInt("character.defaults.max_favor")); charMeta.resetSkills(); saveMeta(charMeta); return charMeta; } public static Set<DCharacter> loadAll() { return Sets.newHashSet(DataManager.characters.values()); } public static DCharacter load(UUID id) { return DataManager.characters.get(id); } public static Meta loadMeta(UUID id) { return DataManager.characterMetas.get(id); } public static Inventory getInventory(UUID id) { try { return DataManager.inventories.get(id); } catch(Exception ignored) {} return null; } public static EnderInventory getEnderInventory(UUID id) { try { return DataManager.enderInventories.get(id); } catch(Exception ignored) {} return null; } public static DSavedPotion getSavedPotion(UUID id) { try { return DataManager.savedPotions.get(id); } catch(Exception ignored) {} return null; } public static void updateUsableCharacters() { for(DCharacter character : loadAll()) character.updateUseable(); } public static DCharacter getCharacterByName(final String name) { try { return Iterators.find(loadAll().iterator(), new Predicate<DCharacter>() { @Override public boolean apply(DCharacter loaded) { return loaded.getName().equalsIgnoreCase(name); } }); } catch(Exception ignored) {} return null; } public static boolean charExists(String name) { return getCharacterByName(name) != null; } public static boolean isCooledDown(DCharacter player, String ability, boolean sendMsg) { if(DataManager.hasKeyTemp(player.getName(), ability + "_cooldown") && Long.parseLong(DataManager.getValueTemp(player.getName(), ability + "_cooldown").toString()) > System.currentTimeMillis()) { if(sendMsg) player.getOfflinePlayer().getPlayer().sendMessage(ChatColor.RED + ability + " has not cooled down!"); return false; } else return true; } public static void setCoolDown(DCharacter player, String ability, long cooldown) { DataManager.saveTemp(player.getName(), ability + "_cooldown", cooldown); } public static long getCoolDown(DCharacter player, String ability) { return Long.parseLong(DataManager.getValueTemp(player.getName(), ability + "_cooldown").toString()); } public static Set<DCharacter> getAllActive() { return Sets.filter(loadAll(), new Predicate<DCharacter>() { @Override public boolean apply(DCharacter character) { return character.isUsable() && character.isActive(); } }); } public static Set<DCharacter> getAllUsable() { return Sets.filter(loadAll(), new Predicate<DCharacter>() { @Override public boolean apply(DCharacter character) { return character.isUsable(); } }); } /** * Returns true if <code>char1</code> is allied with <code>char2</code> based * on their current alliances. * * @param char1 the first character to check. * @param char2 the second character to check. * @return boolean */ public static boolean areAllied(DCharacter char1, DCharacter char2) { return char1.getAlliance().getName().equalsIgnoreCase(char2.getAlliance().getName()); } public static Collection<DCharacter> getOnlineCharactersWithDeity(final String deity) { return getCharactersWithPredicate(new Predicate<DCharacter>() { @Override public boolean apply(DCharacter character) { return character.isActive() && character.getOfflinePlayer().isOnline() && character.getDeity().getName().equalsIgnoreCase(deity); } }); } public static Collection<DCharacter> getOnlineCharactersWithAbility(final String abilityName) { return getCharactersWithPredicate(new Predicate<DCharacter>() { @Override public boolean apply(DCharacter character) { if(character.isActive() && character.getOfflinePlayer().isOnline()) { for(Ability abilityToCheck : character.getDeity().getAbilities()) if(abilityToCheck.getName().equalsIgnoreCase(abilityName)) return true; } return false; } }); } public static Collection<DCharacter> getOnlineCharactersWithAlliance(final Alliance alliance) { return getCharactersWithPredicate(new Predicate<DCharacter>() { @Override public boolean apply(DCharacter character) { return character.isActive() && character.getOfflinePlayer().isOnline() && character.getAlliance().equals(alliance); } }); } public static Collection<DCharacter> getOnlineCharactersWithoutAlliance(final Alliance alliance) { return getCharactersWithPredicate(new Predicate<DCharacter>() { @Override public boolean apply(DCharacter character) { return character.isActive() && character.getOfflinePlayer().isOnline() && !character.getAlliance().equals(alliance); } }); } public static Collection<DCharacter> getOnlineCharactersBelowAscension(final int ascension) { return getCharactersWithPredicate(new Predicate<DCharacter>() { @Override public boolean apply(DCharacter character) { return character.isActive() && character.getOfflinePlayer().isOnline() && character.getMeta().getAscensions() < ascension; } }); } public static Collection<DCharacter> getOnlineCharacters() { return getCharactersWithPredicate(new Predicate<DCharacter>() { @Override public boolean apply(DCharacter character) { return character.isActive() && character.getOfflinePlayer().isOnline(); } }); } public static Collection<DCharacter> getCharactersWithPredicate(Predicate<DCharacter> predicate) { return Collections2.filter(getAllUsable(), predicate); } /** * Updates favor for all online characters. */ public static void updateFavor() { for(Player player : Bukkit.getOnlinePlayers()) { DCharacter character = DPlayer.Util.getPlayer(player).getCurrent(); if(character != null) character.getMeta().addFavor(character.getFavorRegen()); } } } }
Fixed #164.
Demigods-Engine/src/main/java/com/censoredsoftware/demigods/engine/player/DCharacter.java
Fixed #164.
Java
mit
243a86edb20eec64578fb2daac1c42b028c98d96
0
DemigodsRPG/Demigods3
package com.censoredsoftware.demigods.player; import com.censoredsoftware.demigods.Demigods; import com.censoredsoftware.demigods.ability.Ability; import com.censoredsoftware.demigods.battle.Participant; import com.censoredsoftware.demigods.data.DataManager; import com.censoredsoftware.demigods.deity.Deity; import com.censoredsoftware.demigods.helper.ConfigFile; import com.censoredsoftware.demigods.item.DItemStack; import com.censoredsoftware.demigods.location.DLocation; import com.censoredsoftware.demigods.structure.Structure; import com.censoredsoftware.demigods.util.Structures; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.*; import com.google.common.primitives.Ints; import org.bukkit.*; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.serialization.ConfigurationSerializable; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import java.util.*; import java.util.concurrent.ConcurrentHashMap; public class DCharacter implements Participant, ConfigurationSerializable { private UUID id; private String name; private String player; private double health; private double maxhealth; private Integer hunger; private Float experience; private Integer level; private Integer killCount; private Integer deathCount; private UUID location; private String deity; private Boolean active; private Boolean usable; private UUID meta; private UUID inventory; private Set<String> deaths; public DCharacter() { deaths = Sets.newHashSet(); } public DCharacter(UUID id, ConfigurationSection conf) { this.id = id; name = conf.getString("name"); player = conf.getString("player"); health = conf.getDouble("health"); maxhealth = conf.getDouble("maxhealth"); hunger = conf.getInt("hunger"); experience = Float.valueOf(conf.getString("experience")); level = conf.getInt("level"); killCount = conf.getInt("killCount"); deathCount = conf.getInt("deathCount"); location = UUID.fromString(conf.getString("location")); deity = conf.getString("deity"); active = conf.getBoolean("active"); usable = conf.getBoolean("usable"); meta = UUID.fromString(conf.getString("meta")); if(conf.isString("inventory")) inventory = UUID.fromString(conf.getString("inventory")); if(conf.isList("deaths")) deaths = Sets.newHashSet(conf.getStringList("deaths")); } @Override public Map<String, Object> serialize() { Map<String, Object> map = Maps.newHashMap(); map.put("name", name); map.put("player", player); map.put("health", health); map.put("maxhealth", maxhealth); map.put("hunger", hunger); map.put("experience", experience); map.put("level", level); map.put("killCount", killCount); map.put("deathCount", deathCount); map.put("location", location.toString()); map.put("deity", deity); map.put("active", active); map.put("usable", usable); map.put("meta", meta.toString()); if(inventory != null) map.put("inventory", inventory.toString()); if(deaths != null) map.put("deaths", Lists.newArrayList(deaths)); return map; } void generateId() { id = UUID.randomUUID(); } void setName(String name) { this.name = name; } void setDeity(Deity deity) { this.deity = deity.getName(); } void setPlayer(DPlayer player) { this.player = player.getPlayerName(); } public void setActive(boolean option) { this.active = option; Util.save(this); } public void saveInventory() { this.inventory = Util.createInventory(this).getId(); Util.save(this); } public void setHealth(double health) { this.health = health; } public void setMaxHealth(double maxhealth) { this.maxhealth = maxhealth; } public void setHunger(int hunger) { this.hunger = hunger; } public void setLevel(int level) { this.level = level; } public void setExperience(float exp) { this.experience = exp; } public void setLocation(Location location) { this.location = DLocation.Util.create(location).getId(); } public void setMeta(Meta meta) { this.meta = meta.getId(); } public void setUsable(boolean usable) { this.usable = usable; } public Inventory getInventory() { if(Util.getInventory(this.inventory) == null) this.inventory = Util.createEmptyInventory().getId(); return Util.getInventory(this.inventory); } public Meta getMeta() { return Util.loadMeta(this.meta); } public OfflinePlayer getOfflinePlayer() { return Bukkit.getOfflinePlayer(this.player); } public String getName() { return this.name; } public Boolean isActive() { return this.active; } public Location getLocation() { if(this.location == null) return null; return DLocation.Util.load(this.location).toLocation(); } public Location getCurrentLocation() { if(getOfflinePlayer().isOnline()) return getOfflinePlayer().getPlayer().getLocation(); return getLocation(); } @Override public DCharacter getRelatedCharacter() { return this; } @Override public LivingEntity getEntity() { return getOfflinePlayer().getPlayer(); } public String getPlayer() { return player; } public Integer getLevel() { return this.level; } public Double getHealth() { return this.health; } public Double getMaxHealth() { return this.maxhealth; } public Integer getHunger() { return this.hunger; } public Float getExperience() { return this.experience; } public Boolean isDeity(String deityName) { return getDeity().getName().equalsIgnoreCase(deityName); } public Deity getDeity() { return Deity.Util.getDeity(this.deity); } public String getAlliance() { return getDeity().getAlliance(); } /** * Returns the number of total killCount. * * @return int */ public int getKillCount() { return this.killCount; } /** * Sets the amount of killCount to <code>amount</code>. * * @param amount the amount of killCount to set to. */ public void setKillCount(int amount) { this.killCount = amount; Util.save(this); } /** * Adds 1 kill. */ public void addKill() { this.killCount += 1; Util.save(this); } /** * Returns the number of deathCount. * * @return int */ public int getDeathCount() { return this.deathCount; } /** * Sets the number of deathCount to <code>amount</code>. * * @param amount the amount of deathCount to set. */ public void setDeathCount(int amount) { this.deathCount = amount; Util.save(this); } /** * Adds a death. */ public void addDeath() { this.deathCount += 1; if(deaths == null) deaths = Sets.newHashSet(); deaths.add(new Death(this).getId().toString()); Util.save(this); } /** * Adds a death. */ public void addDeath(DCharacter attacker) { this.deathCount += 1; deaths.add(new Death(this, attacker).getId().toString()); Util.save(this); } public Collection<Death> getDeaths() { if(deaths == null) deaths = Sets.newHashSet(); return Collections2.transform(deaths, new Function<String, Death>() { @Override public Death apply(String s) { try { return Death.Util.load(UUID.fromString(s)); } catch(Exception ignored) {} return null; } }); } @Override public void setCanPvp(boolean pvp) { DPlayer.Util.getPlayer(getOfflinePlayer()).setCanPvp(pvp); } @Override public Boolean canPvp() { return DPlayer.Util.getPlayer(getOfflinePlayer()).canPvp(); } @Override public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } public boolean isUsable() { return this.usable; } public void updateUseable() { this.usable = Deity.Util.getDeity(this.deity) != null; } public void refreshBinds() { if(!getOfflinePlayer().isOnline()) return; for(String stringBind : getMeta().getBinds()) { Player player = getOfflinePlayer().getPlayer(); Ability.Bind bind = Ability.Util.loadBind(UUID.fromString(stringBind)); player.getInventory().setItem(bind.getSlot(), bind.getItem()); } } public UUID getId() { return id; } public void remove() { for(Structure.Save structureSave : Structures.getStructuresSavesWithFlag(Structure.Flag.DELETE_WITH_OWNER)) if(structureSave.hasOwner() && structureSave.getOwner().equals(getId())) structureSave.remove(); Util.deleteInventory(getInventory().getId()); Util.deleteMeta(getMeta().getId()); Util.delete(getId()); DPlayer.Util.getPlayer(getOfflinePlayer()).resetCurrent(); } public static class Inventory implements ConfigurationSerializable { private UUID id; private UUID helmet; private UUID chestplate; private UUID leggings; private UUID boots; private String[] items; public Inventory() {} public Inventory(UUID id, ConfigurationSection conf) { this.id = id; if(conf.getString("helmet") != null) helmet = UUID.fromString(conf.getString("helmet")); if(conf.getString("chestplate") != null) chestplate = UUID.fromString(conf.getString("chestplate")); if(conf.getString("leggins") != null) leggings = UUID.fromString(conf.getString("leggings")); if(conf.getString("boots") != null) boots = UUID.fromString(conf.getString("boots")); if(conf.getStringList("items") != null) { List<String> stringItems = conf.getStringList("items"); items = new String[stringItems.size()]; for(int i = 0; i < stringItems.size(); i++) items[i] = stringItems.get(i); } } @Override public Map<String, Object> serialize() { Map<String, Object> map = Maps.newHashMap(); if(helmet != null) map.put("helmet", helmet.toString()); if(chestplate != null) map.put("chestplate", chestplate.toString()); if(leggings != null) map.put("leggings", leggings.toString()); if(boots != null) map.put("boots", boots.toString()); if(items != null) map.put("items", Lists.newArrayList(items)); return map; } public void generateId() { id = UUID.randomUUID(); } void setHelmet(ItemStack helmet) { this.helmet = DItemStack.Util.create(helmet).getId(); } void setChestplate(ItemStack chestplate) { this.chestplate = DItemStack.Util.create(chestplate).getId(); } void setLeggings(ItemStack leggings) { this.leggings = DItemStack.Util.create(leggings).getId(); } void setBoots(ItemStack boots) { this.boots = DItemStack.Util.create(boots).getId(); } void setItems(org.bukkit.inventory.Inventory inventory) { if(this.items == null) this.items = new String[36]; for(int i = 0; i < 35; i++) { if(inventory.getItem(i) == null) this.items[i] = DItemStack.Util.create(new ItemStack(Material.AIR)).getId().toString(); else this.items[i] = DItemStack.Util.create(inventory.getItem(i)).getId().toString(); } } public UUID getId() { return this.id; } public ItemStack getHelmet() { if(this.helmet == null) return null; DItemStack item = DItemStack.Util.load(this.helmet); if(item != null) return item.toItemStack(); return null; } public ItemStack getChestplate() { if(this.chestplate == null) return null; DItemStack item = DItemStack.Util.load(this.chestplate); if(item != null) return item.toItemStack(); return null; } public ItemStack getLeggings() { if(this.leggings == null) return null; DItemStack item = DItemStack.Util.load(this.leggings); if(item != null) return item.toItemStack(); return null; } public ItemStack getBoots() { if(this.boots == null) return null; DItemStack item = DItemStack.Util.load(this.boots); if(item != null) return item.toItemStack(); return null; } /** * Applies this inventory to the given <code>player</code>. * * @param player the player for whom apply the inventory. */ public void setToPlayer(Player player) { // Define the inventory PlayerInventory inventory = player.getInventory(); // Clear it all first inventory.clear(); inventory.setHelmet(new ItemStack(Material.AIR)); inventory.setChestplate(new ItemStack(Material.AIR)); inventory.setLeggings(new ItemStack(Material.AIR)); inventory.setBoots(new ItemStack(Material.AIR)); // Set the armor contents if(getHelmet() != null) inventory.setHelmet(getHelmet()); if(getChestplate() != null) inventory.setChestplate(getChestplate()); if(getLeggings() != null) inventory.setLeggings(getLeggings()); if(getBoots() != null) inventory.setBoots(getBoots()); if(this.items != null) { // Set items for(int i = 0; i < 35; i++) if(this.items[i] != null) inventory.setItem(i, DItemStack.Util.load(UUID.fromString(this.items[i])).toItemStack()); } // Delete Util.deleteInventory(id); } public static class File extends ConfigFile { private static String SAVE_PATH; private static final String SAVE_FILE = "characterInventories.yml"; public File() { super(Demigods.plugin); SAVE_PATH = Demigods.plugin.getDataFolder() + "/data/"; } @Override public ConcurrentHashMap<UUID, Inventory> loadFromFile() { final FileConfiguration data = getData(SAVE_PATH, SAVE_FILE); ConcurrentHashMap<UUID, Inventory> map = new ConcurrentHashMap<UUID, Inventory>(); for(String stringId : data.getKeys(false)) map.put(UUID.fromString(stringId), new Inventory(UUID.fromString(stringId), data.getConfigurationSection(stringId))); return map; } @Override public boolean saveToFile() { FileConfiguration saveFile = getData(SAVE_PATH, SAVE_FILE); Map<UUID, Inventory> currentFile = loadFromFile(); for(UUID id : DataManager.inventories.keySet()) if(!currentFile.keySet().contains(id) || !currentFile.get(id).equals(DataManager.inventories.get(id))) saveFile.createSection(id.toString(), Util.getInventory(id).serialize()); for(UUID id : currentFile.keySet()) if(!DataManager.inventories.keySet().contains(id)) saveFile.set(id.toString(), null); return saveFile(SAVE_PATH, SAVE_FILE, saveFile); } } } public static class Meta implements ConfigurationSerializable { private UUID id; private Integer ascensions; private Integer favor; private Integer maxFavor; private Set<String> binds; private Set<String> notifications; private Map<String, Object> devotionData; private Map<String, Object> warps; private Map<String, Object> invites; public Meta() {} public Meta(UUID id, ConfigurationSection conf) { this.id = id; ascensions = conf.getInt("ascensions"); favor = conf.getInt("favor"); maxFavor = conf.getInt("maxFavor"); binds = Sets.newHashSet(conf.getStringList("binds")); notifications = Sets.newHashSet(conf.getStringList("notifications")); devotionData = conf.getConfigurationSection("devotionData").getValues(false); warps = conf.getConfigurationSection("warps").getValues(false); invites = conf.getConfigurationSection("invites").getValues(false); } @Override public Map<String, Object> serialize() { Map<String, Object> map = Maps.newHashMap(); map.put("ascensions", ascensions); map.put("favor", favor); map.put("maxFavor", maxFavor); map.put("binds", Lists.newArrayList(binds)); map.put("notifications", Lists.newArrayList(notifications)); map.put("devotionData", devotionData); map.put("warps", warps); map.put("invites", invites); return map; } public void generateId() { id = UUID.randomUUID(); } void initialize() { this.binds = Sets.newHashSet(); this.notifications = Sets.newHashSet(); this.warps = Maps.newHashMap(); this.invites = Maps.newHashMap(); this.devotionData = Maps.newHashMap(); } public UUID getId() { return this.id; } public void addNotification(Notification notification) { getNotifications().add(notification.getId().toString()); Util.saveMeta(this); } public void removeNotification(Notification notification) { getNotifications().remove(notification.getId().toString()); Util.saveMeta(this); } public Set<String> getNotifications() { if(this.notifications == null) this.notifications = Sets.newHashSet(); return this.notifications; } public void clearNotifications() { notifications.clear(); } public boolean hasNotifications() { return !this.notifications.isEmpty(); } public void addWarp(String name, Location location) { warps.put(name.toLowerCase(), DLocation.Util.create(location).getId().toString()); Util.saveMeta(this); } public void removeWarp(String name) { getWarps().remove(name.toLowerCase()); Util.saveMeta(this); } public Map<String, Object> getWarps() { if(this.warps == null) this.warps = Maps.newHashMap(); return this.warps; } public void clearWarps() { getWarps().clear(); } public boolean hasWarps() { return !this.warps.isEmpty(); } public void addInvite(String name, Location location) { getInvites().put(name.toLowerCase(), DLocation.Util.create(location).getId().toString()); Util.saveMeta(this); } public void removeInvite(String name) { getInvites().remove(name.toLowerCase()); Util.saveMeta(this); } public Map<String, Object> getInvites() { if(this.invites == null) this.invites = Maps.newHashMap(); return this.invites; } public void clearInvites() { invites.clear(); } public boolean hasInvites() { return !this.invites.isEmpty(); } public void addDevotion(Ability.Devotion devotion) { if(!this.devotionData.containsKey(devotion.getType().toString())) this.devotionData.put(devotion.getType().toString(), devotion.getId().toString()); Util.saveMeta(this); } public Ability.Devotion getDevotion(Ability.Devotion.Type type) { if(this.devotionData.containsKey(type.toString())) return Ability.Util.loadDevotion(UUID.fromString(this.devotionData.get(type.toString()).toString())); else { addDevotion(Ability.Util.createDevotion(type)); return Ability.Util.loadDevotion(UUID.fromString(this.devotionData.get(type.toString()).toString())); } } public boolean checkBind(String ability, ItemStack item) { return(isBound(item) && getBind(item).getAbility().equalsIgnoreCase(ability)); } public boolean checkBind(String ability, int slot) { return(isBound(slot) && getBind(slot).getAbility().equalsIgnoreCase(ability)); } public boolean isBound(int slot) { return getBind(slot) != null; } public boolean isBound(String ability) { return getBind(ability) != null; } public boolean isBound(ItemStack item) { return getBind(item) != null; } public void addBind(Ability.Bind bind) { this.binds.add(bind.getId().toString()); } public Ability.Bind setBound(String ability, int slot, ItemStack item) { Ability.Bind bind = Ability.Util.createBind(ability, slot, item); this.binds.add(bind.getId().toString()); return bind; } public Ability.Bind getBind(int slot) { for(String bind : this.binds) if(Ability.Util.loadBind(UUID.fromString(bind)).getSlot() == slot) return Ability.Util.loadBind(UUID.fromString(bind)); return null; } public Ability.Bind getBind(String ability) { for(String bind : this.binds) if(Ability.Util.loadBind(UUID.fromString(bind)).getAbility().equalsIgnoreCase(ability)) return Ability.Util.loadBind(UUID.fromString(bind)); return null; } public Ability.Bind getBind(ItemStack item) { for(String bind : this.binds) if(item.hasItemMeta() && item.getItemMeta().hasLore() && item.getItemMeta().getLore().toString().contains(Ability.Util.loadBind(UUID.fromString(bind)).getIdentifier())) return Ability.Util.loadBind(UUID.fromString(bind)); return null; } public Set<String> getBinds() { return this.binds; } public void removeBind(String ability) { if(isBound(ability)) { Ability.Bind bind = getBind(ability); this.binds.remove(bind.getId().toString()); Ability.Util.deleteBind(bind.getId()); } } public void removeBind(ItemStack item) { if(isBound(item)) { Ability.Bind bind = getBind(item); this.binds.remove(bind.getId().toString()); Ability.Util.deleteBind(bind.getId()); } } public void removeBind(Ability.Bind bind) { this.binds.remove(bind.getId().toString()); Ability.Util.deleteBind(bind.getId()); } public Integer getAscensions() { return this.ascensions; } public void addAscension() { this.ascensions += 1; Util.saveMeta(this); } public void addAscensions(int amount) { this.ascensions += amount; Util.saveMeta(this); } public void subtractAscensions(int amount) { this.ascensions -= amount; Util.saveMeta(this); } public void setAscensions(int amount) { this.ascensions = amount; Util.saveMeta(this); } public Integer getFavor() { return this.favor; } public void setFavor(int amount) { this.favor = amount; Util.saveMeta(this); } public void addFavor(int amount) { if((this.favor + amount) > this.maxFavor) this.favor = this.maxFavor; else this.favor += amount; Util.saveMeta(this); } public void subtractFavor(int amount) { if((this.favor - amount) < 0) this.favor = 0; else this.favor -= amount; Util.saveMeta(this); } public Integer getMaxFavor() { return this.maxFavor; } public void addMaxFavor(int amount) { if((this.maxFavor + amount) > Demigods.config.getSettingInt("caps.favor")) this.maxFavor = Demigods.config.getSettingInt("caps.favor"); else this.maxFavor += amount; Util.saveMeta(this); } public void setMaxFavor(int amount) { if(amount < 0) this.maxFavor = 0; if(amount > Demigods.config.getSettingInt("caps.favor")) this.maxFavor = Demigods.config.getSettingInt("caps.favor"); else this.maxFavor = amount; Util.saveMeta(this); } @Override public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } public static class File extends ConfigFile { private static String SAVE_PATH; private static final String SAVE_FILE = "characterMetas.yml"; public File() { super(Demigods.plugin); SAVE_PATH = Demigods.plugin.getDataFolder() + "/data/"; } @Override public ConcurrentHashMap<UUID, Meta> loadFromFile() { final FileConfiguration data = getData(SAVE_PATH, SAVE_FILE); ConcurrentHashMap<UUID, Meta> map = new ConcurrentHashMap<UUID, Meta>(); for(String stringId : data.getKeys(false)) map.put(UUID.fromString(stringId), new Meta(UUID.fromString(stringId), data.getConfigurationSection(stringId))); return map; } @Override public boolean saveToFile() { FileConfiguration saveFile = getData(SAVE_PATH, SAVE_FILE); Map<UUID, Meta> currentFile = loadFromFile(); for(UUID id : DataManager.characterMetas.keySet()) if(!currentFile.keySet().contains(id) || !currentFile.get(id).equals(DataManager.characterMetas.get(id))) saveFile.createSection(id.toString(), Util.loadMeta(id).serialize()); for(UUID id : currentFile.keySet()) if(!DataManager.characterMetas.keySet().contains(id)) saveFile.set(id.toString(), null); return saveFile(SAVE_PATH, SAVE_FILE, saveFile); } } } public static class File extends ConfigFile { private static String SAVE_PATH; private static final String SAVE_FILE = "characters.yml"; public File() { super(Demigods.plugin); SAVE_PATH = Demigods.plugin.getDataFolder() + "/data/"; } @Override public ConcurrentHashMap<UUID, DCharacter> loadFromFile() { final FileConfiguration data = getData(SAVE_PATH, SAVE_FILE); ConcurrentHashMap<UUID, DCharacter> map = new ConcurrentHashMap<UUID, DCharacter>(); for(String stringId : data.getKeys(false)) map.put(UUID.fromString(stringId), new DCharacter(UUID.fromString(stringId), data.getConfigurationSection(stringId))); return map; } @Override public boolean saveToFile() { FileConfiguration saveFile = getData(SAVE_PATH, SAVE_FILE); Map<UUID, DCharacter> currentFile = loadFromFile(); for(UUID id : DataManager.characters.keySet()) if(!currentFile.keySet().contains(id) || !currentFile.get(id).equals(DataManager.characters.get(id))) saveFile.createSection(id.toString(), Util.load(id).serialize()); for(UUID id : currentFile.keySet()) if(!DataManager.characters.keySet().contains(id)) saveFile.set(id.toString(), null); return saveFile(SAVE_PATH, SAVE_FILE, saveFile); } } public static class Util { public static void save(DCharacter character) { DataManager.characters.put(character.getId(), character); } public static void saveMeta(Meta meta) { DataManager.characterMetas.put(meta.getId(), meta); } public static void saveInventory(Inventory inventory) { DataManager.inventories.put(inventory.getId(), inventory); } public static void delete(UUID id) { DataManager.characters.remove(id); } public static void deleteMeta(UUID id) { DataManager.characterMetas.remove(id); } public static void deleteInventory(UUID id) { DataManager.inventories.remove(id); } public static void create(DPlayer player, String chosenDeity, String chosenName, boolean switchCharacter) { // Switch to new character if(switchCharacter) player.switchCharacter(create(player, chosenName, chosenDeity)); } public static DCharacter create(DPlayer player, String charName, String charDeity) { if(getCharacterByName(charName) == null) { // Create the Character return create(player, charName, Deity.Util.getDeity(charDeity), true); } return null; } private static DCharacter create(final DPlayer player, final String charName, final Deity deity, final boolean immortal) { DCharacter character = new DCharacter(); character.generateId(); character.setPlayer(player); character.setName(charName); character.setDeity(deity); character.setUsable(true); character.setMaxHealth(40.0); character.setHealth(40.0); character.setHunger(20); character.setExperience(0); character.setLevel(0); character.setKillCount(0); character.setDeathCount(0); character.setLocation(player.getOfflinePlayer().getPlayer().getLocation()); character.setMeta(Util.createMeta()); save(character); return character; } public static Inventory createInventory(DCharacter character) { PlayerInventory inventory = character.getOfflinePlayer().getPlayer().getInventory(); Inventory charInventory = new Inventory(); charInventory.generateId(); if(inventory.getHelmet() != null) charInventory.setHelmet(inventory.getHelmet()); if(inventory.getChestplate() != null) charInventory.setChestplate(inventory.getChestplate()); if(inventory.getLeggings() != null) charInventory.setLeggings(inventory.getLeggings()); if(inventory.getBoots() != null) charInventory.setBoots(inventory.getBoots()); charInventory.setItems(inventory); saveInventory(charInventory); return charInventory; } public static Inventory createEmptyInventory() { Inventory charInventory = new Inventory(); charInventory.generateId(); charInventory.setHelmet(new ItemStack(Material.AIR)); charInventory.setChestplate(new ItemStack(Material.AIR)); charInventory.setLeggings(new ItemStack(Material.AIR)); charInventory.setBoots(new ItemStack(Material.AIR)); saveInventory(charInventory); return charInventory; } public static Meta createMeta() { Meta charMeta = new Meta(); charMeta.initialize(); charMeta.generateId(); charMeta.setAscensions(Demigods.config.getSettingInt("character.defaults.ascensions")); charMeta.setFavor(Demigods.config.getSettingInt("character.defaults.favor")); charMeta.setMaxFavor(Demigods.config.getSettingInt("character.defaults.max_favor")); charMeta.addDevotion(Ability.Util.createDevotion(Ability.Devotion.Type.OFFENSE)); charMeta.addDevotion(Ability.Util.createDevotion(Ability.Devotion.Type.DEFENSE)); charMeta.addDevotion(Ability.Util.createDevotion(Ability.Devotion.Type.PASSIVE)); charMeta.addDevotion(Ability.Util.createDevotion(Ability.Devotion.Type.STEALTH)); charMeta.addDevotion(Ability.Util.createDevotion(Ability.Devotion.Type.SUPPORT)); charMeta.addDevotion(Ability.Util.createDevotion(Ability.Devotion.Type.ULTIMATE)); saveMeta(charMeta); return charMeta; } public static Set<DCharacter> loadAll() { return Sets.newHashSet(DataManager.characters.values()); } public static DCharacter load(UUID id) { return DataManager.characters.get(id); } public static Meta loadMeta(UUID id) { return DataManager.characterMetas.get(id); } public static Inventory getInventory(UUID id) { try { return DataManager.inventories.get(id); } catch(Exception ignored) {} return null; } public static void updateUsableCharacters() { for(DCharacter character : loadAll()) character.updateUseable(); } public static DCharacter getCharacterByName(final String name) { try { Iterators.find(loadAll().iterator(), new Predicate<DCharacter>() { @Override public boolean apply(DCharacter loaded) { return loaded.getName().equalsIgnoreCase(name); } }); } catch(NoSuchElementException ignored) {} return null; } public static boolean charExists(String name) { return getCharacterByName(name) != null; } public static boolean isCooledDown(DCharacter player, String ability, boolean sendMsg) { if(DataManager.hasKeyTemp(player.getName(), ability + "_cooldown") && Long.parseLong(DataManager.getValueTemp(player.getName(), ability + "_cooldown").toString()) > System.currentTimeMillis()) { if(sendMsg) player.getOfflinePlayer().getPlayer().sendMessage(ChatColor.RED + ability + " has not cooled down!"); return false; } else return true; } public static void setCoolDown(DCharacter player, String ability, long cooldown) { DataManager.saveTemp(player.getName(), ability + "_cooldown", cooldown); } public static long getCoolDown(DCharacter player, String ability) { return Long.parseLong(DataManager.getValueTemp(player.getName(), ability + "_cooldown").toString()); } public static Set<DCharacter> getAllActive() { return Sets.filter(loadAll(), new Predicate<DCharacter>() { @Override public boolean apply(DCharacter character) { return character.isActive(); } }); } /** * Returns true if <code>char1</code> is allied with <code>char2</code> based * on their current alliances. * * @param char1 the first character to check. * @param char2 the second character to check. * @return boolean */ public static boolean areAllied(DCharacter char1, DCharacter char2) { return char1.getAlliance().equalsIgnoreCase(char2.getAlliance()); } public static Collection<DCharacter> getOnlineCharactersWithDeity(final String deity) { return getCharactersWithPredicate(new Predicate<DCharacter>() { @Override public boolean apply(DCharacter character) { return character.isActive() && character.getOfflinePlayer().isOnline() && character.getDeity().getName().equalsIgnoreCase(deity); } }); } public static Collection<DCharacter> getOnlineCharactersWithAlliance(final String alliance) { return getCharactersWithPredicate(new Predicate<DCharacter>() { @Override public boolean apply(DCharacter character) { return character.isActive() && character.getOfflinePlayer().isOnline() && character.getAlliance().equalsIgnoreCase(alliance); } }); } public static Collection<DCharacter> getOnlineCharactersBelowAscension(final int ascention) { return getCharactersWithPredicate(new Predicate<DCharacter>() { @Override public boolean apply(DCharacter character) { return character.isActive() && character.getOfflinePlayer().isOnline() && character.getMeta().getAscensions() < ascention; } }); } public static Collection<DCharacter> getOnlineCharacters() { return getCharactersWithPredicate(new Predicate<DCharacter>() { @Override public boolean apply(DCharacter character) { return character.isActive() && character.getOfflinePlayer().isOnline(); } }); } public static Collection<DCharacter> getCharactersWithPredicate(Predicate<DCharacter> predicate) { return Collections2.filter(loadAll(), predicate); } public static int getMedianOverallOnlineAscension() { return median(Ints.toArray(Collections2.transform(getOnlineCharacters(), new Function<DCharacter, Integer>() { @Override public Integer apply(DCharacter character) { return character.getMeta().getAscensions(); } }))); } public static int getMedianOverallAscension() { return median(Ints.toArray(Collections2.transform(loadAll(), new Function<DCharacter, Integer>() { @Override public Integer apply(DCharacter character) { return character.getMeta().getAscensions(); } }))); } private static int median(int[] i) { if(i == null || i.length < 3) return 1; Arrays.sort(i); int middle = i.length / 2; if(i.length % 2 == 0) return (i[middle - 1] + i[middle]) / 2; else return i[middle]; } } }
src/main/java/com/censoredsoftware/demigods/player/DCharacter.java
package com.censoredsoftware.demigods.player; import com.censoredsoftware.demigods.Demigods; import com.censoredsoftware.demigods.ability.Ability; import com.censoredsoftware.demigods.battle.Participant; import com.censoredsoftware.demigods.data.DataManager; import com.censoredsoftware.demigods.deity.Deity; import com.censoredsoftware.demigods.helper.ConfigFile; import com.censoredsoftware.demigods.item.DItemStack; import com.censoredsoftware.demigods.location.DLocation; import com.censoredsoftware.demigods.structure.Structure; import com.censoredsoftware.demigods.util.Structures; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.*; import com.google.common.primitives.Ints; import org.bukkit.*; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.serialization.ConfigurationSerializable; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import java.util.*; import java.util.concurrent.ConcurrentHashMap; public class DCharacter implements Participant, ConfigurationSerializable { private UUID id; private String name; private String player; private double health; private double maxhealth; private Integer hunger; private Float experience; private Integer level; private Integer killCount; private Integer deathCount; private UUID location; private String deity; private Boolean active; private Boolean usable; private UUID meta; private UUID inventory; private Set<String> deaths; public DCharacter() { deaths = Sets.newHashSet(); } public DCharacter(UUID id, ConfigurationSection conf) { this.id = id; name = conf.getString("name"); player = conf.getString("player"); health = conf.getDouble("health"); maxhealth = conf.getDouble("maxhealth"); hunger = conf.getInt("hunger"); experience = Float.valueOf(conf.getString("experience")); level = conf.getInt("level"); killCount = conf.getInt("killCount"); deathCount = conf.getInt("deathCount"); location = UUID.fromString(conf.getString("location")); deity = conf.getString("deity"); active = conf.getBoolean("active"); usable = conf.getBoolean("usable"); meta = UUID.fromString(conf.getString("meta")); if(conf.isString("inventory")) inventory = UUID.fromString(conf.getString("inventory")); if(conf.isList("deaths")) deaths = Sets.newHashSet(conf.getStringList("deaths")); } @Override public Map<String, Object> serialize() { Map<String, Object> map = Maps.newHashMap(); map.put("name", name); map.put("player", player); map.put("health", health); map.put("maxhealth", maxhealth); map.put("hunger", hunger); map.put("experience", experience); map.put("level", level); map.put("killCount", killCount); map.put("deathCount", deathCount); map.put("location", location.toString()); map.put("deity", deity); map.put("active", active); map.put("usable", usable); map.put("meta", meta.toString()); if(inventory != null) map.put("inventory", inventory.toString()); if(deaths != null) map.put("deaths", Lists.newArrayList(deaths)); return map; } void generateId() { id = UUID.randomUUID(); } void setName(String name) { this.name = name; } void setDeity(Deity deity) { this.deity = deity.getName(); } void setPlayer(DPlayer player) { this.player = player.getPlayerName(); } public void setActive(boolean option) { this.active = option; Util.save(this); } public void saveInventory() { this.inventory = Util.createInventory(this).getId(); Util.save(this); } public void setHealth(double health) { this.health = health; } public void setMaxHealth(double maxhealth) { this.maxhealth = maxhealth; } public void setHunger(int hunger) { this.hunger = hunger; } public void setLevel(int level) { this.level = level; } public void setExperience(float exp) { this.experience = exp; } public void setLocation(Location location) { this.location = DLocation.Util.create(location).getId(); } public void setMeta(Meta meta) { this.meta = meta.getId(); } public void setUsable(boolean usable) { this.usable = usable; } public Inventory getInventory() { if(Util.getInventory(this.inventory) == null) this.inventory = Util.createEmptyInventory().getId(); return Util.getInventory(this.inventory); } public Meta getMeta() { return Util.loadMeta(this.meta); } public OfflinePlayer getOfflinePlayer() { return Bukkit.getOfflinePlayer(this.player); } public String getName() { return this.name; } public Boolean isActive() { return this.active; } public Location getLocation() { if(this.location == null) return null; return DLocation.Util.load(this.location).toLocation(); } public Location getCurrentLocation() { if(getOfflinePlayer().isOnline()) return getOfflinePlayer().getPlayer().getLocation(); return getLocation(); } @Override public DCharacter getRelatedCharacter() { return this; } @Override public LivingEntity getEntity() { return getOfflinePlayer().getPlayer(); } public String getPlayer() { return player; } public Integer getLevel() { return this.level; } public Double getHealth() { return this.health; } public Double getMaxHealth() { return this.maxhealth; } public Integer getHunger() { return this.hunger; } public Float getExperience() { return this.experience; } public Boolean isDeity(String deityName) { return getDeity().getName().equalsIgnoreCase(deityName); } public Deity getDeity() { return Deity.Util.getDeity(this.deity); } public String getAlliance() { return getDeity().getAlliance(); } /** * Returns the number of total killCount. * * @return int */ public int getKillCount() { return this.killCount; } /** * Sets the amount of killCount to <code>amount</code>. * * @param amount the amount of killCount to set to. */ public void setKillCount(int amount) { this.killCount = amount; Util.save(this); } /** * Adds 1 kill. */ public void addKill() { this.killCount += 1; Util.save(this); } /** * Returns the number of deathCount. * * @return int */ public int getDeathCount() { return this.deathCount; } /** * Sets the number of deathCount to <code>amount</code>. * * @param amount the amount of deathCount to set. */ public void setDeathCount(int amount) { this.deathCount = amount; Util.save(this); } /** * Adds a death. */ public void addDeath() { this.deathCount += 1; if(deaths == null) deaths = Sets.newHashSet(); deaths.add(new Death(this).getId().toString()); Util.save(this); } /** * Adds a death. */ public void addDeath(DCharacter attacker) { this.deathCount += 1; deaths.add(new Death(this, attacker).getId().toString()); Util.save(this); } public Collection<Death> getDeaths() { if(deaths == null) deaths = Sets.newHashSet(); return Collections2.transform(deaths, new Function<String, Death>() { @Override public Death apply(String s) { try { return Death.Util.load(UUID.fromString(s)); } catch(Exception ignored) {} return null; } }); } @Override public void setCanPvp(boolean pvp) { DPlayer.Util.getPlayer(getOfflinePlayer()).setCanPvp(pvp); } @Override public Boolean canPvp() { return DPlayer.Util.getPlayer(getOfflinePlayer()).canPvp(); } @Override public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } public boolean isUsable() { return this.usable; } public void updateUseable() { this.usable = Deity.Util.getDeity(this.deity) != null; } public void refreshBinds() { if(!getOfflinePlayer().isOnline()) return; for(String stringBind : getMeta().getBinds()) { Player player = getOfflinePlayer().getPlayer(); Ability.Bind bind = Ability.Util.loadBind(UUID.fromString(stringBind)); player.getInventory().setItem(bind.getSlot(), bind.getItem()); } } public UUID getId() { return id; } public void remove() { for(Structure.Save structureSave : Structures.getStructuresSavesWithFlag(Structure.Flag.DELETE_WITH_OWNER)) if(structureSave.hasOwner() && structureSave.getOwner().equals(getId())) structureSave.remove(); Util.deleteInventory(getInventory().getId()); Util.deleteMeta(getMeta().getId()); Util.delete(getId()); DPlayer.Util.getPlayer(getOfflinePlayer()).resetCurrent(); } public static class Inventory implements ConfigurationSerializable { private UUID id; private UUID helmet; private UUID chestplate; private UUID leggings; private UUID boots; private String[] items; public Inventory() {} public Inventory(UUID id, ConfigurationSection conf) { this.id = id; if(conf.getString("helmet") != null) helmet = UUID.fromString(conf.getString("helmet")); if(conf.getString("chestplate") != null) chestplate = UUID.fromString(conf.getString("chestplate")); if(conf.getString("leggins") != null) leggings = UUID.fromString(conf.getString("leggings")); if(conf.getString("boots") != null) boots = UUID.fromString(conf.getString("boots")); if(conf.getStringList("items") != null) { List<String> stringItems = conf.getStringList("items"); items = new String[stringItems.size()]; for(int i = 0; i < stringItems.size(); i++) items[i] = stringItems.get(i); } } @Override public Map<String, Object> serialize() { Map<String, Object> map = Maps.newHashMap(); if(helmet != null) map.put("helmet", helmet.toString()); if(chestplate != null) map.put("chestplate", chestplate.toString()); if(leggings != null) map.put("leggings", leggings.toString()); if(boots != null) map.put("boots", boots.toString()); if(items != null) map.put("items", Lists.newArrayList(items)); return map; } public void generateId() { id = UUID.randomUUID(); } void setHelmet(ItemStack helmet) { this.helmet = DItemStack.Util.create(helmet).getId(); } void setChestplate(ItemStack chestplate) { this.chestplate = DItemStack.Util.create(chestplate).getId(); } void setLeggings(ItemStack leggings) { this.leggings = DItemStack.Util.create(leggings).getId(); } void setBoots(ItemStack boots) { this.boots = DItemStack.Util.create(boots).getId(); } void setItems(org.bukkit.inventory.Inventory inventory) { if(this.items == null) this.items = new String[36]; for(int i = 0; i < 35; i++) { if(inventory.getItem(i) == null) this.items[i] = DItemStack.Util.create(new ItemStack(Material.AIR)).getId().toString(); else this.items[i] = DItemStack.Util.create(inventory.getItem(i)).getId().toString(); } } public UUID getId() { return this.id; } public ItemStack getHelmet() { if(this.helmet == null) return null; DItemStack item = DItemStack.Util.load(this.helmet); if(item != null) return item.toItemStack(); return null; } public ItemStack getChestplate() { if(this.chestplate == null) return null; DItemStack item = DItemStack.Util.load(this.chestplate); if(item != null) return item.toItemStack(); return null; } public ItemStack getLeggings() { if(this.leggings == null) return null; DItemStack item = DItemStack.Util.load(this.leggings); if(item != null) return item.toItemStack(); return null; } public ItemStack getBoots() { if(this.boots == null) return null; DItemStack item = DItemStack.Util.load(this.boots); if(item != null) return item.toItemStack(); return null; } /** * Applies this inventory to the given <code>player</code>. * * @param player the player for whom apply the inventory. */ public void setToPlayer(Player player) { // Define the inventory PlayerInventory inventory = player.getInventory(); // Clear it all first inventory.clear(); inventory.setHelmet(new ItemStack(Material.AIR)); inventory.setChestplate(new ItemStack(Material.AIR)); inventory.setLeggings(new ItemStack(Material.AIR)); inventory.setBoots(new ItemStack(Material.AIR)); // Set the armor contents if(getHelmet() != null) inventory.setHelmet(getHelmet()); if(getChestplate() != null) inventory.setChestplate(getChestplate()); if(getLeggings() != null) inventory.setLeggings(getLeggings()); if(getBoots() != null) inventory.setBoots(getBoots()); if(this.items != null) { // Set items for(int i = 0; i < 35; i++) if(this.items[i] != null) inventory.setItem(i, DItemStack.Util.load(UUID.fromString(this.items[i])).toItemStack()); } // Delete Util.deleteInventory(id); } public static class File extends ConfigFile { private static String SAVE_PATH; private static final String SAVE_FILE = "characterInventories.yml"; public File() { super(Demigods.plugin); SAVE_PATH = Demigods.plugin.getDataFolder() + "/data/"; } @Override public ConcurrentHashMap<UUID, Inventory> loadFromFile() { final FileConfiguration data = getData(SAVE_PATH, SAVE_FILE); ConcurrentHashMap<UUID, Inventory> map = new ConcurrentHashMap<UUID, Inventory>(); for(String stringId : data.getKeys(false)) map.put(UUID.fromString(stringId), new Inventory(UUID.fromString(stringId), data.getConfigurationSection(stringId))); return map; } @Override public boolean saveToFile() { FileConfiguration saveFile = getData(SAVE_PATH, SAVE_FILE); Map<UUID, Inventory> currentFile = loadFromFile(); for(UUID id : DataManager.inventories.keySet()) if(!currentFile.keySet().contains(id) || !currentFile.get(id).equals(DataManager.inventories.get(id))) saveFile.createSection(id.toString(), Util.getInventory(id).serialize()); for(UUID id : currentFile.keySet()) if(!DataManager.inventories.keySet().contains(id)) saveFile.set(id.toString(), null); return saveFile(SAVE_PATH, SAVE_FILE, saveFile); } } } public static class Meta implements ConfigurationSerializable { private UUID id; private Integer ascensions; private Integer favor; private Integer maxFavor; private Set<String> binds; private Set<String> notifications; private Map<String, Object> devotionData; private Map<String, Object> warps; private Map<String, Object> invites; public Meta() {} public Meta(UUID id, ConfigurationSection conf) { this.id = id; ascensions = conf.getInt("ascensions"); favor = conf.getInt("favor"); maxFavor = conf.getInt("maxFavor"); binds = Sets.newHashSet(conf.getStringList("binds")); notifications = Sets.newHashSet(conf.getStringList("notifications")); devotionData = conf.getConfigurationSection("devotionData").getValues(false); warps = conf.getConfigurationSection("warps").getValues(false); invites = conf.getConfigurationSection("invites").getValues(false); } @Override public Map<String, Object> serialize() { Map<String, Object> map = Maps.newHashMap(); map.put("ascensions", ascensions); map.put("favor", favor); map.put("maxFavor", maxFavor); map.put("binds", Lists.newArrayList(binds)); map.put("notifications", Lists.newArrayList(notifications)); map.put("devotionData", devotionData); map.put("warps", warps); map.put("invites", invites); return map; } public void generateId() { id = UUID.randomUUID(); } void initialize() { this.binds = Sets.newHashSet(); this.notifications = Sets.newHashSet(); this.warps = Maps.newHashMap(); this.invites = Maps.newHashMap(); this.devotionData = Maps.newHashMap(); } public UUID getId() { return this.id; } public void addNotification(Notification notification) { getNotifications().add(notification.getId().toString()); Util.saveMeta(this); } public void removeNotification(Notification notification) { getNotifications().remove(notification.getId().toString()); Util.saveMeta(this); } public Set<String> getNotifications() { if(this.notifications == null) this.notifications = Sets.newHashSet(); return this.notifications; } public void clearNotifications() { notifications.clear(); } public boolean hasNotifications() { return !this.notifications.isEmpty(); } public void addWarp(String name, Location location) { warps.put(name.toLowerCase(), DLocation.Util.create(location).getId().toString()); Util.saveMeta(this); } public void removeWarp(String name) { getWarps().remove(name.toLowerCase()); Util.saveMeta(this); } public Map<String, Object> getWarps() { if(this.warps == null) this.warps = Maps.newHashMap(); return this.warps; } public void clearWarps() { getWarps().clear(); } public boolean hasWarps() { return !this.warps.isEmpty(); } public void addInvite(String name, Location location) { getInvites().put(name.toLowerCase(), DLocation.Util.create(location).getId().toString()); Util.saveMeta(this); } public void removeInvite(String name) { getInvites().remove(name.toLowerCase()); Util.saveMeta(this); } public Map<String, Object> getInvites() { if(this.invites == null) this.invites = Maps.newHashMap(); return this.invites; } public void clearInvites() { invites.clear(); } public boolean hasInvites() { return !this.invites.isEmpty(); } public void addDevotion(Ability.Devotion devotion) { if(!this.devotionData.containsKey(devotion.getType().toString())) this.devotionData.put(devotion.getType().toString(), devotion.getId().toString()); Util.saveMeta(this); } public Ability.Devotion getDevotion(Ability.Devotion.Type type) { if(this.devotionData.containsKey(type.toString())) return Ability.Util.loadDevotion(UUID.fromString(this.devotionData.get(type.toString()).toString())); else { addDevotion(Ability.Util.createDevotion(type)); return Ability.Util.loadDevotion(UUID.fromString(this.devotionData.get(type.toString()).toString())); } } public boolean checkBind(String ability, ItemStack item) { return(isBound(item) && getBind(item).getAbility().equalsIgnoreCase(ability)); } public boolean checkBind(String ability, int slot) { return(isBound(slot) && getBind(slot).getAbility().equalsIgnoreCase(ability)); } public boolean isBound(int slot) { return getBind(slot) != null; } public boolean isBound(String ability) { return getBind(ability) != null; } public boolean isBound(ItemStack item) { return getBind(item) != null; } public void addBind(Ability.Bind bind) { this.binds.add(bind.getId().toString()); } public Ability.Bind setBound(String ability, int slot, ItemStack item) { Ability.Bind bind = Ability.Util.createBind(ability, slot, item); this.binds.add(bind.getId().toString()); return bind; } public Ability.Bind getBind(int slot) { for(String bind : this.binds) if(Ability.Util.loadBind(UUID.fromString(bind)).getSlot() == slot) return Ability.Util.loadBind(UUID.fromString(bind)); return null; } public Ability.Bind getBind(String ability) { for(String bind : this.binds) if(Ability.Util.loadBind(UUID.fromString(bind)).getAbility().equalsIgnoreCase(ability)) return Ability.Util.loadBind(UUID.fromString(bind)); return null; } public Ability.Bind getBind(ItemStack item) { for(String bind : this.binds) if(item.hasItemMeta() && item.getItemMeta().hasLore() && item.getItemMeta().getLore().toString().contains(Ability.Util.loadBind(UUID.fromString(bind)).getIdentifier())) return Ability.Util.loadBind(UUID.fromString(bind)); return null; } public Set<String> getBinds() { return this.binds; } public void removeBind(String ability) { if(isBound(ability)) { Ability.Bind bind = getBind(ability); this.binds.remove(bind.getId().toString()); Ability.Util.deleteBind(bind.getId()); } } public void removeBind(ItemStack item) { if(isBound(item)) { Ability.Bind bind = getBind(item); this.binds.remove(bind.getId().toString()); Ability.Util.deleteBind(bind.getId()); } } public void removeBind(Ability.Bind bind) { this.binds.remove(bind.getId().toString()); Ability.Util.deleteBind(bind.getId()); } public Integer getAscensions() { return this.ascensions; } public void addAscension() { this.ascensions += 1; Util.saveMeta(this); } public void addAscensions(int amount) { this.ascensions += amount; Util.saveMeta(this); } public void subtractAscensions(int amount) { this.ascensions -= amount; Util.saveMeta(this); } public void setAscensions(int amount) { this.ascensions = amount; Util.saveMeta(this); } public Integer getFavor() { return this.favor; } public void setFavor(int amount) { this.favor = amount; Util.saveMeta(this); } public void addFavor(int amount) { if((this.favor + amount) > this.maxFavor) this.favor = this.maxFavor; else this.favor += amount; Util.saveMeta(this); } public void subtractFavor(int amount) { if((this.favor - amount) < 0) this.favor = 0; else this.favor -= amount; Util.saveMeta(this); } public Integer getMaxFavor() { return this.maxFavor; } public void addMaxFavor(int amount) { if((this.maxFavor + amount) > Demigods.config.getSettingInt("caps.favor")) this.maxFavor = Demigods.config.getSettingInt("caps.favor"); else this.maxFavor += amount; Util.saveMeta(this); } public void setMaxFavor(int amount) { if(amount < 0) this.maxFavor = 0; if(amount > Demigods.config.getSettingInt("caps.favor")) this.maxFavor = Demigods.config.getSettingInt("caps.favor"); else this.maxFavor = amount; Util.saveMeta(this); } @Override public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } public static class File extends ConfigFile { private static String SAVE_PATH; private static final String SAVE_FILE = "characterMetas.yml"; public File() { super(Demigods.plugin); SAVE_PATH = Demigods.plugin.getDataFolder() + "/data/"; } @Override public ConcurrentHashMap<UUID, Meta> loadFromFile() { final FileConfiguration data = getData(SAVE_PATH, SAVE_FILE); ConcurrentHashMap<UUID, Meta> map = new ConcurrentHashMap<UUID, Meta>(); for(String stringId : data.getKeys(false)) map.put(UUID.fromString(stringId), new Meta(UUID.fromString(stringId), data.getConfigurationSection(stringId))); return map; } @Override public boolean saveToFile() { FileConfiguration saveFile = getData(SAVE_PATH, SAVE_FILE); Map<UUID, Meta> currentFile = loadFromFile(); for(UUID id : DataManager.characterMetas.keySet()) if(!currentFile.keySet().contains(id) || !currentFile.get(id).equals(DataManager.characterMetas.get(id))) saveFile.createSection(id.toString(), Util.loadMeta(id).serialize()); for(UUID id : currentFile.keySet()) if(!DataManager.characterMetas.keySet().contains(id)) saveFile.set(id.toString(), null); return saveFile(SAVE_PATH, SAVE_FILE, saveFile); } } } public static class File extends ConfigFile { private static String SAVE_PATH; private static final String SAVE_FILE = "characters.yml"; public File() { super(Demigods.plugin); SAVE_PATH = Demigods.plugin.getDataFolder() + "/data/"; } @Override public ConcurrentHashMap<UUID, DCharacter> loadFromFile() { final FileConfiguration data = getData(SAVE_PATH, SAVE_FILE); ConcurrentHashMap<UUID, DCharacter> map = new ConcurrentHashMap<UUID, DCharacter>(); for(String stringId : data.getKeys(false)) map.put(UUID.fromString(stringId), new DCharacter(UUID.fromString(stringId), data.getConfigurationSection(stringId))); return map; } @Override public boolean saveToFile() { FileConfiguration saveFile = getData(SAVE_PATH, SAVE_FILE); Map<UUID, DCharacter> currentFile = loadFromFile(); for(UUID id : DataManager.characters.keySet()) if(!currentFile.keySet().contains(id) || !currentFile.get(id).equals(DataManager.characters.get(id))) saveFile.createSection(id.toString(), Util.load(id).serialize()); for(UUID id : currentFile.keySet()) if(!DataManager.characters.keySet().contains(id)) saveFile.set(id.toString(), null); return saveFile(SAVE_PATH, SAVE_FILE, saveFile); } } public static class Util { public static void save(DCharacter character) { DataManager.characters.put(character.getId(), character); } public static void saveMeta(Meta meta) { DataManager.characterMetas.put(meta.getId(), meta); } public static void saveInventory(Inventory inventory) { DataManager.inventories.put(inventory.getId(), inventory); } public static void delete(UUID id) { DataManager.characters.remove(id); } public static void deleteMeta(UUID id) { DataManager.characterMetas.remove(id); } public static void deleteInventory(UUID id) { DataManager.inventories.remove(id); } public static void create(DPlayer player, String chosenDeity, String chosenName, boolean switchCharacter) { // Switch to new character if(switchCharacter) player.switchCharacter(create(player, chosenName, chosenDeity)); } public static DCharacter create(DPlayer player, String charName, String charDeity) { if(getCharacterByName(charName) == null) { // Create the Character return create(player, charName, Deity.Util.getDeity(charDeity), true); } return null; } private static DCharacter create(final DPlayer player, final String charName, final Deity deity, final boolean immortal) { DCharacter character = new DCharacter(); character.generateId(); character.setPlayer(player); character.setName(charName); character.setDeity(deity); character.setUsable(true); character.setMaxHealth(40.0); character.setHealth(40.0); character.setHunger(20); character.setExperience(0); character.setLevel(0); character.setKillCount(0); character.setDeathCount(0); character.setLocation(player.getOfflinePlayer().getPlayer().getLocation()); character.setMeta(Util.createMeta()); save(character); return character; } public static Inventory createInventory(DCharacter character) { PlayerInventory inventory = character.getOfflinePlayer().getPlayer().getInventory(); Inventory charInventory = new Inventory(); charInventory.generateId(); if(inventory.getHelmet() != null) charInventory.setHelmet(inventory.getHelmet()); if(inventory.getChestplate() != null) charInventory.setChestplate(inventory.getChestplate()); if(inventory.getLeggings() != null) charInventory.setLeggings(inventory.getLeggings()); if(inventory.getBoots() != null) charInventory.setBoots(inventory.getBoots()); charInventory.setItems(inventory); saveInventory(charInventory); return charInventory; } public static Inventory createEmptyInventory() { Inventory charInventory = new Inventory(); charInventory.generateId(); charInventory.setHelmet(new ItemStack(Material.AIR)); charInventory.setChestplate(new ItemStack(Material.AIR)); charInventory.setLeggings(new ItemStack(Material.AIR)); charInventory.setBoots(new ItemStack(Material.AIR)); saveInventory(charInventory); return charInventory; } public static Meta createMeta() { Meta charMeta = new Meta(); charMeta.initialize(); charMeta.generateId(); charMeta.setAscensions(Demigods.config.getSettingInt("character.defaults.ascensions")); charMeta.setFavor(Demigods.config.getSettingInt("character.defaults.favor")); charMeta.setMaxFavor(Demigods.config.getSettingInt("character.defaults.max_favor")); charMeta.addDevotion(Ability.Util.createDevotion(Ability.Devotion.Type.OFFENSE)); charMeta.addDevotion(Ability.Util.createDevotion(Ability.Devotion.Type.DEFENSE)); charMeta.addDevotion(Ability.Util.createDevotion(Ability.Devotion.Type.PASSIVE)); charMeta.addDevotion(Ability.Util.createDevotion(Ability.Devotion.Type.STEALTH)); charMeta.addDevotion(Ability.Util.createDevotion(Ability.Devotion.Type.SUPPORT)); charMeta.addDevotion(Ability.Util.createDevotion(Ability.Devotion.Type.ULTIMATE)); saveMeta(charMeta); return charMeta; } public static Set<DCharacter> loadAll() { return Sets.newHashSet(DataManager.characters.values()); } public static DCharacter load(UUID id) { return DataManager.characters.get(id); } public static Meta loadMeta(UUID id) { return DataManager.characterMetas.get(id); } public static Inventory getInventory(UUID id) { try { return DataManager.inventories.get(id); } catch(Exception ignored) {} return null; } public static void updateUsableCharacters() { for(DCharacter character : loadAll()) character.updateUseable(); } public static DCharacter getCharacterByName(final String name) { try { Iterators.find(loadAll().iterator(), new Predicate<DCharacter>() { @Override public boolean apply(DCharacter loaded) { return loaded.getName().equalsIgnoreCase(name); } }); } catch(NoSuchElementException ignored) {} return null; } public static boolean charExists(String name) { return getCharacterByName(name) != null; } public static boolean isCooledDown(DCharacter player, String ability, boolean sendMsg) { if(DataManager.hasKeyTemp(player.getName(), ability + "_cooldown") && Long.parseLong(DataManager.getValueTemp(player.getName(), ability + "_cooldown").toString()) > System.currentTimeMillis()) { if(sendMsg) player.getOfflinePlayer().getPlayer().sendMessage(ChatColor.RED + ability + " has not cooled down!"); return false; } else return true; } public static void setCoolDown(DCharacter player, String ability, long cooldown) { DataManager.saveTemp(player.getName(), ability + "_cooldown", cooldown); } public static long getCoolDown(DCharacter player, String ability) { return Long.parseLong(DataManager.getValueTemp(player.getName(), ability + "_cooldown").toString()); } public static Set<DCharacter> getAllActive() { return Sets.filter(loadAll(), new Predicate<DCharacter>() { @Override public boolean apply(DCharacter character) { return character.isActive(); } }); } /** * Returns true if <code>char1</code> is allied with <code>char2</code> based * on their current alliances. * * @param char1 the first character to check. * @param char2 the second character to check. * @return boolean */ public static boolean areAllied(DCharacter char1, DCharacter char2) { return char1.getAlliance().equalsIgnoreCase(char2.getAlliance()); } public static Collection<DCharacter> getOnlineCharactersWithDeity(final String deity) { return getCharactersWithPredicate(new Predicate<DCharacter>() { @Override public boolean apply(DCharacter character) { return character.isActive() && character.getOfflinePlayer().isOnline() && character.getDeity().getName().equalsIgnoreCase(deity); } }); } public static Collection<DCharacter> getOnlineCharactersWithAlliance(final String alliance) { return getCharactersWithPredicate(new Predicate<DCharacter>() { @Override public boolean apply(DCharacter character) { return character.isActive() && character.getOfflinePlayer().isOnline() && character.getAlliance().equalsIgnoreCase(alliance); } }); } public static Collection<DCharacter> getOnlineCharactersBelowAscension(final int ascention) { return getCharactersWithPredicate(new Predicate<DCharacter>() { @Override public boolean apply(DCharacter character) { return character.isActive() && character.getOfflinePlayer().isOnline() && character.getMeta().getAscensions() < ascention; } }); } public static Collection<DCharacter> getOnlineCharacters() { return getCharactersWithPredicate(new Predicate<DCharacter>() { @Override public boolean apply(DCharacter character) { return character.isActive() && character.getOfflinePlayer().isOnline(); } }); } public static Collection<DCharacter> getCharactersWithPredicate(Predicate<DCharacter> predicate) { return Collections2.filter(loadAll(), predicate); } public static int getMedianOverallOnlineAscension() { return median(Ints.toArray(Collections2.transform(getOnlineCharacters(), new Function<DCharacter, Integer>() { @Override public Integer apply(DCharacter character) { return character.getMeta().getAscensions(); } }))); } public static int getMedianOverallAscension() { return median(Ints.toArray(Collections2.transform(loadAll(), new Function<DCharacter, Integer>() { @Override public Integer apply(DCharacter character) { return character.getMeta().getAscensions(); } }))); } private static int median(int[] i) { if(i.length < 3) return 1; Arrays.sort(i); int middle = i.length / 2; if(i.length % 2 == 0) return (i[middle - 1] + i[middle]) / 2; else return i[middle]; } } }
Additional fix.
src/main/java/com/censoredsoftware/demigods/player/DCharacter.java
Additional fix.
Java
mit
9215d14ac6adf960a3cde594c4714848f2180749
0
Midd-Rides/MiddRides-Android
package com.middleendien.middrides.utils; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceFragment; import android.support.design.widget.Snackbar; import android.util.Log; import android.widget.Button; import android.widget.Toast; import com.middleendien.middrides.MainScreen; import com.middleendien.middrides.R; import com.parse.GetCallback; import com.parse.ParseObject; import com.parse.ParseQuery; import com.parse.ParseUser; import java.text.ParseException; public class SettingsFragment extends PreferenceFragment { private Preference cancelRequestButton; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); cancelRequestButton = findPreference(getString(R.string.cancelRequest_button)); if((boolean)ParseUser.getCurrentUser().get(MainScreen.PENDING_USER_REQUEST_PARSE_KEY) == true){ cancelRequestButton.setEnabled(true); }else{ cancelRequestButton.setEnabled(false); } cancelRequestButton.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { ParseQuery<ParseObject> query = ParseQuery.getQuery(MainScreen.USER_REQUESTS_PARSE_OBJECT); query.getInBackground((String)ParseUser.getCurrentUser().get(MainScreen.PENDING_USER_REQUESTID_PARSE_KEY), new GetCallback<ParseObject>() { @Override public void done(ParseObject requestToDelete, com.parse.ParseException e) { if(e == null){ //Delete pending requests and set peding requests to false requestToDelete.deleteInBackground(); ParseUser.getCurrentUser().put(MainScreen.PENDING_USER_REQUEST_PARSE_KEY, false); ParseUser.getCurrentUser().saveInBackground(); Toast.makeText(getActivity(), "Your current request has been cancelled", Toast.LENGTH_SHORT).show(); cancelRequestButton.setEnabled(false); } else { Toast.makeText(getActivity(),"Something went wrong",Toast.LENGTH_SHORT).show(); } } }); return true; } }); } @Override public void onResume(){ super.onResume(); if((boolean)ParseUser.getCurrentUser().get(MainScreen.PENDING_USER_REQUEST_PARSE_KEY) == true){ cancelRequestButton.setEnabled(true); }else{ cancelRequestButton.setEnabled(false); } } }
app/src/main/java/com/middleendien/middrides/utils/SettingsFragment.java
package com.middleendien.middrides.utils; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceFragment; import android.support.design.widget.Snackbar; import android.util.Log; import android.widget.Button; import android.widget.Toast; import com.middleendien.middrides.MainScreen; import com.middleendien.middrides.R; import com.parse.GetCallback; import com.parse.ParseObject; import com.parse.ParseQuery; import com.parse.ParseUser; import java.text.ParseException; public class SettingsFragment extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); final Preference cancelRequestButton = findPreference(getString(R.string.cancelRequest_button)); if((boolean)ParseUser.getCurrentUser().get(MainScreen.PENDING_USER_REQUEST_PARSE_KEY) == true){ cancelRequestButton.setEnabled(true); }else{ cancelRequestButton.setEnabled(false); } cancelRequestButton.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { ParseQuery<ParseObject> query = ParseQuery.getQuery(MainScreen.USER_REQUESTS_PARSE_OBJECT); query.getInBackground((String)ParseUser.getCurrentUser().get(MainScreen.PENDING_USER_REQUESTID_PARSE_KEY), new GetCallback<ParseObject>() { @Override public void done(ParseObject requestToDelete, com.parse.ParseException e) { if(e == null){ //Delete pending requests and set peding requests to false requestToDelete.deleteInBackground(); ParseUser.getCurrentUser().put(MainScreen.PENDING_USER_REQUEST_PARSE_KEY, false); ParseUser.getCurrentUser().saveInBackground(); Toast.makeText(getActivity(), "Your current request has been cancelled", Toast.LENGTH_SHORT).show(); cancelRequestButton.setEnabled(false); } else { Toast.makeText(getActivity(),"Something went wrong",Toast.LENGTH_SHORT).show(); } } }); return true; } }); } }
Minor bug fixes
app/src/main/java/com/middleendien/middrides/utils/SettingsFragment.java
Minor bug fixes