id
int64
22
34.9k
comment_id
int64
0
328
comment
stringlengths
2
2.55k
code
stringlengths
31
107k
classification
stringclasses
6 values
isFinished
bool
1 class
code_context_2
stringlengths
21
27.3k
code_context_10
stringlengths
29
27.3k
code_context_20
stringlengths
29
27.3k
9,670
8
// Set the top block of the column to be the same type // (this could otherwise go wrong with rounding)
public int applyLayers(int[] data) { checkNotNull(data); BlockVector3 minY = region.getMinimumPoint(); int originX = minY.getBlockX(); int originZ = minY.getBlockZ(); int maxY = region.getMaximumPoint().getBlockY(); BlockState fillerAir = BlockTypes.AIR.getDefaultState(); int blocksChanged = 0; BlockStateHolder<BlockState> tmpBlock = BlockTypes.AIR.getDefaultState(); int maxY4 = maxY << 4; int index = 0; // Apply heightmap for (int z = 0; z < height; ++z) { int zr = z + originZ; for (int x = 0; x < width; ++x) { if (this.invalid != null && this.invalid[index]) { continue; } int curHeight = this.data[index]; //Clamp newHeight within the selection area int newHeight = Math.min(maxY4, data[index++]); int curBlock = (curHeight) >> 4; int newBlock = (newHeight + 15) >> 4; // Offset x,z to be 'real' coordinates int xr = x + originX; // Depending on growing or shrinking we need to start at the bottom or top if (newHeight > curHeight) { // Set the top block of the column to be the same type (this might go wrong with rounding) BlockStateHolder<BlockState> existing = session.getBlock(xr, curBlock, zr); // Skip water/lava if (existing.getBlockType().getMaterial().isMovementBlocker()) { // Grow -- start from 1 below top replacing airblocks for (int setY = newBlock - 1, getY = curBlock; setY >= curBlock; --setY, getY--) { BlockStateHolder<BlockState> get = session.getBlock(xr, getY, zr); if (get != BlockTypes.AIR.getDefaultState()) { tmpBlock = get; } session.setBlock(xr, setY, zr, tmpBlock); ++blocksChanged; } int setData = newHeight & 15; if (setData != 0) { existing = PropertyGroup.LEVEL.set(existing, setData - 1); session.setBlock(xr, newBlock, zr, existing); ++blocksChanged; } else { existing = PropertyGroup.LEVEL.set(existing, 15); session.setBlock(xr, newBlock, zr, existing); ++blocksChanged; } } } else if (curHeight > newHeight) { // Fill rest with air for (int y = newBlock + 1; y <= ((curHeight + 15) >> 4); ++y) { session.setBlock(xr, y, zr, fillerAir); ++blocksChanged; } // Set the top block of the column to be the same type // (this could otherwise go wrong with rounding) int setData = newHeight & 15; BlockStateHolder<BlockState> existing = session.getBlock(xr, curBlock, zr); if (setData != 0) { existing = PropertyGroup.LEVEL.set(existing, setData - 1); session.setBlock(xr, newBlock, zr, existing); } else { existing = PropertyGroup.LEVEL.set(existing, 15); session.setBlock(xr, newBlock, zr, existing); } ++blocksChanged; } } } return blocksChanged; }
IMPLEMENTATION
true
// Depending on growing or shrinking we need to start at the bottom or top if (newHeight > curHeight) { // Set the top block of the column to be the same type (this might go wrong with rounding) BlockStateHolder<BlockState> existing = session.getBlock(xr, curBlock, zr); // Skip water/lava if (existing.getBlockType().getMaterial().isMovementBlocker()) {
} int curHeight = this.data[index]; //Clamp newHeight within the selection area int newHeight = Math.min(maxY4, data[index++]); int curBlock = (curHeight) >> 4; int newBlock = (newHeight + 15) >> 4; // Offset x,z to be 'real' coordinates int xr = x + originX; // Depending on growing or shrinking we need to start at the bottom or top if (newHeight > curHeight) { // Set the top block of the column to be the same type (this might go wrong with rounding) BlockStateHolder<BlockState> existing = session.getBlock(xr, curBlock, zr); // Skip water/lava if (existing.getBlockType().getMaterial().isMovementBlocker()) { // Grow -- start from 1 below top replacing airblocks for (int setY = newBlock - 1, getY = curBlock; setY >= curBlock; --setY, getY--) { BlockStateHolder<BlockState> get = session.getBlock(xr, getY, zr); if (get != BlockTypes.AIR.getDefaultState()) { tmpBlock = get; } session.setBlock(xr, setY, zr, tmpBlock); ++blocksChanged;
int blocksChanged = 0; BlockStateHolder<BlockState> tmpBlock = BlockTypes.AIR.getDefaultState(); int maxY4 = maxY << 4; int index = 0; // Apply heightmap for (int z = 0; z < height; ++z) { int zr = z + originZ; for (int x = 0; x < width; ++x) { if (this.invalid != null && this.invalid[index]) { continue; } int curHeight = this.data[index]; //Clamp newHeight within the selection area int newHeight = Math.min(maxY4, data[index++]); int curBlock = (curHeight) >> 4; int newBlock = (newHeight + 15) >> 4; // Offset x,z to be 'real' coordinates int xr = x + originX; // Depending on growing or shrinking we need to start at the bottom or top if (newHeight > curHeight) { // Set the top block of the column to be the same type (this might go wrong with rounding) BlockStateHolder<BlockState> existing = session.getBlock(xr, curBlock, zr); // Skip water/lava if (existing.getBlockType().getMaterial().isMovementBlocker()) { // Grow -- start from 1 below top replacing airblocks for (int setY = newBlock - 1, getY = curBlock; setY >= curBlock; --setY, getY--) { BlockStateHolder<BlockState> get = session.getBlock(xr, getY, zr); if (get != BlockTypes.AIR.getDefaultState()) { tmpBlock = get; } session.setBlock(xr, setY, zr, tmpBlock); ++blocksChanged; } int setData = newHeight & 15; if (setData != 0) { existing = PropertyGroup.LEVEL.set(existing, setData - 1); session.setBlock(xr, newBlock, zr, existing); ++blocksChanged; } else { existing = PropertyGroup.LEVEL.set(existing, 15); session.setBlock(xr, newBlock, zr, existing); ++blocksChanged;
9,671
0
/** * Apply a raw heightmap to the region. * * @param data the data * @return number of blocks affected * @throws MaxChangedBlocksException if the maximum block change limit is exceeded */
public int apply(int[] data) throws MaxChangedBlocksException { checkNotNull(data); BlockVector3 minY = region.getMinimumPoint(); int originX = minY.getBlockX(); int originY = minY.getBlockY(); int originZ = minY.getBlockZ(); int maxY = region.getMaximumPoint().getBlockY(); BlockState fillerAir = BlockTypes.AIR.getDefaultState(); int blocksChanged = 0; BlockState tmpBlock = BlockTypes.AIR.getDefaultState(); // Apply heightmap int index = 0; for (int z = 0; z < height; ++z) { int zr = z + originZ; for (int x = 0; x < width; ++x, index++) { if (this.invalid != null && this.invalid[index]) { continue; } int curHeight = this.data[index]; // Clamp newHeight within the selection area int newHeight = Math.min(maxY, data[index]); // Offset x,z to be 'real' coordinates int xr = x + originX; // Depending on growing or shrinking we need to start at the bottom or top if (newHeight > curHeight) { // Set the top block of the column to be the same type (this might go wrong with rounding) BlockState existing = session.getBlock(xr, curHeight, zr); // Skip water/lava if (existing.getBlockType().getMaterial().isMovementBlocker()) { int y0 = newHeight - 1; for (int setY = y0, getY = curHeight - 1; setY >= curHeight; setY--, getY--) { BlockState get; if (getY >= 0 && getY < 256) { get = session.getBlock(xr, getY, zr); } else { get = BlockTypes.AIR.getDefaultState(); } if (get != BlockTypes.AIR.getDefaultState()) { tmpBlock = get; } session.setBlock(xr, setY, zr, tmpBlock); ++blocksChanged; } session.setBlock(xr, newHeight, zr, existing); ++blocksChanged; } } else if (curHeight > newHeight) { // Set the top block of the column to be the same type // (this could otherwise go wrong with rounding) session.setBlock(xr, newHeight, zr, session.getBlock(xr, curHeight, zr)); ++blocksChanged; // Fill rest with air for (int y = newHeight + 1; y <= curHeight; ++y) { session.setBlock(xr, y, zr, fillerAir); ++blocksChanged; } } } } // Drop trees to the floor -- TODO return blocksChanged; }
NONSATD
true
public int apply(int[] data) throws MaxChangedBlocksException { checkNotNull(data); BlockVector3 minY = region.getMinimumPoint(); int originX = minY.getBlockX(); int originY = minY.getBlockY(); int originZ = minY.getBlockZ(); int maxY = region.getMaximumPoint().getBlockY(); BlockState fillerAir = BlockTypes.AIR.getDefaultState(); int blocksChanged = 0; BlockState tmpBlock = BlockTypes.AIR.getDefaultState(); // Apply heightmap int index = 0; for (int z = 0; z < height; ++z) { int zr = z + originZ; for (int x = 0; x < width; ++x, index++) { if (this.invalid != null && this.invalid[index]) { continue; } int curHeight = this.data[index]; // Clamp newHeight within the selection area int newHeight = Math.min(maxY, data[index]); // Offset x,z to be 'real' coordinates int xr = x + originX; // Depending on growing or shrinking we need to start at the bottom or top if (newHeight > curHeight) { // Set the top block of the column to be the same type (this might go wrong with rounding) BlockState existing = session.getBlock(xr, curHeight, zr); // Skip water/lava if (existing.getBlockType().getMaterial().isMovementBlocker()) { int y0 = newHeight - 1; for (int setY = y0, getY = curHeight - 1; setY >= curHeight; setY--, getY--) { BlockState get; if (getY >= 0 && getY < 256) { get = session.getBlock(xr, getY, zr); } else { get = BlockTypes.AIR.getDefaultState(); } if (get != BlockTypes.AIR.getDefaultState()) { tmpBlock = get; } session.setBlock(xr, setY, zr, tmpBlock); ++blocksChanged; } session.setBlock(xr, newHeight, zr, existing); ++blocksChanged; } } else if (curHeight > newHeight) { // Set the top block of the column to be the same type // (this could otherwise go wrong with rounding) session.setBlock(xr, newHeight, zr, session.getBlock(xr, curHeight, zr)); ++blocksChanged; // Fill rest with air for (int y = newHeight + 1; y <= curHeight; ++y) { session.setBlock(xr, y, zr, fillerAir); ++blocksChanged; } } } } // Drop trees to the floor -- TODO return blocksChanged; }
public int apply(int[] data) throws MaxChangedBlocksException { checkNotNull(data); BlockVector3 minY = region.getMinimumPoint(); int originX = minY.getBlockX(); int originY = minY.getBlockY(); int originZ = minY.getBlockZ(); int maxY = region.getMaximumPoint().getBlockY(); BlockState fillerAir = BlockTypes.AIR.getDefaultState(); int blocksChanged = 0; BlockState tmpBlock = BlockTypes.AIR.getDefaultState(); // Apply heightmap int index = 0; for (int z = 0; z < height; ++z) { int zr = z + originZ; for (int x = 0; x < width; ++x, index++) { if (this.invalid != null && this.invalid[index]) { continue; } int curHeight = this.data[index]; // Clamp newHeight within the selection area int newHeight = Math.min(maxY, data[index]); // Offset x,z to be 'real' coordinates int xr = x + originX; // Depending on growing or shrinking we need to start at the bottom or top if (newHeight > curHeight) { // Set the top block of the column to be the same type (this might go wrong with rounding) BlockState existing = session.getBlock(xr, curHeight, zr); // Skip water/lava if (existing.getBlockType().getMaterial().isMovementBlocker()) { int y0 = newHeight - 1; for (int setY = y0, getY = curHeight - 1; setY >= curHeight; setY--, getY--) { BlockState get; if (getY >= 0 && getY < 256) { get = session.getBlock(xr, getY, zr); } else { get = BlockTypes.AIR.getDefaultState(); } if (get != BlockTypes.AIR.getDefaultState()) { tmpBlock = get; } session.setBlock(xr, setY, zr, tmpBlock); ++blocksChanged; } session.setBlock(xr, newHeight, zr, existing); ++blocksChanged; } } else if (curHeight > newHeight) { // Set the top block of the column to be the same type // (this could otherwise go wrong with rounding) session.setBlock(xr, newHeight, zr, session.getBlock(xr, curHeight, zr)); ++blocksChanged; // Fill rest with air for (int y = newHeight + 1; y <= curHeight; ++y) { session.setBlock(xr, y, zr, fillerAir); ++blocksChanged; } } } } // Drop trees to the floor -- TODO return blocksChanged; }
public int apply(int[] data) throws MaxChangedBlocksException { checkNotNull(data); BlockVector3 minY = region.getMinimumPoint(); int originX = minY.getBlockX(); int originY = minY.getBlockY(); int originZ = minY.getBlockZ(); int maxY = region.getMaximumPoint().getBlockY(); BlockState fillerAir = BlockTypes.AIR.getDefaultState(); int blocksChanged = 0; BlockState tmpBlock = BlockTypes.AIR.getDefaultState(); // Apply heightmap int index = 0; for (int z = 0; z < height; ++z) { int zr = z + originZ; for (int x = 0; x < width; ++x, index++) { if (this.invalid != null && this.invalid[index]) { continue; } int curHeight = this.data[index]; // Clamp newHeight within the selection area int newHeight = Math.min(maxY, data[index]); // Offset x,z to be 'real' coordinates int xr = x + originX; // Depending on growing or shrinking we need to start at the bottom or top if (newHeight > curHeight) { // Set the top block of the column to be the same type (this might go wrong with rounding) BlockState existing = session.getBlock(xr, curHeight, zr); // Skip water/lava if (existing.getBlockType().getMaterial().isMovementBlocker()) { int y0 = newHeight - 1; for (int setY = y0, getY = curHeight - 1; setY >= curHeight; setY--, getY--) { BlockState get; if (getY >= 0 && getY < 256) { get = session.getBlock(xr, getY, zr); } else { get = BlockTypes.AIR.getDefaultState(); } if (get != BlockTypes.AIR.getDefaultState()) { tmpBlock = get; } session.setBlock(xr, setY, zr, tmpBlock); ++blocksChanged; } session.setBlock(xr, newHeight, zr, existing); ++blocksChanged; } } else if (curHeight > newHeight) { // Set the top block of the column to be the same type // (this could otherwise go wrong with rounding) session.setBlock(xr, newHeight, zr, session.getBlock(xr, curHeight, zr)); ++blocksChanged; // Fill rest with air for (int y = newHeight + 1; y <= curHeight; ++y) { session.setBlock(xr, y, zr, fillerAir); ++blocksChanged; } } } } // Drop trees to the floor -- TODO return blocksChanged; }
9,671
1
// Apply heightmap
public int apply(int[] data) throws MaxChangedBlocksException { checkNotNull(data); BlockVector3 minY = region.getMinimumPoint(); int originX = minY.getBlockX(); int originY = minY.getBlockY(); int originZ = minY.getBlockZ(); int maxY = region.getMaximumPoint().getBlockY(); BlockState fillerAir = BlockTypes.AIR.getDefaultState(); int blocksChanged = 0; BlockState tmpBlock = BlockTypes.AIR.getDefaultState(); // Apply heightmap int index = 0; for (int z = 0; z < height; ++z) { int zr = z + originZ; for (int x = 0; x < width; ++x, index++) { if (this.invalid != null && this.invalid[index]) { continue; } int curHeight = this.data[index]; // Clamp newHeight within the selection area int newHeight = Math.min(maxY, data[index]); // Offset x,z to be 'real' coordinates int xr = x + originX; // Depending on growing or shrinking we need to start at the bottom or top if (newHeight > curHeight) { // Set the top block of the column to be the same type (this might go wrong with rounding) BlockState existing = session.getBlock(xr, curHeight, zr); // Skip water/lava if (existing.getBlockType().getMaterial().isMovementBlocker()) { int y0 = newHeight - 1; for (int setY = y0, getY = curHeight - 1; setY >= curHeight; setY--, getY--) { BlockState get; if (getY >= 0 && getY < 256) { get = session.getBlock(xr, getY, zr); } else { get = BlockTypes.AIR.getDefaultState(); } if (get != BlockTypes.AIR.getDefaultState()) { tmpBlock = get; } session.setBlock(xr, setY, zr, tmpBlock); ++blocksChanged; } session.setBlock(xr, newHeight, zr, existing); ++blocksChanged; } } else if (curHeight > newHeight) { // Set the top block of the column to be the same type // (this could otherwise go wrong with rounding) session.setBlock(xr, newHeight, zr, session.getBlock(xr, curHeight, zr)); ++blocksChanged; // Fill rest with air for (int y = newHeight + 1; y <= curHeight; ++y) { session.setBlock(xr, y, zr, fillerAir); ++blocksChanged; } } } } // Drop trees to the floor -- TODO return blocksChanged; }
NONSATD
true
int blocksChanged = 0; BlockState tmpBlock = BlockTypes.AIR.getDefaultState(); // Apply heightmap int index = 0; for (int z = 0; z < height; ++z) {
public int apply(int[] data) throws MaxChangedBlocksException { checkNotNull(data); BlockVector3 minY = region.getMinimumPoint(); int originX = minY.getBlockX(); int originY = minY.getBlockY(); int originZ = minY.getBlockZ(); int maxY = region.getMaximumPoint().getBlockY(); BlockState fillerAir = BlockTypes.AIR.getDefaultState(); int blocksChanged = 0; BlockState tmpBlock = BlockTypes.AIR.getDefaultState(); // Apply heightmap int index = 0; for (int z = 0; z < height; ++z) { int zr = z + originZ; for (int x = 0; x < width; ++x, index++) { if (this.invalid != null && this.invalid[index]) { continue; } int curHeight = this.data[index]; // Clamp newHeight within the selection area int newHeight = Math.min(maxY, data[index]);
public int apply(int[] data) throws MaxChangedBlocksException { checkNotNull(data); BlockVector3 minY = region.getMinimumPoint(); int originX = minY.getBlockX(); int originY = minY.getBlockY(); int originZ = minY.getBlockZ(); int maxY = region.getMaximumPoint().getBlockY(); BlockState fillerAir = BlockTypes.AIR.getDefaultState(); int blocksChanged = 0; BlockState tmpBlock = BlockTypes.AIR.getDefaultState(); // Apply heightmap int index = 0; for (int z = 0; z < height; ++z) { int zr = z + originZ; for (int x = 0; x < width; ++x, index++) { if (this.invalid != null && this.invalid[index]) { continue; } int curHeight = this.data[index]; // Clamp newHeight within the selection area int newHeight = Math.min(maxY, data[index]); // Offset x,z to be 'real' coordinates int xr = x + originX; // Depending on growing or shrinking we need to start at the bottom or top if (newHeight > curHeight) { // Set the top block of the column to be the same type (this might go wrong with rounding) BlockState existing = session.getBlock(xr, curHeight, zr); // Skip water/lava if (existing.getBlockType().getMaterial().isMovementBlocker()) { int y0 = newHeight - 1; for (int setY = y0, getY = curHeight - 1; setY >= curHeight; setY--, getY--) {
9,671
2
// Clamp newHeight within the selection area
public int apply(int[] data) throws MaxChangedBlocksException { checkNotNull(data); BlockVector3 minY = region.getMinimumPoint(); int originX = minY.getBlockX(); int originY = minY.getBlockY(); int originZ = minY.getBlockZ(); int maxY = region.getMaximumPoint().getBlockY(); BlockState fillerAir = BlockTypes.AIR.getDefaultState(); int blocksChanged = 0; BlockState tmpBlock = BlockTypes.AIR.getDefaultState(); // Apply heightmap int index = 0; for (int z = 0; z < height; ++z) { int zr = z + originZ; for (int x = 0; x < width; ++x, index++) { if (this.invalid != null && this.invalid[index]) { continue; } int curHeight = this.data[index]; // Clamp newHeight within the selection area int newHeight = Math.min(maxY, data[index]); // Offset x,z to be 'real' coordinates int xr = x + originX; // Depending on growing or shrinking we need to start at the bottom or top if (newHeight > curHeight) { // Set the top block of the column to be the same type (this might go wrong with rounding) BlockState existing = session.getBlock(xr, curHeight, zr); // Skip water/lava if (existing.getBlockType().getMaterial().isMovementBlocker()) { int y0 = newHeight - 1; for (int setY = y0, getY = curHeight - 1; setY >= curHeight; setY--, getY--) { BlockState get; if (getY >= 0 && getY < 256) { get = session.getBlock(xr, getY, zr); } else { get = BlockTypes.AIR.getDefaultState(); } if (get != BlockTypes.AIR.getDefaultState()) { tmpBlock = get; } session.setBlock(xr, setY, zr, tmpBlock); ++blocksChanged; } session.setBlock(xr, newHeight, zr, existing); ++blocksChanged; } } else if (curHeight > newHeight) { // Set the top block of the column to be the same type // (this could otherwise go wrong with rounding) session.setBlock(xr, newHeight, zr, session.getBlock(xr, curHeight, zr)); ++blocksChanged; // Fill rest with air for (int y = newHeight + 1; y <= curHeight; ++y) { session.setBlock(xr, y, zr, fillerAir); ++blocksChanged; } } } } // Drop trees to the floor -- TODO return blocksChanged; }
NONSATD
true
} int curHeight = this.data[index]; // Clamp newHeight within the selection area int newHeight = Math.min(maxY, data[index]); // Offset x,z to be 'real' coordinates
BlockState tmpBlock = BlockTypes.AIR.getDefaultState(); // Apply heightmap int index = 0; for (int z = 0; z < height; ++z) { int zr = z + originZ; for (int x = 0; x < width; ++x, index++) { if (this.invalid != null && this.invalid[index]) { continue; } int curHeight = this.data[index]; // Clamp newHeight within the selection area int newHeight = Math.min(maxY, data[index]); // Offset x,z to be 'real' coordinates int xr = x + originX; // Depending on growing or shrinking we need to start at the bottom or top if (newHeight > curHeight) { // Set the top block of the column to be the same type (this might go wrong with rounding) BlockState existing = session.getBlock(xr, curHeight, zr); // Skip water/lava if (existing.getBlockType().getMaterial().isMovementBlocker()) { int y0 = newHeight - 1;
public int apply(int[] data) throws MaxChangedBlocksException { checkNotNull(data); BlockVector3 minY = region.getMinimumPoint(); int originX = minY.getBlockX(); int originY = minY.getBlockY(); int originZ = minY.getBlockZ(); int maxY = region.getMaximumPoint().getBlockY(); BlockState fillerAir = BlockTypes.AIR.getDefaultState(); int blocksChanged = 0; BlockState tmpBlock = BlockTypes.AIR.getDefaultState(); // Apply heightmap int index = 0; for (int z = 0; z < height; ++z) { int zr = z + originZ; for (int x = 0; x < width; ++x, index++) { if (this.invalid != null && this.invalid[index]) { continue; } int curHeight = this.data[index]; // Clamp newHeight within the selection area int newHeight = Math.min(maxY, data[index]); // Offset x,z to be 'real' coordinates int xr = x + originX; // Depending on growing or shrinking we need to start at the bottom or top if (newHeight > curHeight) { // Set the top block of the column to be the same type (this might go wrong with rounding) BlockState existing = session.getBlock(xr, curHeight, zr); // Skip water/lava if (existing.getBlockType().getMaterial().isMovementBlocker()) { int y0 = newHeight - 1; for (int setY = y0, getY = curHeight - 1; setY >= curHeight; setY--, getY--) { BlockState get; if (getY >= 0 && getY < 256) { get = session.getBlock(xr, getY, zr); } else { get = BlockTypes.AIR.getDefaultState(); } if (get != BlockTypes.AIR.getDefaultState()) { tmpBlock = get; }
9,671
3
// Offset x,z to be 'real' coordinates
public int apply(int[] data) throws MaxChangedBlocksException { checkNotNull(data); BlockVector3 minY = region.getMinimumPoint(); int originX = minY.getBlockX(); int originY = minY.getBlockY(); int originZ = minY.getBlockZ(); int maxY = region.getMaximumPoint().getBlockY(); BlockState fillerAir = BlockTypes.AIR.getDefaultState(); int blocksChanged = 0; BlockState tmpBlock = BlockTypes.AIR.getDefaultState(); // Apply heightmap int index = 0; for (int z = 0; z < height; ++z) { int zr = z + originZ; for (int x = 0; x < width; ++x, index++) { if (this.invalid != null && this.invalid[index]) { continue; } int curHeight = this.data[index]; // Clamp newHeight within the selection area int newHeight = Math.min(maxY, data[index]); // Offset x,z to be 'real' coordinates int xr = x + originX; // Depending on growing or shrinking we need to start at the bottom or top if (newHeight > curHeight) { // Set the top block of the column to be the same type (this might go wrong with rounding) BlockState existing = session.getBlock(xr, curHeight, zr); // Skip water/lava if (existing.getBlockType().getMaterial().isMovementBlocker()) { int y0 = newHeight - 1; for (int setY = y0, getY = curHeight - 1; setY >= curHeight; setY--, getY--) { BlockState get; if (getY >= 0 && getY < 256) { get = session.getBlock(xr, getY, zr); } else { get = BlockTypes.AIR.getDefaultState(); } if (get != BlockTypes.AIR.getDefaultState()) { tmpBlock = get; } session.setBlock(xr, setY, zr, tmpBlock); ++blocksChanged; } session.setBlock(xr, newHeight, zr, existing); ++blocksChanged; } } else if (curHeight > newHeight) { // Set the top block of the column to be the same type // (this could otherwise go wrong with rounding) session.setBlock(xr, newHeight, zr, session.getBlock(xr, curHeight, zr)); ++blocksChanged; // Fill rest with air for (int y = newHeight + 1; y <= curHeight; ++y) { session.setBlock(xr, y, zr, fillerAir); ++blocksChanged; } } } } // Drop trees to the floor -- TODO return blocksChanged; }
NONSATD
true
// Clamp newHeight within the selection area int newHeight = Math.min(maxY, data[index]); // Offset x,z to be 'real' coordinates int xr = x + originX; // Depending on growing or shrinking we need to start at the bottom or top
int index = 0; for (int z = 0; z < height; ++z) { int zr = z + originZ; for (int x = 0; x < width; ++x, index++) { if (this.invalid != null && this.invalid[index]) { continue; } int curHeight = this.data[index]; // Clamp newHeight within the selection area int newHeight = Math.min(maxY, data[index]); // Offset x,z to be 'real' coordinates int xr = x + originX; // Depending on growing or shrinking we need to start at the bottom or top if (newHeight > curHeight) { // Set the top block of the column to be the same type (this might go wrong with rounding) BlockState existing = session.getBlock(xr, curHeight, zr); // Skip water/lava if (existing.getBlockType().getMaterial().isMovementBlocker()) { int y0 = newHeight - 1; for (int setY = y0, getY = curHeight - 1; setY >= curHeight; setY--, getY--) { BlockState get;
checkNotNull(data); BlockVector3 minY = region.getMinimumPoint(); int originX = minY.getBlockX(); int originY = minY.getBlockY(); int originZ = minY.getBlockZ(); int maxY = region.getMaximumPoint().getBlockY(); BlockState fillerAir = BlockTypes.AIR.getDefaultState(); int blocksChanged = 0; BlockState tmpBlock = BlockTypes.AIR.getDefaultState(); // Apply heightmap int index = 0; for (int z = 0; z < height; ++z) { int zr = z + originZ; for (int x = 0; x < width; ++x, index++) { if (this.invalid != null && this.invalid[index]) { continue; } int curHeight = this.data[index]; // Clamp newHeight within the selection area int newHeight = Math.min(maxY, data[index]); // Offset x,z to be 'real' coordinates int xr = x + originX; // Depending on growing or shrinking we need to start at the bottom or top if (newHeight > curHeight) { // Set the top block of the column to be the same type (this might go wrong with rounding) BlockState existing = session.getBlock(xr, curHeight, zr); // Skip water/lava if (existing.getBlockType().getMaterial().isMovementBlocker()) { int y0 = newHeight - 1; for (int setY = y0, getY = curHeight - 1; setY >= curHeight; setY--, getY--) { BlockState get; if (getY >= 0 && getY < 256) { get = session.getBlock(xr, getY, zr); } else { get = BlockTypes.AIR.getDefaultState(); } if (get != BlockTypes.AIR.getDefaultState()) { tmpBlock = get; } session.setBlock(xr, setY, zr, tmpBlock); ++blocksChanged;
9,671
4
// Depending on growing or shrinking we need to start at the bottom or top
public int apply(int[] data) throws MaxChangedBlocksException { checkNotNull(data); BlockVector3 minY = region.getMinimumPoint(); int originX = minY.getBlockX(); int originY = minY.getBlockY(); int originZ = minY.getBlockZ(); int maxY = region.getMaximumPoint().getBlockY(); BlockState fillerAir = BlockTypes.AIR.getDefaultState(); int blocksChanged = 0; BlockState tmpBlock = BlockTypes.AIR.getDefaultState(); // Apply heightmap int index = 0; for (int z = 0; z < height; ++z) { int zr = z + originZ; for (int x = 0; x < width; ++x, index++) { if (this.invalid != null && this.invalid[index]) { continue; } int curHeight = this.data[index]; // Clamp newHeight within the selection area int newHeight = Math.min(maxY, data[index]); // Offset x,z to be 'real' coordinates int xr = x + originX; // Depending on growing or shrinking we need to start at the bottom or top if (newHeight > curHeight) { // Set the top block of the column to be the same type (this might go wrong with rounding) BlockState existing = session.getBlock(xr, curHeight, zr); // Skip water/lava if (existing.getBlockType().getMaterial().isMovementBlocker()) { int y0 = newHeight - 1; for (int setY = y0, getY = curHeight - 1; setY >= curHeight; setY--, getY--) { BlockState get; if (getY >= 0 && getY < 256) { get = session.getBlock(xr, getY, zr); } else { get = BlockTypes.AIR.getDefaultState(); } if (get != BlockTypes.AIR.getDefaultState()) { tmpBlock = get; } session.setBlock(xr, setY, zr, tmpBlock); ++blocksChanged; } session.setBlock(xr, newHeight, zr, existing); ++blocksChanged; } } else if (curHeight > newHeight) { // Set the top block of the column to be the same type // (this could otherwise go wrong with rounding) session.setBlock(xr, newHeight, zr, session.getBlock(xr, curHeight, zr)); ++blocksChanged; // Fill rest with air for (int y = newHeight + 1; y <= curHeight; ++y) { session.setBlock(xr, y, zr, fillerAir); ++blocksChanged; } } } } // Drop trees to the floor -- TODO return blocksChanged; }
NONSATD
true
// Offset x,z to be 'real' coordinates int xr = x + originX; // Depending on growing or shrinking we need to start at the bottom or top if (newHeight > curHeight) { // Set the top block of the column to be the same type (this might go wrong with rounding)
int zr = z + originZ; for (int x = 0; x < width; ++x, index++) { if (this.invalid != null && this.invalid[index]) { continue; } int curHeight = this.data[index]; // Clamp newHeight within the selection area int newHeight = Math.min(maxY, data[index]); // Offset x,z to be 'real' coordinates int xr = x + originX; // Depending on growing or shrinking we need to start at the bottom or top if (newHeight > curHeight) { // Set the top block of the column to be the same type (this might go wrong with rounding) BlockState existing = session.getBlock(xr, curHeight, zr); // Skip water/lava if (existing.getBlockType().getMaterial().isMovementBlocker()) { int y0 = newHeight - 1; for (int setY = y0, getY = curHeight - 1; setY >= curHeight; setY--, getY--) { BlockState get; if (getY >= 0 && getY < 256) { get = session.getBlock(xr, getY, zr);
int originX = minY.getBlockX(); int originY = minY.getBlockY(); int originZ = minY.getBlockZ(); int maxY = region.getMaximumPoint().getBlockY(); BlockState fillerAir = BlockTypes.AIR.getDefaultState(); int blocksChanged = 0; BlockState tmpBlock = BlockTypes.AIR.getDefaultState(); // Apply heightmap int index = 0; for (int z = 0; z < height; ++z) { int zr = z + originZ; for (int x = 0; x < width; ++x, index++) { if (this.invalid != null && this.invalid[index]) { continue; } int curHeight = this.data[index]; // Clamp newHeight within the selection area int newHeight = Math.min(maxY, data[index]); // Offset x,z to be 'real' coordinates int xr = x + originX; // Depending on growing or shrinking we need to start at the bottom or top if (newHeight > curHeight) { // Set the top block of the column to be the same type (this might go wrong with rounding) BlockState existing = session.getBlock(xr, curHeight, zr); // Skip water/lava if (existing.getBlockType().getMaterial().isMovementBlocker()) { int y0 = newHeight - 1; for (int setY = y0, getY = curHeight - 1; setY >= curHeight; setY--, getY--) { BlockState get; if (getY >= 0 && getY < 256) { get = session.getBlock(xr, getY, zr); } else { get = BlockTypes.AIR.getDefaultState(); } if (get != BlockTypes.AIR.getDefaultState()) { tmpBlock = get; } session.setBlock(xr, setY, zr, tmpBlock); ++blocksChanged; } session.setBlock(xr, newHeight, zr, existing);
9,671
5
// Set the top block of the column to be the same type (this might go wrong with rounding)
public int apply(int[] data) throws MaxChangedBlocksException { checkNotNull(data); BlockVector3 minY = region.getMinimumPoint(); int originX = minY.getBlockX(); int originY = minY.getBlockY(); int originZ = minY.getBlockZ(); int maxY = region.getMaximumPoint().getBlockY(); BlockState fillerAir = BlockTypes.AIR.getDefaultState(); int blocksChanged = 0; BlockState tmpBlock = BlockTypes.AIR.getDefaultState(); // Apply heightmap int index = 0; for (int z = 0; z < height; ++z) { int zr = z + originZ; for (int x = 0; x < width; ++x, index++) { if (this.invalid != null && this.invalid[index]) { continue; } int curHeight = this.data[index]; // Clamp newHeight within the selection area int newHeight = Math.min(maxY, data[index]); // Offset x,z to be 'real' coordinates int xr = x + originX; // Depending on growing or shrinking we need to start at the bottom or top if (newHeight > curHeight) { // Set the top block of the column to be the same type (this might go wrong with rounding) BlockState existing = session.getBlock(xr, curHeight, zr); // Skip water/lava if (existing.getBlockType().getMaterial().isMovementBlocker()) { int y0 = newHeight - 1; for (int setY = y0, getY = curHeight - 1; setY >= curHeight; setY--, getY--) { BlockState get; if (getY >= 0 && getY < 256) { get = session.getBlock(xr, getY, zr); } else { get = BlockTypes.AIR.getDefaultState(); } if (get != BlockTypes.AIR.getDefaultState()) { tmpBlock = get; } session.setBlock(xr, setY, zr, tmpBlock); ++blocksChanged; } session.setBlock(xr, newHeight, zr, existing); ++blocksChanged; } } else if (curHeight > newHeight) { // Set the top block of the column to be the same type // (this could otherwise go wrong with rounding) session.setBlock(xr, newHeight, zr, session.getBlock(xr, curHeight, zr)); ++blocksChanged; // Fill rest with air for (int y = newHeight + 1; y <= curHeight; ++y) { session.setBlock(xr, y, zr, fillerAir); ++blocksChanged; } } } } // Drop trees to the floor -- TODO return blocksChanged; }
IMPLEMENTATION
true
// Depending on growing or shrinking we need to start at the bottom or top if (newHeight > curHeight) { // Set the top block of the column to be the same type (this might go wrong with rounding) BlockState existing = session.getBlock(xr, curHeight, zr); // Skip water/lava
if (this.invalid != null && this.invalid[index]) { continue; } int curHeight = this.data[index]; // Clamp newHeight within the selection area int newHeight = Math.min(maxY, data[index]); // Offset x,z to be 'real' coordinates int xr = x + originX; // Depending on growing or shrinking we need to start at the bottom or top if (newHeight > curHeight) { // Set the top block of the column to be the same type (this might go wrong with rounding) BlockState existing = session.getBlock(xr, curHeight, zr); // Skip water/lava if (existing.getBlockType().getMaterial().isMovementBlocker()) { int y0 = newHeight - 1; for (int setY = y0, getY = curHeight - 1; setY >= curHeight; setY--, getY--) { BlockState get; if (getY >= 0 && getY < 256) { get = session.getBlock(xr, getY, zr); } else { get = BlockTypes.AIR.getDefaultState();
int originZ = minY.getBlockZ(); int maxY = region.getMaximumPoint().getBlockY(); BlockState fillerAir = BlockTypes.AIR.getDefaultState(); int blocksChanged = 0; BlockState tmpBlock = BlockTypes.AIR.getDefaultState(); // Apply heightmap int index = 0; for (int z = 0; z < height; ++z) { int zr = z + originZ; for (int x = 0; x < width; ++x, index++) { if (this.invalid != null && this.invalid[index]) { continue; } int curHeight = this.data[index]; // Clamp newHeight within the selection area int newHeight = Math.min(maxY, data[index]); // Offset x,z to be 'real' coordinates int xr = x + originX; // Depending on growing or shrinking we need to start at the bottom or top if (newHeight > curHeight) { // Set the top block of the column to be the same type (this might go wrong with rounding) BlockState existing = session.getBlock(xr, curHeight, zr); // Skip water/lava if (existing.getBlockType().getMaterial().isMovementBlocker()) { int y0 = newHeight - 1; for (int setY = y0, getY = curHeight - 1; setY >= curHeight; setY--, getY--) { BlockState get; if (getY >= 0 && getY < 256) { get = session.getBlock(xr, getY, zr); } else { get = BlockTypes.AIR.getDefaultState(); } if (get != BlockTypes.AIR.getDefaultState()) { tmpBlock = get; } session.setBlock(xr, setY, zr, tmpBlock); ++blocksChanged; } session.setBlock(xr, newHeight, zr, existing); ++blocksChanged; }
9,671
6
// Skip water/lava
public int apply(int[] data) throws MaxChangedBlocksException { checkNotNull(data); BlockVector3 minY = region.getMinimumPoint(); int originX = minY.getBlockX(); int originY = minY.getBlockY(); int originZ = minY.getBlockZ(); int maxY = region.getMaximumPoint().getBlockY(); BlockState fillerAir = BlockTypes.AIR.getDefaultState(); int blocksChanged = 0; BlockState tmpBlock = BlockTypes.AIR.getDefaultState(); // Apply heightmap int index = 0; for (int z = 0; z < height; ++z) { int zr = z + originZ; for (int x = 0; x < width; ++x, index++) { if (this.invalid != null && this.invalid[index]) { continue; } int curHeight = this.data[index]; // Clamp newHeight within the selection area int newHeight = Math.min(maxY, data[index]); // Offset x,z to be 'real' coordinates int xr = x + originX; // Depending on growing or shrinking we need to start at the bottom or top if (newHeight > curHeight) { // Set the top block of the column to be the same type (this might go wrong with rounding) BlockState existing = session.getBlock(xr, curHeight, zr); // Skip water/lava if (existing.getBlockType().getMaterial().isMovementBlocker()) { int y0 = newHeight - 1; for (int setY = y0, getY = curHeight - 1; setY >= curHeight; setY--, getY--) { BlockState get; if (getY >= 0 && getY < 256) { get = session.getBlock(xr, getY, zr); } else { get = BlockTypes.AIR.getDefaultState(); } if (get != BlockTypes.AIR.getDefaultState()) { tmpBlock = get; } session.setBlock(xr, setY, zr, tmpBlock); ++blocksChanged; } session.setBlock(xr, newHeight, zr, existing); ++blocksChanged; } } else if (curHeight > newHeight) { // Set the top block of the column to be the same type // (this could otherwise go wrong with rounding) session.setBlock(xr, newHeight, zr, session.getBlock(xr, curHeight, zr)); ++blocksChanged; // Fill rest with air for (int y = newHeight + 1; y <= curHeight; ++y) { session.setBlock(xr, y, zr, fillerAir); ++blocksChanged; } } } } // Drop trees to the floor -- TODO return blocksChanged; }
NONSATD
true
// Set the top block of the column to be the same type (this might go wrong with rounding) BlockState existing = session.getBlock(xr, curHeight, zr); // Skip water/lava if (existing.getBlockType().getMaterial().isMovementBlocker()) { int y0 = newHeight - 1;
} int curHeight = this.data[index]; // Clamp newHeight within the selection area int newHeight = Math.min(maxY, data[index]); // Offset x,z to be 'real' coordinates int xr = x + originX; // Depending on growing or shrinking we need to start at the bottom or top if (newHeight > curHeight) { // Set the top block of the column to be the same type (this might go wrong with rounding) BlockState existing = session.getBlock(xr, curHeight, zr); // Skip water/lava if (existing.getBlockType().getMaterial().isMovementBlocker()) { int y0 = newHeight - 1; for (int setY = y0, getY = curHeight - 1; setY >= curHeight; setY--, getY--) { BlockState get; if (getY >= 0 && getY < 256) { get = session.getBlock(xr, getY, zr); } else { get = BlockTypes.AIR.getDefaultState(); } if (get != BlockTypes.AIR.getDefaultState()) {
BlockState fillerAir = BlockTypes.AIR.getDefaultState(); int blocksChanged = 0; BlockState tmpBlock = BlockTypes.AIR.getDefaultState(); // Apply heightmap int index = 0; for (int z = 0; z < height; ++z) { int zr = z + originZ; for (int x = 0; x < width; ++x, index++) { if (this.invalid != null && this.invalid[index]) { continue; } int curHeight = this.data[index]; // Clamp newHeight within the selection area int newHeight = Math.min(maxY, data[index]); // Offset x,z to be 'real' coordinates int xr = x + originX; // Depending on growing or shrinking we need to start at the bottom or top if (newHeight > curHeight) { // Set the top block of the column to be the same type (this might go wrong with rounding) BlockState existing = session.getBlock(xr, curHeight, zr); // Skip water/lava if (existing.getBlockType().getMaterial().isMovementBlocker()) { int y0 = newHeight - 1; for (int setY = y0, getY = curHeight - 1; setY >= curHeight; setY--, getY--) { BlockState get; if (getY >= 0 && getY < 256) { get = session.getBlock(xr, getY, zr); } else { get = BlockTypes.AIR.getDefaultState(); } if (get != BlockTypes.AIR.getDefaultState()) { tmpBlock = get; } session.setBlock(xr, setY, zr, tmpBlock); ++blocksChanged; } session.setBlock(xr, newHeight, zr, existing); ++blocksChanged; } } else if (curHeight > newHeight) { // Set the top block of the column to be the same type
9,671
7
// Set the top block of the column to be the same type // (this could otherwise go wrong with rounding)
public int apply(int[] data) throws MaxChangedBlocksException { checkNotNull(data); BlockVector3 minY = region.getMinimumPoint(); int originX = minY.getBlockX(); int originY = minY.getBlockY(); int originZ = minY.getBlockZ(); int maxY = region.getMaximumPoint().getBlockY(); BlockState fillerAir = BlockTypes.AIR.getDefaultState(); int blocksChanged = 0; BlockState tmpBlock = BlockTypes.AIR.getDefaultState(); // Apply heightmap int index = 0; for (int z = 0; z < height; ++z) { int zr = z + originZ; for (int x = 0; x < width; ++x, index++) { if (this.invalid != null && this.invalid[index]) { continue; } int curHeight = this.data[index]; // Clamp newHeight within the selection area int newHeight = Math.min(maxY, data[index]); // Offset x,z to be 'real' coordinates int xr = x + originX; // Depending on growing or shrinking we need to start at the bottom or top if (newHeight > curHeight) { // Set the top block of the column to be the same type (this might go wrong with rounding) BlockState existing = session.getBlock(xr, curHeight, zr); // Skip water/lava if (existing.getBlockType().getMaterial().isMovementBlocker()) { int y0 = newHeight - 1; for (int setY = y0, getY = curHeight - 1; setY >= curHeight; setY--, getY--) { BlockState get; if (getY >= 0 && getY < 256) { get = session.getBlock(xr, getY, zr); } else { get = BlockTypes.AIR.getDefaultState(); } if (get != BlockTypes.AIR.getDefaultState()) { tmpBlock = get; } session.setBlock(xr, setY, zr, tmpBlock); ++blocksChanged; } session.setBlock(xr, newHeight, zr, existing); ++blocksChanged; } } else if (curHeight > newHeight) { // Set the top block of the column to be the same type // (this could otherwise go wrong with rounding) session.setBlock(xr, newHeight, zr, session.getBlock(xr, curHeight, zr)); ++blocksChanged; // Fill rest with air for (int y = newHeight + 1; y <= curHeight; ++y) { session.setBlock(xr, y, zr, fillerAir); ++blocksChanged; } } } } // Drop trees to the floor -- TODO return blocksChanged; }
IMPLEMENTATION
true
// Depending on growing or shrinking we need to start at the bottom or top if (newHeight > curHeight) { // Set the top block of the column to be the same type (this might go wrong with rounding) BlockState existing = session.getBlock(xr, curHeight, zr); // Skip water/lava if (existing.getBlockType().getMaterial().isMovementBlocker()) {
if (this.invalid != null && this.invalid[index]) { continue; } int curHeight = this.data[index]; // Clamp newHeight within the selection area int newHeight = Math.min(maxY, data[index]); // Offset x,z to be 'real' coordinates int xr = x + originX; // Depending on growing or shrinking we need to start at the bottom or top if (newHeight > curHeight) { // Set the top block of the column to be the same type (this might go wrong with rounding) BlockState existing = session.getBlock(xr, curHeight, zr); // Skip water/lava if (existing.getBlockType().getMaterial().isMovementBlocker()) { int y0 = newHeight - 1; for (int setY = y0, getY = curHeight - 1; setY >= curHeight; setY--, getY--) { BlockState get; if (getY >= 0 && getY < 256) { get = session.getBlock(xr, getY, zr); } else { get = BlockTypes.AIR.getDefaultState(); }
int originZ = minY.getBlockZ(); int maxY = region.getMaximumPoint().getBlockY(); BlockState fillerAir = BlockTypes.AIR.getDefaultState(); int blocksChanged = 0; BlockState tmpBlock = BlockTypes.AIR.getDefaultState(); // Apply heightmap int index = 0; for (int z = 0; z < height; ++z) { int zr = z + originZ; for (int x = 0; x < width; ++x, index++) { if (this.invalid != null && this.invalid[index]) { continue; } int curHeight = this.data[index]; // Clamp newHeight within the selection area int newHeight = Math.min(maxY, data[index]); // Offset x,z to be 'real' coordinates int xr = x + originX; // Depending on growing or shrinking we need to start at the bottom or top if (newHeight > curHeight) { // Set the top block of the column to be the same type (this might go wrong with rounding) BlockState existing = session.getBlock(xr, curHeight, zr); // Skip water/lava if (existing.getBlockType().getMaterial().isMovementBlocker()) { int y0 = newHeight - 1; for (int setY = y0, getY = curHeight - 1; setY >= curHeight; setY--, getY--) { BlockState get; if (getY >= 0 && getY < 256) { get = session.getBlock(xr, getY, zr); } else { get = BlockTypes.AIR.getDefaultState(); } if (get != BlockTypes.AIR.getDefaultState()) { tmpBlock = get; } session.setBlock(xr, setY, zr, tmpBlock); ++blocksChanged; } session.setBlock(xr, newHeight, zr, existing); ++blocksChanged; } } else if (curHeight > newHeight) {
9,671
8
// Fill rest with air
public int apply(int[] data) throws MaxChangedBlocksException { checkNotNull(data); BlockVector3 minY = region.getMinimumPoint(); int originX = minY.getBlockX(); int originY = minY.getBlockY(); int originZ = minY.getBlockZ(); int maxY = region.getMaximumPoint().getBlockY(); BlockState fillerAir = BlockTypes.AIR.getDefaultState(); int blocksChanged = 0; BlockState tmpBlock = BlockTypes.AIR.getDefaultState(); // Apply heightmap int index = 0; for (int z = 0; z < height; ++z) { int zr = z + originZ; for (int x = 0; x < width; ++x, index++) { if (this.invalid != null && this.invalid[index]) { continue; } int curHeight = this.data[index]; // Clamp newHeight within the selection area int newHeight = Math.min(maxY, data[index]); // Offset x,z to be 'real' coordinates int xr = x + originX; // Depending on growing or shrinking we need to start at the bottom or top if (newHeight > curHeight) { // Set the top block of the column to be the same type (this might go wrong with rounding) BlockState existing = session.getBlock(xr, curHeight, zr); // Skip water/lava if (existing.getBlockType().getMaterial().isMovementBlocker()) { int y0 = newHeight - 1; for (int setY = y0, getY = curHeight - 1; setY >= curHeight; setY--, getY--) { BlockState get; if (getY >= 0 && getY < 256) { get = session.getBlock(xr, getY, zr); } else { get = BlockTypes.AIR.getDefaultState(); } if (get != BlockTypes.AIR.getDefaultState()) { tmpBlock = get; } session.setBlock(xr, setY, zr, tmpBlock); ++blocksChanged; } session.setBlock(xr, newHeight, zr, existing); ++blocksChanged; } } else if (curHeight > newHeight) { // Set the top block of the column to be the same type // (this could otherwise go wrong with rounding) session.setBlock(xr, newHeight, zr, session.getBlock(xr, curHeight, zr)); ++blocksChanged; // Fill rest with air for (int y = newHeight + 1; y <= curHeight; ++y) { session.setBlock(xr, y, zr, fillerAir); ++blocksChanged; } } } } // Drop trees to the floor -- TODO return blocksChanged; }
NONSATD
true
session.setBlock(xr, newHeight, zr, session.getBlock(xr, curHeight, zr)); ++blocksChanged; // Fill rest with air for (int y = newHeight + 1; y <= curHeight; ++y) { session.setBlock(xr, y, zr, fillerAir);
++blocksChanged; } session.setBlock(xr, newHeight, zr, existing); ++blocksChanged; } } else if (curHeight > newHeight) { // Set the top block of the column to be the same type // (this could otherwise go wrong with rounding) session.setBlock(xr, newHeight, zr, session.getBlock(xr, curHeight, zr)); ++blocksChanged; // Fill rest with air for (int y = newHeight + 1; y <= curHeight; ++y) { session.setBlock(xr, y, zr, fillerAir); ++blocksChanged; } } } } // Drop trees to the floor -- TODO return blocksChanged; }
BlockState get; if (getY >= 0 && getY < 256) { get = session.getBlock(xr, getY, zr); } else { get = BlockTypes.AIR.getDefaultState(); } if (get != BlockTypes.AIR.getDefaultState()) { tmpBlock = get; } session.setBlock(xr, setY, zr, tmpBlock); ++blocksChanged; } session.setBlock(xr, newHeight, zr, existing); ++blocksChanged; } } else if (curHeight > newHeight) { // Set the top block of the column to be the same type // (this could otherwise go wrong with rounding) session.setBlock(xr, newHeight, zr, session.getBlock(xr, curHeight, zr)); ++blocksChanged; // Fill rest with air for (int y = newHeight + 1; y <= curHeight; ++y) { session.setBlock(xr, y, zr, fillerAir); ++blocksChanged; } } } } // Drop trees to the floor -- TODO return blocksChanged; }
9,671
9
// Drop trees to the floor -- TODO
public int apply(int[] data) throws MaxChangedBlocksException { checkNotNull(data); BlockVector3 minY = region.getMinimumPoint(); int originX = minY.getBlockX(); int originY = minY.getBlockY(); int originZ = minY.getBlockZ(); int maxY = region.getMaximumPoint().getBlockY(); BlockState fillerAir = BlockTypes.AIR.getDefaultState(); int blocksChanged = 0; BlockState tmpBlock = BlockTypes.AIR.getDefaultState(); // Apply heightmap int index = 0; for (int z = 0; z < height; ++z) { int zr = z + originZ; for (int x = 0; x < width; ++x, index++) { if (this.invalid != null && this.invalid[index]) { continue; } int curHeight = this.data[index]; // Clamp newHeight within the selection area int newHeight = Math.min(maxY, data[index]); // Offset x,z to be 'real' coordinates int xr = x + originX; // Depending on growing or shrinking we need to start at the bottom or top if (newHeight > curHeight) { // Set the top block of the column to be the same type (this might go wrong with rounding) BlockState existing = session.getBlock(xr, curHeight, zr); // Skip water/lava if (existing.getBlockType().getMaterial().isMovementBlocker()) { int y0 = newHeight - 1; for (int setY = y0, getY = curHeight - 1; setY >= curHeight; setY--, getY--) { BlockState get; if (getY >= 0 && getY < 256) { get = session.getBlock(xr, getY, zr); } else { get = BlockTypes.AIR.getDefaultState(); } if (get != BlockTypes.AIR.getDefaultState()) { tmpBlock = get; } session.setBlock(xr, setY, zr, tmpBlock); ++blocksChanged; } session.setBlock(xr, newHeight, zr, existing); ++blocksChanged; } } else if (curHeight > newHeight) { // Set the top block of the column to be the same type // (this could otherwise go wrong with rounding) session.setBlock(xr, newHeight, zr, session.getBlock(xr, curHeight, zr)); ++blocksChanged; // Fill rest with air for (int y = newHeight + 1; y <= curHeight; ++y) { session.setBlock(xr, y, zr, fillerAir); ++blocksChanged; } } } } // Drop trees to the floor -- TODO return blocksChanged; }
NONSATD
true
} } // Drop trees to the floor -- TODO return blocksChanged; }
session.setBlock(xr, newHeight, zr, session.getBlock(xr, curHeight, zr)); ++blocksChanged; // Fill rest with air for (int y = newHeight + 1; y <= curHeight; ++y) { session.setBlock(xr, y, zr, fillerAir); ++blocksChanged; } } } } // Drop trees to the floor -- TODO return blocksChanged; }
} session.setBlock(xr, setY, zr, tmpBlock); ++blocksChanged; } session.setBlock(xr, newHeight, zr, existing); ++blocksChanged; } } else if (curHeight > newHeight) { // Set the top block of the column to be the same type // (this could otherwise go wrong with rounding) session.setBlock(xr, newHeight, zr, session.getBlock(xr, curHeight, zr)); ++blocksChanged; // Fill rest with air for (int y = newHeight + 1; y <= curHeight; ++y) { session.setBlock(xr, y, zr, fillerAir); ++blocksChanged; } } } } // Drop trees to the floor -- TODO return blocksChanged; }
9,669
0
// TODO Embedded Elasticsearch integration tests do not support has child operations
@Override public void testSave() { // TODO Embedded Elasticsearch integration tests do not support has child operations }
IMPLEMENTATION
true
@Override public void testSave() { // TODO Embedded Elasticsearch integration tests do not support has child operations }
@Override public void testSave() { // TODO Embedded Elasticsearch integration tests do not support has child operations }
@Override public void testSave() { // TODO Embedded Elasticsearch integration tests do not support has child operations }
34,249
0
// ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information.
@Override public void onStart() { super.onStart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Sliding Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path") ); AppIndex.AppIndexApi.start(client, viewAction); }
NONSATD
true
public void onStart() { super.onStart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); Action viewAction = Action.newAction(
@Override public void onStart() { super.onStart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Sliding Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path")
@Override public void onStart() { super.onStart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Sliding Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path") ); AppIndex.AppIndexApi.start(client, viewAction); }
34,249
1
// TODO: choose an action type.
@Override public void onStart() { super.onStart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Sliding Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path") ); AppIndex.AppIndexApi.start(client, viewAction); }
DESIGN
true
client.connect(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Sliding Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content,
@Override public void onStart() { super.onStart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Sliding Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path") ); AppIndex.AppIndexApi.start(client, viewAction); }
@Override public void onStart() { super.onStart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Sliding Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path") ); AppIndex.AppIndexApi.start(client, viewAction); }
34,249
2
// TODO: Define a title for the content shown.
@Override public void onStart() { super.onStart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Sliding Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path") ); AppIndex.AppIndexApi.start(client, viewAction); }
IMPLEMENTATION
true
Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Sliding Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct.
@Override public void onStart() { super.onStart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Sliding Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path") ); AppIndex.AppIndexApi.start(client, viewAction); }
@Override public void onStart() { super.onStart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Sliding Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path") ); AppIndex.AppIndexApi.start(client, viewAction); }
34,249
3
// TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null.
@Override public void onStart() { super.onStart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Sliding Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path") ); AppIndex.AppIndexApi.start(client, viewAction); }
DESIGN
true
Action.TYPE_VIEW, // TODO: choose an action type. "Sliding Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct.
@Override public void onStart() { super.onStart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Sliding Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path") ); AppIndex.AppIndexApi.start(client, viewAction); }
@Override public void onStart() { super.onStart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Sliding Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path") ); AppIndex.AppIndexApi.start(client, viewAction); }
34,249
4
// TODO: Make sure this auto-generated app deep link URI is correct.
@Override public void onStart() { super.onStart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Sliding Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path") ); AppIndex.AppIndexApi.start(client, viewAction); }
DESIGN
true
// Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path") );
// ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Sliding Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path") ); AppIndex.AppIndexApi.start(client, viewAction); }
@Override public void onStart() { super.onStart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Sliding Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path") ); AppIndex.AppIndexApi.start(client, viewAction); }
34,250
0
// ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information.
@Override public void onStop() { super.onStop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Sliding Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path") ); AppIndex.AppIndexApi.end(client, viewAction); client.disconnect(); }
NONSATD
true
public void onStop() { super.onStop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type.
@Override public void onStop() { super.onStop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Sliding Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path") );
@Override public void onStop() { super.onStop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Sliding Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path") ); AppIndex.AppIndexApi.end(client, viewAction); client.disconnect(); }
34,250
1
// TODO: choose an action type.
@Override public void onStop() { super.onStop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Sliding Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path") ); AppIndex.AppIndexApi.end(client, viewAction); client.disconnect(); }
DESIGN
true
// See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Sliding Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content,
@Override public void onStop() { super.onStop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Sliding Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path") ); AppIndex.AppIndexApi.end(client, viewAction); client.disconnect();
@Override public void onStop() { super.onStop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Sliding Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path") ); AppIndex.AppIndexApi.end(client, viewAction); client.disconnect(); }
34,250
2
// TODO: Define a title for the content shown.
@Override public void onStop() { super.onStop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Sliding Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path") ); AppIndex.AppIndexApi.end(client, viewAction); client.disconnect(); }
IMPLEMENTATION
true
Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Sliding Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct.
@Override public void onStop() { super.onStop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Sliding Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path") ); AppIndex.AppIndexApi.end(client, viewAction); client.disconnect(); }
@Override public void onStop() { super.onStop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Sliding Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path") ); AppIndex.AppIndexApi.end(client, viewAction); client.disconnect(); }
34,250
3
// TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null.
@Override public void onStop() { super.onStop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Sliding Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path") ); AppIndex.AppIndexApi.end(client, viewAction); client.disconnect(); }
DESIGN
true
Action.TYPE_VIEW, // TODO: choose an action type. "Sliding Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct.
@Override public void onStop() { super.onStop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Sliding Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path") ); AppIndex.AppIndexApi.end(client, viewAction); client.disconnect(); }
@Override public void onStop() { super.onStop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Sliding Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path") ); AppIndex.AppIndexApi.end(client, viewAction); client.disconnect(); }
34,250
4
// TODO: Make sure this auto-generated app deep link URI is correct.
@Override public void onStop() { super.onStop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Sliding Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path") ); AppIndex.AppIndexApi.end(client, viewAction); client.disconnect(); }
DESIGN
true
// Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path") );
super.onStop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Sliding Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path") ); AppIndex.AppIndexApi.end(client, viewAction); client.disconnect(); }
@Override public void onStop() { super.onStop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Sliding Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kaidongyuan.app.basemodule.widget.slidingmenu.activity/http/host/path") ); AppIndex.AppIndexApi.end(client, viewAction); client.disconnect(); }
17,865
0
//Hacky assert but we know that this mockServer will create an exception that will be logged, if there's no log entry //then there's no exception, which means that getCredentials didn't get called on the fetcher
@Test(expected = AmazonClientException.class) public void canBeConfiguredToOnlyRefreshCredentialsAfterFirstCallToGetCredentials() throws InterruptedException { mockServer.setResponseFileName("sessionResponseExpired"); mockServer.setAvailableSecurityCredentials("test-credentials"); InstanceProfileCredentialsProvider credentialsProvider = InstanceProfileCredentialsProvider.createAsyncRefreshingProvider(false); Thread.sleep(1000); //Hacky assert but we know that this mockServer will create an exception that will be logged, if there's no log entry //then there's no exception, which means that getCredentials didn't get called on the fetcher assertThat(loggedEvents(), is(empty())); credentialsProvider.getCredentials(); }
DESIGN
true
InstanceProfileCredentialsProvider credentialsProvider = InstanceProfileCredentialsProvider.createAsyncRefreshingProvider(false); Thread.sleep(1000); //Hacky assert but we know that this mockServer will create an exception that will be logged, if there's no log entry //then there's no exception, which means that getCredentials didn't get called on the fetcher assertThat(loggedEvents(), is(empty())); credentialsProvider.getCredentials();
@Test(expected = AmazonClientException.class) public void canBeConfiguredToOnlyRefreshCredentialsAfterFirstCallToGetCredentials() throws InterruptedException { mockServer.setResponseFileName("sessionResponseExpired"); mockServer.setAvailableSecurityCredentials("test-credentials"); InstanceProfileCredentialsProvider credentialsProvider = InstanceProfileCredentialsProvider.createAsyncRefreshingProvider(false); Thread.sleep(1000); //Hacky assert but we know that this mockServer will create an exception that will be logged, if there's no log entry //then there's no exception, which means that getCredentials didn't get called on the fetcher assertThat(loggedEvents(), is(empty())); credentialsProvider.getCredentials(); }
@Test(expected = AmazonClientException.class) public void canBeConfiguredToOnlyRefreshCredentialsAfterFirstCallToGetCredentials() throws InterruptedException { mockServer.setResponseFileName("sessionResponseExpired"); mockServer.setAvailableSecurityCredentials("test-credentials"); InstanceProfileCredentialsProvider credentialsProvider = InstanceProfileCredentialsProvider.createAsyncRefreshingProvider(false); Thread.sleep(1000); //Hacky assert but we know that this mockServer will create an exception that will be logged, if there's no log entry //then there's no exception, which means that getCredentials didn't get called on the fetcher assertThat(loggedEvents(), is(empty())); credentialsProvider.getCredentials(); }
9,676
0
// TODO: write query to retrieve all movies rated by user with id userId
@Override public List<Movie> getMoviesRatedByUser(int userId) { // TODO: write query to retrieve all movies rated by user with id userId List<Movie> movies = new LinkedList<Movie>(); Genre genre0 = new Genre(0, "genre0"); Genre genre1 = new Genre(1, "genre1"); Genre genre2 = new Genre(2, "genre2"); movies.add(new Movie(0, "Titre 0", Arrays.asList(new Genre[]{genre0, genre1}))); movies.add(new Movie(3, "Titre 3", Arrays.asList(new Genre[]{genre0, genre1, genre2}))); return movies; }
IMPLEMENTATION
true
@Override public List<Movie> getMoviesRatedByUser(int userId) { // TODO: write query to retrieve all movies rated by user with id userId List<Movie> movies = new LinkedList<Movie>(); Genre genre0 = new Genre(0, "genre0");
@Override public List<Movie> getMoviesRatedByUser(int userId) { // TODO: write query to retrieve all movies rated by user with id userId List<Movie> movies = new LinkedList<Movie>(); Genre genre0 = new Genre(0, "genre0"); Genre genre1 = new Genre(1, "genre1"); Genre genre2 = new Genre(2, "genre2"); movies.add(new Movie(0, "Titre 0", Arrays.asList(new Genre[]{genre0, genre1}))); movies.add(new Movie(3, "Titre 3", Arrays.asList(new Genre[]{genre0, genre1, genre2}))); return movies; }
@Override public List<Movie> getMoviesRatedByUser(int userId) { // TODO: write query to retrieve all movies rated by user with id userId List<Movie> movies = new LinkedList<Movie>(); Genre genre0 = new Genre(0, "genre0"); Genre genre1 = new Genre(1, "genre1"); Genre genre2 = new Genre(2, "genre2"); movies.add(new Movie(0, "Titre 0", Arrays.asList(new Genre[]{genre0, genre1}))); movies.add(new Movie(3, "Titre 3", Arrays.asList(new Genre[]{genre0, genre1, genre2}))); return movies; }
1,489
0
//$NON-NLS-1$
public void downloadTiles(){ setVisible(false); final ProgressDialog progressDialog = new ProgressDialog(this, Messages.getString("TileBundleDownloadDialog.DOWNLOADING.TILES")); //$NON-NLS-1$ int numberTiles = 0; final int startZoom = (Integer) startSpinner.getValue(); final int endZoom = (Integer) endSpinner.getValue(); for (int zoom = startZoom; zoom <= endZoom; zoom++) { int x1 = (int) MapUtils.getTileNumberX(zoom, selectionArea.getLon1()); int x2 = (int) MapUtils.getTileNumberX(zoom, selectionArea.getLon2()); int y1 = (int) MapUtils.getTileNumberY(zoom, selectionArea.getLat1()); int y2 = (int) MapUtils.getTileNumberY(zoom, selectionArea.getLat2()); numberTiles += (x2 - x1 + 1) * (y2 - y1 + 1); } final int number = numberTiles; final MapTileDownloader instance = MapTileDownloader.getInstance(MapCreatorVersion.APP_MAP_CREATOR_VERSION); progressDialog.setRunnable(new Runnable(){ @Override public void run() { progressDialog.startTask(Messages.getString("TileBundleDownloadDialog.LOADING"), number); //$NON-NLS-1$ for (int zoom = startZoom; zoom <= endZoom; zoom++) { int x1 = (int) MapUtils.getTileNumberX(zoom, selectionArea.getLon1()); int x2 = (int) MapUtils.getTileNumberX(zoom, selectionArea.getLon2()); int y1 = (int) MapUtils.getTileNumberY(zoom, selectionArea.getLat1()); int y2 = (int) MapUtils.getTileNumberY(zoom, selectionArea.getLat2()); for(int x = x1; x <= x2; x++){ for(int y=y1; y<= y2; y++){ String file = getFileForImage(x, y, zoom, map.getTileFormat()); if(new File(tilesLocation, file).exists()){ progressDialog.progress(1); } else { DownloadRequest req = new DownloadRequest(map.getUrlToLoad(x, y, zoom), new File(tilesLocation, file), x, y, zoom); instance.requestToDownload(req); } } } while(instance.isSomethingBeingDownloaded()){ try { Thread.sleep(100); } catch (InterruptedException e) { throw new IllegalArgumentException(e); } } } } }); ArrayList<IMapDownloaderCallback> previousCallbacks = new ArrayList<IMapDownloaderCallback>(instance.getDownloaderCallbacks()); instance.getDownloaderCallbacks().clear(); instance.addDownloaderCallback(new IMapDownloaderCallback(){ @Override public void tileDownloaded(DownloadRequest request) { // TODO request could be null if bundle loading? progressDialog.progress(1); } }); try { progressDialog.run(); instance.refuseAllPreviousRequests(); } catch (InvocationTargetException e) { ExceptionHandler.handle((Exception) e.getCause()); } catch (InterruptedException e) { ExceptionHandler.handle(e); } finally { instance.getDownloaderCallbacks().clear(); instance.getDownloaderCallbacks().addAll(previousCallbacks); } }
NONSATD
true
public void downloadTiles(){ setVisible(false); final ProgressDialog progressDialog = new ProgressDialog(this, Messages.getString("TileBundleDownloadDialog.DOWNLOADING.TILES")); //$NON-NLS-1$ int numberTiles = 0; final int startZoom = (Integer) startSpinner.getValue();
public void downloadTiles(){ setVisible(false); final ProgressDialog progressDialog = new ProgressDialog(this, Messages.getString("TileBundleDownloadDialog.DOWNLOADING.TILES")); //$NON-NLS-1$ int numberTiles = 0; final int startZoom = (Integer) startSpinner.getValue(); final int endZoom = (Integer) endSpinner.getValue(); for (int zoom = startZoom; zoom <= endZoom; zoom++) { int x1 = (int) MapUtils.getTileNumberX(zoom, selectionArea.getLon1()); int x2 = (int) MapUtils.getTileNumberX(zoom, selectionArea.getLon2()); int y1 = (int) MapUtils.getTileNumberY(zoom, selectionArea.getLat1()); int y2 = (int) MapUtils.getTileNumberY(zoom, selectionArea.getLat2()); numberTiles += (x2 - x1 + 1) * (y2 - y1 + 1); }
public void downloadTiles(){ setVisible(false); final ProgressDialog progressDialog = new ProgressDialog(this, Messages.getString("TileBundleDownloadDialog.DOWNLOADING.TILES")); //$NON-NLS-1$ int numberTiles = 0; final int startZoom = (Integer) startSpinner.getValue(); final int endZoom = (Integer) endSpinner.getValue(); for (int zoom = startZoom; zoom <= endZoom; zoom++) { int x1 = (int) MapUtils.getTileNumberX(zoom, selectionArea.getLon1()); int x2 = (int) MapUtils.getTileNumberX(zoom, selectionArea.getLon2()); int y1 = (int) MapUtils.getTileNumberY(zoom, selectionArea.getLat1()); int y2 = (int) MapUtils.getTileNumberY(zoom, selectionArea.getLat2()); numberTiles += (x2 - x1 + 1) * (y2 - y1 + 1); } final int number = numberTiles; final MapTileDownloader instance = MapTileDownloader.getInstance(MapCreatorVersion.APP_MAP_CREATOR_VERSION); progressDialog.setRunnable(new Runnable(){ @Override public void run() { progressDialog.startTask(Messages.getString("TileBundleDownloadDialog.LOADING"), number); //$NON-NLS-1$ for (int zoom = startZoom; zoom <= endZoom; zoom++) { int x1 = (int) MapUtils.getTileNumberX(zoom, selectionArea.getLon1()); int x2 = (int) MapUtils.getTileNumberX(zoom, selectionArea.getLon2()); int y1 = (int) MapUtils.getTileNumberY(zoom, selectionArea.getLat1());
1,489
1
//$NON-NLS-1$
public void downloadTiles(){ setVisible(false); final ProgressDialog progressDialog = new ProgressDialog(this, Messages.getString("TileBundleDownloadDialog.DOWNLOADING.TILES")); //$NON-NLS-1$ int numberTiles = 0; final int startZoom = (Integer) startSpinner.getValue(); final int endZoom = (Integer) endSpinner.getValue(); for (int zoom = startZoom; zoom <= endZoom; zoom++) { int x1 = (int) MapUtils.getTileNumberX(zoom, selectionArea.getLon1()); int x2 = (int) MapUtils.getTileNumberX(zoom, selectionArea.getLon2()); int y1 = (int) MapUtils.getTileNumberY(zoom, selectionArea.getLat1()); int y2 = (int) MapUtils.getTileNumberY(zoom, selectionArea.getLat2()); numberTiles += (x2 - x1 + 1) * (y2 - y1 + 1); } final int number = numberTiles; final MapTileDownloader instance = MapTileDownloader.getInstance(MapCreatorVersion.APP_MAP_CREATOR_VERSION); progressDialog.setRunnable(new Runnable(){ @Override public void run() { progressDialog.startTask(Messages.getString("TileBundleDownloadDialog.LOADING"), number); //$NON-NLS-1$ for (int zoom = startZoom; zoom <= endZoom; zoom++) { int x1 = (int) MapUtils.getTileNumberX(zoom, selectionArea.getLon1()); int x2 = (int) MapUtils.getTileNumberX(zoom, selectionArea.getLon2()); int y1 = (int) MapUtils.getTileNumberY(zoom, selectionArea.getLat1()); int y2 = (int) MapUtils.getTileNumberY(zoom, selectionArea.getLat2()); for(int x = x1; x <= x2; x++){ for(int y=y1; y<= y2; y++){ String file = getFileForImage(x, y, zoom, map.getTileFormat()); if(new File(tilesLocation, file).exists()){ progressDialog.progress(1); } else { DownloadRequest req = new DownloadRequest(map.getUrlToLoad(x, y, zoom), new File(tilesLocation, file), x, y, zoom); instance.requestToDownload(req); } } } while(instance.isSomethingBeingDownloaded()){ try { Thread.sleep(100); } catch (InterruptedException e) { throw new IllegalArgumentException(e); } } } } }); ArrayList<IMapDownloaderCallback> previousCallbacks = new ArrayList<IMapDownloaderCallback>(instance.getDownloaderCallbacks()); instance.getDownloaderCallbacks().clear(); instance.addDownloaderCallback(new IMapDownloaderCallback(){ @Override public void tileDownloaded(DownloadRequest request) { // TODO request could be null if bundle loading? progressDialog.progress(1); } }); try { progressDialog.run(); instance.refuseAllPreviousRequests(); } catch (InvocationTargetException e) { ExceptionHandler.handle((Exception) e.getCause()); } catch (InterruptedException e) { ExceptionHandler.handle(e); } finally { instance.getDownloaderCallbacks().clear(); instance.getDownloaderCallbacks().addAll(previousCallbacks); } }
NONSATD
true
public void downloadTiles(){ setVisible(false); final ProgressDialog progressDialog = new ProgressDialog(this, Messages.getString("TileBundleDownloadDialog.DOWNLOADING.TILES")); //$NON-NLS-1$ int numberTiles = 0; final int startZoom = (Integer) startSpinner.getValue();
public void downloadTiles(){ setVisible(false); final ProgressDialog progressDialog = new ProgressDialog(this, Messages.getString("TileBundleDownloadDialog.DOWNLOADING.TILES")); //$NON-NLS-1$ int numberTiles = 0; final int startZoom = (Integer) startSpinner.getValue(); final int endZoom = (Integer) endSpinner.getValue(); for (int zoom = startZoom; zoom <= endZoom; zoom++) { int x1 = (int) MapUtils.getTileNumberX(zoom, selectionArea.getLon1()); int x2 = (int) MapUtils.getTileNumberX(zoom, selectionArea.getLon2()); int y1 = (int) MapUtils.getTileNumberY(zoom, selectionArea.getLat1()); int y2 = (int) MapUtils.getTileNumberY(zoom, selectionArea.getLat2()); numberTiles += (x2 - x1 + 1) * (y2 - y1 + 1); }
public void downloadTiles(){ setVisible(false); final ProgressDialog progressDialog = new ProgressDialog(this, Messages.getString("TileBundleDownloadDialog.DOWNLOADING.TILES")); //$NON-NLS-1$ int numberTiles = 0; final int startZoom = (Integer) startSpinner.getValue(); final int endZoom = (Integer) endSpinner.getValue(); for (int zoom = startZoom; zoom <= endZoom; zoom++) { int x1 = (int) MapUtils.getTileNumberX(zoom, selectionArea.getLon1()); int x2 = (int) MapUtils.getTileNumberX(zoom, selectionArea.getLon2()); int y1 = (int) MapUtils.getTileNumberY(zoom, selectionArea.getLat1()); int y2 = (int) MapUtils.getTileNumberY(zoom, selectionArea.getLat2()); numberTiles += (x2 - x1 + 1) * (y2 - y1 + 1); } final int number = numberTiles; final MapTileDownloader instance = MapTileDownloader.getInstance(MapCreatorVersion.APP_MAP_CREATOR_VERSION); progressDialog.setRunnable(new Runnable(){ @Override public void run() { progressDialog.startTask(Messages.getString("TileBundleDownloadDialog.LOADING"), number); //$NON-NLS-1$ for (int zoom = startZoom; zoom <= endZoom; zoom++) { int x1 = (int) MapUtils.getTileNumberX(zoom, selectionArea.getLon1()); int x2 = (int) MapUtils.getTileNumberX(zoom, selectionArea.getLon2()); int y1 = (int) MapUtils.getTileNumberY(zoom, selectionArea.getLat1());
1,489
2
// TODO request could be null if bundle loading?
public void downloadTiles(){ setVisible(false); final ProgressDialog progressDialog = new ProgressDialog(this, Messages.getString("TileBundleDownloadDialog.DOWNLOADING.TILES")); //$NON-NLS-1$ int numberTiles = 0; final int startZoom = (Integer) startSpinner.getValue(); final int endZoom = (Integer) endSpinner.getValue(); for (int zoom = startZoom; zoom <= endZoom; zoom++) { int x1 = (int) MapUtils.getTileNumberX(zoom, selectionArea.getLon1()); int x2 = (int) MapUtils.getTileNumberX(zoom, selectionArea.getLon2()); int y1 = (int) MapUtils.getTileNumberY(zoom, selectionArea.getLat1()); int y2 = (int) MapUtils.getTileNumberY(zoom, selectionArea.getLat2()); numberTiles += (x2 - x1 + 1) * (y2 - y1 + 1); } final int number = numberTiles; final MapTileDownloader instance = MapTileDownloader.getInstance(MapCreatorVersion.APP_MAP_CREATOR_VERSION); progressDialog.setRunnable(new Runnable(){ @Override public void run() { progressDialog.startTask(Messages.getString("TileBundleDownloadDialog.LOADING"), number); //$NON-NLS-1$ for (int zoom = startZoom; zoom <= endZoom; zoom++) { int x1 = (int) MapUtils.getTileNumberX(zoom, selectionArea.getLon1()); int x2 = (int) MapUtils.getTileNumberX(zoom, selectionArea.getLon2()); int y1 = (int) MapUtils.getTileNumberY(zoom, selectionArea.getLat1()); int y2 = (int) MapUtils.getTileNumberY(zoom, selectionArea.getLat2()); for(int x = x1; x <= x2; x++){ for(int y=y1; y<= y2; y++){ String file = getFileForImage(x, y, zoom, map.getTileFormat()); if(new File(tilesLocation, file).exists()){ progressDialog.progress(1); } else { DownloadRequest req = new DownloadRequest(map.getUrlToLoad(x, y, zoom), new File(tilesLocation, file), x, y, zoom); instance.requestToDownload(req); } } } while(instance.isSomethingBeingDownloaded()){ try { Thread.sleep(100); } catch (InterruptedException e) { throw new IllegalArgumentException(e); } } } } }); ArrayList<IMapDownloaderCallback> previousCallbacks = new ArrayList<IMapDownloaderCallback>(instance.getDownloaderCallbacks()); instance.getDownloaderCallbacks().clear(); instance.addDownloaderCallback(new IMapDownloaderCallback(){ @Override public void tileDownloaded(DownloadRequest request) { // TODO request could be null if bundle loading? progressDialog.progress(1); } }); try { progressDialog.run(); instance.refuseAllPreviousRequests(); } catch (InvocationTargetException e) { ExceptionHandler.handle((Exception) e.getCause()); } catch (InterruptedException e) { ExceptionHandler.handle(e); } finally { instance.getDownloaderCallbacks().clear(); instance.getDownloaderCallbacks().addAll(previousCallbacks); } }
IMPLEMENTATION
true
@Override public void tileDownloaded(DownloadRequest request) { // TODO request could be null if bundle loading? progressDialog.progress(1); }
} } } }); ArrayList<IMapDownloaderCallback> previousCallbacks = new ArrayList<IMapDownloaderCallback>(instance.getDownloaderCallbacks()); instance.getDownloaderCallbacks().clear(); instance.addDownloaderCallback(new IMapDownloaderCallback(){ @Override public void tileDownloaded(DownloadRequest request) { // TODO request could be null if bundle loading? progressDialog.progress(1); } }); try { progressDialog.run(); instance.refuseAllPreviousRequests(); } catch (InvocationTargetException e) { ExceptionHandler.handle((Exception) e.getCause()); } catch (InterruptedException e) { ExceptionHandler.handle(e);
instance.requestToDownload(req); } } } while(instance.isSomethingBeingDownloaded()){ try { Thread.sleep(100); } catch (InterruptedException e) { throw new IllegalArgumentException(e); } } } } }); ArrayList<IMapDownloaderCallback> previousCallbacks = new ArrayList<IMapDownloaderCallback>(instance.getDownloaderCallbacks()); instance.getDownloaderCallbacks().clear(); instance.addDownloaderCallback(new IMapDownloaderCallback(){ @Override public void tileDownloaded(DownloadRequest request) { // TODO request could be null if bundle loading? progressDialog.progress(1); } }); try { progressDialog.run(); instance.refuseAllPreviousRequests(); } catch (InvocationTargetException e) { ExceptionHandler.handle((Exception) e.getCause()); } catch (InterruptedException e) { ExceptionHandler.handle(e); } finally { instance.getDownloaderCallbacks().clear(); instance.getDownloaderCallbacks().addAll(previousCallbacks); } }
1,494
0
/** * Initialization is needed before constructing DFA. * * @param minXSize maximum number of the states * @param maxXSize minimum number of the states */
private void initialization(int minXSize, int maxXSize) { // TODO: current implementation is less elegant. code refactoring may be needed. dfaConfig = new DFAConfig(); // allocates a new config every time. Random r = new Random(); dfaConfig.stateSize = r.nextInt((maxXSize - minXSize) + 1) + minXSize; dfaConfig.faultyStateSize = Math.max(dfaConfig.stateSize / 10, 4); LOGGER.debug("Generated overall state size and faulty state size: {}, {}", dfaConfig.stateSize, dfaConfig.faultyStateSize); dfaConfig.states = new int[dfaConfig.stateSize]; for (int i = 0; i < dfaConfig.stateSize; i++) { dfaConfig.states[i] = i; } // alphabet size: range[6 ~ 16] or [10, 20] int base = dfaConfig.stateSize > 20 ? 10 : 6; int alphabetSize = r.nextInt(11) + base; dfaConfig.alphabet = new char[alphabetSize]; LOGGER.debug("Chosen alphabet size is {}", alphabetSize); // randomly fill the alphabet int alphabetSpaceLen = dfaConfig.alphabetSpace.length(); boolean[] tempFlags = new boolean[alphabetSpaceLen]; int tempIndex; for (int i = 0; i < dfaConfig.alphabet.length; i++) { tempIndex = r.nextInt(alphabetSpaceLen); while (tempFlags[tempIndex]) { tempIndex = r.nextInt(alphabetSpaceLen); } tempFlags[tempIndex] = true; dfaConfig.alphabet[i] = dfaConfig.alphabetSpace.charAt(tempIndex); } // faulty event size (make sure it less than a half of alphabet size) int faultEventSize = Math.max(dfaConfig.faultyStateSize / 2, 2); faultEventSize = faultEventSize >= 5 ? 4 : faultEventSize; if (alphabetSize > 15 && (dfaConfig.faultyStateSize / faultEventSize) > 3) { faultEventSize = faultEventSize + r.nextInt(2) + 1; } dfaConfig.faultyEvents = new int[faultEventSize]; LOGGER.debug("Chosen faulty event size: {}", faultEventSize); boolean[] chosenFaultMarks = new boolean[alphabetSize]; int choose; for (int i = 0; i < faultEventSize; i++) { choose = r.nextInt(alphabetSize); while (chosenFaultMarks[choose]) choose = r.nextInt(alphabetSize); chosenFaultMarks[choose] = true; dfaConfig.faultyEvents[i] = choose; } LOGGER.debug("Generated alphabet set: {}", Arrays.toString(dfaConfig.alphabet)); LOGGER.debug("Faulty events (index): {}", Arrays.toString(dfaConfig.faultyEvents)); Set<Integer> faultyEventIndexSet = new HashSet<>(); for (int fi : dfaConfig.faultyEvents) faultyEventIndexSet.add(fi); int ui = 0; int oi = 0; dfaConfig.observableEvents = new char[alphabetSize - faultEventSize]; dfaConfig.unobservableEvents = new char[faultEventSize]; for (int i = 0; i < alphabetSize; i++) { if (faultyEventIndexSet.contains(i)) dfaConfig.unobservableEvents[ui++] = dfaConfig.alphabet[i]; else dfaConfig.observableEvents[oi++] = dfaConfig.alphabet[i]; } LOGGER.debug("selected observable events : {}", Arrays.toString(dfaConfig.observableEvents)); LOGGER.debug("selected unobservable events : {}", Arrays.toString(dfaConfig.unobservableEvents)); }
NONSATD
true
private void initialization(int minXSize, int maxXSize) { // TODO: current implementation is less elegant. code refactoring may be needed. dfaConfig = new DFAConfig(); // allocates a new config every time. Random r = new Random(); dfaConfig.stateSize = r.nextInt((maxXSize - minXSize) + 1) + minXSize; dfaConfig.faultyStateSize = Math.max(dfaConfig.stateSize / 10, 4); LOGGER.debug("Generated overall state size and faulty state size: {}, {}", dfaConfig.stateSize, dfaConfig.faultyStateSize); dfaConfig.states = new int[dfaConfig.stateSize]; for (int i = 0; i < dfaConfig.stateSize; i++) { dfaConfig.states[i] = i; } // alphabet size: range[6 ~ 16] or [10, 20] int base = dfaConfig.stateSize > 20 ? 10 : 6; int alphabetSize = r.nextInt(11) + base; dfaConfig.alphabet = new char[alphabetSize]; LOGGER.debug("Chosen alphabet size is {}", alphabetSize); // randomly fill the alphabet int alphabetSpaceLen = dfaConfig.alphabetSpace.length(); boolean[] tempFlags = new boolean[alphabetSpaceLen]; int tempIndex; for (int i = 0; i < dfaConfig.alphabet.length; i++) { tempIndex = r.nextInt(alphabetSpaceLen); while (tempFlags[tempIndex]) { tempIndex = r.nextInt(alphabetSpaceLen); } tempFlags[tempIndex] = true; dfaConfig.alphabet[i] = dfaConfig.alphabetSpace.charAt(tempIndex); } // faulty event size (make sure it less than a half of alphabet size) int faultEventSize = Math.max(dfaConfig.faultyStateSize / 2, 2); faultEventSize = faultEventSize >= 5 ? 4 : faultEventSize; if (alphabetSize > 15 && (dfaConfig.faultyStateSize / faultEventSize) > 3) { faultEventSize = faultEventSize + r.nextInt(2) + 1; } dfaConfig.faultyEvents = new int[faultEventSize]; LOGGER.debug("Chosen faulty event size: {}", faultEventSize); boolean[] chosenFaultMarks = new boolean[alphabetSize]; int choose; for (int i = 0; i < faultEventSize; i++) { choose = r.nextInt(alphabetSize); while (chosenFaultMarks[choose]) choose = r.nextInt(alphabetSize); chosenFaultMarks[choose] = true; dfaConfig.faultyEvents[i] = choose; } LOGGER.debug("Generated alphabet set: {}", Arrays.toString(dfaConfig.alphabet)); LOGGER.debug("Faulty events (index): {}", Arrays.toString(dfaConfig.faultyEvents)); Set<Integer> faultyEventIndexSet = new HashSet<>(); for (int fi : dfaConfig.faultyEvents) faultyEventIndexSet.add(fi); int ui = 0; int oi = 0; dfaConfig.observableEvents = new char[alphabetSize - faultEventSize]; dfaConfig.unobservableEvents = new char[faultEventSize]; for (int i = 0; i < alphabetSize; i++) { if (faultyEventIndexSet.contains(i)) dfaConfig.unobservableEvents[ui++] = dfaConfig.alphabet[i]; else dfaConfig.observableEvents[oi++] = dfaConfig.alphabet[i]; } LOGGER.debug("selected observable events : {}", Arrays.toString(dfaConfig.observableEvents)); LOGGER.debug("selected unobservable events : {}", Arrays.toString(dfaConfig.unobservableEvents)); }
private void initialization(int minXSize, int maxXSize) { // TODO: current implementation is less elegant. code refactoring may be needed. dfaConfig = new DFAConfig(); // allocates a new config every time. Random r = new Random(); dfaConfig.stateSize = r.nextInt((maxXSize - minXSize) + 1) + minXSize; dfaConfig.faultyStateSize = Math.max(dfaConfig.stateSize / 10, 4); LOGGER.debug("Generated overall state size and faulty state size: {}, {}", dfaConfig.stateSize, dfaConfig.faultyStateSize); dfaConfig.states = new int[dfaConfig.stateSize]; for (int i = 0; i < dfaConfig.stateSize; i++) { dfaConfig.states[i] = i; } // alphabet size: range[6 ~ 16] or [10, 20] int base = dfaConfig.stateSize > 20 ? 10 : 6; int alphabetSize = r.nextInt(11) + base; dfaConfig.alphabet = new char[alphabetSize]; LOGGER.debug("Chosen alphabet size is {}", alphabetSize); // randomly fill the alphabet int alphabetSpaceLen = dfaConfig.alphabetSpace.length(); boolean[] tempFlags = new boolean[alphabetSpaceLen]; int tempIndex; for (int i = 0; i < dfaConfig.alphabet.length; i++) { tempIndex = r.nextInt(alphabetSpaceLen); while (tempFlags[tempIndex]) { tempIndex = r.nextInt(alphabetSpaceLen); } tempFlags[tempIndex] = true; dfaConfig.alphabet[i] = dfaConfig.alphabetSpace.charAt(tempIndex); } // faulty event size (make sure it less than a half of alphabet size) int faultEventSize = Math.max(dfaConfig.faultyStateSize / 2, 2); faultEventSize = faultEventSize >= 5 ? 4 : faultEventSize; if (alphabetSize > 15 && (dfaConfig.faultyStateSize / faultEventSize) > 3) { faultEventSize = faultEventSize + r.nextInt(2) + 1; } dfaConfig.faultyEvents = new int[faultEventSize]; LOGGER.debug("Chosen faulty event size: {}", faultEventSize); boolean[] chosenFaultMarks = new boolean[alphabetSize]; int choose; for (int i = 0; i < faultEventSize; i++) { choose = r.nextInt(alphabetSize); while (chosenFaultMarks[choose]) choose = r.nextInt(alphabetSize); chosenFaultMarks[choose] = true; dfaConfig.faultyEvents[i] = choose; } LOGGER.debug("Generated alphabet set: {}", Arrays.toString(dfaConfig.alphabet)); LOGGER.debug("Faulty events (index): {}", Arrays.toString(dfaConfig.faultyEvents)); Set<Integer> faultyEventIndexSet = new HashSet<>(); for (int fi : dfaConfig.faultyEvents) faultyEventIndexSet.add(fi); int ui = 0; int oi = 0; dfaConfig.observableEvents = new char[alphabetSize - faultEventSize]; dfaConfig.unobservableEvents = new char[faultEventSize]; for (int i = 0; i < alphabetSize; i++) { if (faultyEventIndexSet.contains(i)) dfaConfig.unobservableEvents[ui++] = dfaConfig.alphabet[i]; else dfaConfig.observableEvents[oi++] = dfaConfig.alphabet[i]; } LOGGER.debug("selected observable events : {}", Arrays.toString(dfaConfig.observableEvents)); LOGGER.debug("selected unobservable events : {}", Arrays.toString(dfaConfig.unobservableEvents)); }
private void initialization(int minXSize, int maxXSize) { // TODO: current implementation is less elegant. code refactoring may be needed. dfaConfig = new DFAConfig(); // allocates a new config every time. Random r = new Random(); dfaConfig.stateSize = r.nextInt((maxXSize - minXSize) + 1) + minXSize; dfaConfig.faultyStateSize = Math.max(dfaConfig.stateSize / 10, 4); LOGGER.debug("Generated overall state size and faulty state size: {}, {}", dfaConfig.stateSize, dfaConfig.faultyStateSize); dfaConfig.states = new int[dfaConfig.stateSize]; for (int i = 0; i < dfaConfig.stateSize; i++) { dfaConfig.states[i] = i; } // alphabet size: range[6 ~ 16] or [10, 20] int base = dfaConfig.stateSize > 20 ? 10 : 6; int alphabetSize = r.nextInt(11) + base; dfaConfig.alphabet = new char[alphabetSize]; LOGGER.debug("Chosen alphabet size is {}", alphabetSize); // randomly fill the alphabet int alphabetSpaceLen = dfaConfig.alphabetSpace.length(); boolean[] tempFlags = new boolean[alphabetSpaceLen]; int tempIndex; for (int i = 0; i < dfaConfig.alphabet.length; i++) { tempIndex = r.nextInt(alphabetSpaceLen); while (tempFlags[tempIndex]) { tempIndex = r.nextInt(alphabetSpaceLen); } tempFlags[tempIndex] = true; dfaConfig.alphabet[i] = dfaConfig.alphabetSpace.charAt(tempIndex); } // faulty event size (make sure it less than a half of alphabet size) int faultEventSize = Math.max(dfaConfig.faultyStateSize / 2, 2); faultEventSize = faultEventSize >= 5 ? 4 : faultEventSize; if (alphabetSize > 15 && (dfaConfig.faultyStateSize / faultEventSize) > 3) { faultEventSize = faultEventSize + r.nextInt(2) + 1; } dfaConfig.faultyEvents = new int[faultEventSize]; LOGGER.debug("Chosen faulty event size: {}", faultEventSize); boolean[] chosenFaultMarks = new boolean[alphabetSize]; int choose; for (int i = 0; i < faultEventSize; i++) { choose = r.nextInt(alphabetSize); while (chosenFaultMarks[choose]) choose = r.nextInt(alphabetSize); chosenFaultMarks[choose] = true; dfaConfig.faultyEvents[i] = choose; } LOGGER.debug("Generated alphabet set: {}", Arrays.toString(dfaConfig.alphabet)); LOGGER.debug("Faulty events (index): {}", Arrays.toString(dfaConfig.faultyEvents)); Set<Integer> faultyEventIndexSet = new HashSet<>(); for (int fi : dfaConfig.faultyEvents) faultyEventIndexSet.add(fi); int ui = 0; int oi = 0; dfaConfig.observableEvents = new char[alphabetSize - faultEventSize]; dfaConfig.unobservableEvents = new char[faultEventSize]; for (int i = 0; i < alphabetSize; i++) { if (faultyEventIndexSet.contains(i)) dfaConfig.unobservableEvents[ui++] = dfaConfig.alphabet[i]; else dfaConfig.observableEvents[oi++] = dfaConfig.alphabet[i]; } LOGGER.debug("selected observable events : {}", Arrays.toString(dfaConfig.observableEvents)); LOGGER.debug("selected unobservable events : {}", Arrays.toString(dfaConfig.unobservableEvents)); }
1,494
1
// TODO: current implementation is less elegant. code refactoring may be needed.
private void initialization(int minXSize, int maxXSize) { // TODO: current implementation is less elegant. code refactoring may be needed. dfaConfig = new DFAConfig(); // allocates a new config every time. Random r = new Random(); dfaConfig.stateSize = r.nextInt((maxXSize - minXSize) + 1) + minXSize; dfaConfig.faultyStateSize = Math.max(dfaConfig.stateSize / 10, 4); LOGGER.debug("Generated overall state size and faulty state size: {}, {}", dfaConfig.stateSize, dfaConfig.faultyStateSize); dfaConfig.states = new int[dfaConfig.stateSize]; for (int i = 0; i < dfaConfig.stateSize; i++) { dfaConfig.states[i] = i; } // alphabet size: range[6 ~ 16] or [10, 20] int base = dfaConfig.stateSize > 20 ? 10 : 6; int alphabetSize = r.nextInt(11) + base; dfaConfig.alphabet = new char[alphabetSize]; LOGGER.debug("Chosen alphabet size is {}", alphabetSize); // randomly fill the alphabet int alphabetSpaceLen = dfaConfig.alphabetSpace.length(); boolean[] tempFlags = new boolean[alphabetSpaceLen]; int tempIndex; for (int i = 0; i < dfaConfig.alphabet.length; i++) { tempIndex = r.nextInt(alphabetSpaceLen); while (tempFlags[tempIndex]) { tempIndex = r.nextInt(alphabetSpaceLen); } tempFlags[tempIndex] = true; dfaConfig.alphabet[i] = dfaConfig.alphabetSpace.charAt(tempIndex); } // faulty event size (make sure it less than a half of alphabet size) int faultEventSize = Math.max(dfaConfig.faultyStateSize / 2, 2); faultEventSize = faultEventSize >= 5 ? 4 : faultEventSize; if (alphabetSize > 15 && (dfaConfig.faultyStateSize / faultEventSize) > 3) { faultEventSize = faultEventSize + r.nextInt(2) + 1; } dfaConfig.faultyEvents = new int[faultEventSize]; LOGGER.debug("Chosen faulty event size: {}", faultEventSize); boolean[] chosenFaultMarks = new boolean[alphabetSize]; int choose; for (int i = 0; i < faultEventSize; i++) { choose = r.nextInt(alphabetSize); while (chosenFaultMarks[choose]) choose = r.nextInt(alphabetSize); chosenFaultMarks[choose] = true; dfaConfig.faultyEvents[i] = choose; } LOGGER.debug("Generated alphabet set: {}", Arrays.toString(dfaConfig.alphabet)); LOGGER.debug("Faulty events (index): {}", Arrays.toString(dfaConfig.faultyEvents)); Set<Integer> faultyEventIndexSet = new HashSet<>(); for (int fi : dfaConfig.faultyEvents) faultyEventIndexSet.add(fi); int ui = 0; int oi = 0; dfaConfig.observableEvents = new char[alphabetSize - faultEventSize]; dfaConfig.unobservableEvents = new char[faultEventSize]; for (int i = 0; i < alphabetSize; i++) { if (faultyEventIndexSet.contains(i)) dfaConfig.unobservableEvents[ui++] = dfaConfig.alphabet[i]; else dfaConfig.observableEvents[oi++] = dfaConfig.alphabet[i]; } LOGGER.debug("selected observable events : {}", Arrays.toString(dfaConfig.observableEvents)); LOGGER.debug("selected unobservable events : {}", Arrays.toString(dfaConfig.unobservableEvents)); }
DESIGN
true
private void initialization(int minXSize, int maxXSize) { // TODO: current implementation is less elegant. code refactoring may be needed. dfaConfig = new DFAConfig(); // allocates a new config every time. Random r = new Random();
private void initialization(int minXSize, int maxXSize) { // TODO: current implementation is less elegant. code refactoring may be needed. dfaConfig = new DFAConfig(); // allocates a new config every time. Random r = new Random(); dfaConfig.stateSize = r.nextInt((maxXSize - minXSize) + 1) + minXSize; dfaConfig.faultyStateSize = Math.max(dfaConfig.stateSize / 10, 4); LOGGER.debug("Generated overall state size and faulty state size: {}, {}", dfaConfig.stateSize, dfaConfig.faultyStateSize); dfaConfig.states = new int[dfaConfig.stateSize]; for (int i = 0; i < dfaConfig.stateSize; i++) { dfaConfig.states[i] = i; }
private void initialization(int minXSize, int maxXSize) { // TODO: current implementation is less elegant. code refactoring may be needed. dfaConfig = new DFAConfig(); // allocates a new config every time. Random r = new Random(); dfaConfig.stateSize = r.nextInt((maxXSize - minXSize) + 1) + minXSize; dfaConfig.faultyStateSize = Math.max(dfaConfig.stateSize / 10, 4); LOGGER.debug("Generated overall state size and faulty state size: {}, {}", dfaConfig.stateSize, dfaConfig.faultyStateSize); dfaConfig.states = new int[dfaConfig.stateSize]; for (int i = 0; i < dfaConfig.stateSize; i++) { dfaConfig.states[i] = i; } // alphabet size: range[6 ~ 16] or [10, 20] int base = dfaConfig.stateSize > 20 ? 10 : 6; int alphabetSize = r.nextInt(11) + base; dfaConfig.alphabet = new char[alphabetSize]; LOGGER.debug("Chosen alphabet size is {}", alphabetSize); // randomly fill the alphabet int alphabetSpaceLen = dfaConfig.alphabetSpace.length(); boolean[] tempFlags = new boolean[alphabetSpaceLen]; int tempIndex; for (int i = 0; i < dfaConfig.alphabet.length; i++) {
1,494
2
// allocates a new config every time.
private void initialization(int minXSize, int maxXSize) { // TODO: current implementation is less elegant. code refactoring may be needed. dfaConfig = new DFAConfig(); // allocates a new config every time. Random r = new Random(); dfaConfig.stateSize = r.nextInt((maxXSize - minXSize) + 1) + minXSize; dfaConfig.faultyStateSize = Math.max(dfaConfig.stateSize / 10, 4); LOGGER.debug("Generated overall state size and faulty state size: {}, {}", dfaConfig.stateSize, dfaConfig.faultyStateSize); dfaConfig.states = new int[dfaConfig.stateSize]; for (int i = 0; i < dfaConfig.stateSize; i++) { dfaConfig.states[i] = i; } // alphabet size: range[6 ~ 16] or [10, 20] int base = dfaConfig.stateSize > 20 ? 10 : 6; int alphabetSize = r.nextInt(11) + base; dfaConfig.alphabet = new char[alphabetSize]; LOGGER.debug("Chosen alphabet size is {}", alphabetSize); // randomly fill the alphabet int alphabetSpaceLen = dfaConfig.alphabetSpace.length(); boolean[] tempFlags = new boolean[alphabetSpaceLen]; int tempIndex; for (int i = 0; i < dfaConfig.alphabet.length; i++) { tempIndex = r.nextInt(alphabetSpaceLen); while (tempFlags[tempIndex]) { tempIndex = r.nextInt(alphabetSpaceLen); } tempFlags[tempIndex] = true; dfaConfig.alphabet[i] = dfaConfig.alphabetSpace.charAt(tempIndex); } // faulty event size (make sure it less than a half of alphabet size) int faultEventSize = Math.max(dfaConfig.faultyStateSize / 2, 2); faultEventSize = faultEventSize >= 5 ? 4 : faultEventSize; if (alphabetSize > 15 && (dfaConfig.faultyStateSize / faultEventSize) > 3) { faultEventSize = faultEventSize + r.nextInt(2) + 1; } dfaConfig.faultyEvents = new int[faultEventSize]; LOGGER.debug("Chosen faulty event size: {}", faultEventSize); boolean[] chosenFaultMarks = new boolean[alphabetSize]; int choose; for (int i = 0; i < faultEventSize; i++) { choose = r.nextInt(alphabetSize); while (chosenFaultMarks[choose]) choose = r.nextInt(alphabetSize); chosenFaultMarks[choose] = true; dfaConfig.faultyEvents[i] = choose; } LOGGER.debug("Generated alphabet set: {}", Arrays.toString(dfaConfig.alphabet)); LOGGER.debug("Faulty events (index): {}", Arrays.toString(dfaConfig.faultyEvents)); Set<Integer> faultyEventIndexSet = new HashSet<>(); for (int fi : dfaConfig.faultyEvents) faultyEventIndexSet.add(fi); int ui = 0; int oi = 0; dfaConfig.observableEvents = new char[alphabetSize - faultEventSize]; dfaConfig.unobservableEvents = new char[faultEventSize]; for (int i = 0; i < alphabetSize; i++) { if (faultyEventIndexSet.contains(i)) dfaConfig.unobservableEvents[ui++] = dfaConfig.alphabet[i]; else dfaConfig.observableEvents[oi++] = dfaConfig.alphabet[i]; } LOGGER.debug("selected observable events : {}", Arrays.toString(dfaConfig.observableEvents)); LOGGER.debug("selected unobservable events : {}", Arrays.toString(dfaConfig.unobservableEvents)); }
NONSATD
true
private void initialization(int minXSize, int maxXSize) { // TODO: current implementation is less elegant. code refactoring may be needed. dfaConfig = new DFAConfig(); // allocates a new config every time. Random r = new Random(); dfaConfig.stateSize = r.nextInt((maxXSize - minXSize) + 1) + minXSize;
private void initialization(int minXSize, int maxXSize) { // TODO: current implementation is less elegant. code refactoring may be needed. dfaConfig = new DFAConfig(); // allocates a new config every time. Random r = new Random(); dfaConfig.stateSize = r.nextInt((maxXSize - minXSize) + 1) + minXSize; dfaConfig.faultyStateSize = Math.max(dfaConfig.stateSize / 10, 4); LOGGER.debug("Generated overall state size and faulty state size: {}, {}", dfaConfig.stateSize, dfaConfig.faultyStateSize); dfaConfig.states = new int[dfaConfig.stateSize]; for (int i = 0; i < dfaConfig.stateSize; i++) { dfaConfig.states[i] = i; } // alphabet size: range[6 ~ 16] or [10, 20]
private void initialization(int minXSize, int maxXSize) { // TODO: current implementation is less elegant. code refactoring may be needed. dfaConfig = new DFAConfig(); // allocates a new config every time. Random r = new Random(); dfaConfig.stateSize = r.nextInt((maxXSize - minXSize) + 1) + minXSize; dfaConfig.faultyStateSize = Math.max(dfaConfig.stateSize / 10, 4); LOGGER.debug("Generated overall state size and faulty state size: {}, {}", dfaConfig.stateSize, dfaConfig.faultyStateSize); dfaConfig.states = new int[dfaConfig.stateSize]; for (int i = 0; i < dfaConfig.stateSize; i++) { dfaConfig.states[i] = i; } // alphabet size: range[6 ~ 16] or [10, 20] int base = dfaConfig.stateSize > 20 ? 10 : 6; int alphabetSize = r.nextInt(11) + base; dfaConfig.alphabet = new char[alphabetSize]; LOGGER.debug("Chosen alphabet size is {}", alphabetSize); // randomly fill the alphabet int alphabetSpaceLen = dfaConfig.alphabetSpace.length(); boolean[] tempFlags = new boolean[alphabetSpaceLen]; int tempIndex; for (int i = 0; i < dfaConfig.alphabet.length; i++) { tempIndex = r.nextInt(alphabetSpaceLen);
1,494
3
// alphabet size: range[6 ~ 16] or [10, 20]
private void initialization(int minXSize, int maxXSize) { // TODO: current implementation is less elegant. code refactoring may be needed. dfaConfig = new DFAConfig(); // allocates a new config every time. Random r = new Random(); dfaConfig.stateSize = r.nextInt((maxXSize - minXSize) + 1) + minXSize; dfaConfig.faultyStateSize = Math.max(dfaConfig.stateSize / 10, 4); LOGGER.debug("Generated overall state size and faulty state size: {}, {}", dfaConfig.stateSize, dfaConfig.faultyStateSize); dfaConfig.states = new int[dfaConfig.stateSize]; for (int i = 0; i < dfaConfig.stateSize; i++) { dfaConfig.states[i] = i; } // alphabet size: range[6 ~ 16] or [10, 20] int base = dfaConfig.stateSize > 20 ? 10 : 6; int alphabetSize = r.nextInt(11) + base; dfaConfig.alphabet = new char[alphabetSize]; LOGGER.debug("Chosen alphabet size is {}", alphabetSize); // randomly fill the alphabet int alphabetSpaceLen = dfaConfig.alphabetSpace.length(); boolean[] tempFlags = new boolean[alphabetSpaceLen]; int tempIndex; for (int i = 0; i < dfaConfig.alphabet.length; i++) { tempIndex = r.nextInt(alphabetSpaceLen); while (tempFlags[tempIndex]) { tempIndex = r.nextInt(alphabetSpaceLen); } tempFlags[tempIndex] = true; dfaConfig.alphabet[i] = dfaConfig.alphabetSpace.charAt(tempIndex); } // faulty event size (make sure it less than a half of alphabet size) int faultEventSize = Math.max(dfaConfig.faultyStateSize / 2, 2); faultEventSize = faultEventSize >= 5 ? 4 : faultEventSize; if (alphabetSize > 15 && (dfaConfig.faultyStateSize / faultEventSize) > 3) { faultEventSize = faultEventSize + r.nextInt(2) + 1; } dfaConfig.faultyEvents = new int[faultEventSize]; LOGGER.debug("Chosen faulty event size: {}", faultEventSize); boolean[] chosenFaultMarks = new boolean[alphabetSize]; int choose; for (int i = 0; i < faultEventSize; i++) { choose = r.nextInt(alphabetSize); while (chosenFaultMarks[choose]) choose = r.nextInt(alphabetSize); chosenFaultMarks[choose] = true; dfaConfig.faultyEvents[i] = choose; } LOGGER.debug("Generated alphabet set: {}", Arrays.toString(dfaConfig.alphabet)); LOGGER.debug("Faulty events (index): {}", Arrays.toString(dfaConfig.faultyEvents)); Set<Integer> faultyEventIndexSet = new HashSet<>(); for (int fi : dfaConfig.faultyEvents) faultyEventIndexSet.add(fi); int ui = 0; int oi = 0; dfaConfig.observableEvents = new char[alphabetSize - faultEventSize]; dfaConfig.unobservableEvents = new char[faultEventSize]; for (int i = 0; i < alphabetSize; i++) { if (faultyEventIndexSet.contains(i)) dfaConfig.unobservableEvents[ui++] = dfaConfig.alphabet[i]; else dfaConfig.observableEvents[oi++] = dfaConfig.alphabet[i]; } LOGGER.debug("selected observable events : {}", Arrays.toString(dfaConfig.observableEvents)); LOGGER.debug("selected unobservable events : {}", Arrays.toString(dfaConfig.unobservableEvents)); }
NONSATD
true
dfaConfig.states[i] = i; } // alphabet size: range[6 ~ 16] or [10, 20] int base = dfaConfig.stateSize > 20 ? 10 : 6; int alphabetSize = r.nextInt(11) + base;
dfaConfig = new DFAConfig(); // allocates a new config every time. Random r = new Random(); dfaConfig.stateSize = r.nextInt((maxXSize - minXSize) + 1) + minXSize; dfaConfig.faultyStateSize = Math.max(dfaConfig.stateSize / 10, 4); LOGGER.debug("Generated overall state size and faulty state size: {}, {}", dfaConfig.stateSize, dfaConfig.faultyStateSize); dfaConfig.states = new int[dfaConfig.stateSize]; for (int i = 0; i < dfaConfig.stateSize; i++) { dfaConfig.states[i] = i; } // alphabet size: range[6 ~ 16] or [10, 20] int base = dfaConfig.stateSize > 20 ? 10 : 6; int alphabetSize = r.nextInt(11) + base; dfaConfig.alphabet = new char[alphabetSize]; LOGGER.debug("Chosen alphabet size is {}", alphabetSize); // randomly fill the alphabet int alphabetSpaceLen = dfaConfig.alphabetSpace.length(); boolean[] tempFlags = new boolean[alphabetSpaceLen]; int tempIndex; for (int i = 0; i < dfaConfig.alphabet.length; i++) { tempIndex = r.nextInt(alphabetSpaceLen);
private void initialization(int minXSize, int maxXSize) { // TODO: current implementation is less elegant. code refactoring may be needed. dfaConfig = new DFAConfig(); // allocates a new config every time. Random r = new Random(); dfaConfig.stateSize = r.nextInt((maxXSize - minXSize) + 1) + minXSize; dfaConfig.faultyStateSize = Math.max(dfaConfig.stateSize / 10, 4); LOGGER.debug("Generated overall state size and faulty state size: {}, {}", dfaConfig.stateSize, dfaConfig.faultyStateSize); dfaConfig.states = new int[dfaConfig.stateSize]; for (int i = 0; i < dfaConfig.stateSize; i++) { dfaConfig.states[i] = i; } // alphabet size: range[6 ~ 16] or [10, 20] int base = dfaConfig.stateSize > 20 ? 10 : 6; int alphabetSize = r.nextInt(11) + base; dfaConfig.alphabet = new char[alphabetSize]; LOGGER.debug("Chosen alphabet size is {}", alphabetSize); // randomly fill the alphabet int alphabetSpaceLen = dfaConfig.alphabetSpace.length(); boolean[] tempFlags = new boolean[alphabetSpaceLen]; int tempIndex; for (int i = 0; i < dfaConfig.alphabet.length; i++) { tempIndex = r.nextInt(alphabetSpaceLen); while (tempFlags[tempIndex]) { tempIndex = r.nextInt(alphabetSpaceLen); } tempFlags[tempIndex] = true; dfaConfig.alphabet[i] = dfaConfig.alphabetSpace.charAt(tempIndex); } // faulty event size (make sure it less than a half of alphabet size) int faultEventSize = Math.max(dfaConfig.faultyStateSize / 2, 2); faultEventSize = faultEventSize >= 5 ? 4 : faultEventSize; if (alphabetSize > 15 && (dfaConfig.faultyStateSize / faultEventSize) > 3) {
1,494
4
// randomly fill the alphabet
private void initialization(int minXSize, int maxXSize) { // TODO: current implementation is less elegant. code refactoring may be needed. dfaConfig = new DFAConfig(); // allocates a new config every time. Random r = new Random(); dfaConfig.stateSize = r.nextInt((maxXSize - minXSize) + 1) + minXSize; dfaConfig.faultyStateSize = Math.max(dfaConfig.stateSize / 10, 4); LOGGER.debug("Generated overall state size and faulty state size: {}, {}", dfaConfig.stateSize, dfaConfig.faultyStateSize); dfaConfig.states = new int[dfaConfig.stateSize]; for (int i = 0; i < dfaConfig.stateSize; i++) { dfaConfig.states[i] = i; } // alphabet size: range[6 ~ 16] or [10, 20] int base = dfaConfig.stateSize > 20 ? 10 : 6; int alphabetSize = r.nextInt(11) + base; dfaConfig.alphabet = new char[alphabetSize]; LOGGER.debug("Chosen alphabet size is {}", alphabetSize); // randomly fill the alphabet int alphabetSpaceLen = dfaConfig.alphabetSpace.length(); boolean[] tempFlags = new boolean[alphabetSpaceLen]; int tempIndex; for (int i = 0; i < dfaConfig.alphabet.length; i++) { tempIndex = r.nextInt(alphabetSpaceLen); while (tempFlags[tempIndex]) { tempIndex = r.nextInt(alphabetSpaceLen); } tempFlags[tempIndex] = true; dfaConfig.alphabet[i] = dfaConfig.alphabetSpace.charAt(tempIndex); } // faulty event size (make sure it less than a half of alphabet size) int faultEventSize = Math.max(dfaConfig.faultyStateSize / 2, 2); faultEventSize = faultEventSize >= 5 ? 4 : faultEventSize; if (alphabetSize > 15 && (dfaConfig.faultyStateSize / faultEventSize) > 3) { faultEventSize = faultEventSize + r.nextInt(2) + 1; } dfaConfig.faultyEvents = new int[faultEventSize]; LOGGER.debug("Chosen faulty event size: {}", faultEventSize); boolean[] chosenFaultMarks = new boolean[alphabetSize]; int choose; for (int i = 0; i < faultEventSize; i++) { choose = r.nextInt(alphabetSize); while (chosenFaultMarks[choose]) choose = r.nextInt(alphabetSize); chosenFaultMarks[choose] = true; dfaConfig.faultyEvents[i] = choose; } LOGGER.debug("Generated alphabet set: {}", Arrays.toString(dfaConfig.alphabet)); LOGGER.debug("Faulty events (index): {}", Arrays.toString(dfaConfig.faultyEvents)); Set<Integer> faultyEventIndexSet = new HashSet<>(); for (int fi : dfaConfig.faultyEvents) faultyEventIndexSet.add(fi); int ui = 0; int oi = 0; dfaConfig.observableEvents = new char[alphabetSize - faultEventSize]; dfaConfig.unobservableEvents = new char[faultEventSize]; for (int i = 0; i < alphabetSize; i++) { if (faultyEventIndexSet.contains(i)) dfaConfig.unobservableEvents[ui++] = dfaConfig.alphabet[i]; else dfaConfig.observableEvents[oi++] = dfaConfig.alphabet[i]; } LOGGER.debug("selected observable events : {}", Arrays.toString(dfaConfig.observableEvents)); LOGGER.debug("selected unobservable events : {}", Arrays.toString(dfaConfig.unobservableEvents)); }
NONSATD
true
dfaConfig.alphabet = new char[alphabetSize]; LOGGER.debug("Chosen alphabet size is {}", alphabetSize); // randomly fill the alphabet int alphabetSpaceLen = dfaConfig.alphabetSpace.length(); boolean[] tempFlags = new boolean[alphabetSpaceLen];
dfaConfig.stateSize, dfaConfig.faultyStateSize); dfaConfig.states = new int[dfaConfig.stateSize]; for (int i = 0; i < dfaConfig.stateSize; i++) { dfaConfig.states[i] = i; } // alphabet size: range[6 ~ 16] or [10, 20] int base = dfaConfig.stateSize > 20 ? 10 : 6; int alphabetSize = r.nextInt(11) + base; dfaConfig.alphabet = new char[alphabetSize]; LOGGER.debug("Chosen alphabet size is {}", alphabetSize); // randomly fill the alphabet int alphabetSpaceLen = dfaConfig.alphabetSpace.length(); boolean[] tempFlags = new boolean[alphabetSpaceLen]; int tempIndex; for (int i = 0; i < dfaConfig.alphabet.length; i++) { tempIndex = r.nextInt(alphabetSpaceLen); while (tempFlags[tempIndex]) { tempIndex = r.nextInt(alphabetSpaceLen); } tempFlags[tempIndex] = true; dfaConfig.alphabet[i] = dfaConfig.alphabetSpace.charAt(tempIndex);
private void initialization(int minXSize, int maxXSize) { // TODO: current implementation is less elegant. code refactoring may be needed. dfaConfig = new DFAConfig(); // allocates a new config every time. Random r = new Random(); dfaConfig.stateSize = r.nextInt((maxXSize - minXSize) + 1) + minXSize; dfaConfig.faultyStateSize = Math.max(dfaConfig.stateSize / 10, 4); LOGGER.debug("Generated overall state size and faulty state size: {}, {}", dfaConfig.stateSize, dfaConfig.faultyStateSize); dfaConfig.states = new int[dfaConfig.stateSize]; for (int i = 0; i < dfaConfig.stateSize; i++) { dfaConfig.states[i] = i; } // alphabet size: range[6 ~ 16] or [10, 20] int base = dfaConfig.stateSize > 20 ? 10 : 6; int alphabetSize = r.nextInt(11) + base; dfaConfig.alphabet = new char[alphabetSize]; LOGGER.debug("Chosen alphabet size is {}", alphabetSize); // randomly fill the alphabet int alphabetSpaceLen = dfaConfig.alphabetSpace.length(); boolean[] tempFlags = new boolean[alphabetSpaceLen]; int tempIndex; for (int i = 0; i < dfaConfig.alphabet.length; i++) { tempIndex = r.nextInt(alphabetSpaceLen); while (tempFlags[tempIndex]) { tempIndex = r.nextInt(alphabetSpaceLen); } tempFlags[tempIndex] = true; dfaConfig.alphabet[i] = dfaConfig.alphabetSpace.charAt(tempIndex); } // faulty event size (make sure it less than a half of alphabet size) int faultEventSize = Math.max(dfaConfig.faultyStateSize / 2, 2); faultEventSize = faultEventSize >= 5 ? 4 : faultEventSize; if (alphabetSize > 15 && (dfaConfig.faultyStateSize / faultEventSize) > 3) { faultEventSize = faultEventSize + r.nextInt(2) + 1; } dfaConfig.faultyEvents = new int[faultEventSize]; LOGGER.debug("Chosen faulty event size: {}", faultEventSize); boolean[] chosenFaultMarks = new boolean[alphabetSize];
1,494
5
// faulty event size (make sure it less than a half of alphabet size)
private void initialization(int minXSize, int maxXSize) { // TODO: current implementation is less elegant. code refactoring may be needed. dfaConfig = new DFAConfig(); // allocates a new config every time. Random r = new Random(); dfaConfig.stateSize = r.nextInt((maxXSize - minXSize) + 1) + minXSize; dfaConfig.faultyStateSize = Math.max(dfaConfig.stateSize / 10, 4); LOGGER.debug("Generated overall state size and faulty state size: {}, {}", dfaConfig.stateSize, dfaConfig.faultyStateSize); dfaConfig.states = new int[dfaConfig.stateSize]; for (int i = 0; i < dfaConfig.stateSize; i++) { dfaConfig.states[i] = i; } // alphabet size: range[6 ~ 16] or [10, 20] int base = dfaConfig.stateSize > 20 ? 10 : 6; int alphabetSize = r.nextInt(11) + base; dfaConfig.alphabet = new char[alphabetSize]; LOGGER.debug("Chosen alphabet size is {}", alphabetSize); // randomly fill the alphabet int alphabetSpaceLen = dfaConfig.alphabetSpace.length(); boolean[] tempFlags = new boolean[alphabetSpaceLen]; int tempIndex; for (int i = 0; i < dfaConfig.alphabet.length; i++) { tempIndex = r.nextInt(alphabetSpaceLen); while (tempFlags[tempIndex]) { tempIndex = r.nextInt(alphabetSpaceLen); } tempFlags[tempIndex] = true; dfaConfig.alphabet[i] = dfaConfig.alphabetSpace.charAt(tempIndex); } // faulty event size (make sure it less than a half of alphabet size) int faultEventSize = Math.max(dfaConfig.faultyStateSize / 2, 2); faultEventSize = faultEventSize >= 5 ? 4 : faultEventSize; if (alphabetSize > 15 && (dfaConfig.faultyStateSize / faultEventSize) > 3) { faultEventSize = faultEventSize + r.nextInt(2) + 1; } dfaConfig.faultyEvents = new int[faultEventSize]; LOGGER.debug("Chosen faulty event size: {}", faultEventSize); boolean[] chosenFaultMarks = new boolean[alphabetSize]; int choose; for (int i = 0; i < faultEventSize; i++) { choose = r.nextInt(alphabetSize); while (chosenFaultMarks[choose]) choose = r.nextInt(alphabetSize); chosenFaultMarks[choose] = true; dfaConfig.faultyEvents[i] = choose; } LOGGER.debug("Generated alphabet set: {}", Arrays.toString(dfaConfig.alphabet)); LOGGER.debug("Faulty events (index): {}", Arrays.toString(dfaConfig.faultyEvents)); Set<Integer> faultyEventIndexSet = new HashSet<>(); for (int fi : dfaConfig.faultyEvents) faultyEventIndexSet.add(fi); int ui = 0; int oi = 0; dfaConfig.observableEvents = new char[alphabetSize - faultEventSize]; dfaConfig.unobservableEvents = new char[faultEventSize]; for (int i = 0; i < alphabetSize; i++) { if (faultyEventIndexSet.contains(i)) dfaConfig.unobservableEvents[ui++] = dfaConfig.alphabet[i]; else dfaConfig.observableEvents[oi++] = dfaConfig.alphabet[i]; } LOGGER.debug("selected observable events : {}", Arrays.toString(dfaConfig.observableEvents)); LOGGER.debug("selected unobservable events : {}", Arrays.toString(dfaConfig.unobservableEvents)); }
NONSATD
true
dfaConfig.alphabet[i] = dfaConfig.alphabetSpace.charAt(tempIndex); } // faulty event size (make sure it less than a half of alphabet size) int faultEventSize = Math.max(dfaConfig.faultyStateSize / 2, 2); faultEventSize = faultEventSize >= 5 ? 4 : faultEventSize;
boolean[] tempFlags = new boolean[alphabetSpaceLen]; int tempIndex; for (int i = 0; i < dfaConfig.alphabet.length; i++) { tempIndex = r.nextInt(alphabetSpaceLen); while (tempFlags[tempIndex]) { tempIndex = r.nextInt(alphabetSpaceLen); } tempFlags[tempIndex] = true; dfaConfig.alphabet[i] = dfaConfig.alphabetSpace.charAt(tempIndex); } // faulty event size (make sure it less than a half of alphabet size) int faultEventSize = Math.max(dfaConfig.faultyStateSize / 2, 2); faultEventSize = faultEventSize >= 5 ? 4 : faultEventSize; if (alphabetSize > 15 && (dfaConfig.faultyStateSize / faultEventSize) > 3) { faultEventSize = faultEventSize + r.nextInt(2) + 1; } dfaConfig.faultyEvents = new int[faultEventSize]; LOGGER.debug("Chosen faulty event size: {}", faultEventSize); boolean[] chosenFaultMarks = new boolean[alphabetSize]; int choose; for (int i = 0; i < faultEventSize; i++) {
for (int i = 0; i < dfaConfig.stateSize; i++) { dfaConfig.states[i] = i; } // alphabet size: range[6 ~ 16] or [10, 20] int base = dfaConfig.stateSize > 20 ? 10 : 6; int alphabetSize = r.nextInt(11) + base; dfaConfig.alphabet = new char[alphabetSize]; LOGGER.debug("Chosen alphabet size is {}", alphabetSize); // randomly fill the alphabet int alphabetSpaceLen = dfaConfig.alphabetSpace.length(); boolean[] tempFlags = new boolean[alphabetSpaceLen]; int tempIndex; for (int i = 0; i < dfaConfig.alphabet.length; i++) { tempIndex = r.nextInt(alphabetSpaceLen); while (tempFlags[tempIndex]) { tempIndex = r.nextInt(alphabetSpaceLen); } tempFlags[tempIndex] = true; dfaConfig.alphabet[i] = dfaConfig.alphabetSpace.charAt(tempIndex); } // faulty event size (make sure it less than a half of alphabet size) int faultEventSize = Math.max(dfaConfig.faultyStateSize / 2, 2); faultEventSize = faultEventSize >= 5 ? 4 : faultEventSize; if (alphabetSize > 15 && (dfaConfig.faultyStateSize / faultEventSize) > 3) { faultEventSize = faultEventSize + r.nextInt(2) + 1; } dfaConfig.faultyEvents = new int[faultEventSize]; LOGGER.debug("Chosen faulty event size: {}", faultEventSize); boolean[] chosenFaultMarks = new boolean[alphabetSize]; int choose; for (int i = 0; i < faultEventSize; i++) { choose = r.nextInt(alphabetSize); while (chosenFaultMarks[choose]) choose = r.nextInt(alphabetSize); chosenFaultMarks[choose] = true; dfaConfig.faultyEvents[i] = choose; } LOGGER.debug("Generated alphabet set: {}", Arrays.toString(dfaConfig.alphabet)); LOGGER.debug("Faulty events (index): {}", Arrays.toString(dfaConfig.faultyEvents)); Set<Integer> faultyEventIndexSet = new HashSet<>(); for (int fi : dfaConfig.faultyEvents)
34,283
0
// TODO: actually implement this lol
@Override public BiomeProvider load(AnnotatedType t, Object c, ConfigLoader loader) throws LoadException { return loader.loadType(BiomePipelineProvider.class, c); // TODO: actually implement this lol }
IMPLEMENTATION
true
@Override public BiomeProvider load(AnnotatedType t, Object c, ConfigLoader loader) throws LoadException { return loader.loadType(BiomePipelineProvider.class, c); // TODO: actually implement this lol }
@Override public BiomeProvider load(AnnotatedType t, Object c, ConfigLoader loader) throws LoadException { return loader.loadType(BiomePipelineProvider.class, c); // TODO: actually implement this lol }
@Override public BiomeProvider load(AnnotatedType t, Object c, ConfigLoader loader) throws LoadException { return loader.loadType(BiomePipelineProvider.class, c); // TODO: actually implement this lol }
34,311
0
// Like Junit4, J2CL always counts errors as failures
private void assertTestSummary() { int fails = testResult.fails().size(); int errors = testResult.errors().size(); int succeeds = testResult.succeeds().size(); int testCount = fails + errors + succeeds; if (testMode.isJ2cl()) { // Like Junit4, J2CL always counts errors as failures fails += errors; errors = 0; // TODO(b/32608089): jsunit_test does not report number of tests correctly testCount = 1; // Since total number of tests cannot be asserted; ensure nummber of succeeds is correct. assertThat(consoleLogs.stream().filter(x -> x.contains(": PASSED"))).hasSize(succeeds); } if (fails + errors > 0) { assertTestSummaryForFailure(fails, errors, testCount); } else { assertTestSummaryForSuccess(testCount); } }
NONSATD
true
int testCount = fails + errors + succeeds; if (testMode.isJ2cl()) { // Like Junit4, J2CL always counts errors as failures fails += errors; errors = 0;
private void assertTestSummary() { int fails = testResult.fails().size(); int errors = testResult.errors().size(); int succeeds = testResult.succeeds().size(); int testCount = fails + errors + succeeds; if (testMode.isJ2cl()) { // Like Junit4, J2CL always counts errors as failures fails += errors; errors = 0; // TODO(b/32608089): jsunit_test does not report number of tests correctly testCount = 1; // Since total number of tests cannot be asserted; ensure nummber of succeeds is correct. assertThat(consoleLogs.stream().filter(x -> x.contains(": PASSED"))).hasSize(succeeds); } if (fails + errors > 0) { assertTestSummaryForFailure(fails, errors, testCount); } else {
private void assertTestSummary() { int fails = testResult.fails().size(); int errors = testResult.errors().size(); int succeeds = testResult.succeeds().size(); int testCount = fails + errors + succeeds; if (testMode.isJ2cl()) { // Like Junit4, J2CL always counts errors as failures fails += errors; errors = 0; // TODO(b/32608089): jsunit_test does not report number of tests correctly testCount = 1; // Since total number of tests cannot be asserted; ensure nummber of succeeds is correct. assertThat(consoleLogs.stream().filter(x -> x.contains(": PASSED"))).hasSize(succeeds); } if (fails + errors > 0) { assertTestSummaryForFailure(fails, errors, testCount); } else { assertTestSummaryForSuccess(testCount); } }
34,311
1
// TODO(b/32608089): jsunit_test does not report number of tests correctly
private void assertTestSummary() { int fails = testResult.fails().size(); int errors = testResult.errors().size(); int succeeds = testResult.succeeds().size(); int testCount = fails + errors + succeeds; if (testMode.isJ2cl()) { // Like Junit4, J2CL always counts errors as failures fails += errors; errors = 0; // TODO(b/32608089): jsunit_test does not report number of tests correctly testCount = 1; // Since total number of tests cannot be asserted; ensure nummber of succeeds is correct. assertThat(consoleLogs.stream().filter(x -> x.contains(": PASSED"))).hasSize(succeeds); } if (fails + errors > 0) { assertTestSummaryForFailure(fails, errors, testCount); } else { assertTestSummaryForSuccess(testCount); } }
DEFECT
true
fails += errors; errors = 0; // TODO(b/32608089): jsunit_test does not report number of tests correctly testCount = 1; // Since total number of tests cannot be asserted; ensure nummber of succeeds is correct.
private void assertTestSummary() { int fails = testResult.fails().size(); int errors = testResult.errors().size(); int succeeds = testResult.succeeds().size(); int testCount = fails + errors + succeeds; if (testMode.isJ2cl()) { // Like Junit4, J2CL always counts errors as failures fails += errors; errors = 0; // TODO(b/32608089): jsunit_test does not report number of tests correctly testCount = 1; // Since total number of tests cannot be asserted; ensure nummber of succeeds is correct. assertThat(consoleLogs.stream().filter(x -> x.contains(": PASSED"))).hasSize(succeeds); } if (fails + errors > 0) { assertTestSummaryForFailure(fails, errors, testCount); } else { assertTestSummaryForSuccess(testCount); } }
private void assertTestSummary() { int fails = testResult.fails().size(); int errors = testResult.errors().size(); int succeeds = testResult.succeeds().size(); int testCount = fails + errors + succeeds; if (testMode.isJ2cl()) { // Like Junit4, J2CL always counts errors as failures fails += errors; errors = 0; // TODO(b/32608089): jsunit_test does not report number of tests correctly testCount = 1; // Since total number of tests cannot be asserted; ensure nummber of succeeds is correct. assertThat(consoleLogs.stream().filter(x -> x.contains(": PASSED"))).hasSize(succeeds); } if (fails + errors > 0) { assertTestSummaryForFailure(fails, errors, testCount); } else { assertTestSummaryForSuccess(testCount); } }
34,311
2
// Since total number of tests cannot be asserted; ensure nummber of succeeds is correct.
private void assertTestSummary() { int fails = testResult.fails().size(); int errors = testResult.errors().size(); int succeeds = testResult.succeeds().size(); int testCount = fails + errors + succeeds; if (testMode.isJ2cl()) { // Like Junit4, J2CL always counts errors as failures fails += errors; errors = 0; // TODO(b/32608089): jsunit_test does not report number of tests correctly testCount = 1; // Since total number of tests cannot be asserted; ensure nummber of succeeds is correct. assertThat(consoleLogs.stream().filter(x -> x.contains(": PASSED"))).hasSize(succeeds); } if (fails + errors > 0) { assertTestSummaryForFailure(fails, errors, testCount); } else { assertTestSummaryForSuccess(testCount); } }
NONSATD
true
// TODO(b/32608089): jsunit_test does not report number of tests correctly testCount = 1; // Since total number of tests cannot be asserted; ensure nummber of succeeds is correct. assertThat(consoleLogs.stream().filter(x -> x.contains(": PASSED"))).hasSize(succeeds); }
int fails = testResult.fails().size(); int errors = testResult.errors().size(); int succeeds = testResult.succeeds().size(); int testCount = fails + errors + succeeds; if (testMode.isJ2cl()) { // Like Junit4, J2CL always counts errors as failures fails += errors; errors = 0; // TODO(b/32608089): jsunit_test does not report number of tests correctly testCount = 1; // Since total number of tests cannot be asserted; ensure nummber of succeeds is correct. assertThat(consoleLogs.stream().filter(x -> x.contains(": PASSED"))).hasSize(succeeds); } if (fails + errors > 0) { assertTestSummaryForFailure(fails, errors, testCount); } else { assertTestSummaryForSuccess(testCount); } }
private void assertTestSummary() { int fails = testResult.fails().size(); int errors = testResult.errors().size(); int succeeds = testResult.succeeds().size(); int testCount = fails + errors + succeeds; if (testMode.isJ2cl()) { // Like Junit4, J2CL always counts errors as failures fails += errors; errors = 0; // TODO(b/32608089): jsunit_test does not report number of tests correctly testCount = 1; // Since total number of tests cannot be asserted; ensure nummber of succeeds is correct. assertThat(consoleLogs.stream().filter(x -> x.contains(": PASSED"))).hasSize(succeeds); } if (fails + errors > 0) { assertTestSummaryForFailure(fails, errors, testCount); } else { assertTestSummaryForSuccess(testCount); } }
1,545
0
//Todo: optimize
public void execute(List<String> statements) throws MetaStoreException { for (String statement : statements) { execute(statement); } }
DESIGN
true
public void execute(List<String> statements) throws MetaStoreException { for (String statement : statements) { execute(statement); } }
public void execute(List<String> statements) throws MetaStoreException { for (String statement : statements) { execute(statement); } }
public void execute(List<String> statements) throws MetaStoreException { for (String statement : statements) { execute(statement); } }
17,941
0
// TODO String nextLink = (String) graphMap.get(ODATA_NEXT); // TODO ContinuationData continuationData = nextLink == null ? null : new ContinuationData(new GraphPagination(nextLink));
@Override public ExportResult<CalendarContainerResource> export(TokenAuthData authData) { Request.Builder calendarsBuilder = getBuilder(baseUrl + CALENDARS_URL, authData); List<CalendarModel> calendarModels = new ArrayList<>(); try (Response graphResponse = client.newCall(calendarsBuilder.build()).execute()) { ResponseBody body = graphResponse.body(); if (body == null) { return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving contacts: response body was null"); } String graphBody = new String(body.bytes()); Map graphMap = objectMapper.reader().forType(Map.class).readValue(graphBody); // TODO String nextLink = (String) graphMap.get(ODATA_NEXT); // TODO ContinuationData continuationData = nextLink == null ? null : new ContinuationData(new GraphPagination(nextLink)); @SuppressWarnings("unchecked") List<Map<String, Object>> rawCalendars = (List<Map<String, Object>>) graphMap.get("value"); if (rawCalendars == null) { return new ExportResult<>(ExportResult.ResultType.END); } for (Map<String, Object> rawCalendar : rawCalendars) { TransformResult<CalendarModel> result = transformerService.transform(CalendarModel.class, rawCalendar); if (result.hasProblems()) { // discard // FIXME log problem continue; } calendarModels.add(result.getTransformed()); } } catch (IOException e) { e.printStackTrace(); // FIXME log error return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving calendar: " + e.getMessage()); } List<CalendarEventModel> calendarEventModels = new ArrayList<>(); for (CalendarModel calendarModel : calendarModels) { String id = calendarModel.getId(); Request.Builder eventsBuilder = getBuilder(calculateEventsUrl(id), authData); try (Response graphResponse = client.newCall(eventsBuilder.build()).execute()) { ResponseBody body = graphResponse.body(); if (body == null) { return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving calendar: response body was null"); } String graphBody = new String(body.bytes()); Map graphMap = objectMapper.reader().forType(Map.class).readValue(graphBody); // TODO String nextLink = (String) graphMap.get(ODATA_NEXT); // TODO ContinuationData continuationData = nextLink == null ? null : new ContinuationData(new GraphPagination(nextLink)); @SuppressWarnings("unchecked") List<Map<String, Object>> rawEvents = (List<Map<String, Object>>) graphMap.get("value"); if (rawEvents == null) { return new ExportResult<>(ExportResult.ResultType.END); } for (Map<String, Object> rawEvent : rawEvents) { Map<String, String> properties = new HashMap<>(); properties.put(CALENDAR_ID, id); TransformResult<CalendarEventModel> result = transformerService.transform(CalendarEventModel.class, rawEvent, properties); if (result.hasProblems()) { // discard // FIXME log problem continue; } calendarEventModels.add(result.getTransformed()); } } catch (IOException e) { e.printStackTrace(); // FIXME log error return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving contacts: " + e.getMessage()); } } CalendarContainerResource resource = new CalendarContainerResource(calendarModels, calendarEventModels); return new ExportResult<>(ExportResult.ResultType.END, resource, null); }
NONSATD
true
String graphBody = new String(body.bytes()); Map graphMap = objectMapper.reader().forType(Map.class).readValue(graphBody); // TODO String nextLink = (String) graphMap.get(ODATA_NEXT); // TODO ContinuationData continuationData = nextLink == null ? null : new ContinuationData(new GraphPagination(nextLink)); @SuppressWarnings("unchecked") List<Map<String, Object>> rawCalendars = (List<Map<String, Object>>) graphMap.get("value"); if (rawCalendars == null) {
public ExportResult<CalendarContainerResource> export(TokenAuthData authData) { Request.Builder calendarsBuilder = getBuilder(baseUrl + CALENDARS_URL, authData); List<CalendarModel> calendarModels = new ArrayList<>(); try (Response graphResponse = client.newCall(calendarsBuilder.build()).execute()) { ResponseBody body = graphResponse.body(); if (body == null) { return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving contacts: response body was null"); } String graphBody = new String(body.bytes()); Map graphMap = objectMapper.reader().forType(Map.class).readValue(graphBody); // TODO String nextLink = (String) graphMap.get(ODATA_NEXT); // TODO ContinuationData continuationData = nextLink == null ? null : new ContinuationData(new GraphPagination(nextLink)); @SuppressWarnings("unchecked") List<Map<String, Object>> rawCalendars = (List<Map<String, Object>>) graphMap.get("value"); if (rawCalendars == null) { return new ExportResult<>(ExportResult.ResultType.END); } for (Map<String, Object> rawCalendar : rawCalendars) { TransformResult<CalendarModel> result = transformerService.transform(CalendarModel.class, rawCalendar); if (result.hasProblems()) { // discard // FIXME log problem continue;
@Override public ExportResult<CalendarContainerResource> export(TokenAuthData authData) { Request.Builder calendarsBuilder = getBuilder(baseUrl + CALENDARS_URL, authData); List<CalendarModel> calendarModels = new ArrayList<>(); try (Response graphResponse = client.newCall(calendarsBuilder.build()).execute()) { ResponseBody body = graphResponse.body(); if (body == null) { return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving contacts: response body was null"); } String graphBody = new String(body.bytes()); Map graphMap = objectMapper.reader().forType(Map.class).readValue(graphBody); // TODO String nextLink = (String) graphMap.get(ODATA_NEXT); // TODO ContinuationData continuationData = nextLink == null ? null : new ContinuationData(new GraphPagination(nextLink)); @SuppressWarnings("unchecked") List<Map<String, Object>> rawCalendars = (List<Map<String, Object>>) graphMap.get("value"); if (rawCalendars == null) { return new ExportResult<>(ExportResult.ResultType.END); } for (Map<String, Object> rawCalendar : rawCalendars) { TransformResult<CalendarModel> result = transformerService.transform(CalendarModel.class, rawCalendar); if (result.hasProblems()) { // discard // FIXME log problem continue; } calendarModels.add(result.getTransformed()); } } catch (IOException e) { e.printStackTrace(); // FIXME log error return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving calendar: " + e.getMessage()); } List<CalendarEventModel> calendarEventModels = new ArrayList<>(); for (CalendarModel calendarModel : calendarModels) { String id = calendarModel.getId();
17,941
1
// discard // FIXME log problem
@Override public ExportResult<CalendarContainerResource> export(TokenAuthData authData) { Request.Builder calendarsBuilder = getBuilder(baseUrl + CALENDARS_URL, authData); List<CalendarModel> calendarModels = new ArrayList<>(); try (Response graphResponse = client.newCall(calendarsBuilder.build()).execute()) { ResponseBody body = graphResponse.body(); if (body == null) { return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving contacts: response body was null"); } String graphBody = new String(body.bytes()); Map graphMap = objectMapper.reader().forType(Map.class).readValue(graphBody); // TODO String nextLink = (String) graphMap.get(ODATA_NEXT); // TODO ContinuationData continuationData = nextLink == null ? null : new ContinuationData(new GraphPagination(nextLink)); @SuppressWarnings("unchecked") List<Map<String, Object>> rawCalendars = (List<Map<String, Object>>) graphMap.get("value"); if (rawCalendars == null) { return new ExportResult<>(ExportResult.ResultType.END); } for (Map<String, Object> rawCalendar : rawCalendars) { TransformResult<CalendarModel> result = transformerService.transform(CalendarModel.class, rawCalendar); if (result.hasProblems()) { // discard // FIXME log problem continue; } calendarModels.add(result.getTransformed()); } } catch (IOException e) { e.printStackTrace(); // FIXME log error return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving calendar: " + e.getMessage()); } List<CalendarEventModel> calendarEventModels = new ArrayList<>(); for (CalendarModel calendarModel : calendarModels) { String id = calendarModel.getId(); Request.Builder eventsBuilder = getBuilder(calculateEventsUrl(id), authData); try (Response graphResponse = client.newCall(eventsBuilder.build()).execute()) { ResponseBody body = graphResponse.body(); if (body == null) { return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving calendar: response body was null"); } String graphBody = new String(body.bytes()); Map graphMap = objectMapper.reader().forType(Map.class).readValue(graphBody); // TODO String nextLink = (String) graphMap.get(ODATA_NEXT); // TODO ContinuationData continuationData = nextLink == null ? null : new ContinuationData(new GraphPagination(nextLink)); @SuppressWarnings("unchecked") List<Map<String, Object>> rawEvents = (List<Map<String, Object>>) graphMap.get("value"); if (rawEvents == null) { return new ExportResult<>(ExportResult.ResultType.END); } for (Map<String, Object> rawEvent : rawEvents) { Map<String, String> properties = new HashMap<>(); properties.put(CALENDAR_ID, id); TransformResult<CalendarEventModel> result = transformerService.transform(CalendarEventModel.class, rawEvent, properties); if (result.hasProblems()) { // discard // FIXME log problem continue; } calendarEventModels.add(result.getTransformed()); } } catch (IOException e) { e.printStackTrace(); // FIXME log error return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving contacts: " + e.getMessage()); } } CalendarContainerResource resource = new CalendarContainerResource(calendarModels, calendarEventModels); return new ExportResult<>(ExportResult.ResultType.END, resource, null); }
DEFECT
true
TransformResult<CalendarModel> result = transformerService.transform(CalendarModel.class, rawCalendar); if (result.hasProblems()) { // discard // FIXME log problem continue; }
Map graphMap = objectMapper.reader().forType(Map.class).readValue(graphBody); // TODO String nextLink = (String) graphMap.get(ODATA_NEXT); // TODO ContinuationData continuationData = nextLink == null ? null : new ContinuationData(new GraphPagination(nextLink)); @SuppressWarnings("unchecked") List<Map<String, Object>> rawCalendars = (List<Map<String, Object>>) graphMap.get("value"); if (rawCalendars == null) { return new ExportResult<>(ExportResult.ResultType.END); } for (Map<String, Object> rawCalendar : rawCalendars) { TransformResult<CalendarModel> result = transformerService.transform(CalendarModel.class, rawCalendar); if (result.hasProblems()) { // discard // FIXME log problem continue; } calendarModels.add(result.getTransformed()); } } catch (IOException e) { e.printStackTrace(); // FIXME log error return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving calendar: " + e.getMessage()); } List<CalendarEventModel> calendarEventModels = new ArrayList<>(); for (CalendarModel calendarModel : calendarModels) {
@Override public ExportResult<CalendarContainerResource> export(TokenAuthData authData) { Request.Builder calendarsBuilder = getBuilder(baseUrl + CALENDARS_URL, authData); List<CalendarModel> calendarModels = new ArrayList<>(); try (Response graphResponse = client.newCall(calendarsBuilder.build()).execute()) { ResponseBody body = graphResponse.body(); if (body == null) { return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving contacts: response body was null"); } String graphBody = new String(body.bytes()); Map graphMap = objectMapper.reader().forType(Map.class).readValue(graphBody); // TODO String nextLink = (String) graphMap.get(ODATA_NEXT); // TODO ContinuationData continuationData = nextLink == null ? null : new ContinuationData(new GraphPagination(nextLink)); @SuppressWarnings("unchecked") List<Map<String, Object>> rawCalendars = (List<Map<String, Object>>) graphMap.get("value"); if (rawCalendars == null) { return new ExportResult<>(ExportResult.ResultType.END); } for (Map<String, Object> rawCalendar : rawCalendars) { TransformResult<CalendarModel> result = transformerService.transform(CalendarModel.class, rawCalendar); if (result.hasProblems()) { // discard // FIXME log problem continue; } calendarModels.add(result.getTransformed()); } } catch (IOException e) { e.printStackTrace(); // FIXME log error return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving calendar: " + e.getMessage()); } List<CalendarEventModel> calendarEventModels = new ArrayList<>(); for (CalendarModel calendarModel : calendarModels) { String id = calendarModel.getId(); Request.Builder eventsBuilder = getBuilder(calculateEventsUrl(id), authData); try (Response graphResponse = client.newCall(eventsBuilder.build()).execute()) { ResponseBody body = graphResponse.body(); if (body == null) { return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving calendar: response body was null"); } String graphBody = new String(body.bytes()); Map graphMap = objectMapper.reader().forType(Map.class).readValue(graphBody); // TODO String nextLink = (String) graphMap.get(ODATA_NEXT);
17,941
2
// FIXME log error
@Override public ExportResult<CalendarContainerResource> export(TokenAuthData authData) { Request.Builder calendarsBuilder = getBuilder(baseUrl + CALENDARS_URL, authData); List<CalendarModel> calendarModels = new ArrayList<>(); try (Response graphResponse = client.newCall(calendarsBuilder.build()).execute()) { ResponseBody body = graphResponse.body(); if (body == null) { return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving contacts: response body was null"); } String graphBody = new String(body.bytes()); Map graphMap = objectMapper.reader().forType(Map.class).readValue(graphBody); // TODO String nextLink = (String) graphMap.get(ODATA_NEXT); // TODO ContinuationData continuationData = nextLink == null ? null : new ContinuationData(new GraphPagination(nextLink)); @SuppressWarnings("unchecked") List<Map<String, Object>> rawCalendars = (List<Map<String, Object>>) graphMap.get("value"); if (rawCalendars == null) { return new ExportResult<>(ExportResult.ResultType.END); } for (Map<String, Object> rawCalendar : rawCalendars) { TransformResult<CalendarModel> result = transformerService.transform(CalendarModel.class, rawCalendar); if (result.hasProblems()) { // discard // FIXME log problem continue; } calendarModels.add(result.getTransformed()); } } catch (IOException e) { e.printStackTrace(); // FIXME log error return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving calendar: " + e.getMessage()); } List<CalendarEventModel> calendarEventModels = new ArrayList<>(); for (CalendarModel calendarModel : calendarModels) { String id = calendarModel.getId(); Request.Builder eventsBuilder = getBuilder(calculateEventsUrl(id), authData); try (Response graphResponse = client.newCall(eventsBuilder.build()).execute()) { ResponseBody body = graphResponse.body(); if (body == null) { return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving calendar: response body was null"); } String graphBody = new String(body.bytes()); Map graphMap = objectMapper.reader().forType(Map.class).readValue(graphBody); // TODO String nextLink = (String) graphMap.get(ODATA_NEXT); // TODO ContinuationData continuationData = nextLink == null ? null : new ContinuationData(new GraphPagination(nextLink)); @SuppressWarnings("unchecked") List<Map<String, Object>> rawEvents = (List<Map<String, Object>>) graphMap.get("value"); if (rawEvents == null) { return new ExportResult<>(ExportResult.ResultType.END); } for (Map<String, Object> rawEvent : rawEvents) { Map<String, String> properties = new HashMap<>(); properties.put(CALENDAR_ID, id); TransformResult<CalendarEventModel> result = transformerService.transform(CalendarEventModel.class, rawEvent, properties); if (result.hasProblems()) { // discard // FIXME log problem continue; } calendarEventModels.add(result.getTransformed()); } } catch (IOException e) { e.printStackTrace(); // FIXME log error return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving contacts: " + e.getMessage()); } } CalendarContainerResource resource = new CalendarContainerResource(calendarModels, calendarEventModels); return new ExportResult<>(ExportResult.ResultType.END, resource, null); }
DEFECT
true
} } catch (IOException e) { e.printStackTrace(); // FIXME log error return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving calendar: " + e.getMessage()); }
for (Map<String, Object> rawCalendar : rawCalendars) { TransformResult<CalendarModel> result = transformerService.transform(CalendarModel.class, rawCalendar); if (result.hasProblems()) { // discard // FIXME log problem continue; } calendarModels.add(result.getTransformed()); } } catch (IOException e) { e.printStackTrace(); // FIXME log error return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving calendar: " + e.getMessage()); } List<CalendarEventModel> calendarEventModels = new ArrayList<>(); for (CalendarModel calendarModel : calendarModels) { String id = calendarModel.getId(); Request.Builder eventsBuilder = getBuilder(calculateEventsUrl(id), authData); try (Response graphResponse = client.newCall(eventsBuilder.build()).execute()) { ResponseBody body = graphResponse.body(); if (body == null) { return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving calendar: response body was null");
return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving contacts: response body was null"); } String graphBody = new String(body.bytes()); Map graphMap = objectMapper.reader().forType(Map.class).readValue(graphBody); // TODO String nextLink = (String) graphMap.get(ODATA_NEXT); // TODO ContinuationData continuationData = nextLink == null ? null : new ContinuationData(new GraphPagination(nextLink)); @SuppressWarnings("unchecked") List<Map<String, Object>> rawCalendars = (List<Map<String, Object>>) graphMap.get("value"); if (rawCalendars == null) { return new ExportResult<>(ExportResult.ResultType.END); } for (Map<String, Object> rawCalendar : rawCalendars) { TransformResult<CalendarModel> result = transformerService.transform(CalendarModel.class, rawCalendar); if (result.hasProblems()) { // discard // FIXME log problem continue; } calendarModels.add(result.getTransformed()); } } catch (IOException e) { e.printStackTrace(); // FIXME log error return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving calendar: " + e.getMessage()); } List<CalendarEventModel> calendarEventModels = new ArrayList<>(); for (CalendarModel calendarModel : calendarModels) { String id = calendarModel.getId(); Request.Builder eventsBuilder = getBuilder(calculateEventsUrl(id), authData); try (Response graphResponse = client.newCall(eventsBuilder.build()).execute()) { ResponseBody body = graphResponse.body(); if (body == null) { return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving calendar: response body was null"); } String graphBody = new String(body.bytes()); Map graphMap = objectMapper.reader().forType(Map.class).readValue(graphBody); // TODO String nextLink = (String) graphMap.get(ODATA_NEXT); // TODO ContinuationData continuationData = nextLink == null ? null : new ContinuationData(new GraphPagination(nextLink)); @SuppressWarnings("unchecked") List<Map<String, Object>> rawEvents = (List<Map<String, Object>>) graphMap.get("value"); if (rawEvents == null) { return new ExportResult<>(ExportResult.ResultType.END); } for (Map<String, Object> rawEvent : rawEvents) {
17,941
3
// TODO String nextLink = (String) graphMap.get(ODATA_NEXT); // TODO ContinuationData continuationData = nextLink == null ? null : new ContinuationData(new GraphPagination(nextLink));
@Override public ExportResult<CalendarContainerResource> export(TokenAuthData authData) { Request.Builder calendarsBuilder = getBuilder(baseUrl + CALENDARS_URL, authData); List<CalendarModel> calendarModels = new ArrayList<>(); try (Response graphResponse = client.newCall(calendarsBuilder.build()).execute()) { ResponseBody body = graphResponse.body(); if (body == null) { return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving contacts: response body was null"); } String graphBody = new String(body.bytes()); Map graphMap = objectMapper.reader().forType(Map.class).readValue(graphBody); // TODO String nextLink = (String) graphMap.get(ODATA_NEXT); // TODO ContinuationData continuationData = nextLink == null ? null : new ContinuationData(new GraphPagination(nextLink)); @SuppressWarnings("unchecked") List<Map<String, Object>> rawCalendars = (List<Map<String, Object>>) graphMap.get("value"); if (rawCalendars == null) { return new ExportResult<>(ExportResult.ResultType.END); } for (Map<String, Object> rawCalendar : rawCalendars) { TransformResult<CalendarModel> result = transformerService.transform(CalendarModel.class, rawCalendar); if (result.hasProblems()) { // discard // FIXME log problem continue; } calendarModels.add(result.getTransformed()); } } catch (IOException e) { e.printStackTrace(); // FIXME log error return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving calendar: " + e.getMessage()); } List<CalendarEventModel> calendarEventModels = new ArrayList<>(); for (CalendarModel calendarModel : calendarModels) { String id = calendarModel.getId(); Request.Builder eventsBuilder = getBuilder(calculateEventsUrl(id), authData); try (Response graphResponse = client.newCall(eventsBuilder.build()).execute()) { ResponseBody body = graphResponse.body(); if (body == null) { return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving calendar: response body was null"); } String graphBody = new String(body.bytes()); Map graphMap = objectMapper.reader().forType(Map.class).readValue(graphBody); // TODO String nextLink = (String) graphMap.get(ODATA_NEXT); // TODO ContinuationData continuationData = nextLink == null ? null : new ContinuationData(new GraphPagination(nextLink)); @SuppressWarnings("unchecked") List<Map<String, Object>> rawEvents = (List<Map<String, Object>>) graphMap.get("value"); if (rawEvents == null) { return new ExportResult<>(ExportResult.ResultType.END); } for (Map<String, Object> rawEvent : rawEvents) { Map<String, String> properties = new HashMap<>(); properties.put(CALENDAR_ID, id); TransformResult<CalendarEventModel> result = transformerService.transform(CalendarEventModel.class, rawEvent, properties); if (result.hasProblems()) { // discard // FIXME log problem continue; } calendarEventModels.add(result.getTransformed()); } } catch (IOException e) { e.printStackTrace(); // FIXME log error return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving contacts: " + e.getMessage()); } } CalendarContainerResource resource = new CalendarContainerResource(calendarModels, calendarEventModels); return new ExportResult<>(ExportResult.ResultType.END, resource, null); }
NONSATD
true
String graphBody = new String(body.bytes()); Map graphMap = objectMapper.reader().forType(Map.class).readValue(graphBody); // TODO String nextLink = (String) graphMap.get(ODATA_NEXT); // TODO ContinuationData continuationData = nextLink == null ? null : new ContinuationData(new GraphPagination(nextLink)); @SuppressWarnings("unchecked") List<Map<String, Object>> rawCalendars = (List<Map<String, Object>>) graphMap.get("value"); if (rawCalendars == null) {
public ExportResult<CalendarContainerResource> export(TokenAuthData authData) { Request.Builder calendarsBuilder = getBuilder(baseUrl + CALENDARS_URL, authData); List<CalendarModel> calendarModels = new ArrayList<>(); try (Response graphResponse = client.newCall(calendarsBuilder.build()).execute()) { ResponseBody body = graphResponse.body(); if (body == null) { return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving contacts: response body was null"); } String graphBody = new String(body.bytes()); Map graphMap = objectMapper.reader().forType(Map.class).readValue(graphBody); // TODO String nextLink = (String) graphMap.get(ODATA_NEXT); // TODO ContinuationData continuationData = nextLink == null ? null : new ContinuationData(new GraphPagination(nextLink)); @SuppressWarnings("unchecked") List<Map<String, Object>> rawCalendars = (List<Map<String, Object>>) graphMap.get("value"); if (rawCalendars == null) { return new ExportResult<>(ExportResult.ResultType.END); } for (Map<String, Object> rawCalendar : rawCalendars) { TransformResult<CalendarModel> result = transformerService.transform(CalendarModel.class, rawCalendar); if (result.hasProblems()) { // discard // FIXME log problem continue;
@Override public ExportResult<CalendarContainerResource> export(TokenAuthData authData) { Request.Builder calendarsBuilder = getBuilder(baseUrl + CALENDARS_URL, authData); List<CalendarModel> calendarModels = new ArrayList<>(); try (Response graphResponse = client.newCall(calendarsBuilder.build()).execute()) { ResponseBody body = graphResponse.body(); if (body == null) { return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving contacts: response body was null"); } String graphBody = new String(body.bytes()); Map graphMap = objectMapper.reader().forType(Map.class).readValue(graphBody); // TODO String nextLink = (String) graphMap.get(ODATA_NEXT); // TODO ContinuationData continuationData = nextLink == null ? null : new ContinuationData(new GraphPagination(nextLink)); @SuppressWarnings("unchecked") List<Map<String, Object>> rawCalendars = (List<Map<String, Object>>) graphMap.get("value"); if (rawCalendars == null) { return new ExportResult<>(ExportResult.ResultType.END); } for (Map<String, Object> rawCalendar : rawCalendars) { TransformResult<CalendarModel> result = transformerService.transform(CalendarModel.class, rawCalendar); if (result.hasProblems()) { // discard // FIXME log problem continue; } calendarModels.add(result.getTransformed()); } } catch (IOException e) { e.printStackTrace(); // FIXME log error return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving calendar: " + e.getMessage()); } List<CalendarEventModel> calendarEventModels = new ArrayList<>(); for (CalendarModel calendarModel : calendarModels) { String id = calendarModel.getId();
17,941
4
// discard // FIXME log problem
@Override public ExportResult<CalendarContainerResource> export(TokenAuthData authData) { Request.Builder calendarsBuilder = getBuilder(baseUrl + CALENDARS_URL, authData); List<CalendarModel> calendarModels = new ArrayList<>(); try (Response graphResponse = client.newCall(calendarsBuilder.build()).execute()) { ResponseBody body = graphResponse.body(); if (body == null) { return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving contacts: response body was null"); } String graphBody = new String(body.bytes()); Map graphMap = objectMapper.reader().forType(Map.class).readValue(graphBody); // TODO String nextLink = (String) graphMap.get(ODATA_NEXT); // TODO ContinuationData continuationData = nextLink == null ? null : new ContinuationData(new GraphPagination(nextLink)); @SuppressWarnings("unchecked") List<Map<String, Object>> rawCalendars = (List<Map<String, Object>>) graphMap.get("value"); if (rawCalendars == null) { return new ExportResult<>(ExportResult.ResultType.END); } for (Map<String, Object> rawCalendar : rawCalendars) { TransformResult<CalendarModel> result = transformerService.transform(CalendarModel.class, rawCalendar); if (result.hasProblems()) { // discard // FIXME log problem continue; } calendarModels.add(result.getTransformed()); } } catch (IOException e) { e.printStackTrace(); // FIXME log error return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving calendar: " + e.getMessage()); } List<CalendarEventModel> calendarEventModels = new ArrayList<>(); for (CalendarModel calendarModel : calendarModels) { String id = calendarModel.getId(); Request.Builder eventsBuilder = getBuilder(calculateEventsUrl(id), authData); try (Response graphResponse = client.newCall(eventsBuilder.build()).execute()) { ResponseBody body = graphResponse.body(); if (body == null) { return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving calendar: response body was null"); } String graphBody = new String(body.bytes()); Map graphMap = objectMapper.reader().forType(Map.class).readValue(graphBody); // TODO String nextLink = (String) graphMap.get(ODATA_NEXT); // TODO ContinuationData continuationData = nextLink == null ? null : new ContinuationData(new GraphPagination(nextLink)); @SuppressWarnings("unchecked") List<Map<String, Object>> rawEvents = (List<Map<String, Object>>) graphMap.get("value"); if (rawEvents == null) { return new ExportResult<>(ExportResult.ResultType.END); } for (Map<String, Object> rawEvent : rawEvents) { Map<String, String> properties = new HashMap<>(); properties.put(CALENDAR_ID, id); TransformResult<CalendarEventModel> result = transformerService.transform(CalendarEventModel.class, rawEvent, properties); if (result.hasProblems()) { // discard // FIXME log problem continue; } calendarEventModels.add(result.getTransformed()); } } catch (IOException e) { e.printStackTrace(); // FIXME log error return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving contacts: " + e.getMessage()); } } CalendarContainerResource resource = new CalendarContainerResource(calendarModels, calendarEventModels); return new ExportResult<>(ExportResult.ResultType.END, resource, null); }
DEFECT
true
TransformResult<CalendarModel> result = transformerService.transform(CalendarModel.class, rawCalendar); if (result.hasProblems()) { // discard // FIXME log problem continue; }
Map graphMap = objectMapper.reader().forType(Map.class).readValue(graphBody); // TODO String nextLink = (String) graphMap.get(ODATA_NEXT); // TODO ContinuationData continuationData = nextLink == null ? null : new ContinuationData(new GraphPagination(nextLink)); @SuppressWarnings("unchecked") List<Map<String, Object>> rawCalendars = (List<Map<String, Object>>) graphMap.get("value"); if (rawCalendars == null) { return new ExportResult<>(ExportResult.ResultType.END); } for (Map<String, Object> rawCalendar : rawCalendars) { TransformResult<CalendarModel> result = transformerService.transform(CalendarModel.class, rawCalendar); if (result.hasProblems()) { // discard // FIXME log problem continue; } calendarModels.add(result.getTransformed()); } } catch (IOException e) { e.printStackTrace(); // FIXME log error return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving calendar: " + e.getMessage()); } List<CalendarEventModel> calendarEventModels = new ArrayList<>(); for (CalendarModel calendarModel : calendarModels) {
@Override public ExportResult<CalendarContainerResource> export(TokenAuthData authData) { Request.Builder calendarsBuilder = getBuilder(baseUrl + CALENDARS_URL, authData); List<CalendarModel> calendarModels = new ArrayList<>(); try (Response graphResponse = client.newCall(calendarsBuilder.build()).execute()) { ResponseBody body = graphResponse.body(); if (body == null) { return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving contacts: response body was null"); } String graphBody = new String(body.bytes()); Map graphMap = objectMapper.reader().forType(Map.class).readValue(graphBody); // TODO String nextLink = (String) graphMap.get(ODATA_NEXT); // TODO ContinuationData continuationData = nextLink == null ? null : new ContinuationData(new GraphPagination(nextLink)); @SuppressWarnings("unchecked") List<Map<String, Object>> rawCalendars = (List<Map<String, Object>>) graphMap.get("value"); if (rawCalendars == null) { return new ExportResult<>(ExportResult.ResultType.END); } for (Map<String, Object> rawCalendar : rawCalendars) { TransformResult<CalendarModel> result = transformerService.transform(CalendarModel.class, rawCalendar); if (result.hasProblems()) { // discard // FIXME log problem continue; } calendarModels.add(result.getTransformed()); } } catch (IOException e) { e.printStackTrace(); // FIXME log error return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving calendar: " + e.getMessage()); } List<CalendarEventModel> calendarEventModels = new ArrayList<>(); for (CalendarModel calendarModel : calendarModels) { String id = calendarModel.getId(); Request.Builder eventsBuilder = getBuilder(calculateEventsUrl(id), authData); try (Response graphResponse = client.newCall(eventsBuilder.build()).execute()) { ResponseBody body = graphResponse.body(); if (body == null) { return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving calendar: response body was null"); } String graphBody = new String(body.bytes()); Map graphMap = objectMapper.reader().forType(Map.class).readValue(graphBody); // TODO String nextLink = (String) graphMap.get(ODATA_NEXT);
17,941
5
// FIXME log error
@Override public ExportResult<CalendarContainerResource> export(TokenAuthData authData) { Request.Builder calendarsBuilder = getBuilder(baseUrl + CALENDARS_URL, authData); List<CalendarModel> calendarModels = new ArrayList<>(); try (Response graphResponse = client.newCall(calendarsBuilder.build()).execute()) { ResponseBody body = graphResponse.body(); if (body == null) { return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving contacts: response body was null"); } String graphBody = new String(body.bytes()); Map graphMap = objectMapper.reader().forType(Map.class).readValue(graphBody); // TODO String nextLink = (String) graphMap.get(ODATA_NEXT); // TODO ContinuationData continuationData = nextLink == null ? null : new ContinuationData(new GraphPagination(nextLink)); @SuppressWarnings("unchecked") List<Map<String, Object>> rawCalendars = (List<Map<String, Object>>) graphMap.get("value"); if (rawCalendars == null) { return new ExportResult<>(ExportResult.ResultType.END); } for (Map<String, Object> rawCalendar : rawCalendars) { TransformResult<CalendarModel> result = transformerService.transform(CalendarModel.class, rawCalendar); if (result.hasProblems()) { // discard // FIXME log problem continue; } calendarModels.add(result.getTransformed()); } } catch (IOException e) { e.printStackTrace(); // FIXME log error return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving calendar: " + e.getMessage()); } List<CalendarEventModel> calendarEventModels = new ArrayList<>(); for (CalendarModel calendarModel : calendarModels) { String id = calendarModel.getId(); Request.Builder eventsBuilder = getBuilder(calculateEventsUrl(id), authData); try (Response graphResponse = client.newCall(eventsBuilder.build()).execute()) { ResponseBody body = graphResponse.body(); if (body == null) { return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving calendar: response body was null"); } String graphBody = new String(body.bytes()); Map graphMap = objectMapper.reader().forType(Map.class).readValue(graphBody); // TODO String nextLink = (String) graphMap.get(ODATA_NEXT); // TODO ContinuationData continuationData = nextLink == null ? null : new ContinuationData(new GraphPagination(nextLink)); @SuppressWarnings("unchecked") List<Map<String, Object>> rawEvents = (List<Map<String, Object>>) graphMap.get("value"); if (rawEvents == null) { return new ExportResult<>(ExportResult.ResultType.END); } for (Map<String, Object> rawEvent : rawEvents) { Map<String, String> properties = new HashMap<>(); properties.put(CALENDAR_ID, id); TransformResult<CalendarEventModel> result = transformerService.transform(CalendarEventModel.class, rawEvent, properties); if (result.hasProblems()) { // discard // FIXME log problem continue; } calendarEventModels.add(result.getTransformed()); } } catch (IOException e) { e.printStackTrace(); // FIXME log error return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving contacts: " + e.getMessage()); } } CalendarContainerResource resource = new CalendarContainerResource(calendarModels, calendarEventModels); return new ExportResult<>(ExportResult.ResultType.END, resource, null); }
DEFECT
true
} } catch (IOException e) { e.printStackTrace(); // FIXME log error return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving calendar: " + e.getMessage()); }
for (Map<String, Object> rawCalendar : rawCalendars) { TransformResult<CalendarModel> result = transformerService.transform(CalendarModel.class, rawCalendar); if (result.hasProblems()) { // discard // FIXME log problem continue; } calendarModels.add(result.getTransformed()); } } catch (IOException e) { e.printStackTrace(); // FIXME log error return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving calendar: " + e.getMessage()); } List<CalendarEventModel> calendarEventModels = new ArrayList<>(); for (CalendarModel calendarModel : calendarModels) { String id = calendarModel.getId(); Request.Builder eventsBuilder = getBuilder(calculateEventsUrl(id), authData); try (Response graphResponse = client.newCall(eventsBuilder.build()).execute()) { ResponseBody body = graphResponse.body(); if (body == null) { return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving calendar: response body was null");
return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving contacts: response body was null"); } String graphBody = new String(body.bytes()); Map graphMap = objectMapper.reader().forType(Map.class).readValue(graphBody); // TODO String nextLink = (String) graphMap.get(ODATA_NEXT); // TODO ContinuationData continuationData = nextLink == null ? null : new ContinuationData(new GraphPagination(nextLink)); @SuppressWarnings("unchecked") List<Map<String, Object>> rawCalendars = (List<Map<String, Object>>) graphMap.get("value"); if (rawCalendars == null) { return new ExportResult<>(ExportResult.ResultType.END); } for (Map<String, Object> rawCalendar : rawCalendars) { TransformResult<CalendarModel> result = transformerService.transform(CalendarModel.class, rawCalendar); if (result.hasProblems()) { // discard // FIXME log problem continue; } calendarModels.add(result.getTransformed()); } } catch (IOException e) { e.printStackTrace(); // FIXME log error return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving calendar: " + e.getMessage()); } List<CalendarEventModel> calendarEventModels = new ArrayList<>(); for (CalendarModel calendarModel : calendarModels) { String id = calendarModel.getId(); Request.Builder eventsBuilder = getBuilder(calculateEventsUrl(id), authData); try (Response graphResponse = client.newCall(eventsBuilder.build()).execute()) { ResponseBody body = graphResponse.body(); if (body == null) { return new ExportResult<>(ExportResult.ResultType.ERROR, "Error retrieving calendar: response body was null"); } String graphBody = new String(body.bytes()); Map graphMap = objectMapper.reader().forType(Map.class).readValue(graphBody); // TODO String nextLink = (String) graphMap.get(ODATA_NEXT); // TODO ContinuationData continuationData = nextLink == null ? null : new ContinuationData(new GraphPagination(nextLink)); @SuppressWarnings("unchecked") List<Map<String, Object>> rawEvents = (List<Map<String, Object>>) graphMap.get("value"); if (rawEvents == null) { return new ExportResult<>(ExportResult.ResultType.END); } for (Map<String, Object> rawEvent : rawEvents) {
9,749
0
// There seems to be a bug in the optimizer of 1.6.0_45 so that the output // values are sometimes reordered - dunno why :(
@Test public void testGetFormatted () { IMutableCurrencyValue aCV = new CurrencyValue (ECurrency.EUR, MathHelper.toBigDecimal (5)); if (EJavaVersion.JDK_9.isSupportedVersion ()) assertEquals ("5,00" + CURRENCY_SPACE + "€", aCV.getCurrencyFormatted ()); else assertEquals ("€" + CURRENCY_SPACE + "5,00", aCV.getCurrencyFormatted ()); aCV = new CurrencyValue (ECurrency.EUR, new BigDecimal ("5.12")); if (EJavaVersion.JDK_9.isSupportedVersion ()) assertEquals ("5,12" + CURRENCY_SPACE + "€", aCV.getCurrencyFormatted ()); else assertEquals ("€" + CURRENCY_SPACE + "5,12", aCV.getCurrencyFormatted ()); aCV = new CurrencyValue (ECurrency.USD, new BigDecimal ("5.12")); assertEquals ("$5.12", aCV.getCurrencyFormatted ()); for (final ECurrency eCurrency : ECurrency.values ()) { aCV = new CurrencyValue (eCurrency, new BigDecimal ("5.12")); final String sCurrencyFormatted = aCV.getCurrencyFormatted (); assertNotNull (sCurrencyFormatted); final String sValueFormatted = aCV.getValueFormatted (); assertNotNull (sValueFormatted); assertTrue (sValueFormatted, sValueFormatted.indexOf (CurrencyHelper.getCurrencySymbol (eCurrency)) < 0); CommonsTestHelper.testGetClone (aCV); // There seems to be a bug in the optimizer of 1.6.0_45 so that the output // values are sometimes reordered - dunno why :( LOGGER.info ("[" + sCurrencyFormatted + "][" + sValueFormatted + "]"); } }
DEFECT
true
assertTrue (sValueFormatted, sValueFormatted.indexOf (CurrencyHelper.getCurrencySymbol (eCurrency)) < 0); CommonsTestHelper.testGetClone (aCV); // There seems to be a bug in the optimizer of 1.6.0_45 so that the output // values are sometimes reordered - dunno why :( LOGGER.info ("[" + sCurrencyFormatted + "][" + sValueFormatted + "]"); }
assertEquals ("$5.12", aCV.getCurrencyFormatted ()); for (final ECurrency eCurrency : ECurrency.values ()) { aCV = new CurrencyValue (eCurrency, new BigDecimal ("5.12")); final String sCurrencyFormatted = aCV.getCurrencyFormatted (); assertNotNull (sCurrencyFormatted); final String sValueFormatted = aCV.getValueFormatted (); assertNotNull (sValueFormatted); assertTrue (sValueFormatted, sValueFormatted.indexOf (CurrencyHelper.getCurrencySymbol (eCurrency)) < 0); CommonsTestHelper.testGetClone (aCV); // There seems to be a bug in the optimizer of 1.6.0_45 so that the output // values are sometimes reordered - dunno why :( LOGGER.info ("[" + sCurrencyFormatted + "][" + sValueFormatted + "]"); } }
if (EJavaVersion.JDK_9.isSupportedVersion ()) assertEquals ("5,00" + CURRENCY_SPACE + "€", aCV.getCurrencyFormatted ()); else assertEquals ("€" + CURRENCY_SPACE + "5,00", aCV.getCurrencyFormatted ()); aCV = new CurrencyValue (ECurrency.EUR, new BigDecimal ("5.12")); if (EJavaVersion.JDK_9.isSupportedVersion ()) assertEquals ("5,12" + CURRENCY_SPACE + "€", aCV.getCurrencyFormatted ()); else assertEquals ("€" + CURRENCY_SPACE + "5,12", aCV.getCurrencyFormatted ()); aCV = new CurrencyValue (ECurrency.USD, new BigDecimal ("5.12")); assertEquals ("$5.12", aCV.getCurrencyFormatted ()); for (final ECurrency eCurrency : ECurrency.values ()) { aCV = new CurrencyValue (eCurrency, new BigDecimal ("5.12")); final String sCurrencyFormatted = aCV.getCurrencyFormatted (); assertNotNull (sCurrencyFormatted); final String sValueFormatted = aCV.getValueFormatted (); assertNotNull (sValueFormatted); assertTrue (sValueFormatted, sValueFormatted.indexOf (CurrencyHelper.getCurrencySymbol (eCurrency)) < 0); CommonsTestHelper.testGetClone (aCV); // There seems to be a bug in the optimizer of 1.6.0_45 so that the output // values are sometimes reordered - dunno why :( LOGGER.info ("[" + sCurrencyFormatted + "][" + sValueFormatted + "]"); } }
34,326
0
// currently only support python - maybe in future we'll support js too
public String exportAll(String filename) throws IOException { // currently only support python - maybe in future we'll support js too String python = LangUtils.toPython(); Files.write(Paths.get(filename), python.toString().getBytes()); info("saved %s to %s", getName(), filename); return python; }
DESIGN
true
public String exportAll(String filename) throws IOException { // currently only support python - maybe in future we'll support js too String python = LangUtils.toPython(); Files.write(Paths.get(filename), python.toString().getBytes());
public String exportAll(String filename) throws IOException { // currently only support python - maybe in future we'll support js too String python = LangUtils.toPython(); Files.write(Paths.get(filename), python.toString().getBytes()); info("saved %s to %s", getName(), filename); return python; }
public String exportAll(String filename) throws IOException { // currently only support python - maybe in future we'll support js too String python = LangUtils.toPython(); Files.write(Paths.get(filename), python.toString().getBytes()); info("saved %s to %s", getName(), filename); return python; }
34,339
0
//Play selected song from playlist, to skip forward or back
private void createRowFactory(){ //Play selected song from playlist, to skip forward or back tableView.setRowFactory( tv -> { TableRow<PlaylistSongDisplay> row = new TableRow<>(); row.setOnMouseClicked(event -> { //On double click of song, play it if (event.getClickCount() == 2 && (! row.isEmpty()) ) { playlist.playPlaylistSelection(songHashMap.get(row.getItem())); } //On right click open context menu if (event.getButton() == MouseButton.SECONDARY) { ObservableList<PlaylistSongDisplay> selectedItems = tableView.getSelectionModel().getSelectedItems(); ArrayList<Song> selectedIDs = new ArrayList<>(); for (PlaylistSongDisplay rowSelected : selectedItems) { selectedIDs.add(songHashMap.get(rowSelected)); } //Allow for removal of selected songs from playlist removeSelected.setOnAction((actionEvent -> { playlist.removePlaylistSelection(selectedIDs); for (Song s: selectedIDs){ playlistList.remove(songHashMapRev.get(s)); } })); //Allow for clearing entire playlist clearPlaylist.setOnAction(actionEvent -> { playlist.clearPlaylist(); emptyTable(); }); //Show context menu at location of click playlistContextMenu.show(row, event.getScreenX(), event.getScreenY()); } //Undo selection if user clicks away from focused row if (event.getButton() == MouseButton.PRIMARY && (row.isEmpty())){ tableView.getSelectionModel().clearSelection(); } }); return row; }); //TODO: Add drag listener to move songs around as desired }
NONSATD
true
private void createRowFactory(){ //Play selected song from playlist, to skip forward or back tableView.setRowFactory( tv -> { TableRow<PlaylistSongDisplay> row = new TableRow<>();
private void createRowFactory(){ //Play selected song from playlist, to skip forward or back tableView.setRowFactory( tv -> { TableRow<PlaylistSongDisplay> row = new TableRow<>(); row.setOnMouseClicked(event -> { //On double click of song, play it if (event.getClickCount() == 2 && (! row.isEmpty()) ) { playlist.playPlaylistSelection(songHashMap.get(row.getItem())); } //On right click open context menu if (event.getButton() == MouseButton.SECONDARY) { ObservableList<PlaylistSongDisplay> selectedItems = tableView.getSelectionModel().getSelectedItems();
private void createRowFactory(){ //Play selected song from playlist, to skip forward or back tableView.setRowFactory( tv -> { TableRow<PlaylistSongDisplay> row = new TableRow<>(); row.setOnMouseClicked(event -> { //On double click of song, play it if (event.getClickCount() == 2 && (! row.isEmpty()) ) { playlist.playPlaylistSelection(songHashMap.get(row.getItem())); } //On right click open context menu if (event.getButton() == MouseButton.SECONDARY) { ObservableList<PlaylistSongDisplay> selectedItems = tableView.getSelectionModel().getSelectedItems(); ArrayList<Song> selectedIDs = new ArrayList<>(); for (PlaylistSongDisplay rowSelected : selectedItems) { selectedIDs.add(songHashMap.get(rowSelected)); } //Allow for removal of selected songs from playlist removeSelected.setOnAction((actionEvent -> { playlist.removePlaylistSelection(selectedIDs); for (Song s: selectedIDs){ playlistList.remove(songHashMapRev.get(s)); }
34,339
1
//On double click of song, play it
private void createRowFactory(){ //Play selected song from playlist, to skip forward or back tableView.setRowFactory( tv -> { TableRow<PlaylistSongDisplay> row = new TableRow<>(); row.setOnMouseClicked(event -> { //On double click of song, play it if (event.getClickCount() == 2 && (! row.isEmpty()) ) { playlist.playPlaylistSelection(songHashMap.get(row.getItem())); } //On right click open context menu if (event.getButton() == MouseButton.SECONDARY) { ObservableList<PlaylistSongDisplay> selectedItems = tableView.getSelectionModel().getSelectedItems(); ArrayList<Song> selectedIDs = new ArrayList<>(); for (PlaylistSongDisplay rowSelected : selectedItems) { selectedIDs.add(songHashMap.get(rowSelected)); } //Allow for removal of selected songs from playlist removeSelected.setOnAction((actionEvent -> { playlist.removePlaylistSelection(selectedIDs); for (Song s: selectedIDs){ playlistList.remove(songHashMapRev.get(s)); } })); //Allow for clearing entire playlist clearPlaylist.setOnAction(actionEvent -> { playlist.clearPlaylist(); emptyTable(); }); //Show context menu at location of click playlistContextMenu.show(row, event.getScreenX(), event.getScreenY()); } //Undo selection if user clicks away from focused row if (event.getButton() == MouseButton.PRIMARY && (row.isEmpty())){ tableView.getSelectionModel().clearSelection(); } }); return row; }); //TODO: Add drag listener to move songs around as desired }
NONSATD
true
TableRow<PlaylistSongDisplay> row = new TableRow<>(); row.setOnMouseClicked(event -> { //On double click of song, play it if (event.getClickCount() == 2 && (! row.isEmpty()) ) { playlist.playPlaylistSelection(songHashMap.get(row.getItem()));
private void createRowFactory(){ //Play selected song from playlist, to skip forward or back tableView.setRowFactory( tv -> { TableRow<PlaylistSongDisplay> row = new TableRow<>(); row.setOnMouseClicked(event -> { //On double click of song, play it if (event.getClickCount() == 2 && (! row.isEmpty()) ) { playlist.playPlaylistSelection(songHashMap.get(row.getItem())); } //On right click open context menu if (event.getButton() == MouseButton.SECONDARY) { ObservableList<PlaylistSongDisplay> selectedItems = tableView.getSelectionModel().getSelectedItems(); ArrayList<Song> selectedIDs = new ArrayList<>(); for (PlaylistSongDisplay rowSelected : selectedItems) { selectedIDs.add(songHashMap.get(rowSelected)); }
private void createRowFactory(){ //Play selected song from playlist, to skip forward or back tableView.setRowFactory( tv -> { TableRow<PlaylistSongDisplay> row = new TableRow<>(); row.setOnMouseClicked(event -> { //On double click of song, play it if (event.getClickCount() == 2 && (! row.isEmpty()) ) { playlist.playPlaylistSelection(songHashMap.get(row.getItem())); } //On right click open context menu if (event.getButton() == MouseButton.SECONDARY) { ObservableList<PlaylistSongDisplay> selectedItems = tableView.getSelectionModel().getSelectedItems(); ArrayList<Song> selectedIDs = new ArrayList<>(); for (PlaylistSongDisplay rowSelected : selectedItems) { selectedIDs.add(songHashMap.get(rowSelected)); } //Allow for removal of selected songs from playlist removeSelected.setOnAction((actionEvent -> { playlist.removePlaylistSelection(selectedIDs); for (Song s: selectedIDs){ playlistList.remove(songHashMapRev.get(s)); } })); //Allow for clearing entire playlist clearPlaylist.setOnAction(actionEvent -> { playlist.clearPlaylist();
34,339
2
//On right click open context menu
private void createRowFactory(){ //Play selected song from playlist, to skip forward or back tableView.setRowFactory( tv -> { TableRow<PlaylistSongDisplay> row = new TableRow<>(); row.setOnMouseClicked(event -> { //On double click of song, play it if (event.getClickCount() == 2 && (! row.isEmpty()) ) { playlist.playPlaylistSelection(songHashMap.get(row.getItem())); } //On right click open context menu if (event.getButton() == MouseButton.SECONDARY) { ObservableList<PlaylistSongDisplay> selectedItems = tableView.getSelectionModel().getSelectedItems(); ArrayList<Song> selectedIDs = new ArrayList<>(); for (PlaylistSongDisplay rowSelected : selectedItems) { selectedIDs.add(songHashMap.get(rowSelected)); } //Allow for removal of selected songs from playlist removeSelected.setOnAction((actionEvent -> { playlist.removePlaylistSelection(selectedIDs); for (Song s: selectedIDs){ playlistList.remove(songHashMapRev.get(s)); } })); //Allow for clearing entire playlist clearPlaylist.setOnAction(actionEvent -> { playlist.clearPlaylist(); emptyTable(); }); //Show context menu at location of click playlistContextMenu.show(row, event.getScreenX(), event.getScreenY()); } //Undo selection if user clicks away from focused row if (event.getButton() == MouseButton.PRIMARY && (row.isEmpty())){ tableView.getSelectionModel().clearSelection(); } }); return row; }); //TODO: Add drag listener to move songs around as desired }
NONSATD
true
playlist.playPlaylistSelection(songHashMap.get(row.getItem())); } //On right click open context menu if (event.getButton() == MouseButton.SECONDARY) { ObservableList<PlaylistSongDisplay> selectedItems = tableView.getSelectionModel().getSelectedItems();
private void createRowFactory(){ //Play selected song from playlist, to skip forward or back tableView.setRowFactory( tv -> { TableRow<PlaylistSongDisplay> row = new TableRow<>(); row.setOnMouseClicked(event -> { //On double click of song, play it if (event.getClickCount() == 2 && (! row.isEmpty()) ) { playlist.playPlaylistSelection(songHashMap.get(row.getItem())); } //On right click open context menu if (event.getButton() == MouseButton.SECONDARY) { ObservableList<PlaylistSongDisplay> selectedItems = tableView.getSelectionModel().getSelectedItems(); ArrayList<Song> selectedIDs = new ArrayList<>(); for (PlaylistSongDisplay rowSelected : selectedItems) { selectedIDs.add(songHashMap.get(rowSelected)); } //Allow for removal of selected songs from playlist removeSelected.setOnAction((actionEvent -> { playlist.removePlaylistSelection(selectedIDs); for (Song s: selectedIDs){
private void createRowFactory(){ //Play selected song from playlist, to skip forward or back tableView.setRowFactory( tv -> { TableRow<PlaylistSongDisplay> row = new TableRow<>(); row.setOnMouseClicked(event -> { //On double click of song, play it if (event.getClickCount() == 2 && (! row.isEmpty()) ) { playlist.playPlaylistSelection(songHashMap.get(row.getItem())); } //On right click open context menu if (event.getButton() == MouseButton.SECONDARY) { ObservableList<PlaylistSongDisplay> selectedItems = tableView.getSelectionModel().getSelectedItems(); ArrayList<Song> selectedIDs = new ArrayList<>(); for (PlaylistSongDisplay rowSelected : selectedItems) { selectedIDs.add(songHashMap.get(rowSelected)); } //Allow for removal of selected songs from playlist removeSelected.setOnAction((actionEvent -> { playlist.removePlaylistSelection(selectedIDs); for (Song s: selectedIDs){ playlistList.remove(songHashMapRev.get(s)); } })); //Allow for clearing entire playlist clearPlaylist.setOnAction(actionEvent -> { playlist.clearPlaylist(); emptyTable(); }); //Show context menu at location of click playlistContextMenu.show(row, event.getScreenX(), event.getScreenY());
34,339
3
//Allow for removal of selected songs from playlist
private void createRowFactory(){ //Play selected song from playlist, to skip forward or back tableView.setRowFactory( tv -> { TableRow<PlaylistSongDisplay> row = new TableRow<>(); row.setOnMouseClicked(event -> { //On double click of song, play it if (event.getClickCount() == 2 && (! row.isEmpty()) ) { playlist.playPlaylistSelection(songHashMap.get(row.getItem())); } //On right click open context menu if (event.getButton() == MouseButton.SECONDARY) { ObservableList<PlaylistSongDisplay> selectedItems = tableView.getSelectionModel().getSelectedItems(); ArrayList<Song> selectedIDs = new ArrayList<>(); for (PlaylistSongDisplay rowSelected : selectedItems) { selectedIDs.add(songHashMap.get(rowSelected)); } //Allow for removal of selected songs from playlist removeSelected.setOnAction((actionEvent -> { playlist.removePlaylistSelection(selectedIDs); for (Song s: selectedIDs){ playlistList.remove(songHashMapRev.get(s)); } })); //Allow for clearing entire playlist clearPlaylist.setOnAction(actionEvent -> { playlist.clearPlaylist(); emptyTable(); }); //Show context menu at location of click playlistContextMenu.show(row, event.getScreenX(), event.getScreenY()); } //Undo selection if user clicks away from focused row if (event.getButton() == MouseButton.PRIMARY && (row.isEmpty())){ tableView.getSelectionModel().clearSelection(); } }); return row; }); //TODO: Add drag listener to move songs around as desired }
NONSATD
true
selectedIDs.add(songHashMap.get(rowSelected)); } //Allow for removal of selected songs from playlist removeSelected.setOnAction((actionEvent -> { playlist.removePlaylistSelection(selectedIDs);
if (event.getClickCount() == 2 && (! row.isEmpty()) ) { playlist.playPlaylistSelection(songHashMap.get(row.getItem())); } //On right click open context menu if (event.getButton() == MouseButton.SECONDARY) { ObservableList<PlaylistSongDisplay> selectedItems = tableView.getSelectionModel().getSelectedItems(); ArrayList<Song> selectedIDs = new ArrayList<>(); for (PlaylistSongDisplay rowSelected : selectedItems) { selectedIDs.add(songHashMap.get(rowSelected)); } //Allow for removal of selected songs from playlist removeSelected.setOnAction((actionEvent -> { playlist.removePlaylistSelection(selectedIDs); for (Song s: selectedIDs){ playlistList.remove(songHashMapRev.get(s)); } })); //Allow for clearing entire playlist clearPlaylist.setOnAction(actionEvent -> { playlist.clearPlaylist(); emptyTable();
private void createRowFactory(){ //Play selected song from playlist, to skip forward or back tableView.setRowFactory( tv -> { TableRow<PlaylistSongDisplay> row = new TableRow<>(); row.setOnMouseClicked(event -> { //On double click of song, play it if (event.getClickCount() == 2 && (! row.isEmpty()) ) { playlist.playPlaylistSelection(songHashMap.get(row.getItem())); } //On right click open context menu if (event.getButton() == MouseButton.SECONDARY) { ObservableList<PlaylistSongDisplay> selectedItems = tableView.getSelectionModel().getSelectedItems(); ArrayList<Song> selectedIDs = new ArrayList<>(); for (PlaylistSongDisplay rowSelected : selectedItems) { selectedIDs.add(songHashMap.get(rowSelected)); } //Allow for removal of selected songs from playlist removeSelected.setOnAction((actionEvent -> { playlist.removePlaylistSelection(selectedIDs); for (Song s: selectedIDs){ playlistList.remove(songHashMapRev.get(s)); } })); //Allow for clearing entire playlist clearPlaylist.setOnAction(actionEvent -> { playlist.clearPlaylist(); emptyTable(); }); //Show context menu at location of click playlistContextMenu.show(row, event.getScreenX(), event.getScreenY()); } //Undo selection if user clicks away from focused row if (event.getButton() == MouseButton.PRIMARY && (row.isEmpty())){ tableView.getSelectionModel().clearSelection(); } }); return row;
34,339
4
//Allow for clearing entire playlist
private void createRowFactory(){ //Play selected song from playlist, to skip forward or back tableView.setRowFactory( tv -> { TableRow<PlaylistSongDisplay> row = new TableRow<>(); row.setOnMouseClicked(event -> { //On double click of song, play it if (event.getClickCount() == 2 && (! row.isEmpty()) ) { playlist.playPlaylistSelection(songHashMap.get(row.getItem())); } //On right click open context menu if (event.getButton() == MouseButton.SECONDARY) { ObservableList<PlaylistSongDisplay> selectedItems = tableView.getSelectionModel().getSelectedItems(); ArrayList<Song> selectedIDs = new ArrayList<>(); for (PlaylistSongDisplay rowSelected : selectedItems) { selectedIDs.add(songHashMap.get(rowSelected)); } //Allow for removal of selected songs from playlist removeSelected.setOnAction((actionEvent -> { playlist.removePlaylistSelection(selectedIDs); for (Song s: selectedIDs){ playlistList.remove(songHashMapRev.get(s)); } })); //Allow for clearing entire playlist clearPlaylist.setOnAction(actionEvent -> { playlist.clearPlaylist(); emptyTable(); }); //Show context menu at location of click playlistContextMenu.show(row, event.getScreenX(), event.getScreenY()); } //Undo selection if user clicks away from focused row if (event.getButton() == MouseButton.PRIMARY && (row.isEmpty())){ tableView.getSelectionModel().clearSelection(); } }); return row; }); //TODO: Add drag listener to move songs around as desired }
NONSATD
true
} })); //Allow for clearing entire playlist clearPlaylist.setOnAction(actionEvent -> { playlist.clearPlaylist();
for (PlaylistSongDisplay rowSelected : selectedItems) { selectedIDs.add(songHashMap.get(rowSelected)); } //Allow for removal of selected songs from playlist removeSelected.setOnAction((actionEvent -> { playlist.removePlaylistSelection(selectedIDs); for (Song s: selectedIDs){ playlistList.remove(songHashMapRev.get(s)); } })); //Allow for clearing entire playlist clearPlaylist.setOnAction(actionEvent -> { playlist.clearPlaylist(); emptyTable(); }); //Show context menu at location of click playlistContextMenu.show(row, event.getScreenX(), event.getScreenY()); } //Undo selection if user clicks away from focused row if (event.getButton() == MouseButton.PRIMARY && (row.isEmpty())){ tableView.getSelectionModel().clearSelection();
TableRow<PlaylistSongDisplay> row = new TableRow<>(); row.setOnMouseClicked(event -> { //On double click of song, play it if (event.getClickCount() == 2 && (! row.isEmpty()) ) { playlist.playPlaylistSelection(songHashMap.get(row.getItem())); } //On right click open context menu if (event.getButton() == MouseButton.SECONDARY) { ObservableList<PlaylistSongDisplay> selectedItems = tableView.getSelectionModel().getSelectedItems(); ArrayList<Song> selectedIDs = new ArrayList<>(); for (PlaylistSongDisplay rowSelected : selectedItems) { selectedIDs.add(songHashMap.get(rowSelected)); } //Allow for removal of selected songs from playlist removeSelected.setOnAction((actionEvent -> { playlist.removePlaylistSelection(selectedIDs); for (Song s: selectedIDs){ playlistList.remove(songHashMapRev.get(s)); } })); //Allow for clearing entire playlist clearPlaylist.setOnAction(actionEvent -> { playlist.clearPlaylist(); emptyTable(); }); //Show context menu at location of click playlistContextMenu.show(row, event.getScreenX(), event.getScreenY()); } //Undo selection if user clicks away from focused row if (event.getButton() == MouseButton.PRIMARY && (row.isEmpty())){ tableView.getSelectionModel().clearSelection(); } }); return row; }); //TODO: Add drag listener to move songs around as desired }
34,339
5
//Show context menu at location of click
private void createRowFactory(){ //Play selected song from playlist, to skip forward or back tableView.setRowFactory( tv -> { TableRow<PlaylistSongDisplay> row = new TableRow<>(); row.setOnMouseClicked(event -> { //On double click of song, play it if (event.getClickCount() == 2 && (! row.isEmpty()) ) { playlist.playPlaylistSelection(songHashMap.get(row.getItem())); } //On right click open context menu if (event.getButton() == MouseButton.SECONDARY) { ObservableList<PlaylistSongDisplay> selectedItems = tableView.getSelectionModel().getSelectedItems(); ArrayList<Song> selectedIDs = new ArrayList<>(); for (PlaylistSongDisplay rowSelected : selectedItems) { selectedIDs.add(songHashMap.get(rowSelected)); } //Allow for removal of selected songs from playlist removeSelected.setOnAction((actionEvent -> { playlist.removePlaylistSelection(selectedIDs); for (Song s: selectedIDs){ playlistList.remove(songHashMapRev.get(s)); } })); //Allow for clearing entire playlist clearPlaylist.setOnAction(actionEvent -> { playlist.clearPlaylist(); emptyTable(); }); //Show context menu at location of click playlistContextMenu.show(row, event.getScreenX(), event.getScreenY()); } //Undo selection if user clicks away from focused row if (event.getButton() == MouseButton.PRIMARY && (row.isEmpty())){ tableView.getSelectionModel().clearSelection(); } }); return row; }); //TODO: Add drag listener to move songs around as desired }
NONSATD
true
emptyTable(); }); //Show context menu at location of click playlistContextMenu.show(row, event.getScreenX(), event.getScreenY()); }
playlist.removePlaylistSelection(selectedIDs); for (Song s: selectedIDs){ playlistList.remove(songHashMapRev.get(s)); } })); //Allow for clearing entire playlist clearPlaylist.setOnAction(actionEvent -> { playlist.clearPlaylist(); emptyTable(); }); //Show context menu at location of click playlistContextMenu.show(row, event.getScreenX(), event.getScreenY()); } //Undo selection if user clicks away from focused row if (event.getButton() == MouseButton.PRIMARY && (row.isEmpty())){ tableView.getSelectionModel().clearSelection(); } }); return row; }); //TODO: Add drag listener to move songs around as desired
} //On right click open context menu if (event.getButton() == MouseButton.SECONDARY) { ObservableList<PlaylistSongDisplay> selectedItems = tableView.getSelectionModel().getSelectedItems(); ArrayList<Song> selectedIDs = new ArrayList<>(); for (PlaylistSongDisplay rowSelected : selectedItems) { selectedIDs.add(songHashMap.get(rowSelected)); } //Allow for removal of selected songs from playlist removeSelected.setOnAction((actionEvent -> { playlist.removePlaylistSelection(selectedIDs); for (Song s: selectedIDs){ playlistList.remove(songHashMapRev.get(s)); } })); //Allow for clearing entire playlist clearPlaylist.setOnAction(actionEvent -> { playlist.clearPlaylist(); emptyTable(); }); //Show context menu at location of click playlistContextMenu.show(row, event.getScreenX(), event.getScreenY()); } //Undo selection if user clicks away from focused row if (event.getButton() == MouseButton.PRIMARY && (row.isEmpty())){ tableView.getSelectionModel().clearSelection(); } }); return row; }); //TODO: Add drag listener to move songs around as desired }
34,339
6
//Undo selection if user clicks away from focused row
private void createRowFactory(){ //Play selected song from playlist, to skip forward or back tableView.setRowFactory( tv -> { TableRow<PlaylistSongDisplay> row = new TableRow<>(); row.setOnMouseClicked(event -> { //On double click of song, play it if (event.getClickCount() == 2 && (! row.isEmpty()) ) { playlist.playPlaylistSelection(songHashMap.get(row.getItem())); } //On right click open context menu if (event.getButton() == MouseButton.SECONDARY) { ObservableList<PlaylistSongDisplay> selectedItems = tableView.getSelectionModel().getSelectedItems(); ArrayList<Song> selectedIDs = new ArrayList<>(); for (PlaylistSongDisplay rowSelected : selectedItems) { selectedIDs.add(songHashMap.get(rowSelected)); } //Allow for removal of selected songs from playlist removeSelected.setOnAction((actionEvent -> { playlist.removePlaylistSelection(selectedIDs); for (Song s: selectedIDs){ playlistList.remove(songHashMapRev.get(s)); } })); //Allow for clearing entire playlist clearPlaylist.setOnAction(actionEvent -> { playlist.clearPlaylist(); emptyTable(); }); //Show context menu at location of click playlistContextMenu.show(row, event.getScreenX(), event.getScreenY()); } //Undo selection if user clicks away from focused row if (event.getButton() == MouseButton.PRIMARY && (row.isEmpty())){ tableView.getSelectionModel().clearSelection(); } }); return row; }); //TODO: Add drag listener to move songs around as desired }
NONSATD
true
playlistContextMenu.show(row, event.getScreenX(), event.getScreenY()); } //Undo selection if user clicks away from focused row if (event.getButton() == MouseButton.PRIMARY && (row.isEmpty())){ tableView.getSelectionModel().clearSelection();
} })); //Allow for clearing entire playlist clearPlaylist.setOnAction(actionEvent -> { playlist.clearPlaylist(); emptyTable(); }); //Show context menu at location of click playlistContextMenu.show(row, event.getScreenX(), event.getScreenY()); } //Undo selection if user clicks away from focused row if (event.getButton() == MouseButton.PRIMARY && (row.isEmpty())){ tableView.getSelectionModel().clearSelection(); } }); return row; }); //TODO: Add drag listener to move songs around as desired }
ObservableList<PlaylistSongDisplay> selectedItems = tableView.getSelectionModel().getSelectedItems(); ArrayList<Song> selectedIDs = new ArrayList<>(); for (PlaylistSongDisplay rowSelected : selectedItems) { selectedIDs.add(songHashMap.get(rowSelected)); } //Allow for removal of selected songs from playlist removeSelected.setOnAction((actionEvent -> { playlist.removePlaylistSelection(selectedIDs); for (Song s: selectedIDs){ playlistList.remove(songHashMapRev.get(s)); } })); //Allow for clearing entire playlist clearPlaylist.setOnAction(actionEvent -> { playlist.clearPlaylist(); emptyTable(); }); //Show context menu at location of click playlistContextMenu.show(row, event.getScreenX(), event.getScreenY()); } //Undo selection if user clicks away from focused row if (event.getButton() == MouseButton.PRIMARY && (row.isEmpty())){ tableView.getSelectionModel().clearSelection(); } }); return row; }); //TODO: Add drag listener to move songs around as desired }
34,339
7
//TODO: Add drag listener to move songs around as desired
private void createRowFactory(){ //Play selected song from playlist, to skip forward or back tableView.setRowFactory( tv -> { TableRow<PlaylistSongDisplay> row = new TableRow<>(); row.setOnMouseClicked(event -> { //On double click of song, play it if (event.getClickCount() == 2 && (! row.isEmpty()) ) { playlist.playPlaylistSelection(songHashMap.get(row.getItem())); } //On right click open context menu if (event.getButton() == MouseButton.SECONDARY) { ObservableList<PlaylistSongDisplay> selectedItems = tableView.getSelectionModel().getSelectedItems(); ArrayList<Song> selectedIDs = new ArrayList<>(); for (PlaylistSongDisplay rowSelected : selectedItems) { selectedIDs.add(songHashMap.get(rowSelected)); } //Allow for removal of selected songs from playlist removeSelected.setOnAction((actionEvent -> { playlist.removePlaylistSelection(selectedIDs); for (Song s: selectedIDs){ playlistList.remove(songHashMapRev.get(s)); } })); //Allow for clearing entire playlist clearPlaylist.setOnAction(actionEvent -> { playlist.clearPlaylist(); emptyTable(); }); //Show context menu at location of click playlistContextMenu.show(row, event.getScreenX(), event.getScreenY()); } //Undo selection if user clicks away from focused row if (event.getButton() == MouseButton.PRIMARY && (row.isEmpty())){ tableView.getSelectionModel().clearSelection(); } }); return row; }); //TODO: Add drag listener to move songs around as desired }
IMPLEMENTATION
true
return row; }); //TODO: Add drag listener to move songs around as desired }
//Show context menu at location of click playlistContextMenu.show(row, event.getScreenX(), event.getScreenY()); } //Undo selection if user clicks away from focused row if (event.getButton() == MouseButton.PRIMARY && (row.isEmpty())){ tableView.getSelectionModel().clearSelection(); } }); return row; }); //TODO: Add drag listener to move songs around as desired }
playlist.removePlaylistSelection(selectedIDs); for (Song s: selectedIDs){ playlistList.remove(songHashMapRev.get(s)); } })); //Allow for clearing entire playlist clearPlaylist.setOnAction(actionEvent -> { playlist.clearPlaylist(); emptyTable(); }); //Show context menu at location of click playlistContextMenu.show(row, event.getScreenX(), event.getScreenY()); } //Undo selection if user clicks away from focused row if (event.getButton() == MouseButton.PRIMARY && (row.isEmpty())){ tableView.getSelectionModel().clearSelection(); } }); return row; }); //TODO: Add drag listener to move songs around as desired }
34,349
0
// Map 1 .......... container SUCCEEDED 7 7 0 0 0 0 // TODO: can we pass custom things thru the progress?
public List<List<String>> rows() { try { List<List<String>> results = new ArrayList<>(); for (BaseWork baseWork : topSortedWork) { String vertexName = baseWork.getName(); VertexProgress progress = progressCountsMap.get(vertexName); if (progress != null) { // Map 1 .......... container SUCCEEDED 7 7 0 0 0 0 // TODO: can we pass custom things thru the progress? results.add( Arrays.asList( getNameWithProgress(vertexName, progress.succeededTaskCount, progress.totalTaskCount), getMode(baseWork), progress.vertexStatus(vertexStatusMap.get(vertexName)), progress.total(), progress.completed(), progress.running(), progress.pending(), progress.failed(), progress.killed() ) ); } } return results; } catch (Exception e) { console.printInfo( "Getting Progress Bar table rows failed: " + e.getMessage() + " stack trace: " + Arrays .toString(e.getStackTrace()) ); } return Collections.emptyList(); }
DESIGN
true
VertexProgress progress = progressCountsMap.get(vertexName); if (progress != null) { // Map 1 .......... container SUCCEEDED 7 7 0 0 0 0 // TODO: can we pass custom things thru the progress? results.add( Arrays.asList(
public List<List<String>> rows() { try { List<List<String>> results = new ArrayList<>(); for (BaseWork baseWork : topSortedWork) { String vertexName = baseWork.getName(); VertexProgress progress = progressCountsMap.get(vertexName); if (progress != null) { // Map 1 .......... container SUCCEEDED 7 7 0 0 0 0 // TODO: can we pass custom things thru the progress? results.add( Arrays.asList( getNameWithProgress(vertexName, progress.succeededTaskCount, progress.totalTaskCount), getMode(baseWork), progress.vertexStatus(vertexStatusMap.get(vertexName)), progress.total(), progress.completed(), progress.running(), progress.pending(), progress.failed(),
public List<List<String>> rows() { try { List<List<String>> results = new ArrayList<>(); for (BaseWork baseWork : topSortedWork) { String vertexName = baseWork.getName(); VertexProgress progress = progressCountsMap.get(vertexName); if (progress != null) { // Map 1 .......... container SUCCEEDED 7 7 0 0 0 0 // TODO: can we pass custom things thru the progress? results.add( Arrays.asList( getNameWithProgress(vertexName, progress.succeededTaskCount, progress.totalTaskCount), getMode(baseWork), progress.vertexStatus(vertexStatusMap.get(vertexName)), progress.total(), progress.completed(), progress.running(), progress.pending(), progress.failed(), progress.killed() ) ); } } return results; } catch (Exception e) { console.printInfo( "Getting Progress Bar table rows failed: " + e.getMessage() + " stack trace: " + Arrays .toString(e.getStackTrace())
9,775
0
// Ouch, my fingers hurt! All this typing!
public static void main(String[] args) { File dir = new File("."); Arrays.stream(dir.listFiles()).forEach(file -> { try { System.out.println(file.getCanonicalPath()); } catch (IOException e) { throw new RuntimeException(e); } // Ouch, my fingers hurt! All this typing! }); // TODO use Unchecked.consumer from JOOL library // SOLUTION( Arrays.stream(dir.listFiles()).forEach(Unchecked.consumer(file -> { System.out.println(file.getCanonicalPath()); })); // SOLUTION) }
NONSATD
true
throw new RuntimeException(e); } // Ouch, my fingers hurt! All this typing! }); // TODO use Unchecked.consumer from JOOL library
public static void main(String[] args) { File dir = new File("."); Arrays.stream(dir.listFiles()).forEach(file -> { try { System.out.println(file.getCanonicalPath()); } catch (IOException e) { throw new RuntimeException(e); } // Ouch, my fingers hurt! All this typing! }); // TODO use Unchecked.consumer from JOOL library // SOLUTION( Arrays.stream(dir.listFiles()).forEach(Unchecked.consumer(file -> { System.out.println(file.getCanonicalPath()); })); // SOLUTION) }
public static void main(String[] args) { File dir = new File("."); Arrays.stream(dir.listFiles()).forEach(file -> { try { System.out.println(file.getCanonicalPath()); } catch (IOException e) { throw new RuntimeException(e); } // Ouch, my fingers hurt! All this typing! }); // TODO use Unchecked.consumer from JOOL library // SOLUTION( Arrays.stream(dir.listFiles()).forEach(Unchecked.consumer(file -> { System.out.println(file.getCanonicalPath()); })); // SOLUTION) }
9,775
1
// TODO use Unchecked.consumer from JOOL library // SOLUTION(
public static void main(String[] args) { File dir = new File("."); Arrays.stream(dir.listFiles()).forEach(file -> { try { System.out.println(file.getCanonicalPath()); } catch (IOException e) { throw new RuntimeException(e); } // Ouch, my fingers hurt! All this typing! }); // TODO use Unchecked.consumer from JOOL library // SOLUTION( Arrays.stream(dir.listFiles()).forEach(Unchecked.consumer(file -> { System.out.println(file.getCanonicalPath()); })); // SOLUTION) }
NONSATD
true
// Ouch, my fingers hurt! All this typing! }); // TODO use Unchecked.consumer from JOOL library // SOLUTION( Arrays.stream(dir.listFiles()).forEach(Unchecked.consumer(file -> { System.out.println(file.getCanonicalPath());
public static void main(String[] args) { File dir = new File("."); Arrays.stream(dir.listFiles()).forEach(file -> { try { System.out.println(file.getCanonicalPath()); } catch (IOException e) { throw new RuntimeException(e); } // Ouch, my fingers hurt! All this typing! }); // TODO use Unchecked.consumer from JOOL library // SOLUTION( Arrays.stream(dir.listFiles()).forEach(Unchecked.consumer(file -> { System.out.println(file.getCanonicalPath()); })); // SOLUTION) }
public static void main(String[] args) { File dir = new File("."); Arrays.stream(dir.listFiles()).forEach(file -> { try { System.out.println(file.getCanonicalPath()); } catch (IOException e) { throw new RuntimeException(e); } // Ouch, my fingers hurt! All this typing! }); // TODO use Unchecked.consumer from JOOL library // SOLUTION( Arrays.stream(dir.listFiles()).forEach(Unchecked.consumer(file -> { System.out.println(file.getCanonicalPath()); })); // SOLUTION) }
9,775
2
// SOLUTION)
public static void main(String[] args) { File dir = new File("."); Arrays.stream(dir.listFiles()).forEach(file -> { try { System.out.println(file.getCanonicalPath()); } catch (IOException e) { throw new RuntimeException(e); } // Ouch, my fingers hurt! All this typing! }); // TODO use Unchecked.consumer from JOOL library // SOLUTION( Arrays.stream(dir.listFiles()).forEach(Unchecked.consumer(file -> { System.out.println(file.getCanonicalPath()); })); // SOLUTION) }
NONSATD
true
System.out.println(file.getCanonicalPath()); })); // SOLUTION) }
} catch (IOException e) { throw new RuntimeException(e); } // Ouch, my fingers hurt! All this typing! }); // TODO use Unchecked.consumer from JOOL library // SOLUTION( Arrays.stream(dir.listFiles()).forEach(Unchecked.consumer(file -> { System.out.println(file.getCanonicalPath()); })); // SOLUTION) }
public static void main(String[] args) { File dir = new File("."); Arrays.stream(dir.listFiles()).forEach(file -> { try { System.out.println(file.getCanonicalPath()); } catch (IOException e) { throw new RuntimeException(e); } // Ouch, my fingers hurt! All this typing! }); // TODO use Unchecked.consumer from JOOL library // SOLUTION( Arrays.stream(dir.listFiles()).forEach(Unchecked.consumer(file -> { System.out.println(file.getCanonicalPath()); })); // SOLUTION) }
26,161
0
// We might even consider updating the user-supplied file, if any...
@Override public boolean saveSettings() { // We might even consider updating the user-supplied file, if any... return false; }
DESIGN
true
@Override public boolean saveSettings() { // We might even consider updating the user-supplied file, if any... return false; }
@Override public boolean saveSettings() { // We might even consider updating the user-supplied file, if any... return false; }
@Override public boolean saveSettings() { // We might even consider updating the user-supplied file, if any... return false; }
9,779
0
// todo - improved error message
Statement compileSQLProcedureStatementOrNull(Routine routine, StatementCompound context) { Statement cs = null; HsqlName label = null; RangeVariable[] rangeVariables = context == null ? routine.getParameterRangeVariables() : context.getRangeVariables(); if (!routine.isTrigger() && isSimpleName() && !isReservedKey()) { label = readNewSchemaObjectName(SchemaObject.LABEL, false); // todo - improved error message if (token.tokenType != Tokens.COLON) { throw unexpectedToken(label.getNameString()); } readThis(Tokens.COLON); } compileContext.reset(); HsqlName oldSchema = session.getCurrentSchemaHsqlName(); session.setCurrentSchemaHsqlName(routine.getSchemaName()); try { switch (token.tokenType) { // data case Tokens.OPEN : { if (routine.dataImpact == Routine.CONTAINS_SQL) { throw Error.error(ErrorCode.X_42602, routine.getDataImpactString()); } if (label != null) { throw unexpectedToken(); } cs = compileOpenCursorStatement(context); break; } case Tokens.SELECT : { if (label != null) { throw unexpectedToken(); } cs = compileSelectSingleRowStatement(rangeVariables); break; } // data change case Tokens.INSERT : if (label != null) { throw unexpectedToken(); } cs = compileInsertStatement(rangeVariables); break; case Tokens.UPDATE : if (label != null) { throw unexpectedToken(); } cs = compileUpdateStatement(rangeVariables); break; case Tokens.DELETE : if (label != null) { throw unexpectedToken(); } cs = compileDeleteStatement(rangeVariables); break; case Tokens.TRUNCATE : if (label != null) { throw unexpectedToken(); } cs = compileTruncateStatement(); break; case Tokens.MERGE : if (label != null) { throw unexpectedToken(); } cs = compileMergeStatement(rangeVariables); break; case Tokens.SET : if (label != null) { throw unexpectedToken(); } if (routine.isTrigger()) { if (routine.triggerOperation == StatementTypes.DELETE_WHERE) { cs = compileSetStatement(rangeVariables); break; } if (routine.triggerType != TriggerDef.BEFORE) { cs = compileSetStatement(rangeVariables); break; } int position = super.getPosition(); try { cs = compileTriggerSetStatement( routine.triggerTable, rangeVariables); } catch (HsqlException e) { rewind(position); cs = compileSetStatement(rangeVariables); } } else { cs = compileSetStatement(rangeVariables); } break; case Tokens.GET : if (label != null) { throw unexpectedToken(); } cs = this.compileGetStatement(rangeVariables); break; // control case Tokens.CALL : { if (label != null) { throw unexpectedToken(); } cs = compileCallStatement(rangeVariables, true); Routine proc = ((StatementProcedure) cs).procedure; if (proc != null) { switch (routine.dataImpact) { case Routine.CONTAINS_SQL : { if (proc.dataImpact == Routine.READS_SQL || proc.dataImpact == Routine.MODIFIES_SQL) { throw Error.error( ErrorCode.X_42602, routine.getDataImpactString()); } break; } case Routine.READS_SQL : { if (proc.dataImpact == Routine.MODIFIES_SQL) { throw Error.error( ErrorCode.X_42602, routine.getDataImpactString()); } break; } } } break; } case Tokens.RETURN : { if (routine.isTrigger() || label != null) { throw unexpectedToken(); } read(); cs = compileReturnValue(routine, context); break; } case Tokens.BEGIN : { cs = compileCompoundStatement(routine, context, label); break; } case Tokens.WHILE : { if (routine.isTrigger()) { throw unexpectedToken(); } cs = compileWhile(routine, context, label); break; } case Tokens.REPEAT : { cs = compileRepeat(routine, context, label); break; } case Tokens.LOOP : { cs = compileLoop(routine, context, label); break; } case Tokens.FOR : { cs = compileFor(routine, context, label); break; } case Tokens.ITERATE : { if (label != null) { throw unexpectedToken(); } cs = compileIterate(); break; } case Tokens.LEAVE : { if (label != null) { throw unexpectedToken(); } cs = compileLeave(routine, context); break; } case Tokens.IF : { cs = compileIf(routine, context); break; } case Tokens.CASE : { cs = compileCase(routine, context); break; } case Tokens.SIGNAL : { cs = compileSignal(routine, context, label); break; } case Tokens.RESIGNAL : { cs = compileResignal(routine, context, label); break; } default : return null; } cs.setRoot(routine); cs.setParent(context); return cs; } finally { session.setCurrentSchemaHsqlName(oldSchema); } }
IMPLEMENTATION
true
if (!routine.isTrigger() && isSimpleName() && !isReservedKey()) { label = readNewSchemaObjectName(SchemaObject.LABEL, false); // todo - improved error message if (token.tokenType != Tokens.COLON) { throw unexpectedToken(label.getNameString());
Statement compileSQLProcedureStatementOrNull(Routine routine, StatementCompound context) { Statement cs = null; HsqlName label = null; RangeVariable[] rangeVariables = context == null ? routine.getParameterRangeVariables() : context.getRangeVariables(); if (!routine.isTrigger() && isSimpleName() && !isReservedKey()) { label = readNewSchemaObjectName(SchemaObject.LABEL, false); // todo - improved error message if (token.tokenType != Tokens.COLON) { throw unexpectedToken(label.getNameString()); } readThis(Tokens.COLON); } compileContext.reset(); HsqlName oldSchema = session.getCurrentSchemaHsqlName(); session.setCurrentSchemaHsqlName(routine.getSchemaName()); try { switch (token.tokenType) {
Statement compileSQLProcedureStatementOrNull(Routine routine, StatementCompound context) { Statement cs = null; HsqlName label = null; RangeVariable[] rangeVariables = context == null ? routine.getParameterRangeVariables() : context.getRangeVariables(); if (!routine.isTrigger() && isSimpleName() && !isReservedKey()) { label = readNewSchemaObjectName(SchemaObject.LABEL, false); // todo - improved error message if (token.tokenType != Tokens.COLON) { throw unexpectedToken(label.getNameString()); } readThis(Tokens.COLON); } compileContext.reset(); HsqlName oldSchema = session.getCurrentSchemaHsqlName(); session.setCurrentSchemaHsqlName(routine.getSchemaName()); try { switch (token.tokenType) { // data case Tokens.OPEN : { if (routine.dataImpact == Routine.CONTAINS_SQL) { throw Error.error(ErrorCode.X_42602, routine.getDataImpactString()); } if (label != null) { throw unexpectedToken(); } cs = compileOpenCursorStatement(context);
9,779
1
// data
Statement compileSQLProcedureStatementOrNull(Routine routine, StatementCompound context) { Statement cs = null; HsqlName label = null; RangeVariable[] rangeVariables = context == null ? routine.getParameterRangeVariables() : context.getRangeVariables(); if (!routine.isTrigger() && isSimpleName() && !isReservedKey()) { label = readNewSchemaObjectName(SchemaObject.LABEL, false); // todo - improved error message if (token.tokenType != Tokens.COLON) { throw unexpectedToken(label.getNameString()); } readThis(Tokens.COLON); } compileContext.reset(); HsqlName oldSchema = session.getCurrentSchemaHsqlName(); session.setCurrentSchemaHsqlName(routine.getSchemaName()); try { switch (token.tokenType) { // data case Tokens.OPEN : { if (routine.dataImpact == Routine.CONTAINS_SQL) { throw Error.error(ErrorCode.X_42602, routine.getDataImpactString()); } if (label != null) { throw unexpectedToken(); } cs = compileOpenCursorStatement(context); break; } case Tokens.SELECT : { if (label != null) { throw unexpectedToken(); } cs = compileSelectSingleRowStatement(rangeVariables); break; } // data change case Tokens.INSERT : if (label != null) { throw unexpectedToken(); } cs = compileInsertStatement(rangeVariables); break; case Tokens.UPDATE : if (label != null) { throw unexpectedToken(); } cs = compileUpdateStatement(rangeVariables); break; case Tokens.DELETE : if (label != null) { throw unexpectedToken(); } cs = compileDeleteStatement(rangeVariables); break; case Tokens.TRUNCATE : if (label != null) { throw unexpectedToken(); } cs = compileTruncateStatement(); break; case Tokens.MERGE : if (label != null) { throw unexpectedToken(); } cs = compileMergeStatement(rangeVariables); break; case Tokens.SET : if (label != null) { throw unexpectedToken(); } if (routine.isTrigger()) { if (routine.triggerOperation == StatementTypes.DELETE_WHERE) { cs = compileSetStatement(rangeVariables); break; } if (routine.triggerType != TriggerDef.BEFORE) { cs = compileSetStatement(rangeVariables); break; } int position = super.getPosition(); try { cs = compileTriggerSetStatement( routine.triggerTable, rangeVariables); } catch (HsqlException e) { rewind(position); cs = compileSetStatement(rangeVariables); } } else { cs = compileSetStatement(rangeVariables); } break; case Tokens.GET : if (label != null) { throw unexpectedToken(); } cs = this.compileGetStatement(rangeVariables); break; // control case Tokens.CALL : { if (label != null) { throw unexpectedToken(); } cs = compileCallStatement(rangeVariables, true); Routine proc = ((StatementProcedure) cs).procedure; if (proc != null) { switch (routine.dataImpact) { case Routine.CONTAINS_SQL : { if (proc.dataImpact == Routine.READS_SQL || proc.dataImpact == Routine.MODIFIES_SQL) { throw Error.error( ErrorCode.X_42602, routine.getDataImpactString()); } break; } case Routine.READS_SQL : { if (proc.dataImpact == Routine.MODIFIES_SQL) { throw Error.error( ErrorCode.X_42602, routine.getDataImpactString()); } break; } } } break; } case Tokens.RETURN : { if (routine.isTrigger() || label != null) { throw unexpectedToken(); } read(); cs = compileReturnValue(routine, context); break; } case Tokens.BEGIN : { cs = compileCompoundStatement(routine, context, label); break; } case Tokens.WHILE : { if (routine.isTrigger()) { throw unexpectedToken(); } cs = compileWhile(routine, context, label); break; } case Tokens.REPEAT : { cs = compileRepeat(routine, context, label); break; } case Tokens.LOOP : { cs = compileLoop(routine, context, label); break; } case Tokens.FOR : { cs = compileFor(routine, context, label); break; } case Tokens.ITERATE : { if (label != null) { throw unexpectedToken(); } cs = compileIterate(); break; } case Tokens.LEAVE : { if (label != null) { throw unexpectedToken(); } cs = compileLeave(routine, context); break; } case Tokens.IF : { cs = compileIf(routine, context); break; } case Tokens.CASE : { cs = compileCase(routine, context); break; } case Tokens.SIGNAL : { cs = compileSignal(routine, context, label); break; } case Tokens.RESIGNAL : { cs = compileResignal(routine, context, label); break; } default : return null; } cs.setRoot(routine); cs.setParent(context); return cs; } finally { session.setCurrentSchemaHsqlName(oldSchema); } }
NONSATD
true
try { switch (token.tokenType) { // data case Tokens.OPEN : { if (routine.dataImpact == Routine.CONTAINS_SQL) {
if (token.tokenType != Tokens.COLON) { throw unexpectedToken(label.getNameString()); } readThis(Tokens.COLON); } compileContext.reset(); HsqlName oldSchema = session.getCurrentSchemaHsqlName(); session.setCurrentSchemaHsqlName(routine.getSchemaName()); try { switch (token.tokenType) { // data case Tokens.OPEN : { if (routine.dataImpact == Routine.CONTAINS_SQL) { throw Error.error(ErrorCode.X_42602, routine.getDataImpactString()); } if (label != null) { throw unexpectedToken(); } cs = compileOpenCursorStatement(context); break;
Statement compileSQLProcedureStatementOrNull(Routine routine, StatementCompound context) { Statement cs = null; HsqlName label = null; RangeVariable[] rangeVariables = context == null ? routine.getParameterRangeVariables() : context.getRangeVariables(); if (!routine.isTrigger() && isSimpleName() && !isReservedKey()) { label = readNewSchemaObjectName(SchemaObject.LABEL, false); // todo - improved error message if (token.tokenType != Tokens.COLON) { throw unexpectedToken(label.getNameString()); } readThis(Tokens.COLON); } compileContext.reset(); HsqlName oldSchema = session.getCurrentSchemaHsqlName(); session.setCurrentSchemaHsqlName(routine.getSchemaName()); try { switch (token.tokenType) { // data case Tokens.OPEN : { if (routine.dataImpact == Routine.CONTAINS_SQL) { throw Error.error(ErrorCode.X_42602, routine.getDataImpactString()); } if (label != null) { throw unexpectedToken(); } cs = compileOpenCursorStatement(context); break; } case Tokens.SELECT : { if (label != null) { throw unexpectedToken(); } cs = compileSelectSingleRowStatement(rangeVariables); break; } // data change case Tokens.INSERT :
9,779
2
// data change
Statement compileSQLProcedureStatementOrNull(Routine routine, StatementCompound context) { Statement cs = null; HsqlName label = null; RangeVariable[] rangeVariables = context == null ? routine.getParameterRangeVariables() : context.getRangeVariables(); if (!routine.isTrigger() && isSimpleName() && !isReservedKey()) { label = readNewSchemaObjectName(SchemaObject.LABEL, false); // todo - improved error message if (token.tokenType != Tokens.COLON) { throw unexpectedToken(label.getNameString()); } readThis(Tokens.COLON); } compileContext.reset(); HsqlName oldSchema = session.getCurrentSchemaHsqlName(); session.setCurrentSchemaHsqlName(routine.getSchemaName()); try { switch (token.tokenType) { // data case Tokens.OPEN : { if (routine.dataImpact == Routine.CONTAINS_SQL) { throw Error.error(ErrorCode.X_42602, routine.getDataImpactString()); } if (label != null) { throw unexpectedToken(); } cs = compileOpenCursorStatement(context); break; } case Tokens.SELECT : { if (label != null) { throw unexpectedToken(); } cs = compileSelectSingleRowStatement(rangeVariables); break; } // data change case Tokens.INSERT : if (label != null) { throw unexpectedToken(); } cs = compileInsertStatement(rangeVariables); break; case Tokens.UPDATE : if (label != null) { throw unexpectedToken(); } cs = compileUpdateStatement(rangeVariables); break; case Tokens.DELETE : if (label != null) { throw unexpectedToken(); } cs = compileDeleteStatement(rangeVariables); break; case Tokens.TRUNCATE : if (label != null) { throw unexpectedToken(); } cs = compileTruncateStatement(); break; case Tokens.MERGE : if (label != null) { throw unexpectedToken(); } cs = compileMergeStatement(rangeVariables); break; case Tokens.SET : if (label != null) { throw unexpectedToken(); } if (routine.isTrigger()) { if (routine.triggerOperation == StatementTypes.DELETE_WHERE) { cs = compileSetStatement(rangeVariables); break; } if (routine.triggerType != TriggerDef.BEFORE) { cs = compileSetStatement(rangeVariables); break; } int position = super.getPosition(); try { cs = compileTriggerSetStatement( routine.triggerTable, rangeVariables); } catch (HsqlException e) { rewind(position); cs = compileSetStatement(rangeVariables); } } else { cs = compileSetStatement(rangeVariables); } break; case Tokens.GET : if (label != null) { throw unexpectedToken(); } cs = this.compileGetStatement(rangeVariables); break; // control case Tokens.CALL : { if (label != null) { throw unexpectedToken(); } cs = compileCallStatement(rangeVariables, true); Routine proc = ((StatementProcedure) cs).procedure; if (proc != null) { switch (routine.dataImpact) { case Routine.CONTAINS_SQL : { if (proc.dataImpact == Routine.READS_SQL || proc.dataImpact == Routine.MODIFIES_SQL) { throw Error.error( ErrorCode.X_42602, routine.getDataImpactString()); } break; } case Routine.READS_SQL : { if (proc.dataImpact == Routine.MODIFIES_SQL) { throw Error.error( ErrorCode.X_42602, routine.getDataImpactString()); } break; } } } break; } case Tokens.RETURN : { if (routine.isTrigger() || label != null) { throw unexpectedToken(); } read(); cs = compileReturnValue(routine, context); break; } case Tokens.BEGIN : { cs = compileCompoundStatement(routine, context, label); break; } case Tokens.WHILE : { if (routine.isTrigger()) { throw unexpectedToken(); } cs = compileWhile(routine, context, label); break; } case Tokens.REPEAT : { cs = compileRepeat(routine, context, label); break; } case Tokens.LOOP : { cs = compileLoop(routine, context, label); break; } case Tokens.FOR : { cs = compileFor(routine, context, label); break; } case Tokens.ITERATE : { if (label != null) { throw unexpectedToken(); } cs = compileIterate(); break; } case Tokens.LEAVE : { if (label != null) { throw unexpectedToken(); } cs = compileLeave(routine, context); break; } case Tokens.IF : { cs = compileIf(routine, context); break; } case Tokens.CASE : { cs = compileCase(routine, context); break; } case Tokens.SIGNAL : { cs = compileSignal(routine, context, label); break; } case Tokens.RESIGNAL : { cs = compileResignal(routine, context, label); break; } default : return null; } cs.setRoot(routine); cs.setParent(context); return cs; } finally { session.setCurrentSchemaHsqlName(oldSchema); } }
NONSATD
true
break; } // data change case Tokens.INSERT : if (label != null) {
cs = compileOpenCursorStatement(context); break; } case Tokens.SELECT : { if (label != null) { throw unexpectedToken(); } cs = compileSelectSingleRowStatement(rangeVariables); break; } // data change case Tokens.INSERT : if (label != null) { throw unexpectedToken(); } cs = compileInsertStatement(rangeVariables); break; case Tokens.UPDATE : if (label != null) { throw unexpectedToken(); }
switch (token.tokenType) { // data case Tokens.OPEN : { if (routine.dataImpact == Routine.CONTAINS_SQL) { throw Error.error(ErrorCode.X_42602, routine.getDataImpactString()); } if (label != null) { throw unexpectedToken(); } cs = compileOpenCursorStatement(context); break; } case Tokens.SELECT : { if (label != null) { throw unexpectedToken(); } cs = compileSelectSingleRowStatement(rangeVariables); break; } // data change case Tokens.INSERT : if (label != null) { throw unexpectedToken(); } cs = compileInsertStatement(rangeVariables); break; case Tokens.UPDATE : if (label != null) { throw unexpectedToken(); } cs = compileUpdateStatement(rangeVariables); break; case Tokens.DELETE : if (label != null) { throw unexpectedToken(); } cs = compileDeleteStatement(rangeVariables); break; case Tokens.TRUNCATE : if (label != null) {
9,779
3
// control
Statement compileSQLProcedureStatementOrNull(Routine routine, StatementCompound context) { Statement cs = null; HsqlName label = null; RangeVariable[] rangeVariables = context == null ? routine.getParameterRangeVariables() : context.getRangeVariables(); if (!routine.isTrigger() && isSimpleName() && !isReservedKey()) { label = readNewSchemaObjectName(SchemaObject.LABEL, false); // todo - improved error message if (token.tokenType != Tokens.COLON) { throw unexpectedToken(label.getNameString()); } readThis(Tokens.COLON); } compileContext.reset(); HsqlName oldSchema = session.getCurrentSchemaHsqlName(); session.setCurrentSchemaHsqlName(routine.getSchemaName()); try { switch (token.tokenType) { // data case Tokens.OPEN : { if (routine.dataImpact == Routine.CONTAINS_SQL) { throw Error.error(ErrorCode.X_42602, routine.getDataImpactString()); } if (label != null) { throw unexpectedToken(); } cs = compileOpenCursorStatement(context); break; } case Tokens.SELECT : { if (label != null) { throw unexpectedToken(); } cs = compileSelectSingleRowStatement(rangeVariables); break; } // data change case Tokens.INSERT : if (label != null) { throw unexpectedToken(); } cs = compileInsertStatement(rangeVariables); break; case Tokens.UPDATE : if (label != null) { throw unexpectedToken(); } cs = compileUpdateStatement(rangeVariables); break; case Tokens.DELETE : if (label != null) { throw unexpectedToken(); } cs = compileDeleteStatement(rangeVariables); break; case Tokens.TRUNCATE : if (label != null) { throw unexpectedToken(); } cs = compileTruncateStatement(); break; case Tokens.MERGE : if (label != null) { throw unexpectedToken(); } cs = compileMergeStatement(rangeVariables); break; case Tokens.SET : if (label != null) { throw unexpectedToken(); } if (routine.isTrigger()) { if (routine.triggerOperation == StatementTypes.DELETE_WHERE) { cs = compileSetStatement(rangeVariables); break; } if (routine.triggerType != TriggerDef.BEFORE) { cs = compileSetStatement(rangeVariables); break; } int position = super.getPosition(); try { cs = compileTriggerSetStatement( routine.triggerTable, rangeVariables); } catch (HsqlException e) { rewind(position); cs = compileSetStatement(rangeVariables); } } else { cs = compileSetStatement(rangeVariables); } break; case Tokens.GET : if (label != null) { throw unexpectedToken(); } cs = this.compileGetStatement(rangeVariables); break; // control case Tokens.CALL : { if (label != null) { throw unexpectedToken(); } cs = compileCallStatement(rangeVariables, true); Routine proc = ((StatementProcedure) cs).procedure; if (proc != null) { switch (routine.dataImpact) { case Routine.CONTAINS_SQL : { if (proc.dataImpact == Routine.READS_SQL || proc.dataImpact == Routine.MODIFIES_SQL) { throw Error.error( ErrorCode.X_42602, routine.getDataImpactString()); } break; } case Routine.READS_SQL : { if (proc.dataImpact == Routine.MODIFIES_SQL) { throw Error.error( ErrorCode.X_42602, routine.getDataImpactString()); } break; } } } break; } case Tokens.RETURN : { if (routine.isTrigger() || label != null) { throw unexpectedToken(); } read(); cs = compileReturnValue(routine, context); break; } case Tokens.BEGIN : { cs = compileCompoundStatement(routine, context, label); break; } case Tokens.WHILE : { if (routine.isTrigger()) { throw unexpectedToken(); } cs = compileWhile(routine, context, label); break; } case Tokens.REPEAT : { cs = compileRepeat(routine, context, label); break; } case Tokens.LOOP : { cs = compileLoop(routine, context, label); break; } case Tokens.FOR : { cs = compileFor(routine, context, label); break; } case Tokens.ITERATE : { if (label != null) { throw unexpectedToken(); } cs = compileIterate(); break; } case Tokens.LEAVE : { if (label != null) { throw unexpectedToken(); } cs = compileLeave(routine, context); break; } case Tokens.IF : { cs = compileIf(routine, context); break; } case Tokens.CASE : { cs = compileCase(routine, context); break; } case Tokens.SIGNAL : { cs = compileSignal(routine, context, label); break; } case Tokens.RESIGNAL : { cs = compileResignal(routine, context, label); break; } default : return null; } cs.setRoot(routine); cs.setParent(context); return cs; } finally { session.setCurrentSchemaHsqlName(oldSchema); } }
NONSATD
true
cs = this.compileGetStatement(rangeVariables); break; // control case Tokens.CALL : { if (label != null) {
} else { cs = compileSetStatement(rangeVariables); } break; case Tokens.GET : if (label != null) { throw unexpectedToken(); } cs = this.compileGetStatement(rangeVariables); break; // control case Tokens.CALL : { if (label != null) { throw unexpectedToken(); } cs = compileCallStatement(rangeVariables, true); Routine proc = ((StatementProcedure) cs).procedure; if (proc != null) { switch (routine.dataImpact) { case Routine.CONTAINS_SQL : { if (proc.dataImpact == Routine.READS_SQL
break; } int position = super.getPosition(); try { cs = compileTriggerSetStatement( routine.triggerTable, rangeVariables); } catch (HsqlException e) { rewind(position); cs = compileSetStatement(rangeVariables); } } else { cs = compileSetStatement(rangeVariables); } break; case Tokens.GET : if (label != null) { throw unexpectedToken(); } cs = this.compileGetStatement(rangeVariables); break; // control case Tokens.CALL : { if (label != null) { throw unexpectedToken(); } cs = compileCallStatement(rangeVariables, true); Routine proc = ((StatementProcedure) cs).procedure; if (proc != null) { switch (routine.dataImpact) { case Routine.CONTAINS_SQL : { if (proc.dataImpact == Routine.READS_SQL || proc.dataImpact == Routine.MODIFIES_SQL) { throw Error.error( ErrorCode.X_42602, routine.getDataImpactString()); } break; } case Routine.READS_SQL : { if (proc.dataImpact == Routine.MODIFIES_SQL) {
34,357
0
/** * This method finds all the candidate fields for a given type * Candidate fields will ony ever be fields that have either been directly annotated, * or are custom Appsmith types (and can hence have fields annotated for encryption within them), * or are parameterized collections of custom Appsmith types, * or are parameterized maps with custom Appsmith type values (keys are not scanned for encrypted fields) * * @param source document that needs to be checked for encrypted annotations * @return list of candidate fields for the given type and null if this list can not be found at this time */
List<CandidateField> findCandidateFieldsForType(@NonNull Object source) { // At this point source class represents the true polymorphic type of the document Class<?> sourceClass = source.getClass(); // Lock a thread wanting to find information about the same type // So that this information retrieval is only done once // Ignore this warning, this class reference will be on the heap List<CandidateField> candidateFields = this.encryptedFieldsMap.get(sourceClass); if (candidateFields != null) { // The cache is already aware of this type, return candidate fields for it return candidateFields; } // Don't bother with primitives if (ClassUtils.isPrimitiveOrWrapper(sourceClass)) return Collections.emptyList(); // If it is not known, scan each field for annotation or Appsmith type List<CandidateField> finalCandidateFields = new ArrayList<>(); synchronized (sourceClass) { ReflectionUtils.doWithFields(sourceClass, field -> { if (field.getAnnotation(Encrypted.class) != null) { CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); finalCandidateFields.add(candidateField); } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { CandidateField candidateField = null; field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); if (fieldValue == null) { if (this.encryptedFieldsMap.containsKey(field.getType())) { // If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); } } else { // If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) { // This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates candidateField = new CandidateField(field, appsmithFieldType); } } field.setAccessible(false); if (candidateField != null) { // This will only ever be null if the field value is populated, // and is known to be a non-encryption related field finalCandidateFields.add(candidateField); } } else if (Collection.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { // If this is a collection, check if the Type parameter is an AppsmithDomain Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType; try { subFieldType = (Class<?>) typeArguments[0]; } catch (ClassCastException|ArrayIndexOutOfBoundsException e) { subFieldType = null; } if(subFieldType != null) { if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Collection<?> collection = (Collection<?>) fieldValue; if (collection == null || collection.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_UNKNOWN)); } else { for (final Object o : collection) { if (o == null) { continue; } if (o.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(o); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_POLYMORPHIC)); } break; } } field.setAccessible(false); } } // TODO Add support for nested collections } else if (Map.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType = (Class<?>) typeArguments[1]; if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Map<?, ?> map = (Map<?, ?>) fieldValue; if (map == null || map.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_UNKNOWN)); } else { for (Map.Entry<?, ?> entry : map.entrySet()) { final Object value = entry.getValue(); if (value == null) { continue; } if (value.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(value); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_POLYMORPHIC)); } break; } } field.setAccessible(false); } } }, field -> field.getAnnotation(Encrypted.class) != null || AppsmithDomain.class.isAssignableFrom(field.getType()) || Collection.class.isAssignableFrom(field.getType()) || Map.class.isAssignableFrom(field.getType())); } // Update cache for next use encryptedFieldsMap.put(sourceClass, finalCandidateFields); return finalCandidateFields; }
NONSATD
true
List<CandidateField> findCandidateFieldsForType(@NonNull Object source) { // At this point source class represents the true polymorphic type of the document Class<?> sourceClass = source.getClass(); // Lock a thread wanting to find information about the same type // So that this information retrieval is only done once // Ignore this warning, this class reference will be on the heap List<CandidateField> candidateFields = this.encryptedFieldsMap.get(sourceClass); if (candidateFields != null) { // The cache is already aware of this type, return candidate fields for it return candidateFields; } // Don't bother with primitives if (ClassUtils.isPrimitiveOrWrapper(sourceClass)) return Collections.emptyList(); // If it is not known, scan each field for annotation or Appsmith type List<CandidateField> finalCandidateFields = new ArrayList<>(); synchronized (sourceClass) { ReflectionUtils.doWithFields(sourceClass, field -> { if (field.getAnnotation(Encrypted.class) != null) { CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); finalCandidateFields.add(candidateField); } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { CandidateField candidateField = null; field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); if (fieldValue == null) { if (this.encryptedFieldsMap.containsKey(field.getType())) { // If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); } } else { // If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) { // This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates candidateField = new CandidateField(field, appsmithFieldType); } } field.setAccessible(false); if (candidateField != null) { // This will only ever be null if the field value is populated, // and is known to be a non-encryption related field finalCandidateFields.add(candidateField); } } else if (Collection.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { // If this is a collection, check if the Type parameter is an AppsmithDomain Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType; try { subFieldType = (Class<?>) typeArguments[0]; } catch (ClassCastException|ArrayIndexOutOfBoundsException e) { subFieldType = null; } if(subFieldType != null) { if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Collection<?> collection = (Collection<?>) fieldValue; if (collection == null || collection.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_UNKNOWN)); } else { for (final Object o : collection) { if (o == null) { continue; } if (o.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(o); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_POLYMORPHIC)); } break; } } field.setAccessible(false); } } // TODO Add support for nested collections } else if (Map.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType = (Class<?>) typeArguments[1]; if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Map<?, ?> map = (Map<?, ?>) fieldValue; if (map == null || map.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_UNKNOWN)); } else { for (Map.Entry<?, ?> entry : map.entrySet()) { final Object value = entry.getValue(); if (value == null) { continue; } if (value.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(value); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_POLYMORPHIC)); } break; } } field.setAccessible(false); } } }, field -> field.getAnnotation(Encrypted.class) != null || AppsmithDomain.class.isAssignableFrom(field.getType()) || Collection.class.isAssignableFrom(field.getType()) || Map.class.isAssignableFrom(field.getType())); } // Update cache for next use encryptedFieldsMap.put(sourceClass, finalCandidateFields); return finalCandidateFields; }
List<CandidateField> findCandidateFieldsForType(@NonNull Object source) { // At this point source class represents the true polymorphic type of the document Class<?> sourceClass = source.getClass(); // Lock a thread wanting to find information about the same type // So that this information retrieval is only done once // Ignore this warning, this class reference will be on the heap List<CandidateField> candidateFields = this.encryptedFieldsMap.get(sourceClass); if (candidateFields != null) { // The cache is already aware of this type, return candidate fields for it return candidateFields; } // Don't bother with primitives if (ClassUtils.isPrimitiveOrWrapper(sourceClass)) return Collections.emptyList(); // If it is not known, scan each field for annotation or Appsmith type List<CandidateField> finalCandidateFields = new ArrayList<>(); synchronized (sourceClass) { ReflectionUtils.doWithFields(sourceClass, field -> { if (field.getAnnotation(Encrypted.class) != null) { CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); finalCandidateFields.add(candidateField); } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { CandidateField candidateField = null; field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); if (fieldValue == null) { if (this.encryptedFieldsMap.containsKey(field.getType())) { // If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); } } else { // If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) { // This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates candidateField = new CandidateField(field, appsmithFieldType); } } field.setAccessible(false); if (candidateField != null) { // This will only ever be null if the field value is populated, // and is known to be a non-encryption related field finalCandidateFields.add(candidateField); } } else if (Collection.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { // If this is a collection, check if the Type parameter is an AppsmithDomain Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType; try { subFieldType = (Class<?>) typeArguments[0]; } catch (ClassCastException|ArrayIndexOutOfBoundsException e) { subFieldType = null; } if(subFieldType != null) { if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Collection<?> collection = (Collection<?>) fieldValue; if (collection == null || collection.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_UNKNOWN)); } else { for (final Object o : collection) { if (o == null) { continue; } if (o.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(o); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_POLYMORPHIC)); } break; } } field.setAccessible(false); } } // TODO Add support for nested collections } else if (Map.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType = (Class<?>) typeArguments[1]; if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Map<?, ?> map = (Map<?, ?>) fieldValue; if (map == null || map.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_UNKNOWN)); } else { for (Map.Entry<?, ?> entry : map.entrySet()) { final Object value = entry.getValue(); if (value == null) { continue; } if (value.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(value); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_POLYMORPHIC)); } break; } } field.setAccessible(false); } } }, field -> field.getAnnotation(Encrypted.class) != null || AppsmithDomain.class.isAssignableFrom(field.getType()) || Collection.class.isAssignableFrom(field.getType()) || Map.class.isAssignableFrom(field.getType())); } // Update cache for next use encryptedFieldsMap.put(sourceClass, finalCandidateFields); return finalCandidateFields; }
List<CandidateField> findCandidateFieldsForType(@NonNull Object source) { // At this point source class represents the true polymorphic type of the document Class<?> sourceClass = source.getClass(); // Lock a thread wanting to find information about the same type // So that this information retrieval is only done once // Ignore this warning, this class reference will be on the heap List<CandidateField> candidateFields = this.encryptedFieldsMap.get(sourceClass); if (candidateFields != null) { // The cache is already aware of this type, return candidate fields for it return candidateFields; } // Don't bother with primitives if (ClassUtils.isPrimitiveOrWrapper(sourceClass)) return Collections.emptyList(); // If it is not known, scan each field for annotation or Appsmith type List<CandidateField> finalCandidateFields = new ArrayList<>(); synchronized (sourceClass) { ReflectionUtils.doWithFields(sourceClass, field -> { if (field.getAnnotation(Encrypted.class) != null) { CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); finalCandidateFields.add(candidateField); } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { CandidateField candidateField = null; field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); if (fieldValue == null) { if (this.encryptedFieldsMap.containsKey(field.getType())) { // If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); } } else { // If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) { // This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates candidateField = new CandidateField(field, appsmithFieldType); } } field.setAccessible(false); if (candidateField != null) { // This will only ever be null if the field value is populated, // and is known to be a non-encryption related field finalCandidateFields.add(candidateField); } } else if (Collection.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { // If this is a collection, check if the Type parameter is an AppsmithDomain Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType; try { subFieldType = (Class<?>) typeArguments[0]; } catch (ClassCastException|ArrayIndexOutOfBoundsException e) { subFieldType = null; } if(subFieldType != null) { if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Collection<?> collection = (Collection<?>) fieldValue; if (collection == null || collection.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_UNKNOWN)); } else { for (final Object o : collection) { if (o == null) { continue; } if (o.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(o); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_POLYMORPHIC)); } break; } } field.setAccessible(false); } } // TODO Add support for nested collections } else if (Map.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType = (Class<?>) typeArguments[1]; if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Map<?, ?> map = (Map<?, ?>) fieldValue; if (map == null || map.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_UNKNOWN)); } else { for (Map.Entry<?, ?> entry : map.entrySet()) { final Object value = entry.getValue(); if (value == null) { continue; } if (value.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(value); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_POLYMORPHIC)); } break; } } field.setAccessible(false); } } }, field -> field.getAnnotation(Encrypted.class) != null || AppsmithDomain.class.isAssignableFrom(field.getType()) || Collection.class.isAssignableFrom(field.getType()) || Map.class.isAssignableFrom(field.getType())); } // Update cache for next use encryptedFieldsMap.put(sourceClass, finalCandidateFields); return finalCandidateFields; }
34,357
1
// At this point source class represents the true polymorphic type of the document
List<CandidateField> findCandidateFieldsForType(@NonNull Object source) { // At this point source class represents the true polymorphic type of the document Class<?> sourceClass = source.getClass(); // Lock a thread wanting to find information about the same type // So that this information retrieval is only done once // Ignore this warning, this class reference will be on the heap List<CandidateField> candidateFields = this.encryptedFieldsMap.get(sourceClass); if (candidateFields != null) { // The cache is already aware of this type, return candidate fields for it return candidateFields; } // Don't bother with primitives if (ClassUtils.isPrimitiveOrWrapper(sourceClass)) return Collections.emptyList(); // If it is not known, scan each field for annotation or Appsmith type List<CandidateField> finalCandidateFields = new ArrayList<>(); synchronized (sourceClass) { ReflectionUtils.doWithFields(sourceClass, field -> { if (field.getAnnotation(Encrypted.class) != null) { CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); finalCandidateFields.add(candidateField); } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { CandidateField candidateField = null; field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); if (fieldValue == null) { if (this.encryptedFieldsMap.containsKey(field.getType())) { // If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); } } else { // If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) { // This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates candidateField = new CandidateField(field, appsmithFieldType); } } field.setAccessible(false); if (candidateField != null) { // This will only ever be null if the field value is populated, // and is known to be a non-encryption related field finalCandidateFields.add(candidateField); } } else if (Collection.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { // If this is a collection, check if the Type parameter is an AppsmithDomain Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType; try { subFieldType = (Class<?>) typeArguments[0]; } catch (ClassCastException|ArrayIndexOutOfBoundsException e) { subFieldType = null; } if(subFieldType != null) { if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Collection<?> collection = (Collection<?>) fieldValue; if (collection == null || collection.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_UNKNOWN)); } else { for (final Object o : collection) { if (o == null) { continue; } if (o.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(o); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_POLYMORPHIC)); } break; } } field.setAccessible(false); } } // TODO Add support for nested collections } else if (Map.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType = (Class<?>) typeArguments[1]; if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Map<?, ?> map = (Map<?, ?>) fieldValue; if (map == null || map.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_UNKNOWN)); } else { for (Map.Entry<?, ?> entry : map.entrySet()) { final Object value = entry.getValue(); if (value == null) { continue; } if (value.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(value); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_POLYMORPHIC)); } break; } } field.setAccessible(false); } } }, field -> field.getAnnotation(Encrypted.class) != null || AppsmithDomain.class.isAssignableFrom(field.getType()) || Collection.class.isAssignableFrom(field.getType()) || Map.class.isAssignableFrom(field.getType())); } // Update cache for next use encryptedFieldsMap.put(sourceClass, finalCandidateFields); return finalCandidateFields; }
NONSATD
true
List<CandidateField> findCandidateFieldsForType(@NonNull Object source) { // At this point source class represents the true polymorphic type of the document Class<?> sourceClass = source.getClass(); // Lock a thread wanting to find information about the same type
List<CandidateField> findCandidateFieldsForType(@NonNull Object source) { // At this point source class represents the true polymorphic type of the document Class<?> sourceClass = source.getClass(); // Lock a thread wanting to find information about the same type // So that this information retrieval is only done once // Ignore this warning, this class reference will be on the heap List<CandidateField> candidateFields = this.encryptedFieldsMap.get(sourceClass); if (candidateFields != null) { // The cache is already aware of this type, return candidate fields for it return candidateFields; } // Don't bother with primitives
List<CandidateField> findCandidateFieldsForType(@NonNull Object source) { // At this point source class represents the true polymorphic type of the document Class<?> sourceClass = source.getClass(); // Lock a thread wanting to find information about the same type // So that this information retrieval is only done once // Ignore this warning, this class reference will be on the heap List<CandidateField> candidateFields = this.encryptedFieldsMap.get(sourceClass); if (candidateFields != null) { // The cache is already aware of this type, return candidate fields for it return candidateFields; } // Don't bother with primitives if (ClassUtils.isPrimitiveOrWrapper(sourceClass)) return Collections.emptyList(); // If it is not known, scan each field for annotation or Appsmith type List<CandidateField> finalCandidateFields = new ArrayList<>(); synchronized (sourceClass) { ReflectionUtils.doWithFields(sourceClass, field -> { if (field.getAnnotation(Encrypted.class) != null) { CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); finalCandidateFields.add(candidateField); } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { CandidateField candidateField = null;
34,357
2
// Lock a thread wanting to find information about the same type // So that this information retrieval is only done once // Ignore this warning, this class reference will be on the heap
List<CandidateField> findCandidateFieldsForType(@NonNull Object source) { // At this point source class represents the true polymorphic type of the document Class<?> sourceClass = source.getClass(); // Lock a thread wanting to find information about the same type // So that this information retrieval is only done once // Ignore this warning, this class reference will be on the heap List<CandidateField> candidateFields = this.encryptedFieldsMap.get(sourceClass); if (candidateFields != null) { // The cache is already aware of this type, return candidate fields for it return candidateFields; } // Don't bother with primitives if (ClassUtils.isPrimitiveOrWrapper(sourceClass)) return Collections.emptyList(); // If it is not known, scan each field for annotation or Appsmith type List<CandidateField> finalCandidateFields = new ArrayList<>(); synchronized (sourceClass) { ReflectionUtils.doWithFields(sourceClass, field -> { if (field.getAnnotation(Encrypted.class) != null) { CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); finalCandidateFields.add(candidateField); } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { CandidateField candidateField = null; field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); if (fieldValue == null) { if (this.encryptedFieldsMap.containsKey(field.getType())) { // If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); } } else { // If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) { // This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates candidateField = new CandidateField(field, appsmithFieldType); } } field.setAccessible(false); if (candidateField != null) { // This will only ever be null if the field value is populated, // and is known to be a non-encryption related field finalCandidateFields.add(candidateField); } } else if (Collection.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { // If this is a collection, check if the Type parameter is an AppsmithDomain Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType; try { subFieldType = (Class<?>) typeArguments[0]; } catch (ClassCastException|ArrayIndexOutOfBoundsException e) { subFieldType = null; } if(subFieldType != null) { if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Collection<?> collection = (Collection<?>) fieldValue; if (collection == null || collection.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_UNKNOWN)); } else { for (final Object o : collection) { if (o == null) { continue; } if (o.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(o); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_POLYMORPHIC)); } break; } } field.setAccessible(false); } } // TODO Add support for nested collections } else if (Map.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType = (Class<?>) typeArguments[1]; if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Map<?, ?> map = (Map<?, ?>) fieldValue; if (map == null || map.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_UNKNOWN)); } else { for (Map.Entry<?, ?> entry : map.entrySet()) { final Object value = entry.getValue(); if (value == null) { continue; } if (value.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(value); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_POLYMORPHIC)); } break; } } field.setAccessible(false); } } }, field -> field.getAnnotation(Encrypted.class) != null || AppsmithDomain.class.isAssignableFrom(field.getType()) || Collection.class.isAssignableFrom(field.getType()) || Map.class.isAssignableFrom(field.getType())); } // Update cache for next use encryptedFieldsMap.put(sourceClass, finalCandidateFields); return finalCandidateFields; }
NONSATD
true
// At this point source class represents the true polymorphic type of the document Class<?> sourceClass = source.getClass(); // Lock a thread wanting to find information about the same type // So that this information retrieval is only done once // Ignore this warning, this class reference will be on the heap List<CandidateField> candidateFields = this.encryptedFieldsMap.get(sourceClass); if (candidateFields != null) {
List<CandidateField> findCandidateFieldsForType(@NonNull Object source) { // At this point source class represents the true polymorphic type of the document Class<?> sourceClass = source.getClass(); // Lock a thread wanting to find information about the same type // So that this information retrieval is only done once // Ignore this warning, this class reference will be on the heap List<CandidateField> candidateFields = this.encryptedFieldsMap.get(sourceClass); if (candidateFields != null) { // The cache is already aware of this type, return candidate fields for it return candidateFields; } // Don't bother with primitives if (ClassUtils.isPrimitiveOrWrapper(sourceClass)) return Collections.emptyList(); // If it is not known, scan each field for annotation or Appsmith type List<CandidateField> finalCandidateFields = new ArrayList<>(); synchronized (sourceClass) {
List<CandidateField> findCandidateFieldsForType(@NonNull Object source) { // At this point source class represents the true polymorphic type of the document Class<?> sourceClass = source.getClass(); // Lock a thread wanting to find information about the same type // So that this information retrieval is only done once // Ignore this warning, this class reference will be on the heap List<CandidateField> candidateFields = this.encryptedFieldsMap.get(sourceClass); if (candidateFields != null) { // The cache is already aware of this type, return candidate fields for it return candidateFields; } // Don't bother with primitives if (ClassUtils.isPrimitiveOrWrapper(sourceClass)) return Collections.emptyList(); // If it is not known, scan each field for annotation or Appsmith type List<CandidateField> finalCandidateFields = new ArrayList<>(); synchronized (sourceClass) { ReflectionUtils.doWithFields(sourceClass, field -> { if (field.getAnnotation(Encrypted.class) != null) { CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); finalCandidateFields.add(candidateField); } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { CandidateField candidateField = null; field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); if (fieldValue == null) { if (this.encryptedFieldsMap.containsKey(field.getType())) {
34,357
3
// The cache is already aware of this type, return candidate fields for it
List<CandidateField> findCandidateFieldsForType(@NonNull Object source) { // At this point source class represents the true polymorphic type of the document Class<?> sourceClass = source.getClass(); // Lock a thread wanting to find information about the same type // So that this information retrieval is only done once // Ignore this warning, this class reference will be on the heap List<CandidateField> candidateFields = this.encryptedFieldsMap.get(sourceClass); if (candidateFields != null) { // The cache is already aware of this type, return candidate fields for it return candidateFields; } // Don't bother with primitives if (ClassUtils.isPrimitiveOrWrapper(sourceClass)) return Collections.emptyList(); // If it is not known, scan each field for annotation or Appsmith type List<CandidateField> finalCandidateFields = new ArrayList<>(); synchronized (sourceClass) { ReflectionUtils.doWithFields(sourceClass, field -> { if (field.getAnnotation(Encrypted.class) != null) { CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); finalCandidateFields.add(candidateField); } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { CandidateField candidateField = null; field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); if (fieldValue == null) { if (this.encryptedFieldsMap.containsKey(field.getType())) { // If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); } } else { // If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) { // This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates candidateField = new CandidateField(field, appsmithFieldType); } } field.setAccessible(false); if (candidateField != null) { // This will only ever be null if the field value is populated, // and is known to be a non-encryption related field finalCandidateFields.add(candidateField); } } else if (Collection.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { // If this is a collection, check if the Type parameter is an AppsmithDomain Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType; try { subFieldType = (Class<?>) typeArguments[0]; } catch (ClassCastException|ArrayIndexOutOfBoundsException e) { subFieldType = null; } if(subFieldType != null) { if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Collection<?> collection = (Collection<?>) fieldValue; if (collection == null || collection.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_UNKNOWN)); } else { for (final Object o : collection) { if (o == null) { continue; } if (o.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(o); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_POLYMORPHIC)); } break; } } field.setAccessible(false); } } // TODO Add support for nested collections } else if (Map.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType = (Class<?>) typeArguments[1]; if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Map<?, ?> map = (Map<?, ?>) fieldValue; if (map == null || map.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_UNKNOWN)); } else { for (Map.Entry<?, ?> entry : map.entrySet()) { final Object value = entry.getValue(); if (value == null) { continue; } if (value.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(value); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_POLYMORPHIC)); } break; } } field.setAccessible(false); } } }, field -> field.getAnnotation(Encrypted.class) != null || AppsmithDomain.class.isAssignableFrom(field.getType()) || Collection.class.isAssignableFrom(field.getType()) || Map.class.isAssignableFrom(field.getType())); } // Update cache for next use encryptedFieldsMap.put(sourceClass, finalCandidateFields); return finalCandidateFields; }
NONSATD
true
List<CandidateField> candidateFields = this.encryptedFieldsMap.get(sourceClass); if (candidateFields != null) { // The cache is already aware of this type, return candidate fields for it return candidateFields; }
List<CandidateField> findCandidateFieldsForType(@NonNull Object source) { // At this point source class represents the true polymorphic type of the document Class<?> sourceClass = source.getClass(); // Lock a thread wanting to find information about the same type // So that this information retrieval is only done once // Ignore this warning, this class reference will be on the heap List<CandidateField> candidateFields = this.encryptedFieldsMap.get(sourceClass); if (candidateFields != null) { // The cache is already aware of this type, return candidate fields for it return candidateFields; } // Don't bother with primitives if (ClassUtils.isPrimitiveOrWrapper(sourceClass)) return Collections.emptyList(); // If it is not known, scan each field for annotation or Appsmith type List<CandidateField> finalCandidateFields = new ArrayList<>(); synchronized (sourceClass) { ReflectionUtils.doWithFields(sourceClass, field -> { if (field.getAnnotation(Encrypted.class) != null) { CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD);
List<CandidateField> findCandidateFieldsForType(@NonNull Object source) { // At this point source class represents the true polymorphic type of the document Class<?> sourceClass = source.getClass(); // Lock a thread wanting to find information about the same type // So that this information retrieval is only done once // Ignore this warning, this class reference will be on the heap List<CandidateField> candidateFields = this.encryptedFieldsMap.get(sourceClass); if (candidateFields != null) { // The cache is already aware of this type, return candidate fields for it return candidateFields; } // Don't bother with primitives if (ClassUtils.isPrimitiveOrWrapper(sourceClass)) return Collections.emptyList(); // If it is not known, scan each field for annotation or Appsmith type List<CandidateField> finalCandidateFields = new ArrayList<>(); synchronized (sourceClass) { ReflectionUtils.doWithFields(sourceClass, field -> { if (field.getAnnotation(Encrypted.class) != null) { CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); finalCandidateFields.add(candidateField); } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { CandidateField candidateField = null; field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); if (fieldValue == null) { if (this.encryptedFieldsMap.containsKey(field.getType())) { // If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN);
34,357
4
// Don't bother with primitives
List<CandidateField> findCandidateFieldsForType(@NonNull Object source) { // At this point source class represents the true polymorphic type of the document Class<?> sourceClass = source.getClass(); // Lock a thread wanting to find information about the same type // So that this information retrieval is only done once // Ignore this warning, this class reference will be on the heap List<CandidateField> candidateFields = this.encryptedFieldsMap.get(sourceClass); if (candidateFields != null) { // The cache is already aware of this type, return candidate fields for it return candidateFields; } // Don't bother with primitives if (ClassUtils.isPrimitiveOrWrapper(sourceClass)) return Collections.emptyList(); // If it is not known, scan each field for annotation or Appsmith type List<CandidateField> finalCandidateFields = new ArrayList<>(); synchronized (sourceClass) { ReflectionUtils.doWithFields(sourceClass, field -> { if (field.getAnnotation(Encrypted.class) != null) { CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); finalCandidateFields.add(candidateField); } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { CandidateField candidateField = null; field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); if (fieldValue == null) { if (this.encryptedFieldsMap.containsKey(field.getType())) { // If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); } } else { // If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) { // This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates candidateField = new CandidateField(field, appsmithFieldType); } } field.setAccessible(false); if (candidateField != null) { // This will only ever be null if the field value is populated, // and is known to be a non-encryption related field finalCandidateFields.add(candidateField); } } else if (Collection.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { // If this is a collection, check if the Type parameter is an AppsmithDomain Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType; try { subFieldType = (Class<?>) typeArguments[0]; } catch (ClassCastException|ArrayIndexOutOfBoundsException e) { subFieldType = null; } if(subFieldType != null) { if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Collection<?> collection = (Collection<?>) fieldValue; if (collection == null || collection.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_UNKNOWN)); } else { for (final Object o : collection) { if (o == null) { continue; } if (o.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(o); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_POLYMORPHIC)); } break; } } field.setAccessible(false); } } // TODO Add support for nested collections } else if (Map.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType = (Class<?>) typeArguments[1]; if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Map<?, ?> map = (Map<?, ?>) fieldValue; if (map == null || map.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_UNKNOWN)); } else { for (Map.Entry<?, ?> entry : map.entrySet()) { final Object value = entry.getValue(); if (value == null) { continue; } if (value.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(value); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_POLYMORPHIC)); } break; } } field.setAccessible(false); } } }, field -> field.getAnnotation(Encrypted.class) != null || AppsmithDomain.class.isAssignableFrom(field.getType()) || Collection.class.isAssignableFrom(field.getType()) || Map.class.isAssignableFrom(field.getType())); } // Update cache for next use encryptedFieldsMap.put(sourceClass, finalCandidateFields); return finalCandidateFields; }
NONSATD
true
return candidateFields; } // Don't bother with primitives if (ClassUtils.isPrimitiveOrWrapper(sourceClass)) return Collections.emptyList(); // If it is not known, scan each field for annotation or Appsmith type
// At this point source class represents the true polymorphic type of the document Class<?> sourceClass = source.getClass(); // Lock a thread wanting to find information about the same type // So that this information retrieval is only done once // Ignore this warning, this class reference will be on the heap List<CandidateField> candidateFields = this.encryptedFieldsMap.get(sourceClass); if (candidateFields != null) { // The cache is already aware of this type, return candidate fields for it return candidateFields; } // Don't bother with primitives if (ClassUtils.isPrimitiveOrWrapper(sourceClass)) return Collections.emptyList(); // If it is not known, scan each field for annotation or Appsmith type List<CandidateField> finalCandidateFields = new ArrayList<>(); synchronized (sourceClass) { ReflectionUtils.doWithFields(sourceClass, field -> { if (field.getAnnotation(Encrypted.class) != null) { CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); finalCandidateFields.add(candidateField); } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { CandidateField candidateField = null;
List<CandidateField> findCandidateFieldsForType(@NonNull Object source) { // At this point source class represents the true polymorphic type of the document Class<?> sourceClass = source.getClass(); // Lock a thread wanting to find information about the same type // So that this information retrieval is only done once // Ignore this warning, this class reference will be on the heap List<CandidateField> candidateFields = this.encryptedFieldsMap.get(sourceClass); if (candidateFields != null) { // The cache is already aware of this type, return candidate fields for it return candidateFields; } // Don't bother with primitives if (ClassUtils.isPrimitiveOrWrapper(sourceClass)) return Collections.emptyList(); // If it is not known, scan each field for annotation or Appsmith type List<CandidateField> finalCandidateFields = new ArrayList<>(); synchronized (sourceClass) { ReflectionUtils.doWithFields(sourceClass, field -> { if (field.getAnnotation(Encrypted.class) != null) { CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); finalCandidateFields.add(candidateField); } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { CandidateField candidateField = null; field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); if (fieldValue == null) { if (this.encryptedFieldsMap.containsKey(field.getType())) { // If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic)
34,357
5
// If it is not known, scan each field for annotation or Appsmith type
List<CandidateField> findCandidateFieldsForType(@NonNull Object source) { // At this point source class represents the true polymorphic type of the document Class<?> sourceClass = source.getClass(); // Lock a thread wanting to find information about the same type // So that this information retrieval is only done once // Ignore this warning, this class reference will be on the heap List<CandidateField> candidateFields = this.encryptedFieldsMap.get(sourceClass); if (candidateFields != null) { // The cache is already aware of this type, return candidate fields for it return candidateFields; } // Don't bother with primitives if (ClassUtils.isPrimitiveOrWrapper(sourceClass)) return Collections.emptyList(); // If it is not known, scan each field for annotation or Appsmith type List<CandidateField> finalCandidateFields = new ArrayList<>(); synchronized (sourceClass) { ReflectionUtils.doWithFields(sourceClass, field -> { if (field.getAnnotation(Encrypted.class) != null) { CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); finalCandidateFields.add(candidateField); } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { CandidateField candidateField = null; field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); if (fieldValue == null) { if (this.encryptedFieldsMap.containsKey(field.getType())) { // If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); } } else { // If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) { // This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates candidateField = new CandidateField(field, appsmithFieldType); } } field.setAccessible(false); if (candidateField != null) { // This will only ever be null if the field value is populated, // and is known to be a non-encryption related field finalCandidateFields.add(candidateField); } } else if (Collection.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { // If this is a collection, check if the Type parameter is an AppsmithDomain Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType; try { subFieldType = (Class<?>) typeArguments[0]; } catch (ClassCastException|ArrayIndexOutOfBoundsException e) { subFieldType = null; } if(subFieldType != null) { if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Collection<?> collection = (Collection<?>) fieldValue; if (collection == null || collection.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_UNKNOWN)); } else { for (final Object o : collection) { if (o == null) { continue; } if (o.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(o); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_POLYMORPHIC)); } break; } } field.setAccessible(false); } } // TODO Add support for nested collections } else if (Map.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType = (Class<?>) typeArguments[1]; if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Map<?, ?> map = (Map<?, ?>) fieldValue; if (map == null || map.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_UNKNOWN)); } else { for (Map.Entry<?, ?> entry : map.entrySet()) { final Object value = entry.getValue(); if (value == null) { continue; } if (value.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(value); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_POLYMORPHIC)); } break; } } field.setAccessible(false); } } }, field -> field.getAnnotation(Encrypted.class) != null || AppsmithDomain.class.isAssignableFrom(field.getType()) || Collection.class.isAssignableFrom(field.getType()) || Map.class.isAssignableFrom(field.getType())); } // Update cache for next use encryptedFieldsMap.put(sourceClass, finalCandidateFields); return finalCandidateFields; }
NONSATD
true
// Don't bother with primitives if (ClassUtils.isPrimitiveOrWrapper(sourceClass)) return Collections.emptyList(); // If it is not known, scan each field for annotation or Appsmith type List<CandidateField> finalCandidateFields = new ArrayList<>(); synchronized (sourceClass) {
// Lock a thread wanting to find information about the same type // So that this information retrieval is only done once // Ignore this warning, this class reference will be on the heap List<CandidateField> candidateFields = this.encryptedFieldsMap.get(sourceClass); if (candidateFields != null) { // The cache is already aware of this type, return candidate fields for it return candidateFields; } // Don't bother with primitives if (ClassUtils.isPrimitiveOrWrapper(sourceClass)) return Collections.emptyList(); // If it is not known, scan each field for annotation or Appsmith type List<CandidateField> finalCandidateFields = new ArrayList<>(); synchronized (sourceClass) { ReflectionUtils.doWithFields(sourceClass, field -> { if (field.getAnnotation(Encrypted.class) != null) { CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); finalCandidateFields.add(candidateField); } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { CandidateField candidateField = null; field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source);
List<CandidateField> findCandidateFieldsForType(@NonNull Object source) { // At this point source class represents the true polymorphic type of the document Class<?> sourceClass = source.getClass(); // Lock a thread wanting to find information about the same type // So that this information retrieval is only done once // Ignore this warning, this class reference will be on the heap List<CandidateField> candidateFields = this.encryptedFieldsMap.get(sourceClass); if (candidateFields != null) { // The cache is already aware of this type, return candidate fields for it return candidateFields; } // Don't bother with primitives if (ClassUtils.isPrimitiveOrWrapper(sourceClass)) return Collections.emptyList(); // If it is not known, scan each field for annotation or Appsmith type List<CandidateField> finalCandidateFields = new ArrayList<>(); synchronized (sourceClass) { ReflectionUtils.doWithFields(sourceClass, field -> { if (field.getAnnotation(Encrypted.class) != null) { CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); finalCandidateFields.add(candidateField); } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { CandidateField candidateField = null; field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); if (fieldValue == null) { if (this.encryptedFieldsMap.containsKey(field.getType())) { // If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); }
34,357
6
// If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations
List<CandidateField> findCandidateFieldsForType(@NonNull Object source) { // At this point source class represents the true polymorphic type of the document Class<?> sourceClass = source.getClass(); // Lock a thread wanting to find information about the same type // So that this information retrieval is only done once // Ignore this warning, this class reference will be on the heap List<CandidateField> candidateFields = this.encryptedFieldsMap.get(sourceClass); if (candidateFields != null) { // The cache is already aware of this type, return candidate fields for it return candidateFields; } // Don't bother with primitives if (ClassUtils.isPrimitiveOrWrapper(sourceClass)) return Collections.emptyList(); // If it is not known, scan each field for annotation or Appsmith type List<CandidateField> finalCandidateFields = new ArrayList<>(); synchronized (sourceClass) { ReflectionUtils.doWithFields(sourceClass, field -> { if (field.getAnnotation(Encrypted.class) != null) { CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); finalCandidateFields.add(candidateField); } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { CandidateField candidateField = null; field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); if (fieldValue == null) { if (this.encryptedFieldsMap.containsKey(field.getType())) { // If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); } } else { // If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) { // This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates candidateField = new CandidateField(field, appsmithFieldType); } } field.setAccessible(false); if (candidateField != null) { // This will only ever be null if the field value is populated, // and is known to be a non-encryption related field finalCandidateFields.add(candidateField); } } else if (Collection.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { // If this is a collection, check if the Type parameter is an AppsmithDomain Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType; try { subFieldType = (Class<?>) typeArguments[0]; } catch (ClassCastException|ArrayIndexOutOfBoundsException e) { subFieldType = null; } if(subFieldType != null) { if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Collection<?> collection = (Collection<?>) fieldValue; if (collection == null || collection.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_UNKNOWN)); } else { for (final Object o : collection) { if (o == null) { continue; } if (o.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(o); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_POLYMORPHIC)); } break; } } field.setAccessible(false); } } // TODO Add support for nested collections } else if (Map.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType = (Class<?>) typeArguments[1]; if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Map<?, ?> map = (Map<?, ?>) fieldValue; if (map == null || map.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_UNKNOWN)); } else { for (Map.Entry<?, ?> entry : map.entrySet()) { final Object value = entry.getValue(); if (value == null) { continue; } if (value.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(value); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_POLYMORPHIC)); } break; } } field.setAccessible(false); } } }, field -> field.getAnnotation(Encrypted.class) != null || AppsmithDomain.class.isAssignableFrom(field.getType()) || Collection.class.isAssignableFrom(field.getType()) || Map.class.isAssignableFrom(field.getType())); } // Update cache for next use encryptedFieldsMap.put(sourceClass, finalCandidateFields); return finalCandidateFields; }
NONSATD
true
if (fieldValue == null) { if (this.encryptedFieldsMap.containsKey(field.getType())) { // If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else {
ReflectionUtils.doWithFields(sourceClass, field -> { if (field.getAnnotation(Encrypted.class) != null) { CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); finalCandidateFields.add(candidateField); } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { CandidateField candidateField = null; field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); if (fieldValue == null) { if (this.encryptedFieldsMap.containsKey(field.getType())) { // If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); } } else { // If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) {
List<CandidateField> candidateFields = this.encryptedFieldsMap.get(sourceClass); if (candidateFields != null) { // The cache is already aware of this type, return candidate fields for it return candidateFields; } // Don't bother with primitives if (ClassUtils.isPrimitiveOrWrapper(sourceClass)) return Collections.emptyList(); // If it is not known, scan each field for annotation or Appsmith type List<CandidateField> finalCandidateFields = new ArrayList<>(); synchronized (sourceClass) { ReflectionUtils.doWithFields(sourceClass, field -> { if (field.getAnnotation(Encrypted.class) != null) { CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); finalCandidateFields.add(candidateField); } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { CandidateField candidateField = null; field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); if (fieldValue == null) { if (this.encryptedFieldsMap.containsKey(field.getType())) { // If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); } } else { // If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC)
34,357
7
// If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic)
List<CandidateField> findCandidateFieldsForType(@NonNull Object source) { // At this point source class represents the true polymorphic type of the document Class<?> sourceClass = source.getClass(); // Lock a thread wanting to find information about the same type // So that this information retrieval is only done once // Ignore this warning, this class reference will be on the heap List<CandidateField> candidateFields = this.encryptedFieldsMap.get(sourceClass); if (candidateFields != null) { // The cache is already aware of this type, return candidate fields for it return candidateFields; } // Don't bother with primitives if (ClassUtils.isPrimitiveOrWrapper(sourceClass)) return Collections.emptyList(); // If it is not known, scan each field for annotation or Appsmith type List<CandidateField> finalCandidateFields = new ArrayList<>(); synchronized (sourceClass) { ReflectionUtils.doWithFields(sourceClass, field -> { if (field.getAnnotation(Encrypted.class) != null) { CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); finalCandidateFields.add(candidateField); } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { CandidateField candidateField = null; field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); if (fieldValue == null) { if (this.encryptedFieldsMap.containsKey(field.getType())) { // If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); } } else { // If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) { // This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates candidateField = new CandidateField(field, appsmithFieldType); } } field.setAccessible(false); if (candidateField != null) { // This will only ever be null if the field value is populated, // and is known to be a non-encryption related field finalCandidateFields.add(candidateField); } } else if (Collection.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { // If this is a collection, check if the Type parameter is an AppsmithDomain Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType; try { subFieldType = (Class<?>) typeArguments[0]; } catch (ClassCastException|ArrayIndexOutOfBoundsException e) { subFieldType = null; } if(subFieldType != null) { if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Collection<?> collection = (Collection<?>) fieldValue; if (collection == null || collection.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_UNKNOWN)); } else { for (final Object o : collection) { if (o == null) { continue; } if (o.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(o); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_POLYMORPHIC)); } break; } } field.setAccessible(false); } } // TODO Add support for nested collections } else if (Map.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType = (Class<?>) typeArguments[1]; if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Map<?, ?> map = (Map<?, ?>) fieldValue; if (map == null || map.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_UNKNOWN)); } else { for (Map.Entry<?, ?> entry : map.entrySet()) { final Object value = entry.getValue(); if (value == null) { continue; } if (value.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(value); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_POLYMORPHIC)); } break; } } field.setAccessible(false); } } }, field -> field.getAnnotation(Encrypted.class) != null || AppsmithDomain.class.isAssignableFrom(field.getType()) || Collection.class.isAssignableFrom(field.getType()) || Map.class.isAssignableFrom(field.getType())); } // Update cache for next use encryptedFieldsMap.put(sourceClass, finalCandidateFields); return finalCandidateFields; }
NONSATD
true
candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); }
} else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { CandidateField candidateField = null; field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); if (fieldValue == null) { if (this.encryptedFieldsMap.containsKey(field.getType())) { // If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); } } else { // If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic,
} // Don't bother with primitives if (ClassUtils.isPrimitiveOrWrapper(sourceClass)) return Collections.emptyList(); // If it is not known, scan each field for annotation or Appsmith type List<CandidateField> finalCandidateFields = new ArrayList<>(); synchronized (sourceClass) { ReflectionUtils.doWithFields(sourceClass, field -> { if (field.getAnnotation(Encrypted.class) != null) { CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); finalCandidateFields.add(candidateField); } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { CandidateField candidateField = null; field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); if (fieldValue == null) { if (this.encryptedFieldsMap.containsKey(field.getType())) { // If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); } } else { // If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) { // This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates candidateField = new CandidateField(field, appsmithFieldType);
34,357
8
// If an object exists, check if the object type is the same as the field type
List<CandidateField> findCandidateFieldsForType(@NonNull Object source) { // At this point source class represents the true polymorphic type of the document Class<?> sourceClass = source.getClass(); // Lock a thread wanting to find information about the same type // So that this information retrieval is only done once // Ignore this warning, this class reference will be on the heap List<CandidateField> candidateFields = this.encryptedFieldsMap.get(sourceClass); if (candidateFields != null) { // The cache is already aware of this type, return candidate fields for it return candidateFields; } // Don't bother with primitives if (ClassUtils.isPrimitiveOrWrapper(sourceClass)) return Collections.emptyList(); // If it is not known, scan each field for annotation or Appsmith type List<CandidateField> finalCandidateFields = new ArrayList<>(); synchronized (sourceClass) { ReflectionUtils.doWithFields(sourceClass, field -> { if (field.getAnnotation(Encrypted.class) != null) { CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); finalCandidateFields.add(candidateField); } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { CandidateField candidateField = null; field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); if (fieldValue == null) { if (this.encryptedFieldsMap.containsKey(field.getType())) { // If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); } } else { // If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) { // This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates candidateField = new CandidateField(field, appsmithFieldType); } } field.setAccessible(false); if (candidateField != null) { // This will only ever be null if the field value is populated, // and is known to be a non-encryption related field finalCandidateFields.add(candidateField); } } else if (Collection.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { // If this is a collection, check if the Type parameter is an AppsmithDomain Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType; try { subFieldType = (Class<?>) typeArguments[0]; } catch (ClassCastException|ArrayIndexOutOfBoundsException e) { subFieldType = null; } if(subFieldType != null) { if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Collection<?> collection = (Collection<?>) fieldValue; if (collection == null || collection.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_UNKNOWN)); } else { for (final Object o : collection) { if (o == null) { continue; } if (o.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(o); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_POLYMORPHIC)); } break; } } field.setAccessible(false); } } // TODO Add support for nested collections } else if (Map.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType = (Class<?>) typeArguments[1]; if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Map<?, ?> map = (Map<?, ?>) fieldValue; if (map == null || map.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_UNKNOWN)); } else { for (Map.Entry<?, ?> entry : map.entrySet()) { final Object value = entry.getValue(); if (value == null) { continue; } if (value.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(value); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_POLYMORPHIC)); } break; } } field.setAccessible(false); } } }, field -> field.getAnnotation(Encrypted.class) != null || AppsmithDomain.class.isAssignableFrom(field.getType()) || Collection.class.isAssignableFrom(field.getType()) || Map.class.isAssignableFrom(field.getType())); } // Update cache for next use encryptedFieldsMap.put(sourceClass, finalCandidateFields); return finalCandidateFields; }
NONSATD
true
} } else { // If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) {
if (this.encryptedFieldsMap.containsKey(field.getType())) { // If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); } } else { // If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat
synchronized (sourceClass) { ReflectionUtils.doWithFields(sourceClass, field -> { if (field.getAnnotation(Encrypted.class) != null) { CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); finalCandidateFields.add(candidateField); } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { CandidateField candidateField = null; field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); if (fieldValue == null) { if (this.encryptedFieldsMap.containsKey(field.getType())) { // If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); } } else { // If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) { // This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates candidateField = new CandidateField(field, appsmithFieldType); } } field.setAccessible(false); if (candidateField != null) {
34,357
9
// If they match, then this is going to be an appsmith known field
List<CandidateField> findCandidateFieldsForType(@NonNull Object source) { // At this point source class represents the true polymorphic type of the document Class<?> sourceClass = source.getClass(); // Lock a thread wanting to find information about the same type // So that this information retrieval is only done once // Ignore this warning, this class reference will be on the heap List<CandidateField> candidateFields = this.encryptedFieldsMap.get(sourceClass); if (candidateFields != null) { // The cache is already aware of this type, return candidate fields for it return candidateFields; } // Don't bother with primitives if (ClassUtils.isPrimitiveOrWrapper(sourceClass)) return Collections.emptyList(); // If it is not known, scan each field for annotation or Appsmith type List<CandidateField> finalCandidateFields = new ArrayList<>(); synchronized (sourceClass) { ReflectionUtils.doWithFields(sourceClass, field -> { if (field.getAnnotation(Encrypted.class) != null) { CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); finalCandidateFields.add(candidateField); } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { CandidateField candidateField = null; field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); if (fieldValue == null) { if (this.encryptedFieldsMap.containsKey(field.getType())) { // If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); } } else { // If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) { // This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates candidateField = new CandidateField(field, appsmithFieldType); } } field.setAccessible(false); if (candidateField != null) { // This will only ever be null if the field value is populated, // and is known to be a non-encryption related field finalCandidateFields.add(candidateField); } } else if (Collection.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { // If this is a collection, check if the Type parameter is an AppsmithDomain Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType; try { subFieldType = (Class<?>) typeArguments[0]; } catch (ClassCastException|ArrayIndexOutOfBoundsException e) { subFieldType = null; } if(subFieldType != null) { if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Collection<?> collection = (Collection<?>) fieldValue; if (collection == null || collection.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_UNKNOWN)); } else { for (final Object o : collection) { if (o == null) { continue; } if (o.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(o); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_POLYMORPHIC)); } break; } } field.setAccessible(false); } } // TODO Add support for nested collections } else if (Map.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType = (Class<?>) typeArguments[1]; if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Map<?, ?> map = (Map<?, ?>) fieldValue; if (map == null || map.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_UNKNOWN)); } else { for (Map.Entry<?, ?> entry : map.entrySet()) { final Object value = entry.getValue(); if (value == null) { continue; } if (value.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(value); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_POLYMORPHIC)); } break; } } field.setAccessible(false); } } }, field -> field.getAnnotation(Encrypted.class) != null || AppsmithDomain.class.isAssignableFrom(field.getType()) || Collection.class.isAssignableFrom(field.getType()) || Map.class.isAssignableFrom(field.getType())); } // Update cache for next use encryptedFieldsMap.put(sourceClass, finalCandidateFields); return finalCandidateFields; }
NONSATD
true
CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else {
candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); } } else { // If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) {
CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); finalCandidateFields.add(candidateField); } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { CandidateField candidateField = null; field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); if (fieldValue == null) { if (this.encryptedFieldsMap.containsKey(field.getType())) { // If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); } } else { // If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) { // This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates candidateField = new CandidateField(field, appsmithFieldType); } } field.setAccessible(false); if (candidateField != null) { // This will only ever be null if the field value is populated, // and is known to be a non-encryption related field finalCandidateFields.add(candidateField);
34,357
10
// If not, then this field is polymorphic, // it will need to be checked for type every time
List<CandidateField> findCandidateFieldsForType(@NonNull Object source) { // At this point source class represents the true polymorphic type of the document Class<?> sourceClass = source.getClass(); // Lock a thread wanting to find information about the same type // So that this information retrieval is only done once // Ignore this warning, this class reference will be on the heap List<CandidateField> candidateFields = this.encryptedFieldsMap.get(sourceClass); if (candidateFields != null) { // The cache is already aware of this type, return candidate fields for it return candidateFields; } // Don't bother with primitives if (ClassUtils.isPrimitiveOrWrapper(sourceClass)) return Collections.emptyList(); // If it is not known, scan each field for annotation or Appsmith type List<CandidateField> finalCandidateFields = new ArrayList<>(); synchronized (sourceClass) { ReflectionUtils.doWithFields(sourceClass, field -> { if (field.getAnnotation(Encrypted.class) != null) { CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); finalCandidateFields.add(candidateField); } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { CandidateField candidateField = null; field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); if (fieldValue == null) { if (this.encryptedFieldsMap.containsKey(field.getType())) { // If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); } } else { // If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) { // This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates candidateField = new CandidateField(field, appsmithFieldType); } } field.setAccessible(false); if (candidateField != null) { // This will only ever be null if the field value is populated, // and is known to be a non-encryption related field finalCandidateFields.add(candidateField); } } else if (Collection.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { // If this is a collection, check if the Type parameter is an AppsmithDomain Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType; try { subFieldType = (Class<?>) typeArguments[0]; } catch (ClassCastException|ArrayIndexOutOfBoundsException e) { subFieldType = null; } if(subFieldType != null) { if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Collection<?> collection = (Collection<?>) fieldValue; if (collection == null || collection.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_UNKNOWN)); } else { for (final Object o : collection) { if (o == null) { continue; } if (o.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(o); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_POLYMORPHIC)); } break; } } field.setAccessible(false); } } // TODO Add support for nested collections } else if (Map.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType = (Class<?>) typeArguments[1]; if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Map<?, ?> map = (Map<?, ?>) fieldValue; if (map == null || map.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_UNKNOWN)); } else { for (Map.Entry<?, ?> entry : map.entrySet()) { final Object value = entry.getValue(); if (value == null) { continue; } if (value.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(value); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_POLYMORPHIC)); } break; } } field.setAccessible(false); } } }, field -> field.getAnnotation(Encrypted.class) != null || AppsmithDomain.class.isAssignableFrom(field.getType()) || Collection.class.isAssignableFrom(field.getType()) || Map.class.isAssignableFrom(field.getType())); } // Update cache for next use encryptedFieldsMap.put(sourceClass, finalCandidateFields); return finalCandidateFields; }
NONSATD
true
appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; }
// but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); } } else { // If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) { // This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates candidateField = new CandidateField(field, appsmithFieldType); }
CandidateField candidateField = null; field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); if (fieldValue == null) { if (this.encryptedFieldsMap.containsKey(field.getType())) { // If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); } } else { // If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) { // This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates candidateField = new CandidateField(field, appsmithFieldType); } } field.setAccessible(false); if (candidateField != null) { // This will only ever be null if the field value is populated, // and is known to be a non-encryption related field finalCandidateFields.add(candidateField); } } else if (Collection.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { // If this is a collection, check if the Type parameter is an AppsmithDomain
34,357
11
// Now, go into field type and repeat
List<CandidateField> findCandidateFieldsForType(@NonNull Object source) { // At this point source class represents the true polymorphic type of the document Class<?> sourceClass = source.getClass(); // Lock a thread wanting to find information about the same type // So that this information retrieval is only done once // Ignore this warning, this class reference will be on the heap List<CandidateField> candidateFields = this.encryptedFieldsMap.get(sourceClass); if (candidateFields != null) { // The cache is already aware of this type, return candidate fields for it return candidateFields; } // Don't bother with primitives if (ClassUtils.isPrimitiveOrWrapper(sourceClass)) return Collections.emptyList(); // If it is not known, scan each field for annotation or Appsmith type List<CandidateField> finalCandidateFields = new ArrayList<>(); synchronized (sourceClass) { ReflectionUtils.doWithFields(sourceClass, field -> { if (field.getAnnotation(Encrypted.class) != null) { CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); finalCandidateFields.add(candidateField); } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { CandidateField candidateField = null; field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); if (fieldValue == null) { if (this.encryptedFieldsMap.containsKey(field.getType())) { // If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); } } else { // If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) { // This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates candidateField = new CandidateField(field, appsmithFieldType); } } field.setAccessible(false); if (candidateField != null) { // This will only ever be null if the field value is populated, // and is known to be a non-encryption related field finalCandidateFields.add(candidateField); } } else if (Collection.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { // If this is a collection, check if the Type parameter is an AppsmithDomain Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType; try { subFieldType = (Class<?>) typeArguments[0]; } catch (ClassCastException|ArrayIndexOutOfBoundsException e) { subFieldType = null; } if(subFieldType != null) { if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Collection<?> collection = (Collection<?>) fieldValue; if (collection == null || collection.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_UNKNOWN)); } else { for (final Object o : collection) { if (o == null) { continue; } if (o.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(o); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_POLYMORPHIC)); } break; } } field.setAccessible(false); } } // TODO Add support for nested collections } else if (Map.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType = (Class<?>) typeArguments[1]; if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Map<?, ?> map = (Map<?, ?>) fieldValue; if (map == null || map.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_UNKNOWN)); } else { for (Map.Entry<?, ?> entry : map.entrySet()) { final Object value = entry.getValue(); if (value == null) { continue; } if (value.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(value); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_POLYMORPHIC)); } break; } } field.setAccessible(false); } } }, field -> field.getAnnotation(Encrypted.class) != null || AppsmithDomain.class.isAssignableFrom(field.getType()) || Collection.class.isAssignableFrom(field.getType()) || Map.class.isAssignableFrom(field.getType())); } // Update cache for next use encryptedFieldsMap.put(sourceClass, finalCandidateFields); return finalCandidateFields; }
NONSATD
true
appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC)
// If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) { // This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates candidateField = new CandidateField(field, appsmithFieldType); } } field.setAccessible(false); if (candidateField != null) {
if (this.encryptedFieldsMap.containsKey(field.getType())) { // If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); } } else { // If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) { // This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates candidateField = new CandidateField(field, appsmithFieldType); } } field.setAccessible(false); if (candidateField != null) { // This will only ever be null if the field value is populated, // and is known to be a non-encryption related field finalCandidateFields.add(candidateField); } } else if (Collection.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { // If this is a collection, check if the Type parameter is an AppsmithDomain Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments();
34,357
12
// This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates
List<CandidateField> findCandidateFieldsForType(@NonNull Object source) { // At this point source class represents the true polymorphic type of the document Class<?> sourceClass = source.getClass(); // Lock a thread wanting to find information about the same type // So that this information retrieval is only done once // Ignore this warning, this class reference will be on the heap List<CandidateField> candidateFields = this.encryptedFieldsMap.get(sourceClass); if (candidateFields != null) { // The cache is already aware of this type, return candidate fields for it return candidateFields; } // Don't bother with primitives if (ClassUtils.isPrimitiveOrWrapper(sourceClass)) return Collections.emptyList(); // If it is not known, scan each field for annotation or Appsmith type List<CandidateField> finalCandidateFields = new ArrayList<>(); synchronized (sourceClass) { ReflectionUtils.doWithFields(sourceClass, field -> { if (field.getAnnotation(Encrypted.class) != null) { CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); finalCandidateFields.add(candidateField); } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { CandidateField candidateField = null; field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); if (fieldValue == null) { if (this.encryptedFieldsMap.containsKey(field.getType())) { // If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); } } else { // If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) { // This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates candidateField = new CandidateField(field, appsmithFieldType); } } field.setAccessible(false); if (candidateField != null) { // This will only ever be null if the field value is populated, // and is known to be a non-encryption related field finalCandidateFields.add(candidateField); } } else if (Collection.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { // If this is a collection, check if the Type parameter is an AppsmithDomain Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType; try { subFieldType = (Class<?>) typeArguments[0]; } catch (ClassCastException|ArrayIndexOutOfBoundsException e) { subFieldType = null; } if(subFieldType != null) { if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Collection<?> collection = (Collection<?>) fieldValue; if (collection == null || collection.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_UNKNOWN)); } else { for (final Object o : collection) { if (o == null) { continue; } if (o.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(o); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_POLYMORPHIC)); } break; } } field.setAccessible(false); } } // TODO Add support for nested collections } else if (Map.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType = (Class<?>) typeArguments[1]; if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Map<?, ?> map = (Map<?, ?>) fieldValue; if (map == null || map.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_UNKNOWN)); } else { for (Map.Entry<?, ?> entry : map.entrySet()) { final Object value = entry.getValue(); if (value == null) { continue; } if (value.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(value); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_POLYMORPHIC)); } break; } } field.setAccessible(false); } } }, field -> field.getAnnotation(Encrypted.class) != null || AppsmithDomain.class.isAssignableFrom(field.getType()) || Collection.class.isAssignableFrom(field.getType()) || Map.class.isAssignableFrom(field.getType())); } // Update cache for next use encryptedFieldsMap.put(sourceClass, finalCandidateFields); return finalCandidateFields; }
NONSATD
true
if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) { // This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates candidateField = new CandidateField(field, appsmithFieldType); }
appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) { // This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates candidateField = new CandidateField(field, appsmithFieldType); } } field.setAccessible(false); if (candidateField != null) { // This will only ever be null if the field value is populated, // and is known to be a non-encryption related field finalCandidateFields.add(candidateField); } } else if (Collection.class.isAssignableFrom(field.getType()) &&
} else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); } } else { // If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) { // This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates candidateField = new CandidateField(field, appsmithFieldType); } } field.setAccessible(false); if (candidateField != null) { // This will only ever be null if the field value is populated, // and is known to be a non-encryption related field finalCandidateFields.add(candidateField); } } else if (Collection.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { // If this is a collection, check if the Type parameter is an AppsmithDomain Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType; try { subFieldType = (Class<?>) typeArguments[0]; } catch (ClassCastException|ArrayIndexOutOfBoundsException e) { subFieldType = null;
34,357
13
// This will only ever be null if the field value is populated, // and is known to be a non-encryption related field
List<CandidateField> findCandidateFieldsForType(@NonNull Object source) { // At this point source class represents the true polymorphic type of the document Class<?> sourceClass = source.getClass(); // Lock a thread wanting to find information about the same type // So that this information retrieval is only done once // Ignore this warning, this class reference will be on the heap List<CandidateField> candidateFields = this.encryptedFieldsMap.get(sourceClass); if (candidateFields != null) { // The cache is already aware of this type, return candidate fields for it return candidateFields; } // Don't bother with primitives if (ClassUtils.isPrimitiveOrWrapper(sourceClass)) return Collections.emptyList(); // If it is not known, scan each field for annotation or Appsmith type List<CandidateField> finalCandidateFields = new ArrayList<>(); synchronized (sourceClass) { ReflectionUtils.doWithFields(sourceClass, field -> { if (field.getAnnotation(Encrypted.class) != null) { CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); finalCandidateFields.add(candidateField); } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { CandidateField candidateField = null; field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); if (fieldValue == null) { if (this.encryptedFieldsMap.containsKey(field.getType())) { // If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); } } else { // If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) { // This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates candidateField = new CandidateField(field, appsmithFieldType); } } field.setAccessible(false); if (candidateField != null) { // This will only ever be null if the field value is populated, // and is known to be a non-encryption related field finalCandidateFields.add(candidateField); } } else if (Collection.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { // If this is a collection, check if the Type parameter is an AppsmithDomain Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType; try { subFieldType = (Class<?>) typeArguments[0]; } catch (ClassCastException|ArrayIndexOutOfBoundsException e) { subFieldType = null; } if(subFieldType != null) { if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Collection<?> collection = (Collection<?>) fieldValue; if (collection == null || collection.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_UNKNOWN)); } else { for (final Object o : collection) { if (o == null) { continue; } if (o.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(o); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_POLYMORPHIC)); } break; } } field.setAccessible(false); } } // TODO Add support for nested collections } else if (Map.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType = (Class<?>) typeArguments[1]; if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Map<?, ?> map = (Map<?, ?>) fieldValue; if (map == null || map.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_UNKNOWN)); } else { for (Map.Entry<?, ?> entry : map.entrySet()) { final Object value = entry.getValue(); if (value == null) { continue; } if (value.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(value); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_POLYMORPHIC)); } break; } } field.setAccessible(false); } } }, field -> field.getAnnotation(Encrypted.class) != null || AppsmithDomain.class.isAssignableFrom(field.getType()) || Collection.class.isAssignableFrom(field.getType()) || Map.class.isAssignableFrom(field.getType())); } // Update cache for next use encryptedFieldsMap.put(sourceClass, finalCandidateFields); return finalCandidateFields; }
NONSATD
true
field.setAccessible(false); if (candidateField != null) { // This will only ever be null if the field value is populated, // and is known to be a non-encryption related field finalCandidateFields.add(candidateField); }
List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) { // This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates candidateField = new CandidateField(field, appsmithFieldType); } } field.setAccessible(false); if (candidateField != null) { // This will only ever be null if the field value is populated, // and is known to be a non-encryption related field finalCandidateFields.add(candidateField); } } else if (Collection.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { // If this is a collection, check if the Type parameter is an AppsmithDomain Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType; try {
CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) { // This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates candidateField = new CandidateField(field, appsmithFieldType); } } field.setAccessible(false); if (candidateField != null) { // This will only ever be null if the field value is populated, // and is known to be a non-encryption related field finalCandidateFields.add(candidateField); } } else if (Collection.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { // If this is a collection, check if the Type parameter is an AppsmithDomain Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType; try { subFieldType = (Class<?>) typeArguments[0]; } catch (ClassCastException|ArrayIndexOutOfBoundsException e) { subFieldType = null; } if(subFieldType != null) { if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) {
34,357
14
// If this is a collection, check if the Type parameter is an AppsmithDomain
List<CandidateField> findCandidateFieldsForType(@NonNull Object source) { // At this point source class represents the true polymorphic type of the document Class<?> sourceClass = source.getClass(); // Lock a thread wanting to find information about the same type // So that this information retrieval is only done once // Ignore this warning, this class reference will be on the heap List<CandidateField> candidateFields = this.encryptedFieldsMap.get(sourceClass); if (candidateFields != null) { // The cache is already aware of this type, return candidate fields for it return candidateFields; } // Don't bother with primitives if (ClassUtils.isPrimitiveOrWrapper(sourceClass)) return Collections.emptyList(); // If it is not known, scan each field for annotation or Appsmith type List<CandidateField> finalCandidateFields = new ArrayList<>(); synchronized (sourceClass) { ReflectionUtils.doWithFields(sourceClass, field -> { if (field.getAnnotation(Encrypted.class) != null) { CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); finalCandidateFields.add(candidateField); } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { CandidateField candidateField = null; field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); if (fieldValue == null) { if (this.encryptedFieldsMap.containsKey(field.getType())) { // If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); } } else { // If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) { // This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates candidateField = new CandidateField(field, appsmithFieldType); } } field.setAccessible(false); if (candidateField != null) { // This will only ever be null if the field value is populated, // and is known to be a non-encryption related field finalCandidateFields.add(candidateField); } } else if (Collection.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { // If this is a collection, check if the Type parameter is an AppsmithDomain Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType; try { subFieldType = (Class<?>) typeArguments[0]; } catch (ClassCastException|ArrayIndexOutOfBoundsException e) { subFieldType = null; } if(subFieldType != null) { if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Collection<?> collection = (Collection<?>) fieldValue; if (collection == null || collection.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_UNKNOWN)); } else { for (final Object o : collection) { if (o == null) { continue; } if (o.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(o); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_POLYMORPHIC)); } break; } } field.setAccessible(false); } } // TODO Add support for nested collections } else if (Map.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType = (Class<?>) typeArguments[1]; if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Map<?, ?> map = (Map<?, ?>) fieldValue; if (map == null || map.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_UNKNOWN)); } else { for (Map.Entry<?, ?> entry : map.entrySet()) { final Object value = entry.getValue(); if (value == null) { continue; } if (value.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(value); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_POLYMORPHIC)); } break; } } field.setAccessible(false); } } }, field -> field.getAnnotation(Encrypted.class) != null || AppsmithDomain.class.isAssignableFrom(field.getType()) || Collection.class.isAssignableFrom(field.getType()) || Map.class.isAssignableFrom(field.getType())); } // Update cache for next use encryptedFieldsMap.put(sourceClass, finalCandidateFields); return finalCandidateFields; }
NONSATD
true
} else if (Collection.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { // If this is a collection, check if the Type parameter is an AppsmithDomain Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType();
} } field.setAccessible(false); if (candidateField != null) { // This will only ever be null if the field value is populated, // and is known to be a non-encryption related field finalCandidateFields.add(candidateField); } } else if (Collection.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { // If this is a collection, check if the Type parameter is an AppsmithDomain Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType; try { subFieldType = (Class<?>) typeArguments[0]; } catch (ClassCastException|ArrayIndexOutOfBoundsException e) { subFieldType = null; } if(subFieldType != null) {
// it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) { // This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates candidateField = new CandidateField(field, appsmithFieldType); } } field.setAccessible(false); if (candidateField != null) { // This will only ever be null if the field value is populated, // and is known to be a non-encryption related field finalCandidateFields.add(candidateField); } } else if (Collection.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { // If this is a collection, check if the Type parameter is an AppsmithDomain Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType; try { subFieldType = (Class<?>) typeArguments[0]; } catch (ClassCastException|ArrayIndexOutOfBoundsException e) { subFieldType = null; } if(subFieldType != null) { if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true);
34,357
15
// This is a known type, it should necessarily be of AppsmithDomain type
List<CandidateField> findCandidateFieldsForType(@NonNull Object source) { // At this point source class represents the true polymorphic type of the document Class<?> sourceClass = source.getClass(); // Lock a thread wanting to find information about the same type // So that this information retrieval is only done once // Ignore this warning, this class reference will be on the heap List<CandidateField> candidateFields = this.encryptedFieldsMap.get(sourceClass); if (candidateFields != null) { // The cache is already aware of this type, return candidate fields for it return candidateFields; } // Don't bother with primitives if (ClassUtils.isPrimitiveOrWrapper(sourceClass)) return Collections.emptyList(); // If it is not known, scan each field for annotation or Appsmith type List<CandidateField> finalCandidateFields = new ArrayList<>(); synchronized (sourceClass) { ReflectionUtils.doWithFields(sourceClass, field -> { if (field.getAnnotation(Encrypted.class) != null) { CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); finalCandidateFields.add(candidateField); } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { CandidateField candidateField = null; field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); if (fieldValue == null) { if (this.encryptedFieldsMap.containsKey(field.getType())) { // If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); } } else { // If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) { // This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates candidateField = new CandidateField(field, appsmithFieldType); } } field.setAccessible(false); if (candidateField != null) { // This will only ever be null if the field value is populated, // and is known to be a non-encryption related field finalCandidateFields.add(candidateField); } } else if (Collection.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { // If this is a collection, check if the Type parameter is an AppsmithDomain Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType; try { subFieldType = (Class<?>) typeArguments[0]; } catch (ClassCastException|ArrayIndexOutOfBoundsException e) { subFieldType = null; } if(subFieldType != null) { if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Collection<?> collection = (Collection<?>) fieldValue; if (collection == null || collection.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_UNKNOWN)); } else { for (final Object o : collection) { if (o == null) { continue; } if (o.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(o); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_POLYMORPHIC)); } break; } } field.setAccessible(false); } } // TODO Add support for nested collections } else if (Map.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType = (Class<?>) typeArguments[1]; if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Map<?, ?> map = (Map<?, ?>) fieldValue; if (map == null || map.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_UNKNOWN)); } else { for (Map.Entry<?, ?> entry : map.entrySet()) { final Object value = entry.getValue(); if (value == null) { continue; } if (value.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(value); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_POLYMORPHIC)); } break; } } field.setAccessible(false); } } }, field -> field.getAnnotation(Encrypted.class) != null || AppsmithDomain.class.isAssignableFrom(field.getType()) || Collection.class.isAssignableFrom(field.getType()) || Map.class.isAssignableFrom(field.getType())); } // Update cache for next use encryptedFieldsMap.put(sourceClass, finalCandidateFields); return finalCandidateFields; }
NONSATD
true
if(subFieldType != null) { if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType);
ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType; try { subFieldType = (Class<?>) typeArguments[0]; } catch (ClassCastException|ArrayIndexOutOfBoundsException e) { subFieldType = null; } if(subFieldType != null) { if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Collection<?> collection = (Collection<?>) fieldValue;
field.setAccessible(false); if (candidateField != null) { // This will only ever be null if the field value is populated, // and is known to be a non-encryption related field finalCandidateFields.add(candidateField); } } else if (Collection.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { // If this is a collection, check if the Type parameter is an AppsmithDomain Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType; try { subFieldType = (Class<?>) typeArguments[0]; } catch (ClassCastException|ArrayIndexOutOfBoundsException e) { subFieldType = null; } if(subFieldType != null) { if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Collection<?> collection = (Collection<?>) fieldValue; if (collection == null || collection.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_UNKNOWN)); } else { for (final Object o : collection) { if (o == null) { continue; } if (o.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(o); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) {
34,357
16
// If the type is not known, then this is either not parsed yet, or has polymorphic implementations
List<CandidateField> findCandidateFieldsForType(@NonNull Object source) { // At this point source class represents the true polymorphic type of the document Class<?> sourceClass = source.getClass(); // Lock a thread wanting to find information about the same type // So that this information retrieval is only done once // Ignore this warning, this class reference will be on the heap List<CandidateField> candidateFields = this.encryptedFieldsMap.get(sourceClass); if (candidateFields != null) { // The cache is already aware of this type, return candidate fields for it return candidateFields; } // Don't bother with primitives if (ClassUtils.isPrimitiveOrWrapper(sourceClass)) return Collections.emptyList(); // If it is not known, scan each field for annotation or Appsmith type List<CandidateField> finalCandidateFields = new ArrayList<>(); synchronized (sourceClass) { ReflectionUtils.doWithFields(sourceClass, field -> { if (field.getAnnotation(Encrypted.class) != null) { CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); finalCandidateFields.add(candidateField); } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { CandidateField candidateField = null; field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); if (fieldValue == null) { if (this.encryptedFieldsMap.containsKey(field.getType())) { // If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); } } else { // If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) { // This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates candidateField = new CandidateField(field, appsmithFieldType); } } field.setAccessible(false); if (candidateField != null) { // This will only ever be null if the field value is populated, // and is known to be a non-encryption related field finalCandidateFields.add(candidateField); } } else if (Collection.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { // If this is a collection, check if the Type parameter is an AppsmithDomain Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType; try { subFieldType = (Class<?>) typeArguments[0]; } catch (ClassCastException|ArrayIndexOutOfBoundsException e) { subFieldType = null; } if(subFieldType != null) { if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Collection<?> collection = (Collection<?>) fieldValue; if (collection == null || collection.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_UNKNOWN)); } else { for (final Object o : collection) { if (o == null) { continue; } if (o.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(o); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_POLYMORPHIC)); } break; } } field.setAccessible(false); } } // TODO Add support for nested collections } else if (Map.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType = (Class<?>) typeArguments[1]; if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Map<?, ?> map = (Map<?, ?>) fieldValue; if (map == null || map.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_UNKNOWN)); } else { for (Map.Entry<?, ?> entry : map.entrySet()) { final Object value = entry.getValue(); if (value == null) { continue; } if (value.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(value); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_POLYMORPHIC)); } break; } } field.setAccessible(false); } } }, field -> field.getAnnotation(Encrypted.class) != null || AppsmithDomain.class.isAssignableFrom(field.getType()) || Collection.class.isAssignableFrom(field.getType()) || Map.class.isAssignableFrom(field.getType())); } // Update cache for next use encryptedFieldsMap.put(sourceClass, finalCandidateFields); return finalCandidateFields; }
NONSATD
true
} } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source);
} if(subFieldType != null) { if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Collection<?> collection = (Collection<?>) fieldValue; if (collection == null || collection.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_UNKNOWN)); } else { for (final Object o : collection) { if (o == null) { continue; }
field.getGenericType() instanceof ParameterizedType) { // If this is a collection, check if the Type parameter is an AppsmithDomain Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType; try { subFieldType = (Class<?>) typeArguments[0]; } catch (ClassCastException|ArrayIndexOutOfBoundsException e) { subFieldType = null; } if(subFieldType != null) { if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Collection<?> collection = (Collection<?>) fieldValue; if (collection == null || collection.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_UNKNOWN)); } else { for (final Object o : collection) { if (o == null) { continue; } if (o.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(o); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_POLYMORPHIC)); } break; }
34,357
17
// TODO Add support for nested collections
List<CandidateField> findCandidateFieldsForType(@NonNull Object source) { // At this point source class represents the true polymorphic type of the document Class<?> sourceClass = source.getClass(); // Lock a thread wanting to find information about the same type // So that this information retrieval is only done once // Ignore this warning, this class reference will be on the heap List<CandidateField> candidateFields = this.encryptedFieldsMap.get(sourceClass); if (candidateFields != null) { // The cache is already aware of this type, return candidate fields for it return candidateFields; } // Don't bother with primitives if (ClassUtils.isPrimitiveOrWrapper(sourceClass)) return Collections.emptyList(); // If it is not known, scan each field for annotation or Appsmith type List<CandidateField> finalCandidateFields = new ArrayList<>(); synchronized (sourceClass) { ReflectionUtils.doWithFields(sourceClass, field -> { if (field.getAnnotation(Encrypted.class) != null) { CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); finalCandidateFields.add(candidateField); } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { CandidateField candidateField = null; field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); if (fieldValue == null) { if (this.encryptedFieldsMap.containsKey(field.getType())) { // If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); } } else { // If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) { // This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates candidateField = new CandidateField(field, appsmithFieldType); } } field.setAccessible(false); if (candidateField != null) { // This will only ever be null if the field value is populated, // and is known to be a non-encryption related field finalCandidateFields.add(candidateField); } } else if (Collection.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { // If this is a collection, check if the Type parameter is an AppsmithDomain Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType; try { subFieldType = (Class<?>) typeArguments[0]; } catch (ClassCastException|ArrayIndexOutOfBoundsException e) { subFieldType = null; } if(subFieldType != null) { if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Collection<?> collection = (Collection<?>) fieldValue; if (collection == null || collection.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_UNKNOWN)); } else { for (final Object o : collection) { if (o == null) { continue; } if (o.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(o); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_POLYMORPHIC)); } break; } } field.setAccessible(false); } } // TODO Add support for nested collections } else if (Map.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType = (Class<?>) typeArguments[1]; if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Map<?, ?> map = (Map<?, ?>) fieldValue; if (map == null || map.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_UNKNOWN)); } else { for (Map.Entry<?, ?> entry : map.entrySet()) { final Object value = entry.getValue(); if (value == null) { continue; } if (value.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(value); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_POLYMORPHIC)); } break; } } field.setAccessible(false); } } }, field -> field.getAnnotation(Encrypted.class) != null || AppsmithDomain.class.isAssignableFrom(field.getType()) || Collection.class.isAssignableFrom(field.getType()) || Map.class.isAssignableFrom(field.getType())); } // Update cache for next use encryptedFieldsMap.put(sourceClass, finalCandidateFields); return finalCandidateFields; }
IMPLEMENTATION
true
} } // TODO Add support for nested collections } else if (Map.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) {
} } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_POLYMORPHIC)); } break; } } field.setAccessible(false); } } // TODO Add support for nested collections } else if (Map.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType = (Class<?>) typeArguments[1]; if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType);
finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_UNKNOWN)); } else { for (final Object o : collection) { if (o == null) { continue; } if (o.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(o); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_POLYMORPHIC)); } break; } } field.setAccessible(false); } } // TODO Add support for nested collections } else if (Map.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType = (Class<?>) typeArguments[1]; if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Map<?, ?> map = (Map<?, ?>) fieldValue; if (map == null || map.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_UNKNOWN));
34,357
18
// This is a known type, it should necessarily be of AppsmithDomain type
List<CandidateField> findCandidateFieldsForType(@NonNull Object source) { // At this point source class represents the true polymorphic type of the document Class<?> sourceClass = source.getClass(); // Lock a thread wanting to find information about the same type // So that this information retrieval is only done once // Ignore this warning, this class reference will be on the heap List<CandidateField> candidateFields = this.encryptedFieldsMap.get(sourceClass); if (candidateFields != null) { // The cache is already aware of this type, return candidate fields for it return candidateFields; } // Don't bother with primitives if (ClassUtils.isPrimitiveOrWrapper(sourceClass)) return Collections.emptyList(); // If it is not known, scan each field for annotation or Appsmith type List<CandidateField> finalCandidateFields = new ArrayList<>(); synchronized (sourceClass) { ReflectionUtils.doWithFields(sourceClass, field -> { if (field.getAnnotation(Encrypted.class) != null) { CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); finalCandidateFields.add(candidateField); } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { CandidateField candidateField = null; field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); if (fieldValue == null) { if (this.encryptedFieldsMap.containsKey(field.getType())) { // If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); } } else { // If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) { // This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates candidateField = new CandidateField(field, appsmithFieldType); } } field.setAccessible(false); if (candidateField != null) { // This will only ever be null if the field value is populated, // and is known to be a non-encryption related field finalCandidateFields.add(candidateField); } } else if (Collection.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { // If this is a collection, check if the Type parameter is an AppsmithDomain Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType; try { subFieldType = (Class<?>) typeArguments[0]; } catch (ClassCastException|ArrayIndexOutOfBoundsException e) { subFieldType = null; } if(subFieldType != null) { if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Collection<?> collection = (Collection<?>) fieldValue; if (collection == null || collection.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_UNKNOWN)); } else { for (final Object o : collection) { if (o == null) { continue; } if (o.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(o); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_POLYMORPHIC)); } break; } } field.setAccessible(false); } } // TODO Add support for nested collections } else if (Map.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType = (Class<?>) typeArguments[1]; if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Map<?, ?> map = (Map<?, ?>) fieldValue; if (map == null || map.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_UNKNOWN)); } else { for (Map.Entry<?, ?> entry : map.entrySet()) { final Object value = entry.getValue(); if (value == null) { continue; } if (value.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(value); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_POLYMORPHIC)); } break; } } field.setAccessible(false); } } }, field -> field.getAnnotation(Encrypted.class) != null || AppsmithDomain.class.isAssignableFrom(field.getType()) || Collection.class.isAssignableFrom(field.getType()) || Map.class.isAssignableFrom(field.getType())); } // Update cache for next use encryptedFieldsMap.put(sourceClass, finalCandidateFields); return finalCandidateFields; }
NONSATD
true
if(subFieldType != null) { if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType);
ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType; try { subFieldType = (Class<?>) typeArguments[0]; } catch (ClassCastException|ArrayIndexOutOfBoundsException e) { subFieldType = null; } if(subFieldType != null) { if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Collection<?> collection = (Collection<?>) fieldValue;
field.setAccessible(false); if (candidateField != null) { // This will only ever be null if the field value is populated, // and is known to be a non-encryption related field finalCandidateFields.add(candidateField); } } else if (Collection.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { // If this is a collection, check if the Type parameter is an AppsmithDomain Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType; try { subFieldType = (Class<?>) typeArguments[0]; } catch (ClassCastException|ArrayIndexOutOfBoundsException e) { subFieldType = null; } if(subFieldType != null) { if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Collection<?> collection = (Collection<?>) fieldValue; if (collection == null || collection.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_UNKNOWN)); } else { for (final Object o : collection) { if (o == null) { continue; } if (o.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(o); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) {
34,357
19
// If the type is not known, then this is either not parsed yet, or has polymorphic implementations
List<CandidateField> findCandidateFieldsForType(@NonNull Object source) { // At this point source class represents the true polymorphic type of the document Class<?> sourceClass = source.getClass(); // Lock a thread wanting to find information about the same type // So that this information retrieval is only done once // Ignore this warning, this class reference will be on the heap List<CandidateField> candidateFields = this.encryptedFieldsMap.get(sourceClass); if (candidateFields != null) { // The cache is already aware of this type, return candidate fields for it return candidateFields; } // Don't bother with primitives if (ClassUtils.isPrimitiveOrWrapper(sourceClass)) return Collections.emptyList(); // If it is not known, scan each field for annotation or Appsmith type List<CandidateField> finalCandidateFields = new ArrayList<>(); synchronized (sourceClass) { ReflectionUtils.doWithFields(sourceClass, field -> { if (field.getAnnotation(Encrypted.class) != null) { CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); finalCandidateFields.add(candidateField); } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { CandidateField candidateField = null; field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); if (fieldValue == null) { if (this.encryptedFieldsMap.containsKey(field.getType())) { // If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); } } else { // If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) { // This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates candidateField = new CandidateField(field, appsmithFieldType); } } field.setAccessible(false); if (candidateField != null) { // This will only ever be null if the field value is populated, // and is known to be a non-encryption related field finalCandidateFields.add(candidateField); } } else if (Collection.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { // If this is a collection, check if the Type parameter is an AppsmithDomain Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType; try { subFieldType = (Class<?>) typeArguments[0]; } catch (ClassCastException|ArrayIndexOutOfBoundsException e) { subFieldType = null; } if(subFieldType != null) { if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Collection<?> collection = (Collection<?>) fieldValue; if (collection == null || collection.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_UNKNOWN)); } else { for (final Object o : collection) { if (o == null) { continue; } if (o.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(o); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_POLYMORPHIC)); } break; } } field.setAccessible(false); } } // TODO Add support for nested collections } else if (Map.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType = (Class<?>) typeArguments[1]; if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Map<?, ?> map = (Map<?, ?>) fieldValue; if (map == null || map.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_UNKNOWN)); } else { for (Map.Entry<?, ?> entry : map.entrySet()) { final Object value = entry.getValue(); if (value == null) { continue; } if (value.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(value); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_POLYMORPHIC)); } break; } } field.setAccessible(false); } } }, field -> field.getAnnotation(Encrypted.class) != null || AppsmithDomain.class.isAssignableFrom(field.getType()) || Collection.class.isAssignableFrom(field.getType()) || Map.class.isAssignableFrom(field.getType())); } // Update cache for next use encryptedFieldsMap.put(sourceClass, finalCandidateFields); return finalCandidateFields; }
NONSATD
true
} } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source);
} if(subFieldType != null) { if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Collection<?> collection = (Collection<?>) fieldValue; if (collection == null || collection.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_UNKNOWN)); } else { for (final Object o : collection) { if (o == null) { continue; }
field.getGenericType() instanceof ParameterizedType) { // If this is a collection, check if the Type parameter is an AppsmithDomain Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType; try { subFieldType = (Class<?>) typeArguments[0]; } catch (ClassCastException|ArrayIndexOutOfBoundsException e) { subFieldType = null; } if(subFieldType != null) { if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Collection<?> collection = (Collection<?>) fieldValue; if (collection == null || collection.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_UNKNOWN)); } else { for (final Object o : collection) { if (o == null) { continue; } if (o.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(o); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_POLYMORPHIC)); } break; }
34,357
20
// Update cache for next use
List<CandidateField> findCandidateFieldsForType(@NonNull Object source) { // At this point source class represents the true polymorphic type of the document Class<?> sourceClass = source.getClass(); // Lock a thread wanting to find information about the same type // So that this information retrieval is only done once // Ignore this warning, this class reference will be on the heap List<CandidateField> candidateFields = this.encryptedFieldsMap.get(sourceClass); if (candidateFields != null) { // The cache is already aware of this type, return candidate fields for it return candidateFields; } // Don't bother with primitives if (ClassUtils.isPrimitiveOrWrapper(sourceClass)) return Collections.emptyList(); // If it is not known, scan each field for annotation or Appsmith type List<CandidateField> finalCandidateFields = new ArrayList<>(); synchronized (sourceClass) { ReflectionUtils.doWithFields(sourceClass, field -> { if (field.getAnnotation(Encrypted.class) != null) { CandidateField candidateField = new CandidateField(field, CandidateField.Type.ANNOTATED_FIELD); finalCandidateFields.add(candidateField); } else if (AppsmithDomain.class.isAssignableFrom(field.getType())) { CandidateField candidateField = null; field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); if (fieldValue == null) { if (this.encryptedFieldsMap.containsKey(field.getType())) { // If this field is null, but the cache has a non-empty list of candidates already, // then this is an appsmith field with known annotations candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_KNOWN); } else { // If it is null and the cache is not aware of the field, this is still a prospect, // but with an unknown type (could also be polymorphic) candidateField = new CandidateField(field, CandidateField.Type.APPSMITH_FIELD_UNKNOWN); } } else { // If an object exists, check if the object type is the same as the field type CandidateField.Type appsmithFieldType; if (field.getType().getCanonicalName().equals(fieldValue.getClass().getCanonicalName())) { // If they match, then this is going to be an appsmith known field appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_KNOWN; } else { // If not, then this field is polymorphic, // it will need to be checked for type every time appsmithFieldType = CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC; } // Now, go into field type and repeat List<CandidateField> candidateFieldsForType = findCandidateFieldsForType(fieldValue); if (appsmithFieldType.equals(CandidateField.Type.APPSMITH_FIELD_POLYMORPHIC) || !candidateFieldsForType.isEmpty()) { // This type only qualifies as a candidate if it is polymorphic, // or has a list of candidates candidateField = new CandidateField(field, appsmithFieldType); } } field.setAccessible(false); if (candidateField != null) { // This will only ever be null if the field value is populated, // and is known to be a non-encryption related field finalCandidateFields.add(candidateField); } } else if (Collection.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { // If this is a collection, check if the Type parameter is an AppsmithDomain Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType; try { subFieldType = (Class<?>) typeArguments[0]; } catch (ClassCastException|ArrayIndexOutOfBoundsException e) { subFieldType = null; } if(subFieldType != null) { if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Collection<?> collection = (Collection<?>) fieldValue; if (collection == null || collection.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_UNKNOWN)); } else { for (final Object o : collection) { if (o == null) { continue; } if (o.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(o); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_COLLECTION_POLYMORPHIC)); } break; } } field.setAccessible(false); } } // TODO Add support for nested collections } else if (Map.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) { Type[] typeArguments; ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); typeArguments = parameterizedType.getActualTypeArguments(); Class<?> subFieldType = (Class<?>) typeArguments[1]; if (this.encryptedFieldsMap.containsKey(subFieldType)) { // This is a known type, it should necessarily be of AppsmithDomain type assert AppsmithDomain.class.isAssignableFrom(subFieldType); final List<CandidateField> existingSubTypeCandidates = this.encryptedFieldsMap.get(subFieldType); if (!existingSubTypeCandidates.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else if (AppsmithDomain.class.isAssignableFrom(subFieldType)) { // If the type is not known, then this is either not parsed yet, or has polymorphic implementations field.setAccessible(true); Object fieldValue = ReflectionUtils.getField(field, source); Map<?, ?> map = (Map<?, ?>) fieldValue; if (map == null || map.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_UNKNOWN)); } else { for (Map.Entry<?, ?> entry : map.entrySet()) { final Object value = entry.getValue(); if (value == null) { continue; } if (value.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(value); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_POLYMORPHIC)); } break; } } field.setAccessible(false); } } }, field -> field.getAnnotation(Encrypted.class) != null || AppsmithDomain.class.isAssignableFrom(field.getType()) || Collection.class.isAssignableFrom(field.getType()) || Map.class.isAssignableFrom(field.getType())); } // Update cache for next use encryptedFieldsMap.put(sourceClass, finalCandidateFields); return finalCandidateFields; }
NONSATD
true
Map.class.isAssignableFrom(field.getType())); } // Update cache for next use encryptedFieldsMap.put(sourceClass, finalCandidateFields); return finalCandidateFields;
} } field.setAccessible(false); } } }, field -> field.getAnnotation(Encrypted.class) != null || AppsmithDomain.class.isAssignableFrom(field.getType()) || Collection.class.isAssignableFrom(field.getType()) || Map.class.isAssignableFrom(field.getType())); } // Update cache for next use encryptedFieldsMap.put(sourceClass, finalCandidateFields); return finalCandidateFields; }
} if (value.getClass().getCanonicalName().equals(subFieldType.getTypeName())) { final List<CandidateField> candidateFieldsForListMember = findCandidateFieldsForType(value); if (candidateFieldsForListMember != null && !candidateFieldsForListMember.isEmpty()) { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_KNOWN)); } } else { finalCandidateFields.add(new CandidateField(field, CandidateField.Type.APPSMITH_MAP_POLYMORPHIC)); } break; } } field.setAccessible(false); } } }, field -> field.getAnnotation(Encrypted.class) != null || AppsmithDomain.class.isAssignableFrom(field.getType()) || Collection.class.isAssignableFrom(field.getType()) || Map.class.isAssignableFrom(field.getType())); } // Update cache for next use encryptedFieldsMap.put(sourceClass, finalCandidateFields); return finalCandidateFields; }
1,597
0
// TODO(#496): replace with actual study's org name.
@Transactional() @Override public EmailResponse resendConfirmationthroughEmail( String applicationId, String securityToken, String emailId, String appName) { logger.info("UserManagementProfileServiceImpl - resendConfirmationthroughEmail() - Starts"); AppEntity appPropertiesDetails = null; String content = ""; String subject = ""; AppOrgInfoBean appOrgInfoBean = null; appOrgInfoBean = commonDao.getUserAppDetailsByAllApi("", applicationId); appPropertiesDetails = userProfileManagementDao.getAppPropertiesDetailsByAppId(appOrgInfoBean.getAppInfoId()); Map<String, String> templateArgs = new HashMap<>(); if ((appPropertiesDetails == null) || (appPropertiesDetails.getRegEmailSub() == null) || (appPropertiesDetails.getRegEmailBody() == null) || appPropertiesDetails.getRegEmailBody().equalsIgnoreCase("") || appPropertiesDetails.getRegEmailSub().equalsIgnoreCase("")) { subject = appConfig.getConfirmationMailSubject(); content = appConfig.getConfirmationMail(); } else { content = appPropertiesDetails.getRegEmailBody(); subject = appPropertiesDetails.getRegEmailSub(); } templateArgs.put("appName", appName); // TODO(#496): replace with actual study's org name. templateArgs.put("orgName", appConfig.getOrgName()); templateArgs.put("contactEmail", appConfig.getContactEmail()); templateArgs.put("securitytoken", securityToken); EmailRequest emailRequest = new EmailRequest( appConfig.getFromEmail(), new String[] {emailId}, null, null, subject, content, templateArgs); logger.info("UserManagementProfileServiceImpl - resendConfirmationthroughEmail() - Ends"); return emailService.sendMimeMail(emailRequest); }
DESIGN
true
} templateArgs.put("appName", appName); // TODO(#496): replace with actual study's org name. templateArgs.put("orgName", appConfig.getOrgName()); templateArgs.put("contactEmail", appConfig.getContactEmail());
|| (appPropertiesDetails.getRegEmailBody() == null) || appPropertiesDetails.getRegEmailBody().equalsIgnoreCase("") || appPropertiesDetails.getRegEmailSub().equalsIgnoreCase("")) { subject = appConfig.getConfirmationMailSubject(); content = appConfig.getConfirmationMail(); } else { content = appPropertiesDetails.getRegEmailBody(); subject = appPropertiesDetails.getRegEmailSub(); } templateArgs.put("appName", appName); // TODO(#496): replace with actual study's org name. templateArgs.put("orgName", appConfig.getOrgName()); templateArgs.put("contactEmail", appConfig.getContactEmail()); templateArgs.put("securitytoken", securityToken); EmailRequest emailRequest = new EmailRequest( appConfig.getFromEmail(), new String[] {emailId}, null, null, subject,
AppEntity appPropertiesDetails = null; String content = ""; String subject = ""; AppOrgInfoBean appOrgInfoBean = null; appOrgInfoBean = commonDao.getUserAppDetailsByAllApi("", applicationId); appPropertiesDetails = userProfileManagementDao.getAppPropertiesDetailsByAppId(appOrgInfoBean.getAppInfoId()); Map<String, String> templateArgs = new HashMap<>(); if ((appPropertiesDetails == null) || (appPropertiesDetails.getRegEmailSub() == null) || (appPropertiesDetails.getRegEmailBody() == null) || appPropertiesDetails.getRegEmailBody().equalsIgnoreCase("") || appPropertiesDetails.getRegEmailSub().equalsIgnoreCase("")) { subject = appConfig.getConfirmationMailSubject(); content = appConfig.getConfirmationMail(); } else { content = appPropertiesDetails.getRegEmailBody(); subject = appPropertiesDetails.getRegEmailSub(); } templateArgs.put("appName", appName); // TODO(#496): replace with actual study's org name. templateArgs.put("orgName", appConfig.getOrgName()); templateArgs.put("contactEmail", appConfig.getContactEmail()); templateArgs.put("securitytoken", securityToken); EmailRequest emailRequest = new EmailRequest( appConfig.getFromEmail(), new String[] {emailId}, null, null, subject, content, templateArgs); logger.info("UserManagementProfileServiceImpl - resendConfirmationthroughEmail() - Ends"); return emailService.sendMimeMail(emailRequest); }
26,189
0
//GEN-FIRST:event_addButtonActionPerformed
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed try { // TODO add your handling code here: try { clip.stop(); } catch(Exception e) { } try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } //step2 create the connection object Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); //step3 create the statement object Statement stmt=con.createStatement(); //step4 execute query ResultSet rs=stmt.executeQuery("select * from album"); ArrayList<String> albumList = new ArrayList<String>(); HashMap<String, String> albumID = new HashMap<>(); while(rs.next()) { albumList.add((rs.getString(2))); albumID.put(rs.getString(2), rs.getString(1)); } //step4 execute query rs=stmt.executeQuery("select * from artist"); ArrayList<String> artistList = new ArrayList<String>(); HashMap<String, String> artistID = new HashMap<>(); while(rs.next()) { artistList.add((rs.getString(2))); artistID.put(rs.getString(2), rs.getString(1)); } //step5 close the connection object con.close(); // TODO add your handling code here: // JTextField id = new JTextField(); JTextField name = new JTextField(); JTextField genre = new JTextField(); JTextField song_num = new JTextField(); JComboBox<String> albums = new JComboBox<String>(albumList.toArray(new String[0])); JList artists = new JList(artistList.toArray(new String[0])); artists.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); int[] select = {19, 20, 22}; Object[] input = { // "Id : ", id, "Name : ", name, "Genre :", genre, "Artist :", artists, "Song Number in Album :", song_num, "Album :", albums, }; int option = JOptionPane.showConfirmDialog(this, input, "Enter Song details", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { JFileChooser jfc = new JFileChooser(); int returnValue = jfc.showOpenDialog(null); // int returnValue = jfc.showSaveDialog(null); String filePath = null; if (returnValue == JFileChooser.APPROVE_OPTION) { File selectedFile = jfc.getSelectedFile(); System.out.println(selectedFile.getAbsolutePath()); filePath = selectedFile.getAbsolutePath(); } try{ File f=new File(filePath); Class.forName("oracle.jdbc.driver.OracleDriver"); con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); PreparedStatement ps = con.prepareStatement ("insert into song values(?, ?, ?, ?, ?, ?, ?)"); ps.setString(1, null); ps.setString(2, name.getText()); ps.setString(3, albumID.get(albums.getSelectedItem().toString())); ps.setString(4, genre.getText()); ps.setInt(5, 0); ps.setInt(6, Integer.parseInt(song_num.getText())); System.out.println(""+f.length()); ps.setBytes(7, readFile(filePath)); ps.executeUpdate(); ps.close(); PreparedStatement ps1 = con.prepareStatement ("select id from song where name=? and album_id=?"); ps1.setString(1, name.getText()); ps1.setString(2, albumID.get(albums.getSelectedItem().toString())); //step4 execute query ResultSet rs1=ps1.executeQuery(); String id = ""; while(rs1.next()) { id = rs1.getString(1); } ps1.close(); for(Object a:artists.getSelectedValuesList()) { ps = con.prepareCall ("{call addsongartist(?, ?)}"); ps.setString(1, id); ps.setString(2, artistID.get(a.toString())); ps.executeUpdate(); ps.close(); } con.close(); } catch (Exception e) {e.printStackTrace();} this.updateTable(); JOptionPane.showMessageDialog(this, "Success!\n"); } } catch (Exception e) { JOptionPane.showMessageDialog(this, "Error!\n"+e.getMessage()); } }
NONSATD
true
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed try { // TODO add your handling code here:
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed try { // TODO add your handling code here: try { clip.stop(); } catch(Exception e) { } try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) {
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed try { // TODO add your handling code here: try { clip.stop(); } catch(Exception e) { } try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } //step2 create the connection object Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); //step3 create the statement object Statement stmt=con.createStatement(); //step4 execute query ResultSet rs=stmt.executeQuery("select * from album"); ArrayList<String> albumList = new ArrayList<String>();
26,189
1
// TODO add your handling code here:
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed try { // TODO add your handling code here: try { clip.stop(); } catch(Exception e) { } try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } //step2 create the connection object Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); //step3 create the statement object Statement stmt=con.createStatement(); //step4 execute query ResultSet rs=stmt.executeQuery("select * from album"); ArrayList<String> albumList = new ArrayList<String>(); HashMap<String, String> albumID = new HashMap<>(); while(rs.next()) { albumList.add((rs.getString(2))); albumID.put(rs.getString(2), rs.getString(1)); } //step4 execute query rs=stmt.executeQuery("select * from artist"); ArrayList<String> artistList = new ArrayList<String>(); HashMap<String, String> artistID = new HashMap<>(); while(rs.next()) { artistList.add((rs.getString(2))); artistID.put(rs.getString(2), rs.getString(1)); } //step5 close the connection object con.close(); // TODO add your handling code here: // JTextField id = new JTextField(); JTextField name = new JTextField(); JTextField genre = new JTextField(); JTextField song_num = new JTextField(); JComboBox<String> albums = new JComboBox<String>(albumList.toArray(new String[0])); JList artists = new JList(artistList.toArray(new String[0])); artists.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); int[] select = {19, 20, 22}; Object[] input = { // "Id : ", id, "Name : ", name, "Genre :", genre, "Artist :", artists, "Song Number in Album :", song_num, "Album :", albums, }; int option = JOptionPane.showConfirmDialog(this, input, "Enter Song details", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { JFileChooser jfc = new JFileChooser(); int returnValue = jfc.showOpenDialog(null); // int returnValue = jfc.showSaveDialog(null); String filePath = null; if (returnValue == JFileChooser.APPROVE_OPTION) { File selectedFile = jfc.getSelectedFile(); System.out.println(selectedFile.getAbsolutePath()); filePath = selectedFile.getAbsolutePath(); } try{ File f=new File(filePath); Class.forName("oracle.jdbc.driver.OracleDriver"); con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); PreparedStatement ps = con.prepareStatement ("insert into song values(?, ?, ?, ?, ?, ?, ?)"); ps.setString(1, null); ps.setString(2, name.getText()); ps.setString(3, albumID.get(albums.getSelectedItem().toString())); ps.setString(4, genre.getText()); ps.setInt(5, 0); ps.setInt(6, Integer.parseInt(song_num.getText())); System.out.println(""+f.length()); ps.setBytes(7, readFile(filePath)); ps.executeUpdate(); ps.close(); PreparedStatement ps1 = con.prepareStatement ("select id from song where name=? and album_id=?"); ps1.setString(1, name.getText()); ps1.setString(2, albumID.get(albums.getSelectedItem().toString())); //step4 execute query ResultSet rs1=ps1.executeQuery(); String id = ""; while(rs1.next()) { id = rs1.getString(1); } ps1.close(); for(Object a:artists.getSelectedValuesList()) { ps = con.prepareCall ("{call addsongartist(?, ?)}"); ps.setString(1, id); ps.setString(2, artistID.get(a.toString())); ps.executeUpdate(); ps.close(); } con.close(); } catch (Exception e) {e.printStackTrace();} this.updateTable(); JOptionPane.showMessageDialog(this, "Success!\n"); } } catch (Exception e) { JOptionPane.showMessageDialog(this, "Error!\n"+e.getMessage()); } }
IMPLEMENTATION
true
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed try { // TODO add your handling code here: try { clip.stop();
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed try { // TODO add your handling code here: try { clip.stop(); } catch(Exception e) { } try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); }
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed try { // TODO add your handling code here: try { clip.stop(); } catch(Exception e) { } try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } //step2 create the connection object Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); //step3 create the statement object Statement stmt=con.createStatement(); //step4 execute query ResultSet rs=stmt.executeQuery("select * from album"); ArrayList<String> albumList = new ArrayList<String>(); HashMap<String, String> albumID = new HashMap<>(); while(rs.next()) {
26,189
2
//step2 create the connection object
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed try { // TODO add your handling code here: try { clip.stop(); } catch(Exception e) { } try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } //step2 create the connection object Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); //step3 create the statement object Statement stmt=con.createStatement(); //step4 execute query ResultSet rs=stmt.executeQuery("select * from album"); ArrayList<String> albumList = new ArrayList<String>(); HashMap<String, String> albumID = new HashMap<>(); while(rs.next()) { albumList.add((rs.getString(2))); albumID.put(rs.getString(2), rs.getString(1)); } //step4 execute query rs=stmt.executeQuery("select * from artist"); ArrayList<String> artistList = new ArrayList<String>(); HashMap<String, String> artistID = new HashMap<>(); while(rs.next()) { artistList.add((rs.getString(2))); artistID.put(rs.getString(2), rs.getString(1)); } //step5 close the connection object con.close(); // TODO add your handling code here: // JTextField id = new JTextField(); JTextField name = new JTextField(); JTextField genre = new JTextField(); JTextField song_num = new JTextField(); JComboBox<String> albums = new JComboBox<String>(albumList.toArray(new String[0])); JList artists = new JList(artistList.toArray(new String[0])); artists.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); int[] select = {19, 20, 22}; Object[] input = { // "Id : ", id, "Name : ", name, "Genre :", genre, "Artist :", artists, "Song Number in Album :", song_num, "Album :", albums, }; int option = JOptionPane.showConfirmDialog(this, input, "Enter Song details", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { JFileChooser jfc = new JFileChooser(); int returnValue = jfc.showOpenDialog(null); // int returnValue = jfc.showSaveDialog(null); String filePath = null; if (returnValue == JFileChooser.APPROVE_OPTION) { File selectedFile = jfc.getSelectedFile(); System.out.println(selectedFile.getAbsolutePath()); filePath = selectedFile.getAbsolutePath(); } try{ File f=new File(filePath); Class.forName("oracle.jdbc.driver.OracleDriver"); con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); PreparedStatement ps = con.prepareStatement ("insert into song values(?, ?, ?, ?, ?, ?, ?)"); ps.setString(1, null); ps.setString(2, name.getText()); ps.setString(3, albumID.get(albums.getSelectedItem().toString())); ps.setString(4, genre.getText()); ps.setInt(5, 0); ps.setInt(6, Integer.parseInt(song_num.getText())); System.out.println(""+f.length()); ps.setBytes(7, readFile(filePath)); ps.executeUpdate(); ps.close(); PreparedStatement ps1 = con.prepareStatement ("select id from song where name=? and album_id=?"); ps1.setString(1, name.getText()); ps1.setString(2, albumID.get(albums.getSelectedItem().toString())); //step4 execute query ResultSet rs1=ps1.executeQuery(); String id = ""; while(rs1.next()) { id = rs1.getString(1); } ps1.close(); for(Object a:artists.getSelectedValuesList()) { ps = con.prepareCall ("{call addsongartist(?, ?)}"); ps.setString(1, id); ps.setString(2, artistID.get(a.toString())); ps.executeUpdate(); ps.close(); } con.close(); } catch (Exception e) {e.printStackTrace();} this.updateTable(); JOptionPane.showMessageDialog(this, "Success!\n"); } } catch (Exception e) { JOptionPane.showMessageDialog(this, "Error!\n"+e.getMessage()); } }
NONSATD
true
Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } //step2 create the connection object Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345");
try { clip.stop(); } catch(Exception e) { } try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } //step2 create the connection object Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); //step3 create the statement object Statement stmt=con.createStatement(); //step4 execute query ResultSet rs=stmt.executeQuery("select * from album"); ArrayList<String> albumList = new ArrayList<String>(); HashMap<String, String> albumID = new HashMap<>(); while(rs.next()) { albumList.add((rs.getString(2)));
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed try { // TODO add your handling code here: try { clip.stop(); } catch(Exception e) { } try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } //step2 create the connection object Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); //step3 create the statement object Statement stmt=con.createStatement(); //step4 execute query ResultSet rs=stmt.executeQuery("select * from album"); ArrayList<String> albumList = new ArrayList<String>(); HashMap<String, String> albumID = new HashMap<>(); while(rs.next()) { albumList.add((rs.getString(2))); albumID.put(rs.getString(2), rs.getString(1)); } //step4 execute query rs=stmt.executeQuery("select * from artist"); ArrayList<String> artistList = new ArrayList<String>(); HashMap<String, String> artistID = new HashMap<>(); while(rs.next()) { artistList.add((rs.getString(2))); artistID.put(rs.getString(2), rs.getString(1)); }
26,189
3
//step3 create the statement object
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed try { // TODO add your handling code here: try { clip.stop(); } catch(Exception e) { } try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } //step2 create the connection object Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); //step3 create the statement object Statement stmt=con.createStatement(); //step4 execute query ResultSet rs=stmt.executeQuery("select * from album"); ArrayList<String> albumList = new ArrayList<String>(); HashMap<String, String> albumID = new HashMap<>(); while(rs.next()) { albumList.add((rs.getString(2))); albumID.put(rs.getString(2), rs.getString(1)); } //step4 execute query rs=stmt.executeQuery("select * from artist"); ArrayList<String> artistList = new ArrayList<String>(); HashMap<String, String> artistID = new HashMap<>(); while(rs.next()) { artistList.add((rs.getString(2))); artistID.put(rs.getString(2), rs.getString(1)); } //step5 close the connection object con.close(); // TODO add your handling code here: // JTextField id = new JTextField(); JTextField name = new JTextField(); JTextField genre = new JTextField(); JTextField song_num = new JTextField(); JComboBox<String> albums = new JComboBox<String>(albumList.toArray(new String[0])); JList artists = new JList(artistList.toArray(new String[0])); artists.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); int[] select = {19, 20, 22}; Object[] input = { // "Id : ", id, "Name : ", name, "Genre :", genre, "Artist :", artists, "Song Number in Album :", song_num, "Album :", albums, }; int option = JOptionPane.showConfirmDialog(this, input, "Enter Song details", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { JFileChooser jfc = new JFileChooser(); int returnValue = jfc.showOpenDialog(null); // int returnValue = jfc.showSaveDialog(null); String filePath = null; if (returnValue == JFileChooser.APPROVE_OPTION) { File selectedFile = jfc.getSelectedFile(); System.out.println(selectedFile.getAbsolutePath()); filePath = selectedFile.getAbsolutePath(); } try{ File f=new File(filePath); Class.forName("oracle.jdbc.driver.OracleDriver"); con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); PreparedStatement ps = con.prepareStatement ("insert into song values(?, ?, ?, ?, ?, ?, ?)"); ps.setString(1, null); ps.setString(2, name.getText()); ps.setString(3, albumID.get(albums.getSelectedItem().toString())); ps.setString(4, genre.getText()); ps.setInt(5, 0); ps.setInt(6, Integer.parseInt(song_num.getText())); System.out.println(""+f.length()); ps.setBytes(7, readFile(filePath)); ps.executeUpdate(); ps.close(); PreparedStatement ps1 = con.prepareStatement ("select id from song where name=? and album_id=?"); ps1.setString(1, name.getText()); ps1.setString(2, albumID.get(albums.getSelectedItem().toString())); //step4 execute query ResultSet rs1=ps1.executeQuery(); String id = ""; while(rs1.next()) { id = rs1.getString(1); } ps1.close(); for(Object a:artists.getSelectedValuesList()) { ps = con.prepareCall ("{call addsongartist(?, ?)}"); ps.setString(1, id); ps.setString(2, artistID.get(a.toString())); ps.executeUpdate(); ps.close(); } con.close(); } catch (Exception e) {e.printStackTrace();} this.updateTable(); JOptionPane.showMessageDialog(this, "Success!\n"); } } catch (Exception e) { JOptionPane.showMessageDialog(this, "Error!\n"+e.getMessage()); } }
NONSATD
true
Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); //step3 create the statement object Statement stmt=con.createStatement(); //step4 execute query
catch(Exception e) { } try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } //step2 create the connection object Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); //step3 create the statement object Statement stmt=con.createStatement(); //step4 execute query ResultSet rs=stmt.executeQuery("select * from album"); ArrayList<String> albumList = new ArrayList<String>(); HashMap<String, String> albumID = new HashMap<>(); while(rs.next()) { albumList.add((rs.getString(2))); albumID.put(rs.getString(2), rs.getString(1)); } //step4 execute query
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed try { // TODO add your handling code here: try { clip.stop(); } catch(Exception e) { } try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } //step2 create the connection object Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); //step3 create the statement object Statement stmt=con.createStatement(); //step4 execute query ResultSet rs=stmt.executeQuery("select * from album"); ArrayList<String> albumList = new ArrayList<String>(); HashMap<String, String> albumID = new HashMap<>(); while(rs.next()) { albumList.add((rs.getString(2))); albumID.put(rs.getString(2), rs.getString(1)); } //step4 execute query rs=stmt.executeQuery("select * from artist"); ArrayList<String> artistList = new ArrayList<String>(); HashMap<String, String> artistID = new HashMap<>(); while(rs.next()) { artistList.add((rs.getString(2))); artistID.put(rs.getString(2), rs.getString(1)); } //step5 close the connection object con.close(); // TODO add your handling code here:
26,189
4
//step4 execute query
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed try { // TODO add your handling code here: try { clip.stop(); } catch(Exception e) { } try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } //step2 create the connection object Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); //step3 create the statement object Statement stmt=con.createStatement(); //step4 execute query ResultSet rs=stmt.executeQuery("select * from album"); ArrayList<String> albumList = new ArrayList<String>(); HashMap<String, String> albumID = new HashMap<>(); while(rs.next()) { albumList.add((rs.getString(2))); albumID.put(rs.getString(2), rs.getString(1)); } //step4 execute query rs=stmt.executeQuery("select * from artist"); ArrayList<String> artistList = new ArrayList<String>(); HashMap<String, String> artistID = new HashMap<>(); while(rs.next()) { artistList.add((rs.getString(2))); artistID.put(rs.getString(2), rs.getString(1)); } //step5 close the connection object con.close(); // TODO add your handling code here: // JTextField id = new JTextField(); JTextField name = new JTextField(); JTextField genre = new JTextField(); JTextField song_num = new JTextField(); JComboBox<String> albums = new JComboBox<String>(albumList.toArray(new String[0])); JList artists = new JList(artistList.toArray(new String[0])); artists.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); int[] select = {19, 20, 22}; Object[] input = { // "Id : ", id, "Name : ", name, "Genre :", genre, "Artist :", artists, "Song Number in Album :", song_num, "Album :", albums, }; int option = JOptionPane.showConfirmDialog(this, input, "Enter Song details", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { JFileChooser jfc = new JFileChooser(); int returnValue = jfc.showOpenDialog(null); // int returnValue = jfc.showSaveDialog(null); String filePath = null; if (returnValue == JFileChooser.APPROVE_OPTION) { File selectedFile = jfc.getSelectedFile(); System.out.println(selectedFile.getAbsolutePath()); filePath = selectedFile.getAbsolutePath(); } try{ File f=new File(filePath); Class.forName("oracle.jdbc.driver.OracleDriver"); con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); PreparedStatement ps = con.prepareStatement ("insert into song values(?, ?, ?, ?, ?, ?, ?)"); ps.setString(1, null); ps.setString(2, name.getText()); ps.setString(3, albumID.get(albums.getSelectedItem().toString())); ps.setString(4, genre.getText()); ps.setInt(5, 0); ps.setInt(6, Integer.parseInt(song_num.getText())); System.out.println(""+f.length()); ps.setBytes(7, readFile(filePath)); ps.executeUpdate(); ps.close(); PreparedStatement ps1 = con.prepareStatement ("select id from song where name=? and album_id=?"); ps1.setString(1, name.getText()); ps1.setString(2, albumID.get(albums.getSelectedItem().toString())); //step4 execute query ResultSet rs1=ps1.executeQuery(); String id = ""; while(rs1.next()) { id = rs1.getString(1); } ps1.close(); for(Object a:artists.getSelectedValuesList()) { ps = con.prepareCall ("{call addsongartist(?, ?)}"); ps.setString(1, id); ps.setString(2, artistID.get(a.toString())); ps.executeUpdate(); ps.close(); } con.close(); } catch (Exception e) {e.printStackTrace();} this.updateTable(); JOptionPane.showMessageDialog(this, "Success!\n"); } } catch (Exception e) { JOptionPane.showMessageDialog(this, "Error!\n"+e.getMessage()); } }
NONSATD
true
//step3 create the statement object Statement stmt=con.createStatement(); //step4 execute query ResultSet rs=stmt.executeQuery("select * from album"); ArrayList<String> albumList = new ArrayList<String>();
try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } //step2 create the connection object Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); //step3 create the statement object Statement stmt=con.createStatement(); //step4 execute query ResultSet rs=stmt.executeQuery("select * from album"); ArrayList<String> albumList = new ArrayList<String>(); HashMap<String, String> albumID = new HashMap<>(); while(rs.next()) { albumList.add((rs.getString(2))); albumID.put(rs.getString(2), rs.getString(1)); } //step4 execute query rs=stmt.executeQuery("select * from artist"); ArrayList<String> artistList = new ArrayList<String>();
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed try { // TODO add your handling code here: try { clip.stop(); } catch(Exception e) { } try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } //step2 create the connection object Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); //step3 create the statement object Statement stmt=con.createStatement(); //step4 execute query ResultSet rs=stmt.executeQuery("select * from album"); ArrayList<String> albumList = new ArrayList<String>(); HashMap<String, String> albumID = new HashMap<>(); while(rs.next()) { albumList.add((rs.getString(2))); albumID.put(rs.getString(2), rs.getString(1)); } //step4 execute query rs=stmt.executeQuery("select * from artist"); ArrayList<String> artistList = new ArrayList<String>(); HashMap<String, String> artistID = new HashMap<>(); while(rs.next()) { artistList.add((rs.getString(2))); artistID.put(rs.getString(2), rs.getString(1)); } //step5 close the connection object con.close(); // TODO add your handling code here: // JTextField id = new JTextField(); JTextField name = new JTextField();
26,189
5
//step4 execute query
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed try { // TODO add your handling code here: try { clip.stop(); } catch(Exception e) { } try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } //step2 create the connection object Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); //step3 create the statement object Statement stmt=con.createStatement(); //step4 execute query ResultSet rs=stmt.executeQuery("select * from album"); ArrayList<String> albumList = new ArrayList<String>(); HashMap<String, String> albumID = new HashMap<>(); while(rs.next()) { albumList.add((rs.getString(2))); albumID.put(rs.getString(2), rs.getString(1)); } //step4 execute query rs=stmt.executeQuery("select * from artist"); ArrayList<String> artistList = new ArrayList<String>(); HashMap<String, String> artistID = new HashMap<>(); while(rs.next()) { artistList.add((rs.getString(2))); artistID.put(rs.getString(2), rs.getString(1)); } //step5 close the connection object con.close(); // TODO add your handling code here: // JTextField id = new JTextField(); JTextField name = new JTextField(); JTextField genre = new JTextField(); JTextField song_num = new JTextField(); JComboBox<String> albums = new JComboBox<String>(albumList.toArray(new String[0])); JList artists = new JList(artistList.toArray(new String[0])); artists.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); int[] select = {19, 20, 22}; Object[] input = { // "Id : ", id, "Name : ", name, "Genre :", genre, "Artist :", artists, "Song Number in Album :", song_num, "Album :", albums, }; int option = JOptionPane.showConfirmDialog(this, input, "Enter Song details", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { JFileChooser jfc = new JFileChooser(); int returnValue = jfc.showOpenDialog(null); // int returnValue = jfc.showSaveDialog(null); String filePath = null; if (returnValue == JFileChooser.APPROVE_OPTION) { File selectedFile = jfc.getSelectedFile(); System.out.println(selectedFile.getAbsolutePath()); filePath = selectedFile.getAbsolutePath(); } try{ File f=new File(filePath); Class.forName("oracle.jdbc.driver.OracleDriver"); con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); PreparedStatement ps = con.prepareStatement ("insert into song values(?, ?, ?, ?, ?, ?, ?)"); ps.setString(1, null); ps.setString(2, name.getText()); ps.setString(3, albumID.get(albums.getSelectedItem().toString())); ps.setString(4, genre.getText()); ps.setInt(5, 0); ps.setInt(6, Integer.parseInt(song_num.getText())); System.out.println(""+f.length()); ps.setBytes(7, readFile(filePath)); ps.executeUpdate(); ps.close(); PreparedStatement ps1 = con.prepareStatement ("select id from song where name=? and album_id=?"); ps1.setString(1, name.getText()); ps1.setString(2, albumID.get(albums.getSelectedItem().toString())); //step4 execute query ResultSet rs1=ps1.executeQuery(); String id = ""; while(rs1.next()) { id = rs1.getString(1); } ps1.close(); for(Object a:artists.getSelectedValuesList()) { ps = con.prepareCall ("{call addsongartist(?, ?)}"); ps.setString(1, id); ps.setString(2, artistID.get(a.toString())); ps.executeUpdate(); ps.close(); } con.close(); } catch (Exception e) {e.printStackTrace();} this.updateTable(); JOptionPane.showMessageDialog(this, "Success!\n"); } } catch (Exception e) { JOptionPane.showMessageDialog(this, "Error!\n"+e.getMessage()); } }
NONSATD
true
//step3 create the statement object Statement stmt=con.createStatement(); //step4 execute query ResultSet rs=stmt.executeQuery("select * from album"); ArrayList<String> albumList = new ArrayList<String>();
try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } //step2 create the connection object Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); //step3 create the statement object Statement stmt=con.createStatement(); //step4 execute query ResultSet rs=stmt.executeQuery("select * from album"); ArrayList<String> albumList = new ArrayList<String>(); HashMap<String, String> albumID = new HashMap<>(); while(rs.next()) { albumList.add((rs.getString(2))); albumID.put(rs.getString(2), rs.getString(1)); } //step4 execute query rs=stmt.executeQuery("select * from artist"); ArrayList<String> artistList = new ArrayList<String>();
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed try { // TODO add your handling code here: try { clip.stop(); } catch(Exception e) { } try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } //step2 create the connection object Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); //step3 create the statement object Statement stmt=con.createStatement(); //step4 execute query ResultSet rs=stmt.executeQuery("select * from album"); ArrayList<String> albumList = new ArrayList<String>(); HashMap<String, String> albumID = new HashMap<>(); while(rs.next()) { albumList.add((rs.getString(2))); albumID.put(rs.getString(2), rs.getString(1)); } //step4 execute query rs=stmt.executeQuery("select * from artist"); ArrayList<String> artistList = new ArrayList<String>(); HashMap<String, String> artistID = new HashMap<>(); while(rs.next()) { artistList.add((rs.getString(2))); artistID.put(rs.getString(2), rs.getString(1)); } //step5 close the connection object con.close(); // TODO add your handling code here: // JTextField id = new JTextField(); JTextField name = new JTextField();
26,189
6
//step5 close the connection object
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed try { // TODO add your handling code here: try { clip.stop(); } catch(Exception e) { } try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } //step2 create the connection object Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); //step3 create the statement object Statement stmt=con.createStatement(); //step4 execute query ResultSet rs=stmt.executeQuery("select * from album"); ArrayList<String> albumList = new ArrayList<String>(); HashMap<String, String> albumID = new HashMap<>(); while(rs.next()) { albumList.add((rs.getString(2))); albumID.put(rs.getString(2), rs.getString(1)); } //step4 execute query rs=stmt.executeQuery("select * from artist"); ArrayList<String> artistList = new ArrayList<String>(); HashMap<String, String> artistID = new HashMap<>(); while(rs.next()) { artistList.add((rs.getString(2))); artistID.put(rs.getString(2), rs.getString(1)); } //step5 close the connection object con.close(); // TODO add your handling code here: // JTextField id = new JTextField(); JTextField name = new JTextField(); JTextField genre = new JTextField(); JTextField song_num = new JTextField(); JComboBox<String> albums = new JComboBox<String>(albumList.toArray(new String[0])); JList artists = new JList(artistList.toArray(new String[0])); artists.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); int[] select = {19, 20, 22}; Object[] input = { // "Id : ", id, "Name : ", name, "Genre :", genre, "Artist :", artists, "Song Number in Album :", song_num, "Album :", albums, }; int option = JOptionPane.showConfirmDialog(this, input, "Enter Song details", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { JFileChooser jfc = new JFileChooser(); int returnValue = jfc.showOpenDialog(null); // int returnValue = jfc.showSaveDialog(null); String filePath = null; if (returnValue == JFileChooser.APPROVE_OPTION) { File selectedFile = jfc.getSelectedFile(); System.out.println(selectedFile.getAbsolutePath()); filePath = selectedFile.getAbsolutePath(); } try{ File f=new File(filePath); Class.forName("oracle.jdbc.driver.OracleDriver"); con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); PreparedStatement ps = con.prepareStatement ("insert into song values(?, ?, ?, ?, ?, ?, ?)"); ps.setString(1, null); ps.setString(2, name.getText()); ps.setString(3, albumID.get(albums.getSelectedItem().toString())); ps.setString(4, genre.getText()); ps.setInt(5, 0); ps.setInt(6, Integer.parseInt(song_num.getText())); System.out.println(""+f.length()); ps.setBytes(7, readFile(filePath)); ps.executeUpdate(); ps.close(); PreparedStatement ps1 = con.prepareStatement ("select id from song where name=? and album_id=?"); ps1.setString(1, name.getText()); ps1.setString(2, albumID.get(albums.getSelectedItem().toString())); //step4 execute query ResultSet rs1=ps1.executeQuery(); String id = ""; while(rs1.next()) { id = rs1.getString(1); } ps1.close(); for(Object a:artists.getSelectedValuesList()) { ps = con.prepareCall ("{call addsongartist(?, ?)}"); ps.setString(1, id); ps.setString(2, artistID.get(a.toString())); ps.executeUpdate(); ps.close(); } con.close(); } catch (Exception e) {e.printStackTrace();} this.updateTable(); JOptionPane.showMessageDialog(this, "Success!\n"); } } catch (Exception e) { JOptionPane.showMessageDialog(this, "Error!\n"+e.getMessage()); } }
NONSATD
true
artistID.put(rs.getString(2), rs.getString(1)); } //step5 close the connection object con.close(); // TODO add your handling code here:
albumID.put(rs.getString(2), rs.getString(1)); } //step4 execute query rs=stmt.executeQuery("select * from artist"); ArrayList<String> artistList = new ArrayList<String>(); HashMap<String, String> artistID = new HashMap<>(); while(rs.next()) { artistList.add((rs.getString(2))); artistID.put(rs.getString(2), rs.getString(1)); } //step5 close the connection object con.close(); // TODO add your handling code here: // JTextField id = new JTextField(); JTextField name = new JTextField(); JTextField genre = new JTextField(); JTextField song_num = new JTextField(); JComboBox<String> albums = new JComboBox<String>(albumList.toArray(new String[0])); JList artists = new JList(artistList.toArray(new String[0])); artists.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); //step3 create the statement object Statement stmt=con.createStatement(); //step4 execute query ResultSet rs=stmt.executeQuery("select * from album"); ArrayList<String> albumList = new ArrayList<String>(); HashMap<String, String> albumID = new HashMap<>(); while(rs.next()) { albumList.add((rs.getString(2))); albumID.put(rs.getString(2), rs.getString(1)); } //step4 execute query rs=stmt.executeQuery("select * from artist"); ArrayList<String> artistList = new ArrayList<String>(); HashMap<String, String> artistID = new HashMap<>(); while(rs.next()) { artistList.add((rs.getString(2))); artistID.put(rs.getString(2), rs.getString(1)); } //step5 close the connection object con.close(); // TODO add your handling code here: // JTextField id = new JTextField(); JTextField name = new JTextField(); JTextField genre = new JTextField(); JTextField song_num = new JTextField(); JComboBox<String> albums = new JComboBox<String>(albumList.toArray(new String[0])); JList artists = new JList(artistList.toArray(new String[0])); artists.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); int[] select = {19, 20, 22}; Object[] input = { // "Id : ", id, "Name : ", name, "Genre :", genre, "Artist :", artists, "Song Number in Album :", song_num, "Album :", albums, }; int option = JOptionPane.showConfirmDialog(this, input, "Enter Song details", JOptionPane.OK_CANCEL_OPTION);
26,189
7
// TODO add your handling code here: // JTextField id = new JTextField();
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed try { // TODO add your handling code here: try { clip.stop(); } catch(Exception e) { } try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } //step2 create the connection object Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); //step3 create the statement object Statement stmt=con.createStatement(); //step4 execute query ResultSet rs=stmt.executeQuery("select * from album"); ArrayList<String> albumList = new ArrayList<String>(); HashMap<String, String> albumID = new HashMap<>(); while(rs.next()) { albumList.add((rs.getString(2))); albumID.put(rs.getString(2), rs.getString(1)); } //step4 execute query rs=stmt.executeQuery("select * from artist"); ArrayList<String> artistList = new ArrayList<String>(); HashMap<String, String> artistID = new HashMap<>(); while(rs.next()) { artistList.add((rs.getString(2))); artistID.put(rs.getString(2), rs.getString(1)); } //step5 close the connection object con.close(); // TODO add your handling code here: // JTextField id = new JTextField(); JTextField name = new JTextField(); JTextField genre = new JTextField(); JTextField song_num = new JTextField(); JComboBox<String> albums = new JComboBox<String>(albumList.toArray(new String[0])); JList artists = new JList(artistList.toArray(new String[0])); artists.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); int[] select = {19, 20, 22}; Object[] input = { // "Id : ", id, "Name : ", name, "Genre :", genre, "Artist :", artists, "Song Number in Album :", song_num, "Album :", albums, }; int option = JOptionPane.showConfirmDialog(this, input, "Enter Song details", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { JFileChooser jfc = new JFileChooser(); int returnValue = jfc.showOpenDialog(null); // int returnValue = jfc.showSaveDialog(null); String filePath = null; if (returnValue == JFileChooser.APPROVE_OPTION) { File selectedFile = jfc.getSelectedFile(); System.out.println(selectedFile.getAbsolutePath()); filePath = selectedFile.getAbsolutePath(); } try{ File f=new File(filePath); Class.forName("oracle.jdbc.driver.OracleDriver"); con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); PreparedStatement ps = con.prepareStatement ("insert into song values(?, ?, ?, ?, ?, ?, ?)"); ps.setString(1, null); ps.setString(2, name.getText()); ps.setString(3, albumID.get(albums.getSelectedItem().toString())); ps.setString(4, genre.getText()); ps.setInt(5, 0); ps.setInt(6, Integer.parseInt(song_num.getText())); System.out.println(""+f.length()); ps.setBytes(7, readFile(filePath)); ps.executeUpdate(); ps.close(); PreparedStatement ps1 = con.prepareStatement ("select id from song where name=? and album_id=?"); ps1.setString(1, name.getText()); ps1.setString(2, albumID.get(albums.getSelectedItem().toString())); //step4 execute query ResultSet rs1=ps1.executeQuery(); String id = ""; while(rs1.next()) { id = rs1.getString(1); } ps1.close(); for(Object a:artists.getSelectedValuesList()) { ps = con.prepareCall ("{call addsongartist(?, ?)}"); ps.setString(1, id); ps.setString(2, artistID.get(a.toString())); ps.executeUpdate(); ps.close(); } con.close(); } catch (Exception e) {e.printStackTrace();} this.updateTable(); JOptionPane.showMessageDialog(this, "Success!\n"); } } catch (Exception e) { JOptionPane.showMessageDialog(this, "Error!\n"+e.getMessage()); } }
IMPLEMENTATION
true
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed try { // TODO add your handling code here: try { clip.stop(); }
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed try { // TODO add your handling code here: try { clip.stop(); } catch(Exception e) { } try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } //step2 create the connection object
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed try { // TODO add your handling code here: try { clip.stop(); } catch(Exception e) { } try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } //step2 create the connection object Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); //step3 create the statement object Statement stmt=con.createStatement(); //step4 execute query ResultSet rs=stmt.executeQuery("select * from album"); ArrayList<String> albumList = new ArrayList<String>(); HashMap<String, String> albumID = new HashMap<>(); while(rs.next()) { albumList.add((rs.getString(2)));
26,189
8
// "Id : ", id,
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed try { // TODO add your handling code here: try { clip.stop(); } catch(Exception e) { } try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } //step2 create the connection object Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); //step3 create the statement object Statement stmt=con.createStatement(); //step4 execute query ResultSet rs=stmt.executeQuery("select * from album"); ArrayList<String> albumList = new ArrayList<String>(); HashMap<String, String> albumID = new HashMap<>(); while(rs.next()) { albumList.add((rs.getString(2))); albumID.put(rs.getString(2), rs.getString(1)); } //step4 execute query rs=stmt.executeQuery("select * from artist"); ArrayList<String> artistList = new ArrayList<String>(); HashMap<String, String> artistID = new HashMap<>(); while(rs.next()) { artistList.add((rs.getString(2))); artistID.put(rs.getString(2), rs.getString(1)); } //step5 close the connection object con.close(); // TODO add your handling code here: // JTextField id = new JTextField(); JTextField name = new JTextField(); JTextField genre = new JTextField(); JTextField song_num = new JTextField(); JComboBox<String> albums = new JComboBox<String>(albumList.toArray(new String[0])); JList artists = new JList(artistList.toArray(new String[0])); artists.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); int[] select = {19, 20, 22}; Object[] input = { // "Id : ", id, "Name : ", name, "Genre :", genre, "Artist :", artists, "Song Number in Album :", song_num, "Album :", albums, }; int option = JOptionPane.showConfirmDialog(this, input, "Enter Song details", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { JFileChooser jfc = new JFileChooser(); int returnValue = jfc.showOpenDialog(null); // int returnValue = jfc.showSaveDialog(null); String filePath = null; if (returnValue == JFileChooser.APPROVE_OPTION) { File selectedFile = jfc.getSelectedFile(); System.out.println(selectedFile.getAbsolutePath()); filePath = selectedFile.getAbsolutePath(); } try{ File f=new File(filePath); Class.forName("oracle.jdbc.driver.OracleDriver"); con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); PreparedStatement ps = con.prepareStatement ("insert into song values(?, ?, ?, ?, ?, ?, ?)"); ps.setString(1, null); ps.setString(2, name.getText()); ps.setString(3, albumID.get(albums.getSelectedItem().toString())); ps.setString(4, genre.getText()); ps.setInt(5, 0); ps.setInt(6, Integer.parseInt(song_num.getText())); System.out.println(""+f.length()); ps.setBytes(7, readFile(filePath)); ps.executeUpdate(); ps.close(); PreparedStatement ps1 = con.prepareStatement ("select id from song where name=? and album_id=?"); ps1.setString(1, name.getText()); ps1.setString(2, albumID.get(albums.getSelectedItem().toString())); //step4 execute query ResultSet rs1=ps1.executeQuery(); String id = ""; while(rs1.next()) { id = rs1.getString(1); } ps1.close(); for(Object a:artists.getSelectedValuesList()) { ps = con.prepareCall ("{call addsongartist(?, ?)}"); ps.setString(1, id); ps.setString(2, artistID.get(a.toString())); ps.executeUpdate(); ps.close(); } con.close(); } catch (Exception e) {e.printStackTrace();} this.updateTable(); JOptionPane.showMessageDialog(this, "Success!\n"); } } catch (Exception e) { JOptionPane.showMessageDialog(this, "Error!\n"+e.getMessage()); } }
NONSATD
true
int[] select = {19, 20, 22}; Object[] input = { // "Id : ", id, "Name : ", name, "Genre :", genre,
// JTextField id = new JTextField(); JTextField name = new JTextField(); JTextField genre = new JTextField(); JTextField song_num = new JTextField(); JComboBox<String> albums = new JComboBox<String>(albumList.toArray(new String[0])); JList artists = new JList(artistList.toArray(new String[0])); artists.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); int[] select = {19, 20, 22}; Object[] input = { // "Id : ", id, "Name : ", name, "Genre :", genre, "Artist :", artists, "Song Number in Album :", song_num, "Album :", albums, }; int option = JOptionPane.showConfirmDialog(this, input, "Enter Song details", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { JFileChooser jfc = new JFileChooser(); int returnValue = jfc.showOpenDialog(null);
rs=stmt.executeQuery("select * from artist"); ArrayList<String> artistList = new ArrayList<String>(); HashMap<String, String> artistID = new HashMap<>(); while(rs.next()) { artistList.add((rs.getString(2))); artistID.put(rs.getString(2), rs.getString(1)); } //step5 close the connection object con.close(); // TODO add your handling code here: // JTextField id = new JTextField(); JTextField name = new JTextField(); JTextField genre = new JTextField(); JTextField song_num = new JTextField(); JComboBox<String> albums = new JComboBox<String>(albumList.toArray(new String[0])); JList artists = new JList(artistList.toArray(new String[0])); artists.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); int[] select = {19, 20, 22}; Object[] input = { // "Id : ", id, "Name : ", name, "Genre :", genre, "Artist :", artists, "Song Number in Album :", song_num, "Album :", albums, }; int option = JOptionPane.showConfirmDialog(this, input, "Enter Song details", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { JFileChooser jfc = new JFileChooser(); int returnValue = jfc.showOpenDialog(null); // int returnValue = jfc.showSaveDialog(null); String filePath = null; if (returnValue == JFileChooser.APPROVE_OPTION) { File selectedFile = jfc.getSelectedFile(); System.out.println(selectedFile.getAbsolutePath()); filePath = selectedFile.getAbsolutePath(); } try{ File f=new File(filePath); Class.forName("oracle.jdbc.driver.OracleDriver");
26,189
9
// int returnValue = jfc.showSaveDialog(null);
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed try { // TODO add your handling code here: try { clip.stop(); } catch(Exception e) { } try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } //step2 create the connection object Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); //step3 create the statement object Statement stmt=con.createStatement(); //step4 execute query ResultSet rs=stmt.executeQuery("select * from album"); ArrayList<String> albumList = new ArrayList<String>(); HashMap<String, String> albumID = new HashMap<>(); while(rs.next()) { albumList.add((rs.getString(2))); albumID.put(rs.getString(2), rs.getString(1)); } //step4 execute query rs=stmt.executeQuery("select * from artist"); ArrayList<String> artistList = new ArrayList<String>(); HashMap<String, String> artistID = new HashMap<>(); while(rs.next()) { artistList.add((rs.getString(2))); artistID.put(rs.getString(2), rs.getString(1)); } //step5 close the connection object con.close(); // TODO add your handling code here: // JTextField id = new JTextField(); JTextField name = new JTextField(); JTextField genre = new JTextField(); JTextField song_num = new JTextField(); JComboBox<String> albums = new JComboBox<String>(albumList.toArray(new String[0])); JList artists = new JList(artistList.toArray(new String[0])); artists.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); int[] select = {19, 20, 22}; Object[] input = { // "Id : ", id, "Name : ", name, "Genre :", genre, "Artist :", artists, "Song Number in Album :", song_num, "Album :", albums, }; int option = JOptionPane.showConfirmDialog(this, input, "Enter Song details", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { JFileChooser jfc = new JFileChooser(); int returnValue = jfc.showOpenDialog(null); // int returnValue = jfc.showSaveDialog(null); String filePath = null; if (returnValue == JFileChooser.APPROVE_OPTION) { File selectedFile = jfc.getSelectedFile(); System.out.println(selectedFile.getAbsolutePath()); filePath = selectedFile.getAbsolutePath(); } try{ File f=new File(filePath); Class.forName("oracle.jdbc.driver.OracleDriver"); con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); PreparedStatement ps = con.prepareStatement ("insert into song values(?, ?, ?, ?, ?, ?, ?)"); ps.setString(1, null); ps.setString(2, name.getText()); ps.setString(3, albumID.get(albums.getSelectedItem().toString())); ps.setString(4, genre.getText()); ps.setInt(5, 0); ps.setInt(6, Integer.parseInt(song_num.getText())); System.out.println(""+f.length()); ps.setBytes(7, readFile(filePath)); ps.executeUpdate(); ps.close(); PreparedStatement ps1 = con.prepareStatement ("select id from song where name=? and album_id=?"); ps1.setString(1, name.getText()); ps1.setString(2, albumID.get(albums.getSelectedItem().toString())); //step4 execute query ResultSet rs1=ps1.executeQuery(); String id = ""; while(rs1.next()) { id = rs1.getString(1); } ps1.close(); for(Object a:artists.getSelectedValuesList()) { ps = con.prepareCall ("{call addsongartist(?, ?)}"); ps.setString(1, id); ps.setString(2, artistID.get(a.toString())); ps.executeUpdate(); ps.close(); } con.close(); } catch (Exception e) {e.printStackTrace();} this.updateTable(); JOptionPane.showMessageDialog(this, "Success!\n"); } } catch (Exception e) { JOptionPane.showMessageDialog(this, "Error!\n"+e.getMessage()); } }
NONSATD
true
JFileChooser jfc = new JFileChooser(); int returnValue = jfc.showOpenDialog(null); // int returnValue = jfc.showSaveDialog(null); String filePath = null; if (returnValue == JFileChooser.APPROVE_OPTION) {
"Name : ", name, "Genre :", genre, "Artist :", artists, "Song Number in Album :", song_num, "Album :", albums, }; int option = JOptionPane.showConfirmDialog(this, input, "Enter Song details", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { JFileChooser jfc = new JFileChooser(); int returnValue = jfc.showOpenDialog(null); // int returnValue = jfc.showSaveDialog(null); String filePath = null; if (returnValue == JFileChooser.APPROVE_OPTION) { File selectedFile = jfc.getSelectedFile(); System.out.println(selectedFile.getAbsolutePath()); filePath = selectedFile.getAbsolutePath(); } try{ File f=new File(filePath); Class.forName("oracle.jdbc.driver.OracleDriver"); con = DriverManager.getConnection(
JTextField name = new JTextField(); JTextField genre = new JTextField(); JTextField song_num = new JTextField(); JComboBox<String> albums = new JComboBox<String>(albumList.toArray(new String[0])); JList artists = new JList(artistList.toArray(new String[0])); artists.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); int[] select = {19, 20, 22}; Object[] input = { // "Id : ", id, "Name : ", name, "Genre :", genre, "Artist :", artists, "Song Number in Album :", song_num, "Album :", albums, }; int option = JOptionPane.showConfirmDialog(this, input, "Enter Song details", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { JFileChooser jfc = new JFileChooser(); int returnValue = jfc.showOpenDialog(null); // int returnValue = jfc.showSaveDialog(null); String filePath = null; if (returnValue == JFileChooser.APPROVE_OPTION) { File selectedFile = jfc.getSelectedFile(); System.out.println(selectedFile.getAbsolutePath()); filePath = selectedFile.getAbsolutePath(); } try{ File f=new File(filePath); Class.forName("oracle.jdbc.driver.OracleDriver"); con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); PreparedStatement ps = con.prepareStatement ("insert into song values(?, ?, ?, ?, ?, ?, ?)"); ps.setString(1, null); ps.setString(2, name.getText()); ps.setString(3, albumID.get(albums.getSelectedItem().toString())); ps.setString(4, genre.getText()); ps.setInt(5, 0); ps.setInt(6, Integer.parseInt(song_num.getText())); System.out.println(""+f.length()); ps.setBytes(7, readFile(filePath));
26,189
10
//step4 execute query
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed try { // TODO add your handling code here: try { clip.stop(); } catch(Exception e) { } try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } //step2 create the connection object Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); //step3 create the statement object Statement stmt=con.createStatement(); //step4 execute query ResultSet rs=stmt.executeQuery("select * from album"); ArrayList<String> albumList = new ArrayList<String>(); HashMap<String, String> albumID = new HashMap<>(); while(rs.next()) { albumList.add((rs.getString(2))); albumID.put(rs.getString(2), rs.getString(1)); } //step4 execute query rs=stmt.executeQuery("select * from artist"); ArrayList<String> artistList = new ArrayList<String>(); HashMap<String, String> artistID = new HashMap<>(); while(rs.next()) { artistList.add((rs.getString(2))); artistID.put(rs.getString(2), rs.getString(1)); } //step5 close the connection object con.close(); // TODO add your handling code here: // JTextField id = new JTextField(); JTextField name = new JTextField(); JTextField genre = new JTextField(); JTextField song_num = new JTextField(); JComboBox<String> albums = new JComboBox<String>(albumList.toArray(new String[0])); JList artists = new JList(artistList.toArray(new String[0])); artists.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); int[] select = {19, 20, 22}; Object[] input = { // "Id : ", id, "Name : ", name, "Genre :", genre, "Artist :", artists, "Song Number in Album :", song_num, "Album :", albums, }; int option = JOptionPane.showConfirmDialog(this, input, "Enter Song details", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { JFileChooser jfc = new JFileChooser(); int returnValue = jfc.showOpenDialog(null); // int returnValue = jfc.showSaveDialog(null); String filePath = null; if (returnValue == JFileChooser.APPROVE_OPTION) { File selectedFile = jfc.getSelectedFile(); System.out.println(selectedFile.getAbsolutePath()); filePath = selectedFile.getAbsolutePath(); } try{ File f=new File(filePath); Class.forName("oracle.jdbc.driver.OracleDriver"); con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); PreparedStatement ps = con.prepareStatement ("insert into song values(?, ?, ?, ?, ?, ?, ?)"); ps.setString(1, null); ps.setString(2, name.getText()); ps.setString(3, albumID.get(albums.getSelectedItem().toString())); ps.setString(4, genre.getText()); ps.setInt(5, 0); ps.setInt(6, Integer.parseInt(song_num.getText())); System.out.println(""+f.length()); ps.setBytes(7, readFile(filePath)); ps.executeUpdate(); ps.close(); PreparedStatement ps1 = con.prepareStatement ("select id from song where name=? and album_id=?"); ps1.setString(1, name.getText()); ps1.setString(2, albumID.get(albums.getSelectedItem().toString())); //step4 execute query ResultSet rs1=ps1.executeQuery(); String id = ""; while(rs1.next()) { id = rs1.getString(1); } ps1.close(); for(Object a:artists.getSelectedValuesList()) { ps = con.prepareCall ("{call addsongartist(?, ?)}"); ps.setString(1, id); ps.setString(2, artistID.get(a.toString())); ps.executeUpdate(); ps.close(); } con.close(); } catch (Exception e) {e.printStackTrace();} this.updateTable(); JOptionPane.showMessageDialog(this, "Success!\n"); } } catch (Exception e) { JOptionPane.showMessageDialog(this, "Error!\n"+e.getMessage()); } }
NONSATD
true
//step3 create the statement object Statement stmt=con.createStatement(); //step4 execute query ResultSet rs=stmt.executeQuery("select * from album"); ArrayList<String> albumList = new ArrayList<String>();
try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } //step2 create the connection object Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); //step3 create the statement object Statement stmt=con.createStatement(); //step4 execute query ResultSet rs=stmt.executeQuery("select * from album"); ArrayList<String> albumList = new ArrayList<String>(); HashMap<String, String> albumID = new HashMap<>(); while(rs.next()) { albumList.add((rs.getString(2))); albumID.put(rs.getString(2), rs.getString(1)); } //step4 execute query rs=stmt.executeQuery("select * from artist"); ArrayList<String> artistList = new ArrayList<String>();
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed try { // TODO add your handling code here: try { clip.stop(); } catch(Exception e) { } try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } //step2 create the connection object Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); //step3 create the statement object Statement stmt=con.createStatement(); //step4 execute query ResultSet rs=stmt.executeQuery("select * from album"); ArrayList<String> albumList = new ArrayList<String>(); HashMap<String, String> albumID = new HashMap<>(); while(rs.next()) { albumList.add((rs.getString(2))); albumID.put(rs.getString(2), rs.getString(1)); } //step4 execute query rs=stmt.executeQuery("select * from artist"); ArrayList<String> artistList = new ArrayList<String>(); HashMap<String, String> artistID = new HashMap<>(); while(rs.next()) { artistList.add((rs.getString(2))); artistID.put(rs.getString(2), rs.getString(1)); } //step5 close the connection object con.close(); // TODO add your handling code here: // JTextField id = new JTextField(); JTextField name = new JTextField();
26,190
0
//GEN-FIRST:event_addArtistActionPerformed
private void addArtistActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addArtistActionPerformed // TODO add your handling code here: try { // TODO add your handling code here: searchText.setText(""); try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } // TODO add your handling code here: // JTextField id = new JTextField(); JTextField name = new JTextField(); JTextField about = new JTextField(); Object[] input = { // "Id : ", id, "Name : ", name, "About : ", about, }; int option = JOptionPane.showConfirmDialog(this, input, "Enter Artist details", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { try{ Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); CallableStatement ps = con.prepareCall ("{call addartist(?, ?, ?)}"); ps.setString(1,null); ps.setString(2, name.getText()); ps.setString(3, about.getText()); ps.executeUpdate(); ps.close(); con.close(); } catch (Exception e) {e.printStackTrace();} JOptionPane.showMessageDialog(this, "Success!\n"); } } catch (Exception e) { JOptionPane.showMessageDialog(this, "Error!\n"+e.getMessage()); } }
NONSATD
true
private void addArtistActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addArtistActionPerformed // TODO add your handling code here: try {
private void addArtistActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addArtistActionPerformed // TODO add your handling code here: try { // TODO add your handling code here: searchText.setText(""); try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } // TODO add your handling code here:
private void addArtistActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addArtistActionPerformed // TODO add your handling code here: try { // TODO add your handling code here: searchText.setText(""); try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } // TODO add your handling code here: // JTextField id = new JTextField(); JTextField name = new JTextField(); JTextField about = new JTextField(); Object[] input = { // "Id : ", id, "Name : ", name, "About : ", about, }; int option = JOptionPane.showConfirmDialog(this, input, "Enter Artist details", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) {
26,190
1
// TODO add your handling code here:
private void addArtistActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addArtistActionPerformed // TODO add your handling code here: try { // TODO add your handling code here: searchText.setText(""); try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } // TODO add your handling code here: // JTextField id = new JTextField(); JTextField name = new JTextField(); JTextField about = new JTextField(); Object[] input = { // "Id : ", id, "Name : ", name, "About : ", about, }; int option = JOptionPane.showConfirmDialog(this, input, "Enter Artist details", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { try{ Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); CallableStatement ps = con.prepareCall ("{call addartist(?, ?, ?)}"); ps.setString(1,null); ps.setString(2, name.getText()); ps.setString(3, about.getText()); ps.executeUpdate(); ps.close(); con.close(); } catch (Exception e) {e.printStackTrace();} JOptionPane.showMessageDialog(this, "Success!\n"); } } catch (Exception e) { JOptionPane.showMessageDialog(this, "Error!\n"+e.getMessage()); } }
IMPLEMENTATION
true
private void addArtistActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addArtistActionPerformed // TODO add your handling code here: try { // TODO add your handling code here:
private void addArtistActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addArtistActionPerformed // TODO add your handling code here: try { // TODO add your handling code here: searchText.setText(""); try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } // TODO add your handling code here: // JTextField id = new JTextField();
private void addArtistActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addArtistActionPerformed // TODO add your handling code here: try { // TODO add your handling code here: searchText.setText(""); try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } // TODO add your handling code here: // JTextField id = new JTextField(); JTextField name = new JTextField(); JTextField about = new JTextField(); Object[] input = { // "Id : ", id, "Name : ", name, "About : ", about, }; int option = JOptionPane.showConfirmDialog(this, input, "Enter Artist details", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { try{
26,190
2
// TODO add your handling code here:
private void addArtistActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addArtistActionPerformed // TODO add your handling code here: try { // TODO add your handling code here: searchText.setText(""); try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } // TODO add your handling code here: // JTextField id = new JTextField(); JTextField name = new JTextField(); JTextField about = new JTextField(); Object[] input = { // "Id : ", id, "Name : ", name, "About : ", about, }; int option = JOptionPane.showConfirmDialog(this, input, "Enter Artist details", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { try{ Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); CallableStatement ps = con.prepareCall ("{call addartist(?, ?, ?)}"); ps.setString(1,null); ps.setString(2, name.getText()); ps.setString(3, about.getText()); ps.executeUpdate(); ps.close(); con.close(); } catch (Exception e) {e.printStackTrace();} JOptionPane.showMessageDialog(this, "Success!\n"); } } catch (Exception e) { JOptionPane.showMessageDialog(this, "Error!\n"+e.getMessage()); } }
IMPLEMENTATION
true
private void addArtistActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addArtistActionPerformed // TODO add your handling code here: try { // TODO add your handling code here:
private void addArtistActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addArtistActionPerformed // TODO add your handling code here: try { // TODO add your handling code here: searchText.setText(""); try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } // TODO add your handling code here: // JTextField id = new JTextField();
private void addArtistActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addArtistActionPerformed // TODO add your handling code here: try { // TODO add your handling code here: searchText.setText(""); try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } // TODO add your handling code here: // JTextField id = new JTextField(); JTextField name = new JTextField(); JTextField about = new JTextField(); Object[] input = { // "Id : ", id, "Name : ", name, "About : ", about, }; int option = JOptionPane.showConfirmDialog(this, input, "Enter Artist details", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { try{
26,190
3
// TODO add your handling code here: // JTextField id = new JTextField();
private void addArtistActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addArtistActionPerformed // TODO add your handling code here: try { // TODO add your handling code here: searchText.setText(""); try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } // TODO add your handling code here: // JTextField id = new JTextField(); JTextField name = new JTextField(); JTextField about = new JTextField(); Object[] input = { // "Id : ", id, "Name : ", name, "About : ", about, }; int option = JOptionPane.showConfirmDialog(this, input, "Enter Artist details", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { try{ Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); CallableStatement ps = con.prepareCall ("{call addartist(?, ?, ?)}"); ps.setString(1,null); ps.setString(2, name.getText()); ps.setString(3, about.getText()); ps.executeUpdate(); ps.close(); con.close(); } catch (Exception e) {e.printStackTrace();} JOptionPane.showMessageDialog(this, "Success!\n"); } } catch (Exception e) { JOptionPane.showMessageDialog(this, "Error!\n"+e.getMessage()); } }
IMPLEMENTATION
true
private void addArtistActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addArtistActionPerformed // TODO add your handling code here: try { // TODO add your handling code here: searchText.setText("");
private void addArtistActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addArtistActionPerformed // TODO add your handling code here: try { // TODO add your handling code here: searchText.setText(""); try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } // TODO add your handling code here: // JTextField id = new JTextField(); JTextField name = new JTextField();
private void addArtistActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addArtistActionPerformed // TODO add your handling code here: try { // TODO add your handling code here: searchText.setText(""); try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex); } // TODO add your handling code here: // JTextField id = new JTextField(); JTextField name = new JTextField(); JTextField about = new JTextField(); Object[] input = { // "Id : ", id, "Name : ", name, "About : ", about, }; int option = JOptionPane.showConfirmDialog(this, input, "Enter Artist details", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { try{ Class.forName("oracle.jdbc.driver.OracleDriver");