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
|
---|---|---|---|---|---|---|
CD4017BE/ThermokineticEngineering | src/java/cd4017be/kineng/jeiPlugin/KineticCategory.java | // Path: src/java/cd4017be/kineng/Main.java
// @Mod(modid = Main.ID, useMetadata = true)
// public class Main {
//
// public static final String ID = "kineng";
//
// @Instance(ID)
// public static Main instance;
//
// public static Logger LOG;
//
// @SidedProxy(clientSide = "cd4017be." + ID + ".ClientProxy", serverSide = "cd4017be." + ID + ".CommonProxy")
// public static CommonProxy proxy;
//
// public Main() {
// RecipeScriptContext.scriptRegistry.add(new Version("kinetic", "/assets/" + ID + "/config/recipes.rcp"));
// }
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// LOG = event.getModLog();
// proxy.preInit();
// StructureLocations.register();
// RecipeScriptContext.instance.run("kinetic.PRE_INIT");
// }
//
// @Mod.EventHandler
// public void load(FMLInitializationEvent event) {
// Objects.init();
// proxy.init(new ConfigConstants(RecipeScriptContext.instance.modules.get("kinetic")));
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// Ticking.init();
// }
//
// @Mod.EventHandler
// public void onShutdown(FMLServerStoppingEvent event) {
// Ticking.clear();
// }
//
// }
//
// Path: src/java/cd4017be/kineng/recipe/ProcessingRecipes.java
// public class ProcessingRecipes implements IRecipeHandler {
//
// public final HashMap<ItemKey, KineticRecipe> recipes = new HashMap<>();
// public final String name;
//
// public ProcessingRecipes(int type, String name) {
// this.name = name;
// type >>= 8;
// if (type >= recipeList.length)
// recipeList = Arrays.copyOf(recipeList, recipeList.length << 1);
// recipeList[type] = this;
// }
//
// public KineticRecipe get(ItemStack ing) {
// KineticRecipe rcp = recipes.get(new ItemKey(ing));
// if (rcp == null && ing.getHasSubtypes())
// rcp = recipes.get(new ItemKey(new ItemStack(ing.getItem(), 1, OreDictionary.WILDCARD_VALUE)));
// return rcp;
// }
//
// public void add(KineticRecipe rcp) {
// recipes.put(new ItemKey(rcp.io[0]), rcp);
// }
//
// @Override
// public void addRecipe(Parameters param) {
// Object[] out = param.getArrayOrAll(4);
// KineticRecipe rcp = new KineticRecipe(param.getNumber(3), param.getNumber(2), new ItemStack[out.length + 1]);
// System.arraycopy(out, 0, rcp.io, 1, out.length);
// Object o;
// if (param.param[1] instanceof OreDictStack)
// o = ((OreDictStack)param.param[1]).getItems();
// else o = param.get(1);
// for (Object e : o instanceof Object[] ? (Object[])o : new Object[] {o})
// if (e instanceof ItemStack && !((ItemStack)e).isEmpty()) {
// if (rcp.io[0] == null) rcp.io[0] = (ItemStack)e;
// recipes.put(new ItemKey((ItemStack)e), rcp);
// }
// }
//
// public String jeiName() {
// return Main.ID + ":" + name;
// }
//
// public static ProcessingRecipes[] recipeList = new ProcessingRecipes[16];
// public static final ProcessingRecipes SAWMILL = new ProcessingRecipes(T_SAWBLADE, "sawmill");
// public static final ProcessingRecipes GRINDER = new ProcessingRecipes(T_GRINDER, "grinder");
// public static final ProcessingRecipes LATHE = new ProcessingRecipes(T_ANGULAR, "lathe");
// public static final ProcessingRecipes PRESS = new ProcessingRecipes(T_BELT, "press");
// public static IntConsumer JEI_SHOW_RECIPES;
// public static final ResourceLocation GUI_TEX = new ResourceLocation(Main.ID, "textures/gui/processing.png");
//
// public static ProcessingRecipes getRecipeList(int mode) {
// mode >>>= 8;
// return mode < recipeList.length ? recipeList[mode] : null;
// }
//
// }
| import cd4017be.kineng.Main;
import cd4017be.kineng.recipe.ProcessingRecipes;
import cd4017be.lib.util.TooltipUtil;
import mezz.jei.api.IGuiHelper;
import mezz.jei.api.gui.*;
import mezz.jei.api.ingredients.IIngredients;
import mezz.jei.api.recipe.IRecipeCategory;
import net.minecraft.client.Minecraft;
| package cd4017be.kineng.jeiPlugin;
/**
* @author CD4017BE
*
*/
public class KineticCategory implements IRecipeCategory<KineticRecipeW> {
public final String uid;
final IDrawable icon;
final String title;
public KineticCategory(IGuiHelper guiHelper, String uid, int type) {
this.uid = uid;
this.icon = guiHelper.createDrawable(ProcessingRecipes.GUI_TEX, 208, type * 16, 16, 16);
this.title = TooltipUtil.translate("gui.kineng.pr_mode" + type);
}
@Override
public String getUid() {
return uid;
}
@Override
public String getTitle() {
return title;
}
@Override
public String getModName() {
| // Path: src/java/cd4017be/kineng/Main.java
// @Mod(modid = Main.ID, useMetadata = true)
// public class Main {
//
// public static final String ID = "kineng";
//
// @Instance(ID)
// public static Main instance;
//
// public static Logger LOG;
//
// @SidedProxy(clientSide = "cd4017be." + ID + ".ClientProxy", serverSide = "cd4017be." + ID + ".CommonProxy")
// public static CommonProxy proxy;
//
// public Main() {
// RecipeScriptContext.scriptRegistry.add(new Version("kinetic", "/assets/" + ID + "/config/recipes.rcp"));
// }
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// LOG = event.getModLog();
// proxy.preInit();
// StructureLocations.register();
// RecipeScriptContext.instance.run("kinetic.PRE_INIT");
// }
//
// @Mod.EventHandler
// public void load(FMLInitializationEvent event) {
// Objects.init();
// proxy.init(new ConfigConstants(RecipeScriptContext.instance.modules.get("kinetic")));
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// Ticking.init();
// }
//
// @Mod.EventHandler
// public void onShutdown(FMLServerStoppingEvent event) {
// Ticking.clear();
// }
//
// }
//
// Path: src/java/cd4017be/kineng/recipe/ProcessingRecipes.java
// public class ProcessingRecipes implements IRecipeHandler {
//
// public final HashMap<ItemKey, KineticRecipe> recipes = new HashMap<>();
// public final String name;
//
// public ProcessingRecipes(int type, String name) {
// this.name = name;
// type >>= 8;
// if (type >= recipeList.length)
// recipeList = Arrays.copyOf(recipeList, recipeList.length << 1);
// recipeList[type] = this;
// }
//
// public KineticRecipe get(ItemStack ing) {
// KineticRecipe rcp = recipes.get(new ItemKey(ing));
// if (rcp == null && ing.getHasSubtypes())
// rcp = recipes.get(new ItemKey(new ItemStack(ing.getItem(), 1, OreDictionary.WILDCARD_VALUE)));
// return rcp;
// }
//
// public void add(KineticRecipe rcp) {
// recipes.put(new ItemKey(rcp.io[0]), rcp);
// }
//
// @Override
// public void addRecipe(Parameters param) {
// Object[] out = param.getArrayOrAll(4);
// KineticRecipe rcp = new KineticRecipe(param.getNumber(3), param.getNumber(2), new ItemStack[out.length + 1]);
// System.arraycopy(out, 0, rcp.io, 1, out.length);
// Object o;
// if (param.param[1] instanceof OreDictStack)
// o = ((OreDictStack)param.param[1]).getItems();
// else o = param.get(1);
// for (Object e : o instanceof Object[] ? (Object[])o : new Object[] {o})
// if (e instanceof ItemStack && !((ItemStack)e).isEmpty()) {
// if (rcp.io[0] == null) rcp.io[0] = (ItemStack)e;
// recipes.put(new ItemKey((ItemStack)e), rcp);
// }
// }
//
// public String jeiName() {
// return Main.ID + ":" + name;
// }
//
// public static ProcessingRecipes[] recipeList = new ProcessingRecipes[16];
// public static final ProcessingRecipes SAWMILL = new ProcessingRecipes(T_SAWBLADE, "sawmill");
// public static final ProcessingRecipes GRINDER = new ProcessingRecipes(T_GRINDER, "grinder");
// public static final ProcessingRecipes LATHE = new ProcessingRecipes(T_ANGULAR, "lathe");
// public static final ProcessingRecipes PRESS = new ProcessingRecipes(T_BELT, "press");
// public static IntConsumer JEI_SHOW_RECIPES;
// public static final ResourceLocation GUI_TEX = new ResourceLocation(Main.ID, "textures/gui/processing.png");
//
// public static ProcessingRecipes getRecipeList(int mode) {
// mode >>>= 8;
// return mode < recipeList.length ? recipeList[mode] : null;
// }
//
// }
// Path: src/java/cd4017be/kineng/jeiPlugin/KineticCategory.java
import cd4017be.kineng.Main;
import cd4017be.kineng.recipe.ProcessingRecipes;
import cd4017be.lib.util.TooltipUtil;
import mezz.jei.api.IGuiHelper;
import mezz.jei.api.gui.*;
import mezz.jei.api.ingredients.IIngredients;
import mezz.jei.api.recipe.IRecipeCategory;
import net.minecraft.client.Minecraft;
package cd4017be.kineng.jeiPlugin;
/**
* @author CD4017BE
*
*/
public class KineticCategory implements IRecipeCategory<KineticRecipeW> {
public final String uid;
final IDrawable icon;
final String title;
public KineticCategory(IGuiHelper guiHelper, String uid, int type) {
this.uid = uid;
this.icon = guiHelper.createDrawable(ProcessingRecipes.GUI_TEX, 208, type * 16, 16, 16);
this.title = TooltipUtil.translate("gui.kineng.pr_mode" + type);
}
@Override
public String getUid() {
return uid;
}
@Override
public String getTitle() {
return title;
}
@Override
public String getModName() {
| return Main.ID;
|
CD4017BE/ThermokineticEngineering | src/java/cd4017be/kineng/tileentity/RotaryTool.java | // Path: src/java/cd4017be/kineng/block/BlockRotaryTool.java
// public class BlockRotaryTool extends BlockShaft {
//
// public double maxF;
// public final int type;
// public ItemStack scrap = ItemStack.EMPTY;
//
// /**
// * @param id
// * @param m
// * @param r
// * @param tile
// */
// public BlockRotaryTool(String id, ShaftMaterial m, int type, double r, Class<? extends TileEntity> tile) {
// super(id, m, r, tile);
// this.type = type;
// }
//
// @Override
// public double J(IBlockState state) {
// return J_dens;
// }
//
// @Override
// public double getDebris(IBlockState state, List<ItemStack> items) {
// items.add(shaftMat.scrap);
// items.add(scrap);
// return r;
// }
//
// public void setMaterials(ShaftMaterial mat, double r, double h) {
// J_dens = Formula.J_biCylinder(0.25, shaftMat.density, r, mat.density, h);
// av_max = Math.min(
// Formula.rip_vel(shaftMat.strength / shaftMat.density, 0.25),
// Formula.rip_vel(mat.strength / mat.density, r)
// );
// }
//
// @Override
// @SideOnly(Side.CLIENT)
// protected void addInformation(IBlockState state, List<String> tooltip, ITooltipFlag advanced) {
// super.addInformation(state, tooltip, advanced);
// tooltip.add(TooltipUtil.format("info.kineng.toolstats", radius(state), maxF));
// }
//
// }
| import cd4017be.kineng.block.BlockRotaryTool;
import cd4017be.kineng.physics.*;
import cd4017be.lib.block.AdvancedBlock.INeighborAwareTile;
import cd4017be.lib.util.Utils;
import net.minecraft.block.Block;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumFacing.Axis;
import net.minecraft.util.math.BlockPos;
| package cd4017be.kineng.tileentity;
/**
* @author CD4017BE */
public class RotaryTool extends ShaftPart implements IKineticLink, INeighborAwareTile {
private ForceCon[] cons = new ForceCon[4];
@Override
public double setShaft(ShaftAxis shaft, double v0) {
v0 = IKineticLink.super.setShaft(shaft, vSave);
this.shaft = shaft;
return v0;
}
@Override
public ForceCon getCon(EnumFacing side) {
Axis a = axis();
int d = (1 - (side.getAxis().ordinal() - a.ordinal() + 4) % 3)
* side.getAxisDirection().getOffset();
if (d == 0) return null;
int i = side.ordinal();
if (i >= 2 && a != Axis.X) i -= 2;
ForceCon con = cons[i];
if (con != null) return con;
| // Path: src/java/cd4017be/kineng/block/BlockRotaryTool.java
// public class BlockRotaryTool extends BlockShaft {
//
// public double maxF;
// public final int type;
// public ItemStack scrap = ItemStack.EMPTY;
//
// /**
// * @param id
// * @param m
// * @param r
// * @param tile
// */
// public BlockRotaryTool(String id, ShaftMaterial m, int type, double r, Class<? extends TileEntity> tile) {
// super(id, m, r, tile);
// this.type = type;
// }
//
// @Override
// public double J(IBlockState state) {
// return J_dens;
// }
//
// @Override
// public double getDebris(IBlockState state, List<ItemStack> items) {
// items.add(shaftMat.scrap);
// items.add(scrap);
// return r;
// }
//
// public void setMaterials(ShaftMaterial mat, double r, double h) {
// J_dens = Formula.J_biCylinder(0.25, shaftMat.density, r, mat.density, h);
// av_max = Math.min(
// Formula.rip_vel(shaftMat.strength / shaftMat.density, 0.25),
// Formula.rip_vel(mat.strength / mat.density, r)
// );
// }
//
// @Override
// @SideOnly(Side.CLIENT)
// protected void addInformation(IBlockState state, List<String> tooltip, ITooltipFlag advanced) {
// super.addInformation(state, tooltip, advanced);
// tooltip.add(TooltipUtil.format("info.kineng.toolstats", radius(state), maxF));
// }
//
// }
// Path: src/java/cd4017be/kineng/tileentity/RotaryTool.java
import cd4017be.kineng.block.BlockRotaryTool;
import cd4017be.kineng.physics.*;
import cd4017be.lib.block.AdvancedBlock.INeighborAwareTile;
import cd4017be.lib.util.Utils;
import net.minecraft.block.Block;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumFacing.Axis;
import net.minecraft.util.math.BlockPos;
package cd4017be.kineng.tileentity;
/**
* @author CD4017BE */
public class RotaryTool extends ShaftPart implements IKineticLink, INeighborAwareTile {
private ForceCon[] cons = new ForceCon[4];
@Override
public double setShaft(ShaftAxis shaft, double v0) {
v0 = IKineticLink.super.setShaft(shaft, vSave);
this.shaft = shaft;
return v0;
}
@Override
public ForceCon getCon(EnumFacing side) {
Axis a = axis();
int d = (1 - (side.getAxis().ordinal() - a.ordinal() + 4) % 3)
* side.getAxisDirection().getOffset();
if (d == 0) return null;
int i = side.ordinal();
if (i >= 2 && a != Axis.X) i -= 2;
ForceCon con = cons[i];
if (con != null) return con;
| BlockRotaryTool block = block();
|
CD4017BE/ThermokineticEngineering | src/java/cd4017be/kineng/tileentity/LakeConnection.java | // Path: src/java/cd4017be/kineng/capability/StructureLocations.java
// @CapabilityInject(StructureLocations.class)
// public static final Capability<StructureLocations> MULTIBLOCKS = null;
//
// Path: src/java/cd4017be/kineng/capability/StructureLocations.java
// public class Entry implements Iterator<Entry>, Iterable<Entry> {
//
// private final BlockPos pos;
// private final int k;
// private int i = 0, c, p0, s;
//
// private Entry(BlockPos pos, int id) {
// this.pos = pos;
// this.k = 0x4020100 | id << 27
// | (pos.getX() & 0xff)
// | (pos.getY() & 0xff) << 9
// | (pos.getZ() & 0xff) << 18;
// }
//
// @Override
// public boolean hasNext() {
// int[] str = structures;
// int i = this.i, n = count;
// for (int k = this.k;
// i < n && ((k - str[i+1] | 0x4020100) - str[i+2] & 0xfc020100) != 0;
// i+=3);
// return (this.i = i) < n;
// }
//
// @Override
// public Entry next() {
// int[] str = structures;
// int i = this.i;
// c = str[i];
// p0 = str[i+1];
// s = str[i+2];
// this.i = i + 3;
// return this;
// }
//
// public BlockPos core() {
// return new BlockPos(
// x0() + (c - p0 & 0xff), c >> 9 & 0xff,
// z0() + ((c >> 18) - (p0 >> 18) & 0xff)
// );
// }
//
// public final int x0() {
// int x = p0 & 0xff;
// return pos.getX() - x & 0xffffff00 | x;
// }
// public final int y0() {
// return p0 >> 9 & 0xff;
// }
// public final int z0() {
// int z = p0 >> 18 & 0xff;
// return pos.getZ() - z & 0xffffff00 | z;
// }
// public final int sx() {return s & 0xff;}
// public final int sy() {return s >> 9 & 0xff;}
// public final int sz() {return s >> 18 & 0xff;}
// public final int x1() {return x0() + sx();}
// public final int y1() {return y0() + sy();}
// public final int z1() {return z0() + sz();}
//
// @Override
// public Iterator<Entry> iterator() {
// return this;
// }
// }
| import static cd4017be.kineng.capability.StructureLocations.MULTIBLOCKS;
import java.util.List;
import cd4017be.kineng.capability.StructureLocations.Entry;
import cd4017be.lib.block.AdvancedBlock.ITilePlaceHarvest;
import cd4017be.lib.tileentity.BaseTileEntity;
import cd4017be.lib.tileentity.BaseTileEntity.ITickableServerOnly;
import cd4017be.lib.util.Utils;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString;
| package cd4017be.kineng.tileentity;
/**
* @author CD4017BE */
public abstract class LakeConnection extends BaseTileEntity
implements ITickableServerOnly, ITilePlaceHarvest {
protected BlockPos core;
protected StorageLake lake;
@Override
public void update() {
if (lake != null && !lake.invalid() || getLake())
tickLakeInteract();
}
protected abstract void tickLakeInteract();
protected float relLiquidLvl() {
return (float)(core.getY() - pos.getY() + (lake.level >> 1)) + lake.partLevel();
}
protected boolean getLake() {
if (core == null) return false;
TileEntity te = Utils.getTileAt(world, core);
if (te instanceof StorageLake) {
lake = (StorageLake)te;
return true;
} else return false;
}
@Override
public void onLoad() {
super.onLoad();
BlockPos pos = this.pos.offset(getOrientation().back);
| // Path: src/java/cd4017be/kineng/capability/StructureLocations.java
// @CapabilityInject(StructureLocations.class)
// public static final Capability<StructureLocations> MULTIBLOCKS = null;
//
// Path: src/java/cd4017be/kineng/capability/StructureLocations.java
// public class Entry implements Iterator<Entry>, Iterable<Entry> {
//
// private final BlockPos pos;
// private final int k;
// private int i = 0, c, p0, s;
//
// private Entry(BlockPos pos, int id) {
// this.pos = pos;
// this.k = 0x4020100 | id << 27
// | (pos.getX() & 0xff)
// | (pos.getY() & 0xff) << 9
// | (pos.getZ() & 0xff) << 18;
// }
//
// @Override
// public boolean hasNext() {
// int[] str = structures;
// int i = this.i, n = count;
// for (int k = this.k;
// i < n && ((k - str[i+1] | 0x4020100) - str[i+2] & 0xfc020100) != 0;
// i+=3);
// return (this.i = i) < n;
// }
//
// @Override
// public Entry next() {
// int[] str = structures;
// int i = this.i;
// c = str[i];
// p0 = str[i+1];
// s = str[i+2];
// this.i = i + 3;
// return this;
// }
//
// public BlockPos core() {
// return new BlockPos(
// x0() + (c - p0 & 0xff), c >> 9 & 0xff,
// z0() + ((c >> 18) - (p0 >> 18) & 0xff)
// );
// }
//
// public final int x0() {
// int x = p0 & 0xff;
// return pos.getX() - x & 0xffffff00 | x;
// }
// public final int y0() {
// return p0 >> 9 & 0xff;
// }
// public final int z0() {
// int z = p0 >> 18 & 0xff;
// return pos.getZ() - z & 0xffffff00 | z;
// }
// public final int sx() {return s & 0xff;}
// public final int sy() {return s >> 9 & 0xff;}
// public final int sz() {return s >> 18 & 0xff;}
// public final int x1() {return x0() + sx();}
// public final int y1() {return y0() + sy();}
// public final int z1() {return z0() + sz();}
//
// @Override
// public Iterator<Entry> iterator() {
// return this;
// }
// }
// Path: src/java/cd4017be/kineng/tileentity/LakeConnection.java
import static cd4017be.kineng.capability.StructureLocations.MULTIBLOCKS;
import java.util.List;
import cd4017be.kineng.capability.StructureLocations.Entry;
import cd4017be.lib.block.AdvancedBlock.ITilePlaceHarvest;
import cd4017be.lib.tileentity.BaseTileEntity;
import cd4017be.lib.tileentity.BaseTileEntity.ITickableServerOnly;
import cd4017be.lib.util.Utils;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString;
package cd4017be.kineng.tileentity;
/**
* @author CD4017BE */
public abstract class LakeConnection extends BaseTileEntity
implements ITickableServerOnly, ITilePlaceHarvest {
protected BlockPos core;
protected StorageLake lake;
@Override
public void update() {
if (lake != null && !lake.invalid() || getLake())
tickLakeInteract();
}
protected abstract void tickLakeInteract();
protected float relLiquidLvl() {
return (float)(core.getY() - pos.getY() + (lake.level >> 1)) + lake.partLevel();
}
protected boolean getLake() {
if (core == null) return false;
TileEntity te = Utils.getTileAt(world, core);
if (te instanceof StorageLake) {
lake = (StorageLake)te;
return true;
} else return false;
}
@Override
public void onLoad() {
super.onLoad();
BlockPos pos = this.pos.offset(getOrientation().back);
| for (Entry e : getChunk().getCapability(MULTIBLOCKS, null).find(pos, 0)) {
|
CD4017BE/ThermokineticEngineering | src/java/cd4017be/kineng/tileentity/LakeConnection.java | // Path: src/java/cd4017be/kineng/capability/StructureLocations.java
// @CapabilityInject(StructureLocations.class)
// public static final Capability<StructureLocations> MULTIBLOCKS = null;
//
// Path: src/java/cd4017be/kineng/capability/StructureLocations.java
// public class Entry implements Iterator<Entry>, Iterable<Entry> {
//
// private final BlockPos pos;
// private final int k;
// private int i = 0, c, p0, s;
//
// private Entry(BlockPos pos, int id) {
// this.pos = pos;
// this.k = 0x4020100 | id << 27
// | (pos.getX() & 0xff)
// | (pos.getY() & 0xff) << 9
// | (pos.getZ() & 0xff) << 18;
// }
//
// @Override
// public boolean hasNext() {
// int[] str = structures;
// int i = this.i, n = count;
// for (int k = this.k;
// i < n && ((k - str[i+1] | 0x4020100) - str[i+2] & 0xfc020100) != 0;
// i+=3);
// return (this.i = i) < n;
// }
//
// @Override
// public Entry next() {
// int[] str = structures;
// int i = this.i;
// c = str[i];
// p0 = str[i+1];
// s = str[i+2];
// this.i = i + 3;
// return this;
// }
//
// public BlockPos core() {
// return new BlockPos(
// x0() + (c - p0 & 0xff), c >> 9 & 0xff,
// z0() + ((c >> 18) - (p0 >> 18) & 0xff)
// );
// }
//
// public final int x0() {
// int x = p0 & 0xff;
// return pos.getX() - x & 0xffffff00 | x;
// }
// public final int y0() {
// return p0 >> 9 & 0xff;
// }
// public final int z0() {
// int z = p0 >> 18 & 0xff;
// return pos.getZ() - z & 0xffffff00 | z;
// }
// public final int sx() {return s & 0xff;}
// public final int sy() {return s >> 9 & 0xff;}
// public final int sz() {return s >> 18 & 0xff;}
// public final int x1() {return x0() + sx();}
// public final int y1() {return y0() + sy();}
// public final int z1() {return z0() + sz();}
//
// @Override
// public Iterator<Entry> iterator() {
// return this;
// }
// }
| import static cd4017be.kineng.capability.StructureLocations.MULTIBLOCKS;
import java.util.List;
import cd4017be.kineng.capability.StructureLocations.Entry;
import cd4017be.lib.block.AdvancedBlock.ITilePlaceHarvest;
import cd4017be.lib.tileentity.BaseTileEntity;
import cd4017be.lib.tileentity.BaseTileEntity.ITickableServerOnly;
import cd4017be.lib.util.Utils;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString;
| package cd4017be.kineng.tileentity;
/**
* @author CD4017BE */
public abstract class LakeConnection extends BaseTileEntity
implements ITickableServerOnly, ITilePlaceHarvest {
protected BlockPos core;
protected StorageLake lake;
@Override
public void update() {
if (lake != null && !lake.invalid() || getLake())
tickLakeInteract();
}
protected abstract void tickLakeInteract();
protected float relLiquidLvl() {
return (float)(core.getY() - pos.getY() + (lake.level >> 1)) + lake.partLevel();
}
protected boolean getLake() {
if (core == null) return false;
TileEntity te = Utils.getTileAt(world, core);
if (te instanceof StorageLake) {
lake = (StorageLake)te;
return true;
} else return false;
}
@Override
public void onLoad() {
super.onLoad();
BlockPos pos = this.pos.offset(getOrientation().back);
| // Path: src/java/cd4017be/kineng/capability/StructureLocations.java
// @CapabilityInject(StructureLocations.class)
// public static final Capability<StructureLocations> MULTIBLOCKS = null;
//
// Path: src/java/cd4017be/kineng/capability/StructureLocations.java
// public class Entry implements Iterator<Entry>, Iterable<Entry> {
//
// private final BlockPos pos;
// private final int k;
// private int i = 0, c, p0, s;
//
// private Entry(BlockPos pos, int id) {
// this.pos = pos;
// this.k = 0x4020100 | id << 27
// | (pos.getX() & 0xff)
// | (pos.getY() & 0xff) << 9
// | (pos.getZ() & 0xff) << 18;
// }
//
// @Override
// public boolean hasNext() {
// int[] str = structures;
// int i = this.i, n = count;
// for (int k = this.k;
// i < n && ((k - str[i+1] | 0x4020100) - str[i+2] & 0xfc020100) != 0;
// i+=3);
// return (this.i = i) < n;
// }
//
// @Override
// public Entry next() {
// int[] str = structures;
// int i = this.i;
// c = str[i];
// p0 = str[i+1];
// s = str[i+2];
// this.i = i + 3;
// return this;
// }
//
// public BlockPos core() {
// return new BlockPos(
// x0() + (c - p0 & 0xff), c >> 9 & 0xff,
// z0() + ((c >> 18) - (p0 >> 18) & 0xff)
// );
// }
//
// public final int x0() {
// int x = p0 & 0xff;
// return pos.getX() - x & 0xffffff00 | x;
// }
// public final int y0() {
// return p0 >> 9 & 0xff;
// }
// public final int z0() {
// int z = p0 >> 18 & 0xff;
// return pos.getZ() - z & 0xffffff00 | z;
// }
// public final int sx() {return s & 0xff;}
// public final int sy() {return s >> 9 & 0xff;}
// public final int sz() {return s >> 18 & 0xff;}
// public final int x1() {return x0() + sx();}
// public final int y1() {return y0() + sy();}
// public final int z1() {return z0() + sz();}
//
// @Override
// public Iterator<Entry> iterator() {
// return this;
// }
// }
// Path: src/java/cd4017be/kineng/tileentity/LakeConnection.java
import static cd4017be.kineng.capability.StructureLocations.MULTIBLOCKS;
import java.util.List;
import cd4017be.kineng.capability.StructureLocations.Entry;
import cd4017be.lib.block.AdvancedBlock.ITilePlaceHarvest;
import cd4017be.lib.tileentity.BaseTileEntity;
import cd4017be.lib.tileentity.BaseTileEntity.ITickableServerOnly;
import cd4017be.lib.util.Utils;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString;
package cd4017be.kineng.tileentity;
/**
* @author CD4017BE */
public abstract class LakeConnection extends BaseTileEntity
implements ITickableServerOnly, ITilePlaceHarvest {
protected BlockPos core;
protected StorageLake lake;
@Override
public void update() {
if (lake != null && !lake.invalid() || getLake())
tickLakeInteract();
}
protected abstract void tickLakeInteract();
protected float relLiquidLvl() {
return (float)(core.getY() - pos.getY() + (lake.level >> 1)) + lake.partLevel();
}
protected boolean getLake() {
if (core == null) return false;
TileEntity te = Utils.getTileAt(world, core);
if (te instanceof StorageLake) {
lake = (StorageLake)te;
return true;
} else return false;
}
@Override
public void onLoad() {
super.onLoad();
BlockPos pos = this.pos.offset(getOrientation().back);
| for (Entry e : getChunk().getCapability(MULTIBLOCKS, null).find(pos, 0)) {
|
CD4017BE/ThermokineticEngineering | src/java/cd4017be/kineng/tileentity/TorqueTransducer.java | // Path: src/java/cd4017be/kineng/Main.java
// @Mod(modid = Main.ID, useMetadata = true)
// public class Main {
//
// public static final String ID = "kineng";
//
// @Instance(ID)
// public static Main instance;
//
// public static Logger LOG;
//
// @SidedProxy(clientSide = "cd4017be." + ID + ".ClientProxy", serverSide = "cd4017be." + ID + ".CommonProxy")
// public static CommonProxy proxy;
//
// public Main() {
// RecipeScriptContext.scriptRegistry.add(new Version("kinetic", "/assets/" + ID + "/config/recipes.rcp"));
// }
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// LOG = event.getModLog();
// proxy.preInit();
// StructureLocations.register();
// RecipeScriptContext.instance.run("kinetic.PRE_INIT");
// }
//
// @Mod.EventHandler
// public void load(FMLInitializationEvent event) {
// Objects.init();
// proxy.init(new ConfigConstants(RecipeScriptContext.instance.modules.get("kinetic")));
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// Ticking.init();
// }
//
// @Mod.EventHandler
// public void onShutdown(FMLServerStoppingEvent event) {
// Ticking.clear();
// }
//
// }
| import static cd4017be.lib.network.Sync.GUI;
import java.util.ArrayList;
import cd4017be.kineng.Main;
import cd4017be.kineng.physics.*;
import cd4017be.lib.Gui.AdvancedContainer;
import cd4017be.lib.Gui.AdvancedContainer.IStateInteractionHandler;
import cd4017be.lib.Gui.ModularGui;
import cd4017be.lib.Gui.comp.*;
import cd4017be.lib.block.AdvancedBlock.IRedstoneTile;
import cd4017be.lib.network.*;
import cd4017be.lib.tileentity.BaseTileEntity.ITickableServerOnly;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
| if (!found)
while(i < cons.size() && cons.get(i).host == part)
i++;
}
}
this.idx = i;
this.dJ = dJ / sJ * 0.5;
}
@Override
public double setShaft(ShaftAxis shaft) {
idx = -1;
return super.setShaft(shaft);
}
@Override
public int redstoneLevel(EnumFacing side, boolean strong) {
return strong ? 0 : lastRS;
}
@Override
public boolean connectRedstone(EnumFacing side) {
return true;
}
@Override
public AdvancedContainer getContainer(EntityPlayer player, int id) {
return new AdvancedContainer(this, StateSyncAdv.of(false, this), player);
}
| // Path: src/java/cd4017be/kineng/Main.java
// @Mod(modid = Main.ID, useMetadata = true)
// public class Main {
//
// public static final String ID = "kineng";
//
// @Instance(ID)
// public static Main instance;
//
// public static Logger LOG;
//
// @SidedProxy(clientSide = "cd4017be." + ID + ".ClientProxy", serverSide = "cd4017be." + ID + ".CommonProxy")
// public static CommonProxy proxy;
//
// public Main() {
// RecipeScriptContext.scriptRegistry.add(new Version("kinetic", "/assets/" + ID + "/config/recipes.rcp"));
// }
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// LOG = event.getModLog();
// proxy.preInit();
// StructureLocations.register();
// RecipeScriptContext.instance.run("kinetic.PRE_INIT");
// }
//
// @Mod.EventHandler
// public void load(FMLInitializationEvent event) {
// Objects.init();
// proxy.init(new ConfigConstants(RecipeScriptContext.instance.modules.get("kinetic")));
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// Ticking.init();
// }
//
// @Mod.EventHandler
// public void onShutdown(FMLServerStoppingEvent event) {
// Ticking.clear();
// }
//
// }
// Path: src/java/cd4017be/kineng/tileentity/TorqueTransducer.java
import static cd4017be.lib.network.Sync.GUI;
import java.util.ArrayList;
import cd4017be.kineng.Main;
import cd4017be.kineng.physics.*;
import cd4017be.lib.Gui.AdvancedContainer;
import cd4017be.lib.Gui.AdvancedContainer.IStateInteractionHandler;
import cd4017be.lib.Gui.ModularGui;
import cd4017be.lib.Gui.comp.*;
import cd4017be.lib.block.AdvancedBlock.IRedstoneTile;
import cd4017be.lib.network.*;
import cd4017be.lib.tileentity.BaseTileEntity.ITickableServerOnly;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
if (!found)
while(i < cons.size() && cons.get(i).host == part)
i++;
}
}
this.idx = i;
this.dJ = dJ / sJ * 0.5;
}
@Override
public double setShaft(ShaftAxis shaft) {
idx = -1;
return super.setShaft(shaft);
}
@Override
public int redstoneLevel(EnumFacing side, boolean strong) {
return strong ? 0 : lastRS;
}
@Override
public boolean connectRedstone(EnumFacing side) {
return true;
}
@Override
public AdvancedContainer getContainer(EntityPlayer player, int id) {
return new AdvancedContainer(this, StateSyncAdv.of(false, this), player);
}
| private static final ResourceLocation GUI_TEX = new ResourceLocation(Main.ID, "textures/gui/debug.png");
|
CD4017BE/ThermokineticEngineering | src/java/cd4017be/kineng/physics/Formula.java | // Path: src/java/cd4017be/kineng/Main.java
// @Mod(modid = Main.ID, useMetadata = true)
// public class Main {
//
// public static final String ID = "kineng";
//
// @Instance(ID)
// public static Main instance;
//
// public static Logger LOG;
//
// @SidedProxy(clientSide = "cd4017be." + ID + ".ClientProxy", serverSide = "cd4017be." + ID + ".CommonProxy")
// public static CommonProxy proxy;
//
// public Main() {
// RecipeScriptContext.scriptRegistry.add(new Version("kinetic", "/assets/" + ID + "/config/recipes.rcp"));
// }
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// LOG = event.getModLog();
// proxy.preInit();
// StructureLocations.register();
// RecipeScriptContext.instance.run("kinetic.PRE_INIT");
// }
//
// @Mod.EventHandler
// public void load(FMLInitializationEvent event) {
// Objects.init();
// proxy.init(new ConfigConstants(RecipeScriptContext.instance.modules.get("kinetic")));
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// Ticking.init();
// }
//
// @Mod.EventHandler
// public void onShutdown(FMLServerStoppingEvent event) {
// Ticking.clear();
// }
//
// }
| import java.util.Arrays;
import java.util.Formatter;
import cd4017be.kineng.Main;
| public static float[][] MATRIX = new float[4][8];
public static int m, n;
/** initialize the {@link #MATRIX} with zeroes and increase size if necessary
* @param m number of rows
* @param n number of columns
*/
public static void initMatrix(int m, int n) {
int oldM = MATRIX.length, oldN = MATRIX[0].length;
boolean grow = false;
if (m > oldM) {
oldM = Math.max(m, oldM << 1);
grow = true;
}
if (n > oldN) {
oldN = Math.max(n, oldN << 1);
grow = true;
}
if (grow) MATRIX = new float[m][n];
else for (int i = 0; i < m; i++)
Arrays.fill(MATRIX[i], 0, n, 0F);
Formula.m = m;
Formula.n = n;
}
/** solve the system of linear equations previously set up in {@link #MATRIX},
* leaving the solution in columns {@link #m} ... {@link #n} - 1.
*/
public static void solveMatrix() {
if (n < m) throw new IllegalStateException("can't solve with less columns than rows!");
| // Path: src/java/cd4017be/kineng/Main.java
// @Mod(modid = Main.ID, useMetadata = true)
// public class Main {
//
// public static final String ID = "kineng";
//
// @Instance(ID)
// public static Main instance;
//
// public static Logger LOG;
//
// @SidedProxy(clientSide = "cd4017be." + ID + ".ClientProxy", serverSide = "cd4017be." + ID + ".CommonProxy")
// public static CommonProxy proxy;
//
// public Main() {
// RecipeScriptContext.scriptRegistry.add(new Version("kinetic", "/assets/" + ID + "/config/recipes.rcp"));
// }
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// LOG = event.getModLog();
// proxy.preInit();
// StructureLocations.register();
// RecipeScriptContext.instance.run("kinetic.PRE_INIT");
// }
//
// @Mod.EventHandler
// public void load(FMLInitializationEvent event) {
// Objects.init();
// proxy.init(new ConfigConstants(RecipeScriptContext.instance.modules.get("kinetic")));
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// Ticking.init();
// }
//
// @Mod.EventHandler
// public void onShutdown(FMLServerStoppingEvent event) {
// Ticking.clear();
// }
//
// }
// Path: src/java/cd4017be/kineng/physics/Formula.java
import java.util.Arrays;
import java.util.Formatter;
import cd4017be.kineng.Main;
public static float[][] MATRIX = new float[4][8];
public static int m, n;
/** initialize the {@link #MATRIX} with zeroes and increase size if necessary
* @param m number of rows
* @param n number of columns
*/
public static void initMatrix(int m, int n) {
int oldM = MATRIX.length, oldN = MATRIX[0].length;
boolean grow = false;
if (m > oldM) {
oldM = Math.max(m, oldM << 1);
grow = true;
}
if (n > oldN) {
oldN = Math.max(n, oldN << 1);
grow = true;
}
if (grow) MATRIX = new float[m][n];
else for (int i = 0; i < m; i++)
Arrays.fill(MATRIX[i], 0, n, 0F);
Formula.m = m;
Formula.n = n;
}
/** solve the system of linear equations previously set up in {@link #MATRIX},
* leaving the solution in columns {@link #m} ... {@link #n} - 1.
*/
public static void solveMatrix() {
if (n < m) throw new IllegalStateException("can't solve with less columns than rows!");
| if (Ticking.DEBUG) Main.LOG.info(printMatrix());
|
CD4017BE/ThermokineticEngineering | src/java/cd4017be/kineng/block/BlockFillCustom.java | // Path: src/java/cd4017be/kineng/tileentity/CircularMultiblockPart.java
// public class CircularMultiblockPart extends BaseTileEntity implements INeighborAwareTile, ITilePlaceHarvest {
//
// public CircularMultiblockCore link;
// public double r, m, v;
// public IBlockState storedBlock = Blocks.AIR.getDefaultState();
// public boolean isLinked;
//
// public void link(CircularMultiblockCore target) {
// if (link == target) return;
// link = target;
// isLinked = true;
// r = Math.sqrt(pos.distanceSq(target.getPos()));
// link.mergeMomentum(m * r * r, m * r * v);
// markDirty(REDRAW);
// }
//
// public void unlink() {
// if (link == null) return;
// link.remove(this);
// link = null;
// isLinked = false;
// if (!unloaded) markDirty(REDRAW);
// }
//
// @Override
// protected void onUnload() {
// super.onUnload();
// unlink();
// }
//
// @Override
// protected void storeState(NBTTagCompound nbt, int mode) {
// super.storeState(nbt, mode);
// if (mode == SAVE) {
// nbt.setDouble("m", m);
// if (link != null) v = link.shaft.av() * r;
// nbt.setDouble("v", v);
// }
// nbt.setInteger("block", Block.getStateId(storedBlock));
// if (mode >= CLIENT) nbt.setBoolean("lk", isLinked);
// }
//
// @Override
// protected void loadState(NBTTagCompound nbt, int mode) {
// super.loadState(nbt, mode);
// if (mode == SAVE) {
// m = nbt.getDouble("m");
// v = nbt.getDouble("v");
// }
// storedBlock = Block.getStateById(nbt.getInteger("block"));
// if (mode >= CLIENT) isLinked = nbt.getBoolean("lk");
// }
//
// @Override
// public void neighborBlockChange(Block b, BlockPos src) {
// if (link != null) link.neighborBlockChange(b, src);
// }
//
// @Override
// public void onPlaced(EntityLivingBase entity, ItemStack item) {}
//
// @Override
// public List<ItemStack> dropItem(IBlockState state, int fortune) {
// NonNullList<ItemStack> list = NonNullList.create();
// storedBlock.getBlock().getDrops(list, world, pos, storedBlock, fortune);
// return list;
// }
//
// @Override
// public void neighborTileChange(TileEntity te, EnumFacing side) {}
//
// }
| import cd4017be.kineng.tileentity.CircularMultiblockPart;
import cd4017be.lib.block.AdvancedBlock;
import cd4017be.lib.property.PropertyBlockMimic;
import net.minecraft.block.Block;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyBool;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.world.Explosion;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.property.ExtendedBlockState;
import net.minecraftforge.common.property.IExtendedBlockState;
import net.minecraftforge.common.property.IUnlistedProperty;
| package cd4017be.kineng.block;
public class BlockFillCustom extends AdvancedBlock {
public static final PropertyBool linked = PropertyBool.create("link");
public BlockFillCustom(String id, Material m, SoundType sound, Class<? extends TileEntity> tile) {
super(id, m, sound, 3, tile);
setDefaultState(getBlockState().getBaseState().withProperty(linked, false));
}
@Override
protected BlockStateContainer createBlockState() {
return new ExtendedBlockState(this, new IProperty[]{linked}, new IUnlistedProperty[] {PropertyBlockMimic.instance});
}
@Override
public IBlockState getStateFromMeta(int meta) {
return getDefaultState();
}
@Override
public int getMetaFromState(IBlockState state) {
return 0;
}
@Override
public IBlockState getActualState(IBlockState state, IBlockAccess world, BlockPos pos) {
TileEntity te = world.getTileEntity(pos);
| // Path: src/java/cd4017be/kineng/tileentity/CircularMultiblockPart.java
// public class CircularMultiblockPart extends BaseTileEntity implements INeighborAwareTile, ITilePlaceHarvest {
//
// public CircularMultiblockCore link;
// public double r, m, v;
// public IBlockState storedBlock = Blocks.AIR.getDefaultState();
// public boolean isLinked;
//
// public void link(CircularMultiblockCore target) {
// if (link == target) return;
// link = target;
// isLinked = true;
// r = Math.sqrt(pos.distanceSq(target.getPos()));
// link.mergeMomentum(m * r * r, m * r * v);
// markDirty(REDRAW);
// }
//
// public void unlink() {
// if (link == null) return;
// link.remove(this);
// link = null;
// isLinked = false;
// if (!unloaded) markDirty(REDRAW);
// }
//
// @Override
// protected void onUnload() {
// super.onUnload();
// unlink();
// }
//
// @Override
// protected void storeState(NBTTagCompound nbt, int mode) {
// super.storeState(nbt, mode);
// if (mode == SAVE) {
// nbt.setDouble("m", m);
// if (link != null) v = link.shaft.av() * r;
// nbt.setDouble("v", v);
// }
// nbt.setInteger("block", Block.getStateId(storedBlock));
// if (mode >= CLIENT) nbt.setBoolean("lk", isLinked);
// }
//
// @Override
// protected void loadState(NBTTagCompound nbt, int mode) {
// super.loadState(nbt, mode);
// if (mode == SAVE) {
// m = nbt.getDouble("m");
// v = nbt.getDouble("v");
// }
// storedBlock = Block.getStateById(nbt.getInteger("block"));
// if (mode >= CLIENT) isLinked = nbt.getBoolean("lk");
// }
//
// @Override
// public void neighborBlockChange(Block b, BlockPos src) {
// if (link != null) link.neighborBlockChange(b, src);
// }
//
// @Override
// public void onPlaced(EntityLivingBase entity, ItemStack item) {}
//
// @Override
// public List<ItemStack> dropItem(IBlockState state, int fortune) {
// NonNullList<ItemStack> list = NonNullList.create();
// storedBlock.getBlock().getDrops(list, world, pos, storedBlock, fortune);
// return list;
// }
//
// @Override
// public void neighborTileChange(TileEntity te, EnumFacing side) {}
//
// }
// Path: src/java/cd4017be/kineng/block/BlockFillCustom.java
import cd4017be.kineng.tileentity.CircularMultiblockPart;
import cd4017be.lib.block.AdvancedBlock;
import cd4017be.lib.property.PropertyBlockMimic;
import net.minecraft.block.Block;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyBool;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.world.Explosion;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.property.ExtendedBlockState;
import net.minecraftforge.common.property.IExtendedBlockState;
import net.minecraftforge.common.property.IUnlistedProperty;
package cd4017be.kineng.block;
public class BlockFillCustom extends AdvancedBlock {
public static final PropertyBool linked = PropertyBool.create("link");
public BlockFillCustom(String id, Material m, SoundType sound, Class<? extends TileEntity> tile) {
super(id, m, sound, 3, tile);
setDefaultState(getBlockState().getBaseState().withProperty(linked, false));
}
@Override
protected BlockStateContainer createBlockState() {
return new ExtendedBlockState(this, new IProperty[]{linked}, new IUnlistedProperty[] {PropertyBlockMimic.instance});
}
@Override
public IBlockState getStateFromMeta(int meta) {
return getDefaultState();
}
@Override
public int getMetaFromState(IBlockState state) {
return 0;
}
@Override
public IBlockState getActualState(IBlockState state, IBlockAccess world, BlockPos pos) {
TileEntity te = world.getTileEntity(pos);
| if (te instanceof CircularMultiblockPart)
|
CD4017BE/ThermokineticEngineering | src/java/cd4017be/kineng/jeiPlugin/KineticRecipeW.java | // Path: src/java/cd4017be/kineng/recipe/KineticRecipe.java
// public class KineticRecipe {
//
// public final ItemStack[] io;
// /** [m] distance to move per operation */
// public final double s;
// /** [N] force to apply */
// public final double F;
//
// public KineticRecipe(double s, double F, ItemStack... io) {
// this.io = io;
// this.s = s;
// this.F = F;
// }
//
// }
| import java.util.*;
import java.util.Map.Entry;
import cd4017be.kineng.recipe.KineticRecipe;
import cd4017be.lib.util.ItemKey;
import cd4017be.lib.util.TooltipUtil;
import mezz.jei.api.gui.IDrawableStatic;
import mezz.jei.api.ingredients.IIngredients;
import mezz.jei.api.recipe.IRecipeWrapper;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.item.ItemStack;
| package cd4017be.kineng.jeiPlugin;
/**
* @author CD4017BE
*
*/
public class KineticRecipeW implements IRecipeWrapper {
public static IDrawableStatic PROGRESSBAR, BACKGROUND;
public static long t0;
public final List<ItemStack> ingred, output;
final String info;
final int t;
| // Path: src/java/cd4017be/kineng/recipe/KineticRecipe.java
// public class KineticRecipe {
//
// public final ItemStack[] io;
// /** [m] distance to move per operation */
// public final double s;
// /** [N] force to apply */
// public final double F;
//
// public KineticRecipe(double s, double F, ItemStack... io) {
// this.io = io;
// this.s = s;
// this.F = F;
// }
//
// }
// Path: src/java/cd4017be/kineng/jeiPlugin/KineticRecipeW.java
import java.util.*;
import java.util.Map.Entry;
import cd4017be.kineng.recipe.KineticRecipe;
import cd4017be.lib.util.ItemKey;
import cd4017be.lib.util.TooltipUtil;
import mezz.jei.api.gui.IDrawableStatic;
import mezz.jei.api.ingredients.IIngredients;
import mezz.jei.api.recipe.IRecipeWrapper;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.item.ItemStack;
package cd4017be.kineng.jeiPlugin;
/**
* @author CD4017BE
*
*/
public class KineticRecipeW implements IRecipeWrapper {
public static IDrawableStatic PROGRESSBAR, BACKGROUND;
public static long t0;
public final List<ItemStack> ingred, output;
final String info;
final int t;
| public KineticRecipeW(Entry<ItemKey, KineticRecipe> entry) {
|
CD4017BE/ThermokineticEngineering | src/java/cd4017be/kineng/tileentity/ManualPower.java | // Path: src/java/cd4017be/kineng/block/BlockRotaryTool.java
// public class BlockRotaryTool extends BlockShaft {
//
// public double maxF;
// public final int type;
// public ItemStack scrap = ItemStack.EMPTY;
//
// /**
// * @param id
// * @param m
// * @param r
// * @param tile
// */
// public BlockRotaryTool(String id, ShaftMaterial m, int type, double r, Class<? extends TileEntity> tile) {
// super(id, m, r, tile);
// this.type = type;
// }
//
// @Override
// public double J(IBlockState state) {
// return J_dens;
// }
//
// @Override
// public double getDebris(IBlockState state, List<ItemStack> items) {
// items.add(shaftMat.scrap);
// items.add(scrap);
// return r;
// }
//
// public void setMaterials(ShaftMaterial mat, double r, double h) {
// J_dens = Formula.J_biCylinder(0.25, shaftMat.density, r, mat.density, h);
// av_max = Math.min(
// Formula.rip_vel(shaftMat.strength / shaftMat.density, 0.25),
// Formula.rip_vel(mat.strength / mat.density, r)
// );
// }
//
// @Override
// @SideOnly(Side.CLIENT)
// protected void addInformation(IBlockState state, List<String> tooltip, ITooltipFlag advanced) {
// super.addInformation(state, tooltip, advanced);
// tooltip.add(TooltipUtil.format("info.kineng.toolstats", radius(state), maxF));
// }
//
// }
| import static net.minecraft.util.EnumFacing.AxisDirection.POSITIVE;
import java.util.*;
import cd4017be.kineng.block.BlockRotaryTool;
import cd4017be.kineng.physics.*;
import cd4017be.lib.block.AdvancedBlock.IInteractiveTile;
import cd4017be.lib.block.AdvancedBlock.INeighborAwareTile;
import cd4017be.lib.tileentity.BaseTileEntity.ITickableServerOnly;
import cd4017be.lib.util.TooltipUtil;
import cd4017be.math.cplx.CplxF;
import net.minecraft.block.Block;
import net.minecraft.block.BlockFence;
import net.minecraft.entity.*;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.*;
import net.minecraft.util.math.*;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.world.chunk.Chunk;
| || Math.abs(px - lh.posX) + Math.abs(pz - lh.posZ) >= 0.25
|| e.getHealth() < e.getMaxHealth()
) continue;
CplxF str = ENTITY_STRENGTH.get(e.getClass());
if (str == null) continue;
double F = Math.copySign(str.r, lh.posY - py), dv = v * F / str.i - 0.5;
dv = Math.max(1.0 - 4.0 * dv * dv, 0);
if (e instanceof EntityAgeable) {
EntityAgeable ea = (EntityAgeable)e;
int age = ea.getGrowingAge();
if (age < -MAX_TIME) {
F = 0;
dv = 0;
} else {
if (age > 0) age = 0;
remT += Math.max(age + MAX_TIME, 0);
}
ea.setGrowingAge(age - (int)(CHECK_INTERVAL * (1.0 + dv)));
n++;
} else if (rand.nextFloat() < dv)
e.setHealth(e.getMaxHealth() * 0.5F);
acc.add(str);
force.F += F;
}
if (force.F != 0)
force.Fdv = -Math.abs(force.F * acc.r / acc.i);
if (n > 0) remT /= n;
}
@Override
| // Path: src/java/cd4017be/kineng/block/BlockRotaryTool.java
// public class BlockRotaryTool extends BlockShaft {
//
// public double maxF;
// public final int type;
// public ItemStack scrap = ItemStack.EMPTY;
//
// /**
// * @param id
// * @param m
// * @param r
// * @param tile
// */
// public BlockRotaryTool(String id, ShaftMaterial m, int type, double r, Class<? extends TileEntity> tile) {
// super(id, m, r, tile);
// this.type = type;
// }
//
// @Override
// public double J(IBlockState state) {
// return J_dens;
// }
//
// @Override
// public double getDebris(IBlockState state, List<ItemStack> items) {
// items.add(shaftMat.scrap);
// items.add(scrap);
// return r;
// }
//
// public void setMaterials(ShaftMaterial mat, double r, double h) {
// J_dens = Formula.J_biCylinder(0.25, shaftMat.density, r, mat.density, h);
// av_max = Math.min(
// Formula.rip_vel(shaftMat.strength / shaftMat.density, 0.25),
// Formula.rip_vel(mat.strength / mat.density, r)
// );
// }
//
// @Override
// @SideOnly(Side.CLIENT)
// protected void addInformation(IBlockState state, List<String> tooltip, ITooltipFlag advanced) {
// super.addInformation(state, tooltip, advanced);
// tooltip.add(TooltipUtil.format("info.kineng.toolstats", radius(state), maxF));
// }
//
// }
// Path: src/java/cd4017be/kineng/tileentity/ManualPower.java
import static net.minecraft.util.EnumFacing.AxisDirection.POSITIVE;
import java.util.*;
import cd4017be.kineng.block.BlockRotaryTool;
import cd4017be.kineng.physics.*;
import cd4017be.lib.block.AdvancedBlock.IInteractiveTile;
import cd4017be.lib.block.AdvancedBlock.INeighborAwareTile;
import cd4017be.lib.tileentity.BaseTileEntity.ITickableServerOnly;
import cd4017be.lib.util.TooltipUtil;
import cd4017be.math.cplx.CplxF;
import net.minecraft.block.Block;
import net.minecraft.block.BlockFence;
import net.minecraft.entity.*;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.*;
import net.minecraft.util.math.*;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.world.chunk.Chunk;
|| Math.abs(px - lh.posX) + Math.abs(pz - lh.posZ) >= 0.25
|| e.getHealth() < e.getMaxHealth()
) continue;
CplxF str = ENTITY_STRENGTH.get(e.getClass());
if (str == null) continue;
double F = Math.copySign(str.r, lh.posY - py), dv = v * F / str.i - 0.5;
dv = Math.max(1.0 - 4.0 * dv * dv, 0);
if (e instanceof EntityAgeable) {
EntityAgeable ea = (EntityAgeable)e;
int age = ea.getGrowingAge();
if (age < -MAX_TIME) {
F = 0;
dv = 0;
} else {
if (age > 0) age = 0;
remT += Math.max(age + MAX_TIME, 0);
}
ea.setGrowingAge(age - (int)(CHECK_INTERVAL * (1.0 + dv)));
n++;
} else if (rand.nextFloat() < dv)
e.setHealth(e.getMaxHealth() * 0.5F);
acc.add(str);
force.F += F;
}
if (force.F != 0)
force.Fdv = -Math.abs(force.F * acc.r / acc.i);
if (n > 0) remT /= n;
}
@Override
| protected DynamicForce createForce(BlockRotaryTool block) {
|
CD4017BE/ThermokineticEngineering | src/java/cd4017be/kineng/recipe/ProcessingRecipes.java | // Path: src/java/cd4017be/kineng/tileentity/IKineticLink.java
// public interface IKineticLink extends IShaftPart {
//
// /** {@link #type()} bit-masks */
// public static final int T_TIER = 0xff, T_SHAPE = ~T_TIER;
// /** {@link #type()} standard shapes */
// public static final int
// T_ANGULAR = 0x000, T_BELT = 0x100, T_LINEAR = 0x200, T_MAGNETIC = 0x300,
// T_GRINDER = 0x400, T_SAWBLADE = 0x500;
//
// /**@return the link type as a {@link #T_SHAPE} with a {@link #T_TIER}.
// * Used to determine connection compatibility. */
// int type();
//
// ForceCon getCon(EnumFacing side);
//
// IForceProvider findLink(EnumFacing side);
//
// @Override
// default double setShaft(ShaftAxis shaft, double v0) {
// v0 = IShaftPart.super.setShaft(shaft, v0);
// for(EnumFacing side : EnumFacing.values()) {
// ForceCon con = getCon(side);
// if(con == null) continue;
// con.setShaft(shaft);
// if (shaft == null)
// con.link(null);
// }
// return v0;
// }
//
// @Override
// default void connect(boolean client) {
// if (invalid()) return;
// if (!client)
// for(EnumFacing side : VALUES)
// check(side);
// IShaftPart.super.connect(client);
// }
//
// default void check(EnumFacing side) {
// ForceCon con = getCon(side);
// if(con == null) return;
// IForceProvider fp = findLink(side);
// con.link(fp == null ? null : fp.connect(this, side.getOpposite()));
// }
//
// }
//
// Path: src/java/cd4017be/kineng/Main.java
// @Mod(modid = Main.ID, useMetadata = true)
// public class Main {
//
// public static final String ID = "kineng";
//
// @Instance(ID)
// public static Main instance;
//
// public static Logger LOG;
//
// @SidedProxy(clientSide = "cd4017be." + ID + ".ClientProxy", serverSide = "cd4017be." + ID + ".CommonProxy")
// public static CommonProxy proxy;
//
// public Main() {
// RecipeScriptContext.scriptRegistry.add(new Version("kinetic", "/assets/" + ID + "/config/recipes.rcp"));
// }
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// LOG = event.getModLog();
// proxy.preInit();
// StructureLocations.register();
// RecipeScriptContext.instance.run("kinetic.PRE_INIT");
// }
//
// @Mod.EventHandler
// public void load(FMLInitializationEvent event) {
// Objects.init();
// proxy.init(new ConfigConstants(RecipeScriptContext.instance.modules.get("kinetic")));
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// Ticking.init();
// }
//
// @Mod.EventHandler
// public void onShutdown(FMLServerStoppingEvent event) {
// Ticking.clear();
// }
//
// }
| import static cd4017be.kineng.tileentity.IKineticLink.*;
import java.util.*;
import java.util.function.*;
import cd4017be.api.recipes.RecipeAPI.IRecipeHandler;
import cd4017be.kineng.Main;
import cd4017be.lib.script.Parameters;
import cd4017be.lib.util.ItemKey;
import cd4017be.lib.util.OreDictStack;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.oredict.OreDictionary;
| }
public KineticRecipe get(ItemStack ing) {
KineticRecipe rcp = recipes.get(new ItemKey(ing));
if (rcp == null && ing.getHasSubtypes())
rcp = recipes.get(new ItemKey(new ItemStack(ing.getItem(), 1, OreDictionary.WILDCARD_VALUE)));
return rcp;
}
public void add(KineticRecipe rcp) {
recipes.put(new ItemKey(rcp.io[0]), rcp);
}
@Override
public void addRecipe(Parameters param) {
Object[] out = param.getArrayOrAll(4);
KineticRecipe rcp = new KineticRecipe(param.getNumber(3), param.getNumber(2), new ItemStack[out.length + 1]);
System.arraycopy(out, 0, rcp.io, 1, out.length);
Object o;
if (param.param[1] instanceof OreDictStack)
o = ((OreDictStack)param.param[1]).getItems();
else o = param.get(1);
for (Object e : o instanceof Object[] ? (Object[])o : new Object[] {o})
if (e instanceof ItemStack && !((ItemStack)e).isEmpty()) {
if (rcp.io[0] == null) rcp.io[0] = (ItemStack)e;
recipes.put(new ItemKey((ItemStack)e), rcp);
}
}
public String jeiName() {
| // Path: src/java/cd4017be/kineng/tileentity/IKineticLink.java
// public interface IKineticLink extends IShaftPart {
//
// /** {@link #type()} bit-masks */
// public static final int T_TIER = 0xff, T_SHAPE = ~T_TIER;
// /** {@link #type()} standard shapes */
// public static final int
// T_ANGULAR = 0x000, T_BELT = 0x100, T_LINEAR = 0x200, T_MAGNETIC = 0x300,
// T_GRINDER = 0x400, T_SAWBLADE = 0x500;
//
// /**@return the link type as a {@link #T_SHAPE} with a {@link #T_TIER}.
// * Used to determine connection compatibility. */
// int type();
//
// ForceCon getCon(EnumFacing side);
//
// IForceProvider findLink(EnumFacing side);
//
// @Override
// default double setShaft(ShaftAxis shaft, double v0) {
// v0 = IShaftPart.super.setShaft(shaft, v0);
// for(EnumFacing side : EnumFacing.values()) {
// ForceCon con = getCon(side);
// if(con == null) continue;
// con.setShaft(shaft);
// if (shaft == null)
// con.link(null);
// }
// return v0;
// }
//
// @Override
// default void connect(boolean client) {
// if (invalid()) return;
// if (!client)
// for(EnumFacing side : VALUES)
// check(side);
// IShaftPart.super.connect(client);
// }
//
// default void check(EnumFacing side) {
// ForceCon con = getCon(side);
// if(con == null) return;
// IForceProvider fp = findLink(side);
// con.link(fp == null ? null : fp.connect(this, side.getOpposite()));
// }
//
// }
//
// Path: src/java/cd4017be/kineng/Main.java
// @Mod(modid = Main.ID, useMetadata = true)
// public class Main {
//
// public static final String ID = "kineng";
//
// @Instance(ID)
// public static Main instance;
//
// public static Logger LOG;
//
// @SidedProxy(clientSide = "cd4017be." + ID + ".ClientProxy", serverSide = "cd4017be." + ID + ".CommonProxy")
// public static CommonProxy proxy;
//
// public Main() {
// RecipeScriptContext.scriptRegistry.add(new Version("kinetic", "/assets/" + ID + "/config/recipes.rcp"));
// }
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// LOG = event.getModLog();
// proxy.preInit();
// StructureLocations.register();
// RecipeScriptContext.instance.run("kinetic.PRE_INIT");
// }
//
// @Mod.EventHandler
// public void load(FMLInitializationEvent event) {
// Objects.init();
// proxy.init(new ConfigConstants(RecipeScriptContext.instance.modules.get("kinetic")));
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// Ticking.init();
// }
//
// @Mod.EventHandler
// public void onShutdown(FMLServerStoppingEvent event) {
// Ticking.clear();
// }
//
// }
// Path: src/java/cd4017be/kineng/recipe/ProcessingRecipes.java
import static cd4017be.kineng.tileentity.IKineticLink.*;
import java.util.*;
import java.util.function.*;
import cd4017be.api.recipes.RecipeAPI.IRecipeHandler;
import cd4017be.kineng.Main;
import cd4017be.lib.script.Parameters;
import cd4017be.lib.util.ItemKey;
import cd4017be.lib.util.OreDictStack;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.oredict.OreDictionary;
}
public KineticRecipe get(ItemStack ing) {
KineticRecipe rcp = recipes.get(new ItemKey(ing));
if (rcp == null && ing.getHasSubtypes())
rcp = recipes.get(new ItemKey(new ItemStack(ing.getItem(), 1, OreDictionary.WILDCARD_VALUE)));
return rcp;
}
public void add(KineticRecipe rcp) {
recipes.put(new ItemKey(rcp.io[0]), rcp);
}
@Override
public void addRecipe(Parameters param) {
Object[] out = param.getArrayOrAll(4);
KineticRecipe rcp = new KineticRecipe(param.getNumber(3), param.getNumber(2), new ItemStack[out.length + 1]);
System.arraycopy(out, 0, rcp.io, 1, out.length);
Object o;
if (param.param[1] instanceof OreDictStack)
o = ((OreDictStack)param.param[1]).getItems();
else o = param.get(1);
for (Object e : o instanceof Object[] ? (Object[])o : new Object[] {o})
if (e instanceof ItemStack && !((ItemStack)e).isEmpty()) {
if (rcp.io[0] == null) rcp.io[0] = (ItemStack)e;
recipes.put(new ItemKey((ItemStack)e), rcp);
}
}
public String jeiName() {
| return Main.ID + ":" + name;
|
CD4017BE/ThermokineticEngineering | src/java/cd4017be/kineng/tileentity/WaterWheel.java | // Path: src/java/cd4017be/kineng/physics/Ticking.java
// public static final double dt = 0.05;
//
// Path: src/java/cd4017be/kineng/block/BlockRotaryTool.java
// public class BlockRotaryTool extends BlockShaft {
//
// public double maxF;
// public final int type;
// public ItemStack scrap = ItemStack.EMPTY;
//
// /**
// * @param id
// * @param m
// * @param r
// * @param tile
// */
// public BlockRotaryTool(String id, ShaftMaterial m, int type, double r, Class<? extends TileEntity> tile) {
// super(id, m, r, tile);
// this.type = type;
// }
//
// @Override
// public double J(IBlockState state) {
// return J_dens;
// }
//
// @Override
// public double getDebris(IBlockState state, List<ItemStack> items) {
// items.add(shaftMat.scrap);
// items.add(scrap);
// return r;
// }
//
// public void setMaterials(ShaftMaterial mat, double r, double h) {
// J_dens = Formula.J_biCylinder(0.25, shaftMat.density, r, mat.density, h);
// av_max = Math.min(
// Formula.rip_vel(shaftMat.strength / shaftMat.density, 0.25),
// Formula.rip_vel(mat.strength / mat.density, r)
// );
// }
//
// @Override
// @SideOnly(Side.CLIENT)
// protected void addInformation(IBlockState state, List<String> tooltip, ITooltipFlag advanced) {
// super.addInformation(state, tooltip, advanced);
// tooltip.add(TooltipUtil.format("info.kineng.toolstats", radius(state), maxF));
// }
//
// }
| import static cd4017be.kineng.physics.Ticking.dt;
import static java.lang.Math.*;
import static net.minecraftforge.fluids.FluidRegistry.WATER;
import cd4017be.kineng.block.BlockRotaryTool;
import cd4017be.kineng.physics.*;
import cd4017be.lib.block.AdvancedBlock.IInteractiveTile;
import cd4017be.math.cplx.CplxD;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.text.TextComponentString;
import net.minecraftforge.fluids.*;
| package cd4017be.kineng.tileentity;
/**
* @author CD4017BE */
public class WaterWheel extends KineticMachine implements IWaterWheel, IInteractiveTile {
public static boolean WATER_ONLY = true;
double vsq;
@Override
public double passLiquid(double vsq, FluidStack liquid, EnumFacing dir) {
if (con == null || dir.getAxis() == axis()) return vsq;
if (WATER_ONLY && liquid.getFluid() != WATER) return vsq;
Wheel wheel = getForce();
int d = dir.ordinal();
wheel.add(
liquid.amount * liquid.getFluid().getDensity(liquid) * 0.001,
copySign(vsq, ((d ^ d << 1) & 2) - 1)
);
return min(wheel.vsq, vsq);
}
@Override
| // Path: src/java/cd4017be/kineng/physics/Ticking.java
// public static final double dt = 0.05;
//
// Path: src/java/cd4017be/kineng/block/BlockRotaryTool.java
// public class BlockRotaryTool extends BlockShaft {
//
// public double maxF;
// public final int type;
// public ItemStack scrap = ItemStack.EMPTY;
//
// /**
// * @param id
// * @param m
// * @param r
// * @param tile
// */
// public BlockRotaryTool(String id, ShaftMaterial m, int type, double r, Class<? extends TileEntity> tile) {
// super(id, m, r, tile);
// this.type = type;
// }
//
// @Override
// public double J(IBlockState state) {
// return J_dens;
// }
//
// @Override
// public double getDebris(IBlockState state, List<ItemStack> items) {
// items.add(shaftMat.scrap);
// items.add(scrap);
// return r;
// }
//
// public void setMaterials(ShaftMaterial mat, double r, double h) {
// J_dens = Formula.J_biCylinder(0.25, shaftMat.density, r, mat.density, h);
// av_max = Math.min(
// Formula.rip_vel(shaftMat.strength / shaftMat.density, 0.25),
// Formula.rip_vel(mat.strength / mat.density, r)
// );
// }
//
// @Override
// @SideOnly(Side.CLIENT)
// protected void addInformation(IBlockState state, List<String> tooltip, ITooltipFlag advanced) {
// super.addInformation(state, tooltip, advanced);
// tooltip.add(TooltipUtil.format("info.kineng.toolstats", radius(state), maxF));
// }
//
// }
// Path: src/java/cd4017be/kineng/tileentity/WaterWheel.java
import static cd4017be.kineng.physics.Ticking.dt;
import static java.lang.Math.*;
import static net.minecraftforge.fluids.FluidRegistry.WATER;
import cd4017be.kineng.block.BlockRotaryTool;
import cd4017be.kineng.physics.*;
import cd4017be.lib.block.AdvancedBlock.IInteractiveTile;
import cd4017be.math.cplx.CplxD;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.text.TextComponentString;
import net.minecraftforge.fluids.*;
package cd4017be.kineng.tileentity;
/**
* @author CD4017BE */
public class WaterWheel extends KineticMachine implements IWaterWheel, IInteractiveTile {
public static boolean WATER_ONLY = true;
double vsq;
@Override
public double passLiquid(double vsq, FluidStack liquid, EnumFacing dir) {
if (con == null || dir.getAxis() == axis()) return vsq;
if (WATER_ONLY && liquid.getFluid() != WATER) return vsq;
Wheel wheel = getForce();
int d = dir.ordinal();
wheel.add(
liquid.amount * liquid.getFluid().getDensity(liquid) * 0.001,
copySign(vsq, ((d ^ d << 1) & 2) - 1)
);
return min(wheel.vsq, vsq);
}
@Override
| protected DynamicForce createForce(BlockRotaryTool block) {
|
CD4017BE/ThermokineticEngineering | src/java/cd4017be/kineng/tileentity/WaterWheel.java | // Path: src/java/cd4017be/kineng/physics/Ticking.java
// public static final double dt = 0.05;
//
// Path: src/java/cd4017be/kineng/block/BlockRotaryTool.java
// public class BlockRotaryTool extends BlockShaft {
//
// public double maxF;
// public final int type;
// public ItemStack scrap = ItemStack.EMPTY;
//
// /**
// * @param id
// * @param m
// * @param r
// * @param tile
// */
// public BlockRotaryTool(String id, ShaftMaterial m, int type, double r, Class<? extends TileEntity> tile) {
// super(id, m, r, tile);
// this.type = type;
// }
//
// @Override
// public double J(IBlockState state) {
// return J_dens;
// }
//
// @Override
// public double getDebris(IBlockState state, List<ItemStack> items) {
// items.add(shaftMat.scrap);
// items.add(scrap);
// return r;
// }
//
// public void setMaterials(ShaftMaterial mat, double r, double h) {
// J_dens = Formula.J_biCylinder(0.25, shaftMat.density, r, mat.density, h);
// av_max = Math.min(
// Formula.rip_vel(shaftMat.strength / shaftMat.density, 0.25),
// Formula.rip_vel(mat.strength / mat.density, r)
// );
// }
//
// @Override
// @SideOnly(Side.CLIENT)
// protected void addInformation(IBlockState state, List<String> tooltip, ITooltipFlag advanced) {
// super.addInformation(state, tooltip, advanced);
// tooltip.add(TooltipUtil.format("info.kineng.toolstats", radius(state), maxF));
// }
//
// }
| import static cd4017be.kineng.physics.Ticking.dt;
import static java.lang.Math.*;
import static net.minecraftforge.fluids.FluidRegistry.WATER;
import cd4017be.kineng.block.BlockRotaryTool;
import cd4017be.kineng.physics.*;
import cd4017be.lib.block.AdvancedBlock.IInteractiveTile;
import cd4017be.math.cplx.CplxD;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.text.TextComponentString;
import net.minecraftforge.fluids.*;
| Wheel w = getForce();
player.sendStatusMessage(new TextComponentString(
String.format("%.0f mB/t @ %.1f m/s", w.p_m, sqrt(abs(w.p_Ekin / w.p_m)))
), true);
return true;
}
@Override
public void onClicked(EntityPlayer player) {}
static class Wheel extends DynamicForce {
double Ekin, m;
double p_Ekin, p_m, vsq;
void add(double m, double vsq) {
this.m += m;
this.Ekin += vsq * m;
}
@Override
public void work(double dE, double ds, double v) {
vsq = v * v;
p_Ekin = Ekin;
p_m = m;
Ekin = m = 0;
}
@Override
public ForceCon getM(CplxD M, double av) {
| // Path: src/java/cd4017be/kineng/physics/Ticking.java
// public static final double dt = 0.05;
//
// Path: src/java/cd4017be/kineng/block/BlockRotaryTool.java
// public class BlockRotaryTool extends BlockShaft {
//
// public double maxF;
// public final int type;
// public ItemStack scrap = ItemStack.EMPTY;
//
// /**
// * @param id
// * @param m
// * @param r
// * @param tile
// */
// public BlockRotaryTool(String id, ShaftMaterial m, int type, double r, Class<? extends TileEntity> tile) {
// super(id, m, r, tile);
// this.type = type;
// }
//
// @Override
// public double J(IBlockState state) {
// return J_dens;
// }
//
// @Override
// public double getDebris(IBlockState state, List<ItemStack> items) {
// items.add(shaftMat.scrap);
// items.add(scrap);
// return r;
// }
//
// public void setMaterials(ShaftMaterial mat, double r, double h) {
// J_dens = Formula.J_biCylinder(0.25, shaftMat.density, r, mat.density, h);
// av_max = Math.min(
// Formula.rip_vel(shaftMat.strength / shaftMat.density, 0.25),
// Formula.rip_vel(mat.strength / mat.density, r)
// );
// }
//
// @Override
// @SideOnly(Side.CLIENT)
// protected void addInformation(IBlockState state, List<String> tooltip, ITooltipFlag advanced) {
// super.addInformation(state, tooltip, advanced);
// tooltip.add(TooltipUtil.format("info.kineng.toolstats", radius(state), maxF));
// }
//
// }
// Path: src/java/cd4017be/kineng/tileentity/WaterWheel.java
import static cd4017be.kineng.physics.Ticking.dt;
import static java.lang.Math.*;
import static net.minecraftforge.fluids.FluidRegistry.WATER;
import cd4017be.kineng.block.BlockRotaryTool;
import cd4017be.kineng.physics.*;
import cd4017be.lib.block.AdvancedBlock.IInteractiveTile;
import cd4017be.math.cplx.CplxD;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.text.TextComponentString;
import net.minecraftforge.fluids.*;
Wheel w = getForce();
player.sendStatusMessage(new TextComponentString(
String.format("%.0f mB/t @ %.1f m/s", w.p_m, sqrt(abs(w.p_Ekin / w.p_m)))
), true);
return true;
}
@Override
public void onClicked(EntityPlayer player) {}
static class Wheel extends DynamicForce {
double Ekin, m;
double p_Ekin, p_m, vsq;
void add(double m, double vsq) {
this.m += m;
this.Ekin += vsq * m;
}
@Override
public void work(double dE, double ds, double v) {
vsq = v * v;
p_Ekin = Ekin;
p_m = m;
Ekin = m = 0;
}
@Override
public ForceCon getM(CplxD M, double av) {
| Fdv = -0.5 * m / dt;
|
CD4017BE/ThermokineticEngineering | src/java/cd4017be/kineng/tileentity/Tachometer.java | // Path: src/java/cd4017be/kineng/Main.java
// @Mod(modid = Main.ID, useMetadata = true)
// public class Main {
//
// public static final String ID = "kineng";
//
// @Instance(ID)
// public static Main instance;
//
// public static Logger LOG;
//
// @SidedProxy(clientSide = "cd4017be." + ID + ".ClientProxy", serverSide = "cd4017be." + ID + ".CommonProxy")
// public static CommonProxy proxy;
//
// public Main() {
// RecipeScriptContext.scriptRegistry.add(new Version("kinetic", "/assets/" + ID + "/config/recipes.rcp"));
// }
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// LOG = event.getModLog();
// proxy.preInit();
// StructureLocations.register();
// RecipeScriptContext.instance.run("kinetic.PRE_INIT");
// }
//
// @Mod.EventHandler
// public void load(FMLInitializationEvent event) {
// Objects.init();
// proxy.init(new ConfigConstants(RecipeScriptContext.instance.modules.get("kinetic")));
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// Ticking.init();
// }
//
// @Mod.EventHandler
// public void onShutdown(FMLServerStoppingEvent event) {
// Ticking.clear();
// }
//
// }
| import static cd4017be.lib.network.Sync.GUI;
import cd4017be.kineng.Main;
import cd4017be.lib.Gui.AdvancedContainer;
import cd4017be.lib.Gui.AdvancedContainer.IStateInteractionHandler;
import cd4017be.lib.Gui.ModularGui;
import cd4017be.lib.Gui.comp.*;
import cd4017be.lib.block.AdvancedBlock.IRedstoneTile;
import cd4017be.lib.network.*;
import cd4017be.lib.tileentity.BaseTileEntity.ITickableServerOnly;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
| package cd4017be.kineng.tileentity;
/**
* @author CD4017BE */
public class Tachometer extends ShaftPart
implements ITickableServerOnly, IRedstoneTile, IGuiHandlerTile, IStateInteractionHandler {
public @Sync(to=SAVE|GUI, tag="ref") float refV = 1F;
public @Sync(to=GUI) float v;
public @Sync(to=SAVE|GUI, tag="rs") int lastRS;
@Override
public void update() {
if (shaft == null) return;
v = (float)shaft.av();
int rs = Math.round(v / refV);
if (rs != lastRS) {
lastRS = rs;
world.notifyNeighborsOfStateChange(pos, blockType, false);
}
}
@Override
public int redstoneLevel(EnumFacing side, boolean strong) {
return strong ? 0 : lastRS;
}
@Override
public boolean connectRedstone(EnumFacing side) {
return true;
}
@Override
public AdvancedContainer getContainer(EntityPlayer player, int id) {
return new AdvancedContainer(this, StateSyncAdv.of(false, this), player);
}
| // Path: src/java/cd4017be/kineng/Main.java
// @Mod(modid = Main.ID, useMetadata = true)
// public class Main {
//
// public static final String ID = "kineng";
//
// @Instance(ID)
// public static Main instance;
//
// public static Logger LOG;
//
// @SidedProxy(clientSide = "cd4017be." + ID + ".ClientProxy", serverSide = "cd4017be." + ID + ".CommonProxy")
// public static CommonProxy proxy;
//
// public Main() {
// RecipeScriptContext.scriptRegistry.add(new Version("kinetic", "/assets/" + ID + "/config/recipes.rcp"));
// }
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// LOG = event.getModLog();
// proxy.preInit();
// StructureLocations.register();
// RecipeScriptContext.instance.run("kinetic.PRE_INIT");
// }
//
// @Mod.EventHandler
// public void load(FMLInitializationEvent event) {
// Objects.init();
// proxy.init(new ConfigConstants(RecipeScriptContext.instance.modules.get("kinetic")));
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// Ticking.init();
// }
//
// @Mod.EventHandler
// public void onShutdown(FMLServerStoppingEvent event) {
// Ticking.clear();
// }
//
// }
// Path: src/java/cd4017be/kineng/tileentity/Tachometer.java
import static cd4017be.lib.network.Sync.GUI;
import cd4017be.kineng.Main;
import cd4017be.lib.Gui.AdvancedContainer;
import cd4017be.lib.Gui.AdvancedContainer.IStateInteractionHandler;
import cd4017be.lib.Gui.ModularGui;
import cd4017be.lib.Gui.comp.*;
import cd4017be.lib.block.AdvancedBlock.IRedstoneTile;
import cd4017be.lib.network.*;
import cd4017be.lib.tileentity.BaseTileEntity.ITickableServerOnly;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
package cd4017be.kineng.tileentity;
/**
* @author CD4017BE */
public class Tachometer extends ShaftPart
implements ITickableServerOnly, IRedstoneTile, IGuiHandlerTile, IStateInteractionHandler {
public @Sync(to=SAVE|GUI, tag="ref") float refV = 1F;
public @Sync(to=GUI) float v;
public @Sync(to=SAVE|GUI, tag="rs") int lastRS;
@Override
public void update() {
if (shaft == null) return;
v = (float)shaft.av();
int rs = Math.round(v / refV);
if (rs != lastRS) {
lastRS = rs;
world.notifyNeighborsOfStateChange(pos, blockType, false);
}
}
@Override
public int redstoneLevel(EnumFacing side, boolean strong) {
return strong ? 0 : lastRS;
}
@Override
public boolean connectRedstone(EnumFacing side) {
return true;
}
@Override
public AdvancedContainer getContainer(EntityPlayer player, int id) {
return new AdvancedContainer(this, StateSyncAdv.of(false, this), player);
}
| private static final ResourceLocation GUI_TEX = new ResourceLocation(Main.ID, "textures/gui/debug.png");
|
CD4017BE/ThermokineticEngineering | src/java/cd4017be/kineng/tileentity/MechanicalDebug.java | // Path: src/java/cd4017be/kineng/physics/Ticking.java
// public static final double dt = 0.05;
//
// Path: src/java/cd4017be/kineng/Main.java
// @Mod(modid = Main.ID, useMetadata = true)
// public class Main {
//
// public static final String ID = "kineng";
//
// @Instance(ID)
// public static Main instance;
//
// public static Logger LOG;
//
// @SidedProxy(clientSide = "cd4017be." + ID + ".ClientProxy", serverSide = "cd4017be." + ID + ".CommonProxy")
// public static CommonProxy proxy;
//
// public Main() {
// RecipeScriptContext.scriptRegistry.add(new Version("kinetic", "/assets/" + ID + "/config/recipes.rcp"));
// }
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// LOG = event.getModLog();
// proxy.preInit();
// StructureLocations.register();
// RecipeScriptContext.instance.run("kinetic.PRE_INIT");
// }
//
// @Mod.EventHandler
// public void load(FMLInitializationEvent event) {
// Objects.init();
// proxy.init(new ConfigConstants(RecipeScriptContext.instance.modules.get("kinetic")));
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// Ticking.init();
// }
//
// @Mod.EventHandler
// public void onShutdown(FMLServerStoppingEvent event) {
// Ticking.clear();
// }
//
// }
| import static cd4017be.kineng.physics.Ticking.dt;
import static cd4017be.lib.network.Sync.GUI;
import cd4017be.kineng.Main;
import cd4017be.kineng.physics.*;
import cd4017be.lib.Gui.AdvancedContainer;
import cd4017be.lib.Gui.AdvancedContainer.IStateInteractionHandler;
import cd4017be.lib.Gui.ModularGui;
import cd4017be.lib.Gui.comp.*;
import cd4017be.lib.network.*;
import cd4017be.math.cplx.CplxD;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.*;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
| @Sync public void mode(byte mode) {
if (mode == this.mode) return;
this.mode = mode;
if (world != null && world.isRemote) return;
switch(mode) {
case A_CONST_PWR:
con.link(new ConstPower());
break;
case A_CONST_VEL:
con.link(new ConstSpeed());
break;
case A_FRICTION:
con.link(new Friction());
break;
default:
con.link(null);
}
}
@Override
public double setShaft(ShaftAxis shaft) {
con.setShaft(shaft);
return super.setShaft(shaft);
}
@Override
public AdvancedContainer getContainer(EntityPlayer player, int id) {
return new AdvancedContainer(this, StateSyncAdv.of(false, this), player);
}
| // Path: src/java/cd4017be/kineng/physics/Ticking.java
// public static final double dt = 0.05;
//
// Path: src/java/cd4017be/kineng/Main.java
// @Mod(modid = Main.ID, useMetadata = true)
// public class Main {
//
// public static final String ID = "kineng";
//
// @Instance(ID)
// public static Main instance;
//
// public static Logger LOG;
//
// @SidedProxy(clientSide = "cd4017be." + ID + ".ClientProxy", serverSide = "cd4017be." + ID + ".CommonProxy")
// public static CommonProxy proxy;
//
// public Main() {
// RecipeScriptContext.scriptRegistry.add(new Version("kinetic", "/assets/" + ID + "/config/recipes.rcp"));
// }
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// LOG = event.getModLog();
// proxy.preInit();
// StructureLocations.register();
// RecipeScriptContext.instance.run("kinetic.PRE_INIT");
// }
//
// @Mod.EventHandler
// public void load(FMLInitializationEvent event) {
// Objects.init();
// proxy.init(new ConfigConstants(RecipeScriptContext.instance.modules.get("kinetic")));
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// Ticking.init();
// }
//
// @Mod.EventHandler
// public void onShutdown(FMLServerStoppingEvent event) {
// Ticking.clear();
// }
//
// }
// Path: src/java/cd4017be/kineng/tileentity/MechanicalDebug.java
import static cd4017be.kineng.physics.Ticking.dt;
import static cd4017be.lib.network.Sync.GUI;
import cd4017be.kineng.Main;
import cd4017be.kineng.physics.*;
import cd4017be.lib.Gui.AdvancedContainer;
import cd4017be.lib.Gui.AdvancedContainer.IStateInteractionHandler;
import cd4017be.lib.Gui.ModularGui;
import cd4017be.lib.Gui.comp.*;
import cd4017be.lib.network.*;
import cd4017be.math.cplx.CplxD;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.*;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@Sync public void mode(byte mode) {
if (mode == this.mode) return;
this.mode = mode;
if (world != null && world.isRemote) return;
switch(mode) {
case A_CONST_PWR:
con.link(new ConstPower());
break;
case A_CONST_VEL:
con.link(new ConstSpeed());
break;
case A_FRICTION:
con.link(new Friction());
break;
default:
con.link(null);
}
}
@Override
public double setShaft(ShaftAxis shaft) {
con.setShaft(shaft);
return super.setShaft(shaft);
}
@Override
public AdvancedContainer getContainer(EntityPlayer player, int id) {
return new AdvancedContainer(this, StateSyncAdv.of(false, this), player);
}
| private static final ResourceLocation GUI_TEX = new ResourceLocation(Main.ID, "textures/gui/debug.png");
|
CD4017BE/ThermokineticEngineering | src/java/cd4017be/kineng/tileentity/MechanicalDebug.java | // Path: src/java/cd4017be/kineng/physics/Ticking.java
// public static final double dt = 0.05;
//
// Path: src/java/cd4017be/kineng/Main.java
// @Mod(modid = Main.ID, useMetadata = true)
// public class Main {
//
// public static final String ID = "kineng";
//
// @Instance(ID)
// public static Main instance;
//
// public static Logger LOG;
//
// @SidedProxy(clientSide = "cd4017be." + ID + ".ClientProxy", serverSide = "cd4017be." + ID + ".CommonProxy")
// public static CommonProxy proxy;
//
// public Main() {
// RecipeScriptContext.scriptRegistry.add(new Version("kinetic", "/assets/" + ID + "/config/recipes.rcp"));
// }
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// LOG = event.getModLog();
// proxy.preInit();
// StructureLocations.register();
// RecipeScriptContext.instance.run("kinetic.PRE_INIT");
// }
//
// @Mod.EventHandler
// public void load(FMLInitializationEvent event) {
// Objects.init();
// proxy.init(new ConfigConstants(RecipeScriptContext.instance.modules.get("kinetic")));
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// Ticking.init();
// }
//
// @Mod.EventHandler
// public void onShutdown(FMLServerStoppingEvent event) {
// Ticking.clear();
// }
//
// }
| import static cd4017be.kineng.physics.Ticking.dt;
import static cd4017be.lib.network.Sync.GUI;
import cd4017be.kineng.Main;
import cd4017be.kineng.physics.*;
import cd4017be.lib.Gui.AdvancedContainer;
import cd4017be.lib.Gui.AdvancedContainer.IStateInteractionHandler;
import cd4017be.lib.Gui.ModularGui;
import cd4017be.lib.Gui.comp.*;
import cd4017be.lib.network.*;
import cd4017be.math.cplx.CplxD;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.*;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
| c0 = 0F; //target speed [m/s]
c1 = 0F; //strength [N*s/m]
con.link(new ConstSpeed());
break;
case A_FRICTION:
if (con.force instanceof Friction) break;
mode = a;
c0 = 0F; //friction force [N]
c1 = 0.01F; //null velocity [m/s]
con.link(new Friction());
break;
case A_C0:
c0 = pkt.readFloat();
break;
case A_C1:
c1 = pkt.readFloat();
break;
case A_RESET:
Eacc = 0;
break;
}
}
private class ConstPower extends DynamicForce {
/** [J] */
public double E;
@Override
public void work(double dE, double ds, double v1) {
| // Path: src/java/cd4017be/kineng/physics/Ticking.java
// public static final double dt = 0.05;
//
// Path: src/java/cd4017be/kineng/Main.java
// @Mod(modid = Main.ID, useMetadata = true)
// public class Main {
//
// public static final String ID = "kineng";
//
// @Instance(ID)
// public static Main instance;
//
// public static Logger LOG;
//
// @SidedProxy(clientSide = "cd4017be." + ID + ".ClientProxy", serverSide = "cd4017be." + ID + ".CommonProxy")
// public static CommonProxy proxy;
//
// public Main() {
// RecipeScriptContext.scriptRegistry.add(new Version("kinetic", "/assets/" + ID + "/config/recipes.rcp"));
// }
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// LOG = event.getModLog();
// proxy.preInit();
// StructureLocations.register();
// RecipeScriptContext.instance.run("kinetic.PRE_INIT");
// }
//
// @Mod.EventHandler
// public void load(FMLInitializationEvent event) {
// Objects.init();
// proxy.init(new ConfigConstants(RecipeScriptContext.instance.modules.get("kinetic")));
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// Ticking.init();
// }
//
// @Mod.EventHandler
// public void onShutdown(FMLServerStoppingEvent event) {
// Ticking.clear();
// }
//
// }
// Path: src/java/cd4017be/kineng/tileentity/MechanicalDebug.java
import static cd4017be.kineng.physics.Ticking.dt;
import static cd4017be.lib.network.Sync.GUI;
import cd4017be.kineng.Main;
import cd4017be.kineng.physics.*;
import cd4017be.lib.Gui.AdvancedContainer;
import cd4017be.lib.Gui.AdvancedContainer.IStateInteractionHandler;
import cd4017be.lib.Gui.ModularGui;
import cd4017be.lib.Gui.comp.*;
import cd4017be.lib.network.*;
import cd4017be.math.cplx.CplxD;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.*;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
c0 = 0F; //target speed [m/s]
c1 = 0F; //strength [N*s/m]
con.link(new ConstSpeed());
break;
case A_FRICTION:
if (con.force instanceof Friction) break;
mode = a;
c0 = 0F; //friction force [N]
c1 = 0.01F; //null velocity [m/s]
con.link(new Friction());
break;
case A_C0:
c0 = pkt.readFloat();
break;
case A_C1:
c1 = pkt.readFloat();
break;
case A_RESET:
Eacc = 0;
break;
}
}
private class ConstPower extends DynamicForce {
/** [J] */
public double E;
@Override
public void work(double dE, double ds, double v1) {
| E += c0 * dt - dE;
|
CD4017BE/ThermokineticEngineering | src/java/cd4017be/kineng/tileentity/KineticMachine.java | // Path: src/java/cd4017be/kineng/block/BlockRotaryTool.java
// public class BlockRotaryTool extends BlockShaft {
//
// public double maxF;
// public final int type;
// public ItemStack scrap = ItemStack.EMPTY;
//
// /**
// * @param id
// * @param m
// * @param r
// * @param tile
// */
// public BlockRotaryTool(String id, ShaftMaterial m, int type, double r, Class<? extends TileEntity> tile) {
// super(id, m, r, tile);
// this.type = type;
// }
//
// @Override
// public double J(IBlockState state) {
// return J_dens;
// }
//
// @Override
// public double getDebris(IBlockState state, List<ItemStack> items) {
// items.add(shaftMat.scrap);
// items.add(scrap);
// return r;
// }
//
// public void setMaterials(ShaftMaterial mat, double r, double h) {
// J_dens = Formula.J_biCylinder(0.25, shaftMat.density, r, mat.density, h);
// av_max = Math.min(
// Formula.rip_vel(shaftMat.strength / shaftMat.density, 0.25),
// Formula.rip_vel(mat.strength / mat.density, r)
// );
// }
//
// @Override
// @SideOnly(Side.CLIENT)
// protected void addInformation(IBlockState state, List<String> tooltip, ITooltipFlag advanced) {
// super.addInformation(state, tooltip, advanced);
// tooltip.add(TooltipUtil.format("info.kineng.toolstats", radius(state), maxF));
// }
//
// }
| import cd4017be.kineng.block.BlockRotaryTool;
import cd4017be.kineng.physics.*;
| package cd4017be.kineng.tileentity;
/**
* @author CD4017BE */
public abstract class KineticMachine extends ShaftPart {
protected ForceCon con;
@Override
public double setShaft(ShaftAxis shaft, double v0) {
if (con == null && shaft != null) {
| // Path: src/java/cd4017be/kineng/block/BlockRotaryTool.java
// public class BlockRotaryTool extends BlockShaft {
//
// public double maxF;
// public final int type;
// public ItemStack scrap = ItemStack.EMPTY;
//
// /**
// * @param id
// * @param m
// * @param r
// * @param tile
// */
// public BlockRotaryTool(String id, ShaftMaterial m, int type, double r, Class<? extends TileEntity> tile) {
// super(id, m, r, tile);
// this.type = type;
// }
//
// @Override
// public double J(IBlockState state) {
// return J_dens;
// }
//
// @Override
// public double getDebris(IBlockState state, List<ItemStack> items) {
// items.add(shaftMat.scrap);
// items.add(scrap);
// return r;
// }
//
// public void setMaterials(ShaftMaterial mat, double r, double h) {
// J_dens = Formula.J_biCylinder(0.25, shaftMat.density, r, mat.density, h);
// av_max = Math.min(
// Formula.rip_vel(shaftMat.strength / shaftMat.density, 0.25),
// Formula.rip_vel(mat.strength / mat.density, r)
// );
// }
//
// @Override
// @SideOnly(Side.CLIENT)
// protected void addInformation(IBlockState state, List<String> tooltip, ITooltipFlag advanced) {
// super.addInformation(state, tooltip, advanced);
// tooltip.add(TooltipUtil.format("info.kineng.toolstats", radius(state), maxF));
// }
//
// }
// Path: src/java/cd4017be/kineng/tileentity/KineticMachine.java
import cd4017be.kineng.block.BlockRotaryTool;
import cd4017be.kineng.physics.*;
package cd4017be.kineng.tileentity;
/**
* @author CD4017BE */
public abstract class KineticMachine extends ShaftPart {
protected ForceCon con;
@Override
public double setShaft(ShaftAxis shaft, double v0) {
if (con == null && shaft != null) {
| BlockRotaryTool block = block();
|
cqyijifu/OpenFalcon-SuitAgent | src/main/java/com/yiji/falcon/agent/jmx/vo/JMXMetricsValueInfo.java | // Path: src/main/java/com/yiji/falcon/agent/vo/jmx/JMXMetricsConfiguration.java
// @Getter
// @Setter
// @ToString
// public class JMXMetricsConfiguration {
//
// private String objectName;
// private String metrics;
// private String valueExpress;
// private String alias;
// private String counterType;
// private String tag;
// private boolean hasCollect = false;
//
// }
| import com.yiji.falcon.agent.vo.jmx.JMXMetricsConfiguration;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.List;
import java.util.Set; | /*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
package com.yiji.falcon.agent.jmx.vo;
/*
* 修订记录:
* [email protected] 2016-06-22 17:48 创建
*/
/**
* JMX mBean值的info类
* @author [email protected]
*/
@Getter
@Setter
@ToString
public class JMXMetricsValueInfo {
private long timestamp;
/**
* 需要监控的配置项
*/ | // Path: src/main/java/com/yiji/falcon/agent/vo/jmx/JMXMetricsConfiguration.java
// @Getter
// @Setter
// @ToString
// public class JMXMetricsConfiguration {
//
// private String objectName;
// private String metrics;
// private String valueExpress;
// private String alias;
// private String counterType;
// private String tag;
// private boolean hasCollect = false;
//
// }
// Path: src/main/java/com/yiji/falcon/agent/jmx/vo/JMXMetricsValueInfo.java
import com.yiji.falcon.agent.vo.jmx.JMXMetricsConfiguration;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.List;
import java.util.Set;
/*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
package com.yiji.falcon.agent.jmx.vo;
/*
* 修订记录:
* [email protected] 2016-06-22 17:48 创建
*/
/**
* JMX mBean值的info类
* @author [email protected]
*/
@Getter
@Setter
@ToString
public class JMXMetricsValueInfo {
private long timestamp;
/**
* 需要监控的配置项
*/ | Set<JMXMetricsConfiguration> jmxMetricsConfigurations; |
cqyijifu/OpenFalcon-SuitAgent | src/main/java/com/yiji/falcon/agent/plugins/Plugin.java | // Path: src/main/java/com/yiji/falcon/agent/plugins/util/PluginActivateType.java
// public enum PluginActivateType {
// /**
// * 插件不运行
// */
// DISABLED("不启用"),
// /**
// * 无论服务是否运行,都启动插件
// */
// FORCE("强制启动"),
// /**
// * 当监控服务可用时,自动进行插件启动
// */
// AUTO("自动运行");
//
// /**
// * 活动描述
// */
// private String desc;
//
// PluginActivateType(String desc) {
// this.desc = desc;
// }
//
// public String getDesc() {
// return desc;
// }
// }
| import com.yiji.falcon.agent.plugins.util.PluginActivateType;
import java.util.Map; | /*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
package com.yiji.falcon.agent.plugins;
/*
* 修订记录:
* [email protected] 2016-06-23 16:56 创建
*/
/**
* @author [email protected]
*/
public interface Plugin {
/**
* 插件初始化操作
* 该方法将会在插件运行前进行调用
* @param properties
* 包含的配置:
* 1、插件目录绝对路径的(key 为 pluginDir),可利用此属性进行插件自定制资源文件读取
* 2、插件指定的配置文件的全部配置信息(参见 {@link com.yiji.falcon.agent.plugins.Plugin#configFileName()} 接口项)
* 3、授权配置项(参见 {@link com.yiji.falcon.agent.plugins.Plugin#authorizationKeyPrefix()} 接口项
*/
void init(Map<String,String> properties);
/**
* 插件名
* 默认为插件的简单类名
* @return
*/
default String pluginName(){
return this.getClass().getSimpleName();
}
/**
* 该插件在指定插件配置目录下的配置文件名
* @return
* 返回该插件对应的配置文件名
* 默认值:插件简单类名第一个字母小写 加 .properties 后缀
*/
default String configFileName(){
String className = this.getClass().getSimpleName();
return className.substring(0,1).toLowerCase() + className.substring(1) + ".properties";
}
/**
* 授权登陆配置的key前缀(配置在authorization.properties文件中)
* 将会通过init方法的map属性中,将符合该插件的授权配置传入,以供插件进行初始化操作
*
* 如 authorizationKeyPrefix = authorization.prefix , 并且在配置文件中配置了如下信息:
* authorization.prefix.xxx1 = xxx1
* authorization.prefix.xxx2 = xxx2
* 则init中的map中将会传入该KV:
* authorization.prefix.xxx1 : xxx1
* authorization.prefix.xxx2 : xxx2
*
* @return
* 若不覆盖此方法,默认返回空,既该插件无需授权配置
*/
default String authorizationKeyPrefix(){
return "";
}
/**
* 该插件监控的服务名
* 该服务名会上报到Falcon监控值的tag(service)中,可用于区分监控值服务
* @return
*/
String serverName();
/**
* 监控值的获取和上报周期(秒)
* @return
*/
int step();
/**
* 插件运行方式
* @return
*/ | // Path: src/main/java/com/yiji/falcon/agent/plugins/util/PluginActivateType.java
// public enum PluginActivateType {
// /**
// * 插件不运行
// */
// DISABLED("不启用"),
// /**
// * 无论服务是否运行,都启动插件
// */
// FORCE("强制启动"),
// /**
// * 当监控服务可用时,自动进行插件启动
// */
// AUTO("自动运行");
//
// /**
// * 活动描述
// */
// private String desc;
//
// PluginActivateType(String desc) {
// this.desc = desc;
// }
//
// public String getDesc() {
// return desc;
// }
// }
// Path: src/main/java/com/yiji/falcon/agent/plugins/Plugin.java
import com.yiji.falcon.agent.plugins.util.PluginActivateType;
import java.util.Map;
/*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
package com.yiji.falcon.agent.plugins;
/*
* 修订记录:
* [email protected] 2016-06-23 16:56 创建
*/
/**
* @author [email protected]
*/
public interface Plugin {
/**
* 插件初始化操作
* 该方法将会在插件运行前进行调用
* @param properties
* 包含的配置:
* 1、插件目录绝对路径的(key 为 pluginDir),可利用此属性进行插件自定制资源文件读取
* 2、插件指定的配置文件的全部配置信息(参见 {@link com.yiji.falcon.agent.plugins.Plugin#configFileName()} 接口项)
* 3、授权配置项(参见 {@link com.yiji.falcon.agent.plugins.Plugin#authorizationKeyPrefix()} 接口项
*/
void init(Map<String,String> properties);
/**
* 插件名
* 默认为插件的简单类名
* @return
*/
default String pluginName(){
return this.getClass().getSimpleName();
}
/**
* 该插件在指定插件配置目录下的配置文件名
* @return
* 返回该插件对应的配置文件名
* 默认值:插件简单类名第一个字母小写 加 .properties 后缀
*/
default String configFileName(){
String className = this.getClass().getSimpleName();
return className.substring(0,1).toLowerCase() + className.substring(1) + ".properties";
}
/**
* 授权登陆配置的key前缀(配置在authorization.properties文件中)
* 将会通过init方法的map属性中,将符合该插件的授权配置传入,以供插件进行初始化操作
*
* 如 authorizationKeyPrefix = authorization.prefix , 并且在配置文件中配置了如下信息:
* authorization.prefix.xxx1 = xxx1
* authorization.prefix.xxx2 = xxx2
* 则init中的map中将会传入该KV:
* authorization.prefix.xxx1 : xxx1
* authorization.prefix.xxx2 : xxx2
*
* @return
* 若不覆盖此方法,默认返回空,既该插件无需授权配置
*/
default String authorizationKeyPrefix(){
return "";
}
/**
* 该插件监控的服务名
* 该服务名会上报到Falcon监控值的tag(service)中,可用于区分监控值服务
* @return
*/
String serverName();
/**
* 监控值的获取和上报周期(秒)
* @return
*/
int step();
/**
* 插件运行方式
* @return
*/ | PluginActivateType activateType(); |
cqyijifu/OpenFalcon-SuitAgent | src/main/java/com/yiji/falcon/agent/jmx/JMXConnectWithTimeout.java | // Path: src/main/java/com/yiji/falcon/agent/util/BlockingQueueUtil.java
// public class BlockingQueueUtil {
//
// /**
// * 获取结果
// * @param blockingQueue
// * @param timeout
// * @param unit
// * @return
// * @throws InterruptedIOException
// */
// public static Object getResult(BlockingQueue<Object> blockingQueue,long timeout, TimeUnit unit) throws InterruptedIOException {
// Object result;
// try {
// result = blockingQueue.poll(timeout, unit);
// if (result == null) {
// if (!blockingQueue.offer(""))
// result = blockingQueue.take();
// }
// } catch (InterruptedException e) {
// throw ExceptionUtil.initCause(new InterruptedIOException(e.getMessage()), e);
// }
// return result;
// }
//
// }
//
// Path: src/main/java/com/yiji/falcon/agent/util/ExecuteThreadUtil.java
// public class ExecuteThreadUtil {
// private static ExecutorService executorService;
//
// static {
// final int maxPoolSize = AgentConfiguration.INSTANCE.getAgentMaxThreadCount();
// //定义并发执行服务
// executorService = new ThreadPoolExecutor(5, maxPoolSize, 0L, TimeUnit.MILLISECONDS,
// new SynchronousQueue<>(),
// r -> {
// Thread t = new Thread(r);
// t.setName("agentThreadPool");
// return t;
// },new ThreadPoolExecutor.DiscardOldestPolicy()
// );
// }
//
// /**
// * 执行线程任务
// *
// * @param task
// */
// public static void execute(Runnable task) {
// executorService.submit(task);
// }
//
// /**
// * 执行线程任务
// *
// * @param task
// * @param <T>
// * @return
// */
// public static <T> Future<T> execute(Callable<T> task) {
// return executorService.submit(task);
// }
//
// /**
// * 关闭线程池
// */
// public static void shutdown() {
// executorService.shutdown();
// }
// }
| import com.yiji.falcon.agent.util.BlockingQueueUtil;
import com.yiji.falcon.agent.util.ExecuteThreadUtil;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit; | /*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
package com.yiji.falcon.agent.jmx;
/*
* 修订记录:
* [email protected] 2016-08-09 10:25 创建
*/
/**
* @author [email protected]
*/
public class JMXConnectWithTimeout {
/**
* JMX连接
* @param url
* JMX连接地址
* @param jmxUser
* JMX授权用户 null为无授权用户
* @param jmxPassword
* JMX授权密码 null为无授权密码
* @param timeout
* 超时时间
* @param unit
* 超时单位
* @return
* @throws IOException
*/
public static JMXConnector connectWithTimeout( final JMXServiceURL url,String jmxUser,String jmxPassword, long timeout, TimeUnit unit) throws Exception {
final BlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(1); | // Path: src/main/java/com/yiji/falcon/agent/util/BlockingQueueUtil.java
// public class BlockingQueueUtil {
//
// /**
// * 获取结果
// * @param blockingQueue
// * @param timeout
// * @param unit
// * @return
// * @throws InterruptedIOException
// */
// public static Object getResult(BlockingQueue<Object> blockingQueue,long timeout, TimeUnit unit) throws InterruptedIOException {
// Object result;
// try {
// result = blockingQueue.poll(timeout, unit);
// if (result == null) {
// if (!blockingQueue.offer(""))
// result = blockingQueue.take();
// }
// } catch (InterruptedException e) {
// throw ExceptionUtil.initCause(new InterruptedIOException(e.getMessage()), e);
// }
// return result;
// }
//
// }
//
// Path: src/main/java/com/yiji/falcon/agent/util/ExecuteThreadUtil.java
// public class ExecuteThreadUtil {
// private static ExecutorService executorService;
//
// static {
// final int maxPoolSize = AgentConfiguration.INSTANCE.getAgentMaxThreadCount();
// //定义并发执行服务
// executorService = new ThreadPoolExecutor(5, maxPoolSize, 0L, TimeUnit.MILLISECONDS,
// new SynchronousQueue<>(),
// r -> {
// Thread t = new Thread(r);
// t.setName("agentThreadPool");
// return t;
// },new ThreadPoolExecutor.DiscardOldestPolicy()
// );
// }
//
// /**
// * 执行线程任务
// *
// * @param task
// */
// public static void execute(Runnable task) {
// executorService.submit(task);
// }
//
// /**
// * 执行线程任务
// *
// * @param task
// * @param <T>
// * @return
// */
// public static <T> Future<T> execute(Callable<T> task) {
// return executorService.submit(task);
// }
//
// /**
// * 关闭线程池
// */
// public static void shutdown() {
// executorService.shutdown();
// }
// }
// Path: src/main/java/com/yiji/falcon/agent/jmx/JMXConnectWithTimeout.java
import com.yiji.falcon.agent.util.BlockingQueueUtil;
import com.yiji.falcon.agent.util.ExecuteThreadUtil;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
/*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
package com.yiji.falcon.agent.jmx;
/*
* 修订记录:
* [email protected] 2016-08-09 10:25 创建
*/
/**
* @author [email protected]
*/
public class JMXConnectWithTimeout {
/**
* JMX连接
* @param url
* JMX连接地址
* @param jmxUser
* JMX授权用户 null为无授权用户
* @param jmxPassword
* JMX授权密码 null为无授权密码
* @param timeout
* 超时时间
* @param unit
* 超时单位
* @return
* @throws IOException
*/
public static JMXConnector connectWithTimeout( final JMXServiceURL url,String jmxUser,String jmxPassword, long timeout, TimeUnit unit) throws Exception {
final BlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(1); | ExecuteThreadUtil.execute(() -> { |
cqyijifu/OpenFalcon-SuitAgent | src/main/java/com/yiji/falcon/agent/jmx/JMXConnectWithTimeout.java | // Path: src/main/java/com/yiji/falcon/agent/util/BlockingQueueUtil.java
// public class BlockingQueueUtil {
//
// /**
// * 获取结果
// * @param blockingQueue
// * @param timeout
// * @param unit
// * @return
// * @throws InterruptedIOException
// */
// public static Object getResult(BlockingQueue<Object> blockingQueue,long timeout, TimeUnit unit) throws InterruptedIOException {
// Object result;
// try {
// result = blockingQueue.poll(timeout, unit);
// if (result == null) {
// if (!blockingQueue.offer(""))
// result = blockingQueue.take();
// }
// } catch (InterruptedException e) {
// throw ExceptionUtil.initCause(new InterruptedIOException(e.getMessage()), e);
// }
// return result;
// }
//
// }
//
// Path: src/main/java/com/yiji/falcon/agent/util/ExecuteThreadUtil.java
// public class ExecuteThreadUtil {
// private static ExecutorService executorService;
//
// static {
// final int maxPoolSize = AgentConfiguration.INSTANCE.getAgentMaxThreadCount();
// //定义并发执行服务
// executorService = new ThreadPoolExecutor(5, maxPoolSize, 0L, TimeUnit.MILLISECONDS,
// new SynchronousQueue<>(),
// r -> {
// Thread t = new Thread(r);
// t.setName("agentThreadPool");
// return t;
// },new ThreadPoolExecutor.DiscardOldestPolicy()
// );
// }
//
// /**
// * 执行线程任务
// *
// * @param task
// */
// public static void execute(Runnable task) {
// executorService.submit(task);
// }
//
// /**
// * 执行线程任务
// *
// * @param task
// * @param <T>
// * @return
// */
// public static <T> Future<T> execute(Callable<T> task) {
// return executorService.submit(task);
// }
//
// /**
// * 关闭线程池
// */
// public static void shutdown() {
// executorService.shutdown();
// }
// }
| import com.yiji.falcon.agent.util.BlockingQueueUtil;
import com.yiji.falcon.agent.util.ExecuteThreadUtil;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit; | /*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
package com.yiji.falcon.agent.jmx;
/*
* 修订记录:
* [email protected] 2016-08-09 10:25 创建
*/
/**
* @author [email protected]
*/
public class JMXConnectWithTimeout {
/**
* JMX连接
* @param url
* JMX连接地址
* @param jmxUser
* JMX授权用户 null为无授权用户
* @param jmxPassword
* JMX授权密码 null为无授权密码
* @param timeout
* 超时时间
* @param unit
* 超时单位
* @return
* @throws IOException
*/
public static JMXConnector connectWithTimeout( final JMXServiceURL url,String jmxUser,String jmxPassword, long timeout, TimeUnit unit) throws Exception {
final BlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(1);
ExecuteThreadUtil.execute(() -> {
try {
JMXConnector connector;
if(jmxUser != null && jmxPassword != null){
Map<String,Object> env = new HashMap<>();
String[] credentials = new String[] { jmxUser, jmxPassword };
env.put(JMXConnector.CREDENTIALS, credentials);
connector = JMXConnectorFactory.connect(url,env);
}else{
connector = JMXConnectorFactory.connect(url,null);
}
if (!blockingQueue.offer(connector))
connector.close();
} catch (Throwable t) {
blockingQueue.offer(t);
}
});
| // Path: src/main/java/com/yiji/falcon/agent/util/BlockingQueueUtil.java
// public class BlockingQueueUtil {
//
// /**
// * 获取结果
// * @param blockingQueue
// * @param timeout
// * @param unit
// * @return
// * @throws InterruptedIOException
// */
// public static Object getResult(BlockingQueue<Object> blockingQueue,long timeout, TimeUnit unit) throws InterruptedIOException {
// Object result;
// try {
// result = blockingQueue.poll(timeout, unit);
// if (result == null) {
// if (!blockingQueue.offer(""))
// result = blockingQueue.take();
// }
// } catch (InterruptedException e) {
// throw ExceptionUtil.initCause(new InterruptedIOException(e.getMessage()), e);
// }
// return result;
// }
//
// }
//
// Path: src/main/java/com/yiji/falcon/agent/util/ExecuteThreadUtil.java
// public class ExecuteThreadUtil {
// private static ExecutorService executorService;
//
// static {
// final int maxPoolSize = AgentConfiguration.INSTANCE.getAgentMaxThreadCount();
// //定义并发执行服务
// executorService = new ThreadPoolExecutor(5, maxPoolSize, 0L, TimeUnit.MILLISECONDS,
// new SynchronousQueue<>(),
// r -> {
// Thread t = new Thread(r);
// t.setName("agentThreadPool");
// return t;
// },new ThreadPoolExecutor.DiscardOldestPolicy()
// );
// }
//
// /**
// * 执行线程任务
// *
// * @param task
// */
// public static void execute(Runnable task) {
// executorService.submit(task);
// }
//
// /**
// * 执行线程任务
// *
// * @param task
// * @param <T>
// * @return
// */
// public static <T> Future<T> execute(Callable<T> task) {
// return executorService.submit(task);
// }
//
// /**
// * 关闭线程池
// */
// public static void shutdown() {
// executorService.shutdown();
// }
// }
// Path: src/main/java/com/yiji/falcon/agent/jmx/JMXConnectWithTimeout.java
import com.yiji.falcon.agent.util.BlockingQueueUtil;
import com.yiji.falcon.agent.util.ExecuteThreadUtil;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
/*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
package com.yiji.falcon.agent.jmx;
/*
* 修订记录:
* [email protected] 2016-08-09 10:25 创建
*/
/**
* @author [email protected]
*/
public class JMXConnectWithTimeout {
/**
* JMX连接
* @param url
* JMX连接地址
* @param jmxUser
* JMX授权用户 null为无授权用户
* @param jmxPassword
* JMX授权密码 null为无授权密码
* @param timeout
* 超时时间
* @param unit
* 超时单位
* @return
* @throws IOException
*/
public static JMXConnector connectWithTimeout( final JMXServiceURL url,String jmxUser,String jmxPassword, long timeout, TimeUnit unit) throws Exception {
final BlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(1);
ExecuteThreadUtil.execute(() -> {
try {
JMXConnector connector;
if(jmxUser != null && jmxPassword != null){
Map<String,Object> env = new HashMap<>();
String[] credentials = new String[] { jmxUser, jmxPassword };
env.put(JMXConnector.CREDENTIALS, credentials);
connector = JMXConnectorFactory.connect(url,env);
}else{
connector = JMXConnectorFactory.connect(url,null);
}
if (!blockingQueue.offer(connector))
connector.close();
} catch (Throwable t) {
blockingQueue.offer(t);
}
});
| Object result = BlockingQueueUtil.getResult(blockingQueue,timeout,unit); |
cqyijifu/OpenFalcon-SuitAgent | src/main/java/com/yiji/falcon/agent/web/Request.java | // Path: src/main/java/com/yiji/falcon/agent/util/StringUtils.java
// public class StringUtils {
//
// /**
// * 判断传入的String是否为空('' or null)
// * @param str
// * @return
// */
// public static boolean isEmpty(String str){
// return str == null || str.length() == 0;
// }
//
// /**
// * 返回指定数字的字符串形式
// * @param value
// * @return
// */
// public static String getStringByInt(int value){
// return String.valueOf(value).intern();
// }
//
// }
| import com.yiji.falcon.agent.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List; | int i;
byte[] buffer = new byte[2048];
try {
i = input.read(buffer);
} catch (IOException e) {
log.error("request parse error",e);
i = -1;
}
for (int j = 0; j < i; j++) {
request.append((char) buffer[j]);
}
header = request.toString();
log.debug("Request Header : \r\n {}",header);
parseUri();
parseUrlPath();
}
private void parseUri() {
int index1, index2;
index1 = header.indexOf(' ');
if (index1 != -1) {
index2 = header.indexOf(' ', index1 + 1);
if (index2 > index1)
uri = header.substring(index1 + 1, index2);
}
}
private void parseUrlPath() {
urlPath = new ArrayList<>(); | // Path: src/main/java/com/yiji/falcon/agent/util/StringUtils.java
// public class StringUtils {
//
// /**
// * 判断传入的String是否为空('' or null)
// * @param str
// * @return
// */
// public static boolean isEmpty(String str){
// return str == null || str.length() == 0;
// }
//
// /**
// * 返回指定数字的字符串形式
// * @param value
// * @return
// */
// public static String getStringByInt(int value){
// return String.valueOf(value).intern();
// }
//
// }
// Path: src/main/java/com/yiji/falcon/agent/web/Request.java
import com.yiji.falcon.agent.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
int i;
byte[] buffer = new byte[2048];
try {
i = input.read(buffer);
} catch (IOException e) {
log.error("request parse error",e);
i = -1;
}
for (int j = 0; j < i; j++) {
request.append((char) buffer[j]);
}
header = request.toString();
log.debug("Request Header : \r\n {}",header);
parseUri();
parseUrlPath();
}
private void parseUri() {
int index1, index2;
index1 = header.indexOf(' ');
if (index1 != -1) {
index2 = header.indexOf(' ', index1 + 1);
if (index2 > index1)
uri = header.substring(index1 + 1, index2);
}
}
private void parseUrlPath() {
urlPath = new ArrayList<>(); | if(!StringUtils.isEmpty(uri)){ |
cqyijifu/OpenFalcon-SuitAgent | src/main/java/com/yiji/falcon/agent/config/AgentConfiguration.java | // Path: src/main/java/com/yiji/falcon/agent/util/StringUtils.java
// public class StringUtils {
//
// /**
// * 判断传入的String是否为空('' or null)
// * @param str
// * @return
// */
// public static boolean isEmpty(String str){
// return str == null || str.length() == 0;
// }
//
// /**
// * 返回指定数字的字符串形式
// * @param value
// * @return
// */
// public static String getStringByInt(int value){
// return String.valueOf(value).intern();
// }
//
// }
| import com.yiji.falcon.agent.util.StringUtils;
import lombok.Getter;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties; |
private String agentHomeDir;
private static final String CONF_AGENT_ENDPOINT = "agent.endpoint";
private static final String CONF_AGENT_HOME = "agent.home.dir";
private static final String CONF_AGENT_FLUSH_TIME = "agent.flush.time";
private static final String CONF_AGENT_MAX_THREAD = "agent.thread.maxCount";
private static final String CONF_AGENT_FALCON_PUSH_URL = "agent.falcon.push.url";
private static final String CONF_AGENT_PORT = "agent.port";
private static final String CONF_AGENT_WEB_PORT = "agent.web.port";
private static final String CONF_AGENT_WEB_ENABLE = "agent.web.enable";
private static final String CONF_AGENT_MOCK_VALID_TIME = "agent.mock.valid.time";
private static final String AUTHORIZATION_CONF_PATH = "authorization.conf.path";
private static final String FALCON_DIR_PATH = "agent.falcon.dir";
private static final String FALCON_CONF_DIR_PATH = "agent.falcon.conf.dir";
private static final String CONF_AGENT_JMX_LOCAL_CONNECT = "agent.jmx.localConnectSupport";
private static final String CONF_AGENT_UPDATE_URL = "agent.update.pack.url";
private Properties agentConf = null;
/**
* 初始化agent配置
*/
AgentConfiguration() {
instance();
}
private void instance(){ | // Path: src/main/java/com/yiji/falcon/agent/util/StringUtils.java
// public class StringUtils {
//
// /**
// * 判断传入的String是否为空('' or null)
// * @param str
// * @return
// */
// public static boolean isEmpty(String str){
// return str == null || str.length() == 0;
// }
//
// /**
// * 返回指定数字的字符串形式
// * @param value
// * @return
// */
// public static String getStringByInt(int value){
// return String.valueOf(value).intern();
// }
//
// }
// Path: src/main/java/com/yiji/falcon/agent/config/AgentConfiguration.java
import com.yiji.falcon.agent.util.StringUtils;
import lombok.Getter;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
private String agentHomeDir;
private static final String CONF_AGENT_ENDPOINT = "agent.endpoint";
private static final String CONF_AGENT_HOME = "agent.home.dir";
private static final String CONF_AGENT_FLUSH_TIME = "agent.flush.time";
private static final String CONF_AGENT_MAX_THREAD = "agent.thread.maxCount";
private static final String CONF_AGENT_FALCON_PUSH_URL = "agent.falcon.push.url";
private static final String CONF_AGENT_PORT = "agent.port";
private static final String CONF_AGENT_WEB_PORT = "agent.web.port";
private static final String CONF_AGENT_WEB_ENABLE = "agent.web.enable";
private static final String CONF_AGENT_MOCK_VALID_TIME = "agent.mock.valid.time";
private static final String AUTHORIZATION_CONF_PATH = "authorization.conf.path";
private static final String FALCON_DIR_PATH = "agent.falcon.dir";
private static final String FALCON_CONF_DIR_PATH = "agent.falcon.conf.dir";
private static final String CONF_AGENT_JMX_LOCAL_CONNECT = "agent.jmx.localConnectSupport";
private static final String CONF_AGENT_UPDATE_URL = "agent.update.pack.url";
private Properties agentConf = null;
/**
* 初始化agent配置
*/
AgentConfiguration() {
instance();
}
private void instance(){ | if(StringUtils.isEmpty(System.getProperty("agent.conf.path"))){ |
cqyijifu/OpenFalcon-SuitAgent | src/main/java/com/yiji/falcon/agent/util/SchedulerUtil.java | // Path: src/main/java/com/yiji/falcon/agent/common/SchedulerFactory.java
// public class SchedulerFactory {
//
// /**
// * 获取调度器
// * @return
// * @throws SchedulerException
// * 调度器获取失败异常
// */
// public static Scheduler getScheduler() throws SchedulerException {
// org.quartz.SchedulerFactory sf = new StdSchedulerFactory(AgentConfiguration.INSTANCE.getQuartzConfPath());
// return sf.getScheduler();
// }
//
// }
//
// Path: src/main/java/com/yiji/falcon/agent/vo/sceduler/ScheduleJobResult.java
// @Data
// public class ScheduleJobResult implements Serializable {
//
// private TriggerKey triggerKey;
// private JobKey jobKey;
// private JobDetail jobDetail;
// private Trigger trigger;
// private ScheduleJobStatus scheduleJobStatus;
//
// }
//
// Path: src/main/java/com/yiji/falcon/agent/vo/sceduler/ScheduleJobStatus.java
// public enum ScheduleJobStatus {
//
// /**
// * 任务创建成功
// */
// SUCCESS,
// /**
// * 已存在相同的任务(key)
// */
// ISEXIST,
// /**
// * 传入的对象条不满足任务的创建条件
// */
// DISCONTENT,
// /**
// * 创建任务失败
// */
// FAILED;
//
// }
| import com.yiji.falcon.agent.common.SchedulerFactory;
import com.yiji.falcon.agent.vo.sceduler.ScheduleJobResult;
import com.yiji.falcon.agent.vo.sceduler.ScheduleJobStatus;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger; | /*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
package com.yiji.falcon.agent.util;
/*
* 修订记录:
* [email protected] 2016-06-22 17:48 创建
*/
/**
* 计划任务辅助工具类
* @author [email protected]
*/
@Slf4j
public class SchedulerUtil {
/**
* 执行计划任务
* @param job
* @param trigger
* @return
* @throws SchedulerException
*/ | // Path: src/main/java/com/yiji/falcon/agent/common/SchedulerFactory.java
// public class SchedulerFactory {
//
// /**
// * 获取调度器
// * @return
// * @throws SchedulerException
// * 调度器获取失败异常
// */
// public static Scheduler getScheduler() throws SchedulerException {
// org.quartz.SchedulerFactory sf = new StdSchedulerFactory(AgentConfiguration.INSTANCE.getQuartzConfPath());
// return sf.getScheduler();
// }
//
// }
//
// Path: src/main/java/com/yiji/falcon/agent/vo/sceduler/ScheduleJobResult.java
// @Data
// public class ScheduleJobResult implements Serializable {
//
// private TriggerKey triggerKey;
// private JobKey jobKey;
// private JobDetail jobDetail;
// private Trigger trigger;
// private ScheduleJobStatus scheduleJobStatus;
//
// }
//
// Path: src/main/java/com/yiji/falcon/agent/vo/sceduler/ScheduleJobStatus.java
// public enum ScheduleJobStatus {
//
// /**
// * 任务创建成功
// */
// SUCCESS,
// /**
// * 已存在相同的任务(key)
// */
// ISEXIST,
// /**
// * 传入的对象条不满足任务的创建条件
// */
// DISCONTENT,
// /**
// * 创建任务失败
// */
// FAILED;
//
// }
// Path: src/main/java/com/yiji/falcon/agent/util/SchedulerUtil.java
import com.yiji.falcon.agent.common.SchedulerFactory;
import com.yiji.falcon.agent.vo.sceduler.ScheduleJobResult;
import com.yiji.falcon.agent.vo.sceduler.ScheduleJobStatus;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
/*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
package com.yiji.falcon.agent.util;
/*
* 修订记录:
* [email protected] 2016-06-22 17:48 创建
*/
/**
* 计划任务辅助工具类
* @author [email protected]
*/
@Slf4j
public class SchedulerUtil {
/**
* 执行计划任务
* @param job
* @param trigger
* @return
* @throws SchedulerException
*/ | public static ScheduleJobResult executeScheduleJob(JobDetail job, Trigger trigger) throws SchedulerException { |
cqyijifu/OpenFalcon-SuitAgent | src/main/java/com/yiji/falcon/agent/util/SchedulerUtil.java | // Path: src/main/java/com/yiji/falcon/agent/common/SchedulerFactory.java
// public class SchedulerFactory {
//
// /**
// * 获取调度器
// * @return
// * @throws SchedulerException
// * 调度器获取失败异常
// */
// public static Scheduler getScheduler() throws SchedulerException {
// org.quartz.SchedulerFactory sf = new StdSchedulerFactory(AgentConfiguration.INSTANCE.getQuartzConfPath());
// return sf.getScheduler();
// }
//
// }
//
// Path: src/main/java/com/yiji/falcon/agent/vo/sceduler/ScheduleJobResult.java
// @Data
// public class ScheduleJobResult implements Serializable {
//
// private TriggerKey triggerKey;
// private JobKey jobKey;
// private JobDetail jobDetail;
// private Trigger trigger;
// private ScheduleJobStatus scheduleJobStatus;
//
// }
//
// Path: src/main/java/com/yiji/falcon/agent/vo/sceduler/ScheduleJobStatus.java
// public enum ScheduleJobStatus {
//
// /**
// * 任务创建成功
// */
// SUCCESS,
// /**
// * 已存在相同的任务(key)
// */
// ISEXIST,
// /**
// * 传入的对象条不满足任务的创建条件
// */
// DISCONTENT,
// /**
// * 创建任务失败
// */
// FAILED;
//
// }
| import com.yiji.falcon.agent.common.SchedulerFactory;
import com.yiji.falcon.agent.vo.sceduler.ScheduleJobResult;
import com.yiji.falcon.agent.vo.sceduler.ScheduleJobStatus;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger; | /*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
package com.yiji.falcon.agent.util;
/*
* 修订记录:
* [email protected] 2016-06-22 17:48 创建
*/
/**
* 计划任务辅助工具类
* @author [email protected]
*/
@Slf4j
public class SchedulerUtil {
/**
* 执行计划任务
* @param job
* @param trigger
* @return
* @throws SchedulerException
*/
public static ScheduleJobResult executeScheduleJob(JobDetail job, Trigger trigger) throws SchedulerException {
ScheduleJobResult scheduleJobResult = new ScheduleJobResult();
//判断是否满足计划任务的创建条件
if(job.getKey() == null || trigger.getKey() == null || job.getJobDataMap() == null){ | // Path: src/main/java/com/yiji/falcon/agent/common/SchedulerFactory.java
// public class SchedulerFactory {
//
// /**
// * 获取调度器
// * @return
// * @throws SchedulerException
// * 调度器获取失败异常
// */
// public static Scheduler getScheduler() throws SchedulerException {
// org.quartz.SchedulerFactory sf = new StdSchedulerFactory(AgentConfiguration.INSTANCE.getQuartzConfPath());
// return sf.getScheduler();
// }
//
// }
//
// Path: src/main/java/com/yiji/falcon/agent/vo/sceduler/ScheduleJobResult.java
// @Data
// public class ScheduleJobResult implements Serializable {
//
// private TriggerKey triggerKey;
// private JobKey jobKey;
// private JobDetail jobDetail;
// private Trigger trigger;
// private ScheduleJobStatus scheduleJobStatus;
//
// }
//
// Path: src/main/java/com/yiji/falcon/agent/vo/sceduler/ScheduleJobStatus.java
// public enum ScheduleJobStatus {
//
// /**
// * 任务创建成功
// */
// SUCCESS,
// /**
// * 已存在相同的任务(key)
// */
// ISEXIST,
// /**
// * 传入的对象条不满足任务的创建条件
// */
// DISCONTENT,
// /**
// * 创建任务失败
// */
// FAILED;
//
// }
// Path: src/main/java/com/yiji/falcon/agent/util/SchedulerUtil.java
import com.yiji.falcon.agent.common.SchedulerFactory;
import com.yiji.falcon.agent.vo.sceduler.ScheduleJobResult;
import com.yiji.falcon.agent.vo.sceduler.ScheduleJobStatus;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
/*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
package com.yiji.falcon.agent.util;
/*
* 修订记录:
* [email protected] 2016-06-22 17:48 创建
*/
/**
* 计划任务辅助工具类
* @author [email protected]
*/
@Slf4j
public class SchedulerUtil {
/**
* 执行计划任务
* @param job
* @param trigger
* @return
* @throws SchedulerException
*/
public static ScheduleJobResult executeScheduleJob(JobDetail job, Trigger trigger) throws SchedulerException {
ScheduleJobResult scheduleJobResult = new ScheduleJobResult();
//判断是否满足计划任务的创建条件
if(job.getKey() == null || trigger.getKey() == null || job.getJobDataMap() == null){ | scheduleJobResult.setScheduleJobStatus(ScheduleJobStatus.FAILED); |
cqyijifu/OpenFalcon-SuitAgent | src/main/java/com/yiji/falcon/agent/util/SchedulerUtil.java | // Path: src/main/java/com/yiji/falcon/agent/common/SchedulerFactory.java
// public class SchedulerFactory {
//
// /**
// * 获取调度器
// * @return
// * @throws SchedulerException
// * 调度器获取失败异常
// */
// public static Scheduler getScheduler() throws SchedulerException {
// org.quartz.SchedulerFactory sf = new StdSchedulerFactory(AgentConfiguration.INSTANCE.getQuartzConfPath());
// return sf.getScheduler();
// }
//
// }
//
// Path: src/main/java/com/yiji/falcon/agent/vo/sceduler/ScheduleJobResult.java
// @Data
// public class ScheduleJobResult implements Serializable {
//
// private TriggerKey triggerKey;
// private JobKey jobKey;
// private JobDetail jobDetail;
// private Trigger trigger;
// private ScheduleJobStatus scheduleJobStatus;
//
// }
//
// Path: src/main/java/com/yiji/falcon/agent/vo/sceduler/ScheduleJobStatus.java
// public enum ScheduleJobStatus {
//
// /**
// * 任务创建成功
// */
// SUCCESS,
// /**
// * 已存在相同的任务(key)
// */
// ISEXIST,
// /**
// * 传入的对象条不满足任务的创建条件
// */
// DISCONTENT,
// /**
// * 创建任务失败
// */
// FAILED;
//
// }
| import com.yiji.falcon.agent.common.SchedulerFactory;
import com.yiji.falcon.agent.vo.sceduler.ScheduleJobResult;
import com.yiji.falcon.agent.vo.sceduler.ScheduleJobStatus;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger; | /*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
package com.yiji.falcon.agent.util;
/*
* 修订记录:
* [email protected] 2016-06-22 17:48 创建
*/
/**
* 计划任务辅助工具类
* @author [email protected]
*/
@Slf4j
public class SchedulerUtil {
/**
* 执行计划任务
* @param job
* @param trigger
* @return
* @throws SchedulerException
*/
public static ScheduleJobResult executeScheduleJob(JobDetail job, Trigger trigger) throws SchedulerException {
ScheduleJobResult scheduleJobResult = new ScheduleJobResult();
//判断是否满足计划任务的创建条件
if(job.getKey() == null || trigger.getKey() == null || job.getJobDataMap() == null){
scheduleJobResult.setScheduleJobStatus(ScheduleJobStatus.FAILED);
//不满足计划任务的创建条件,返回scheduleJobResult值类
return scheduleJobResult;
}
scheduleJobResult.setJobDetail(job);
scheduleJobResult.setTrigger(trigger);
//开始分配计划任务 | // Path: src/main/java/com/yiji/falcon/agent/common/SchedulerFactory.java
// public class SchedulerFactory {
//
// /**
// * 获取调度器
// * @return
// * @throws SchedulerException
// * 调度器获取失败异常
// */
// public static Scheduler getScheduler() throws SchedulerException {
// org.quartz.SchedulerFactory sf = new StdSchedulerFactory(AgentConfiguration.INSTANCE.getQuartzConfPath());
// return sf.getScheduler();
// }
//
// }
//
// Path: src/main/java/com/yiji/falcon/agent/vo/sceduler/ScheduleJobResult.java
// @Data
// public class ScheduleJobResult implements Serializable {
//
// private TriggerKey triggerKey;
// private JobKey jobKey;
// private JobDetail jobDetail;
// private Trigger trigger;
// private ScheduleJobStatus scheduleJobStatus;
//
// }
//
// Path: src/main/java/com/yiji/falcon/agent/vo/sceduler/ScheduleJobStatus.java
// public enum ScheduleJobStatus {
//
// /**
// * 任务创建成功
// */
// SUCCESS,
// /**
// * 已存在相同的任务(key)
// */
// ISEXIST,
// /**
// * 传入的对象条不满足任务的创建条件
// */
// DISCONTENT,
// /**
// * 创建任务失败
// */
// FAILED;
//
// }
// Path: src/main/java/com/yiji/falcon/agent/util/SchedulerUtil.java
import com.yiji.falcon.agent.common.SchedulerFactory;
import com.yiji.falcon.agent.vo.sceduler.ScheduleJobResult;
import com.yiji.falcon.agent.vo.sceduler.ScheduleJobStatus;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
/*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
package com.yiji.falcon.agent.util;
/*
* 修订记录:
* [email protected] 2016-06-22 17:48 创建
*/
/**
* 计划任务辅助工具类
* @author [email protected]
*/
@Slf4j
public class SchedulerUtil {
/**
* 执行计划任务
* @param job
* @param trigger
* @return
* @throws SchedulerException
*/
public static ScheduleJobResult executeScheduleJob(JobDetail job, Trigger trigger) throws SchedulerException {
ScheduleJobResult scheduleJobResult = new ScheduleJobResult();
//判断是否满足计划任务的创建条件
if(job.getKey() == null || trigger.getKey() == null || job.getJobDataMap() == null){
scheduleJobResult.setScheduleJobStatus(ScheduleJobStatus.FAILED);
//不满足计划任务的创建条件,返回scheduleJobResult值类
return scheduleJobResult;
}
scheduleJobResult.setJobDetail(job);
scheduleJobResult.setTrigger(trigger);
//开始分配计划任务 | Scheduler scheduler = SchedulerFactory.getScheduler(); |
cqyijifu/OpenFalcon-SuitAgent | src/main/java/com/yiji/falcon/agent/falcon/FalconReportObject.java | // Path: src/main/java/com/yiji/falcon/agent/util/StringUtils.java
// public class StringUtils {
//
// /**
// * 判断传入的String是否为空('' or null)
// * @param str
// * @return
// */
// public static boolean isEmpty(String str){
// return str == null || str.length() == 0;
// }
//
// /**
// * 返回指定数字的字符串形式
// * @param value
// * @return
// */
// public static String getStringByInt(int value){
// return String.valueOf(value).intern();
// }
//
// }
| import javax.management.ObjectName;
import com.yiji.falcon.agent.util.StringUtils;
import lombok.Data; | /*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
package com.yiji.falcon.agent.falcon;
/*
* 修订记录:
* [email protected] 2016-06-22 17:48 创建
*/
/**
* push到falcon的数据报告对象
* @author [email protected]
*/
@Data
public class FalconReportObject implements Cloneable{
/**
* 标明Metric的主体(属主),比如metric是cpu_idle,那么Endpoint就表示这是哪台机器的cpu_idle
*/
private String endpoint;
/**
* 最核心的字段,代表这个采集项具体度量的是什么, 比如是cpu_idle呢,还是memory_free, 还是qps
*/
private String metric;
/**
* 表示汇报该数据时的unix时间戳,注意是整数,代表的是秒
*/
private long timestamp;
/**
* 表示该数据采集项的汇报周期,这对于后续的配置监控策略很重要,必须明确指定。
*/
private int step;
/**
* 代表该metric在当前时间点的值,数值类型
*/
private String value;
/**
* 只能是COUNTER或者GAUGE二选一,前者表示该数据采集项为计时器类型,后者表示其为原值 (注意大小写)
GAUGE:即用户上传什么样的值,就原封不动的存储
COUNTER:指标在存储和展现的时候,会被计算为speed,即(当前值 - 上次值)/ 时间间隔
*/
private CounterType counterType;
/**
* 一组逗号分割的键值对, 对metric进一步描述和细化, 可以是空字符串. 比如idc=lg,比如service=xbox等,多个tag之间用逗号分割
*/
private String tags;
/**
* 仅供系统使用
*/
private ObjectName objectName;
@Override
public FalconReportObject clone() {
try {
return (FalconReportObject) super.clone();
} catch (CloneNotSupportedException e) {
return new FalconReportObject();
}
}
/**
* 添加tag
* @param newTag
* @return
*/
public FalconReportObject appendTags(String newTag){ | // Path: src/main/java/com/yiji/falcon/agent/util/StringUtils.java
// public class StringUtils {
//
// /**
// * 判断传入的String是否为空('' or null)
// * @param str
// * @return
// */
// public static boolean isEmpty(String str){
// return str == null || str.length() == 0;
// }
//
// /**
// * 返回指定数字的字符串形式
// * @param value
// * @return
// */
// public static String getStringByInt(int value){
// return String.valueOf(value).intern();
// }
//
// }
// Path: src/main/java/com/yiji/falcon/agent/falcon/FalconReportObject.java
import javax.management.ObjectName;
import com.yiji.falcon.agent.util.StringUtils;
import lombok.Data;
/*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
package com.yiji.falcon.agent.falcon;
/*
* 修订记录:
* [email protected] 2016-06-22 17:48 创建
*/
/**
* push到falcon的数据报告对象
* @author [email protected]
*/
@Data
public class FalconReportObject implements Cloneable{
/**
* 标明Metric的主体(属主),比如metric是cpu_idle,那么Endpoint就表示这是哪台机器的cpu_idle
*/
private String endpoint;
/**
* 最核心的字段,代表这个采集项具体度量的是什么, 比如是cpu_idle呢,还是memory_free, 还是qps
*/
private String metric;
/**
* 表示汇报该数据时的unix时间戳,注意是整数,代表的是秒
*/
private long timestamp;
/**
* 表示该数据采集项的汇报周期,这对于后续的配置监控策略很重要,必须明确指定。
*/
private int step;
/**
* 代表该metric在当前时间点的值,数值类型
*/
private String value;
/**
* 只能是COUNTER或者GAUGE二选一,前者表示该数据采集项为计时器类型,后者表示其为原值 (注意大小写)
GAUGE:即用户上传什么样的值,就原封不动的存储
COUNTER:指标在存储和展现的时候,会被计算为speed,即(当前值 - 上次值)/ 时间间隔
*/
private CounterType counterType;
/**
* 一组逗号分割的键值对, 对metric进一步描述和细化, 可以是空字符串. 比如idc=lg,比如service=xbox等,多个tag之间用逗号分割
*/
private String tags;
/**
* 仅供系统使用
*/
private ObjectName objectName;
@Override
public FalconReportObject clone() {
try {
return (FalconReportObject) super.clone();
} catch (CloneNotSupportedException e) {
return new FalconReportObject();
}
}
/**
* 添加tag
* @param newTag
* @return
*/
public FalconReportObject appendTags(String newTag){ | if(!StringUtils.isEmpty(newTag)){ |
cqyijifu/OpenFalcon-SuitAgent | src/main/java/com/yiji/falcon/agent/plugins/util/CacheUtil.java | // Path: src/main/java/com/yiji/falcon/agent/util/StringUtils.java
// public class StringUtils {
//
// /**
// * 判断传入的String是否为空('' or null)
// * @param str
// * @return
// */
// public static boolean isEmpty(String str){
// return str == null || str.length() == 0;
// }
//
// /**
// * 返回指定数字的字符串形式
// * @param value
// * @return
// */
// public static String getStringByInt(int value){
// return String.valueOf(value).intern();
// }
//
// }
| import com.yiji.falcon.agent.util.StringUtils;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap; | /*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
package com.yiji.falcon.agent.plugins.util;
/*
* 修订记录:
* [email protected] 2016-11-16 09:51 创建
*/
/**
* @author [email protected]
*/
public class CacheUtil {
/**
* 获取缓存中,超时的key
* @param map
* @return
*/
public static List<String> getTimeoutCacheKeys(ConcurrentHashMap<String,String> map){
List<String> keys = new ArrayList<>();
long now = System.currentTimeMillis();
for (Map.Entry<String, String> entry : map.entrySet()) {
long cacheTime = getCacheTime(entry.getValue());
if(cacheTime == 0){
keys.add(entry.getKey());
}else if(now - cacheTime >= 2 * 24 * 60 * 60 * 1000){
//超时2天
keys.add(entry.getKey());
}
}
return keys;
}
/**
* 设置缓存值,添加时间戳
* @param value
* @return
*/
public static String setCacheValue(String value){ | // Path: src/main/java/com/yiji/falcon/agent/util/StringUtils.java
// public class StringUtils {
//
// /**
// * 判断传入的String是否为空('' or null)
// * @param str
// * @return
// */
// public static boolean isEmpty(String str){
// return str == null || str.length() == 0;
// }
//
// /**
// * 返回指定数字的字符串形式
// * @param value
// * @return
// */
// public static String getStringByInt(int value){
// return String.valueOf(value).intern();
// }
//
// }
// Path: src/main/java/com/yiji/falcon/agent/plugins/util/CacheUtil.java
import com.yiji.falcon.agent.util.StringUtils;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
package com.yiji.falcon.agent.plugins.util;
/*
* 修订记录:
* [email protected] 2016-11-16 09:51 创建
*/
/**
* @author [email protected]
*/
public class CacheUtil {
/**
* 获取缓存中,超时的key
* @param map
* @return
*/
public static List<String> getTimeoutCacheKeys(ConcurrentHashMap<String,String> map){
List<String> keys = new ArrayList<>();
long now = System.currentTimeMillis();
for (Map.Entry<String, String> entry : map.entrySet()) {
long cacheTime = getCacheTime(entry.getValue());
if(cacheTime == 0){
keys.add(entry.getKey());
}else if(now - cacheTime >= 2 * 24 * 60 * 60 * 1000){
//超时2天
keys.add(entry.getKey());
}
}
return keys;
}
/**
* 设置缓存值,添加时间戳
* @param value
* @return
*/
public static String setCacheValue(String value){ | if(!StringUtils.isEmpty(value)){ |
cqyijifu/OpenFalcon-SuitAgent | src/main/java/com/yiji/falcon/agent/plugins/util/SNMPHelper.java | // Path: src/main/java/com/yiji/falcon/agent/util/StringUtils.java
// public class StringUtils {
//
// /**
// * 判断传入的String是否为空('' or null)
// * @param str
// * @return
// */
// public static boolean isEmpty(String str){
// return str == null || str.length() == 0;
// }
//
// /**
// * 返回指定数字的字符串形式
// * @param value
// * @return
// */
// public static String getStringByInt(int value){
// return String.valueOf(value).intern();
// }
//
// }
| import com.yiji.falcon.agent.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.snmp4j.PDU;
import org.snmp4j.ScopedPDU;
import org.snmp4j.Snmp;
import org.snmp4j.Target;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.smi.Integer32;
import org.snmp4j.smi.Null;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.VariableBinding;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; |
return pduList;
}
private static boolean checkWalkFinished(OID targetOID, PDU pdu, VariableBinding vb) {
boolean finished = false;
if (pdu.getErrorStatus() != 0) {
finished = true;
} else if (vb.getOid() == null) {
finished = true;
} else if (vb.getOid().size() < targetOID.size()) {
finished = true;
} else if (targetOID.leftMostCompare(targetOID.size(), vb.getOid()) != 0) {
finished = true;
} else if (Null.isExceptionSyntax(vb.getVariable().getSyntax())) {
finished = true;
} else if (vb.getOid().compareTo(targetOID) <= 0) {
finished = true;
}
return finished;
}
/**
* 根据系统信息获取供应商
*
* @param sysDesc
* @return
*/
public static VendorType getVendorBySysDesc(String sysDesc) { | // Path: src/main/java/com/yiji/falcon/agent/util/StringUtils.java
// public class StringUtils {
//
// /**
// * 判断传入的String是否为空('' or null)
// * @param str
// * @return
// */
// public static boolean isEmpty(String str){
// return str == null || str.length() == 0;
// }
//
// /**
// * 返回指定数字的字符串形式
// * @param value
// * @return
// */
// public static String getStringByInt(int value){
// return String.valueOf(value).intern();
// }
//
// }
// Path: src/main/java/com/yiji/falcon/agent/plugins/util/SNMPHelper.java
import com.yiji.falcon.agent.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.snmp4j.PDU;
import org.snmp4j.ScopedPDU;
import org.snmp4j.Snmp;
import org.snmp4j.Target;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.smi.Integer32;
import org.snmp4j.smi.Null;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.VariableBinding;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
return pduList;
}
private static boolean checkWalkFinished(OID targetOID, PDU pdu, VariableBinding vb) {
boolean finished = false;
if (pdu.getErrorStatus() != 0) {
finished = true;
} else if (vb.getOid() == null) {
finished = true;
} else if (vb.getOid().size() < targetOID.size()) {
finished = true;
} else if (targetOID.leftMostCompare(targetOID.size(), vb.getOid()) != 0) {
finished = true;
} else if (Null.isExceptionSyntax(vb.getVariable().getSyntax())) {
finished = true;
} else if (vb.getOid().compareTo(targetOID) <= 0) {
finished = true;
}
return finished;
}
/**
* 根据系统信息获取供应商
*
* @param sysDesc
* @return
*/
public static VendorType getVendorBySysDesc(String sysDesc) { | if(StringUtils.isEmpty(sysDesc)){ |
cqyijifu/OpenFalcon-SuitAgent | src/main/java/com/yiji/falcon/agent/plugins/JDBCPlugin.java | // Path: src/main/java/com/yiji/falcon/agent/falcon/FalconReportObject.java
// @Data
// public class FalconReportObject implements Cloneable{
//
// /**
// * 标明Metric的主体(属主),比如metric是cpu_idle,那么Endpoint就表示这是哪台机器的cpu_idle
// */
// private String endpoint;
// /**
// * 最核心的字段,代表这个采集项具体度量的是什么, 比如是cpu_idle呢,还是memory_free, 还是qps
// */
// private String metric;
// /**
// * 表示汇报该数据时的unix时间戳,注意是整数,代表的是秒
// */
// private long timestamp;
// /**
// * 表示该数据采集项的汇报周期,这对于后续的配置监控策略很重要,必须明确指定。
// */
// private int step;
// /**
// * 代表该metric在当前时间点的值,数值类型
// */
// private String value;
// /**
// * 只能是COUNTER或者GAUGE二选一,前者表示该数据采集项为计时器类型,后者表示其为原值 (注意大小写)
// GAUGE:即用户上传什么样的值,就原封不动的存储
// COUNTER:指标在存储和展现的时候,会被计算为speed,即(当前值 - 上次值)/ 时间间隔
// */
// private CounterType counterType;
// /**
// * 一组逗号分割的键值对, 对metric进一步描述和细化, 可以是空字符串. 比如idc=lg,比如service=xbox等,多个tag之间用逗号分割
// */
// private String tags;
//
// /**
// * 仅供系统使用
// */
// private ObjectName objectName;
//
// @Override
// public FalconReportObject clone() {
// try {
// return (FalconReportObject) super.clone();
// } catch (CloneNotSupportedException e) {
// return new FalconReportObject();
// }
// }
//
// /**
// * 添加tag
// * @param newTag
// * @return
// */
// public FalconReportObject appendTags(String newTag){
// if(!StringUtils.isEmpty(newTag)){
// if(StringUtils.isEmpty(this.getTags())){
// this.setTags(newTag);
// }else{
// this.setTags(this.getTags() + "," + newTag);
// }
// }
// return this;
// }
//
// }
//
// Path: src/main/java/com/yiji/falcon/agent/vo/jdbc/JDBCConnectionInfo.java
// @Data
// public class JDBCConnectionInfo {
// private String url;
// private String username;
// private String password;
//
// public JDBCConnectionInfo(String url, String username, String password) {
// this.url = url;
// this.username = username;
// this.password = password;
// }
// }
| import com.yiji.falcon.agent.falcon.FalconReportObject;
import com.yiji.falcon.agent.vo.jdbc.JDBCConnectionInfo;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection; | /*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
package com.yiji.falcon.agent.plugins;
/*
* 修订记录:
* [email protected] 2016-06-23 15:46 创建
*/
/**
* JDBC 插件接口
* @author [email protected]
*/
public interface JDBCPlugin extends Plugin{
/**
* 数据库的JDBC连接驱动名称
* @return
*/
String getJDBCDriveName();
/**
* 数据库的连接对象集合
* 系统将根据此对象建立数据库连接
* @return
*/ | // Path: src/main/java/com/yiji/falcon/agent/falcon/FalconReportObject.java
// @Data
// public class FalconReportObject implements Cloneable{
//
// /**
// * 标明Metric的主体(属主),比如metric是cpu_idle,那么Endpoint就表示这是哪台机器的cpu_idle
// */
// private String endpoint;
// /**
// * 最核心的字段,代表这个采集项具体度量的是什么, 比如是cpu_idle呢,还是memory_free, 还是qps
// */
// private String metric;
// /**
// * 表示汇报该数据时的unix时间戳,注意是整数,代表的是秒
// */
// private long timestamp;
// /**
// * 表示该数据采集项的汇报周期,这对于后续的配置监控策略很重要,必须明确指定。
// */
// private int step;
// /**
// * 代表该metric在当前时间点的值,数值类型
// */
// private String value;
// /**
// * 只能是COUNTER或者GAUGE二选一,前者表示该数据采集项为计时器类型,后者表示其为原值 (注意大小写)
// GAUGE:即用户上传什么样的值,就原封不动的存储
// COUNTER:指标在存储和展现的时候,会被计算为speed,即(当前值 - 上次值)/ 时间间隔
// */
// private CounterType counterType;
// /**
// * 一组逗号分割的键值对, 对metric进一步描述和细化, 可以是空字符串. 比如idc=lg,比如service=xbox等,多个tag之间用逗号分割
// */
// private String tags;
//
// /**
// * 仅供系统使用
// */
// private ObjectName objectName;
//
// @Override
// public FalconReportObject clone() {
// try {
// return (FalconReportObject) super.clone();
// } catch (CloneNotSupportedException e) {
// return new FalconReportObject();
// }
// }
//
// /**
// * 添加tag
// * @param newTag
// * @return
// */
// public FalconReportObject appendTags(String newTag){
// if(!StringUtils.isEmpty(newTag)){
// if(StringUtils.isEmpty(this.getTags())){
// this.setTags(newTag);
// }else{
// this.setTags(this.getTags() + "," + newTag);
// }
// }
// return this;
// }
//
// }
//
// Path: src/main/java/com/yiji/falcon/agent/vo/jdbc/JDBCConnectionInfo.java
// @Data
// public class JDBCConnectionInfo {
// private String url;
// private String username;
// private String password;
//
// public JDBCConnectionInfo(String url, String username, String password) {
// this.url = url;
// this.username = username;
// this.password = password;
// }
// }
// Path: src/main/java/com/yiji/falcon/agent/plugins/JDBCPlugin.java
import com.yiji.falcon.agent.falcon.FalconReportObject;
import com.yiji.falcon.agent.vo.jdbc.JDBCConnectionInfo;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
/*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
package com.yiji.falcon.agent.plugins;
/*
* 修订记录:
* [email protected] 2016-06-23 15:46 创建
*/
/**
* JDBC 插件接口
* @author [email protected]
*/
public interface JDBCPlugin extends Plugin{
/**
* 数据库的JDBC连接驱动名称
* @return
*/
String getJDBCDriveName();
/**
* 数据库的连接对象集合
* 系统将根据此对象建立数据库连接
* @return
*/ | Collection<JDBCConnectionInfo> getConnectionInfos(); |
cqyijifu/OpenFalcon-SuitAgent | src/main/java/com/yiji/falcon/agent/plugins/util/SNMPV3Session.java | // Path: src/main/java/com/yiji/falcon/agent/exception/AgentArgumentException.java
// public class AgentArgumentException extends Exception {
//
// private String err;
//
// /**
// * Constructs a new exception with the specified detail message. The
// * cause is not initialized, and may subsequently be initialized by
// * a call to {@link #initCause}.
// *
// * @param err the detail message. The detail message is saved for
// * later retrieval by the {@link #getMessage()} method.
// */
// public AgentArgumentException(String err) {
// super(err);
// this.err = err;
// }
//
// public String getErr() {
// return err;
// }
//
// }
//
// Path: src/main/java/com/yiji/falcon/agent/util/StringUtils.java
// public class StringUtils {
//
// /**
// * 判断传入的String是否为空('' or null)
// * @param str
// * @return
// */
// public static boolean isEmpty(String str){
// return str == null || str.length() == 0;
// }
//
// /**
// * 返回指定数字的字符串形式
// * @param value
// * @return
// */
// public static String getStringByInt(int value){
// return String.valueOf(value).intern();
// }
//
// }
//
// Path: src/main/java/com/yiji/falcon/agent/vo/snmp/SNMPV3UserInfo.java
// @Data
// public class SNMPV3UserInfo {
//
// /**
// * 网络协议 如udp、tcp
// */
// private String protocol = "udp";
// /**
// * 网络设备的IP地址
// */
// private String address = "";
// /**
// * 网络设备的连接端口号
// */
// private String port = "161";
// /**
// * 用户名
// */
// private String username = "";
// /**
// * 认证算法,如 none,MD5,SHA
// */
// private String aythType = "";
// /**
// * 认证密码
// */
// private String authPswd = "";
// /**
// * 加密算法,如 none,DES,3DES,AES128,AES,AES192,AES256
// */
// private String privType = "";
// /**
// * 加密密码
// */
// private String privPswd = "";
// /**
// * endPoint
// */
// private String endPoint = "";
//
// /**
// * 允许采集哪些名称的接口数据
// * 注:只采集集合中的接口名称的数据。若为空,则不会采集接口数据
// */
// private List<String> ifCollectNameEnables;
//
// }
| import com.yiji.falcon.agent.exception.AgentArgumentException;
import com.yiji.falcon.agent.util.StringUtils;
import com.yiji.falcon.agent.vo.snmp.SNMPV3UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.UserTarget;
import org.snmp4j.mp.MPv3;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.security.*;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap; | /*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
package com.yiji.falcon.agent.plugins.util;
/*
* 修订记录:
* [email protected] 2016-07-12 10:47 创建
*/
/**
* @author [email protected]
*/
@Slf4j
public class SNMPV3Session {
// private static final String cacheKey_equipmentName = "equipmentName";
private static final String cacheKey_sysDesc = "sysDesc";
private static final String cacheKey_sysVendor = "sysVendor";
private static final String cacheKey_version = "version";
private Snmp snmp;
private UserTarget target; | // Path: src/main/java/com/yiji/falcon/agent/exception/AgentArgumentException.java
// public class AgentArgumentException extends Exception {
//
// private String err;
//
// /**
// * Constructs a new exception with the specified detail message. The
// * cause is not initialized, and may subsequently be initialized by
// * a call to {@link #initCause}.
// *
// * @param err the detail message. The detail message is saved for
// * later retrieval by the {@link #getMessage()} method.
// */
// public AgentArgumentException(String err) {
// super(err);
// this.err = err;
// }
//
// public String getErr() {
// return err;
// }
//
// }
//
// Path: src/main/java/com/yiji/falcon/agent/util/StringUtils.java
// public class StringUtils {
//
// /**
// * 判断传入的String是否为空('' or null)
// * @param str
// * @return
// */
// public static boolean isEmpty(String str){
// return str == null || str.length() == 0;
// }
//
// /**
// * 返回指定数字的字符串形式
// * @param value
// * @return
// */
// public static String getStringByInt(int value){
// return String.valueOf(value).intern();
// }
//
// }
//
// Path: src/main/java/com/yiji/falcon/agent/vo/snmp/SNMPV3UserInfo.java
// @Data
// public class SNMPV3UserInfo {
//
// /**
// * 网络协议 如udp、tcp
// */
// private String protocol = "udp";
// /**
// * 网络设备的IP地址
// */
// private String address = "";
// /**
// * 网络设备的连接端口号
// */
// private String port = "161";
// /**
// * 用户名
// */
// private String username = "";
// /**
// * 认证算法,如 none,MD5,SHA
// */
// private String aythType = "";
// /**
// * 认证密码
// */
// private String authPswd = "";
// /**
// * 加密算法,如 none,DES,3DES,AES128,AES,AES192,AES256
// */
// private String privType = "";
// /**
// * 加密密码
// */
// private String privPswd = "";
// /**
// * endPoint
// */
// private String endPoint = "";
//
// /**
// * 允许采集哪些名称的接口数据
// * 注:只采集集合中的接口名称的数据。若为空,则不会采集接口数据
// */
// private List<String> ifCollectNameEnables;
//
// }
// Path: src/main/java/com/yiji/falcon/agent/plugins/util/SNMPV3Session.java
import com.yiji.falcon.agent.exception.AgentArgumentException;
import com.yiji.falcon.agent.util.StringUtils;
import com.yiji.falcon.agent.vo.snmp.SNMPV3UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.UserTarget;
import org.snmp4j.mp.MPv3;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.security.*;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
/*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
package com.yiji.falcon.agent.plugins.util;
/*
* 修订记录:
* [email protected] 2016-07-12 10:47 创建
*/
/**
* @author [email protected]
*/
@Slf4j
public class SNMPV3Session {
// private static final String cacheKey_equipmentName = "equipmentName";
private static final String cacheKey_sysDesc = "sysDesc";
private static final String cacheKey_sysVendor = "sysVendor";
private static final String cacheKey_version = "version";
private Snmp snmp;
private UserTarget target; | private SNMPV3UserInfo userInfo; |
cqyijifu/OpenFalcon-SuitAgent | src/main/java/com/yiji/falcon/agent/plugins/util/SNMPV3Session.java | // Path: src/main/java/com/yiji/falcon/agent/exception/AgentArgumentException.java
// public class AgentArgumentException extends Exception {
//
// private String err;
//
// /**
// * Constructs a new exception with the specified detail message. The
// * cause is not initialized, and may subsequently be initialized by
// * a call to {@link #initCause}.
// *
// * @param err the detail message. The detail message is saved for
// * later retrieval by the {@link #getMessage()} method.
// */
// public AgentArgumentException(String err) {
// super(err);
// this.err = err;
// }
//
// public String getErr() {
// return err;
// }
//
// }
//
// Path: src/main/java/com/yiji/falcon/agent/util/StringUtils.java
// public class StringUtils {
//
// /**
// * 判断传入的String是否为空('' or null)
// * @param str
// * @return
// */
// public static boolean isEmpty(String str){
// return str == null || str.length() == 0;
// }
//
// /**
// * 返回指定数字的字符串形式
// * @param value
// * @return
// */
// public static String getStringByInt(int value){
// return String.valueOf(value).intern();
// }
//
// }
//
// Path: src/main/java/com/yiji/falcon/agent/vo/snmp/SNMPV3UserInfo.java
// @Data
// public class SNMPV3UserInfo {
//
// /**
// * 网络协议 如udp、tcp
// */
// private String protocol = "udp";
// /**
// * 网络设备的IP地址
// */
// private String address = "";
// /**
// * 网络设备的连接端口号
// */
// private String port = "161";
// /**
// * 用户名
// */
// private String username = "";
// /**
// * 认证算法,如 none,MD5,SHA
// */
// private String aythType = "";
// /**
// * 认证密码
// */
// private String authPswd = "";
// /**
// * 加密算法,如 none,DES,3DES,AES128,AES,AES192,AES256
// */
// private String privType = "";
// /**
// * 加密密码
// */
// private String privPswd = "";
// /**
// * endPoint
// */
// private String endPoint = "";
//
// /**
// * 允许采集哪些名称的接口数据
// * 注:只采集集合中的接口名称的数据。若为空,则不会采集接口数据
// */
// private List<String> ifCollectNameEnables;
//
// }
| import com.yiji.falcon.agent.exception.AgentArgumentException;
import com.yiji.falcon.agent.util.StringUtils;
import com.yiji.falcon.agent.vo.snmp.SNMPV3UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.UserTarget;
import org.snmp4j.mp.MPv3;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.security.*;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap; | /*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
package com.yiji.falcon.agent.plugins.util;
/*
* 修订记录:
* [email protected] 2016-07-12 10:47 创建
*/
/**
* @author [email protected]
*/
@Slf4j
public class SNMPV3Session {
// private static final String cacheKey_equipmentName = "equipmentName";
private static final String cacheKey_sysDesc = "sysDesc";
private static final String cacheKey_sysVendor = "sysVendor";
private static final String cacheKey_version = "version";
private Snmp snmp;
private UserTarget target;
private SNMPV3UserInfo userInfo;
//信息缓存
private final ConcurrentHashMap<String,Object> infoCache = new ConcurrentHashMap<>();
@Override
public String toString() {
return "SNMPV3Session{" +
"snmp=" + snmp +
", target=" + target +
", userInfo=" + userInfo +
'}';
}
/**
* 创建SNMPV3会话
* @param userInfo
* @throws IOException
* @throws AgentArgumentException
*/ | // Path: src/main/java/com/yiji/falcon/agent/exception/AgentArgumentException.java
// public class AgentArgumentException extends Exception {
//
// private String err;
//
// /**
// * Constructs a new exception with the specified detail message. The
// * cause is not initialized, and may subsequently be initialized by
// * a call to {@link #initCause}.
// *
// * @param err the detail message. The detail message is saved for
// * later retrieval by the {@link #getMessage()} method.
// */
// public AgentArgumentException(String err) {
// super(err);
// this.err = err;
// }
//
// public String getErr() {
// return err;
// }
//
// }
//
// Path: src/main/java/com/yiji/falcon/agent/util/StringUtils.java
// public class StringUtils {
//
// /**
// * 判断传入的String是否为空('' or null)
// * @param str
// * @return
// */
// public static boolean isEmpty(String str){
// return str == null || str.length() == 0;
// }
//
// /**
// * 返回指定数字的字符串形式
// * @param value
// * @return
// */
// public static String getStringByInt(int value){
// return String.valueOf(value).intern();
// }
//
// }
//
// Path: src/main/java/com/yiji/falcon/agent/vo/snmp/SNMPV3UserInfo.java
// @Data
// public class SNMPV3UserInfo {
//
// /**
// * 网络协议 如udp、tcp
// */
// private String protocol = "udp";
// /**
// * 网络设备的IP地址
// */
// private String address = "";
// /**
// * 网络设备的连接端口号
// */
// private String port = "161";
// /**
// * 用户名
// */
// private String username = "";
// /**
// * 认证算法,如 none,MD5,SHA
// */
// private String aythType = "";
// /**
// * 认证密码
// */
// private String authPswd = "";
// /**
// * 加密算法,如 none,DES,3DES,AES128,AES,AES192,AES256
// */
// private String privType = "";
// /**
// * 加密密码
// */
// private String privPswd = "";
// /**
// * endPoint
// */
// private String endPoint = "";
//
// /**
// * 允许采集哪些名称的接口数据
// * 注:只采集集合中的接口名称的数据。若为空,则不会采集接口数据
// */
// private List<String> ifCollectNameEnables;
//
// }
// Path: src/main/java/com/yiji/falcon/agent/plugins/util/SNMPV3Session.java
import com.yiji.falcon.agent.exception.AgentArgumentException;
import com.yiji.falcon.agent.util.StringUtils;
import com.yiji.falcon.agent.vo.snmp.SNMPV3UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.UserTarget;
import org.snmp4j.mp.MPv3;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.security.*;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
/*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
package com.yiji.falcon.agent.plugins.util;
/*
* 修订记录:
* [email protected] 2016-07-12 10:47 创建
*/
/**
* @author [email protected]
*/
@Slf4j
public class SNMPV3Session {
// private static final String cacheKey_equipmentName = "equipmentName";
private static final String cacheKey_sysDesc = "sysDesc";
private static final String cacheKey_sysVendor = "sysVendor";
private static final String cacheKey_version = "version";
private Snmp snmp;
private UserTarget target;
private SNMPV3UserInfo userInfo;
//信息缓存
private final ConcurrentHashMap<String,Object> infoCache = new ConcurrentHashMap<>();
@Override
public String toString() {
return "SNMPV3Session{" +
"snmp=" + snmp +
", target=" + target +
", userInfo=" + userInfo +
'}';
}
/**
* 创建SNMPV3会话
* @param userInfo
* @throws IOException
* @throws AgentArgumentException
*/ | public SNMPV3Session(SNMPV3UserInfo userInfo) throws IOException, AgentArgumentException { |
cqyijifu/OpenFalcon-SuitAgent | src/main/java/com/yiji/falcon/agent/plugins/util/SNMPV3Session.java | // Path: src/main/java/com/yiji/falcon/agent/exception/AgentArgumentException.java
// public class AgentArgumentException extends Exception {
//
// private String err;
//
// /**
// * Constructs a new exception with the specified detail message. The
// * cause is not initialized, and may subsequently be initialized by
// * a call to {@link #initCause}.
// *
// * @param err the detail message. The detail message is saved for
// * later retrieval by the {@link #getMessage()} method.
// */
// public AgentArgumentException(String err) {
// super(err);
// this.err = err;
// }
//
// public String getErr() {
// return err;
// }
//
// }
//
// Path: src/main/java/com/yiji/falcon/agent/util/StringUtils.java
// public class StringUtils {
//
// /**
// * 判断传入的String是否为空('' or null)
// * @param str
// * @return
// */
// public static boolean isEmpty(String str){
// return str == null || str.length() == 0;
// }
//
// /**
// * 返回指定数字的字符串形式
// * @param value
// * @return
// */
// public static String getStringByInt(int value){
// return String.valueOf(value).intern();
// }
//
// }
//
// Path: src/main/java/com/yiji/falcon/agent/vo/snmp/SNMPV3UserInfo.java
// @Data
// public class SNMPV3UserInfo {
//
// /**
// * 网络协议 如udp、tcp
// */
// private String protocol = "udp";
// /**
// * 网络设备的IP地址
// */
// private String address = "";
// /**
// * 网络设备的连接端口号
// */
// private String port = "161";
// /**
// * 用户名
// */
// private String username = "";
// /**
// * 认证算法,如 none,MD5,SHA
// */
// private String aythType = "";
// /**
// * 认证密码
// */
// private String authPswd = "";
// /**
// * 加密算法,如 none,DES,3DES,AES128,AES,AES192,AES256
// */
// private String privType = "";
// /**
// * 加密密码
// */
// private String privPswd = "";
// /**
// * endPoint
// */
// private String endPoint = "";
//
// /**
// * 允许采集哪些名称的接口数据
// * 注:只采集集合中的接口名称的数据。若为空,则不会采集接口数据
// */
// private List<String> ifCollectNameEnables;
//
// }
| import com.yiji.falcon.agent.exception.AgentArgumentException;
import com.yiji.falcon.agent.util.StringUtils;
import com.yiji.falcon.agent.vo.snmp.SNMPV3UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.UserTarget;
import org.snmp4j.mp.MPv3;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.security.*;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap; | /*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
package com.yiji.falcon.agent.plugins.util;
/*
* 修订记录:
* [email protected] 2016-07-12 10:47 创建
*/
/**
* @author [email protected]
*/
@Slf4j
public class SNMPV3Session {
// private static final String cacheKey_equipmentName = "equipmentName";
private static final String cacheKey_sysDesc = "sysDesc";
private static final String cacheKey_sysVendor = "sysVendor";
private static final String cacheKey_version = "version";
private Snmp snmp;
private UserTarget target;
private SNMPV3UserInfo userInfo;
//信息缓存
private final ConcurrentHashMap<String,Object> infoCache = new ConcurrentHashMap<>();
@Override
public String toString() {
return "SNMPV3Session{" +
"snmp=" + snmp +
", target=" + target +
", userInfo=" + userInfo +
'}';
}
/**
* 创建SNMPV3会话
* @param userInfo
* @throws IOException
* @throws AgentArgumentException
*/
public SNMPV3Session(SNMPV3UserInfo userInfo) throws IOException, AgentArgumentException { | // Path: src/main/java/com/yiji/falcon/agent/exception/AgentArgumentException.java
// public class AgentArgumentException extends Exception {
//
// private String err;
//
// /**
// * Constructs a new exception with the specified detail message. The
// * cause is not initialized, and may subsequently be initialized by
// * a call to {@link #initCause}.
// *
// * @param err the detail message. The detail message is saved for
// * later retrieval by the {@link #getMessage()} method.
// */
// public AgentArgumentException(String err) {
// super(err);
// this.err = err;
// }
//
// public String getErr() {
// return err;
// }
//
// }
//
// Path: src/main/java/com/yiji/falcon/agent/util/StringUtils.java
// public class StringUtils {
//
// /**
// * 判断传入的String是否为空('' or null)
// * @param str
// * @return
// */
// public static boolean isEmpty(String str){
// return str == null || str.length() == 0;
// }
//
// /**
// * 返回指定数字的字符串形式
// * @param value
// * @return
// */
// public static String getStringByInt(int value){
// return String.valueOf(value).intern();
// }
//
// }
//
// Path: src/main/java/com/yiji/falcon/agent/vo/snmp/SNMPV3UserInfo.java
// @Data
// public class SNMPV3UserInfo {
//
// /**
// * 网络协议 如udp、tcp
// */
// private String protocol = "udp";
// /**
// * 网络设备的IP地址
// */
// private String address = "";
// /**
// * 网络设备的连接端口号
// */
// private String port = "161";
// /**
// * 用户名
// */
// private String username = "";
// /**
// * 认证算法,如 none,MD5,SHA
// */
// private String aythType = "";
// /**
// * 认证密码
// */
// private String authPswd = "";
// /**
// * 加密算法,如 none,DES,3DES,AES128,AES,AES192,AES256
// */
// private String privType = "";
// /**
// * 加密密码
// */
// private String privPswd = "";
// /**
// * endPoint
// */
// private String endPoint = "";
//
// /**
// * 允许采集哪些名称的接口数据
// * 注:只采集集合中的接口名称的数据。若为空,则不会采集接口数据
// */
// private List<String> ifCollectNameEnables;
//
// }
// Path: src/main/java/com/yiji/falcon/agent/plugins/util/SNMPV3Session.java
import com.yiji.falcon.agent.exception.AgentArgumentException;
import com.yiji.falcon.agent.util.StringUtils;
import com.yiji.falcon.agent.vo.snmp.SNMPV3UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.UserTarget;
import org.snmp4j.mp.MPv3;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.security.*;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
/*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
package com.yiji.falcon.agent.plugins.util;
/*
* 修订记录:
* [email protected] 2016-07-12 10:47 创建
*/
/**
* @author [email protected]
*/
@Slf4j
public class SNMPV3Session {
// private static final String cacheKey_equipmentName = "equipmentName";
private static final String cacheKey_sysDesc = "sysDesc";
private static final String cacheKey_sysVendor = "sysVendor";
private static final String cacheKey_version = "version";
private Snmp snmp;
private UserTarget target;
private SNMPV3UserInfo userInfo;
//信息缓存
private final ConcurrentHashMap<String,Object> infoCache = new ConcurrentHashMap<>();
@Override
public String toString() {
return "SNMPV3Session{" +
"snmp=" + snmp +
", target=" + target +
", userInfo=" + userInfo +
'}';
}
/**
* 创建SNMPV3会话
* @param userInfo
* @throws IOException
* @throws AgentArgumentException
*/
public SNMPV3Session(SNMPV3UserInfo userInfo) throws IOException, AgentArgumentException { | if(StringUtils.isEmpty(userInfo.getAddress())){ |
cqyijifu/OpenFalcon-SuitAgent | src/main/java/com/yiji/falcon/agent/plugins/DetectPlugin.java | // Path: src/main/java/com/yiji/falcon/agent/plugins/util/PluginActivateType.java
// public enum PluginActivateType {
// /**
// * 插件不运行
// */
// DISABLED("不启用"),
// /**
// * 无论服务是否运行,都启动插件
// */
// FORCE("强制启动"),
// /**
// * 当监控服务可用时,自动进行插件启动
// */
// AUTO("自动运行");
//
// /**
// * 活动描述
// */
// private String desc;
//
// PluginActivateType(String desc) {
// this.desc = desc;
// }
//
// public String getDesc() {
// return desc;
// }
// }
//
// Path: src/main/java/com/yiji/falcon/agent/util/StringUtils.java
// public class StringUtils {
//
// /**
// * 判断传入的String是否为空('' or null)
// * @param str
// * @return
// */
// public static boolean isEmpty(String str){
// return str == null || str.length() == 0;
// }
//
// /**
// * 返回指定数字的字符串形式
// * @param value
// * @return
// */
// public static String getStringByInt(int value){
// return String.valueOf(value).intern();
// }
//
// }
//
// Path: src/main/java/com/yiji/falcon/agent/vo/detect/DetectResult.java
// @Data
// public class DetectResult {
//
// /**
// * 探测结果,Agent将根据此属性进行探测地址的可用性上报
// */
// private boolean success;
//
// /**
// * 自定义的监控值
// * Agent会将此Map中的key当做metrics名称,{@link com.yiji.falcon.agent.vo.detect.DetectResult.Metric} 对象组建上报值进行上报
// */
// private List<Metric> metricsList;
//
//
// /**
// * 自定义的公共的tag信息
// * 形如tag1={tag1},tag2={tag2}
// * 设置后,将会对每个监控值都会打上此tag
// */
// private String commonTag;
//
// @ToString
// public static class Metric{
// /**
// * 自定义监控名
// */
// public String metricName;
// /**
// * 自定义监控值的value
// */
// public String value;
// /**
// * 自定义监控值的上报类型
// */
// public CounterType counterType;
// /**
// * 自定义监控值的tag
// */
// public String tags;
//
// /**
// * @param metricName
// * @param value
// * @param counterType
// * @param tags
// */
// public Metric(String metricName,String value, CounterType counterType, String tags) {
// this.metricName = metricName;
// this.value = value;
// this.counterType = counterType;
// this.tags = tags;
// }
// }
// }
| import com.yiji.falcon.agent.plugins.util.PluginActivateType;
import com.yiji.falcon.agent.util.StringUtils;
import com.yiji.falcon.agent.vo.detect.DetectResult;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set; | /*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
package com.yiji.falcon.agent.plugins;
/*
* 修订记录:
* [email protected] 2016-07-21 14:57 创建
*/
/**
* 探测监控插件
* @author [email protected]
*/
public interface DetectPlugin extends Plugin {
/**
* 监控的具体服务的agentSignName tag值
* @param address
* 被监控的探测地址
* @return
* 根据地址提炼的标识,如域名等
*/
String agentSignName(String address);
/**
* 一次地址的探测结果
* @param address
* 被探测的地址,地址来源于方法 {@link com.yiji.falcon.agent.plugins.DetectPlugin#detectAddressCollection()}
* @return
* 返回被探测的地址的探测结果,将用于上报监控状态
*/ | // Path: src/main/java/com/yiji/falcon/agent/plugins/util/PluginActivateType.java
// public enum PluginActivateType {
// /**
// * 插件不运行
// */
// DISABLED("不启用"),
// /**
// * 无论服务是否运行,都启动插件
// */
// FORCE("强制启动"),
// /**
// * 当监控服务可用时,自动进行插件启动
// */
// AUTO("自动运行");
//
// /**
// * 活动描述
// */
// private String desc;
//
// PluginActivateType(String desc) {
// this.desc = desc;
// }
//
// public String getDesc() {
// return desc;
// }
// }
//
// Path: src/main/java/com/yiji/falcon/agent/util/StringUtils.java
// public class StringUtils {
//
// /**
// * 判断传入的String是否为空('' or null)
// * @param str
// * @return
// */
// public static boolean isEmpty(String str){
// return str == null || str.length() == 0;
// }
//
// /**
// * 返回指定数字的字符串形式
// * @param value
// * @return
// */
// public static String getStringByInt(int value){
// return String.valueOf(value).intern();
// }
//
// }
//
// Path: src/main/java/com/yiji/falcon/agent/vo/detect/DetectResult.java
// @Data
// public class DetectResult {
//
// /**
// * 探测结果,Agent将根据此属性进行探测地址的可用性上报
// */
// private boolean success;
//
// /**
// * 自定义的监控值
// * Agent会将此Map中的key当做metrics名称,{@link com.yiji.falcon.agent.vo.detect.DetectResult.Metric} 对象组建上报值进行上报
// */
// private List<Metric> metricsList;
//
//
// /**
// * 自定义的公共的tag信息
// * 形如tag1={tag1},tag2={tag2}
// * 设置后,将会对每个监控值都会打上此tag
// */
// private String commonTag;
//
// @ToString
// public static class Metric{
// /**
// * 自定义监控名
// */
// public String metricName;
// /**
// * 自定义监控值的value
// */
// public String value;
// /**
// * 自定义监控值的上报类型
// */
// public CounterType counterType;
// /**
// * 自定义监控值的tag
// */
// public String tags;
//
// /**
// * @param metricName
// * @param value
// * @param counterType
// * @param tags
// */
// public Metric(String metricName,String value, CounterType counterType, String tags) {
// this.metricName = metricName;
// this.value = value;
// this.counterType = counterType;
// this.tags = tags;
// }
// }
// }
// Path: src/main/java/com/yiji/falcon/agent/plugins/DetectPlugin.java
import com.yiji.falcon.agent.plugins.util.PluginActivateType;
import com.yiji.falcon.agent.util.StringUtils;
import com.yiji.falcon.agent.vo.detect.DetectResult;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
package com.yiji.falcon.agent.plugins;
/*
* 修订记录:
* [email protected] 2016-07-21 14:57 创建
*/
/**
* 探测监控插件
* @author [email protected]
*/
public interface DetectPlugin extends Plugin {
/**
* 监控的具体服务的agentSignName tag值
* @param address
* 被监控的探测地址
* @return
* 根据地址提炼的标识,如域名等
*/
String agentSignName(String address);
/**
* 一次地址的探测结果
* @param address
* 被探测的地址,地址来源于方法 {@link com.yiji.falcon.agent.plugins.DetectPlugin#detectAddressCollection()}
* @return
* 返回被探测的地址的探测结果,将用于上报监控状态
*/ | DetectResult detectResult(String address); |
cqyijifu/OpenFalcon-SuitAgent | src/main/java/com/yiji/falcon/agent/plugins/DetectPlugin.java | // Path: src/main/java/com/yiji/falcon/agent/plugins/util/PluginActivateType.java
// public enum PluginActivateType {
// /**
// * 插件不运行
// */
// DISABLED("不启用"),
// /**
// * 无论服务是否运行,都启动插件
// */
// FORCE("强制启动"),
// /**
// * 当监控服务可用时,自动进行插件启动
// */
// AUTO("自动运行");
//
// /**
// * 活动描述
// */
// private String desc;
//
// PluginActivateType(String desc) {
// this.desc = desc;
// }
//
// public String getDesc() {
// return desc;
// }
// }
//
// Path: src/main/java/com/yiji/falcon/agent/util/StringUtils.java
// public class StringUtils {
//
// /**
// * 判断传入的String是否为空('' or null)
// * @param str
// * @return
// */
// public static boolean isEmpty(String str){
// return str == null || str.length() == 0;
// }
//
// /**
// * 返回指定数字的字符串形式
// * @param value
// * @return
// */
// public static String getStringByInt(int value){
// return String.valueOf(value).intern();
// }
//
// }
//
// Path: src/main/java/com/yiji/falcon/agent/vo/detect/DetectResult.java
// @Data
// public class DetectResult {
//
// /**
// * 探测结果,Agent将根据此属性进行探测地址的可用性上报
// */
// private boolean success;
//
// /**
// * 自定义的监控值
// * Agent会将此Map中的key当做metrics名称,{@link com.yiji.falcon.agent.vo.detect.DetectResult.Metric} 对象组建上报值进行上报
// */
// private List<Metric> metricsList;
//
//
// /**
// * 自定义的公共的tag信息
// * 形如tag1={tag1},tag2={tag2}
// * 设置后,将会对每个监控值都会打上此tag
// */
// private String commonTag;
//
// @ToString
// public static class Metric{
// /**
// * 自定义监控名
// */
// public String metricName;
// /**
// * 自定义监控值的value
// */
// public String value;
// /**
// * 自定义监控值的上报类型
// */
// public CounterType counterType;
// /**
// * 自定义监控值的tag
// */
// public String tags;
//
// /**
// * @param metricName
// * @param value
// * @param counterType
// * @param tags
// */
// public Metric(String metricName,String value, CounterType counterType, String tags) {
// this.metricName = metricName;
// this.value = value;
// this.counterType = counterType;
// this.tags = tags;
// }
// }
// }
| import com.yiji.falcon.agent.plugins.util.PluginActivateType;
import com.yiji.falcon.agent.util.StringUtils;
import com.yiji.falcon.agent.vo.detect.DetectResult;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set; | /*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
package com.yiji.falcon.agent.plugins;
/*
* 修订记录:
* [email protected] 2016-07-21 14:57 创建
*/
/**
* 探测监控插件
* @author [email protected]
*/
public interface DetectPlugin extends Plugin {
/**
* 监控的具体服务的agentSignName tag值
* @param address
* 被监控的探测地址
* @return
* 根据地址提炼的标识,如域名等
*/
String agentSignName(String address);
/**
* 一次地址的探测结果
* @param address
* 被探测的地址,地址来源于方法 {@link com.yiji.falcon.agent.plugins.DetectPlugin#detectAddressCollection()}
* @return
* 返回被探测的地址的探测结果,将用于上报监控状态
*/
DetectResult detectResult(String address);
/**
* 被探测的地址集合
* @return
* 只要该集合不为空,就会触发监控
* pluginActivateType属性将不起作用
*/
Collection<String> detectAddressCollection();
/**
* 无需配置该属性,此类插件pluginActivateType属性将不起作用
* 运行方式见 {@link com.yiji.falcon.agent.plugins.DetectPlugin#detectAddressCollection()}
*
* 插件运行方式
*
* @return
*/
@Override | // Path: src/main/java/com/yiji/falcon/agent/plugins/util/PluginActivateType.java
// public enum PluginActivateType {
// /**
// * 插件不运行
// */
// DISABLED("不启用"),
// /**
// * 无论服务是否运行,都启动插件
// */
// FORCE("强制启动"),
// /**
// * 当监控服务可用时,自动进行插件启动
// */
// AUTO("自动运行");
//
// /**
// * 活动描述
// */
// private String desc;
//
// PluginActivateType(String desc) {
// this.desc = desc;
// }
//
// public String getDesc() {
// return desc;
// }
// }
//
// Path: src/main/java/com/yiji/falcon/agent/util/StringUtils.java
// public class StringUtils {
//
// /**
// * 判断传入的String是否为空('' or null)
// * @param str
// * @return
// */
// public static boolean isEmpty(String str){
// return str == null || str.length() == 0;
// }
//
// /**
// * 返回指定数字的字符串形式
// * @param value
// * @return
// */
// public static String getStringByInt(int value){
// return String.valueOf(value).intern();
// }
//
// }
//
// Path: src/main/java/com/yiji/falcon/agent/vo/detect/DetectResult.java
// @Data
// public class DetectResult {
//
// /**
// * 探测结果,Agent将根据此属性进行探测地址的可用性上报
// */
// private boolean success;
//
// /**
// * 自定义的监控值
// * Agent会将此Map中的key当做metrics名称,{@link com.yiji.falcon.agent.vo.detect.DetectResult.Metric} 对象组建上报值进行上报
// */
// private List<Metric> metricsList;
//
//
// /**
// * 自定义的公共的tag信息
// * 形如tag1={tag1},tag2={tag2}
// * 设置后,将会对每个监控值都会打上此tag
// */
// private String commonTag;
//
// @ToString
// public static class Metric{
// /**
// * 自定义监控名
// */
// public String metricName;
// /**
// * 自定义监控值的value
// */
// public String value;
// /**
// * 自定义监控值的上报类型
// */
// public CounterType counterType;
// /**
// * 自定义监控值的tag
// */
// public String tags;
//
// /**
// * @param metricName
// * @param value
// * @param counterType
// * @param tags
// */
// public Metric(String metricName,String value, CounterType counterType, String tags) {
// this.metricName = metricName;
// this.value = value;
// this.counterType = counterType;
// this.tags = tags;
// }
// }
// }
// Path: src/main/java/com/yiji/falcon/agent/plugins/DetectPlugin.java
import com.yiji.falcon.agent.plugins.util.PluginActivateType;
import com.yiji.falcon.agent.util.StringUtils;
import com.yiji.falcon.agent.vo.detect.DetectResult;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
package com.yiji.falcon.agent.plugins;
/*
* 修订记录:
* [email protected] 2016-07-21 14:57 创建
*/
/**
* 探测监控插件
* @author [email protected]
*/
public interface DetectPlugin extends Plugin {
/**
* 监控的具体服务的agentSignName tag值
* @param address
* 被监控的探测地址
* @return
* 根据地址提炼的标识,如域名等
*/
String agentSignName(String address);
/**
* 一次地址的探测结果
* @param address
* 被探测的地址,地址来源于方法 {@link com.yiji.falcon.agent.plugins.DetectPlugin#detectAddressCollection()}
* @return
* 返回被探测的地址的探测结果,将用于上报监控状态
*/
DetectResult detectResult(String address);
/**
* 被探测的地址集合
* @return
* 只要该集合不为空,就会触发监控
* pluginActivateType属性将不起作用
*/
Collection<String> detectAddressCollection();
/**
* 无需配置该属性,此类插件pluginActivateType属性将不起作用
* 运行方式见 {@link com.yiji.falcon.agent.plugins.DetectPlugin#detectAddressCollection()}
*
* 插件运行方式
*
* @return
*/
@Override | default PluginActivateType activateType(){ |
cqyijifu/OpenFalcon-SuitAgent | src/main/java/com/yiji/falcon/agent/util/HttpUtil.java | // Path: src/main/java/com/yiji/falcon/agent/vo/HttpResult.java
// @Data
// public class HttpResult {
//
// /**
// * 状态码
// */
// private int status;
// /**
// * 返回结果
// */
// private String result;
//
// /**
// * 响应时间
// */
// private long responseTime;
// }
| import com.github.kevinsawicki.http.HttpRequest;
import com.yiji.falcon.agent.vo.HttpResult;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | /*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
package com.yiji.falcon.agent.util;
/*
* 修订记录:
* [email protected] 2016-06-22 17:48 创建
*/
/**
* @author [email protected]
*/
@Slf4j
public class HttpUtil {
/**
* 发送json post请求
* @param url
* @param data
* @return
* @throws IOException
*/ | // Path: src/main/java/com/yiji/falcon/agent/vo/HttpResult.java
// @Data
// public class HttpResult {
//
// /**
// * 状态码
// */
// private int status;
// /**
// * 返回结果
// */
// private String result;
//
// /**
// * 响应时间
// */
// private long responseTime;
// }
// Path: src/main/java/com/yiji/falcon/agent/util/HttpUtil.java
import com.github.kevinsawicki.http.HttpRequest;
import com.yiji.falcon.agent.vo.HttpResult;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
package com.yiji.falcon.agent.util;
/*
* 修订记录:
* [email protected] 2016-06-22 17:48 创建
*/
/**
* @author [email protected]
*/
@Slf4j
public class HttpUtil {
/**
* 发送json post请求
* @param url
* @param data
* @return
* @throws IOException
*/ | public static HttpResult postJSON(String url,String data) throws IOException { |
cqyijifu/OpenFalcon-SuitAgent | src/main/java/com/yiji/falcon/agent/vo/detect/DetectResult.java | // Path: src/main/java/com/yiji/falcon/agent/falcon/CounterType.java
// public enum CounterType {
// /**
// * 用户上传什么样的值,就原封不动的存储
// */
// GAUGE,
// /**
// * 指标在存储和展现的时候,会被计算为speed,即(当前值 - 上次值)/ 时间间隔
// */
// COUNTER
// }
| import com.yiji.falcon.agent.falcon.CounterType;
import lombok.Data;
import lombok.ToString;
import java.util.List; | /*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
package com.yiji.falcon.agent.vo.detect;
/*
* 修订记录:
* [email protected] 2016-07-22 11:49 创建
*/
/**
* 一次探测的结果
* @author [email protected]
*/
@Data
public class DetectResult {
/**
* 探测结果,Agent将根据此属性进行探测地址的可用性上报
*/
private boolean success;
/**
* 自定义的监控值
* Agent会将此Map中的key当做metrics名称,{@link com.yiji.falcon.agent.vo.detect.DetectResult.Metric} 对象组建上报值进行上报
*/
private List<Metric> metricsList;
/**
* 自定义的公共的tag信息
* 形如tag1={tag1},tag2={tag2}
* 设置后,将会对每个监控值都会打上此tag
*/
private String commonTag;
@ToString
public static class Metric{
/**
* 自定义监控名
*/
public String metricName;
/**
* 自定义监控值的value
*/
public String value;
/**
* 自定义监控值的上报类型
*/ | // Path: src/main/java/com/yiji/falcon/agent/falcon/CounterType.java
// public enum CounterType {
// /**
// * 用户上传什么样的值,就原封不动的存储
// */
// GAUGE,
// /**
// * 指标在存储和展现的时候,会被计算为speed,即(当前值 - 上次值)/ 时间间隔
// */
// COUNTER
// }
// Path: src/main/java/com/yiji/falcon/agent/vo/detect/DetectResult.java
import com.yiji.falcon.agent.falcon.CounterType;
import lombok.Data;
import lombok.ToString;
import java.util.List;
/*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
package com.yiji.falcon.agent.vo.detect;
/*
* 修订记录:
* [email protected] 2016-07-22 11:49 创建
*/
/**
* 一次探测的结果
* @author [email protected]
*/
@Data
public class DetectResult {
/**
* 探测结果,Agent将根据此属性进行探测地址的可用性上报
*/
private boolean success;
/**
* 自定义的监控值
* Agent会将此Map中的key当做metrics名称,{@link com.yiji.falcon.agent.vo.detect.DetectResult.Metric} 对象组建上报值进行上报
*/
private List<Metric> metricsList;
/**
* 自定义的公共的tag信息
* 形如tag1={tag1},tag2={tag2}
* 设置后,将会对每个监控值都会打上此tag
*/
private String commonTag;
@ToString
public static class Metric{
/**
* 自定义监控名
*/
public String metricName;
/**
* 自定义监控值的value
*/
public String value;
/**
* 自定义监控值的上报类型
*/ | public CounterType counterType; |
akeranen/the-one | src/test/AllTests.java | // Path: src/core/SettingsError.java
// public class SettingsError extends SimError {
//
// public SettingsError(String cause) {
// super(cause);
// }
//
// public SettingsError(String cause, Exception e) {
// super(cause,e);
// }
//
// public SettingsError(Exception e) {
// super(e);
// }
//
// }
| import core.SettingsError;
import junit.framework.Test;
import junit.framework.TestSuite; | /*
* Copyright 2010 Aalto University, ComNet
* Released under GPLv3. See LICENSE.txt for details.
*/
package test;
public class AllTests {
public static Test suite() {
TestSuite suite = new TestSuite("the ONE tests");
try {
TestSettings.init(null); | // Path: src/core/SettingsError.java
// public class SettingsError extends SimError {
//
// public SettingsError(String cause) {
// super(cause);
// }
//
// public SettingsError(String cause, Exception e) {
// super(cause,e);
// }
//
// public SettingsError(Exception e) {
// super(e);
// }
//
// }
// Path: src/test/AllTests.java
import core.SettingsError;
import junit.framework.Test;
import junit.framework.TestSuite;
/*
* Copyright 2010 Aalto University, ComNet
* Released under GPLv3. See LICENSE.txt for details.
*/
package test;
public class AllTests {
public static Test suite() {
TestSuite suite = new TestSuite("the ONE tests");
try {
TestSettings.init(null); | } catch (SettingsError e) { |
akeranen/the-one | src/input/ExternalPathMovementReader.java | // Path: src/core/SettingsError.java
// public class SettingsError extends SimError {
//
// public SettingsError(String cause) {
// super(cause);
// }
//
// public SettingsError(String cause, Exception e) {
// super(cause,e);
// }
//
// public SettingsError(Exception e) {
// super(e);
// }
//
// }
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import core.SettingsError; | * caches.
*
* @param traceFilePath path to the trace file
* @param activityFilePath path to the activity file
*/
private ExternalPathMovementReader(String traceFilePath,
String activityFilePath) throws IOException {
// Open the trace file for reading
File inFile = new File(traceFilePath);
long traceSize = inFile.length();
long totalRead = 0;
long readSize = 0;
long printSize = 5*1024*1024;
BufferedReader reader = null;
ZipFile zf = null;
try {
if (traceFilePath.endsWith(".zip")) {
// Grab the first entry from the zip file
// TODO: try to find the correct entry based on file name
zf = new ZipFile(traceFilePath);
ZipEntry ze = zf.entries().nextElement();
reader = new BufferedReader(
new InputStreamReader(zf.getInputStream(ze)));
traceSize = ze.getSize();
} else {
reader = new BufferedReader(
new FileReader(traceFilePath));
}
} catch (FileNotFoundException e1) { | // Path: src/core/SettingsError.java
// public class SettingsError extends SimError {
//
// public SettingsError(String cause) {
// super(cause);
// }
//
// public SettingsError(String cause, Exception e) {
// super(cause,e);
// }
//
// public SettingsError(Exception e) {
// super(e);
// }
//
// }
// Path: src/input/ExternalPathMovementReader.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import core.SettingsError;
* caches.
*
* @param traceFilePath path to the trace file
* @param activityFilePath path to the activity file
*/
private ExternalPathMovementReader(String traceFilePath,
String activityFilePath) throws IOException {
// Open the trace file for reading
File inFile = new File(traceFilePath);
long traceSize = inFile.length();
long totalRead = 0;
long readSize = 0;
long printSize = 5*1024*1024;
BufferedReader reader = null;
ZipFile zf = null;
try {
if (traceFilePath.endsWith(".zip")) {
// Grab the first entry from the zip file
// TODO: try to find the correct entry based on file name
zf = new ZipFile(traceFilePath);
ZipEntry ze = zf.entries().nextElement();
reader = new BufferedReader(
new InputStreamReader(zf.getInputStream(ze)));
traceSize = ze.getSize();
} else {
reader = new BufferedReader(
new FileReader(traceFilePath));
}
} catch (FileNotFoundException e1) { | throw new SettingsError("Couldn't find external movement input " + |
akeranen/the-one | src/core/World.java | // Path: src/input/ScheduledUpdatesQueue.java
// public class ScheduledUpdatesQueue implements EventQueue {
// /** Time of the event (simulated seconds) */
// private ExternalEvent nextEvent;
// private List<ExternalEvent> updates;
//
// /**
// * Constructor. Creates an empty update queue.
// */
// public ScheduledUpdatesQueue(){
// this.nextEvent = new ExternalEvent(Double.MAX_VALUE);
// this.updates = new ArrayList<ExternalEvent>();
// }
//
// /**
// * Returns the next scheduled event or event with time Double.MAX_VALUE
// * if there aren't any.
// * @return the next scheduled event
// */
// public ExternalEvent nextEvent() {
// ExternalEvent event = this.nextEvent;
//
// if (this.updates.size() == 0) {
// this.nextEvent = new ExternalEvent(Double.MAX_VALUE);
// }
// else {
// this.nextEvent = this.updates.remove(0);
// }
//
// return event;
// }
//
// /**
// * Returns the next scheduled event's time or Double.MAX_VALUE if there
// * aren't any events left
// * @return the next scheduled event's time
// */
// public double nextEventsTime() {
// return this.nextEvent.getTime();
// }
//
// /**
// * Add a new update request for the given time
// * @param simTime The time when the update should happen
// */
// public void addUpdate(double simTime) {
// ExternalEvent ee = new ExternalEvent(simTime);
//
// if (ee.compareTo(nextEvent) == 0) { // this event is already next
// return;
// }
// else if (this.nextEvent.getTime() > simTime) { // new nextEvent
// putToQueue(this.nextEvent); // put the old nextEvent back to q
// this.nextEvent = ee;
// }
// else { // given event happens later..
// putToQueue(ee);
// }
// }
//
// /**
// * Puts a event to the queue in the right place
// * @param ee The event to put to the queue
// */
// private void putToQueue(ExternalEvent ee) {
// double eeTime = ee.getTime();
//
// for (int i=0, n=this.updates.size(); i<n; i++) {
// double time = updates.get(i).getTime();
// if (time == eeTime) {
// return; // update with the given time exists -> no need for new
// }
// else if (eeTime < time) {
// this.updates.add(i, ee);
// return;
// }
// }
//
// /* all existing updates are earlier -> add to the end of the list */
// this.updates.add(ee);
// }
//
// public String toString() {
// String times = "updates @ " + this.nextEvent.getTime();
//
// for (ExternalEvent ee : this.updates) {
// times += ", " + ee.getTime();
// }
//
// return times;
// }
// }
| import input.EventQueue;
import input.ExternalEvent;
import input.ScheduledUpdatesQueue;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random; | /*
* Copyright 2010 Aalto University, ComNet
* Released under GPLv3. See LICENSE.txt for details.
*/
package core;
/**
* World contains all the nodes and is responsible for updating their
* location and connections.
*/
public class World {
/** name space of optimization settings ({@value})*/
public static final String OPTIMIZATION_SETTINGS_NS = "Optimization";
/**
* Should the order of node updates be different (random) within every
* update step -setting id ({@value}). Boolean (true/false) variable.
* Default is @link {@link #DEF_RANDOMIZE_UPDATES}.
*/
public static final String RANDOMIZE_UPDATES_S = "randomizeUpdateOrder";
/** should the update order of nodes be randomized -setting's default value
* ({@value}) */
public static final boolean DEF_RANDOMIZE_UPDATES = true;
/**
* Real-time simulation enabled -setting id ({@value}).
* If set to true and simulation time moves faster than real time,
* the simulation will pause after each update round to wait until real
* time catches up. Default = false.
*/
public static final String REALTIME_SIM_S = "realtime";
/** should the update order of nodes be randomized -setting's default value
* ({@value}) */
/**
* Should the connectivity simulation be stopped after one round
* -setting id ({@value}). Boolean (true/false) variable. Default = false.
*/
public static final String SIMULATE_CON_ONCE_S = "simulateConnectionsOnce";
private int sizeX;
private int sizeY;
private List<EventQueue> eventQueues;
private double updateInterval;
private SimClock simClock;
private double nextQueueEventTime;
private EventQueue nextEventQueue;
/** list of nodes; nodes are indexed by their network address */
private List<DTNHost> hosts;
private boolean simulateConnections;
/** nodes in the order they should be updated (if the order should be
* randomized; null value means that the order should not be randomized) */
private ArrayList<DTNHost> updateOrder;
/** is cancellation of simulation requested from UI */
private boolean isCancelled;
private List<UpdateListener> updateListeners;
/** Queue of scheduled update requests */ | // Path: src/input/ScheduledUpdatesQueue.java
// public class ScheduledUpdatesQueue implements EventQueue {
// /** Time of the event (simulated seconds) */
// private ExternalEvent nextEvent;
// private List<ExternalEvent> updates;
//
// /**
// * Constructor. Creates an empty update queue.
// */
// public ScheduledUpdatesQueue(){
// this.nextEvent = new ExternalEvent(Double.MAX_VALUE);
// this.updates = new ArrayList<ExternalEvent>();
// }
//
// /**
// * Returns the next scheduled event or event with time Double.MAX_VALUE
// * if there aren't any.
// * @return the next scheduled event
// */
// public ExternalEvent nextEvent() {
// ExternalEvent event = this.nextEvent;
//
// if (this.updates.size() == 0) {
// this.nextEvent = new ExternalEvent(Double.MAX_VALUE);
// }
// else {
// this.nextEvent = this.updates.remove(0);
// }
//
// return event;
// }
//
// /**
// * Returns the next scheduled event's time or Double.MAX_VALUE if there
// * aren't any events left
// * @return the next scheduled event's time
// */
// public double nextEventsTime() {
// return this.nextEvent.getTime();
// }
//
// /**
// * Add a new update request for the given time
// * @param simTime The time when the update should happen
// */
// public void addUpdate(double simTime) {
// ExternalEvent ee = new ExternalEvent(simTime);
//
// if (ee.compareTo(nextEvent) == 0) { // this event is already next
// return;
// }
// else if (this.nextEvent.getTime() > simTime) { // new nextEvent
// putToQueue(this.nextEvent); // put the old nextEvent back to q
// this.nextEvent = ee;
// }
// else { // given event happens later..
// putToQueue(ee);
// }
// }
//
// /**
// * Puts a event to the queue in the right place
// * @param ee The event to put to the queue
// */
// private void putToQueue(ExternalEvent ee) {
// double eeTime = ee.getTime();
//
// for (int i=0, n=this.updates.size(); i<n; i++) {
// double time = updates.get(i).getTime();
// if (time == eeTime) {
// return; // update with the given time exists -> no need for new
// }
// else if (eeTime < time) {
// this.updates.add(i, ee);
// return;
// }
// }
//
// /* all existing updates are earlier -> add to the end of the list */
// this.updates.add(ee);
// }
//
// public String toString() {
// String times = "updates @ " + this.nextEvent.getTime();
//
// for (ExternalEvent ee : this.updates) {
// times += ", " + ee.getTime();
// }
//
// return times;
// }
// }
// Path: src/core/World.java
import input.EventQueue;
import input.ExternalEvent;
import input.ScheduledUpdatesQueue;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
/*
* Copyright 2010 Aalto University, ComNet
* Released under GPLv3. See LICENSE.txt for details.
*/
package core;
/**
* World contains all the nodes and is responsible for updating their
* location and connections.
*/
public class World {
/** name space of optimization settings ({@value})*/
public static final String OPTIMIZATION_SETTINGS_NS = "Optimization";
/**
* Should the order of node updates be different (random) within every
* update step -setting id ({@value}). Boolean (true/false) variable.
* Default is @link {@link #DEF_RANDOMIZE_UPDATES}.
*/
public static final String RANDOMIZE_UPDATES_S = "randomizeUpdateOrder";
/** should the update order of nodes be randomized -setting's default value
* ({@value}) */
public static final boolean DEF_RANDOMIZE_UPDATES = true;
/**
* Real-time simulation enabled -setting id ({@value}).
* If set to true and simulation time moves faster than real time,
* the simulation will pause after each update round to wait until real
* time catches up. Default = false.
*/
public static final String REALTIME_SIM_S = "realtime";
/** should the update order of nodes be randomized -setting's default value
* ({@value}) */
/**
* Should the connectivity simulation be stopped after one round
* -setting id ({@value}). Boolean (true/false) variable. Default = false.
*/
public static final String SIMULATE_CON_ONCE_S = "simulateConnectionsOnce";
private int sizeX;
private int sizeY;
private List<EventQueue> eventQueues;
private double updateInterval;
private SimClock simClock;
private double nextQueueEventTime;
private EventQueue nextEventQueue;
/** list of nodes; nodes are indexed by their network address */
private List<DTNHost> hosts;
private boolean simulateConnections;
/** nodes in the order they should be updated (if the order should be
* randomized; null value means that the order should not be randomized) */
private ArrayList<DTNHost> updateOrder;
/** is cancellation of simulation requested from UI */
private boolean isCancelled;
private List<UpdateListener> updateListeners;
/** Queue of scheduled update requests */ | private ScheduledUpdatesQueue scheduledUpdates; |
akeranen/the-one | src/input/ExternalMovementReader.java | // Path: src/util/Tuple.java
// public class Tuple<K,V> {
// private K key;
// private V value;
//
// /**
// * Creates a new tuple.
// * @param key The key of the tuple
// * @param value The value of the tuple
// */
// public Tuple(K key, V value) {
// this.key = key;
// this.value = value;
// }
//
// /**
// * Returns the key
// * @return the key
// */
// public K getKey() {
// return key;
// }
//
// /**
// * Returns the value
// * @return the value
// */
// public V getValue() {
// return value;
// }
//
// /**
// * Returns a string representation of the tuple
// * @return a string representation of the tuple
// */
// public String toString() {
// return key.toString() + ":" + value.toString();
// }
// }
//
// Path: src/core/SettingsError.java
// public class SettingsError extends SimError {
//
// public SettingsError(String cause) {
// super(cause);
// }
//
// public SettingsError(String cause, Exception e) {
// super(cause,e);
// }
//
// public SettingsError(Exception e) {
// super(e);
// }
//
// }
| import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import util.Tuple;
import core.Coord;
import core.SettingsError; | /*
* Copyright 2010 Aalto University, ComNet
* Released under GPLv3. See LICENSE.txt for details.
*/
package input;
/**
* Reader for ExternalMovement movement model's time-location tuples.
* <P>
* First line of the file should be the offset header. Syntax of the header
* should be:<BR>
* <CODE>minTime maxTime minX maxX minY maxY minZ maxZ</CODE>
* <BR>
* Last two values (Z-axis) are ignored at the moment but can be present
* in the file.
* <P>
* Following lines' syntax should be:<BR>
* <CODE>time id xPos yPos</CODE><BR>
* where <CODE>time</CODE> is the time when a node with <CODE>id</CODE> should
* be at location <CODE>(xPos, yPos)</CODE>.
* </P>
* <P>
* All lines must be sorted by time. Sampling interval (time difference between
* two time instances) must be same for the whole file.
* </P>
*/
public class ExternalMovementReader {
/* Prefix for comment lines (lines starting with this are ignored) */
public static final String COMMENT_PREFIX = "#";
private Scanner scanner;
private double lastTimeStamp = -1;
private String lastLine;
private double minTime;
private double maxTime;
private double minX;
private double maxX;
private double minY;
private double maxY;
private boolean normalize;
/**
* Constructor. Creates a new reader that reads the data from a file.
* @param inFilePath Path to the file where the data is read
* @throws SettingsError if the file wasn't found
*/
public ExternalMovementReader(String inFilePath) {
this.normalize = true;
File inFile = new File(inFilePath);
try {
scanner = new Scanner(inFile);
} catch (FileNotFoundException e) { | // Path: src/util/Tuple.java
// public class Tuple<K,V> {
// private K key;
// private V value;
//
// /**
// * Creates a new tuple.
// * @param key The key of the tuple
// * @param value The value of the tuple
// */
// public Tuple(K key, V value) {
// this.key = key;
// this.value = value;
// }
//
// /**
// * Returns the key
// * @return the key
// */
// public K getKey() {
// return key;
// }
//
// /**
// * Returns the value
// * @return the value
// */
// public V getValue() {
// return value;
// }
//
// /**
// * Returns a string representation of the tuple
// * @return a string representation of the tuple
// */
// public String toString() {
// return key.toString() + ":" + value.toString();
// }
// }
//
// Path: src/core/SettingsError.java
// public class SettingsError extends SimError {
//
// public SettingsError(String cause) {
// super(cause);
// }
//
// public SettingsError(String cause, Exception e) {
// super(cause,e);
// }
//
// public SettingsError(Exception e) {
// super(e);
// }
//
// }
// Path: src/input/ExternalMovementReader.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import util.Tuple;
import core.Coord;
import core.SettingsError;
/*
* Copyright 2010 Aalto University, ComNet
* Released under GPLv3. See LICENSE.txt for details.
*/
package input;
/**
* Reader for ExternalMovement movement model's time-location tuples.
* <P>
* First line of the file should be the offset header. Syntax of the header
* should be:<BR>
* <CODE>minTime maxTime minX maxX minY maxY minZ maxZ</CODE>
* <BR>
* Last two values (Z-axis) are ignored at the moment but can be present
* in the file.
* <P>
* Following lines' syntax should be:<BR>
* <CODE>time id xPos yPos</CODE><BR>
* where <CODE>time</CODE> is the time when a node with <CODE>id</CODE> should
* be at location <CODE>(xPos, yPos)</CODE>.
* </P>
* <P>
* All lines must be sorted by time. Sampling interval (time difference between
* two time instances) must be same for the whole file.
* </P>
*/
public class ExternalMovementReader {
/* Prefix for comment lines (lines starting with this are ignored) */
public static final String COMMENT_PREFIX = "#";
private Scanner scanner;
private double lastTimeStamp = -1;
private String lastLine;
private double minTime;
private double maxTime;
private double minX;
private double maxX;
private double minY;
private double maxY;
private boolean normalize;
/**
* Constructor. Creates a new reader that reads the data from a file.
* @param inFilePath Path to the file where the data is read
* @throws SettingsError if the file wasn't found
*/
public ExternalMovementReader(String inFilePath) {
this.normalize = true;
File inFile = new File(inFilePath);
try {
scanner = new Scanner(inFile);
} catch (FileNotFoundException e) { | throw new SettingsError("Couldn't find external movement input " + |
akeranen/the-one | src/input/ExternalMovementReader.java | // Path: src/util/Tuple.java
// public class Tuple<K,V> {
// private K key;
// private V value;
//
// /**
// * Creates a new tuple.
// * @param key The key of the tuple
// * @param value The value of the tuple
// */
// public Tuple(K key, V value) {
// this.key = key;
// this.value = value;
// }
//
// /**
// * Returns the key
// * @return the key
// */
// public K getKey() {
// return key;
// }
//
// /**
// * Returns the value
// * @return the value
// */
// public V getValue() {
// return value;
// }
//
// /**
// * Returns a string representation of the tuple
// * @return a string representation of the tuple
// */
// public String toString() {
// return key.toString() + ":" + value.toString();
// }
// }
//
// Path: src/core/SettingsError.java
// public class SettingsError extends SimError {
//
// public SettingsError(String cause) {
// super(cause);
// }
//
// public SettingsError(String cause, Exception e) {
// super(cause,e);
// }
//
// public SettingsError(Exception e) {
// super(e);
// }
//
// }
| import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import util.Tuple;
import core.Coord;
import core.SettingsError; | maxX = lineScan.nextDouble();
minY = lineScan.nextDouble();
maxY = lineScan.nextDouble();
} catch (Exception e) {
throw new SettingsError("Invalid offset line '" + offsets + "'");
}
finally {
if (lineScan != null) {
lineScan.close();
}
}
lastLine = scanner.nextLine();
}
/**
* Sets normalizing of read values on/off. If on, values returned by
* {@link #readNextMovements()} are decremented by minimum values of the
* offsets. Default is on (normalize).
* @param normalize If true, normalizing is on (false -> off).
*/
public void setNormalize(boolean normalize) {
this.normalize = normalize;
}
/**
* Reads all new id-coordinate tuples that belong to the same time instance
* @return A list of tuples or empty list if there were no more moves
* @throws SettingError if an invalid line was read
*/ | // Path: src/util/Tuple.java
// public class Tuple<K,V> {
// private K key;
// private V value;
//
// /**
// * Creates a new tuple.
// * @param key The key of the tuple
// * @param value The value of the tuple
// */
// public Tuple(K key, V value) {
// this.key = key;
// this.value = value;
// }
//
// /**
// * Returns the key
// * @return the key
// */
// public K getKey() {
// return key;
// }
//
// /**
// * Returns the value
// * @return the value
// */
// public V getValue() {
// return value;
// }
//
// /**
// * Returns a string representation of the tuple
// * @return a string representation of the tuple
// */
// public String toString() {
// return key.toString() + ":" + value.toString();
// }
// }
//
// Path: src/core/SettingsError.java
// public class SettingsError extends SimError {
//
// public SettingsError(String cause) {
// super(cause);
// }
//
// public SettingsError(String cause, Exception e) {
// super(cause,e);
// }
//
// public SettingsError(Exception e) {
// super(e);
// }
//
// }
// Path: src/input/ExternalMovementReader.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import util.Tuple;
import core.Coord;
import core.SettingsError;
maxX = lineScan.nextDouble();
minY = lineScan.nextDouble();
maxY = lineScan.nextDouble();
} catch (Exception e) {
throw new SettingsError("Invalid offset line '" + offsets + "'");
}
finally {
if (lineScan != null) {
lineScan.close();
}
}
lastLine = scanner.nextLine();
}
/**
* Sets normalizing of read values on/off. If on, values returned by
* {@link #readNextMovements()} are decremented by minimum values of the
* offsets. Default is on (normalize).
* @param normalize If true, normalizing is on (false -> off).
*/
public void setNormalize(boolean normalize) {
this.normalize = normalize;
}
/**
* Reads all new id-coordinate tuples that belong to the same time instance
* @return A list of tuples or empty list if there were no more moves
* @throws SettingError if an invalid line was read
*/ | public List<Tuple<String, Coord>> readNextMovements() { |
akeranen/the-one | src/core/Settings.java | // Path: src/util/Range.java
// public class Range {
//
// private double min;
// private double max;
//
// /**
// * Creates a new range
// * @param min The minimum bound of the range
// * @param max The maximum bound
// */
// public Range(double min, double max) {
// this.min = min;
// this.max = max;
// checkRangeValidity(min, max);
// }
//
// /**
// * Parses a range from the given string
// * @param str The string to parse
// * @throws NumberFormatException if the range didn't contain numeric values
// */
// public Range(String str) throws NumberFormatException {
// if (str.indexOf("-") != str.lastIndexOf("-")) {
// /* TODO */
// throw new Error("Ranges with negative values not supported");
// }
//
// if (str.substring(1).contains("-")) {
// /* has "-" but not as the first char -> range */
// String[] vals = str.split("-");
// this.min = Double.parseDouble(vals[0]);
// this.max = Double.parseDouble(vals[1]);
// } else {
// this.min = this.max = Double.parseDouble(str);
// }
// checkRangeValidity(min, max);
// }
//
// /**
// * Checks if the given values for a valid range
// * @param min The minimum value
// * @param max The maximum value
// * @throws Error if min > max
// */
// private void checkRangeValidity(double min, double max) {
// if (min > max) {
// throw new Error("Minimum value is larger than maximum");
// }
// }
//
// /**
// * Returns true if the given value is within this range [min, max],
// * min and max included
// * @param value The value to check
// * @return True if the given value is in the range, false if not
// */
// public boolean isInRange(double value) {
// return (value >= min && value <= max);
// }
//
// @Override
// public String toString() {
// return "Range [" + min + ", " + max + "]";
// }
//
// }
| import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Properties;
import java.util.Scanner;
import java.util.Set;
import java.util.Stack;
import util.Range; | return values;
}
/**
* Returns an array of CSV setting integer values
* @param name Name of the setting
* @param expectedCount how many values are expected
* @return Array of values that were comma-separated
* @see #getCsvSetting(String, int)
*/
public int[] getCsvInts(String name, int expectedCount) {
return convertToInts(getCsvDoubles(name, expectedCount), name);
}
/**
* Returns an array of CSV setting integer values
* @param name Name of the setting
* @return Array of values that were comma-separated
* @see #getCsvSetting(String, int)
*/
public int[] getCsvInts(String name) {
return convertToInts(getCsvDoubles(name), name);
}
/**
* Returns comma-separated ranges (e.g., "3-5, 17-20, 15")
* @param name Name of the setting
* @return Array of ranges that were comma-separated in the setting
* @throws SettingsError if something went wrong with reading
*/ | // Path: src/util/Range.java
// public class Range {
//
// private double min;
// private double max;
//
// /**
// * Creates a new range
// * @param min The minimum bound of the range
// * @param max The maximum bound
// */
// public Range(double min, double max) {
// this.min = min;
// this.max = max;
// checkRangeValidity(min, max);
// }
//
// /**
// * Parses a range from the given string
// * @param str The string to parse
// * @throws NumberFormatException if the range didn't contain numeric values
// */
// public Range(String str) throws NumberFormatException {
// if (str.indexOf("-") != str.lastIndexOf("-")) {
// /* TODO */
// throw new Error("Ranges with negative values not supported");
// }
//
// if (str.substring(1).contains("-")) {
// /* has "-" but not as the first char -> range */
// String[] vals = str.split("-");
// this.min = Double.parseDouble(vals[0]);
// this.max = Double.parseDouble(vals[1]);
// } else {
// this.min = this.max = Double.parseDouble(str);
// }
// checkRangeValidity(min, max);
// }
//
// /**
// * Checks if the given values for a valid range
// * @param min The minimum value
// * @param max The maximum value
// * @throws Error if min > max
// */
// private void checkRangeValidity(double min, double max) {
// if (min > max) {
// throw new Error("Minimum value is larger than maximum");
// }
// }
//
// /**
// * Returns true if the given value is within this range [min, max],
// * min and max included
// * @param value The value to check
// * @return True if the given value is in the range, false if not
// */
// public boolean isInRange(double value) {
// return (value >= min && value <= max);
// }
//
// @Override
// public String toString() {
// return "Range [" + min + ", " + max + "]";
// }
//
// }
// Path: src/core/Settings.java
import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Properties;
import java.util.Scanner;
import java.util.Set;
import java.util.Stack;
import util.Range;
return values;
}
/**
* Returns an array of CSV setting integer values
* @param name Name of the setting
* @param expectedCount how many values are expected
* @return Array of values that were comma-separated
* @see #getCsvSetting(String, int)
*/
public int[] getCsvInts(String name, int expectedCount) {
return convertToInts(getCsvDoubles(name, expectedCount), name);
}
/**
* Returns an array of CSV setting integer values
* @param name Name of the setting
* @return Array of values that were comma-separated
* @see #getCsvSetting(String, int)
*/
public int[] getCsvInts(String name) {
return convertToInts(getCsvDoubles(name), name);
}
/**
* Returns comma-separated ranges (e.g., "3-5, 17-20, 15")
* @param name Name of the setting
* @return Array of ranges that were comma-separated in the setting
* @throws SettingsError if something went wrong with reading
*/ | public Range[] getCsvRanges(String name) { |
akeranen/the-one | src/core/DTN2Manager.java | // Path: src/report/DTN2Reporter.java
// public class DTN2Reporter extends Report implements MessageListener {
// /**
// * Creates a new reporter object.
// */
// public DTN2Reporter() {
// super.init();
// DTN2Manager.setReporter(this);
// }
//
// // Implement MessageListener
// /**
// * Method is called when a new message is created
// * @param m Message that was created
// */
// public void newMessage(Message m) {}
//
// /**
// * Method is called when a message's transfer is started
// * @param m The message that is going to be transferred
// * @param from Node where the message is transferred from
// * @param to Node where the message is transferred to
// */
// public void messageTransferStarted(Message m, DTNHost from, DTNHost to){}
//
// /**
// * Method is called when a message is deleted
// * @param m The message that was deleted
// * @param where The host where the message was deleted
// * @param dropped True if the message was dropped, false if removed
// */
// public void messageDeleted(Message m, DTNHost where, boolean dropped){}
//
// /**
// * Method is called when a message's transfer was aborted before
// * it finished
// * @param m The message that was being transferred
// * @param from Node where the message was being transferred from
// * @param to Node where the message was being transferred to
// */
// public void messageTransferAborted(Message m, DTNHost from, DTNHost to){}
//
// /**
// * Method is called when a message is successfully transferred from
// * a node to another.
// * @param m The message that was transferred
// * @param from Node where the message was transferred from
// * @param to Node where the message was transferred to
// * @param firstDelivery Was the target node final destination of the message
// * and received this message for the first time.
// */
// public void messageTransferred(Message m, DTNHost from, DTNHost to,
// boolean firstDelivery) {
// if (firstDelivery) {
// // We received a BundleMessage that should be passed to dtnd
// CLAParser p = DTN2Manager.getParser(to);
// if (p != null) { // Check that there's a CLA connected to this node
// p.sendBundle( (DTN2Manager.getBundle(m.getId())).file );
// }
// }
// }
// }
| import input.DTN2Events;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import report.DTN2Reporter;
import fi.tkk.netlab.dtn.ecla.Bundle;
import fi.tkk.netlab.dtn.ecla.CLAParser;
import static core.Constants.DEBUG; | /*
* Copyright 2010 Aalto University, ComNet
* Released under GPLv3. See LICENSE.txt for details.
*/
package core;
/**
* Manages the external convergence layer connections to dtnd.
* Parses the configuration file and sets up the CLAParsers
* and EID->host mappings.
* @author teemuk
*/
public class DTN2Manager {
private static Map<DTNHost, CLAParser> CLAs = null;
/** Mapping from EID to DTNHost */
private static Collection<EIDHost> EID_to_host = null;
/** Set of all bundles in the simulator */
private static Map<String, Bundle> bundles = null;
/** Reporter object that passes messages from ONE to dtnd */ | // Path: src/report/DTN2Reporter.java
// public class DTN2Reporter extends Report implements MessageListener {
// /**
// * Creates a new reporter object.
// */
// public DTN2Reporter() {
// super.init();
// DTN2Manager.setReporter(this);
// }
//
// // Implement MessageListener
// /**
// * Method is called when a new message is created
// * @param m Message that was created
// */
// public void newMessage(Message m) {}
//
// /**
// * Method is called when a message's transfer is started
// * @param m The message that is going to be transferred
// * @param from Node where the message is transferred from
// * @param to Node where the message is transferred to
// */
// public void messageTransferStarted(Message m, DTNHost from, DTNHost to){}
//
// /**
// * Method is called when a message is deleted
// * @param m The message that was deleted
// * @param where The host where the message was deleted
// * @param dropped True if the message was dropped, false if removed
// */
// public void messageDeleted(Message m, DTNHost where, boolean dropped){}
//
// /**
// * Method is called when a message's transfer was aborted before
// * it finished
// * @param m The message that was being transferred
// * @param from Node where the message was being transferred from
// * @param to Node where the message was being transferred to
// */
// public void messageTransferAborted(Message m, DTNHost from, DTNHost to){}
//
// /**
// * Method is called when a message is successfully transferred from
// * a node to another.
// * @param m The message that was transferred
// * @param from Node where the message was transferred from
// * @param to Node where the message was transferred to
// * @param firstDelivery Was the target node final destination of the message
// * and received this message for the first time.
// */
// public void messageTransferred(Message m, DTNHost from, DTNHost to,
// boolean firstDelivery) {
// if (firstDelivery) {
// // We received a BundleMessage that should be passed to dtnd
// CLAParser p = DTN2Manager.getParser(to);
// if (p != null) { // Check that there's a CLA connected to this node
// p.sendBundle( (DTN2Manager.getBundle(m.getId())).file );
// }
// }
// }
// }
// Path: src/core/DTN2Manager.java
import input.DTN2Events;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import report.DTN2Reporter;
import fi.tkk.netlab.dtn.ecla.Bundle;
import fi.tkk.netlab.dtn.ecla.CLAParser;
import static core.Constants.DEBUG;
/*
* Copyright 2010 Aalto University, ComNet
* Released under GPLv3. See LICENSE.txt for details.
*/
package core;
/**
* Manages the external convergence layer connections to dtnd.
* Parses the configuration file and sets up the CLAParsers
* and EID->host mappings.
* @author teemuk
*/
public class DTN2Manager {
private static Map<DTNHost, CLAParser> CLAs = null;
/** Mapping from EID to DTNHost */
private static Collection<EIDHost> EID_to_host = null;
/** Set of all bundles in the simulator */
private static Map<String, Bundle> bundles = null;
/** Reporter object that passes messages from ONE to dtnd */ | private static DTN2Reporter reporter = null; |
zsoltk/GameOfLife | app/src/test/java/hu/supercluster/gameoflife/game/grid/EndlessGridHandlerTest.java | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/SimpleCellFactory.java
// public class SimpleCellFactory implements CellFactory<SimpleCell> {
// @Override
// public SimpleCell create(int x, int y) {
// return new SimpleCell(x, y, SimpleCell.STATE_DEAD);
// }
//
// @Override
// public int[] flatten(SimpleCell cell) {
// final int[] flattened = new int[4];
// flattened[0] = cell.x;
// flattened[1] = cell.y;
// flattened[2] = cell.state;
// flattened[3] = cell.neighborCount;
//
// return flattened;
// }
//
// @Override
// public SimpleCell inflate(int[] flattened) {
// final SimpleCell cell = new SimpleCell(
// flattened[0],
// flattened[1],
// flattened[2]
// );
//
// cell.neighborCount = flattened[3];
//
// return cell;
// }
// }
//
// Path: app/src/test/java/hu/supercluster/gameoflife/test/RobolectricTest.java
// @RunWith(RobolectricGradleTestRunner.class)
// @Config(
// constants = BuildConfig.class,
// sdk = Build.VERSION_CODES.JELLY_BEAN,
// packageName = "hu.supercluster.gameoflife"
// )
// abstract public class RobolectricTest {
//
// }
| import org.junit.Before;
import org.junit.Test;
import hu.supercluster.gameoflife.game.cell.Cell;
import hu.supercluster.gameoflife.game.cell.SimpleCellFactory;
import hu.supercluster.gameoflife.test.RobolectricTest;
import static org.fest.assertions.api.Assertions.assertThat; | package hu.supercluster.gameoflife.game.grid;
public class EndlessGridHandlerTest extends RobolectricTest {
EndlessGridHandler gridHandler; | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/SimpleCellFactory.java
// public class SimpleCellFactory implements CellFactory<SimpleCell> {
// @Override
// public SimpleCell create(int x, int y) {
// return new SimpleCell(x, y, SimpleCell.STATE_DEAD);
// }
//
// @Override
// public int[] flatten(SimpleCell cell) {
// final int[] flattened = new int[4];
// flattened[0] = cell.x;
// flattened[1] = cell.y;
// flattened[2] = cell.state;
// flattened[3] = cell.neighborCount;
//
// return flattened;
// }
//
// @Override
// public SimpleCell inflate(int[] flattened) {
// final SimpleCell cell = new SimpleCell(
// flattened[0],
// flattened[1],
// flattened[2]
// );
//
// cell.neighborCount = flattened[3];
//
// return cell;
// }
// }
//
// Path: app/src/test/java/hu/supercluster/gameoflife/test/RobolectricTest.java
// @RunWith(RobolectricGradleTestRunner.class)
// @Config(
// constants = BuildConfig.class,
// sdk = Build.VERSION_CODES.JELLY_BEAN,
// packageName = "hu.supercluster.gameoflife"
// )
// abstract public class RobolectricTest {
//
// }
// Path: app/src/test/java/hu/supercluster/gameoflife/game/grid/EndlessGridHandlerTest.java
import org.junit.Before;
import org.junit.Test;
import hu.supercluster.gameoflife.game.cell.Cell;
import hu.supercluster.gameoflife.game.cell.SimpleCellFactory;
import hu.supercluster.gameoflife.test.RobolectricTest;
import static org.fest.assertions.api.Assertions.assertThat;
package hu.supercluster.gameoflife.game.grid;
public class EndlessGridHandlerTest extends RobolectricTest {
EndlessGridHandler gridHandler; | private SimpleCellFactory cellFactory; |
zsoltk/GameOfLife | app/src/test/java/hu/supercluster/gameoflife/game/grid/EndlessGridHandlerTest.java | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/SimpleCellFactory.java
// public class SimpleCellFactory implements CellFactory<SimpleCell> {
// @Override
// public SimpleCell create(int x, int y) {
// return new SimpleCell(x, y, SimpleCell.STATE_DEAD);
// }
//
// @Override
// public int[] flatten(SimpleCell cell) {
// final int[] flattened = new int[4];
// flattened[0] = cell.x;
// flattened[1] = cell.y;
// flattened[2] = cell.state;
// flattened[3] = cell.neighborCount;
//
// return flattened;
// }
//
// @Override
// public SimpleCell inflate(int[] flattened) {
// final SimpleCell cell = new SimpleCell(
// flattened[0],
// flattened[1],
// flattened[2]
// );
//
// cell.neighborCount = flattened[3];
//
// return cell;
// }
// }
//
// Path: app/src/test/java/hu/supercluster/gameoflife/test/RobolectricTest.java
// @RunWith(RobolectricGradleTestRunner.class)
// @Config(
// constants = BuildConfig.class,
// sdk = Build.VERSION_CODES.JELLY_BEAN,
// packageName = "hu.supercluster.gameoflife"
// )
// abstract public class RobolectricTest {
//
// }
| import org.junit.Before;
import org.junit.Test;
import hu.supercluster.gameoflife.game.cell.Cell;
import hu.supercluster.gameoflife.game.cell.SimpleCellFactory;
import hu.supercluster.gameoflife.test.RobolectricTest;
import static org.fest.assertions.api.Assertions.assertThat; | package hu.supercluster.gameoflife.game.grid;
public class EndlessGridHandlerTest extends RobolectricTest {
EndlessGridHandler gridHandler;
private SimpleCellFactory cellFactory;
@Before
public void setup() {
cellFactory = new SimpleCellFactory();
gridHandler = new EndlessGridHandler(3, 3, cellFactory);
}
@Test
public void testGetCurrentAfterCreation() {
assertThat(gridHandler.getCurrent()).isEqualTo(new EndlessGrid(3, 3, cellFactory));
}
@Test
public void testCreateNew() {
assertThat(gridHandler.createNew()).isEqualTo(new EndlessGrid(3, 3, cellFactory));
}
@Test
public void testSetCurrent() {
Grid newGrid = gridHandler.createNew(); | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/SimpleCellFactory.java
// public class SimpleCellFactory implements CellFactory<SimpleCell> {
// @Override
// public SimpleCell create(int x, int y) {
// return new SimpleCell(x, y, SimpleCell.STATE_DEAD);
// }
//
// @Override
// public int[] flatten(SimpleCell cell) {
// final int[] flattened = new int[4];
// flattened[0] = cell.x;
// flattened[1] = cell.y;
// flattened[2] = cell.state;
// flattened[3] = cell.neighborCount;
//
// return flattened;
// }
//
// @Override
// public SimpleCell inflate(int[] flattened) {
// final SimpleCell cell = new SimpleCell(
// flattened[0],
// flattened[1],
// flattened[2]
// );
//
// cell.neighborCount = flattened[3];
//
// return cell;
// }
// }
//
// Path: app/src/test/java/hu/supercluster/gameoflife/test/RobolectricTest.java
// @RunWith(RobolectricGradleTestRunner.class)
// @Config(
// constants = BuildConfig.class,
// sdk = Build.VERSION_CODES.JELLY_BEAN,
// packageName = "hu.supercluster.gameoflife"
// )
// abstract public class RobolectricTest {
//
// }
// Path: app/src/test/java/hu/supercluster/gameoflife/game/grid/EndlessGridHandlerTest.java
import org.junit.Before;
import org.junit.Test;
import hu.supercluster.gameoflife.game.cell.Cell;
import hu.supercluster.gameoflife.game.cell.SimpleCellFactory;
import hu.supercluster.gameoflife.test.RobolectricTest;
import static org.fest.assertions.api.Assertions.assertThat;
package hu.supercluster.gameoflife.game.grid;
public class EndlessGridHandlerTest extends RobolectricTest {
EndlessGridHandler gridHandler;
private SimpleCellFactory cellFactory;
@Before
public void setup() {
cellFactory = new SimpleCellFactory();
gridHandler = new EndlessGridHandler(3, 3, cellFactory);
}
@Test
public void testGetCurrentAfterCreation() {
assertThat(gridHandler.getCurrent()).isEqualTo(new EndlessGrid(3, 3, cellFactory));
}
@Test
public void testCreateNew() {
assertThat(gridHandler.createNew()).isEqualTo(new EndlessGrid(3, 3, cellFactory));
}
@Test
public void testSetCurrent() {
Grid newGrid = gridHandler.createNew(); | newGrid.getCell(1, 1).setState(Cell.STATE_ALIVE); |
zsoltk/GameOfLife | app/src/test/java/hu/supercluster/gameoflife/game/testutils/GrowableCell.java | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Overseer.java
// public interface Overseer {
// void onCellStateChanged(CellStateChange cellStateChange);
// }
| import java.util.concurrent.atomic.AtomicLong;
import hu.supercluster.gameoflife.game.cell.Cell;
import hu.supercluster.gameoflife.game.cell.Overseer; | package hu.supercluster.gameoflife.game.testutils;
public class GrowableCell implements Cell {
static final AtomicLong NEXT_ID = new AtomicLong(0);
final long id = NEXT_ID.getAndIncrement();
final int x;
final int y;
int state; | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Overseer.java
// public interface Overseer {
// void onCellStateChanged(CellStateChange cellStateChange);
// }
// Path: app/src/test/java/hu/supercluster/gameoflife/game/testutils/GrowableCell.java
import java.util.concurrent.atomic.AtomicLong;
import hu.supercluster.gameoflife.game.cell.Cell;
import hu.supercluster.gameoflife.game.cell.Overseer;
package hu.supercluster.gameoflife.game.testutils;
public class GrowableCell implements Cell {
static final AtomicLong NEXT_ID = new AtomicLong(0);
final long id = NEXT_ID.getAndIncrement();
final int x;
final int y;
int state; | Overseer overseer; |
zsoltk/GameOfLife | app/src/main/java/hu/supercluster/gameoflife/app/activity/main/MainActivity.java | // Path: app/src/main/java/hu/supercluster/gameoflife/app/view/AutomatonView.java
// public class AutomatonView extends SurfaceView implements SurfaceHolder.Callback {
// private CellularAutomaton automaton;
// private GameParams params;
// private AutomatonThread thread;
//
// public AutomatonView(Context context) {
// super(context);
// }
//
// public AutomatonView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public AutomatonView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// }
//
// @DebugLog
// public void init(CellularAutomaton automaton, GameParams params) {
// this.automaton = automaton;
// this.params = params;
//
// SurfaceHolder surfaceHolder = getHolder();
// surfaceHolder.addCallback(this);
// }
//
// @Override
// @DebugLog
// public void surfaceCreated(SurfaceHolder holder) {
// if (thread == null || thread.getState() == Thread.State.TERMINATED) {
// thread = new AutomatonThread(automaton, holder, params);
// thread.start();
// }
//
// thread.setRunning(true);
// }
//
// @Override
// public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// //
// }
//
// @Override
// @DebugLog
// public void surfaceDestroyed(SurfaceHolder holder) {
// thread.setRunning(false);
// waitForThreadToDie();
// }
//
// @DebugLog
// private void waitForThreadToDie() {
// while (true) {
// try {
// thread.join();
// break;
//
// } catch (InterruptedException e) {
// }
// }
// }
//
// @Override
// public boolean onTouchEvent(MotionEvent event) {
// paint(event);
//
// return true;
// }
//
// protected void paint(MotionEvent event) {
// int x = Math.round(event.getX() / params.getCellSizeInPixels());
// int y = Math.round(event.getY() / params.getCellSizeInPixels());
//
// EventBus.getInstance().post(new PaintWithBrush(x, y));
// }
// }
| import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageButton;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Fullscreen;
import org.androidannotations.annotations.InstanceState;
import org.androidannotations.annotations.ViewById;
import hu.supercluster.gameoflife.R;
import hu.supercluster.gameoflife.app.view.AutomatonView;
import hugo.weaving.DebugLog; | package hu.supercluster.gameoflife.app.activity.main;
@EActivity(R.layout.activity_main)
@Fullscreen
public class MainActivity extends Activity {
@InstanceState
boolean paused;
@InstanceState
int lastOrientation;
@InstanceState
Bundle gameState;
@Bean
MainPresenter presenter;
@ViewById | // Path: app/src/main/java/hu/supercluster/gameoflife/app/view/AutomatonView.java
// public class AutomatonView extends SurfaceView implements SurfaceHolder.Callback {
// private CellularAutomaton automaton;
// private GameParams params;
// private AutomatonThread thread;
//
// public AutomatonView(Context context) {
// super(context);
// }
//
// public AutomatonView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public AutomatonView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// }
//
// @DebugLog
// public void init(CellularAutomaton automaton, GameParams params) {
// this.automaton = automaton;
// this.params = params;
//
// SurfaceHolder surfaceHolder = getHolder();
// surfaceHolder.addCallback(this);
// }
//
// @Override
// @DebugLog
// public void surfaceCreated(SurfaceHolder holder) {
// if (thread == null || thread.getState() == Thread.State.TERMINATED) {
// thread = new AutomatonThread(automaton, holder, params);
// thread.start();
// }
//
// thread.setRunning(true);
// }
//
// @Override
// public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// //
// }
//
// @Override
// @DebugLog
// public void surfaceDestroyed(SurfaceHolder holder) {
// thread.setRunning(false);
// waitForThreadToDie();
// }
//
// @DebugLog
// private void waitForThreadToDie() {
// while (true) {
// try {
// thread.join();
// break;
//
// } catch (InterruptedException e) {
// }
// }
// }
//
// @Override
// public boolean onTouchEvent(MotionEvent event) {
// paint(event);
//
// return true;
// }
//
// protected void paint(MotionEvent event) {
// int x = Math.round(event.getX() / params.getCellSizeInPixels());
// int y = Math.round(event.getY() / params.getCellSizeInPixels());
//
// EventBus.getInstance().post(new PaintWithBrush(x, y));
// }
// }
// Path: app/src/main/java/hu/supercluster/gameoflife/app/activity/main/MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageButton;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Fullscreen;
import org.androidannotations.annotations.InstanceState;
import org.androidannotations.annotations.ViewById;
import hu.supercluster.gameoflife.R;
import hu.supercluster.gameoflife.app.view.AutomatonView;
import hugo.weaving.DebugLog;
package hu.supercluster.gameoflife.app.activity.main;
@EActivity(R.layout.activity_main)
@Fullscreen
public class MainActivity extends Activity {
@InstanceState
boolean paused;
@InstanceState
int lastOrientation;
@InstanceState
Bundle gameState;
@Bean
MainPresenter presenter;
@ViewById | AutomatonView automatonView; |
zsoltk/GameOfLife | app/src/main/java/hu/supercluster/gameoflife/game/event/CellStateChange.java | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
| import hu.supercluster.gameoflife.game.cell.Cell; | package hu.supercluster.gameoflife.game.event;
public class CellStateChange {
public final int x;
public final int y;
public final int stateSnapshot; | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
// Path: app/src/main/java/hu/supercluster/gameoflife/game/event/CellStateChange.java
import hu.supercluster.gameoflife.game.cell.Cell;
package hu.supercluster.gameoflife.game.event;
public class CellStateChange {
public final int x;
public final int y;
public final int stateSnapshot; | public final Cell cell; |
zsoltk/GameOfLife | app/src/main/java/hu/supercluster/gameoflife/game/transformer/ThreadedGridTransformer.java | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/grid/Grid.java
// public interface Grid<T extends Cell> extends Parcelable {
// int getSizeX();
// int getSizeY();
// T getCell(int x, int y);
// void putCell(T cell);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/rule/Rule.java
// public interface Rule<T extends Cell> extends Serializable {
// int apply(Grid<T> grid, int x, int y);
// }
| import android.graphics.Point;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import hu.supercluster.gameoflife.game.cell.Cell;
import hu.supercluster.gameoflife.game.grid.Grid;
import hu.supercluster.gameoflife.game.rule.Rule; | package hu.supercluster.gameoflife.game.transformer;
public class ThreadedGridTransformer<T extends Cell> implements GridTransformer<T> {
private final int threadCount;
private ExecutorService executorService;
private CountDownLatch countDownLatch;
private int[][] stateChanges;
public ThreadedGridTransformer() {
this(2 * Runtime.getRuntime().availableProcessors());
}
public ThreadedGridTransformer(int threadCount) {
this.threadCount = threadCount;
executorService = Executors.newFixedThreadPool(threadCount);
}
@Override | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/grid/Grid.java
// public interface Grid<T extends Cell> extends Parcelable {
// int getSizeX();
// int getSizeY();
// T getCell(int x, int y);
// void putCell(T cell);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/rule/Rule.java
// public interface Rule<T extends Cell> extends Serializable {
// int apply(Grid<T> grid, int x, int y);
// }
// Path: app/src/main/java/hu/supercluster/gameoflife/game/transformer/ThreadedGridTransformer.java
import android.graphics.Point;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import hu.supercluster.gameoflife.game.cell.Cell;
import hu.supercluster.gameoflife.game.grid.Grid;
import hu.supercluster.gameoflife.game.rule.Rule;
package hu.supercluster.gameoflife.game.transformer;
public class ThreadedGridTransformer<T extends Cell> implements GridTransformer<T> {
private final int threadCount;
private ExecutorService executorService;
private CountDownLatch countDownLatch;
private int[][] stateChanges;
public ThreadedGridTransformer() {
this(2 * Runtime.getRuntime().availableProcessors());
}
public ThreadedGridTransformer(int threadCount) {
this.threadCount = threadCount;
executorService = Executors.newFixedThreadPool(threadCount);
}
@Override | public final void transform(Grid<T> grid, Rule<T> rule) { |
zsoltk/GameOfLife | app/src/main/java/hu/supercluster/gameoflife/game/transformer/ThreadedGridTransformer.java | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/grid/Grid.java
// public interface Grid<T extends Cell> extends Parcelable {
// int getSizeX();
// int getSizeY();
// T getCell(int x, int y);
// void putCell(T cell);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/rule/Rule.java
// public interface Rule<T extends Cell> extends Serializable {
// int apply(Grid<T> grid, int x, int y);
// }
| import android.graphics.Point;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import hu.supercluster.gameoflife.game.cell.Cell;
import hu.supercluster.gameoflife.game.grid.Grid;
import hu.supercluster.gameoflife.game.rule.Rule; | package hu.supercluster.gameoflife.game.transformer;
public class ThreadedGridTransformer<T extends Cell> implements GridTransformer<T> {
private final int threadCount;
private ExecutorService executorService;
private CountDownLatch countDownLatch;
private int[][] stateChanges;
public ThreadedGridTransformer() {
this(2 * Runtime.getRuntime().availableProcessors());
}
public ThreadedGridTransformer(int threadCount) {
this.threadCount = threadCount;
executorService = Executors.newFixedThreadPool(threadCount);
}
@Override | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/grid/Grid.java
// public interface Grid<T extends Cell> extends Parcelable {
// int getSizeX();
// int getSizeY();
// T getCell(int x, int y);
// void putCell(T cell);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/rule/Rule.java
// public interface Rule<T extends Cell> extends Serializable {
// int apply(Grid<T> grid, int x, int y);
// }
// Path: app/src/main/java/hu/supercluster/gameoflife/game/transformer/ThreadedGridTransformer.java
import android.graphics.Point;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import hu.supercluster.gameoflife.game.cell.Cell;
import hu.supercluster.gameoflife.game.grid.Grid;
import hu.supercluster.gameoflife.game.rule.Rule;
package hu.supercluster.gameoflife.game.transformer;
public class ThreadedGridTransformer<T extends Cell> implements GridTransformer<T> {
private final int threadCount;
private ExecutorService executorService;
private CountDownLatch countDownLatch;
private int[][] stateChanges;
public ThreadedGridTransformer() {
this(2 * Runtime.getRuntime().availableProcessors());
}
public ThreadedGridTransformer(int threadCount) {
this.threadCount = threadCount;
executorService = Executors.newFixedThreadPool(threadCount);
}
@Override | public final void transform(Grid<T> grid, Rule<T> rule) { |
zsoltk/GameOfLife | app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/CellularAutomaton.java | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/grid/Grid.java
// public interface Grid<T extends Cell> extends Parcelable {
// int getSizeX();
// int getSizeY();
// T getCell(int x, int y);
// void putCell(T cell);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/rule/Rule.java
// public interface Rule<T extends Cell> extends Serializable {
// int apply(Grid<T> grid, int x, int y);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/visualization/brush/Paintable.java
// public interface Paintable {
// void paint(int x, int y, int state);
// }
| import android.os.Parcelable;
import hu.supercluster.gameoflife.game.cell.Cell;
import hu.supercluster.gameoflife.game.grid.Grid;
import hu.supercluster.gameoflife.game.rule.Rule;
import hu.supercluster.gameoflife.game.visualization.brush.Paintable; | package hu.supercluster.gameoflife.game.cellularautomaton;
public interface CellularAutomaton<T extends Cell> extends Parcelable, Paintable {
int getSizeX();
int getSizeY();
int getDefaultCellState();
void reset();
void randomFill(Fill fill);
void step();
void step(int count); | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/grid/Grid.java
// public interface Grid<T extends Cell> extends Parcelable {
// int getSizeX();
// int getSizeY();
// T getCell(int x, int y);
// void putCell(T cell);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/rule/Rule.java
// public interface Rule<T extends Cell> extends Serializable {
// int apply(Grid<T> grid, int x, int y);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/visualization/brush/Paintable.java
// public interface Paintable {
// void paint(int x, int y, int state);
// }
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/CellularAutomaton.java
import android.os.Parcelable;
import hu.supercluster.gameoflife.game.cell.Cell;
import hu.supercluster.gameoflife.game.grid.Grid;
import hu.supercluster.gameoflife.game.rule.Rule;
import hu.supercluster.gameoflife.game.visualization.brush.Paintable;
package hu.supercluster.gameoflife.game.cellularautomaton;
public interface CellularAutomaton<T extends Cell> extends Parcelable, Paintable {
int getSizeX();
int getSizeY();
int getDefaultCellState();
void reset();
void randomFill(Fill fill);
void step();
void step(int count); | Grid<T> getCurrentState(); |
zsoltk/GameOfLife | app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/CellularAutomaton.java | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/grid/Grid.java
// public interface Grid<T extends Cell> extends Parcelable {
// int getSizeX();
// int getSizeY();
// T getCell(int x, int y);
// void putCell(T cell);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/rule/Rule.java
// public interface Rule<T extends Cell> extends Serializable {
// int apply(Grid<T> grid, int x, int y);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/visualization/brush/Paintable.java
// public interface Paintable {
// void paint(int x, int y, int state);
// }
| import android.os.Parcelable;
import hu.supercluster.gameoflife.game.cell.Cell;
import hu.supercluster.gameoflife.game.grid.Grid;
import hu.supercluster.gameoflife.game.rule.Rule;
import hu.supercluster.gameoflife.game.visualization.brush.Paintable; | package hu.supercluster.gameoflife.game.cellularautomaton;
public interface CellularAutomaton<T extends Cell> extends Parcelable, Paintable {
int getSizeX();
int getSizeY();
int getDefaultCellState();
void reset();
void randomFill(Fill fill);
void step();
void step(int count);
Grid<T> getCurrentState();
void setState(Grid<T> grid); | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/grid/Grid.java
// public interface Grid<T extends Cell> extends Parcelable {
// int getSizeX();
// int getSizeY();
// T getCell(int x, int y);
// void putCell(T cell);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/rule/Rule.java
// public interface Rule<T extends Cell> extends Serializable {
// int apply(Grid<T> grid, int x, int y);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/visualization/brush/Paintable.java
// public interface Paintable {
// void paint(int x, int y, int state);
// }
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/CellularAutomaton.java
import android.os.Parcelable;
import hu.supercluster.gameoflife.game.cell.Cell;
import hu.supercluster.gameoflife.game.grid.Grid;
import hu.supercluster.gameoflife.game.rule.Rule;
import hu.supercluster.gameoflife.game.visualization.brush.Paintable;
package hu.supercluster.gameoflife.game.cellularautomaton;
public interface CellularAutomaton<T extends Cell> extends Parcelable, Paintable {
int getSizeX();
int getSizeY();
int getDefaultCellState();
void reset();
void randomFill(Fill fill);
void step();
void step(int count);
Grid<T> getCurrentState();
void setState(Grid<T> grid); | Rule<T> getRule(); |
zsoltk/GameOfLife | app/src/main/java/hu/supercluster/gameoflife/game/manager/GameParamsBuilder.java | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/Fill.java
// public class Fill {
// private final float percentage;
// private final int state;
//
// public Fill(float percentage, int state) {
// this.percentage = percentage;
// this.state = state;
// }
//
// public float getPercentage() {
// return percentage;
// }
//
// public int getState() {
// return state;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/visualization/cell/CellColors.java
// public interface CellColors {
// Paint getPaint(int state);
// }
| import android.graphics.Point;
import hu.supercluster.gameoflife.game.cellularautomaton.Fill;
import hu.supercluster.gameoflife.game.visualization.cell.CellColors; | package hu.supercluster.gameoflife.game.manager;
public class GameParamsBuilder {
private int screenOrientation;
private Point displaySize;
private int cellSizeInPixels; | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/Fill.java
// public class Fill {
// private final float percentage;
// private final int state;
//
// public Fill(float percentage, int state) {
// this.percentage = percentage;
// this.state = state;
// }
//
// public float getPercentage() {
// return percentage;
// }
//
// public int getState() {
// return state;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/visualization/cell/CellColors.java
// public interface CellColors {
// Paint getPaint(int state);
// }
// Path: app/src/main/java/hu/supercluster/gameoflife/game/manager/GameParamsBuilder.java
import android.graphics.Point;
import hu.supercluster.gameoflife.game.cellularautomaton.Fill;
import hu.supercluster.gameoflife.game.visualization.cell.CellColors;
package hu.supercluster.gameoflife.game.manager;
public class GameParamsBuilder {
private int screenOrientation;
private Point displaySize;
private int cellSizeInPixels; | private Fill fill; |
zsoltk/GameOfLife | app/src/main/java/hu/supercluster/gameoflife/game/manager/GameParamsBuilder.java | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/Fill.java
// public class Fill {
// private final float percentage;
// private final int state;
//
// public Fill(float percentage, int state) {
// this.percentage = percentage;
// this.state = state;
// }
//
// public float getPercentage() {
// return percentage;
// }
//
// public int getState() {
// return state;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/visualization/cell/CellColors.java
// public interface CellColors {
// Paint getPaint(int state);
// }
| import android.graphics.Point;
import hu.supercluster.gameoflife.game.cellularautomaton.Fill;
import hu.supercluster.gameoflife.game.visualization.cell.CellColors; | package hu.supercluster.gameoflife.game.manager;
public class GameParamsBuilder {
private int screenOrientation;
private Point displaySize;
private int cellSizeInPixels;
private Fill fill; | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/Fill.java
// public class Fill {
// private final float percentage;
// private final int state;
//
// public Fill(float percentage, int state) {
// this.percentage = percentage;
// this.state = state;
// }
//
// public float getPercentage() {
// return percentage;
// }
//
// public int getState() {
// return state;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/visualization/cell/CellColors.java
// public interface CellColors {
// Paint getPaint(int state);
// }
// Path: app/src/main/java/hu/supercluster/gameoflife/game/manager/GameParamsBuilder.java
import android.graphics.Point;
import hu.supercluster.gameoflife.game.cellularautomaton.Fill;
import hu.supercluster.gameoflife.game.visualization.cell.CellColors;
package hu.supercluster.gameoflife.game.manager;
public class GameParamsBuilder {
private int screenOrientation;
private Point displaySize;
private int cellSizeInPixels;
private Fill fill; | private CellColors cellColors; |
zsoltk/GameOfLife | app/src/test/java/hu/supercluster/gameoflife/game/grid/EndlessGridTest.java | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/CellFactory.java
// public interface CellFactory<T extends Cell> extends Serializable {
// T create(int x, int y);
// int[] flatten(T cell);
// T inflate(int[] flattened);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/SimpleCell.java
// public class SimpleCell implements Cell {
// static final AtomicLong NEXT_ID = new AtomicLong(0);
// final long id = NEXT_ID.getAndIncrement();
// final int x;
// final int y;
// int state;
// int neighborCount;
// Overseer overseer;
//
// public SimpleCell(int x, int y, int state) {
// this.x = x;
// this.y = y;
// this.state = state;
// }
//
// @Override
// public void setOverseer(Overseer overseer) {
// this.overseer = overseer;
// }
//
// @Override
// public void reset(int state) {
// this.state = state;
// neighborCount = 0;
// }
//
// @Override
// public long getId() {
// return id;
// }
//
// @Override
// public int getX() {
// return x;
// }
//
// @Override
// public int getY() {
// return y;
// }
//
// @Override
// public int getState() {
// return state;
// }
//
// @Override
// public void setState(int newState) {
// int oldState = this.state;
// this.state = newState;
//
// if (newState != oldState && overseer != null) {
// overseer.onCellStateChanged(new CellStateChange(this));
// }
// }
//
// @Override
// public boolean isAlive() {
// return !isDead();
// }
//
// @Override
// public boolean isDead() {
// return state == STATE_DEAD;
// }
//
// @Override
// public void onNeighborStateChange(int newState) {
// if (newState == STATE_DEAD) {
// decreaseNeighborCount();
//
// } else {
// increaseNeighborCount();
// }
// }
//
// void increaseNeighborCount() {
// neighborCount++;
// }
//
// void decreaseNeighborCount() {
// neighborCount--;
// }
//
// public int getNeighborCount() {
// return neighborCount;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// SimpleCell that = (SimpleCell) o;
//
// if (neighborCount != that.neighborCount) return false;
// if (state != that.state) return false;
// if (x != that.x) return false;
// if (y != that.y) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = x;
// result = 31 * result + y;
// result = 31 * result + state;
// result = 31 * result + neighborCount;
// return result;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/SimpleCellFactory.java
// public class SimpleCellFactory implements CellFactory<SimpleCell> {
// @Override
// public SimpleCell create(int x, int y) {
// return new SimpleCell(x, y, SimpleCell.STATE_DEAD);
// }
//
// @Override
// public int[] flatten(SimpleCell cell) {
// final int[] flattened = new int[4];
// flattened[0] = cell.x;
// flattened[1] = cell.y;
// flattened[2] = cell.state;
// flattened[3] = cell.neighborCount;
//
// return flattened;
// }
//
// @Override
// public SimpleCell inflate(int[] flattened) {
// final SimpleCell cell = new SimpleCell(
// flattened[0],
// flattened[1],
// flattened[2]
// );
//
// cell.neighborCount = flattened[3];
//
// return cell;
// }
// }
//
// Path: app/src/test/java/hu/supercluster/gameoflife/test/RobolectricTest.java
// @RunWith(RobolectricGradleTestRunner.class)
// @Config(
// constants = BuildConfig.class,
// sdk = Build.VERSION_CODES.JELLY_BEAN,
// packageName = "hu.supercluster.gameoflife"
// )
// abstract public class RobolectricTest {
//
// }
| import org.junit.Before;
import org.junit.Test;
import hu.supercluster.gameoflife.game.cell.Cell;
import hu.supercluster.gameoflife.game.cell.CellFactory;
import hu.supercluster.gameoflife.game.cell.SimpleCell;
import hu.supercluster.gameoflife.game.cell.SimpleCellFactory;
import hu.supercluster.gameoflife.test.RobolectricTest;
import static org.fest.assertions.api.Assertions.*; | package hu.supercluster.gameoflife.game.grid;
public class EndlessGridTest extends RobolectricTest {
EndlessGrid<SimpleCell> grid; | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/CellFactory.java
// public interface CellFactory<T extends Cell> extends Serializable {
// T create(int x, int y);
// int[] flatten(T cell);
// T inflate(int[] flattened);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/SimpleCell.java
// public class SimpleCell implements Cell {
// static final AtomicLong NEXT_ID = new AtomicLong(0);
// final long id = NEXT_ID.getAndIncrement();
// final int x;
// final int y;
// int state;
// int neighborCount;
// Overseer overseer;
//
// public SimpleCell(int x, int y, int state) {
// this.x = x;
// this.y = y;
// this.state = state;
// }
//
// @Override
// public void setOverseer(Overseer overseer) {
// this.overseer = overseer;
// }
//
// @Override
// public void reset(int state) {
// this.state = state;
// neighborCount = 0;
// }
//
// @Override
// public long getId() {
// return id;
// }
//
// @Override
// public int getX() {
// return x;
// }
//
// @Override
// public int getY() {
// return y;
// }
//
// @Override
// public int getState() {
// return state;
// }
//
// @Override
// public void setState(int newState) {
// int oldState = this.state;
// this.state = newState;
//
// if (newState != oldState && overseer != null) {
// overseer.onCellStateChanged(new CellStateChange(this));
// }
// }
//
// @Override
// public boolean isAlive() {
// return !isDead();
// }
//
// @Override
// public boolean isDead() {
// return state == STATE_DEAD;
// }
//
// @Override
// public void onNeighborStateChange(int newState) {
// if (newState == STATE_DEAD) {
// decreaseNeighborCount();
//
// } else {
// increaseNeighborCount();
// }
// }
//
// void increaseNeighborCount() {
// neighborCount++;
// }
//
// void decreaseNeighborCount() {
// neighborCount--;
// }
//
// public int getNeighborCount() {
// return neighborCount;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// SimpleCell that = (SimpleCell) o;
//
// if (neighborCount != that.neighborCount) return false;
// if (state != that.state) return false;
// if (x != that.x) return false;
// if (y != that.y) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = x;
// result = 31 * result + y;
// result = 31 * result + state;
// result = 31 * result + neighborCount;
// return result;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/SimpleCellFactory.java
// public class SimpleCellFactory implements CellFactory<SimpleCell> {
// @Override
// public SimpleCell create(int x, int y) {
// return new SimpleCell(x, y, SimpleCell.STATE_DEAD);
// }
//
// @Override
// public int[] flatten(SimpleCell cell) {
// final int[] flattened = new int[4];
// flattened[0] = cell.x;
// flattened[1] = cell.y;
// flattened[2] = cell.state;
// flattened[3] = cell.neighborCount;
//
// return flattened;
// }
//
// @Override
// public SimpleCell inflate(int[] flattened) {
// final SimpleCell cell = new SimpleCell(
// flattened[0],
// flattened[1],
// flattened[2]
// );
//
// cell.neighborCount = flattened[3];
//
// return cell;
// }
// }
//
// Path: app/src/test/java/hu/supercluster/gameoflife/test/RobolectricTest.java
// @RunWith(RobolectricGradleTestRunner.class)
// @Config(
// constants = BuildConfig.class,
// sdk = Build.VERSION_CODES.JELLY_BEAN,
// packageName = "hu.supercluster.gameoflife"
// )
// abstract public class RobolectricTest {
//
// }
// Path: app/src/test/java/hu/supercluster/gameoflife/game/grid/EndlessGridTest.java
import org.junit.Before;
import org.junit.Test;
import hu.supercluster.gameoflife.game.cell.Cell;
import hu.supercluster.gameoflife.game.cell.CellFactory;
import hu.supercluster.gameoflife.game.cell.SimpleCell;
import hu.supercluster.gameoflife.game.cell.SimpleCellFactory;
import hu.supercluster.gameoflife.test.RobolectricTest;
import static org.fest.assertions.api.Assertions.*;
package hu.supercluster.gameoflife.game.grid;
public class EndlessGridTest extends RobolectricTest {
EndlessGrid<SimpleCell> grid; | CellFactory<SimpleCell> cellFactory; |
zsoltk/GameOfLife | app/src/test/java/hu/supercluster/gameoflife/game/grid/EndlessGridTest.java | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/CellFactory.java
// public interface CellFactory<T extends Cell> extends Serializable {
// T create(int x, int y);
// int[] flatten(T cell);
// T inflate(int[] flattened);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/SimpleCell.java
// public class SimpleCell implements Cell {
// static final AtomicLong NEXT_ID = new AtomicLong(0);
// final long id = NEXT_ID.getAndIncrement();
// final int x;
// final int y;
// int state;
// int neighborCount;
// Overseer overseer;
//
// public SimpleCell(int x, int y, int state) {
// this.x = x;
// this.y = y;
// this.state = state;
// }
//
// @Override
// public void setOverseer(Overseer overseer) {
// this.overseer = overseer;
// }
//
// @Override
// public void reset(int state) {
// this.state = state;
// neighborCount = 0;
// }
//
// @Override
// public long getId() {
// return id;
// }
//
// @Override
// public int getX() {
// return x;
// }
//
// @Override
// public int getY() {
// return y;
// }
//
// @Override
// public int getState() {
// return state;
// }
//
// @Override
// public void setState(int newState) {
// int oldState = this.state;
// this.state = newState;
//
// if (newState != oldState && overseer != null) {
// overseer.onCellStateChanged(new CellStateChange(this));
// }
// }
//
// @Override
// public boolean isAlive() {
// return !isDead();
// }
//
// @Override
// public boolean isDead() {
// return state == STATE_DEAD;
// }
//
// @Override
// public void onNeighborStateChange(int newState) {
// if (newState == STATE_DEAD) {
// decreaseNeighborCount();
//
// } else {
// increaseNeighborCount();
// }
// }
//
// void increaseNeighborCount() {
// neighborCount++;
// }
//
// void decreaseNeighborCount() {
// neighborCount--;
// }
//
// public int getNeighborCount() {
// return neighborCount;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// SimpleCell that = (SimpleCell) o;
//
// if (neighborCount != that.neighborCount) return false;
// if (state != that.state) return false;
// if (x != that.x) return false;
// if (y != that.y) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = x;
// result = 31 * result + y;
// result = 31 * result + state;
// result = 31 * result + neighborCount;
// return result;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/SimpleCellFactory.java
// public class SimpleCellFactory implements CellFactory<SimpleCell> {
// @Override
// public SimpleCell create(int x, int y) {
// return new SimpleCell(x, y, SimpleCell.STATE_DEAD);
// }
//
// @Override
// public int[] flatten(SimpleCell cell) {
// final int[] flattened = new int[4];
// flattened[0] = cell.x;
// flattened[1] = cell.y;
// flattened[2] = cell.state;
// flattened[3] = cell.neighborCount;
//
// return flattened;
// }
//
// @Override
// public SimpleCell inflate(int[] flattened) {
// final SimpleCell cell = new SimpleCell(
// flattened[0],
// flattened[1],
// flattened[2]
// );
//
// cell.neighborCount = flattened[3];
//
// return cell;
// }
// }
//
// Path: app/src/test/java/hu/supercluster/gameoflife/test/RobolectricTest.java
// @RunWith(RobolectricGradleTestRunner.class)
// @Config(
// constants = BuildConfig.class,
// sdk = Build.VERSION_CODES.JELLY_BEAN,
// packageName = "hu.supercluster.gameoflife"
// )
// abstract public class RobolectricTest {
//
// }
| import org.junit.Before;
import org.junit.Test;
import hu.supercluster.gameoflife.game.cell.Cell;
import hu.supercluster.gameoflife.game.cell.CellFactory;
import hu.supercluster.gameoflife.game.cell.SimpleCell;
import hu.supercluster.gameoflife.game.cell.SimpleCellFactory;
import hu.supercluster.gameoflife.test.RobolectricTest;
import static org.fest.assertions.api.Assertions.*; | package hu.supercluster.gameoflife.game.grid;
public class EndlessGridTest extends RobolectricTest {
EndlessGrid<SimpleCell> grid;
CellFactory<SimpleCell> cellFactory;
@Before
public void setup() { | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/CellFactory.java
// public interface CellFactory<T extends Cell> extends Serializable {
// T create(int x, int y);
// int[] flatten(T cell);
// T inflate(int[] flattened);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/SimpleCell.java
// public class SimpleCell implements Cell {
// static final AtomicLong NEXT_ID = new AtomicLong(0);
// final long id = NEXT_ID.getAndIncrement();
// final int x;
// final int y;
// int state;
// int neighborCount;
// Overseer overseer;
//
// public SimpleCell(int x, int y, int state) {
// this.x = x;
// this.y = y;
// this.state = state;
// }
//
// @Override
// public void setOverseer(Overseer overseer) {
// this.overseer = overseer;
// }
//
// @Override
// public void reset(int state) {
// this.state = state;
// neighborCount = 0;
// }
//
// @Override
// public long getId() {
// return id;
// }
//
// @Override
// public int getX() {
// return x;
// }
//
// @Override
// public int getY() {
// return y;
// }
//
// @Override
// public int getState() {
// return state;
// }
//
// @Override
// public void setState(int newState) {
// int oldState = this.state;
// this.state = newState;
//
// if (newState != oldState && overseer != null) {
// overseer.onCellStateChanged(new CellStateChange(this));
// }
// }
//
// @Override
// public boolean isAlive() {
// return !isDead();
// }
//
// @Override
// public boolean isDead() {
// return state == STATE_DEAD;
// }
//
// @Override
// public void onNeighborStateChange(int newState) {
// if (newState == STATE_DEAD) {
// decreaseNeighborCount();
//
// } else {
// increaseNeighborCount();
// }
// }
//
// void increaseNeighborCount() {
// neighborCount++;
// }
//
// void decreaseNeighborCount() {
// neighborCount--;
// }
//
// public int getNeighborCount() {
// return neighborCount;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// SimpleCell that = (SimpleCell) o;
//
// if (neighborCount != that.neighborCount) return false;
// if (state != that.state) return false;
// if (x != that.x) return false;
// if (y != that.y) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = x;
// result = 31 * result + y;
// result = 31 * result + state;
// result = 31 * result + neighborCount;
// return result;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/SimpleCellFactory.java
// public class SimpleCellFactory implements CellFactory<SimpleCell> {
// @Override
// public SimpleCell create(int x, int y) {
// return new SimpleCell(x, y, SimpleCell.STATE_DEAD);
// }
//
// @Override
// public int[] flatten(SimpleCell cell) {
// final int[] flattened = new int[4];
// flattened[0] = cell.x;
// flattened[1] = cell.y;
// flattened[2] = cell.state;
// flattened[3] = cell.neighborCount;
//
// return flattened;
// }
//
// @Override
// public SimpleCell inflate(int[] flattened) {
// final SimpleCell cell = new SimpleCell(
// flattened[0],
// flattened[1],
// flattened[2]
// );
//
// cell.neighborCount = flattened[3];
//
// return cell;
// }
// }
//
// Path: app/src/test/java/hu/supercluster/gameoflife/test/RobolectricTest.java
// @RunWith(RobolectricGradleTestRunner.class)
// @Config(
// constants = BuildConfig.class,
// sdk = Build.VERSION_CODES.JELLY_BEAN,
// packageName = "hu.supercluster.gameoflife"
// )
// abstract public class RobolectricTest {
//
// }
// Path: app/src/test/java/hu/supercluster/gameoflife/game/grid/EndlessGridTest.java
import org.junit.Before;
import org.junit.Test;
import hu.supercluster.gameoflife.game.cell.Cell;
import hu.supercluster.gameoflife.game.cell.CellFactory;
import hu.supercluster.gameoflife.game.cell.SimpleCell;
import hu.supercluster.gameoflife.game.cell.SimpleCellFactory;
import hu.supercluster.gameoflife.test.RobolectricTest;
import static org.fest.assertions.api.Assertions.*;
package hu.supercluster.gameoflife.game.grid;
public class EndlessGridTest extends RobolectricTest {
EndlessGrid<SimpleCell> grid;
CellFactory<SimpleCell> cellFactory;
@Before
public void setup() { | cellFactory = new SimpleCellFactory(); |
zsoltk/GameOfLife | app/src/test/java/hu/supercluster/gameoflife/game/transformer/ThreadedGridTransformerTest.java | // Path: app/src/test/java/hu/supercluster/gameoflife/game/testutils/GrowableCell.java
// public class GrowableCell implements Cell {
// static final AtomicLong NEXT_ID = new AtomicLong(0);
// final long id = NEXT_ID.getAndIncrement();
//
// final int x;
// final int y;
// int state;
// Overseer overseer;
//
// public GrowableCell(int x, int y, int state) {
// this.x = x;
// this.y = y;
// this.state = state;
// }
//
// @Override
// public void setOverseer(Overseer overseer) {
// this.overseer = overseer;
// }
//
// @Override
// public void reset(int state) {
// this.state = state;
// }
//
// @Override
// public long getId() {
// return id;
// }
//
// @Override
// public int getX() {
// return x;
// }
//
// @Override
// public int getY() {
// return y;
// }
//
// @Override
// public int getState() {
// return state;
// }
//
// @Override
// public void setState(int newState) {
// this.state = newState;
// }
//
// @Override
// public boolean isAlive() {
// return !isDead();
// }
//
// @Override
// public boolean isDead() {
// return state == STATE_DEAD;
// }
//
// @Override
// public void onNeighborStateChange(int newState) {
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// GrowableCell that = (GrowableCell) o;
//
// if (state != that.state) return false;
// if (x != that.x) return false;
// if (y != that.y) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = x;
// result = 31 * result + y;
// result = 31 * result + state;
// return result;
// }
//
// @Override
// public String toString() {
// return "GrowableCell{" +
// "id=" + id +
// ", x=" + x +
// ", y=" + y +
// ", state=" + state +
// '}';
// }
// }
| import hu.supercluster.gameoflife.game.testutils.GrowableCell; | package hu.supercluster.gameoflife.game.transformer;
public class ThreadedGridTransformerTest extends AbstractGridTransformerTester {
@Override | // Path: app/src/test/java/hu/supercluster/gameoflife/game/testutils/GrowableCell.java
// public class GrowableCell implements Cell {
// static final AtomicLong NEXT_ID = new AtomicLong(0);
// final long id = NEXT_ID.getAndIncrement();
//
// final int x;
// final int y;
// int state;
// Overseer overseer;
//
// public GrowableCell(int x, int y, int state) {
// this.x = x;
// this.y = y;
// this.state = state;
// }
//
// @Override
// public void setOverseer(Overseer overseer) {
// this.overseer = overseer;
// }
//
// @Override
// public void reset(int state) {
// this.state = state;
// }
//
// @Override
// public long getId() {
// return id;
// }
//
// @Override
// public int getX() {
// return x;
// }
//
// @Override
// public int getY() {
// return y;
// }
//
// @Override
// public int getState() {
// return state;
// }
//
// @Override
// public void setState(int newState) {
// this.state = newState;
// }
//
// @Override
// public boolean isAlive() {
// return !isDead();
// }
//
// @Override
// public boolean isDead() {
// return state == STATE_DEAD;
// }
//
// @Override
// public void onNeighborStateChange(int newState) {
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// GrowableCell that = (GrowableCell) o;
//
// if (state != that.state) return false;
// if (x != that.x) return false;
// if (y != that.y) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = x;
// result = 31 * result + y;
// result = 31 * result + state;
// return result;
// }
//
// @Override
// public String toString() {
// return "GrowableCell{" +
// "id=" + id +
// ", x=" + x +
// ", y=" + y +
// ", state=" + state +
// '}';
// }
// }
// Path: app/src/test/java/hu/supercluster/gameoflife/game/transformer/ThreadedGridTransformerTest.java
import hu.supercluster.gameoflife.game.testutils.GrowableCell;
package hu.supercluster.gameoflife.game.transformer;
public class ThreadedGridTransformerTest extends AbstractGridTransformerTester {
@Override | protected GridTransformer<GrowableCell> getTransformer() { |
zsoltk/GameOfLife | app/src/main/java/hu/supercluster/gameoflife/game/cell/SimpleCell.java | // Path: app/src/main/java/hu/supercluster/gameoflife/game/event/CellStateChange.java
// public class CellStateChange {
// public final int x;
// public final int y;
// public final int stateSnapshot;
// public final Cell cell;
//
// public CellStateChange(Cell cell) {
// this.cell = cell;
// x = cell.getX();
// y = cell.getY();
// stateSnapshot = cell.getState();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// CellStateChange that = (CellStateChange) o;
//
// if (stateSnapshot != that.stateSnapshot) return false;
// if (x != that.x) return false;
// if (y != that.y) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = x;
// result = 31 * result + y;
// result = 31 * result + stateSnapshot;
// return result;
// }
// }
| import java.util.concurrent.atomic.AtomicLong;
import hu.supercluster.gameoflife.game.event.CellStateChange; | this.state = state;
neighborCount = 0;
}
@Override
public long getId() {
return id;
}
@Override
public int getX() {
return x;
}
@Override
public int getY() {
return y;
}
@Override
public int getState() {
return state;
}
@Override
public void setState(int newState) {
int oldState = this.state;
this.state = newState;
if (newState != oldState && overseer != null) { | // Path: app/src/main/java/hu/supercluster/gameoflife/game/event/CellStateChange.java
// public class CellStateChange {
// public final int x;
// public final int y;
// public final int stateSnapshot;
// public final Cell cell;
//
// public CellStateChange(Cell cell) {
// this.cell = cell;
// x = cell.getX();
// y = cell.getY();
// stateSnapshot = cell.getState();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// CellStateChange that = (CellStateChange) o;
//
// if (stateSnapshot != that.stateSnapshot) return false;
// if (x != that.x) return false;
// if (y != that.y) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = x;
// result = 31 * result + y;
// result = 31 * result + stateSnapshot;
// return result;
// }
// }
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/SimpleCell.java
import java.util.concurrent.atomic.AtomicLong;
import hu.supercluster.gameoflife.game.event.CellStateChange;
this.state = state;
neighborCount = 0;
}
@Override
public long getId() {
return id;
}
@Override
public int getX() {
return x;
}
@Override
public int getY() {
return y;
}
@Override
public int getState() {
return state;
}
@Override
public void setState(int newState) {
int oldState = this.state;
this.state = newState;
if (newState != oldState && overseer != null) { | overseer.onCellStateChanged(new CellStateChange(this)); |
zsoltk/GameOfLife | app/src/test/java/hu/supercluster/gameoflife/game/testutils/SimpleIncrementingRule.java | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/grid/Grid.java
// public interface Grid<T extends Cell> extends Parcelable {
// int getSizeX();
// int getSizeY();
// T getCell(int x, int y);
// void putCell(T cell);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/rule/Rule.java
// public interface Rule<T extends Cell> extends Serializable {
// int apply(Grid<T> grid, int x, int y);
// }
| import hu.supercluster.gameoflife.game.cell.Cell;
import hu.supercluster.gameoflife.game.grid.Grid;
import hu.supercluster.gameoflife.game.rule.Rule; | package hu.supercluster.gameoflife.game.testutils;
public class SimpleIncrementingRule implements Rule<GrowableCell> {
@Override | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/grid/Grid.java
// public interface Grid<T extends Cell> extends Parcelable {
// int getSizeX();
// int getSizeY();
// T getCell(int x, int y);
// void putCell(T cell);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/rule/Rule.java
// public interface Rule<T extends Cell> extends Serializable {
// int apply(Grid<T> grid, int x, int y);
// }
// Path: app/src/test/java/hu/supercluster/gameoflife/game/testutils/SimpleIncrementingRule.java
import hu.supercluster.gameoflife.game.cell.Cell;
import hu.supercluster.gameoflife.game.grid.Grid;
import hu.supercluster.gameoflife.game.rule.Rule;
package hu.supercluster.gameoflife.game.testutils;
public class SimpleIncrementingRule implements Rule<GrowableCell> {
@Override | public int apply(Grid<GrowableCell> grid, int x, int y) { |
zsoltk/GameOfLife | app/src/test/java/hu/supercluster/gameoflife/game/testutils/SimpleIncrementingRule.java | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/grid/Grid.java
// public interface Grid<T extends Cell> extends Parcelable {
// int getSizeX();
// int getSizeY();
// T getCell(int x, int y);
// void putCell(T cell);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/rule/Rule.java
// public interface Rule<T extends Cell> extends Serializable {
// int apply(Grid<T> grid, int x, int y);
// }
| import hu.supercluster.gameoflife.game.cell.Cell;
import hu.supercluster.gameoflife.game.grid.Grid;
import hu.supercluster.gameoflife.game.rule.Rule; | package hu.supercluster.gameoflife.game.testutils;
public class SimpleIncrementingRule implements Rule<GrowableCell> {
@Override
public int apply(Grid<GrowableCell> grid, int x, int y) { | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/grid/Grid.java
// public interface Grid<T extends Cell> extends Parcelable {
// int getSizeX();
// int getSizeY();
// T getCell(int x, int y);
// void putCell(T cell);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/rule/Rule.java
// public interface Rule<T extends Cell> extends Serializable {
// int apply(Grid<T> grid, int x, int y);
// }
// Path: app/src/test/java/hu/supercluster/gameoflife/game/testutils/SimpleIncrementingRule.java
import hu.supercluster.gameoflife.game.cell.Cell;
import hu.supercluster.gameoflife.game.grid.Grid;
import hu.supercluster.gameoflife.game.rule.Rule;
package hu.supercluster.gameoflife.game.testutils;
public class SimpleIncrementingRule implements Rule<GrowableCell> {
@Override
public int apply(Grid<GrowableCell> grid, int x, int y) { | Cell cell = grid.getCell(x, y); |
zsoltk/GameOfLife | app/src/main/java/hu/supercluster/gameoflife/game/manager/GameParams.java | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/Fill.java
// public class Fill {
// private final float percentage;
// private final int state;
//
// public Fill(float percentage, int state) {
// this.percentage = percentage;
// this.state = state;
// }
//
// public float getPercentage() {
// return percentage;
// }
//
// public int getState() {
// return state;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/visualization/cell/CellColors.java
// public interface CellColors {
// Paint getPaint(int state);
// }
| import android.graphics.Point;
import hu.supercluster.gameoflife.game.cellularautomaton.Fill;
import hu.supercluster.gameoflife.game.visualization.cell.CellColors; | package hu.supercluster.gameoflife.game.manager;
public class GameParams {
private final int screenOrientation;
private final Point displaySize;
private int gridSizeX;
private int gridSizeY;
private final int cellSizeInPixels; | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/Fill.java
// public class Fill {
// private final float percentage;
// private final int state;
//
// public Fill(float percentage, int state) {
// this.percentage = percentage;
// this.state = state;
// }
//
// public float getPercentage() {
// return percentage;
// }
//
// public int getState() {
// return state;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/visualization/cell/CellColors.java
// public interface CellColors {
// Paint getPaint(int state);
// }
// Path: app/src/main/java/hu/supercluster/gameoflife/game/manager/GameParams.java
import android.graphics.Point;
import hu.supercluster.gameoflife.game.cellularautomaton.Fill;
import hu.supercluster.gameoflife.game.visualization.cell.CellColors;
package hu.supercluster.gameoflife.game.manager;
public class GameParams {
private final int screenOrientation;
private final Point displaySize;
private int gridSizeX;
private int gridSizeY;
private final int cellSizeInPixels; | private final Fill fill; |
zsoltk/GameOfLife | app/src/main/java/hu/supercluster/gameoflife/game/manager/GameParams.java | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/Fill.java
// public class Fill {
// private final float percentage;
// private final int state;
//
// public Fill(float percentage, int state) {
// this.percentage = percentage;
// this.state = state;
// }
//
// public float getPercentage() {
// return percentage;
// }
//
// public int getState() {
// return state;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/visualization/cell/CellColors.java
// public interface CellColors {
// Paint getPaint(int state);
// }
| import android.graphics.Point;
import hu.supercluster.gameoflife.game.cellularautomaton.Fill;
import hu.supercluster.gameoflife.game.visualization.cell.CellColors; | package hu.supercluster.gameoflife.game.manager;
public class GameParams {
private final int screenOrientation;
private final Point displaySize;
private int gridSizeX;
private int gridSizeY;
private final int cellSizeInPixels;
private final Fill fill; | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/Fill.java
// public class Fill {
// private final float percentage;
// private final int state;
//
// public Fill(float percentage, int state) {
// this.percentage = percentage;
// this.state = state;
// }
//
// public float getPercentage() {
// return percentage;
// }
//
// public int getState() {
// return state;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/visualization/cell/CellColors.java
// public interface CellColors {
// Paint getPaint(int state);
// }
// Path: app/src/main/java/hu/supercluster/gameoflife/game/manager/GameParams.java
import android.graphics.Point;
import hu.supercluster.gameoflife.game.cellularautomaton.Fill;
import hu.supercluster.gameoflife.game.visualization.cell.CellColors;
package hu.supercluster.gameoflife.game.manager;
public class GameParams {
private final int screenOrientation;
private final Point displaySize;
private int gridSizeX;
private int gridSizeY;
private final int cellSizeInPixels;
private final Fill fill; | private final CellColors cellColors; |
zsoltk/GameOfLife | app/src/main/java/hu/supercluster/gameoflife/game/manager/GameManager.java | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/CellularAutomaton.java
// public interface CellularAutomaton<T extends Cell> extends Parcelable, Paintable {
// int getSizeX();
// int getSizeY();
// int getDefaultCellState();
// void reset();
// void randomFill(Fill fill);
// void step();
// void step(int count);
// Grid<T> getCurrentState();
// void setState(Grid<T> grid);
// Rule<T> getRule();
// void setRule(Rule<T> rule);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/CellularAutomatonFactory.java
// public interface CellularAutomatonFactory {
// CellularAutomaton<?> create(int gridSizeX, int gridSizeY);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/app/view/AutomatonView.java
// public class AutomatonView extends SurfaceView implements SurfaceHolder.Callback {
// private CellularAutomaton automaton;
// private GameParams params;
// private AutomatonThread thread;
//
// public AutomatonView(Context context) {
// super(context);
// }
//
// public AutomatonView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public AutomatonView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// }
//
// @DebugLog
// public void init(CellularAutomaton automaton, GameParams params) {
// this.automaton = automaton;
// this.params = params;
//
// SurfaceHolder surfaceHolder = getHolder();
// surfaceHolder.addCallback(this);
// }
//
// @Override
// @DebugLog
// public void surfaceCreated(SurfaceHolder holder) {
// if (thread == null || thread.getState() == Thread.State.TERMINATED) {
// thread = new AutomatonThread(automaton, holder, params);
// thread.start();
// }
//
// thread.setRunning(true);
// }
//
// @Override
// public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// //
// }
//
// @Override
// @DebugLog
// public void surfaceDestroyed(SurfaceHolder holder) {
// thread.setRunning(false);
// waitForThreadToDie();
// }
//
// @DebugLog
// private void waitForThreadToDie() {
// while (true) {
// try {
// thread.join();
// break;
//
// } catch (InterruptedException e) {
// }
// }
// }
//
// @Override
// public boolean onTouchEvent(MotionEvent event) {
// paint(event);
//
// return true;
// }
//
// protected void paint(MotionEvent event) {
// int x = Math.round(event.getX() / params.getCellSizeInPixels());
// int y = Math.round(event.getY() / params.getCellSizeInPixels());
//
// EventBus.getInstance().post(new PaintWithBrush(x, y));
// }
// }
| import android.os.Bundle;
import hu.supercluster.gameoflife.game.cellularautomaton.CellularAutomaton;
import hu.supercluster.gameoflife.game.cellularautomaton.CellularAutomatonFactory;
import hu.supercluster.gameoflife.app.view.AutomatonView; | package hu.supercluster.gameoflife.game.manager;
public class GameManager {
public static final String KEY_AUTOMATON = "automaton"; | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/CellularAutomaton.java
// public interface CellularAutomaton<T extends Cell> extends Parcelable, Paintable {
// int getSizeX();
// int getSizeY();
// int getDefaultCellState();
// void reset();
// void randomFill(Fill fill);
// void step();
// void step(int count);
// Grid<T> getCurrentState();
// void setState(Grid<T> grid);
// Rule<T> getRule();
// void setRule(Rule<T> rule);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/CellularAutomatonFactory.java
// public interface CellularAutomatonFactory {
// CellularAutomaton<?> create(int gridSizeX, int gridSizeY);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/app/view/AutomatonView.java
// public class AutomatonView extends SurfaceView implements SurfaceHolder.Callback {
// private CellularAutomaton automaton;
// private GameParams params;
// private AutomatonThread thread;
//
// public AutomatonView(Context context) {
// super(context);
// }
//
// public AutomatonView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public AutomatonView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// }
//
// @DebugLog
// public void init(CellularAutomaton automaton, GameParams params) {
// this.automaton = automaton;
// this.params = params;
//
// SurfaceHolder surfaceHolder = getHolder();
// surfaceHolder.addCallback(this);
// }
//
// @Override
// @DebugLog
// public void surfaceCreated(SurfaceHolder holder) {
// if (thread == null || thread.getState() == Thread.State.TERMINATED) {
// thread = new AutomatonThread(automaton, holder, params);
// thread.start();
// }
//
// thread.setRunning(true);
// }
//
// @Override
// public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// //
// }
//
// @Override
// @DebugLog
// public void surfaceDestroyed(SurfaceHolder holder) {
// thread.setRunning(false);
// waitForThreadToDie();
// }
//
// @DebugLog
// private void waitForThreadToDie() {
// while (true) {
// try {
// thread.join();
// break;
//
// } catch (InterruptedException e) {
// }
// }
// }
//
// @Override
// public boolean onTouchEvent(MotionEvent event) {
// paint(event);
//
// return true;
// }
//
// protected void paint(MotionEvent event) {
// int x = Math.round(event.getX() / params.getCellSizeInPixels());
// int y = Math.round(event.getY() / params.getCellSizeInPixels());
//
// EventBus.getInstance().post(new PaintWithBrush(x, y));
// }
// }
// Path: app/src/main/java/hu/supercluster/gameoflife/game/manager/GameManager.java
import android.os.Bundle;
import hu.supercluster.gameoflife.game.cellularautomaton.CellularAutomaton;
import hu.supercluster.gameoflife.game.cellularautomaton.CellularAutomatonFactory;
import hu.supercluster.gameoflife.app.view.AutomatonView;
package hu.supercluster.gameoflife.game.manager;
public class GameManager {
public static final String KEY_AUTOMATON = "automaton"; | private final AutomatonView automatonView; |
zsoltk/GameOfLife | app/src/main/java/hu/supercluster/gameoflife/game/manager/GameManager.java | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/CellularAutomaton.java
// public interface CellularAutomaton<T extends Cell> extends Parcelable, Paintable {
// int getSizeX();
// int getSizeY();
// int getDefaultCellState();
// void reset();
// void randomFill(Fill fill);
// void step();
// void step(int count);
// Grid<T> getCurrentState();
// void setState(Grid<T> grid);
// Rule<T> getRule();
// void setRule(Rule<T> rule);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/CellularAutomatonFactory.java
// public interface CellularAutomatonFactory {
// CellularAutomaton<?> create(int gridSizeX, int gridSizeY);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/app/view/AutomatonView.java
// public class AutomatonView extends SurfaceView implements SurfaceHolder.Callback {
// private CellularAutomaton automaton;
// private GameParams params;
// private AutomatonThread thread;
//
// public AutomatonView(Context context) {
// super(context);
// }
//
// public AutomatonView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public AutomatonView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// }
//
// @DebugLog
// public void init(CellularAutomaton automaton, GameParams params) {
// this.automaton = automaton;
// this.params = params;
//
// SurfaceHolder surfaceHolder = getHolder();
// surfaceHolder.addCallback(this);
// }
//
// @Override
// @DebugLog
// public void surfaceCreated(SurfaceHolder holder) {
// if (thread == null || thread.getState() == Thread.State.TERMINATED) {
// thread = new AutomatonThread(automaton, holder, params);
// thread.start();
// }
//
// thread.setRunning(true);
// }
//
// @Override
// public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// //
// }
//
// @Override
// @DebugLog
// public void surfaceDestroyed(SurfaceHolder holder) {
// thread.setRunning(false);
// waitForThreadToDie();
// }
//
// @DebugLog
// private void waitForThreadToDie() {
// while (true) {
// try {
// thread.join();
// break;
//
// } catch (InterruptedException e) {
// }
// }
// }
//
// @Override
// public boolean onTouchEvent(MotionEvent event) {
// paint(event);
//
// return true;
// }
//
// protected void paint(MotionEvent event) {
// int x = Math.round(event.getX() / params.getCellSizeInPixels());
// int y = Math.round(event.getY() / params.getCellSizeInPixels());
//
// EventBus.getInstance().post(new PaintWithBrush(x, y));
// }
// }
| import android.os.Bundle;
import hu.supercluster.gameoflife.game.cellularautomaton.CellularAutomaton;
import hu.supercluster.gameoflife.game.cellularautomaton.CellularAutomatonFactory;
import hu.supercluster.gameoflife.app.view.AutomatonView; | package hu.supercluster.gameoflife.game.manager;
public class GameManager {
public static final String KEY_AUTOMATON = "automaton";
private final AutomatonView automatonView; | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/CellularAutomaton.java
// public interface CellularAutomaton<T extends Cell> extends Parcelable, Paintable {
// int getSizeX();
// int getSizeY();
// int getDefaultCellState();
// void reset();
// void randomFill(Fill fill);
// void step();
// void step(int count);
// Grid<T> getCurrentState();
// void setState(Grid<T> grid);
// Rule<T> getRule();
// void setRule(Rule<T> rule);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/CellularAutomatonFactory.java
// public interface CellularAutomatonFactory {
// CellularAutomaton<?> create(int gridSizeX, int gridSizeY);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/app/view/AutomatonView.java
// public class AutomatonView extends SurfaceView implements SurfaceHolder.Callback {
// private CellularAutomaton automaton;
// private GameParams params;
// private AutomatonThread thread;
//
// public AutomatonView(Context context) {
// super(context);
// }
//
// public AutomatonView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public AutomatonView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// }
//
// @DebugLog
// public void init(CellularAutomaton automaton, GameParams params) {
// this.automaton = automaton;
// this.params = params;
//
// SurfaceHolder surfaceHolder = getHolder();
// surfaceHolder.addCallback(this);
// }
//
// @Override
// @DebugLog
// public void surfaceCreated(SurfaceHolder holder) {
// if (thread == null || thread.getState() == Thread.State.TERMINATED) {
// thread = new AutomatonThread(automaton, holder, params);
// thread.start();
// }
//
// thread.setRunning(true);
// }
//
// @Override
// public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// //
// }
//
// @Override
// @DebugLog
// public void surfaceDestroyed(SurfaceHolder holder) {
// thread.setRunning(false);
// waitForThreadToDie();
// }
//
// @DebugLog
// private void waitForThreadToDie() {
// while (true) {
// try {
// thread.join();
// break;
//
// } catch (InterruptedException e) {
// }
// }
// }
//
// @Override
// public boolean onTouchEvent(MotionEvent event) {
// paint(event);
//
// return true;
// }
//
// protected void paint(MotionEvent event) {
// int x = Math.round(event.getX() / params.getCellSizeInPixels());
// int y = Math.round(event.getY() / params.getCellSizeInPixels());
//
// EventBus.getInstance().post(new PaintWithBrush(x, y));
// }
// }
// Path: app/src/main/java/hu/supercluster/gameoflife/game/manager/GameManager.java
import android.os.Bundle;
import hu.supercluster.gameoflife.game.cellularautomaton.CellularAutomaton;
import hu.supercluster.gameoflife.game.cellularautomaton.CellularAutomatonFactory;
import hu.supercluster.gameoflife.app.view.AutomatonView;
package hu.supercluster.gameoflife.game.manager;
public class GameManager {
public static final String KEY_AUTOMATON = "automaton";
private final AutomatonView automatonView; | private CellularAutomaton automaton; |
zsoltk/GameOfLife | app/src/main/java/hu/supercluster/gameoflife/game/manager/GameManager.java | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/CellularAutomaton.java
// public interface CellularAutomaton<T extends Cell> extends Parcelable, Paintable {
// int getSizeX();
// int getSizeY();
// int getDefaultCellState();
// void reset();
// void randomFill(Fill fill);
// void step();
// void step(int count);
// Grid<T> getCurrentState();
// void setState(Grid<T> grid);
// Rule<T> getRule();
// void setRule(Rule<T> rule);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/CellularAutomatonFactory.java
// public interface CellularAutomatonFactory {
// CellularAutomaton<?> create(int gridSizeX, int gridSizeY);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/app/view/AutomatonView.java
// public class AutomatonView extends SurfaceView implements SurfaceHolder.Callback {
// private CellularAutomaton automaton;
// private GameParams params;
// private AutomatonThread thread;
//
// public AutomatonView(Context context) {
// super(context);
// }
//
// public AutomatonView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public AutomatonView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// }
//
// @DebugLog
// public void init(CellularAutomaton automaton, GameParams params) {
// this.automaton = automaton;
// this.params = params;
//
// SurfaceHolder surfaceHolder = getHolder();
// surfaceHolder.addCallback(this);
// }
//
// @Override
// @DebugLog
// public void surfaceCreated(SurfaceHolder holder) {
// if (thread == null || thread.getState() == Thread.State.TERMINATED) {
// thread = new AutomatonThread(automaton, holder, params);
// thread.start();
// }
//
// thread.setRunning(true);
// }
//
// @Override
// public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// //
// }
//
// @Override
// @DebugLog
// public void surfaceDestroyed(SurfaceHolder holder) {
// thread.setRunning(false);
// waitForThreadToDie();
// }
//
// @DebugLog
// private void waitForThreadToDie() {
// while (true) {
// try {
// thread.join();
// break;
//
// } catch (InterruptedException e) {
// }
// }
// }
//
// @Override
// public boolean onTouchEvent(MotionEvent event) {
// paint(event);
//
// return true;
// }
//
// protected void paint(MotionEvent event) {
// int x = Math.round(event.getX() / params.getCellSizeInPixels());
// int y = Math.round(event.getY() / params.getCellSizeInPixels());
//
// EventBus.getInstance().post(new PaintWithBrush(x, y));
// }
// }
| import android.os.Bundle;
import hu.supercluster.gameoflife.game.cellularautomaton.CellularAutomaton;
import hu.supercluster.gameoflife.game.cellularautomaton.CellularAutomatonFactory;
import hu.supercluster.gameoflife.app.view.AutomatonView; | package hu.supercluster.gameoflife.game.manager;
public class GameManager {
public static final String KEY_AUTOMATON = "automaton";
private final AutomatonView automatonView;
private CellularAutomaton automaton;
private GameParams params;
| // Path: app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/CellularAutomaton.java
// public interface CellularAutomaton<T extends Cell> extends Parcelable, Paintable {
// int getSizeX();
// int getSizeY();
// int getDefaultCellState();
// void reset();
// void randomFill(Fill fill);
// void step();
// void step(int count);
// Grid<T> getCurrentState();
// void setState(Grid<T> grid);
// Rule<T> getRule();
// void setRule(Rule<T> rule);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/CellularAutomatonFactory.java
// public interface CellularAutomatonFactory {
// CellularAutomaton<?> create(int gridSizeX, int gridSizeY);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/app/view/AutomatonView.java
// public class AutomatonView extends SurfaceView implements SurfaceHolder.Callback {
// private CellularAutomaton automaton;
// private GameParams params;
// private AutomatonThread thread;
//
// public AutomatonView(Context context) {
// super(context);
// }
//
// public AutomatonView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public AutomatonView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// }
//
// @DebugLog
// public void init(CellularAutomaton automaton, GameParams params) {
// this.automaton = automaton;
// this.params = params;
//
// SurfaceHolder surfaceHolder = getHolder();
// surfaceHolder.addCallback(this);
// }
//
// @Override
// @DebugLog
// public void surfaceCreated(SurfaceHolder holder) {
// if (thread == null || thread.getState() == Thread.State.TERMINATED) {
// thread = new AutomatonThread(automaton, holder, params);
// thread.start();
// }
//
// thread.setRunning(true);
// }
//
// @Override
// public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// //
// }
//
// @Override
// @DebugLog
// public void surfaceDestroyed(SurfaceHolder holder) {
// thread.setRunning(false);
// waitForThreadToDie();
// }
//
// @DebugLog
// private void waitForThreadToDie() {
// while (true) {
// try {
// thread.join();
// break;
//
// } catch (InterruptedException e) {
// }
// }
// }
//
// @Override
// public boolean onTouchEvent(MotionEvent event) {
// paint(event);
//
// return true;
// }
//
// protected void paint(MotionEvent event) {
// int x = Math.round(event.getX() / params.getCellSizeInPixels());
// int y = Math.round(event.getY() / params.getCellSizeInPixels());
//
// EventBus.getInstance().post(new PaintWithBrush(x, y));
// }
// }
// Path: app/src/main/java/hu/supercluster/gameoflife/game/manager/GameManager.java
import android.os.Bundle;
import hu.supercluster.gameoflife.game.cellularautomaton.CellularAutomaton;
import hu.supercluster.gameoflife.game.cellularautomaton.CellularAutomatonFactory;
import hu.supercluster.gameoflife.app.view.AutomatonView;
package hu.supercluster.gameoflife.game.manager;
public class GameManager {
public static final String KEY_AUTOMATON = "automaton";
private final AutomatonView automatonView;
private CellularAutomaton automaton;
private GameParams params;
| public GameManager(Bundle savedGameState, AutomatonView automatonView, CellularAutomatonFactory factory, GameParams params) { |
zsoltk/GameOfLife | app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/GameOfLife.java | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/CellFactory.java
// public interface CellFactory<T extends Cell> extends Serializable {
// T create(int x, int y);
// int[] flatten(T cell);
// T inflate(int[] flattened);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/SimpleCell.java
// public class SimpleCell implements Cell {
// static final AtomicLong NEXT_ID = new AtomicLong(0);
// final long id = NEXT_ID.getAndIncrement();
// final int x;
// final int y;
// int state;
// int neighborCount;
// Overseer overseer;
//
// public SimpleCell(int x, int y, int state) {
// this.x = x;
// this.y = y;
// this.state = state;
// }
//
// @Override
// public void setOverseer(Overseer overseer) {
// this.overseer = overseer;
// }
//
// @Override
// public void reset(int state) {
// this.state = state;
// neighborCount = 0;
// }
//
// @Override
// public long getId() {
// return id;
// }
//
// @Override
// public int getX() {
// return x;
// }
//
// @Override
// public int getY() {
// return y;
// }
//
// @Override
// public int getState() {
// return state;
// }
//
// @Override
// public void setState(int newState) {
// int oldState = this.state;
// this.state = newState;
//
// if (newState != oldState && overseer != null) {
// overseer.onCellStateChanged(new CellStateChange(this));
// }
// }
//
// @Override
// public boolean isAlive() {
// return !isDead();
// }
//
// @Override
// public boolean isDead() {
// return state == STATE_DEAD;
// }
//
// @Override
// public void onNeighborStateChange(int newState) {
// if (newState == STATE_DEAD) {
// decreaseNeighborCount();
//
// } else {
// increaseNeighborCount();
// }
// }
//
// void increaseNeighborCount() {
// neighborCount++;
// }
//
// void decreaseNeighborCount() {
// neighborCount--;
// }
//
// public int getNeighborCount() {
// return neighborCount;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// SimpleCell that = (SimpleCell) o;
//
// if (neighborCount != that.neighborCount) return false;
// if (state != that.state) return false;
// if (x != that.x) return false;
// if (y != that.y) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = x;
// result = 31 * result + y;
// result = 31 * result + state;
// result = 31 * result + neighborCount;
// return result;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/SimpleCellFactory.java
// public class SimpleCellFactory implements CellFactory<SimpleCell> {
// @Override
// public SimpleCell create(int x, int y) {
// return new SimpleCell(x, y, SimpleCell.STATE_DEAD);
// }
//
// @Override
// public int[] flatten(SimpleCell cell) {
// final int[] flattened = new int[4];
// flattened[0] = cell.x;
// flattened[1] = cell.y;
// flattened[2] = cell.state;
// flattened[3] = cell.neighborCount;
//
// return flattened;
// }
//
// @Override
// public SimpleCell inflate(int[] flattened) {
// final SimpleCell cell = new SimpleCell(
// flattened[0],
// flattened[1],
// flattened[2]
// );
//
// cell.neighborCount = flattened[3];
//
// return cell;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/rule/ConwaysRule.java
// public class ConwaysRule extends NeighborCountBasedRule {
// public ConwaysRule() {
// super("23/3");
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/rule/Rule.java
// public interface Rule<T extends Cell> extends Serializable {
// int apply(Grid<T> grid, int x, int y);
// }
| import android.os.Parcel;
import hu.supercluster.gameoflife.game.cell.CellFactory;
import hu.supercluster.gameoflife.game.cell.SimpleCell;
import hu.supercluster.gameoflife.game.cell.SimpleCellFactory;
import hu.supercluster.gameoflife.game.rule.ConwaysRule;
import hu.supercluster.gameoflife.game.rule.Rule; | package hu.supercluster.gameoflife.game.cellularautomaton;
public class GameOfLife extends AbstractCellularAutomaton<SimpleCell> {
public GameOfLife(int gridSizeX, int gridSizeY) {
super(gridSizeX, gridSizeY);
}
public GameOfLife(Parcel source) {
super(source);
}
@Override | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/CellFactory.java
// public interface CellFactory<T extends Cell> extends Serializable {
// T create(int x, int y);
// int[] flatten(T cell);
// T inflate(int[] flattened);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/SimpleCell.java
// public class SimpleCell implements Cell {
// static final AtomicLong NEXT_ID = new AtomicLong(0);
// final long id = NEXT_ID.getAndIncrement();
// final int x;
// final int y;
// int state;
// int neighborCount;
// Overseer overseer;
//
// public SimpleCell(int x, int y, int state) {
// this.x = x;
// this.y = y;
// this.state = state;
// }
//
// @Override
// public void setOverseer(Overseer overseer) {
// this.overseer = overseer;
// }
//
// @Override
// public void reset(int state) {
// this.state = state;
// neighborCount = 0;
// }
//
// @Override
// public long getId() {
// return id;
// }
//
// @Override
// public int getX() {
// return x;
// }
//
// @Override
// public int getY() {
// return y;
// }
//
// @Override
// public int getState() {
// return state;
// }
//
// @Override
// public void setState(int newState) {
// int oldState = this.state;
// this.state = newState;
//
// if (newState != oldState && overseer != null) {
// overseer.onCellStateChanged(new CellStateChange(this));
// }
// }
//
// @Override
// public boolean isAlive() {
// return !isDead();
// }
//
// @Override
// public boolean isDead() {
// return state == STATE_DEAD;
// }
//
// @Override
// public void onNeighborStateChange(int newState) {
// if (newState == STATE_DEAD) {
// decreaseNeighborCount();
//
// } else {
// increaseNeighborCount();
// }
// }
//
// void increaseNeighborCount() {
// neighborCount++;
// }
//
// void decreaseNeighborCount() {
// neighborCount--;
// }
//
// public int getNeighborCount() {
// return neighborCount;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// SimpleCell that = (SimpleCell) o;
//
// if (neighborCount != that.neighborCount) return false;
// if (state != that.state) return false;
// if (x != that.x) return false;
// if (y != that.y) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = x;
// result = 31 * result + y;
// result = 31 * result + state;
// result = 31 * result + neighborCount;
// return result;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/SimpleCellFactory.java
// public class SimpleCellFactory implements CellFactory<SimpleCell> {
// @Override
// public SimpleCell create(int x, int y) {
// return new SimpleCell(x, y, SimpleCell.STATE_DEAD);
// }
//
// @Override
// public int[] flatten(SimpleCell cell) {
// final int[] flattened = new int[4];
// flattened[0] = cell.x;
// flattened[1] = cell.y;
// flattened[2] = cell.state;
// flattened[3] = cell.neighborCount;
//
// return flattened;
// }
//
// @Override
// public SimpleCell inflate(int[] flattened) {
// final SimpleCell cell = new SimpleCell(
// flattened[0],
// flattened[1],
// flattened[2]
// );
//
// cell.neighborCount = flattened[3];
//
// return cell;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/rule/ConwaysRule.java
// public class ConwaysRule extends NeighborCountBasedRule {
// public ConwaysRule() {
// super("23/3");
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/rule/Rule.java
// public interface Rule<T extends Cell> extends Serializable {
// int apply(Grid<T> grid, int x, int y);
// }
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/GameOfLife.java
import android.os.Parcel;
import hu.supercluster.gameoflife.game.cell.CellFactory;
import hu.supercluster.gameoflife.game.cell.SimpleCell;
import hu.supercluster.gameoflife.game.cell.SimpleCellFactory;
import hu.supercluster.gameoflife.game.rule.ConwaysRule;
import hu.supercluster.gameoflife.game.rule.Rule;
package hu.supercluster.gameoflife.game.cellularautomaton;
public class GameOfLife extends AbstractCellularAutomaton<SimpleCell> {
public GameOfLife(int gridSizeX, int gridSizeY) {
super(gridSizeX, gridSizeY);
}
public GameOfLife(Parcel source) {
super(source);
}
@Override | protected CellFactory<SimpleCell> getFactory() { |
zsoltk/GameOfLife | app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/GameOfLife.java | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/CellFactory.java
// public interface CellFactory<T extends Cell> extends Serializable {
// T create(int x, int y);
// int[] flatten(T cell);
// T inflate(int[] flattened);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/SimpleCell.java
// public class SimpleCell implements Cell {
// static final AtomicLong NEXT_ID = new AtomicLong(0);
// final long id = NEXT_ID.getAndIncrement();
// final int x;
// final int y;
// int state;
// int neighborCount;
// Overseer overseer;
//
// public SimpleCell(int x, int y, int state) {
// this.x = x;
// this.y = y;
// this.state = state;
// }
//
// @Override
// public void setOverseer(Overseer overseer) {
// this.overseer = overseer;
// }
//
// @Override
// public void reset(int state) {
// this.state = state;
// neighborCount = 0;
// }
//
// @Override
// public long getId() {
// return id;
// }
//
// @Override
// public int getX() {
// return x;
// }
//
// @Override
// public int getY() {
// return y;
// }
//
// @Override
// public int getState() {
// return state;
// }
//
// @Override
// public void setState(int newState) {
// int oldState = this.state;
// this.state = newState;
//
// if (newState != oldState && overseer != null) {
// overseer.onCellStateChanged(new CellStateChange(this));
// }
// }
//
// @Override
// public boolean isAlive() {
// return !isDead();
// }
//
// @Override
// public boolean isDead() {
// return state == STATE_DEAD;
// }
//
// @Override
// public void onNeighborStateChange(int newState) {
// if (newState == STATE_DEAD) {
// decreaseNeighborCount();
//
// } else {
// increaseNeighborCount();
// }
// }
//
// void increaseNeighborCount() {
// neighborCount++;
// }
//
// void decreaseNeighborCount() {
// neighborCount--;
// }
//
// public int getNeighborCount() {
// return neighborCount;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// SimpleCell that = (SimpleCell) o;
//
// if (neighborCount != that.neighborCount) return false;
// if (state != that.state) return false;
// if (x != that.x) return false;
// if (y != that.y) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = x;
// result = 31 * result + y;
// result = 31 * result + state;
// result = 31 * result + neighborCount;
// return result;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/SimpleCellFactory.java
// public class SimpleCellFactory implements CellFactory<SimpleCell> {
// @Override
// public SimpleCell create(int x, int y) {
// return new SimpleCell(x, y, SimpleCell.STATE_DEAD);
// }
//
// @Override
// public int[] flatten(SimpleCell cell) {
// final int[] flattened = new int[4];
// flattened[0] = cell.x;
// flattened[1] = cell.y;
// flattened[2] = cell.state;
// flattened[3] = cell.neighborCount;
//
// return flattened;
// }
//
// @Override
// public SimpleCell inflate(int[] flattened) {
// final SimpleCell cell = new SimpleCell(
// flattened[0],
// flattened[1],
// flattened[2]
// );
//
// cell.neighborCount = flattened[3];
//
// return cell;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/rule/ConwaysRule.java
// public class ConwaysRule extends NeighborCountBasedRule {
// public ConwaysRule() {
// super("23/3");
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/rule/Rule.java
// public interface Rule<T extends Cell> extends Serializable {
// int apply(Grid<T> grid, int x, int y);
// }
| import android.os.Parcel;
import hu.supercluster.gameoflife.game.cell.CellFactory;
import hu.supercluster.gameoflife.game.cell.SimpleCell;
import hu.supercluster.gameoflife.game.cell.SimpleCellFactory;
import hu.supercluster.gameoflife.game.rule.ConwaysRule;
import hu.supercluster.gameoflife.game.rule.Rule; | package hu.supercluster.gameoflife.game.cellularautomaton;
public class GameOfLife extends AbstractCellularAutomaton<SimpleCell> {
public GameOfLife(int gridSizeX, int gridSizeY) {
super(gridSizeX, gridSizeY);
}
public GameOfLife(Parcel source) {
super(source);
}
@Override
protected CellFactory<SimpleCell> getFactory() { | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/CellFactory.java
// public interface CellFactory<T extends Cell> extends Serializable {
// T create(int x, int y);
// int[] flatten(T cell);
// T inflate(int[] flattened);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/SimpleCell.java
// public class SimpleCell implements Cell {
// static final AtomicLong NEXT_ID = new AtomicLong(0);
// final long id = NEXT_ID.getAndIncrement();
// final int x;
// final int y;
// int state;
// int neighborCount;
// Overseer overseer;
//
// public SimpleCell(int x, int y, int state) {
// this.x = x;
// this.y = y;
// this.state = state;
// }
//
// @Override
// public void setOverseer(Overseer overseer) {
// this.overseer = overseer;
// }
//
// @Override
// public void reset(int state) {
// this.state = state;
// neighborCount = 0;
// }
//
// @Override
// public long getId() {
// return id;
// }
//
// @Override
// public int getX() {
// return x;
// }
//
// @Override
// public int getY() {
// return y;
// }
//
// @Override
// public int getState() {
// return state;
// }
//
// @Override
// public void setState(int newState) {
// int oldState = this.state;
// this.state = newState;
//
// if (newState != oldState && overseer != null) {
// overseer.onCellStateChanged(new CellStateChange(this));
// }
// }
//
// @Override
// public boolean isAlive() {
// return !isDead();
// }
//
// @Override
// public boolean isDead() {
// return state == STATE_DEAD;
// }
//
// @Override
// public void onNeighborStateChange(int newState) {
// if (newState == STATE_DEAD) {
// decreaseNeighborCount();
//
// } else {
// increaseNeighborCount();
// }
// }
//
// void increaseNeighborCount() {
// neighborCount++;
// }
//
// void decreaseNeighborCount() {
// neighborCount--;
// }
//
// public int getNeighborCount() {
// return neighborCount;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// SimpleCell that = (SimpleCell) o;
//
// if (neighborCount != that.neighborCount) return false;
// if (state != that.state) return false;
// if (x != that.x) return false;
// if (y != that.y) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = x;
// result = 31 * result + y;
// result = 31 * result + state;
// result = 31 * result + neighborCount;
// return result;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/SimpleCellFactory.java
// public class SimpleCellFactory implements CellFactory<SimpleCell> {
// @Override
// public SimpleCell create(int x, int y) {
// return new SimpleCell(x, y, SimpleCell.STATE_DEAD);
// }
//
// @Override
// public int[] flatten(SimpleCell cell) {
// final int[] flattened = new int[4];
// flattened[0] = cell.x;
// flattened[1] = cell.y;
// flattened[2] = cell.state;
// flattened[3] = cell.neighborCount;
//
// return flattened;
// }
//
// @Override
// public SimpleCell inflate(int[] flattened) {
// final SimpleCell cell = new SimpleCell(
// flattened[0],
// flattened[1],
// flattened[2]
// );
//
// cell.neighborCount = flattened[3];
//
// return cell;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/rule/ConwaysRule.java
// public class ConwaysRule extends NeighborCountBasedRule {
// public ConwaysRule() {
// super("23/3");
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/rule/Rule.java
// public interface Rule<T extends Cell> extends Serializable {
// int apply(Grid<T> grid, int x, int y);
// }
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/GameOfLife.java
import android.os.Parcel;
import hu.supercluster.gameoflife.game.cell.CellFactory;
import hu.supercluster.gameoflife.game.cell.SimpleCell;
import hu.supercluster.gameoflife.game.cell.SimpleCellFactory;
import hu.supercluster.gameoflife.game.rule.ConwaysRule;
import hu.supercluster.gameoflife.game.rule.Rule;
package hu.supercluster.gameoflife.game.cellularautomaton;
public class GameOfLife extends AbstractCellularAutomaton<SimpleCell> {
public GameOfLife(int gridSizeX, int gridSizeY) {
super(gridSizeX, gridSizeY);
}
public GameOfLife(Parcel source) {
super(source);
}
@Override
protected CellFactory<SimpleCell> getFactory() { | return new SimpleCellFactory(); |
zsoltk/GameOfLife | app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/GameOfLife.java | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/CellFactory.java
// public interface CellFactory<T extends Cell> extends Serializable {
// T create(int x, int y);
// int[] flatten(T cell);
// T inflate(int[] flattened);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/SimpleCell.java
// public class SimpleCell implements Cell {
// static final AtomicLong NEXT_ID = new AtomicLong(0);
// final long id = NEXT_ID.getAndIncrement();
// final int x;
// final int y;
// int state;
// int neighborCount;
// Overseer overseer;
//
// public SimpleCell(int x, int y, int state) {
// this.x = x;
// this.y = y;
// this.state = state;
// }
//
// @Override
// public void setOverseer(Overseer overseer) {
// this.overseer = overseer;
// }
//
// @Override
// public void reset(int state) {
// this.state = state;
// neighborCount = 0;
// }
//
// @Override
// public long getId() {
// return id;
// }
//
// @Override
// public int getX() {
// return x;
// }
//
// @Override
// public int getY() {
// return y;
// }
//
// @Override
// public int getState() {
// return state;
// }
//
// @Override
// public void setState(int newState) {
// int oldState = this.state;
// this.state = newState;
//
// if (newState != oldState && overseer != null) {
// overseer.onCellStateChanged(new CellStateChange(this));
// }
// }
//
// @Override
// public boolean isAlive() {
// return !isDead();
// }
//
// @Override
// public boolean isDead() {
// return state == STATE_DEAD;
// }
//
// @Override
// public void onNeighborStateChange(int newState) {
// if (newState == STATE_DEAD) {
// decreaseNeighborCount();
//
// } else {
// increaseNeighborCount();
// }
// }
//
// void increaseNeighborCount() {
// neighborCount++;
// }
//
// void decreaseNeighborCount() {
// neighborCount--;
// }
//
// public int getNeighborCount() {
// return neighborCount;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// SimpleCell that = (SimpleCell) o;
//
// if (neighborCount != that.neighborCount) return false;
// if (state != that.state) return false;
// if (x != that.x) return false;
// if (y != that.y) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = x;
// result = 31 * result + y;
// result = 31 * result + state;
// result = 31 * result + neighborCount;
// return result;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/SimpleCellFactory.java
// public class SimpleCellFactory implements CellFactory<SimpleCell> {
// @Override
// public SimpleCell create(int x, int y) {
// return new SimpleCell(x, y, SimpleCell.STATE_DEAD);
// }
//
// @Override
// public int[] flatten(SimpleCell cell) {
// final int[] flattened = new int[4];
// flattened[0] = cell.x;
// flattened[1] = cell.y;
// flattened[2] = cell.state;
// flattened[3] = cell.neighborCount;
//
// return flattened;
// }
//
// @Override
// public SimpleCell inflate(int[] flattened) {
// final SimpleCell cell = new SimpleCell(
// flattened[0],
// flattened[1],
// flattened[2]
// );
//
// cell.neighborCount = flattened[3];
//
// return cell;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/rule/ConwaysRule.java
// public class ConwaysRule extends NeighborCountBasedRule {
// public ConwaysRule() {
// super("23/3");
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/rule/Rule.java
// public interface Rule<T extends Cell> extends Serializable {
// int apply(Grid<T> grid, int x, int y);
// }
| import android.os.Parcel;
import hu.supercluster.gameoflife.game.cell.CellFactory;
import hu.supercluster.gameoflife.game.cell.SimpleCell;
import hu.supercluster.gameoflife.game.cell.SimpleCellFactory;
import hu.supercluster.gameoflife.game.rule.ConwaysRule;
import hu.supercluster.gameoflife.game.rule.Rule; | package hu.supercluster.gameoflife.game.cellularautomaton;
public class GameOfLife extends AbstractCellularAutomaton<SimpleCell> {
public GameOfLife(int gridSizeX, int gridSizeY) {
super(gridSizeX, gridSizeY);
}
public GameOfLife(Parcel source) {
super(source);
}
@Override
protected CellFactory<SimpleCell> getFactory() {
return new SimpleCellFactory();
}
@Override | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/CellFactory.java
// public interface CellFactory<T extends Cell> extends Serializable {
// T create(int x, int y);
// int[] flatten(T cell);
// T inflate(int[] flattened);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/SimpleCell.java
// public class SimpleCell implements Cell {
// static final AtomicLong NEXT_ID = new AtomicLong(0);
// final long id = NEXT_ID.getAndIncrement();
// final int x;
// final int y;
// int state;
// int neighborCount;
// Overseer overseer;
//
// public SimpleCell(int x, int y, int state) {
// this.x = x;
// this.y = y;
// this.state = state;
// }
//
// @Override
// public void setOverseer(Overseer overseer) {
// this.overseer = overseer;
// }
//
// @Override
// public void reset(int state) {
// this.state = state;
// neighborCount = 0;
// }
//
// @Override
// public long getId() {
// return id;
// }
//
// @Override
// public int getX() {
// return x;
// }
//
// @Override
// public int getY() {
// return y;
// }
//
// @Override
// public int getState() {
// return state;
// }
//
// @Override
// public void setState(int newState) {
// int oldState = this.state;
// this.state = newState;
//
// if (newState != oldState && overseer != null) {
// overseer.onCellStateChanged(new CellStateChange(this));
// }
// }
//
// @Override
// public boolean isAlive() {
// return !isDead();
// }
//
// @Override
// public boolean isDead() {
// return state == STATE_DEAD;
// }
//
// @Override
// public void onNeighborStateChange(int newState) {
// if (newState == STATE_DEAD) {
// decreaseNeighborCount();
//
// } else {
// increaseNeighborCount();
// }
// }
//
// void increaseNeighborCount() {
// neighborCount++;
// }
//
// void decreaseNeighborCount() {
// neighborCount--;
// }
//
// public int getNeighborCount() {
// return neighborCount;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// SimpleCell that = (SimpleCell) o;
//
// if (neighborCount != that.neighborCount) return false;
// if (state != that.state) return false;
// if (x != that.x) return false;
// if (y != that.y) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = x;
// result = 31 * result + y;
// result = 31 * result + state;
// result = 31 * result + neighborCount;
// return result;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/SimpleCellFactory.java
// public class SimpleCellFactory implements CellFactory<SimpleCell> {
// @Override
// public SimpleCell create(int x, int y) {
// return new SimpleCell(x, y, SimpleCell.STATE_DEAD);
// }
//
// @Override
// public int[] flatten(SimpleCell cell) {
// final int[] flattened = new int[4];
// flattened[0] = cell.x;
// flattened[1] = cell.y;
// flattened[2] = cell.state;
// flattened[3] = cell.neighborCount;
//
// return flattened;
// }
//
// @Override
// public SimpleCell inflate(int[] flattened) {
// final SimpleCell cell = new SimpleCell(
// flattened[0],
// flattened[1],
// flattened[2]
// );
//
// cell.neighborCount = flattened[3];
//
// return cell;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/rule/ConwaysRule.java
// public class ConwaysRule extends NeighborCountBasedRule {
// public ConwaysRule() {
// super("23/3");
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/rule/Rule.java
// public interface Rule<T extends Cell> extends Serializable {
// int apply(Grid<T> grid, int x, int y);
// }
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/GameOfLife.java
import android.os.Parcel;
import hu.supercluster.gameoflife.game.cell.CellFactory;
import hu.supercluster.gameoflife.game.cell.SimpleCell;
import hu.supercluster.gameoflife.game.cell.SimpleCellFactory;
import hu.supercluster.gameoflife.game.rule.ConwaysRule;
import hu.supercluster.gameoflife.game.rule.Rule;
package hu.supercluster.gameoflife.game.cellularautomaton;
public class GameOfLife extends AbstractCellularAutomaton<SimpleCell> {
public GameOfLife(int gridSizeX, int gridSizeY) {
super(gridSizeX, gridSizeY);
}
public GameOfLife(Parcel source) {
super(source);
}
@Override
protected CellFactory<SimpleCell> getFactory() {
return new SimpleCellFactory();
}
@Override | public Rule<SimpleCell> createRule() { |
zsoltk/GameOfLife | app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/GameOfLife.java | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/CellFactory.java
// public interface CellFactory<T extends Cell> extends Serializable {
// T create(int x, int y);
// int[] flatten(T cell);
// T inflate(int[] flattened);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/SimpleCell.java
// public class SimpleCell implements Cell {
// static final AtomicLong NEXT_ID = new AtomicLong(0);
// final long id = NEXT_ID.getAndIncrement();
// final int x;
// final int y;
// int state;
// int neighborCount;
// Overseer overseer;
//
// public SimpleCell(int x, int y, int state) {
// this.x = x;
// this.y = y;
// this.state = state;
// }
//
// @Override
// public void setOverseer(Overseer overseer) {
// this.overseer = overseer;
// }
//
// @Override
// public void reset(int state) {
// this.state = state;
// neighborCount = 0;
// }
//
// @Override
// public long getId() {
// return id;
// }
//
// @Override
// public int getX() {
// return x;
// }
//
// @Override
// public int getY() {
// return y;
// }
//
// @Override
// public int getState() {
// return state;
// }
//
// @Override
// public void setState(int newState) {
// int oldState = this.state;
// this.state = newState;
//
// if (newState != oldState && overseer != null) {
// overseer.onCellStateChanged(new CellStateChange(this));
// }
// }
//
// @Override
// public boolean isAlive() {
// return !isDead();
// }
//
// @Override
// public boolean isDead() {
// return state == STATE_DEAD;
// }
//
// @Override
// public void onNeighborStateChange(int newState) {
// if (newState == STATE_DEAD) {
// decreaseNeighborCount();
//
// } else {
// increaseNeighborCount();
// }
// }
//
// void increaseNeighborCount() {
// neighborCount++;
// }
//
// void decreaseNeighborCount() {
// neighborCount--;
// }
//
// public int getNeighborCount() {
// return neighborCount;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// SimpleCell that = (SimpleCell) o;
//
// if (neighborCount != that.neighborCount) return false;
// if (state != that.state) return false;
// if (x != that.x) return false;
// if (y != that.y) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = x;
// result = 31 * result + y;
// result = 31 * result + state;
// result = 31 * result + neighborCount;
// return result;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/SimpleCellFactory.java
// public class SimpleCellFactory implements CellFactory<SimpleCell> {
// @Override
// public SimpleCell create(int x, int y) {
// return new SimpleCell(x, y, SimpleCell.STATE_DEAD);
// }
//
// @Override
// public int[] flatten(SimpleCell cell) {
// final int[] flattened = new int[4];
// flattened[0] = cell.x;
// flattened[1] = cell.y;
// flattened[2] = cell.state;
// flattened[3] = cell.neighborCount;
//
// return flattened;
// }
//
// @Override
// public SimpleCell inflate(int[] flattened) {
// final SimpleCell cell = new SimpleCell(
// flattened[0],
// flattened[1],
// flattened[2]
// );
//
// cell.neighborCount = flattened[3];
//
// return cell;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/rule/ConwaysRule.java
// public class ConwaysRule extends NeighborCountBasedRule {
// public ConwaysRule() {
// super("23/3");
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/rule/Rule.java
// public interface Rule<T extends Cell> extends Serializable {
// int apply(Grid<T> grid, int x, int y);
// }
| import android.os.Parcel;
import hu.supercluster.gameoflife.game.cell.CellFactory;
import hu.supercluster.gameoflife.game.cell.SimpleCell;
import hu.supercluster.gameoflife.game.cell.SimpleCellFactory;
import hu.supercluster.gameoflife.game.rule.ConwaysRule;
import hu.supercluster.gameoflife.game.rule.Rule; | package hu.supercluster.gameoflife.game.cellularautomaton;
public class GameOfLife extends AbstractCellularAutomaton<SimpleCell> {
public GameOfLife(int gridSizeX, int gridSizeY) {
super(gridSizeX, gridSizeY);
}
public GameOfLife(Parcel source) {
super(source);
}
@Override
protected CellFactory<SimpleCell> getFactory() {
return new SimpleCellFactory();
}
@Override
public Rule<SimpleCell> createRule() { | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/CellFactory.java
// public interface CellFactory<T extends Cell> extends Serializable {
// T create(int x, int y);
// int[] flatten(T cell);
// T inflate(int[] flattened);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/SimpleCell.java
// public class SimpleCell implements Cell {
// static final AtomicLong NEXT_ID = new AtomicLong(0);
// final long id = NEXT_ID.getAndIncrement();
// final int x;
// final int y;
// int state;
// int neighborCount;
// Overseer overseer;
//
// public SimpleCell(int x, int y, int state) {
// this.x = x;
// this.y = y;
// this.state = state;
// }
//
// @Override
// public void setOverseer(Overseer overseer) {
// this.overseer = overseer;
// }
//
// @Override
// public void reset(int state) {
// this.state = state;
// neighborCount = 0;
// }
//
// @Override
// public long getId() {
// return id;
// }
//
// @Override
// public int getX() {
// return x;
// }
//
// @Override
// public int getY() {
// return y;
// }
//
// @Override
// public int getState() {
// return state;
// }
//
// @Override
// public void setState(int newState) {
// int oldState = this.state;
// this.state = newState;
//
// if (newState != oldState && overseer != null) {
// overseer.onCellStateChanged(new CellStateChange(this));
// }
// }
//
// @Override
// public boolean isAlive() {
// return !isDead();
// }
//
// @Override
// public boolean isDead() {
// return state == STATE_DEAD;
// }
//
// @Override
// public void onNeighborStateChange(int newState) {
// if (newState == STATE_DEAD) {
// decreaseNeighborCount();
//
// } else {
// increaseNeighborCount();
// }
// }
//
// void increaseNeighborCount() {
// neighborCount++;
// }
//
// void decreaseNeighborCount() {
// neighborCount--;
// }
//
// public int getNeighborCount() {
// return neighborCount;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// SimpleCell that = (SimpleCell) o;
//
// if (neighborCount != that.neighborCount) return false;
// if (state != that.state) return false;
// if (x != that.x) return false;
// if (y != that.y) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = x;
// result = 31 * result + y;
// result = 31 * result + state;
// result = 31 * result + neighborCount;
// return result;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/SimpleCellFactory.java
// public class SimpleCellFactory implements CellFactory<SimpleCell> {
// @Override
// public SimpleCell create(int x, int y) {
// return new SimpleCell(x, y, SimpleCell.STATE_DEAD);
// }
//
// @Override
// public int[] flatten(SimpleCell cell) {
// final int[] flattened = new int[4];
// flattened[0] = cell.x;
// flattened[1] = cell.y;
// flattened[2] = cell.state;
// flattened[3] = cell.neighborCount;
//
// return flattened;
// }
//
// @Override
// public SimpleCell inflate(int[] flattened) {
// final SimpleCell cell = new SimpleCell(
// flattened[0],
// flattened[1],
// flattened[2]
// );
//
// cell.neighborCount = flattened[3];
//
// return cell;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/rule/ConwaysRule.java
// public class ConwaysRule extends NeighborCountBasedRule {
// public ConwaysRule() {
// super("23/3");
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/rule/Rule.java
// public interface Rule<T extends Cell> extends Serializable {
// int apply(Grid<T> grid, int x, int y);
// }
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/GameOfLife.java
import android.os.Parcel;
import hu.supercluster.gameoflife.game.cell.CellFactory;
import hu.supercluster.gameoflife.game.cell.SimpleCell;
import hu.supercluster.gameoflife.game.cell.SimpleCellFactory;
import hu.supercluster.gameoflife.game.rule.ConwaysRule;
import hu.supercluster.gameoflife.game.rule.Rule;
package hu.supercluster.gameoflife.game.cellularautomaton;
public class GameOfLife extends AbstractCellularAutomaton<SimpleCell> {
public GameOfLife(int gridSizeX, int gridSizeY) {
super(gridSizeX, gridSizeY);
}
public GameOfLife(Parcel source) {
super(source);
}
@Override
protected CellFactory<SimpleCell> getFactory() {
return new SimpleCellFactory();
}
@Override
public Rule<SimpleCell> createRule() { | return new ConwaysRule(); |
zsoltk/GameOfLife | app/src/main/java/hu/supercluster/gameoflife/game/visualization/cell/SimpleCellColors.java | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
| import hu.supercluster.gameoflife.game.cell.Cell; | package hu.supercluster.gameoflife.game.visualization.cell;
public class SimpleCellColors extends AbstractCellColors {
public SimpleCellColors() {
super(); | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
// Path: app/src/main/java/hu/supercluster/gameoflife/game/visualization/cell/SimpleCellColors.java
import hu.supercluster.gameoflife.game.cell.Cell;
package hu.supercluster.gameoflife.game.visualization.cell;
public class SimpleCellColors extends AbstractCellColors {
public SimpleCellColors() {
super(); | paintMap.put(Cell.STATE_DEAD, createPaint("#000000")); |
zsoltk/GameOfLife | app/src/main/java/hu/supercluster/gameoflife/game/rule/NeighborCountBasedRule.java | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/SimpleCell.java
// public class SimpleCell implements Cell {
// static final AtomicLong NEXT_ID = new AtomicLong(0);
// final long id = NEXT_ID.getAndIncrement();
// final int x;
// final int y;
// int state;
// int neighborCount;
// Overseer overseer;
//
// public SimpleCell(int x, int y, int state) {
// this.x = x;
// this.y = y;
// this.state = state;
// }
//
// @Override
// public void setOverseer(Overseer overseer) {
// this.overseer = overseer;
// }
//
// @Override
// public void reset(int state) {
// this.state = state;
// neighborCount = 0;
// }
//
// @Override
// public long getId() {
// return id;
// }
//
// @Override
// public int getX() {
// return x;
// }
//
// @Override
// public int getY() {
// return y;
// }
//
// @Override
// public int getState() {
// return state;
// }
//
// @Override
// public void setState(int newState) {
// int oldState = this.state;
// this.state = newState;
//
// if (newState != oldState && overseer != null) {
// overseer.onCellStateChanged(new CellStateChange(this));
// }
// }
//
// @Override
// public boolean isAlive() {
// return !isDead();
// }
//
// @Override
// public boolean isDead() {
// return state == STATE_DEAD;
// }
//
// @Override
// public void onNeighborStateChange(int newState) {
// if (newState == STATE_DEAD) {
// decreaseNeighborCount();
//
// } else {
// increaseNeighborCount();
// }
// }
//
// void increaseNeighborCount() {
// neighborCount++;
// }
//
// void decreaseNeighborCount() {
// neighborCount--;
// }
//
// public int getNeighborCount() {
// return neighborCount;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// SimpleCell that = (SimpleCell) o;
//
// if (neighborCount != that.neighborCount) return false;
// if (state != that.state) return false;
// if (x != that.x) return false;
// if (y != that.y) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = x;
// result = 31 * result + y;
// result = 31 * result + state;
// result = 31 * result + neighborCount;
// return result;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/grid/Grid.java
// public interface Grid<T extends Cell> extends Parcelable {
// int getSizeX();
// int getSizeY();
// T getCell(int x, int y);
// void putCell(T cell);
// }
| import java.util.HashSet;
import java.util.Set;
import hu.supercluster.gameoflife.game.cell.Cell;
import hu.supercluster.gameoflife.game.cell.SimpleCell;
import hu.supercluster.gameoflife.game.grid.Grid; | public NeighborCountBasedRule(String rule) {
String[] split = rule.split("/");
if (split.length != 2) {
throw new IllegalArgumentException("Invalid rule string: " + rule);
}
try {
survivalNbCounts = new HashSet<>();
String survival = split[0];
for (int i = 0; i < survival.length(); i++) {
survivalNbCounts.add(Integer.valueOf(String.valueOf(survival.charAt(i))));
}
creationNbCounts = new HashSet<>();
String creation = split[1];
for (int i = 0; i < creation.length(); i++) {
creationNbCounts.add(Integer.valueOf(String.valueOf(creation.charAt(i))));
}
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid rule string: " + rule);
}
}
public NeighborCountBasedRule(NeighborCountBasedRule other) {
this.survivalNbCounts = new HashSet<>(other.survivalNbCounts);
this.creationNbCounts = new HashSet<>(other.creationNbCounts);
}
@Override | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/SimpleCell.java
// public class SimpleCell implements Cell {
// static final AtomicLong NEXT_ID = new AtomicLong(0);
// final long id = NEXT_ID.getAndIncrement();
// final int x;
// final int y;
// int state;
// int neighborCount;
// Overseer overseer;
//
// public SimpleCell(int x, int y, int state) {
// this.x = x;
// this.y = y;
// this.state = state;
// }
//
// @Override
// public void setOverseer(Overseer overseer) {
// this.overseer = overseer;
// }
//
// @Override
// public void reset(int state) {
// this.state = state;
// neighborCount = 0;
// }
//
// @Override
// public long getId() {
// return id;
// }
//
// @Override
// public int getX() {
// return x;
// }
//
// @Override
// public int getY() {
// return y;
// }
//
// @Override
// public int getState() {
// return state;
// }
//
// @Override
// public void setState(int newState) {
// int oldState = this.state;
// this.state = newState;
//
// if (newState != oldState && overseer != null) {
// overseer.onCellStateChanged(new CellStateChange(this));
// }
// }
//
// @Override
// public boolean isAlive() {
// return !isDead();
// }
//
// @Override
// public boolean isDead() {
// return state == STATE_DEAD;
// }
//
// @Override
// public void onNeighborStateChange(int newState) {
// if (newState == STATE_DEAD) {
// decreaseNeighborCount();
//
// } else {
// increaseNeighborCount();
// }
// }
//
// void increaseNeighborCount() {
// neighborCount++;
// }
//
// void decreaseNeighborCount() {
// neighborCount--;
// }
//
// public int getNeighborCount() {
// return neighborCount;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// SimpleCell that = (SimpleCell) o;
//
// if (neighborCount != that.neighborCount) return false;
// if (state != that.state) return false;
// if (x != that.x) return false;
// if (y != that.y) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = x;
// result = 31 * result + y;
// result = 31 * result + state;
// result = 31 * result + neighborCount;
// return result;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/grid/Grid.java
// public interface Grid<T extends Cell> extends Parcelable {
// int getSizeX();
// int getSizeY();
// T getCell(int x, int y);
// void putCell(T cell);
// }
// Path: app/src/main/java/hu/supercluster/gameoflife/game/rule/NeighborCountBasedRule.java
import java.util.HashSet;
import java.util.Set;
import hu.supercluster.gameoflife.game.cell.Cell;
import hu.supercluster.gameoflife.game.cell.SimpleCell;
import hu.supercluster.gameoflife.game.grid.Grid;
public NeighborCountBasedRule(String rule) {
String[] split = rule.split("/");
if (split.length != 2) {
throw new IllegalArgumentException("Invalid rule string: " + rule);
}
try {
survivalNbCounts = new HashSet<>();
String survival = split[0];
for (int i = 0; i < survival.length(); i++) {
survivalNbCounts.add(Integer.valueOf(String.valueOf(survival.charAt(i))));
}
creationNbCounts = new HashSet<>();
String creation = split[1];
for (int i = 0; i < creation.length(); i++) {
creationNbCounts.add(Integer.valueOf(String.valueOf(creation.charAt(i))));
}
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid rule string: " + rule);
}
}
public NeighborCountBasedRule(NeighborCountBasedRule other) {
this.survivalNbCounts = new HashSet<>(other.survivalNbCounts);
this.creationNbCounts = new HashSet<>(other.creationNbCounts);
}
@Override | public int apply(Grid<SimpleCell> grid, int x, int y) { |
zsoltk/GameOfLife | app/src/main/java/hu/supercluster/gameoflife/game/rule/NeighborCountBasedRule.java | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/SimpleCell.java
// public class SimpleCell implements Cell {
// static final AtomicLong NEXT_ID = new AtomicLong(0);
// final long id = NEXT_ID.getAndIncrement();
// final int x;
// final int y;
// int state;
// int neighborCount;
// Overseer overseer;
//
// public SimpleCell(int x, int y, int state) {
// this.x = x;
// this.y = y;
// this.state = state;
// }
//
// @Override
// public void setOverseer(Overseer overseer) {
// this.overseer = overseer;
// }
//
// @Override
// public void reset(int state) {
// this.state = state;
// neighborCount = 0;
// }
//
// @Override
// public long getId() {
// return id;
// }
//
// @Override
// public int getX() {
// return x;
// }
//
// @Override
// public int getY() {
// return y;
// }
//
// @Override
// public int getState() {
// return state;
// }
//
// @Override
// public void setState(int newState) {
// int oldState = this.state;
// this.state = newState;
//
// if (newState != oldState && overseer != null) {
// overseer.onCellStateChanged(new CellStateChange(this));
// }
// }
//
// @Override
// public boolean isAlive() {
// return !isDead();
// }
//
// @Override
// public boolean isDead() {
// return state == STATE_DEAD;
// }
//
// @Override
// public void onNeighborStateChange(int newState) {
// if (newState == STATE_DEAD) {
// decreaseNeighborCount();
//
// } else {
// increaseNeighborCount();
// }
// }
//
// void increaseNeighborCount() {
// neighborCount++;
// }
//
// void decreaseNeighborCount() {
// neighborCount--;
// }
//
// public int getNeighborCount() {
// return neighborCount;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// SimpleCell that = (SimpleCell) o;
//
// if (neighborCount != that.neighborCount) return false;
// if (state != that.state) return false;
// if (x != that.x) return false;
// if (y != that.y) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = x;
// result = 31 * result + y;
// result = 31 * result + state;
// result = 31 * result + neighborCount;
// return result;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/grid/Grid.java
// public interface Grid<T extends Cell> extends Parcelable {
// int getSizeX();
// int getSizeY();
// T getCell(int x, int y);
// void putCell(T cell);
// }
| import java.util.HashSet;
import java.util.Set;
import hu.supercluster.gameoflife.game.cell.Cell;
import hu.supercluster.gameoflife.game.cell.SimpleCell;
import hu.supercluster.gameoflife.game.grid.Grid; | for (int i = 0; i < creation.length(); i++) {
creationNbCounts.add(Integer.valueOf(String.valueOf(creation.charAt(i))));
}
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid rule string: " + rule);
}
}
public NeighborCountBasedRule(NeighborCountBasedRule other) {
this.survivalNbCounts = new HashSet<>(other.survivalNbCounts);
this.creationNbCounts = new HashSet<>(other.creationNbCounts);
}
@Override
public int apply(Grid<SimpleCell> grid, int x, int y) {
SimpleCell current = grid.getCell(x, y);
int n = current.getNeighborCount();
if (grid.getCell(x, y).isAlive()) {
return staysAlive(n);
} else {
return getsCreated(n);
}
}
private int staysAlive(int n) {
if (survivalNbCounts.contains(n)) { | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/SimpleCell.java
// public class SimpleCell implements Cell {
// static final AtomicLong NEXT_ID = new AtomicLong(0);
// final long id = NEXT_ID.getAndIncrement();
// final int x;
// final int y;
// int state;
// int neighborCount;
// Overseer overseer;
//
// public SimpleCell(int x, int y, int state) {
// this.x = x;
// this.y = y;
// this.state = state;
// }
//
// @Override
// public void setOverseer(Overseer overseer) {
// this.overseer = overseer;
// }
//
// @Override
// public void reset(int state) {
// this.state = state;
// neighborCount = 0;
// }
//
// @Override
// public long getId() {
// return id;
// }
//
// @Override
// public int getX() {
// return x;
// }
//
// @Override
// public int getY() {
// return y;
// }
//
// @Override
// public int getState() {
// return state;
// }
//
// @Override
// public void setState(int newState) {
// int oldState = this.state;
// this.state = newState;
//
// if (newState != oldState && overseer != null) {
// overseer.onCellStateChanged(new CellStateChange(this));
// }
// }
//
// @Override
// public boolean isAlive() {
// return !isDead();
// }
//
// @Override
// public boolean isDead() {
// return state == STATE_DEAD;
// }
//
// @Override
// public void onNeighborStateChange(int newState) {
// if (newState == STATE_DEAD) {
// decreaseNeighborCount();
//
// } else {
// increaseNeighborCount();
// }
// }
//
// void increaseNeighborCount() {
// neighborCount++;
// }
//
// void decreaseNeighborCount() {
// neighborCount--;
// }
//
// public int getNeighborCount() {
// return neighborCount;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// SimpleCell that = (SimpleCell) o;
//
// if (neighborCount != that.neighborCount) return false;
// if (state != that.state) return false;
// if (x != that.x) return false;
// if (y != that.y) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = x;
// result = 31 * result + y;
// result = 31 * result + state;
// result = 31 * result + neighborCount;
// return result;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/grid/Grid.java
// public interface Grid<T extends Cell> extends Parcelable {
// int getSizeX();
// int getSizeY();
// T getCell(int x, int y);
// void putCell(T cell);
// }
// Path: app/src/main/java/hu/supercluster/gameoflife/game/rule/NeighborCountBasedRule.java
import java.util.HashSet;
import java.util.Set;
import hu.supercluster.gameoflife.game.cell.Cell;
import hu.supercluster.gameoflife.game.cell.SimpleCell;
import hu.supercluster.gameoflife.game.grid.Grid;
for (int i = 0; i < creation.length(); i++) {
creationNbCounts.add(Integer.valueOf(String.valueOf(creation.charAt(i))));
}
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid rule string: " + rule);
}
}
public NeighborCountBasedRule(NeighborCountBasedRule other) {
this.survivalNbCounts = new HashSet<>(other.survivalNbCounts);
this.creationNbCounts = new HashSet<>(other.creationNbCounts);
}
@Override
public int apply(Grid<SimpleCell> grid, int x, int y) {
SimpleCell current = grid.getCell(x, y);
int n = current.getNeighborCount();
if (grid.getCell(x, y).isAlive()) {
return staysAlive(n);
} else {
return getsCreated(n);
}
}
private int staysAlive(int n) {
if (survivalNbCounts.contains(n)) { | return Cell.STATE_ALIVE; |
zsoltk/GameOfLife | app/src/test/java/hu/supercluster/gameoflife/game/transformer/SimpleGridTransformerTest.java | // Path: app/src/test/java/hu/supercluster/gameoflife/game/testutils/GrowableCell.java
// public class GrowableCell implements Cell {
// static final AtomicLong NEXT_ID = new AtomicLong(0);
// final long id = NEXT_ID.getAndIncrement();
//
// final int x;
// final int y;
// int state;
// Overseer overseer;
//
// public GrowableCell(int x, int y, int state) {
// this.x = x;
// this.y = y;
// this.state = state;
// }
//
// @Override
// public void setOverseer(Overseer overseer) {
// this.overseer = overseer;
// }
//
// @Override
// public void reset(int state) {
// this.state = state;
// }
//
// @Override
// public long getId() {
// return id;
// }
//
// @Override
// public int getX() {
// return x;
// }
//
// @Override
// public int getY() {
// return y;
// }
//
// @Override
// public int getState() {
// return state;
// }
//
// @Override
// public void setState(int newState) {
// this.state = newState;
// }
//
// @Override
// public boolean isAlive() {
// return !isDead();
// }
//
// @Override
// public boolean isDead() {
// return state == STATE_DEAD;
// }
//
// @Override
// public void onNeighborStateChange(int newState) {
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// GrowableCell that = (GrowableCell) o;
//
// if (state != that.state) return false;
// if (x != that.x) return false;
// if (y != that.y) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = x;
// result = 31 * result + y;
// result = 31 * result + state;
// return result;
// }
//
// @Override
// public String toString() {
// return "GrowableCell{" +
// "id=" + id +
// ", x=" + x +
// ", y=" + y +
// ", state=" + state +
// '}';
// }
// }
| import hu.supercluster.gameoflife.game.testutils.GrowableCell; | package hu.supercluster.gameoflife.game.transformer;
public class SimpleGridTransformerTest extends AbstractGridTransformerTester {
@Override | // Path: app/src/test/java/hu/supercluster/gameoflife/game/testutils/GrowableCell.java
// public class GrowableCell implements Cell {
// static final AtomicLong NEXT_ID = new AtomicLong(0);
// final long id = NEXT_ID.getAndIncrement();
//
// final int x;
// final int y;
// int state;
// Overseer overseer;
//
// public GrowableCell(int x, int y, int state) {
// this.x = x;
// this.y = y;
// this.state = state;
// }
//
// @Override
// public void setOverseer(Overseer overseer) {
// this.overseer = overseer;
// }
//
// @Override
// public void reset(int state) {
// this.state = state;
// }
//
// @Override
// public long getId() {
// return id;
// }
//
// @Override
// public int getX() {
// return x;
// }
//
// @Override
// public int getY() {
// return y;
// }
//
// @Override
// public int getState() {
// return state;
// }
//
// @Override
// public void setState(int newState) {
// this.state = newState;
// }
//
// @Override
// public boolean isAlive() {
// return !isDead();
// }
//
// @Override
// public boolean isDead() {
// return state == STATE_DEAD;
// }
//
// @Override
// public void onNeighborStateChange(int newState) {
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// GrowableCell that = (GrowableCell) o;
//
// if (state != that.state) return false;
// if (x != that.x) return false;
// if (y != that.y) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = x;
// result = 31 * result + y;
// result = 31 * result + state;
// return result;
// }
//
// @Override
// public String toString() {
// return "GrowableCell{" +
// "id=" + id +
// ", x=" + x +
// ", y=" + y +
// ", state=" + state +
// '}';
// }
// }
// Path: app/src/test/java/hu/supercluster/gameoflife/game/transformer/SimpleGridTransformerTest.java
import hu.supercluster.gameoflife.game.testutils.GrowableCell;
package hu.supercluster.gameoflife.game.transformer;
public class SimpleGridTransformerTest extends AbstractGridTransformerTester {
@Override | protected GridTransformer<GrowableCell> getTransformer() { |
zsoltk/GameOfLife | app/src/main/java/hu/supercluster/gameoflife/game/grid/EndlessGridHandler.java | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/CellFactory.java
// public interface CellFactory<T extends Cell> extends Serializable {
// T create(int x, int y);
// int[] flatten(T cell);
// T inflate(int[] flattened);
// }
| import hu.supercluster.gameoflife.game.cell.Cell;
import hu.supercluster.gameoflife.game.cell.CellFactory; | package hu.supercluster.gameoflife.game.grid;
public class EndlessGridHandler<T extends Cell> implements GridHandler<T> {
private final int x;
private final int y; | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/CellFactory.java
// public interface CellFactory<T extends Cell> extends Serializable {
// T create(int x, int y);
// int[] flatten(T cell);
// T inflate(int[] flattened);
// }
// Path: app/src/main/java/hu/supercluster/gameoflife/game/grid/EndlessGridHandler.java
import hu.supercluster.gameoflife.game.cell.Cell;
import hu.supercluster.gameoflife.game.cell.CellFactory;
package hu.supercluster.gameoflife.game.grid;
public class EndlessGridHandler<T extends Cell> implements GridHandler<T> {
private final int x;
private final int y; | private final CellFactory<T> cellFactory; |
zsoltk/GameOfLife | app/src/main/java/hu/supercluster/gameoflife/game/visualization/brush/DefaultBlockBrush.java | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
| import hu.supercluster.gameoflife.game.cell.Cell; | package hu.supercluster.gameoflife.game.visualization.brush;
public class DefaultBlockBrush extends AbstractBrush {
@Override
protected void doPaint() { | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
// Path: app/src/main/java/hu/supercluster/gameoflife/game/visualization/brush/DefaultBlockBrush.java
import hu.supercluster.gameoflife.game.cell.Cell;
package hu.supercluster.gameoflife.game.visualization.brush;
public class DefaultBlockBrush extends AbstractBrush {
@Override
protected void doPaint() { | paintWith(Cell.STATE_ALIVE); |
zsoltk/GameOfLife | app/src/main/java/hu/supercluster/gameoflife/app/preset/Preset.java | // Path: app/src/main/java/hu/supercluster/gameoflife/game/rule/NeighborCountBasedRule.java
// public class NeighborCountBasedRule implements Rule<SimpleCell> {
// private final Set<Integer> survivalNbCounts;
// private final Set<Integer> creationNbCounts;
//
// public NeighborCountBasedRule(Set<Integer> survivalNbCounts, Set<Integer> creationNbCounts) {
// this.survivalNbCounts = new HashSet<>(survivalNbCounts);
// this.creationNbCounts = new HashSet<>(creationNbCounts);
// }
//
// public NeighborCountBasedRule(String rule) {
// String[] split = rule.split("/");
// if (split.length != 2) {
// throw new IllegalArgumentException("Invalid rule string: " + rule);
// }
//
// try {
// survivalNbCounts = new HashSet<>();
// String survival = split[0];
// for (int i = 0; i < survival.length(); i++) {
// survivalNbCounts.add(Integer.valueOf(String.valueOf(survival.charAt(i))));
// }
//
// creationNbCounts = new HashSet<>();
// String creation = split[1];
// for (int i = 0; i < creation.length(); i++) {
// creationNbCounts.add(Integer.valueOf(String.valueOf(creation.charAt(i))));
// }
//
// } catch (NumberFormatException e) {
// throw new IllegalArgumentException("Invalid rule string: " + rule);
// }
// }
//
// public NeighborCountBasedRule(NeighborCountBasedRule other) {
// this.survivalNbCounts = new HashSet<>(other.survivalNbCounts);
// this.creationNbCounts = new HashSet<>(other.creationNbCounts);
// }
//
// @Override
// public int apply(Grid<SimpleCell> grid, int x, int y) {
// SimpleCell current = grid.getCell(x, y);
// int n = current.getNeighborCount();
//
// if (grid.getCell(x, y).isAlive()) {
// return staysAlive(n);
//
// } else {
// return getsCreated(n);
// }
//
// }
//
// private int staysAlive(int n) {
// if (survivalNbCounts.contains(n)) {
// return Cell.STATE_ALIVE;
//
// } else {
// return Cell.STATE_DEAD;
// }
// }
//
// private int getsCreated(int n) {
// if (creationNbCounts.contains(n)) {
// return Cell.STATE_ALIVE;
//
// } else {
// return Cell.STATE_DEAD;
// }
// }
//
// public Set<Integer> getSurvivalNbCounts() {
// return survivalNbCounts;
// }
//
// public Set<Integer> getCreationNbCounts() {
// return creationNbCounts;
// }
//
// public void toggleSurvivalForNbCount(int nbCount) {
// if (survivalNbCounts.contains(nbCount)) {
// survivalNbCounts.remove(nbCount);
// } else {
// survivalNbCounts.add(nbCount);
// }
// }
//
// public void toggleCreationForNbCount(int nbCount) {
// if (creationNbCounts.contains(nbCount)) {
// creationNbCounts.remove(nbCount);
// } else {
// creationNbCounts.add(nbCount);
// }
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// NeighborCountBasedRule that = (NeighborCountBasedRule) o;
//
// if (!survivalNbCounts.equals(that.survivalNbCounts)) return false;
// if (!creationNbCounts.equals(that.creationNbCounts)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = survivalNbCounts.hashCode();
// result = 31 * result + creationNbCounts.hashCode();
//
// return result;
// }
// }
| import hu.supercluster.gameoflife.game.rule.NeighborCountBasedRule; | package hu.supercluster.gameoflife.app.preset;
public class Preset {
private final String name;
private final Type type; | // Path: app/src/main/java/hu/supercluster/gameoflife/game/rule/NeighborCountBasedRule.java
// public class NeighborCountBasedRule implements Rule<SimpleCell> {
// private final Set<Integer> survivalNbCounts;
// private final Set<Integer> creationNbCounts;
//
// public NeighborCountBasedRule(Set<Integer> survivalNbCounts, Set<Integer> creationNbCounts) {
// this.survivalNbCounts = new HashSet<>(survivalNbCounts);
// this.creationNbCounts = new HashSet<>(creationNbCounts);
// }
//
// public NeighborCountBasedRule(String rule) {
// String[] split = rule.split("/");
// if (split.length != 2) {
// throw new IllegalArgumentException("Invalid rule string: " + rule);
// }
//
// try {
// survivalNbCounts = new HashSet<>();
// String survival = split[0];
// for (int i = 0; i < survival.length(); i++) {
// survivalNbCounts.add(Integer.valueOf(String.valueOf(survival.charAt(i))));
// }
//
// creationNbCounts = new HashSet<>();
// String creation = split[1];
// for (int i = 0; i < creation.length(); i++) {
// creationNbCounts.add(Integer.valueOf(String.valueOf(creation.charAt(i))));
// }
//
// } catch (NumberFormatException e) {
// throw new IllegalArgumentException("Invalid rule string: " + rule);
// }
// }
//
// public NeighborCountBasedRule(NeighborCountBasedRule other) {
// this.survivalNbCounts = new HashSet<>(other.survivalNbCounts);
// this.creationNbCounts = new HashSet<>(other.creationNbCounts);
// }
//
// @Override
// public int apply(Grid<SimpleCell> grid, int x, int y) {
// SimpleCell current = grid.getCell(x, y);
// int n = current.getNeighborCount();
//
// if (grid.getCell(x, y).isAlive()) {
// return staysAlive(n);
//
// } else {
// return getsCreated(n);
// }
//
// }
//
// private int staysAlive(int n) {
// if (survivalNbCounts.contains(n)) {
// return Cell.STATE_ALIVE;
//
// } else {
// return Cell.STATE_DEAD;
// }
// }
//
// private int getsCreated(int n) {
// if (creationNbCounts.contains(n)) {
// return Cell.STATE_ALIVE;
//
// } else {
// return Cell.STATE_DEAD;
// }
// }
//
// public Set<Integer> getSurvivalNbCounts() {
// return survivalNbCounts;
// }
//
// public Set<Integer> getCreationNbCounts() {
// return creationNbCounts;
// }
//
// public void toggleSurvivalForNbCount(int nbCount) {
// if (survivalNbCounts.contains(nbCount)) {
// survivalNbCounts.remove(nbCount);
// } else {
// survivalNbCounts.add(nbCount);
// }
// }
//
// public void toggleCreationForNbCount(int nbCount) {
// if (creationNbCounts.contains(nbCount)) {
// creationNbCounts.remove(nbCount);
// } else {
// creationNbCounts.add(nbCount);
// }
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// NeighborCountBasedRule that = (NeighborCountBasedRule) o;
//
// if (!survivalNbCounts.equals(that.survivalNbCounts)) return false;
// if (!creationNbCounts.equals(that.creationNbCounts)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = survivalNbCounts.hashCode();
// result = 31 * result + creationNbCounts.hashCode();
//
// return result;
// }
// }
// Path: app/src/main/java/hu/supercluster/gameoflife/app/preset/Preset.java
import hu.supercluster.gameoflife.game.rule.NeighborCountBasedRule;
package hu.supercluster.gameoflife.app.preset;
public class Preset {
private final String name;
private final Type type; | private final NeighborCountBasedRule rule; |
zsoltk/GameOfLife | app/src/main/java/hu/supercluster/gameoflife/game/transformer/SimpleGridTransformer.java | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/grid/Grid.java
// public interface Grid<T extends Cell> extends Parcelable {
// int getSizeX();
// int getSizeY();
// T getCell(int x, int y);
// void putCell(T cell);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/rule/Rule.java
// public interface Rule<T extends Cell> extends Serializable {
// int apply(Grid<T> grid, int x, int y);
// }
| import hu.supercluster.gameoflife.game.cell.Cell;
import hu.supercluster.gameoflife.game.grid.Grid;
import hu.supercluster.gameoflife.game.rule.Rule;
import hugo.weaving.DebugLog; | package hu.supercluster.gameoflife.game.transformer;
public class SimpleGridTransformer<T extends Cell> implements GridTransformer<T> {
private int[][] stateChanges;
@Override | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/grid/Grid.java
// public interface Grid<T extends Cell> extends Parcelable {
// int getSizeX();
// int getSizeY();
// T getCell(int x, int y);
// void putCell(T cell);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/rule/Rule.java
// public interface Rule<T extends Cell> extends Serializable {
// int apply(Grid<T> grid, int x, int y);
// }
// Path: app/src/main/java/hu/supercluster/gameoflife/game/transformer/SimpleGridTransformer.java
import hu.supercluster.gameoflife.game.cell.Cell;
import hu.supercluster.gameoflife.game.grid.Grid;
import hu.supercluster.gameoflife.game.rule.Rule;
import hugo.weaving.DebugLog;
package hu.supercluster.gameoflife.game.transformer;
public class SimpleGridTransformer<T extends Cell> implements GridTransformer<T> {
private int[][] stateChanges;
@Override | public final void transform(Grid<T> grid, Rule<T> rule) { |
zsoltk/GameOfLife | app/src/main/java/hu/supercluster/gameoflife/game/transformer/SimpleGridTransformer.java | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/grid/Grid.java
// public interface Grid<T extends Cell> extends Parcelable {
// int getSizeX();
// int getSizeY();
// T getCell(int x, int y);
// void putCell(T cell);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/rule/Rule.java
// public interface Rule<T extends Cell> extends Serializable {
// int apply(Grid<T> grid, int x, int y);
// }
| import hu.supercluster.gameoflife.game.cell.Cell;
import hu.supercluster.gameoflife.game.grid.Grid;
import hu.supercluster.gameoflife.game.rule.Rule;
import hugo.weaving.DebugLog; | package hu.supercluster.gameoflife.game.transformer;
public class SimpleGridTransformer<T extends Cell> implements GridTransformer<T> {
private int[][] stateChanges;
@Override | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cell/Cell.java
// public interface Cell {
// public static final int STATE_ALIVE = 1;
// public static final int STATE_DEAD = 0;
//
// void reset(int state);
// long getId();
// int getY();
// int getX();
// void setState(int state);
// int getState();
// boolean isAlive();
// boolean isDead();
// void onNeighborStateChange(int newState);
// void setOverseer(Overseer overseer);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/grid/Grid.java
// public interface Grid<T extends Cell> extends Parcelable {
// int getSizeX();
// int getSizeY();
// T getCell(int x, int y);
// void putCell(T cell);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/rule/Rule.java
// public interface Rule<T extends Cell> extends Serializable {
// int apply(Grid<T> grid, int x, int y);
// }
// Path: app/src/main/java/hu/supercluster/gameoflife/game/transformer/SimpleGridTransformer.java
import hu.supercluster.gameoflife.game.cell.Cell;
import hu.supercluster.gameoflife.game.grid.Grid;
import hu.supercluster.gameoflife.game.rule.Rule;
import hugo.weaving.DebugLog;
package hu.supercluster.gameoflife.game.transformer;
public class SimpleGridTransformer<T extends Cell> implements GridTransformer<T> {
private int[][] stateChanges;
@Override | public final void transform(Grid<T> grid, Rule<T> rule) { |
zsoltk/GameOfLife | app/src/main/java/hu/supercluster/gameoflife/app/rate/dialog/SuggestDialog.java | // Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/event/SuggestDialogNoEvent.java
// public class SuggestDialogNoEvent {
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/event/SuggestDialogYesEvent.java
// public class SuggestDialogYesEvent {
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/util/EventBus.java
// public class EventBus extends Bus {
// private static EventBus instance;
//
// private EventBus() {
// super(ThreadEnforcer.ANY);
// }
//
// public static EventBus getInstance() {
// if (instance == null) {
// instance = new EventBus();
// }
//
// return instance;
// }
//
// @Override
// public void unregister(Object object) {
// try {
// super.unregister(object);
//
// } catch (IllegalArgumentException e) {
// e.printStackTrace();
// }
// }
// }
| import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import org.androidannotations.annotations.EFragment;
import hu.supercluster.gameoflife.R;
import hu.supercluster.gameoflife.app.rate.event.SuggestDialogNoEvent;
import hu.supercluster.gameoflife.app.rate.event.SuggestDialogYesEvent;
import hu.supercluster.gameoflife.util.EventBus; | package hu.supercluster.gameoflife.app.rate.dialog;
@EFragment
public class SuggestDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder
.setCancelable(false)
.setTitle(R.string.dialog_suggest_title)
.setMessage(R.string.dialog_suggest_body)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) { | // Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/event/SuggestDialogNoEvent.java
// public class SuggestDialogNoEvent {
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/event/SuggestDialogYesEvent.java
// public class SuggestDialogYesEvent {
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/util/EventBus.java
// public class EventBus extends Bus {
// private static EventBus instance;
//
// private EventBus() {
// super(ThreadEnforcer.ANY);
// }
//
// public static EventBus getInstance() {
// if (instance == null) {
// instance = new EventBus();
// }
//
// return instance;
// }
//
// @Override
// public void unregister(Object object) {
// try {
// super.unregister(object);
//
// } catch (IllegalArgumentException e) {
// e.printStackTrace();
// }
// }
// }
// Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/dialog/SuggestDialog.java
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import org.androidannotations.annotations.EFragment;
import hu.supercluster.gameoflife.R;
import hu.supercluster.gameoflife.app.rate.event.SuggestDialogNoEvent;
import hu.supercluster.gameoflife.app.rate.event.SuggestDialogYesEvent;
import hu.supercluster.gameoflife.util.EventBus;
package hu.supercluster.gameoflife.app.rate.dialog;
@EFragment
public class SuggestDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder
.setCancelable(false)
.setTitle(R.string.dialog_suggest_title)
.setMessage(R.string.dialog_suggest_body)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) { | EventBus.getInstance().post(new SuggestDialogYesEvent()); |
zsoltk/GameOfLife | app/src/main/java/hu/supercluster/gameoflife/app/rate/dialog/SuggestDialog.java | // Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/event/SuggestDialogNoEvent.java
// public class SuggestDialogNoEvent {
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/event/SuggestDialogYesEvent.java
// public class SuggestDialogYesEvent {
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/util/EventBus.java
// public class EventBus extends Bus {
// private static EventBus instance;
//
// private EventBus() {
// super(ThreadEnforcer.ANY);
// }
//
// public static EventBus getInstance() {
// if (instance == null) {
// instance = new EventBus();
// }
//
// return instance;
// }
//
// @Override
// public void unregister(Object object) {
// try {
// super.unregister(object);
//
// } catch (IllegalArgumentException e) {
// e.printStackTrace();
// }
// }
// }
| import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import org.androidannotations.annotations.EFragment;
import hu.supercluster.gameoflife.R;
import hu.supercluster.gameoflife.app.rate.event.SuggestDialogNoEvent;
import hu.supercluster.gameoflife.app.rate.event.SuggestDialogYesEvent;
import hu.supercluster.gameoflife.util.EventBus; | package hu.supercluster.gameoflife.app.rate.dialog;
@EFragment
public class SuggestDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder
.setCancelable(false)
.setTitle(R.string.dialog_suggest_title)
.setMessage(R.string.dialog_suggest_body)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) { | // Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/event/SuggestDialogNoEvent.java
// public class SuggestDialogNoEvent {
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/event/SuggestDialogYesEvent.java
// public class SuggestDialogYesEvent {
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/util/EventBus.java
// public class EventBus extends Bus {
// private static EventBus instance;
//
// private EventBus() {
// super(ThreadEnforcer.ANY);
// }
//
// public static EventBus getInstance() {
// if (instance == null) {
// instance = new EventBus();
// }
//
// return instance;
// }
//
// @Override
// public void unregister(Object object) {
// try {
// super.unregister(object);
//
// } catch (IllegalArgumentException e) {
// e.printStackTrace();
// }
// }
// }
// Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/dialog/SuggestDialog.java
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import org.androidannotations.annotations.EFragment;
import hu.supercluster.gameoflife.R;
import hu.supercluster.gameoflife.app.rate.event.SuggestDialogNoEvent;
import hu.supercluster.gameoflife.app.rate.event.SuggestDialogYesEvent;
import hu.supercluster.gameoflife.util.EventBus;
package hu.supercluster.gameoflife.app.rate.dialog;
@EFragment
public class SuggestDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder
.setCancelable(false)
.setTitle(R.string.dialog_suggest_title)
.setMessage(R.string.dialog_suggest_body)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) { | EventBus.getInstance().post(new SuggestDialogYesEvent()); |
zsoltk/GameOfLife | app/src/main/java/hu/supercluster/gameoflife/app/rate/dialog/SuggestDialog.java | // Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/event/SuggestDialogNoEvent.java
// public class SuggestDialogNoEvent {
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/event/SuggestDialogYesEvent.java
// public class SuggestDialogYesEvent {
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/util/EventBus.java
// public class EventBus extends Bus {
// private static EventBus instance;
//
// private EventBus() {
// super(ThreadEnforcer.ANY);
// }
//
// public static EventBus getInstance() {
// if (instance == null) {
// instance = new EventBus();
// }
//
// return instance;
// }
//
// @Override
// public void unregister(Object object) {
// try {
// super.unregister(object);
//
// } catch (IllegalArgumentException e) {
// e.printStackTrace();
// }
// }
// }
| import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import org.androidannotations.annotations.EFragment;
import hu.supercluster.gameoflife.R;
import hu.supercluster.gameoflife.app.rate.event.SuggestDialogNoEvent;
import hu.supercluster.gameoflife.app.rate.event.SuggestDialogYesEvent;
import hu.supercluster.gameoflife.util.EventBus; | package hu.supercluster.gameoflife.app.rate.dialog;
@EFragment
public class SuggestDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder
.setCancelable(false)
.setTitle(R.string.dialog_suggest_title)
.setMessage(R.string.dialog_suggest_body)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
EventBus.getInstance().post(new SuggestDialogYesEvent());
dialog.dismiss();
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) { | // Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/event/SuggestDialogNoEvent.java
// public class SuggestDialogNoEvent {
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/event/SuggestDialogYesEvent.java
// public class SuggestDialogYesEvent {
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/util/EventBus.java
// public class EventBus extends Bus {
// private static EventBus instance;
//
// private EventBus() {
// super(ThreadEnforcer.ANY);
// }
//
// public static EventBus getInstance() {
// if (instance == null) {
// instance = new EventBus();
// }
//
// return instance;
// }
//
// @Override
// public void unregister(Object object) {
// try {
// super.unregister(object);
//
// } catch (IllegalArgumentException e) {
// e.printStackTrace();
// }
// }
// }
// Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/dialog/SuggestDialog.java
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import org.androidannotations.annotations.EFragment;
import hu.supercluster.gameoflife.R;
import hu.supercluster.gameoflife.app.rate.event.SuggestDialogNoEvent;
import hu.supercluster.gameoflife.app.rate.event.SuggestDialogYesEvent;
import hu.supercluster.gameoflife.util.EventBus;
package hu.supercluster.gameoflife.app.rate.dialog;
@EFragment
public class SuggestDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder
.setCancelable(false)
.setTitle(R.string.dialog_suggest_title)
.setMessage(R.string.dialog_suggest_body)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
EventBus.getInstance().post(new SuggestDialogYesEvent());
dialog.dismiss();
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) { | EventBus.getInstance().post(new SuggestDialogNoEvent()); |
zsoltk/GameOfLife | app/src/main/java/hu/supercluster/gameoflife/app/view/AutomatonView.java | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/CellularAutomaton.java
// public interface CellularAutomaton<T extends Cell> extends Parcelable, Paintable {
// int getSizeX();
// int getSizeY();
// int getDefaultCellState();
// void reset();
// void randomFill(Fill fill);
// void step();
// void step(int count);
// Grid<T> getCurrentState();
// void setState(Grid<T> grid);
// Rule<T> getRule();
// void setRule(Rule<T> rule);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/event/PaintWithBrush.java
// public class PaintWithBrush {
// public final int x;
// public final int y;
//
// public PaintWithBrush(int x, int y) {
// this.x = x;
// this.y = y;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/manager/GameParams.java
// public class GameParams {
// private final int screenOrientation;
// private final Point displaySize;
// private int gridSizeX;
// private int gridSizeY;
// private final int cellSizeInPixels;
// private final Fill fill;
// private final CellColors cellColors;
// private final int fps;
// private final boolean startPaused;
//
// public GameParams(int screenOrientation, Point displaySize, int cellSizeInPixels, Fill fill, CellColors cellColors, int fps, boolean startPaused) {
// this.screenOrientation = screenOrientation;
// this.displaySize = displaySize;
// gridSizeX = displaySize.x / cellSizeInPixels;
// gridSizeY = displaySize.y / cellSizeInPixels;
// this.cellSizeInPixels = cellSizeInPixels;
// this.fill = fill;
// this.cellColors = cellColors;
// this.fps = fps;
// this.startPaused = startPaused;
// }
//
// public int getScreenOrientation() {
// return screenOrientation;
// }
//
// public Point getDisplaySize() {
// return displaySize;
// }
//
// public int getGridSizeX() {
// return gridSizeX;
// }
//
// public int getGridSizeY() {
// return gridSizeY;
// }
//
// public int getCellSizeInPixels() {
// return cellSizeInPixels;
// }
//
// public Fill getFill() {
// return fill;
// }
//
// public CellColors getCellColors() {
// return cellColors;
// }
//
// public int getFps() {
// return fps;
// }
//
// public boolean startPaused() {
// return startPaused;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/util/EventBus.java
// public class EventBus extends Bus {
// private static EventBus instance;
//
// private EventBus() {
// super(ThreadEnforcer.ANY);
// }
//
// public static EventBus getInstance() {
// if (instance == null) {
// instance = new EventBus();
// }
//
// return instance;
// }
//
// @Override
// public void unregister(Object object) {
// try {
// super.unregister(object);
//
// } catch (IllegalArgumentException e) {
// e.printStackTrace();
// }
// }
// }
| import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import hu.supercluster.gameoflife.game.cellularautomaton.CellularAutomaton;
import hu.supercluster.gameoflife.game.event.PaintWithBrush;
import hu.supercluster.gameoflife.game.manager.GameParams;
import hu.supercluster.gameoflife.util.EventBus;
import hugo.weaving.DebugLog; | package hu.supercluster.gameoflife.app.view;
public class AutomatonView extends SurfaceView implements SurfaceHolder.Callback {
private CellularAutomaton automaton; | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/CellularAutomaton.java
// public interface CellularAutomaton<T extends Cell> extends Parcelable, Paintable {
// int getSizeX();
// int getSizeY();
// int getDefaultCellState();
// void reset();
// void randomFill(Fill fill);
// void step();
// void step(int count);
// Grid<T> getCurrentState();
// void setState(Grid<T> grid);
// Rule<T> getRule();
// void setRule(Rule<T> rule);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/event/PaintWithBrush.java
// public class PaintWithBrush {
// public final int x;
// public final int y;
//
// public PaintWithBrush(int x, int y) {
// this.x = x;
// this.y = y;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/manager/GameParams.java
// public class GameParams {
// private final int screenOrientation;
// private final Point displaySize;
// private int gridSizeX;
// private int gridSizeY;
// private final int cellSizeInPixels;
// private final Fill fill;
// private final CellColors cellColors;
// private final int fps;
// private final boolean startPaused;
//
// public GameParams(int screenOrientation, Point displaySize, int cellSizeInPixels, Fill fill, CellColors cellColors, int fps, boolean startPaused) {
// this.screenOrientation = screenOrientation;
// this.displaySize = displaySize;
// gridSizeX = displaySize.x / cellSizeInPixels;
// gridSizeY = displaySize.y / cellSizeInPixels;
// this.cellSizeInPixels = cellSizeInPixels;
// this.fill = fill;
// this.cellColors = cellColors;
// this.fps = fps;
// this.startPaused = startPaused;
// }
//
// public int getScreenOrientation() {
// return screenOrientation;
// }
//
// public Point getDisplaySize() {
// return displaySize;
// }
//
// public int getGridSizeX() {
// return gridSizeX;
// }
//
// public int getGridSizeY() {
// return gridSizeY;
// }
//
// public int getCellSizeInPixels() {
// return cellSizeInPixels;
// }
//
// public Fill getFill() {
// return fill;
// }
//
// public CellColors getCellColors() {
// return cellColors;
// }
//
// public int getFps() {
// return fps;
// }
//
// public boolean startPaused() {
// return startPaused;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/util/EventBus.java
// public class EventBus extends Bus {
// private static EventBus instance;
//
// private EventBus() {
// super(ThreadEnforcer.ANY);
// }
//
// public static EventBus getInstance() {
// if (instance == null) {
// instance = new EventBus();
// }
//
// return instance;
// }
//
// @Override
// public void unregister(Object object) {
// try {
// super.unregister(object);
//
// } catch (IllegalArgumentException e) {
// e.printStackTrace();
// }
// }
// }
// Path: app/src/main/java/hu/supercluster/gameoflife/app/view/AutomatonView.java
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import hu.supercluster.gameoflife.game.cellularautomaton.CellularAutomaton;
import hu.supercluster.gameoflife.game.event.PaintWithBrush;
import hu.supercluster.gameoflife.game.manager.GameParams;
import hu.supercluster.gameoflife.util.EventBus;
import hugo.weaving.DebugLog;
package hu.supercluster.gameoflife.app.view;
public class AutomatonView extends SurfaceView implements SurfaceHolder.Callback {
private CellularAutomaton automaton; | private GameParams params; |
zsoltk/GameOfLife | app/src/main/java/hu/supercluster/gameoflife/app/view/AutomatonView.java | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/CellularAutomaton.java
// public interface CellularAutomaton<T extends Cell> extends Parcelable, Paintable {
// int getSizeX();
// int getSizeY();
// int getDefaultCellState();
// void reset();
// void randomFill(Fill fill);
// void step();
// void step(int count);
// Grid<T> getCurrentState();
// void setState(Grid<T> grid);
// Rule<T> getRule();
// void setRule(Rule<T> rule);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/event/PaintWithBrush.java
// public class PaintWithBrush {
// public final int x;
// public final int y;
//
// public PaintWithBrush(int x, int y) {
// this.x = x;
// this.y = y;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/manager/GameParams.java
// public class GameParams {
// private final int screenOrientation;
// private final Point displaySize;
// private int gridSizeX;
// private int gridSizeY;
// private final int cellSizeInPixels;
// private final Fill fill;
// private final CellColors cellColors;
// private final int fps;
// private final boolean startPaused;
//
// public GameParams(int screenOrientation, Point displaySize, int cellSizeInPixels, Fill fill, CellColors cellColors, int fps, boolean startPaused) {
// this.screenOrientation = screenOrientation;
// this.displaySize = displaySize;
// gridSizeX = displaySize.x / cellSizeInPixels;
// gridSizeY = displaySize.y / cellSizeInPixels;
// this.cellSizeInPixels = cellSizeInPixels;
// this.fill = fill;
// this.cellColors = cellColors;
// this.fps = fps;
// this.startPaused = startPaused;
// }
//
// public int getScreenOrientation() {
// return screenOrientation;
// }
//
// public Point getDisplaySize() {
// return displaySize;
// }
//
// public int getGridSizeX() {
// return gridSizeX;
// }
//
// public int getGridSizeY() {
// return gridSizeY;
// }
//
// public int getCellSizeInPixels() {
// return cellSizeInPixels;
// }
//
// public Fill getFill() {
// return fill;
// }
//
// public CellColors getCellColors() {
// return cellColors;
// }
//
// public int getFps() {
// return fps;
// }
//
// public boolean startPaused() {
// return startPaused;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/util/EventBus.java
// public class EventBus extends Bus {
// private static EventBus instance;
//
// private EventBus() {
// super(ThreadEnforcer.ANY);
// }
//
// public static EventBus getInstance() {
// if (instance == null) {
// instance = new EventBus();
// }
//
// return instance;
// }
//
// @Override
// public void unregister(Object object) {
// try {
// super.unregister(object);
//
// } catch (IllegalArgumentException e) {
// e.printStackTrace();
// }
// }
// }
| import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import hu.supercluster.gameoflife.game.cellularautomaton.CellularAutomaton;
import hu.supercluster.gameoflife.game.event.PaintWithBrush;
import hu.supercluster.gameoflife.game.manager.GameParams;
import hu.supercluster.gameoflife.util.EventBus;
import hugo.weaving.DebugLog; | @Override
@DebugLog
public void surfaceDestroyed(SurfaceHolder holder) {
thread.setRunning(false);
waitForThreadToDie();
}
@DebugLog
private void waitForThreadToDie() {
while (true) {
try {
thread.join();
break;
} catch (InterruptedException e) {
}
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
paint(event);
return true;
}
protected void paint(MotionEvent event) {
int x = Math.round(event.getX() / params.getCellSizeInPixels());
int y = Math.round(event.getY() / params.getCellSizeInPixels());
| // Path: app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/CellularAutomaton.java
// public interface CellularAutomaton<T extends Cell> extends Parcelable, Paintable {
// int getSizeX();
// int getSizeY();
// int getDefaultCellState();
// void reset();
// void randomFill(Fill fill);
// void step();
// void step(int count);
// Grid<T> getCurrentState();
// void setState(Grid<T> grid);
// Rule<T> getRule();
// void setRule(Rule<T> rule);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/event/PaintWithBrush.java
// public class PaintWithBrush {
// public final int x;
// public final int y;
//
// public PaintWithBrush(int x, int y) {
// this.x = x;
// this.y = y;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/manager/GameParams.java
// public class GameParams {
// private final int screenOrientation;
// private final Point displaySize;
// private int gridSizeX;
// private int gridSizeY;
// private final int cellSizeInPixels;
// private final Fill fill;
// private final CellColors cellColors;
// private final int fps;
// private final boolean startPaused;
//
// public GameParams(int screenOrientation, Point displaySize, int cellSizeInPixels, Fill fill, CellColors cellColors, int fps, boolean startPaused) {
// this.screenOrientation = screenOrientation;
// this.displaySize = displaySize;
// gridSizeX = displaySize.x / cellSizeInPixels;
// gridSizeY = displaySize.y / cellSizeInPixels;
// this.cellSizeInPixels = cellSizeInPixels;
// this.fill = fill;
// this.cellColors = cellColors;
// this.fps = fps;
// this.startPaused = startPaused;
// }
//
// public int getScreenOrientation() {
// return screenOrientation;
// }
//
// public Point getDisplaySize() {
// return displaySize;
// }
//
// public int getGridSizeX() {
// return gridSizeX;
// }
//
// public int getGridSizeY() {
// return gridSizeY;
// }
//
// public int getCellSizeInPixels() {
// return cellSizeInPixels;
// }
//
// public Fill getFill() {
// return fill;
// }
//
// public CellColors getCellColors() {
// return cellColors;
// }
//
// public int getFps() {
// return fps;
// }
//
// public boolean startPaused() {
// return startPaused;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/util/EventBus.java
// public class EventBus extends Bus {
// private static EventBus instance;
//
// private EventBus() {
// super(ThreadEnforcer.ANY);
// }
//
// public static EventBus getInstance() {
// if (instance == null) {
// instance = new EventBus();
// }
//
// return instance;
// }
//
// @Override
// public void unregister(Object object) {
// try {
// super.unregister(object);
//
// } catch (IllegalArgumentException e) {
// e.printStackTrace();
// }
// }
// }
// Path: app/src/main/java/hu/supercluster/gameoflife/app/view/AutomatonView.java
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import hu.supercluster.gameoflife.game.cellularautomaton.CellularAutomaton;
import hu.supercluster.gameoflife.game.event.PaintWithBrush;
import hu.supercluster.gameoflife.game.manager.GameParams;
import hu.supercluster.gameoflife.util.EventBus;
import hugo.weaving.DebugLog;
@Override
@DebugLog
public void surfaceDestroyed(SurfaceHolder holder) {
thread.setRunning(false);
waitForThreadToDie();
}
@DebugLog
private void waitForThreadToDie() {
while (true) {
try {
thread.join();
break;
} catch (InterruptedException e) {
}
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
paint(event);
return true;
}
protected void paint(MotionEvent event) {
int x = Math.round(event.getX() / params.getCellSizeInPixels());
int y = Math.round(event.getY() / params.getCellSizeInPixels());
| EventBus.getInstance().post(new PaintWithBrush(x, y)); |
zsoltk/GameOfLife | app/src/main/java/hu/supercluster/gameoflife/app/view/AutomatonView.java | // Path: app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/CellularAutomaton.java
// public interface CellularAutomaton<T extends Cell> extends Parcelable, Paintable {
// int getSizeX();
// int getSizeY();
// int getDefaultCellState();
// void reset();
// void randomFill(Fill fill);
// void step();
// void step(int count);
// Grid<T> getCurrentState();
// void setState(Grid<T> grid);
// Rule<T> getRule();
// void setRule(Rule<T> rule);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/event/PaintWithBrush.java
// public class PaintWithBrush {
// public final int x;
// public final int y;
//
// public PaintWithBrush(int x, int y) {
// this.x = x;
// this.y = y;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/manager/GameParams.java
// public class GameParams {
// private final int screenOrientation;
// private final Point displaySize;
// private int gridSizeX;
// private int gridSizeY;
// private final int cellSizeInPixels;
// private final Fill fill;
// private final CellColors cellColors;
// private final int fps;
// private final boolean startPaused;
//
// public GameParams(int screenOrientation, Point displaySize, int cellSizeInPixels, Fill fill, CellColors cellColors, int fps, boolean startPaused) {
// this.screenOrientation = screenOrientation;
// this.displaySize = displaySize;
// gridSizeX = displaySize.x / cellSizeInPixels;
// gridSizeY = displaySize.y / cellSizeInPixels;
// this.cellSizeInPixels = cellSizeInPixels;
// this.fill = fill;
// this.cellColors = cellColors;
// this.fps = fps;
// this.startPaused = startPaused;
// }
//
// public int getScreenOrientation() {
// return screenOrientation;
// }
//
// public Point getDisplaySize() {
// return displaySize;
// }
//
// public int getGridSizeX() {
// return gridSizeX;
// }
//
// public int getGridSizeY() {
// return gridSizeY;
// }
//
// public int getCellSizeInPixels() {
// return cellSizeInPixels;
// }
//
// public Fill getFill() {
// return fill;
// }
//
// public CellColors getCellColors() {
// return cellColors;
// }
//
// public int getFps() {
// return fps;
// }
//
// public boolean startPaused() {
// return startPaused;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/util/EventBus.java
// public class EventBus extends Bus {
// private static EventBus instance;
//
// private EventBus() {
// super(ThreadEnforcer.ANY);
// }
//
// public static EventBus getInstance() {
// if (instance == null) {
// instance = new EventBus();
// }
//
// return instance;
// }
//
// @Override
// public void unregister(Object object) {
// try {
// super.unregister(object);
//
// } catch (IllegalArgumentException e) {
// e.printStackTrace();
// }
// }
// }
| import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import hu.supercluster.gameoflife.game.cellularautomaton.CellularAutomaton;
import hu.supercluster.gameoflife.game.event.PaintWithBrush;
import hu.supercluster.gameoflife.game.manager.GameParams;
import hu.supercluster.gameoflife.util.EventBus;
import hugo.weaving.DebugLog; | @Override
@DebugLog
public void surfaceDestroyed(SurfaceHolder holder) {
thread.setRunning(false);
waitForThreadToDie();
}
@DebugLog
private void waitForThreadToDie() {
while (true) {
try {
thread.join();
break;
} catch (InterruptedException e) {
}
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
paint(event);
return true;
}
protected void paint(MotionEvent event) {
int x = Math.round(event.getX() / params.getCellSizeInPixels());
int y = Math.round(event.getY() / params.getCellSizeInPixels());
| // Path: app/src/main/java/hu/supercluster/gameoflife/game/cellularautomaton/CellularAutomaton.java
// public interface CellularAutomaton<T extends Cell> extends Parcelable, Paintable {
// int getSizeX();
// int getSizeY();
// int getDefaultCellState();
// void reset();
// void randomFill(Fill fill);
// void step();
// void step(int count);
// Grid<T> getCurrentState();
// void setState(Grid<T> grid);
// Rule<T> getRule();
// void setRule(Rule<T> rule);
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/event/PaintWithBrush.java
// public class PaintWithBrush {
// public final int x;
// public final int y;
//
// public PaintWithBrush(int x, int y) {
// this.x = x;
// this.y = y;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/game/manager/GameParams.java
// public class GameParams {
// private final int screenOrientation;
// private final Point displaySize;
// private int gridSizeX;
// private int gridSizeY;
// private final int cellSizeInPixels;
// private final Fill fill;
// private final CellColors cellColors;
// private final int fps;
// private final boolean startPaused;
//
// public GameParams(int screenOrientation, Point displaySize, int cellSizeInPixels, Fill fill, CellColors cellColors, int fps, boolean startPaused) {
// this.screenOrientation = screenOrientation;
// this.displaySize = displaySize;
// gridSizeX = displaySize.x / cellSizeInPixels;
// gridSizeY = displaySize.y / cellSizeInPixels;
// this.cellSizeInPixels = cellSizeInPixels;
// this.fill = fill;
// this.cellColors = cellColors;
// this.fps = fps;
// this.startPaused = startPaused;
// }
//
// public int getScreenOrientation() {
// return screenOrientation;
// }
//
// public Point getDisplaySize() {
// return displaySize;
// }
//
// public int getGridSizeX() {
// return gridSizeX;
// }
//
// public int getGridSizeY() {
// return gridSizeY;
// }
//
// public int getCellSizeInPixels() {
// return cellSizeInPixels;
// }
//
// public Fill getFill() {
// return fill;
// }
//
// public CellColors getCellColors() {
// return cellColors;
// }
//
// public int getFps() {
// return fps;
// }
//
// public boolean startPaused() {
// return startPaused;
// }
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/util/EventBus.java
// public class EventBus extends Bus {
// private static EventBus instance;
//
// private EventBus() {
// super(ThreadEnforcer.ANY);
// }
//
// public static EventBus getInstance() {
// if (instance == null) {
// instance = new EventBus();
// }
//
// return instance;
// }
//
// @Override
// public void unregister(Object object) {
// try {
// super.unregister(object);
//
// } catch (IllegalArgumentException e) {
// e.printStackTrace();
// }
// }
// }
// Path: app/src/main/java/hu/supercluster/gameoflife/app/view/AutomatonView.java
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import hu.supercluster.gameoflife.game.cellularautomaton.CellularAutomaton;
import hu.supercluster.gameoflife.game.event.PaintWithBrush;
import hu.supercluster.gameoflife.game.manager.GameParams;
import hu.supercluster.gameoflife.util.EventBus;
import hugo.weaving.DebugLog;
@Override
@DebugLog
public void surfaceDestroyed(SurfaceHolder holder) {
thread.setRunning(false);
waitForThreadToDie();
}
@DebugLog
private void waitForThreadToDie() {
while (true) {
try {
thread.join();
break;
} catch (InterruptedException e) {
}
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
paint(event);
return true;
}
protected void paint(MotionEvent event) {
int x = Math.round(event.getX() / params.getCellSizeInPixels());
int y = Math.round(event.getY() / params.getCellSizeInPixels());
| EventBus.getInstance().post(new PaintWithBrush(x, y)); |
zsoltk/GameOfLife | app/src/main/java/hu/supercluster/gameoflife/app/rate/dialog/RatingDialog.java | // Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/event/RatingDialogLaterEvent.java
// public class RatingDialogLaterEvent {
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/event/RatingDialogNoEvent.java
// public class RatingDialogNoEvent {
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/event/RatingDialogYesEvent.java
// public class RatingDialogYesEvent {
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/util/EventBus.java
// public class EventBus extends Bus {
// private static EventBus instance;
//
// private EventBus() {
// super(ThreadEnforcer.ANY);
// }
//
// public static EventBus getInstance() {
// if (instance == null) {
// instance = new EventBus();
// }
//
// return instance;
// }
//
// @Override
// public void unregister(Object object) {
// try {
// super.unregister(object);
//
// } catch (IllegalArgumentException e) {
// e.printStackTrace();
// }
// }
// }
| import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import org.androidannotations.annotations.EFragment;
import hu.supercluster.gameoflife.R;
import hu.supercluster.gameoflife.app.rate.event.RatingDialogLaterEvent;
import hu.supercluster.gameoflife.app.rate.event.RatingDialogNoEvent;
import hu.supercluster.gameoflife.app.rate.event.RatingDialogYesEvent;
import hu.supercluster.gameoflife.util.EventBus; | package hu.supercluster.gameoflife.app.rate.dialog;
@EFragment
public class RatingDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder
.setCancelable(false)
.setTitle(R.string.dialog_rate_title)
.setMessage(R.string.dialog_rate_body)
.setPositiveButton(R.string.dialog_rate_rate, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) { | // Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/event/RatingDialogLaterEvent.java
// public class RatingDialogLaterEvent {
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/event/RatingDialogNoEvent.java
// public class RatingDialogNoEvent {
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/event/RatingDialogYesEvent.java
// public class RatingDialogYesEvent {
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/util/EventBus.java
// public class EventBus extends Bus {
// private static EventBus instance;
//
// private EventBus() {
// super(ThreadEnforcer.ANY);
// }
//
// public static EventBus getInstance() {
// if (instance == null) {
// instance = new EventBus();
// }
//
// return instance;
// }
//
// @Override
// public void unregister(Object object) {
// try {
// super.unregister(object);
//
// } catch (IllegalArgumentException e) {
// e.printStackTrace();
// }
// }
// }
// Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/dialog/RatingDialog.java
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import org.androidannotations.annotations.EFragment;
import hu.supercluster.gameoflife.R;
import hu.supercluster.gameoflife.app.rate.event.RatingDialogLaterEvent;
import hu.supercluster.gameoflife.app.rate.event.RatingDialogNoEvent;
import hu.supercluster.gameoflife.app.rate.event.RatingDialogYesEvent;
import hu.supercluster.gameoflife.util.EventBus;
package hu.supercluster.gameoflife.app.rate.dialog;
@EFragment
public class RatingDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder
.setCancelable(false)
.setTitle(R.string.dialog_rate_title)
.setMessage(R.string.dialog_rate_body)
.setPositiveButton(R.string.dialog_rate_rate, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) { | EventBus.getInstance().post(new RatingDialogYesEvent()); |
zsoltk/GameOfLife | app/src/main/java/hu/supercluster/gameoflife/app/rate/dialog/RatingDialog.java | // Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/event/RatingDialogLaterEvent.java
// public class RatingDialogLaterEvent {
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/event/RatingDialogNoEvent.java
// public class RatingDialogNoEvent {
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/event/RatingDialogYesEvent.java
// public class RatingDialogYesEvent {
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/util/EventBus.java
// public class EventBus extends Bus {
// private static EventBus instance;
//
// private EventBus() {
// super(ThreadEnforcer.ANY);
// }
//
// public static EventBus getInstance() {
// if (instance == null) {
// instance = new EventBus();
// }
//
// return instance;
// }
//
// @Override
// public void unregister(Object object) {
// try {
// super.unregister(object);
//
// } catch (IllegalArgumentException e) {
// e.printStackTrace();
// }
// }
// }
| import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import org.androidannotations.annotations.EFragment;
import hu.supercluster.gameoflife.R;
import hu.supercluster.gameoflife.app.rate.event.RatingDialogLaterEvent;
import hu.supercluster.gameoflife.app.rate.event.RatingDialogNoEvent;
import hu.supercluster.gameoflife.app.rate.event.RatingDialogYesEvent;
import hu.supercluster.gameoflife.util.EventBus; | package hu.supercluster.gameoflife.app.rate.dialog;
@EFragment
public class RatingDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder
.setCancelable(false)
.setTitle(R.string.dialog_rate_title)
.setMessage(R.string.dialog_rate_body)
.setPositiveButton(R.string.dialog_rate_rate, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) { | // Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/event/RatingDialogLaterEvent.java
// public class RatingDialogLaterEvent {
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/event/RatingDialogNoEvent.java
// public class RatingDialogNoEvent {
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/event/RatingDialogYesEvent.java
// public class RatingDialogYesEvent {
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/util/EventBus.java
// public class EventBus extends Bus {
// private static EventBus instance;
//
// private EventBus() {
// super(ThreadEnforcer.ANY);
// }
//
// public static EventBus getInstance() {
// if (instance == null) {
// instance = new EventBus();
// }
//
// return instance;
// }
//
// @Override
// public void unregister(Object object) {
// try {
// super.unregister(object);
//
// } catch (IllegalArgumentException e) {
// e.printStackTrace();
// }
// }
// }
// Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/dialog/RatingDialog.java
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import org.androidannotations.annotations.EFragment;
import hu.supercluster.gameoflife.R;
import hu.supercluster.gameoflife.app.rate.event.RatingDialogLaterEvent;
import hu.supercluster.gameoflife.app.rate.event.RatingDialogNoEvent;
import hu.supercluster.gameoflife.app.rate.event.RatingDialogYesEvent;
import hu.supercluster.gameoflife.util.EventBus;
package hu.supercluster.gameoflife.app.rate.dialog;
@EFragment
public class RatingDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder
.setCancelable(false)
.setTitle(R.string.dialog_rate_title)
.setMessage(R.string.dialog_rate_body)
.setPositiveButton(R.string.dialog_rate_rate, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) { | EventBus.getInstance().post(new RatingDialogYesEvent()); |
zsoltk/GameOfLife | app/src/main/java/hu/supercluster/gameoflife/app/rate/dialog/RatingDialog.java | // Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/event/RatingDialogLaterEvent.java
// public class RatingDialogLaterEvent {
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/event/RatingDialogNoEvent.java
// public class RatingDialogNoEvent {
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/event/RatingDialogYesEvent.java
// public class RatingDialogYesEvent {
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/util/EventBus.java
// public class EventBus extends Bus {
// private static EventBus instance;
//
// private EventBus() {
// super(ThreadEnforcer.ANY);
// }
//
// public static EventBus getInstance() {
// if (instance == null) {
// instance = new EventBus();
// }
//
// return instance;
// }
//
// @Override
// public void unregister(Object object) {
// try {
// super.unregister(object);
//
// } catch (IllegalArgumentException e) {
// e.printStackTrace();
// }
// }
// }
| import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import org.androidannotations.annotations.EFragment;
import hu.supercluster.gameoflife.R;
import hu.supercluster.gameoflife.app.rate.event.RatingDialogLaterEvent;
import hu.supercluster.gameoflife.app.rate.event.RatingDialogNoEvent;
import hu.supercluster.gameoflife.app.rate.event.RatingDialogYesEvent;
import hu.supercluster.gameoflife.util.EventBus; | package hu.supercluster.gameoflife.app.rate.dialog;
@EFragment
public class RatingDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder
.setCancelable(false)
.setTitle(R.string.dialog_rate_title)
.setMessage(R.string.dialog_rate_body)
.setPositiveButton(R.string.dialog_rate_rate, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
EventBus.getInstance().post(new RatingDialogYesEvent());
dialog.dismiss();
}
})
.setNeutralButton(R.string.dialog_rate_later, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) { | // Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/event/RatingDialogLaterEvent.java
// public class RatingDialogLaterEvent {
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/event/RatingDialogNoEvent.java
// public class RatingDialogNoEvent {
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/event/RatingDialogYesEvent.java
// public class RatingDialogYesEvent {
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/util/EventBus.java
// public class EventBus extends Bus {
// private static EventBus instance;
//
// private EventBus() {
// super(ThreadEnforcer.ANY);
// }
//
// public static EventBus getInstance() {
// if (instance == null) {
// instance = new EventBus();
// }
//
// return instance;
// }
//
// @Override
// public void unregister(Object object) {
// try {
// super.unregister(object);
//
// } catch (IllegalArgumentException e) {
// e.printStackTrace();
// }
// }
// }
// Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/dialog/RatingDialog.java
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import org.androidannotations.annotations.EFragment;
import hu.supercluster.gameoflife.R;
import hu.supercluster.gameoflife.app.rate.event.RatingDialogLaterEvent;
import hu.supercluster.gameoflife.app.rate.event.RatingDialogNoEvent;
import hu.supercluster.gameoflife.app.rate.event.RatingDialogYesEvent;
import hu.supercluster.gameoflife.util.EventBus;
package hu.supercluster.gameoflife.app.rate.dialog;
@EFragment
public class RatingDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder
.setCancelable(false)
.setTitle(R.string.dialog_rate_title)
.setMessage(R.string.dialog_rate_body)
.setPositiveButton(R.string.dialog_rate_rate, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
EventBus.getInstance().post(new RatingDialogYesEvent());
dialog.dismiss();
}
})
.setNeutralButton(R.string.dialog_rate_later, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) { | EventBus.getInstance().post(new RatingDialogLaterEvent()); |
zsoltk/GameOfLife | app/src/main/java/hu/supercluster/gameoflife/app/rate/dialog/RatingDialog.java | // Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/event/RatingDialogLaterEvent.java
// public class RatingDialogLaterEvent {
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/event/RatingDialogNoEvent.java
// public class RatingDialogNoEvent {
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/event/RatingDialogYesEvent.java
// public class RatingDialogYesEvent {
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/util/EventBus.java
// public class EventBus extends Bus {
// private static EventBus instance;
//
// private EventBus() {
// super(ThreadEnforcer.ANY);
// }
//
// public static EventBus getInstance() {
// if (instance == null) {
// instance = new EventBus();
// }
//
// return instance;
// }
//
// @Override
// public void unregister(Object object) {
// try {
// super.unregister(object);
//
// } catch (IllegalArgumentException e) {
// e.printStackTrace();
// }
// }
// }
| import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import org.androidannotations.annotations.EFragment;
import hu.supercluster.gameoflife.R;
import hu.supercluster.gameoflife.app.rate.event.RatingDialogLaterEvent;
import hu.supercluster.gameoflife.app.rate.event.RatingDialogNoEvent;
import hu.supercluster.gameoflife.app.rate.event.RatingDialogYesEvent;
import hu.supercluster.gameoflife.util.EventBus; | package hu.supercluster.gameoflife.app.rate.dialog;
@EFragment
public class RatingDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder
.setCancelable(false)
.setTitle(R.string.dialog_rate_title)
.setMessage(R.string.dialog_rate_body)
.setPositiveButton(R.string.dialog_rate_rate, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
EventBus.getInstance().post(new RatingDialogYesEvent());
dialog.dismiss();
}
})
.setNeutralButton(R.string.dialog_rate_later, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
EventBus.getInstance().post(new RatingDialogLaterEvent());
dialog.dismiss();
}
})
.setNegativeButton(R.string.dialog_rate_no_thanks, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) { | // Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/event/RatingDialogLaterEvent.java
// public class RatingDialogLaterEvent {
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/event/RatingDialogNoEvent.java
// public class RatingDialogNoEvent {
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/event/RatingDialogYesEvent.java
// public class RatingDialogYesEvent {
// }
//
// Path: app/src/main/java/hu/supercluster/gameoflife/util/EventBus.java
// public class EventBus extends Bus {
// private static EventBus instance;
//
// private EventBus() {
// super(ThreadEnforcer.ANY);
// }
//
// public static EventBus getInstance() {
// if (instance == null) {
// instance = new EventBus();
// }
//
// return instance;
// }
//
// @Override
// public void unregister(Object object) {
// try {
// super.unregister(object);
//
// } catch (IllegalArgumentException e) {
// e.printStackTrace();
// }
// }
// }
// Path: app/src/main/java/hu/supercluster/gameoflife/app/rate/dialog/RatingDialog.java
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import org.androidannotations.annotations.EFragment;
import hu.supercluster.gameoflife.R;
import hu.supercluster.gameoflife.app.rate.event.RatingDialogLaterEvent;
import hu.supercluster.gameoflife.app.rate.event.RatingDialogNoEvent;
import hu.supercluster.gameoflife.app.rate.event.RatingDialogYesEvent;
import hu.supercluster.gameoflife.util.EventBus;
package hu.supercluster.gameoflife.app.rate.dialog;
@EFragment
public class RatingDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder
.setCancelable(false)
.setTitle(R.string.dialog_rate_title)
.setMessage(R.string.dialog_rate_body)
.setPositiveButton(R.string.dialog_rate_rate, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
EventBus.getInstance().post(new RatingDialogYesEvent());
dialog.dismiss();
}
})
.setNeutralButton(R.string.dialog_rate_later, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
EventBus.getInstance().post(new RatingDialogLaterEvent());
dialog.dismiss();
}
})
.setNegativeButton(R.string.dialog_rate_no_thanks, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) { | EventBus.getInstance().post(new RatingDialogNoEvent()); |
exxeleron/qJava | src/test/java/com/exxeleron/qjava/TestCollections.java | // Path: src/main/java/com/exxeleron/qjava/QKeyedTable.java
// public class KeyValuePair {
//
// private int index;
//
// KeyValuePair(final int index) {
// this.index = index;
// }
//
// /**
// * Returns index of the row.
// *
// * @return {@link int}
// */
// public int getRowIndex() {
// return index;
// }
//
// /**
// * Moves the row view to new index.
// *
// * @param index
// * the index to set
// */
// public void setRowIndex( final int index ) {
// if ( index < 0 || index > getRowsCount() ) {
// throw new IndexOutOfBoundsException();
// }
// this.index = index;
// }
//
// /**
// * Returns key from given pair.
// *
// * @return key
// */
// public QTable.Row getKey() {
// return keys.get(index);
// }
//
// /**
// * Returns value from given pair.
// *
// * @return value
// */
// public QTable.Row getValue() {
// return values.get(index);
// }
// }
//
// Path: src/main/java/com/exxeleron/qjava/QTable.java
// public class Row implements Iterable<Object> {
//
// private int rowIndex;
//
// /**
// * Creates row view for row with given index.
// *
// * @param rowIndex
// * index of the row
// */
// Row(final int rowIndex) {
// setRowIndex(rowIndex);
// }
//
// /**
// * Returns index of the row.
// *
// * @return {@link int}
// */
// public int getRowIndex() {
// return rowIndex;
// }
//
// /**
// * Moves the row view to new index.
// *
// * @param rowIndex
// * the rowIndex to set
// */
// public void setRowIndex( final int rowIndex ) {
// if ( rowIndex < 0 || rowIndex > rowsCount ) {
// throw new IndexOutOfBoundsException();
// }
// this.rowIndex = rowIndex;
// }
//
// /**
// * Creates a copy of entire row and returns it as an {@link Object} array.
// *
// * @return {@link Object}[] with copy of entire row
// */
// public Object[] toArray() {
// final int length = getLength();
// final Object[] row = new Object[length];
//
// for ( int i = 0; i < length; i++ ) {
// row[i] = get(i);
// }
//
// return row;
// }
//
// /**
// * Returns number of columns in the current {@link QTable}.
// *
// * @return number of columns
// */
// public int getLength() {
// return columns.length;
// }
//
// /**
// * Gets an object stored under specific index.
// *
// * @param index
// * 0 based index
// * @return object
// */
// public Object get( final int index ) {
// return Array.get(data[index], rowIndex);
// }
//
// /**
// * Sets an object stored under specific index.
// *
// * @param index
// * 0 based index
// * @param value
// * value to be set
// */
// public void set( final int index, final Object value ) {
// Array.set(data[index], rowIndex, value);
// }
//
// @Override
// public String toString() {
// return Utils.arrayToString(columns) + "!" + Utils.arrayToString(toArray());
// }
//
// /**
// * <p>
// * Returns an iterator over columns in a particular row in the table.
// * </p>
// *
// * <p>
// * Note that the iterator returned by this method will throw an {@link UnsupportedOperationException} in
// * response to its <code>remove</code> method.
// * </p>
// *
// * @see java.lang.Iterable#iterator()
// */
// public Iterator<Object> iterator() {
// return new Iterator<Object>() {
//
// int index = 0;
//
// public boolean hasNext() {
// return index < getLength();
// }
//
// public Object next() {
// if ( hasNext() ) {
// return Array.get(data[index++], rowIndex);
// } else {
// throw new NoSuchElementException();
// }
// }
//
// public void remove() {
// throw new UnsupportedOperationException();
// }
// };
// }
//
// }
| import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.lang.reflect.Array;
import java.util.Iterator;
import org.junit.Test;
import com.exxeleron.qjava.QKeyedTable.KeyValuePair;
import com.exxeleron.qjava.QTable.Row; |
assertEquals(t.getRowsCount(), i);
}
@Test
public void testQKeyedTable() {
final QKeyedTable t = new QKeyedTable(getTestTable(), getTestTable(new String[] { "ff", "ii", "s" }));
assertEquals(t, t);
assertEquals(t.getKeys(), getTestTable());
assertEquals(t.getValues(), getTestTable(new String[] { "ff", "ii", "s" }));
assertTrue(t.hasColumn("f"));
assertTrue(t.hasColumn("ff"));
assertFalse(t.hasColumn("unknown"));
assertEquals(0, t.getColumnIndex("f"));
assertEquals(3, t.getColumnIndex("ff"));
assertEquals(2, t.getColumnIndex("s"));
try {
t.getColumnIndex("unknown");
fail("NullPointerException was expected");
} catch ( NullPointerException e ) {
assertTrue(true);
} catch ( Exception e ) {
fail("NullPointerException was expected");
}
int i = 0; | // Path: src/main/java/com/exxeleron/qjava/QKeyedTable.java
// public class KeyValuePair {
//
// private int index;
//
// KeyValuePair(final int index) {
// this.index = index;
// }
//
// /**
// * Returns index of the row.
// *
// * @return {@link int}
// */
// public int getRowIndex() {
// return index;
// }
//
// /**
// * Moves the row view to new index.
// *
// * @param index
// * the index to set
// */
// public void setRowIndex( final int index ) {
// if ( index < 0 || index > getRowsCount() ) {
// throw new IndexOutOfBoundsException();
// }
// this.index = index;
// }
//
// /**
// * Returns key from given pair.
// *
// * @return key
// */
// public QTable.Row getKey() {
// return keys.get(index);
// }
//
// /**
// * Returns value from given pair.
// *
// * @return value
// */
// public QTable.Row getValue() {
// return values.get(index);
// }
// }
//
// Path: src/main/java/com/exxeleron/qjava/QTable.java
// public class Row implements Iterable<Object> {
//
// private int rowIndex;
//
// /**
// * Creates row view for row with given index.
// *
// * @param rowIndex
// * index of the row
// */
// Row(final int rowIndex) {
// setRowIndex(rowIndex);
// }
//
// /**
// * Returns index of the row.
// *
// * @return {@link int}
// */
// public int getRowIndex() {
// return rowIndex;
// }
//
// /**
// * Moves the row view to new index.
// *
// * @param rowIndex
// * the rowIndex to set
// */
// public void setRowIndex( final int rowIndex ) {
// if ( rowIndex < 0 || rowIndex > rowsCount ) {
// throw new IndexOutOfBoundsException();
// }
// this.rowIndex = rowIndex;
// }
//
// /**
// * Creates a copy of entire row and returns it as an {@link Object} array.
// *
// * @return {@link Object}[] with copy of entire row
// */
// public Object[] toArray() {
// final int length = getLength();
// final Object[] row = new Object[length];
//
// for ( int i = 0; i < length; i++ ) {
// row[i] = get(i);
// }
//
// return row;
// }
//
// /**
// * Returns number of columns in the current {@link QTable}.
// *
// * @return number of columns
// */
// public int getLength() {
// return columns.length;
// }
//
// /**
// * Gets an object stored under specific index.
// *
// * @param index
// * 0 based index
// * @return object
// */
// public Object get( final int index ) {
// return Array.get(data[index], rowIndex);
// }
//
// /**
// * Sets an object stored under specific index.
// *
// * @param index
// * 0 based index
// * @param value
// * value to be set
// */
// public void set( final int index, final Object value ) {
// Array.set(data[index], rowIndex, value);
// }
//
// @Override
// public String toString() {
// return Utils.arrayToString(columns) + "!" + Utils.arrayToString(toArray());
// }
//
// /**
// * <p>
// * Returns an iterator over columns in a particular row in the table.
// * </p>
// *
// * <p>
// * Note that the iterator returned by this method will throw an {@link UnsupportedOperationException} in
// * response to its <code>remove</code> method.
// * </p>
// *
// * @see java.lang.Iterable#iterator()
// */
// public Iterator<Object> iterator() {
// return new Iterator<Object>() {
//
// int index = 0;
//
// public boolean hasNext() {
// return index < getLength();
// }
//
// public Object next() {
// if ( hasNext() ) {
// return Array.get(data[index++], rowIndex);
// } else {
// throw new NoSuchElementException();
// }
// }
//
// public void remove() {
// throw new UnsupportedOperationException();
// }
// };
// }
//
// }
// Path: src/test/java/com/exxeleron/qjava/TestCollections.java
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.lang.reflect.Array;
import java.util.Iterator;
import org.junit.Test;
import com.exxeleron.qjava.QKeyedTable.KeyValuePair;
import com.exxeleron.qjava.QTable.Row;
assertEquals(t.getRowsCount(), i);
}
@Test
public void testQKeyedTable() {
final QKeyedTable t = new QKeyedTable(getTestTable(), getTestTable(new String[] { "ff", "ii", "s" }));
assertEquals(t, t);
assertEquals(t.getKeys(), getTestTable());
assertEquals(t.getValues(), getTestTable(new String[] { "ff", "ii", "s" }));
assertTrue(t.hasColumn("f"));
assertTrue(t.hasColumn("ff"));
assertFalse(t.hasColumn("unknown"));
assertEquals(0, t.getColumnIndex("f"));
assertEquals(3, t.getColumnIndex("ff"));
assertEquals(2, t.getColumnIndex("s"));
try {
t.getColumnIndex("unknown");
fail("NullPointerException was expected");
} catch ( NullPointerException e ) {
assertTrue(true);
} catch ( Exception e ) {
fail("NullPointerException was expected");
}
int i = 0; | final Iterator<KeyValuePair> it = t.iterator(); |
eroshenkoam/htmlelements | src/test/java/io/qameta/htmlelements/MatcherTest.java | // Path: src/test/java/io/qameta/htmlelements/example/element/SuggestItem.java
// public interface SuggestItem extends ExtendedWebElement<SuggestItem>{
//
// @FindBy(TestData.SUGGEST_ITEM_XPATH)
// HtmlElement title();
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/statement/Listener.java
// public interface Listener {
//
// default void beforeMethodCall(String description, Method method, Object[] args) {
// }
//
// default void onMethodFailed(String description, Method method, Throwable exception) {
// }
//
// default void afterMethodCall(String description, Method method) {
// }
//
// }
//
// Path: src/test/java/io/qameta/htmlelements/example/TestData.java
// public class TestData {
//
// public static final String SEARCH_ARROW_XPATH = "//form[contains(@class, 'search2 suggest2-form')]";
//
// public static final String SUGGEST_XPATH = "//div[@class='suggest']";
//
// public static final String SUGGEST_ITEM_XPATH = "//a";
//
// public static final String SEARCH_FORM_XPATH = "//div[@class='form']";
//
// public static final String SEARCH_FORM_TEMPLATE = "//div[@class='{{ className }}']";
//
// public static final String REQUEST_INPUT_XPATH = "//div[@class='input']";
//
//
// public static WebDriver mockDriver() {
//
// WebElement textInput = mockWebElement()
// .withText("text input")
// .withDisplayed(true)
// .build();
//
// List<WebElement> suggest = Arrays.asList(
// mockWebElement()
// .withChildElement(SUGGEST_ITEM_XPATH, mockWebElement().withText("first suggest item").build())
// .withText("first suggest")
// .withDisplayed(false, true)
// .build(),
// mockWebElement()
// .withChildElement(SUGGEST_ITEM_XPATH, mockWebElement().withText("second suggest item").build())
// .withText("second suggest")
// .withDisplayed(false, false, false, true)
// .build()
// );
//
// WebElement searchForm = mockWebElement()
// .withChildElement(REQUEST_INPUT_XPATH, textInput)
// .withText("searchForm")
// .build();
//
// WebElement searchArrow = mockWebElement()
// .withChildElements(SUGGEST_XPATH, suggest)
// .withChildElement(SEARCH_FORM_XPATH, searchForm)
// .withText("search-arro", "search", "search-arrow")
// .withDisplayed(true)
// .build();
//
//
// WebDriver driver = mock(WebDriver.class);
// when(driver.findElement(By.xpath(SEARCH_ARROW_XPATH))).thenReturn(searchArrow);
//
// return driver;
// }
//
// private static WebElement createWebElement(String text, Boolean displayed, Boolean... displayedNext) {
// WebElement webElement = mock(WebElement.class);
// when(webElement.getText()).thenReturn(text);
// when(webElement.toString()).thenReturn(text);
// when(webElement.isDisplayed()).thenReturn(displayed, displayedNext);
// return webElement;
// }
//
// public static class WebElementBuilder {
//
// public static WebElementBuilder mockWebElement() {
// return new WebElementBuilder();
// }
//
// private final WebElement element;
//
// public WebElementBuilder() {
// this.element = mock(WebElement.class);
// }
//
// public WebElementBuilder withText(String text, String... other) {
// when(getElement().getText()).thenReturn(text, other);
// return this;
// }
//
// public WebElementBuilder withDisplayed(boolean displayed, Boolean... other) {
// when(getElement().isDisplayed()).thenReturn(displayed, other);
// return this;
// }
//
// public WebElementBuilder withChildElement(String xpath, WebElement element) {
// when(getElement().findElement(By.xpath(xpath))).thenReturn(element);
// return this;
// }
//
// public WebElementBuilder withChildElements(String xpath, List<WebElement> elements) {
// when(getElement().findElements(By.xpath(xpath))).thenReturn(elements);
// return this;
// }
//
// private WebElement getElement() {
// return element;
// }
//
// public WebElement build() {
// return getElement();
// }
//
// }
// }
//
// Path: src/test/java/io/qameta/htmlelements/example/page/SearchPage.java
// @BaseUrl("http://www.base.url")
// public interface SearchPage extends WebPage {
//
// @Description("Поисковая строка")
// @FindBy(TestData.SEARCH_ARROW_XPATH)
// SearchArrow searchArrow();
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/matcher/DisplayedMatcher.java
// @Factory
// public static Matcher<WebElement> displayed() {
// return new DisplayedMatcher();
// }
//
// Path: src/main/java/io/qameta/htmlelements/matcher/HasTextMatcher.java
// @Factory
// public static Matcher<WebElement> hasText(final Matcher<String> textMatcher) {
// return new HasTextMatcher(textMatcher);
// }
| import io.qameta.htmlelements.example.element.SuggestItem;
import io.qameta.htmlelements.statement.Listener;
import org.openqa.selenium.WebDriver;
import io.qameta.htmlelements.example.TestData;
import io.qameta.htmlelements.example.page.SearchPage;
import org.junit.Test;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import java.lang.reflect.Method;
import static io.qameta.htmlelements.matcher.DisplayedMatcher.displayed;
import static io.qameta.htmlelements.matcher.HasTextMatcher.hasText;
import static java.lang.String.format;
import static org.hamcrest.Matchers.*; | package io.qameta.htmlelements;
public class MatcherTest {
private WebDriver driver = TestData.mockDriver();
@Test
@SuppressWarnings("unchecked")
public void testOutput() throws Exception {
WebPageFactory pageObjectFactory = new WebPageFactory()
.property("retry.timeout", "2")
.property("retry.polling", "100") | // Path: src/test/java/io/qameta/htmlelements/example/element/SuggestItem.java
// public interface SuggestItem extends ExtendedWebElement<SuggestItem>{
//
// @FindBy(TestData.SUGGEST_ITEM_XPATH)
// HtmlElement title();
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/statement/Listener.java
// public interface Listener {
//
// default void beforeMethodCall(String description, Method method, Object[] args) {
// }
//
// default void onMethodFailed(String description, Method method, Throwable exception) {
// }
//
// default void afterMethodCall(String description, Method method) {
// }
//
// }
//
// Path: src/test/java/io/qameta/htmlelements/example/TestData.java
// public class TestData {
//
// public static final String SEARCH_ARROW_XPATH = "//form[contains(@class, 'search2 suggest2-form')]";
//
// public static final String SUGGEST_XPATH = "//div[@class='suggest']";
//
// public static final String SUGGEST_ITEM_XPATH = "//a";
//
// public static final String SEARCH_FORM_XPATH = "//div[@class='form']";
//
// public static final String SEARCH_FORM_TEMPLATE = "//div[@class='{{ className }}']";
//
// public static final String REQUEST_INPUT_XPATH = "//div[@class='input']";
//
//
// public static WebDriver mockDriver() {
//
// WebElement textInput = mockWebElement()
// .withText("text input")
// .withDisplayed(true)
// .build();
//
// List<WebElement> suggest = Arrays.asList(
// mockWebElement()
// .withChildElement(SUGGEST_ITEM_XPATH, mockWebElement().withText("first suggest item").build())
// .withText("first suggest")
// .withDisplayed(false, true)
// .build(),
// mockWebElement()
// .withChildElement(SUGGEST_ITEM_XPATH, mockWebElement().withText("second suggest item").build())
// .withText("second suggest")
// .withDisplayed(false, false, false, true)
// .build()
// );
//
// WebElement searchForm = mockWebElement()
// .withChildElement(REQUEST_INPUT_XPATH, textInput)
// .withText("searchForm")
// .build();
//
// WebElement searchArrow = mockWebElement()
// .withChildElements(SUGGEST_XPATH, suggest)
// .withChildElement(SEARCH_FORM_XPATH, searchForm)
// .withText("search-arro", "search", "search-arrow")
// .withDisplayed(true)
// .build();
//
//
// WebDriver driver = mock(WebDriver.class);
// when(driver.findElement(By.xpath(SEARCH_ARROW_XPATH))).thenReturn(searchArrow);
//
// return driver;
// }
//
// private static WebElement createWebElement(String text, Boolean displayed, Boolean... displayedNext) {
// WebElement webElement = mock(WebElement.class);
// when(webElement.getText()).thenReturn(text);
// when(webElement.toString()).thenReturn(text);
// when(webElement.isDisplayed()).thenReturn(displayed, displayedNext);
// return webElement;
// }
//
// public static class WebElementBuilder {
//
// public static WebElementBuilder mockWebElement() {
// return new WebElementBuilder();
// }
//
// private final WebElement element;
//
// public WebElementBuilder() {
// this.element = mock(WebElement.class);
// }
//
// public WebElementBuilder withText(String text, String... other) {
// when(getElement().getText()).thenReturn(text, other);
// return this;
// }
//
// public WebElementBuilder withDisplayed(boolean displayed, Boolean... other) {
// when(getElement().isDisplayed()).thenReturn(displayed, other);
// return this;
// }
//
// public WebElementBuilder withChildElement(String xpath, WebElement element) {
// when(getElement().findElement(By.xpath(xpath))).thenReturn(element);
// return this;
// }
//
// public WebElementBuilder withChildElements(String xpath, List<WebElement> elements) {
// when(getElement().findElements(By.xpath(xpath))).thenReturn(elements);
// return this;
// }
//
// private WebElement getElement() {
// return element;
// }
//
// public WebElement build() {
// return getElement();
// }
//
// }
// }
//
// Path: src/test/java/io/qameta/htmlelements/example/page/SearchPage.java
// @BaseUrl("http://www.base.url")
// public interface SearchPage extends WebPage {
//
// @Description("Поисковая строка")
// @FindBy(TestData.SEARCH_ARROW_XPATH)
// SearchArrow searchArrow();
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/matcher/DisplayedMatcher.java
// @Factory
// public static Matcher<WebElement> displayed() {
// return new DisplayedMatcher();
// }
//
// Path: src/main/java/io/qameta/htmlelements/matcher/HasTextMatcher.java
// @Factory
// public static Matcher<WebElement> hasText(final Matcher<String> textMatcher) {
// return new HasTextMatcher(textMatcher);
// }
// Path: src/test/java/io/qameta/htmlelements/MatcherTest.java
import io.qameta.htmlelements.example.element.SuggestItem;
import io.qameta.htmlelements.statement.Listener;
import org.openqa.selenium.WebDriver;
import io.qameta.htmlelements.example.TestData;
import io.qameta.htmlelements.example.page.SearchPage;
import org.junit.Test;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import java.lang.reflect.Method;
import static io.qameta.htmlelements.matcher.DisplayedMatcher.displayed;
import static io.qameta.htmlelements.matcher.HasTextMatcher.hasText;
import static java.lang.String.format;
import static org.hamcrest.Matchers.*;
package io.qameta.htmlelements;
public class MatcherTest {
private WebDriver driver = TestData.mockDriver();
@Test
@SuppressWarnings("unchecked")
public void testOutput() throws Exception {
WebPageFactory pageObjectFactory = new WebPageFactory()
.property("retry.timeout", "2")
.property("retry.polling", "100") | .listener(new Listener() { |
eroshenkoam/htmlelements | src/main/java/io/qameta/htmlelements/extension/page/GoMethod.java | // Path: src/main/java/io/qameta/htmlelements/context/Context.java
// public class Context {
//
// public static final String DESCRIPTION_KEY = "description";
//
// public static final String LISTENERS_KEY = "listeners";
//
// public static final String PROPERTIES_KEY = "properties";
//
// public static final String PARAMETERS_KEY = "parameters";
//
// public static final String DRIVER_KEY = "driver";
//
// private Context parent;
//
// private Store store;
//
// private ExtensionRegistry registry;
//
// private Context() {
// this.store = new DefaultStore();
// }
//
// public Optional<Context> getParent() {
// return Optional.ofNullable(parent);
// }
//
// private void setParent(Context parent) {
// this.parent = parent;
// }
//
// public Store getStore() {
// return store;
// }
//
// public ExtensionRegistry getRegistry() {
// return registry;
// }
//
// private void setRegistry(ExtensionRegistry registry) {
// this.registry = registry;
// }
//
// public Context newChildContext(Method method, Class<?> proxyClass) {
// Context childContext = new Context();
// childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null));
// childContext.setRegistry(ExtensionRegistry.create(proxyClass));
// childContext.getRegistry().registerExtensions(method);
// childContext.setParent(this);
// //extension
// getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PROPERTIES_KEY, child);
// });
// getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PARAMETERS_KEY, child);
// });
// getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> {
// childContext.getStore().put(LISTENERS_KEY, listeners);
// });
// getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> {
// childContext.getStore().put(DRIVER_KEY, driver);
// });
// return childContext;
// }
//
// public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) {
// Context context = new Context();
// context.setRegistry(ExtensionRegistry.create(webPageClass));
// context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass));
// context.getStore().put(DRIVER_KEY, driver);
// return context;
// }
//
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/exception/WebPageException.java
// public class WebPageException extends RuntimeException {
//
// public WebPageException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/io/qameta/htmlelements/extension/MethodHandler.java
// public interface MethodHandler<R> {
//
// R handle(Context context, Object proxy, Method method, Object[] args) throws Throwable;
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/util/WebDriverUtils.java
// public class WebDriverUtils {
//
// public static boolean pageIsLoaded(WebDriver webDriver) {
// if (webDriver instanceof JavascriptExecutor) {
// Object result = ((JavascriptExecutor) webDriver)
// .executeScript("if (document.readyState) return document.readyState;");
// return result != null && "complete".equals(result);
// } else {
// throw new WebPageException("Driver must support javascript execution");
// }
// }
// }
| import com.google.common.base.Predicate;
import io.qameta.htmlelements.context.Context;
import io.qameta.htmlelements.exception.WebPageException;
import io.qameta.htmlelements.extension.HandleWith;
import io.qameta.htmlelements.extension.MethodHandler;
import io.qameta.htmlelements.util.WebDriverUtils;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import static io.qameta.htmlelements.context.Store.BASE_URL_KEY;
import static io.qameta.htmlelements.context.Store.DRIVER_KEY; | package io.qameta.htmlelements.extension.page;
/**
* @author ehborisov
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@HandleWith(GoMethod.Extension.class)
public @interface GoMethod {
| // Path: src/main/java/io/qameta/htmlelements/context/Context.java
// public class Context {
//
// public static final String DESCRIPTION_KEY = "description";
//
// public static final String LISTENERS_KEY = "listeners";
//
// public static final String PROPERTIES_KEY = "properties";
//
// public static final String PARAMETERS_KEY = "parameters";
//
// public static final String DRIVER_KEY = "driver";
//
// private Context parent;
//
// private Store store;
//
// private ExtensionRegistry registry;
//
// private Context() {
// this.store = new DefaultStore();
// }
//
// public Optional<Context> getParent() {
// return Optional.ofNullable(parent);
// }
//
// private void setParent(Context parent) {
// this.parent = parent;
// }
//
// public Store getStore() {
// return store;
// }
//
// public ExtensionRegistry getRegistry() {
// return registry;
// }
//
// private void setRegistry(ExtensionRegistry registry) {
// this.registry = registry;
// }
//
// public Context newChildContext(Method method, Class<?> proxyClass) {
// Context childContext = new Context();
// childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null));
// childContext.setRegistry(ExtensionRegistry.create(proxyClass));
// childContext.getRegistry().registerExtensions(method);
// childContext.setParent(this);
// //extension
// getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PROPERTIES_KEY, child);
// });
// getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PARAMETERS_KEY, child);
// });
// getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> {
// childContext.getStore().put(LISTENERS_KEY, listeners);
// });
// getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> {
// childContext.getStore().put(DRIVER_KEY, driver);
// });
// return childContext;
// }
//
// public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) {
// Context context = new Context();
// context.setRegistry(ExtensionRegistry.create(webPageClass));
// context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass));
// context.getStore().put(DRIVER_KEY, driver);
// return context;
// }
//
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/exception/WebPageException.java
// public class WebPageException extends RuntimeException {
//
// public WebPageException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/io/qameta/htmlelements/extension/MethodHandler.java
// public interface MethodHandler<R> {
//
// R handle(Context context, Object proxy, Method method, Object[] args) throws Throwable;
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/util/WebDriverUtils.java
// public class WebDriverUtils {
//
// public static boolean pageIsLoaded(WebDriver webDriver) {
// if (webDriver instanceof JavascriptExecutor) {
// Object result = ((JavascriptExecutor) webDriver)
// .executeScript("if (document.readyState) return document.readyState;");
// return result != null && "complete".equals(result);
// } else {
// throw new WebPageException("Driver must support javascript execution");
// }
// }
// }
// Path: src/main/java/io/qameta/htmlelements/extension/page/GoMethod.java
import com.google.common.base.Predicate;
import io.qameta.htmlelements.context.Context;
import io.qameta.htmlelements.exception.WebPageException;
import io.qameta.htmlelements.extension.HandleWith;
import io.qameta.htmlelements.extension.MethodHandler;
import io.qameta.htmlelements.util.WebDriverUtils;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import static io.qameta.htmlelements.context.Store.BASE_URL_KEY;
import static io.qameta.htmlelements.context.Store.DRIVER_KEY;
package io.qameta.htmlelements.extension.page;
/**
* @author ehborisov
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@HandleWith(GoMethod.Extension.class)
public @interface GoMethod {
| class Extension implements MethodHandler { |
eroshenkoam/htmlelements | src/main/java/io/qameta/htmlelements/extension/page/GoMethod.java | // Path: src/main/java/io/qameta/htmlelements/context/Context.java
// public class Context {
//
// public static final String DESCRIPTION_KEY = "description";
//
// public static final String LISTENERS_KEY = "listeners";
//
// public static final String PROPERTIES_KEY = "properties";
//
// public static final String PARAMETERS_KEY = "parameters";
//
// public static final String DRIVER_KEY = "driver";
//
// private Context parent;
//
// private Store store;
//
// private ExtensionRegistry registry;
//
// private Context() {
// this.store = new DefaultStore();
// }
//
// public Optional<Context> getParent() {
// return Optional.ofNullable(parent);
// }
//
// private void setParent(Context parent) {
// this.parent = parent;
// }
//
// public Store getStore() {
// return store;
// }
//
// public ExtensionRegistry getRegistry() {
// return registry;
// }
//
// private void setRegistry(ExtensionRegistry registry) {
// this.registry = registry;
// }
//
// public Context newChildContext(Method method, Class<?> proxyClass) {
// Context childContext = new Context();
// childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null));
// childContext.setRegistry(ExtensionRegistry.create(proxyClass));
// childContext.getRegistry().registerExtensions(method);
// childContext.setParent(this);
// //extension
// getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PROPERTIES_KEY, child);
// });
// getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PARAMETERS_KEY, child);
// });
// getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> {
// childContext.getStore().put(LISTENERS_KEY, listeners);
// });
// getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> {
// childContext.getStore().put(DRIVER_KEY, driver);
// });
// return childContext;
// }
//
// public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) {
// Context context = new Context();
// context.setRegistry(ExtensionRegistry.create(webPageClass));
// context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass));
// context.getStore().put(DRIVER_KEY, driver);
// return context;
// }
//
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/exception/WebPageException.java
// public class WebPageException extends RuntimeException {
//
// public WebPageException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/io/qameta/htmlelements/extension/MethodHandler.java
// public interface MethodHandler<R> {
//
// R handle(Context context, Object proxy, Method method, Object[] args) throws Throwable;
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/util/WebDriverUtils.java
// public class WebDriverUtils {
//
// public static boolean pageIsLoaded(WebDriver webDriver) {
// if (webDriver instanceof JavascriptExecutor) {
// Object result = ((JavascriptExecutor) webDriver)
// .executeScript("if (document.readyState) return document.readyState;");
// return result != null && "complete".equals(result);
// } else {
// throw new WebPageException("Driver must support javascript execution");
// }
// }
// }
| import com.google.common.base.Predicate;
import io.qameta.htmlelements.context.Context;
import io.qameta.htmlelements.exception.WebPageException;
import io.qameta.htmlelements.extension.HandleWith;
import io.qameta.htmlelements.extension.MethodHandler;
import io.qameta.htmlelements.util.WebDriverUtils;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import static io.qameta.htmlelements.context.Store.BASE_URL_KEY;
import static io.qameta.htmlelements.context.Store.DRIVER_KEY; | package io.qameta.htmlelements.extension.page;
/**
* @author ehborisov
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@HandleWith(GoMethod.Extension.class)
public @interface GoMethod {
class Extension implements MethodHandler {
@Override | // Path: src/main/java/io/qameta/htmlelements/context/Context.java
// public class Context {
//
// public static final String DESCRIPTION_KEY = "description";
//
// public static final String LISTENERS_KEY = "listeners";
//
// public static final String PROPERTIES_KEY = "properties";
//
// public static final String PARAMETERS_KEY = "parameters";
//
// public static final String DRIVER_KEY = "driver";
//
// private Context parent;
//
// private Store store;
//
// private ExtensionRegistry registry;
//
// private Context() {
// this.store = new DefaultStore();
// }
//
// public Optional<Context> getParent() {
// return Optional.ofNullable(parent);
// }
//
// private void setParent(Context parent) {
// this.parent = parent;
// }
//
// public Store getStore() {
// return store;
// }
//
// public ExtensionRegistry getRegistry() {
// return registry;
// }
//
// private void setRegistry(ExtensionRegistry registry) {
// this.registry = registry;
// }
//
// public Context newChildContext(Method method, Class<?> proxyClass) {
// Context childContext = new Context();
// childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null));
// childContext.setRegistry(ExtensionRegistry.create(proxyClass));
// childContext.getRegistry().registerExtensions(method);
// childContext.setParent(this);
// //extension
// getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PROPERTIES_KEY, child);
// });
// getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PARAMETERS_KEY, child);
// });
// getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> {
// childContext.getStore().put(LISTENERS_KEY, listeners);
// });
// getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> {
// childContext.getStore().put(DRIVER_KEY, driver);
// });
// return childContext;
// }
//
// public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) {
// Context context = new Context();
// context.setRegistry(ExtensionRegistry.create(webPageClass));
// context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass));
// context.getStore().put(DRIVER_KEY, driver);
// return context;
// }
//
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/exception/WebPageException.java
// public class WebPageException extends RuntimeException {
//
// public WebPageException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/io/qameta/htmlelements/extension/MethodHandler.java
// public interface MethodHandler<R> {
//
// R handle(Context context, Object proxy, Method method, Object[] args) throws Throwable;
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/util/WebDriverUtils.java
// public class WebDriverUtils {
//
// public static boolean pageIsLoaded(WebDriver webDriver) {
// if (webDriver instanceof JavascriptExecutor) {
// Object result = ((JavascriptExecutor) webDriver)
// .executeScript("if (document.readyState) return document.readyState;");
// return result != null && "complete".equals(result);
// } else {
// throw new WebPageException("Driver must support javascript execution");
// }
// }
// }
// Path: src/main/java/io/qameta/htmlelements/extension/page/GoMethod.java
import com.google.common.base.Predicate;
import io.qameta.htmlelements.context.Context;
import io.qameta.htmlelements.exception.WebPageException;
import io.qameta.htmlelements.extension.HandleWith;
import io.qameta.htmlelements.extension.MethodHandler;
import io.qameta.htmlelements.util.WebDriverUtils;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import static io.qameta.htmlelements.context.Store.BASE_URL_KEY;
import static io.qameta.htmlelements.context.Store.DRIVER_KEY;
package io.qameta.htmlelements.extension.page;
/**
* @author ehborisov
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@HandleWith(GoMethod.Extension.class)
public @interface GoMethod {
class Extension implements MethodHandler {
@Override | public Object handle(Context context, Object proxy, Method method, Object[] args) throws Throwable { |
eroshenkoam/htmlelements | src/main/java/io/qameta/htmlelements/extension/page/GoMethod.java | // Path: src/main/java/io/qameta/htmlelements/context/Context.java
// public class Context {
//
// public static final String DESCRIPTION_KEY = "description";
//
// public static final String LISTENERS_KEY = "listeners";
//
// public static final String PROPERTIES_KEY = "properties";
//
// public static final String PARAMETERS_KEY = "parameters";
//
// public static final String DRIVER_KEY = "driver";
//
// private Context parent;
//
// private Store store;
//
// private ExtensionRegistry registry;
//
// private Context() {
// this.store = new DefaultStore();
// }
//
// public Optional<Context> getParent() {
// return Optional.ofNullable(parent);
// }
//
// private void setParent(Context parent) {
// this.parent = parent;
// }
//
// public Store getStore() {
// return store;
// }
//
// public ExtensionRegistry getRegistry() {
// return registry;
// }
//
// private void setRegistry(ExtensionRegistry registry) {
// this.registry = registry;
// }
//
// public Context newChildContext(Method method, Class<?> proxyClass) {
// Context childContext = new Context();
// childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null));
// childContext.setRegistry(ExtensionRegistry.create(proxyClass));
// childContext.getRegistry().registerExtensions(method);
// childContext.setParent(this);
// //extension
// getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PROPERTIES_KEY, child);
// });
// getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PARAMETERS_KEY, child);
// });
// getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> {
// childContext.getStore().put(LISTENERS_KEY, listeners);
// });
// getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> {
// childContext.getStore().put(DRIVER_KEY, driver);
// });
// return childContext;
// }
//
// public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) {
// Context context = new Context();
// context.setRegistry(ExtensionRegistry.create(webPageClass));
// context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass));
// context.getStore().put(DRIVER_KEY, driver);
// return context;
// }
//
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/exception/WebPageException.java
// public class WebPageException extends RuntimeException {
//
// public WebPageException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/io/qameta/htmlelements/extension/MethodHandler.java
// public interface MethodHandler<R> {
//
// R handle(Context context, Object proxy, Method method, Object[] args) throws Throwable;
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/util/WebDriverUtils.java
// public class WebDriverUtils {
//
// public static boolean pageIsLoaded(WebDriver webDriver) {
// if (webDriver instanceof JavascriptExecutor) {
// Object result = ((JavascriptExecutor) webDriver)
// .executeScript("if (document.readyState) return document.readyState;");
// return result != null && "complete".equals(result);
// } else {
// throw new WebPageException("Driver must support javascript execution");
// }
// }
// }
| import com.google.common.base.Predicate;
import io.qameta.htmlelements.context.Context;
import io.qameta.htmlelements.exception.WebPageException;
import io.qameta.htmlelements.extension.HandleWith;
import io.qameta.htmlelements.extension.MethodHandler;
import io.qameta.htmlelements.util.WebDriverUtils;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import static io.qameta.htmlelements.context.Store.BASE_URL_KEY;
import static io.qameta.htmlelements.context.Store.DRIVER_KEY; | package io.qameta.htmlelements.extension.page;
/**
* @author ehborisov
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@HandleWith(GoMethod.Extension.class)
public @interface GoMethod {
class Extension implements MethodHandler {
@Override
public Object handle(Context context, Object proxy, Method method, Object[] args) throws Throwable {
String url = (String) context.getStore().get(BASE_URL_KEY) | // Path: src/main/java/io/qameta/htmlelements/context/Context.java
// public class Context {
//
// public static final String DESCRIPTION_KEY = "description";
//
// public static final String LISTENERS_KEY = "listeners";
//
// public static final String PROPERTIES_KEY = "properties";
//
// public static final String PARAMETERS_KEY = "parameters";
//
// public static final String DRIVER_KEY = "driver";
//
// private Context parent;
//
// private Store store;
//
// private ExtensionRegistry registry;
//
// private Context() {
// this.store = new DefaultStore();
// }
//
// public Optional<Context> getParent() {
// return Optional.ofNullable(parent);
// }
//
// private void setParent(Context parent) {
// this.parent = parent;
// }
//
// public Store getStore() {
// return store;
// }
//
// public ExtensionRegistry getRegistry() {
// return registry;
// }
//
// private void setRegistry(ExtensionRegistry registry) {
// this.registry = registry;
// }
//
// public Context newChildContext(Method method, Class<?> proxyClass) {
// Context childContext = new Context();
// childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null));
// childContext.setRegistry(ExtensionRegistry.create(proxyClass));
// childContext.getRegistry().registerExtensions(method);
// childContext.setParent(this);
// //extension
// getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PROPERTIES_KEY, child);
// });
// getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PARAMETERS_KEY, child);
// });
// getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> {
// childContext.getStore().put(LISTENERS_KEY, listeners);
// });
// getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> {
// childContext.getStore().put(DRIVER_KEY, driver);
// });
// return childContext;
// }
//
// public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) {
// Context context = new Context();
// context.setRegistry(ExtensionRegistry.create(webPageClass));
// context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass));
// context.getStore().put(DRIVER_KEY, driver);
// return context;
// }
//
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/exception/WebPageException.java
// public class WebPageException extends RuntimeException {
//
// public WebPageException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/io/qameta/htmlelements/extension/MethodHandler.java
// public interface MethodHandler<R> {
//
// R handle(Context context, Object proxy, Method method, Object[] args) throws Throwable;
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/util/WebDriverUtils.java
// public class WebDriverUtils {
//
// public static boolean pageIsLoaded(WebDriver webDriver) {
// if (webDriver instanceof JavascriptExecutor) {
// Object result = ((JavascriptExecutor) webDriver)
// .executeScript("if (document.readyState) return document.readyState;");
// return result != null && "complete".equals(result);
// } else {
// throw new WebPageException("Driver must support javascript execution");
// }
// }
// }
// Path: src/main/java/io/qameta/htmlelements/extension/page/GoMethod.java
import com.google.common.base.Predicate;
import io.qameta.htmlelements.context.Context;
import io.qameta.htmlelements.exception.WebPageException;
import io.qameta.htmlelements.extension.HandleWith;
import io.qameta.htmlelements.extension.MethodHandler;
import io.qameta.htmlelements.util.WebDriverUtils;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import static io.qameta.htmlelements.context.Store.BASE_URL_KEY;
import static io.qameta.htmlelements.context.Store.DRIVER_KEY;
package io.qameta.htmlelements.extension.page;
/**
* @author ehborisov
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@HandleWith(GoMethod.Extension.class)
public @interface GoMethod {
class Extension implements MethodHandler {
@Override
public Object handle(Context context, Object proxy, Method method, Object[] args) throws Throwable {
String url = (String) context.getStore().get(BASE_URL_KEY) | .orElseThrow(() -> new WebPageException("BaseUrl annotation is not declared for this web page")); |
eroshenkoam/htmlelements | src/main/java/io/qameta/htmlelements/extension/page/GoMethod.java | // Path: src/main/java/io/qameta/htmlelements/context/Context.java
// public class Context {
//
// public static final String DESCRIPTION_KEY = "description";
//
// public static final String LISTENERS_KEY = "listeners";
//
// public static final String PROPERTIES_KEY = "properties";
//
// public static final String PARAMETERS_KEY = "parameters";
//
// public static final String DRIVER_KEY = "driver";
//
// private Context parent;
//
// private Store store;
//
// private ExtensionRegistry registry;
//
// private Context() {
// this.store = new DefaultStore();
// }
//
// public Optional<Context> getParent() {
// return Optional.ofNullable(parent);
// }
//
// private void setParent(Context parent) {
// this.parent = parent;
// }
//
// public Store getStore() {
// return store;
// }
//
// public ExtensionRegistry getRegistry() {
// return registry;
// }
//
// private void setRegistry(ExtensionRegistry registry) {
// this.registry = registry;
// }
//
// public Context newChildContext(Method method, Class<?> proxyClass) {
// Context childContext = new Context();
// childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null));
// childContext.setRegistry(ExtensionRegistry.create(proxyClass));
// childContext.getRegistry().registerExtensions(method);
// childContext.setParent(this);
// //extension
// getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PROPERTIES_KEY, child);
// });
// getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PARAMETERS_KEY, child);
// });
// getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> {
// childContext.getStore().put(LISTENERS_KEY, listeners);
// });
// getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> {
// childContext.getStore().put(DRIVER_KEY, driver);
// });
// return childContext;
// }
//
// public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) {
// Context context = new Context();
// context.setRegistry(ExtensionRegistry.create(webPageClass));
// context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass));
// context.getStore().put(DRIVER_KEY, driver);
// return context;
// }
//
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/exception/WebPageException.java
// public class WebPageException extends RuntimeException {
//
// public WebPageException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/io/qameta/htmlelements/extension/MethodHandler.java
// public interface MethodHandler<R> {
//
// R handle(Context context, Object proxy, Method method, Object[] args) throws Throwable;
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/util/WebDriverUtils.java
// public class WebDriverUtils {
//
// public static boolean pageIsLoaded(WebDriver webDriver) {
// if (webDriver instanceof JavascriptExecutor) {
// Object result = ((JavascriptExecutor) webDriver)
// .executeScript("if (document.readyState) return document.readyState;");
// return result != null && "complete".equals(result);
// } else {
// throw new WebPageException("Driver must support javascript execution");
// }
// }
// }
| import com.google.common.base.Predicate;
import io.qameta.htmlelements.context.Context;
import io.qameta.htmlelements.exception.WebPageException;
import io.qameta.htmlelements.extension.HandleWith;
import io.qameta.htmlelements.extension.MethodHandler;
import io.qameta.htmlelements.util.WebDriverUtils;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import static io.qameta.htmlelements.context.Store.BASE_URL_KEY;
import static io.qameta.htmlelements.context.Store.DRIVER_KEY; | package io.qameta.htmlelements.extension.page;
/**
* @author ehborisov
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@HandleWith(GoMethod.Extension.class)
public @interface GoMethod {
class Extension implements MethodHandler {
@Override
public Object handle(Context context, Object proxy, Method method, Object[] args) throws Throwable {
String url = (String) context.getStore().get(BASE_URL_KEY)
.orElseThrow(() -> new WebPageException("BaseUrl annotation is not declared for this web page"));
WebDriver driver = context.getStore().get(DRIVER_KEY, WebDriver.class)
.orElseThrow(() -> new WebPageException("WebDriver is missing"));
driver.get(url);
new WebDriverWait(driver, 5)
.ignoring(Throwable.class)
.withMessage(String.format("Couldn't wait for page with url %s to load", url))
.until((Predicate<WebDriver>) (d) -> (d != null && d.getCurrentUrl().equals(url)) && | // Path: src/main/java/io/qameta/htmlelements/context/Context.java
// public class Context {
//
// public static final String DESCRIPTION_KEY = "description";
//
// public static final String LISTENERS_KEY = "listeners";
//
// public static final String PROPERTIES_KEY = "properties";
//
// public static final String PARAMETERS_KEY = "parameters";
//
// public static final String DRIVER_KEY = "driver";
//
// private Context parent;
//
// private Store store;
//
// private ExtensionRegistry registry;
//
// private Context() {
// this.store = new DefaultStore();
// }
//
// public Optional<Context> getParent() {
// return Optional.ofNullable(parent);
// }
//
// private void setParent(Context parent) {
// this.parent = parent;
// }
//
// public Store getStore() {
// return store;
// }
//
// public ExtensionRegistry getRegistry() {
// return registry;
// }
//
// private void setRegistry(ExtensionRegistry registry) {
// this.registry = registry;
// }
//
// public Context newChildContext(Method method, Class<?> proxyClass) {
// Context childContext = new Context();
// childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null));
// childContext.setRegistry(ExtensionRegistry.create(proxyClass));
// childContext.getRegistry().registerExtensions(method);
// childContext.setParent(this);
// //extension
// getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PROPERTIES_KEY, child);
// });
// getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PARAMETERS_KEY, child);
// });
// getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> {
// childContext.getStore().put(LISTENERS_KEY, listeners);
// });
// getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> {
// childContext.getStore().put(DRIVER_KEY, driver);
// });
// return childContext;
// }
//
// public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) {
// Context context = new Context();
// context.setRegistry(ExtensionRegistry.create(webPageClass));
// context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass));
// context.getStore().put(DRIVER_KEY, driver);
// return context;
// }
//
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/exception/WebPageException.java
// public class WebPageException extends RuntimeException {
//
// public WebPageException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/io/qameta/htmlelements/extension/MethodHandler.java
// public interface MethodHandler<R> {
//
// R handle(Context context, Object proxy, Method method, Object[] args) throws Throwable;
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/util/WebDriverUtils.java
// public class WebDriverUtils {
//
// public static boolean pageIsLoaded(WebDriver webDriver) {
// if (webDriver instanceof JavascriptExecutor) {
// Object result = ((JavascriptExecutor) webDriver)
// .executeScript("if (document.readyState) return document.readyState;");
// return result != null && "complete".equals(result);
// } else {
// throw new WebPageException("Driver must support javascript execution");
// }
// }
// }
// Path: src/main/java/io/qameta/htmlelements/extension/page/GoMethod.java
import com.google.common.base.Predicate;
import io.qameta.htmlelements.context.Context;
import io.qameta.htmlelements.exception.WebPageException;
import io.qameta.htmlelements.extension.HandleWith;
import io.qameta.htmlelements.extension.MethodHandler;
import io.qameta.htmlelements.util.WebDriverUtils;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import static io.qameta.htmlelements.context.Store.BASE_URL_KEY;
import static io.qameta.htmlelements.context.Store.DRIVER_KEY;
package io.qameta.htmlelements.extension.page;
/**
* @author ehborisov
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@HandleWith(GoMethod.Extension.class)
public @interface GoMethod {
class Extension implements MethodHandler {
@Override
public Object handle(Context context, Object proxy, Method method, Object[] args) throws Throwable {
String url = (String) context.getStore().get(BASE_URL_KEY)
.orElseThrow(() -> new WebPageException("BaseUrl annotation is not declared for this web page"));
WebDriver driver = context.getStore().get(DRIVER_KEY, WebDriver.class)
.orElseThrow(() -> new WebPageException("WebDriver is missing"));
driver.get(url);
new WebDriverWait(driver, 5)
.ignoring(Throwable.class)
.withMessage(String.format("Couldn't wait for page with url %s to load", url))
.until((Predicate<WebDriver>) (d) -> (d != null && d.getCurrentUrl().equals(url)) && | WebDriverUtils.pageIsLoaded(d)); |
eroshenkoam/htmlelements | src/main/java/io/qameta/htmlelements/extension/Retry.java | // Path: src/main/java/io/qameta/htmlelements/context/Context.java
// public class Context {
//
// public static final String DESCRIPTION_KEY = "description";
//
// public static final String LISTENERS_KEY = "listeners";
//
// public static final String PROPERTIES_KEY = "properties";
//
// public static final String PARAMETERS_KEY = "parameters";
//
// public static final String DRIVER_KEY = "driver";
//
// private Context parent;
//
// private Store store;
//
// private ExtensionRegistry registry;
//
// private Context() {
// this.store = new DefaultStore();
// }
//
// public Optional<Context> getParent() {
// return Optional.ofNullable(parent);
// }
//
// private void setParent(Context parent) {
// this.parent = parent;
// }
//
// public Store getStore() {
// return store;
// }
//
// public ExtensionRegistry getRegistry() {
// return registry;
// }
//
// private void setRegistry(ExtensionRegistry registry) {
// this.registry = registry;
// }
//
// public Context newChildContext(Method method, Class<?> proxyClass) {
// Context childContext = new Context();
// childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null));
// childContext.setRegistry(ExtensionRegistry.create(proxyClass));
// childContext.getRegistry().registerExtensions(method);
// childContext.setParent(this);
// //extension
// getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PROPERTIES_KEY, child);
// });
// getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PARAMETERS_KEY, child);
// });
// getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> {
// childContext.getStore().put(LISTENERS_KEY, listeners);
// });
// getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> {
// childContext.getStore().put(DRIVER_KEY, driver);
// });
// return childContext;
// }
//
// public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) {
// Context context = new Context();
// context.setRegistry(ExtensionRegistry.create(webPageClass));
// context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass));
// context.getStore().put(DRIVER_KEY, driver);
// return context;
// }
//
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/statement/RetryStatement.java
// public class RetryStatement implements StatementWrapper {
//
// public static final String TIMEOUT_KEY = "retry.timeout";
//
// public static final String POLLING_KEY = "retry.polling";
//
// private Duration timeout;
//
// private Duration polling;
//
// private List<Class<? extends Throwable>> ignoring;
//
// public RetryStatement(Properties properties) {
// this.timeout = new Duration(Long.parseLong(properties.getProperty(TIMEOUT_KEY, "5")), TimeUnit.SECONDS);
// this.polling = new Duration(Long.parseLong(properties.getProperty(POLLING_KEY, "250")), TimeUnit.MILLISECONDS);
// this.ignoring = new ArrayList<>();
// }
//
// public RetryStatement withTimeout(long time, TimeUnit unit) {
// this.timeout = new Duration(time, unit);
// return this;
// }
//
// public RetryStatement pollingEvery(long time, TimeUnit unit) {
// this.polling = new Duration(time, unit);
// return this;
// }
//
// @SafeVarargs
// public final RetryStatement ignoring(Class<? extends Throwable>... exceptionType) {
// this.ignoring.addAll(Arrays.asList(exceptionType));
// return this;
// }
//
// @Override
// public Statement apply(Statement statement) throws Throwable {
// return () -> {
// Clock clock = new SystemClock();
// long end = clock.laterBy(timeout.in(TimeUnit.MILLISECONDS));
// Throwable lastException;
// do {
// try {
// return statement.evaluate();
// } catch (Throwable e) {
// lastException = e;
// if (ignoring.stream().anyMatch(clazz -> clazz.isInstance(e))) {
// try {
// Thread.sleep(polling.in(TimeUnit.MILLISECONDS));
// } catch (InterruptedException i) {
// break;
// }
// } else {
// Throwables.propagate(e);
// }
// }
// } while ((clock.isNowBefore(end)));
// throw lastException;
// };
// }
//
// }
| import io.qameta.htmlelements.context.Context;
import io.qameta.htmlelements.statement.RetryStatement;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.util.Properties; | package io.qameta.htmlelements.extension;
/**
* eroshenkoam
* 22.03.17
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@ExtendWith(Retry.Extension.class)
public @interface Retry {
int timeoutInSeconds() default 5;
int poolingInMillis() default 250;
Class<? extends Throwable>[] ignoring() default {};
class Extension implements ContextEnricher {
@Override | // Path: src/main/java/io/qameta/htmlelements/context/Context.java
// public class Context {
//
// public static final String DESCRIPTION_KEY = "description";
//
// public static final String LISTENERS_KEY = "listeners";
//
// public static final String PROPERTIES_KEY = "properties";
//
// public static final String PARAMETERS_KEY = "parameters";
//
// public static final String DRIVER_KEY = "driver";
//
// private Context parent;
//
// private Store store;
//
// private ExtensionRegistry registry;
//
// private Context() {
// this.store = new DefaultStore();
// }
//
// public Optional<Context> getParent() {
// return Optional.ofNullable(parent);
// }
//
// private void setParent(Context parent) {
// this.parent = parent;
// }
//
// public Store getStore() {
// return store;
// }
//
// public ExtensionRegistry getRegistry() {
// return registry;
// }
//
// private void setRegistry(ExtensionRegistry registry) {
// this.registry = registry;
// }
//
// public Context newChildContext(Method method, Class<?> proxyClass) {
// Context childContext = new Context();
// childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null));
// childContext.setRegistry(ExtensionRegistry.create(proxyClass));
// childContext.getRegistry().registerExtensions(method);
// childContext.setParent(this);
// //extension
// getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PROPERTIES_KEY, child);
// });
// getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PARAMETERS_KEY, child);
// });
// getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> {
// childContext.getStore().put(LISTENERS_KEY, listeners);
// });
// getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> {
// childContext.getStore().put(DRIVER_KEY, driver);
// });
// return childContext;
// }
//
// public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) {
// Context context = new Context();
// context.setRegistry(ExtensionRegistry.create(webPageClass));
// context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass));
// context.getStore().put(DRIVER_KEY, driver);
// return context;
// }
//
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/statement/RetryStatement.java
// public class RetryStatement implements StatementWrapper {
//
// public static final String TIMEOUT_KEY = "retry.timeout";
//
// public static final String POLLING_KEY = "retry.polling";
//
// private Duration timeout;
//
// private Duration polling;
//
// private List<Class<? extends Throwable>> ignoring;
//
// public RetryStatement(Properties properties) {
// this.timeout = new Duration(Long.parseLong(properties.getProperty(TIMEOUT_KEY, "5")), TimeUnit.SECONDS);
// this.polling = new Duration(Long.parseLong(properties.getProperty(POLLING_KEY, "250")), TimeUnit.MILLISECONDS);
// this.ignoring = new ArrayList<>();
// }
//
// public RetryStatement withTimeout(long time, TimeUnit unit) {
// this.timeout = new Duration(time, unit);
// return this;
// }
//
// public RetryStatement pollingEvery(long time, TimeUnit unit) {
// this.polling = new Duration(time, unit);
// return this;
// }
//
// @SafeVarargs
// public final RetryStatement ignoring(Class<? extends Throwable>... exceptionType) {
// this.ignoring.addAll(Arrays.asList(exceptionType));
// return this;
// }
//
// @Override
// public Statement apply(Statement statement) throws Throwable {
// return () -> {
// Clock clock = new SystemClock();
// long end = clock.laterBy(timeout.in(TimeUnit.MILLISECONDS));
// Throwable lastException;
// do {
// try {
// return statement.evaluate();
// } catch (Throwable e) {
// lastException = e;
// if (ignoring.stream().anyMatch(clazz -> clazz.isInstance(e))) {
// try {
// Thread.sleep(polling.in(TimeUnit.MILLISECONDS));
// } catch (InterruptedException i) {
// break;
// }
// } else {
// Throwables.propagate(e);
// }
// }
// } while ((clock.isNowBefore(end)));
// throw lastException;
// };
// }
//
// }
// Path: src/main/java/io/qameta/htmlelements/extension/Retry.java
import io.qameta.htmlelements.context.Context;
import io.qameta.htmlelements.statement.RetryStatement;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.util.Properties;
package io.qameta.htmlelements.extension;
/**
* eroshenkoam
* 22.03.17
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@ExtendWith(Retry.Extension.class)
public @interface Retry {
int timeoutInSeconds() default 5;
int poolingInMillis() default 250;
Class<? extends Throwable>[] ignoring() default {};
class Extension implements ContextEnricher {
@Override | public void enrich(Context context, Method method, Object[] args) { |
eroshenkoam/htmlelements | src/main/java/io/qameta/htmlelements/extension/Retry.java | // Path: src/main/java/io/qameta/htmlelements/context/Context.java
// public class Context {
//
// public static final String DESCRIPTION_KEY = "description";
//
// public static final String LISTENERS_KEY = "listeners";
//
// public static final String PROPERTIES_KEY = "properties";
//
// public static final String PARAMETERS_KEY = "parameters";
//
// public static final String DRIVER_KEY = "driver";
//
// private Context parent;
//
// private Store store;
//
// private ExtensionRegistry registry;
//
// private Context() {
// this.store = new DefaultStore();
// }
//
// public Optional<Context> getParent() {
// return Optional.ofNullable(parent);
// }
//
// private void setParent(Context parent) {
// this.parent = parent;
// }
//
// public Store getStore() {
// return store;
// }
//
// public ExtensionRegistry getRegistry() {
// return registry;
// }
//
// private void setRegistry(ExtensionRegistry registry) {
// this.registry = registry;
// }
//
// public Context newChildContext(Method method, Class<?> proxyClass) {
// Context childContext = new Context();
// childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null));
// childContext.setRegistry(ExtensionRegistry.create(proxyClass));
// childContext.getRegistry().registerExtensions(method);
// childContext.setParent(this);
// //extension
// getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PROPERTIES_KEY, child);
// });
// getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PARAMETERS_KEY, child);
// });
// getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> {
// childContext.getStore().put(LISTENERS_KEY, listeners);
// });
// getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> {
// childContext.getStore().put(DRIVER_KEY, driver);
// });
// return childContext;
// }
//
// public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) {
// Context context = new Context();
// context.setRegistry(ExtensionRegistry.create(webPageClass));
// context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass));
// context.getStore().put(DRIVER_KEY, driver);
// return context;
// }
//
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/statement/RetryStatement.java
// public class RetryStatement implements StatementWrapper {
//
// public static final String TIMEOUT_KEY = "retry.timeout";
//
// public static final String POLLING_KEY = "retry.polling";
//
// private Duration timeout;
//
// private Duration polling;
//
// private List<Class<? extends Throwable>> ignoring;
//
// public RetryStatement(Properties properties) {
// this.timeout = new Duration(Long.parseLong(properties.getProperty(TIMEOUT_KEY, "5")), TimeUnit.SECONDS);
// this.polling = new Duration(Long.parseLong(properties.getProperty(POLLING_KEY, "250")), TimeUnit.MILLISECONDS);
// this.ignoring = new ArrayList<>();
// }
//
// public RetryStatement withTimeout(long time, TimeUnit unit) {
// this.timeout = new Duration(time, unit);
// return this;
// }
//
// public RetryStatement pollingEvery(long time, TimeUnit unit) {
// this.polling = new Duration(time, unit);
// return this;
// }
//
// @SafeVarargs
// public final RetryStatement ignoring(Class<? extends Throwable>... exceptionType) {
// this.ignoring.addAll(Arrays.asList(exceptionType));
// return this;
// }
//
// @Override
// public Statement apply(Statement statement) throws Throwable {
// return () -> {
// Clock clock = new SystemClock();
// long end = clock.laterBy(timeout.in(TimeUnit.MILLISECONDS));
// Throwable lastException;
// do {
// try {
// return statement.evaluate();
// } catch (Throwable e) {
// lastException = e;
// if (ignoring.stream().anyMatch(clazz -> clazz.isInstance(e))) {
// try {
// Thread.sleep(polling.in(TimeUnit.MILLISECONDS));
// } catch (InterruptedException i) {
// break;
// }
// } else {
// Throwables.propagate(e);
// }
// }
// } while ((clock.isNowBefore(end)));
// throw lastException;
// };
// }
//
// }
| import io.qameta.htmlelements.context.Context;
import io.qameta.htmlelements.statement.RetryStatement;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.util.Properties; | package io.qameta.htmlelements.extension;
/**
* eroshenkoam
* 22.03.17
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@ExtendWith(Retry.Extension.class)
public @interface Retry {
int timeoutInSeconds() default 5;
int poolingInMillis() default 250;
Class<? extends Throwable>[] ignoring() default {};
class Extension implements ContextEnricher {
@Override
public void enrich(Context context, Method method, Object[] args) {
if (method.isAnnotationPresent(Retry.class)) {
Retry retry = method.getAnnotation(Retry.class);
context.getStore().get(Context.PROPERTIES_KEY, Properties.class).ifPresent(properties -> { | // Path: src/main/java/io/qameta/htmlelements/context/Context.java
// public class Context {
//
// public static final String DESCRIPTION_KEY = "description";
//
// public static final String LISTENERS_KEY = "listeners";
//
// public static final String PROPERTIES_KEY = "properties";
//
// public static final String PARAMETERS_KEY = "parameters";
//
// public static final String DRIVER_KEY = "driver";
//
// private Context parent;
//
// private Store store;
//
// private ExtensionRegistry registry;
//
// private Context() {
// this.store = new DefaultStore();
// }
//
// public Optional<Context> getParent() {
// return Optional.ofNullable(parent);
// }
//
// private void setParent(Context parent) {
// this.parent = parent;
// }
//
// public Store getStore() {
// return store;
// }
//
// public ExtensionRegistry getRegistry() {
// return registry;
// }
//
// private void setRegistry(ExtensionRegistry registry) {
// this.registry = registry;
// }
//
// public Context newChildContext(Method method, Class<?> proxyClass) {
// Context childContext = new Context();
// childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null));
// childContext.setRegistry(ExtensionRegistry.create(proxyClass));
// childContext.getRegistry().registerExtensions(method);
// childContext.setParent(this);
// //extension
// getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PROPERTIES_KEY, child);
// });
// getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PARAMETERS_KEY, child);
// });
// getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> {
// childContext.getStore().put(LISTENERS_KEY, listeners);
// });
// getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> {
// childContext.getStore().put(DRIVER_KEY, driver);
// });
// return childContext;
// }
//
// public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) {
// Context context = new Context();
// context.setRegistry(ExtensionRegistry.create(webPageClass));
// context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass));
// context.getStore().put(DRIVER_KEY, driver);
// return context;
// }
//
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/statement/RetryStatement.java
// public class RetryStatement implements StatementWrapper {
//
// public static final String TIMEOUT_KEY = "retry.timeout";
//
// public static final String POLLING_KEY = "retry.polling";
//
// private Duration timeout;
//
// private Duration polling;
//
// private List<Class<? extends Throwable>> ignoring;
//
// public RetryStatement(Properties properties) {
// this.timeout = new Duration(Long.parseLong(properties.getProperty(TIMEOUT_KEY, "5")), TimeUnit.SECONDS);
// this.polling = new Duration(Long.parseLong(properties.getProperty(POLLING_KEY, "250")), TimeUnit.MILLISECONDS);
// this.ignoring = new ArrayList<>();
// }
//
// public RetryStatement withTimeout(long time, TimeUnit unit) {
// this.timeout = new Duration(time, unit);
// return this;
// }
//
// public RetryStatement pollingEvery(long time, TimeUnit unit) {
// this.polling = new Duration(time, unit);
// return this;
// }
//
// @SafeVarargs
// public final RetryStatement ignoring(Class<? extends Throwable>... exceptionType) {
// this.ignoring.addAll(Arrays.asList(exceptionType));
// return this;
// }
//
// @Override
// public Statement apply(Statement statement) throws Throwable {
// return () -> {
// Clock clock = new SystemClock();
// long end = clock.laterBy(timeout.in(TimeUnit.MILLISECONDS));
// Throwable lastException;
// do {
// try {
// return statement.evaluate();
// } catch (Throwable e) {
// lastException = e;
// if (ignoring.stream().anyMatch(clazz -> clazz.isInstance(e))) {
// try {
// Thread.sleep(polling.in(TimeUnit.MILLISECONDS));
// } catch (InterruptedException i) {
// break;
// }
// } else {
// Throwables.propagate(e);
// }
// }
// } while ((clock.isNowBefore(end)));
// throw lastException;
// };
// }
//
// }
// Path: src/main/java/io/qameta/htmlelements/extension/Retry.java
import io.qameta.htmlelements.context.Context;
import io.qameta.htmlelements.statement.RetryStatement;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.util.Properties;
package io.qameta.htmlelements.extension;
/**
* eroshenkoam
* 22.03.17
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@ExtendWith(Retry.Extension.class)
public @interface Retry {
int timeoutInSeconds() default 5;
int poolingInMillis() default 250;
Class<? extends Throwable>[] ignoring() default {};
class Extension implements ContextEnricher {
@Override
public void enrich(Context context, Method method, Object[] args) {
if (method.isAnnotationPresent(Retry.class)) {
Retry retry = method.getAnnotation(Retry.class);
context.getStore().get(Context.PROPERTIES_KEY, Properties.class).ifPresent(properties -> { | properties.setProperty(RetryStatement.TIMEOUT_KEY, retry.timeoutInSeconds() + ""); |
eroshenkoam/htmlelements | src/main/java/io/qameta/htmlelements/extension/page/IsAtMethod.java | // Path: src/main/java/io/qameta/htmlelements/context/Context.java
// public class Context {
//
// public static final String DESCRIPTION_KEY = "description";
//
// public static final String LISTENERS_KEY = "listeners";
//
// public static final String PROPERTIES_KEY = "properties";
//
// public static final String PARAMETERS_KEY = "parameters";
//
// public static final String DRIVER_KEY = "driver";
//
// private Context parent;
//
// private Store store;
//
// private ExtensionRegistry registry;
//
// private Context() {
// this.store = new DefaultStore();
// }
//
// public Optional<Context> getParent() {
// return Optional.ofNullable(parent);
// }
//
// private void setParent(Context parent) {
// this.parent = parent;
// }
//
// public Store getStore() {
// return store;
// }
//
// public ExtensionRegistry getRegistry() {
// return registry;
// }
//
// private void setRegistry(ExtensionRegistry registry) {
// this.registry = registry;
// }
//
// public Context newChildContext(Method method, Class<?> proxyClass) {
// Context childContext = new Context();
// childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null));
// childContext.setRegistry(ExtensionRegistry.create(proxyClass));
// childContext.getRegistry().registerExtensions(method);
// childContext.setParent(this);
// //extension
// getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PROPERTIES_KEY, child);
// });
// getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PARAMETERS_KEY, child);
// });
// getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> {
// childContext.getStore().put(LISTENERS_KEY, listeners);
// });
// getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> {
// childContext.getStore().put(DRIVER_KEY, driver);
// });
// return childContext;
// }
//
// public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) {
// Context context = new Context();
// context.setRegistry(ExtensionRegistry.create(webPageClass));
// context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass));
// context.getStore().put(DRIVER_KEY, driver);
// return context;
// }
//
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/exception/WebPageException.java
// public class WebPageException extends RuntimeException {
//
// public WebPageException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/io/qameta/htmlelements/extension/MethodHandler.java
// public interface MethodHandler<R> {
//
// R handle(Context context, Object proxy, Method method, Object[] args) throws Throwable;
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/util/WebDriverUtils.java
// public class WebDriverUtils {
//
// public static boolean pageIsLoaded(WebDriver webDriver) {
// if (webDriver instanceof JavascriptExecutor) {
// Object result = ((JavascriptExecutor) webDriver)
// .executeScript("if (document.readyState) return document.readyState;");
// return result != null && "complete".equals(result);
// } else {
// throw new WebPageException("Driver must support javascript execution");
// }
// }
// }
| import com.google.common.base.Predicate;
import io.qameta.htmlelements.context.Context;
import io.qameta.htmlelements.exception.WebPageException;
import io.qameta.htmlelements.extension.HandleWith;
import io.qameta.htmlelements.extension.MethodHandler;
import io.qameta.htmlelements.util.WebDriverUtils;
import org.hamcrest.Matcher;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import static io.qameta.htmlelements.context.Store.DRIVER_KEY;
import static java.lang.String.format; | package io.qameta.htmlelements.extension.page;
/**
* @author ehborisov
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@HandleWith(IsAtMethod.Extension.class)
public @interface IsAtMethod {
| // Path: src/main/java/io/qameta/htmlelements/context/Context.java
// public class Context {
//
// public static final String DESCRIPTION_KEY = "description";
//
// public static final String LISTENERS_KEY = "listeners";
//
// public static final String PROPERTIES_KEY = "properties";
//
// public static final String PARAMETERS_KEY = "parameters";
//
// public static final String DRIVER_KEY = "driver";
//
// private Context parent;
//
// private Store store;
//
// private ExtensionRegistry registry;
//
// private Context() {
// this.store = new DefaultStore();
// }
//
// public Optional<Context> getParent() {
// return Optional.ofNullable(parent);
// }
//
// private void setParent(Context parent) {
// this.parent = parent;
// }
//
// public Store getStore() {
// return store;
// }
//
// public ExtensionRegistry getRegistry() {
// return registry;
// }
//
// private void setRegistry(ExtensionRegistry registry) {
// this.registry = registry;
// }
//
// public Context newChildContext(Method method, Class<?> proxyClass) {
// Context childContext = new Context();
// childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null));
// childContext.setRegistry(ExtensionRegistry.create(proxyClass));
// childContext.getRegistry().registerExtensions(method);
// childContext.setParent(this);
// //extension
// getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PROPERTIES_KEY, child);
// });
// getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PARAMETERS_KEY, child);
// });
// getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> {
// childContext.getStore().put(LISTENERS_KEY, listeners);
// });
// getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> {
// childContext.getStore().put(DRIVER_KEY, driver);
// });
// return childContext;
// }
//
// public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) {
// Context context = new Context();
// context.setRegistry(ExtensionRegistry.create(webPageClass));
// context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass));
// context.getStore().put(DRIVER_KEY, driver);
// return context;
// }
//
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/exception/WebPageException.java
// public class WebPageException extends RuntimeException {
//
// public WebPageException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/io/qameta/htmlelements/extension/MethodHandler.java
// public interface MethodHandler<R> {
//
// R handle(Context context, Object proxy, Method method, Object[] args) throws Throwable;
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/util/WebDriverUtils.java
// public class WebDriverUtils {
//
// public static boolean pageIsLoaded(WebDriver webDriver) {
// if (webDriver instanceof JavascriptExecutor) {
// Object result = ((JavascriptExecutor) webDriver)
// .executeScript("if (document.readyState) return document.readyState;");
// return result != null && "complete".equals(result);
// } else {
// throw new WebPageException("Driver must support javascript execution");
// }
// }
// }
// Path: src/main/java/io/qameta/htmlelements/extension/page/IsAtMethod.java
import com.google.common.base.Predicate;
import io.qameta.htmlelements.context.Context;
import io.qameta.htmlelements.exception.WebPageException;
import io.qameta.htmlelements.extension.HandleWith;
import io.qameta.htmlelements.extension.MethodHandler;
import io.qameta.htmlelements.util.WebDriverUtils;
import org.hamcrest.Matcher;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import static io.qameta.htmlelements.context.Store.DRIVER_KEY;
import static java.lang.String.format;
package io.qameta.htmlelements.extension.page;
/**
* @author ehborisov
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@HandleWith(IsAtMethod.Extension.class)
public @interface IsAtMethod {
| class Extension implements MethodHandler { |
eroshenkoam/htmlelements | src/main/java/io/qameta/htmlelements/extension/page/IsAtMethod.java | // Path: src/main/java/io/qameta/htmlelements/context/Context.java
// public class Context {
//
// public static final String DESCRIPTION_KEY = "description";
//
// public static final String LISTENERS_KEY = "listeners";
//
// public static final String PROPERTIES_KEY = "properties";
//
// public static final String PARAMETERS_KEY = "parameters";
//
// public static final String DRIVER_KEY = "driver";
//
// private Context parent;
//
// private Store store;
//
// private ExtensionRegistry registry;
//
// private Context() {
// this.store = new DefaultStore();
// }
//
// public Optional<Context> getParent() {
// return Optional.ofNullable(parent);
// }
//
// private void setParent(Context parent) {
// this.parent = parent;
// }
//
// public Store getStore() {
// return store;
// }
//
// public ExtensionRegistry getRegistry() {
// return registry;
// }
//
// private void setRegistry(ExtensionRegistry registry) {
// this.registry = registry;
// }
//
// public Context newChildContext(Method method, Class<?> proxyClass) {
// Context childContext = new Context();
// childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null));
// childContext.setRegistry(ExtensionRegistry.create(proxyClass));
// childContext.getRegistry().registerExtensions(method);
// childContext.setParent(this);
// //extension
// getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PROPERTIES_KEY, child);
// });
// getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PARAMETERS_KEY, child);
// });
// getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> {
// childContext.getStore().put(LISTENERS_KEY, listeners);
// });
// getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> {
// childContext.getStore().put(DRIVER_KEY, driver);
// });
// return childContext;
// }
//
// public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) {
// Context context = new Context();
// context.setRegistry(ExtensionRegistry.create(webPageClass));
// context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass));
// context.getStore().put(DRIVER_KEY, driver);
// return context;
// }
//
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/exception/WebPageException.java
// public class WebPageException extends RuntimeException {
//
// public WebPageException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/io/qameta/htmlelements/extension/MethodHandler.java
// public interface MethodHandler<R> {
//
// R handle(Context context, Object proxy, Method method, Object[] args) throws Throwable;
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/util/WebDriverUtils.java
// public class WebDriverUtils {
//
// public static boolean pageIsLoaded(WebDriver webDriver) {
// if (webDriver instanceof JavascriptExecutor) {
// Object result = ((JavascriptExecutor) webDriver)
// .executeScript("if (document.readyState) return document.readyState;");
// return result != null && "complete".equals(result);
// } else {
// throw new WebPageException("Driver must support javascript execution");
// }
// }
// }
| import com.google.common.base.Predicate;
import io.qameta.htmlelements.context.Context;
import io.qameta.htmlelements.exception.WebPageException;
import io.qameta.htmlelements.extension.HandleWith;
import io.qameta.htmlelements.extension.MethodHandler;
import io.qameta.htmlelements.util.WebDriverUtils;
import org.hamcrest.Matcher;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import static io.qameta.htmlelements.context.Store.DRIVER_KEY;
import static java.lang.String.format; | package io.qameta.htmlelements.extension.page;
/**
* @author ehborisov
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@HandleWith(IsAtMethod.Extension.class)
public @interface IsAtMethod {
class Extension implements MethodHandler {
@Override
@SuppressWarnings("unchecked") | // Path: src/main/java/io/qameta/htmlelements/context/Context.java
// public class Context {
//
// public static final String DESCRIPTION_KEY = "description";
//
// public static final String LISTENERS_KEY = "listeners";
//
// public static final String PROPERTIES_KEY = "properties";
//
// public static final String PARAMETERS_KEY = "parameters";
//
// public static final String DRIVER_KEY = "driver";
//
// private Context parent;
//
// private Store store;
//
// private ExtensionRegistry registry;
//
// private Context() {
// this.store = new DefaultStore();
// }
//
// public Optional<Context> getParent() {
// return Optional.ofNullable(parent);
// }
//
// private void setParent(Context parent) {
// this.parent = parent;
// }
//
// public Store getStore() {
// return store;
// }
//
// public ExtensionRegistry getRegistry() {
// return registry;
// }
//
// private void setRegistry(ExtensionRegistry registry) {
// this.registry = registry;
// }
//
// public Context newChildContext(Method method, Class<?> proxyClass) {
// Context childContext = new Context();
// childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null));
// childContext.setRegistry(ExtensionRegistry.create(proxyClass));
// childContext.getRegistry().registerExtensions(method);
// childContext.setParent(this);
// //extension
// getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PROPERTIES_KEY, child);
// });
// getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PARAMETERS_KEY, child);
// });
// getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> {
// childContext.getStore().put(LISTENERS_KEY, listeners);
// });
// getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> {
// childContext.getStore().put(DRIVER_KEY, driver);
// });
// return childContext;
// }
//
// public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) {
// Context context = new Context();
// context.setRegistry(ExtensionRegistry.create(webPageClass));
// context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass));
// context.getStore().put(DRIVER_KEY, driver);
// return context;
// }
//
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/exception/WebPageException.java
// public class WebPageException extends RuntimeException {
//
// public WebPageException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/io/qameta/htmlelements/extension/MethodHandler.java
// public interface MethodHandler<R> {
//
// R handle(Context context, Object proxy, Method method, Object[] args) throws Throwable;
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/util/WebDriverUtils.java
// public class WebDriverUtils {
//
// public static boolean pageIsLoaded(WebDriver webDriver) {
// if (webDriver instanceof JavascriptExecutor) {
// Object result = ((JavascriptExecutor) webDriver)
// .executeScript("if (document.readyState) return document.readyState;");
// return result != null && "complete".equals(result);
// } else {
// throw new WebPageException("Driver must support javascript execution");
// }
// }
// }
// Path: src/main/java/io/qameta/htmlelements/extension/page/IsAtMethod.java
import com.google.common.base.Predicate;
import io.qameta.htmlelements.context.Context;
import io.qameta.htmlelements.exception.WebPageException;
import io.qameta.htmlelements.extension.HandleWith;
import io.qameta.htmlelements.extension.MethodHandler;
import io.qameta.htmlelements.util.WebDriverUtils;
import org.hamcrest.Matcher;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import static io.qameta.htmlelements.context.Store.DRIVER_KEY;
import static java.lang.String.format;
package io.qameta.htmlelements.extension.page;
/**
* @author ehborisov
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@HandleWith(IsAtMethod.Extension.class)
public @interface IsAtMethod {
class Extension implements MethodHandler {
@Override
@SuppressWarnings("unchecked") | public Object handle(Context context, Object proxy, Method method, Object[] args) throws Throwable { |
eroshenkoam/htmlelements | src/main/java/io/qameta/htmlelements/extension/page/IsAtMethod.java | // Path: src/main/java/io/qameta/htmlelements/context/Context.java
// public class Context {
//
// public static final String DESCRIPTION_KEY = "description";
//
// public static final String LISTENERS_KEY = "listeners";
//
// public static final String PROPERTIES_KEY = "properties";
//
// public static final String PARAMETERS_KEY = "parameters";
//
// public static final String DRIVER_KEY = "driver";
//
// private Context parent;
//
// private Store store;
//
// private ExtensionRegistry registry;
//
// private Context() {
// this.store = new DefaultStore();
// }
//
// public Optional<Context> getParent() {
// return Optional.ofNullable(parent);
// }
//
// private void setParent(Context parent) {
// this.parent = parent;
// }
//
// public Store getStore() {
// return store;
// }
//
// public ExtensionRegistry getRegistry() {
// return registry;
// }
//
// private void setRegistry(ExtensionRegistry registry) {
// this.registry = registry;
// }
//
// public Context newChildContext(Method method, Class<?> proxyClass) {
// Context childContext = new Context();
// childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null));
// childContext.setRegistry(ExtensionRegistry.create(proxyClass));
// childContext.getRegistry().registerExtensions(method);
// childContext.setParent(this);
// //extension
// getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PROPERTIES_KEY, child);
// });
// getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PARAMETERS_KEY, child);
// });
// getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> {
// childContext.getStore().put(LISTENERS_KEY, listeners);
// });
// getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> {
// childContext.getStore().put(DRIVER_KEY, driver);
// });
// return childContext;
// }
//
// public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) {
// Context context = new Context();
// context.setRegistry(ExtensionRegistry.create(webPageClass));
// context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass));
// context.getStore().put(DRIVER_KEY, driver);
// return context;
// }
//
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/exception/WebPageException.java
// public class WebPageException extends RuntimeException {
//
// public WebPageException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/io/qameta/htmlelements/extension/MethodHandler.java
// public interface MethodHandler<R> {
//
// R handle(Context context, Object proxy, Method method, Object[] args) throws Throwable;
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/util/WebDriverUtils.java
// public class WebDriverUtils {
//
// public static boolean pageIsLoaded(WebDriver webDriver) {
// if (webDriver instanceof JavascriptExecutor) {
// Object result = ((JavascriptExecutor) webDriver)
// .executeScript("if (document.readyState) return document.readyState;");
// return result != null && "complete".equals(result);
// } else {
// throw new WebPageException("Driver must support javascript execution");
// }
// }
// }
| import com.google.common.base.Predicate;
import io.qameta.htmlelements.context.Context;
import io.qameta.htmlelements.exception.WebPageException;
import io.qameta.htmlelements.extension.HandleWith;
import io.qameta.htmlelements.extension.MethodHandler;
import io.qameta.htmlelements.util.WebDriverUtils;
import org.hamcrest.Matcher;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import static io.qameta.htmlelements.context.Store.DRIVER_KEY;
import static java.lang.String.format; | package io.qameta.htmlelements.extension.page;
/**
* @author ehborisov
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@HandleWith(IsAtMethod.Extension.class)
public @interface IsAtMethod {
class Extension implements MethodHandler {
@Override
@SuppressWarnings("unchecked")
public Object handle(Context context, Object proxy, Method method, Object[] args) throws Throwable {
Matcher<String> expectedUrlMacher = (Matcher<String>) args[0];
WebDriver driver = context.getStore().get(DRIVER_KEY, WebDriver.class) | // Path: src/main/java/io/qameta/htmlelements/context/Context.java
// public class Context {
//
// public static final String DESCRIPTION_KEY = "description";
//
// public static final String LISTENERS_KEY = "listeners";
//
// public static final String PROPERTIES_KEY = "properties";
//
// public static final String PARAMETERS_KEY = "parameters";
//
// public static final String DRIVER_KEY = "driver";
//
// private Context parent;
//
// private Store store;
//
// private ExtensionRegistry registry;
//
// private Context() {
// this.store = new DefaultStore();
// }
//
// public Optional<Context> getParent() {
// return Optional.ofNullable(parent);
// }
//
// private void setParent(Context parent) {
// this.parent = parent;
// }
//
// public Store getStore() {
// return store;
// }
//
// public ExtensionRegistry getRegistry() {
// return registry;
// }
//
// private void setRegistry(ExtensionRegistry registry) {
// this.registry = registry;
// }
//
// public Context newChildContext(Method method, Class<?> proxyClass) {
// Context childContext = new Context();
// childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null));
// childContext.setRegistry(ExtensionRegistry.create(proxyClass));
// childContext.getRegistry().registerExtensions(method);
// childContext.setParent(this);
// //extension
// getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PROPERTIES_KEY, child);
// });
// getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PARAMETERS_KEY, child);
// });
// getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> {
// childContext.getStore().put(LISTENERS_KEY, listeners);
// });
// getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> {
// childContext.getStore().put(DRIVER_KEY, driver);
// });
// return childContext;
// }
//
// public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) {
// Context context = new Context();
// context.setRegistry(ExtensionRegistry.create(webPageClass));
// context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass));
// context.getStore().put(DRIVER_KEY, driver);
// return context;
// }
//
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/exception/WebPageException.java
// public class WebPageException extends RuntimeException {
//
// public WebPageException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/io/qameta/htmlelements/extension/MethodHandler.java
// public interface MethodHandler<R> {
//
// R handle(Context context, Object proxy, Method method, Object[] args) throws Throwable;
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/util/WebDriverUtils.java
// public class WebDriverUtils {
//
// public static boolean pageIsLoaded(WebDriver webDriver) {
// if (webDriver instanceof JavascriptExecutor) {
// Object result = ((JavascriptExecutor) webDriver)
// .executeScript("if (document.readyState) return document.readyState;");
// return result != null && "complete".equals(result);
// } else {
// throw new WebPageException("Driver must support javascript execution");
// }
// }
// }
// Path: src/main/java/io/qameta/htmlelements/extension/page/IsAtMethod.java
import com.google.common.base.Predicate;
import io.qameta.htmlelements.context.Context;
import io.qameta.htmlelements.exception.WebPageException;
import io.qameta.htmlelements.extension.HandleWith;
import io.qameta.htmlelements.extension.MethodHandler;
import io.qameta.htmlelements.util.WebDriverUtils;
import org.hamcrest.Matcher;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import static io.qameta.htmlelements.context.Store.DRIVER_KEY;
import static java.lang.String.format;
package io.qameta.htmlelements.extension.page;
/**
* @author ehborisov
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@HandleWith(IsAtMethod.Extension.class)
public @interface IsAtMethod {
class Extension implements MethodHandler {
@Override
@SuppressWarnings("unchecked")
public Object handle(Context context, Object proxy, Method method, Object[] args) throws Throwable {
Matcher<String> expectedUrlMacher = (Matcher<String>) args[0];
WebDriver driver = context.getStore().get(DRIVER_KEY, WebDriver.class) | .orElseThrow(() -> new WebPageException("WebDriver is missing")); |
eroshenkoam/htmlelements | src/main/java/io/qameta/htmlelements/extension/page/IsAtMethod.java | // Path: src/main/java/io/qameta/htmlelements/context/Context.java
// public class Context {
//
// public static final String DESCRIPTION_KEY = "description";
//
// public static final String LISTENERS_KEY = "listeners";
//
// public static final String PROPERTIES_KEY = "properties";
//
// public static final String PARAMETERS_KEY = "parameters";
//
// public static final String DRIVER_KEY = "driver";
//
// private Context parent;
//
// private Store store;
//
// private ExtensionRegistry registry;
//
// private Context() {
// this.store = new DefaultStore();
// }
//
// public Optional<Context> getParent() {
// return Optional.ofNullable(parent);
// }
//
// private void setParent(Context parent) {
// this.parent = parent;
// }
//
// public Store getStore() {
// return store;
// }
//
// public ExtensionRegistry getRegistry() {
// return registry;
// }
//
// private void setRegistry(ExtensionRegistry registry) {
// this.registry = registry;
// }
//
// public Context newChildContext(Method method, Class<?> proxyClass) {
// Context childContext = new Context();
// childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null));
// childContext.setRegistry(ExtensionRegistry.create(proxyClass));
// childContext.getRegistry().registerExtensions(method);
// childContext.setParent(this);
// //extension
// getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PROPERTIES_KEY, child);
// });
// getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PARAMETERS_KEY, child);
// });
// getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> {
// childContext.getStore().put(LISTENERS_KEY, listeners);
// });
// getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> {
// childContext.getStore().put(DRIVER_KEY, driver);
// });
// return childContext;
// }
//
// public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) {
// Context context = new Context();
// context.setRegistry(ExtensionRegistry.create(webPageClass));
// context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass));
// context.getStore().put(DRIVER_KEY, driver);
// return context;
// }
//
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/exception/WebPageException.java
// public class WebPageException extends RuntimeException {
//
// public WebPageException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/io/qameta/htmlelements/extension/MethodHandler.java
// public interface MethodHandler<R> {
//
// R handle(Context context, Object proxy, Method method, Object[] args) throws Throwable;
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/util/WebDriverUtils.java
// public class WebDriverUtils {
//
// public static boolean pageIsLoaded(WebDriver webDriver) {
// if (webDriver instanceof JavascriptExecutor) {
// Object result = ((JavascriptExecutor) webDriver)
// .executeScript("if (document.readyState) return document.readyState;");
// return result != null && "complete".equals(result);
// } else {
// throw new WebPageException("Driver must support javascript execution");
// }
// }
// }
| import com.google.common.base.Predicate;
import io.qameta.htmlelements.context.Context;
import io.qameta.htmlelements.exception.WebPageException;
import io.qameta.htmlelements.extension.HandleWith;
import io.qameta.htmlelements.extension.MethodHandler;
import io.qameta.htmlelements.util.WebDriverUtils;
import org.hamcrest.Matcher;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import static io.qameta.htmlelements.context.Store.DRIVER_KEY;
import static java.lang.String.format; | package io.qameta.htmlelements.extension.page;
/**
* @author ehborisov
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@HandleWith(IsAtMethod.Extension.class)
public @interface IsAtMethod {
class Extension implements MethodHandler {
@Override
@SuppressWarnings("unchecked")
public Object handle(Context context, Object proxy, Method method, Object[] args) throws Throwable {
Matcher<String> expectedUrlMacher = (Matcher<String>) args[0];
WebDriver driver = context.getStore().get(DRIVER_KEY, WebDriver.class)
.orElseThrow(() -> new WebPageException("WebDriver is missing"));
new WebDriverWait(driver, 5)
.ignoring(Throwable.class)
.withMessage(format("Couldn't wait for page with url %s to load", expectedUrlMacher))
.until((Predicate<WebDriver>) (d) -> (d != null && expectedUrlMacher.matches(d.getCurrentUrl())) && | // Path: src/main/java/io/qameta/htmlelements/context/Context.java
// public class Context {
//
// public static final String DESCRIPTION_KEY = "description";
//
// public static final String LISTENERS_KEY = "listeners";
//
// public static final String PROPERTIES_KEY = "properties";
//
// public static final String PARAMETERS_KEY = "parameters";
//
// public static final String DRIVER_KEY = "driver";
//
// private Context parent;
//
// private Store store;
//
// private ExtensionRegistry registry;
//
// private Context() {
// this.store = new DefaultStore();
// }
//
// public Optional<Context> getParent() {
// return Optional.ofNullable(parent);
// }
//
// private void setParent(Context parent) {
// this.parent = parent;
// }
//
// public Store getStore() {
// return store;
// }
//
// public ExtensionRegistry getRegistry() {
// return registry;
// }
//
// private void setRegistry(ExtensionRegistry registry) {
// this.registry = registry;
// }
//
// public Context newChildContext(Method method, Class<?> proxyClass) {
// Context childContext = new Context();
// childContext.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(method, null));
// childContext.setRegistry(ExtensionRegistry.create(proxyClass));
// childContext.getRegistry().registerExtensions(method);
// childContext.setParent(this);
// //extension
// getStore().get(PROPERTIES_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PROPERTIES_KEY, child);
// });
// getStore().get(PARAMETERS_KEY, Properties.class).ifPresent(properties -> {
// Properties child = new Properties();
// child.putAll(properties);
// childContext.getStore().put(PARAMETERS_KEY, child);
// });
// getStore().get(LISTENERS_KEY, List.class).ifPresent(listeners -> {
// childContext.getStore().put(LISTENERS_KEY, listeners);
// });
// getStore().get(DRIVER_KEY, WebDriver.class).ifPresent(driver -> {
// childContext.getStore().put(DRIVER_KEY, driver);
// });
// return childContext;
// }
//
// public static Context newWebPageContext(Class<?> webPageClass, WebDriver driver) {
// Context context = new Context();
// context.setRegistry(ExtensionRegistry.create(webPageClass));
// context.getStore().put(DESCRIPTION_KEY, ReflectionUtils.getDescription(webPageClass));
// context.getStore().put(DRIVER_KEY, driver);
// return context;
// }
//
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/exception/WebPageException.java
// public class WebPageException extends RuntimeException {
//
// public WebPageException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/io/qameta/htmlelements/extension/MethodHandler.java
// public interface MethodHandler<R> {
//
// R handle(Context context, Object proxy, Method method, Object[] args) throws Throwable;
//
// }
//
// Path: src/main/java/io/qameta/htmlelements/util/WebDriverUtils.java
// public class WebDriverUtils {
//
// public static boolean pageIsLoaded(WebDriver webDriver) {
// if (webDriver instanceof JavascriptExecutor) {
// Object result = ((JavascriptExecutor) webDriver)
// .executeScript("if (document.readyState) return document.readyState;");
// return result != null && "complete".equals(result);
// } else {
// throw new WebPageException("Driver must support javascript execution");
// }
// }
// }
// Path: src/main/java/io/qameta/htmlelements/extension/page/IsAtMethod.java
import com.google.common.base.Predicate;
import io.qameta.htmlelements.context.Context;
import io.qameta.htmlelements.exception.WebPageException;
import io.qameta.htmlelements.extension.HandleWith;
import io.qameta.htmlelements.extension.MethodHandler;
import io.qameta.htmlelements.util.WebDriverUtils;
import org.hamcrest.Matcher;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import static io.qameta.htmlelements.context.Store.DRIVER_KEY;
import static java.lang.String.format;
package io.qameta.htmlelements.extension.page;
/**
* @author ehborisov
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@HandleWith(IsAtMethod.Extension.class)
public @interface IsAtMethod {
class Extension implements MethodHandler {
@Override
@SuppressWarnings("unchecked")
public Object handle(Context context, Object proxy, Method method, Object[] args) throws Throwable {
Matcher<String> expectedUrlMacher = (Matcher<String>) args[0];
WebDriver driver = context.getStore().get(DRIVER_KEY, WebDriver.class)
.orElseThrow(() -> new WebPageException("WebDriver is missing"));
new WebDriverWait(driver, 5)
.ignoring(Throwable.class)
.withMessage(format("Couldn't wait for page with url %s to load", expectedUrlMacher))
.until((Predicate<WebDriver>) (d) -> (d != null && expectedUrlMacher.matches(d.getCurrentUrl())) && | WebDriverUtils.pageIsLoaded(d)); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.