repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
InfinityStudio/ExoticPower
src/main/java/infstudio/exoticpower/block/BlockMachine.java
// Path: src/main/java/infstudio/exoticpower/ExoticPower.java // @Mod(modid = "ExoticPower", name = "ExoticPower", version = "1.0.0") // public class ExoticPower { // // public static final NormalExoticPowerTab NEPTab = new NormalExoticPowerTab(); // public static final MageExoticPowerTab MEPTab = new MageExoticPowerTab(); // // @SidedProxy(clientSide = "infstudio.exoticpower.proxy.ClientProxy", // serverSide = "infstudio.exoticpower.proxy.CommonProxy") // public static CommonProxy proxy; // // @Instance("ExoticPower") // public static ExoticPower instance; // // @EventHandler // public void preInit(FMLPreInitializationEvent event) { // proxy.preInit(event); // } // // @EventHandler // public void init(FMLInitializationEvent event) { // proxy.init(event); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) { // proxy.postInit(event); // } // // }
import infstudio.exoticpower.ExoticPower; import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World;
package infstudio.exoticpower.block; public class BlockMachine extends BlockContainer { public int Guiid; public BlockMachine() { super(Material.rock);
// Path: src/main/java/infstudio/exoticpower/ExoticPower.java // @Mod(modid = "ExoticPower", name = "ExoticPower", version = "1.0.0") // public class ExoticPower { // // public static final NormalExoticPowerTab NEPTab = new NormalExoticPowerTab(); // public static final MageExoticPowerTab MEPTab = new MageExoticPowerTab(); // // @SidedProxy(clientSide = "infstudio.exoticpower.proxy.ClientProxy", // serverSide = "infstudio.exoticpower.proxy.CommonProxy") // public static CommonProxy proxy; // // @Instance("ExoticPower") // public static ExoticPower instance; // // @EventHandler // public void preInit(FMLPreInitializationEvent event) { // proxy.preInit(event); // } // // @EventHandler // public void init(FMLInitializationEvent event) { // proxy.init(event); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) { // proxy.postInit(event); // } // // } // Path: src/main/java/infstudio/exoticpower/block/BlockMachine.java import infstudio.exoticpower.ExoticPower; import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; package infstudio.exoticpower.block; public class BlockMachine extends BlockContainer { public int Guiid; public BlockMachine() { super(Material.rock);
this.setCreativeTab(ExoticPower.ept);
InfinityStudio/ExoticPower
src/main/java/cn/academy/energy/api/IFItemManager.java
// Path: src/main/java/cn/academy/energy/api/item/ImagEnergyItem.java // public interface ImagEnergyItem { // // double getMaxEnergy(); // // double getBandwidth(); // // // } // // Path: src/main/java/cn/academy/support/EnergyItemHelper.java // public interface EnergyItemManager { // // boolean isSupported(ItemStack stack); // // double getEnergy(ItemStack stack); // // void setEnergy(ItemStack stack, double energy); // // /** // * @return How much energy not transfered into stack(left) // */ // double charge(ItemStack stack, double amt, boolean ignoreBandwidth); // // /** // * @return How much energy pulled out of stack // */ // double pull(ItemStack stack, double amt, boolean ignoreBandwidth); // // } // // Path: src/main/java/cn/liutils/util/mc/StackUtils.java // public class StackUtils { // // public static void dropItems(World world, int x, int y, int z, IInventory inv) { // Random rand = new Random(); // // for (int i = 0; i < inv.getSizeInventory(); ++i) { // ItemStack stack = inv.getStackInSlot(i); // if (stack != null && stack.stackSize > 0) { // float rx = rand.nextFloat() * 0.8F + 0.1F; // float ry = rand.nextFloat() * 0.8F + 0.1F; // float rz = rand.nextFloat() * 0.8F + 0.1F; // // EntityItem entityItem = new EntityItem(world, x + rx, y + ry, z + rz, stack.copy()); // // if (stack.hasTagCompound()) { // entityItem.getEntityItem().setTagCompound((NBTTagCompound) stack.getTagCompound().copy()); // } // // float factor = 0.05F; // entityItem.motionX = rand.nextGaussian() * factor; // entityItem.motionY = rand.nextGaussian() * factor + 0.2F; // entityItem.motionZ = rand.nextGaussian() * factor; // world.spawnEntityInWorld(entityItem); // stack.stackSize = 0; // } // } // } // // /** // * Return whether two stack's item instance and data are equal. // */ // public static boolean isStackDataEqual(ItemStack s1, ItemStack s2) { // if (s1.getItem() != s1.getItem()) // return false; // NBTTagCompound tag1 = s1.getTagCompound(), tag2 = s2.getTagCompound(); // if (tag1 == null || tag2 == null) { // return tag1 == null && tag2 == null; // } // // return tag1.equals(tag2); // } // // public static NBTTagCompound loadTag(ItemStack stack) { // NBTTagCompound ret = stack.getTagCompound(); // if (ret == null) // stack.setTagCompound(new NBTTagCompound()); // ret = stack.getTagCompound(); // return ret; // } // // }
import cn.liutils.util.mc.StackUtils; import net.minecraft.item.ItemStack; import cn.academy.energy.api.item.ImagEnergyItem; import cn.academy.support.EnergyItemHelper.EnergyItemManager;
/** * Copyright (c) Lambda Innovation, 2013-2015 * 本作品版权由Lambda Innovation所有。 * http://www.li-dev.cn/ * <p/> * This project is open-source, and it is distributed under * the terms of GNU General Public License. You can modify * and distribute freely as long as you follow the license. * 本项目是一个开源项目,且遵循GNU通用公共授权协议。 * 在遵照该协议的情况下,您可以自由传播和修改。 * http://www.gnu.org/licenses/gpl.html */ package cn.academy.energy.api; /** * @author WeathFolD */ public final class IFItemManager implements EnergyItemManager { public static IFItemManager instance = new IFItemManager(); private IFItemManager() { } public double getEnergy(ItemStack stack) {
// Path: src/main/java/cn/academy/energy/api/item/ImagEnergyItem.java // public interface ImagEnergyItem { // // double getMaxEnergy(); // // double getBandwidth(); // // // } // // Path: src/main/java/cn/academy/support/EnergyItemHelper.java // public interface EnergyItemManager { // // boolean isSupported(ItemStack stack); // // double getEnergy(ItemStack stack); // // void setEnergy(ItemStack stack, double energy); // // /** // * @return How much energy not transfered into stack(left) // */ // double charge(ItemStack stack, double amt, boolean ignoreBandwidth); // // /** // * @return How much energy pulled out of stack // */ // double pull(ItemStack stack, double amt, boolean ignoreBandwidth); // // } // // Path: src/main/java/cn/liutils/util/mc/StackUtils.java // public class StackUtils { // // public static void dropItems(World world, int x, int y, int z, IInventory inv) { // Random rand = new Random(); // // for (int i = 0; i < inv.getSizeInventory(); ++i) { // ItemStack stack = inv.getStackInSlot(i); // if (stack != null && stack.stackSize > 0) { // float rx = rand.nextFloat() * 0.8F + 0.1F; // float ry = rand.nextFloat() * 0.8F + 0.1F; // float rz = rand.nextFloat() * 0.8F + 0.1F; // // EntityItem entityItem = new EntityItem(world, x + rx, y + ry, z + rz, stack.copy()); // // if (stack.hasTagCompound()) { // entityItem.getEntityItem().setTagCompound((NBTTagCompound) stack.getTagCompound().copy()); // } // // float factor = 0.05F; // entityItem.motionX = rand.nextGaussian() * factor; // entityItem.motionY = rand.nextGaussian() * factor + 0.2F; // entityItem.motionZ = rand.nextGaussian() * factor; // world.spawnEntityInWorld(entityItem); // stack.stackSize = 0; // } // } // } // // /** // * Return whether two stack's item instance and data are equal. // */ // public static boolean isStackDataEqual(ItemStack s1, ItemStack s2) { // if (s1.getItem() != s1.getItem()) // return false; // NBTTagCompound tag1 = s1.getTagCompound(), tag2 = s2.getTagCompound(); // if (tag1 == null || tag2 == null) { // return tag1 == null && tag2 == null; // } // // return tag1.equals(tag2); // } // // public static NBTTagCompound loadTag(ItemStack stack) { // NBTTagCompound ret = stack.getTagCompound(); // if (ret == null) // stack.setTagCompound(new NBTTagCompound()); // ret = stack.getTagCompound(); // return ret; // } // // } // Path: src/main/java/cn/academy/energy/api/IFItemManager.java import cn.liutils.util.mc.StackUtils; import net.minecraft.item.ItemStack; import cn.academy.energy.api.item.ImagEnergyItem; import cn.academy.support.EnergyItemHelper.EnergyItemManager; /** * Copyright (c) Lambda Innovation, 2013-2015 * 本作品版权由Lambda Innovation所有。 * http://www.li-dev.cn/ * <p/> * This project is open-source, and it is distributed under * the terms of GNU General Public License. You can modify * and distribute freely as long as you follow the license. * 本项目是一个开源项目,且遵循GNU通用公共授权协议。 * 在遵照该协议的情况下,您可以自由传播和修改。 * http://www.gnu.org/licenses/gpl.html */ package cn.academy.energy.api; /** * @author WeathFolD */ public final class IFItemManager implements EnergyItemManager { public static IFItemManager instance = new IFItemManager(); private IFItemManager() { } public double getEnergy(ItemStack stack) {
ImagEnergyItem item = (ImagEnergyItem) stack.getItem();
InfinityStudio/ExoticPower
src/main/java/cn/academy/energy/api/IFItemManager.java
// Path: src/main/java/cn/academy/energy/api/item/ImagEnergyItem.java // public interface ImagEnergyItem { // // double getMaxEnergy(); // // double getBandwidth(); // // // } // // Path: src/main/java/cn/academy/support/EnergyItemHelper.java // public interface EnergyItemManager { // // boolean isSupported(ItemStack stack); // // double getEnergy(ItemStack stack); // // void setEnergy(ItemStack stack, double energy); // // /** // * @return How much energy not transfered into stack(left) // */ // double charge(ItemStack stack, double amt, boolean ignoreBandwidth); // // /** // * @return How much energy pulled out of stack // */ // double pull(ItemStack stack, double amt, boolean ignoreBandwidth); // // } // // Path: src/main/java/cn/liutils/util/mc/StackUtils.java // public class StackUtils { // // public static void dropItems(World world, int x, int y, int z, IInventory inv) { // Random rand = new Random(); // // for (int i = 0; i < inv.getSizeInventory(); ++i) { // ItemStack stack = inv.getStackInSlot(i); // if (stack != null && stack.stackSize > 0) { // float rx = rand.nextFloat() * 0.8F + 0.1F; // float ry = rand.nextFloat() * 0.8F + 0.1F; // float rz = rand.nextFloat() * 0.8F + 0.1F; // // EntityItem entityItem = new EntityItem(world, x + rx, y + ry, z + rz, stack.copy()); // // if (stack.hasTagCompound()) { // entityItem.getEntityItem().setTagCompound((NBTTagCompound) stack.getTagCompound().copy()); // } // // float factor = 0.05F; // entityItem.motionX = rand.nextGaussian() * factor; // entityItem.motionY = rand.nextGaussian() * factor + 0.2F; // entityItem.motionZ = rand.nextGaussian() * factor; // world.spawnEntityInWorld(entityItem); // stack.stackSize = 0; // } // } // } // // /** // * Return whether two stack's item instance and data are equal. // */ // public static boolean isStackDataEqual(ItemStack s1, ItemStack s2) { // if (s1.getItem() != s1.getItem()) // return false; // NBTTagCompound tag1 = s1.getTagCompound(), tag2 = s2.getTagCompound(); // if (tag1 == null || tag2 == null) { // return tag1 == null && tag2 == null; // } // // return tag1.equals(tag2); // } // // public static NBTTagCompound loadTag(ItemStack stack) { // NBTTagCompound ret = stack.getTagCompound(); // if (ret == null) // stack.setTagCompound(new NBTTagCompound()); // ret = stack.getTagCompound(); // return ret; // } // // }
import cn.liutils.util.mc.StackUtils; import net.minecraft.item.ItemStack; import cn.academy.energy.api.item.ImagEnergyItem; import cn.academy.support.EnergyItemHelper.EnergyItemManager;
/** * Copyright (c) Lambda Innovation, 2013-2015 * 本作品版权由Lambda Innovation所有。 * http://www.li-dev.cn/ * <p/> * This project is open-source, and it is distributed under * the terms of GNU General Public License. You can modify * and distribute freely as long as you follow the license. * 本项目是一个开源项目,且遵循GNU通用公共授权协议。 * 在遵照该协议的情况下,您可以自由传播和修改。 * http://www.gnu.org/licenses/gpl.html */ package cn.academy.energy.api; /** * @author WeathFolD */ public final class IFItemManager implements EnergyItemManager { public static IFItemManager instance = new IFItemManager(); private IFItemManager() { } public double getEnergy(ItemStack stack) { ImagEnergyItem item = (ImagEnergyItem) stack.getItem();
// Path: src/main/java/cn/academy/energy/api/item/ImagEnergyItem.java // public interface ImagEnergyItem { // // double getMaxEnergy(); // // double getBandwidth(); // // // } // // Path: src/main/java/cn/academy/support/EnergyItemHelper.java // public interface EnergyItemManager { // // boolean isSupported(ItemStack stack); // // double getEnergy(ItemStack stack); // // void setEnergy(ItemStack stack, double energy); // // /** // * @return How much energy not transfered into stack(left) // */ // double charge(ItemStack stack, double amt, boolean ignoreBandwidth); // // /** // * @return How much energy pulled out of stack // */ // double pull(ItemStack stack, double amt, boolean ignoreBandwidth); // // } // // Path: src/main/java/cn/liutils/util/mc/StackUtils.java // public class StackUtils { // // public static void dropItems(World world, int x, int y, int z, IInventory inv) { // Random rand = new Random(); // // for (int i = 0; i < inv.getSizeInventory(); ++i) { // ItemStack stack = inv.getStackInSlot(i); // if (stack != null && stack.stackSize > 0) { // float rx = rand.nextFloat() * 0.8F + 0.1F; // float ry = rand.nextFloat() * 0.8F + 0.1F; // float rz = rand.nextFloat() * 0.8F + 0.1F; // // EntityItem entityItem = new EntityItem(world, x + rx, y + ry, z + rz, stack.copy()); // // if (stack.hasTagCompound()) { // entityItem.getEntityItem().setTagCompound((NBTTagCompound) stack.getTagCompound().copy()); // } // // float factor = 0.05F; // entityItem.motionX = rand.nextGaussian() * factor; // entityItem.motionY = rand.nextGaussian() * factor + 0.2F; // entityItem.motionZ = rand.nextGaussian() * factor; // world.spawnEntityInWorld(entityItem); // stack.stackSize = 0; // } // } // } // // /** // * Return whether two stack's item instance and data are equal. // */ // public static boolean isStackDataEqual(ItemStack s1, ItemStack s2) { // if (s1.getItem() != s1.getItem()) // return false; // NBTTagCompound tag1 = s1.getTagCompound(), tag2 = s2.getTagCompound(); // if (tag1 == null || tag2 == null) { // return tag1 == null && tag2 == null; // } // // return tag1.equals(tag2); // } // // public static NBTTagCompound loadTag(ItemStack stack) { // NBTTagCompound ret = stack.getTagCompound(); // if (ret == null) // stack.setTagCompound(new NBTTagCompound()); // ret = stack.getTagCompound(); // return ret; // } // // } // Path: src/main/java/cn/academy/energy/api/IFItemManager.java import cn.liutils.util.mc.StackUtils; import net.minecraft.item.ItemStack; import cn.academy.energy.api.item.ImagEnergyItem; import cn.academy.support.EnergyItemHelper.EnergyItemManager; /** * Copyright (c) Lambda Innovation, 2013-2015 * 本作品版权由Lambda Innovation所有。 * http://www.li-dev.cn/ * <p/> * This project is open-source, and it is distributed under * the terms of GNU General Public License. You can modify * and distribute freely as long as you follow the license. * 本项目是一个开源项目,且遵循GNU通用公共授权协议。 * 在遵照该协议的情况下,您可以自由传播和修改。 * http://www.gnu.org/licenses/gpl.html */ package cn.academy.energy.api; /** * @author WeathFolD */ public final class IFItemManager implements EnergyItemManager { public static IFItemManager instance = new IFItemManager(); private IFItemManager() { } public double getEnergy(ItemStack stack) { ImagEnergyItem item = (ImagEnergyItem) stack.getItem();
return StackUtils.loadTag(stack).getDouble("energy");
InfinityStudio/ExoticPower
src/main/java/cn/academy/energy/api/event/wen/UnlinkNodeEvent.java
// Path: src/main/java/cn/academy/energy/api/block/IWirelessNode.java // public interface IWirelessNode extends IWirelessTile { // // double getMaxEnergy(); // // double getEnergy(); // // void setEnergy(double value); // // /** // * @return How many energy that this node can transfer each tick. // */ // double getBandwidth(); // // int getCapacity(); // // /** // * @return How far this node's signal can reach. // */ // double getRange(); // // /** // * @return the user custom name of the node // */ // String getNodeName(); // // } // // Path: src/main/java/cn/academy/energy/api/block/IWirelessTile.java // public interface IWirelessTile { // // } // // Path: src/main/java/cn/academy/energy/api/event/WirelessEvent.java // public class WirelessEvent extends Event { // // public final IWirelessTile tile; // // public WirelessEvent(IWirelessTile _tile) { // tile = _tile; // } // // public TileEntity getTileEntity() { // return (TileEntity) tile; // } // // public World getWorld() { // return getTileEntity().getWorld(); // } // // }
import cn.academy.energy.api.event.WirelessEvent; import cn.academy.energy.api.block.IWirelessNode; import cn.academy.energy.api.block.IWirelessTile;
/** * Copyright (c) Lambda Innovation, 2013-2015 * 本作品版权由Lambda Innovation所有。 * http://www.li-dev.cn/ * <p/> * This project is open-source, and it is distributed under * the terms of GNU General Public License. You can modify * and distribute freely as long as you follow the license. * 本项目是一个开源项目,且遵循GNU通用公共授权协议。 * 在遵照该协议的情况下,您可以自由传播和修改。 * http://www.gnu.org/licenses/gpl.html */ package cn.academy.energy.api.event.wen; /** * Fired when a node is to be unlinked. * @author WeathFolD */ public class UnlinkNodeEvent extends WirelessEvent { public final IWirelessNode node;
// Path: src/main/java/cn/academy/energy/api/block/IWirelessNode.java // public interface IWirelessNode extends IWirelessTile { // // double getMaxEnergy(); // // double getEnergy(); // // void setEnergy(double value); // // /** // * @return How many energy that this node can transfer each tick. // */ // double getBandwidth(); // // int getCapacity(); // // /** // * @return How far this node's signal can reach. // */ // double getRange(); // // /** // * @return the user custom name of the node // */ // String getNodeName(); // // } // // Path: src/main/java/cn/academy/energy/api/block/IWirelessTile.java // public interface IWirelessTile { // // } // // Path: src/main/java/cn/academy/energy/api/event/WirelessEvent.java // public class WirelessEvent extends Event { // // public final IWirelessTile tile; // // public WirelessEvent(IWirelessTile _tile) { // tile = _tile; // } // // public TileEntity getTileEntity() { // return (TileEntity) tile; // } // // public World getWorld() { // return getTileEntity().getWorld(); // } // // } // Path: src/main/java/cn/academy/energy/api/event/wen/UnlinkNodeEvent.java import cn.academy.energy.api.event.WirelessEvent; import cn.academy.energy.api.block.IWirelessNode; import cn.academy.energy.api.block.IWirelessTile; /** * Copyright (c) Lambda Innovation, 2013-2015 * 本作品版权由Lambda Innovation所有。 * http://www.li-dev.cn/ * <p/> * This project is open-source, and it is distributed under * the terms of GNU General Public License. You can modify * and distribute freely as long as you follow the license. * 本项目是一个开源项目,且遵循GNU通用公共授权协议。 * 在遵照该协议的情况下,您可以自由传播和修改。 * http://www.gnu.org/licenses/gpl.html */ package cn.academy.energy.api.event.wen; /** * Fired when a node is to be unlinked. * @author WeathFolD */ public class UnlinkNodeEvent extends WirelessEvent { public final IWirelessNode node;
public UnlinkNodeEvent(IWirelessTile _node) {
InfinityStudio/ExoticPower
src/main/java/cn/liutils/util/mc/WorldUtils.java
// Path: src/main/java/cn/liutils/util/mc/EntitySelectors.java // public static class SelectorList implements Predicate<Entity> { // // List<Predicate> list = new ArrayList(); // // public SelectorList(Predicate... sels) { // for (Predicate i : sels) // list.add(i); // } // // public SelectorList append(Predicate selector) { // list.add(selector); // return this; // } // // @Override // public boolean apply(Entity entity) { // // for (Predicate i : list) // if (!i.apply(entity)) // return false; // return true; // } // // }
import cn.liutils.util.mc.EntitySelectors.SelectorList; import com.google.common.base.Predicate; import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.BlockPos; import net.minecraft.util.MathHelper; import net.minecraft.util.Vec3; import net.minecraft.world.World; import java.util.ArrayList; import java.util.List;
for (IBlockFilter f : filter) { if (!f.accepts(world, x, y, z, world.getBlockState(new BlockPos(x, y, z)).getBlock())) { match = false; break; } } if (match) { ret.add(new BlockPos(x, y, z)); if (ret.size() == max) return ret; } } } } return ret; } public static List<Entity> getEntities(TileEntity te, double range, Predicate filter) { return getEntities(te.getWorld(), te.getPos().getX() + 0.5, te.getPos().getY() + 0.5, te.getPos().getZ() + 0.5, range, filter); } public static List<Entity> getEntities(Entity ent, double range, Predicate filter) { return getEntities(ent.worldObj, ent.posX, ent.posY, ent.posZ, range, filter); } public static List<Entity> getEntities(World world, double x, double y, double z, double range, Predicate filter) { AxisAlignedBB box = new AxisAlignedBB( x - range, y - range, z - range, x + range, y + range, z + range);
// Path: src/main/java/cn/liutils/util/mc/EntitySelectors.java // public static class SelectorList implements Predicate<Entity> { // // List<Predicate> list = new ArrayList(); // // public SelectorList(Predicate... sels) { // for (Predicate i : sels) // list.add(i); // } // // public SelectorList append(Predicate selector) { // list.add(selector); // return this; // } // // @Override // public boolean apply(Entity entity) { // // for (Predicate i : list) // if (!i.apply(entity)) // return false; // return true; // } // // } // Path: src/main/java/cn/liutils/util/mc/WorldUtils.java import cn.liutils.util.mc.EntitySelectors.SelectorList; import com.google.common.base.Predicate; import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.BlockPos; import net.minecraft.util.MathHelper; import net.minecraft.util.Vec3; import net.minecraft.world.World; import java.util.ArrayList; import java.util.List; for (IBlockFilter f : filter) { if (!f.accepts(world, x, y, z, world.getBlockState(new BlockPos(x, y, z)).getBlock())) { match = false; break; } } if (match) { ret.add(new BlockPos(x, y, z)); if (ret.size() == max) return ret; } } } } return ret; } public static List<Entity> getEntities(TileEntity te, double range, Predicate filter) { return getEntities(te.getWorld(), te.getPos().getX() + 0.5, te.getPos().getY() + 0.5, te.getPos().getZ() + 0.5, range, filter); } public static List<Entity> getEntities(Entity ent, double range, Predicate filter) { return getEntities(ent.worldObj, ent.posX, ent.posY, ent.posZ, range, filter); } public static List<Entity> getEntities(World world, double x, double y, double z, double range, Predicate filter) { AxisAlignedBB box = new AxisAlignedBB( x - range, y - range, z - range, x + range, y + range, z + range);
SelectorList list = new SelectorList(filter, new EntitySelectors.RestrictRange(x, y, z, range));
InfinityStudio/ExoticPower
src/main/java/cn/academy/energy/api/IFNodeManager.java
// Path: src/main/java/cn/academy/energy/api/block/IWirelessNode.java // public interface IWirelessNode extends IWirelessTile { // // double getMaxEnergy(); // // double getEnergy(); // // void setEnergy(double value); // // /** // * @return How many energy that this node can transfer each tick. // */ // double getBandwidth(); // // int getCapacity(); // // /** // * @return How far this node's signal can reach. // */ // double getRange(); // // /** // * @return the user custom name of the node // */ // String getNodeName(); // // } // // Path: src/main/java/cn/academy/support/EnergyBlockHelper.java // public class EnergyBlockHelper { // // private static List<IEnergyBlockManager> handlers = new ArrayList(); // // public static void register(IEnergyBlockManager handler) { // handlers.add(handler); // } // // public static boolean isSupported(TileEntity tile) { // for (IEnergyBlockManager handler : handlers) // if (handler.isSupported(tile)) // return true; // return false; // } // // public static double getEnergy(TileEntity tile) { // for (IEnergyBlockManager handler : handlers) // if (handler.isSupported(tile)) // return handler.getEnergy(tile); // return 0; // } // // public static void setEnergy(TileEntity tile, double energy) { // for (IEnergyBlockManager handler : handlers) // if (handler.isSupported(tile)) { // handler.setEnergy(tile, energy); // break; // } // } // // public static double charge(TileEntity tile, double amt, boolean ignoreBandwidth) { // for (IEnergyBlockManager handler : handlers) // if (handler.isSupported(tile)) { // return handler.charge(tile, amt, ignoreBandwidth); // } // return amt; // } // // public static double pull(TileEntity tile, double amt, boolean ignoreBandwidth) { // for (IEnergyBlockManager handler : handlers) // if (handler.isSupported(tile)) { // return handler.pull(tile, amt, ignoreBandwidth); // } // return 0; // } // // public static interface IEnergyBlockManager { // // boolean isSupported(TileEntity tile); // // double getEnergy(TileEntity tile); // // void setEnergy(TileEntity tile, double energy); // // /** // * Charge a specified amount of energy into the tile. // * // * @return How much energy not charged into the tile(left) // */ // double charge(TileEntity tile, double amt, boolean ignoreBandwidth); // // /** // * Pull a specified amount of energy from the energy tile. // * // * @return How much energy pulled out // */ // double pull(TileEntity tile, double amt, boolean ignoreBandwidth); // // } // // } // // Path: src/main/java/cn/academy/support/EnergyBlockHelper.java // public static interface IEnergyBlockManager { // // boolean isSupported(TileEntity tile); // // double getEnergy(TileEntity tile); // // void setEnergy(TileEntity tile, double energy); // // /** // * Charge a specified amount of energy into the tile. // * // * @return How much energy not charged into the tile(left) // */ // double charge(TileEntity tile, double amt, boolean ignoreBandwidth); // // /** // * Pull a specified amount of energy from the energy tile. // * // * @return How much energy pulled out // */ // double pull(TileEntity tile, double amt, boolean ignoreBandwidth); // // }
import cn.academy.energy.api.block.IWirelessNode; import cn.academy.support.EnergyBlockHelper; import cn.academy.support.EnergyBlockHelper.IEnergyBlockManager; import cn.annoreg.core.Registrant; import net.minecraft.tileentity.TileEntity;
/** * Copyright (c) Lambda Innovation, 2013-2015 * 本作品版权由Lambda Innovation所有。 * http://www.li-dev.cn/ * <p/> * This project is open-source, and it is distributed under * the terms of GNU General Public License. You can modify * and distribute freely as long as you follow the license. * 本项目是一个开源项目,且遵循GNU通用公共授权协议。 * 在遵照该协议的情况下,您可以自由传播和修改。 * http://www.gnu.org/licenses/gpl.html */ package cn.academy.energy.api; /** * @author WeAthFolD */ @Registrant public class IFNodeManager implements IEnergyBlockManager { public static IFNodeManager instance = new IFNodeManager(); private IFNodeManager() {
// Path: src/main/java/cn/academy/energy/api/block/IWirelessNode.java // public interface IWirelessNode extends IWirelessTile { // // double getMaxEnergy(); // // double getEnergy(); // // void setEnergy(double value); // // /** // * @return How many energy that this node can transfer each tick. // */ // double getBandwidth(); // // int getCapacity(); // // /** // * @return How far this node's signal can reach. // */ // double getRange(); // // /** // * @return the user custom name of the node // */ // String getNodeName(); // // } // // Path: src/main/java/cn/academy/support/EnergyBlockHelper.java // public class EnergyBlockHelper { // // private static List<IEnergyBlockManager> handlers = new ArrayList(); // // public static void register(IEnergyBlockManager handler) { // handlers.add(handler); // } // // public static boolean isSupported(TileEntity tile) { // for (IEnergyBlockManager handler : handlers) // if (handler.isSupported(tile)) // return true; // return false; // } // // public static double getEnergy(TileEntity tile) { // for (IEnergyBlockManager handler : handlers) // if (handler.isSupported(tile)) // return handler.getEnergy(tile); // return 0; // } // // public static void setEnergy(TileEntity tile, double energy) { // for (IEnergyBlockManager handler : handlers) // if (handler.isSupported(tile)) { // handler.setEnergy(tile, energy); // break; // } // } // // public static double charge(TileEntity tile, double amt, boolean ignoreBandwidth) { // for (IEnergyBlockManager handler : handlers) // if (handler.isSupported(tile)) { // return handler.charge(tile, amt, ignoreBandwidth); // } // return amt; // } // // public static double pull(TileEntity tile, double amt, boolean ignoreBandwidth) { // for (IEnergyBlockManager handler : handlers) // if (handler.isSupported(tile)) { // return handler.pull(tile, amt, ignoreBandwidth); // } // return 0; // } // // public static interface IEnergyBlockManager { // // boolean isSupported(TileEntity tile); // // double getEnergy(TileEntity tile); // // void setEnergy(TileEntity tile, double energy); // // /** // * Charge a specified amount of energy into the tile. // * // * @return How much energy not charged into the tile(left) // */ // double charge(TileEntity tile, double amt, boolean ignoreBandwidth); // // /** // * Pull a specified amount of energy from the energy tile. // * // * @return How much energy pulled out // */ // double pull(TileEntity tile, double amt, boolean ignoreBandwidth); // // } // // } // // Path: src/main/java/cn/academy/support/EnergyBlockHelper.java // public static interface IEnergyBlockManager { // // boolean isSupported(TileEntity tile); // // double getEnergy(TileEntity tile); // // void setEnergy(TileEntity tile, double energy); // // /** // * Charge a specified amount of energy into the tile. // * // * @return How much energy not charged into the tile(left) // */ // double charge(TileEntity tile, double amt, boolean ignoreBandwidth); // // /** // * Pull a specified amount of energy from the energy tile. // * // * @return How much energy pulled out // */ // double pull(TileEntity tile, double amt, boolean ignoreBandwidth); // // } // Path: src/main/java/cn/academy/energy/api/IFNodeManager.java import cn.academy.energy.api.block.IWirelessNode; import cn.academy.support.EnergyBlockHelper; import cn.academy.support.EnergyBlockHelper.IEnergyBlockManager; import cn.annoreg.core.Registrant; import net.minecraft.tileentity.TileEntity; /** * Copyright (c) Lambda Innovation, 2013-2015 * 本作品版权由Lambda Innovation所有。 * http://www.li-dev.cn/ * <p/> * This project is open-source, and it is distributed under * the terms of GNU General Public License. You can modify * and distribute freely as long as you follow the license. * 本项目是一个开源项目,且遵循GNU通用公共授权协议。 * 在遵照该协议的情况下,您可以自由传播和修改。 * http://www.gnu.org/licenses/gpl.html */ package cn.academy.energy.api; /** * @author WeAthFolD */ @Registrant public class IFNodeManager implements IEnergyBlockManager { public static IFNodeManager instance = new IFNodeManager(); private IFNodeManager() {
EnergyBlockHelper.register(this);
InfinityStudio/ExoticPower
src/main/java/cn/academy/energy/api/IFNodeManager.java
// Path: src/main/java/cn/academy/energy/api/block/IWirelessNode.java // public interface IWirelessNode extends IWirelessTile { // // double getMaxEnergy(); // // double getEnergy(); // // void setEnergy(double value); // // /** // * @return How many energy that this node can transfer each tick. // */ // double getBandwidth(); // // int getCapacity(); // // /** // * @return How far this node's signal can reach. // */ // double getRange(); // // /** // * @return the user custom name of the node // */ // String getNodeName(); // // } // // Path: src/main/java/cn/academy/support/EnergyBlockHelper.java // public class EnergyBlockHelper { // // private static List<IEnergyBlockManager> handlers = new ArrayList(); // // public static void register(IEnergyBlockManager handler) { // handlers.add(handler); // } // // public static boolean isSupported(TileEntity tile) { // for (IEnergyBlockManager handler : handlers) // if (handler.isSupported(tile)) // return true; // return false; // } // // public static double getEnergy(TileEntity tile) { // for (IEnergyBlockManager handler : handlers) // if (handler.isSupported(tile)) // return handler.getEnergy(tile); // return 0; // } // // public static void setEnergy(TileEntity tile, double energy) { // for (IEnergyBlockManager handler : handlers) // if (handler.isSupported(tile)) { // handler.setEnergy(tile, energy); // break; // } // } // // public static double charge(TileEntity tile, double amt, boolean ignoreBandwidth) { // for (IEnergyBlockManager handler : handlers) // if (handler.isSupported(tile)) { // return handler.charge(tile, amt, ignoreBandwidth); // } // return amt; // } // // public static double pull(TileEntity tile, double amt, boolean ignoreBandwidth) { // for (IEnergyBlockManager handler : handlers) // if (handler.isSupported(tile)) { // return handler.pull(tile, amt, ignoreBandwidth); // } // return 0; // } // // public static interface IEnergyBlockManager { // // boolean isSupported(TileEntity tile); // // double getEnergy(TileEntity tile); // // void setEnergy(TileEntity tile, double energy); // // /** // * Charge a specified amount of energy into the tile. // * // * @return How much energy not charged into the tile(left) // */ // double charge(TileEntity tile, double amt, boolean ignoreBandwidth); // // /** // * Pull a specified amount of energy from the energy tile. // * // * @return How much energy pulled out // */ // double pull(TileEntity tile, double amt, boolean ignoreBandwidth); // // } // // } // // Path: src/main/java/cn/academy/support/EnergyBlockHelper.java // public static interface IEnergyBlockManager { // // boolean isSupported(TileEntity tile); // // double getEnergy(TileEntity tile); // // void setEnergy(TileEntity tile, double energy); // // /** // * Charge a specified amount of energy into the tile. // * // * @return How much energy not charged into the tile(left) // */ // double charge(TileEntity tile, double amt, boolean ignoreBandwidth); // // /** // * Pull a specified amount of energy from the energy tile. // * // * @return How much energy pulled out // */ // double pull(TileEntity tile, double amt, boolean ignoreBandwidth); // // }
import cn.academy.energy.api.block.IWirelessNode; import cn.academy.support.EnergyBlockHelper; import cn.academy.support.EnergyBlockHelper.IEnergyBlockManager; import cn.annoreg.core.Registrant; import net.minecraft.tileentity.TileEntity;
/** * Copyright (c) Lambda Innovation, 2013-2015 * 本作品版权由Lambda Innovation所有。 * http://www.li-dev.cn/ * <p/> * This project is open-source, and it is distributed under * the terms of GNU General Public License. You can modify * and distribute freely as long as you follow the license. * 本项目是一个开源项目,且遵循GNU通用公共授权协议。 * 在遵照该协议的情况下,您可以自由传播和修改。 * http://www.gnu.org/licenses/gpl.html */ package cn.academy.energy.api; /** * @author WeAthFolD */ @Registrant public class IFNodeManager implements IEnergyBlockManager { public static IFNodeManager instance = new IFNodeManager(); private IFNodeManager() { EnergyBlockHelper.register(this); } @Override public boolean isSupported(TileEntity tile) {
// Path: src/main/java/cn/academy/energy/api/block/IWirelessNode.java // public interface IWirelessNode extends IWirelessTile { // // double getMaxEnergy(); // // double getEnergy(); // // void setEnergy(double value); // // /** // * @return How many energy that this node can transfer each tick. // */ // double getBandwidth(); // // int getCapacity(); // // /** // * @return How far this node's signal can reach. // */ // double getRange(); // // /** // * @return the user custom name of the node // */ // String getNodeName(); // // } // // Path: src/main/java/cn/academy/support/EnergyBlockHelper.java // public class EnergyBlockHelper { // // private static List<IEnergyBlockManager> handlers = new ArrayList(); // // public static void register(IEnergyBlockManager handler) { // handlers.add(handler); // } // // public static boolean isSupported(TileEntity tile) { // for (IEnergyBlockManager handler : handlers) // if (handler.isSupported(tile)) // return true; // return false; // } // // public static double getEnergy(TileEntity tile) { // for (IEnergyBlockManager handler : handlers) // if (handler.isSupported(tile)) // return handler.getEnergy(tile); // return 0; // } // // public static void setEnergy(TileEntity tile, double energy) { // for (IEnergyBlockManager handler : handlers) // if (handler.isSupported(tile)) { // handler.setEnergy(tile, energy); // break; // } // } // // public static double charge(TileEntity tile, double amt, boolean ignoreBandwidth) { // for (IEnergyBlockManager handler : handlers) // if (handler.isSupported(tile)) { // return handler.charge(tile, amt, ignoreBandwidth); // } // return amt; // } // // public static double pull(TileEntity tile, double amt, boolean ignoreBandwidth) { // for (IEnergyBlockManager handler : handlers) // if (handler.isSupported(tile)) { // return handler.pull(tile, amt, ignoreBandwidth); // } // return 0; // } // // public static interface IEnergyBlockManager { // // boolean isSupported(TileEntity tile); // // double getEnergy(TileEntity tile); // // void setEnergy(TileEntity tile, double energy); // // /** // * Charge a specified amount of energy into the tile. // * // * @return How much energy not charged into the tile(left) // */ // double charge(TileEntity tile, double amt, boolean ignoreBandwidth); // // /** // * Pull a specified amount of energy from the energy tile. // * // * @return How much energy pulled out // */ // double pull(TileEntity tile, double amt, boolean ignoreBandwidth); // // } // // } // // Path: src/main/java/cn/academy/support/EnergyBlockHelper.java // public static interface IEnergyBlockManager { // // boolean isSupported(TileEntity tile); // // double getEnergy(TileEntity tile); // // void setEnergy(TileEntity tile, double energy); // // /** // * Charge a specified amount of energy into the tile. // * // * @return How much energy not charged into the tile(left) // */ // double charge(TileEntity tile, double amt, boolean ignoreBandwidth); // // /** // * Pull a specified amount of energy from the energy tile. // * // * @return How much energy pulled out // */ // double pull(TileEntity tile, double amt, boolean ignoreBandwidth); // // } // Path: src/main/java/cn/academy/energy/api/IFNodeManager.java import cn.academy.energy.api.block.IWirelessNode; import cn.academy.support.EnergyBlockHelper; import cn.academy.support.EnergyBlockHelper.IEnergyBlockManager; import cn.annoreg.core.Registrant; import net.minecraft.tileentity.TileEntity; /** * Copyright (c) Lambda Innovation, 2013-2015 * 本作品版权由Lambda Innovation所有。 * http://www.li-dev.cn/ * <p/> * This project is open-source, and it is distributed under * the terms of GNU General Public License. You can modify * and distribute freely as long as you follow the license. * 本项目是一个开源项目,且遵循GNU通用公共授权协议。 * 在遵照该协议的情况下,您可以自由传播和修改。 * http://www.gnu.org/licenses/gpl.html */ package cn.academy.energy.api; /** * @author WeAthFolD */ @Registrant public class IFNodeManager implements IEnergyBlockManager { public static IFNodeManager instance = new IFNodeManager(); private IFNodeManager() { EnergyBlockHelper.register(this); } @Override public boolean isSupported(TileEntity tile) {
return tile instanceof IWirelessNode;
InfinityStudio/ExoticPower
src/main/java/infstudio/exoticpower/block/BlockSoulOre.java
// Path: src/main/java/infstudio/exoticpower/ExoticPower.java // @Mod(modid = "ExoticPower", name = "ExoticPower", version = "1.0.0") // public class ExoticPower { // // public static final NormalExoticPowerTab NEPTab = new NormalExoticPowerTab(); // public static final MageExoticPowerTab MEPTab = new MageExoticPowerTab(); // // @SidedProxy(clientSide = "infstudio.exoticpower.proxy.ClientProxy", // serverSide = "infstudio.exoticpower.proxy.CommonProxy") // public static CommonProxy proxy; // // @Instance("ExoticPower") // public static ExoticPower instance; // // @EventHandler // public void preInit(FMLPreInitializationEvent event) { // proxy.preInit(event); // } // // @EventHandler // public void init(FMLInitializationEvent event) { // proxy.init(event); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) { // proxy.postInit(event); // } // // } // // Path: src/main/java/infstudio/exoticpower/item/ItemSoulFire.java // public class ItemSoulFire extends Item { // // public ItemSoulFire() { // this.setUnlocalizedName("soulfire"); // this.setCreativeTab(ExoticPower.ept); // EPItems.itemList.add(this); // } // // }
import infstudio.exoticpower.ExoticPower; import infstudio.exoticpower.item.ItemSoulFire; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.item.Item; import java.util.Random;
package infstudio.exoticpower.block; public class BlockSoulOre extends Block { protected BlockSoulOre() { super(Material.rock); this.setUnlocalizedName("soulore");
// Path: src/main/java/infstudio/exoticpower/ExoticPower.java // @Mod(modid = "ExoticPower", name = "ExoticPower", version = "1.0.0") // public class ExoticPower { // // public static final NormalExoticPowerTab NEPTab = new NormalExoticPowerTab(); // public static final MageExoticPowerTab MEPTab = new MageExoticPowerTab(); // // @SidedProxy(clientSide = "infstudio.exoticpower.proxy.ClientProxy", // serverSide = "infstudio.exoticpower.proxy.CommonProxy") // public static CommonProxy proxy; // // @Instance("ExoticPower") // public static ExoticPower instance; // // @EventHandler // public void preInit(FMLPreInitializationEvent event) { // proxy.preInit(event); // } // // @EventHandler // public void init(FMLInitializationEvent event) { // proxy.init(event); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) { // proxy.postInit(event); // } // // } // // Path: src/main/java/infstudio/exoticpower/item/ItemSoulFire.java // public class ItemSoulFire extends Item { // // public ItemSoulFire() { // this.setUnlocalizedName("soulfire"); // this.setCreativeTab(ExoticPower.ept); // EPItems.itemList.add(this); // } // // } // Path: src/main/java/infstudio/exoticpower/block/BlockSoulOre.java import infstudio.exoticpower.ExoticPower; import infstudio.exoticpower.item.ItemSoulFire; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.item.Item; import java.util.Random; package infstudio.exoticpower.block; public class BlockSoulOre extends Block { protected BlockSoulOre() { super(Material.rock); this.setUnlocalizedName("soulore");
this.setCreativeTab(ExoticPower.ept);
InfinityStudio/ExoticPower
src/main/java/infstudio/exoticpower/block/BlockSoulOre.java
// Path: src/main/java/infstudio/exoticpower/ExoticPower.java // @Mod(modid = "ExoticPower", name = "ExoticPower", version = "1.0.0") // public class ExoticPower { // // public static final NormalExoticPowerTab NEPTab = new NormalExoticPowerTab(); // public static final MageExoticPowerTab MEPTab = new MageExoticPowerTab(); // // @SidedProxy(clientSide = "infstudio.exoticpower.proxy.ClientProxy", // serverSide = "infstudio.exoticpower.proxy.CommonProxy") // public static CommonProxy proxy; // // @Instance("ExoticPower") // public static ExoticPower instance; // // @EventHandler // public void preInit(FMLPreInitializationEvent event) { // proxy.preInit(event); // } // // @EventHandler // public void init(FMLInitializationEvent event) { // proxy.init(event); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) { // proxy.postInit(event); // } // // } // // Path: src/main/java/infstudio/exoticpower/item/ItemSoulFire.java // public class ItemSoulFire extends Item { // // public ItemSoulFire() { // this.setUnlocalizedName("soulfire"); // this.setCreativeTab(ExoticPower.ept); // EPItems.itemList.add(this); // } // // }
import infstudio.exoticpower.ExoticPower; import infstudio.exoticpower.item.ItemSoulFire; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.item.Item; import java.util.Random;
package infstudio.exoticpower.block; public class BlockSoulOre extends Block { protected BlockSoulOre() { super(Material.rock); this.setUnlocalizedName("soulore"); this.setCreativeTab(ExoticPower.ept); this.setStepSound(soundTypeStone); this.setHardness(3.0F); this.setResistance(15.0F); this.setLightLevel(7.0F); this.setHarvestLevel("pickaxe", 2); EPBlocks.blockList.add(this); } @Override public Item getItemDropped(IBlockState state, Random rand, int fortune) {
// Path: src/main/java/infstudio/exoticpower/ExoticPower.java // @Mod(modid = "ExoticPower", name = "ExoticPower", version = "1.0.0") // public class ExoticPower { // // public static final NormalExoticPowerTab NEPTab = new NormalExoticPowerTab(); // public static final MageExoticPowerTab MEPTab = new MageExoticPowerTab(); // // @SidedProxy(clientSide = "infstudio.exoticpower.proxy.ClientProxy", // serverSide = "infstudio.exoticpower.proxy.CommonProxy") // public static CommonProxy proxy; // // @Instance("ExoticPower") // public static ExoticPower instance; // // @EventHandler // public void preInit(FMLPreInitializationEvent event) { // proxy.preInit(event); // } // // @EventHandler // public void init(FMLInitializationEvent event) { // proxy.init(event); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) { // proxy.postInit(event); // } // // } // // Path: src/main/java/infstudio/exoticpower/item/ItemSoulFire.java // public class ItemSoulFire extends Item { // // public ItemSoulFire() { // this.setUnlocalizedName("soulfire"); // this.setCreativeTab(ExoticPower.ept); // EPItems.itemList.add(this); // } // // } // Path: src/main/java/infstudio/exoticpower/block/BlockSoulOre.java import infstudio.exoticpower.ExoticPower; import infstudio.exoticpower.item.ItemSoulFire; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.item.Item; import java.util.Random; package infstudio.exoticpower.block; public class BlockSoulOre extends Block { protected BlockSoulOre() { super(Material.rock); this.setUnlocalizedName("soulore"); this.setCreativeTab(ExoticPower.ept); this.setStepSound(soundTypeStone); this.setHardness(3.0F); this.setResistance(15.0F); this.setLightLevel(7.0F); this.setHarvestLevel("pickaxe", 2); EPBlocks.blockList.add(this); } @Override public Item getItemDropped(IBlockState state, Random rand, int fortune) {
return new ItemSoulFire();
InfinityStudio/ExoticPower
src/main/java/cn/academy/energy/api/event/WirelessUserEvent.java
// Path: src/main/java/cn/academy/energy/api/block/IWirelessGenerator.java // public interface IWirelessGenerator extends IWirelessUser { // // /** // * @param req How much energy is required // * @return How much energy this generator can provide. Must be guaranteed 0<=ret<=req // */ // public double getProvidedEnergy(double req); // // /** // * @return Max energy transmitted each tick // */ // public double getBandwidth(); // // } // // Path: src/main/java/cn/academy/energy/api/block/IWirelessReceiver.java // public interface IWirelessReceiver extends IWirelessUser { // // double getRequiredEnergy(); // // /** // * Inject some amount of energy into the machine. ALWAYS positive // * @return energy not injected // */ // double injectEnergy(double amt); // // /** // * Pull some energy out of the machine. ALWAYS positive // * @param amt The amount // * @return energy really pulled out. // */ // double pullEnergy(double amt); // // /** // * @return How much energy this receiver can retrieve each tick. // */ // double getBandwidth(); // // } // // Path: src/main/java/cn/academy/energy/api/block/IWirelessTile.java // public interface IWirelessTile { // // }
import cn.academy.energy.api.block.IWirelessTile; import cn.academy.energy.api.block.IWirelessGenerator; import cn.academy.energy.api.block.IWirelessReceiver;
/** * Copyright (c) Lambda Innovation, 2013-2015 * 本作品版权由Lambda Innovation所有。 * http://www.li-dev.cn/ * <p/> * This project is open-source, and it is distributed under * the terms of GNU General Public License. You can modify * and distribute freely as long as you follow the license. * 本项目是一个开源项目,且遵循GNU通用公共授权协议。 * 在遵照该协议的情况下,您可以自由传播和修改。 * http://www.gnu.org/licenses/gpl.html */ package cn.academy.energy.api.event; /** * @author WeathFolD * */ public class WirelessUserEvent extends WirelessEvent { public final UserType type;
// Path: src/main/java/cn/academy/energy/api/block/IWirelessGenerator.java // public interface IWirelessGenerator extends IWirelessUser { // // /** // * @param req How much energy is required // * @return How much energy this generator can provide. Must be guaranteed 0<=ret<=req // */ // public double getProvidedEnergy(double req); // // /** // * @return Max energy transmitted each tick // */ // public double getBandwidth(); // // } // // Path: src/main/java/cn/academy/energy/api/block/IWirelessReceiver.java // public interface IWirelessReceiver extends IWirelessUser { // // double getRequiredEnergy(); // // /** // * Inject some amount of energy into the machine. ALWAYS positive // * @return energy not injected // */ // double injectEnergy(double amt); // // /** // * Pull some energy out of the machine. ALWAYS positive // * @param amt The amount // * @return energy really pulled out. // */ // double pullEnergy(double amt); // // /** // * @return How much energy this receiver can retrieve each tick. // */ // double getBandwidth(); // // } // // Path: src/main/java/cn/academy/energy/api/block/IWirelessTile.java // public interface IWirelessTile { // // } // Path: src/main/java/cn/academy/energy/api/event/WirelessUserEvent.java import cn.academy.energy.api.block.IWirelessTile; import cn.academy.energy.api.block.IWirelessGenerator; import cn.academy.energy.api.block.IWirelessReceiver; /** * Copyright (c) Lambda Innovation, 2013-2015 * 本作品版权由Lambda Innovation所有。 * http://www.li-dev.cn/ * <p/> * This project is open-source, and it is distributed under * the terms of GNU General Public License. You can modify * and distribute freely as long as you follow the license. * 本项目是一个开源项目,且遵循GNU通用公共授权协议。 * 在遵照该协议的情况下,您可以自由传播和修改。 * http://www.gnu.org/licenses/gpl.html */ package cn.academy.energy.api.event; /** * @author WeathFolD * */ public class WirelessUserEvent extends WirelessEvent { public final UserType type;
public WirelessUserEvent(IWirelessTile _tile) {
InfinityStudio/ExoticPower
src/main/java/cn/academy/energy/api/event/WirelessUserEvent.java
// Path: src/main/java/cn/academy/energy/api/block/IWirelessGenerator.java // public interface IWirelessGenerator extends IWirelessUser { // // /** // * @param req How much energy is required // * @return How much energy this generator can provide. Must be guaranteed 0<=ret<=req // */ // public double getProvidedEnergy(double req); // // /** // * @return Max energy transmitted each tick // */ // public double getBandwidth(); // // } // // Path: src/main/java/cn/academy/energy/api/block/IWirelessReceiver.java // public interface IWirelessReceiver extends IWirelessUser { // // double getRequiredEnergy(); // // /** // * Inject some amount of energy into the machine. ALWAYS positive // * @return energy not injected // */ // double injectEnergy(double amt); // // /** // * Pull some energy out of the machine. ALWAYS positive // * @param amt The amount // * @return energy really pulled out. // */ // double pullEnergy(double amt); // // /** // * @return How much energy this receiver can retrieve each tick. // */ // double getBandwidth(); // // } // // Path: src/main/java/cn/academy/energy/api/block/IWirelessTile.java // public interface IWirelessTile { // // }
import cn.academy.energy.api.block.IWirelessTile; import cn.academy.energy.api.block.IWirelessGenerator; import cn.academy.energy.api.block.IWirelessReceiver;
/** * Copyright (c) Lambda Innovation, 2013-2015 * 本作品版权由Lambda Innovation所有。 * http://www.li-dev.cn/ * <p/> * This project is open-source, and it is distributed under * the terms of GNU General Public License. You can modify * and distribute freely as long as you follow the license. * 本项目是一个开源项目,且遵循GNU通用公共授权协议。 * 在遵照该协议的情况下,您可以自由传播和修改。 * http://www.gnu.org/licenses/gpl.html */ package cn.academy.energy.api.event; /** * @author WeathFolD * */ public class WirelessUserEvent extends WirelessEvent { public final UserType type; public WirelessUserEvent(IWirelessTile _tile) { super(_tile);
// Path: src/main/java/cn/academy/energy/api/block/IWirelessGenerator.java // public interface IWirelessGenerator extends IWirelessUser { // // /** // * @param req How much energy is required // * @return How much energy this generator can provide. Must be guaranteed 0<=ret<=req // */ // public double getProvidedEnergy(double req); // // /** // * @return Max energy transmitted each tick // */ // public double getBandwidth(); // // } // // Path: src/main/java/cn/academy/energy/api/block/IWirelessReceiver.java // public interface IWirelessReceiver extends IWirelessUser { // // double getRequiredEnergy(); // // /** // * Inject some amount of energy into the machine. ALWAYS positive // * @return energy not injected // */ // double injectEnergy(double amt); // // /** // * Pull some energy out of the machine. ALWAYS positive // * @param amt The amount // * @return energy really pulled out. // */ // double pullEnergy(double amt); // // /** // * @return How much energy this receiver can retrieve each tick. // */ // double getBandwidth(); // // } // // Path: src/main/java/cn/academy/energy/api/block/IWirelessTile.java // public interface IWirelessTile { // // } // Path: src/main/java/cn/academy/energy/api/event/WirelessUserEvent.java import cn.academy.energy.api.block.IWirelessTile; import cn.academy.energy.api.block.IWirelessGenerator; import cn.academy.energy.api.block.IWirelessReceiver; /** * Copyright (c) Lambda Innovation, 2013-2015 * 本作品版权由Lambda Innovation所有。 * http://www.li-dev.cn/ * <p/> * This project is open-source, and it is distributed under * the terms of GNU General Public License. You can modify * and distribute freely as long as you follow the license. * 本项目是一个开源项目,且遵循GNU通用公共授权协议。 * 在遵照该协议的情况下,您可以自由传播和修改。 * http://www.gnu.org/licenses/gpl.html */ package cn.academy.energy.api.event; /** * @author WeathFolD * */ public class WirelessUserEvent extends WirelessEvent { public final UserType type; public WirelessUserEvent(IWirelessTile _tile) { super(_tile);
if (_tile instanceof IWirelessGenerator) {
InfinityStudio/ExoticPower
src/main/java/cn/academy/energy/api/event/WirelessUserEvent.java
// Path: src/main/java/cn/academy/energy/api/block/IWirelessGenerator.java // public interface IWirelessGenerator extends IWirelessUser { // // /** // * @param req How much energy is required // * @return How much energy this generator can provide. Must be guaranteed 0<=ret<=req // */ // public double getProvidedEnergy(double req); // // /** // * @return Max energy transmitted each tick // */ // public double getBandwidth(); // // } // // Path: src/main/java/cn/academy/energy/api/block/IWirelessReceiver.java // public interface IWirelessReceiver extends IWirelessUser { // // double getRequiredEnergy(); // // /** // * Inject some amount of energy into the machine. ALWAYS positive // * @return energy not injected // */ // double injectEnergy(double amt); // // /** // * Pull some energy out of the machine. ALWAYS positive // * @param amt The amount // * @return energy really pulled out. // */ // double pullEnergy(double amt); // // /** // * @return How much energy this receiver can retrieve each tick. // */ // double getBandwidth(); // // } // // Path: src/main/java/cn/academy/energy/api/block/IWirelessTile.java // public interface IWirelessTile { // // }
import cn.academy.energy.api.block.IWirelessTile; import cn.academy.energy.api.block.IWirelessGenerator; import cn.academy.energy.api.block.IWirelessReceiver;
/** * Copyright (c) Lambda Innovation, 2013-2015 * 本作品版权由Lambda Innovation所有。 * http://www.li-dev.cn/ * <p/> * This project is open-source, and it is distributed under * the terms of GNU General Public License. You can modify * and distribute freely as long as you follow the license. * 本项目是一个开源项目,且遵循GNU通用公共授权协议。 * 在遵照该协议的情况下,您可以自由传播和修改。 * http://www.gnu.org/licenses/gpl.html */ package cn.academy.energy.api.event; /** * @author WeathFolD * */ public class WirelessUserEvent extends WirelessEvent { public final UserType type; public WirelessUserEvent(IWirelessTile _tile) { super(_tile); if (_tile instanceof IWirelessGenerator) { type = UserType.GENERATOR;
// Path: src/main/java/cn/academy/energy/api/block/IWirelessGenerator.java // public interface IWirelessGenerator extends IWirelessUser { // // /** // * @param req How much energy is required // * @return How much energy this generator can provide. Must be guaranteed 0<=ret<=req // */ // public double getProvidedEnergy(double req); // // /** // * @return Max energy transmitted each tick // */ // public double getBandwidth(); // // } // // Path: src/main/java/cn/academy/energy/api/block/IWirelessReceiver.java // public interface IWirelessReceiver extends IWirelessUser { // // double getRequiredEnergy(); // // /** // * Inject some amount of energy into the machine. ALWAYS positive // * @return energy not injected // */ // double injectEnergy(double amt); // // /** // * Pull some energy out of the machine. ALWAYS positive // * @param amt The amount // * @return energy really pulled out. // */ // double pullEnergy(double amt); // // /** // * @return How much energy this receiver can retrieve each tick. // */ // double getBandwidth(); // // } // // Path: src/main/java/cn/academy/energy/api/block/IWirelessTile.java // public interface IWirelessTile { // // } // Path: src/main/java/cn/academy/energy/api/event/WirelessUserEvent.java import cn.academy.energy.api.block.IWirelessTile; import cn.academy.energy.api.block.IWirelessGenerator; import cn.academy.energy.api.block.IWirelessReceiver; /** * Copyright (c) Lambda Innovation, 2013-2015 * 本作品版权由Lambda Innovation所有。 * http://www.li-dev.cn/ * <p/> * This project is open-source, and it is distributed under * the terms of GNU General Public License. You can modify * and distribute freely as long as you follow the license. * 本项目是一个开源项目,且遵循GNU通用公共授权协议。 * 在遵照该协议的情况下,您可以自由传播和修改。 * http://www.gnu.org/licenses/gpl.html */ package cn.academy.energy.api.event; /** * @author WeathFolD * */ public class WirelessUserEvent extends WirelessEvent { public final UserType type; public WirelessUserEvent(IWirelessTile _tile) { super(_tile); if (_tile instanceof IWirelessGenerator) { type = UserType.GENERATOR;
} else if (_tile instanceof IWirelessReceiver) {
jotorren/microservices-transactions-tcc
rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/impl/CompositeTransactionManagerMemoryImpl.java
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionManager.java // public interface CompositeTransactionManager { // // void open(String txId); // void enlist(String txId, EntityCommand<?> ec); // List<EntityCommand<?>> fetch(String txId); // void close(String txId); // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/EntityCommand.java // public class EntityCommand<T> implements Serializable{ // private static final long serialVersionUID = -3927305961526601453L; // // public enum Action { // INSERT, UPDATE, DELETE, QUERY // } // // private T entity; // private Action action; // private String transactionId; // private long timestamp; // // public T getEntity() { // return entity; // } // // public void setEntity(T entity) { // this.entity = entity; // } // // public Action getAction() { // return action; // } // // public void setAction(Action action) { // this.action = action; // } // // public String getTransactionId() { // return transactionId; // } // // public void setTransactionId(String transactionId) { // this.transactionId = transactionId; // } // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // }
import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import net.jotorren.microservices.tx.CompositeTransactionManager; import net.jotorren.microservices.tx.EntityCommand; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package net.jotorren.microservices.tx.impl; public class CompositeTransactionManagerMemoryImpl implements CompositeTransactionManager { private static final Logger LOG = LoggerFactory.getLogger(CompositeTransactionManager.class);
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionManager.java // public interface CompositeTransactionManager { // // void open(String txId); // void enlist(String txId, EntityCommand<?> ec); // List<EntityCommand<?>> fetch(String txId); // void close(String txId); // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/EntityCommand.java // public class EntityCommand<T> implements Serializable{ // private static final long serialVersionUID = -3927305961526601453L; // // public enum Action { // INSERT, UPDATE, DELETE, QUERY // } // // private T entity; // private Action action; // private String transactionId; // private long timestamp; // // public T getEntity() { // return entity; // } // // public void setEntity(T entity) { // this.entity = entity; // } // // public Action getAction() { // return action; // } // // public void setAction(Action action) { // this.action = action; // } // // public String getTransactionId() { // return transactionId; // } // // public void setTransactionId(String transactionId) { // this.transactionId = transactionId; // } // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // } // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/impl/CompositeTransactionManagerMemoryImpl.java import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import net.jotorren.microservices.tx.CompositeTransactionManager; import net.jotorren.microservices.tx.EntityCommand; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package net.jotorren.microservices.tx.impl; public class CompositeTransactionManagerMemoryImpl implements CompositeTransactionManager { private static final Logger LOG = LoggerFactory.getLogger(CompositeTransactionManager.class);
private Map<String, List<EntityCommand<?>>> transactions = new ConcurrentHashMap<String, List<EntityCommand<?>>>();
jotorren/microservices-transactions-tcc
rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/impl/CompositeTransactionManagerKafkaImpl.java
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionManager.java // public interface CompositeTransactionManager { // // void open(String txId); // void enlist(String txId, EntityCommand<?> ec); // List<EntityCommand<?>> fetch(String txId); // void close(String txId); // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/EntityCommand.java // public class EntityCommand<T> implements Serializable{ // private static final long serialVersionUID = -3927305961526601453L; // // public enum Action { // INSERT, UPDATE, DELETE, QUERY // } // // private T entity; // private Action action; // private String transactionId; // private long timestamp; // // public T getEntity() { // return entity; // } // // public void setEntity(T entity) { // this.entity = entity; // } // // public Action getAction() { // return action; // } // // public void setAction(Action action) { // this.action = action; // } // // public String getTransactionId() { // return transactionId; // } // // public void setTransactionId(String transactionId) { // this.transactionId = transactionId; // } // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/Serializer.java // public interface Serializer<T> { // // byte[] write(T object) throws SerializationFailedException; // String writeToString(T object) throws SerializationFailedException; // // T read(byte[] bytes) throws SerializationFailedException; // T readFromString(String chars) throws SerializationFailedException; // }
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.UUID; import kafka.admin.AdminUtils; import kafka.admin.RackAwareMode; import kafka.utils.ZkUtils; import net.jotorren.microservices.tx.CompositeTransactionManager; import net.jotorren.microservices.tx.EntityCommand; import net.jotorren.microservices.tx.Serializer; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.serializer.support.SerializationFailedException; import org.springframework.kafka.core.KafkaTemplate;
package net.jotorren.microservices.tx.impl; public class CompositeTransactionManagerKafkaImpl implements CompositeTransactionManager { private static final Logger LOG = LoggerFactory.getLogger(CompositeTransactionManager.class); @Value("${zookeeper.partitions:0}") private int zooPartitions; @Value("${zookeeper.replication:0}") private int zooReplication; @Value("${kafka.consumer.poll.timeout:0}") private long kafkaConsumerPollTimeout; @Autowired(required = false) private ZkUtils zkUtils; @Autowired(required = false) private KafkaTemplate<Integer, String> kafkaTemplate; @Autowired(required = false) @Qualifier("kafkaConsumerConfiguration") private Map<String, Object> configuration; @Autowired(required = false)
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionManager.java // public interface CompositeTransactionManager { // // void open(String txId); // void enlist(String txId, EntityCommand<?> ec); // List<EntityCommand<?>> fetch(String txId); // void close(String txId); // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/EntityCommand.java // public class EntityCommand<T> implements Serializable{ // private static final long serialVersionUID = -3927305961526601453L; // // public enum Action { // INSERT, UPDATE, DELETE, QUERY // } // // private T entity; // private Action action; // private String transactionId; // private long timestamp; // // public T getEntity() { // return entity; // } // // public void setEntity(T entity) { // this.entity = entity; // } // // public Action getAction() { // return action; // } // // public void setAction(Action action) { // this.action = action; // } // // public String getTransactionId() { // return transactionId; // } // // public void setTransactionId(String transactionId) { // this.transactionId = transactionId; // } // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/Serializer.java // public interface Serializer<T> { // // byte[] write(T object) throws SerializationFailedException; // String writeToString(T object) throws SerializationFailedException; // // T read(byte[] bytes) throws SerializationFailedException; // T readFromString(String chars) throws SerializationFailedException; // } // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/impl/CompositeTransactionManagerKafkaImpl.java import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.UUID; import kafka.admin.AdminUtils; import kafka.admin.RackAwareMode; import kafka.utils.ZkUtils; import net.jotorren.microservices.tx.CompositeTransactionManager; import net.jotorren.microservices.tx.EntityCommand; import net.jotorren.microservices.tx.Serializer; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.serializer.support.SerializationFailedException; import org.springframework.kafka.core.KafkaTemplate; package net.jotorren.microservices.tx.impl; public class CompositeTransactionManagerKafkaImpl implements CompositeTransactionManager { private static final Logger LOG = LoggerFactory.getLogger(CompositeTransactionManager.class); @Value("${zookeeper.partitions:0}") private int zooPartitions; @Value("${zookeeper.replication:0}") private int zooReplication; @Value("${kafka.consumer.poll.timeout:0}") private long kafkaConsumerPollTimeout; @Autowired(required = false) private ZkUtils zkUtils; @Autowired(required = false) private KafkaTemplate<Integer, String> kafkaTemplate; @Autowired(required = false) @Qualifier("kafkaConsumerConfiguration") private Map<String, Object> configuration; @Autowired(required = false)
private Serializer<EntityCommand<?>> serializer;
jotorren/microservices-transactions-tcc
rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/impl/CompositeTransactionManagerKafkaImpl.java
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionManager.java // public interface CompositeTransactionManager { // // void open(String txId); // void enlist(String txId, EntityCommand<?> ec); // List<EntityCommand<?>> fetch(String txId); // void close(String txId); // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/EntityCommand.java // public class EntityCommand<T> implements Serializable{ // private static final long serialVersionUID = -3927305961526601453L; // // public enum Action { // INSERT, UPDATE, DELETE, QUERY // } // // private T entity; // private Action action; // private String transactionId; // private long timestamp; // // public T getEntity() { // return entity; // } // // public void setEntity(T entity) { // this.entity = entity; // } // // public Action getAction() { // return action; // } // // public void setAction(Action action) { // this.action = action; // } // // public String getTransactionId() { // return transactionId; // } // // public void setTransactionId(String transactionId) { // this.transactionId = transactionId; // } // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/Serializer.java // public interface Serializer<T> { // // byte[] write(T object) throws SerializationFailedException; // String writeToString(T object) throws SerializationFailedException; // // T read(byte[] bytes) throws SerializationFailedException; // T readFromString(String chars) throws SerializationFailedException; // }
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.UUID; import kafka.admin.AdminUtils; import kafka.admin.RackAwareMode; import kafka.utils.ZkUtils; import net.jotorren.microservices.tx.CompositeTransactionManager; import net.jotorren.microservices.tx.EntityCommand; import net.jotorren.microservices.tx.Serializer; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.serializer.support.SerializationFailedException; import org.springframework.kafka.core.KafkaTemplate;
package net.jotorren.microservices.tx.impl; public class CompositeTransactionManagerKafkaImpl implements CompositeTransactionManager { private static final Logger LOG = LoggerFactory.getLogger(CompositeTransactionManager.class); @Value("${zookeeper.partitions:0}") private int zooPartitions; @Value("${zookeeper.replication:0}") private int zooReplication; @Value("${kafka.consumer.poll.timeout:0}") private long kafkaConsumerPollTimeout; @Autowired(required = false) private ZkUtils zkUtils; @Autowired(required = false) private KafkaTemplate<Integer, String> kafkaTemplate; @Autowired(required = false) @Qualifier("kafkaConsumerConfiguration") private Map<String, Object> configuration; @Autowired(required = false)
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionManager.java // public interface CompositeTransactionManager { // // void open(String txId); // void enlist(String txId, EntityCommand<?> ec); // List<EntityCommand<?>> fetch(String txId); // void close(String txId); // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/EntityCommand.java // public class EntityCommand<T> implements Serializable{ // private static final long serialVersionUID = -3927305961526601453L; // // public enum Action { // INSERT, UPDATE, DELETE, QUERY // } // // private T entity; // private Action action; // private String transactionId; // private long timestamp; // // public T getEntity() { // return entity; // } // // public void setEntity(T entity) { // this.entity = entity; // } // // public Action getAction() { // return action; // } // // public void setAction(Action action) { // this.action = action; // } // // public String getTransactionId() { // return transactionId; // } // // public void setTransactionId(String transactionId) { // this.transactionId = transactionId; // } // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/Serializer.java // public interface Serializer<T> { // // byte[] write(T object) throws SerializationFailedException; // String writeToString(T object) throws SerializationFailedException; // // T read(byte[] bytes) throws SerializationFailedException; // T readFromString(String chars) throws SerializationFailedException; // } // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/impl/CompositeTransactionManagerKafkaImpl.java import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.UUID; import kafka.admin.AdminUtils; import kafka.admin.RackAwareMode; import kafka.utils.ZkUtils; import net.jotorren.microservices.tx.CompositeTransactionManager; import net.jotorren.microservices.tx.EntityCommand; import net.jotorren.microservices.tx.Serializer; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.serializer.support.SerializationFailedException; import org.springframework.kafka.core.KafkaTemplate; package net.jotorren.microservices.tx.impl; public class CompositeTransactionManagerKafkaImpl implements CompositeTransactionManager { private static final Logger LOG = LoggerFactory.getLogger(CompositeTransactionManager.class); @Value("${zookeeper.partitions:0}") private int zooPartitions; @Value("${zookeeper.replication:0}") private int zooReplication; @Value("${kafka.consumer.poll.timeout:0}") private long kafkaConsumerPollTimeout; @Autowired(required = false) private ZkUtils zkUtils; @Autowired(required = false) private KafkaTemplate<Integer, String> kafkaTemplate; @Autowired(required = false) @Qualifier("kafkaConsumerConfiguration") private Map<String, Object> configuration; @Autowired(required = false)
private Serializer<EntityCommand<?>> serializer;
jotorren/microservices-transactions-tcc
rahub-forum-service/src/main/java/net/jotorren/microservices/forum/configuration/CompositeTransactionConfiguration.java
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/context/SpringContextProvider.java // public class SpringContextProvider implements ApplicationContextAware { // private static ApplicationContext ctx = null; // // public static ApplicationContext getApplicationContext() { // return ctx; // } // // public void setApplicationContext(ApplicationContext ctx) { // SpringContextProvider.ctx = ctx; // } // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionManager.java // public interface CompositeTransactionManager { // // void open(String txId); // void enlist(String txId, EntityCommand<?> ec); // List<EntityCommand<?>> fetch(String txId); // void close(String txId); // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/impl/CompositeTransactionManagerKafkaImpl.java // public class CompositeTransactionManagerKafkaImpl implements CompositeTransactionManager { // // private static final Logger LOG = LoggerFactory.getLogger(CompositeTransactionManager.class); // // @Value("${zookeeper.partitions:0}") // private int zooPartitions; // // @Value("${zookeeper.replication:0}") // private int zooReplication; // // @Value("${kafka.consumer.poll.timeout:0}") // private long kafkaConsumerPollTimeout; // // // @Autowired(required = false) // private ZkUtils zkUtils; // // @Autowired(required = false) // private KafkaTemplate<Integer, String> kafkaTemplate; // // @Autowired(required = false) // @Qualifier("kafkaConsumerConfiguration") // private Map<String, Object> configuration; // // @Autowired(required = false) // private Serializer<EntityCommand<?>> serializer; // // @Override // public void open(String txId) { // // Add topic configuration here // Properties topicConfig = new Properties(); // // AdminUtils.createTopic(zkUtils, txId, zooPartitions, zooReplication, topicConfig, RackAwareMode.Enforced$.MODULE$); // } // // @Override // public void enlist(String txId, EntityCommand<?> command) { // kafkaTemplate.send(txId, serializer.writeToString(command)); // } // // @SuppressWarnings("unchecked") // @Override // public List<EntityCommand<?>> fetch(String txId) { // List<EntityCommand<?>> transactionOperations = new ArrayList<EntityCommand<?>>(); // // Map<String, Object> consumerConfigs = (Map<String, Object>)configuration.get("kafkaConsumerConfiguration"); // consumerConfigs.put(ConsumerConfig.GROUP_ID_CONFIG, UUID.randomUUID().toString()); // // KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<String, String>(consumerConfigs); // kafkaConsumer.subscribe(Arrays.asList(txId)); // // ConsumerRecords<String, String> records = kafkaConsumer.poll(kafkaConsumerPollTimeout); // for (ConsumerRecord<String, String> record : records){ // LOG.info("offset = {}, key = {}, value = {}", record.offset(), record.key(), record.value()); // try { // transactionOperations.add(serializer.readFromString(record.value())); // } catch (SerializationFailedException e) { // LOG.error("Unable to deserialize [{}] because of: {}", record.value(), e.getMessage()); // } // } // // kafkaConsumer.close(); // // return transactionOperations; // } // // @Override // public void close(String txId) { // AdminUtils.deleteTopic(zkUtils, txId); // } // }
import java.util.HashMap; import java.util.Map; import net.jotorren.microservices.context.SpringContextProvider; import net.jotorren.microservices.tx.CompositeTransactionManager; import net.jotorren.microservices.tx.impl.CompositeTransactionManagerKafkaImpl; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.serialization.StringDeserializer; import org.apache.kafka.common.serialization.StringSerializer; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.kafka.core.DefaultKafkaProducerFactory; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.core.ProducerFactory;
package net.jotorren.microservices.forum.configuration; @Configuration public class CompositeTransactionConfiguration { @Value("${kafka.bootstrap-servers}") private String kafkaBootstrapServers; @Value("${kafka.consumer.enable.auto.commit}") private String kafkaEnableAutoCommit; @Value("${kafka.consumer.auto.commit.interval}") private String kafkaAutoCommitInterval; @Value("${kafka.consumer.session.timeout}") private String kafkaSessionTimeout; @Value("${kafka.consumer.auto.offset.reset}") private String kafkaAutoOffsetReset; @Bean
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/context/SpringContextProvider.java // public class SpringContextProvider implements ApplicationContextAware { // private static ApplicationContext ctx = null; // // public static ApplicationContext getApplicationContext() { // return ctx; // } // // public void setApplicationContext(ApplicationContext ctx) { // SpringContextProvider.ctx = ctx; // } // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionManager.java // public interface CompositeTransactionManager { // // void open(String txId); // void enlist(String txId, EntityCommand<?> ec); // List<EntityCommand<?>> fetch(String txId); // void close(String txId); // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/impl/CompositeTransactionManagerKafkaImpl.java // public class CompositeTransactionManagerKafkaImpl implements CompositeTransactionManager { // // private static final Logger LOG = LoggerFactory.getLogger(CompositeTransactionManager.class); // // @Value("${zookeeper.partitions:0}") // private int zooPartitions; // // @Value("${zookeeper.replication:0}") // private int zooReplication; // // @Value("${kafka.consumer.poll.timeout:0}") // private long kafkaConsumerPollTimeout; // // // @Autowired(required = false) // private ZkUtils zkUtils; // // @Autowired(required = false) // private KafkaTemplate<Integer, String> kafkaTemplate; // // @Autowired(required = false) // @Qualifier("kafkaConsumerConfiguration") // private Map<String, Object> configuration; // // @Autowired(required = false) // private Serializer<EntityCommand<?>> serializer; // // @Override // public void open(String txId) { // // Add topic configuration here // Properties topicConfig = new Properties(); // // AdminUtils.createTopic(zkUtils, txId, zooPartitions, zooReplication, topicConfig, RackAwareMode.Enforced$.MODULE$); // } // // @Override // public void enlist(String txId, EntityCommand<?> command) { // kafkaTemplate.send(txId, serializer.writeToString(command)); // } // // @SuppressWarnings("unchecked") // @Override // public List<EntityCommand<?>> fetch(String txId) { // List<EntityCommand<?>> transactionOperations = new ArrayList<EntityCommand<?>>(); // // Map<String, Object> consumerConfigs = (Map<String, Object>)configuration.get("kafkaConsumerConfiguration"); // consumerConfigs.put(ConsumerConfig.GROUP_ID_CONFIG, UUID.randomUUID().toString()); // // KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<String, String>(consumerConfigs); // kafkaConsumer.subscribe(Arrays.asList(txId)); // // ConsumerRecords<String, String> records = kafkaConsumer.poll(kafkaConsumerPollTimeout); // for (ConsumerRecord<String, String> record : records){ // LOG.info("offset = {}, key = {}, value = {}", record.offset(), record.key(), record.value()); // try { // transactionOperations.add(serializer.readFromString(record.value())); // } catch (SerializationFailedException e) { // LOG.error("Unable to deserialize [{}] because of: {}", record.value(), e.getMessage()); // } // } // // kafkaConsumer.close(); // // return transactionOperations; // } // // @Override // public void close(String txId) { // AdminUtils.deleteTopic(zkUtils, txId); // } // } // Path: rahub-forum-service/src/main/java/net/jotorren/microservices/forum/configuration/CompositeTransactionConfiguration.java import java.util.HashMap; import java.util.Map; import net.jotorren.microservices.context.SpringContextProvider; import net.jotorren.microservices.tx.CompositeTransactionManager; import net.jotorren.microservices.tx.impl.CompositeTransactionManagerKafkaImpl; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.serialization.StringDeserializer; import org.apache.kafka.common.serialization.StringSerializer; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.kafka.core.DefaultKafkaProducerFactory; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.core.ProducerFactory; package net.jotorren.microservices.forum.configuration; @Configuration public class CompositeTransactionConfiguration { @Value("${kafka.bootstrap-servers}") private String kafkaBootstrapServers; @Value("${kafka.consumer.enable.auto.commit}") private String kafkaEnableAutoCommit; @Value("${kafka.consumer.auto.commit.interval}") private String kafkaAutoCommitInterval; @Value("${kafka.consumer.session.timeout}") private String kafkaSessionTimeout; @Value("${kafka.consumer.auto.offset.reset}") private String kafkaAutoOffsetReset; @Bean
public SpringContextProvider springContextProvider(){
jotorren/microservices-transactions-tcc
rahub-forum-service/src/main/java/net/jotorren/microservices/forum/configuration/CompositeTransactionConfiguration.java
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/context/SpringContextProvider.java // public class SpringContextProvider implements ApplicationContextAware { // private static ApplicationContext ctx = null; // // public static ApplicationContext getApplicationContext() { // return ctx; // } // // public void setApplicationContext(ApplicationContext ctx) { // SpringContextProvider.ctx = ctx; // } // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionManager.java // public interface CompositeTransactionManager { // // void open(String txId); // void enlist(String txId, EntityCommand<?> ec); // List<EntityCommand<?>> fetch(String txId); // void close(String txId); // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/impl/CompositeTransactionManagerKafkaImpl.java // public class CompositeTransactionManagerKafkaImpl implements CompositeTransactionManager { // // private static final Logger LOG = LoggerFactory.getLogger(CompositeTransactionManager.class); // // @Value("${zookeeper.partitions:0}") // private int zooPartitions; // // @Value("${zookeeper.replication:0}") // private int zooReplication; // // @Value("${kafka.consumer.poll.timeout:0}") // private long kafkaConsumerPollTimeout; // // // @Autowired(required = false) // private ZkUtils zkUtils; // // @Autowired(required = false) // private KafkaTemplate<Integer, String> kafkaTemplate; // // @Autowired(required = false) // @Qualifier("kafkaConsumerConfiguration") // private Map<String, Object> configuration; // // @Autowired(required = false) // private Serializer<EntityCommand<?>> serializer; // // @Override // public void open(String txId) { // // Add topic configuration here // Properties topicConfig = new Properties(); // // AdminUtils.createTopic(zkUtils, txId, zooPartitions, zooReplication, topicConfig, RackAwareMode.Enforced$.MODULE$); // } // // @Override // public void enlist(String txId, EntityCommand<?> command) { // kafkaTemplate.send(txId, serializer.writeToString(command)); // } // // @SuppressWarnings("unchecked") // @Override // public List<EntityCommand<?>> fetch(String txId) { // List<EntityCommand<?>> transactionOperations = new ArrayList<EntityCommand<?>>(); // // Map<String, Object> consumerConfigs = (Map<String, Object>)configuration.get("kafkaConsumerConfiguration"); // consumerConfigs.put(ConsumerConfig.GROUP_ID_CONFIG, UUID.randomUUID().toString()); // // KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<String, String>(consumerConfigs); // kafkaConsumer.subscribe(Arrays.asList(txId)); // // ConsumerRecords<String, String> records = kafkaConsumer.poll(kafkaConsumerPollTimeout); // for (ConsumerRecord<String, String> record : records){ // LOG.info("offset = {}, key = {}, value = {}", record.offset(), record.key(), record.value()); // try { // transactionOperations.add(serializer.readFromString(record.value())); // } catch (SerializationFailedException e) { // LOG.error("Unable to deserialize [{}] because of: {}", record.value(), e.getMessage()); // } // } // // kafkaConsumer.close(); // // return transactionOperations; // } // // @Override // public void close(String txId) { // AdminUtils.deleteTopic(zkUtils, txId); // } // }
import java.util.HashMap; import java.util.Map; import net.jotorren.microservices.context.SpringContextProvider; import net.jotorren.microservices.tx.CompositeTransactionManager; import net.jotorren.microservices.tx.impl.CompositeTransactionManagerKafkaImpl; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.serialization.StringDeserializer; import org.apache.kafka.common.serialization.StringSerializer; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.kafka.core.DefaultKafkaProducerFactory; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.core.ProducerFactory;
package net.jotorren.microservices.forum.configuration; @Configuration public class CompositeTransactionConfiguration { @Value("${kafka.bootstrap-servers}") private String kafkaBootstrapServers; @Value("${kafka.consumer.enable.auto.commit}") private String kafkaEnableAutoCommit; @Value("${kafka.consumer.auto.commit.interval}") private String kafkaAutoCommitInterval; @Value("${kafka.consumer.session.timeout}") private String kafkaSessionTimeout; @Value("${kafka.consumer.auto.offset.reset}") private String kafkaAutoOffsetReset; @Bean public SpringContextProvider springContextProvider(){ return new SpringContextProvider(); } @Bean
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/context/SpringContextProvider.java // public class SpringContextProvider implements ApplicationContextAware { // private static ApplicationContext ctx = null; // // public static ApplicationContext getApplicationContext() { // return ctx; // } // // public void setApplicationContext(ApplicationContext ctx) { // SpringContextProvider.ctx = ctx; // } // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionManager.java // public interface CompositeTransactionManager { // // void open(String txId); // void enlist(String txId, EntityCommand<?> ec); // List<EntityCommand<?>> fetch(String txId); // void close(String txId); // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/impl/CompositeTransactionManagerKafkaImpl.java // public class CompositeTransactionManagerKafkaImpl implements CompositeTransactionManager { // // private static final Logger LOG = LoggerFactory.getLogger(CompositeTransactionManager.class); // // @Value("${zookeeper.partitions:0}") // private int zooPartitions; // // @Value("${zookeeper.replication:0}") // private int zooReplication; // // @Value("${kafka.consumer.poll.timeout:0}") // private long kafkaConsumerPollTimeout; // // // @Autowired(required = false) // private ZkUtils zkUtils; // // @Autowired(required = false) // private KafkaTemplate<Integer, String> kafkaTemplate; // // @Autowired(required = false) // @Qualifier("kafkaConsumerConfiguration") // private Map<String, Object> configuration; // // @Autowired(required = false) // private Serializer<EntityCommand<?>> serializer; // // @Override // public void open(String txId) { // // Add topic configuration here // Properties topicConfig = new Properties(); // // AdminUtils.createTopic(zkUtils, txId, zooPartitions, zooReplication, topicConfig, RackAwareMode.Enforced$.MODULE$); // } // // @Override // public void enlist(String txId, EntityCommand<?> command) { // kafkaTemplate.send(txId, serializer.writeToString(command)); // } // // @SuppressWarnings("unchecked") // @Override // public List<EntityCommand<?>> fetch(String txId) { // List<EntityCommand<?>> transactionOperations = new ArrayList<EntityCommand<?>>(); // // Map<String, Object> consumerConfigs = (Map<String, Object>)configuration.get("kafkaConsumerConfiguration"); // consumerConfigs.put(ConsumerConfig.GROUP_ID_CONFIG, UUID.randomUUID().toString()); // // KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<String, String>(consumerConfigs); // kafkaConsumer.subscribe(Arrays.asList(txId)); // // ConsumerRecords<String, String> records = kafkaConsumer.poll(kafkaConsumerPollTimeout); // for (ConsumerRecord<String, String> record : records){ // LOG.info("offset = {}, key = {}, value = {}", record.offset(), record.key(), record.value()); // try { // transactionOperations.add(serializer.readFromString(record.value())); // } catch (SerializationFailedException e) { // LOG.error("Unable to deserialize [{}] because of: {}", record.value(), e.getMessage()); // } // } // // kafkaConsumer.close(); // // return transactionOperations; // } // // @Override // public void close(String txId) { // AdminUtils.deleteTopic(zkUtils, txId); // } // } // Path: rahub-forum-service/src/main/java/net/jotorren/microservices/forum/configuration/CompositeTransactionConfiguration.java import java.util.HashMap; import java.util.Map; import net.jotorren.microservices.context.SpringContextProvider; import net.jotorren.microservices.tx.CompositeTransactionManager; import net.jotorren.microservices.tx.impl.CompositeTransactionManagerKafkaImpl; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.serialization.StringDeserializer; import org.apache.kafka.common.serialization.StringSerializer; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.kafka.core.DefaultKafkaProducerFactory; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.core.ProducerFactory; package net.jotorren.microservices.forum.configuration; @Configuration public class CompositeTransactionConfiguration { @Value("${kafka.bootstrap-servers}") private String kafkaBootstrapServers; @Value("${kafka.consumer.enable.auto.commit}") private String kafkaEnableAutoCommit; @Value("${kafka.consumer.auto.commit.interval}") private String kafkaAutoCommitInterval; @Value("${kafka.consumer.session.timeout}") private String kafkaSessionTimeout; @Value("${kafka.consumer.auto.offset.reset}") private String kafkaAutoOffsetReset; @Bean public SpringContextProvider springContextProvider(){ return new SpringContextProvider(); } @Bean
public CompositeTransactionManager compositeTransactionManager() {
jotorren/microservices-transactions-tcc
rahub-forum-service/src/main/java/net/jotorren/microservices/forum/configuration/CompositeTransactionConfiguration.java
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/context/SpringContextProvider.java // public class SpringContextProvider implements ApplicationContextAware { // private static ApplicationContext ctx = null; // // public static ApplicationContext getApplicationContext() { // return ctx; // } // // public void setApplicationContext(ApplicationContext ctx) { // SpringContextProvider.ctx = ctx; // } // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionManager.java // public interface CompositeTransactionManager { // // void open(String txId); // void enlist(String txId, EntityCommand<?> ec); // List<EntityCommand<?>> fetch(String txId); // void close(String txId); // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/impl/CompositeTransactionManagerKafkaImpl.java // public class CompositeTransactionManagerKafkaImpl implements CompositeTransactionManager { // // private static final Logger LOG = LoggerFactory.getLogger(CompositeTransactionManager.class); // // @Value("${zookeeper.partitions:0}") // private int zooPartitions; // // @Value("${zookeeper.replication:0}") // private int zooReplication; // // @Value("${kafka.consumer.poll.timeout:0}") // private long kafkaConsumerPollTimeout; // // // @Autowired(required = false) // private ZkUtils zkUtils; // // @Autowired(required = false) // private KafkaTemplate<Integer, String> kafkaTemplate; // // @Autowired(required = false) // @Qualifier("kafkaConsumerConfiguration") // private Map<String, Object> configuration; // // @Autowired(required = false) // private Serializer<EntityCommand<?>> serializer; // // @Override // public void open(String txId) { // // Add topic configuration here // Properties topicConfig = new Properties(); // // AdminUtils.createTopic(zkUtils, txId, zooPartitions, zooReplication, topicConfig, RackAwareMode.Enforced$.MODULE$); // } // // @Override // public void enlist(String txId, EntityCommand<?> command) { // kafkaTemplate.send(txId, serializer.writeToString(command)); // } // // @SuppressWarnings("unchecked") // @Override // public List<EntityCommand<?>> fetch(String txId) { // List<EntityCommand<?>> transactionOperations = new ArrayList<EntityCommand<?>>(); // // Map<String, Object> consumerConfigs = (Map<String, Object>)configuration.get("kafkaConsumerConfiguration"); // consumerConfigs.put(ConsumerConfig.GROUP_ID_CONFIG, UUID.randomUUID().toString()); // // KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<String, String>(consumerConfigs); // kafkaConsumer.subscribe(Arrays.asList(txId)); // // ConsumerRecords<String, String> records = kafkaConsumer.poll(kafkaConsumerPollTimeout); // for (ConsumerRecord<String, String> record : records){ // LOG.info("offset = {}, key = {}, value = {}", record.offset(), record.key(), record.value()); // try { // transactionOperations.add(serializer.readFromString(record.value())); // } catch (SerializationFailedException e) { // LOG.error("Unable to deserialize [{}] because of: {}", record.value(), e.getMessage()); // } // } // // kafkaConsumer.close(); // // return transactionOperations; // } // // @Override // public void close(String txId) { // AdminUtils.deleteTopic(zkUtils, txId); // } // }
import java.util.HashMap; import java.util.Map; import net.jotorren.microservices.context.SpringContextProvider; import net.jotorren.microservices.tx.CompositeTransactionManager; import net.jotorren.microservices.tx.impl.CompositeTransactionManagerKafkaImpl; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.serialization.StringDeserializer; import org.apache.kafka.common.serialization.StringSerializer; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.kafka.core.DefaultKafkaProducerFactory; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.core.ProducerFactory;
package net.jotorren.microservices.forum.configuration; @Configuration public class CompositeTransactionConfiguration { @Value("${kafka.bootstrap-servers}") private String kafkaBootstrapServers; @Value("${kafka.consumer.enable.auto.commit}") private String kafkaEnableAutoCommit; @Value("${kafka.consumer.auto.commit.interval}") private String kafkaAutoCommitInterval; @Value("${kafka.consumer.session.timeout}") private String kafkaSessionTimeout; @Value("${kafka.consumer.auto.offset.reset}") private String kafkaAutoOffsetReset; @Bean public SpringContextProvider springContextProvider(){ return new SpringContextProvider(); } @Bean public CompositeTransactionManager compositeTransactionManager() {
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/context/SpringContextProvider.java // public class SpringContextProvider implements ApplicationContextAware { // private static ApplicationContext ctx = null; // // public static ApplicationContext getApplicationContext() { // return ctx; // } // // public void setApplicationContext(ApplicationContext ctx) { // SpringContextProvider.ctx = ctx; // } // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionManager.java // public interface CompositeTransactionManager { // // void open(String txId); // void enlist(String txId, EntityCommand<?> ec); // List<EntityCommand<?>> fetch(String txId); // void close(String txId); // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/impl/CompositeTransactionManagerKafkaImpl.java // public class CompositeTransactionManagerKafkaImpl implements CompositeTransactionManager { // // private static final Logger LOG = LoggerFactory.getLogger(CompositeTransactionManager.class); // // @Value("${zookeeper.partitions:0}") // private int zooPartitions; // // @Value("${zookeeper.replication:0}") // private int zooReplication; // // @Value("${kafka.consumer.poll.timeout:0}") // private long kafkaConsumerPollTimeout; // // // @Autowired(required = false) // private ZkUtils zkUtils; // // @Autowired(required = false) // private KafkaTemplate<Integer, String> kafkaTemplate; // // @Autowired(required = false) // @Qualifier("kafkaConsumerConfiguration") // private Map<String, Object> configuration; // // @Autowired(required = false) // private Serializer<EntityCommand<?>> serializer; // // @Override // public void open(String txId) { // // Add topic configuration here // Properties topicConfig = new Properties(); // // AdminUtils.createTopic(zkUtils, txId, zooPartitions, zooReplication, topicConfig, RackAwareMode.Enforced$.MODULE$); // } // // @Override // public void enlist(String txId, EntityCommand<?> command) { // kafkaTemplate.send(txId, serializer.writeToString(command)); // } // // @SuppressWarnings("unchecked") // @Override // public List<EntityCommand<?>> fetch(String txId) { // List<EntityCommand<?>> transactionOperations = new ArrayList<EntityCommand<?>>(); // // Map<String, Object> consumerConfigs = (Map<String, Object>)configuration.get("kafkaConsumerConfiguration"); // consumerConfigs.put(ConsumerConfig.GROUP_ID_CONFIG, UUID.randomUUID().toString()); // // KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<String, String>(consumerConfigs); // kafkaConsumer.subscribe(Arrays.asList(txId)); // // ConsumerRecords<String, String> records = kafkaConsumer.poll(kafkaConsumerPollTimeout); // for (ConsumerRecord<String, String> record : records){ // LOG.info("offset = {}, key = {}, value = {}", record.offset(), record.key(), record.value()); // try { // transactionOperations.add(serializer.readFromString(record.value())); // } catch (SerializationFailedException e) { // LOG.error("Unable to deserialize [{}] because of: {}", record.value(), e.getMessage()); // } // } // // kafkaConsumer.close(); // // return transactionOperations; // } // // @Override // public void close(String txId) { // AdminUtils.deleteTopic(zkUtils, txId); // } // } // Path: rahub-forum-service/src/main/java/net/jotorren/microservices/forum/configuration/CompositeTransactionConfiguration.java import java.util.HashMap; import java.util.Map; import net.jotorren.microservices.context.SpringContextProvider; import net.jotorren.microservices.tx.CompositeTransactionManager; import net.jotorren.microservices.tx.impl.CompositeTransactionManagerKafkaImpl; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.serialization.StringDeserializer; import org.apache.kafka.common.serialization.StringSerializer; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.kafka.core.DefaultKafkaProducerFactory; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.core.ProducerFactory; package net.jotorren.microservices.forum.configuration; @Configuration public class CompositeTransactionConfiguration { @Value("${kafka.bootstrap-servers}") private String kafkaBootstrapServers; @Value("${kafka.consumer.enable.auto.commit}") private String kafkaEnableAutoCommit; @Value("${kafka.consumer.auto.commit.interval}") private String kafkaAutoCommitInterval; @Value("${kafka.consumer.session.timeout}") private String kafkaSessionTimeout; @Value("${kafka.consumer.auto.offset.reset}") private String kafkaAutoOffsetReset; @Bean public SpringContextProvider springContextProvider(){ return new SpringContextProvider(); } @Bean public CompositeTransactionManager compositeTransactionManager() {
return new CompositeTransactionManagerKafkaImpl();
jotorren/microservices-transactions-tcc
rahub-forum-service/src/main/java/net/jotorren/microservices/forum/domain/ForumSerializer.java
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/AbstractEntityCommandJsonSerializer.java // public abstract class AbstractEntityCommandJsonSerializer<T> implements Serializer<EntityCommand<T>> { // // private ObjectMapper jacksonMapper = new ObjectMapper(); // // public ObjectMapper getJacksonMapper(){ // return jacksonMapper; // } // // @Override // public byte[] write(EntityCommand<T> object) throws SerializationFailedException { // return writeToString(object).getBytes(); // } // // @Override // public String writeToString(EntityCommand<T> object) throws SerializationFailedException { // try { // return jacksonMapper.writeValueAsString(object); // } catch (JsonProcessingException e) { // throw new SerializationFailedException("Error performing EntityCommand serialization", e); // } // } // // @Override // public EntityCommand<T> read(byte[] bytes) throws SerializationFailedException { // return readFromString(new String(bytes)); // } // // @Override // public abstract EntityCommand<T> readFromString(String chars) throws SerializationFailedException; // // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/EntityCommand.java // public class EntityCommand<T> implements Serializable{ // private static final long serialVersionUID = -3927305961526601453L; // // public enum Action { // INSERT, UPDATE, DELETE, QUERY // } // // private T entity; // private Action action; // private String transactionId; // private long timestamp; // // public T getEntity() { // return entity; // } // // public void setEntity(T entity) { // this.entity = entity; // } // // public Action getAction() { // return action; // } // // public void setAction(Action action) { // this.action = action; // } // // public String getTransactionId() { // return transactionId; // } // // public void setTransactionId(String transactionId) { // this.transactionId = transactionId; // } // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // }
import java.io.IOException; import net.jotorren.microservices.tx.AbstractEntityCommandJsonSerializer; import net.jotorren.microservices.tx.EntityCommand; import org.springframework.core.serializer.support.SerializationFailedException; import org.springframework.stereotype.Component; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode;
package net.jotorren.microservices.forum.domain; @Component public class ForumSerializer extends AbstractEntityCommandJsonSerializer<Forum>{ @Override
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/AbstractEntityCommandJsonSerializer.java // public abstract class AbstractEntityCommandJsonSerializer<T> implements Serializer<EntityCommand<T>> { // // private ObjectMapper jacksonMapper = new ObjectMapper(); // // public ObjectMapper getJacksonMapper(){ // return jacksonMapper; // } // // @Override // public byte[] write(EntityCommand<T> object) throws SerializationFailedException { // return writeToString(object).getBytes(); // } // // @Override // public String writeToString(EntityCommand<T> object) throws SerializationFailedException { // try { // return jacksonMapper.writeValueAsString(object); // } catch (JsonProcessingException e) { // throw new SerializationFailedException("Error performing EntityCommand serialization", e); // } // } // // @Override // public EntityCommand<T> read(byte[] bytes) throws SerializationFailedException { // return readFromString(new String(bytes)); // } // // @Override // public abstract EntityCommand<T> readFromString(String chars) throws SerializationFailedException; // // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/EntityCommand.java // public class EntityCommand<T> implements Serializable{ // private static final long serialVersionUID = -3927305961526601453L; // // public enum Action { // INSERT, UPDATE, DELETE, QUERY // } // // private T entity; // private Action action; // private String transactionId; // private long timestamp; // // public T getEntity() { // return entity; // } // // public void setEntity(T entity) { // this.entity = entity; // } // // public Action getAction() { // return action; // } // // public void setAction(Action action) { // this.action = action; // } // // public String getTransactionId() { // return transactionId; // } // // public void setTransactionId(String transactionId) { // this.transactionId = transactionId; // } // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // } // Path: rahub-forum-service/src/main/java/net/jotorren/microservices/forum/domain/ForumSerializer.java import java.io.IOException; import net.jotorren.microservices.tx.AbstractEntityCommandJsonSerializer; import net.jotorren.microservices.tx.EntityCommand; import org.springframework.core.serializer.support.SerializationFailedException; import org.springframework.stereotype.Component; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; package net.jotorren.microservices.forum.domain; @Component public class ForumSerializer extends AbstractEntityCommandJsonSerializer<Forum>{ @Override
public EntityCommand<Forum> readFromString(String chars)
jotorren/microservices-transactions-tcc
rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionParticipantService.java
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/context/ThreadLocalContext.java // public final class ThreadLocalContext { // // private static final Logger LOG = LoggerFactory.getLogger(ThreadLocalContext.class); // // /** Initial size of the map */ // private static final int HT_SIZE = 5; // // /** Thread local map variable to store any shared object */ // private static final ThreadLocal<Map<String, Object>> THREAD_LOCAL_HOLDER = new ThreadLocal<Map<String, Object>>() { // // protected java.util.Map<String, Object> initialValue() { // return new HashMap<String, Object>(HT_SIZE); // }; // }; // // private ThreadLocalContext() { // } // // public static void put(String key, Object payload) { // if (null == key) { // LOG.error("Unable to put a null key"); // return; // } // // if (null == payload) { // LOG.error("Unable to put a null value"); // return; // } // // THREAD_LOCAL_HOLDER.get().put(key, payload); // } // // public static Object get(String key) { // if (null == key) { // LOG.error("Unable to get a null key"); // return null; // } // // return THREAD_LOCAL_HOLDER.get().get(key); // } // // @SuppressWarnings("unchecked") // public static <T> T get(String key, Class<T> requiredType) { // return (T) get(key); // } // // public static Object remove(String key) { // if (null == key) { // LOG.error("Unable to remove a null key"); // return null; // } // // return THREAD_LOCAL_HOLDER.get().remove(key); // } // // public static void cleanup() { // THREAD_LOCAL_HOLDER.get().clear(); // THREAD_LOCAL_HOLDER.remove(); // } // // public static Map<String, Object> exportContext() { // return THREAD_LOCAL_HOLDER.get(); // } // // public static void importContext(Map<String, Object> context) { // THREAD_LOCAL_HOLDER.get().putAll(context); // } // }
import java.util.List; import net.jotorren.microservices.context.ThreadLocalContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired;
package net.jotorren.microservices.tx; public abstract class CompositeTransactionParticipantService { private static final Logger LOG = LoggerFactory.getLogger(CompositeTransactionParticipantService.class); public static final String CURRENT_TRANSACTION_KEY = "current.opened.tx"; @Autowired private CompositeTransactionManager txManager; public CompositeTransactionManager getCompositeTransactionManager(){ return txManager; } public void cancel(String txId) {
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/context/ThreadLocalContext.java // public final class ThreadLocalContext { // // private static final Logger LOG = LoggerFactory.getLogger(ThreadLocalContext.class); // // /** Initial size of the map */ // private static final int HT_SIZE = 5; // // /** Thread local map variable to store any shared object */ // private static final ThreadLocal<Map<String, Object>> THREAD_LOCAL_HOLDER = new ThreadLocal<Map<String, Object>>() { // // protected java.util.Map<String, Object> initialValue() { // return new HashMap<String, Object>(HT_SIZE); // }; // }; // // private ThreadLocalContext() { // } // // public static void put(String key, Object payload) { // if (null == key) { // LOG.error("Unable to put a null key"); // return; // } // // if (null == payload) { // LOG.error("Unable to put a null value"); // return; // } // // THREAD_LOCAL_HOLDER.get().put(key, payload); // } // // public static Object get(String key) { // if (null == key) { // LOG.error("Unable to get a null key"); // return null; // } // // return THREAD_LOCAL_HOLDER.get().get(key); // } // // @SuppressWarnings("unchecked") // public static <T> T get(String key, Class<T> requiredType) { // return (T) get(key); // } // // public static Object remove(String key) { // if (null == key) { // LOG.error("Unable to remove a null key"); // return null; // } // // return THREAD_LOCAL_HOLDER.get().remove(key); // } // // public static void cleanup() { // THREAD_LOCAL_HOLDER.get().clear(); // THREAD_LOCAL_HOLDER.remove(); // } // // public static Map<String, Object> exportContext() { // return THREAD_LOCAL_HOLDER.get(); // } // // public static void importContext(Map<String, Object> context) { // THREAD_LOCAL_HOLDER.get().putAll(context); // } // } // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionParticipantService.java import java.util.List; import net.jotorren.microservices.context.ThreadLocalContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; package net.jotorren.microservices.tx; public abstract class CompositeTransactionParticipantService { private static final Logger LOG = LoggerFactory.getLogger(CompositeTransactionParticipantService.class); public static final String CURRENT_TRANSACTION_KEY = "current.opened.tx"; @Autowired private CompositeTransactionManager txManager; public CompositeTransactionManager getCompositeTransactionManager(){ return txManager; } public void cancel(String txId) {
ThreadLocalContext.remove(CURRENT_TRANSACTION_KEY);
jotorren/microservices-transactions-tcc
rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/ChangeStateJpaListener.java
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/context/SpringContext.java // public final class SpringContext { // // private static final Logger LOG = LoggerFactory.getLogger(SpringContext.class); // // private SpringContext() { // } // // public static <T> T getBean(Class<T> clazz) { // // if (null == SpringContextProvider.getApplicationContext()) { // LOG.warn("No application context available"); // return null; // } else { // return SpringContextProvider.getApplicationContext().getBean(clazz); // } // } // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/context/ThreadLocalContext.java // public final class ThreadLocalContext { // // private static final Logger LOG = LoggerFactory.getLogger(ThreadLocalContext.class); // // /** Initial size of the map */ // private static final int HT_SIZE = 5; // // /** Thread local map variable to store any shared object */ // private static final ThreadLocal<Map<String, Object>> THREAD_LOCAL_HOLDER = new ThreadLocal<Map<String, Object>>() { // // protected java.util.Map<String, Object> initialValue() { // return new HashMap<String, Object>(HT_SIZE); // }; // }; // // private ThreadLocalContext() { // } // // public static void put(String key, Object payload) { // if (null == key) { // LOG.error("Unable to put a null key"); // return; // } // // if (null == payload) { // LOG.error("Unable to put a null value"); // return; // } // // THREAD_LOCAL_HOLDER.get().put(key, payload); // } // // public static Object get(String key) { // if (null == key) { // LOG.error("Unable to get a null key"); // return null; // } // // return THREAD_LOCAL_HOLDER.get().get(key); // } // // @SuppressWarnings("unchecked") // public static <T> T get(String key, Class<T> requiredType) { // return (T) get(key); // } // // public static Object remove(String key) { // if (null == key) { // LOG.error("Unable to remove a null key"); // return null; // } // // return THREAD_LOCAL_HOLDER.get().remove(key); // } // // public static void cleanup() { // THREAD_LOCAL_HOLDER.get().clear(); // THREAD_LOCAL_HOLDER.remove(); // } // // public static Map<String, Object> exportContext() { // return THREAD_LOCAL_HOLDER.get(); // } // // public static void importContext(Map<String, Object> context) { // THREAD_LOCAL_HOLDER.get().putAll(context); // } // }
import javax.persistence.PrePersist; import javax.persistence.PreRemove; import javax.persistence.PreUpdate; import net.jotorren.microservices.context.SpringContext; import net.jotorren.microservices.context.ThreadLocalContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package net.jotorren.microservices.tx; public class ChangeStateJpaListener { private static final Logger LOG = LoggerFactory.getLogger(ChangeStateJpaListener.class); private void enlist(Object entity, EntityCommand.Action action, String txId){ EntityCommand<Object> command = new EntityCommand<Object>(); command.setEntity(entity); command.setAction(action); command.setTransactionId(txId); command.setTimestamp(System.currentTimeMillis());
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/context/SpringContext.java // public final class SpringContext { // // private static final Logger LOG = LoggerFactory.getLogger(SpringContext.class); // // private SpringContext() { // } // // public static <T> T getBean(Class<T> clazz) { // // if (null == SpringContextProvider.getApplicationContext()) { // LOG.warn("No application context available"); // return null; // } else { // return SpringContextProvider.getApplicationContext().getBean(clazz); // } // } // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/context/ThreadLocalContext.java // public final class ThreadLocalContext { // // private static final Logger LOG = LoggerFactory.getLogger(ThreadLocalContext.class); // // /** Initial size of the map */ // private static final int HT_SIZE = 5; // // /** Thread local map variable to store any shared object */ // private static final ThreadLocal<Map<String, Object>> THREAD_LOCAL_HOLDER = new ThreadLocal<Map<String, Object>>() { // // protected java.util.Map<String, Object> initialValue() { // return new HashMap<String, Object>(HT_SIZE); // }; // }; // // private ThreadLocalContext() { // } // // public static void put(String key, Object payload) { // if (null == key) { // LOG.error("Unable to put a null key"); // return; // } // // if (null == payload) { // LOG.error("Unable to put a null value"); // return; // } // // THREAD_LOCAL_HOLDER.get().put(key, payload); // } // // public static Object get(String key) { // if (null == key) { // LOG.error("Unable to get a null key"); // return null; // } // // return THREAD_LOCAL_HOLDER.get().get(key); // } // // @SuppressWarnings("unchecked") // public static <T> T get(String key, Class<T> requiredType) { // return (T) get(key); // } // // public static Object remove(String key) { // if (null == key) { // LOG.error("Unable to remove a null key"); // return null; // } // // return THREAD_LOCAL_HOLDER.get().remove(key); // } // // public static void cleanup() { // THREAD_LOCAL_HOLDER.get().clear(); // THREAD_LOCAL_HOLDER.remove(); // } // // public static Map<String, Object> exportContext() { // return THREAD_LOCAL_HOLDER.get(); // } // // public static void importContext(Map<String, Object> context) { // THREAD_LOCAL_HOLDER.get().putAll(context); // } // } // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/ChangeStateJpaListener.java import javax.persistence.PrePersist; import javax.persistence.PreRemove; import javax.persistence.PreUpdate; import net.jotorren.microservices.context.SpringContext; import net.jotorren.microservices.context.ThreadLocalContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package net.jotorren.microservices.tx; public class ChangeStateJpaListener { private static final Logger LOG = LoggerFactory.getLogger(ChangeStateJpaListener.class); private void enlist(Object entity, EntityCommand.Action action, String txId){ EntityCommand<Object> command = new EntityCommand<Object>(); command.setEntity(entity); command.setAction(action); command.setTransactionId(txId); command.setTimestamp(System.currentTimeMillis());
CompositeTransactionManager txManager = SpringContext.getBean(CompositeTransactionManager.class);
jotorren/microservices-transactions-tcc
rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/ChangeStateJpaListener.java
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/context/SpringContext.java // public final class SpringContext { // // private static final Logger LOG = LoggerFactory.getLogger(SpringContext.class); // // private SpringContext() { // } // // public static <T> T getBean(Class<T> clazz) { // // if (null == SpringContextProvider.getApplicationContext()) { // LOG.warn("No application context available"); // return null; // } else { // return SpringContextProvider.getApplicationContext().getBean(clazz); // } // } // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/context/ThreadLocalContext.java // public final class ThreadLocalContext { // // private static final Logger LOG = LoggerFactory.getLogger(ThreadLocalContext.class); // // /** Initial size of the map */ // private static final int HT_SIZE = 5; // // /** Thread local map variable to store any shared object */ // private static final ThreadLocal<Map<String, Object>> THREAD_LOCAL_HOLDER = new ThreadLocal<Map<String, Object>>() { // // protected java.util.Map<String, Object> initialValue() { // return new HashMap<String, Object>(HT_SIZE); // }; // }; // // private ThreadLocalContext() { // } // // public static void put(String key, Object payload) { // if (null == key) { // LOG.error("Unable to put a null key"); // return; // } // // if (null == payload) { // LOG.error("Unable to put a null value"); // return; // } // // THREAD_LOCAL_HOLDER.get().put(key, payload); // } // // public static Object get(String key) { // if (null == key) { // LOG.error("Unable to get a null key"); // return null; // } // // return THREAD_LOCAL_HOLDER.get().get(key); // } // // @SuppressWarnings("unchecked") // public static <T> T get(String key, Class<T> requiredType) { // return (T) get(key); // } // // public static Object remove(String key) { // if (null == key) { // LOG.error("Unable to remove a null key"); // return null; // } // // return THREAD_LOCAL_HOLDER.get().remove(key); // } // // public static void cleanup() { // THREAD_LOCAL_HOLDER.get().clear(); // THREAD_LOCAL_HOLDER.remove(); // } // // public static Map<String, Object> exportContext() { // return THREAD_LOCAL_HOLDER.get(); // } // // public static void importContext(Map<String, Object> context) { // THREAD_LOCAL_HOLDER.get().putAll(context); // } // }
import javax.persistence.PrePersist; import javax.persistence.PreRemove; import javax.persistence.PreUpdate; import net.jotorren.microservices.context.SpringContext; import net.jotorren.microservices.context.ThreadLocalContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package net.jotorren.microservices.tx; public class ChangeStateJpaListener { private static final Logger LOG = LoggerFactory.getLogger(ChangeStateJpaListener.class); private void enlist(Object entity, EntityCommand.Action action, String txId){ EntityCommand<Object> command = new EntityCommand<Object>(); command.setEntity(entity); command.setAction(action); command.setTransactionId(txId); command.setTimestamp(System.currentTimeMillis()); CompositeTransactionManager txManager = SpringContext.getBean(CompositeTransactionManager.class); txManager.enlist(txId, command); } @PrePersist void onPrePersist(Object o) {
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/context/SpringContext.java // public final class SpringContext { // // private static final Logger LOG = LoggerFactory.getLogger(SpringContext.class); // // private SpringContext() { // } // // public static <T> T getBean(Class<T> clazz) { // // if (null == SpringContextProvider.getApplicationContext()) { // LOG.warn("No application context available"); // return null; // } else { // return SpringContextProvider.getApplicationContext().getBean(clazz); // } // } // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/context/ThreadLocalContext.java // public final class ThreadLocalContext { // // private static final Logger LOG = LoggerFactory.getLogger(ThreadLocalContext.class); // // /** Initial size of the map */ // private static final int HT_SIZE = 5; // // /** Thread local map variable to store any shared object */ // private static final ThreadLocal<Map<String, Object>> THREAD_LOCAL_HOLDER = new ThreadLocal<Map<String, Object>>() { // // protected java.util.Map<String, Object> initialValue() { // return new HashMap<String, Object>(HT_SIZE); // }; // }; // // private ThreadLocalContext() { // } // // public static void put(String key, Object payload) { // if (null == key) { // LOG.error("Unable to put a null key"); // return; // } // // if (null == payload) { // LOG.error("Unable to put a null value"); // return; // } // // THREAD_LOCAL_HOLDER.get().put(key, payload); // } // // public static Object get(String key) { // if (null == key) { // LOG.error("Unable to get a null key"); // return null; // } // // return THREAD_LOCAL_HOLDER.get().get(key); // } // // @SuppressWarnings("unchecked") // public static <T> T get(String key, Class<T> requiredType) { // return (T) get(key); // } // // public static Object remove(String key) { // if (null == key) { // LOG.error("Unable to remove a null key"); // return null; // } // // return THREAD_LOCAL_HOLDER.get().remove(key); // } // // public static void cleanup() { // THREAD_LOCAL_HOLDER.get().clear(); // THREAD_LOCAL_HOLDER.remove(); // } // // public static Map<String, Object> exportContext() { // return THREAD_LOCAL_HOLDER.get(); // } // // public static void importContext(Map<String, Object> context) { // THREAD_LOCAL_HOLDER.get().putAll(context); // } // } // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/ChangeStateJpaListener.java import javax.persistence.PrePersist; import javax.persistence.PreRemove; import javax.persistence.PreUpdate; import net.jotorren.microservices.context.SpringContext; import net.jotorren.microservices.context.ThreadLocalContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package net.jotorren.microservices.tx; public class ChangeStateJpaListener { private static final Logger LOG = LoggerFactory.getLogger(ChangeStateJpaListener.class); private void enlist(Object entity, EntityCommand.Action action, String txId){ EntityCommand<Object> command = new EntityCommand<Object>(); command.setEntity(entity); command.setAction(action); command.setTransactionId(txId); command.setTimestamp(System.currentTimeMillis()); CompositeTransactionManager txManager = SpringContext.getBean(CompositeTransactionManager.class); txManager.enlist(txId, command); } @PrePersist void onPrePersist(Object o) {
String txId = (String)ThreadLocalContext.get(CompositeTransactionParticipantService.CURRENT_TRANSACTION_KEY);
jotorren/microservices-transactions-tcc
rahub-source-code-service/src/main/java/net/jotorren/microservices/content/domain/SourceCodeItemSerializer.java
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/AbstractEntityCommandJsonSerializer.java // public abstract class AbstractEntityCommandJsonSerializer<T> implements Serializer<EntityCommand<T>> { // // private ObjectMapper jacksonMapper = new ObjectMapper(); // // public ObjectMapper getJacksonMapper(){ // return jacksonMapper; // } // // @Override // public byte[] write(EntityCommand<T> object) throws SerializationFailedException { // return writeToString(object).getBytes(); // } // // @Override // public String writeToString(EntityCommand<T> object) throws SerializationFailedException { // try { // return jacksonMapper.writeValueAsString(object); // } catch (JsonProcessingException e) { // throw new SerializationFailedException("Error performing EntityCommand serialization", e); // } // } // // @Override // public EntityCommand<T> read(byte[] bytes) throws SerializationFailedException { // return readFromString(new String(bytes)); // } // // @Override // public abstract EntityCommand<T> readFromString(String chars) throws SerializationFailedException; // // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/EntityCommand.java // public class EntityCommand<T> implements Serializable{ // private static final long serialVersionUID = -3927305961526601453L; // // public enum Action { // INSERT, UPDATE, DELETE, QUERY // } // // private T entity; // private Action action; // private String transactionId; // private long timestamp; // // public T getEntity() { // return entity; // } // // public void setEntity(T entity) { // this.entity = entity; // } // // public Action getAction() { // return action; // } // // public void setAction(Action action) { // this.action = action; // } // // public String getTransactionId() { // return transactionId; // } // // public void setTransactionId(String transactionId) { // this.transactionId = transactionId; // } // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // }
import java.io.IOException; import net.jotorren.microservices.tx.AbstractEntityCommandJsonSerializer; import net.jotorren.microservices.tx.EntityCommand; import org.springframework.core.serializer.support.SerializationFailedException; import org.springframework.stereotype.Component; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode;
package net.jotorren.microservices.content.domain; @Component public class SourceCodeItemSerializer extends AbstractEntityCommandJsonSerializer<SourceCodeItem>{ @Override
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/AbstractEntityCommandJsonSerializer.java // public abstract class AbstractEntityCommandJsonSerializer<T> implements Serializer<EntityCommand<T>> { // // private ObjectMapper jacksonMapper = new ObjectMapper(); // // public ObjectMapper getJacksonMapper(){ // return jacksonMapper; // } // // @Override // public byte[] write(EntityCommand<T> object) throws SerializationFailedException { // return writeToString(object).getBytes(); // } // // @Override // public String writeToString(EntityCommand<T> object) throws SerializationFailedException { // try { // return jacksonMapper.writeValueAsString(object); // } catch (JsonProcessingException e) { // throw new SerializationFailedException("Error performing EntityCommand serialization", e); // } // } // // @Override // public EntityCommand<T> read(byte[] bytes) throws SerializationFailedException { // return readFromString(new String(bytes)); // } // // @Override // public abstract EntityCommand<T> readFromString(String chars) throws SerializationFailedException; // // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/EntityCommand.java // public class EntityCommand<T> implements Serializable{ // private static final long serialVersionUID = -3927305961526601453L; // // public enum Action { // INSERT, UPDATE, DELETE, QUERY // } // // private T entity; // private Action action; // private String transactionId; // private long timestamp; // // public T getEntity() { // return entity; // } // // public void setEntity(T entity) { // this.entity = entity; // } // // public Action getAction() { // return action; // } // // public void setAction(Action action) { // this.action = action; // } // // public String getTransactionId() { // return transactionId; // } // // public void setTransactionId(String transactionId) { // this.transactionId = transactionId; // } // // public long getTimestamp() { // return timestamp; // } // // public void setTimestamp(long timestamp) { // this.timestamp = timestamp; // } // } // Path: rahub-source-code-service/src/main/java/net/jotorren/microservices/content/domain/SourceCodeItemSerializer.java import java.io.IOException; import net.jotorren.microservices.tx.AbstractEntityCommandJsonSerializer; import net.jotorren.microservices.tx.EntityCommand; import org.springframework.core.serializer.support.SerializationFailedException; import org.springframework.stereotype.Component; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; package net.jotorren.microservices.content.domain; @Component public class SourceCodeItemSerializer extends AbstractEntityCommandJsonSerializer<SourceCodeItem>{ @Override
public EntityCommand<SourceCodeItem> readFromString(String chars)
jotorren/microservices-transactions-tcc
rahub-composite-service/src/main/java/net/jotorren/microservices/configuration/CompositeTransactionConfiguration.java
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionManager.java // public interface CompositeTransactionManager { // // void open(String txId); // void enlist(String txId, EntityCommand<?> ec); // List<EntityCommand<?>> fetch(String txId); // void close(String txId); // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/impl/CompositeTransactionManagerKafkaImpl.java // public class CompositeTransactionManagerKafkaImpl implements CompositeTransactionManager { // // private static final Logger LOG = LoggerFactory.getLogger(CompositeTransactionManager.class); // // @Value("${zookeeper.partitions:0}") // private int zooPartitions; // // @Value("${zookeeper.replication:0}") // private int zooReplication; // // @Value("${kafka.consumer.poll.timeout:0}") // private long kafkaConsumerPollTimeout; // // // @Autowired(required = false) // private ZkUtils zkUtils; // // @Autowired(required = false) // private KafkaTemplate<Integer, String> kafkaTemplate; // // @Autowired(required = false) // @Qualifier("kafkaConsumerConfiguration") // private Map<String, Object> configuration; // // @Autowired(required = false) // private Serializer<EntityCommand<?>> serializer; // // @Override // public void open(String txId) { // // Add topic configuration here // Properties topicConfig = new Properties(); // // AdminUtils.createTopic(zkUtils, txId, zooPartitions, zooReplication, topicConfig, RackAwareMode.Enforced$.MODULE$); // } // // @Override // public void enlist(String txId, EntityCommand<?> command) { // kafkaTemplate.send(txId, serializer.writeToString(command)); // } // // @SuppressWarnings("unchecked") // @Override // public List<EntityCommand<?>> fetch(String txId) { // List<EntityCommand<?>> transactionOperations = new ArrayList<EntityCommand<?>>(); // // Map<String, Object> consumerConfigs = (Map<String, Object>)configuration.get("kafkaConsumerConfiguration"); // consumerConfigs.put(ConsumerConfig.GROUP_ID_CONFIG, UUID.randomUUID().toString()); // // KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<String, String>(consumerConfigs); // kafkaConsumer.subscribe(Arrays.asList(txId)); // // ConsumerRecords<String, String> records = kafkaConsumer.poll(kafkaConsumerPollTimeout); // for (ConsumerRecord<String, String> record : records){ // LOG.info("offset = {}, key = {}, value = {}", record.offset(), record.key(), record.value()); // try { // transactionOperations.add(serializer.readFromString(record.value())); // } catch (SerializationFailedException e) { // LOG.error("Unable to deserialize [{}] because of: {}", record.value(), e.getMessage()); // } // } // // kafkaConsumer.close(); // // return transactionOperations; // } // // @Override // public void close(String txId) { // AdminUtils.deleteTopic(zkUtils, txId); // } // }
import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import kafka.utils.ZKStringSerializer$; import kafka.utils.ZkUtils; import net.jotorren.microservices.tx.CompositeTransactionManager; import net.jotorren.microservices.tx.impl.CompositeTransactionManagerKafkaImpl; import org.I0Itec.zkclient.ZkClient; import org.I0Itec.zkclient.ZkConnection; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.atomikos.icatch.tcc.rest.CoordinatorImp; import com.atomikos.icatch.tcc.rest.TransactionProvider; import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
package net.jotorren.microservices.configuration; @Configuration public class CompositeTransactionConfiguration { @Value("${tcc.service.base.url}") private String tccCoordinatorBaseUrl; @Value("${zookeeper.servers}") private String zooServers; @Value("${zookeeper.session.timeout}") private int zooSessionTimeout; @Value("${zookeeper.connection.timeout}") private int zooConnectionTimeout; @Bean public CoordinatorImp tccCoordinatorService() { return new CoordinatorImp(); } @Bean public WebTarget tccCoordinatorClient() { Client client = ClientBuilder.newClient(); client.register(new JacksonJaxbJsonProvider()); client.register(new TransactionProvider()); WebTarget target = client.target(tccCoordinatorBaseUrl); return target.path("/coordinator"); } @Bean
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionManager.java // public interface CompositeTransactionManager { // // void open(String txId); // void enlist(String txId, EntityCommand<?> ec); // List<EntityCommand<?>> fetch(String txId); // void close(String txId); // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/impl/CompositeTransactionManagerKafkaImpl.java // public class CompositeTransactionManagerKafkaImpl implements CompositeTransactionManager { // // private static final Logger LOG = LoggerFactory.getLogger(CompositeTransactionManager.class); // // @Value("${zookeeper.partitions:0}") // private int zooPartitions; // // @Value("${zookeeper.replication:0}") // private int zooReplication; // // @Value("${kafka.consumer.poll.timeout:0}") // private long kafkaConsumerPollTimeout; // // // @Autowired(required = false) // private ZkUtils zkUtils; // // @Autowired(required = false) // private KafkaTemplate<Integer, String> kafkaTemplate; // // @Autowired(required = false) // @Qualifier("kafkaConsumerConfiguration") // private Map<String, Object> configuration; // // @Autowired(required = false) // private Serializer<EntityCommand<?>> serializer; // // @Override // public void open(String txId) { // // Add topic configuration here // Properties topicConfig = new Properties(); // // AdminUtils.createTopic(zkUtils, txId, zooPartitions, zooReplication, topicConfig, RackAwareMode.Enforced$.MODULE$); // } // // @Override // public void enlist(String txId, EntityCommand<?> command) { // kafkaTemplate.send(txId, serializer.writeToString(command)); // } // // @SuppressWarnings("unchecked") // @Override // public List<EntityCommand<?>> fetch(String txId) { // List<EntityCommand<?>> transactionOperations = new ArrayList<EntityCommand<?>>(); // // Map<String, Object> consumerConfigs = (Map<String, Object>)configuration.get("kafkaConsumerConfiguration"); // consumerConfigs.put(ConsumerConfig.GROUP_ID_CONFIG, UUID.randomUUID().toString()); // // KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<String, String>(consumerConfigs); // kafkaConsumer.subscribe(Arrays.asList(txId)); // // ConsumerRecords<String, String> records = kafkaConsumer.poll(kafkaConsumerPollTimeout); // for (ConsumerRecord<String, String> record : records){ // LOG.info("offset = {}, key = {}, value = {}", record.offset(), record.key(), record.value()); // try { // transactionOperations.add(serializer.readFromString(record.value())); // } catch (SerializationFailedException e) { // LOG.error("Unable to deserialize [{}] because of: {}", record.value(), e.getMessage()); // } // } // // kafkaConsumer.close(); // // return transactionOperations; // } // // @Override // public void close(String txId) { // AdminUtils.deleteTopic(zkUtils, txId); // } // } // Path: rahub-composite-service/src/main/java/net/jotorren/microservices/configuration/CompositeTransactionConfiguration.java import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import kafka.utils.ZKStringSerializer$; import kafka.utils.ZkUtils; import net.jotorren.microservices.tx.CompositeTransactionManager; import net.jotorren.microservices.tx.impl.CompositeTransactionManagerKafkaImpl; import org.I0Itec.zkclient.ZkClient; import org.I0Itec.zkclient.ZkConnection; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.atomikos.icatch.tcc.rest.CoordinatorImp; import com.atomikos.icatch.tcc.rest.TransactionProvider; import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; package net.jotorren.microservices.configuration; @Configuration public class CompositeTransactionConfiguration { @Value("${tcc.service.base.url}") private String tccCoordinatorBaseUrl; @Value("${zookeeper.servers}") private String zooServers; @Value("${zookeeper.session.timeout}") private int zooSessionTimeout; @Value("${zookeeper.connection.timeout}") private int zooConnectionTimeout; @Bean public CoordinatorImp tccCoordinatorService() { return new CoordinatorImp(); } @Bean public WebTarget tccCoordinatorClient() { Client client = ClientBuilder.newClient(); client.register(new JacksonJaxbJsonProvider()); client.register(new TransactionProvider()); WebTarget target = client.target(tccCoordinatorBaseUrl); return target.path("/coordinator"); } @Bean
public CompositeTransactionManager compositeTransactionManager() {
jotorren/microservices-transactions-tcc
rahub-composite-service/src/main/java/net/jotorren/microservices/configuration/CompositeTransactionConfiguration.java
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionManager.java // public interface CompositeTransactionManager { // // void open(String txId); // void enlist(String txId, EntityCommand<?> ec); // List<EntityCommand<?>> fetch(String txId); // void close(String txId); // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/impl/CompositeTransactionManagerKafkaImpl.java // public class CompositeTransactionManagerKafkaImpl implements CompositeTransactionManager { // // private static final Logger LOG = LoggerFactory.getLogger(CompositeTransactionManager.class); // // @Value("${zookeeper.partitions:0}") // private int zooPartitions; // // @Value("${zookeeper.replication:0}") // private int zooReplication; // // @Value("${kafka.consumer.poll.timeout:0}") // private long kafkaConsumerPollTimeout; // // // @Autowired(required = false) // private ZkUtils zkUtils; // // @Autowired(required = false) // private KafkaTemplate<Integer, String> kafkaTemplate; // // @Autowired(required = false) // @Qualifier("kafkaConsumerConfiguration") // private Map<String, Object> configuration; // // @Autowired(required = false) // private Serializer<EntityCommand<?>> serializer; // // @Override // public void open(String txId) { // // Add topic configuration here // Properties topicConfig = new Properties(); // // AdminUtils.createTopic(zkUtils, txId, zooPartitions, zooReplication, topicConfig, RackAwareMode.Enforced$.MODULE$); // } // // @Override // public void enlist(String txId, EntityCommand<?> command) { // kafkaTemplate.send(txId, serializer.writeToString(command)); // } // // @SuppressWarnings("unchecked") // @Override // public List<EntityCommand<?>> fetch(String txId) { // List<EntityCommand<?>> transactionOperations = new ArrayList<EntityCommand<?>>(); // // Map<String, Object> consumerConfigs = (Map<String, Object>)configuration.get("kafkaConsumerConfiguration"); // consumerConfigs.put(ConsumerConfig.GROUP_ID_CONFIG, UUID.randomUUID().toString()); // // KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<String, String>(consumerConfigs); // kafkaConsumer.subscribe(Arrays.asList(txId)); // // ConsumerRecords<String, String> records = kafkaConsumer.poll(kafkaConsumerPollTimeout); // for (ConsumerRecord<String, String> record : records){ // LOG.info("offset = {}, key = {}, value = {}", record.offset(), record.key(), record.value()); // try { // transactionOperations.add(serializer.readFromString(record.value())); // } catch (SerializationFailedException e) { // LOG.error("Unable to deserialize [{}] because of: {}", record.value(), e.getMessage()); // } // } // // kafkaConsumer.close(); // // return transactionOperations; // } // // @Override // public void close(String txId) { // AdminUtils.deleteTopic(zkUtils, txId); // } // }
import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import kafka.utils.ZKStringSerializer$; import kafka.utils.ZkUtils; import net.jotorren.microservices.tx.CompositeTransactionManager; import net.jotorren.microservices.tx.impl.CompositeTransactionManagerKafkaImpl; import org.I0Itec.zkclient.ZkClient; import org.I0Itec.zkclient.ZkConnection; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.atomikos.icatch.tcc.rest.CoordinatorImp; import com.atomikos.icatch.tcc.rest.TransactionProvider; import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
package net.jotorren.microservices.configuration; @Configuration public class CompositeTransactionConfiguration { @Value("${tcc.service.base.url}") private String tccCoordinatorBaseUrl; @Value("${zookeeper.servers}") private String zooServers; @Value("${zookeeper.session.timeout}") private int zooSessionTimeout; @Value("${zookeeper.connection.timeout}") private int zooConnectionTimeout; @Bean public CoordinatorImp tccCoordinatorService() { return new CoordinatorImp(); } @Bean public WebTarget tccCoordinatorClient() { Client client = ClientBuilder.newClient(); client.register(new JacksonJaxbJsonProvider()); client.register(new TransactionProvider()); WebTarget target = client.target(tccCoordinatorBaseUrl); return target.path("/coordinator"); } @Bean public CompositeTransactionManager compositeTransactionManager() {
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionManager.java // public interface CompositeTransactionManager { // // void open(String txId); // void enlist(String txId, EntityCommand<?> ec); // List<EntityCommand<?>> fetch(String txId); // void close(String txId); // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/impl/CompositeTransactionManagerKafkaImpl.java // public class CompositeTransactionManagerKafkaImpl implements CompositeTransactionManager { // // private static final Logger LOG = LoggerFactory.getLogger(CompositeTransactionManager.class); // // @Value("${zookeeper.partitions:0}") // private int zooPartitions; // // @Value("${zookeeper.replication:0}") // private int zooReplication; // // @Value("${kafka.consumer.poll.timeout:0}") // private long kafkaConsumerPollTimeout; // // // @Autowired(required = false) // private ZkUtils zkUtils; // // @Autowired(required = false) // private KafkaTemplate<Integer, String> kafkaTemplate; // // @Autowired(required = false) // @Qualifier("kafkaConsumerConfiguration") // private Map<String, Object> configuration; // // @Autowired(required = false) // private Serializer<EntityCommand<?>> serializer; // // @Override // public void open(String txId) { // // Add topic configuration here // Properties topicConfig = new Properties(); // // AdminUtils.createTopic(zkUtils, txId, zooPartitions, zooReplication, topicConfig, RackAwareMode.Enforced$.MODULE$); // } // // @Override // public void enlist(String txId, EntityCommand<?> command) { // kafkaTemplate.send(txId, serializer.writeToString(command)); // } // // @SuppressWarnings("unchecked") // @Override // public List<EntityCommand<?>> fetch(String txId) { // List<EntityCommand<?>> transactionOperations = new ArrayList<EntityCommand<?>>(); // // Map<String, Object> consumerConfigs = (Map<String, Object>)configuration.get("kafkaConsumerConfiguration"); // consumerConfigs.put(ConsumerConfig.GROUP_ID_CONFIG, UUID.randomUUID().toString()); // // KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<String, String>(consumerConfigs); // kafkaConsumer.subscribe(Arrays.asList(txId)); // // ConsumerRecords<String, String> records = kafkaConsumer.poll(kafkaConsumerPollTimeout); // for (ConsumerRecord<String, String> record : records){ // LOG.info("offset = {}, key = {}, value = {}", record.offset(), record.key(), record.value()); // try { // transactionOperations.add(serializer.readFromString(record.value())); // } catch (SerializationFailedException e) { // LOG.error("Unable to deserialize [{}] because of: {}", record.value(), e.getMessage()); // } // } // // kafkaConsumer.close(); // // return transactionOperations; // } // // @Override // public void close(String txId) { // AdminUtils.deleteTopic(zkUtils, txId); // } // } // Path: rahub-composite-service/src/main/java/net/jotorren/microservices/configuration/CompositeTransactionConfiguration.java import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import kafka.utils.ZKStringSerializer$; import kafka.utils.ZkUtils; import net.jotorren.microservices.tx.CompositeTransactionManager; import net.jotorren.microservices.tx.impl.CompositeTransactionManagerKafkaImpl; import org.I0Itec.zkclient.ZkClient; import org.I0Itec.zkclient.ZkConnection; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.atomikos.icatch.tcc.rest.CoordinatorImp; import com.atomikos.icatch.tcc.rest.TransactionProvider; import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; package net.jotorren.microservices.configuration; @Configuration public class CompositeTransactionConfiguration { @Value("${tcc.service.base.url}") private String tccCoordinatorBaseUrl; @Value("${zookeeper.servers}") private String zooServers; @Value("${zookeeper.session.timeout}") private int zooSessionTimeout; @Value("${zookeeper.connection.timeout}") private int zooConnectionTimeout; @Bean public CoordinatorImp tccCoordinatorService() { return new CoordinatorImp(); } @Bean public WebTarget tccCoordinatorClient() { Client client = ClientBuilder.newClient(); client.register(new JacksonJaxbJsonProvider()); client.register(new TransactionProvider()); WebTarget target = client.target(tccCoordinatorBaseUrl); return target.path("/coordinator"); } @Bean public CompositeTransactionManager compositeTransactionManager() {
return new CompositeTransactionManagerKafkaImpl();
jotorren/microservices-transactions-tcc
rahub-source-code-service/src/main/java/net/jotorren/microservices/content/dao/ContentTransactionAwareDao.java
// Path: rahub-source-code-service/src/main/java/net/jotorren/microservices/content/domain/SourceCodeItem.java // @Entity // public class SourceCodeItem implements Serializable { // private static final long serialVersionUID = 7803210035898675537L; // // @Id // @Column(nullable=false) // private String itemId; // // @Column(nullable=false) // private String fileName; // // @Column(nullable=false) // private String fileLocation; // // @Column // private String fileContent; // // @Column // private String fileDescription; // // @Column(nullable=false) // private String fileOwner; // // public String getFileName() { // return fileName; // } // // public void setFileName(String fileName) { // this.fileName = fileName; // } // // public String getFileLocation() { // return fileLocation; // } // // public void setFileLocation(String fileLocation) { // this.fileLocation = fileLocation; // } // // public String getFileContent() { // return fileContent; // } // // public void setFileContent(String fileContent) { // this.fileContent = fileContent; // } // // public String getFileDescription() { // return fileDescription; // } // // public void setFileDescription(String fileDescription) { // this.fileDescription = fileDescription; // } // // public String getFileOwner() { // return fileOwner; // } // // public void setFileOwner(String fileOwner) { // this.fileOwner = fileOwner; // } // // public String getItemId() { // return itemId; // } // // public void setItemId(String itemId) { // this.itemId = itemId; // } // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionParticipantDao.java // public class CompositeTransactionParticipantDao { // // @PersistenceContext(type = PersistenceContextType.EXTENDED, synchronization = SynchronizationType.UNSYNCHRONIZED) // private EntityManager em; // // public EntityManager getEntityManager() { // return em; // } // // public void save(Object entity) { // em.persist(entity); // } // // public <T> T saveOrUpdate(T entity) { // return em.merge(entity); // } // // public void remove(Object entity) { // em.remove(entity); // } // // @Transactional(readOnly=false) // public void commit() { // em.joinTransaction(); // } // // public void apply(List<EntityCommand<?>> transactionOperations) { // if (null == transactionOperations) { // return; // } // // for (EntityCommand<?> command : transactionOperations) { // switch (command.getAction().ordinal()) { // case 0: // save(command.getEntity()); // break; // case 1: // saveOrUpdate(command.getEntity()); // break; // case 2: // remove(command.getEntity()); // break; // } // } // } // }
import net.jotorren.microservices.content.domain.SourceCodeItem; import net.jotorren.microservices.tx.CompositeTransactionParticipantDao; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Repository;
package net.jotorren.microservices.content.dao; @Repository @Scope("prototype")
// Path: rahub-source-code-service/src/main/java/net/jotorren/microservices/content/domain/SourceCodeItem.java // @Entity // public class SourceCodeItem implements Serializable { // private static final long serialVersionUID = 7803210035898675537L; // // @Id // @Column(nullable=false) // private String itemId; // // @Column(nullable=false) // private String fileName; // // @Column(nullable=false) // private String fileLocation; // // @Column // private String fileContent; // // @Column // private String fileDescription; // // @Column(nullable=false) // private String fileOwner; // // public String getFileName() { // return fileName; // } // // public void setFileName(String fileName) { // this.fileName = fileName; // } // // public String getFileLocation() { // return fileLocation; // } // // public void setFileLocation(String fileLocation) { // this.fileLocation = fileLocation; // } // // public String getFileContent() { // return fileContent; // } // // public void setFileContent(String fileContent) { // this.fileContent = fileContent; // } // // public String getFileDescription() { // return fileDescription; // } // // public void setFileDescription(String fileDescription) { // this.fileDescription = fileDescription; // } // // public String getFileOwner() { // return fileOwner; // } // // public void setFileOwner(String fileOwner) { // this.fileOwner = fileOwner; // } // // public String getItemId() { // return itemId; // } // // public void setItemId(String itemId) { // this.itemId = itemId; // } // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionParticipantDao.java // public class CompositeTransactionParticipantDao { // // @PersistenceContext(type = PersistenceContextType.EXTENDED, synchronization = SynchronizationType.UNSYNCHRONIZED) // private EntityManager em; // // public EntityManager getEntityManager() { // return em; // } // // public void save(Object entity) { // em.persist(entity); // } // // public <T> T saveOrUpdate(T entity) { // return em.merge(entity); // } // // public void remove(Object entity) { // em.remove(entity); // } // // @Transactional(readOnly=false) // public void commit() { // em.joinTransaction(); // } // // public void apply(List<EntityCommand<?>> transactionOperations) { // if (null == transactionOperations) { // return; // } // // for (EntityCommand<?> command : transactionOperations) { // switch (command.getAction().ordinal()) { // case 0: // save(command.getEntity()); // break; // case 1: // saveOrUpdate(command.getEntity()); // break; // case 2: // remove(command.getEntity()); // break; // } // } // } // } // Path: rahub-source-code-service/src/main/java/net/jotorren/microservices/content/dao/ContentTransactionAwareDao.java import net.jotorren.microservices.content.domain.SourceCodeItem; import net.jotorren.microservices.tx.CompositeTransactionParticipantDao; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Repository; package net.jotorren.microservices.content.dao; @Repository @Scope("prototype")
public class ContentTransactionAwareDao extends CompositeTransactionParticipantDao{
jotorren/microservices-transactions-tcc
rahub-source-code-service/src/main/java/net/jotorren/microservices/content/dao/ContentTransactionAwareDao.java
// Path: rahub-source-code-service/src/main/java/net/jotorren/microservices/content/domain/SourceCodeItem.java // @Entity // public class SourceCodeItem implements Serializable { // private static final long serialVersionUID = 7803210035898675537L; // // @Id // @Column(nullable=false) // private String itemId; // // @Column(nullable=false) // private String fileName; // // @Column(nullable=false) // private String fileLocation; // // @Column // private String fileContent; // // @Column // private String fileDescription; // // @Column(nullable=false) // private String fileOwner; // // public String getFileName() { // return fileName; // } // // public void setFileName(String fileName) { // this.fileName = fileName; // } // // public String getFileLocation() { // return fileLocation; // } // // public void setFileLocation(String fileLocation) { // this.fileLocation = fileLocation; // } // // public String getFileContent() { // return fileContent; // } // // public void setFileContent(String fileContent) { // this.fileContent = fileContent; // } // // public String getFileDescription() { // return fileDescription; // } // // public void setFileDescription(String fileDescription) { // this.fileDescription = fileDescription; // } // // public String getFileOwner() { // return fileOwner; // } // // public void setFileOwner(String fileOwner) { // this.fileOwner = fileOwner; // } // // public String getItemId() { // return itemId; // } // // public void setItemId(String itemId) { // this.itemId = itemId; // } // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionParticipantDao.java // public class CompositeTransactionParticipantDao { // // @PersistenceContext(type = PersistenceContextType.EXTENDED, synchronization = SynchronizationType.UNSYNCHRONIZED) // private EntityManager em; // // public EntityManager getEntityManager() { // return em; // } // // public void save(Object entity) { // em.persist(entity); // } // // public <T> T saveOrUpdate(T entity) { // return em.merge(entity); // } // // public void remove(Object entity) { // em.remove(entity); // } // // @Transactional(readOnly=false) // public void commit() { // em.joinTransaction(); // } // // public void apply(List<EntityCommand<?>> transactionOperations) { // if (null == transactionOperations) { // return; // } // // for (EntityCommand<?> command : transactionOperations) { // switch (command.getAction().ordinal()) { // case 0: // save(command.getEntity()); // break; // case 1: // saveOrUpdate(command.getEntity()); // break; // case 2: // remove(command.getEntity()); // break; // } // } // } // }
import net.jotorren.microservices.content.domain.SourceCodeItem; import net.jotorren.microservices.tx.CompositeTransactionParticipantDao; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Repository;
package net.jotorren.microservices.content.dao; @Repository @Scope("prototype") public class ContentTransactionAwareDao extends CompositeTransactionParticipantDao{
// Path: rahub-source-code-service/src/main/java/net/jotorren/microservices/content/domain/SourceCodeItem.java // @Entity // public class SourceCodeItem implements Serializable { // private static final long serialVersionUID = 7803210035898675537L; // // @Id // @Column(nullable=false) // private String itemId; // // @Column(nullable=false) // private String fileName; // // @Column(nullable=false) // private String fileLocation; // // @Column // private String fileContent; // // @Column // private String fileDescription; // // @Column(nullable=false) // private String fileOwner; // // public String getFileName() { // return fileName; // } // // public void setFileName(String fileName) { // this.fileName = fileName; // } // // public String getFileLocation() { // return fileLocation; // } // // public void setFileLocation(String fileLocation) { // this.fileLocation = fileLocation; // } // // public String getFileContent() { // return fileContent; // } // // public void setFileContent(String fileContent) { // this.fileContent = fileContent; // } // // public String getFileDescription() { // return fileDescription; // } // // public void setFileDescription(String fileDescription) { // this.fileDescription = fileDescription; // } // // public String getFileOwner() { // return fileOwner; // } // // public void setFileOwner(String fileOwner) { // this.fileOwner = fileOwner; // } // // public String getItemId() { // return itemId; // } // // public void setItemId(String itemId) { // this.itemId = itemId; // } // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionParticipantDao.java // public class CompositeTransactionParticipantDao { // // @PersistenceContext(type = PersistenceContextType.EXTENDED, synchronization = SynchronizationType.UNSYNCHRONIZED) // private EntityManager em; // // public EntityManager getEntityManager() { // return em; // } // // public void save(Object entity) { // em.persist(entity); // } // // public <T> T saveOrUpdate(T entity) { // return em.merge(entity); // } // // public void remove(Object entity) { // em.remove(entity); // } // // @Transactional(readOnly=false) // public void commit() { // em.joinTransaction(); // } // // public void apply(List<EntityCommand<?>> transactionOperations) { // if (null == transactionOperations) { // return; // } // // for (EntityCommand<?> command : transactionOperations) { // switch (command.getAction().ordinal()) { // case 0: // save(command.getEntity()); // break; // case 1: // saveOrUpdate(command.getEntity()); // break; // case 2: // remove(command.getEntity()); // break; // } // } // } // } // Path: rahub-source-code-service/src/main/java/net/jotorren/microservices/content/dao/ContentTransactionAwareDao.java import net.jotorren.microservices.content.domain.SourceCodeItem; import net.jotorren.microservices.tx.CompositeTransactionParticipantDao; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Repository; package net.jotorren.microservices.content.dao; @Repository @Scope("prototype") public class ContentTransactionAwareDao extends CompositeTransactionParticipantDao{
public SourceCodeItem findOne(String pk){
jotorren/microservices-transactions-tcc
rahub-composite-service/src/main/java/net/jotorren/microservices/tcc/TccRestCoordinator.java
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransaction.java // public class CompositeTransaction extends Transaction { // // @JsonIgnore // private String id; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getPartialTransactionId(int index) { // if (index < 0 || null == participantLinks || index >= participantLinks.size()){ // return null; // } // // String participantUri = participantLinks.get(index).getUri(); // return participantUri.substring(participantUri.lastIndexOf("/") + 1); // } // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionManager.java // public interface CompositeTransactionManager { // // void open(String txId); // void enlist(String txId, EntityCommand<?> ec); // List<EntityCommand<?>> fetch(String txId); // void close(String txId); // }
import java.util.ArrayList; import java.util.List; import java.util.UUID; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Response; import net.jotorren.microservices.tx.CompositeTransaction; import net.jotorren.microservices.tx.CompositeTransactionManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import com.atomikos.tcc.rest.ParticipantLink; import com.atomikos.tcc.rest.Transaction;
package net.jotorren.microservices.tcc; @Service public class TccRestCoordinator { @Autowired @Qualifier("tccCoordinatorClient") private WebTarget tccCoordinatorClient; @Autowired
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransaction.java // public class CompositeTransaction extends Transaction { // // @JsonIgnore // private String id; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getPartialTransactionId(int index) { // if (index < 0 || null == participantLinks || index >= participantLinks.size()){ // return null; // } // // String participantUri = participantLinks.get(index).getUri(); // return participantUri.substring(participantUri.lastIndexOf("/") + 1); // } // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionManager.java // public interface CompositeTransactionManager { // // void open(String txId); // void enlist(String txId, EntityCommand<?> ec); // List<EntityCommand<?>> fetch(String txId); // void close(String txId); // } // Path: rahub-composite-service/src/main/java/net/jotorren/microservices/tcc/TccRestCoordinator.java import java.util.ArrayList; import java.util.List; import java.util.UUID; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Response; import net.jotorren.microservices.tx.CompositeTransaction; import net.jotorren.microservices.tx.CompositeTransactionManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import com.atomikos.tcc.rest.ParticipantLink; import com.atomikos.tcc.rest.Transaction; package net.jotorren.microservices.tcc; @Service public class TccRestCoordinator { @Autowired @Qualifier("tccCoordinatorClient") private WebTarget tccCoordinatorClient; @Autowired
private CompositeTransactionManager txManager;
jotorren/microservices-transactions-tcc
rahub-composite-service/src/main/java/net/jotorren/microservices/tcc/TccRestCoordinator.java
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransaction.java // public class CompositeTransaction extends Transaction { // // @JsonIgnore // private String id; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getPartialTransactionId(int index) { // if (index < 0 || null == participantLinks || index >= participantLinks.size()){ // return null; // } // // String participantUri = participantLinks.get(index).getUri(); // return participantUri.substring(participantUri.lastIndexOf("/") + 1); // } // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionManager.java // public interface CompositeTransactionManager { // // void open(String txId); // void enlist(String txId, EntityCommand<?> ec); // List<EntityCommand<?>> fetch(String txId); // void close(String txId); // }
import java.util.ArrayList; import java.util.List; import java.util.UUID; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Response; import net.jotorren.microservices.tx.CompositeTransaction; import net.jotorren.microservices.tx.CompositeTransactionManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import com.atomikos.tcc.rest.ParticipantLink; import com.atomikos.tcc.rest.Transaction;
package net.jotorren.microservices.tcc; @Service public class TccRestCoordinator { @Autowired @Qualifier("tccCoordinatorClient") private WebTarget tccCoordinatorClient; @Autowired private CompositeTransactionManager txManager;
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransaction.java // public class CompositeTransaction extends Transaction { // // @JsonIgnore // private String id; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getPartialTransactionId(int index) { // if (index < 0 || null == participantLinks || index >= participantLinks.size()){ // return null; // } // // String participantUri = participantLinks.get(index).getUri(); // return participantUri.substring(participantUri.lastIndexOf("/") + 1); // } // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionManager.java // public interface CompositeTransactionManager { // // void open(String txId); // void enlist(String txId, EntityCommand<?> ec); // List<EntityCommand<?>> fetch(String txId); // void close(String txId); // } // Path: rahub-composite-service/src/main/java/net/jotorren/microservices/tcc/TccRestCoordinator.java import java.util.ArrayList; import java.util.List; import java.util.UUID; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Response; import net.jotorren.microservices.tx.CompositeTransaction; import net.jotorren.microservices.tx.CompositeTransactionManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import com.atomikos.tcc.rest.ParticipantLink; import com.atomikos.tcc.rest.Transaction; package net.jotorren.microservices.tcc; @Service public class TccRestCoordinator { @Autowired @Qualifier("tccCoordinatorClient") private WebTarget tccCoordinatorClient; @Autowired private CompositeTransactionManager txManager;
public CompositeTransaction open(long timestamp, String... participantUris){
jotorren/microservices-transactions-tcc
rahub-source-code-service/src/main/java/net/jotorren/microservices/content/configuration/CompositeTransactionConfiguration.java
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/context/SpringContextProvider.java // public class SpringContextProvider implements ApplicationContextAware { // private static ApplicationContext ctx = null; // // public static ApplicationContext getApplicationContext() { // return ctx; // } // // public void setApplicationContext(ApplicationContext ctx) { // SpringContextProvider.ctx = ctx; // } // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionManager.java // public interface CompositeTransactionManager { // // void open(String txId); // void enlist(String txId, EntityCommand<?> ec); // List<EntityCommand<?>> fetch(String txId); // void close(String txId); // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/impl/CompositeTransactionManagerKafkaImpl.java // public class CompositeTransactionManagerKafkaImpl implements CompositeTransactionManager { // // private static final Logger LOG = LoggerFactory.getLogger(CompositeTransactionManager.class); // // @Value("${zookeeper.partitions:0}") // private int zooPartitions; // // @Value("${zookeeper.replication:0}") // private int zooReplication; // // @Value("${kafka.consumer.poll.timeout:0}") // private long kafkaConsumerPollTimeout; // // // @Autowired(required = false) // private ZkUtils zkUtils; // // @Autowired(required = false) // private KafkaTemplate<Integer, String> kafkaTemplate; // // @Autowired(required = false) // @Qualifier("kafkaConsumerConfiguration") // private Map<String, Object> configuration; // // @Autowired(required = false) // private Serializer<EntityCommand<?>> serializer; // // @Override // public void open(String txId) { // // Add topic configuration here // Properties topicConfig = new Properties(); // // AdminUtils.createTopic(zkUtils, txId, zooPartitions, zooReplication, topicConfig, RackAwareMode.Enforced$.MODULE$); // } // // @Override // public void enlist(String txId, EntityCommand<?> command) { // kafkaTemplate.send(txId, serializer.writeToString(command)); // } // // @SuppressWarnings("unchecked") // @Override // public List<EntityCommand<?>> fetch(String txId) { // List<EntityCommand<?>> transactionOperations = new ArrayList<EntityCommand<?>>(); // // Map<String, Object> consumerConfigs = (Map<String, Object>)configuration.get("kafkaConsumerConfiguration"); // consumerConfigs.put(ConsumerConfig.GROUP_ID_CONFIG, UUID.randomUUID().toString()); // // KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<String, String>(consumerConfigs); // kafkaConsumer.subscribe(Arrays.asList(txId)); // // ConsumerRecords<String, String> records = kafkaConsumer.poll(kafkaConsumerPollTimeout); // for (ConsumerRecord<String, String> record : records){ // LOG.info("offset = {}, key = {}, value = {}", record.offset(), record.key(), record.value()); // try { // transactionOperations.add(serializer.readFromString(record.value())); // } catch (SerializationFailedException e) { // LOG.error("Unable to deserialize [{}] because of: {}", record.value(), e.getMessage()); // } // } // // kafkaConsumer.close(); // // return transactionOperations; // } // // @Override // public void close(String txId) { // AdminUtils.deleteTopic(zkUtils, txId); // } // }
import java.util.HashMap; import java.util.Map; import net.jotorren.microservices.context.SpringContextProvider; import net.jotorren.microservices.tx.CompositeTransactionManager; import net.jotorren.microservices.tx.impl.CompositeTransactionManagerKafkaImpl; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.serialization.StringDeserializer; import org.apache.kafka.common.serialization.StringSerializer; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.kafka.core.DefaultKafkaProducerFactory; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.core.ProducerFactory;
package net.jotorren.microservices.content.configuration; @Configuration public class CompositeTransactionConfiguration { @Value("${kafka.bootstrap-servers}") private String kafkaBootstrapServers; @Value("${kafka.consumer.enable.auto.commit}") private String kafkaEnableAutoCommit; @Value("${kafka.consumer.auto.commit.interval}") private String kafkaAutoCommitInterval; @Value("${kafka.consumer.session.timeout}") private String kafkaSessionTimeout; @Value("${kafka.consumer.auto.offset.reset}") private String kafkaAutoOffsetReset; @Bean
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/context/SpringContextProvider.java // public class SpringContextProvider implements ApplicationContextAware { // private static ApplicationContext ctx = null; // // public static ApplicationContext getApplicationContext() { // return ctx; // } // // public void setApplicationContext(ApplicationContext ctx) { // SpringContextProvider.ctx = ctx; // } // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionManager.java // public interface CompositeTransactionManager { // // void open(String txId); // void enlist(String txId, EntityCommand<?> ec); // List<EntityCommand<?>> fetch(String txId); // void close(String txId); // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/impl/CompositeTransactionManagerKafkaImpl.java // public class CompositeTransactionManagerKafkaImpl implements CompositeTransactionManager { // // private static final Logger LOG = LoggerFactory.getLogger(CompositeTransactionManager.class); // // @Value("${zookeeper.partitions:0}") // private int zooPartitions; // // @Value("${zookeeper.replication:0}") // private int zooReplication; // // @Value("${kafka.consumer.poll.timeout:0}") // private long kafkaConsumerPollTimeout; // // // @Autowired(required = false) // private ZkUtils zkUtils; // // @Autowired(required = false) // private KafkaTemplate<Integer, String> kafkaTemplate; // // @Autowired(required = false) // @Qualifier("kafkaConsumerConfiguration") // private Map<String, Object> configuration; // // @Autowired(required = false) // private Serializer<EntityCommand<?>> serializer; // // @Override // public void open(String txId) { // // Add topic configuration here // Properties topicConfig = new Properties(); // // AdminUtils.createTopic(zkUtils, txId, zooPartitions, zooReplication, topicConfig, RackAwareMode.Enforced$.MODULE$); // } // // @Override // public void enlist(String txId, EntityCommand<?> command) { // kafkaTemplate.send(txId, serializer.writeToString(command)); // } // // @SuppressWarnings("unchecked") // @Override // public List<EntityCommand<?>> fetch(String txId) { // List<EntityCommand<?>> transactionOperations = new ArrayList<EntityCommand<?>>(); // // Map<String, Object> consumerConfigs = (Map<String, Object>)configuration.get("kafkaConsumerConfiguration"); // consumerConfigs.put(ConsumerConfig.GROUP_ID_CONFIG, UUID.randomUUID().toString()); // // KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<String, String>(consumerConfigs); // kafkaConsumer.subscribe(Arrays.asList(txId)); // // ConsumerRecords<String, String> records = kafkaConsumer.poll(kafkaConsumerPollTimeout); // for (ConsumerRecord<String, String> record : records){ // LOG.info("offset = {}, key = {}, value = {}", record.offset(), record.key(), record.value()); // try { // transactionOperations.add(serializer.readFromString(record.value())); // } catch (SerializationFailedException e) { // LOG.error("Unable to deserialize [{}] because of: {}", record.value(), e.getMessage()); // } // } // // kafkaConsumer.close(); // // return transactionOperations; // } // // @Override // public void close(String txId) { // AdminUtils.deleteTopic(zkUtils, txId); // } // } // Path: rahub-source-code-service/src/main/java/net/jotorren/microservices/content/configuration/CompositeTransactionConfiguration.java import java.util.HashMap; import java.util.Map; import net.jotorren.microservices.context.SpringContextProvider; import net.jotorren.microservices.tx.CompositeTransactionManager; import net.jotorren.microservices.tx.impl.CompositeTransactionManagerKafkaImpl; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.serialization.StringDeserializer; import org.apache.kafka.common.serialization.StringSerializer; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.kafka.core.DefaultKafkaProducerFactory; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.core.ProducerFactory; package net.jotorren.microservices.content.configuration; @Configuration public class CompositeTransactionConfiguration { @Value("${kafka.bootstrap-servers}") private String kafkaBootstrapServers; @Value("${kafka.consumer.enable.auto.commit}") private String kafkaEnableAutoCommit; @Value("${kafka.consumer.auto.commit.interval}") private String kafkaAutoCommitInterval; @Value("${kafka.consumer.session.timeout}") private String kafkaSessionTimeout; @Value("${kafka.consumer.auto.offset.reset}") private String kafkaAutoOffsetReset; @Bean
public SpringContextProvider springContextProvider(){
jotorren/microservices-transactions-tcc
rahub-source-code-service/src/main/java/net/jotorren/microservices/content/configuration/CompositeTransactionConfiguration.java
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/context/SpringContextProvider.java // public class SpringContextProvider implements ApplicationContextAware { // private static ApplicationContext ctx = null; // // public static ApplicationContext getApplicationContext() { // return ctx; // } // // public void setApplicationContext(ApplicationContext ctx) { // SpringContextProvider.ctx = ctx; // } // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionManager.java // public interface CompositeTransactionManager { // // void open(String txId); // void enlist(String txId, EntityCommand<?> ec); // List<EntityCommand<?>> fetch(String txId); // void close(String txId); // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/impl/CompositeTransactionManagerKafkaImpl.java // public class CompositeTransactionManagerKafkaImpl implements CompositeTransactionManager { // // private static final Logger LOG = LoggerFactory.getLogger(CompositeTransactionManager.class); // // @Value("${zookeeper.partitions:0}") // private int zooPartitions; // // @Value("${zookeeper.replication:0}") // private int zooReplication; // // @Value("${kafka.consumer.poll.timeout:0}") // private long kafkaConsumerPollTimeout; // // // @Autowired(required = false) // private ZkUtils zkUtils; // // @Autowired(required = false) // private KafkaTemplate<Integer, String> kafkaTemplate; // // @Autowired(required = false) // @Qualifier("kafkaConsumerConfiguration") // private Map<String, Object> configuration; // // @Autowired(required = false) // private Serializer<EntityCommand<?>> serializer; // // @Override // public void open(String txId) { // // Add topic configuration here // Properties topicConfig = new Properties(); // // AdminUtils.createTopic(zkUtils, txId, zooPartitions, zooReplication, topicConfig, RackAwareMode.Enforced$.MODULE$); // } // // @Override // public void enlist(String txId, EntityCommand<?> command) { // kafkaTemplate.send(txId, serializer.writeToString(command)); // } // // @SuppressWarnings("unchecked") // @Override // public List<EntityCommand<?>> fetch(String txId) { // List<EntityCommand<?>> transactionOperations = new ArrayList<EntityCommand<?>>(); // // Map<String, Object> consumerConfigs = (Map<String, Object>)configuration.get("kafkaConsumerConfiguration"); // consumerConfigs.put(ConsumerConfig.GROUP_ID_CONFIG, UUID.randomUUID().toString()); // // KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<String, String>(consumerConfigs); // kafkaConsumer.subscribe(Arrays.asList(txId)); // // ConsumerRecords<String, String> records = kafkaConsumer.poll(kafkaConsumerPollTimeout); // for (ConsumerRecord<String, String> record : records){ // LOG.info("offset = {}, key = {}, value = {}", record.offset(), record.key(), record.value()); // try { // transactionOperations.add(serializer.readFromString(record.value())); // } catch (SerializationFailedException e) { // LOG.error("Unable to deserialize [{}] because of: {}", record.value(), e.getMessage()); // } // } // // kafkaConsumer.close(); // // return transactionOperations; // } // // @Override // public void close(String txId) { // AdminUtils.deleteTopic(zkUtils, txId); // } // }
import java.util.HashMap; import java.util.Map; import net.jotorren.microservices.context.SpringContextProvider; import net.jotorren.microservices.tx.CompositeTransactionManager; import net.jotorren.microservices.tx.impl.CompositeTransactionManagerKafkaImpl; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.serialization.StringDeserializer; import org.apache.kafka.common.serialization.StringSerializer; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.kafka.core.DefaultKafkaProducerFactory; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.core.ProducerFactory;
package net.jotorren.microservices.content.configuration; @Configuration public class CompositeTransactionConfiguration { @Value("${kafka.bootstrap-servers}") private String kafkaBootstrapServers; @Value("${kafka.consumer.enable.auto.commit}") private String kafkaEnableAutoCommit; @Value("${kafka.consumer.auto.commit.interval}") private String kafkaAutoCommitInterval; @Value("${kafka.consumer.session.timeout}") private String kafkaSessionTimeout; @Value("${kafka.consumer.auto.offset.reset}") private String kafkaAutoOffsetReset; @Bean public SpringContextProvider springContextProvider(){ return new SpringContextProvider(); } @Bean
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/context/SpringContextProvider.java // public class SpringContextProvider implements ApplicationContextAware { // private static ApplicationContext ctx = null; // // public static ApplicationContext getApplicationContext() { // return ctx; // } // // public void setApplicationContext(ApplicationContext ctx) { // SpringContextProvider.ctx = ctx; // } // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionManager.java // public interface CompositeTransactionManager { // // void open(String txId); // void enlist(String txId, EntityCommand<?> ec); // List<EntityCommand<?>> fetch(String txId); // void close(String txId); // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/impl/CompositeTransactionManagerKafkaImpl.java // public class CompositeTransactionManagerKafkaImpl implements CompositeTransactionManager { // // private static final Logger LOG = LoggerFactory.getLogger(CompositeTransactionManager.class); // // @Value("${zookeeper.partitions:0}") // private int zooPartitions; // // @Value("${zookeeper.replication:0}") // private int zooReplication; // // @Value("${kafka.consumer.poll.timeout:0}") // private long kafkaConsumerPollTimeout; // // // @Autowired(required = false) // private ZkUtils zkUtils; // // @Autowired(required = false) // private KafkaTemplate<Integer, String> kafkaTemplate; // // @Autowired(required = false) // @Qualifier("kafkaConsumerConfiguration") // private Map<String, Object> configuration; // // @Autowired(required = false) // private Serializer<EntityCommand<?>> serializer; // // @Override // public void open(String txId) { // // Add topic configuration here // Properties topicConfig = new Properties(); // // AdminUtils.createTopic(zkUtils, txId, zooPartitions, zooReplication, topicConfig, RackAwareMode.Enforced$.MODULE$); // } // // @Override // public void enlist(String txId, EntityCommand<?> command) { // kafkaTemplate.send(txId, serializer.writeToString(command)); // } // // @SuppressWarnings("unchecked") // @Override // public List<EntityCommand<?>> fetch(String txId) { // List<EntityCommand<?>> transactionOperations = new ArrayList<EntityCommand<?>>(); // // Map<String, Object> consumerConfigs = (Map<String, Object>)configuration.get("kafkaConsumerConfiguration"); // consumerConfigs.put(ConsumerConfig.GROUP_ID_CONFIG, UUID.randomUUID().toString()); // // KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<String, String>(consumerConfigs); // kafkaConsumer.subscribe(Arrays.asList(txId)); // // ConsumerRecords<String, String> records = kafkaConsumer.poll(kafkaConsumerPollTimeout); // for (ConsumerRecord<String, String> record : records){ // LOG.info("offset = {}, key = {}, value = {}", record.offset(), record.key(), record.value()); // try { // transactionOperations.add(serializer.readFromString(record.value())); // } catch (SerializationFailedException e) { // LOG.error("Unable to deserialize [{}] because of: {}", record.value(), e.getMessage()); // } // } // // kafkaConsumer.close(); // // return transactionOperations; // } // // @Override // public void close(String txId) { // AdminUtils.deleteTopic(zkUtils, txId); // } // } // Path: rahub-source-code-service/src/main/java/net/jotorren/microservices/content/configuration/CompositeTransactionConfiguration.java import java.util.HashMap; import java.util.Map; import net.jotorren.microservices.context.SpringContextProvider; import net.jotorren.microservices.tx.CompositeTransactionManager; import net.jotorren.microservices.tx.impl.CompositeTransactionManagerKafkaImpl; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.serialization.StringDeserializer; import org.apache.kafka.common.serialization.StringSerializer; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.kafka.core.DefaultKafkaProducerFactory; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.core.ProducerFactory; package net.jotorren.microservices.content.configuration; @Configuration public class CompositeTransactionConfiguration { @Value("${kafka.bootstrap-servers}") private String kafkaBootstrapServers; @Value("${kafka.consumer.enable.auto.commit}") private String kafkaEnableAutoCommit; @Value("${kafka.consumer.auto.commit.interval}") private String kafkaAutoCommitInterval; @Value("${kafka.consumer.session.timeout}") private String kafkaSessionTimeout; @Value("${kafka.consumer.auto.offset.reset}") private String kafkaAutoOffsetReset; @Bean public SpringContextProvider springContextProvider(){ return new SpringContextProvider(); } @Bean
public CompositeTransactionManager compositeTransactionManager() {
jotorren/microservices-transactions-tcc
rahub-source-code-service/src/main/java/net/jotorren/microservices/content/configuration/CompositeTransactionConfiguration.java
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/context/SpringContextProvider.java // public class SpringContextProvider implements ApplicationContextAware { // private static ApplicationContext ctx = null; // // public static ApplicationContext getApplicationContext() { // return ctx; // } // // public void setApplicationContext(ApplicationContext ctx) { // SpringContextProvider.ctx = ctx; // } // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionManager.java // public interface CompositeTransactionManager { // // void open(String txId); // void enlist(String txId, EntityCommand<?> ec); // List<EntityCommand<?>> fetch(String txId); // void close(String txId); // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/impl/CompositeTransactionManagerKafkaImpl.java // public class CompositeTransactionManagerKafkaImpl implements CompositeTransactionManager { // // private static final Logger LOG = LoggerFactory.getLogger(CompositeTransactionManager.class); // // @Value("${zookeeper.partitions:0}") // private int zooPartitions; // // @Value("${zookeeper.replication:0}") // private int zooReplication; // // @Value("${kafka.consumer.poll.timeout:0}") // private long kafkaConsumerPollTimeout; // // // @Autowired(required = false) // private ZkUtils zkUtils; // // @Autowired(required = false) // private KafkaTemplate<Integer, String> kafkaTemplate; // // @Autowired(required = false) // @Qualifier("kafkaConsumerConfiguration") // private Map<String, Object> configuration; // // @Autowired(required = false) // private Serializer<EntityCommand<?>> serializer; // // @Override // public void open(String txId) { // // Add topic configuration here // Properties topicConfig = new Properties(); // // AdminUtils.createTopic(zkUtils, txId, zooPartitions, zooReplication, topicConfig, RackAwareMode.Enforced$.MODULE$); // } // // @Override // public void enlist(String txId, EntityCommand<?> command) { // kafkaTemplate.send(txId, serializer.writeToString(command)); // } // // @SuppressWarnings("unchecked") // @Override // public List<EntityCommand<?>> fetch(String txId) { // List<EntityCommand<?>> transactionOperations = new ArrayList<EntityCommand<?>>(); // // Map<String, Object> consumerConfigs = (Map<String, Object>)configuration.get("kafkaConsumerConfiguration"); // consumerConfigs.put(ConsumerConfig.GROUP_ID_CONFIG, UUID.randomUUID().toString()); // // KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<String, String>(consumerConfigs); // kafkaConsumer.subscribe(Arrays.asList(txId)); // // ConsumerRecords<String, String> records = kafkaConsumer.poll(kafkaConsumerPollTimeout); // for (ConsumerRecord<String, String> record : records){ // LOG.info("offset = {}, key = {}, value = {}", record.offset(), record.key(), record.value()); // try { // transactionOperations.add(serializer.readFromString(record.value())); // } catch (SerializationFailedException e) { // LOG.error("Unable to deserialize [{}] because of: {}", record.value(), e.getMessage()); // } // } // // kafkaConsumer.close(); // // return transactionOperations; // } // // @Override // public void close(String txId) { // AdminUtils.deleteTopic(zkUtils, txId); // } // }
import java.util.HashMap; import java.util.Map; import net.jotorren.microservices.context.SpringContextProvider; import net.jotorren.microservices.tx.CompositeTransactionManager; import net.jotorren.microservices.tx.impl.CompositeTransactionManagerKafkaImpl; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.serialization.StringDeserializer; import org.apache.kafka.common.serialization.StringSerializer; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.kafka.core.DefaultKafkaProducerFactory; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.core.ProducerFactory;
package net.jotorren.microservices.content.configuration; @Configuration public class CompositeTransactionConfiguration { @Value("${kafka.bootstrap-servers}") private String kafkaBootstrapServers; @Value("${kafka.consumer.enable.auto.commit}") private String kafkaEnableAutoCommit; @Value("${kafka.consumer.auto.commit.interval}") private String kafkaAutoCommitInterval; @Value("${kafka.consumer.session.timeout}") private String kafkaSessionTimeout; @Value("${kafka.consumer.auto.offset.reset}") private String kafkaAutoOffsetReset; @Bean public SpringContextProvider springContextProvider(){ return new SpringContextProvider(); } @Bean public CompositeTransactionManager compositeTransactionManager() {
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/context/SpringContextProvider.java // public class SpringContextProvider implements ApplicationContextAware { // private static ApplicationContext ctx = null; // // public static ApplicationContext getApplicationContext() { // return ctx; // } // // public void setApplicationContext(ApplicationContext ctx) { // SpringContextProvider.ctx = ctx; // } // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionManager.java // public interface CompositeTransactionManager { // // void open(String txId); // void enlist(String txId, EntityCommand<?> ec); // List<EntityCommand<?>> fetch(String txId); // void close(String txId); // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/impl/CompositeTransactionManagerKafkaImpl.java // public class CompositeTransactionManagerKafkaImpl implements CompositeTransactionManager { // // private static final Logger LOG = LoggerFactory.getLogger(CompositeTransactionManager.class); // // @Value("${zookeeper.partitions:0}") // private int zooPartitions; // // @Value("${zookeeper.replication:0}") // private int zooReplication; // // @Value("${kafka.consumer.poll.timeout:0}") // private long kafkaConsumerPollTimeout; // // // @Autowired(required = false) // private ZkUtils zkUtils; // // @Autowired(required = false) // private KafkaTemplate<Integer, String> kafkaTemplate; // // @Autowired(required = false) // @Qualifier("kafkaConsumerConfiguration") // private Map<String, Object> configuration; // // @Autowired(required = false) // private Serializer<EntityCommand<?>> serializer; // // @Override // public void open(String txId) { // // Add topic configuration here // Properties topicConfig = new Properties(); // // AdminUtils.createTopic(zkUtils, txId, zooPartitions, zooReplication, topicConfig, RackAwareMode.Enforced$.MODULE$); // } // // @Override // public void enlist(String txId, EntityCommand<?> command) { // kafkaTemplate.send(txId, serializer.writeToString(command)); // } // // @SuppressWarnings("unchecked") // @Override // public List<EntityCommand<?>> fetch(String txId) { // List<EntityCommand<?>> transactionOperations = new ArrayList<EntityCommand<?>>(); // // Map<String, Object> consumerConfigs = (Map<String, Object>)configuration.get("kafkaConsumerConfiguration"); // consumerConfigs.put(ConsumerConfig.GROUP_ID_CONFIG, UUID.randomUUID().toString()); // // KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<String, String>(consumerConfigs); // kafkaConsumer.subscribe(Arrays.asList(txId)); // // ConsumerRecords<String, String> records = kafkaConsumer.poll(kafkaConsumerPollTimeout); // for (ConsumerRecord<String, String> record : records){ // LOG.info("offset = {}, key = {}, value = {}", record.offset(), record.key(), record.value()); // try { // transactionOperations.add(serializer.readFromString(record.value())); // } catch (SerializationFailedException e) { // LOG.error("Unable to deserialize [{}] because of: {}", record.value(), e.getMessage()); // } // } // // kafkaConsumer.close(); // // return transactionOperations; // } // // @Override // public void close(String txId) { // AdminUtils.deleteTopic(zkUtils, txId); // } // } // Path: rahub-source-code-service/src/main/java/net/jotorren/microservices/content/configuration/CompositeTransactionConfiguration.java import java.util.HashMap; import java.util.Map; import net.jotorren.microservices.context.SpringContextProvider; import net.jotorren.microservices.tx.CompositeTransactionManager; import net.jotorren.microservices.tx.impl.CompositeTransactionManagerKafkaImpl; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.serialization.StringDeserializer; import org.apache.kafka.common.serialization.StringSerializer; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.kafka.core.DefaultKafkaProducerFactory; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.core.ProducerFactory; package net.jotorren.microservices.content.configuration; @Configuration public class CompositeTransactionConfiguration { @Value("${kafka.bootstrap-servers}") private String kafkaBootstrapServers; @Value("${kafka.consumer.enable.auto.commit}") private String kafkaEnableAutoCommit; @Value("${kafka.consumer.auto.commit.interval}") private String kafkaAutoCommitInterval; @Value("${kafka.consumer.session.timeout}") private String kafkaSessionTimeout; @Value("${kafka.consumer.auto.offset.reset}") private String kafkaAutoOffsetReset; @Bean public SpringContextProvider springContextProvider(){ return new SpringContextProvider(); } @Bean public CompositeTransactionManager compositeTransactionManager() {
return new CompositeTransactionManagerKafkaImpl();
jotorren/microservices-transactions-tcc
rahub-composite-service/src/main/java/net/jotorren/microservices/configuration/WebServicesConfiguration.java
// Path: rahub-composite-service/src/main/java/net/jotorren/microservices/composite/controller/CompositeController.java // @RestController // @Path("/") // @Api(value = "API Services") // public class CompositeController { // // @Autowired // private CompositeService service; // // @POST // @Path("files") // @Produces ( "application/json" ) // @ApiOperation( // code = 201, // value = "Save new content while creating its discussion board", // notes = "Both operations (new content and forum) must succeed within a given time interval, otherwise both will be canceled or rolled back. " // + "The newly created resource(s) can be referenced by the URI(s) returned in the entity of the response, with the URI for the " // + "distributed transaction given by the Location header field", // response = String.class, // responseContainer = "List", // responseHeaders = { // @ResponseHeader(name = "Location", description = "The distributed transaction URI", response = String.class) // } // ) // @ApiResponses(value = { // @ApiResponse(code=500, message="Error processing request", response = ErrorDetails.class) // }) // public Response save(@Context UriInfo uriInfo, // @ApiParam(value = "Data to pass to server", required = true) CompositeData data // ) throws CompositeTransactionException { // // Entry<String, List<String>> txEntities = service.saveAllEntities(data); // // URI location = uriInfo.getAbsolutePathBuilder().path("{id}") // .resolveTemplate("id", txEntities.getKey()).build(); // // return Response.created(location).entity(txEntities.getValue()).build(); // } // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/rs/ExceptionRestHandler.java // public class ExceptionRestHandler implements ExceptionMapper<Exception>{ // // public class ErrorDetails { // private int code; // private String message; // private String stack; // // public ErrorDetails(int code, String message, String stack){ // this.code = code; // this.message = message; // this.stack = stack; // } // // public int getCode() { // return code; // } // // public String getMessage() { // return message; // } // // public String getStack() { // return stack; // } // } // // @Override // public Response toResponse(Exception exception) { // return toResponse(exception, Response.Status.INTERNAL_SERVER_ERROR); // } // // public Response toResponse(Exception exception, Response.Status status) { // return Response.status(status).entity( // new ErrorDetails(status.getStatusCode(), exception.getMessage(), toString(exception))).build(); // } // // public String toString(Exception exception) { // StringWriter sw = new StringWriter(); // PrintWriter pw = new PrintWriter(sw); // exception.printStackTrace(pw); // String stack = sw.toString(); // pw.close(); // // return stack; // } // }
import java.util.Arrays; import java.util.HashMap; import java.util.Map; import net.jotorren.microservices.composite.controller.CompositeController; import net.jotorren.microservices.rs.ExceptionRestHandler; import org.apache.cxf.Bus; import org.apache.cxf.endpoint.Server; import org.apache.cxf.feature.LoggingFeature; import org.apache.cxf.jaxrs.JAXRSServerFactoryBean; import org.apache.cxf.jaxrs.swagger.Swagger2Feature; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; import com.atomikos.icatch.tcc.rest.CoordinatorImp; import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
package net.jotorren.microservices.configuration; @Configuration public class WebServicesConfiguration { @Value("${swagger.title}") private String title; @Value("${swagger.description}") private String description; @Value("${swagger.version}") private String version; @Value("${swagger.contact}") private String contact; @Value("${swagger.schemes}") private String schemes; @Value("${swagger.basePath}") private String basePath; @Value("${swagger.resourcePackage}") private String resourcePackage; @Value("${swagger.prettyPrint}") private boolean prettyPrint; @Value("${swagger.scan}") private boolean scan; @Autowired private Bus bus; @Autowired private CoordinatorImp tccCoordinatorService; @Autowired
// Path: rahub-composite-service/src/main/java/net/jotorren/microservices/composite/controller/CompositeController.java // @RestController // @Path("/") // @Api(value = "API Services") // public class CompositeController { // // @Autowired // private CompositeService service; // // @POST // @Path("files") // @Produces ( "application/json" ) // @ApiOperation( // code = 201, // value = "Save new content while creating its discussion board", // notes = "Both operations (new content and forum) must succeed within a given time interval, otherwise both will be canceled or rolled back. " // + "The newly created resource(s) can be referenced by the URI(s) returned in the entity of the response, with the URI for the " // + "distributed transaction given by the Location header field", // response = String.class, // responseContainer = "List", // responseHeaders = { // @ResponseHeader(name = "Location", description = "The distributed transaction URI", response = String.class) // } // ) // @ApiResponses(value = { // @ApiResponse(code=500, message="Error processing request", response = ErrorDetails.class) // }) // public Response save(@Context UriInfo uriInfo, // @ApiParam(value = "Data to pass to server", required = true) CompositeData data // ) throws CompositeTransactionException { // // Entry<String, List<String>> txEntities = service.saveAllEntities(data); // // URI location = uriInfo.getAbsolutePathBuilder().path("{id}") // .resolveTemplate("id", txEntities.getKey()).build(); // // return Response.created(location).entity(txEntities.getValue()).build(); // } // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/rs/ExceptionRestHandler.java // public class ExceptionRestHandler implements ExceptionMapper<Exception>{ // // public class ErrorDetails { // private int code; // private String message; // private String stack; // // public ErrorDetails(int code, String message, String stack){ // this.code = code; // this.message = message; // this.stack = stack; // } // // public int getCode() { // return code; // } // // public String getMessage() { // return message; // } // // public String getStack() { // return stack; // } // } // // @Override // public Response toResponse(Exception exception) { // return toResponse(exception, Response.Status.INTERNAL_SERVER_ERROR); // } // // public Response toResponse(Exception exception, Response.Status status) { // return Response.status(status).entity( // new ErrorDetails(status.getStatusCode(), exception.getMessage(), toString(exception))).build(); // } // // public String toString(Exception exception) { // StringWriter sw = new StringWriter(); // PrintWriter pw = new PrintWriter(sw); // exception.printStackTrace(pw); // String stack = sw.toString(); // pw.close(); // // return stack; // } // } // Path: rahub-composite-service/src/main/java/net/jotorren/microservices/configuration/WebServicesConfiguration.java import java.util.Arrays; import java.util.HashMap; import java.util.Map; import net.jotorren.microservices.composite.controller.CompositeController; import net.jotorren.microservices.rs.ExceptionRestHandler; import org.apache.cxf.Bus; import org.apache.cxf.endpoint.Server; import org.apache.cxf.feature.LoggingFeature; import org.apache.cxf.jaxrs.JAXRSServerFactoryBean; import org.apache.cxf.jaxrs.swagger.Swagger2Feature; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; import com.atomikos.icatch.tcc.rest.CoordinatorImp; import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; package net.jotorren.microservices.configuration; @Configuration public class WebServicesConfiguration { @Value("${swagger.title}") private String title; @Value("${swagger.description}") private String description; @Value("${swagger.version}") private String version; @Value("${swagger.contact}") private String contact; @Value("${swagger.schemes}") private String schemes; @Value("${swagger.basePath}") private String basePath; @Value("${swagger.resourcePackage}") private String resourcePackage; @Value("${swagger.prettyPrint}") private boolean prettyPrint; @Value("${swagger.scan}") private boolean scan; @Autowired private Bus bus; @Autowired private CoordinatorImp tccCoordinatorService; @Autowired
private CompositeController compositeController;
jotorren/microservices-transactions-tcc
rahub-composite-service/src/main/java/net/jotorren/microservices/configuration/WebServicesConfiguration.java
// Path: rahub-composite-service/src/main/java/net/jotorren/microservices/composite/controller/CompositeController.java // @RestController // @Path("/") // @Api(value = "API Services") // public class CompositeController { // // @Autowired // private CompositeService service; // // @POST // @Path("files") // @Produces ( "application/json" ) // @ApiOperation( // code = 201, // value = "Save new content while creating its discussion board", // notes = "Both operations (new content and forum) must succeed within a given time interval, otherwise both will be canceled or rolled back. " // + "The newly created resource(s) can be referenced by the URI(s) returned in the entity of the response, with the URI for the " // + "distributed transaction given by the Location header field", // response = String.class, // responseContainer = "List", // responseHeaders = { // @ResponseHeader(name = "Location", description = "The distributed transaction URI", response = String.class) // } // ) // @ApiResponses(value = { // @ApiResponse(code=500, message="Error processing request", response = ErrorDetails.class) // }) // public Response save(@Context UriInfo uriInfo, // @ApiParam(value = "Data to pass to server", required = true) CompositeData data // ) throws CompositeTransactionException { // // Entry<String, List<String>> txEntities = service.saveAllEntities(data); // // URI location = uriInfo.getAbsolutePathBuilder().path("{id}") // .resolveTemplate("id", txEntities.getKey()).build(); // // return Response.created(location).entity(txEntities.getValue()).build(); // } // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/rs/ExceptionRestHandler.java // public class ExceptionRestHandler implements ExceptionMapper<Exception>{ // // public class ErrorDetails { // private int code; // private String message; // private String stack; // // public ErrorDetails(int code, String message, String stack){ // this.code = code; // this.message = message; // this.stack = stack; // } // // public int getCode() { // return code; // } // // public String getMessage() { // return message; // } // // public String getStack() { // return stack; // } // } // // @Override // public Response toResponse(Exception exception) { // return toResponse(exception, Response.Status.INTERNAL_SERVER_ERROR); // } // // public Response toResponse(Exception exception, Response.Status status) { // return Response.status(status).entity( // new ErrorDetails(status.getStatusCode(), exception.getMessage(), toString(exception))).build(); // } // // public String toString(Exception exception) { // StringWriter sw = new StringWriter(); // PrintWriter pw = new PrintWriter(sw); // exception.printStackTrace(pw); // String stack = sw.toString(); // pw.close(); // // return stack; // } // }
import java.util.Arrays; import java.util.HashMap; import java.util.Map; import net.jotorren.microservices.composite.controller.CompositeController; import net.jotorren.microservices.rs.ExceptionRestHandler; import org.apache.cxf.Bus; import org.apache.cxf.endpoint.Server; import org.apache.cxf.feature.LoggingFeature; import org.apache.cxf.jaxrs.JAXRSServerFactoryBean; import org.apache.cxf.jaxrs.swagger.Swagger2Feature; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; import com.atomikos.icatch.tcc.rest.CoordinatorImp; import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
@Value("${swagger.schemes}") private String schemes; @Value("${swagger.basePath}") private String basePath; @Value("${swagger.resourcePackage}") private String resourcePackage; @Value("${swagger.prettyPrint}") private boolean prettyPrint; @Value("${swagger.scan}") private boolean scan; @Autowired private Bus bus; @Autowired private CoordinatorImp tccCoordinatorService; @Autowired private CompositeController compositeController; @Bean public Server rsServer() { JAXRSServerFactoryBean endpoint = new JAXRSServerFactoryBean(); endpoint.setBus(bus); endpoint.setAddress("/");
// Path: rahub-composite-service/src/main/java/net/jotorren/microservices/composite/controller/CompositeController.java // @RestController // @Path("/") // @Api(value = "API Services") // public class CompositeController { // // @Autowired // private CompositeService service; // // @POST // @Path("files") // @Produces ( "application/json" ) // @ApiOperation( // code = 201, // value = "Save new content while creating its discussion board", // notes = "Both operations (new content and forum) must succeed within a given time interval, otherwise both will be canceled or rolled back. " // + "The newly created resource(s) can be referenced by the URI(s) returned in the entity of the response, with the URI for the " // + "distributed transaction given by the Location header field", // response = String.class, // responseContainer = "List", // responseHeaders = { // @ResponseHeader(name = "Location", description = "The distributed transaction URI", response = String.class) // } // ) // @ApiResponses(value = { // @ApiResponse(code=500, message="Error processing request", response = ErrorDetails.class) // }) // public Response save(@Context UriInfo uriInfo, // @ApiParam(value = "Data to pass to server", required = true) CompositeData data // ) throws CompositeTransactionException { // // Entry<String, List<String>> txEntities = service.saveAllEntities(data); // // URI location = uriInfo.getAbsolutePathBuilder().path("{id}") // .resolveTemplate("id", txEntities.getKey()).build(); // // return Response.created(location).entity(txEntities.getValue()).build(); // } // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/rs/ExceptionRestHandler.java // public class ExceptionRestHandler implements ExceptionMapper<Exception>{ // // public class ErrorDetails { // private int code; // private String message; // private String stack; // // public ErrorDetails(int code, String message, String stack){ // this.code = code; // this.message = message; // this.stack = stack; // } // // public int getCode() { // return code; // } // // public String getMessage() { // return message; // } // // public String getStack() { // return stack; // } // } // // @Override // public Response toResponse(Exception exception) { // return toResponse(exception, Response.Status.INTERNAL_SERVER_ERROR); // } // // public Response toResponse(Exception exception, Response.Status status) { // return Response.status(status).entity( // new ErrorDetails(status.getStatusCode(), exception.getMessage(), toString(exception))).build(); // } // // public String toString(Exception exception) { // StringWriter sw = new StringWriter(); // PrintWriter pw = new PrintWriter(sw); // exception.printStackTrace(pw); // String stack = sw.toString(); // pw.close(); // // return stack; // } // } // Path: rahub-composite-service/src/main/java/net/jotorren/microservices/configuration/WebServicesConfiguration.java import java.util.Arrays; import java.util.HashMap; import java.util.Map; import net.jotorren.microservices.composite.controller.CompositeController; import net.jotorren.microservices.rs.ExceptionRestHandler; import org.apache.cxf.Bus; import org.apache.cxf.endpoint.Server; import org.apache.cxf.feature.LoggingFeature; import org.apache.cxf.jaxrs.JAXRSServerFactoryBean; import org.apache.cxf.jaxrs.swagger.Swagger2Feature; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; import com.atomikos.icatch.tcc.rest.CoordinatorImp; import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; @Value("${swagger.schemes}") private String schemes; @Value("${swagger.basePath}") private String basePath; @Value("${swagger.resourcePackage}") private String resourcePackage; @Value("${swagger.prettyPrint}") private boolean prettyPrint; @Value("${swagger.scan}") private boolean scan; @Autowired private Bus bus; @Autowired private CoordinatorImp tccCoordinatorService; @Autowired private CompositeController compositeController; @Bean public Server rsServer() { JAXRSServerFactoryBean endpoint = new JAXRSServerFactoryBean(); endpoint.setBus(bus); endpoint.setAddress("/");
endpoint.setProviders(Arrays.asList(new JacksonJsonProvider(), new ExceptionRestHandler()));
jotorren/microservices-transactions-tcc
rahub-forum-service/src/main/java/net/jotorren/microservices/forum/dao/ForumTransactionAwareDao.java
// Path: rahub-forum-service/src/main/java/net/jotorren/microservices/forum/domain/Forum.java // @Entity // public class Forum implements Serializable { // private static final long serialVersionUID = -8739470216693425165L; // // @Id // @Column(nullable=false) // private String forumId; // // @Column(nullable=false) // private String topicName; // // @Column // private String topicCategory; // // @Column(nullable=false) // private String subjectId; // // public String getForumId() { // return forumId; // } // // public void setForumId(String forumId) { // this.forumId = forumId; // } // // public String getTopicName() { // return topicName; // } // // public void setTopicName(String topicName) { // this.topicName = topicName; // } // // public String getTopicCategory() { // return topicCategory; // } // // public void setTopicCategory(String topicCategory) { // this.topicCategory = topicCategory; // } // // public String getSubjectId() { // return subjectId; // } // // public void setSubjectId(String subjectId) { // this.subjectId = subjectId; // } // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionParticipantDao.java // public class CompositeTransactionParticipantDao { // // @PersistenceContext(type = PersistenceContextType.EXTENDED, synchronization = SynchronizationType.UNSYNCHRONIZED) // private EntityManager em; // // public EntityManager getEntityManager() { // return em; // } // // public void save(Object entity) { // em.persist(entity); // } // // public <T> T saveOrUpdate(T entity) { // return em.merge(entity); // } // // public void remove(Object entity) { // em.remove(entity); // } // // @Transactional(readOnly=false) // public void commit() { // em.joinTransaction(); // } // // public void apply(List<EntityCommand<?>> transactionOperations) { // if (null == transactionOperations) { // return; // } // // for (EntityCommand<?> command : transactionOperations) { // switch (command.getAction().ordinal()) { // case 0: // save(command.getEntity()); // break; // case 1: // saveOrUpdate(command.getEntity()); // break; // case 2: // remove(command.getEntity()); // break; // } // } // } // }
import net.jotorren.microservices.forum.domain.Forum; import net.jotorren.microservices.tx.CompositeTransactionParticipantDao; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Repository;
package net.jotorren.microservices.forum.dao; @Repository @Scope("prototype")
// Path: rahub-forum-service/src/main/java/net/jotorren/microservices/forum/domain/Forum.java // @Entity // public class Forum implements Serializable { // private static final long serialVersionUID = -8739470216693425165L; // // @Id // @Column(nullable=false) // private String forumId; // // @Column(nullable=false) // private String topicName; // // @Column // private String topicCategory; // // @Column(nullable=false) // private String subjectId; // // public String getForumId() { // return forumId; // } // // public void setForumId(String forumId) { // this.forumId = forumId; // } // // public String getTopicName() { // return topicName; // } // // public void setTopicName(String topicName) { // this.topicName = topicName; // } // // public String getTopicCategory() { // return topicCategory; // } // // public void setTopicCategory(String topicCategory) { // this.topicCategory = topicCategory; // } // // public String getSubjectId() { // return subjectId; // } // // public void setSubjectId(String subjectId) { // this.subjectId = subjectId; // } // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionParticipantDao.java // public class CompositeTransactionParticipantDao { // // @PersistenceContext(type = PersistenceContextType.EXTENDED, synchronization = SynchronizationType.UNSYNCHRONIZED) // private EntityManager em; // // public EntityManager getEntityManager() { // return em; // } // // public void save(Object entity) { // em.persist(entity); // } // // public <T> T saveOrUpdate(T entity) { // return em.merge(entity); // } // // public void remove(Object entity) { // em.remove(entity); // } // // @Transactional(readOnly=false) // public void commit() { // em.joinTransaction(); // } // // public void apply(List<EntityCommand<?>> transactionOperations) { // if (null == transactionOperations) { // return; // } // // for (EntityCommand<?> command : transactionOperations) { // switch (command.getAction().ordinal()) { // case 0: // save(command.getEntity()); // break; // case 1: // saveOrUpdate(command.getEntity()); // break; // case 2: // remove(command.getEntity()); // break; // } // } // } // } // Path: rahub-forum-service/src/main/java/net/jotorren/microservices/forum/dao/ForumTransactionAwareDao.java import net.jotorren.microservices.forum.domain.Forum; import net.jotorren.microservices.tx.CompositeTransactionParticipantDao; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Repository; package net.jotorren.microservices.forum.dao; @Repository @Scope("prototype")
public class ForumTransactionAwareDao extends CompositeTransactionParticipantDao{
jotorren/microservices-transactions-tcc
rahub-forum-service/src/main/java/net/jotorren/microservices/forum/dao/ForumTransactionAwareDao.java
// Path: rahub-forum-service/src/main/java/net/jotorren/microservices/forum/domain/Forum.java // @Entity // public class Forum implements Serializable { // private static final long serialVersionUID = -8739470216693425165L; // // @Id // @Column(nullable=false) // private String forumId; // // @Column(nullable=false) // private String topicName; // // @Column // private String topicCategory; // // @Column(nullable=false) // private String subjectId; // // public String getForumId() { // return forumId; // } // // public void setForumId(String forumId) { // this.forumId = forumId; // } // // public String getTopicName() { // return topicName; // } // // public void setTopicName(String topicName) { // this.topicName = topicName; // } // // public String getTopicCategory() { // return topicCategory; // } // // public void setTopicCategory(String topicCategory) { // this.topicCategory = topicCategory; // } // // public String getSubjectId() { // return subjectId; // } // // public void setSubjectId(String subjectId) { // this.subjectId = subjectId; // } // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionParticipantDao.java // public class CompositeTransactionParticipantDao { // // @PersistenceContext(type = PersistenceContextType.EXTENDED, synchronization = SynchronizationType.UNSYNCHRONIZED) // private EntityManager em; // // public EntityManager getEntityManager() { // return em; // } // // public void save(Object entity) { // em.persist(entity); // } // // public <T> T saveOrUpdate(T entity) { // return em.merge(entity); // } // // public void remove(Object entity) { // em.remove(entity); // } // // @Transactional(readOnly=false) // public void commit() { // em.joinTransaction(); // } // // public void apply(List<EntityCommand<?>> transactionOperations) { // if (null == transactionOperations) { // return; // } // // for (EntityCommand<?> command : transactionOperations) { // switch (command.getAction().ordinal()) { // case 0: // save(command.getEntity()); // break; // case 1: // saveOrUpdate(command.getEntity()); // break; // case 2: // remove(command.getEntity()); // break; // } // } // } // }
import net.jotorren.microservices.forum.domain.Forum; import net.jotorren.microservices.tx.CompositeTransactionParticipantDao; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Repository;
package net.jotorren.microservices.forum.dao; @Repository @Scope("prototype") public class ForumTransactionAwareDao extends CompositeTransactionParticipantDao{
// Path: rahub-forum-service/src/main/java/net/jotorren/microservices/forum/domain/Forum.java // @Entity // public class Forum implements Serializable { // private static final long serialVersionUID = -8739470216693425165L; // // @Id // @Column(nullable=false) // private String forumId; // // @Column(nullable=false) // private String topicName; // // @Column // private String topicCategory; // // @Column(nullable=false) // private String subjectId; // // public String getForumId() { // return forumId; // } // // public void setForumId(String forumId) { // this.forumId = forumId; // } // // public String getTopicName() { // return topicName; // } // // public void setTopicName(String topicName) { // this.topicName = topicName; // } // // public String getTopicCategory() { // return topicCategory; // } // // public void setTopicCategory(String topicCategory) { // this.topicCategory = topicCategory; // } // // public String getSubjectId() { // return subjectId; // } // // public void setSubjectId(String subjectId) { // this.subjectId = subjectId; // } // } // // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionParticipantDao.java // public class CompositeTransactionParticipantDao { // // @PersistenceContext(type = PersistenceContextType.EXTENDED, synchronization = SynchronizationType.UNSYNCHRONIZED) // private EntityManager em; // // public EntityManager getEntityManager() { // return em; // } // // public void save(Object entity) { // em.persist(entity); // } // // public <T> T saveOrUpdate(T entity) { // return em.merge(entity); // } // // public void remove(Object entity) { // em.remove(entity); // } // // @Transactional(readOnly=false) // public void commit() { // em.joinTransaction(); // } // // public void apply(List<EntityCommand<?>> transactionOperations) { // if (null == transactionOperations) { // return; // } // // for (EntityCommand<?> command : transactionOperations) { // switch (command.getAction().ordinal()) { // case 0: // save(command.getEntity()); // break; // case 1: // saveOrUpdate(command.getEntity()); // break; // case 2: // remove(command.getEntity()); // break; // } // } // } // } // Path: rahub-forum-service/src/main/java/net/jotorren/microservices/forum/dao/ForumTransactionAwareDao.java import net.jotorren.microservices.forum.domain.Forum; import net.jotorren.microservices.tx.CompositeTransactionParticipantDao; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Repository; package net.jotorren.microservices.forum.dao; @Repository @Scope("prototype") public class ForumTransactionAwareDao extends CompositeTransactionParticipantDao{
public Forum findOne(String pk){
jotorren/microservices-transactions-tcc
rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionParticipantController.java
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/rs/ExceptionRestHandler.java // public class ExceptionRestHandler implements ExceptionMapper<Exception>{ // // public class ErrorDetails { // private int code; // private String message; // private String stack; // // public ErrorDetails(int code, String message, String stack){ // this.code = code; // this.message = message; // this.stack = stack; // } // // public int getCode() { // return code; // } // // public String getMessage() { // return message; // } // // public String getStack() { // return stack; // } // } // // @Override // public Response toResponse(Exception exception) { // return toResponse(exception, Response.Status.INTERNAL_SERVER_ERROR); // } // // public Response toResponse(Exception exception, Response.Status status) { // return Response.status(status).entity( // new ErrorDetails(status.getStatusCode(), exception.getMessage(), toString(exception))).build(); // } // // public String toString(Exception exception) { // StringWriter sw = new StringWriter(); // PrintWriter pw = new PrintWriter(sw); // exception.printStackTrace(pw); // String stack = sw.toString(); // pw.close(); // // return stack; // } // }
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import net.jotorren.microservices.rs.ExceptionRestHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
getCompositeTransactionParticipantService().cancel(txid); LOG.info("Transaction [{}] rolled back", txid); } @PUT @Path("/tcc/{txid}") @Consumes("application/tcc") @ApiOperation( code = 204, response = String.class, value = "Commit a given composite transaction", notes = "See https://www.atomikos.com/Blog/TransactionManagementAPIForRESTTCC", consumes = "application/tcc" ) @ApiResponses(value = { @ApiResponse(code=404, message="Error committing transaction", response = String.class) }) public void confirm( @ApiParam(value = "Id of the composite transaction to commit", required = true) @PathParam("txid") String txid ){ LOG.info("Trying to commit transaction [{}]", txid); try { getCompositeTransactionParticipantService().confirm(txid); LOG.info("Transaction [{}] committed", txid); } catch(Exception e){ // See com.atomikos.icatch.tcc.rest.ParticipantAdapterImp.callConfirmOnJaxrsClient() Response response = Response.status(Response.Status.NOT_FOUND)
// Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/rs/ExceptionRestHandler.java // public class ExceptionRestHandler implements ExceptionMapper<Exception>{ // // public class ErrorDetails { // private int code; // private String message; // private String stack; // // public ErrorDetails(int code, String message, String stack){ // this.code = code; // this.message = message; // this.stack = stack; // } // // public int getCode() { // return code; // } // // public String getMessage() { // return message; // } // // public String getStack() { // return stack; // } // } // // @Override // public Response toResponse(Exception exception) { // return toResponse(exception, Response.Status.INTERNAL_SERVER_ERROR); // } // // public Response toResponse(Exception exception, Response.Status status) { // return Response.status(status).entity( // new ErrorDetails(status.getStatusCode(), exception.getMessage(), toString(exception))).build(); // } // // public String toString(Exception exception) { // StringWriter sw = new StringWriter(); // PrintWriter pw = new PrintWriter(sw); // exception.printStackTrace(pw); // String stack = sw.toString(); // pw.close(); // // return stack; // } // } // Path: rahub-cross-cutting-concerns/src/main/java/net/jotorren/microservices/tx/CompositeTransactionParticipantController.java import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import net.jotorren.microservices.rs.ExceptionRestHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; getCompositeTransactionParticipantService().cancel(txid); LOG.info("Transaction [{}] rolled back", txid); } @PUT @Path("/tcc/{txid}") @Consumes("application/tcc") @ApiOperation( code = 204, response = String.class, value = "Commit a given composite transaction", notes = "See https://www.atomikos.com/Blog/TransactionManagementAPIForRESTTCC", consumes = "application/tcc" ) @ApiResponses(value = { @ApiResponse(code=404, message="Error committing transaction", response = String.class) }) public void confirm( @ApiParam(value = "Id of the composite transaction to commit", required = true) @PathParam("txid") String txid ){ LOG.info("Trying to commit transaction [{}]", txid); try { getCompositeTransactionParticipantService().confirm(txid); LOG.info("Transaction [{}] committed", txid); } catch(Exception e){ // See com.atomikos.icatch.tcc.rest.ParticipantAdapterImp.callConfirmOnJaxrsClient() Response response = Response.status(Response.Status.NOT_FOUND)
.entity(new ExceptionRestHandler().toString(e)).type(MediaType.TEXT_PLAIN).build();
turbolocust/GZipper
src/main/java/org/gzipper/java/application/algorithm/AbstractAlgorithm.java
// Path: src/main/java/org/gzipper/java/application/observer/NotifierImpl.java // public class NotifierImpl<T> implements Notifier<T> { // // /** // * Unique identifier of this instance. // */ // private final int _id = hashCode(); // // /** // * Listeners to be notified if the associated value has been updated. // */ // private final List<Listener<T>> _listeners = new CopyOnWriteArrayList<>(); // // /** // * True if value has changed, false otherwise. // */ // private boolean _hasChanged = false; // // /** // * The associated value which may change. // */ // private T _value; // // @Override // public int getId() { // return _id; // } // // @Override // public final synchronized T getValue() { // return _value; // } // // @Override // public final synchronized void setValue(T value) { // _value = value; // } // // @Override // public final void notifyListeners() { // if (hasChanged()) { // _listeners.forEach((listener) -> listener.update(this, _value)); // clearChanged(); // } // } // // @Override // public final synchronized boolean hasChanged() { // return _hasChanged; // } // // @Override // public final synchronized void setChanged() { // _hasChanged = true; // } // // @Override // public final synchronized void clearChanged() { // _hasChanged = false; // } // // @Override // public final void attach(Listener<T> listener) { // Objects.requireNonNull(listener); // if (!_listeners.contains(listener)) { // _listeners.add(listener); // } // } // // @Override // public final boolean detach(Listener<T> listener) { // return _listeners.remove(listener); // } // // @Override // public final void clearListeners() { // _listeners.clear(); // } // } // // Path: src/main/java/org/gzipper/java/application/predicates/Predicates.java // public final class Predicates { // // private Predicates() { // throw new AssertionError("Holds static members only"); // } // // /** // * Creates a new {@link Predicate} which always evaluates to <b>true</b>. // * // * @param <T> the type of the object that is to be consumed by the predicate // * and thus the type of the input to the predicate. // * @return a new instance of {@link Predicate} with the specified type. // */ // public static <T> Predicate<T> createAlwaysTrue() { // return p -> true; // } // // /** // * Creates a new {@link Predicate} which always evaluates to <b>false</b>. // * // * @param <T> the type of the object that is to be consumed by the predicate // * and thus the type of the input to the predicate. // * @return a new instance of {@link Predicate} with the specified type. // */ // public static <T> Predicate<T> createAlwaysFalse() { // return p -> false; // } // }
import org.apache.commons.compress.archivers.ArchiveException; import org.apache.commons.compress.compressors.CompressorException; import org.gzipper.java.application.ArchiveInfo; import org.gzipper.java.application.observer.NotifierImpl; import org.gzipper.java.application.predicates.Predicates; import java.io.File; import java.io.IOException; import java.util.Objects; import java.util.function.Predicate;
/* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.algorithm; /** * Abstract class that offers generally used attributes and methods for * archiving algorithms. Any class that represents an archiving algorithm should * derive from this class. * * @author Matthias Fussenegger */ public abstract class AbstractAlgorithm extends NotifierImpl<Integer> implements CompressionAlgorithm { /** * If set to true the currently running operation will be interrupted. */ protected volatile boolean interrupt = false; /** * The compression level. Will only be considered if supported by algorithm. */ protected int compressionLevel; /** * Object used to update the progress of the algorithm. */ protected AlgorithmProgress algorithmProgress; /** * Predicate used to filter files or entries when processing archives. */ protected Predicate<String> filterPredicate; /** * The default constructor of this class. */ public AbstractAlgorithm() { // accepts all files/entries since the test result is never false
// Path: src/main/java/org/gzipper/java/application/observer/NotifierImpl.java // public class NotifierImpl<T> implements Notifier<T> { // // /** // * Unique identifier of this instance. // */ // private final int _id = hashCode(); // // /** // * Listeners to be notified if the associated value has been updated. // */ // private final List<Listener<T>> _listeners = new CopyOnWriteArrayList<>(); // // /** // * True if value has changed, false otherwise. // */ // private boolean _hasChanged = false; // // /** // * The associated value which may change. // */ // private T _value; // // @Override // public int getId() { // return _id; // } // // @Override // public final synchronized T getValue() { // return _value; // } // // @Override // public final synchronized void setValue(T value) { // _value = value; // } // // @Override // public final void notifyListeners() { // if (hasChanged()) { // _listeners.forEach((listener) -> listener.update(this, _value)); // clearChanged(); // } // } // // @Override // public final synchronized boolean hasChanged() { // return _hasChanged; // } // // @Override // public final synchronized void setChanged() { // _hasChanged = true; // } // // @Override // public final synchronized void clearChanged() { // _hasChanged = false; // } // // @Override // public final void attach(Listener<T> listener) { // Objects.requireNonNull(listener); // if (!_listeners.contains(listener)) { // _listeners.add(listener); // } // } // // @Override // public final boolean detach(Listener<T> listener) { // return _listeners.remove(listener); // } // // @Override // public final void clearListeners() { // _listeners.clear(); // } // } // // Path: src/main/java/org/gzipper/java/application/predicates/Predicates.java // public final class Predicates { // // private Predicates() { // throw new AssertionError("Holds static members only"); // } // // /** // * Creates a new {@link Predicate} which always evaluates to <b>true</b>. // * // * @param <T> the type of the object that is to be consumed by the predicate // * and thus the type of the input to the predicate. // * @return a new instance of {@link Predicate} with the specified type. // */ // public static <T> Predicate<T> createAlwaysTrue() { // return p -> true; // } // // /** // * Creates a new {@link Predicate} which always evaluates to <b>false</b>. // * // * @param <T> the type of the object that is to be consumed by the predicate // * and thus the type of the input to the predicate. // * @return a new instance of {@link Predicate} with the specified type. // */ // public static <T> Predicate<T> createAlwaysFalse() { // return p -> false; // } // } // Path: src/main/java/org/gzipper/java/application/algorithm/AbstractAlgorithm.java import org.apache.commons.compress.archivers.ArchiveException; import org.apache.commons.compress.compressors.CompressorException; import org.gzipper.java.application.ArchiveInfo; import org.gzipper.java.application.observer.NotifierImpl; import org.gzipper.java.application.predicates.Predicates; import java.io.File; import java.io.IOException; import java.util.Objects; import java.util.function.Predicate; /* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.algorithm; /** * Abstract class that offers generally used attributes and methods for * archiving algorithms. Any class that represents an archiving algorithm should * derive from this class. * * @author Matthias Fussenegger */ public abstract class AbstractAlgorithm extends NotifierImpl<Integer> implements CompressionAlgorithm { /** * If set to true the currently running operation will be interrupted. */ protected volatile boolean interrupt = false; /** * The compression level. Will only be considered if supported by algorithm. */ protected int compressionLevel; /** * Object used to update the progress of the algorithm. */ protected AlgorithmProgress algorithmProgress; /** * Predicate used to filter files or entries when processing archives. */ protected Predicate<String> filterPredicate; /** * The default constructor of this class. */ public AbstractAlgorithm() { // accepts all files/entries since the test result is never false
filterPredicate = Predicates.createAlwaysTrue();
turbolocust/GZipper
src/main/java/org/gzipper/java/util/Settings.java
// Path: src/main/java/org/gzipper/java/application/model/OperatingSystem.java // public class OperatingSystem { // // /** // * The aggregated enumeration which represents the operating system. // */ // protected final OS _operatingSystem; // // /** // * Constructs a new instance of this class using the specified enumeration. // * // * @param operatingSystem the operating system to be aggregated. // */ // public OperatingSystem(OS operatingSystem) { // _operatingSystem = operatingSystem; // } // // /** // * Returns the default user directory of the system. // * // * @return the default user directory as string. // */ // public String getDefaultUserDirectory() { // return System.getProperty("user.home"); // } // // /** // * Returns the enumeration for the current operating system. // * // * @return the enumeration for the current operating system. // */ // public OS getOsInfo() { // return _operatingSystem; // } // } // // Path: src/main/java/org/gzipper/java/application/util/StringUtils.java // public final class StringUtils { // // /** // * An empty string. // */ // public static final String EMPTY = ""; // // private StringUtils() { // throw new AssertionError("Holds static members only"); // } // // /** // * Checks whether the given string is {@code null} or empty. // * // * @param string the string to be checked. // * @return true if string is {@code null} or empty, false otherwise. // */ // public static boolean isNullOrEmpty(String string) { // return string == null || string.isEmpty(); // } // }
import org.gzipper.java.application.model.OperatingSystem; import org.gzipper.java.application.util.StringUtils; import java.io.*; import java.util.Properties;
/* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.util; /** * Singleton that provides convenience when working with {@link Properties} and * represents the settings file that can be used globally. * * @author Matthias Fussenegger */ public final class Settings { public static final String FALSE_STRING = "false"; public static final String TRUE_STRING = "true"; /** * The actual properties file. Required to store away changed properties. */ private File _propsFile; /** * The properties read from the {@link #_propsFile}; */ private Properties _props; /** * The default properties values for restoration. */ private final Properties _defaults; /** * The operating system the JVM runs on. */
// Path: src/main/java/org/gzipper/java/application/model/OperatingSystem.java // public class OperatingSystem { // // /** // * The aggregated enumeration which represents the operating system. // */ // protected final OS _operatingSystem; // // /** // * Constructs a new instance of this class using the specified enumeration. // * // * @param operatingSystem the operating system to be aggregated. // */ // public OperatingSystem(OS operatingSystem) { // _operatingSystem = operatingSystem; // } // // /** // * Returns the default user directory of the system. // * // * @return the default user directory as string. // */ // public String getDefaultUserDirectory() { // return System.getProperty("user.home"); // } // // /** // * Returns the enumeration for the current operating system. // * // * @return the enumeration for the current operating system. // */ // public OS getOsInfo() { // return _operatingSystem; // } // } // // Path: src/main/java/org/gzipper/java/application/util/StringUtils.java // public final class StringUtils { // // /** // * An empty string. // */ // public static final String EMPTY = ""; // // private StringUtils() { // throw new AssertionError("Holds static members only"); // } // // /** // * Checks whether the given string is {@code null} or empty. // * // * @param string the string to be checked. // * @return true if string is {@code null} or empty, false otherwise. // */ // public static boolean isNullOrEmpty(String string) { // return string == null || string.isEmpty(); // } // } // Path: src/main/java/org/gzipper/java/util/Settings.java import org.gzipper.java.application.model.OperatingSystem; import org.gzipper.java.application.util.StringUtils; import java.io.*; import java.util.Properties; /* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.util; /** * Singleton that provides convenience when working with {@link Properties} and * represents the settings file that can be used globally. * * @author Matthias Fussenegger */ public final class Settings { public static final String FALSE_STRING = "false"; public static final String TRUE_STRING = "true"; /** * The actual properties file. Required to store away changed properties. */ private File _propsFile; /** * The properties read from the {@link #_propsFile}; */ private Properties _props; /** * The default properties values for restoration. */ private final Properties _defaults; /** * The operating system the JVM runs on. */
private OperatingSystem _os;
turbolocust/GZipper
src/main/java/org/gzipper/java/util/Settings.java
// Path: src/main/java/org/gzipper/java/application/model/OperatingSystem.java // public class OperatingSystem { // // /** // * The aggregated enumeration which represents the operating system. // */ // protected final OS _operatingSystem; // // /** // * Constructs a new instance of this class using the specified enumeration. // * // * @param operatingSystem the operating system to be aggregated. // */ // public OperatingSystem(OS operatingSystem) { // _operatingSystem = operatingSystem; // } // // /** // * Returns the default user directory of the system. // * // * @return the default user directory as string. // */ // public String getDefaultUserDirectory() { // return System.getProperty("user.home"); // } // // /** // * Returns the enumeration for the current operating system. // * // * @return the enumeration for the current operating system. // */ // public OS getOsInfo() { // return _operatingSystem; // } // } // // Path: src/main/java/org/gzipper/java/application/util/StringUtils.java // public final class StringUtils { // // /** // * An empty string. // */ // public static final String EMPTY = ""; // // private StringUtils() { // throw new AssertionError("Holds static members only"); // } // // /** // * Checks whether the given string is {@code null} or empty. // * // * @param string the string to be checked. // * @return true if string is {@code null} or empty, false otherwise. // */ // public static boolean isNullOrEmpty(String string) { // return string == null || string.isEmpty(); // } // }
import org.gzipper.java.application.model.OperatingSystem; import org.gzipper.java.application.util.StringUtils; import java.io.*; import java.util.Properties;
/* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.util; /** * Singleton that provides convenience when working with {@link Properties} and * represents the settings file that can be used globally. * * @author Matthias Fussenegger */ public final class Settings { public static final String FALSE_STRING = "false"; public static final String TRUE_STRING = "true"; /** * The actual properties file. Required to store away changed properties. */ private File _propsFile; /** * The properties read from the {@link #_propsFile}; */ private Properties _props; /** * The default properties values for restoration. */ private final Properties _defaults; /** * The operating system the JVM runs on. */ private OperatingSystem _os; private Settings() { _defaults = initDefaults(); } /** * Initializes this singleton class. This may only be called once. * * @param props the properties file to initialize this class with. * @param os the current operating system. */ public void init(File props, OperatingSystem os) { if (_props == null) { _os = os; // to receive environment variables if (props != null) { _propsFile = props; _props = new Properties(_defaults); try (final FileInputStream fis = new FileInputStream(props); final BufferedInputStream bis = new BufferedInputStream(fis)) { _props.load(bis); } catch (IOException ex) { Log.e(ex.getLocalizedMessage(), ex); } } } } /** * Initializes the default properties values. * * @return the default properties. */ private Properties initDefaults() { final Properties defaults = new Properties(); defaults.setProperty("loggingEnabled", FALSE_STRING);
// Path: src/main/java/org/gzipper/java/application/model/OperatingSystem.java // public class OperatingSystem { // // /** // * The aggregated enumeration which represents the operating system. // */ // protected final OS _operatingSystem; // // /** // * Constructs a new instance of this class using the specified enumeration. // * // * @param operatingSystem the operating system to be aggregated. // */ // public OperatingSystem(OS operatingSystem) { // _operatingSystem = operatingSystem; // } // // /** // * Returns the default user directory of the system. // * // * @return the default user directory as string. // */ // public String getDefaultUserDirectory() { // return System.getProperty("user.home"); // } // // /** // * Returns the enumeration for the current operating system. // * // * @return the enumeration for the current operating system. // */ // public OS getOsInfo() { // return _operatingSystem; // } // } // // Path: src/main/java/org/gzipper/java/application/util/StringUtils.java // public final class StringUtils { // // /** // * An empty string. // */ // public static final String EMPTY = ""; // // private StringUtils() { // throw new AssertionError("Holds static members only"); // } // // /** // * Checks whether the given string is {@code null} or empty. // * // * @param string the string to be checked. // * @return true if string is {@code null} or empty, false otherwise. // */ // public static boolean isNullOrEmpty(String string) { // return string == null || string.isEmpty(); // } // } // Path: src/main/java/org/gzipper/java/util/Settings.java import org.gzipper.java.application.model.OperatingSystem; import org.gzipper.java.application.util.StringUtils; import java.io.*; import java.util.Properties; /* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.util; /** * Singleton that provides convenience when working with {@link Properties} and * represents the settings file that can be used globally. * * @author Matthias Fussenegger */ public final class Settings { public static final String FALSE_STRING = "false"; public static final String TRUE_STRING = "true"; /** * The actual properties file. Required to store away changed properties. */ private File _propsFile; /** * The properties read from the {@link #_propsFile}; */ private Properties _props; /** * The default properties values for restoration. */ private final Properties _defaults; /** * The operating system the JVM runs on. */ private OperatingSystem _os; private Settings() { _defaults = initDefaults(); } /** * Initializes this singleton class. This may only be called once. * * @param props the properties file to initialize this class with. * @param os the current operating system. */ public void init(File props, OperatingSystem os) { if (_props == null) { _os = os; // to receive environment variables if (props != null) { _propsFile = props; _props = new Properties(_defaults); try (final FileInputStream fis = new FileInputStream(props); final BufferedInputStream bis = new BufferedInputStream(fis)) { _props.load(bis); } catch (IOException ex) { Log.e(ex.getLocalizedMessage(), ex); } } } } /** * Initializes the default properties values. * * @return the default properties. */ private Properties initDefaults() { final Properties defaults = new Properties(); defaults.setProperty("loggingEnabled", FALSE_STRING);
defaults.setProperty("recentPath", StringUtils.EMPTY);
turbolocust/GZipper
src/main/java/org/gzipper/java/application/hashing/MessageDigestResult.java
// Path: src/main/java/org/gzipper/java/application/util/StringUtils.java // public final class StringUtils { // // /** // * An empty string. // */ // public static final String EMPTY = ""; // // private StringUtils() { // throw new AssertionError("Holds static members only"); // } // // /** // * Checks whether the given string is {@code null} or empty. // * // * @param string the string to be checked. // * @return true if string is {@code null} or empty, false otherwise. // */ // public static boolean isNullOrEmpty(String string) { // return string == null || string.isEmpty(); // } // }
import org.gzipper.java.application.util.StringUtils; import java.util.Arrays; import java.util.Objects;
/* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.hashing; /** * Holds result values of message digest algorithms. * * @author Matthias Fussenegger */ public final class MessageDigestResult { private final byte[] _hashedBytes; private final String _hashedValue; public MessageDigestResult() { _hashedBytes = new byte[0];
// Path: src/main/java/org/gzipper/java/application/util/StringUtils.java // public final class StringUtils { // // /** // * An empty string. // */ // public static final String EMPTY = ""; // // private StringUtils() { // throw new AssertionError("Holds static members only"); // } // // /** // * Checks whether the given string is {@code null} or empty. // * // * @param string the string to be checked. // * @return true if string is {@code null} or empty, false otherwise. // */ // public static boolean isNullOrEmpty(String string) { // return string == null || string.isEmpty(); // } // } // Path: src/main/java/org/gzipper/java/application/hashing/MessageDigestResult.java import org.gzipper.java.application.util.StringUtils; import java.util.Arrays; import java.util.Objects; /* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.hashing; /** * Holds result values of message digest algorithms. * * @author Matthias Fussenegger */ public final class MessageDigestResult { private final byte[] _hashedBytes; private final String _hashedValue; public MessageDigestResult() { _hashedBytes = new byte[0];
_hashedValue = StringUtils.EMPTY;
turbolocust/GZipper
src/main/java/org/gzipper/java/application/model/ArchiveType.java
// Path: src/main/java/org/gzipper/java/application/algorithm/CompressionAlgorithm.java // public interface CompressionAlgorithm extends Interruptible, Notifier<Integer> { // // /** // * The default buffer size for chunks. // */ // int DEFAULT_BUFFER_SIZE = 8192; // // /** // * Compresses files using the algorithm of the concrete class with default // * settings and stores an archive to the specified path. // * // * @param files the files selected from the file chooser. // * @param location defines where to store the archive. // * @param name the name of the archive without the directory path. // * @throws IOException if an I/O error occurs. // * @throws ArchiveException if an error related to the archiver occurs. // * @throws CompressorException if an error related to the compressor occurs. // */ // void compress(File[] files, String location, String name) // throws IOException, ArchiveException, CompressorException; // // /** // * Compresses files using the algorithm of the concrete class with default // * settings and stores an archive to the path specified in // * {@link ArchiveInfo}. // * // * @param info POJO that holds information required for compression. // * @throws IOException if an I/O error occurs. // * @throws ArchiveException if an error related to the archiver occurs. // * @throws CompressorException if an error related to the compressor occurs. // */ // void compress(ArchiveInfo info) // throws IOException, ArchiveException, CompressorException; // // /** // * Extracts an archive using the algorithm of the concrete class and stores // * the files of the archive to the specified path. // * // * @param location the location where to extract the archive. // * @param fullname the filename of the archive to extract. // * @throws IOException if an I/O error occurs. // * @throws ArchiveException if an error related to the archiver occurs. // * @throws CompressorException if an error related to the compressor occurs. // */ // void extract(String location, String fullname) // throws IOException, ArchiveException, CompressorException; // // /** // * Extracts an archive using the algorithm of the concrete class and stores // * the files of the archive to the path specified in {@link ArchiveInfo}. // * // * @param info POJO that holds information required for extraction. // * @throws IOException if an I/O error occurs. // * @throws ArchiveException if an error related to the archiver occurs. // * @throws CompressorException if an error related to the compressor occurs. // */ // void extract(ArchiveInfo info) // throws IOException, ArchiveException, CompressorException; // // /** // * Sets the specified {@link Predicate} which will be used as a filter when // * compressing files or decompressing archive entries by evaluating the name // * of the file or entry. // * // * @param predicate the {@link Predicate} to be used. // */ // void setPredicate(Predicate<String> predicate); // // }
import org.gzipper.java.application.algorithm.CompressionAlgorithm; import org.gzipper.java.application.algorithm.type.*;
/* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.model; /** * Enumeration for archive types. * * @author Matthias Fussenegger */ public enum ArchiveType { ZIP("Zip", "ZIP", new String[]{"*.zip"}) { @Override
// Path: src/main/java/org/gzipper/java/application/algorithm/CompressionAlgorithm.java // public interface CompressionAlgorithm extends Interruptible, Notifier<Integer> { // // /** // * The default buffer size for chunks. // */ // int DEFAULT_BUFFER_SIZE = 8192; // // /** // * Compresses files using the algorithm of the concrete class with default // * settings and stores an archive to the specified path. // * // * @param files the files selected from the file chooser. // * @param location defines where to store the archive. // * @param name the name of the archive without the directory path. // * @throws IOException if an I/O error occurs. // * @throws ArchiveException if an error related to the archiver occurs. // * @throws CompressorException if an error related to the compressor occurs. // */ // void compress(File[] files, String location, String name) // throws IOException, ArchiveException, CompressorException; // // /** // * Compresses files using the algorithm of the concrete class with default // * settings and stores an archive to the path specified in // * {@link ArchiveInfo}. // * // * @param info POJO that holds information required for compression. // * @throws IOException if an I/O error occurs. // * @throws ArchiveException if an error related to the archiver occurs. // * @throws CompressorException if an error related to the compressor occurs. // */ // void compress(ArchiveInfo info) // throws IOException, ArchiveException, CompressorException; // // /** // * Extracts an archive using the algorithm of the concrete class and stores // * the files of the archive to the specified path. // * // * @param location the location where to extract the archive. // * @param fullname the filename of the archive to extract. // * @throws IOException if an I/O error occurs. // * @throws ArchiveException if an error related to the archiver occurs. // * @throws CompressorException if an error related to the compressor occurs. // */ // void extract(String location, String fullname) // throws IOException, ArchiveException, CompressorException; // // /** // * Extracts an archive using the algorithm of the concrete class and stores // * the files of the archive to the path specified in {@link ArchiveInfo}. // * // * @param info POJO that holds information required for extraction. // * @throws IOException if an I/O error occurs. // * @throws ArchiveException if an error related to the archiver occurs. // * @throws CompressorException if an error related to the compressor occurs. // */ // void extract(ArchiveInfo info) // throws IOException, ArchiveException, CompressorException; // // /** // * Sets the specified {@link Predicate} which will be used as a filter when // * compressing files or decompressing archive entries by evaluating the name // * of the file or entry. // * // * @param predicate the {@link Predicate} to be used. // */ // void setPredicate(Predicate<String> predicate); // // } // Path: src/main/java/org/gzipper/java/application/model/ArchiveType.java import org.gzipper.java.application.algorithm.CompressionAlgorithm; import org.gzipper.java.application.algorithm.type.*; /* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.model; /** * Enumeration for archive types. * * @author Matthias Fussenegger */ public enum ArchiveType { ZIP("Zip", "ZIP", new String[]{"*.zip"}) { @Override
public CompressionAlgorithm getAlgorithm() {
turbolocust/GZipper
src/main/java/org/gzipper/java/presentation/controller/BaseController.java
// Path: src/main/java/org/gzipper/java/presentation/CSS.java // public final class CSS { // // private CSS() { // throw new AssertionError("Holds static members only"); // } // // /** // * Applies the specified {@link Theme} to the specified {@link Scene}. // * <p> // * To be more precise, this method clears the list of style sheets of the // * specified scene and adds the resource location of the respective CSS file // * in external form to the list. This way the alternative theme will be // * loaded. // * // * @param theme the theme to be loaded. // * @param scene the scene to which to apply the theme. // */ // public static void load(Theme theme, Scene scene) { // List<String> stylesheets = scene.getStylesheets(); // stylesheets.clear(); // if (theme != Theme.getDefault()) { // stylesheets.add(CSS.class.getResource(theme.getLocation()).toExternalForm()); // } // } // // /** // * Enumeration that consists of all existing visual themes. // */ // public enum Theme { // // MODENA("MODENA"), // DARK_THEME("/css/DarkTheme.css"); // // /** // * The physical location of the associated style sheet. // */ // private final String _location; // // Theme(String location) { // _location = location; // } // // /** // * Returns the physical location of the associated style sheet. // * // * @return the physical location of the associated style sheet. // */ // public String getLocation() { // return _location; // } // // /** // * Returns the default theme of the application. // * // * @return the default theme. // */ // public static Theme getDefault() { // return MODENA; // } // } // }
import javafx.application.HostServices; import javafx.application.Platform; import javafx.fxml.Initializable; import javafx.scene.image.Image; import javafx.stage.Stage; import org.gzipper.java.presentation.CSS; import java.util.HashSet; import java.util.Set;
/* * Copyright (C) 2017 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.presentation.controller; /** * The base controller each other controller should derive from. * * @author Matthias Fussenegger */ public abstract class BaseController implements Initializable { //<editor-fold desc="Static members"> /** * The default archive name of an archive if not explicitly specified. */ protected static final String DEFAULT_ARCHIVE_NAME = "gzipper_out"; /** * A set with all the stages currently open. */ private static final Set<Stage> _stages = new HashSet<>(); /** * Returns all currently open stages. * * @return all currently open stages. */ public static Set<Stage> getStages() { return _stages; } /** * The icon image used for each stage. */ protected static Image iconImage; /** * Returns the icon image that is to be used for each stage. * * @return the icon image that is to be used for each stage. */ public static Image getIconImage() { var resource = BaseController.class.getResource("/images/icon_32.png"); return iconImage = new Image(resource.toExternalForm()); } //</editor-fold> /** * The aggregated primary stage. */ protected Stage primaryStage; /** * Sets the primary stage of this controller. * * @param primaryStage the primary stage to be set. */ public void setPrimaryStage(Stage primaryStage) { this.primaryStage = primaryStage; } /** * The aggregated host services. May be {@code null} if not set. */ protected HostServices hostServices; /** * The currently active theme. */
// Path: src/main/java/org/gzipper/java/presentation/CSS.java // public final class CSS { // // private CSS() { // throw new AssertionError("Holds static members only"); // } // // /** // * Applies the specified {@link Theme} to the specified {@link Scene}. // * <p> // * To be more precise, this method clears the list of style sheets of the // * specified scene and adds the resource location of the respective CSS file // * in external form to the list. This way the alternative theme will be // * loaded. // * // * @param theme the theme to be loaded. // * @param scene the scene to which to apply the theme. // */ // public static void load(Theme theme, Scene scene) { // List<String> stylesheets = scene.getStylesheets(); // stylesheets.clear(); // if (theme != Theme.getDefault()) { // stylesheets.add(CSS.class.getResource(theme.getLocation()).toExternalForm()); // } // } // // /** // * Enumeration that consists of all existing visual themes. // */ // public enum Theme { // // MODENA("MODENA"), // DARK_THEME("/css/DarkTheme.css"); // // /** // * The physical location of the associated style sheet. // */ // private final String _location; // // Theme(String location) { // _location = location; // } // // /** // * Returns the physical location of the associated style sheet. // * // * @return the physical location of the associated style sheet. // */ // public String getLocation() { // return _location; // } // // /** // * Returns the default theme of the application. // * // * @return the default theme. // */ // public static Theme getDefault() { // return MODENA; // } // } // } // Path: src/main/java/org/gzipper/java/presentation/controller/BaseController.java import javafx.application.HostServices; import javafx.application.Platform; import javafx.fxml.Initializable; import javafx.scene.image.Image; import javafx.stage.Stage; import org.gzipper.java.presentation.CSS; import java.util.HashSet; import java.util.Set; /* * Copyright (C) 2017 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.presentation.controller; /** * The base controller each other controller should derive from. * * @author Matthias Fussenegger */ public abstract class BaseController implements Initializable { //<editor-fold desc="Static members"> /** * The default archive name of an archive if not explicitly specified. */ protected static final String DEFAULT_ARCHIVE_NAME = "gzipper_out"; /** * A set with all the stages currently open. */ private static final Set<Stage> _stages = new HashSet<>(); /** * Returns all currently open stages. * * @return all currently open stages. */ public static Set<Stage> getStages() { return _stages; } /** * The icon image used for each stage. */ protected static Image iconImage; /** * Returns the icon image that is to be used for each stage. * * @return the icon image that is to be used for each stage. */ public static Image getIconImage() { var resource = BaseController.class.getResource("/images/icon_32.png"); return iconImage = new Image(resource.toExternalForm()); } //</editor-fold> /** * The aggregated primary stage. */ protected Stage primaryStage; /** * Sets the primary stage of this controller. * * @param primaryStage the primary stage to be set. */ public void setPrimaryStage(Stage primaryStage) { this.primaryStage = primaryStage; } /** * The aggregated host services. May be {@code null} if not set. */ protected HostServices hostServices; /** * The currently active theme. */
protected CSS.Theme theme;
reines/game
game-graphics/src/main/java/com/game/graphics/renderer/TextRenderer.java
// Path: game-common/src/main/java/com/game/common/util/PersistenceManager.java // public class PersistenceManager { // private static final Logger log = LoggerFactory.getLogger(PersistenceManager.class); // // public class PacketHandler { // public Packet.Type[] types; // public Class<?> handler; // } // // public class ItemHandler { // public int[] ids; // public Class<?> handler; // } // // protected static final XStream xstream; // // static { // xstream = new XStream(); // // xstream.alias("type", Packet.Type.class); // // xstream.alias("PacketHandler", PacketHandler.class); // xstream.alias("ItemHandler", ItemHandler.class); // // xstream.alias("ItemDef", Item.Definition.class); // xstream.alias("TileDef", Tile.Definition.class); // } // // public static void alias(String name, Class<?> type) { // xstream.alias(name, type); // } // // public static Object load(URL path) { // try { // InputStream in = path.openStream(); // Object o = xstream.fromXML(in); // in.close(); // // return o; // } // catch (IOException ioe) { // log.error("Error loading object: " + ioe.getMessage()); // System.exit(1); // fatal error // // return null; // } // } // // public static void save(Object o, File f) throws IOException { // OutputStream out = new FileOutputStream(f); // xstream.toXML(o, out); // out.close(); // } // }
import java.awt.image.BufferedImage; import java.io.IOException; import java.net.URL; import javax.imageio.ImageIO; import org.lwjgl.opengl.GL11; import com.game.common.util.PersistenceManager;
package com.game.graphics.renderer; public class TextRenderer { public static final char REPLACEMENT_CHAR = '?'; static {
// Path: game-common/src/main/java/com/game/common/util/PersistenceManager.java // public class PersistenceManager { // private static final Logger log = LoggerFactory.getLogger(PersistenceManager.class); // // public class PacketHandler { // public Packet.Type[] types; // public Class<?> handler; // } // // public class ItemHandler { // public int[] ids; // public Class<?> handler; // } // // protected static final XStream xstream; // // static { // xstream = new XStream(); // // xstream.alias("type", Packet.Type.class); // // xstream.alias("PacketHandler", PacketHandler.class); // xstream.alias("ItemHandler", ItemHandler.class); // // xstream.alias("ItemDef", Item.Definition.class); // xstream.alias("TileDef", Tile.Definition.class); // } // // public static void alias(String name, Class<?> type) { // xstream.alias(name, type); // } // // public static Object load(URL path) { // try { // InputStream in = path.openStream(); // Object o = xstream.fromXML(in); // in.close(); // // return o; // } // catch (IOException ioe) { // log.error("Error loading object: " + ioe.getMessage()); // System.exit(1); // fatal error // // return null; // } // } // // public static void save(Object o, File f) throws IOException { // OutputStream out = new FileOutputStream(f); // xstream.toXML(o, out); // out.close(); // } // } // Path: game-graphics/src/main/java/com/game/graphics/renderer/TextRenderer.java import java.awt.image.BufferedImage; import java.io.IOException; import java.net.URL; import javax.imageio.ImageIO; import org.lwjgl.opengl.GL11; import com.game.common.util.PersistenceManager; package com.game.graphics.renderer; public class TextRenderer { public static final char REPLACEMENT_CHAR = '?'; static {
PersistenceManager.alias("FontData", FontData.class);
reines/game
game-graphics/src/main/java/com/game/graphics/renderer/Graphics.java
// Path: game-graphics/src/main/java/com/game/graphics/models/Model.java // public abstract class Model extends Pickable { // // protected final Graphics graphics; // protected final boolean animated; // // protected float scale; // protected int rotation; // protected Mesh[] meshes; // // public Model(Graphics graphics, boolean animated) { // this.graphics = graphics; // this.animated = animated; // // this.setScale(1); // this.setRotation(0); // // meshes = new Mesh[0]; // } // // public boolean isAnimated() { // return animated; // } // // public float getScale() { // return scale; // } // // public void setScale(float scale) { // this.scale = scale; // } // // public int getRotation() { // return rotation; // } // // public void setRotation(int rotation) { // rotation += 180; // this.rotation = 360 - (rotation % 360); // } // // protected void init() { // // TODO: Load this model into a vertex buffer, so the only way to draw is via the buffer // } // // public abstract void update(); // // @Override // protected void draw() { // for (Mesh mesh : meshes) { // // Set the texture for this mesh // Material material = mesh.getMaterial(); // if (material != null) { // GL11.glMaterial(GL11.GL_FRONT, GL11.GL_AMBIENT, material.ambient); // GL11.glMaterial(GL11.GL_FRONT, GL11.GL_DIFFUSE, material.diffuse); // GL11.glMaterial(GL11.GL_FRONT, GL11.GL_SPECULAR, material.specular); // GL11.glMaterial(GL11.GL_FRONT, GL11.GL_EMISSION, material.emissive); // GL11.glMaterialf(GL11.GL_FRONT, GL11.GL_SHININESS, material.shininess); // // // If we have a texture, bind it // if (material.colorMap != null) // GL11.glBindTexture(GL11.GL_TEXTURE_2D, material.colorMap.textureID); // } // // GL11.glBegin(GL11.GL_TRIANGLES); // { // for (Triangle triangle : mesh.triangles) { // for (Triangle.Point point : triangle.points) { // GL11.glNormal3f(point.normal.x, point.normal.y, point.normal.z); // GL11.glTexCoord2f(point.vertex.texturePosition.x, point.vertex.texturePosition.y); // // // If there is no bone, just draw the vertex // Joint joint = point.vertex.getJoint(); // if (joint == null || !animated) // GL11.glVertex3f(point.vertex.position.x, point.vertex.position.y, point.vertex.position.z); // // Otherwise calculate the animation and draw // else { // Vector3f animationVector = joint.finalMatrix.vectorRotate(point.vertex.position); // TODO: or joint.position? // // animationVector.x += joint.finalMatrix.m03; // animationVector.y += joint.finalMatrix.m13; // animationVector.z += joint.finalMatrix.m23; // // GL11.glVertex3f(animationVector.x, animationVector.y, animationVector.z); // } // } // } // } // GL11.glEnd(); // // // Unbind the texture // GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0); // } // } // // @Override // public String toString() { // return "model[meshes = " + meshes.length + "]"; // } // }
import java.awt.Color; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.IntBuffer; import java.util.HashMap; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.DisplayMode; import org.lwjgl.opengl.GL11; import com.game.graphics.models.Model;
catch (IOException e) { // fatal error throw new RuntimeException("Unable to load sprite pack: " + e); } } public Sprite loadSprite(String path) { URL resource = Sprite.class.getResource("sprites/" + path); if (resource == null) { // fatal error throw new RuntimeException("Unable to find resource: " + path); } return this.loadSprite(resource); } public Sprite loadSprite(URL resource) { try { InputStream in = resource.openStream(); Sprite sprite = new Sprite(in, this); in.close(); return sprite; } catch (IOException e) { // fatal error throw new RuntimeException("Unable to load sprite: " + e); } }
// Path: game-graphics/src/main/java/com/game/graphics/models/Model.java // public abstract class Model extends Pickable { // // protected final Graphics graphics; // protected final boolean animated; // // protected float scale; // protected int rotation; // protected Mesh[] meshes; // // public Model(Graphics graphics, boolean animated) { // this.graphics = graphics; // this.animated = animated; // // this.setScale(1); // this.setRotation(0); // // meshes = new Mesh[0]; // } // // public boolean isAnimated() { // return animated; // } // // public float getScale() { // return scale; // } // // public void setScale(float scale) { // this.scale = scale; // } // // public int getRotation() { // return rotation; // } // // public void setRotation(int rotation) { // rotation += 180; // this.rotation = 360 - (rotation % 360); // } // // protected void init() { // // TODO: Load this model into a vertex buffer, so the only way to draw is via the buffer // } // // public abstract void update(); // // @Override // protected void draw() { // for (Mesh mesh : meshes) { // // Set the texture for this mesh // Material material = mesh.getMaterial(); // if (material != null) { // GL11.glMaterial(GL11.GL_FRONT, GL11.GL_AMBIENT, material.ambient); // GL11.glMaterial(GL11.GL_FRONT, GL11.GL_DIFFUSE, material.diffuse); // GL11.glMaterial(GL11.GL_FRONT, GL11.GL_SPECULAR, material.specular); // GL11.glMaterial(GL11.GL_FRONT, GL11.GL_EMISSION, material.emissive); // GL11.glMaterialf(GL11.GL_FRONT, GL11.GL_SHININESS, material.shininess); // // // If we have a texture, bind it // if (material.colorMap != null) // GL11.glBindTexture(GL11.GL_TEXTURE_2D, material.colorMap.textureID); // } // // GL11.glBegin(GL11.GL_TRIANGLES); // { // for (Triangle triangle : mesh.triangles) { // for (Triangle.Point point : triangle.points) { // GL11.glNormal3f(point.normal.x, point.normal.y, point.normal.z); // GL11.glTexCoord2f(point.vertex.texturePosition.x, point.vertex.texturePosition.y); // // // If there is no bone, just draw the vertex // Joint joint = point.vertex.getJoint(); // if (joint == null || !animated) // GL11.glVertex3f(point.vertex.position.x, point.vertex.position.y, point.vertex.position.z); // // Otherwise calculate the animation and draw // else { // Vector3f animationVector = joint.finalMatrix.vectorRotate(point.vertex.position); // TODO: or joint.position? // // animationVector.x += joint.finalMatrix.m03; // animationVector.y += joint.finalMatrix.m13; // animationVector.z += joint.finalMatrix.m23; // // GL11.glVertex3f(animationVector.x, animationVector.y, animationVector.z); // } // } // } // } // GL11.glEnd(); // // // Unbind the texture // GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0); // } // } // // @Override // public String toString() { // return "model[meshes = " + meshes.length + "]"; // } // } // Path: game-graphics/src/main/java/com/game/graphics/renderer/Graphics.java import java.awt.Color; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.IntBuffer; import java.util.HashMap; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.DisplayMode; import org.lwjgl.opengl.GL11; import com.game.graphics.models.Model; catch (IOException e) { // fatal error throw new RuntimeException("Unable to load sprite pack: " + e); } } public Sprite loadSprite(String path) { URL resource = Sprite.class.getResource("sprites/" + path); if (resource == null) { // fatal error throw new RuntimeException("Unable to find resource: " + path); } return this.loadSprite(resource); } public Sprite loadSprite(URL resource) { try { InputStream in = resource.openStream(); Sprite sprite = new Sprite(in, this); in.close(); return sprite; } catch (IOException e) { // fatal error throw new RuntimeException("Unable to load sprite: " + e); } }
public Model loadModel(String path, Class<? extends Model> type) {
reines/game
game-common/src/test/java/com/game/common/util/HashTest.java
// Path: game-common/src/main/java/com/game/common/model/Hash.java // public class Hash implements Comparable<Hash>, Serializable { // private static final Logger log = LoggerFactory.getLogger(Hash.class); // private static final long serialVersionUID = 1L; // // public static final int LENGTH = 20; // in bytes // public static final String ALGORITHM = "SHA-1"; // // protected static MessageDigest digest; // // static { // try { // digest = MessageDigest.getInstance(ALGORITHM); // } // catch (NoSuchAlgorithmException e) { // log.error("No such hashing algorithm: " + ALGORITHM); // System.exit(1); // fatal error // } // } // // public static Hash fromString(String hex) { // Hash hash = new Hash(); // hash.setHex(hex); // // return hash; // } // // public static Hash fromBytes(byte[] bytes) { // Hash hash = new Hash(); // hash.setBytes(bytes); // // return hash; // } // // protected String hex; // // public Hash(String str) { // try { // digest.update(str.getBytes("UTF-8")); // } // catch (UnsupportedEncodingException e) { } // // this.setBytes(digest.digest()); // } // // private Hash() { // hex = null; // } // // private void setHex(String hex) { // this.hex = hex; // } // // private void setBytes(byte[] bytes) { // Formatter foramtter = new Formatter(); // // for (byte b : bytes) // foramtter.format("%02x", b); // // this.hex = foramtter.toString(); // } // // public byte[] getBytes() { // byte[] bytes = new byte[LENGTH]; // // for (int i = 0;i < LENGTH;i++) // bytes[i] = (byte) Short.parseShort(hex.substring(2 * i, 2 * (i + 1)), 16); // // return bytes; // } // // @Override // public String toString() { // return hex; // } // // @Override // public int hashCode() { // return hex.hashCode(); // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof Hash)) // return false; // // Hash h = (Hash) o; // return hex.equals(h.hex); // } // // @Override // public int compareTo(Hash h) { // return hex.compareTo(h.hex); // } // }
import com.game.common.model.Hash; import junit.framework.TestCase;
package com.game.common.util; public class HashTest extends TestCase { public void testFromString() {
// Path: game-common/src/main/java/com/game/common/model/Hash.java // public class Hash implements Comparable<Hash>, Serializable { // private static final Logger log = LoggerFactory.getLogger(Hash.class); // private static final long serialVersionUID = 1L; // // public static final int LENGTH = 20; // in bytes // public static final String ALGORITHM = "SHA-1"; // // protected static MessageDigest digest; // // static { // try { // digest = MessageDigest.getInstance(ALGORITHM); // } // catch (NoSuchAlgorithmException e) { // log.error("No such hashing algorithm: " + ALGORITHM); // System.exit(1); // fatal error // } // } // // public static Hash fromString(String hex) { // Hash hash = new Hash(); // hash.setHex(hex); // // return hash; // } // // public static Hash fromBytes(byte[] bytes) { // Hash hash = new Hash(); // hash.setBytes(bytes); // // return hash; // } // // protected String hex; // // public Hash(String str) { // try { // digest.update(str.getBytes("UTF-8")); // } // catch (UnsupportedEncodingException e) { } // // this.setBytes(digest.digest()); // } // // private Hash() { // hex = null; // } // // private void setHex(String hex) { // this.hex = hex; // } // // private void setBytes(byte[] bytes) { // Formatter foramtter = new Formatter(); // // for (byte b : bytes) // foramtter.format("%02x", b); // // this.hex = foramtter.toString(); // } // // public byte[] getBytes() { // byte[] bytes = new byte[LENGTH]; // // for (int i = 0;i < LENGTH;i++) // bytes[i] = (byte) Short.parseShort(hex.substring(2 * i, 2 * (i + 1)), 16); // // return bytes; // } // // @Override // public String toString() { // return hex; // } // // @Override // public int hashCode() { // return hex.hashCode(); // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof Hash)) // return false; // // Hash h = (Hash) o; // return hex.equals(h.hex); // } // // @Override // public int compareTo(Hash h) { // return hex.compareTo(h.hex); // } // } // Path: game-common/src/test/java/com/game/common/util/HashTest.java import com.game.common.model.Hash; import junit.framework.TestCase; package com.game.common.util; public class HashTest extends TestCase { public void testFromString() {
Hash h1 = Hash.fromString("aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d");
reines/game
game-common/src/main/java/com/game/common/util/EntityList.java
// Path: game-common/src/main/java/com/game/common/model/Entity.java // public abstract class Entity extends Observable { // // public abstract Hash getID(); // public abstract Point getLocation(); // public abstract void setLocation(Point p); // // } // // Path: game-common/src/main/java/com/game/common/model/Hash.java // public class Hash implements Comparable<Hash>, Serializable { // private static final Logger log = LoggerFactory.getLogger(Hash.class); // private static final long serialVersionUID = 1L; // // public static final int LENGTH = 20; // in bytes // public static final String ALGORITHM = "SHA-1"; // // protected static MessageDigest digest; // // static { // try { // digest = MessageDigest.getInstance(ALGORITHM); // } // catch (NoSuchAlgorithmException e) { // log.error("No such hashing algorithm: " + ALGORITHM); // System.exit(1); // fatal error // } // } // // public static Hash fromString(String hex) { // Hash hash = new Hash(); // hash.setHex(hex); // // return hash; // } // // public static Hash fromBytes(byte[] bytes) { // Hash hash = new Hash(); // hash.setBytes(bytes); // // return hash; // } // // protected String hex; // // public Hash(String str) { // try { // digest.update(str.getBytes("UTF-8")); // } // catch (UnsupportedEncodingException e) { } // // this.setBytes(digest.digest()); // } // // private Hash() { // hex = null; // } // // private void setHex(String hex) { // this.hex = hex; // } // // private void setBytes(byte[] bytes) { // Formatter foramtter = new Formatter(); // // for (byte b : bytes) // foramtter.format("%02x", b); // // this.hex = foramtter.toString(); // } // // public byte[] getBytes() { // byte[] bytes = new byte[LENGTH]; // // for (int i = 0;i < LENGTH;i++) // bytes[i] = (byte) Short.parseShort(hex.substring(2 * i, 2 * (i + 1)), 16); // // return bytes; // } // // @Override // public String toString() { // return hex; // } // // @Override // public int hashCode() { // return hex.hashCode(); // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof Hash)) // return false; // // Hash h = (Hash) o; // return hex.equals(h.hex); // } // // @Override // public int compareTo(Hash h) { // return hex.compareTo(h.hex); // } // }
import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Observable; import java.util.Observer; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.game.common.model.Entity; import com.game.common.model.Hash;
package com.game.common.util; public class EntityList<T extends Entity> implements Observer, Iterable<T> { private static final Logger log = LoggerFactory.getLogger(EntityList.class);
// Path: game-common/src/main/java/com/game/common/model/Entity.java // public abstract class Entity extends Observable { // // public abstract Hash getID(); // public abstract Point getLocation(); // public abstract void setLocation(Point p); // // } // // Path: game-common/src/main/java/com/game/common/model/Hash.java // public class Hash implements Comparable<Hash>, Serializable { // private static final Logger log = LoggerFactory.getLogger(Hash.class); // private static final long serialVersionUID = 1L; // // public static final int LENGTH = 20; // in bytes // public static final String ALGORITHM = "SHA-1"; // // protected static MessageDigest digest; // // static { // try { // digest = MessageDigest.getInstance(ALGORITHM); // } // catch (NoSuchAlgorithmException e) { // log.error("No such hashing algorithm: " + ALGORITHM); // System.exit(1); // fatal error // } // } // // public static Hash fromString(String hex) { // Hash hash = new Hash(); // hash.setHex(hex); // // return hash; // } // // public static Hash fromBytes(byte[] bytes) { // Hash hash = new Hash(); // hash.setBytes(bytes); // // return hash; // } // // protected String hex; // // public Hash(String str) { // try { // digest.update(str.getBytes("UTF-8")); // } // catch (UnsupportedEncodingException e) { } // // this.setBytes(digest.digest()); // } // // private Hash() { // hex = null; // } // // private void setHex(String hex) { // this.hex = hex; // } // // private void setBytes(byte[] bytes) { // Formatter foramtter = new Formatter(); // // for (byte b : bytes) // foramtter.format("%02x", b); // // this.hex = foramtter.toString(); // } // // public byte[] getBytes() { // byte[] bytes = new byte[LENGTH]; // // for (int i = 0;i < LENGTH;i++) // bytes[i] = (byte) Short.parseShort(hex.substring(2 * i, 2 * (i + 1)), 16); // // return bytes; // } // // @Override // public String toString() { // return hex; // } // // @Override // public int hashCode() { // return hex.hashCode(); // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof Hash)) // return false; // // Hash h = (Hash) o; // return hex.equals(h.hex); // } // // @Override // public int compareTo(Hash h) { // return hex.compareTo(h.hex); // } // } // Path: game-common/src/main/java/com/game/common/util/EntityList.java import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Observable; import java.util.Observer; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.game.common.model.Entity; import com.game.common.model.Hash; package com.game.common.util; public class EntityList<T extends Entity> implements Observer, Iterable<T> { private static final Logger log = LoggerFactory.getLogger(EntityList.class);
protected final Map<Hash, T> allEntities;
reines/game
game-tools/src/main/java/com/game/tools/mapeditor/ui/SpriteBox.java
// Path: game-tools/src/main/java/com/game/tools/mapeditor/SpriteMap.java // public class SpriteMap implements Iterable<Image> { // // public final int elementWidth; // public final int elementHeight; // protected final List<Image> sprites; // // public SpriteMap(int elementWidth, int elementHeight) { // this.elementWidth = elementWidth; // this.elementHeight = elementHeight; // // sprites = new ArrayList<Image>(); // } // // public SpriteMap(URL resource, int elementWidth, int elementHeight) throws IOException { // this (elementWidth, elementHeight); // // BufferedImage image = ImageIO.read(resource); // // if (image.getWidth() % elementWidth != 0 || image.getHeight() % elementHeight != 0) { // // fatal error // throw new RuntimeException("Attempted to load sprite map, but the image dimensions aren't multiples of the element dimensions."); // } // // int width = image.getWidth() / elementWidth; // int height = image.getHeight() / elementHeight; // // for (int y = 0;y < height;y++) { // for (int x = 0;x < width;x++) { // Image sprite = image.getSubimage(x * elementWidth, y * elementHeight, elementWidth, elementHeight); // this.add(sprite); // } // } // } // // public void add(Image sprite) { // sprites.add(sprite); // } // // public Image get(int index) { // return sprites.get(index); // } // // public BufferedImage generateImage() { // return null; // generate 1 image with all the sprites tiled // } // // @Override // public Iterator<Image> iterator() { // return sprites.iterator(); // } // }
import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Image; import java.awt.image.BufferedImage; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.ListCellRenderer; import javax.swing.SwingConstants; import javax.swing.UIManager; import com.game.tools.mapeditor.SpriteMap;
package com.game.tools.mapeditor.ui; @SuppressWarnings("serial") public class SpriteBox extends JComboBox { protected static class SpriteBoxRenderer extends JLabel implements ListCellRenderer { protected final SpriteBox box; public SpriteBoxRenderer(SpriteBox box) { this.box = box; super.setBackground(Color.BLACK); super.setOpaque(true); super.setHorizontalAlignment(SwingConstants.CENTER); super.setVerticalAlignment(SwingConstants.CENTER); } @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.setIcon((ImageIcon) value); super.setBorder(isSelected ? BorderFactory.createLineBorder(Color.RED) : null); return this; } } // Width needs to account for the scrollbar/dropdown arrow
// Path: game-tools/src/main/java/com/game/tools/mapeditor/SpriteMap.java // public class SpriteMap implements Iterable<Image> { // // public final int elementWidth; // public final int elementHeight; // protected final List<Image> sprites; // // public SpriteMap(int elementWidth, int elementHeight) { // this.elementWidth = elementWidth; // this.elementHeight = elementHeight; // // sprites = new ArrayList<Image>(); // } // // public SpriteMap(URL resource, int elementWidth, int elementHeight) throws IOException { // this (elementWidth, elementHeight); // // BufferedImage image = ImageIO.read(resource); // // if (image.getWidth() % elementWidth != 0 || image.getHeight() % elementHeight != 0) { // // fatal error // throw new RuntimeException("Attempted to load sprite map, but the image dimensions aren't multiples of the element dimensions."); // } // // int width = image.getWidth() / elementWidth; // int height = image.getHeight() / elementHeight; // // for (int y = 0;y < height;y++) { // for (int x = 0;x < width;x++) { // Image sprite = image.getSubimage(x * elementWidth, y * elementHeight, elementWidth, elementHeight); // this.add(sprite); // } // } // } // // public void add(Image sprite) { // sprites.add(sprite); // } // // public Image get(int index) { // return sprites.get(index); // } // // public BufferedImage generateImage() { // return null; // generate 1 image with all the sprites tiled // } // // @Override // public Iterator<Image> iterator() { // return sprites.iterator(); // } // } // Path: game-tools/src/main/java/com/game/tools/mapeditor/ui/SpriteBox.java import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Image; import java.awt.image.BufferedImage; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.ListCellRenderer; import javax.swing.SwingConstants; import javax.swing.UIManager; import com.game.tools.mapeditor.SpriteMap; package com.game.tools.mapeditor.ui; @SuppressWarnings("serial") public class SpriteBox extends JComboBox { protected static class SpriteBoxRenderer extends JLabel implements ListCellRenderer { protected final SpriteBox box; public SpriteBoxRenderer(SpriteBox box) { this.box = box; super.setBackground(Color.BLACK); super.setOpaque(true); super.setHorizontalAlignment(SwingConstants.CENTER); super.setVerticalAlignment(SwingConstants.CENTER); } @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.setIcon((ImageIcon) value); super.setBorder(isSelected ? BorderFactory.createLineBorder(Color.RED) : null); return this; } } // Width needs to account for the scrollbar/dropdown arrow
public SpriteBox(SpriteMap sprites, boolean addBlank) {
reines/game
game-common/src/main/java/com/game/common/util/FriendList.java
// Path: game-common/src/main/java/com/game/common/model/Friend.java // public class Friend implements Serializable { // private static final long serialVersionUID = 1L; // // protected Hash id; // protected String username; // protected transient boolean online; // // public Friend(Hash id, String username, boolean online) { // this.id = id; // this.username = username; // this.online = online; // } // // @SuppressWarnings("unused") // private Friend() { } // for hibernate // // public Hash getID() { // return id; // } // // public String getUsername() { // return username; // } // // public boolean isOnline() { // return online; // } // // public void setOnline(boolean online) { // this.online = online; // } // // @Override // public int hashCode() { // return id.hashCode(); // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof Friend)) // return false; // // Friend f = (Friend) o; // return id.equals(f.id); // } // // @Override // public String toString() { // return "friend[id = " + id + ", username = '" + username + "', online = " + online + "]"; // } // // private void writeObject(ObjectOutputStream out) throws IOException { // out.defaultWriteObject(); // } // // private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { // in.defaultReadObject(); // this.setOnline(false); // Default to offline unless we're told otherwise // } // } // // Path: game-common/src/main/java/com/game/common/model/Hash.java // public class Hash implements Comparable<Hash>, Serializable { // private static final Logger log = LoggerFactory.getLogger(Hash.class); // private static final long serialVersionUID = 1L; // // public static final int LENGTH = 20; // in bytes // public static final String ALGORITHM = "SHA-1"; // // protected static MessageDigest digest; // // static { // try { // digest = MessageDigest.getInstance(ALGORITHM); // } // catch (NoSuchAlgorithmException e) { // log.error("No such hashing algorithm: " + ALGORITHM); // System.exit(1); // fatal error // } // } // // public static Hash fromString(String hex) { // Hash hash = new Hash(); // hash.setHex(hex); // // return hash; // } // // public static Hash fromBytes(byte[] bytes) { // Hash hash = new Hash(); // hash.setBytes(bytes); // // return hash; // } // // protected String hex; // // public Hash(String str) { // try { // digest.update(str.getBytes("UTF-8")); // } // catch (UnsupportedEncodingException e) { } // // this.setBytes(digest.digest()); // } // // private Hash() { // hex = null; // } // // private void setHex(String hex) { // this.hex = hex; // } // // private void setBytes(byte[] bytes) { // Formatter foramtter = new Formatter(); // // for (byte b : bytes) // foramtter.format("%02x", b); // // this.hex = foramtter.toString(); // } // // public byte[] getBytes() { // byte[] bytes = new byte[LENGTH]; // // for (int i = 0;i < LENGTH;i++) // bytes[i] = (byte) Short.parseShort(hex.substring(2 * i, 2 * (i + 1)), 16); // // return bytes; // } // // @Override // public String toString() { // return hex; // } // // @Override // public int hashCode() { // return hex.hashCode(); // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof Hash)) // return false; // // Hash h = (Hash) o; // return hex.equals(h.hex); // } // // @Override // public int compareTo(Hash h) { // return hex.compareTo(h.hex); // } // }
import java.io.Serializable; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import com.game.common.model.Friend; import com.game.common.model.Hash;
package com.game.common.util; public class FriendList implements Iterable<Friend>, Serializable { private static final long serialVersionUID = 1L;
// Path: game-common/src/main/java/com/game/common/model/Friend.java // public class Friend implements Serializable { // private static final long serialVersionUID = 1L; // // protected Hash id; // protected String username; // protected transient boolean online; // // public Friend(Hash id, String username, boolean online) { // this.id = id; // this.username = username; // this.online = online; // } // // @SuppressWarnings("unused") // private Friend() { } // for hibernate // // public Hash getID() { // return id; // } // // public String getUsername() { // return username; // } // // public boolean isOnline() { // return online; // } // // public void setOnline(boolean online) { // this.online = online; // } // // @Override // public int hashCode() { // return id.hashCode(); // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof Friend)) // return false; // // Friend f = (Friend) o; // return id.equals(f.id); // } // // @Override // public String toString() { // return "friend[id = " + id + ", username = '" + username + "', online = " + online + "]"; // } // // private void writeObject(ObjectOutputStream out) throws IOException { // out.defaultWriteObject(); // } // // private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { // in.defaultReadObject(); // this.setOnline(false); // Default to offline unless we're told otherwise // } // } // // Path: game-common/src/main/java/com/game/common/model/Hash.java // public class Hash implements Comparable<Hash>, Serializable { // private static final Logger log = LoggerFactory.getLogger(Hash.class); // private static final long serialVersionUID = 1L; // // public static final int LENGTH = 20; // in bytes // public static final String ALGORITHM = "SHA-1"; // // protected static MessageDigest digest; // // static { // try { // digest = MessageDigest.getInstance(ALGORITHM); // } // catch (NoSuchAlgorithmException e) { // log.error("No such hashing algorithm: " + ALGORITHM); // System.exit(1); // fatal error // } // } // // public static Hash fromString(String hex) { // Hash hash = new Hash(); // hash.setHex(hex); // // return hash; // } // // public static Hash fromBytes(byte[] bytes) { // Hash hash = new Hash(); // hash.setBytes(bytes); // // return hash; // } // // protected String hex; // // public Hash(String str) { // try { // digest.update(str.getBytes("UTF-8")); // } // catch (UnsupportedEncodingException e) { } // // this.setBytes(digest.digest()); // } // // private Hash() { // hex = null; // } // // private void setHex(String hex) { // this.hex = hex; // } // // private void setBytes(byte[] bytes) { // Formatter foramtter = new Formatter(); // // for (byte b : bytes) // foramtter.format("%02x", b); // // this.hex = foramtter.toString(); // } // // public byte[] getBytes() { // byte[] bytes = new byte[LENGTH]; // // for (int i = 0;i < LENGTH;i++) // bytes[i] = (byte) Short.parseShort(hex.substring(2 * i, 2 * (i + 1)), 16); // // return bytes; // } // // @Override // public String toString() { // return hex; // } // // @Override // public int hashCode() { // return hex.hashCode(); // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof Hash)) // return false; // // Hash h = (Hash) o; // return hex.equals(h.hex); // } // // @Override // public int compareTo(Hash h) { // return hex.compareTo(h.hex); // } // } // Path: game-common/src/main/java/com/game/common/util/FriendList.java import java.io.Serializable; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import com.game.common.model.Friend; import com.game.common.model.Hash; package com.game.common.util; public class FriendList implements Iterable<Friend>, Serializable { private static final long serialVersionUID = 1L;
protected Map<Hash, Friend> friends;
reines/game
game-common/src/main/java/com/game/common/model/Tile.java
// Path: game-common/src/main/java/com/game/common/util/PersistenceManager.java // public class PersistenceManager { // private static final Logger log = LoggerFactory.getLogger(PersistenceManager.class); // // public class PacketHandler { // public Packet.Type[] types; // public Class<?> handler; // } // // public class ItemHandler { // public int[] ids; // public Class<?> handler; // } // // protected static final XStream xstream; // // static { // xstream = new XStream(); // // xstream.alias("type", Packet.Type.class); // // xstream.alias("PacketHandler", PacketHandler.class); // xstream.alias("ItemHandler", ItemHandler.class); // // xstream.alias("ItemDef", Item.Definition.class); // xstream.alias("TileDef", Tile.Definition.class); // } // // public static void alias(String name, Class<?> type) { // xstream.alias(name, type); // } // // public static Object load(URL path) { // try { // InputStream in = path.openStream(); // Object o = xstream.fromXML(in); // in.close(); // // return o; // } // catch (IOException ioe) { // log.error("Error loading object: " + ioe.getMessage()); // System.exit(1); // fatal error // // return null; // } // } // // public static void save(Object o, File f) throws IOException { // OutputStream out = new FileOutputStream(f); // xstream.toXML(o, out); // out.close(); // } // }
import java.io.DataInputStream; import java.io.IOException; import java.net.URL; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.game.common.util.PersistenceManager;
package com.game.common.model; public abstract class Tile { private static final Logger log = LoggerFactory.getLogger(Tile.class); public static final int DATA_LENGTH = 5; protected static final Map<Byte, Definition> definitions; static { definitions = Tile.loadDefinitions(); if (log.isDebugEnabled()) log.debug("Loaded " + definitions.size() + " tile definitions"); } public static Map<Byte, Definition> getDefinitions() { return definitions; } // do nothing - static {} does the work public static void load() { } @SuppressWarnings("unchecked") private static Map<Byte, Definition> loadDefinitions() { URL path = Tile.class.getResource("tiles.xml"); if (path == null) { log.error("Unable to find tiles.xml resource"); System.exit(1); // fatal error return null; }
// Path: game-common/src/main/java/com/game/common/util/PersistenceManager.java // public class PersistenceManager { // private static final Logger log = LoggerFactory.getLogger(PersistenceManager.class); // // public class PacketHandler { // public Packet.Type[] types; // public Class<?> handler; // } // // public class ItemHandler { // public int[] ids; // public Class<?> handler; // } // // protected static final XStream xstream; // // static { // xstream = new XStream(); // // xstream.alias("type", Packet.Type.class); // // xstream.alias("PacketHandler", PacketHandler.class); // xstream.alias("ItemHandler", ItemHandler.class); // // xstream.alias("ItemDef", Item.Definition.class); // xstream.alias("TileDef", Tile.Definition.class); // } // // public static void alias(String name, Class<?> type) { // xstream.alias(name, type); // } // // public static Object load(URL path) { // try { // InputStream in = path.openStream(); // Object o = xstream.fromXML(in); // in.close(); // // return o; // } // catch (IOException ioe) { // log.error("Error loading object: " + ioe.getMessage()); // System.exit(1); // fatal error // // return null; // } // } // // public static void save(Object o, File f) throws IOException { // OutputStream out = new FileOutputStream(f); // xstream.toXML(o, out); // out.close(); // } // } // Path: game-common/src/main/java/com/game/common/model/Tile.java import java.io.DataInputStream; import java.io.IOException; import java.net.URL; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.game.common.util.PersistenceManager; package com.game.common.model; public abstract class Tile { private static final Logger log = LoggerFactory.getLogger(Tile.class); public static final int DATA_LENGTH = 5; protected static final Map<Byte, Definition> definitions; static { definitions = Tile.loadDefinitions(); if (log.isDebugEnabled()) log.debug("Loaded " + definitions.size() + " tile definitions"); } public static Map<Byte, Definition> getDefinitions() { return definitions; } // do nothing - static {} does the work public static void load() { } @SuppressWarnings("unchecked") private static Map<Byte, Definition> loadDefinitions() { URL path = Tile.class.getResource("tiles.xml"); if (path == null) { log.error("Unable to find tiles.xml resource"); System.exit(1); // fatal error return null; }
return (Map<Byte, Definition>) PersistenceManager.load(path);
reines/game
game-graphics/src/main/java/com/game/graphics/widget/ProgressBar.java
// Path: game-graphics/src/main/java/com/game/graphics/renderer/Graphics2D.java // public class Graphics2D { // protected final TextRenderer textRenderer; // protected final Graphics graphics; // protected final DisplayMode mode; // protected final FloatBuffer projMatrix; // // protected Graphics2D(Graphics graphics, DisplayMode mode) { // this.graphics = graphics; // this.mode = mode; // // textRenderer = new TextRenderer(graphics); // // // Set up our 2D mode // GL11.glViewport(graphics.viewport.get(0), graphics.viewport.get(1), graphics.viewport.get(2), graphics.viewport.get(3)); // GL11.glMatrixMode(GL11.GL_PROJECTION); // GL11.glLoadIdentity(); // GLU.gluOrtho2D(0, mode.getWidth(), mode.getHeight(), 0); // GL11.glMatrixMode(GL11.GL_MODELVIEW); // // projMatrix = BufferUtils.createFloatBuffer(16); // GL11.glGetFloat(GL11.GL_PROJECTION_MATRIX, projMatrix); // } // // public Graphics getGraphics() { // return graphics; // } // // public void begin() { // GL11.glPushMatrix(); // graphics.setMode(Graphics.Mode.G2D); // // // Disable lighting effects // GL11.glDisable(GL11.GL_LIGHTING); // // // Disable fog // GL11.glDisable(GL11.GL_FOG); // // // Disable depth testing // GL11.glDisable(GL11.GL_DEPTH_TEST); // // // Disable anti-aliasing // GL11.glDisable(GL11.GL_LINE_SMOOTH); // // // Disable culling // GL11.glDisable(GL11.GL_CULL_FACE); // } // // public void end() { // GL11.glPopMatrix(); // } // // public int getFontWidth(String message) { // return textRenderer.getWidth(message); // } // // public int getFontHeight() { // return textRenderer.getHeight(); // } // // protected void setColor(Color c) { // GL11.glColor4f(c.getRed() / 255f, c.getGreen() / 255f, c.getBlue() / 255f, c.getAlpha() / 255f); // } // // public void drawRect(int x, int y, int width, int height, Color c) { // this.setColor(c); // GL11.glBegin(GL11.GL_LINE_LOOP); // { // GL11.glVertex2i(x, y); // GL11.glVertex2i(x + width, y); // GL11.glVertex2i(x + width, y + height); // GL11.glVertex2i(x, y + height); // } // GL11.glEnd(); // this.setColor(Color.WHITE); // } // // public void fillRect(int x, int y, int width, int height, Color c) { // this.setColor(c); // GL11.glBegin(GL11.GL_QUADS); // { // GL11.glVertex2i(x, y); // GL11.glVertex2i(x + width, y); // GL11.glVertex2i(x + width, y + height); // GL11.glVertex2i(x, y + height); // } // GL11.glEnd(); // this.setColor(Color.WHITE); // } // // public void drawLine(int x1, int y1, int x2, int y2, Color c) { // this.setColor(c); // GL11.glBegin(GL11.GL_LINES); // { // GL11.glVertex2i(x1, y1); // GL11.glVertex2i(x2, y2); // } // GL11.glEnd(); // this.setColor(Color.WHITE); // } // // public void drawString(String str, int x, int y, Color c) { // this.drawString(str, x, y, c, false); // } // // public void drawString(String str, int x, int y, Color c, boolean shadow) { // textRenderer.begin(); // { // if (shadow) { // this.setColor(Color.BLACK); // textRenderer.drawString(str, x + 1, y + 1); // } // // this.setColor(c); // textRenderer.drawString(str, x, y); // this.setColor(Color.WHITE); // } // textRenderer.end(); // } // // public void drawSprite(Sprite sprite, int x, int y, int width, int height) { // // Bind the texture // GL11.glBindTexture(GL11.GL_TEXTURE_2D, sprite.textureID); // // GL11.glBegin(GL11.GL_QUADS); // { // GL11.glTexCoord2f(0, 0); // GL11.glVertex2i(x, y); // // GL11.glTexCoord2f(0, 1); // GL11.glVertex2i(x, y + height); // // GL11.glTexCoord2f(1, 1); // GL11.glVertex2i(x + width, y + height); // // GL11.glTexCoord2f(1, 0); // GL11.glVertex2i(x + width, y); // } // GL11.glEnd(); // // // Unbind the texture // GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0); // } // }
import java.awt.Color; import com.game.graphics.renderer.Graphics2D;
package com.game.graphics.widget; public class ProgressBar extends Widget { protected int value; protected Color color; public ProgressBar(int width, int height) { super(width, height, false); // Default to not started color = new Color(0f, 0.5f, 0f); value = 0; } public int getValue() { return value; } public Color getColor() { return color; } @Override
// Path: game-graphics/src/main/java/com/game/graphics/renderer/Graphics2D.java // public class Graphics2D { // protected final TextRenderer textRenderer; // protected final Graphics graphics; // protected final DisplayMode mode; // protected final FloatBuffer projMatrix; // // protected Graphics2D(Graphics graphics, DisplayMode mode) { // this.graphics = graphics; // this.mode = mode; // // textRenderer = new TextRenderer(graphics); // // // Set up our 2D mode // GL11.glViewport(graphics.viewport.get(0), graphics.viewport.get(1), graphics.viewport.get(2), graphics.viewport.get(3)); // GL11.glMatrixMode(GL11.GL_PROJECTION); // GL11.glLoadIdentity(); // GLU.gluOrtho2D(0, mode.getWidth(), mode.getHeight(), 0); // GL11.glMatrixMode(GL11.GL_MODELVIEW); // // projMatrix = BufferUtils.createFloatBuffer(16); // GL11.glGetFloat(GL11.GL_PROJECTION_MATRIX, projMatrix); // } // // public Graphics getGraphics() { // return graphics; // } // // public void begin() { // GL11.glPushMatrix(); // graphics.setMode(Graphics.Mode.G2D); // // // Disable lighting effects // GL11.glDisable(GL11.GL_LIGHTING); // // // Disable fog // GL11.glDisable(GL11.GL_FOG); // // // Disable depth testing // GL11.glDisable(GL11.GL_DEPTH_TEST); // // // Disable anti-aliasing // GL11.glDisable(GL11.GL_LINE_SMOOTH); // // // Disable culling // GL11.glDisable(GL11.GL_CULL_FACE); // } // // public void end() { // GL11.glPopMatrix(); // } // // public int getFontWidth(String message) { // return textRenderer.getWidth(message); // } // // public int getFontHeight() { // return textRenderer.getHeight(); // } // // protected void setColor(Color c) { // GL11.glColor4f(c.getRed() / 255f, c.getGreen() / 255f, c.getBlue() / 255f, c.getAlpha() / 255f); // } // // public void drawRect(int x, int y, int width, int height, Color c) { // this.setColor(c); // GL11.glBegin(GL11.GL_LINE_LOOP); // { // GL11.glVertex2i(x, y); // GL11.glVertex2i(x + width, y); // GL11.glVertex2i(x + width, y + height); // GL11.glVertex2i(x, y + height); // } // GL11.glEnd(); // this.setColor(Color.WHITE); // } // // public void fillRect(int x, int y, int width, int height, Color c) { // this.setColor(c); // GL11.glBegin(GL11.GL_QUADS); // { // GL11.glVertex2i(x, y); // GL11.glVertex2i(x + width, y); // GL11.glVertex2i(x + width, y + height); // GL11.glVertex2i(x, y + height); // } // GL11.glEnd(); // this.setColor(Color.WHITE); // } // // public void drawLine(int x1, int y1, int x2, int y2, Color c) { // this.setColor(c); // GL11.glBegin(GL11.GL_LINES); // { // GL11.glVertex2i(x1, y1); // GL11.glVertex2i(x2, y2); // } // GL11.glEnd(); // this.setColor(Color.WHITE); // } // // public void drawString(String str, int x, int y, Color c) { // this.drawString(str, x, y, c, false); // } // // public void drawString(String str, int x, int y, Color c, boolean shadow) { // textRenderer.begin(); // { // if (shadow) { // this.setColor(Color.BLACK); // textRenderer.drawString(str, x + 1, y + 1); // } // // this.setColor(c); // textRenderer.drawString(str, x, y); // this.setColor(Color.WHITE); // } // textRenderer.end(); // } // // public void drawSprite(Sprite sprite, int x, int y, int width, int height) { // // Bind the texture // GL11.glBindTexture(GL11.GL_TEXTURE_2D, sprite.textureID); // // GL11.glBegin(GL11.GL_QUADS); // { // GL11.glTexCoord2f(0, 0); // GL11.glVertex2i(x, y); // // GL11.glTexCoord2f(0, 1); // GL11.glVertex2i(x, y + height); // // GL11.glTexCoord2f(1, 1); // GL11.glVertex2i(x + width, y + height); // // GL11.glTexCoord2f(1, 0); // GL11.glVertex2i(x + width, y); // } // GL11.glEnd(); // // // Unbind the texture // GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0); // } // } // Path: game-graphics/src/main/java/com/game/graphics/widget/ProgressBar.java import java.awt.Color; import com.game.graphics.renderer.Graphics2D; package com.game.graphics.widget; public class ProgressBar extends Widget { protected int value; protected Color color; public ProgressBar(int width, int height) { super(width, height, false); // Default to not started color = new Color(0f, 0.5f, 0f); value = 0; } public int getValue() { return value; } public Color getColor() { return color; } @Override
protected void display(Graphics2D g, int x, int y) {
reines/game
game-tools/src/main/java/com/game/tools/fontconverter/FontConverter.java
// Path: game-common/src/main/java/com/game/common/util/PersistenceManager.java // public class PersistenceManager { // private static final Logger log = LoggerFactory.getLogger(PersistenceManager.class); // // public class PacketHandler { // public Packet.Type[] types; // public Class<?> handler; // } // // public class ItemHandler { // public int[] ids; // public Class<?> handler; // } // // protected static final XStream xstream; // // static { // xstream = new XStream(); // // xstream.alias("type", Packet.Type.class); // // xstream.alias("PacketHandler", PacketHandler.class); // xstream.alias("ItemHandler", ItemHandler.class); // // xstream.alias("ItemDef", Item.Definition.class); // xstream.alias("TileDef", Tile.Definition.class); // } // // public static void alias(String name, Class<?> type) { // xstream.alias(name, type); // } // // public static Object load(URL path) { // try { // InputStream in = path.openStream(); // Object o = xstream.fromXML(in); // in.close(); // // return o; // } // catch (IOException ioe) { // log.error("Error loading object: " + ioe.getMessage()); // System.exit(1); // fatal error // // return null; // } // } // // public static void save(Object o, File f) throws IOException { // OutputStream out = new FileOutputStream(f); // xstream.toXML(o, out); // out.close(); // } // } // // Path: game-graphics/src/main/java/com/game/graphics/renderer/FontData.java // public class FontData { // public final Glyph[] glyphs; // public final int fontHeight; // // public FontData(int numGlyphs, int fontHeight) { // glyphs = new Glyph[numGlyphs]; // this.fontHeight = fontHeight; // } // } // // Path: game-graphics/src/main/java/com/game/graphics/renderer/Glyph.java // public class Glyph { // public final int width; // public final int height; // public final int x; // public final int y; // // public Glyph(int width, int height, int x, int y) { // this.width = width; // this.height = height; // this.x = x; // this.y = y; // } // }
import java.awt.Color; import java.awt.Font; import java.awt.FontFormatException; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.game.common.util.PersistenceManager; import com.game.graphics.renderer.FontData; import com.game.graphics.renderer.Glyph;
package com.game.tools.fontconverter; public class FontConverter { private static final Logger log = LoggerFactory.getLogger(FontConverter.class); public static final int DEFAULT_FONT_SIZE = 11; protected static final Options options; static { options = new Options(); options.addOption("h", "help", false, "Print this help."); options.addOption("i", "input-file", true, "The TTF font file to convert."); options.addOption("go", "glyph-output-file", true, "Path to the glyph output file, default <fontname>.png."); options.addOption("do", "data-output-file", true, "Path to the data output file, default <fontname>.xml."); options.addOption("s", "size", true, "The font size, default " + DEFAULT_FONT_SIZE + ".");
// Path: game-common/src/main/java/com/game/common/util/PersistenceManager.java // public class PersistenceManager { // private static final Logger log = LoggerFactory.getLogger(PersistenceManager.class); // // public class PacketHandler { // public Packet.Type[] types; // public Class<?> handler; // } // // public class ItemHandler { // public int[] ids; // public Class<?> handler; // } // // protected static final XStream xstream; // // static { // xstream = new XStream(); // // xstream.alias("type", Packet.Type.class); // // xstream.alias("PacketHandler", PacketHandler.class); // xstream.alias("ItemHandler", ItemHandler.class); // // xstream.alias("ItemDef", Item.Definition.class); // xstream.alias("TileDef", Tile.Definition.class); // } // // public static void alias(String name, Class<?> type) { // xstream.alias(name, type); // } // // public static Object load(URL path) { // try { // InputStream in = path.openStream(); // Object o = xstream.fromXML(in); // in.close(); // // return o; // } // catch (IOException ioe) { // log.error("Error loading object: " + ioe.getMessage()); // System.exit(1); // fatal error // // return null; // } // } // // public static void save(Object o, File f) throws IOException { // OutputStream out = new FileOutputStream(f); // xstream.toXML(o, out); // out.close(); // } // } // // Path: game-graphics/src/main/java/com/game/graphics/renderer/FontData.java // public class FontData { // public final Glyph[] glyphs; // public final int fontHeight; // // public FontData(int numGlyphs, int fontHeight) { // glyphs = new Glyph[numGlyphs]; // this.fontHeight = fontHeight; // } // } // // Path: game-graphics/src/main/java/com/game/graphics/renderer/Glyph.java // public class Glyph { // public final int width; // public final int height; // public final int x; // public final int y; // // public Glyph(int width, int height, int x, int y) { // this.width = width; // this.height = height; // this.x = x; // this.y = y; // } // } // Path: game-tools/src/main/java/com/game/tools/fontconverter/FontConverter.java import java.awt.Color; import java.awt.Font; import java.awt.FontFormatException; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.game.common.util.PersistenceManager; import com.game.graphics.renderer.FontData; import com.game.graphics.renderer.Glyph; package com.game.tools.fontconverter; public class FontConverter { private static final Logger log = LoggerFactory.getLogger(FontConverter.class); public static final int DEFAULT_FONT_SIZE = 11; protected static final Options options; static { options = new Options(); options.addOption("h", "help", false, "Print this help."); options.addOption("i", "input-file", true, "The TTF font file to convert."); options.addOption("go", "glyph-output-file", true, "Path to the glyph output file, default <fontname>.png."); options.addOption("do", "data-output-file", true, "Path to the data output file, default <fontname>.xml."); options.addOption("s", "size", true, "The font size, default " + DEFAULT_FONT_SIZE + ".");
PersistenceManager.alias("FontData", FontData.class);
reines/game
game-tools/src/main/java/com/game/tools/fontconverter/FontConverter.java
// Path: game-common/src/main/java/com/game/common/util/PersistenceManager.java // public class PersistenceManager { // private static final Logger log = LoggerFactory.getLogger(PersistenceManager.class); // // public class PacketHandler { // public Packet.Type[] types; // public Class<?> handler; // } // // public class ItemHandler { // public int[] ids; // public Class<?> handler; // } // // protected static final XStream xstream; // // static { // xstream = new XStream(); // // xstream.alias("type", Packet.Type.class); // // xstream.alias("PacketHandler", PacketHandler.class); // xstream.alias("ItemHandler", ItemHandler.class); // // xstream.alias("ItemDef", Item.Definition.class); // xstream.alias("TileDef", Tile.Definition.class); // } // // public static void alias(String name, Class<?> type) { // xstream.alias(name, type); // } // // public static Object load(URL path) { // try { // InputStream in = path.openStream(); // Object o = xstream.fromXML(in); // in.close(); // // return o; // } // catch (IOException ioe) { // log.error("Error loading object: " + ioe.getMessage()); // System.exit(1); // fatal error // // return null; // } // } // // public static void save(Object o, File f) throws IOException { // OutputStream out = new FileOutputStream(f); // xstream.toXML(o, out); // out.close(); // } // } // // Path: game-graphics/src/main/java/com/game/graphics/renderer/FontData.java // public class FontData { // public final Glyph[] glyphs; // public final int fontHeight; // // public FontData(int numGlyphs, int fontHeight) { // glyphs = new Glyph[numGlyphs]; // this.fontHeight = fontHeight; // } // } // // Path: game-graphics/src/main/java/com/game/graphics/renderer/Glyph.java // public class Glyph { // public final int width; // public final int height; // public final int x; // public final int y; // // public Glyph(int width, int height, int x, int y) { // this.width = width; // this.height = height; // this.x = x; // this.y = y; // } // }
import java.awt.Color; import java.awt.Font; import java.awt.FontFormatException; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.game.common.util.PersistenceManager; import com.game.graphics.renderer.FontData; import com.game.graphics.renderer.Glyph;
package com.game.tools.fontconverter; public class FontConverter { private static final Logger log = LoggerFactory.getLogger(FontConverter.class); public static final int DEFAULT_FONT_SIZE = 11; protected static final Options options; static { options = new Options(); options.addOption("h", "help", false, "Print this help."); options.addOption("i", "input-file", true, "The TTF font file to convert."); options.addOption("go", "glyph-output-file", true, "Path to the glyph output file, default <fontname>.png."); options.addOption("do", "data-output-file", true, "Path to the data output file, default <fontname>.xml."); options.addOption("s", "size", true, "The font size, default " + DEFAULT_FONT_SIZE + ".");
// Path: game-common/src/main/java/com/game/common/util/PersistenceManager.java // public class PersistenceManager { // private static final Logger log = LoggerFactory.getLogger(PersistenceManager.class); // // public class PacketHandler { // public Packet.Type[] types; // public Class<?> handler; // } // // public class ItemHandler { // public int[] ids; // public Class<?> handler; // } // // protected static final XStream xstream; // // static { // xstream = new XStream(); // // xstream.alias("type", Packet.Type.class); // // xstream.alias("PacketHandler", PacketHandler.class); // xstream.alias("ItemHandler", ItemHandler.class); // // xstream.alias("ItemDef", Item.Definition.class); // xstream.alias("TileDef", Tile.Definition.class); // } // // public static void alias(String name, Class<?> type) { // xstream.alias(name, type); // } // // public static Object load(URL path) { // try { // InputStream in = path.openStream(); // Object o = xstream.fromXML(in); // in.close(); // // return o; // } // catch (IOException ioe) { // log.error("Error loading object: " + ioe.getMessage()); // System.exit(1); // fatal error // // return null; // } // } // // public static void save(Object o, File f) throws IOException { // OutputStream out = new FileOutputStream(f); // xstream.toXML(o, out); // out.close(); // } // } // // Path: game-graphics/src/main/java/com/game/graphics/renderer/FontData.java // public class FontData { // public final Glyph[] glyphs; // public final int fontHeight; // // public FontData(int numGlyphs, int fontHeight) { // glyphs = new Glyph[numGlyphs]; // this.fontHeight = fontHeight; // } // } // // Path: game-graphics/src/main/java/com/game/graphics/renderer/Glyph.java // public class Glyph { // public final int width; // public final int height; // public final int x; // public final int y; // // public Glyph(int width, int height, int x, int y) { // this.width = width; // this.height = height; // this.x = x; // this.y = y; // } // } // Path: game-tools/src/main/java/com/game/tools/fontconverter/FontConverter.java import java.awt.Color; import java.awt.Font; import java.awt.FontFormatException; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.game.common.util.PersistenceManager; import com.game.graphics.renderer.FontData; import com.game.graphics.renderer.Glyph; package com.game.tools.fontconverter; public class FontConverter { private static final Logger log = LoggerFactory.getLogger(FontConverter.class); public static final int DEFAULT_FONT_SIZE = 11; protected static final Options options; static { options = new Options(); options.addOption("h", "help", false, "Print this help."); options.addOption("i", "input-file", true, "The TTF font file to convert."); options.addOption("go", "glyph-output-file", true, "Path to the glyph output file, default <fontname>.png."); options.addOption("do", "data-output-file", true, "Path to the data output file, default <fontname>.xml."); options.addOption("s", "size", true, "The font size, default " + DEFAULT_FONT_SIZE + ".");
PersistenceManager.alias("FontData", FontData.class);
reines/game
game-tools/src/main/java/com/game/tools/fontconverter/FontConverter.java
// Path: game-common/src/main/java/com/game/common/util/PersistenceManager.java // public class PersistenceManager { // private static final Logger log = LoggerFactory.getLogger(PersistenceManager.class); // // public class PacketHandler { // public Packet.Type[] types; // public Class<?> handler; // } // // public class ItemHandler { // public int[] ids; // public Class<?> handler; // } // // protected static final XStream xstream; // // static { // xstream = new XStream(); // // xstream.alias("type", Packet.Type.class); // // xstream.alias("PacketHandler", PacketHandler.class); // xstream.alias("ItemHandler", ItemHandler.class); // // xstream.alias("ItemDef", Item.Definition.class); // xstream.alias("TileDef", Tile.Definition.class); // } // // public static void alias(String name, Class<?> type) { // xstream.alias(name, type); // } // // public static Object load(URL path) { // try { // InputStream in = path.openStream(); // Object o = xstream.fromXML(in); // in.close(); // // return o; // } // catch (IOException ioe) { // log.error("Error loading object: " + ioe.getMessage()); // System.exit(1); // fatal error // // return null; // } // } // // public static void save(Object o, File f) throws IOException { // OutputStream out = new FileOutputStream(f); // xstream.toXML(o, out); // out.close(); // } // } // // Path: game-graphics/src/main/java/com/game/graphics/renderer/FontData.java // public class FontData { // public final Glyph[] glyphs; // public final int fontHeight; // // public FontData(int numGlyphs, int fontHeight) { // glyphs = new Glyph[numGlyphs]; // this.fontHeight = fontHeight; // } // } // // Path: game-graphics/src/main/java/com/game/graphics/renderer/Glyph.java // public class Glyph { // public final int width; // public final int height; // public final int x; // public final int y; // // public Glyph(int width, int height, int x, int y) { // this.width = width; // this.height = height; // this.x = x; // this.y = y; // } // }
import java.awt.Color; import java.awt.Font; import java.awt.FontFormatException; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.game.common.util.PersistenceManager; import com.game.graphics.renderer.FontData; import com.game.graphics.renderer.Glyph;
package com.game.tools.fontconverter; public class FontConverter { private static final Logger log = LoggerFactory.getLogger(FontConverter.class); public static final int DEFAULT_FONT_SIZE = 11; protected static final Options options; static { options = new Options(); options.addOption("h", "help", false, "Print this help."); options.addOption("i", "input-file", true, "The TTF font file to convert."); options.addOption("go", "glyph-output-file", true, "Path to the glyph output file, default <fontname>.png."); options.addOption("do", "data-output-file", true, "Path to the data output file, default <fontname>.xml."); options.addOption("s", "size", true, "The font size, default " + DEFAULT_FONT_SIZE + "."); PersistenceManager.alias("FontData", FontData.class);
// Path: game-common/src/main/java/com/game/common/util/PersistenceManager.java // public class PersistenceManager { // private static final Logger log = LoggerFactory.getLogger(PersistenceManager.class); // // public class PacketHandler { // public Packet.Type[] types; // public Class<?> handler; // } // // public class ItemHandler { // public int[] ids; // public Class<?> handler; // } // // protected static final XStream xstream; // // static { // xstream = new XStream(); // // xstream.alias("type", Packet.Type.class); // // xstream.alias("PacketHandler", PacketHandler.class); // xstream.alias("ItemHandler", ItemHandler.class); // // xstream.alias("ItemDef", Item.Definition.class); // xstream.alias("TileDef", Tile.Definition.class); // } // // public static void alias(String name, Class<?> type) { // xstream.alias(name, type); // } // // public static Object load(URL path) { // try { // InputStream in = path.openStream(); // Object o = xstream.fromXML(in); // in.close(); // // return o; // } // catch (IOException ioe) { // log.error("Error loading object: " + ioe.getMessage()); // System.exit(1); // fatal error // // return null; // } // } // // public static void save(Object o, File f) throws IOException { // OutputStream out = new FileOutputStream(f); // xstream.toXML(o, out); // out.close(); // } // } // // Path: game-graphics/src/main/java/com/game/graphics/renderer/FontData.java // public class FontData { // public final Glyph[] glyphs; // public final int fontHeight; // // public FontData(int numGlyphs, int fontHeight) { // glyphs = new Glyph[numGlyphs]; // this.fontHeight = fontHeight; // } // } // // Path: game-graphics/src/main/java/com/game/graphics/renderer/Glyph.java // public class Glyph { // public final int width; // public final int height; // public final int x; // public final int y; // // public Glyph(int width, int height, int x, int y) { // this.width = width; // this.height = height; // this.x = x; // this.y = y; // } // } // Path: game-tools/src/main/java/com/game/tools/fontconverter/FontConverter.java import java.awt.Color; import java.awt.Font; import java.awt.FontFormatException; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.game.common.util.PersistenceManager; import com.game.graphics.renderer.FontData; import com.game.graphics.renderer.Glyph; package com.game.tools.fontconverter; public class FontConverter { private static final Logger log = LoggerFactory.getLogger(FontConverter.class); public static final int DEFAULT_FONT_SIZE = 11; protected static final Options options; static { options = new Options(); options.addOption("h", "help", false, "Print this help."); options.addOption("i", "input-file", true, "The TTF font file to convert."); options.addOption("go", "glyph-output-file", true, "Path to the glyph output file, default <fontname>.png."); options.addOption("do", "data-output-file", true, "Path to the data output file, default <fontname>.xml."); options.addOption("s", "size", true, "The font size, default " + DEFAULT_FONT_SIZE + "."); PersistenceManager.alias("FontData", FontData.class);
PersistenceManager.alias("Glyph", Glyph.class);
reines/game
game-client/src/main/java/com/game/client/engine/Camera.java
// Path: game-graphics/src/main/java/com/game/graphics/input/Keyboard.java // public class Keyboard { // // public static final int KEY_UP = 200; // public static final int KEY_LEFT = 203; // public static final int KEY_RIGHT = 205; // public static final int KEY_DOWN = 208; // // public static final int KEY_F1 = 59; // public static final int KEY_F2 = 60; // public static final int KEY_F3 = 61; // public static final int KEY_F4 = 62; // public static final int KEY_F5 = 63; // public static final int KEY_F6 = 64; // public static final int KEY_F7 = 65; // public static final int KEY_F8 = 66; // public static final int KEY_F9 = 67; // public static final int KEY_F10 = 68; // public static final int KEY_F11 = 87; // public static final int KEY_F12 = 88; // public static final int KEY_F13 = 100; // public static final int KEY_F14 = 101; // public static final int KEY_F15 = 102; // // public Keyboard() { // try { // org.lwjgl.input.Keyboard.enableRepeatEvents(true); // org.lwjgl.input.Keyboard.create(); // } // catch (LWJGLException e) { // // fatal error // throw new RuntimeException("Error setting up keyboard: " + e); // } // } // // public boolean isKeyDown(int keyCode) { // return org.lwjgl.input.Keyboard.isKeyDown(keyCode); // } // // public void update(KeyListener listener) { // while (org.lwjgl.input.Keyboard.next()) { // // If it wasn't a press, ignore it // if (!org.lwjgl.input.Keyboard.getEventKeyState()) // continue; // // listener.keyPressed(org.lwjgl.input.Keyboard.getEventKey(), org.lwjgl.input.Keyboard.getEventCharacter()); // } // } // }
import com.game.graphics.input.Keyboard;
package com.game.client.engine; public class Camera { public static final int ROTATION_STEP = 10; public static final int ROTATION_DEFAULT = 0; public static final int ZOOM_STEP = 1; public static final int ZOOM_DEFAULT = 8; public static final int ZOOM_MIN = 6; public static final int ZOOM_MAX = 12;
// Path: game-graphics/src/main/java/com/game/graphics/input/Keyboard.java // public class Keyboard { // // public static final int KEY_UP = 200; // public static final int KEY_LEFT = 203; // public static final int KEY_RIGHT = 205; // public static final int KEY_DOWN = 208; // // public static final int KEY_F1 = 59; // public static final int KEY_F2 = 60; // public static final int KEY_F3 = 61; // public static final int KEY_F4 = 62; // public static final int KEY_F5 = 63; // public static final int KEY_F6 = 64; // public static final int KEY_F7 = 65; // public static final int KEY_F8 = 66; // public static final int KEY_F9 = 67; // public static final int KEY_F10 = 68; // public static final int KEY_F11 = 87; // public static final int KEY_F12 = 88; // public static final int KEY_F13 = 100; // public static final int KEY_F14 = 101; // public static final int KEY_F15 = 102; // // public Keyboard() { // try { // org.lwjgl.input.Keyboard.enableRepeatEvents(true); // org.lwjgl.input.Keyboard.create(); // } // catch (LWJGLException e) { // // fatal error // throw new RuntimeException("Error setting up keyboard: " + e); // } // } // // public boolean isKeyDown(int keyCode) { // return org.lwjgl.input.Keyboard.isKeyDown(keyCode); // } // // public void update(KeyListener listener) { // while (org.lwjgl.input.Keyboard.next()) { // // If it wasn't a press, ignore it // if (!org.lwjgl.input.Keyboard.getEventKeyState()) // continue; // // listener.keyPressed(org.lwjgl.input.Keyboard.getEventKey(), org.lwjgl.input.Keyboard.getEventCharacter()); // } // } // } // Path: game-client/src/main/java/com/game/client/engine/Camera.java import com.game.graphics.input.Keyboard; package com.game.client.engine; public class Camera { public static final int ROTATION_STEP = 10; public static final int ROTATION_DEFAULT = 0; public static final int ZOOM_STEP = 1; public static final int ZOOM_DEFAULT = 8; public static final int ZOOM_MIN = 6; public static final int ZOOM_MAX = 12;
protected final Keyboard keyboard;
reines/game
game-common/src/test/java/com/game/common/util/EntityListTest.java
// Path: game-common/src/main/java/com/game/common/model/Entity.java // public abstract class Entity extends Observable { // // public abstract Hash getID(); // public abstract Point getLocation(); // public abstract void setLocation(Point p); // // } // // Path: game-common/src/main/java/com/game/common/model/Hash.java // public class Hash implements Comparable<Hash>, Serializable { // private static final Logger log = LoggerFactory.getLogger(Hash.class); // private static final long serialVersionUID = 1L; // // public static final int LENGTH = 20; // in bytes // public static final String ALGORITHM = "SHA-1"; // // protected static MessageDigest digest; // // static { // try { // digest = MessageDigest.getInstance(ALGORITHM); // } // catch (NoSuchAlgorithmException e) { // log.error("No such hashing algorithm: " + ALGORITHM); // System.exit(1); // fatal error // } // } // // public static Hash fromString(String hex) { // Hash hash = new Hash(); // hash.setHex(hex); // // return hash; // } // // public static Hash fromBytes(byte[] bytes) { // Hash hash = new Hash(); // hash.setBytes(bytes); // // return hash; // } // // protected String hex; // // public Hash(String str) { // try { // digest.update(str.getBytes("UTF-8")); // } // catch (UnsupportedEncodingException e) { } // // this.setBytes(digest.digest()); // } // // private Hash() { // hex = null; // } // // private void setHex(String hex) { // this.hex = hex; // } // // private void setBytes(byte[] bytes) { // Formatter foramtter = new Formatter(); // // for (byte b : bytes) // foramtter.format("%02x", b); // // this.hex = foramtter.toString(); // } // // public byte[] getBytes() { // byte[] bytes = new byte[LENGTH]; // // for (int i = 0;i < LENGTH;i++) // bytes[i] = (byte) Short.parseShort(hex.substring(2 * i, 2 * (i + 1)), 16); // // return bytes; // } // // @Override // public String toString() { // return hex; // } // // @Override // public int hashCode() { // return hex.hashCode(); // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof Hash)) // return false; // // Hash h = (Hash) o; // return hex.equals(h.hex); // } // // @Override // public int compareTo(Hash h) { // return hex.compareTo(h.hex); // } // } // // Path: game-common/src/main/java/com/game/common/model/Point.java // public class Point implements Serializable { // private static final long serialVersionUID = 1L; // // public static final Point ZERO = new Point(0, 0); // // public int x; // public int y; // // @SuppressWarnings("unused") // private Point() { } // For hibernate // // public Point(int x, int y) { // this.x = x; // this.y = y; // } // // public void set(Point location) { // this.x = location.x; // this.y = location.y; // } // // public double distanceTo(Point p) { // // Euclidean distance // return Math.sqrt(Math.pow(this.x - p.x, 2) + Math.pow(this.y - p.y, 2)); // } // // @Override // public int hashCode() { // return x << 16 | y; // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof Point)) // return false; // // Point p = (Point) o; // return x == p.x && y == p.y; // } // // @Override // public String toString() { // return "(" + x + ", " + y + ")"; // } // }
import junit.framework.TestCase; import com.game.common.model.Entity; import com.game.common.model.Hash; import com.game.common.model.Point;
package com.game.common.util; public class EntityListTest extends TestCase { private static class TestEntity extends Entity {
// Path: game-common/src/main/java/com/game/common/model/Entity.java // public abstract class Entity extends Observable { // // public abstract Hash getID(); // public abstract Point getLocation(); // public abstract void setLocation(Point p); // // } // // Path: game-common/src/main/java/com/game/common/model/Hash.java // public class Hash implements Comparable<Hash>, Serializable { // private static final Logger log = LoggerFactory.getLogger(Hash.class); // private static final long serialVersionUID = 1L; // // public static final int LENGTH = 20; // in bytes // public static final String ALGORITHM = "SHA-1"; // // protected static MessageDigest digest; // // static { // try { // digest = MessageDigest.getInstance(ALGORITHM); // } // catch (NoSuchAlgorithmException e) { // log.error("No such hashing algorithm: " + ALGORITHM); // System.exit(1); // fatal error // } // } // // public static Hash fromString(String hex) { // Hash hash = new Hash(); // hash.setHex(hex); // // return hash; // } // // public static Hash fromBytes(byte[] bytes) { // Hash hash = new Hash(); // hash.setBytes(bytes); // // return hash; // } // // protected String hex; // // public Hash(String str) { // try { // digest.update(str.getBytes("UTF-8")); // } // catch (UnsupportedEncodingException e) { } // // this.setBytes(digest.digest()); // } // // private Hash() { // hex = null; // } // // private void setHex(String hex) { // this.hex = hex; // } // // private void setBytes(byte[] bytes) { // Formatter foramtter = new Formatter(); // // for (byte b : bytes) // foramtter.format("%02x", b); // // this.hex = foramtter.toString(); // } // // public byte[] getBytes() { // byte[] bytes = new byte[LENGTH]; // // for (int i = 0;i < LENGTH;i++) // bytes[i] = (byte) Short.parseShort(hex.substring(2 * i, 2 * (i + 1)), 16); // // return bytes; // } // // @Override // public String toString() { // return hex; // } // // @Override // public int hashCode() { // return hex.hashCode(); // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof Hash)) // return false; // // Hash h = (Hash) o; // return hex.equals(h.hex); // } // // @Override // public int compareTo(Hash h) { // return hex.compareTo(h.hex); // } // } // // Path: game-common/src/main/java/com/game/common/model/Point.java // public class Point implements Serializable { // private static final long serialVersionUID = 1L; // // public static final Point ZERO = new Point(0, 0); // // public int x; // public int y; // // @SuppressWarnings("unused") // private Point() { } // For hibernate // // public Point(int x, int y) { // this.x = x; // this.y = y; // } // // public void set(Point location) { // this.x = location.x; // this.y = location.y; // } // // public double distanceTo(Point p) { // // Euclidean distance // return Math.sqrt(Math.pow(this.x - p.x, 2) + Math.pow(this.y - p.y, 2)); // } // // @Override // public int hashCode() { // return x << 16 | y; // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof Point)) // return false; // // Point p = (Point) o; // return x == p.x && y == p.y; // } // // @Override // public String toString() { // return "(" + x + ", " + y + ")"; // } // } // Path: game-common/src/test/java/com/game/common/util/EntityListTest.java import junit.framework.TestCase; import com.game.common.model.Entity; import com.game.common.model.Hash; import com.game.common.model.Point; package com.game.common.util; public class EntityListTest extends TestCase { private static class TestEntity extends Entity {
protected final Hash id;
reines/game
game-common/src/test/java/com/game/common/util/EntityListTest.java
// Path: game-common/src/main/java/com/game/common/model/Entity.java // public abstract class Entity extends Observable { // // public abstract Hash getID(); // public abstract Point getLocation(); // public abstract void setLocation(Point p); // // } // // Path: game-common/src/main/java/com/game/common/model/Hash.java // public class Hash implements Comparable<Hash>, Serializable { // private static final Logger log = LoggerFactory.getLogger(Hash.class); // private static final long serialVersionUID = 1L; // // public static final int LENGTH = 20; // in bytes // public static final String ALGORITHM = "SHA-1"; // // protected static MessageDigest digest; // // static { // try { // digest = MessageDigest.getInstance(ALGORITHM); // } // catch (NoSuchAlgorithmException e) { // log.error("No such hashing algorithm: " + ALGORITHM); // System.exit(1); // fatal error // } // } // // public static Hash fromString(String hex) { // Hash hash = new Hash(); // hash.setHex(hex); // // return hash; // } // // public static Hash fromBytes(byte[] bytes) { // Hash hash = new Hash(); // hash.setBytes(bytes); // // return hash; // } // // protected String hex; // // public Hash(String str) { // try { // digest.update(str.getBytes("UTF-8")); // } // catch (UnsupportedEncodingException e) { } // // this.setBytes(digest.digest()); // } // // private Hash() { // hex = null; // } // // private void setHex(String hex) { // this.hex = hex; // } // // private void setBytes(byte[] bytes) { // Formatter foramtter = new Formatter(); // // for (byte b : bytes) // foramtter.format("%02x", b); // // this.hex = foramtter.toString(); // } // // public byte[] getBytes() { // byte[] bytes = new byte[LENGTH]; // // for (int i = 0;i < LENGTH;i++) // bytes[i] = (byte) Short.parseShort(hex.substring(2 * i, 2 * (i + 1)), 16); // // return bytes; // } // // @Override // public String toString() { // return hex; // } // // @Override // public int hashCode() { // return hex.hashCode(); // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof Hash)) // return false; // // Hash h = (Hash) o; // return hex.equals(h.hex); // } // // @Override // public int compareTo(Hash h) { // return hex.compareTo(h.hex); // } // } // // Path: game-common/src/main/java/com/game/common/model/Point.java // public class Point implements Serializable { // private static final long serialVersionUID = 1L; // // public static final Point ZERO = new Point(0, 0); // // public int x; // public int y; // // @SuppressWarnings("unused") // private Point() { } // For hibernate // // public Point(int x, int y) { // this.x = x; // this.y = y; // } // // public void set(Point location) { // this.x = location.x; // this.y = location.y; // } // // public double distanceTo(Point p) { // // Euclidean distance // return Math.sqrt(Math.pow(this.x - p.x, 2) + Math.pow(this.y - p.y, 2)); // } // // @Override // public int hashCode() { // return x << 16 | y; // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof Point)) // return false; // // Point p = (Point) o; // return x == p.x && y == p.y; // } // // @Override // public String toString() { // return "(" + x + ", " + y + ")"; // } // }
import junit.framework.TestCase; import com.game.common.model.Entity; import com.game.common.model.Hash; import com.game.common.model.Point;
package com.game.common.util; public class EntityListTest extends TestCase { private static class TestEntity extends Entity { protected final Hash id; public TestEntity(String str) { id = new Hash(str); } @Override public Hash getID() { return id; } @Override
// Path: game-common/src/main/java/com/game/common/model/Entity.java // public abstract class Entity extends Observable { // // public abstract Hash getID(); // public abstract Point getLocation(); // public abstract void setLocation(Point p); // // } // // Path: game-common/src/main/java/com/game/common/model/Hash.java // public class Hash implements Comparable<Hash>, Serializable { // private static final Logger log = LoggerFactory.getLogger(Hash.class); // private static final long serialVersionUID = 1L; // // public static final int LENGTH = 20; // in bytes // public static final String ALGORITHM = "SHA-1"; // // protected static MessageDigest digest; // // static { // try { // digest = MessageDigest.getInstance(ALGORITHM); // } // catch (NoSuchAlgorithmException e) { // log.error("No such hashing algorithm: " + ALGORITHM); // System.exit(1); // fatal error // } // } // // public static Hash fromString(String hex) { // Hash hash = new Hash(); // hash.setHex(hex); // // return hash; // } // // public static Hash fromBytes(byte[] bytes) { // Hash hash = new Hash(); // hash.setBytes(bytes); // // return hash; // } // // protected String hex; // // public Hash(String str) { // try { // digest.update(str.getBytes("UTF-8")); // } // catch (UnsupportedEncodingException e) { } // // this.setBytes(digest.digest()); // } // // private Hash() { // hex = null; // } // // private void setHex(String hex) { // this.hex = hex; // } // // private void setBytes(byte[] bytes) { // Formatter foramtter = new Formatter(); // // for (byte b : bytes) // foramtter.format("%02x", b); // // this.hex = foramtter.toString(); // } // // public byte[] getBytes() { // byte[] bytes = new byte[LENGTH]; // // for (int i = 0;i < LENGTH;i++) // bytes[i] = (byte) Short.parseShort(hex.substring(2 * i, 2 * (i + 1)), 16); // // return bytes; // } // // @Override // public String toString() { // return hex; // } // // @Override // public int hashCode() { // return hex.hashCode(); // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof Hash)) // return false; // // Hash h = (Hash) o; // return hex.equals(h.hex); // } // // @Override // public int compareTo(Hash h) { // return hex.compareTo(h.hex); // } // } // // Path: game-common/src/main/java/com/game/common/model/Point.java // public class Point implements Serializable { // private static final long serialVersionUID = 1L; // // public static final Point ZERO = new Point(0, 0); // // public int x; // public int y; // // @SuppressWarnings("unused") // private Point() { } // For hibernate // // public Point(int x, int y) { // this.x = x; // this.y = y; // } // // public void set(Point location) { // this.x = location.x; // this.y = location.y; // } // // public double distanceTo(Point p) { // // Euclidean distance // return Math.sqrt(Math.pow(this.x - p.x, 2) + Math.pow(this.y - p.y, 2)); // } // // @Override // public int hashCode() { // return x << 16 | y; // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof Point)) // return false; // // Point p = (Point) o; // return x == p.x && y == p.y; // } // // @Override // public String toString() { // return "(" + x + ", " + y + ")"; // } // } // Path: game-common/src/test/java/com/game/common/util/EntityListTest.java import junit.framework.TestCase; import com.game.common.model.Entity; import com.game.common.model.Hash; import com.game.common.model.Point; package com.game.common.util; public class EntityListTest extends TestCase { private static class TestEntity extends Entity { protected final Hash id; public TestEntity(String str) { id = new Hash(str); } @Override public Hash getID() { return id; } @Override
public Point getLocation() {
reines/game
game-client/src/main/java/com/game/client/model/LocalMapSector.java
// Path: game-common/src/main/java/com/game/common/model/Map.java // public abstract class Map { // public static final int MAGIC_NUMBER = 0x4531; // // protected final int width; // protected final int height; // protected final int sectorSize; // // protected Map(int width, int height, int sectorSize) { // this.width = width; // this.height = height; // this.sectorSize = sectorSize; // } // // public int getSectorSize() { // return sectorSize; // } // // public int getWidth() { // return width * sectorSize; // } // // public int getHeight() { // return height * sectorSize; // } // // public abstract Tile getTile(int x, int y); // // public abstract Tile getTile(Point p); // // public Path generatePath(Point start, Point target) { // PathFinder finder = new PathFinder(this, start); // // return finder.generatePath(target); // } // // public boolean isValidStep(Point from, Point to) { // // If the step is more than 1 tile away, it isn't valid // if (from.distanceTo(to) >= 2) // return false; // // Tile fromTile = this.getTile(from); // // This shouldn't happen! // if (fromTile == null) // return false; // // Tile toTile = this.getTile(to); // // If it isn't found in the map, or isn't walkable then skip it // if (toTile == null || !toTile.isWalkable()) // return false; // // // Moving left, check our old y // if (from.x > to.x) { // Tile toCheck = this.getTile(from.x, from.y); // if (toCheck == null || toCheck.isBlockedVertically()) // return false; // } // // Moving right, check our old y // else if (from.x < to.x) { // Tile toCheck = this.getTile(from.x + 1, from.y); // if (toCheck == null || toCheck.isBlockedVertically()) // return false; // } // // // Moving down, check our old x // if (from.y > to.y){ // Tile toCheck = this.getTile(from.x, from.y - 1); // if (toCheck == null || toCheck.isBlockedHorizontally()) // return false; // } // // Moving up, check our old x // else if (from.y < to.y) { // Tile toCheck = this.getTile(from.x, from.y); // if (toCheck == null || toCheck.isBlockedHorizontally()) // return false; // } // // // We are moving straight, and aren't blocked // if ((from.x == to.x) || (from.y == to.y)) // return true; // // // We are moving diagonal, so we also need to check the destination tile isn't blocked // // // Moving left, check our new y // if (from.x > to.x) { // Tile toCheck = this.getTile(to.x + 1, to.y); // if (toCheck == null || toCheck.isBlockedVertically()) // return false; // } // // Moving right, check our new y // else if (from.x < to.x) { // Tile toCheck = this.getTile(to.x, to.y); // if (toCheck == null || toCheck.isBlockedVertically()) // return false; // } // // // Moving down, check our new x // if (from.y > to.y) { // Tile toCheck = this.getTile(to.x, to.y); // if (toCheck == null || toCheck.isBlockedHorizontally()) // return false; // } // // Moving up, check our new x // else if (from.y < to.y) { // Tile toCheck = this.getTile(to.x, to.y - 1); // if (toCheck == null || toCheck.isBlockedHorizontally()) // return false; // } // // return true; // } // // @Override // public String toString() { // return "map[width = " + this.getWidth() + ", height = " + this.getHeight() + ", sectorSize = " + this.getSectorSize() + "]"; // } // } // // Path: game-common/src/main/java/com/game/common/model/Point.java // public class Point implements Serializable { // private static final long serialVersionUID = 1L; // // public static final Point ZERO = new Point(0, 0); // // public int x; // public int y; // // @SuppressWarnings("unused") // private Point() { } // For hibernate // // public Point(int x, int y) { // this.x = x; // this.y = y; // } // // public void set(Point location) { // this.x = location.x; // this.y = location.y; // } // // public double distanceTo(Point p) { // // Euclidean distance // return Math.sqrt(Math.pow(this.x - p.x, 2) + Math.pow(this.y - p.y, 2)); // } // // @Override // public int hashCode() { // return x << 16 | y; // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof Point)) // return false; // // Point p = (Point) o; // return x == p.x && y == p.y; // } // // @Override // public String toString() { // return "(" + x + ", " + y + ")"; // } // }
import java.io.DataInputStream; import java.io.IOException; import java.net.URL; import java.util.zip.GZIPInputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.game.common.model.Map; import com.game.common.model.Point;
package com.game.client.model; public class LocalMapSector { private static final Logger log = LoggerFactory.getLogger(LocalMapSector.class);
// Path: game-common/src/main/java/com/game/common/model/Map.java // public abstract class Map { // public static final int MAGIC_NUMBER = 0x4531; // // protected final int width; // protected final int height; // protected final int sectorSize; // // protected Map(int width, int height, int sectorSize) { // this.width = width; // this.height = height; // this.sectorSize = sectorSize; // } // // public int getSectorSize() { // return sectorSize; // } // // public int getWidth() { // return width * sectorSize; // } // // public int getHeight() { // return height * sectorSize; // } // // public abstract Tile getTile(int x, int y); // // public abstract Tile getTile(Point p); // // public Path generatePath(Point start, Point target) { // PathFinder finder = new PathFinder(this, start); // // return finder.generatePath(target); // } // // public boolean isValidStep(Point from, Point to) { // // If the step is more than 1 tile away, it isn't valid // if (from.distanceTo(to) >= 2) // return false; // // Tile fromTile = this.getTile(from); // // This shouldn't happen! // if (fromTile == null) // return false; // // Tile toTile = this.getTile(to); // // If it isn't found in the map, or isn't walkable then skip it // if (toTile == null || !toTile.isWalkable()) // return false; // // // Moving left, check our old y // if (from.x > to.x) { // Tile toCheck = this.getTile(from.x, from.y); // if (toCheck == null || toCheck.isBlockedVertically()) // return false; // } // // Moving right, check our old y // else if (from.x < to.x) { // Tile toCheck = this.getTile(from.x + 1, from.y); // if (toCheck == null || toCheck.isBlockedVertically()) // return false; // } // // // Moving down, check our old x // if (from.y > to.y){ // Tile toCheck = this.getTile(from.x, from.y - 1); // if (toCheck == null || toCheck.isBlockedHorizontally()) // return false; // } // // Moving up, check our old x // else if (from.y < to.y) { // Tile toCheck = this.getTile(from.x, from.y); // if (toCheck == null || toCheck.isBlockedHorizontally()) // return false; // } // // // We are moving straight, and aren't blocked // if ((from.x == to.x) || (from.y == to.y)) // return true; // // // We are moving diagonal, so we also need to check the destination tile isn't blocked // // // Moving left, check our new y // if (from.x > to.x) { // Tile toCheck = this.getTile(to.x + 1, to.y); // if (toCheck == null || toCheck.isBlockedVertically()) // return false; // } // // Moving right, check our new y // else if (from.x < to.x) { // Tile toCheck = this.getTile(to.x, to.y); // if (toCheck == null || toCheck.isBlockedVertically()) // return false; // } // // // Moving down, check our new x // if (from.y > to.y) { // Tile toCheck = this.getTile(to.x, to.y); // if (toCheck == null || toCheck.isBlockedHorizontally()) // return false; // } // // Moving up, check our new x // else if (from.y < to.y) { // Tile toCheck = this.getTile(to.x, to.y - 1); // if (toCheck == null || toCheck.isBlockedHorizontally()) // return false; // } // // return true; // } // // @Override // public String toString() { // return "map[width = " + this.getWidth() + ", height = " + this.getHeight() + ", sectorSize = " + this.getSectorSize() + "]"; // } // } // // Path: game-common/src/main/java/com/game/common/model/Point.java // public class Point implements Serializable { // private static final long serialVersionUID = 1L; // // public static final Point ZERO = new Point(0, 0); // // public int x; // public int y; // // @SuppressWarnings("unused") // private Point() { } // For hibernate // // public Point(int x, int y) { // this.x = x; // this.y = y; // } // // public void set(Point location) { // this.x = location.x; // this.y = location.y; // } // // public double distanceTo(Point p) { // // Euclidean distance // return Math.sqrt(Math.pow(this.x - p.x, 2) + Math.pow(this.y - p.y, 2)); // } // // @Override // public int hashCode() { // return x << 16 | y; // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof Point)) // return false; // // Point p = (Point) o; // return x == p.x && y == p.y; // } // // @Override // public String toString() { // return "(" + x + ", " + y + ")"; // } // } // Path: game-client/src/main/java/com/game/client/model/LocalMapSector.java import java.io.DataInputStream; import java.io.IOException; import java.net.URL; import java.util.zip.GZIPInputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.game.common.model.Map; import com.game.common.model.Point; package com.game.client.model; public class LocalMapSector { private static final Logger log = LoggerFactory.getLogger(LocalMapSector.class);
public static LocalMapSector load(URL path, Point offset) {
reines/game
game-common/src/main/java/com/game/common/model/Item.java
// Path: game-common/src/main/java/com/game/common/util/PersistenceManager.java // public class PersistenceManager { // private static final Logger log = LoggerFactory.getLogger(PersistenceManager.class); // // public class PacketHandler { // public Packet.Type[] types; // public Class<?> handler; // } // // public class ItemHandler { // public int[] ids; // public Class<?> handler; // } // // protected static final XStream xstream; // // static { // xstream = new XStream(); // // xstream.alias("type", Packet.Type.class); // // xstream.alias("PacketHandler", PacketHandler.class); // xstream.alias("ItemHandler", ItemHandler.class); // // xstream.alias("ItemDef", Item.Definition.class); // xstream.alias("TileDef", Tile.Definition.class); // } // // public static void alias(String name, Class<?> type) { // xstream.alias(name, type); // } // // public static Object load(URL path) { // try { // InputStream in = path.openStream(); // Object o = xstream.fromXML(in); // in.close(); // // return o; // } // catch (IOException ioe) { // log.error("Error loading object: " + ioe.getMessage()); // System.exit(1); // fatal error // // return null; // } // } // // public static void save(Object o, File f) throws IOException { // OutputStream out = new FileOutputStream(f); // xstream.toXML(o, out); // out.close(); // } // }
import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.net.URL; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.game.common.util.PersistenceManager;
package com.game.common.model; public class Item implements Serializable { private static final Logger log = LoggerFactory.getLogger(Item.class); private static final long serialVersionUID = 1L; protected static final Map<Integer, Definition> definitions; static { definitions = Item.loadDefinitions(); if (log.isDebugEnabled()) log.debug("Loaded " + definitions.size() + " item definitions"); } public static Map<Integer, Definition> getDefinitions() { return definitions; } // do nothing - static {} does the work public static void load() { } @SuppressWarnings("unchecked") private static Map<Integer, Definition> loadDefinitions() { URL path = Item.class.getResource("items.xml"); if (path == null) { log.error("Unable to find items.xml resource"); System.exit(1); // fatal error return null; }
// Path: game-common/src/main/java/com/game/common/util/PersistenceManager.java // public class PersistenceManager { // private static final Logger log = LoggerFactory.getLogger(PersistenceManager.class); // // public class PacketHandler { // public Packet.Type[] types; // public Class<?> handler; // } // // public class ItemHandler { // public int[] ids; // public Class<?> handler; // } // // protected static final XStream xstream; // // static { // xstream = new XStream(); // // xstream.alias("type", Packet.Type.class); // // xstream.alias("PacketHandler", PacketHandler.class); // xstream.alias("ItemHandler", ItemHandler.class); // // xstream.alias("ItemDef", Item.Definition.class); // xstream.alias("TileDef", Tile.Definition.class); // } // // public static void alias(String name, Class<?> type) { // xstream.alias(name, type); // } // // public static Object load(URL path) { // try { // InputStream in = path.openStream(); // Object o = xstream.fromXML(in); // in.close(); // // return o; // } // catch (IOException ioe) { // log.error("Error loading object: " + ioe.getMessage()); // System.exit(1); // fatal error // // return null; // } // } // // public static void save(Object o, File f) throws IOException { // OutputStream out = new FileOutputStream(f); // xstream.toXML(o, out); // out.close(); // } // } // Path: game-common/src/main/java/com/game/common/model/Item.java import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.net.URL; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.game.common.util.PersistenceManager; package com.game.common.model; public class Item implements Serializable { private static final Logger log = LoggerFactory.getLogger(Item.class); private static final long serialVersionUID = 1L; protected static final Map<Integer, Definition> definitions; static { definitions = Item.loadDefinitions(); if (log.isDebugEnabled()) log.debug("Loaded " + definitions.size() + " item definitions"); } public static Map<Integer, Definition> getDefinitions() { return definitions; } // do nothing - static {} does the work public static void load() { } @SuppressWarnings("unchecked") private static Map<Integer, Definition> loadDefinitions() { URL path = Item.class.getResource("items.xml"); if (path == null) { log.error("Unable to find items.xml resource"); System.exit(1); // fatal error return null; }
return (Map<Integer, Definition>) PersistenceManager.load(path);
reines/game
game-graphics/src/main/java/com/game/graphics/renderer/SpriteMap.java
// Path: game-graphics/src/main/java/com/game/graphics/math/Dimension.java // public class Dimension { // // public float x1; // public float y1; // public float x2; // public float y2; // // public Dimension() { // this (0, 0, 0, 0); // } // // public Dimension(float x1, float y1, float x2, float y2) { // this.x1 = x1; // this.y1 = y1; // this.x2 = x2; // this.y2 = y2; // } // }
import com.game.graphics.math.Dimension;
package com.game.graphics.renderer; public class SpriteMap { public final Sprite sprite; public final int elementWidth; public final int elementHeight; // The amount of elements stored in this sprite public final int width; public final int height; public SpriteMap(Sprite sprite, int elementWidth, int elementHeight) { this.sprite = sprite; this.elementWidth = elementWidth; this.elementHeight = elementHeight; if (sprite.originalWidth % elementWidth != 0 || sprite.originalHeight % elementHeight != 0) { // fatal error throw new RuntimeException("Attempted to load sprite map, but the sprites dimensions aren't multiples of the element dimensions."); } width = sprite.originalWidth / elementWidth; height = sprite.originalHeight / elementHeight; }
// Path: game-graphics/src/main/java/com/game/graphics/math/Dimension.java // public class Dimension { // // public float x1; // public float y1; // public float x2; // public float y2; // // public Dimension() { // this (0, 0, 0, 0); // } // // public Dimension(float x1, float y1, float x2, float y2) { // this.x1 = x1; // this.y1 = y1; // this.x2 = x2; // this.y2 = y2; // } // } // Path: game-graphics/src/main/java/com/game/graphics/renderer/SpriteMap.java import com.game.graphics.math.Dimension; package com.game.graphics.renderer; public class SpriteMap { public final Sprite sprite; public final int elementWidth; public final int elementHeight; // The amount of elements stored in this sprite public final int width; public final int height; public SpriteMap(Sprite sprite, int elementWidth, int elementHeight) { this.sprite = sprite; this.elementWidth = elementWidth; this.elementHeight = elementHeight; if (sprite.originalWidth % elementWidth != 0 || sprite.originalHeight % elementHeight != 0) { // fatal error throw new RuntimeException("Attempted to load sprite map, but the sprites dimensions aren't multiples of the element dimensions."); } width = sprite.originalWidth / elementWidth; height = sprite.originalHeight / elementHeight; }
public Dimension getSprite(int index) {
reines/game
game-graphics/src/main/java/com/game/graphics/models/Material.java
// Path: game-graphics/src/main/java/com/game/graphics/renderer/Sprite.java // public class Sprite { // public static final ColorModel ALPHA_COLOR_MODEL; // public static final ColorModel COLOR_MODEL; // // static { // ALPHA_COLOR_MODEL = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), new int[] {8, 8, 8, 8}, true, false, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE); // COLOR_MODEL = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), new int[] {8, 8, 8, 0}, false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE); // } // // @SuppressWarnings("rawtypes") // public static ByteBuffer getDataBuffer(BufferedImage image, int width, int height, boolean hasAlpha) { // WritableRaster textureRaster; // BufferedImage textureImage; // if (hasAlpha) { // textureRaster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, width, height, 4, null); // textureImage = new BufferedImage(ALPHA_COLOR_MODEL, textureRaster, false, new Hashtable()); // } // else { // textureRaster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, width, height, 3, null); // textureImage = new BufferedImage(COLOR_MODEL, textureRaster, false, new Hashtable()); // } // // Graphics2D g = textureImage.createGraphics(); // g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // g.drawImage(image, 0, 0, width, height, null); // // byte[] data = ((DataBufferByte) textureImage.getRaster().getDataBuffer()).getData(); // // ByteBuffer dataBuffer = ByteBuffer.allocateDirect(data.length); // dataBuffer.order(ByteOrder.nativeOrder()); // dataBuffer.put(data, 0, data.length); // dataBuffer.flip(); // // return dataBuffer; // } // // public final Graphics graphics; // public final int textureID; // public final int originalWidth; // public final int originalHeight; // public final int width; // public final int height; // public final boolean hasAlpha; // protected final ByteBuffer dataBuffer; // // protected Sprite(InputStream in, Graphics graphics) throws IOException { // this (ImageIO.read(in), graphics); // } // // protected Sprite(BufferedImage image, Graphics graphics) { // this.graphics = graphics; // // int width = image.getWidth(); // int height = image.getHeight(); // // originalWidth = width; // originalHeight = height; // // // Check the width is a power of 2 // if ((width & (width - 1)) != 0) { // width = 2; // while (width < image.getWidth()) // width *= 2; // } // // // Check the height is a power of 2 // if ((height & (height - 1)) != 0) { // height = 2; // while (height < image.getHeight()) // height *= 2; // } // // this.width = width; // this.height = height; // // hasAlpha = image.getColorModel().hasAlpha(); // dataBuffer = Sprite.getDataBuffer(image, width, height, hasAlpha); // // // Generate an OpenGL texture // textureID = graphics.generateTexture(this); // } // // protected Sprite(int width, int height, boolean hasAlpha, Graphics graphics) { // this.width = this.originalWidth = width; // this.height = this.originalHeight = height; // // dataBuffer = ByteBuffer.allocateDirect(width * height * (hasAlpha ? 4 : 3)); // dataBuffer.order(ByteOrder.nativeOrder()); // // this.hasAlpha = hasAlpha; // this.graphics = graphics; // // // Generate an OpenGL texture // textureID = graphics.generateTexture(this); // } // // public ByteBuffer getDataBuffer() { // dataBuffer.rewind(); // return dataBuffer; // } // // public int getDataLength() { // return dataBuffer.capacity(); // } // // @Override // public String toString() { // return "sprite[width=" + width + ", height=" + height + ", hasAlpha = " + hasAlpha + ", dataBuffer.length = " + dataBuffer.capacity() + "];"; // } // }
import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import com.game.graphics.renderer.Sprite;
package com.game.graphics.models; public class Material { private static final ByteBuffer dummyBuffer = ByteBuffer.allocateDirect(16).order(ByteOrder.nativeOrder()); public final String name; public final FloatBuffer ambient; public final FloatBuffer diffuse; public final FloatBuffer specular; public final FloatBuffer emissive; public final float shininess; public final float transparency;
// Path: game-graphics/src/main/java/com/game/graphics/renderer/Sprite.java // public class Sprite { // public static final ColorModel ALPHA_COLOR_MODEL; // public static final ColorModel COLOR_MODEL; // // static { // ALPHA_COLOR_MODEL = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), new int[] {8, 8, 8, 8}, true, false, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE); // COLOR_MODEL = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), new int[] {8, 8, 8, 0}, false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE); // } // // @SuppressWarnings("rawtypes") // public static ByteBuffer getDataBuffer(BufferedImage image, int width, int height, boolean hasAlpha) { // WritableRaster textureRaster; // BufferedImage textureImage; // if (hasAlpha) { // textureRaster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, width, height, 4, null); // textureImage = new BufferedImage(ALPHA_COLOR_MODEL, textureRaster, false, new Hashtable()); // } // else { // textureRaster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, width, height, 3, null); // textureImage = new BufferedImage(COLOR_MODEL, textureRaster, false, new Hashtable()); // } // // Graphics2D g = textureImage.createGraphics(); // g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // g.drawImage(image, 0, 0, width, height, null); // // byte[] data = ((DataBufferByte) textureImage.getRaster().getDataBuffer()).getData(); // // ByteBuffer dataBuffer = ByteBuffer.allocateDirect(data.length); // dataBuffer.order(ByteOrder.nativeOrder()); // dataBuffer.put(data, 0, data.length); // dataBuffer.flip(); // // return dataBuffer; // } // // public final Graphics graphics; // public final int textureID; // public final int originalWidth; // public final int originalHeight; // public final int width; // public final int height; // public final boolean hasAlpha; // protected final ByteBuffer dataBuffer; // // protected Sprite(InputStream in, Graphics graphics) throws IOException { // this (ImageIO.read(in), graphics); // } // // protected Sprite(BufferedImage image, Graphics graphics) { // this.graphics = graphics; // // int width = image.getWidth(); // int height = image.getHeight(); // // originalWidth = width; // originalHeight = height; // // // Check the width is a power of 2 // if ((width & (width - 1)) != 0) { // width = 2; // while (width < image.getWidth()) // width *= 2; // } // // // Check the height is a power of 2 // if ((height & (height - 1)) != 0) { // height = 2; // while (height < image.getHeight()) // height *= 2; // } // // this.width = width; // this.height = height; // // hasAlpha = image.getColorModel().hasAlpha(); // dataBuffer = Sprite.getDataBuffer(image, width, height, hasAlpha); // // // Generate an OpenGL texture // textureID = graphics.generateTexture(this); // } // // protected Sprite(int width, int height, boolean hasAlpha, Graphics graphics) { // this.width = this.originalWidth = width; // this.height = this.originalHeight = height; // // dataBuffer = ByteBuffer.allocateDirect(width * height * (hasAlpha ? 4 : 3)); // dataBuffer.order(ByteOrder.nativeOrder()); // // this.hasAlpha = hasAlpha; // this.graphics = graphics; // // // Generate an OpenGL texture // textureID = graphics.generateTexture(this); // } // // public ByteBuffer getDataBuffer() { // dataBuffer.rewind(); // return dataBuffer; // } // // public int getDataLength() { // return dataBuffer.capacity(); // } // // @Override // public String toString() { // return "sprite[width=" + width + ", height=" + height + ", hasAlpha = " + hasAlpha + ", dataBuffer.length = " + dataBuffer.capacity() + "];"; // } // } // Path: game-graphics/src/main/java/com/game/graphics/models/Material.java import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import com.game.graphics.renderer.Sprite; package com.game.graphics.models; public class Material { private static final ByteBuffer dummyBuffer = ByteBuffer.allocateDirect(16).order(ByteOrder.nativeOrder()); public final String name; public final FloatBuffer ambient; public final FloatBuffer diffuse; public final FloatBuffer specular; public final FloatBuffer emissive; public final float shininess; public final float transparency;
public final Sprite colorMap;
reines/game
game-common/src/main/java/com/game/common/util/EntityListIterator.java
// Path: game-common/src/main/java/com/game/common/model/Entity.java // public abstract class Entity extends Observable { // // public abstract Hash getID(); // public abstract Point getLocation(); // public abstract void setLocation(Point p); // // } // // Path: game-common/src/main/java/com/game/common/model/Hash.java // public class Hash implements Comparable<Hash>, Serializable { // private static final Logger log = LoggerFactory.getLogger(Hash.class); // private static final long serialVersionUID = 1L; // // public static final int LENGTH = 20; // in bytes // public static final String ALGORITHM = "SHA-1"; // // protected static MessageDigest digest; // // static { // try { // digest = MessageDigest.getInstance(ALGORITHM); // } // catch (NoSuchAlgorithmException e) { // log.error("No such hashing algorithm: " + ALGORITHM); // System.exit(1); // fatal error // } // } // // public static Hash fromString(String hex) { // Hash hash = new Hash(); // hash.setHex(hex); // // return hash; // } // // public static Hash fromBytes(byte[] bytes) { // Hash hash = new Hash(); // hash.setBytes(bytes); // // return hash; // } // // protected String hex; // // public Hash(String str) { // try { // digest.update(str.getBytes("UTF-8")); // } // catch (UnsupportedEncodingException e) { } // // this.setBytes(digest.digest()); // } // // private Hash() { // hex = null; // } // // private void setHex(String hex) { // this.hex = hex; // } // // private void setBytes(byte[] bytes) { // Formatter foramtter = new Formatter(); // // for (byte b : bytes) // foramtter.format("%02x", b); // // this.hex = foramtter.toString(); // } // // public byte[] getBytes() { // byte[] bytes = new byte[LENGTH]; // // for (int i = 0;i < LENGTH;i++) // bytes[i] = (byte) Short.parseShort(hex.substring(2 * i, 2 * (i + 1)), 16); // // return bytes; // } // // @Override // public String toString() { // return hex; // } // // @Override // public int hashCode() { // return hex.hashCode(); // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof Hash)) // return false; // // Hash h = (Hash) o; // return hex.equals(h.hex); // } // // @Override // public int compareTo(Hash h) { // return hex.compareTo(h.hex); // } // }
import java.util.Iterator; import com.game.common.model.Entity; import com.game.common.model.Hash;
package com.game.common.util; public class EntityListIterator<T extends Entity> implements Iterator<T> { protected final EntityList<T> list;
// Path: game-common/src/main/java/com/game/common/model/Entity.java // public abstract class Entity extends Observable { // // public abstract Hash getID(); // public abstract Point getLocation(); // public abstract void setLocation(Point p); // // } // // Path: game-common/src/main/java/com/game/common/model/Hash.java // public class Hash implements Comparable<Hash>, Serializable { // private static final Logger log = LoggerFactory.getLogger(Hash.class); // private static final long serialVersionUID = 1L; // // public static final int LENGTH = 20; // in bytes // public static final String ALGORITHM = "SHA-1"; // // protected static MessageDigest digest; // // static { // try { // digest = MessageDigest.getInstance(ALGORITHM); // } // catch (NoSuchAlgorithmException e) { // log.error("No such hashing algorithm: " + ALGORITHM); // System.exit(1); // fatal error // } // } // // public static Hash fromString(String hex) { // Hash hash = new Hash(); // hash.setHex(hex); // // return hash; // } // // public static Hash fromBytes(byte[] bytes) { // Hash hash = new Hash(); // hash.setBytes(bytes); // // return hash; // } // // protected String hex; // // public Hash(String str) { // try { // digest.update(str.getBytes("UTF-8")); // } // catch (UnsupportedEncodingException e) { } // // this.setBytes(digest.digest()); // } // // private Hash() { // hex = null; // } // // private void setHex(String hex) { // this.hex = hex; // } // // private void setBytes(byte[] bytes) { // Formatter foramtter = new Formatter(); // // for (byte b : bytes) // foramtter.format("%02x", b); // // this.hex = foramtter.toString(); // } // // public byte[] getBytes() { // byte[] bytes = new byte[LENGTH]; // // for (int i = 0;i < LENGTH;i++) // bytes[i] = (byte) Short.parseShort(hex.substring(2 * i, 2 * (i + 1)), 16); // // return bytes; // } // // @Override // public String toString() { // return hex; // } // // @Override // public int hashCode() { // return hex.hashCode(); // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof Hash)) // return false; // // Hash h = (Hash) o; // return hex.equals(h.hex); // } // // @Override // public int compareTo(Hash h) { // return hex.compareTo(h.hex); // } // } // Path: game-common/src/main/java/com/game/common/util/EntityListIterator.java import java.util.Iterator; import com.game.common.model.Entity; import com.game.common.model.Hash; package com.game.common.util; public class EntityListIterator<T extends Entity> implements Iterator<T> { protected final EntityList<T> list;
protected final Hash[] keySet;
reines/game
game-common/src/main/java/com/game/common/model/PlayerProfile.java
// Path: game-common/src/main/java/com/game/common/util/FriendList.java // public class FriendList implements Iterable<Friend>, Serializable { // private static final long serialVersionUID = 1L; // // protected Map<Hash, Friend> friends; // // public FriendList() { // friends = new HashMap<Hash, Friend>(); // } // // public void add(Friend friend) { // friends.put(friend.getID(), friend); // } // // public boolean contains(Hash id) { // return friends.containsKey(id); // } // // public Friend get(Hash id) { // return friends.get(id); // } // // public Friend remove(Hash id) { // return friends.remove(id); // } // // public int size() { // return friends.size(); // } // // @Override // public Iterator<Friend> iterator() { // return friends.values().iterator(); // } // } // // Path: game-common/src/main/java/com/game/common/util/StatList.java // public class StatList implements Iterable<Stat>, Observer, Serializable { // private static final long serialVersionUID = 1L; // // public static final int NUM_STATS; // // static { // NUM_STATS = Stat.Type.values().length; // } // // protected List<Stat> stats; // protected transient int combatLevel; // protected transient int skillTotal; // // public StatList(List<Stat> stats) { // // Add us as an observer for all the stats // for (Stat stat : stats) // stat.addObserver(this); // // this.stats = stats; // // // Calculate the combat level and skill total // this.update(null, true); // } // // @SuppressWarnings("unused") // private StatList() { } // for hibernate // // public Stat get(Stat.Type type) { // return stats.get(type.ordinal()); // } // // public synchronized int getCombatLevel() { // return combatLevel; // } // // public synchronized int getSkillTotal() { // return skillTotal; // } // // public int size() { // return stats.size(); // } // // @Override // public Iterator<Stat> iterator() { // return stats.iterator(); // } // // protected synchronized int calcCombatLevel() { // int total = 0; // // total += this.get(Stat.Type.ATTACK).getLevel(); // total += this.get(Stat.Type.DEFENSE).getLevel(); // total += this.get(Stat.Type.STRENGTH).getLevel(); // total += this.get(Stat.Type.MAGIC).getLevel(); // total += this.get(Stat.Type.ARCHERY).getLevel(); // // total /= 2; // // total += this.get(Stat.Type.HITPOINTS).getLevel(); // // return total / 3; // } // // protected synchronized int calcSkillTotal() { // int total = 0; // // for (Stat stat : this) // total += stat.getLevel(); // // return total; // } // // @Override // public synchronized void update(Observable o, Object arg) { // boolean changedLevel = (Boolean) arg; // // Check if the level changed, or just the experience // if (!changedLevel) // return; // // // Something has changed, update the combat level and skill total // combatLevel = this.calcCombatLevel(); // skillTotal = this.calcSkillTotal(); // } // // private void writeObject(ObjectOutputStream out) throws IOException { // out.defaultWriteObject(); // } // // private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { // in.defaultReadObject(); // this.update(null, true); // Call a fake update to calculate the combat level and skill total // } // }
import java.io.Serializable; import java.util.Date; import com.game.common.util.FriendList; import com.game.common.util.StatList;
package com.game.common.model; public class PlayerProfile implements Serializable { private static final long serialVersionUID = 1L; public Hash id; @SuppressWarnings("unused") private Hash password; // for hibernate public String username; public Point location; public Inventory inventory;
// Path: game-common/src/main/java/com/game/common/util/FriendList.java // public class FriendList implements Iterable<Friend>, Serializable { // private static final long serialVersionUID = 1L; // // protected Map<Hash, Friend> friends; // // public FriendList() { // friends = new HashMap<Hash, Friend>(); // } // // public void add(Friend friend) { // friends.put(friend.getID(), friend); // } // // public boolean contains(Hash id) { // return friends.containsKey(id); // } // // public Friend get(Hash id) { // return friends.get(id); // } // // public Friend remove(Hash id) { // return friends.remove(id); // } // // public int size() { // return friends.size(); // } // // @Override // public Iterator<Friend> iterator() { // return friends.values().iterator(); // } // } // // Path: game-common/src/main/java/com/game/common/util/StatList.java // public class StatList implements Iterable<Stat>, Observer, Serializable { // private static final long serialVersionUID = 1L; // // public static final int NUM_STATS; // // static { // NUM_STATS = Stat.Type.values().length; // } // // protected List<Stat> stats; // protected transient int combatLevel; // protected transient int skillTotal; // // public StatList(List<Stat> stats) { // // Add us as an observer for all the stats // for (Stat stat : stats) // stat.addObserver(this); // // this.stats = stats; // // // Calculate the combat level and skill total // this.update(null, true); // } // // @SuppressWarnings("unused") // private StatList() { } // for hibernate // // public Stat get(Stat.Type type) { // return stats.get(type.ordinal()); // } // // public synchronized int getCombatLevel() { // return combatLevel; // } // // public synchronized int getSkillTotal() { // return skillTotal; // } // // public int size() { // return stats.size(); // } // // @Override // public Iterator<Stat> iterator() { // return stats.iterator(); // } // // protected synchronized int calcCombatLevel() { // int total = 0; // // total += this.get(Stat.Type.ATTACK).getLevel(); // total += this.get(Stat.Type.DEFENSE).getLevel(); // total += this.get(Stat.Type.STRENGTH).getLevel(); // total += this.get(Stat.Type.MAGIC).getLevel(); // total += this.get(Stat.Type.ARCHERY).getLevel(); // // total /= 2; // // total += this.get(Stat.Type.HITPOINTS).getLevel(); // // return total / 3; // } // // protected synchronized int calcSkillTotal() { // int total = 0; // // for (Stat stat : this) // total += stat.getLevel(); // // return total; // } // // @Override // public synchronized void update(Observable o, Object arg) { // boolean changedLevel = (Boolean) arg; // // Check if the level changed, or just the experience // if (!changedLevel) // return; // // // Something has changed, update the combat level and skill total // combatLevel = this.calcCombatLevel(); // skillTotal = this.calcSkillTotal(); // } // // private void writeObject(ObjectOutputStream out) throws IOException { // out.defaultWriteObject(); // } // // private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { // in.defaultReadObject(); // this.update(null, true); // Call a fake update to calculate the combat level and skill total // } // } // Path: game-common/src/main/java/com/game/common/model/PlayerProfile.java import java.io.Serializable; import java.util.Date; import com.game.common.util.FriendList; import com.game.common.util.StatList; package com.game.common.model; public class PlayerProfile implements Serializable { private static final long serialVersionUID = 1L; public Hash id; @SuppressWarnings("unused") private Hash password; // for hibernate public String username; public Point location; public Inventory inventory;
public StatList stats;
reines/game
game-common/src/main/java/com/game/common/model/PlayerProfile.java
// Path: game-common/src/main/java/com/game/common/util/FriendList.java // public class FriendList implements Iterable<Friend>, Serializable { // private static final long serialVersionUID = 1L; // // protected Map<Hash, Friend> friends; // // public FriendList() { // friends = new HashMap<Hash, Friend>(); // } // // public void add(Friend friend) { // friends.put(friend.getID(), friend); // } // // public boolean contains(Hash id) { // return friends.containsKey(id); // } // // public Friend get(Hash id) { // return friends.get(id); // } // // public Friend remove(Hash id) { // return friends.remove(id); // } // // public int size() { // return friends.size(); // } // // @Override // public Iterator<Friend> iterator() { // return friends.values().iterator(); // } // } // // Path: game-common/src/main/java/com/game/common/util/StatList.java // public class StatList implements Iterable<Stat>, Observer, Serializable { // private static final long serialVersionUID = 1L; // // public static final int NUM_STATS; // // static { // NUM_STATS = Stat.Type.values().length; // } // // protected List<Stat> stats; // protected transient int combatLevel; // protected transient int skillTotal; // // public StatList(List<Stat> stats) { // // Add us as an observer for all the stats // for (Stat stat : stats) // stat.addObserver(this); // // this.stats = stats; // // // Calculate the combat level and skill total // this.update(null, true); // } // // @SuppressWarnings("unused") // private StatList() { } // for hibernate // // public Stat get(Stat.Type type) { // return stats.get(type.ordinal()); // } // // public synchronized int getCombatLevel() { // return combatLevel; // } // // public synchronized int getSkillTotal() { // return skillTotal; // } // // public int size() { // return stats.size(); // } // // @Override // public Iterator<Stat> iterator() { // return stats.iterator(); // } // // protected synchronized int calcCombatLevel() { // int total = 0; // // total += this.get(Stat.Type.ATTACK).getLevel(); // total += this.get(Stat.Type.DEFENSE).getLevel(); // total += this.get(Stat.Type.STRENGTH).getLevel(); // total += this.get(Stat.Type.MAGIC).getLevel(); // total += this.get(Stat.Type.ARCHERY).getLevel(); // // total /= 2; // // total += this.get(Stat.Type.HITPOINTS).getLevel(); // // return total / 3; // } // // protected synchronized int calcSkillTotal() { // int total = 0; // // for (Stat stat : this) // total += stat.getLevel(); // // return total; // } // // @Override // public synchronized void update(Observable o, Object arg) { // boolean changedLevel = (Boolean) arg; // // Check if the level changed, or just the experience // if (!changedLevel) // return; // // // Something has changed, update the combat level and skill total // combatLevel = this.calcCombatLevel(); // skillTotal = this.calcSkillTotal(); // } // // private void writeObject(ObjectOutputStream out) throws IOException { // out.defaultWriteObject(); // } // // private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { // in.defaultReadObject(); // this.update(null, true); // Call a fake update to calculate the combat level and skill total // } // }
import java.io.Serializable; import java.util.Date; import com.game.common.util.FriendList; import com.game.common.util.StatList;
package com.game.common.model; public class PlayerProfile implements Serializable { private static final long serialVersionUID = 1L; public Hash id; @SuppressWarnings("unused") private Hash password; // for hibernate public String username; public Point location; public Inventory inventory; public StatList stats;
// Path: game-common/src/main/java/com/game/common/util/FriendList.java // public class FriendList implements Iterable<Friend>, Serializable { // private static final long serialVersionUID = 1L; // // protected Map<Hash, Friend> friends; // // public FriendList() { // friends = new HashMap<Hash, Friend>(); // } // // public void add(Friend friend) { // friends.put(friend.getID(), friend); // } // // public boolean contains(Hash id) { // return friends.containsKey(id); // } // // public Friend get(Hash id) { // return friends.get(id); // } // // public Friend remove(Hash id) { // return friends.remove(id); // } // // public int size() { // return friends.size(); // } // // @Override // public Iterator<Friend> iterator() { // return friends.values().iterator(); // } // } // // Path: game-common/src/main/java/com/game/common/util/StatList.java // public class StatList implements Iterable<Stat>, Observer, Serializable { // private static final long serialVersionUID = 1L; // // public static final int NUM_STATS; // // static { // NUM_STATS = Stat.Type.values().length; // } // // protected List<Stat> stats; // protected transient int combatLevel; // protected transient int skillTotal; // // public StatList(List<Stat> stats) { // // Add us as an observer for all the stats // for (Stat stat : stats) // stat.addObserver(this); // // this.stats = stats; // // // Calculate the combat level and skill total // this.update(null, true); // } // // @SuppressWarnings("unused") // private StatList() { } // for hibernate // // public Stat get(Stat.Type type) { // return stats.get(type.ordinal()); // } // // public synchronized int getCombatLevel() { // return combatLevel; // } // // public synchronized int getSkillTotal() { // return skillTotal; // } // // public int size() { // return stats.size(); // } // // @Override // public Iterator<Stat> iterator() { // return stats.iterator(); // } // // protected synchronized int calcCombatLevel() { // int total = 0; // // total += this.get(Stat.Type.ATTACK).getLevel(); // total += this.get(Stat.Type.DEFENSE).getLevel(); // total += this.get(Stat.Type.STRENGTH).getLevel(); // total += this.get(Stat.Type.MAGIC).getLevel(); // total += this.get(Stat.Type.ARCHERY).getLevel(); // // total /= 2; // // total += this.get(Stat.Type.HITPOINTS).getLevel(); // // return total / 3; // } // // protected synchronized int calcSkillTotal() { // int total = 0; // // for (Stat stat : this) // total += stat.getLevel(); // // return total; // } // // @Override // public synchronized void update(Observable o, Object arg) { // boolean changedLevel = (Boolean) arg; // // Check if the level changed, or just the experience // if (!changedLevel) // return; // // // Something has changed, update the combat level and skill total // combatLevel = this.calcCombatLevel(); // skillTotal = this.calcSkillTotal(); // } // // private void writeObject(ObjectOutputStream out) throws IOException { // out.defaultWriteObject(); // } // // private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { // in.defaultReadObject(); // this.update(null, true); // Call a fake update to calculate the combat level and skill total // } // } // Path: game-common/src/main/java/com/game/common/model/PlayerProfile.java import java.io.Serializable; import java.util.Date; import com.game.common.util.FriendList; import com.game.common.util.StatList; package com.game.common.model; public class PlayerProfile implements Serializable { private static final long serialVersionUID = 1L; public Hash id; @SuppressWarnings("unused") private Hash password; // for hibernate public String username; public Point location; public Inventory inventory; public StatList stats;
public FriendList friends;
DDTH/ddth-commons
ddth-commons-core/src/test/java/com/github/ddth/commons/qnd/utils/QndDateFormatUtil.java
// Path: ddth-commons-core/src/main/java/com/github/ddth/commons/utils/DateFormatUtils.java // public class DateFormatUtils { // // /** // * @since 0.7.0 // */ // public final static String DF_ISO8601 = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; // // /** // * @since 0.2.2.3 // */ // private final static class MyDateFormat extends SimpleDateFormat { // private static final long serialVersionUID = 1L; // private final UUID id = UUID.randomUUID(); // // public MyDateFormat(String format) { // super(format); // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (!(o instanceof MyDateFormat)) { // return false; // } // // MyDateFormat that = (MyDateFormat) o; // if (id != null ? !id.equals(that.id) : that.id != null) { // return false; // } // // return true; // } // // @Override // public int hashCode() { // return id != null ? id.hashCode() : 0; // } // } // // private final static class DateFormatFactory extends BasePooledObjectFactory<DateFormat> { // private String format; // // public DateFormatFactory(String format) { // this.format = format; // } // // /** // * {@inheritDoc} // */ // @Override // public DateFormat create() throws Exception { // return new MyDateFormat(format); // } // // /** // * {@inheritDoc} // */ // @Override // public PooledObject<DateFormat> wrap(DateFormat df) { // return new DefaultPooledObject<DateFormat>(df); // } // } // // private final static LoadingCache<String, ObjectPool<DateFormat>> cachedDateFormat = CacheBuilder // .newBuilder().maximumSize(100).expireAfterAccess(3600, TimeUnit.SECONDS) // .concurrencyLevel(2) // .removalListener(new RemovalListener<String, ObjectPool<DateFormat>>() { // @Override // public void onRemoval(RemovalNotification<String, ObjectPool<DateFormat>> event) { // event.getValue().close(); // } // }).build(new CacheLoader<String, ObjectPool<DateFormat>>() { // @Override // public ObjectPool<DateFormat> load(String format) throws Exception { // DateFormatFactory dff = new DateFormatFactory(format); // ObjectPool<DateFormat> obj = new GenericObjectPool<DateFormat>(dff); // return obj; // } // }); // // /** // * Convert a {@link Date} to string, based on the specified {@code format}. // * // * @param date // * @param format // * @return // * @see {@link SimpleDateFormat} // */ // public static String toString(Date date, String format) { // try { // ObjectPool<DateFormat> pool = cachedDateFormat.get(format); // try { // DateFormat df = pool.borrowObject(); // try { // return df.format(date); // } finally { // pool.returnObject(df); // } // } catch (Exception e) { // throw e instanceof RuntimeException ? (RuntimeException) e // : new RuntimeException(e); // } // } catch (ExecutionException e) { // throw new RuntimeException(e); // } // } // // /** // * Convert a {@link Calendar} to string, based on the specified {@code format}. // * // * @param calendar // * @param format // * @return // * @see {@link SimpleDateFormat} // * @since 0.9.1.1 // */ // public static String toString(Calendar calendar, String format) { // return toString(calendar.getTime(), format); // } // // /** // * Parse a string to {@link Date}, based on the specified {@code format}. // * // * @param source // * @param format // * @return // */ // public static Date fromString(String source, String format) { // try { // ObjectPool<DateFormat> pool = cachedDateFormat.get(format); // try { // DateFormat df = pool.borrowObject(); // try { // return df.parse(source); // } finally { // pool.returnObject(df); // } // } catch (Exception e) { // throw e instanceof RuntimeException ? (RuntimeException) e // : new RuntimeException(e); // } // } catch (ExecutionException e) { // throw new RuntimeException(e); // } // } // }
import java.util.Date; import com.github.ddth.commons.utils.DateFormatUtils;
package com.github.ddth.commons.qnd.utils; public class QndDateFormatUtil { public static void main(String[] args) { final String DF = "yyyy-MM-dd"; final String INPUT = "2014-09-29"; for (int i = 0; i < 16; i++) { Thread t = new Thread() { public void run() { for (int j = 0; j < 100; j++) {
// Path: ddth-commons-core/src/main/java/com/github/ddth/commons/utils/DateFormatUtils.java // public class DateFormatUtils { // // /** // * @since 0.7.0 // */ // public final static String DF_ISO8601 = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; // // /** // * @since 0.2.2.3 // */ // private final static class MyDateFormat extends SimpleDateFormat { // private static final long serialVersionUID = 1L; // private final UUID id = UUID.randomUUID(); // // public MyDateFormat(String format) { // super(format); // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (!(o instanceof MyDateFormat)) { // return false; // } // // MyDateFormat that = (MyDateFormat) o; // if (id != null ? !id.equals(that.id) : that.id != null) { // return false; // } // // return true; // } // // @Override // public int hashCode() { // return id != null ? id.hashCode() : 0; // } // } // // private final static class DateFormatFactory extends BasePooledObjectFactory<DateFormat> { // private String format; // // public DateFormatFactory(String format) { // this.format = format; // } // // /** // * {@inheritDoc} // */ // @Override // public DateFormat create() throws Exception { // return new MyDateFormat(format); // } // // /** // * {@inheritDoc} // */ // @Override // public PooledObject<DateFormat> wrap(DateFormat df) { // return new DefaultPooledObject<DateFormat>(df); // } // } // // private final static LoadingCache<String, ObjectPool<DateFormat>> cachedDateFormat = CacheBuilder // .newBuilder().maximumSize(100).expireAfterAccess(3600, TimeUnit.SECONDS) // .concurrencyLevel(2) // .removalListener(new RemovalListener<String, ObjectPool<DateFormat>>() { // @Override // public void onRemoval(RemovalNotification<String, ObjectPool<DateFormat>> event) { // event.getValue().close(); // } // }).build(new CacheLoader<String, ObjectPool<DateFormat>>() { // @Override // public ObjectPool<DateFormat> load(String format) throws Exception { // DateFormatFactory dff = new DateFormatFactory(format); // ObjectPool<DateFormat> obj = new GenericObjectPool<DateFormat>(dff); // return obj; // } // }); // // /** // * Convert a {@link Date} to string, based on the specified {@code format}. // * // * @param date // * @param format // * @return // * @see {@link SimpleDateFormat} // */ // public static String toString(Date date, String format) { // try { // ObjectPool<DateFormat> pool = cachedDateFormat.get(format); // try { // DateFormat df = pool.borrowObject(); // try { // return df.format(date); // } finally { // pool.returnObject(df); // } // } catch (Exception e) { // throw e instanceof RuntimeException ? (RuntimeException) e // : new RuntimeException(e); // } // } catch (ExecutionException e) { // throw new RuntimeException(e); // } // } // // /** // * Convert a {@link Calendar} to string, based on the specified {@code format}. // * // * @param calendar // * @param format // * @return // * @see {@link SimpleDateFormat} // * @since 0.9.1.1 // */ // public static String toString(Calendar calendar, String format) { // return toString(calendar.getTime(), format); // } // // /** // * Parse a string to {@link Date}, based on the specified {@code format}. // * // * @param source // * @param format // * @return // */ // public static Date fromString(String source, String format) { // try { // ObjectPool<DateFormat> pool = cachedDateFormat.get(format); // try { // DateFormat df = pool.borrowObject(); // try { // return df.parse(source); // } finally { // pool.returnObject(df); // } // } catch (Exception e) { // throw e instanceof RuntimeException ? (RuntimeException) e // : new RuntimeException(e); // } // } catch (ExecutionException e) { // throw new RuntimeException(e); // } // } // } // Path: ddth-commons-core/src/test/java/com/github/ddth/commons/qnd/utils/QndDateFormatUtil.java import java.util.Date; import com.github.ddth.commons.utils.DateFormatUtils; package com.github.ddth.commons.qnd.utils; public class QndDateFormatUtil { public static void main(String[] args) { final String DF = "yyyy-MM-dd"; final String INPUT = "2014-09-29"; for (int i = 0; i < 16; i++) { Thread t = new Thread() { public void run() { for (int j = 0; j < 100; j++) {
Date d = DateFormatUtils.fromString(INPUT, DF);
DDTH/ddth-commons
ddth-commons-core/src/test/java/com/github/ddth/commons/qnd/redis/QndJedisConnector.java
// Path: ddth-commons-core/src/main/java/com/github/ddth/commons/redis/JedisConnector.java // public class JedisConnector implements AutoCloseable { // private final Logger LOGGER = LoggerFactory.getLogger(JedisConnector.class); // // private String redisHostsAndPorts = Protocol.DEFAULT_HOST + ":" + Protocol.DEFAULT_PORT; // private String redisPassword; // private JedisPoolConfig poolConfig; // private JedisPool jedisPool; // private JedisCluster jedisCluster; // private ShardedJedisPool shardedJedisPool; // // public JedisPoolConfig getJedisPoolConfig() { // return poolConfig; // } // // public JedisConnector setJedisPoolConfig(JedisPoolConfig poolConfig) { // this.poolConfig = poolConfig; // return this; // } // // /** // * Get Redis' hosts and ports scheme (format {@code host1:port1,host2:port2}). // * // * @return // */ // public String getRedisHostsAndPorts() { // return redisHostsAndPorts; // } // // /** // * Set Redis' hosts and ports scheme (format {@code host1:port1,host2:port2}). // * // * @param redisHostsAndPorts // * @return // */ // public JedisConnector setRedisHostsAndPorts(String redisHostsAndPorts) { // this.redisHostsAndPorts = redisHostsAndPorts; // return this; // } // // public String getRedisPassword() { // return redisPassword; // } // // public JedisConnector setRedisPassword(String redisPassword) { // this.redisPassword = redisPassword; // return this; // } // // synchronized private void connectJedisPool() { // if (jedisPool == null) { // String[] tokens = redisHostsAndPorts.split("[,;\\s]+"); // jedisPool = JedisUtils.newJedisPool(getJedisPoolConfig(), tokens[0], // getRedisPassword()); // } // } // // public Jedis getJedis() { // if (jedisPool == null) { // connectJedisPool(); // } // return jedisPool.getResource(); // } // // synchronized private void connectJedisCluster() { // if (jedisCluster == null) { // jedisCluster = JedisUtils.newJedisCluster(getJedisPoolConfig(), getRedisHostsAndPorts(), // getRedisPassword()); // } // } // // public JedisCluster getJedisCluster() { // if (jedisCluster == null) { // connectJedisCluster(); // } // return jedisCluster; // } // // synchronized private void connectShardedJedisPool() { // if (shardedJedisPool == null) { // shardedJedisPool = JedisUtils.newShardedJedisPool(getJedisPoolConfig(), // getRedisHostsAndPorts(), getRedisPassword()); // } // } // // public ShardedJedis getShardedJedis() { // if (shardedJedisPool == null) { // connectShardedJedisPool(); // } // return shardedJedisPool.getResource(); // } // // public JedisConnector init() { // return this; // } // // public void destroy() { // if (jedisPool != null) { // try { // jedisPool.close(); // } catch (Exception e) { // LOGGER.warn(e.getMessage(), e); // } finally { // jedisPool = null; // } // } // // if (jedisCluster != null) { // try { // jedisCluster.close(); // } catch (Exception e) { // LOGGER.warn(e.getMessage(), e); // } finally { // jedisCluster = null; // } // } // // if (shardedJedisPool != null) { // try { // shardedJedisPool.close(); // } catch (Exception e) { // LOGGER.warn(e.getMessage(), e); // } finally { // shardedJedisPool = null; // } // } // } // // /** // * {@inheritDoc} // */ // @Override // public void close() { // destroy(); // } // // }
import com.github.ddth.commons.redis.JedisConnector; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisCluster; import redis.clients.jedis.JedisPoolConfig; import redis.clients.jedis.ShardedJedis;
package com.github.ddth.commons.qnd.redis; /* * mvn exec:java -Dexec.mainClass="com.github.ddth.commons.qnd.redis.QndJedisConnector" */ public class QndJedisConnector { public static void main(String[] args) { // create a JedisPoolConfig instance JedisPoolConfig poolConfig = new JedisPoolConfig(); { // configure the JedisPoolConfig int maxTotal = Runtime.getRuntime().availableProcessors(); int maxIdle = maxTotal / 2; poolConfig.setMaxTotal(maxTotal); poolConfig.setMinIdle(1); poolConfig.setMaxIdle(maxIdle > 0 ? maxIdle : 1); poolConfig.setMaxWaitMillis(5000); poolConfig.setTestOnBorrow(false); poolConfig.setTestWhileIdle(true); } // create & initialize JedisConnector
// Path: ddth-commons-core/src/main/java/com/github/ddth/commons/redis/JedisConnector.java // public class JedisConnector implements AutoCloseable { // private final Logger LOGGER = LoggerFactory.getLogger(JedisConnector.class); // // private String redisHostsAndPorts = Protocol.DEFAULT_HOST + ":" + Protocol.DEFAULT_PORT; // private String redisPassword; // private JedisPoolConfig poolConfig; // private JedisPool jedisPool; // private JedisCluster jedisCluster; // private ShardedJedisPool shardedJedisPool; // // public JedisPoolConfig getJedisPoolConfig() { // return poolConfig; // } // // public JedisConnector setJedisPoolConfig(JedisPoolConfig poolConfig) { // this.poolConfig = poolConfig; // return this; // } // // /** // * Get Redis' hosts and ports scheme (format {@code host1:port1,host2:port2}). // * // * @return // */ // public String getRedisHostsAndPorts() { // return redisHostsAndPorts; // } // // /** // * Set Redis' hosts and ports scheme (format {@code host1:port1,host2:port2}). // * // * @param redisHostsAndPorts // * @return // */ // public JedisConnector setRedisHostsAndPorts(String redisHostsAndPorts) { // this.redisHostsAndPorts = redisHostsAndPorts; // return this; // } // // public String getRedisPassword() { // return redisPassword; // } // // public JedisConnector setRedisPassword(String redisPassword) { // this.redisPassword = redisPassword; // return this; // } // // synchronized private void connectJedisPool() { // if (jedisPool == null) { // String[] tokens = redisHostsAndPorts.split("[,;\\s]+"); // jedisPool = JedisUtils.newJedisPool(getJedisPoolConfig(), tokens[0], // getRedisPassword()); // } // } // // public Jedis getJedis() { // if (jedisPool == null) { // connectJedisPool(); // } // return jedisPool.getResource(); // } // // synchronized private void connectJedisCluster() { // if (jedisCluster == null) { // jedisCluster = JedisUtils.newJedisCluster(getJedisPoolConfig(), getRedisHostsAndPorts(), // getRedisPassword()); // } // } // // public JedisCluster getJedisCluster() { // if (jedisCluster == null) { // connectJedisCluster(); // } // return jedisCluster; // } // // synchronized private void connectShardedJedisPool() { // if (shardedJedisPool == null) { // shardedJedisPool = JedisUtils.newShardedJedisPool(getJedisPoolConfig(), // getRedisHostsAndPorts(), getRedisPassword()); // } // } // // public ShardedJedis getShardedJedis() { // if (shardedJedisPool == null) { // connectShardedJedisPool(); // } // return shardedJedisPool.getResource(); // } // // public JedisConnector init() { // return this; // } // // public void destroy() { // if (jedisPool != null) { // try { // jedisPool.close(); // } catch (Exception e) { // LOGGER.warn(e.getMessage(), e); // } finally { // jedisPool = null; // } // } // // if (jedisCluster != null) { // try { // jedisCluster.close(); // } catch (Exception e) { // LOGGER.warn(e.getMessage(), e); // } finally { // jedisCluster = null; // } // } // // if (shardedJedisPool != null) { // try { // shardedJedisPool.close(); // } catch (Exception e) { // LOGGER.warn(e.getMessage(), e); // } finally { // shardedJedisPool = null; // } // } // } // // /** // * {@inheritDoc} // */ // @Override // public void close() { // destroy(); // } // // } // Path: ddth-commons-core/src/test/java/com/github/ddth/commons/qnd/redis/QndJedisConnector.java import com.github.ddth.commons.redis.JedisConnector; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisCluster; import redis.clients.jedis.JedisPoolConfig; import redis.clients.jedis.ShardedJedis; package com.github.ddth.commons.qnd.redis; /* * mvn exec:java -Dexec.mainClass="com.github.ddth.commons.qnd.redis.QndJedisConnector" */ public class QndJedisConnector { public static void main(String[] args) { // create a JedisPoolConfig instance JedisPoolConfig poolConfig = new JedisPoolConfig(); { // configure the JedisPoolConfig int maxTotal = Runtime.getRuntime().availableProcessors(); int maxIdle = maxTotal / 2; poolConfig.setMaxTotal(maxTotal); poolConfig.setMinIdle(1); poolConfig.setMaxIdle(maxIdle > 0 ? maxIdle : 1); poolConfig.setMaxWaitMillis(5000); poolConfig.setTestOnBorrow(false); poolConfig.setTestWhileIdle(true); } // create & initialize JedisConnector
try (JedisConnector connector = new JedisConnector()) {
DDTH/ddth-commons
ddth-commons-core/src/test/java/com/github/ddth/commons/test/ClassB.java
// Path: ddth-commons-core/src/main/java/com/github/ddth/commons/utils/MapUtils.java // public class MapUtils { // /** // * Extract a date value from the map. If the extracted value is // * a string, parse it as a {@link Date} using the specified date-time format. // * // * @param map // * @param key // * @param dateTimeFormat // * @return // * @since 0.6.3.1 // */ // public static Date getDate(Map<String, Object> map, String key, String dateTimeFormat) { // Object obj = map.get(key); // return obj instanceof Number ? new Date(((Number) obj).longValue()) // : (obj instanceof String // ? DateFormatUtils.fromString(obj.toString(), dateTimeFormat) // : (obj instanceof Date ? (Date) obj : null)); // } // // /** // * Extract a value from a map. // * // * @param map // * @param key // * @param clazz // * @return // */ // public static <T> T getValue(Map<String, Object> map, String key, Class<T> clazz) { // return map != null ? ValueUtils.convertValue(map.get(key), clazz) : null; // } // // /** // * Create a {@link Map} from flat array of objects. // * // * @param keysAndValues // * @return // */ // @SuppressWarnings("unchecked") // public static <K extends Object, V extends Object> Map<K, V> createMap( // Object... keysAndValues) { // if (keysAndValues == null) { // return null; // } // if (keysAndValues.length % 2 != 0) { // throw new IllegalArgumentException("Number of arguments must be even!"); // } // Map<K, V> result = new LinkedHashMap<>(); // for (int i = 0, n = keysAndValues.length / 2; i < n; i++) { // result.put((K) keysAndValues[i * 2], (V) keysAndValues[i * 2 + 1]); // } // return result; // } // // /** // * Remove null values from map. // * // * @param map // * @return // * @since 0.9.0 // */ // public static <K, V> Map<K, V> removeNulls(Map<K, V> map) { // Map<K, V> result = new LinkedHashMap<>(); // map.forEach((k, v) -> { // if (v != null) { // result.put(k, v); // } // }); // return result; // } // }
import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.commons.lang3.builder.EqualsBuilder; import com.github.ddth.commons.utils.MapUtils;
package com.github.ddth.commons.test; public class ClassB { public ClassA fieldA = new ClassA(); protected int[] fieldArrInt = { 1, 2, 3, 4 };
// Path: ddth-commons-core/src/main/java/com/github/ddth/commons/utils/MapUtils.java // public class MapUtils { // /** // * Extract a date value from the map. If the extracted value is // * a string, parse it as a {@link Date} using the specified date-time format. // * // * @param map // * @param key // * @param dateTimeFormat // * @return // * @since 0.6.3.1 // */ // public static Date getDate(Map<String, Object> map, String key, String dateTimeFormat) { // Object obj = map.get(key); // return obj instanceof Number ? new Date(((Number) obj).longValue()) // : (obj instanceof String // ? DateFormatUtils.fromString(obj.toString(), dateTimeFormat) // : (obj instanceof Date ? (Date) obj : null)); // } // // /** // * Extract a value from a map. // * // * @param map // * @param key // * @param clazz // * @return // */ // public static <T> T getValue(Map<String, Object> map, String key, Class<T> clazz) { // return map != null ? ValueUtils.convertValue(map.get(key), clazz) : null; // } // // /** // * Create a {@link Map} from flat array of objects. // * // * @param keysAndValues // * @return // */ // @SuppressWarnings("unchecked") // public static <K extends Object, V extends Object> Map<K, V> createMap( // Object... keysAndValues) { // if (keysAndValues == null) { // return null; // } // if (keysAndValues.length % 2 != 0) { // throw new IllegalArgumentException("Number of arguments must be even!"); // } // Map<K, V> result = new LinkedHashMap<>(); // for (int i = 0, n = keysAndValues.length / 2; i < n; i++) { // result.put((K) keysAndValues[i * 2], (V) keysAndValues[i * 2 + 1]); // } // return result; // } // // /** // * Remove null values from map. // * // * @param map // * @return // * @since 0.9.0 // */ // public static <K, V> Map<K, V> removeNulls(Map<K, V> map) { // Map<K, V> result = new LinkedHashMap<>(); // map.forEach((k, v) -> { // if (v != null) { // result.put(k, v); // } // }); // return result; // } // } // Path: ddth-commons-core/src/test/java/com/github/ddth/commons/test/ClassB.java import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.commons.lang3.builder.EqualsBuilder; import com.github.ddth.commons.utils.MapUtils; package com.github.ddth.commons.test; public class ClassB { public ClassA fieldA = new ClassA(); protected int[] fieldArrInt = { 1, 2, 3, 4 };
private Map<String, Object> fieldMap = MapUtils.createMap("a", "1", "b", 2, "c", true);
DDTH/ddth-commons
ddth-commons-core/src/test/java/com/github/ddth/commons/qnd/utils/QndJedisConnector.java
// Path: ddth-commons-core/src/main/java/com/github/ddth/commons/redis/JedisConnector.java // public class JedisConnector implements AutoCloseable { // private final Logger LOGGER = LoggerFactory.getLogger(JedisConnector.class); // // private String redisHostsAndPorts = Protocol.DEFAULT_HOST + ":" + Protocol.DEFAULT_PORT; // private String redisPassword; // private JedisPoolConfig poolConfig; // private JedisPool jedisPool; // private JedisCluster jedisCluster; // private ShardedJedisPool shardedJedisPool; // // public JedisPoolConfig getJedisPoolConfig() { // return poolConfig; // } // // public JedisConnector setJedisPoolConfig(JedisPoolConfig poolConfig) { // this.poolConfig = poolConfig; // return this; // } // // /** // * Get Redis' hosts and ports scheme (format {@code host1:port1,host2:port2}). // * // * @return // */ // public String getRedisHostsAndPorts() { // return redisHostsAndPorts; // } // // /** // * Set Redis' hosts and ports scheme (format {@code host1:port1,host2:port2}). // * // * @param redisHostsAndPorts // * @return // */ // public JedisConnector setRedisHostsAndPorts(String redisHostsAndPorts) { // this.redisHostsAndPorts = redisHostsAndPorts; // return this; // } // // public String getRedisPassword() { // return redisPassword; // } // // public JedisConnector setRedisPassword(String redisPassword) { // this.redisPassword = redisPassword; // return this; // } // // synchronized private void connectJedisPool() { // if (jedisPool == null) { // String[] tokens = redisHostsAndPorts.split("[,;\\s]+"); // jedisPool = JedisUtils.newJedisPool(getJedisPoolConfig(), tokens[0], // getRedisPassword()); // } // } // // public Jedis getJedis() { // if (jedisPool == null) { // connectJedisPool(); // } // return jedisPool.getResource(); // } // // synchronized private void connectJedisCluster() { // if (jedisCluster == null) { // jedisCluster = JedisUtils.newJedisCluster(getJedisPoolConfig(), getRedisHostsAndPorts(), // getRedisPassword()); // } // } // // public JedisCluster getJedisCluster() { // if (jedisCluster == null) { // connectJedisCluster(); // } // return jedisCluster; // } // // synchronized private void connectShardedJedisPool() { // if (shardedJedisPool == null) { // shardedJedisPool = JedisUtils.newShardedJedisPool(getJedisPoolConfig(), // getRedisHostsAndPorts(), getRedisPassword()); // } // } // // public ShardedJedis getShardedJedis() { // if (shardedJedisPool == null) { // connectShardedJedisPool(); // } // return shardedJedisPool.getResource(); // } // // public JedisConnector init() { // return this; // } // // public void destroy() { // if (jedisPool != null) { // try { // jedisPool.close(); // } catch (Exception e) { // LOGGER.warn(e.getMessage(), e); // } finally { // jedisPool = null; // } // } // // if (jedisCluster != null) { // try { // jedisCluster.close(); // } catch (Exception e) { // LOGGER.warn(e.getMessage(), e); // } finally { // jedisCluster = null; // } // } // // if (shardedJedisPool != null) { // try { // shardedJedisPool.close(); // } catch (Exception e) { // LOGGER.warn(e.getMessage(), e); // } finally { // shardedJedisPool = null; // } // } // } // // /** // * {@inheritDoc} // */ // @Override // public void close() { // destroy(); // } // // }
import java.io.IOException; import com.github.ddth.commons.redis.JedisConnector; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisCluster; import redis.clients.jedis.ShardedJedis;
package com.github.ddth.commons.qnd.utils; public class QndJedisConnector { public static void main(String[] args) throws IOException {
// Path: ddth-commons-core/src/main/java/com/github/ddth/commons/redis/JedisConnector.java // public class JedisConnector implements AutoCloseable { // private final Logger LOGGER = LoggerFactory.getLogger(JedisConnector.class); // // private String redisHostsAndPorts = Protocol.DEFAULT_HOST + ":" + Protocol.DEFAULT_PORT; // private String redisPassword; // private JedisPoolConfig poolConfig; // private JedisPool jedisPool; // private JedisCluster jedisCluster; // private ShardedJedisPool shardedJedisPool; // // public JedisPoolConfig getJedisPoolConfig() { // return poolConfig; // } // // public JedisConnector setJedisPoolConfig(JedisPoolConfig poolConfig) { // this.poolConfig = poolConfig; // return this; // } // // /** // * Get Redis' hosts and ports scheme (format {@code host1:port1,host2:port2}). // * // * @return // */ // public String getRedisHostsAndPorts() { // return redisHostsAndPorts; // } // // /** // * Set Redis' hosts and ports scheme (format {@code host1:port1,host2:port2}). // * // * @param redisHostsAndPorts // * @return // */ // public JedisConnector setRedisHostsAndPorts(String redisHostsAndPorts) { // this.redisHostsAndPorts = redisHostsAndPorts; // return this; // } // // public String getRedisPassword() { // return redisPassword; // } // // public JedisConnector setRedisPassword(String redisPassword) { // this.redisPassword = redisPassword; // return this; // } // // synchronized private void connectJedisPool() { // if (jedisPool == null) { // String[] tokens = redisHostsAndPorts.split("[,;\\s]+"); // jedisPool = JedisUtils.newJedisPool(getJedisPoolConfig(), tokens[0], // getRedisPassword()); // } // } // // public Jedis getJedis() { // if (jedisPool == null) { // connectJedisPool(); // } // return jedisPool.getResource(); // } // // synchronized private void connectJedisCluster() { // if (jedisCluster == null) { // jedisCluster = JedisUtils.newJedisCluster(getJedisPoolConfig(), getRedisHostsAndPorts(), // getRedisPassword()); // } // } // // public JedisCluster getJedisCluster() { // if (jedisCluster == null) { // connectJedisCluster(); // } // return jedisCluster; // } // // synchronized private void connectShardedJedisPool() { // if (shardedJedisPool == null) { // shardedJedisPool = JedisUtils.newShardedJedisPool(getJedisPoolConfig(), // getRedisHostsAndPorts(), getRedisPassword()); // } // } // // public ShardedJedis getShardedJedis() { // if (shardedJedisPool == null) { // connectShardedJedisPool(); // } // return shardedJedisPool.getResource(); // } // // public JedisConnector init() { // return this; // } // // public void destroy() { // if (jedisPool != null) { // try { // jedisPool.close(); // } catch (Exception e) { // LOGGER.warn(e.getMessage(), e); // } finally { // jedisPool = null; // } // } // // if (jedisCluster != null) { // try { // jedisCluster.close(); // } catch (Exception e) { // LOGGER.warn(e.getMessage(), e); // } finally { // jedisCluster = null; // } // } // // if (shardedJedisPool != null) { // try { // shardedJedisPool.close(); // } catch (Exception e) { // LOGGER.warn(e.getMessage(), e); // } finally { // shardedJedisPool = null; // } // } // } // // /** // * {@inheritDoc} // */ // @Override // public void close() { // destroy(); // } // // } // Path: ddth-commons-core/src/test/java/com/github/ddth/commons/qnd/utils/QndJedisConnector.java import java.io.IOException; import com.github.ddth.commons.redis.JedisConnector; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisCluster; import redis.clients.jedis.ShardedJedis; package com.github.ddth.commons.qnd.utils; public class QndJedisConnector { public static void main(String[] args) throws IOException {
try (JedisConnector jc = new JedisConnector()) {
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/SerializationUtils.java
// Path: ddth-commons-core/src/main/java/com/github/ddth/commons/serialization/DeserializationException.java // public class DeserializationException extends SerDeserException { // // private static final long serialVersionUID = 1L; // // public DeserializationException() { // } // // public DeserializationException(String message) { // super(message); // } // // public DeserializationException(Throwable cause) { // super(cause); // } // // public DeserializationException(String message, Throwable cause) { // super(message, cause); // } // // public DeserializationException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // } // // Path: ddth-commons-core/src/main/java/com/github/ddth/commons/serialization/ISerializationSupport.java // public interface ISerializationSupport { // /** // * Serializes this object to {@code byte[]}. // * // * @return // * @throws SerializationException // */ // public byte[] toBytes() throws SerializationException; // // /** // * Deserializes and populates this object. // * // * @param data // * @return // * @throws DeserializationException // */ // public ISerializationSupport fromBytes(byte[] data) throws DeserializationException; // } // // Path: ddth-commons-core/src/main/java/com/github/ddth/commons/serialization/SerializationException.java // public class SerializationException extends SerDeserException { // // private static final long serialVersionUID = 1L; // // public SerializationException() { // } // // public SerializationException(String message) { // super(message); // } // // public SerializationException(Throwable cause) { // super(cause); // } // // public SerializationException(String message, Throwable cause) { // super(message, cause); // } // // public SerializationException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // }
import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.Reader; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import org.apache.commons.lang3.StringUtils; import org.apache.commons.pool2.BasePooledObjectFactory; import org.apache.commons.pool2.ObjectPool; import org.apache.commons.pool2.PooledObject; import org.apache.commons.pool2.impl.DefaultPooledObject; import org.apache.commons.pool2.impl.GenericObjectPool; import org.nustaq.serialization.FSTConfiguration; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.esotericsoftware.kryo.util.Pool; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.NullNode; import com.github.ddth.commons.serialization.DeserializationException; import com.github.ddth.commons.serialization.ISerializationSupport; import com.github.ddth.commons.serialization.SerializationException;
package com.github.ddth.commons.utils; /** * Serialization helper class. * * <ul> * <li>JSON serialization: use {@code com.fasterxml.jackson} library.</li> * <li>Binary serialization: 3 choices of API * <ul> * <li>{@code jboss-serialization} library (deprecated since v0.6.0!), or</li> * <li>{@code Kryo} library or</li> * <li>{@code FST} library</li> * </ul> * </li> * </ul> * * @author Thanh Nguyen <[email protected]> * @since 0.2.0 */ public class SerializationUtils { /*----------------------------------------------------------------------*/ /** * Serialize an object to byte array. * * <p> * If the target object implements {@link ISerializationSupport}, this * method calls its {@link ISerializationSupport#toBytes()} method; * otherwise FST library is used to serialize the object. * </p> * * @param obj * @return * @deprecated since 0.9.2 with no replacement, use {@link #toByteArrayFst(Object)} or * {@link #toByteArrayKryo(Object)} */ public static byte[] toByteArray(Object obj) { return toByteArray(obj, null); } /** * Serialize an object to byte array, with a custom class loader. * * <p> * If the target object implements {@link ISerializationSupport}, this * method calls its {@link ISerializationSupport#toBytes()} method; * otherwise FST library is used to serialize the object. * </p> * * @param obj * @param classLoader * @return * @deprecated since 0.9.2 with no replacement, use {@link #toByteArrayFst(Object, ClassLoader)} * or {@link #toByteArrayKryo(Object, ClassLoader)} */ public static byte[] toByteArray(Object obj, ClassLoader classLoader) {
// Path: ddth-commons-core/src/main/java/com/github/ddth/commons/serialization/DeserializationException.java // public class DeserializationException extends SerDeserException { // // private static final long serialVersionUID = 1L; // // public DeserializationException() { // } // // public DeserializationException(String message) { // super(message); // } // // public DeserializationException(Throwable cause) { // super(cause); // } // // public DeserializationException(String message, Throwable cause) { // super(message, cause); // } // // public DeserializationException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // } // // Path: ddth-commons-core/src/main/java/com/github/ddth/commons/serialization/ISerializationSupport.java // public interface ISerializationSupport { // /** // * Serializes this object to {@code byte[]}. // * // * @return // * @throws SerializationException // */ // public byte[] toBytes() throws SerializationException; // // /** // * Deserializes and populates this object. // * // * @param data // * @return // * @throws DeserializationException // */ // public ISerializationSupport fromBytes(byte[] data) throws DeserializationException; // } // // Path: ddth-commons-core/src/main/java/com/github/ddth/commons/serialization/SerializationException.java // public class SerializationException extends SerDeserException { // // private static final long serialVersionUID = 1L; // // public SerializationException() { // } // // public SerializationException(String message) { // super(message); // } // // public SerializationException(Throwable cause) { // super(cause); // } // // public SerializationException(String message, Throwable cause) { // super(message, cause); // } // // public SerializationException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // } // Path: ddth-commons-core/src/main/java/com/github/ddth/commons/utils/SerializationUtils.java import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.Reader; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import org.apache.commons.lang3.StringUtils; import org.apache.commons.pool2.BasePooledObjectFactory; import org.apache.commons.pool2.ObjectPool; import org.apache.commons.pool2.PooledObject; import org.apache.commons.pool2.impl.DefaultPooledObject; import org.apache.commons.pool2.impl.GenericObjectPool; import org.nustaq.serialization.FSTConfiguration; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.esotericsoftware.kryo.util.Pool; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.NullNode; import com.github.ddth.commons.serialization.DeserializationException; import com.github.ddth.commons.serialization.ISerializationSupport; import com.github.ddth.commons.serialization.SerializationException; package com.github.ddth.commons.utils; /** * Serialization helper class. * * <ul> * <li>JSON serialization: use {@code com.fasterxml.jackson} library.</li> * <li>Binary serialization: 3 choices of API * <ul> * <li>{@code jboss-serialization} library (deprecated since v0.6.0!), or</li> * <li>{@code Kryo} library or</li> * <li>{@code FST} library</li> * </ul> * </li> * </ul> * * @author Thanh Nguyen <[email protected]> * @since 0.2.0 */ public class SerializationUtils { /*----------------------------------------------------------------------*/ /** * Serialize an object to byte array. * * <p> * If the target object implements {@link ISerializationSupport}, this * method calls its {@link ISerializationSupport#toBytes()} method; * otherwise FST library is used to serialize the object. * </p> * * @param obj * @return * @deprecated since 0.9.2 with no replacement, use {@link #toByteArrayFst(Object)} or * {@link #toByteArrayKryo(Object)} */ public static byte[] toByteArray(Object obj) { return toByteArray(obj, null); } /** * Serialize an object to byte array, with a custom class loader. * * <p> * If the target object implements {@link ISerializationSupport}, this * method calls its {@link ISerializationSupport#toBytes()} method; * otherwise FST library is used to serialize the object. * </p> * * @param obj * @param classLoader * @return * @deprecated since 0.9.2 with no replacement, use {@link #toByteArrayFst(Object, ClassLoader)} * or {@link #toByteArrayKryo(Object, ClassLoader)} */ public static byte[] toByteArray(Object obj, ClassLoader classLoader) {
if (obj instanceof ISerializationSupport) {
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/SerializationUtils.java
// Path: ddth-commons-core/src/main/java/com/github/ddth/commons/serialization/DeserializationException.java // public class DeserializationException extends SerDeserException { // // private static final long serialVersionUID = 1L; // // public DeserializationException() { // } // // public DeserializationException(String message) { // super(message); // } // // public DeserializationException(Throwable cause) { // super(cause); // } // // public DeserializationException(String message, Throwable cause) { // super(message, cause); // } // // public DeserializationException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // } // // Path: ddth-commons-core/src/main/java/com/github/ddth/commons/serialization/ISerializationSupport.java // public interface ISerializationSupport { // /** // * Serializes this object to {@code byte[]}. // * // * @return // * @throws SerializationException // */ // public byte[] toBytes() throws SerializationException; // // /** // * Deserializes and populates this object. // * // * @param data // * @return // * @throws DeserializationException // */ // public ISerializationSupport fromBytes(byte[] data) throws DeserializationException; // } // // Path: ddth-commons-core/src/main/java/com/github/ddth/commons/serialization/SerializationException.java // public class SerializationException extends SerDeserException { // // private static final long serialVersionUID = 1L; // // public SerializationException() { // } // // public SerializationException(String message) { // super(message); // } // // public SerializationException(Throwable cause) { // super(cause); // } // // public SerializationException(String message, Throwable cause) { // super(message, cause); // } // // public SerializationException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // }
import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.Reader; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import org.apache.commons.lang3.StringUtils; import org.apache.commons.pool2.BasePooledObjectFactory; import org.apache.commons.pool2.ObjectPool; import org.apache.commons.pool2.PooledObject; import org.apache.commons.pool2.impl.DefaultPooledObject; import org.apache.commons.pool2.impl.GenericObjectPool; import org.nustaq.serialization.FSTConfiguration; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.esotericsoftware.kryo.util.Pool; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.NullNode; import com.github.ddth.commons.serialization.DeserializationException; import com.github.ddth.commons.serialization.ISerializationSupport; import com.github.ddth.commons.serialization.SerializationException;
* If the target class implements {@link ISerializationSupport}, this method * calls its {@link ISerializationSupport#toBytes()} method; otherwise FST * library is used to serialize the object. * </p> * * @param data * @param clazz * @param classLoader * @return * @deprecated since 0.9.2 with no replacement, use * {@link #fromByteArrayFst(byte[], Class, ClassLoader)} or * {@link #fromByteArrayKryo(byte[], Class, ClassLoader)} */ public static <T> T fromByteArray(byte[] data, Class<T> clazz, ClassLoader classLoader) { if (data == null) { return null; } if (ReflectionUtils.hasInterface(clazz, ISerializationSupport.class)) { ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); if (classLoader != null) { Thread.currentThread().setContextClassLoader(classLoader); } try { Constructor<T> constructor = clazz.getDeclaredConstructor(); constructor.setAccessible(true); T obj = constructor.newInstance(); ((ISerializationSupport) obj).fromBytes(data); return obj; } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException e) {
// Path: ddth-commons-core/src/main/java/com/github/ddth/commons/serialization/DeserializationException.java // public class DeserializationException extends SerDeserException { // // private static final long serialVersionUID = 1L; // // public DeserializationException() { // } // // public DeserializationException(String message) { // super(message); // } // // public DeserializationException(Throwable cause) { // super(cause); // } // // public DeserializationException(String message, Throwable cause) { // super(message, cause); // } // // public DeserializationException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // } // // Path: ddth-commons-core/src/main/java/com/github/ddth/commons/serialization/ISerializationSupport.java // public interface ISerializationSupport { // /** // * Serializes this object to {@code byte[]}. // * // * @return // * @throws SerializationException // */ // public byte[] toBytes() throws SerializationException; // // /** // * Deserializes and populates this object. // * // * @param data // * @return // * @throws DeserializationException // */ // public ISerializationSupport fromBytes(byte[] data) throws DeserializationException; // } // // Path: ddth-commons-core/src/main/java/com/github/ddth/commons/serialization/SerializationException.java // public class SerializationException extends SerDeserException { // // private static final long serialVersionUID = 1L; // // public SerializationException() { // } // // public SerializationException(String message) { // super(message); // } // // public SerializationException(Throwable cause) { // super(cause); // } // // public SerializationException(String message, Throwable cause) { // super(message, cause); // } // // public SerializationException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // } // Path: ddth-commons-core/src/main/java/com/github/ddth/commons/utils/SerializationUtils.java import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.Reader; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import org.apache.commons.lang3.StringUtils; import org.apache.commons.pool2.BasePooledObjectFactory; import org.apache.commons.pool2.ObjectPool; import org.apache.commons.pool2.PooledObject; import org.apache.commons.pool2.impl.DefaultPooledObject; import org.apache.commons.pool2.impl.GenericObjectPool; import org.nustaq.serialization.FSTConfiguration; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.esotericsoftware.kryo.util.Pool; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.NullNode; import com.github.ddth.commons.serialization.DeserializationException; import com.github.ddth.commons.serialization.ISerializationSupport; import com.github.ddth.commons.serialization.SerializationException; * If the target class implements {@link ISerializationSupport}, this method * calls its {@link ISerializationSupport#toBytes()} method; otherwise FST * library is used to serialize the object. * </p> * * @param data * @param clazz * @param classLoader * @return * @deprecated since 0.9.2 with no replacement, use * {@link #fromByteArrayFst(byte[], Class, ClassLoader)} or * {@link #fromByteArrayKryo(byte[], Class, ClassLoader)} */ public static <T> T fromByteArray(byte[] data, Class<T> clazz, ClassLoader classLoader) { if (data == null) { return null; } if (ReflectionUtils.hasInterface(clazz, ISerializationSupport.class)) { ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); if (classLoader != null) { Thread.currentThread().setContextClassLoader(classLoader); } try { Constructor<T> constructor = clazz.getDeclaredConstructor(); constructor.setAccessible(true); T obj = constructor.newInstance(); ((ISerializationSupport) obj).fromBytes(data); return obj; } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException e) {
throw new DeserializationException(e);
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/SerializationUtils.java
// Path: ddth-commons-core/src/main/java/com/github/ddth/commons/serialization/DeserializationException.java // public class DeserializationException extends SerDeserException { // // private static final long serialVersionUID = 1L; // // public DeserializationException() { // } // // public DeserializationException(String message) { // super(message); // } // // public DeserializationException(Throwable cause) { // super(cause); // } // // public DeserializationException(String message, Throwable cause) { // super(message, cause); // } // // public DeserializationException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // } // // Path: ddth-commons-core/src/main/java/com/github/ddth/commons/serialization/ISerializationSupport.java // public interface ISerializationSupport { // /** // * Serializes this object to {@code byte[]}. // * // * @return // * @throws SerializationException // */ // public byte[] toBytes() throws SerializationException; // // /** // * Deserializes and populates this object. // * // * @param data // * @return // * @throws DeserializationException // */ // public ISerializationSupport fromBytes(byte[] data) throws DeserializationException; // } // // Path: ddth-commons-core/src/main/java/com/github/ddth/commons/serialization/SerializationException.java // public class SerializationException extends SerDeserException { // // private static final long serialVersionUID = 1L; // // public SerializationException() { // } // // public SerializationException(String message) { // super(message); // } // // public SerializationException(Throwable cause) { // super(cause); // } // // public SerializationException(String message, Throwable cause) { // super(message, cause); // } // // public SerializationException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // }
import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.Reader; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import org.apache.commons.lang3.StringUtils; import org.apache.commons.pool2.BasePooledObjectFactory; import org.apache.commons.pool2.ObjectPool; import org.apache.commons.pool2.PooledObject; import org.apache.commons.pool2.impl.DefaultPooledObject; import org.apache.commons.pool2.impl.GenericObjectPool; import org.nustaq.serialization.FSTConfiguration; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.esotericsoftware.kryo.util.Pool; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.NullNode; import com.github.ddth.commons.serialization.DeserializationException; import com.github.ddth.commons.serialization.ISerializationSupport; import com.github.ddth.commons.serialization.SerializationException;
/** * Serialize an object to byte array, with a custom class loader. * * <p> * This method uses Kryo lib. * </p> * * @param obj * @param classLoader * @return */ public static byte[] toByteArrayKryo(Object obj, ClassLoader classLoader) { if (obj == null) { return null; } Kryo kryo = kryoPool.obtain(); try { ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); if (classLoader != null) { Thread.currentThread().setContextClassLoader(classLoader); } try { Output output = kryoOutputPool.obtain(); try { kryo.setClassLoader(classLoader != null ? classLoader : oldClassLoader); // kryo.writeObject(output, obj); kryo.writeClassAndObject(output, obj); output.close(); return output.toBytes(); } catch (Exception e) {
// Path: ddth-commons-core/src/main/java/com/github/ddth/commons/serialization/DeserializationException.java // public class DeserializationException extends SerDeserException { // // private static final long serialVersionUID = 1L; // // public DeserializationException() { // } // // public DeserializationException(String message) { // super(message); // } // // public DeserializationException(Throwable cause) { // super(cause); // } // // public DeserializationException(String message, Throwable cause) { // super(message, cause); // } // // public DeserializationException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // } // // Path: ddth-commons-core/src/main/java/com/github/ddth/commons/serialization/ISerializationSupport.java // public interface ISerializationSupport { // /** // * Serializes this object to {@code byte[]}. // * // * @return // * @throws SerializationException // */ // public byte[] toBytes() throws SerializationException; // // /** // * Deserializes and populates this object. // * // * @param data // * @return // * @throws DeserializationException // */ // public ISerializationSupport fromBytes(byte[] data) throws DeserializationException; // } // // Path: ddth-commons-core/src/main/java/com/github/ddth/commons/serialization/SerializationException.java // public class SerializationException extends SerDeserException { // // private static final long serialVersionUID = 1L; // // public SerializationException() { // } // // public SerializationException(String message) { // super(message); // } // // public SerializationException(Throwable cause) { // super(cause); // } // // public SerializationException(String message, Throwable cause) { // super(message, cause); // } // // public SerializationException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // } // Path: ddth-commons-core/src/main/java/com/github/ddth/commons/utils/SerializationUtils.java import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.Reader; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import org.apache.commons.lang3.StringUtils; import org.apache.commons.pool2.BasePooledObjectFactory; import org.apache.commons.pool2.ObjectPool; import org.apache.commons.pool2.PooledObject; import org.apache.commons.pool2.impl.DefaultPooledObject; import org.apache.commons.pool2.impl.GenericObjectPool; import org.nustaq.serialization.FSTConfiguration; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.esotericsoftware.kryo.util.Pool; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.NullNode; import com.github.ddth.commons.serialization.DeserializationException; import com.github.ddth.commons.serialization.ISerializationSupport; import com.github.ddth.commons.serialization.SerializationException; /** * Serialize an object to byte array, with a custom class loader. * * <p> * This method uses Kryo lib. * </p> * * @param obj * @param classLoader * @return */ public static byte[] toByteArrayKryo(Object obj, ClassLoader classLoader) { if (obj == null) { return null; } Kryo kryo = kryoPool.obtain(); try { ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); if (classLoader != null) { Thread.currentThread().setContextClassLoader(classLoader); } try { Output output = kryoOutputPool.obtain(); try { kryo.setClassLoader(classLoader != null ? classLoader : oldClassLoader); // kryo.writeObject(output, obj); kryo.writeClassAndObject(output, obj); output.close(); return output.toBytes(); } catch (Exception e) {
throw e instanceof SerializationException ? (SerializationException) e
DDTH/ddth-commons
ddth-commons-core/src/test/java/com/github/ddth/commons/qnd/utils/QndIpv4.java
// Path: ddth-commons-core/src/main/java/com/github/ddth/commons/utils/Ipv4Utils.java // public class Ipv4Utils { // private final static Pattern IP_PATTERN_FULL = Pattern // .compile("^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$"); // // /** // * Check is an IP is valid. // * // * @param ip // * @return // * @since 0.9.1.1 // */ // public static boolean isValidIp(String ip) { // if (!IP_PATTERN_FULL.matcher(ip).matches()) { // return false; // } // String[] ipArr = ip.split("\\."); // for (String part : ipArr) { // int v = Integer.parseInt(part); // if (v < 0 || v > 255) { // return false; // } // } // return true; // } // // /** // * IP address to long (e.g. 10.0.0.1 -> 167772161). // * // * @param ip // * @return // */ // public static long ipToLong(String ip) { // if (!isValidIp(ip)) { // throw new IllegalArgumentException("Invalid IP address: " + ip); // } // // long result = 0; // String[] ipArr = ip.split("\\."); // for (int i = 3; i >= 0; i--) { // long part = Long.parseLong(ipArr[3 - i]); // result |= part << (i * 8); // } // return result; // } // // /** // * Long to IP address (e.g. 167772161 -> 10.0.0.1) // * // * @param ip // * @return // */ // public static String longToIp(long ip) { // return ((ip >> 24) & 0xFF) + "." + ((ip >> 16) & 0xFF) + "." + ((ip >> 8) & 0xFF) + "." // + (ip & 0xFF); // } // // private final static Pattern IP_PATTERN_PARTIAL = Pattern // .compile("^(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\.\\*?$"); // // private final static Pattern IP_PATTERN_RANGE = Pattern // .compile("^(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\.(\\d{1,3})\\-(\\d{1,3})$"); // // private final static Pattern IP_PATTERN_SUBNET = Pattern // .compile("^(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\/(\\d{1,3})$"); // // /** // * Checks if an IP (e.g. 10.0.0.5) matches a subnet (e.g. 10.0.0.0/24). // * // * @param ip // * in format {@code x.x.x.x} // * @param subnet // * in format {@code x.x.x.x} or {@code x.x.x.x/y} or // * {@code x.x.x.x-y} or {@code x.x.x.*} (alias of // * {@code x.x.x.x/24}) or {@code x.x.x.} (another alias of // * {@code x.x.x.x/24}) // * @return // */ // public static boolean isBelongToSubnet(String ip, String subnet) { // if (subnet == null || ip == null) { // throw new NullPointerException("IP or Subnet is null!"); // } // if (!IP_PATTERN_FULL.matcher(ip).matches()) { // throw new IllegalArgumentException("Invalid IP address: " + ip); // } // // if (IP_PATTERN_FULL.matcher(subnet).matches()) { // return StringUtils.equals(ip, subnet); // } // // long ipAsLong = ipToLong(ip); // Matcher matcherRange = IP_PATTERN_RANGE.matcher(subnet); // if (matcherRange.matches()) { // long ipAsLongStart = ipToLong(matcherRange.group(1) + "." + matcherRange.group(2)); // long ipAsLongEnd = ipToLong(matcherRange.group(1) + "." + matcherRange.group(3)); // return ipAsLongStart <= ipAsLong && ipAsLong <= ipAsLongEnd; // } // // Matcher matcherPartial = IP_PATTERN_PARTIAL.matcher(subnet); // if (matcherPartial.matches()) { // subnet = matcherPartial.group(1) + ".0/24"; // } // Matcher matcherSubnet = IP_PATTERN_SUBNET.matcher(subnet); // if (matcherSubnet.matches()) { // int mask = Integer.parseInt(matcherSubnet.group(2)); // if (mask > 32) { // throw new IllegalArgumentException("Invalid subnet: " + subnet); // } // // String maskAsBinary = StringUtils.repeat('1', mask) // + StringUtils.repeat('0', 32 - mask); // long maskAsLong = Long.parseLong(maskAsBinary, 2); // // String ipBase = matcherSubnet.group(1); // long ipBaseAsLong = ipToLong(ipBase); // ipBaseAsLong &= maskAsLong; // // return ipBaseAsLong == (ipAsLong & maskAsLong); // } // // throw new IllegalArgumentException("Invalid subnet: " + subnet); // } // }
import com.github.ddth.commons.utils.Ipv4Utils;
package com.github.ddth.commons.qnd.utils; public class QndIpv4 { public static void main(String[] args) { String ip = "192.168.1.5"; String subnet = "192.168.1.0/29";
// Path: ddth-commons-core/src/main/java/com/github/ddth/commons/utils/Ipv4Utils.java // public class Ipv4Utils { // private final static Pattern IP_PATTERN_FULL = Pattern // .compile("^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$"); // // /** // * Check is an IP is valid. // * // * @param ip // * @return // * @since 0.9.1.1 // */ // public static boolean isValidIp(String ip) { // if (!IP_PATTERN_FULL.matcher(ip).matches()) { // return false; // } // String[] ipArr = ip.split("\\."); // for (String part : ipArr) { // int v = Integer.parseInt(part); // if (v < 0 || v > 255) { // return false; // } // } // return true; // } // // /** // * IP address to long (e.g. 10.0.0.1 -> 167772161). // * // * @param ip // * @return // */ // public static long ipToLong(String ip) { // if (!isValidIp(ip)) { // throw new IllegalArgumentException("Invalid IP address: " + ip); // } // // long result = 0; // String[] ipArr = ip.split("\\."); // for (int i = 3; i >= 0; i--) { // long part = Long.parseLong(ipArr[3 - i]); // result |= part << (i * 8); // } // return result; // } // // /** // * Long to IP address (e.g. 167772161 -> 10.0.0.1) // * // * @param ip // * @return // */ // public static String longToIp(long ip) { // return ((ip >> 24) & 0xFF) + "." + ((ip >> 16) & 0xFF) + "." + ((ip >> 8) & 0xFF) + "." // + (ip & 0xFF); // } // // private final static Pattern IP_PATTERN_PARTIAL = Pattern // .compile("^(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\.\\*?$"); // // private final static Pattern IP_PATTERN_RANGE = Pattern // .compile("^(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\.(\\d{1,3})\\-(\\d{1,3})$"); // // private final static Pattern IP_PATTERN_SUBNET = Pattern // .compile("^(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\/(\\d{1,3})$"); // // /** // * Checks if an IP (e.g. 10.0.0.5) matches a subnet (e.g. 10.0.0.0/24). // * // * @param ip // * in format {@code x.x.x.x} // * @param subnet // * in format {@code x.x.x.x} or {@code x.x.x.x/y} or // * {@code x.x.x.x-y} or {@code x.x.x.*} (alias of // * {@code x.x.x.x/24}) or {@code x.x.x.} (another alias of // * {@code x.x.x.x/24}) // * @return // */ // public static boolean isBelongToSubnet(String ip, String subnet) { // if (subnet == null || ip == null) { // throw new NullPointerException("IP or Subnet is null!"); // } // if (!IP_PATTERN_FULL.matcher(ip).matches()) { // throw new IllegalArgumentException("Invalid IP address: " + ip); // } // // if (IP_PATTERN_FULL.matcher(subnet).matches()) { // return StringUtils.equals(ip, subnet); // } // // long ipAsLong = ipToLong(ip); // Matcher matcherRange = IP_PATTERN_RANGE.matcher(subnet); // if (matcherRange.matches()) { // long ipAsLongStart = ipToLong(matcherRange.group(1) + "." + matcherRange.group(2)); // long ipAsLongEnd = ipToLong(matcherRange.group(1) + "." + matcherRange.group(3)); // return ipAsLongStart <= ipAsLong && ipAsLong <= ipAsLongEnd; // } // // Matcher matcherPartial = IP_PATTERN_PARTIAL.matcher(subnet); // if (matcherPartial.matches()) { // subnet = matcherPartial.group(1) + ".0/24"; // } // Matcher matcherSubnet = IP_PATTERN_SUBNET.matcher(subnet); // if (matcherSubnet.matches()) { // int mask = Integer.parseInt(matcherSubnet.group(2)); // if (mask > 32) { // throw new IllegalArgumentException("Invalid subnet: " + subnet); // } // // String maskAsBinary = StringUtils.repeat('1', mask) // + StringUtils.repeat('0', 32 - mask); // long maskAsLong = Long.parseLong(maskAsBinary, 2); // // String ipBase = matcherSubnet.group(1); // long ipBaseAsLong = ipToLong(ipBase); // ipBaseAsLong &= maskAsLong; // // return ipBaseAsLong == (ipAsLong & maskAsLong); // } // // throw new IllegalArgumentException("Invalid subnet: " + subnet); // } // } // Path: ddth-commons-core/src/test/java/com/github/ddth/commons/qnd/utils/QndIpv4.java import com.github.ddth.commons.utils.Ipv4Utils; package com.github.ddth.commons.qnd.utils; public class QndIpv4 { public static void main(String[] args) { String ip = "192.168.1.5"; String subnet = "192.168.1.0/29";
System.out.println(Ipv4Utils.isBelongToSubnet(ip, subnet));
DDTH/ddth-commons
ddth-commons-core/src/test/java/com/github/ddth/commons/test/serialization/FstSerDeserTest.java
// Path: ddth-commons-core/src/main/java/com/github/ddth/commons/serialization/FstSerDeser.java // public class FstSerDeser implements ISerDeser { // /** // * {@inheritDoc} // */ // @Override // public byte[] toBytes(Object obj) throws SerializationException { // return toBytes(obj, null); // } // // /** // * {@inheritDoc} // */ // @Override // public byte[] toBytes(Object obj, ClassLoader classLoader) throws SerializationException { // return SerializationUtils.toByteArrayFst(obj, classLoader); // } // // /** // * {@inheritDoc} // */ // @Override // public <T> T fromBytes(byte[] data, Class<T> clazz) throws DeserializationException { // return fromBytes(data, clazz, null); // } // // /** // * {@inheritDoc} // */ // @Override // public <T> T fromBytes(byte[] data, Class<T> clazz, ClassLoader classLoader) // throws DeserializationException { // return SerializationUtils.fromByteArrayFst(data, clazz, classLoader); // } // }
import com.github.ddth.commons.serialization.FstSerDeser; import junit.framework.Test; import junit.framework.TestSuite;
package com.github.ddth.commons.test.serialization; /* * mvn test -DskipTests=false -Dtest=com.github.ddth.commons.test.serialization.FstSerDeserTest */ public class FstSerDeserTest extends BaseSerDeserTest { public FstSerDeserTest(String testName) { super(testName); } public static Test suite() { return new TestSuite(FstSerDeserTest.class); } @org.junit.Test public void testFst() {
// Path: ddth-commons-core/src/main/java/com/github/ddth/commons/serialization/FstSerDeser.java // public class FstSerDeser implements ISerDeser { // /** // * {@inheritDoc} // */ // @Override // public byte[] toBytes(Object obj) throws SerializationException { // return toBytes(obj, null); // } // // /** // * {@inheritDoc} // */ // @Override // public byte[] toBytes(Object obj, ClassLoader classLoader) throws SerializationException { // return SerializationUtils.toByteArrayFst(obj, classLoader); // } // // /** // * {@inheritDoc} // */ // @Override // public <T> T fromBytes(byte[] data, Class<T> clazz) throws DeserializationException { // return fromBytes(data, clazz, null); // } // // /** // * {@inheritDoc} // */ // @Override // public <T> T fromBytes(byte[] data, Class<T> clazz, ClassLoader classLoader) // throws DeserializationException { // return SerializationUtils.fromByteArrayFst(data, clazz, classLoader); // } // } // Path: ddth-commons-core/src/test/java/com/github/ddth/commons/test/serialization/FstSerDeserTest.java import com.github.ddth.commons.serialization.FstSerDeser; import junit.framework.Test; import junit.framework.TestSuite; package com.github.ddth.commons.test.serialization; /* * mvn test -DskipTests=false -Dtest=com.github.ddth.commons.test.serialization.FstSerDeserTest */ public class FstSerDeserTest extends BaseSerDeserTest { public FstSerDeserTest(String testName) { super(testName); } public static Test suite() { return new TestSuite(FstSerDeserTest.class); } @org.junit.Test public void testFst() {
doTest(new FstSerDeser());
DDTH/ddth-commons
ddth-commons-core/src/test/java/com/github/ddth/commons/test/utils/DateFormatUtilsTest.java
// Path: ddth-commons-core/src/main/java/com/github/ddth/commons/utils/DateFormatUtils.java // public class DateFormatUtils { // // /** // * @since 0.7.0 // */ // public final static String DF_ISO8601 = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; // // /** // * @since 0.2.2.3 // */ // private final static class MyDateFormat extends SimpleDateFormat { // private static final long serialVersionUID = 1L; // private final UUID id = UUID.randomUUID(); // // public MyDateFormat(String format) { // super(format); // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (!(o instanceof MyDateFormat)) { // return false; // } // // MyDateFormat that = (MyDateFormat) o; // if (id != null ? !id.equals(that.id) : that.id != null) { // return false; // } // // return true; // } // // @Override // public int hashCode() { // return id != null ? id.hashCode() : 0; // } // } // // private final static class DateFormatFactory extends BasePooledObjectFactory<DateFormat> { // private String format; // // public DateFormatFactory(String format) { // this.format = format; // } // // /** // * {@inheritDoc} // */ // @Override // public DateFormat create() throws Exception { // return new MyDateFormat(format); // } // // /** // * {@inheritDoc} // */ // @Override // public PooledObject<DateFormat> wrap(DateFormat df) { // return new DefaultPooledObject<DateFormat>(df); // } // } // // private final static LoadingCache<String, ObjectPool<DateFormat>> cachedDateFormat = CacheBuilder // .newBuilder().maximumSize(100).expireAfterAccess(3600, TimeUnit.SECONDS) // .concurrencyLevel(2) // .removalListener(new RemovalListener<String, ObjectPool<DateFormat>>() { // @Override // public void onRemoval(RemovalNotification<String, ObjectPool<DateFormat>> event) { // event.getValue().close(); // } // }).build(new CacheLoader<String, ObjectPool<DateFormat>>() { // @Override // public ObjectPool<DateFormat> load(String format) throws Exception { // DateFormatFactory dff = new DateFormatFactory(format); // ObjectPool<DateFormat> obj = new GenericObjectPool<DateFormat>(dff); // return obj; // } // }); // // /** // * Convert a {@link Date} to string, based on the specified {@code format}. // * // * @param date // * @param format // * @return // * @see {@link SimpleDateFormat} // */ // public static String toString(Date date, String format) { // try { // ObjectPool<DateFormat> pool = cachedDateFormat.get(format); // try { // DateFormat df = pool.borrowObject(); // try { // return df.format(date); // } finally { // pool.returnObject(df); // } // } catch (Exception e) { // throw e instanceof RuntimeException ? (RuntimeException) e // : new RuntimeException(e); // } // } catch (ExecutionException e) { // throw new RuntimeException(e); // } // } // // /** // * Convert a {@link Calendar} to string, based on the specified {@code format}. // * // * @param calendar // * @param format // * @return // * @see {@link SimpleDateFormat} // * @since 0.9.1.1 // */ // public static String toString(Calendar calendar, String format) { // return toString(calendar.getTime(), format); // } // // /** // * Parse a string to {@link Date}, based on the specified {@code format}. // * // * @param source // * @param format // * @return // */ // public static Date fromString(String source, String format) { // try { // ObjectPool<DateFormat> pool = cachedDateFormat.get(format); // try { // DateFormat df = pool.borrowObject(); // try { // return df.parse(source); // } finally { // pool.returnObject(df); // } // } catch (Exception e) { // throw e instanceof RuntimeException ? (RuntimeException) e // : new RuntimeException(e); // } // } catch (ExecutionException e) { // throw new RuntimeException(e); // } // } // }
import java.util.Calendar; import com.github.ddth.commons.utils.DateFormatUtils; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite;
public static Test suite() { return new TestSuite(DateFormatUtilsTest.class); } private static int[] FIELDS = { Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND }; private static int[] FIELD_VALUES = { 2018, Calendar.MARCH, 01, 04, 29, 01, 981 }; private static String[] FORMATS = { "yyyy", "MM", "dd", "HH", "mm", "ss", "SSS" }; private static String[] DELIMS = { " ", ":", "-", "_", "/", ".", ";" }; private static Calendar testData() { final Calendar cal = Calendar.getInstance(); for (int i = 0; i < FIELDS.length; i++) { cal.set(FIELDS[i], FIELD_VALUES[i]); } return cal; } private static String normValue(int i, int index) { if (index == 1) { i++; } return i < 10 ? "0" + String.valueOf(i) : String.valueOf(i); } @org.junit.Test public void testToStringDate1() { final Calendar cal = testData(); for (int i = 0; i < FORMATS.length; i++) { String format = FORMATS[i];
// Path: ddth-commons-core/src/main/java/com/github/ddth/commons/utils/DateFormatUtils.java // public class DateFormatUtils { // // /** // * @since 0.7.0 // */ // public final static String DF_ISO8601 = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; // // /** // * @since 0.2.2.3 // */ // private final static class MyDateFormat extends SimpleDateFormat { // private static final long serialVersionUID = 1L; // private final UUID id = UUID.randomUUID(); // // public MyDateFormat(String format) { // super(format); // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (!(o instanceof MyDateFormat)) { // return false; // } // // MyDateFormat that = (MyDateFormat) o; // if (id != null ? !id.equals(that.id) : that.id != null) { // return false; // } // // return true; // } // // @Override // public int hashCode() { // return id != null ? id.hashCode() : 0; // } // } // // private final static class DateFormatFactory extends BasePooledObjectFactory<DateFormat> { // private String format; // // public DateFormatFactory(String format) { // this.format = format; // } // // /** // * {@inheritDoc} // */ // @Override // public DateFormat create() throws Exception { // return new MyDateFormat(format); // } // // /** // * {@inheritDoc} // */ // @Override // public PooledObject<DateFormat> wrap(DateFormat df) { // return new DefaultPooledObject<DateFormat>(df); // } // } // // private final static LoadingCache<String, ObjectPool<DateFormat>> cachedDateFormat = CacheBuilder // .newBuilder().maximumSize(100).expireAfterAccess(3600, TimeUnit.SECONDS) // .concurrencyLevel(2) // .removalListener(new RemovalListener<String, ObjectPool<DateFormat>>() { // @Override // public void onRemoval(RemovalNotification<String, ObjectPool<DateFormat>> event) { // event.getValue().close(); // } // }).build(new CacheLoader<String, ObjectPool<DateFormat>>() { // @Override // public ObjectPool<DateFormat> load(String format) throws Exception { // DateFormatFactory dff = new DateFormatFactory(format); // ObjectPool<DateFormat> obj = new GenericObjectPool<DateFormat>(dff); // return obj; // } // }); // // /** // * Convert a {@link Date} to string, based on the specified {@code format}. // * // * @param date // * @param format // * @return // * @see {@link SimpleDateFormat} // */ // public static String toString(Date date, String format) { // try { // ObjectPool<DateFormat> pool = cachedDateFormat.get(format); // try { // DateFormat df = pool.borrowObject(); // try { // return df.format(date); // } finally { // pool.returnObject(df); // } // } catch (Exception e) { // throw e instanceof RuntimeException ? (RuntimeException) e // : new RuntimeException(e); // } // } catch (ExecutionException e) { // throw new RuntimeException(e); // } // } // // /** // * Convert a {@link Calendar} to string, based on the specified {@code format}. // * // * @param calendar // * @param format // * @return // * @see {@link SimpleDateFormat} // * @since 0.9.1.1 // */ // public static String toString(Calendar calendar, String format) { // return toString(calendar.getTime(), format); // } // // /** // * Parse a string to {@link Date}, based on the specified {@code format}. // * // * @param source // * @param format // * @return // */ // public static Date fromString(String source, String format) { // try { // ObjectPool<DateFormat> pool = cachedDateFormat.get(format); // try { // DateFormat df = pool.borrowObject(); // try { // return df.parse(source); // } finally { // pool.returnObject(df); // } // } catch (Exception e) { // throw e instanceof RuntimeException ? (RuntimeException) e // : new RuntimeException(e); // } // } catch (ExecutionException e) { // throw new RuntimeException(e); // } // } // } // Path: ddth-commons-core/src/test/java/com/github/ddth/commons/test/utils/DateFormatUtilsTest.java import java.util.Calendar; import com.github.ddth.commons.utils.DateFormatUtils; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; public static Test suite() { return new TestSuite(DateFormatUtilsTest.class); } private static int[] FIELDS = { Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND }; private static int[] FIELD_VALUES = { 2018, Calendar.MARCH, 01, 04, 29, 01, 981 }; private static String[] FORMATS = { "yyyy", "MM", "dd", "HH", "mm", "ss", "SSS" }; private static String[] DELIMS = { " ", ":", "-", "_", "/", ".", ";" }; private static Calendar testData() { final Calendar cal = Calendar.getInstance(); for (int i = 0; i < FIELDS.length; i++) { cal.set(FIELDS[i], FIELD_VALUES[i]); } return cal; } private static String normValue(int i, int index) { if (index == 1) { i++; } return i < 10 ? "0" + String.valueOf(i) : String.valueOf(i); } @org.junit.Test public void testToStringDate1() { final Calendar cal = testData(); for (int i = 0; i < FORMATS.length; i++) { String format = FORMATS[i];
String actual = DateFormatUtils.toString(cal.getTime(), format);
DDTH/ddth-commons
ddth-commons-core/src/test/java/com/github/ddth/commons/test/serialization/KryoSerDeserTest.java
// Path: ddth-commons-core/src/main/java/com/github/ddth/commons/serialization/KryoSerDeser.java // public class KryoSerDeser implements ISerDeser { // /** // * {@inheritDoc} // */ // @Override // public byte[] toBytes(Object obj) throws SerializationException { // return toBytes(obj, null); // } // // /** // * {@inheritDoc} // */ // @Override // public byte[] toBytes(Object obj, ClassLoader classLoader) throws SerializationException { // return SerializationUtils.toByteArrayKryo(obj, classLoader); // } // // /** // * {@inheritDoc} // */ // @Override // public <T> T fromBytes(byte[] data, Class<T> clazz) throws DeserializationException { // return fromBytes(data, clazz, null); // } // // /** // * {@inheritDoc} // */ // @Override // public <T> T fromBytes(byte[] data, Class<T> clazz, ClassLoader classLoader) // throws DeserializationException { // return SerializationUtils.fromByteArrayKryo(data, clazz, classLoader); // } // }
import com.github.ddth.commons.serialization.KryoSerDeser; import junit.framework.Test; import junit.framework.TestSuite;
package com.github.ddth.commons.test.serialization; /* * mvn test -DskipTests=false -Dtest=com.github.ddth.commons.test.serialization.KryoSerDeserTest */ public class KryoSerDeserTest extends BaseSerDeserTest { public KryoSerDeserTest(String testName) { super(testName); } public static Test suite() { return new TestSuite(KryoSerDeserTest.class); } @org.junit.Test public void testKryo() {
// Path: ddth-commons-core/src/main/java/com/github/ddth/commons/serialization/KryoSerDeser.java // public class KryoSerDeser implements ISerDeser { // /** // * {@inheritDoc} // */ // @Override // public byte[] toBytes(Object obj) throws SerializationException { // return toBytes(obj, null); // } // // /** // * {@inheritDoc} // */ // @Override // public byte[] toBytes(Object obj, ClassLoader classLoader) throws SerializationException { // return SerializationUtils.toByteArrayKryo(obj, classLoader); // } // // /** // * {@inheritDoc} // */ // @Override // public <T> T fromBytes(byte[] data, Class<T> clazz) throws DeserializationException { // return fromBytes(data, clazz, null); // } // // /** // * {@inheritDoc} // */ // @Override // public <T> T fromBytes(byte[] data, Class<T> clazz, ClassLoader classLoader) // throws DeserializationException { // return SerializationUtils.fromByteArrayKryo(data, clazz, classLoader); // } // } // Path: ddth-commons-core/src/test/java/com/github/ddth/commons/test/serialization/KryoSerDeserTest.java import com.github.ddth.commons.serialization.KryoSerDeser; import junit.framework.Test; import junit.framework.TestSuite; package com.github.ddth.commons.test.serialization; /* * mvn test -DskipTests=false -Dtest=com.github.ddth.commons.test.serialization.KryoSerDeserTest */ public class KryoSerDeserTest extends BaseSerDeserTest { public KryoSerDeserTest(String testName) { super(testName); } public static Test suite() { return new TestSuite(KryoSerDeserTest.class); } @org.junit.Test public void testKryo() {
doTest(new KryoSerDeser());
DDTH/ddth-commons
ddth-commons-core/src/test/java/com/github/ddth/commons/test/utils/ReflectionUtilsTest1.java
// Path: ddth-commons-core/src/main/java/com/github/ddth/commons/utils/ReflectionUtils.java // public class ReflectionUtils { // /** // * Get a class' constructor. Return {@code null} if no such constructor found. // * // * <p> // * This method can get private and protected constructors. // * </p> // * // * @param clazz // * @param parameterTypes // * @return // * @since 0.9.1.4 // */ // public static <T> Constructor<T> getConstructor(Class<T> clazz, Class<?>... parameterTypes) { // try { // return clazz != null ? clazz.getDeclaredConstructor(parameterTypes) : null; // } catch (NoSuchMethodException e) { // return null; // } // } // // /** // * Get a class' method by name. Return {@code null} if no such method found. // * // * @param methodName // * @param clazz // * @param parameterTypes // * @return // * @since 0.9.1.5 // */ // private static Method getDeclaredMethod(String methodName, Class<?> clazz, // Class<?>... parameterTypes) { // try { // return clazz != null ? clazz.getDeclaredMethod(methodName, parameterTypes) : null; // } catch (NoSuchMethodException e) { // return null; // } // } // // /** // * Get a class' method by name. Return {@code null} if no such method found. // * // * <p> // * This method can get private and protected methods. // * </p> // * // * <p> // * This method can get methods from super classes/interfaces. // * </p> // * // * @param methodName // * @param clazz // * @param parameterTypes // * @return // * @since 0.9.1.4 // */ // public static Method getMethod(String methodName, Class<?> clazz, Class<?>... parameterTypes) { // if (clazz == null) { // return null; // } // Method m = getDeclaredMethod(methodName, clazz, parameterTypes); // if (m == null) { // List<Class<?>> interfacesAndSuperClasses = new LinkedList<>(); // interfacesAndSuperClasses.add(clazz.getSuperclass()); // for (Class<?> cl : clazz.getInterfaces()) { // interfacesAndSuperClasses.add(cl); // } // for (Class<?> cl : interfacesAndSuperClasses) { // m = getMethod(methodName, cl, parameterTypes); // if (m != null) { // return m; // } // } // return null; // } else { // return m; // } // } // // /** // * Tells if a class is a sub-class of a super-class. // * // * Note: // * <ul> // * <li>Sub-class against super-class: this method returns {@code true}.</li> // * <li>Sub-interface against super-interface: this method returns // * {@code true}.</li> // * <li>Class against interface: this method returns {@code false}.</li> // * </ul> // * // * @param clazz // * class to check // * @param superClazz // * the super-class to check // * @return {@code true} if {@code superClazz} is indeed the super-class of // * {@code clazz} // */ // public static boolean hasSuperClass(Class<?> clazz, Class<?> superClazz) { // if (clazz == null || superClazz == null || clazz == superClazz) { // return false; // } // // if (clazz.isInterface()) { // return superClazz.isAssignableFrom(clazz); // } // // Class<?> parent = clazz.getSuperclass(); // while (parent != null) { // if (parent == superClazz) { // return true; // } // parent = parent.getSuperclass(); // } // return false; // } // // /** // * Tells if a class (or one of its super-classes) implements an interface; // * or an interface is a sub-interface of a super-interface. // * // * Note: // * <ul> // * <li>Sub-interface against super-interface: this method returns // * {@code true}.</li> // * <li>Class against interface: this method returns {@code true}.</li> // * <li>Class against super-interface: this method returns {@code true}.</li> // * </ul> // * // * @param clazz // * @param iface // * @return // */ // public static boolean hasInterface(Class<?> clazz, Class<?> iface) { // if (clazz == null || iface == null || clazz == iface) { // return false; // } // return iface.isInterface() && iface.isAssignableFrom(clazz); // } // }
import org.junit.After; import org.junit.Assert; import org.junit.Before; import com.github.ddth.commons.utils.ReflectionUtils; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite;
package com.github.ddth.commons.test.utils; /** * Test {@link ReflectionUtils#hasInterface(Class, Class)} and * {@link ReflectionUtils#hasSuperClass(Class, Class)}. */ public class ReflectionUtilsTest1 extends TestCase { public ReflectionUtilsTest1(String testName) { super(testName); } public static Test suite() { return new TestSuite(ReflectionUtilsTest1.class); } @Before public void setUp() { } @After public void tearDown() { } @org.junit.Test public void testHasSuperClassSomeClass() {
// Path: ddth-commons-core/src/main/java/com/github/ddth/commons/utils/ReflectionUtils.java // public class ReflectionUtils { // /** // * Get a class' constructor. Return {@code null} if no such constructor found. // * // * <p> // * This method can get private and protected constructors. // * </p> // * // * @param clazz // * @param parameterTypes // * @return // * @since 0.9.1.4 // */ // public static <T> Constructor<T> getConstructor(Class<T> clazz, Class<?>... parameterTypes) { // try { // return clazz != null ? clazz.getDeclaredConstructor(parameterTypes) : null; // } catch (NoSuchMethodException e) { // return null; // } // } // // /** // * Get a class' method by name. Return {@code null} if no such method found. // * // * @param methodName // * @param clazz // * @param parameterTypes // * @return // * @since 0.9.1.5 // */ // private static Method getDeclaredMethod(String methodName, Class<?> clazz, // Class<?>... parameterTypes) { // try { // return clazz != null ? clazz.getDeclaredMethod(methodName, parameterTypes) : null; // } catch (NoSuchMethodException e) { // return null; // } // } // // /** // * Get a class' method by name. Return {@code null} if no such method found. // * // * <p> // * This method can get private and protected methods. // * </p> // * // * <p> // * This method can get methods from super classes/interfaces. // * </p> // * // * @param methodName // * @param clazz // * @param parameterTypes // * @return // * @since 0.9.1.4 // */ // public static Method getMethod(String methodName, Class<?> clazz, Class<?>... parameterTypes) { // if (clazz == null) { // return null; // } // Method m = getDeclaredMethod(methodName, clazz, parameterTypes); // if (m == null) { // List<Class<?>> interfacesAndSuperClasses = new LinkedList<>(); // interfacesAndSuperClasses.add(clazz.getSuperclass()); // for (Class<?> cl : clazz.getInterfaces()) { // interfacesAndSuperClasses.add(cl); // } // for (Class<?> cl : interfacesAndSuperClasses) { // m = getMethod(methodName, cl, parameterTypes); // if (m != null) { // return m; // } // } // return null; // } else { // return m; // } // } // // /** // * Tells if a class is a sub-class of a super-class. // * // * Note: // * <ul> // * <li>Sub-class against super-class: this method returns {@code true}.</li> // * <li>Sub-interface against super-interface: this method returns // * {@code true}.</li> // * <li>Class against interface: this method returns {@code false}.</li> // * </ul> // * // * @param clazz // * class to check // * @param superClazz // * the super-class to check // * @return {@code true} if {@code superClazz} is indeed the super-class of // * {@code clazz} // */ // public static boolean hasSuperClass(Class<?> clazz, Class<?> superClazz) { // if (clazz == null || superClazz == null || clazz == superClazz) { // return false; // } // // if (clazz.isInterface()) { // return superClazz.isAssignableFrom(clazz); // } // // Class<?> parent = clazz.getSuperclass(); // while (parent != null) { // if (parent == superClazz) { // return true; // } // parent = parent.getSuperclass(); // } // return false; // } // // /** // * Tells if a class (or one of its super-classes) implements an interface; // * or an interface is a sub-interface of a super-interface. // * // * Note: // * <ul> // * <li>Sub-interface against super-interface: this method returns // * {@code true}.</li> // * <li>Class against interface: this method returns {@code true}.</li> // * <li>Class against super-interface: this method returns {@code true}.</li> // * </ul> // * // * @param clazz // * @param iface // * @return // */ // public static boolean hasInterface(Class<?> clazz, Class<?> iface) { // if (clazz == null || iface == null || clazz == iface) { // return false; // } // return iface.isInterface() && iface.isAssignableFrom(clazz); // } // } // Path: ddth-commons-core/src/test/java/com/github/ddth/commons/test/utils/ReflectionUtilsTest1.java import org.junit.After; import org.junit.Assert; import org.junit.Before; import com.github.ddth.commons.utils.ReflectionUtils; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; package com.github.ddth.commons.test.utils; /** * Test {@link ReflectionUtils#hasInterface(Class, Class)} and * {@link ReflectionUtils#hasSuperClass(Class, Class)}. */ public class ReflectionUtilsTest1 extends TestCase { public ReflectionUtilsTest1(String testName) { super(testName); } public static Test suite() { return new TestSuite(ReflectionUtilsTest1.class); } @Before public void setUp() { } @After public void tearDown() { } @org.junit.Test public void testHasSuperClassSomeClass() {
assertFalse(ReflectionUtils.hasSuperClass(SomeClass.class, SuperClass.class));
DDTH/ddth-commons
ddth-commons-core/src/test/java/com/github/ddth/commons/test/utils/Ipv4UtilsTest.java
// Path: ddth-commons-core/src/main/java/com/github/ddth/commons/utils/Ipv4Utils.java // public class Ipv4Utils { // private final static Pattern IP_PATTERN_FULL = Pattern // .compile("^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$"); // // /** // * Check is an IP is valid. // * // * @param ip // * @return // * @since 0.9.1.1 // */ // public static boolean isValidIp(String ip) { // if (!IP_PATTERN_FULL.matcher(ip).matches()) { // return false; // } // String[] ipArr = ip.split("\\."); // for (String part : ipArr) { // int v = Integer.parseInt(part); // if (v < 0 || v > 255) { // return false; // } // } // return true; // } // // /** // * IP address to long (e.g. 10.0.0.1 -> 167772161). // * // * @param ip // * @return // */ // public static long ipToLong(String ip) { // if (!isValidIp(ip)) { // throw new IllegalArgumentException("Invalid IP address: " + ip); // } // // long result = 0; // String[] ipArr = ip.split("\\."); // for (int i = 3; i >= 0; i--) { // long part = Long.parseLong(ipArr[3 - i]); // result |= part << (i * 8); // } // return result; // } // // /** // * Long to IP address (e.g. 167772161 -> 10.0.0.1) // * // * @param ip // * @return // */ // public static String longToIp(long ip) { // return ((ip >> 24) & 0xFF) + "." + ((ip >> 16) & 0xFF) + "." + ((ip >> 8) & 0xFF) + "." // + (ip & 0xFF); // } // // private final static Pattern IP_PATTERN_PARTIAL = Pattern // .compile("^(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\.\\*?$"); // // private final static Pattern IP_PATTERN_RANGE = Pattern // .compile("^(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\.(\\d{1,3})\\-(\\d{1,3})$"); // // private final static Pattern IP_PATTERN_SUBNET = Pattern // .compile("^(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\/(\\d{1,3})$"); // // /** // * Checks if an IP (e.g. 10.0.0.5) matches a subnet (e.g. 10.0.0.0/24). // * // * @param ip // * in format {@code x.x.x.x} // * @param subnet // * in format {@code x.x.x.x} or {@code x.x.x.x/y} or // * {@code x.x.x.x-y} or {@code x.x.x.*} (alias of // * {@code x.x.x.x/24}) or {@code x.x.x.} (another alias of // * {@code x.x.x.x/24}) // * @return // */ // public static boolean isBelongToSubnet(String ip, String subnet) { // if (subnet == null || ip == null) { // throw new NullPointerException("IP or Subnet is null!"); // } // if (!IP_PATTERN_FULL.matcher(ip).matches()) { // throw new IllegalArgumentException("Invalid IP address: " + ip); // } // // if (IP_PATTERN_FULL.matcher(subnet).matches()) { // return StringUtils.equals(ip, subnet); // } // // long ipAsLong = ipToLong(ip); // Matcher matcherRange = IP_PATTERN_RANGE.matcher(subnet); // if (matcherRange.matches()) { // long ipAsLongStart = ipToLong(matcherRange.group(1) + "." + matcherRange.group(2)); // long ipAsLongEnd = ipToLong(matcherRange.group(1) + "." + matcherRange.group(3)); // return ipAsLongStart <= ipAsLong && ipAsLong <= ipAsLongEnd; // } // // Matcher matcherPartial = IP_PATTERN_PARTIAL.matcher(subnet); // if (matcherPartial.matches()) { // subnet = matcherPartial.group(1) + ".0/24"; // } // Matcher matcherSubnet = IP_PATTERN_SUBNET.matcher(subnet); // if (matcherSubnet.matches()) { // int mask = Integer.parseInt(matcherSubnet.group(2)); // if (mask > 32) { // throw new IllegalArgumentException("Invalid subnet: " + subnet); // } // // String maskAsBinary = StringUtils.repeat('1', mask) // + StringUtils.repeat('0', 32 - mask); // long maskAsLong = Long.parseLong(maskAsBinary, 2); // // String ipBase = matcherSubnet.group(1); // long ipBaseAsLong = ipToLong(ipBase); // ipBaseAsLong &= maskAsLong; // // return ipBaseAsLong == (ipAsLong & maskAsLong); // } // // throw new IllegalArgumentException("Invalid subnet: " + subnet); // } // }
import com.github.ddth.commons.utils.Ipv4Utils; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite;
package com.github.ddth.commons.test.utils; public class Ipv4UtilsTest extends TestCase { public Ipv4UtilsTest(String testName) { super(testName); } public static Test suite() { return new TestSuite(Ipv4UtilsTest.class); } @org.junit.Test public void testIsValidIp() {
// Path: ddth-commons-core/src/main/java/com/github/ddth/commons/utils/Ipv4Utils.java // public class Ipv4Utils { // private final static Pattern IP_PATTERN_FULL = Pattern // .compile("^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$"); // // /** // * Check is an IP is valid. // * // * @param ip // * @return // * @since 0.9.1.1 // */ // public static boolean isValidIp(String ip) { // if (!IP_PATTERN_FULL.matcher(ip).matches()) { // return false; // } // String[] ipArr = ip.split("\\."); // for (String part : ipArr) { // int v = Integer.parseInt(part); // if (v < 0 || v > 255) { // return false; // } // } // return true; // } // // /** // * IP address to long (e.g. 10.0.0.1 -> 167772161). // * // * @param ip // * @return // */ // public static long ipToLong(String ip) { // if (!isValidIp(ip)) { // throw new IllegalArgumentException("Invalid IP address: " + ip); // } // // long result = 0; // String[] ipArr = ip.split("\\."); // for (int i = 3; i >= 0; i--) { // long part = Long.parseLong(ipArr[3 - i]); // result |= part << (i * 8); // } // return result; // } // // /** // * Long to IP address (e.g. 167772161 -> 10.0.0.1) // * // * @param ip // * @return // */ // public static String longToIp(long ip) { // return ((ip >> 24) & 0xFF) + "." + ((ip >> 16) & 0xFF) + "." + ((ip >> 8) & 0xFF) + "." // + (ip & 0xFF); // } // // private final static Pattern IP_PATTERN_PARTIAL = Pattern // .compile("^(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\.\\*?$"); // // private final static Pattern IP_PATTERN_RANGE = Pattern // .compile("^(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\.(\\d{1,3})\\-(\\d{1,3})$"); // // private final static Pattern IP_PATTERN_SUBNET = Pattern // .compile("^(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\/(\\d{1,3})$"); // // /** // * Checks if an IP (e.g. 10.0.0.5) matches a subnet (e.g. 10.0.0.0/24). // * // * @param ip // * in format {@code x.x.x.x} // * @param subnet // * in format {@code x.x.x.x} or {@code x.x.x.x/y} or // * {@code x.x.x.x-y} or {@code x.x.x.*} (alias of // * {@code x.x.x.x/24}) or {@code x.x.x.} (another alias of // * {@code x.x.x.x/24}) // * @return // */ // public static boolean isBelongToSubnet(String ip, String subnet) { // if (subnet == null || ip == null) { // throw new NullPointerException("IP or Subnet is null!"); // } // if (!IP_PATTERN_FULL.matcher(ip).matches()) { // throw new IllegalArgumentException("Invalid IP address: " + ip); // } // // if (IP_PATTERN_FULL.matcher(subnet).matches()) { // return StringUtils.equals(ip, subnet); // } // // long ipAsLong = ipToLong(ip); // Matcher matcherRange = IP_PATTERN_RANGE.matcher(subnet); // if (matcherRange.matches()) { // long ipAsLongStart = ipToLong(matcherRange.group(1) + "." + matcherRange.group(2)); // long ipAsLongEnd = ipToLong(matcherRange.group(1) + "." + matcherRange.group(3)); // return ipAsLongStart <= ipAsLong && ipAsLong <= ipAsLongEnd; // } // // Matcher matcherPartial = IP_PATTERN_PARTIAL.matcher(subnet); // if (matcherPartial.matches()) { // subnet = matcherPartial.group(1) + ".0/24"; // } // Matcher matcherSubnet = IP_PATTERN_SUBNET.matcher(subnet); // if (matcherSubnet.matches()) { // int mask = Integer.parseInt(matcherSubnet.group(2)); // if (mask > 32) { // throw new IllegalArgumentException("Invalid subnet: " + subnet); // } // // String maskAsBinary = StringUtils.repeat('1', mask) // + StringUtils.repeat('0', 32 - mask); // long maskAsLong = Long.parseLong(maskAsBinary, 2); // // String ipBase = matcherSubnet.group(1); // long ipBaseAsLong = ipToLong(ipBase); // ipBaseAsLong &= maskAsLong; // // return ipBaseAsLong == (ipAsLong & maskAsLong); // } // // throw new IllegalArgumentException("Invalid subnet: " + subnet); // } // } // Path: ddth-commons-core/src/test/java/com/github/ddth/commons/test/utils/Ipv4UtilsTest.java import com.github.ddth.commons.utils.Ipv4Utils; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; package com.github.ddth.commons.test.utils; public class Ipv4UtilsTest extends TestCase { public Ipv4UtilsTest(String testName) { super(testName); } public static Test suite() { return new TestSuite(Ipv4UtilsTest.class); } @org.junit.Test public void testIsValidIp() {
assertTrue(Ipv4Utils.isValidIp("192.168.0.1"));
DDTH/ddth-commons
ddth-commons-core/src/test/java/com/github/ddth/commons/test/serialization/JsonSerDeserTest.java
// Path: ddth-commons-core/src/main/java/com/github/ddth/commons/serialization/JsonSerDeser.java // public class JsonSerDeser implements ISerDeser { // /** // * {@inheritDoc} // */ // @Override // public byte[] toBytes(Object obj) throws SerializationException { // return toBytes(obj, null); // } // // /** // * {@inheritDoc} // */ // @Override // public byte[] toBytes(Object obj, ClassLoader classLoader) throws SerializationException { // String json = SerializationUtils.toJsonString(obj, classLoader); // return json != null ? json.getBytes(StandardCharsets.UTF_8) : null; // } // // /** // * {@inheritDoc} // */ // @Override // public <T> T fromBytes(byte[] data, Class<T> clazz) throws DeserializationException { // return fromBytes(data, clazz, null); // } // // /** // * {@inheritDoc} // */ // @Override // public <T> T fromBytes(byte[] data, Class<T> clazz, ClassLoader classLoader) // throws DeserializationException { // String json = data != null ? new String(data, StandardCharsets.UTF_8) : null; // return SerializationUtils.fromJsonString(json, clazz, classLoader); // } // }
import com.github.ddth.commons.serialization.JsonSerDeser; import junit.framework.Test; import junit.framework.TestSuite;
package com.github.ddth.commons.test.serialization; /* * mvn test -DskipTests=false -Dtest=com.github.ddth.commons.test.serialization.JsonSerDeserTest */ public class JsonSerDeserTest extends BaseSerDeserTest { public JsonSerDeserTest(String testName) { super(testName); } public static Test suite() { return new TestSuite(JsonSerDeserTest.class); } @org.junit.Test public void testJson() {
// Path: ddth-commons-core/src/main/java/com/github/ddth/commons/serialization/JsonSerDeser.java // public class JsonSerDeser implements ISerDeser { // /** // * {@inheritDoc} // */ // @Override // public byte[] toBytes(Object obj) throws SerializationException { // return toBytes(obj, null); // } // // /** // * {@inheritDoc} // */ // @Override // public byte[] toBytes(Object obj, ClassLoader classLoader) throws SerializationException { // String json = SerializationUtils.toJsonString(obj, classLoader); // return json != null ? json.getBytes(StandardCharsets.UTF_8) : null; // } // // /** // * {@inheritDoc} // */ // @Override // public <T> T fromBytes(byte[] data, Class<T> clazz) throws DeserializationException { // return fromBytes(data, clazz, null); // } // // /** // * {@inheritDoc} // */ // @Override // public <T> T fromBytes(byte[] data, Class<T> clazz, ClassLoader classLoader) // throws DeserializationException { // String json = data != null ? new String(data, StandardCharsets.UTF_8) : null; // return SerializationUtils.fromJsonString(json, clazz, classLoader); // } // } // Path: ddth-commons-core/src/test/java/com/github/ddth/commons/test/serialization/JsonSerDeserTest.java import com.github.ddth.commons.serialization.JsonSerDeser; import junit.framework.Test; import junit.framework.TestSuite; package com.github.ddth.commons.test.serialization; /* * mvn test -DskipTests=false -Dtest=com.github.ddth.commons.test.serialization.JsonSerDeserTest */ public class JsonSerDeserTest extends BaseSerDeserTest { public JsonSerDeserTest(String testName) { super(testName); } public static Test suite() { return new TestSuite(JsonSerDeserTest.class); } @org.junit.Test public void testJson() {
doTest(new JsonSerDeser());
DDTH/ddth-commons
ddth-commons-core/src/test/java/com/github/ddth/commons/qnd/utils/QndReflectionUtils.java
// Path: ddth-commons-core/src/main/java/com/github/ddth/commons/utils/ReflectionUtils.java // public class ReflectionUtils { // /** // * Get a class' constructor. Return {@code null} if no such constructor found. // * // * <p> // * This method can get private and protected constructors. // * </p> // * // * @param clazz // * @param parameterTypes // * @return // * @since 0.9.1.4 // */ // public static <T> Constructor<T> getConstructor(Class<T> clazz, Class<?>... parameterTypes) { // try { // return clazz != null ? clazz.getDeclaredConstructor(parameterTypes) : null; // } catch (NoSuchMethodException e) { // return null; // } // } // // /** // * Get a class' method by name. Return {@code null} if no such method found. // * // * @param methodName // * @param clazz // * @param parameterTypes // * @return // * @since 0.9.1.5 // */ // private static Method getDeclaredMethod(String methodName, Class<?> clazz, // Class<?>... parameterTypes) { // try { // return clazz != null ? clazz.getDeclaredMethod(methodName, parameterTypes) : null; // } catch (NoSuchMethodException e) { // return null; // } // } // // /** // * Get a class' method by name. Return {@code null} if no such method found. // * // * <p> // * This method can get private and protected methods. // * </p> // * // * <p> // * This method can get methods from super classes/interfaces. // * </p> // * // * @param methodName // * @param clazz // * @param parameterTypes // * @return // * @since 0.9.1.4 // */ // public static Method getMethod(String methodName, Class<?> clazz, Class<?>... parameterTypes) { // if (clazz == null) { // return null; // } // Method m = getDeclaredMethod(methodName, clazz, parameterTypes); // if (m == null) { // List<Class<?>> interfacesAndSuperClasses = new LinkedList<>(); // interfacesAndSuperClasses.add(clazz.getSuperclass()); // for (Class<?> cl : clazz.getInterfaces()) { // interfacesAndSuperClasses.add(cl); // } // for (Class<?> cl : interfacesAndSuperClasses) { // m = getMethod(methodName, cl, parameterTypes); // if (m != null) { // return m; // } // } // return null; // } else { // return m; // } // } // // /** // * Tells if a class is a sub-class of a super-class. // * // * Note: // * <ul> // * <li>Sub-class against super-class: this method returns {@code true}.</li> // * <li>Sub-interface against super-interface: this method returns // * {@code true}.</li> // * <li>Class against interface: this method returns {@code false}.</li> // * </ul> // * // * @param clazz // * class to check // * @param superClazz // * the super-class to check // * @return {@code true} if {@code superClazz} is indeed the super-class of // * {@code clazz} // */ // public static boolean hasSuperClass(Class<?> clazz, Class<?> superClazz) { // if (clazz == null || superClazz == null || clazz == superClazz) { // return false; // } // // if (clazz.isInterface()) { // return superClazz.isAssignableFrom(clazz); // } // // Class<?> parent = clazz.getSuperclass(); // while (parent != null) { // if (parent == superClazz) { // return true; // } // parent = parent.getSuperclass(); // } // return false; // } // // /** // * Tells if a class (or one of its super-classes) implements an interface; // * or an interface is a sub-interface of a super-interface. // * // * Note: // * <ul> // * <li>Sub-interface against super-interface: this method returns // * {@code true}.</li> // * <li>Class against interface: this method returns {@code true}.</li> // * <li>Class against super-interface: this method returns {@code true}.</li> // * </ul> // * // * @param clazz // * @param iface // * @return // */ // public static boolean hasInterface(Class<?> clazz, Class<?> iface) { // if (clazz == null || iface == null || clazz == iface) { // return false; // } // return iface.isInterface() && iface.isAssignableFrom(clazz); // } // }
import com.github.ddth.commons.utils.ReflectionUtils;
public static abstract class ParentClass implements ChildInterface { public ParentClass(String param) { } public void method1(String param) { } protected void method2(String param) { } @SuppressWarnings("unused") private void method3(long param) { } public abstract void method4(Object param); } public static abstract class ChildClass extends ParentClass { public ChildClass() { super("child"); } public void method5(String param) { } protected abstract void method6(); } public static void main(String[] args) { System.out.println("Parent, constructor with args : "
// Path: ddth-commons-core/src/main/java/com/github/ddth/commons/utils/ReflectionUtils.java // public class ReflectionUtils { // /** // * Get a class' constructor. Return {@code null} if no such constructor found. // * // * <p> // * This method can get private and protected constructors. // * </p> // * // * @param clazz // * @param parameterTypes // * @return // * @since 0.9.1.4 // */ // public static <T> Constructor<T> getConstructor(Class<T> clazz, Class<?>... parameterTypes) { // try { // return clazz != null ? clazz.getDeclaredConstructor(parameterTypes) : null; // } catch (NoSuchMethodException e) { // return null; // } // } // // /** // * Get a class' method by name. Return {@code null} if no such method found. // * // * @param methodName // * @param clazz // * @param parameterTypes // * @return // * @since 0.9.1.5 // */ // private static Method getDeclaredMethod(String methodName, Class<?> clazz, // Class<?>... parameterTypes) { // try { // return clazz != null ? clazz.getDeclaredMethod(methodName, parameterTypes) : null; // } catch (NoSuchMethodException e) { // return null; // } // } // // /** // * Get a class' method by name. Return {@code null} if no such method found. // * // * <p> // * This method can get private and protected methods. // * </p> // * // * <p> // * This method can get methods from super classes/interfaces. // * </p> // * // * @param methodName // * @param clazz // * @param parameterTypes // * @return // * @since 0.9.1.4 // */ // public static Method getMethod(String methodName, Class<?> clazz, Class<?>... parameterTypes) { // if (clazz == null) { // return null; // } // Method m = getDeclaredMethod(methodName, clazz, parameterTypes); // if (m == null) { // List<Class<?>> interfacesAndSuperClasses = new LinkedList<>(); // interfacesAndSuperClasses.add(clazz.getSuperclass()); // for (Class<?> cl : clazz.getInterfaces()) { // interfacesAndSuperClasses.add(cl); // } // for (Class<?> cl : interfacesAndSuperClasses) { // m = getMethod(methodName, cl, parameterTypes); // if (m != null) { // return m; // } // } // return null; // } else { // return m; // } // } // // /** // * Tells if a class is a sub-class of a super-class. // * // * Note: // * <ul> // * <li>Sub-class against super-class: this method returns {@code true}.</li> // * <li>Sub-interface against super-interface: this method returns // * {@code true}.</li> // * <li>Class against interface: this method returns {@code false}.</li> // * </ul> // * // * @param clazz // * class to check // * @param superClazz // * the super-class to check // * @return {@code true} if {@code superClazz} is indeed the super-class of // * {@code clazz} // */ // public static boolean hasSuperClass(Class<?> clazz, Class<?> superClazz) { // if (clazz == null || superClazz == null || clazz == superClazz) { // return false; // } // // if (clazz.isInterface()) { // return superClazz.isAssignableFrom(clazz); // } // // Class<?> parent = clazz.getSuperclass(); // while (parent != null) { // if (parent == superClazz) { // return true; // } // parent = parent.getSuperclass(); // } // return false; // } // // /** // * Tells if a class (or one of its super-classes) implements an interface; // * or an interface is a sub-interface of a super-interface. // * // * Note: // * <ul> // * <li>Sub-interface against super-interface: this method returns // * {@code true}.</li> // * <li>Class against interface: this method returns {@code true}.</li> // * <li>Class against super-interface: this method returns {@code true}.</li> // * </ul> // * // * @param clazz // * @param iface // * @return // */ // public static boolean hasInterface(Class<?> clazz, Class<?> iface) { // if (clazz == null || iface == null || clazz == iface) { // return false; // } // return iface.isInterface() && iface.isAssignableFrom(clazz); // } // } // Path: ddth-commons-core/src/test/java/com/github/ddth/commons/qnd/utils/QndReflectionUtils.java import com.github.ddth.commons.utils.ReflectionUtils; public static abstract class ParentClass implements ChildInterface { public ParentClass(String param) { } public void method1(String param) { } protected void method2(String param) { } @SuppressWarnings("unused") private void method3(long param) { } public abstract void method4(Object param); } public static abstract class ChildClass extends ParentClass { public ChildClass() { super("child"); } public void method5(String param) { } protected abstract void method6(); } public static void main(String[] args) { System.out.println("Parent, constructor with args : "
+ ReflectionUtils.getConstructor(ParentClass.class, String.class));
yyon/grapplemod
main/java/com/yyon/grapplinghook/ServerProxyClass.java
// Path: main/java/com/yyon/grapplinghook/network/LoggedInMessage.java // public class LoggedInMessage implements IMessage { // GrappleConfig.Config conf = null; // // public LoggedInMessage() { } // // public LoggedInMessage(GrappleConfig.Config serverconf) { // this.conf = serverconf; // } // // @Override // public void fromBytes(ByteBuf buf) { // Class<GrappleConfig.Config> confclass = GrappleConfig.Config.class; // Field[] fields = confclass.getDeclaredFields(); // Arrays.sort(fields, new Comparator<Field>() { // @Override // public int compare(Field o1, Field o2) { // return o1.getName().compareTo(o2.getName()); // } // }); // // this.conf = new GrappleConfig.Config(); // // for (Field field : fields) { // Type fieldtype = field.getGenericType(); // try { // if (fieldtype.getTypeName().equals("int")) { // field.setInt(this.conf, buf.readInt()); // } else if (fieldtype.getTypeName().equals("double")) { // field.setDouble(this.conf, buf.readDouble()); // } else if (fieldtype.getTypeName().equals("boolean")) { // field.setBoolean(this.conf, buf.readBoolean()); // } else if (fieldtype.getTypeName().equals("java.lang.String")) { // int len = buf.readInt(); // CharSequence charseq = buf.readCharSequence(len, Charset.defaultCharset()); // field.set(this.conf, charseq.toString()); // } else { // System.out.println("Unknown Type"); // System.out.println(fieldtype.getTypeName()); // } // } catch (IllegalAccessException e) { // System.out.println(e); // } // } // } // // @Override // public void toBytes(ByteBuf buf) { // Class<GrappleConfig.Config> confclass = GrappleConfig.Config.class; // Field[] fields = confclass.getDeclaredFields(); // Arrays.sort(fields, new Comparator<Field>() { // @Override // public int compare(Field o1, Field o2) { // return o1.getName().compareTo(o2.getName()); // } // }); // // for (Field field : fields) { // Type fieldtype = field.getGenericType(); // try { // if (fieldtype.getTypeName().equals("int")) { // buf.writeInt(field.getInt(this.conf)); // } else if (fieldtype.getTypeName().equals("double")) { // buf.writeDouble(field.getDouble(this.conf)); // } else if (fieldtype.getTypeName().equals("boolean")) { // buf.writeBoolean(field.getBoolean(this.conf)); // } else if (fieldtype.getTypeName().equals("java.lang.String")) { // String str = (String) field.get(this.conf); // buf.writeInt(str.length()); // buf.writeCharSequence(str.subSequence(0, str.length()), Charset.defaultCharset()); // } else { // System.out.println("Unknown Type"); // System.out.println(fieldtype.getTypeName()); // } // } catch (IllegalAccessException e) { // System.out.println(e); // } // } // } // // public static class Handler implements IMessageHandler<LoggedInMessage, IMessage> { // public class runner implements Runnable { // LoggedInMessage message; // MessageContext ctx; // public runner(LoggedInMessage message, MessageContext ctx) { // super(); // this.message = message; // this.ctx = ctx; // } // // @Override // public void run() { // GrappleConfig.setserveroptions(this.message.conf); // } // } // // // @Override // public IMessage onMessage(LoggedInMessage message, MessageContext ctx) { // // IThreadListener mainThread = Minecraft.getMinecraft(); // mainThread.addScheduledTask(new runner(message, ctx)); // // return null; // } // } // }
import com.yyon.grapplinghook.network.LoggedInMessage; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraftforge.event.entity.living.LivingDeathEvent; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent;
package com.yyon.grapplinghook; public class ServerProxyClass extends CommonProxyClass { @Override public void preInit(FMLPreInitializationEvent event) { super.preInit(event); } @Override public void init(FMLInitializationEvent event, grapplemod grapplemod) { super.init(event, grapplemod); } @Override public void postInit(FMLPostInitializationEvent event) { super.postInit(event); if (GrappleConfig.getconf().override_allowflight) { FMLCommonHandler.instance().getMinecraftServerInstance().setAllowFlight(true); } } @SubscribeEvent public void onPlayerLoggedInEvent(PlayerLoggedInEvent e) { if (e.player instanceof EntityPlayerMP) {
// Path: main/java/com/yyon/grapplinghook/network/LoggedInMessage.java // public class LoggedInMessage implements IMessage { // GrappleConfig.Config conf = null; // // public LoggedInMessage() { } // // public LoggedInMessage(GrappleConfig.Config serverconf) { // this.conf = serverconf; // } // // @Override // public void fromBytes(ByteBuf buf) { // Class<GrappleConfig.Config> confclass = GrappleConfig.Config.class; // Field[] fields = confclass.getDeclaredFields(); // Arrays.sort(fields, new Comparator<Field>() { // @Override // public int compare(Field o1, Field o2) { // return o1.getName().compareTo(o2.getName()); // } // }); // // this.conf = new GrappleConfig.Config(); // // for (Field field : fields) { // Type fieldtype = field.getGenericType(); // try { // if (fieldtype.getTypeName().equals("int")) { // field.setInt(this.conf, buf.readInt()); // } else if (fieldtype.getTypeName().equals("double")) { // field.setDouble(this.conf, buf.readDouble()); // } else if (fieldtype.getTypeName().equals("boolean")) { // field.setBoolean(this.conf, buf.readBoolean()); // } else if (fieldtype.getTypeName().equals("java.lang.String")) { // int len = buf.readInt(); // CharSequence charseq = buf.readCharSequence(len, Charset.defaultCharset()); // field.set(this.conf, charseq.toString()); // } else { // System.out.println("Unknown Type"); // System.out.println(fieldtype.getTypeName()); // } // } catch (IllegalAccessException e) { // System.out.println(e); // } // } // } // // @Override // public void toBytes(ByteBuf buf) { // Class<GrappleConfig.Config> confclass = GrappleConfig.Config.class; // Field[] fields = confclass.getDeclaredFields(); // Arrays.sort(fields, new Comparator<Field>() { // @Override // public int compare(Field o1, Field o2) { // return o1.getName().compareTo(o2.getName()); // } // }); // // for (Field field : fields) { // Type fieldtype = field.getGenericType(); // try { // if (fieldtype.getTypeName().equals("int")) { // buf.writeInt(field.getInt(this.conf)); // } else if (fieldtype.getTypeName().equals("double")) { // buf.writeDouble(field.getDouble(this.conf)); // } else if (fieldtype.getTypeName().equals("boolean")) { // buf.writeBoolean(field.getBoolean(this.conf)); // } else if (fieldtype.getTypeName().equals("java.lang.String")) { // String str = (String) field.get(this.conf); // buf.writeInt(str.length()); // buf.writeCharSequence(str.subSequence(0, str.length()), Charset.defaultCharset()); // } else { // System.out.println("Unknown Type"); // System.out.println(fieldtype.getTypeName()); // } // } catch (IllegalAccessException e) { // System.out.println(e); // } // } // } // // public static class Handler implements IMessageHandler<LoggedInMessage, IMessage> { // public class runner implements Runnable { // LoggedInMessage message; // MessageContext ctx; // public runner(LoggedInMessage message, MessageContext ctx) { // super(); // this.message = message; // this.ctx = ctx; // } // // @Override // public void run() { // GrappleConfig.setserveroptions(this.message.conf); // } // } // // // @Override // public IMessage onMessage(LoggedInMessage message, MessageContext ctx) { // // IThreadListener mainThread = Minecraft.getMinecraft(); // mainThread.addScheduledTask(new runner(message, ctx)); // // return null; // } // } // } // Path: main/java/com/yyon/grapplinghook/ServerProxyClass.java import com.yyon.grapplinghook.network.LoggedInMessage; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraftforge.event.entity.living.LivingDeathEvent; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent; package com.yyon.grapplinghook; public class ServerProxyClass extends CommonProxyClass { @Override public void preInit(FMLPreInitializationEvent event) { super.preInit(event); } @Override public void init(FMLInitializationEvent event, grapplemod grapplemod) { super.init(event, grapplemod); } @Override public void postInit(FMLPostInitializationEvent event) { super.postInit(event); if (GrappleConfig.getconf().override_allowflight) { FMLCommonHandler.instance().getMinecraftServerInstance().setAllowFlight(true); } } @SubscribeEvent public void onPlayerLoggedInEvent(PlayerLoggedInEvent e) { if (e.player instanceof EntityPlayerMP) {
grapplemod.network.sendTo(new LoggedInMessage(GrappleConfig.options), (EntityPlayerMP) e.player);
mscharhag/java-ee-8-mvc
request-data/src/main/java/com/mscharhag/javaee8/mvc/requestparams/bean/User.java
// Path: request-data/src/main/java/com/mscharhag/javaee8/mvc/requestparams/Role.java // public enum Role { // admin, reporter, accountant // }
import com.mscharhag.javaee8.mvc.requestparams.Role; import javax.ws.rs.FormParam;
package com.mscharhag.javaee8.mvc.requestparams.bean; public class User { @FormParam("id") private long id; @FormParam("name") private String name; @FormParam("role")
// Path: request-data/src/main/java/com/mscharhag/javaee8/mvc/requestparams/Role.java // public enum Role { // admin, reporter, accountant // } // Path: request-data/src/main/java/com/mscharhag/javaee8/mvc/requestparams/bean/User.java import com.mscharhag.javaee8.mvc.requestparams.Role; import javax.ws.rs.FormParam; package com.mscharhag.javaee8.mvc.requestparams.bean; public class User { @FormParam("id") private long id; @FormParam("name") private String name; @FormParam("role")
private Role role;
smart-fun/smartGL
smartgl/src/main/java/fr/arnaudguyon/smartgl/opengl/ShaderColorLights.java
// Path: smartgl/src/main/java/fr/arnaudguyon/smartgl/tools/Assert.java // public class Assert { // // public static void assertTrue(boolean condition) { // assertTrue("", condition); // } // public static void assertTrue(String text, boolean condition) { // if (!condition) { // doAssert(text); // } // } // public static void assertNotNull(Object object) { // assertNotNull("", object); // } // public static void assertNotNull(String text, Object object) { // if (object == null) { // doAssert(text); // } // } // // public static void assertEquals(Object object1, Object object2) { // if (object1 == null) { // if (object2 != null) { // doAssert(""); // } // } else { // if (object2 == null) { // doAssert(""); // } else { // if (!object1.equals(object2)) { // doAssert(""); // } // } // } // } // // private static void doAssert(String text) { // throw new RuntimeException(text); // } // }
import android.opengl.GLES20; import java.nio.FloatBuffer; import fr.arnaudguyon.smartgl.tools.Assert;
@Override protected String getVertexAttribName() { return "m_Position"; } @Override protected String getUVAttribName() { return null; } @Override protected String getColorAttribName() { return "m_Color"; } @Override protected String getProjMatrixAttribName() { return "m_ProjectionMatrix"; } @Override protected void init(int programId) { super.init(programId); mModelMatrixId = GLES20.glGetUniformLocation(programId, "mModelMatrix"); mParallelLightDirectionId = GLES20.glGetUniformLocation(programId, "mParallelLightDirection"); mParallelLightColorId = GLES20.glGetUniformLocation(programId, "mParallelLightColor"); mLightAmbiantId = GLES20.glGetUniformLocation(programId, "mAmbiantColor"); mNormalsId = GLES20.glGetAttribLocation(programId, "mNormals");
// Path: smartgl/src/main/java/fr/arnaudguyon/smartgl/tools/Assert.java // public class Assert { // // public static void assertTrue(boolean condition) { // assertTrue("", condition); // } // public static void assertTrue(String text, boolean condition) { // if (!condition) { // doAssert(text); // } // } // public static void assertNotNull(Object object) { // assertNotNull("", object); // } // public static void assertNotNull(String text, Object object) { // if (object == null) { // doAssert(text); // } // } // // public static void assertEquals(Object object1, Object object2) { // if (object1 == null) { // if (object2 != null) { // doAssert(""); // } // } else { // if (object2 == null) { // doAssert(""); // } else { // if (!object1.equals(object2)) { // doAssert(""); // } // } // } // } // // private static void doAssert(String text) { // throw new RuntimeException(text); // } // } // Path: smartgl/src/main/java/fr/arnaudguyon/smartgl/opengl/ShaderColorLights.java import android.opengl.GLES20; import java.nio.FloatBuffer; import fr.arnaudguyon.smartgl.tools.Assert; @Override protected String getVertexAttribName() { return "m_Position"; } @Override protected String getUVAttribName() { return null; } @Override protected String getColorAttribName() { return "m_Color"; } @Override protected String getProjMatrixAttribName() { return "m_ProjectionMatrix"; } @Override protected void init(int programId) { super.init(programId); mModelMatrixId = GLES20.glGetUniformLocation(programId, "mModelMatrix"); mParallelLightDirectionId = GLES20.glGetUniformLocation(programId, "mParallelLightDirection"); mParallelLightColorId = GLES20.glGetUniformLocation(programId, "mParallelLightColor"); mLightAmbiantId = GLES20.glGetUniformLocation(programId, "mAmbiantColor"); mNormalsId = GLES20.glGetAttribLocation(programId, "mNormals");
Assert.assertTrue(mModelMatrixId >= 0);
smart-fun/smartGL
smartgl/src/main/java/fr/arnaudguyon/smartgl/opengl/CollisionCircle.java
// Path: smartgl/src/main/java/fr/arnaudguyon/smartgl/tools/Assert.java // public class Assert { // // public static void assertTrue(boolean condition) { // assertTrue("", condition); // } // public static void assertTrue(String text, boolean condition) { // if (!condition) { // doAssert(text); // } // } // public static void assertNotNull(Object object) { // assertNotNull("", object); // } // public static void assertNotNull(String text, Object object) { // if (object == null) { // doAssert(text); // } // } // // public static void assertEquals(Object object1, Object object2) { // if (object1 == null) { // if (object2 != null) { // doAssert(""); // } // } else { // if (object2 == null) { // doAssert(""); // } else { // if (!object1.equals(object2)) { // doAssert(""); // } // } // } // } // // private static void doAssert(String text) { // throw new RuntimeException(text); // } // }
import fr.arnaudguyon.smartgl.tools.Assert;
// } //@Override float getWidth() { return getRadius()*2; } //@Override float getHeight() { return getRadius()*2; } public float getRadius() { return mGlobalRadius * mOwner.getScaleX(); } @Override public boolean collide(Collision otherCol) { if (! (otherCol instanceof CollisionCircle)) { return otherCol.collide(this); } final CollisionCircle other = (CollisionCircle) otherCol; final float squaredDistance = getSquaredDistanceToCenter(other); final float radiusSum = getRadius() + other.getRadius(); return (squaredDistance < (radiusSum * radiusSum)); } // @Override public boolean isInside(Collision otherCol) { if (! (otherCol instanceof CollisionCircle)) {
// Path: smartgl/src/main/java/fr/arnaudguyon/smartgl/tools/Assert.java // public class Assert { // // public static void assertTrue(boolean condition) { // assertTrue("", condition); // } // public static void assertTrue(String text, boolean condition) { // if (!condition) { // doAssert(text); // } // } // public static void assertNotNull(Object object) { // assertNotNull("", object); // } // public static void assertNotNull(String text, Object object) { // if (object == null) { // doAssert(text); // } // } // // public static void assertEquals(Object object1, Object object2) { // if (object1 == null) { // if (object2 != null) { // doAssert(""); // } // } else { // if (object2 == null) { // doAssert(""); // } else { // if (!object1.equals(object2)) { // doAssert(""); // } // } // } // } // // private static void doAssert(String text) { // throw new RuntimeException(text); // } // } // Path: smartgl/src/main/java/fr/arnaudguyon/smartgl/opengl/CollisionCircle.java import fr.arnaudguyon.smartgl.tools.Assert; // } //@Override float getWidth() { return getRadius()*2; } //@Override float getHeight() { return getRadius()*2; } public float getRadius() { return mGlobalRadius * mOwner.getScaleX(); } @Override public boolean collide(Collision otherCol) { if (! (otherCol instanceof CollisionCircle)) { return otherCol.collide(this); } final CollisionCircle other = (CollisionCircle) otherCol; final float squaredDistance = getSquaredDistanceToCenter(other); final float radiusSum = getRadius() + other.getRadius(); return (squaredDistance < (radiusSum * radiusSum)); } // @Override public boolean isInside(Collision otherCol) { if (! (otherCol instanceof CollisionCircle)) {
Assert.assertTrue(false); // other kind of collision not handled yet
smart-fun/smartGL
smartgl/src/main/java/fr/arnaudguyon/smartgl/opengl/CollisionRectangle.java
// Path: smartgl/src/main/java/fr/arnaudguyon/smartgl/tools/Assert.java // public class Assert { // // public static void assertTrue(boolean condition) { // assertTrue("", condition); // } // public static void assertTrue(String text, boolean condition) { // if (!condition) { // doAssert(text); // } // } // public static void assertNotNull(Object object) { // assertNotNull("", object); // } // public static void assertNotNull(String text, Object object) { // if (object == null) { // doAssert(text); // } // } // // public static void assertEquals(Object object1, Object object2) { // if (object1 == null) { // if (object2 != null) { // doAssert(""); // } // } else { // if (object2 == null) { // doAssert(""); // } else { // if (!object1.equals(object2)) { // doAssert(""); // } // } // } // } // // private static void doAssert(String text) { // throw new RuntimeException(text); // } // }
import android.util.Log; import fr.arnaudguyon.smartgl.tools.Assert;
//mOwner = owner; mLeftPercent = leftPercent; mTopPercent = topPercent; mRightPercent = rightPercent; mBottomPercent = bottomPercent; } private static boolean sWarned = false; @Override public void computePositionAndSize() { //Assert.assertTrue(mOwner.getRotation() == 0); // rotation not handled if (mOwner.getRotation() != 0) { if (!sWarned) { Log.e(TAG, "CollisionRectangle cannot be rotated yet! " + mOwner); sWarned = true; } } mLeftPos = mOwner.getPosX() + ((mLeftPercent - mOwner.getPivotX()) * mOwner.getWidth()); mTopPos = mOwner.getPosY() + ((mTopPercent - mOwner.getPivotY()) * mOwner.getHeight()); mRightPos = mOwner.getPosX() + ((mRightPercent - mOwner.getPivotX()) * mOwner.getWidth()); mBottomPos = mOwner.getPosY() + ((mBottomPercent - mOwner.getPivotY()) * mOwner.getHeight()); } @Override public boolean collide(Collision otherCol) { if (otherCol instanceof CollisionCircle) { return collideWithCircle((CollisionCircle) otherCol); } else {
// Path: smartgl/src/main/java/fr/arnaudguyon/smartgl/tools/Assert.java // public class Assert { // // public static void assertTrue(boolean condition) { // assertTrue("", condition); // } // public static void assertTrue(String text, boolean condition) { // if (!condition) { // doAssert(text); // } // } // public static void assertNotNull(Object object) { // assertNotNull("", object); // } // public static void assertNotNull(String text, Object object) { // if (object == null) { // doAssert(text); // } // } // // public static void assertEquals(Object object1, Object object2) { // if (object1 == null) { // if (object2 != null) { // doAssert(""); // } // } else { // if (object2 == null) { // doAssert(""); // } else { // if (!object1.equals(object2)) { // doAssert(""); // } // } // } // } // // private static void doAssert(String text) { // throw new RuntimeException(text); // } // } // Path: smartgl/src/main/java/fr/arnaudguyon/smartgl/opengl/CollisionRectangle.java import android.util.Log; import fr.arnaudguyon.smartgl.tools.Assert; //mOwner = owner; mLeftPercent = leftPercent; mTopPercent = topPercent; mRightPercent = rightPercent; mBottomPercent = bottomPercent; } private static boolean sWarned = false; @Override public void computePositionAndSize() { //Assert.assertTrue(mOwner.getRotation() == 0); // rotation not handled if (mOwner.getRotation() != 0) { if (!sWarned) { Log.e(TAG, "CollisionRectangle cannot be rotated yet! " + mOwner); sWarned = true; } } mLeftPos = mOwner.getPosX() + ((mLeftPercent - mOwner.getPivotX()) * mOwner.getWidth()); mTopPos = mOwner.getPosY() + ((mTopPercent - mOwner.getPivotY()) * mOwner.getHeight()); mRightPos = mOwner.getPosX() + ((mRightPercent - mOwner.getPivotX()) * mOwner.getWidth()); mBottomPos = mOwner.getPosY() + ((mBottomPercent - mOwner.getPivotY()) * mOwner.getHeight()); } @Override public boolean collide(Collision otherCol) { if (otherCol instanceof CollisionCircle) { return collideWithCircle((CollisionCircle) otherCol); } else {
Assert.assertTrue(false); // not handled yet
smart-fun/smartGL
smartgl/src/main/java/fr/arnaudguyon/smartgl/opengl/ShaderTextureAmbiant.java
// Path: smartgl/src/main/java/fr/arnaudguyon/smartgl/tools/Assert.java // public class Assert { // // public static void assertTrue(boolean condition) { // assertTrue("", condition); // } // public static void assertTrue(String text, boolean condition) { // if (!condition) { // doAssert(text); // } // } // public static void assertNotNull(Object object) { // assertNotNull("", object); // } // public static void assertNotNull(String text, Object object) { // if (object == null) { // doAssert(text); // } // } // // public static void assertEquals(Object object1, Object object2) { // if (object1 == null) { // if (object2 != null) { // doAssert(""); // } // } else { // if (object2 == null) { // doAssert(""); // } else { // if (!object1.equals(object2)) { // doAssert(""); // } // } // } // } // // private static void doAssert(String text) { // throw new RuntimeException(text); // } // }
import android.opengl.GLES20; import fr.arnaudguyon.smartgl.tools.Assert;
" vTextureCoord = m_UV;" + "}"; private final static String PIXEL_SHADER_TEXTURE_SCRIPT = "precision mediump float;" + "uniform vec4 mAmbiantColor;" + "varying vec2 vTextureCoord;" + "uniform sampler2D sTexture;" + "void main() {" + " gl_FragColor = texture2D(sTexture, vTextureCoord) * mAmbiantColor;" + "}"; private int mLightAmbiantId; public ShaderTextureAmbiant() { super(VERTEX_SHADER_TEXTURE_SCRIPT, PIXEL_SHADER_TEXTURE_SCRIPT); } @Override public boolean useTexture() { return true; } @Override public boolean useColor() { return false; } @Override protected String getVertexAttribName() { return "m_Position"; } @Override protected String getUVAttribName() { return "m_UV"; } @Override protected String getColorAttribName() { return null; } @Override protected String getProjMatrixAttribName() { return "m_ProjectionMatrix"; } @Override protected void init(int programId) { super.init(programId); mLightAmbiantId = GLES20.glGetUniformLocation(programId, "mAmbiantColor");
// Path: smartgl/src/main/java/fr/arnaudguyon/smartgl/tools/Assert.java // public class Assert { // // public static void assertTrue(boolean condition) { // assertTrue("", condition); // } // public static void assertTrue(String text, boolean condition) { // if (!condition) { // doAssert(text); // } // } // public static void assertNotNull(Object object) { // assertNotNull("", object); // } // public static void assertNotNull(String text, Object object) { // if (object == null) { // doAssert(text); // } // } // // public static void assertEquals(Object object1, Object object2) { // if (object1 == null) { // if (object2 != null) { // doAssert(""); // } // } else { // if (object2 == null) { // doAssert(""); // } else { // if (!object1.equals(object2)) { // doAssert(""); // } // } // } // } // // private static void doAssert(String text) { // throw new RuntimeException(text); // } // } // Path: smartgl/src/main/java/fr/arnaudguyon/smartgl/opengl/ShaderTextureAmbiant.java import android.opengl.GLES20; import fr.arnaudguyon.smartgl.tools.Assert; " vTextureCoord = m_UV;" + "}"; private final static String PIXEL_SHADER_TEXTURE_SCRIPT = "precision mediump float;" + "uniform vec4 mAmbiantColor;" + "varying vec2 vTextureCoord;" + "uniform sampler2D sTexture;" + "void main() {" + " gl_FragColor = texture2D(sTexture, vTextureCoord) * mAmbiantColor;" + "}"; private int mLightAmbiantId; public ShaderTextureAmbiant() { super(VERTEX_SHADER_TEXTURE_SCRIPT, PIXEL_SHADER_TEXTURE_SCRIPT); } @Override public boolean useTexture() { return true; } @Override public boolean useColor() { return false; } @Override protected String getVertexAttribName() { return "m_Position"; } @Override protected String getUVAttribName() { return "m_UV"; } @Override protected String getColorAttribName() { return null; } @Override protected String getProjMatrixAttribName() { return "m_ProjectionMatrix"; } @Override protected void init(int programId) { super.init(programId); mLightAmbiantId = GLES20.glGetUniformLocation(programId, "mAmbiantColor");
Assert.assertTrue(mLightAmbiantId >= 0);
smart-fun/smartGL
smartgl/src/main/java/fr/arnaudguyon/smartgl/opengl/ShaderTextureLights.java
// Path: smartgl/src/main/java/fr/arnaudguyon/smartgl/tools/Assert.java // public class Assert { // // public static void assertTrue(boolean condition) { // assertTrue("", condition); // } // public static void assertTrue(String text, boolean condition) { // if (!condition) { // doAssert(text); // } // } // public static void assertNotNull(Object object) { // assertNotNull("", object); // } // public static void assertNotNull(String text, Object object) { // if (object == null) { // doAssert(text); // } // } // // public static void assertEquals(Object object1, Object object2) { // if (object1 == null) { // if (object2 != null) { // doAssert(""); // } // } else { // if (object2 == null) { // doAssert(""); // } else { // if (!object1.equals(object2)) { // doAssert(""); // } // } // } // } // // private static void doAssert(String text) { // throw new RuntimeException(text); // } // }
import android.opengl.GLES20; import java.nio.FloatBuffer; import fr.arnaudguyon.smartgl.tools.Assert;
@Override protected String getVertexAttribName() { return "m_Position"; } @Override protected String getUVAttribName() { return "m_UV"; } @Override protected String getColorAttribName() { return null; } @Override protected String getProjMatrixAttribName() { return "m_ProjectionMatrix"; } @Override protected void init(int programId) { super.init(programId); mModelMatrixId = GLES20.glGetUniformLocation(programId, "mModelMatrix"); mParallelLightDirectionId = GLES20.glGetUniformLocation(programId, "mParallelLightDirection"); mParallelLightColorId = GLES20.glGetUniformLocation(programId, "mParallelLightColor"); mLightAmbiantId = GLES20.glGetUniformLocation(programId, "mAmbiantColor"); mNormalsId = GLES20.glGetAttribLocation(programId, "mNormals");
// Path: smartgl/src/main/java/fr/arnaudguyon/smartgl/tools/Assert.java // public class Assert { // // public static void assertTrue(boolean condition) { // assertTrue("", condition); // } // public static void assertTrue(String text, boolean condition) { // if (!condition) { // doAssert(text); // } // } // public static void assertNotNull(Object object) { // assertNotNull("", object); // } // public static void assertNotNull(String text, Object object) { // if (object == null) { // doAssert(text); // } // } // // public static void assertEquals(Object object1, Object object2) { // if (object1 == null) { // if (object2 != null) { // doAssert(""); // } // } else { // if (object2 == null) { // doAssert(""); // } else { // if (!object1.equals(object2)) { // doAssert(""); // } // } // } // } // // private static void doAssert(String text) { // throw new RuntimeException(text); // } // } // Path: smartgl/src/main/java/fr/arnaudguyon/smartgl/opengl/ShaderTextureLights.java import android.opengl.GLES20; import java.nio.FloatBuffer; import fr.arnaudguyon.smartgl.tools.Assert; @Override protected String getVertexAttribName() { return "m_Position"; } @Override protected String getUVAttribName() { return "m_UV"; } @Override protected String getColorAttribName() { return null; } @Override protected String getProjMatrixAttribName() { return "m_ProjectionMatrix"; } @Override protected void init(int programId) { super.init(programId); mModelMatrixId = GLES20.glGetUniformLocation(programId, "mModelMatrix"); mParallelLightDirectionId = GLES20.glGetUniformLocation(programId, "mParallelLightDirection"); mParallelLightColorId = GLES20.glGetUniformLocation(programId, "mParallelLightColor"); mLightAmbiantId = GLES20.glGetUniformLocation(programId, "mAmbiantColor"); mNormalsId = GLES20.glGetAttribLocation(programId, "mNormals");
Assert.assertTrue(mModelMatrixId >= 0);
smart-fun/smartGL
smartgl/src/main/java/fr/arnaudguyon/smartgl/opengl/Shader.java
// Path: smartgl/src/main/java/fr/arnaudguyon/smartgl/tools/Assert.java // public class Assert { // // public static void assertTrue(boolean condition) { // assertTrue("", condition); // } // public static void assertTrue(String text, boolean condition) { // if (!condition) { // doAssert(text); // } // } // public static void assertNotNull(Object object) { // assertNotNull("", object); // } // public static void assertNotNull(String text, Object object) { // if (object == null) { // doAssert(text); // } // } // // public static void assertEquals(Object object1, Object object2) { // if (object1 == null) { // if (object2 != null) { // doAssert(""); // } // } else { // if (object2 == null) { // doAssert(""); // } else { // if (!object1.equals(object2)) { // doAssert(""); // } // } // } // } // // private static void doAssert(String text) { // throw new RuntimeException(text); // } // }
import android.opengl.GLES20; import android.util.Log; import fr.arnaudguyon.smartgl.tools.Assert;
public int getPixelScriptId() { return mPixelScriptId; } public abstract boolean useTexture(); public abstract boolean useColor(); protected abstract String getVertexAttribName(); protected abstract String getUVAttribName(); protected abstract String getColorAttribName(); protected abstract String getProjMatrixAttribName(); public int getVertexAttribId() { return mVertexAttribId; } public int getUVAttribId() { return mUVAttribId; } public int getColorAttribId() { return mColorAttribId; } public int getProjMatrixId() { return mProjMatrixId; } private int loadShader(int shaderType, String script) { int shader = GLES20.glCreateShader(shaderType);
// Path: smartgl/src/main/java/fr/arnaudguyon/smartgl/tools/Assert.java // public class Assert { // // public static void assertTrue(boolean condition) { // assertTrue("", condition); // } // public static void assertTrue(String text, boolean condition) { // if (!condition) { // doAssert(text); // } // } // public static void assertNotNull(Object object) { // assertNotNull("", object); // } // public static void assertNotNull(String text, Object object) { // if (object == null) { // doAssert(text); // } // } // // public static void assertEquals(Object object1, Object object2) { // if (object1 == null) { // if (object2 != null) { // doAssert(""); // } // } else { // if (object2 == null) { // doAssert(""); // } else { // if (!object1.equals(object2)) { // doAssert(""); // } // } // } // } // // private static void doAssert(String text) { // throw new RuntimeException(text); // } // } // Path: smartgl/src/main/java/fr/arnaudguyon/smartgl/opengl/Shader.java import android.opengl.GLES20; import android.util.Log; import fr.arnaudguyon.smartgl.tools.Assert; public int getPixelScriptId() { return mPixelScriptId; } public abstract boolean useTexture(); public abstract boolean useColor(); protected abstract String getVertexAttribName(); protected abstract String getUVAttribName(); protected abstract String getColorAttribName(); protected abstract String getProjMatrixAttribName(); public int getVertexAttribId() { return mVertexAttribId; } public int getUVAttribId() { return mUVAttribId; } public int getColorAttribId() { return mColorAttribId; } public int getProjMatrixId() { return mProjMatrixId; } private int loadShader(int shaderType, String script) { int shader = GLES20.glCreateShader(shaderType);
Assert.assertTrue(shader != 0);
smart-fun/smartGL
smartgl/src/main/java/fr/arnaudguyon/smartgl/opengl/LightParallel.java
// Path: smartgl/src/main/java/fr/arnaudguyon/smartgl/math/Vector3D.java // public class Vector3D { // // private float[] mVector = new float[3]; // // public Vector3D(float x, float y, float z) { // mVector[0] = x; // mVector[1] = y; // mVector[2] = z; // } // // public float[] getArray() { // return mVector; // } // // public Vector3D normalize() { // float norm = (float) Math.sqrt(mVector[0]*mVector[0] + mVector[1]*mVector[1] + mVector[2]*mVector[2]); // if (norm > 0) { // mVector[0] /= norm; // mVector[1] /= norm; // mVector[2] /= norm; // } else { // mVector[0] = 1; // mVector[1] = 0; // mVector[2] = 0; // } // return this; // } // // public float dot(@NonNull Vector3D other) { // return (mVector[0] * other.mVector[0]) + (mVector[1] * other.mVector[1]) + (mVector[2] * other.mVector[2]); // } // // public Vector3D add(@NonNull Vector3D other) { // mVector[0] += other.mVector[0]; // mVector[1] += other.mVector[1]; // mVector[2] += other.mVector[2]; // return this; // } // public Vector3D multiply(float scale) { // mVector[0] *= scale; // mVector[1] *= scale; // mVector[2] *= scale; // return this; // } // // public Vector3D vectorProduct(@NonNull Vector3D o) { // float x = mVector[1] * o.mVector[2] - mVector[2] * o.mVector[1]; // float y = mVector[2] * o.mVector[0] - mVector[0] * o.mVector[2]; // float z = mVector[0] * o.mVector[1] - mVector[1] * o.mVector[0]; // return new Vector3D(x, y, z); // } // // }
import androidx.annotation.NonNull; import fr.arnaudguyon.smartgl.math.Vector3D;
/* Copyright 2017 Arnaud Guyon Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package fr.arnaudguyon.smartgl.opengl; /** * Parallel Light for OpenGL */ public class LightParallel extends Light { private SmartColor mColor;
// Path: smartgl/src/main/java/fr/arnaudguyon/smartgl/math/Vector3D.java // public class Vector3D { // // private float[] mVector = new float[3]; // // public Vector3D(float x, float y, float z) { // mVector[0] = x; // mVector[1] = y; // mVector[2] = z; // } // // public float[] getArray() { // return mVector; // } // // public Vector3D normalize() { // float norm = (float) Math.sqrt(mVector[0]*mVector[0] + mVector[1]*mVector[1] + mVector[2]*mVector[2]); // if (norm > 0) { // mVector[0] /= norm; // mVector[1] /= norm; // mVector[2] /= norm; // } else { // mVector[0] = 1; // mVector[1] = 0; // mVector[2] = 0; // } // return this; // } // // public float dot(@NonNull Vector3D other) { // return (mVector[0] * other.mVector[0]) + (mVector[1] * other.mVector[1]) + (mVector[2] * other.mVector[2]); // } // // public Vector3D add(@NonNull Vector3D other) { // mVector[0] += other.mVector[0]; // mVector[1] += other.mVector[1]; // mVector[2] += other.mVector[2]; // return this; // } // public Vector3D multiply(float scale) { // mVector[0] *= scale; // mVector[1] *= scale; // mVector[2] *= scale; // return this; // } // // public Vector3D vectorProduct(@NonNull Vector3D o) { // float x = mVector[1] * o.mVector[2] - mVector[2] * o.mVector[1]; // float y = mVector[2] * o.mVector[0] - mVector[0] * o.mVector[2]; // float z = mVector[0] * o.mVector[1] - mVector[1] * o.mVector[0]; // return new Vector3D(x, y, z); // } // // } // Path: smartgl/src/main/java/fr/arnaudguyon/smartgl/opengl/LightParallel.java import androidx.annotation.NonNull; import fr.arnaudguyon.smartgl.math.Vector3D; /* Copyright 2017 Arnaud Guyon Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package fr.arnaudguyon.smartgl.opengl; /** * Parallel Light for OpenGL */ public class LightParallel extends Light { private SmartColor mColor;
private Vector3D mDirection;
smart-fun/smartGL
smartgl/src/main/java/fr/arnaudguyon/smartgl/opengl/RenderPass.java
// Path: smartgl/src/main/java/fr/arnaudguyon/smartgl/tools/Assert.java // public class Assert { // // public static void assertTrue(boolean condition) { // assertTrue("", condition); // } // public static void assertTrue(String text, boolean condition) { // if (!condition) { // doAssert(text); // } // } // public static void assertNotNull(Object object) { // assertNotNull("", object); // } // public static void assertNotNull(String text, Object object) { // if (object == null) { // doAssert(text); // } // } // // public static void assertEquals(Object object1, Object object2) { // if (object1 == null) { // if (object2 != null) { // doAssert(""); // } // } else { // if (object2 == null) { // doAssert(""); // } else { // if (!object1.equals(object2)) { // doAssert(""); // } // } // } // } // // private static void doAssert(String text) { // throw new RuntimeException(text); // } // }
import java.util.Vector; import android.opengl.GLES20; import fr.arnaudguyon.smartgl.tools.Assert;
/* Copyright 2016 Arnaud Guyon Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package fr.arnaudguyon.smartgl.opengl; public class RenderPass { private final static int NOPROGRAM = 0; private int mProgramId = NOPROGRAM; private Shader mShaders; private Vector<RenderObject> mRenderObjects = new Vector<>(); private boolean mUseZBuffer = false; private boolean mClearZBuffer = false; /* package */ boolean isLoaded() { return (mProgramId != NOPROGRAM); } /* package */ void load() {
// Path: smartgl/src/main/java/fr/arnaudguyon/smartgl/tools/Assert.java // public class Assert { // // public static void assertTrue(boolean condition) { // assertTrue("", condition); // } // public static void assertTrue(String text, boolean condition) { // if (!condition) { // doAssert(text); // } // } // public static void assertNotNull(Object object) { // assertNotNull("", object); // } // public static void assertNotNull(String text, Object object) { // if (object == null) { // doAssert(text); // } // } // // public static void assertEquals(Object object1, Object object2) { // if (object1 == null) { // if (object2 != null) { // doAssert(""); // } // } else { // if (object2 == null) { // doAssert(""); // } else { // if (!object1.equals(object2)) { // doAssert(""); // } // } // } // } // // private static void doAssert(String text) { // throw new RuntimeException(text); // } // } // Path: smartgl/src/main/java/fr/arnaudguyon/smartgl/opengl/RenderPass.java import java.util.Vector; import android.opengl.GLES20; import fr.arnaudguyon.smartgl.tools.Assert; /* Copyright 2016 Arnaud Guyon Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package fr.arnaudguyon.smartgl.opengl; public class RenderPass { private final static int NOPROGRAM = 0; private int mProgramId = NOPROGRAM; private Shader mShaders; private Vector<RenderObject> mRenderObjects = new Vector<>(); private boolean mUseZBuffer = false; private boolean mClearZBuffer = false; /* package */ boolean isLoaded() { return (mProgramId != NOPROGRAM); } /* package */ void load() {
Assert.assertTrue(!isLoaded());
RxHandsOn/MarketData
marketdata-external/src/main/java/com/handson/market/StaticDataProvider.java
// Path: marketdata-common/src/main/java/com/handson/dto/Stock.java // public class Stock { // // public final String code; // // public final String companyName; // // public final String market; // // public Stock(String code, String companyName, String market) { // this.code = code; // this.companyName = companyName; // this.market = market; // } // // public static Stock fromJson(String input) { // return new Gson().fromJson(input, Stock.class); // } // // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/HttpRequest.java // public class HttpRequest { // // private final Map<String, List<String>> parameters; // // public HttpRequest(Map<String, List<String>> parameters) { // this.parameters = parameters; // } // // public String getParameter(String name) { // if (parameters.get(name) == null) { // return null; // } // return parameters.get(name).get(0); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/RxNettyRequestReplyServer.java // public abstract class RxNettyRequestReplyServer { // // private final int port; // // private final String paramName; // // public RxNettyRequestReplyServer(int port, String paramName) { // this.port = port; // this.paramName = paramName; // } // // public HttpServer<ByteBuf, ByteBuf> createServer() { // return RxNetty.createHttpServer(port, (request, response) -> { // // HttpRequest httpRequest = new HttpRequest(request.getQueryParameters()); // String content = getResponseContent(httpRequest); // return response.writeStringAndFlush(content); // }); // } // // protected abstract String getResponseContent(HttpRequest request); // // }
import com.handson.dto.Stock; import com.handson.infra.HttpRequest; import com.handson.infra.RxNettyRequestReplyServer; import java.util.HashMap; import java.util.Map;
package com.handson.market; public class StaticDataProvider extends RxNettyRequestReplyServer { private final Map<String, Stock> stocks; public StaticDataProvider(int port) { super(port, "code"); stocks = new HashMap<>(); stocks.put("GOOGL", new Stock("GOOGL", "Alphabet Inc", "NASDAQ")); stocks.put("IBM", new Stock("IBM", "International Business Machines Corp.", "NYSE")); stocks.put("AAPL", new Stock("AAPL", "Apple Inc.", "NASDAQ")); stocks.put("HPQ", new Stock("HPQ", "HP Inc", "NYSE")); stocks.put("MSFT", new Stock("MSFT", "Microsoft Corporation", "NASDAQ")); stocks.put("CRM", new Stock("CRM", "salesforce.com, inc.", "NYSE")); stocks.put("ADBE", new Stock("ADBE", "Adobe Systems Incorporated", "NASDAQ")); stocks.put("ORCL", new Stock("ORCL", "Oracle Corporation", "NYSE")); } @Override
// Path: marketdata-common/src/main/java/com/handson/dto/Stock.java // public class Stock { // // public final String code; // // public final String companyName; // // public final String market; // // public Stock(String code, String companyName, String market) { // this.code = code; // this.companyName = companyName; // this.market = market; // } // // public static Stock fromJson(String input) { // return new Gson().fromJson(input, Stock.class); // } // // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/HttpRequest.java // public class HttpRequest { // // private final Map<String, List<String>> parameters; // // public HttpRequest(Map<String, List<String>> parameters) { // this.parameters = parameters; // } // // public String getParameter(String name) { // if (parameters.get(name) == null) { // return null; // } // return parameters.get(name).get(0); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/RxNettyRequestReplyServer.java // public abstract class RxNettyRequestReplyServer { // // private final int port; // // private final String paramName; // // public RxNettyRequestReplyServer(int port, String paramName) { // this.port = port; // this.paramName = paramName; // } // // public HttpServer<ByteBuf, ByteBuf> createServer() { // return RxNetty.createHttpServer(port, (request, response) -> { // // HttpRequest httpRequest = new HttpRequest(request.getQueryParameters()); // String content = getResponseContent(httpRequest); // return response.writeStringAndFlush(content); // }); // } // // protected abstract String getResponseContent(HttpRequest request); // // } // Path: marketdata-external/src/main/java/com/handson/market/StaticDataProvider.java import com.handson.dto.Stock; import com.handson.infra.HttpRequest; import com.handson.infra.RxNettyRequestReplyServer; import java.util.HashMap; import java.util.Map; package com.handson.market; public class StaticDataProvider extends RxNettyRequestReplyServer { private final Map<String, Stock> stocks; public StaticDataProvider(int port) { super(port, "code"); stocks = new HashMap<>(); stocks.put("GOOGL", new Stock("GOOGL", "Alphabet Inc", "NASDAQ")); stocks.put("IBM", new Stock("IBM", "International Business Machines Corp.", "NYSE")); stocks.put("AAPL", new Stock("AAPL", "Apple Inc.", "NASDAQ")); stocks.put("HPQ", new Stock("HPQ", "HP Inc", "NYSE")); stocks.put("MSFT", new Stock("MSFT", "Microsoft Corporation", "NASDAQ")); stocks.put("CRM", new Stock("CRM", "salesforce.com, inc.", "NYSE")); stocks.put("ADBE", new Stock("ADBE", "Adobe Systems Incorporated", "NASDAQ")); stocks.put("ORCL", new Stock("ORCL", "Oracle Corporation", "NYSE")); } @Override
protected String getResponseContent(HttpRequest request) {
RxHandsOn/MarketData
marketdata-external/src/main/java/com/handson/market/ForexProvider.java
// Path: marketdata-common/src/main/java/com/handson/infra/RandomSequenceGenerator.java // public class RandomSequenceGenerator { // // private final double min; // private final double max; // private final Random random; // private double bias = 0.3; // // public RandomSequenceGenerator(double min, double max) { // this.min = min; // this.max = max; // this.random = new Random(); // } // // public Observable<Double> create(long interval, TimeUnit timeUnit) { // double init = (min + max) /2; // return Observable // .interval(interval, timeUnit) // .scan(init, (previous, i) -> computeNextNumber(previous)); // } // // public Observable<Integer> createIntegerSequence(long interval, TimeUnit timeUnit) { // double range = max - min; // return Observable // .interval(interval, timeUnit) // .map(i -> ((Double)(random.nextDouble() * range + min)).intValue()); // } // // public double computeNextNumber(double previous) { // double range = (max - min) / 20; // double scaled = (random.nextDouble() - 0.5 + bias) * range; // double shifted = previous + scaled; // if (shifted < min || shifted > max) { // shifted = previous - scaled; // bias = -bias; // } // // shifted = ((Long)Math.round(shifted * 10000)).doubleValue() /10000; // // return shifted; // } // // } // // Path: marketdata-common/src/main/java/com/handson/infra/RxNettyEventBroadcaster.java // public abstract class RxNettyEventBroadcaster<T> extends RxNettyEventServer { // // // private final boolean flaky; // private Observable<T> events; // // public RxNettyEventBroadcaster(int port, boolean flaky) { // super(port); // this.flaky = flaky; // } // // public HttpServer<ByteBuf, ServerSentEvent> createServer() { // if (flaky) { // events = SubscriptionLimiter // .limitSubscriptions(1,initializeEventStream()); // } else { // events = initializeEventStream(); // } // return super.createServer(); // } // // protected abstract Observable<T> initializeEventStream(); // // public Observable<T> getEvents(HttpRequest request) { // return events; // } // // } // // Path: marketdata-common/src/main/java/com/handson/dto/Quote.java // public class Quote { // // public final String code; // public final double quote; // // public Quote(String code, double quote) { // this.code = code; // this.quote = quote; // } // // public static Quote fromJson(String input) { // return new Gson().fromJson(input, Quote.class); // } // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // }
import com.handson.infra.RandomSequenceGenerator; import com.handson.infra.RxNettyEventBroadcaster; import com.handson.dto.Quote; import rx.Observable; import java.util.concurrent.TimeUnit;
package com.handson.market; public class ForexProvider extends RxNettyEventBroadcaster<Quote> { private static final int INTERVAL = 500; public ForexProvider(int port, boolean flaky) { super(port, flaky); } @Override protected Observable<Quote> initializeEventStream() {
// Path: marketdata-common/src/main/java/com/handson/infra/RandomSequenceGenerator.java // public class RandomSequenceGenerator { // // private final double min; // private final double max; // private final Random random; // private double bias = 0.3; // // public RandomSequenceGenerator(double min, double max) { // this.min = min; // this.max = max; // this.random = new Random(); // } // // public Observable<Double> create(long interval, TimeUnit timeUnit) { // double init = (min + max) /2; // return Observable // .interval(interval, timeUnit) // .scan(init, (previous, i) -> computeNextNumber(previous)); // } // // public Observable<Integer> createIntegerSequence(long interval, TimeUnit timeUnit) { // double range = max - min; // return Observable // .interval(interval, timeUnit) // .map(i -> ((Double)(random.nextDouble() * range + min)).intValue()); // } // // public double computeNextNumber(double previous) { // double range = (max - min) / 20; // double scaled = (random.nextDouble() - 0.5 + bias) * range; // double shifted = previous + scaled; // if (shifted < min || shifted > max) { // shifted = previous - scaled; // bias = -bias; // } // // shifted = ((Long)Math.round(shifted * 10000)).doubleValue() /10000; // // return shifted; // } // // } // // Path: marketdata-common/src/main/java/com/handson/infra/RxNettyEventBroadcaster.java // public abstract class RxNettyEventBroadcaster<T> extends RxNettyEventServer { // // // private final boolean flaky; // private Observable<T> events; // // public RxNettyEventBroadcaster(int port, boolean flaky) { // super(port); // this.flaky = flaky; // } // // public HttpServer<ByteBuf, ServerSentEvent> createServer() { // if (flaky) { // events = SubscriptionLimiter // .limitSubscriptions(1,initializeEventStream()); // } else { // events = initializeEventStream(); // } // return super.createServer(); // } // // protected abstract Observable<T> initializeEventStream(); // // public Observable<T> getEvents(HttpRequest request) { // return events; // } // // } // // Path: marketdata-common/src/main/java/com/handson/dto/Quote.java // public class Quote { // // public final String code; // public final double quote; // // public Quote(String code, double quote) { // this.code = code; // this.quote = quote; // } // // public static Quote fromJson(String input) { // return new Gson().fromJson(input, Quote.class); // } // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // Path: marketdata-external/src/main/java/com/handson/market/ForexProvider.java import com.handson.infra.RandomSequenceGenerator; import com.handson.infra.RxNettyEventBroadcaster; import com.handson.dto.Quote; import rx.Observable; import java.util.concurrent.TimeUnit; package com.handson.market; public class ForexProvider extends RxNettyEventBroadcaster<Quote> { private static final int INTERVAL = 500; public ForexProvider(int port, boolean flaky) { super(port, flaky); } @Override protected Observable<Quote> initializeEventStream() {
return new RandomSequenceGenerator(1.2, 1.3)
RxHandsOn/MarketData
marketdata-web/src/main/java/com/handson/rx/StockServer.java
// Path: marketdata-common/src/main/java/com/handson/dto/Quote.java // public class Quote { // // public final String code; // public final double quote; // // public Quote(String code, double quote) { // this.code = code; // this.quote = quote; // } // // public static Quote fromJson(String input) { // return new Gson().fromJson(input, Quote.class); // } // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/dto/Stock.java // public class Stock { // // public final String code; // // public final String companyName; // // public final String market; // // public Stock(String code, String companyName, String market) { // this.code = code; // this.companyName = companyName; // this.market = market; // } // // public static Stock fromJson(String input) { // return new Gson().fromJson(input, Stock.class); // } // // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/EventStreamClient.java // public interface EventStreamClient { // // Observable<String> readServerSideEvents(); // } // // Path: marketdata-common/src/main/java/com/handson/infra/HttpRequest.java // public class HttpRequest { // // private final Map<String, List<String>> parameters; // // public HttpRequest(Map<String, List<String>> parameters) { // this.parameters = parameters; // } // // public String getParameter(String name) { // if (parameters.get(name) == null) { // return null; // } // return parameters.get(name).get(0); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/RequestReplyClient.java // public interface RequestReplyClient { // // Observable<String> request(String parameter); // } // // Path: marketdata-common/src/main/java/com/handson/infra/RxNettyEventServer.java // public abstract class RxNettyEventServer<T> { // // // private final int port; // // public RxNettyEventServer(int port) { // this.port = port; // } // // public HttpServer<ByteBuf, ServerSentEvent> createServer() { // HttpServer<ByteBuf, ServerSentEvent> server = RxNetty.createHttpServer(port, // (request, response) -> { // response.getHeaders().set(ACCESS_CONTROL_ALLOW_ORIGIN, "*"); // response.getHeaders().set(CACHE_CONTROL, "no-cache"); // response.getHeaders().set(CONNECTION, "keep-alive"); // response.getHeaders().set(CONTENT_TYPE, "text/event-stream"); // return getIntervalObservable(request, response); // }, PipelineConfigurators.<ByteBuf>serveSseConfigurator()); // System.out.println("HTTP Server Sent Events server started..."); // return server; // } // // private Observable<Void> getIntervalObservable(HttpServerRequest<?> request, final HttpServerResponse<ServerSentEvent> response) { // HttpRequest simpleRequest = new HttpRequest(request.getQueryParameters()); // return getEvents(simpleRequest) // .flatMap(event -> { // System.out.println("Writing SSE event: " + event); // ByteBuf data = response.getAllocator().buffer().writeBytes(( event + "\n").getBytes()); // ServerSentEvent sse = new ServerSentEvent(data); // return response.writeAndFlush(sse); // }).materialize() // .takeWhile(notification -> { // if (notification.isOnError()) { // System.out.println("Write to client failed, stopping response sending."); // notification.getThrowable().printStackTrace(System.err); // } // return !notification.isOnError(); // }) // .map((Func1<Notification<Void>, Void>) notification -> null); // } // // // protected abstract Observable<T> getEvents(HttpRequest request); // // // }
import com.handson.dto.Quote; import com.handson.dto.Stock; import com.handson.infra.EventStreamClient; import com.handson.infra.HttpRequest; import com.handson.infra.RequestReplyClient; import com.handson.infra.RxNettyEventServer; import rx.Observable; import rx.Scheduler; import java.util.concurrent.TimeUnit;
package com.handson.rx; public class StockServer extends RxNettyEventServer<Stock> { private final RequestReplyClient stockClient;
// Path: marketdata-common/src/main/java/com/handson/dto/Quote.java // public class Quote { // // public final String code; // public final double quote; // // public Quote(String code, double quote) { // this.code = code; // this.quote = quote; // } // // public static Quote fromJson(String input) { // return new Gson().fromJson(input, Quote.class); // } // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/dto/Stock.java // public class Stock { // // public final String code; // // public final String companyName; // // public final String market; // // public Stock(String code, String companyName, String market) { // this.code = code; // this.companyName = companyName; // this.market = market; // } // // public static Stock fromJson(String input) { // return new Gson().fromJson(input, Stock.class); // } // // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/EventStreamClient.java // public interface EventStreamClient { // // Observable<String> readServerSideEvents(); // } // // Path: marketdata-common/src/main/java/com/handson/infra/HttpRequest.java // public class HttpRequest { // // private final Map<String, List<String>> parameters; // // public HttpRequest(Map<String, List<String>> parameters) { // this.parameters = parameters; // } // // public String getParameter(String name) { // if (parameters.get(name) == null) { // return null; // } // return parameters.get(name).get(0); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/RequestReplyClient.java // public interface RequestReplyClient { // // Observable<String> request(String parameter); // } // // Path: marketdata-common/src/main/java/com/handson/infra/RxNettyEventServer.java // public abstract class RxNettyEventServer<T> { // // // private final int port; // // public RxNettyEventServer(int port) { // this.port = port; // } // // public HttpServer<ByteBuf, ServerSentEvent> createServer() { // HttpServer<ByteBuf, ServerSentEvent> server = RxNetty.createHttpServer(port, // (request, response) -> { // response.getHeaders().set(ACCESS_CONTROL_ALLOW_ORIGIN, "*"); // response.getHeaders().set(CACHE_CONTROL, "no-cache"); // response.getHeaders().set(CONNECTION, "keep-alive"); // response.getHeaders().set(CONTENT_TYPE, "text/event-stream"); // return getIntervalObservable(request, response); // }, PipelineConfigurators.<ByteBuf>serveSseConfigurator()); // System.out.println("HTTP Server Sent Events server started..."); // return server; // } // // private Observable<Void> getIntervalObservable(HttpServerRequest<?> request, final HttpServerResponse<ServerSentEvent> response) { // HttpRequest simpleRequest = new HttpRequest(request.getQueryParameters()); // return getEvents(simpleRequest) // .flatMap(event -> { // System.out.println("Writing SSE event: " + event); // ByteBuf data = response.getAllocator().buffer().writeBytes(( event + "\n").getBytes()); // ServerSentEvent sse = new ServerSentEvent(data); // return response.writeAndFlush(sse); // }).materialize() // .takeWhile(notification -> { // if (notification.isOnError()) { // System.out.println("Write to client failed, stopping response sending."); // notification.getThrowable().printStackTrace(System.err); // } // return !notification.isOnError(); // }) // .map((Func1<Notification<Void>, Void>) notification -> null); // } // // // protected abstract Observable<T> getEvents(HttpRequest request); // // // } // Path: marketdata-web/src/main/java/com/handson/rx/StockServer.java import com.handson.dto.Quote; import com.handson.dto.Stock; import com.handson.infra.EventStreamClient; import com.handson.infra.HttpRequest; import com.handson.infra.RequestReplyClient; import com.handson.infra.RxNettyEventServer; import rx.Observable; import rx.Scheduler; import java.util.concurrent.TimeUnit; package com.handson.rx; public class StockServer extends RxNettyEventServer<Stock> { private final RequestReplyClient stockClient;
private final EventStreamClient quoteEventStreamClient;
RxHandsOn/MarketData
marketdata-web/src/main/java/com/handson/rx/StockServer.java
// Path: marketdata-common/src/main/java/com/handson/dto/Quote.java // public class Quote { // // public final String code; // public final double quote; // // public Quote(String code, double quote) { // this.code = code; // this.quote = quote; // } // // public static Quote fromJson(String input) { // return new Gson().fromJson(input, Quote.class); // } // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/dto/Stock.java // public class Stock { // // public final String code; // // public final String companyName; // // public final String market; // // public Stock(String code, String companyName, String market) { // this.code = code; // this.companyName = companyName; // this.market = market; // } // // public static Stock fromJson(String input) { // return new Gson().fromJson(input, Stock.class); // } // // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/EventStreamClient.java // public interface EventStreamClient { // // Observable<String> readServerSideEvents(); // } // // Path: marketdata-common/src/main/java/com/handson/infra/HttpRequest.java // public class HttpRequest { // // private final Map<String, List<String>> parameters; // // public HttpRequest(Map<String, List<String>> parameters) { // this.parameters = parameters; // } // // public String getParameter(String name) { // if (parameters.get(name) == null) { // return null; // } // return parameters.get(name).get(0); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/RequestReplyClient.java // public interface RequestReplyClient { // // Observable<String> request(String parameter); // } // // Path: marketdata-common/src/main/java/com/handson/infra/RxNettyEventServer.java // public abstract class RxNettyEventServer<T> { // // // private final int port; // // public RxNettyEventServer(int port) { // this.port = port; // } // // public HttpServer<ByteBuf, ServerSentEvent> createServer() { // HttpServer<ByteBuf, ServerSentEvent> server = RxNetty.createHttpServer(port, // (request, response) -> { // response.getHeaders().set(ACCESS_CONTROL_ALLOW_ORIGIN, "*"); // response.getHeaders().set(CACHE_CONTROL, "no-cache"); // response.getHeaders().set(CONNECTION, "keep-alive"); // response.getHeaders().set(CONTENT_TYPE, "text/event-stream"); // return getIntervalObservable(request, response); // }, PipelineConfigurators.<ByteBuf>serveSseConfigurator()); // System.out.println("HTTP Server Sent Events server started..."); // return server; // } // // private Observable<Void> getIntervalObservable(HttpServerRequest<?> request, final HttpServerResponse<ServerSentEvent> response) { // HttpRequest simpleRequest = new HttpRequest(request.getQueryParameters()); // return getEvents(simpleRequest) // .flatMap(event -> { // System.out.println("Writing SSE event: " + event); // ByteBuf data = response.getAllocator().buffer().writeBytes(( event + "\n").getBytes()); // ServerSentEvent sse = new ServerSentEvent(data); // return response.writeAndFlush(sse); // }).materialize() // .takeWhile(notification -> { // if (notification.isOnError()) { // System.out.println("Write to client failed, stopping response sending."); // notification.getThrowable().printStackTrace(System.err); // } // return !notification.isOnError(); // }) // .map((Func1<Notification<Void>, Void>) notification -> null); // } // // // protected abstract Observable<T> getEvents(HttpRequest request); // // // }
import com.handson.dto.Quote; import com.handson.dto.Stock; import com.handson.infra.EventStreamClient; import com.handson.infra.HttpRequest; import com.handson.infra.RequestReplyClient; import com.handson.infra.RxNettyEventServer; import rx.Observable; import rx.Scheduler; import java.util.concurrent.TimeUnit;
package com.handson.rx; public class StockServer extends RxNettyEventServer<Stock> { private final RequestReplyClient stockClient; private final EventStreamClient quoteEventStreamClient; private final Scheduler scheduler; public StockServer(int port, RequestReplyClient stockClient, EventStreamClient quoteEventStreamClient, Scheduler scheduler) { super(port); this.stockClient = stockClient; this.quoteEventStreamClient = quoteEventStreamClient; this.scheduler = scheduler; } @Override
// Path: marketdata-common/src/main/java/com/handson/dto/Quote.java // public class Quote { // // public final String code; // public final double quote; // // public Quote(String code, double quote) { // this.code = code; // this.quote = quote; // } // // public static Quote fromJson(String input) { // return new Gson().fromJson(input, Quote.class); // } // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/dto/Stock.java // public class Stock { // // public final String code; // // public final String companyName; // // public final String market; // // public Stock(String code, String companyName, String market) { // this.code = code; // this.companyName = companyName; // this.market = market; // } // // public static Stock fromJson(String input) { // return new Gson().fromJson(input, Stock.class); // } // // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/EventStreamClient.java // public interface EventStreamClient { // // Observable<String> readServerSideEvents(); // } // // Path: marketdata-common/src/main/java/com/handson/infra/HttpRequest.java // public class HttpRequest { // // private final Map<String, List<String>> parameters; // // public HttpRequest(Map<String, List<String>> parameters) { // this.parameters = parameters; // } // // public String getParameter(String name) { // if (parameters.get(name) == null) { // return null; // } // return parameters.get(name).get(0); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/RequestReplyClient.java // public interface RequestReplyClient { // // Observable<String> request(String parameter); // } // // Path: marketdata-common/src/main/java/com/handson/infra/RxNettyEventServer.java // public abstract class RxNettyEventServer<T> { // // // private final int port; // // public RxNettyEventServer(int port) { // this.port = port; // } // // public HttpServer<ByteBuf, ServerSentEvent> createServer() { // HttpServer<ByteBuf, ServerSentEvent> server = RxNetty.createHttpServer(port, // (request, response) -> { // response.getHeaders().set(ACCESS_CONTROL_ALLOW_ORIGIN, "*"); // response.getHeaders().set(CACHE_CONTROL, "no-cache"); // response.getHeaders().set(CONNECTION, "keep-alive"); // response.getHeaders().set(CONTENT_TYPE, "text/event-stream"); // return getIntervalObservable(request, response); // }, PipelineConfigurators.<ByteBuf>serveSseConfigurator()); // System.out.println("HTTP Server Sent Events server started..."); // return server; // } // // private Observable<Void> getIntervalObservable(HttpServerRequest<?> request, final HttpServerResponse<ServerSentEvent> response) { // HttpRequest simpleRequest = new HttpRequest(request.getQueryParameters()); // return getEvents(simpleRequest) // .flatMap(event -> { // System.out.println("Writing SSE event: " + event); // ByteBuf data = response.getAllocator().buffer().writeBytes(( event + "\n").getBytes()); // ServerSentEvent sse = new ServerSentEvent(data); // return response.writeAndFlush(sse); // }).materialize() // .takeWhile(notification -> { // if (notification.isOnError()) { // System.out.println("Write to client failed, stopping response sending."); // notification.getThrowable().printStackTrace(System.err); // } // return !notification.isOnError(); // }) // .map((Func1<Notification<Void>, Void>) notification -> null); // } // // // protected abstract Observable<T> getEvents(HttpRequest request); // // // } // Path: marketdata-web/src/main/java/com/handson/rx/StockServer.java import com.handson.dto.Quote; import com.handson.dto.Stock; import com.handson.infra.EventStreamClient; import com.handson.infra.HttpRequest; import com.handson.infra.RequestReplyClient; import com.handson.infra.RxNettyEventServer; import rx.Observable; import rx.Scheduler; import java.util.concurrent.TimeUnit; package com.handson.rx; public class StockServer extends RxNettyEventServer<Stock> { private final RequestReplyClient stockClient; private final EventStreamClient quoteEventStreamClient; private final Scheduler scheduler; public StockServer(int port, RequestReplyClient stockClient, EventStreamClient quoteEventStreamClient, Scheduler scheduler) { super(port); this.stockClient = stockClient; this.quoteEventStreamClient = quoteEventStreamClient; this.scheduler = scheduler; } @Override
protected Observable<Stock> getEvents(HttpRequest request) {
RxHandsOn/MarketData
marketdata-web/src/test/java/com/handson/rx/MulticastEventStreamClientTest.java
// Path: marketdata-common/src/main/java/com/handson/infra/EventStreamClient.java // public interface EventStreamClient { // // Observable<String> readServerSideEvents(); // }
import com.handson.infra.EventStreamClient; import org.junit.Ignore; import org.junit.Test; import rx.Observable; import rx.observers.TestSubscriber; import rx.schedulers.Schedulers; import rx.schedulers.TestScheduler; import rx.subjects.PublishSubject; import rx.subjects.TestSubject; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package com.handson.rx; public class MulticastEventStreamClientTest { @Test public void Should_transmit_events_from_the_target_client() { // given TestScheduler scheduler = Schedulers.test(); PublishSubject<String> subject = PublishSubject.create();
// Path: marketdata-common/src/main/java/com/handson/infra/EventStreamClient.java // public interface EventStreamClient { // // Observable<String> readServerSideEvents(); // } // Path: marketdata-web/src/test/java/com/handson/rx/MulticastEventStreamClientTest.java import com.handson.infra.EventStreamClient; import org.junit.Ignore; import org.junit.Test; import rx.Observable; import rx.observers.TestSubscriber; import rx.schedulers.Schedulers; import rx.schedulers.TestScheduler; import rx.subjects.PublishSubject; import rx.subjects.TestSubject; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package com.handson.rx; public class MulticastEventStreamClientTest { @Test public void Should_transmit_events_from_the_target_client() { // given TestScheduler scheduler = Schedulers.test(); PublishSubject<String> subject = PublishSubject.create();
EventStreamClient targetClient = mock(EventStreamClient.class);
RxHandsOn/MarketData
marketdata-external/src/main/java/com/handson/market/StockQuoteProvider.java
// Path: marketdata-common/src/main/java/com/handson/dto/Quote.java // public class Quote { // // public final String code; // public final double quote; // // public Quote(String code, double quote) { // this.code = code; // this.quote = quote; // } // // public static Quote fromJson(String input) { // return new Gson().fromJson(input, Quote.class); // } // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/RandomSequenceGenerator.java // public class RandomSequenceGenerator { // // private final double min; // private final double max; // private final Random random; // private double bias = 0.3; // // public RandomSequenceGenerator(double min, double max) { // this.min = min; // this.max = max; // this.random = new Random(); // } // // public Observable<Double> create(long interval, TimeUnit timeUnit) { // double init = (min + max) /2; // return Observable // .interval(interval, timeUnit) // .scan(init, (previous, i) -> computeNextNumber(previous)); // } // // public Observable<Integer> createIntegerSequence(long interval, TimeUnit timeUnit) { // double range = max - min; // return Observable // .interval(interval, timeUnit) // .map(i -> ((Double)(random.nextDouble() * range + min)).intValue()); // } // // public double computeNextNumber(double previous) { // double range = (max - min) / 20; // double scaled = (random.nextDouble() - 0.5 + bias) * range; // double shifted = previous + scaled; // if (shifted < min || shifted > max) { // shifted = previous - scaled; // bias = -bias; // } // // shifted = ((Long)Math.round(shifted * 10000)).doubleValue() /10000; // // return shifted; // } // // } // // Path: marketdata-common/src/main/java/com/handson/infra/RxNettyEventBroadcaster.java // public abstract class RxNettyEventBroadcaster<T> extends RxNettyEventServer { // // // private final boolean flaky; // private Observable<T> events; // // public RxNettyEventBroadcaster(int port, boolean flaky) { // super(port); // this.flaky = flaky; // } // // public HttpServer<ByteBuf, ServerSentEvent> createServer() { // if (flaky) { // events = SubscriptionLimiter // .limitSubscriptions(1,initializeEventStream()); // } else { // events = initializeEventStream(); // } // return super.createServer(); // } // // protected abstract Observable<T> initializeEventStream(); // // public Observable<T> getEvents(HttpRequest request) { // return events; // } // // }
import com.handson.dto.Quote; import com.handson.infra.RandomSequenceGenerator; import com.handson.infra.RxNettyEventBroadcaster; import rx.Observable; import java.util.concurrent.TimeUnit;
package com.handson.market; public class StockQuoteProvider extends RxNettyEventBroadcaster<Quote> { public static final int PORT = 8098; private static final double GOOGLE_MIN = 116; private static final double GOOGLE_MAX = 136; private static final double IBM_MIN = 120; private static final double IBM_MAX = 135; private static final double HP_MIN = 12.5; private static final double HP_MAX = 14; private static final double APPLE_MIN = 94; private static final double APPLE_MAX = 99; private static final double MICROSOFT_MIN = 51; private static final double MICROSOFT_MAX = 53; public StockQuoteProvider(int port, boolean flaky) { super(port, flaky); } @Override protected Observable<Quote> initializeEventStream() { Observable<Quote> googleStock
// Path: marketdata-common/src/main/java/com/handson/dto/Quote.java // public class Quote { // // public final String code; // public final double quote; // // public Quote(String code, double quote) { // this.code = code; // this.quote = quote; // } // // public static Quote fromJson(String input) { // return new Gson().fromJson(input, Quote.class); // } // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/RandomSequenceGenerator.java // public class RandomSequenceGenerator { // // private final double min; // private final double max; // private final Random random; // private double bias = 0.3; // // public RandomSequenceGenerator(double min, double max) { // this.min = min; // this.max = max; // this.random = new Random(); // } // // public Observable<Double> create(long interval, TimeUnit timeUnit) { // double init = (min + max) /2; // return Observable // .interval(interval, timeUnit) // .scan(init, (previous, i) -> computeNextNumber(previous)); // } // // public Observable<Integer> createIntegerSequence(long interval, TimeUnit timeUnit) { // double range = max - min; // return Observable // .interval(interval, timeUnit) // .map(i -> ((Double)(random.nextDouble() * range + min)).intValue()); // } // // public double computeNextNumber(double previous) { // double range = (max - min) / 20; // double scaled = (random.nextDouble() - 0.5 + bias) * range; // double shifted = previous + scaled; // if (shifted < min || shifted > max) { // shifted = previous - scaled; // bias = -bias; // } // // shifted = ((Long)Math.round(shifted * 10000)).doubleValue() /10000; // // return shifted; // } // // } // // Path: marketdata-common/src/main/java/com/handson/infra/RxNettyEventBroadcaster.java // public abstract class RxNettyEventBroadcaster<T> extends RxNettyEventServer { // // // private final boolean flaky; // private Observable<T> events; // // public RxNettyEventBroadcaster(int port, boolean flaky) { // super(port); // this.flaky = flaky; // } // // public HttpServer<ByteBuf, ServerSentEvent> createServer() { // if (flaky) { // events = SubscriptionLimiter // .limitSubscriptions(1,initializeEventStream()); // } else { // events = initializeEventStream(); // } // return super.createServer(); // } // // protected abstract Observable<T> initializeEventStream(); // // public Observable<T> getEvents(HttpRequest request) { // return events; // } // // } // Path: marketdata-external/src/main/java/com/handson/market/StockQuoteProvider.java import com.handson.dto.Quote; import com.handson.infra.RandomSequenceGenerator; import com.handson.infra.RxNettyEventBroadcaster; import rx.Observable; import java.util.concurrent.TimeUnit; package com.handson.market; public class StockQuoteProvider extends RxNettyEventBroadcaster<Quote> { public static final int PORT = 8098; private static final double GOOGLE_MIN = 116; private static final double GOOGLE_MAX = 136; private static final double IBM_MIN = 120; private static final double IBM_MAX = 135; private static final double HP_MIN = 12.5; private static final double HP_MAX = 14; private static final double APPLE_MIN = 94; private static final double APPLE_MAX = 99; private static final double MICROSOFT_MIN = 51; private static final double MICROSOFT_MAX = 53; public StockQuoteProvider(int port, boolean flaky) { super(port, flaky); } @Override protected Observable<Quote> initializeEventStream() { Observable<Quote> googleStock
= new RandomSequenceGenerator(GOOGLE_MIN, GOOGLE_MAX)
RxHandsOn/MarketData
marketdata-web/src/main/java/com/handson/rx/ForexServer.java
// Path: marketdata-common/src/main/java/com/handson/dto/Quote.java // public class Quote { // // public final String code; // public final double quote; // // public Quote(String code, double quote) { // this.code = code; // this.quote = quote; // } // // public static Quote fromJson(String input) { // return new Gson().fromJson(input, Quote.class); // } // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/EventStreamClient.java // public interface EventStreamClient { // // Observable<String> readServerSideEvents(); // } // // Path: marketdata-common/src/main/java/com/handson/infra/HttpRequest.java // public class HttpRequest { // // private final Map<String, List<String>> parameters; // // public HttpRequest(Map<String, List<String>> parameters) { // this.parameters = parameters; // } // // public String getParameter(String name) { // if (parameters.get(name) == null) { // return null; // } // return parameters.get(name).get(0); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/RxNettyEventServer.java // public abstract class RxNettyEventServer<T> { // // // private final int port; // // public RxNettyEventServer(int port) { // this.port = port; // } // // public HttpServer<ByteBuf, ServerSentEvent> createServer() { // HttpServer<ByteBuf, ServerSentEvent> server = RxNetty.createHttpServer(port, // (request, response) -> { // response.getHeaders().set(ACCESS_CONTROL_ALLOW_ORIGIN, "*"); // response.getHeaders().set(CACHE_CONTROL, "no-cache"); // response.getHeaders().set(CONNECTION, "keep-alive"); // response.getHeaders().set(CONTENT_TYPE, "text/event-stream"); // return getIntervalObservable(request, response); // }, PipelineConfigurators.<ByteBuf>serveSseConfigurator()); // System.out.println("HTTP Server Sent Events server started..."); // return server; // } // // private Observable<Void> getIntervalObservable(HttpServerRequest<?> request, final HttpServerResponse<ServerSentEvent> response) { // HttpRequest simpleRequest = new HttpRequest(request.getQueryParameters()); // return getEvents(simpleRequest) // .flatMap(event -> { // System.out.println("Writing SSE event: " + event); // ByteBuf data = response.getAllocator().buffer().writeBytes(( event + "\n").getBytes()); // ServerSentEvent sse = new ServerSentEvent(data); // return response.writeAndFlush(sse); // }).materialize() // .takeWhile(notification -> { // if (notification.isOnError()) { // System.out.println("Write to client failed, stopping response sending."); // notification.getThrowable().printStackTrace(System.err); // } // return !notification.isOnError(); // }) // .map((Func1<Notification<Void>, Void>) notification -> null); // } // // // protected abstract Observable<T> getEvents(HttpRequest request); // // // }
import com.handson.dto.Quote; import com.handson.infra.EventStreamClient; import com.handson.infra.HttpRequest; import com.handson.infra.RxNettyEventServer; import rx.Observable; import rx.Scheduler; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit;
package com.handson.rx; public class ForexServer extends RxNettyEventServer<Double> { private final EventStreamClient forexEventStreamClient; public ForexServer(int port, EventStreamClient eventStreamClient) { super(port); this.forexEventStreamClient = eventStreamClient; } @Override
// Path: marketdata-common/src/main/java/com/handson/dto/Quote.java // public class Quote { // // public final String code; // public final double quote; // // public Quote(String code, double quote) { // this.code = code; // this.quote = quote; // } // // public static Quote fromJson(String input) { // return new Gson().fromJson(input, Quote.class); // } // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/EventStreamClient.java // public interface EventStreamClient { // // Observable<String> readServerSideEvents(); // } // // Path: marketdata-common/src/main/java/com/handson/infra/HttpRequest.java // public class HttpRequest { // // private final Map<String, List<String>> parameters; // // public HttpRequest(Map<String, List<String>> parameters) { // this.parameters = parameters; // } // // public String getParameter(String name) { // if (parameters.get(name) == null) { // return null; // } // return parameters.get(name).get(0); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/RxNettyEventServer.java // public abstract class RxNettyEventServer<T> { // // // private final int port; // // public RxNettyEventServer(int port) { // this.port = port; // } // // public HttpServer<ByteBuf, ServerSentEvent> createServer() { // HttpServer<ByteBuf, ServerSentEvent> server = RxNetty.createHttpServer(port, // (request, response) -> { // response.getHeaders().set(ACCESS_CONTROL_ALLOW_ORIGIN, "*"); // response.getHeaders().set(CACHE_CONTROL, "no-cache"); // response.getHeaders().set(CONNECTION, "keep-alive"); // response.getHeaders().set(CONTENT_TYPE, "text/event-stream"); // return getIntervalObservable(request, response); // }, PipelineConfigurators.<ByteBuf>serveSseConfigurator()); // System.out.println("HTTP Server Sent Events server started..."); // return server; // } // // private Observable<Void> getIntervalObservable(HttpServerRequest<?> request, final HttpServerResponse<ServerSentEvent> response) { // HttpRequest simpleRequest = new HttpRequest(request.getQueryParameters()); // return getEvents(simpleRequest) // .flatMap(event -> { // System.out.println("Writing SSE event: " + event); // ByteBuf data = response.getAllocator().buffer().writeBytes(( event + "\n").getBytes()); // ServerSentEvent sse = new ServerSentEvent(data); // return response.writeAndFlush(sse); // }).materialize() // .takeWhile(notification -> { // if (notification.isOnError()) { // System.out.println("Write to client failed, stopping response sending."); // notification.getThrowable().printStackTrace(System.err); // } // return !notification.isOnError(); // }) // .map((Func1<Notification<Void>, Void>) notification -> null); // } // // // protected abstract Observable<T> getEvents(HttpRequest request); // // // } // Path: marketdata-web/src/main/java/com/handson/rx/ForexServer.java import com.handson.dto.Quote; import com.handson.infra.EventStreamClient; import com.handson.infra.HttpRequest; import com.handson.infra.RxNettyEventServer; import rx.Observable; import rx.Scheduler; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; package com.handson.rx; public class ForexServer extends RxNettyEventServer<Double> { private final EventStreamClient forexEventStreamClient; public ForexServer(int port, EventStreamClient eventStreamClient) { super(port); this.forexEventStreamClient = eventStreamClient; } @Override
protected Observable<Double> getEvents(HttpRequest request) {
RxHandsOn/MarketData
marketdata-web/src/main/java/com/handson/rx/VwapServer.java
// Path: marketdata-common/src/main/java/com/handson/dto/Trade.java // public class Trade { // // public final String code; // public final int quantity; // public final double nominal; // // public Trade(String code, int quantity, double nominal) { // this.code = code; // this.quantity = quantity; // this.nominal = nominal; // } // // public static Trade fromJson(String input) { // return new Gson().fromJson(input, Trade.class); // } // // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/dto/Vwap.java // public class Vwap { // // public final String code; // public final double vwap; // public final double volume; // // public Vwap(String code) { // this.code = code; // this.vwap = 0; // this.volume = 0; // } // // public Vwap(String code, double vwap, double volume) { // this.code = code; // this.vwap = vwap; // this.volume = volume; // } // // public Vwap addTrade(Trade t) { // double volume = this.volume + t.quantity; // double vwap = (this.volume * this.vwap + t.nominal) / volume; // return new Vwap(t.code, vwap, volume); // } // // public static Vwap fromJson(String input) { // return new Gson().fromJson(input, Vwap.class); // } // // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/EventStreamClient.java // public interface EventStreamClient { // // Observable<String> readServerSideEvents(); // } // // Path: marketdata-common/src/main/java/com/handson/infra/HttpRequest.java // public class HttpRequest { // // private final Map<String, List<String>> parameters; // // public HttpRequest(Map<String, List<String>> parameters) { // this.parameters = parameters; // } // // public String getParameter(String name) { // if (parameters.get(name) == null) { // return null; // } // return parameters.get(name).get(0); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/RxNettyEventServer.java // public abstract class RxNettyEventServer<T> { // // // private final int port; // // public RxNettyEventServer(int port) { // this.port = port; // } // // public HttpServer<ByteBuf, ServerSentEvent> createServer() { // HttpServer<ByteBuf, ServerSentEvent> server = RxNetty.createHttpServer(port, // (request, response) -> { // response.getHeaders().set(ACCESS_CONTROL_ALLOW_ORIGIN, "*"); // response.getHeaders().set(CACHE_CONTROL, "no-cache"); // response.getHeaders().set(CONNECTION, "keep-alive"); // response.getHeaders().set(CONTENT_TYPE, "text/event-stream"); // return getIntervalObservable(request, response); // }, PipelineConfigurators.<ByteBuf>serveSseConfigurator()); // System.out.println("HTTP Server Sent Events server started..."); // return server; // } // // private Observable<Void> getIntervalObservable(HttpServerRequest<?> request, final HttpServerResponse<ServerSentEvent> response) { // HttpRequest simpleRequest = new HttpRequest(request.getQueryParameters()); // return getEvents(simpleRequest) // .flatMap(event -> { // System.out.println("Writing SSE event: " + event); // ByteBuf data = response.getAllocator().buffer().writeBytes(( event + "\n").getBytes()); // ServerSentEvent sse = new ServerSentEvent(data); // return response.writeAndFlush(sse); // }).materialize() // .takeWhile(notification -> { // if (notification.isOnError()) { // System.out.println("Write to client failed, stopping response sending."); // notification.getThrowable().printStackTrace(System.err); // } // return !notification.isOnError(); // }) // .map((Func1<Notification<Void>, Void>) notification -> null); // } // // // protected abstract Observable<T> getEvents(HttpRequest request); // // // }
import com.handson.dto.Trade; import com.handson.dto.Vwap; import com.handson.infra.EventStreamClient; import com.handson.infra.HttpRequest; import com.handson.infra.RxNettyEventServer; import rx.Observable; import rx.Scheduler; import java.util.concurrent.TimeUnit;
package com.handson.rx; public class VwapServer extends RxNettyEventServer<Vwap> { private final EventStreamClient tradeEventStreamClient; private final Scheduler scheduler; public VwapServer(int port, EventStreamClient tradeEventStreamClient, Scheduler scheduler) { super(port); this.tradeEventStreamClient = tradeEventStreamClient; this.scheduler = scheduler; } @Override
// Path: marketdata-common/src/main/java/com/handson/dto/Trade.java // public class Trade { // // public final String code; // public final int quantity; // public final double nominal; // // public Trade(String code, int quantity, double nominal) { // this.code = code; // this.quantity = quantity; // this.nominal = nominal; // } // // public static Trade fromJson(String input) { // return new Gson().fromJson(input, Trade.class); // } // // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/dto/Vwap.java // public class Vwap { // // public final String code; // public final double vwap; // public final double volume; // // public Vwap(String code) { // this.code = code; // this.vwap = 0; // this.volume = 0; // } // // public Vwap(String code, double vwap, double volume) { // this.code = code; // this.vwap = vwap; // this.volume = volume; // } // // public Vwap addTrade(Trade t) { // double volume = this.volume + t.quantity; // double vwap = (this.volume * this.vwap + t.nominal) / volume; // return new Vwap(t.code, vwap, volume); // } // // public static Vwap fromJson(String input) { // return new Gson().fromJson(input, Vwap.class); // } // // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/EventStreamClient.java // public interface EventStreamClient { // // Observable<String> readServerSideEvents(); // } // // Path: marketdata-common/src/main/java/com/handson/infra/HttpRequest.java // public class HttpRequest { // // private final Map<String, List<String>> parameters; // // public HttpRequest(Map<String, List<String>> parameters) { // this.parameters = parameters; // } // // public String getParameter(String name) { // if (parameters.get(name) == null) { // return null; // } // return parameters.get(name).get(0); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/RxNettyEventServer.java // public abstract class RxNettyEventServer<T> { // // // private final int port; // // public RxNettyEventServer(int port) { // this.port = port; // } // // public HttpServer<ByteBuf, ServerSentEvent> createServer() { // HttpServer<ByteBuf, ServerSentEvent> server = RxNetty.createHttpServer(port, // (request, response) -> { // response.getHeaders().set(ACCESS_CONTROL_ALLOW_ORIGIN, "*"); // response.getHeaders().set(CACHE_CONTROL, "no-cache"); // response.getHeaders().set(CONNECTION, "keep-alive"); // response.getHeaders().set(CONTENT_TYPE, "text/event-stream"); // return getIntervalObservable(request, response); // }, PipelineConfigurators.<ByteBuf>serveSseConfigurator()); // System.out.println("HTTP Server Sent Events server started..."); // return server; // } // // private Observable<Void> getIntervalObservable(HttpServerRequest<?> request, final HttpServerResponse<ServerSentEvent> response) { // HttpRequest simpleRequest = new HttpRequest(request.getQueryParameters()); // return getEvents(simpleRequest) // .flatMap(event -> { // System.out.println("Writing SSE event: " + event); // ByteBuf data = response.getAllocator().buffer().writeBytes(( event + "\n").getBytes()); // ServerSentEvent sse = new ServerSentEvent(data); // return response.writeAndFlush(sse); // }).materialize() // .takeWhile(notification -> { // if (notification.isOnError()) { // System.out.println("Write to client failed, stopping response sending."); // notification.getThrowable().printStackTrace(System.err); // } // return !notification.isOnError(); // }) // .map((Func1<Notification<Void>, Void>) notification -> null); // } // // // protected abstract Observable<T> getEvents(HttpRequest request); // // // } // Path: marketdata-web/src/main/java/com/handson/rx/VwapServer.java import com.handson.dto.Trade; import com.handson.dto.Vwap; import com.handson.infra.EventStreamClient; import com.handson.infra.HttpRequest; import com.handson.infra.RxNettyEventServer; import rx.Observable; import rx.Scheduler; import java.util.concurrent.TimeUnit; package com.handson.rx; public class VwapServer extends RxNettyEventServer<Vwap> { private final EventStreamClient tradeEventStreamClient; private final Scheduler scheduler; public VwapServer(int port, EventStreamClient tradeEventStreamClient, Scheduler scheduler) { super(port); this.tradeEventStreamClient = tradeEventStreamClient; this.scheduler = scheduler; } @Override
protected Observable<Vwap> getEvents(HttpRequest request) {
RxHandsOn/MarketData
marketdata-web/src/test/java/com/handson/rx/StockQuoteServerTest.java
// Path: marketdata-common/src/main/java/com/handson/dto/Quote.java // public class Quote { // // public final String code; // public final double quote; // // public Quote(String code, double quote) { // this.code = code; // this.quote = quote; // } // // public static Quote fromJson(String input) { // return new Gson().fromJson(input, Quote.class); // } // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/EventStreamClient.java // public interface EventStreamClient { // // Observable<String> readServerSideEvents(); // } // // Path: marketdata-common/src/main/java/com/handson/infra/HttpRequest.java // public class HttpRequest { // // private final Map<String, List<String>> parameters; // // public HttpRequest(Map<String, List<String>> parameters) { // this.parameters = parameters; // } // // public String getParameter(String name) { // if (parameters.get(name) == null) { // return null; // } // return parameters.get(name).get(0); // } // }
import com.handson.dto.Quote; import com.handson.infra.EventStreamClient; import com.handson.infra.HttpRequest; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import rx.Observable; import rx.marble.HotObservable; import rx.marble.junit.MarbleRule; import java.util.Arrays; import java.util.Collections; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static rx.marble.MapHelper.of; import static rx.marble.junit.MarbleRule.*;
package com.handson.rx; public class StockQuoteServerTest { @Rule public MarbleRule marble = new MarbleRule(1000); /** * Test 3 */ @Test @Ignore public void should_filter_quotes_for_requested_stock() { // given Observable<String> quoteSource
// Path: marketdata-common/src/main/java/com/handson/dto/Quote.java // public class Quote { // // public final String code; // public final double quote; // // public Quote(String code, double quote) { // this.code = code; // this.quote = quote; // } // // public static Quote fromJson(String input) { // return new Gson().fromJson(input, Quote.class); // } // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/EventStreamClient.java // public interface EventStreamClient { // // Observable<String> readServerSideEvents(); // } // // Path: marketdata-common/src/main/java/com/handson/infra/HttpRequest.java // public class HttpRequest { // // private final Map<String, List<String>> parameters; // // public HttpRequest(Map<String, List<String>> parameters) { // this.parameters = parameters; // } // // public String getParameter(String name) { // if (parameters.get(name) == null) { // return null; // } // return parameters.get(name).get(0); // } // } // Path: marketdata-web/src/test/java/com/handson/rx/StockQuoteServerTest.java import com.handson.dto.Quote; import com.handson.infra.EventStreamClient; import com.handson.infra.HttpRequest; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import rx.Observable; import rx.marble.HotObservable; import rx.marble.junit.MarbleRule; import java.util.Arrays; import java.util.Collections; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static rx.marble.MapHelper.of; import static rx.marble.junit.MarbleRule.*; package com.handson.rx; public class StockQuoteServerTest { @Rule public MarbleRule marble = new MarbleRule(1000); /** * Test 3 */ @Test @Ignore public void should_filter_quotes_for_requested_stock() { // given Observable<String> quoteSource
= hot("--(ga)--", of("g", new Quote("GOOGL", 705.8673).toJson(),
RxHandsOn/MarketData
marketdata-web/src/test/java/com/handson/rx/StockQuoteServerTest.java
// Path: marketdata-common/src/main/java/com/handson/dto/Quote.java // public class Quote { // // public final String code; // public final double quote; // // public Quote(String code, double quote) { // this.code = code; // this.quote = quote; // } // // public static Quote fromJson(String input) { // return new Gson().fromJson(input, Quote.class); // } // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/EventStreamClient.java // public interface EventStreamClient { // // Observable<String> readServerSideEvents(); // } // // Path: marketdata-common/src/main/java/com/handson/infra/HttpRequest.java // public class HttpRequest { // // private final Map<String, List<String>> parameters; // // public HttpRequest(Map<String, List<String>> parameters) { // this.parameters = parameters; // } // // public String getParameter(String name) { // if (parameters.get(name) == null) { // return null; // } // return parameters.get(name).get(0); // } // }
import com.handson.dto.Quote; import com.handson.infra.EventStreamClient; import com.handson.infra.HttpRequest; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import rx.Observable; import rx.marble.HotObservable; import rx.marble.junit.MarbleRule; import java.util.Arrays; import java.util.Collections; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static rx.marble.MapHelper.of; import static rx.marble.junit.MarbleRule.*;
package com.handson.rx; public class StockQuoteServerTest { @Rule public MarbleRule marble = new MarbleRule(1000); /** * Test 3 */ @Test @Ignore public void should_filter_quotes_for_requested_stock() { // given Observable<String> quoteSource = hot("--(ga)--", of("g", new Quote("GOOGL", 705.8673).toJson(), "a", new Quote("APPLE", 98.18).toJson())); Observable<String> forexSource = hot("--f--", of("f", new Quote("EUR/USD", 1).toJson())); // when StockQuoteServer stockQuoteServer = createServer(quoteSource, forexSource);
// Path: marketdata-common/src/main/java/com/handson/dto/Quote.java // public class Quote { // // public final String code; // public final double quote; // // public Quote(String code, double quote) { // this.code = code; // this.quote = quote; // } // // public static Quote fromJson(String input) { // return new Gson().fromJson(input, Quote.class); // } // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/EventStreamClient.java // public interface EventStreamClient { // // Observable<String> readServerSideEvents(); // } // // Path: marketdata-common/src/main/java/com/handson/infra/HttpRequest.java // public class HttpRequest { // // private final Map<String, List<String>> parameters; // // public HttpRequest(Map<String, List<String>> parameters) { // this.parameters = parameters; // } // // public String getParameter(String name) { // if (parameters.get(name) == null) { // return null; // } // return parameters.get(name).get(0); // } // } // Path: marketdata-web/src/test/java/com/handson/rx/StockQuoteServerTest.java import com.handson.dto.Quote; import com.handson.infra.EventStreamClient; import com.handson.infra.HttpRequest; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import rx.Observable; import rx.marble.HotObservable; import rx.marble.junit.MarbleRule; import java.util.Arrays; import java.util.Collections; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static rx.marble.MapHelper.of; import static rx.marble.junit.MarbleRule.*; package com.handson.rx; public class StockQuoteServerTest { @Rule public MarbleRule marble = new MarbleRule(1000); /** * Test 3 */ @Test @Ignore public void should_filter_quotes_for_requested_stock() { // given Observable<String> quoteSource = hot("--(ga)--", of("g", new Quote("GOOGL", 705.8673).toJson(), "a", new Quote("APPLE", 98.18).toJson())); Observable<String> forexSource = hot("--f--", of("f", new Quote("EUR/USD", 1).toJson())); // when StockQuoteServer stockQuoteServer = createServer(quoteSource, forexSource);
HttpRequest request = createRequest("code", "GOOGL");
RxHandsOn/MarketData
marketdata-web/src/test/java/com/handson/rx/StockQuoteServerTest.java
// Path: marketdata-common/src/main/java/com/handson/dto/Quote.java // public class Quote { // // public final String code; // public final double quote; // // public Quote(String code, double quote) { // this.code = code; // this.quote = quote; // } // // public static Quote fromJson(String input) { // return new Gson().fromJson(input, Quote.class); // } // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/EventStreamClient.java // public interface EventStreamClient { // // Observable<String> readServerSideEvents(); // } // // Path: marketdata-common/src/main/java/com/handson/infra/HttpRequest.java // public class HttpRequest { // // private final Map<String, List<String>> parameters; // // public HttpRequest(Map<String, List<String>> parameters) { // this.parameters = parameters; // } // // public String getParameter(String name) { // if (parameters.get(name) == null) { // return null; // } // return parameters.get(name).get(0); // } // }
import com.handson.dto.Quote; import com.handson.infra.EventStreamClient; import com.handson.infra.HttpRequest; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import rx.Observable; import rx.marble.HotObservable; import rx.marble.junit.MarbleRule; import java.util.Arrays; import java.util.Collections; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static rx.marble.MapHelper.of; import static rx.marble.junit.MarbleRule.*;
stockQuoteServer.getEvents(request).takeUntil(stopSource).subscribe(); // then expectSubscriptions(forexSource.getSubscriptions()) .toBe("^-----!-"); } /** * Test 16 */ @Test @Ignore public void should_send_an_error_when_no_forex_data_after_five_seconds() { // given Observable<String> quoteSource = hot("-g-----", of("g", new Quote("GOOGL", 1300).toJson())); Observable<String> forexSource = hot("-------"); // when StockQuoteServer stockQuoteServer = createServer(quoteSource, forexSource); HttpRequest request = createRequest("code", "GOOGL"); // then expectObservable(stockQuoteServer.getEvents(request)) .toBe("------#"); } public HttpRequest createRequest(String name, String value) { return new HttpRequest(Collections.singletonMap(name, Arrays.asList(value))); } public StockQuoteServer createServer(Observable<String> quoteSource, Observable<String> forexSource) {
// Path: marketdata-common/src/main/java/com/handson/dto/Quote.java // public class Quote { // // public final String code; // public final double quote; // // public Quote(String code, double quote) { // this.code = code; // this.quote = quote; // } // // public static Quote fromJson(String input) { // return new Gson().fromJson(input, Quote.class); // } // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/EventStreamClient.java // public interface EventStreamClient { // // Observable<String> readServerSideEvents(); // } // // Path: marketdata-common/src/main/java/com/handson/infra/HttpRequest.java // public class HttpRequest { // // private final Map<String, List<String>> parameters; // // public HttpRequest(Map<String, List<String>> parameters) { // this.parameters = parameters; // } // // public String getParameter(String name) { // if (parameters.get(name) == null) { // return null; // } // return parameters.get(name).get(0); // } // } // Path: marketdata-web/src/test/java/com/handson/rx/StockQuoteServerTest.java import com.handson.dto.Quote; import com.handson.infra.EventStreamClient; import com.handson.infra.HttpRequest; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import rx.Observable; import rx.marble.HotObservable; import rx.marble.junit.MarbleRule; import java.util.Arrays; import java.util.Collections; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static rx.marble.MapHelper.of; import static rx.marble.junit.MarbleRule.*; stockQuoteServer.getEvents(request).takeUntil(stopSource).subscribe(); // then expectSubscriptions(forexSource.getSubscriptions()) .toBe("^-----!-"); } /** * Test 16 */ @Test @Ignore public void should_send_an_error_when_no_forex_data_after_five_seconds() { // given Observable<String> quoteSource = hot("-g-----", of("g", new Quote("GOOGL", 1300).toJson())); Observable<String> forexSource = hot("-------"); // when StockQuoteServer stockQuoteServer = createServer(quoteSource, forexSource); HttpRequest request = createRequest("code", "GOOGL"); // then expectObservable(stockQuoteServer.getEvents(request)) .toBe("------#"); } public HttpRequest createRequest(String name, String value) { return new HttpRequest(Collections.singletonMap(name, Arrays.asList(value))); } public StockQuoteServer createServer(Observable<String> quoteSource, Observable<String> forexSource) {
EventStreamClient stockQuoteEventStreamClient = mock(EventStreamClient.class);