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
DaanVanYperen/odb-little-fortune-planet
core/src/net/mostlyoriginal/game/system/planet/cells/WaterCellSimulator.java
// Path: components/src/net/mostlyoriginal/game/component/PlanetCell.java // public class PlanetCell { // public static final int SPACE_AIR_STARTS_AT_DEPTH = 20; // public int x; // public int y; // public int color = 0; // public int down = -1; // public float height = 0; // public CellType type = CellType.STATIC; // // // public CellType nextType = null; // public int nextColor = -1; // // public static int[][] directions = { // {-1, -1}, // {0, -1}, // {1, -1}, // {1, 0}, // {1, 1}, // {0, 1}, // {-1, 1}, // {-1, 0} // }; // // public int sleep; // // public int up() { // return (down + 4) % 8; // } // // public int left() { // return (down + 6) % 8; // } // // public int right() { // return (down + 2) % 8; // } // // public int upL() { // return (down + 3) % 8; // } // // public int downL() { // return (down + 7) % 8; // } // // public int downR() { // return (down + 1) % 8; // } // // public int upR() { // return (down + 5) % 8; // } // // public void activateNextType() { // if (nextType != null) { // type = nextType; // nextType = null; // sleep=0; // } // if (nextColor != -1) { // color = nextColor; // nextColor = -1; // } // } // // public float depth() { // return ((G.SIMULATION_WIDTH / 2) - height); // } // // public enum CellType { // STATIC(null, false), // LAVA(5f, true), // WATER(1f, true), // AIR(0f, true), // ICE(null, false), // STEAM(-0.5f, true), // LAVA_CRUST(5f, true), // CLOUD(-0.7f, false), // FIRE(-0.7f, false), // NOTHING(-100f,false), // ORGANIC(null, false), ORGANIC_SPORE(-0.7f, false); // // public final Float density; // private boolean flows; // // CellType(Float density, boolean flows) { // this.density = density; // this.flows = flows; // } // // public boolean flows() { // return flows; // } // // public boolean isLighter(CellType type) { // return type.density != null && density != null && type.density < density; // } // } // // public boolean isSpaceAir() { // return depth() < SPACE_AIR_STARTS_AT_DEPTH && type == PlanetCell.CellType.AIR; // } // } // // Path: components/src/net/mostlyoriginal/game/component/StatusMask.java // public class StatusMask { // public static final float ARID_TEMPERATURE = 300; // public static float MAX_TEMPERATURE = 300; // public float temperature=0; // // public void reset() { // temperature=0; // } // }
import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.math.MathUtils; import net.mostlyoriginal.game.component.PlanetCell; import net.mostlyoriginal.game.component.StatusMask;
if (temperature < 0 && FauxRng.random(100) < -temperature) { c.setNextType(PlanetCell.CellType.ICE); } } } // Turn to steam by lava. if (c.getNeighbour(PlanetCell.CellType.LAVA, PlanetCell.CellType.LAVA_CRUST) != null) { int lavaCount = c.countNeighbour(PlanetCell.CellType.LAVA, PlanetCell.CellType.LAVA_CRUST); if (lavaCount >= 1) { if (FauxRng.random(100) < 75f) { // small chance of transforming self. if (c.cell.nextType == null) { c.setNextType(PlanetCell.CellType.STEAM); } } else { // small chance of transforming nearby. for (int i = 0; i < lavaCount; i++) { PlanetCell planetCell = c.getNeighbour(PlanetCell.CellType.AIR); if (planetCell == null) planetCell = c.getNeighbour(PlanetCell.CellType.WATER); if (planetCell != null && planetCell.nextType == null) { c.forChild(planetCell).setNextType(PlanetCell.CellType.STEAM); } } } } } if (c.cell.nextType == null) { final float temperature = c.mask().temperature;
// Path: components/src/net/mostlyoriginal/game/component/PlanetCell.java // public class PlanetCell { // public static final int SPACE_AIR_STARTS_AT_DEPTH = 20; // public int x; // public int y; // public int color = 0; // public int down = -1; // public float height = 0; // public CellType type = CellType.STATIC; // // // public CellType nextType = null; // public int nextColor = -1; // // public static int[][] directions = { // {-1, -1}, // {0, -1}, // {1, -1}, // {1, 0}, // {1, 1}, // {0, 1}, // {-1, 1}, // {-1, 0} // }; // // public int sleep; // // public int up() { // return (down + 4) % 8; // } // // public int left() { // return (down + 6) % 8; // } // // public int right() { // return (down + 2) % 8; // } // // public int upL() { // return (down + 3) % 8; // } // // public int downL() { // return (down + 7) % 8; // } // // public int downR() { // return (down + 1) % 8; // } // // public int upR() { // return (down + 5) % 8; // } // // public void activateNextType() { // if (nextType != null) { // type = nextType; // nextType = null; // sleep=0; // } // if (nextColor != -1) { // color = nextColor; // nextColor = -1; // } // } // // public float depth() { // return ((G.SIMULATION_WIDTH / 2) - height); // } // // public enum CellType { // STATIC(null, false), // LAVA(5f, true), // WATER(1f, true), // AIR(0f, true), // ICE(null, false), // STEAM(-0.5f, true), // LAVA_CRUST(5f, true), // CLOUD(-0.7f, false), // FIRE(-0.7f, false), // NOTHING(-100f,false), // ORGANIC(null, false), ORGANIC_SPORE(-0.7f, false); // // public final Float density; // private boolean flows; // // CellType(Float density, boolean flows) { // this.density = density; // this.flows = flows; // } // // public boolean flows() { // return flows; // } // // public boolean isLighter(CellType type) { // return type.density != null && density != null && type.density < density; // } // } // // public boolean isSpaceAir() { // return depth() < SPACE_AIR_STARTS_AT_DEPTH && type == PlanetCell.CellType.AIR; // } // } // // Path: components/src/net/mostlyoriginal/game/component/StatusMask.java // public class StatusMask { // public static final float ARID_TEMPERATURE = 300; // public static float MAX_TEMPERATURE = 300; // public float temperature=0; // // public void reset() { // temperature=0; // } // } // Path: core/src/net/mostlyoriginal/game/system/planet/cells/WaterCellSimulator.java import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.math.MathUtils; import net.mostlyoriginal.game.component.PlanetCell; import net.mostlyoriginal.game.component.StatusMask; if (temperature < 0 && FauxRng.random(100) < -temperature) { c.setNextType(PlanetCell.CellType.ICE); } } } // Turn to steam by lava. if (c.getNeighbour(PlanetCell.CellType.LAVA, PlanetCell.CellType.LAVA_CRUST) != null) { int lavaCount = c.countNeighbour(PlanetCell.CellType.LAVA, PlanetCell.CellType.LAVA_CRUST); if (lavaCount >= 1) { if (FauxRng.random(100) < 75f) { // small chance of transforming self. if (c.cell.nextType == null) { c.setNextType(PlanetCell.CellType.STEAM); } } else { // small chance of transforming nearby. for (int i = 0; i < lavaCount; i++) { PlanetCell planetCell = c.getNeighbour(PlanetCell.CellType.AIR); if (planetCell == null) planetCell = c.getNeighbour(PlanetCell.CellType.WATER); if (planetCell != null && planetCell.nextType == null) { c.forChild(planetCell).setNextType(PlanetCell.CellType.STEAM); } } } } } if (c.cell.nextType == null) { final float temperature = c.mask().temperature;
if (temperature >= StatusMask.ARID_TEMPERATURE && FauxRng.random( 100) < 4) {
DaanVanYperen/odb-little-fortune-planet
core/src/net/mostlyoriginal/game/system/planet/cells/IceCellSimulator.java
// Path: components/src/net/mostlyoriginal/game/component/PlanetCell.java // public class PlanetCell { // public static final int SPACE_AIR_STARTS_AT_DEPTH = 20; // public int x; // public int y; // public int color = 0; // public int down = -1; // public float height = 0; // public CellType type = CellType.STATIC; // // // public CellType nextType = null; // public int nextColor = -1; // // public static int[][] directions = { // {-1, -1}, // {0, -1}, // {1, -1}, // {1, 0}, // {1, 1}, // {0, 1}, // {-1, 1}, // {-1, 0} // }; // // public int sleep; // // public int up() { // return (down + 4) % 8; // } // // public int left() { // return (down + 6) % 8; // } // // public int right() { // return (down + 2) % 8; // } // // public int upL() { // return (down + 3) % 8; // } // // public int downL() { // return (down + 7) % 8; // } // // public int downR() { // return (down + 1) % 8; // } // // public int upR() { // return (down + 5) % 8; // } // // public void activateNextType() { // if (nextType != null) { // type = nextType; // nextType = null; // sleep=0; // } // if (nextColor != -1) { // color = nextColor; // nextColor = -1; // } // } // // public float depth() { // return ((G.SIMULATION_WIDTH / 2) - height); // } // // public enum CellType { // STATIC(null, false), // LAVA(5f, true), // WATER(1f, true), // AIR(0f, true), // ICE(null, false), // STEAM(-0.5f, true), // LAVA_CRUST(5f, true), // CLOUD(-0.7f, false), // FIRE(-0.7f, false), // NOTHING(-100f,false), // ORGANIC(null, false), ORGANIC_SPORE(-0.7f, false); // // public final Float density; // private boolean flows; // // CellType(Float density, boolean flows) { // this.density = density; // this.flows = flows; // } // // public boolean flows() { // return flows; // } // // public boolean isLighter(CellType type) { // return type.density != null && density != null && type.density < density; // } // } // // public boolean isSpaceAir() { // return depth() < SPACE_AIR_STARTS_AT_DEPTH && type == PlanetCell.CellType.AIR; // } // }
import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.math.MathUtils; import net.mostlyoriginal.game.component.PlanetCell;
package net.mostlyoriginal.game.system.planet.cells; /** * @author Daan van Yperen */ public class IceCellSimulator implements CellSimulator { @Override public void process(CellDecorator c, float delta) { final float temperature = c.mask().temperature; if ( temperature > 0 && MathUtils.random(100) < temperature ) {
// Path: components/src/net/mostlyoriginal/game/component/PlanetCell.java // public class PlanetCell { // public static final int SPACE_AIR_STARTS_AT_DEPTH = 20; // public int x; // public int y; // public int color = 0; // public int down = -1; // public float height = 0; // public CellType type = CellType.STATIC; // // // public CellType nextType = null; // public int nextColor = -1; // // public static int[][] directions = { // {-1, -1}, // {0, -1}, // {1, -1}, // {1, 0}, // {1, 1}, // {0, 1}, // {-1, 1}, // {-1, 0} // }; // // public int sleep; // // public int up() { // return (down + 4) % 8; // } // // public int left() { // return (down + 6) % 8; // } // // public int right() { // return (down + 2) % 8; // } // // public int upL() { // return (down + 3) % 8; // } // // public int downL() { // return (down + 7) % 8; // } // // public int downR() { // return (down + 1) % 8; // } // // public int upR() { // return (down + 5) % 8; // } // // public void activateNextType() { // if (nextType != null) { // type = nextType; // nextType = null; // sleep=0; // } // if (nextColor != -1) { // color = nextColor; // nextColor = -1; // } // } // // public float depth() { // return ((G.SIMULATION_WIDTH / 2) - height); // } // // public enum CellType { // STATIC(null, false), // LAVA(5f, true), // WATER(1f, true), // AIR(0f, true), // ICE(null, false), // STEAM(-0.5f, true), // LAVA_CRUST(5f, true), // CLOUD(-0.7f, false), // FIRE(-0.7f, false), // NOTHING(-100f,false), // ORGANIC(null, false), ORGANIC_SPORE(-0.7f, false); // // public final Float density; // private boolean flows; // // CellType(Float density, boolean flows) { // this.density = density; // this.flows = flows; // } // // public boolean flows() { // return flows; // } // // public boolean isLighter(CellType type) { // return type.density != null && density != null && type.density < density; // } // } // // public boolean isSpaceAir() { // return depth() < SPACE_AIR_STARTS_AT_DEPTH && type == PlanetCell.CellType.AIR; // } // } // Path: core/src/net/mostlyoriginal/game/system/planet/cells/IceCellSimulator.java import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.math.MathUtils; import net.mostlyoriginal.game.component.PlanetCell; package net.mostlyoriginal.game.system.planet.cells; /** * @author Daan van Yperen */ public class IceCellSimulator implements CellSimulator { @Override public void process(CellDecorator c, float delta) { final float temperature = c.mask().temperature; if ( temperature > 0 && MathUtils.random(100) < temperature ) {
c.setNextType(PlanetCell.CellType.WATER);
DaanVanYperen/odb-little-fortune-planet
core/src/net/mostlyoriginal/game/system/planet/cells/AirCellSimulator.java
// Path: components/src/net/mostlyoriginal/game/component/PlanetCell.java // public class PlanetCell { // public static final int SPACE_AIR_STARTS_AT_DEPTH = 20; // public int x; // public int y; // public int color = 0; // public int down = -1; // public float height = 0; // public CellType type = CellType.STATIC; // // // public CellType nextType = null; // public int nextColor = -1; // // public static int[][] directions = { // {-1, -1}, // {0, -1}, // {1, -1}, // {1, 0}, // {1, 1}, // {0, 1}, // {-1, 1}, // {-1, 0} // }; // // public int sleep; // // public int up() { // return (down + 4) % 8; // } // // public int left() { // return (down + 6) % 8; // } // // public int right() { // return (down + 2) % 8; // } // // public int upL() { // return (down + 3) % 8; // } // // public int downL() { // return (down + 7) % 8; // } // // public int downR() { // return (down + 1) % 8; // } // // public int upR() { // return (down + 5) % 8; // } // // public void activateNextType() { // if (nextType != null) { // type = nextType; // nextType = null; // sleep=0; // } // if (nextColor != -1) { // color = nextColor; // nextColor = -1; // } // } // // public float depth() { // return ((G.SIMULATION_WIDTH / 2) - height); // } // // public enum CellType { // STATIC(null, false), // LAVA(5f, true), // WATER(1f, true), // AIR(0f, true), // ICE(null, false), // STEAM(-0.5f, true), // LAVA_CRUST(5f, true), // CLOUD(-0.7f, false), // FIRE(-0.7f, false), // NOTHING(-100f,false), // ORGANIC(null, false), ORGANIC_SPORE(-0.7f, false); // // public final Float density; // private boolean flows; // // CellType(Float density, boolean flows) { // this.density = density; // this.flows = flows; // } // // public boolean flows() { // return flows; // } // // public boolean isLighter(CellType type) { // return type.density != null && density != null && type.density < density; // } // } // // public boolean isSpaceAir() { // return depth() < SPACE_AIR_STARTS_AT_DEPTH && type == PlanetCell.CellType.AIR; // } // } // // Path: components/src/net/mostlyoriginal/game/component/StatusMask.java // public class StatusMask { // public static final float ARID_TEMPERATURE = 300; // public static float MAX_TEMPERATURE = 300; // public float temperature=0; // // public void reset() { // temperature=0; // } // }
import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.math.MathUtils; import net.mostlyoriginal.game.component.PlanetCell; import net.mostlyoriginal.game.component.StatusMask;
package net.mostlyoriginal.game.system.planet.cells; /** * @author Daan van Yperen */ public class AirCellSimulator implements CellSimulator { public static final float AIR_FADE_BAND_WIDTH = 50f; Color coldColor; Color aridColor; Color workColor = new Color(); @Override public void color(CellDecorator c, float delta) { if (FauxRng.random(100) < 40) { // expensive, so run less often! if (aridColor == null) { coldColor = new Color(); aridColor = new Color();
// Path: components/src/net/mostlyoriginal/game/component/PlanetCell.java // public class PlanetCell { // public static final int SPACE_AIR_STARTS_AT_DEPTH = 20; // public int x; // public int y; // public int color = 0; // public int down = -1; // public float height = 0; // public CellType type = CellType.STATIC; // // // public CellType nextType = null; // public int nextColor = -1; // // public static int[][] directions = { // {-1, -1}, // {0, -1}, // {1, -1}, // {1, 0}, // {1, 1}, // {0, 1}, // {-1, 1}, // {-1, 0} // }; // // public int sleep; // // public int up() { // return (down + 4) % 8; // } // // public int left() { // return (down + 6) % 8; // } // // public int right() { // return (down + 2) % 8; // } // // public int upL() { // return (down + 3) % 8; // } // // public int downL() { // return (down + 7) % 8; // } // // public int downR() { // return (down + 1) % 8; // } // // public int upR() { // return (down + 5) % 8; // } // // public void activateNextType() { // if (nextType != null) { // type = nextType; // nextType = null; // sleep=0; // } // if (nextColor != -1) { // color = nextColor; // nextColor = -1; // } // } // // public float depth() { // return ((G.SIMULATION_WIDTH / 2) - height); // } // // public enum CellType { // STATIC(null, false), // LAVA(5f, true), // WATER(1f, true), // AIR(0f, true), // ICE(null, false), // STEAM(-0.5f, true), // LAVA_CRUST(5f, true), // CLOUD(-0.7f, false), // FIRE(-0.7f, false), // NOTHING(-100f,false), // ORGANIC(null, false), ORGANIC_SPORE(-0.7f, false); // // public final Float density; // private boolean flows; // // CellType(Float density, boolean flows) { // this.density = density; // this.flows = flows; // } // // public boolean flows() { // return flows; // } // // public boolean isLighter(CellType type) { // return type.density != null && density != null && type.density < density; // } // } // // public boolean isSpaceAir() { // return depth() < SPACE_AIR_STARTS_AT_DEPTH && type == PlanetCell.CellType.AIR; // } // } // // Path: components/src/net/mostlyoriginal/game/component/StatusMask.java // public class StatusMask { // public static final float ARID_TEMPERATURE = 300; // public static float MAX_TEMPERATURE = 300; // public float temperature=0; // // public void reset() { // temperature=0; // } // } // Path: core/src/net/mostlyoriginal/game/system/planet/cells/AirCellSimulator.java import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.math.MathUtils; import net.mostlyoriginal.game.component.PlanetCell; import net.mostlyoriginal.game.component.StatusMask; package net.mostlyoriginal.game.system.planet.cells; /** * @author Daan van Yperen */ public class AirCellSimulator implements CellSimulator { public static final float AIR_FADE_BAND_WIDTH = 50f; Color coldColor; Color aridColor; Color workColor = new Color(); @Override public void color(CellDecorator c, float delta) { if (FauxRng.random(100) < 40) { // expensive, so run less often! if (aridColor == null) { coldColor = new Color(); aridColor = new Color();
Color.rgba8888ToColor(coldColor, c.planet.cellColor[PlanetCell.CellType.AIR.ordinal()]);
DaanVanYperen/odb-little-fortune-planet
core/src/net/mostlyoriginal/game/system/planet/cells/AirCellSimulator.java
// Path: components/src/net/mostlyoriginal/game/component/PlanetCell.java // public class PlanetCell { // public static final int SPACE_AIR_STARTS_AT_DEPTH = 20; // public int x; // public int y; // public int color = 0; // public int down = -1; // public float height = 0; // public CellType type = CellType.STATIC; // // // public CellType nextType = null; // public int nextColor = -1; // // public static int[][] directions = { // {-1, -1}, // {0, -1}, // {1, -1}, // {1, 0}, // {1, 1}, // {0, 1}, // {-1, 1}, // {-1, 0} // }; // // public int sleep; // // public int up() { // return (down + 4) % 8; // } // // public int left() { // return (down + 6) % 8; // } // // public int right() { // return (down + 2) % 8; // } // // public int upL() { // return (down + 3) % 8; // } // // public int downL() { // return (down + 7) % 8; // } // // public int downR() { // return (down + 1) % 8; // } // // public int upR() { // return (down + 5) % 8; // } // // public void activateNextType() { // if (nextType != null) { // type = nextType; // nextType = null; // sleep=0; // } // if (nextColor != -1) { // color = nextColor; // nextColor = -1; // } // } // // public float depth() { // return ((G.SIMULATION_WIDTH / 2) - height); // } // // public enum CellType { // STATIC(null, false), // LAVA(5f, true), // WATER(1f, true), // AIR(0f, true), // ICE(null, false), // STEAM(-0.5f, true), // LAVA_CRUST(5f, true), // CLOUD(-0.7f, false), // FIRE(-0.7f, false), // NOTHING(-100f,false), // ORGANIC(null, false), ORGANIC_SPORE(-0.7f, false); // // public final Float density; // private boolean flows; // // CellType(Float density, boolean flows) { // this.density = density; // this.flows = flows; // } // // public boolean flows() { // return flows; // } // // public boolean isLighter(CellType type) { // return type.density != null && density != null && type.density < density; // } // } // // public boolean isSpaceAir() { // return depth() < SPACE_AIR_STARTS_AT_DEPTH && type == PlanetCell.CellType.AIR; // } // } // // Path: components/src/net/mostlyoriginal/game/component/StatusMask.java // public class StatusMask { // public static final float ARID_TEMPERATURE = 300; // public static float MAX_TEMPERATURE = 300; // public float temperature=0; // // public void reset() { // temperature=0; // } // }
import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.math.MathUtils; import net.mostlyoriginal.game.component.PlanetCell; import net.mostlyoriginal.game.component.StatusMask;
package net.mostlyoriginal.game.system.planet.cells; /** * @author Daan van Yperen */ public class AirCellSimulator implements CellSimulator { public static final float AIR_FADE_BAND_WIDTH = 50f; Color coldColor; Color aridColor; Color workColor = new Color(); @Override public void color(CellDecorator c, float delta) { if (FauxRng.random(100) < 40) { // expensive, so run less often! if (aridColor == null) { coldColor = new Color(); aridColor = new Color(); Color.rgba8888ToColor(coldColor, c.planet.cellColor[PlanetCell.CellType.AIR.ordinal()]); Color.rgba8888ToColor(aridColor, c.planet.cellColorSecondary[PlanetCell.CellType.AIR.ordinal()]); coldColor.a = aridColor.a = 1f; }
// Path: components/src/net/mostlyoriginal/game/component/PlanetCell.java // public class PlanetCell { // public static final int SPACE_AIR_STARTS_AT_DEPTH = 20; // public int x; // public int y; // public int color = 0; // public int down = -1; // public float height = 0; // public CellType type = CellType.STATIC; // // // public CellType nextType = null; // public int nextColor = -1; // // public static int[][] directions = { // {-1, -1}, // {0, -1}, // {1, -1}, // {1, 0}, // {1, 1}, // {0, 1}, // {-1, 1}, // {-1, 0} // }; // // public int sleep; // // public int up() { // return (down + 4) % 8; // } // // public int left() { // return (down + 6) % 8; // } // // public int right() { // return (down + 2) % 8; // } // // public int upL() { // return (down + 3) % 8; // } // // public int downL() { // return (down + 7) % 8; // } // // public int downR() { // return (down + 1) % 8; // } // // public int upR() { // return (down + 5) % 8; // } // // public void activateNextType() { // if (nextType != null) { // type = nextType; // nextType = null; // sleep=0; // } // if (nextColor != -1) { // color = nextColor; // nextColor = -1; // } // } // // public float depth() { // return ((G.SIMULATION_WIDTH / 2) - height); // } // // public enum CellType { // STATIC(null, false), // LAVA(5f, true), // WATER(1f, true), // AIR(0f, true), // ICE(null, false), // STEAM(-0.5f, true), // LAVA_CRUST(5f, true), // CLOUD(-0.7f, false), // FIRE(-0.7f, false), // NOTHING(-100f,false), // ORGANIC(null, false), ORGANIC_SPORE(-0.7f, false); // // public final Float density; // private boolean flows; // // CellType(Float density, boolean flows) { // this.density = density; // this.flows = flows; // } // // public boolean flows() { // return flows; // } // // public boolean isLighter(CellType type) { // return type.density != null && density != null && type.density < density; // } // } // // public boolean isSpaceAir() { // return depth() < SPACE_AIR_STARTS_AT_DEPTH && type == PlanetCell.CellType.AIR; // } // } // // Path: components/src/net/mostlyoriginal/game/component/StatusMask.java // public class StatusMask { // public static final float ARID_TEMPERATURE = 300; // public static float MAX_TEMPERATURE = 300; // public float temperature=0; // // public void reset() { // temperature=0; // } // } // Path: core/src/net/mostlyoriginal/game/system/planet/cells/AirCellSimulator.java import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.math.MathUtils; import net.mostlyoriginal.game.component.PlanetCell; import net.mostlyoriginal.game.component.StatusMask; package net.mostlyoriginal.game.system.planet.cells; /** * @author Daan van Yperen */ public class AirCellSimulator implements CellSimulator { public static final float AIR_FADE_BAND_WIDTH = 50f; Color coldColor; Color aridColor; Color workColor = new Color(); @Override public void color(CellDecorator c, float delta) { if (FauxRng.random(100) < 40) { // expensive, so run less often! if (aridColor == null) { coldColor = new Color(); aridColor = new Color(); Color.rgba8888ToColor(coldColor, c.planet.cellColor[PlanetCell.CellType.AIR.ordinal()]); Color.rgba8888ToColor(aridColor, c.planet.cellColorSecondary[PlanetCell.CellType.AIR.ordinal()]); coldColor.a = aridColor.a = 1f; }
float a = MathUtils.clamp((c.mask().temperature / StatusMask.ARID_TEMPERATURE), 0f, 1f);
DaanVanYperen/odb-little-fortune-planet
core/src/net/mostlyoriginal/game/system/stencil/StencilData.java
// Path: components/src/net/mostlyoriginal/game/component/PlanetCell.java // public class PlanetCell { // public static final int SPACE_AIR_STARTS_AT_DEPTH = 20; // public int x; // public int y; // public int color = 0; // public int down = -1; // public float height = 0; // public CellType type = CellType.STATIC; // // // public CellType nextType = null; // public int nextColor = -1; // // public static int[][] directions = { // {-1, -1}, // {0, -1}, // {1, -1}, // {1, 0}, // {1, 1}, // {0, 1}, // {-1, 1}, // {-1, 0} // }; // // public int sleep; // // public int up() { // return (down + 4) % 8; // } // // public int left() { // return (down + 6) % 8; // } // // public int right() { // return (down + 2) % 8; // } // // public int upL() { // return (down + 3) % 8; // } // // public int downL() { // return (down + 7) % 8; // } // // public int downR() { // return (down + 1) % 8; // } // // public int upR() { // return (down + 5) % 8; // } // // public void activateNextType() { // if (nextType != null) { // type = nextType; // nextType = null; // sleep=0; // } // if (nextColor != -1) { // color = nextColor; // nextColor = -1; // } // } // // public float depth() { // return ((G.SIMULATION_WIDTH / 2) - height); // } // // public enum CellType { // STATIC(null, false), // LAVA(5f, true), // WATER(1f, true), // AIR(0f, true), // ICE(null, false), // STEAM(-0.5f, true), // LAVA_CRUST(5f, true), // CLOUD(-0.7f, false), // FIRE(-0.7f, false), // NOTHING(-100f,false), // ORGANIC(null, false), ORGANIC_SPORE(-0.7f, false); // // public final Float density; // private boolean flows; // // CellType(Float density, boolean flows) { // this.density = density; // this.flows = flows; // } // // public boolean flows() { // return flows; // } // // public boolean isLighter(CellType type) { // return type.density != null && density != null && type.density < density; // } // } // // public boolean isSpaceAir() { // return depth() < SPACE_AIR_STARTS_AT_DEPTH && type == PlanetCell.CellType.AIR; // } // }
import net.mostlyoriginal.game.component.PlanetCell;
package net.mostlyoriginal.game.system.stencil; /** * @author Daan van Yperen */ public class StencilData { public String id; public String comment; // not used. public String texture;
// Path: components/src/net/mostlyoriginal/game/component/PlanetCell.java // public class PlanetCell { // public static final int SPACE_AIR_STARTS_AT_DEPTH = 20; // public int x; // public int y; // public int color = 0; // public int down = -1; // public float height = 0; // public CellType type = CellType.STATIC; // // // public CellType nextType = null; // public int nextColor = -1; // // public static int[][] directions = { // {-1, -1}, // {0, -1}, // {1, -1}, // {1, 0}, // {1, 1}, // {0, 1}, // {-1, 1}, // {-1, 0} // }; // // public int sleep; // // public int up() { // return (down + 4) % 8; // } // // public int left() { // return (down + 6) % 8; // } // // public int right() { // return (down + 2) % 8; // } // // public int upL() { // return (down + 3) % 8; // } // // public int downL() { // return (down + 7) % 8; // } // // public int downR() { // return (down + 1) % 8; // } // // public int upR() { // return (down + 5) % 8; // } // // public void activateNextType() { // if (nextType != null) { // type = nextType; // nextType = null; // sleep=0; // } // if (nextColor != -1) { // color = nextColor; // nextColor = -1; // } // } // // public float depth() { // return ((G.SIMULATION_WIDTH / 2) - height); // } // // public enum CellType { // STATIC(null, false), // LAVA(5f, true), // WATER(1f, true), // AIR(0f, true), // ICE(null, false), // STEAM(-0.5f, true), // LAVA_CRUST(5f, true), // CLOUD(-0.7f, false), // FIRE(-0.7f, false), // NOTHING(-100f,false), // ORGANIC(null, false), ORGANIC_SPORE(-0.7f, false); // // public final Float density; // private boolean flows; // // CellType(Float density, boolean flows) { // this.density = density; // this.flows = flows; // } // // public boolean flows() { // return flows; // } // // public boolean isLighter(CellType type) { // return type.density != null && density != null && type.density < density; // } // } // // public boolean isSpaceAir() { // return depth() < SPACE_AIR_STARTS_AT_DEPTH && type == PlanetCell.CellType.AIR; // } // } // Path: core/src/net/mostlyoriginal/game/system/stencil/StencilData.java import net.mostlyoriginal.game.component.PlanetCell; package net.mostlyoriginal.game.system.stencil; /** * @author Daan van Yperen */ public class StencilData { public String id; public String comment; // not used. public String texture;
public PlanetCell.CellType[] replaceTypes;
DaanVanYperen/odb-little-fortune-planet
desktop/src/net/mostlyoriginal/game/desktop/DesktopLauncher.java
// Path: core/src/net/mostlyoriginal/game/GdxArtemisGame.java // public class GdxArtemisGame extends Game { // // private static GdxArtemisGame instance; // // @Override // public void create() { // instance = this; // restart(); // } // // public void restart() { // setScreen(new GameScreen()); // } // // public static GdxArtemisGame getInstance() // { // return instance; // } // } // // Path: components/src/net/mostlyoriginal/game/component/G.java // public class G { // // public static final int LOGO_WIDTH = 280; // public static final int LOGO_HEIGHT = 221; // public static final int LAYER_CURSOR = 2000; // // public static final boolean PRODUCTION = false; // // public static final boolean INTERLACING_SIMULATION = true; // // public static final boolean DEBUG_SKIP_INTRO = (!PRODUCTION && false); // public static final boolean DEBUG_ACHIEVEMENTS = (!PRODUCTION && false); // public static final boolean DEBUG_DRAWING = (!PRODUCTION && true); // public static final boolean DEBUG_NO_MUSIC =(!PRODUCTION && false); // public static final boolean DEBUG_NO_ENTITY_RENDERING =(!PRODUCTION && false); // public static final boolean DEBUG_NO_SECOND_PASS =(!PRODUCTION && false); // public static final boolean DEBUG_NO_ACHIEVEMENTS = (!PRODUCTION && true); // public static boolean DEBUG_NO_FLOW = (!PRODUCTION && false); // public static boolean DEBUG_AIR_PLANET = (!PRODUCTION && false); // public static boolean DEBUG_NAIVE_GRAVITY = (!PRODUCTION && false); // public static boolean DEBUG_NO_CARDS = (!PRODUCTION && true); // // public static final float CARD_X = 5; // public static final float CARD_Y = 5; // // // public static final int SIMULATION_WIDTH = 220 + 50; // public static final int SIMULATION_HEIGHT = 220 + 50; // public static final int MARGIN_BETWEEN_CARDS = 5; // // public static final int LAYER_STAR = -50; // public static final int LAYER_STRUCTURES_BACKGROUND = -2; // public static final int LAYER_PLANET = 0; // public static final int LAYER_DUDES = 99; // public static final int LAYER_GHOST = 100; // public static final int LAYER_CARDS = 1000; // public static final int LAYER_CARDS_HOVER = 1001; // public static final int LAYER_CARDS_FLYING = 1002; // public static final int LAYER_ACHIEVEMENTS = 900; // public static final int LAYER_STRUCTURES = -1; // public static final int LAYER_STRUCTURES_FOREGROUND = 101; // // public static int CAMERA_ZOOM = 2; // public static final int SCREEN_WIDTH = SIMULATION_WIDTH * 2 * CAMERA_ZOOM; // private static int CARD_HEIGHT = 90; // private static int MARGIN_BETWEEN_CARD_AND_SIM = 10; // // public static int PLANET_X = (SIMULATION_WIDTH) - (SIMULATION_WIDTH / 2); // public static int PLANET_Y = MARGIN_BETWEEN_CARD_AND_SIM + CARD_HEIGHT; // private static final int MARGIN_BETWEEN_SIM_AND_ROOF = 20; // public static final int SCREEN_HEIGHT = (SIMULATION_HEIGHT + CARD_HEIGHT + MARGIN_BETWEEN_CARD_AND_SIM + MARGIN_BETWEEN_SIM_AND_ROOF) * CAMERA_ZOOM; // // public static final int PLANET_CENTER_X = PLANET_X + (SIMULATION_WIDTH / 2); // public static final int PLANET_CENTER_Y = PLANET_Y + (SIMULATION_HEIGHT / 2); // // public static final int GRADIENT_SCALE = 5; // public static float TOOL_HEIGHT = 50; // }
import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; import net.mostlyoriginal.game.GdxArtemisGame; import net.mostlyoriginal.game.component.G;
package net.mostlyoriginal.game.desktop; public class DesktopLauncher { public static void main (String[] arg) { LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
// Path: core/src/net/mostlyoriginal/game/GdxArtemisGame.java // public class GdxArtemisGame extends Game { // // private static GdxArtemisGame instance; // // @Override // public void create() { // instance = this; // restart(); // } // // public void restart() { // setScreen(new GameScreen()); // } // // public static GdxArtemisGame getInstance() // { // return instance; // } // } // // Path: components/src/net/mostlyoriginal/game/component/G.java // public class G { // // public static final int LOGO_WIDTH = 280; // public static final int LOGO_HEIGHT = 221; // public static final int LAYER_CURSOR = 2000; // // public static final boolean PRODUCTION = false; // // public static final boolean INTERLACING_SIMULATION = true; // // public static final boolean DEBUG_SKIP_INTRO = (!PRODUCTION && false); // public static final boolean DEBUG_ACHIEVEMENTS = (!PRODUCTION && false); // public static final boolean DEBUG_DRAWING = (!PRODUCTION && true); // public static final boolean DEBUG_NO_MUSIC =(!PRODUCTION && false); // public static final boolean DEBUG_NO_ENTITY_RENDERING =(!PRODUCTION && false); // public static final boolean DEBUG_NO_SECOND_PASS =(!PRODUCTION && false); // public static final boolean DEBUG_NO_ACHIEVEMENTS = (!PRODUCTION && true); // public static boolean DEBUG_NO_FLOW = (!PRODUCTION && false); // public static boolean DEBUG_AIR_PLANET = (!PRODUCTION && false); // public static boolean DEBUG_NAIVE_GRAVITY = (!PRODUCTION && false); // public static boolean DEBUG_NO_CARDS = (!PRODUCTION && true); // // public static final float CARD_X = 5; // public static final float CARD_Y = 5; // // // public static final int SIMULATION_WIDTH = 220 + 50; // public static final int SIMULATION_HEIGHT = 220 + 50; // public static final int MARGIN_BETWEEN_CARDS = 5; // // public static final int LAYER_STAR = -50; // public static final int LAYER_STRUCTURES_BACKGROUND = -2; // public static final int LAYER_PLANET = 0; // public static final int LAYER_DUDES = 99; // public static final int LAYER_GHOST = 100; // public static final int LAYER_CARDS = 1000; // public static final int LAYER_CARDS_HOVER = 1001; // public static final int LAYER_CARDS_FLYING = 1002; // public static final int LAYER_ACHIEVEMENTS = 900; // public static final int LAYER_STRUCTURES = -1; // public static final int LAYER_STRUCTURES_FOREGROUND = 101; // // public static int CAMERA_ZOOM = 2; // public static final int SCREEN_WIDTH = SIMULATION_WIDTH * 2 * CAMERA_ZOOM; // private static int CARD_HEIGHT = 90; // private static int MARGIN_BETWEEN_CARD_AND_SIM = 10; // // public static int PLANET_X = (SIMULATION_WIDTH) - (SIMULATION_WIDTH / 2); // public static int PLANET_Y = MARGIN_BETWEEN_CARD_AND_SIM + CARD_HEIGHT; // private static final int MARGIN_BETWEEN_SIM_AND_ROOF = 20; // public static final int SCREEN_HEIGHT = (SIMULATION_HEIGHT + CARD_HEIGHT + MARGIN_BETWEEN_CARD_AND_SIM + MARGIN_BETWEEN_SIM_AND_ROOF) * CAMERA_ZOOM; // // public static final int PLANET_CENTER_X = PLANET_X + (SIMULATION_WIDTH / 2); // public static final int PLANET_CENTER_Y = PLANET_Y + (SIMULATION_HEIGHT / 2); // // public static final int GRADIENT_SCALE = 5; // public static float TOOL_HEIGHT = 50; // } // Path: desktop/src/net/mostlyoriginal/game/desktop/DesktopLauncher.java import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; import net.mostlyoriginal.game.GdxArtemisGame; import net.mostlyoriginal.game.component.G; package net.mostlyoriginal.game.desktop; public class DesktopLauncher { public static void main (String[] arg) { LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.width = G.SCREEN_WIDTH;
DaanVanYperen/odb-little-fortune-planet
desktop/src/net/mostlyoriginal/game/desktop/DesktopLauncher.java
// Path: core/src/net/mostlyoriginal/game/GdxArtemisGame.java // public class GdxArtemisGame extends Game { // // private static GdxArtemisGame instance; // // @Override // public void create() { // instance = this; // restart(); // } // // public void restart() { // setScreen(new GameScreen()); // } // // public static GdxArtemisGame getInstance() // { // return instance; // } // } // // Path: components/src/net/mostlyoriginal/game/component/G.java // public class G { // // public static final int LOGO_WIDTH = 280; // public static final int LOGO_HEIGHT = 221; // public static final int LAYER_CURSOR = 2000; // // public static final boolean PRODUCTION = false; // // public static final boolean INTERLACING_SIMULATION = true; // // public static final boolean DEBUG_SKIP_INTRO = (!PRODUCTION && false); // public static final boolean DEBUG_ACHIEVEMENTS = (!PRODUCTION && false); // public static final boolean DEBUG_DRAWING = (!PRODUCTION && true); // public static final boolean DEBUG_NO_MUSIC =(!PRODUCTION && false); // public static final boolean DEBUG_NO_ENTITY_RENDERING =(!PRODUCTION && false); // public static final boolean DEBUG_NO_SECOND_PASS =(!PRODUCTION && false); // public static final boolean DEBUG_NO_ACHIEVEMENTS = (!PRODUCTION && true); // public static boolean DEBUG_NO_FLOW = (!PRODUCTION && false); // public static boolean DEBUG_AIR_PLANET = (!PRODUCTION && false); // public static boolean DEBUG_NAIVE_GRAVITY = (!PRODUCTION && false); // public static boolean DEBUG_NO_CARDS = (!PRODUCTION && true); // // public static final float CARD_X = 5; // public static final float CARD_Y = 5; // // // public static final int SIMULATION_WIDTH = 220 + 50; // public static final int SIMULATION_HEIGHT = 220 + 50; // public static final int MARGIN_BETWEEN_CARDS = 5; // // public static final int LAYER_STAR = -50; // public static final int LAYER_STRUCTURES_BACKGROUND = -2; // public static final int LAYER_PLANET = 0; // public static final int LAYER_DUDES = 99; // public static final int LAYER_GHOST = 100; // public static final int LAYER_CARDS = 1000; // public static final int LAYER_CARDS_HOVER = 1001; // public static final int LAYER_CARDS_FLYING = 1002; // public static final int LAYER_ACHIEVEMENTS = 900; // public static final int LAYER_STRUCTURES = -1; // public static final int LAYER_STRUCTURES_FOREGROUND = 101; // // public static int CAMERA_ZOOM = 2; // public static final int SCREEN_WIDTH = SIMULATION_WIDTH * 2 * CAMERA_ZOOM; // private static int CARD_HEIGHT = 90; // private static int MARGIN_BETWEEN_CARD_AND_SIM = 10; // // public static int PLANET_X = (SIMULATION_WIDTH) - (SIMULATION_WIDTH / 2); // public static int PLANET_Y = MARGIN_BETWEEN_CARD_AND_SIM + CARD_HEIGHT; // private static final int MARGIN_BETWEEN_SIM_AND_ROOF = 20; // public static final int SCREEN_HEIGHT = (SIMULATION_HEIGHT + CARD_HEIGHT + MARGIN_BETWEEN_CARD_AND_SIM + MARGIN_BETWEEN_SIM_AND_ROOF) * CAMERA_ZOOM; // // public static final int PLANET_CENTER_X = PLANET_X + (SIMULATION_WIDTH / 2); // public static final int PLANET_CENTER_Y = PLANET_Y + (SIMULATION_HEIGHT / 2); // // public static final int GRADIENT_SCALE = 5; // public static float TOOL_HEIGHT = 50; // }
import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; import net.mostlyoriginal.game.GdxArtemisGame; import net.mostlyoriginal.game.component.G;
package net.mostlyoriginal.game.desktop; public class DesktopLauncher { public static void main (String[] arg) { LwjglApplicationConfiguration config = new LwjglApplicationConfiguration(); config.width = G.SCREEN_WIDTH; config.height = G.SCREEN_HEIGHT; config.title = "Little Fortune Planet Sandbox - LD38 Post Compo";
// Path: core/src/net/mostlyoriginal/game/GdxArtemisGame.java // public class GdxArtemisGame extends Game { // // private static GdxArtemisGame instance; // // @Override // public void create() { // instance = this; // restart(); // } // // public void restart() { // setScreen(new GameScreen()); // } // // public static GdxArtemisGame getInstance() // { // return instance; // } // } // // Path: components/src/net/mostlyoriginal/game/component/G.java // public class G { // // public static final int LOGO_WIDTH = 280; // public static final int LOGO_HEIGHT = 221; // public static final int LAYER_CURSOR = 2000; // // public static final boolean PRODUCTION = false; // // public static final boolean INTERLACING_SIMULATION = true; // // public static final boolean DEBUG_SKIP_INTRO = (!PRODUCTION && false); // public static final boolean DEBUG_ACHIEVEMENTS = (!PRODUCTION && false); // public static final boolean DEBUG_DRAWING = (!PRODUCTION && true); // public static final boolean DEBUG_NO_MUSIC =(!PRODUCTION && false); // public static final boolean DEBUG_NO_ENTITY_RENDERING =(!PRODUCTION && false); // public static final boolean DEBUG_NO_SECOND_PASS =(!PRODUCTION && false); // public static final boolean DEBUG_NO_ACHIEVEMENTS = (!PRODUCTION && true); // public static boolean DEBUG_NO_FLOW = (!PRODUCTION && false); // public static boolean DEBUG_AIR_PLANET = (!PRODUCTION && false); // public static boolean DEBUG_NAIVE_GRAVITY = (!PRODUCTION && false); // public static boolean DEBUG_NO_CARDS = (!PRODUCTION && true); // // public static final float CARD_X = 5; // public static final float CARD_Y = 5; // // // public static final int SIMULATION_WIDTH = 220 + 50; // public static final int SIMULATION_HEIGHT = 220 + 50; // public static final int MARGIN_BETWEEN_CARDS = 5; // // public static final int LAYER_STAR = -50; // public static final int LAYER_STRUCTURES_BACKGROUND = -2; // public static final int LAYER_PLANET = 0; // public static final int LAYER_DUDES = 99; // public static final int LAYER_GHOST = 100; // public static final int LAYER_CARDS = 1000; // public static final int LAYER_CARDS_HOVER = 1001; // public static final int LAYER_CARDS_FLYING = 1002; // public static final int LAYER_ACHIEVEMENTS = 900; // public static final int LAYER_STRUCTURES = -1; // public static final int LAYER_STRUCTURES_FOREGROUND = 101; // // public static int CAMERA_ZOOM = 2; // public static final int SCREEN_WIDTH = SIMULATION_WIDTH * 2 * CAMERA_ZOOM; // private static int CARD_HEIGHT = 90; // private static int MARGIN_BETWEEN_CARD_AND_SIM = 10; // // public static int PLANET_X = (SIMULATION_WIDTH) - (SIMULATION_WIDTH / 2); // public static int PLANET_Y = MARGIN_BETWEEN_CARD_AND_SIM + CARD_HEIGHT; // private static final int MARGIN_BETWEEN_SIM_AND_ROOF = 20; // public static final int SCREEN_HEIGHT = (SIMULATION_HEIGHT + CARD_HEIGHT + MARGIN_BETWEEN_CARD_AND_SIM + MARGIN_BETWEEN_SIM_AND_ROOF) * CAMERA_ZOOM; // // public static final int PLANET_CENTER_X = PLANET_X + (SIMULATION_WIDTH / 2); // public static final int PLANET_CENTER_Y = PLANET_Y + (SIMULATION_HEIGHT / 2); // // public static final int GRADIENT_SCALE = 5; // public static float TOOL_HEIGHT = 50; // } // Path: desktop/src/net/mostlyoriginal/game/desktop/DesktopLauncher.java import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; import net.mostlyoriginal.game.GdxArtemisGame; import net.mostlyoriginal.game.component.G; package net.mostlyoriginal.game.desktop; public class DesktopLauncher { public static void main (String[] arg) { LwjglApplicationConfiguration config = new LwjglApplicationConfiguration(); config.width = G.SCREEN_WIDTH; config.height = G.SCREEN_HEIGHT; config.title = "Little Fortune Planet Sandbox - LD38 Post Compo";
new LwjglApplication(new GdxArtemisGame(), config);
DaanVanYperen/odb-little-fortune-planet
html/src/net/mostlyoriginal/game/client/HtmlLauncher.java
// Path: core/src/net/mostlyoriginal/game/GdxArtemisGame.java // public class GdxArtemisGame extends Game { // // private static GdxArtemisGame instance; // // @Override // public void create() { // instance = this; // restart(); // } // // public void restart() { // setScreen(new GameScreen()); // } // // public static GdxArtemisGame getInstance() // { // return instance; // } // } // // Path: components/src/net/mostlyoriginal/game/component/G.java // public class G { // // public static final int LOGO_WIDTH = 280; // public static final int LOGO_HEIGHT = 221; // public static final int LAYER_CURSOR = 2000; // // public static final boolean PRODUCTION = false; // // public static final boolean INTERLACING_SIMULATION = true; // // public static final boolean DEBUG_SKIP_INTRO = (!PRODUCTION && false); // public static final boolean DEBUG_ACHIEVEMENTS = (!PRODUCTION && false); // public static final boolean DEBUG_DRAWING = (!PRODUCTION && true); // public static final boolean DEBUG_NO_MUSIC =(!PRODUCTION && false); // public static final boolean DEBUG_NO_ENTITY_RENDERING =(!PRODUCTION && false); // public static final boolean DEBUG_NO_SECOND_PASS =(!PRODUCTION && false); // public static final boolean DEBUG_NO_ACHIEVEMENTS = (!PRODUCTION && true); // public static boolean DEBUG_NO_FLOW = (!PRODUCTION && false); // public static boolean DEBUG_AIR_PLANET = (!PRODUCTION && false); // public static boolean DEBUG_NAIVE_GRAVITY = (!PRODUCTION && false); // public static boolean DEBUG_NO_CARDS = (!PRODUCTION && true); // // public static final float CARD_X = 5; // public static final float CARD_Y = 5; // // // public static final int SIMULATION_WIDTH = 220 + 50; // public static final int SIMULATION_HEIGHT = 220 + 50; // public static final int MARGIN_BETWEEN_CARDS = 5; // // public static final int LAYER_STAR = -50; // public static final int LAYER_STRUCTURES_BACKGROUND = -2; // public static final int LAYER_PLANET = 0; // public static final int LAYER_DUDES = 99; // public static final int LAYER_GHOST = 100; // public static final int LAYER_CARDS = 1000; // public static final int LAYER_CARDS_HOVER = 1001; // public static final int LAYER_CARDS_FLYING = 1002; // public static final int LAYER_ACHIEVEMENTS = 900; // public static final int LAYER_STRUCTURES = -1; // public static final int LAYER_STRUCTURES_FOREGROUND = 101; // // public static int CAMERA_ZOOM = 2; // public static final int SCREEN_WIDTH = SIMULATION_WIDTH * 2 * CAMERA_ZOOM; // private static int CARD_HEIGHT = 90; // private static int MARGIN_BETWEEN_CARD_AND_SIM = 10; // // public static int PLANET_X = (SIMULATION_WIDTH) - (SIMULATION_WIDTH / 2); // public static int PLANET_Y = MARGIN_BETWEEN_CARD_AND_SIM + CARD_HEIGHT; // private static final int MARGIN_BETWEEN_SIM_AND_ROOF = 20; // public static final int SCREEN_HEIGHT = (SIMULATION_HEIGHT + CARD_HEIGHT + MARGIN_BETWEEN_CARD_AND_SIM + MARGIN_BETWEEN_SIM_AND_ROOF) * CAMERA_ZOOM; // // public static final int PLANET_CENTER_X = PLANET_X + (SIMULATION_WIDTH / 2); // public static final int PLANET_CENTER_Y = PLANET_Y + (SIMULATION_HEIGHT / 2); // // public static final int GRADIENT_SCALE = 5; // public static float TOOL_HEIGHT = 50; // }
import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.backends.gwt.GwtApplication; import com.badlogic.gdx.backends.gwt.GwtApplicationConfiguration; import com.badlogic.gdx.backends.gwt.preloader.Preloader; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.Style; import com.google.gwt.user.client.ui.*; import net.mostlyoriginal.game.GdxArtemisGame; import net.mostlyoriginal.game.component.G;
package net.mostlyoriginal.game.client; public class HtmlLauncher extends GwtApplication { @Override public GwtApplicationConfiguration getConfig() {
// Path: core/src/net/mostlyoriginal/game/GdxArtemisGame.java // public class GdxArtemisGame extends Game { // // private static GdxArtemisGame instance; // // @Override // public void create() { // instance = this; // restart(); // } // // public void restart() { // setScreen(new GameScreen()); // } // // public static GdxArtemisGame getInstance() // { // return instance; // } // } // // Path: components/src/net/mostlyoriginal/game/component/G.java // public class G { // // public static final int LOGO_WIDTH = 280; // public static final int LOGO_HEIGHT = 221; // public static final int LAYER_CURSOR = 2000; // // public static final boolean PRODUCTION = false; // // public static final boolean INTERLACING_SIMULATION = true; // // public static final boolean DEBUG_SKIP_INTRO = (!PRODUCTION && false); // public static final boolean DEBUG_ACHIEVEMENTS = (!PRODUCTION && false); // public static final boolean DEBUG_DRAWING = (!PRODUCTION && true); // public static final boolean DEBUG_NO_MUSIC =(!PRODUCTION && false); // public static final boolean DEBUG_NO_ENTITY_RENDERING =(!PRODUCTION && false); // public static final boolean DEBUG_NO_SECOND_PASS =(!PRODUCTION && false); // public static final boolean DEBUG_NO_ACHIEVEMENTS = (!PRODUCTION && true); // public static boolean DEBUG_NO_FLOW = (!PRODUCTION && false); // public static boolean DEBUG_AIR_PLANET = (!PRODUCTION && false); // public static boolean DEBUG_NAIVE_GRAVITY = (!PRODUCTION && false); // public static boolean DEBUG_NO_CARDS = (!PRODUCTION && true); // // public static final float CARD_X = 5; // public static final float CARD_Y = 5; // // // public static final int SIMULATION_WIDTH = 220 + 50; // public static final int SIMULATION_HEIGHT = 220 + 50; // public static final int MARGIN_BETWEEN_CARDS = 5; // // public static final int LAYER_STAR = -50; // public static final int LAYER_STRUCTURES_BACKGROUND = -2; // public static final int LAYER_PLANET = 0; // public static final int LAYER_DUDES = 99; // public static final int LAYER_GHOST = 100; // public static final int LAYER_CARDS = 1000; // public static final int LAYER_CARDS_HOVER = 1001; // public static final int LAYER_CARDS_FLYING = 1002; // public static final int LAYER_ACHIEVEMENTS = 900; // public static final int LAYER_STRUCTURES = -1; // public static final int LAYER_STRUCTURES_FOREGROUND = 101; // // public static int CAMERA_ZOOM = 2; // public static final int SCREEN_WIDTH = SIMULATION_WIDTH * 2 * CAMERA_ZOOM; // private static int CARD_HEIGHT = 90; // private static int MARGIN_BETWEEN_CARD_AND_SIM = 10; // // public static int PLANET_X = (SIMULATION_WIDTH) - (SIMULATION_WIDTH / 2); // public static int PLANET_Y = MARGIN_BETWEEN_CARD_AND_SIM + CARD_HEIGHT; // private static final int MARGIN_BETWEEN_SIM_AND_ROOF = 20; // public static final int SCREEN_HEIGHT = (SIMULATION_HEIGHT + CARD_HEIGHT + MARGIN_BETWEEN_CARD_AND_SIM + MARGIN_BETWEEN_SIM_AND_ROOF) * CAMERA_ZOOM; // // public static final int PLANET_CENTER_X = PLANET_X + (SIMULATION_WIDTH / 2); // public static final int PLANET_CENTER_Y = PLANET_Y + (SIMULATION_HEIGHT / 2); // // public static final int GRADIENT_SCALE = 5; // public static float TOOL_HEIGHT = 50; // } // Path: html/src/net/mostlyoriginal/game/client/HtmlLauncher.java import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.backends.gwt.GwtApplication; import com.badlogic.gdx.backends.gwt.GwtApplicationConfiguration; import com.badlogic.gdx.backends.gwt.preloader.Preloader; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.Style; import com.google.gwt.user.client.ui.*; import net.mostlyoriginal.game.GdxArtemisGame; import net.mostlyoriginal.game.component.G; package net.mostlyoriginal.game.client; public class HtmlLauncher extends GwtApplication { @Override public GwtApplicationConfiguration getConfig() {
GwtApplicationConfiguration configuration = new GwtApplicationConfiguration(G.SCREEN_WIDTH, G.SCREEN_HEIGHT);
DaanVanYperen/odb-little-fortune-planet
html/src/net/mostlyoriginal/game/client/HtmlLauncher.java
// Path: core/src/net/mostlyoriginal/game/GdxArtemisGame.java // public class GdxArtemisGame extends Game { // // private static GdxArtemisGame instance; // // @Override // public void create() { // instance = this; // restart(); // } // // public void restart() { // setScreen(new GameScreen()); // } // // public static GdxArtemisGame getInstance() // { // return instance; // } // } // // Path: components/src/net/mostlyoriginal/game/component/G.java // public class G { // // public static final int LOGO_WIDTH = 280; // public static final int LOGO_HEIGHT = 221; // public static final int LAYER_CURSOR = 2000; // // public static final boolean PRODUCTION = false; // // public static final boolean INTERLACING_SIMULATION = true; // // public static final boolean DEBUG_SKIP_INTRO = (!PRODUCTION && false); // public static final boolean DEBUG_ACHIEVEMENTS = (!PRODUCTION && false); // public static final boolean DEBUG_DRAWING = (!PRODUCTION && true); // public static final boolean DEBUG_NO_MUSIC =(!PRODUCTION && false); // public static final boolean DEBUG_NO_ENTITY_RENDERING =(!PRODUCTION && false); // public static final boolean DEBUG_NO_SECOND_PASS =(!PRODUCTION && false); // public static final boolean DEBUG_NO_ACHIEVEMENTS = (!PRODUCTION && true); // public static boolean DEBUG_NO_FLOW = (!PRODUCTION && false); // public static boolean DEBUG_AIR_PLANET = (!PRODUCTION && false); // public static boolean DEBUG_NAIVE_GRAVITY = (!PRODUCTION && false); // public static boolean DEBUG_NO_CARDS = (!PRODUCTION && true); // // public static final float CARD_X = 5; // public static final float CARD_Y = 5; // // // public static final int SIMULATION_WIDTH = 220 + 50; // public static final int SIMULATION_HEIGHT = 220 + 50; // public static final int MARGIN_BETWEEN_CARDS = 5; // // public static final int LAYER_STAR = -50; // public static final int LAYER_STRUCTURES_BACKGROUND = -2; // public static final int LAYER_PLANET = 0; // public static final int LAYER_DUDES = 99; // public static final int LAYER_GHOST = 100; // public static final int LAYER_CARDS = 1000; // public static final int LAYER_CARDS_HOVER = 1001; // public static final int LAYER_CARDS_FLYING = 1002; // public static final int LAYER_ACHIEVEMENTS = 900; // public static final int LAYER_STRUCTURES = -1; // public static final int LAYER_STRUCTURES_FOREGROUND = 101; // // public static int CAMERA_ZOOM = 2; // public static final int SCREEN_WIDTH = SIMULATION_WIDTH * 2 * CAMERA_ZOOM; // private static int CARD_HEIGHT = 90; // private static int MARGIN_BETWEEN_CARD_AND_SIM = 10; // // public static int PLANET_X = (SIMULATION_WIDTH) - (SIMULATION_WIDTH / 2); // public static int PLANET_Y = MARGIN_BETWEEN_CARD_AND_SIM + CARD_HEIGHT; // private static final int MARGIN_BETWEEN_SIM_AND_ROOF = 20; // public static final int SCREEN_HEIGHT = (SIMULATION_HEIGHT + CARD_HEIGHT + MARGIN_BETWEEN_CARD_AND_SIM + MARGIN_BETWEEN_SIM_AND_ROOF) * CAMERA_ZOOM; // // public static final int PLANET_CENTER_X = PLANET_X + (SIMULATION_WIDTH / 2); // public static final int PLANET_CENTER_Y = PLANET_Y + (SIMULATION_HEIGHT / 2); // // public static final int GRADIENT_SCALE = 5; // public static float TOOL_HEIGHT = 50; // }
import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.backends.gwt.GwtApplication; import com.badlogic.gdx.backends.gwt.GwtApplicationConfiguration; import com.badlogic.gdx.backends.gwt.preloader.Preloader; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.Style; import com.google.gwt.user.client.ui.*; import net.mostlyoriginal.game.GdxArtemisGame; import net.mostlyoriginal.game.component.G;
package net.mostlyoriginal.game.client; public class HtmlLauncher extends GwtApplication { @Override public GwtApplicationConfiguration getConfig() { GwtApplicationConfiguration configuration = new GwtApplicationConfiguration(G.SCREEN_WIDTH, G.SCREEN_HEIGHT); return configuration; } @Override public ApplicationListener createApplicationListener() {
// Path: core/src/net/mostlyoriginal/game/GdxArtemisGame.java // public class GdxArtemisGame extends Game { // // private static GdxArtemisGame instance; // // @Override // public void create() { // instance = this; // restart(); // } // // public void restart() { // setScreen(new GameScreen()); // } // // public static GdxArtemisGame getInstance() // { // return instance; // } // } // // Path: components/src/net/mostlyoriginal/game/component/G.java // public class G { // // public static final int LOGO_WIDTH = 280; // public static final int LOGO_HEIGHT = 221; // public static final int LAYER_CURSOR = 2000; // // public static final boolean PRODUCTION = false; // // public static final boolean INTERLACING_SIMULATION = true; // // public static final boolean DEBUG_SKIP_INTRO = (!PRODUCTION && false); // public static final boolean DEBUG_ACHIEVEMENTS = (!PRODUCTION && false); // public static final boolean DEBUG_DRAWING = (!PRODUCTION && true); // public static final boolean DEBUG_NO_MUSIC =(!PRODUCTION && false); // public static final boolean DEBUG_NO_ENTITY_RENDERING =(!PRODUCTION && false); // public static final boolean DEBUG_NO_SECOND_PASS =(!PRODUCTION && false); // public static final boolean DEBUG_NO_ACHIEVEMENTS = (!PRODUCTION && true); // public static boolean DEBUG_NO_FLOW = (!PRODUCTION && false); // public static boolean DEBUG_AIR_PLANET = (!PRODUCTION && false); // public static boolean DEBUG_NAIVE_GRAVITY = (!PRODUCTION && false); // public static boolean DEBUG_NO_CARDS = (!PRODUCTION && true); // // public static final float CARD_X = 5; // public static final float CARD_Y = 5; // // // public static final int SIMULATION_WIDTH = 220 + 50; // public static final int SIMULATION_HEIGHT = 220 + 50; // public static final int MARGIN_BETWEEN_CARDS = 5; // // public static final int LAYER_STAR = -50; // public static final int LAYER_STRUCTURES_BACKGROUND = -2; // public static final int LAYER_PLANET = 0; // public static final int LAYER_DUDES = 99; // public static final int LAYER_GHOST = 100; // public static final int LAYER_CARDS = 1000; // public static final int LAYER_CARDS_HOVER = 1001; // public static final int LAYER_CARDS_FLYING = 1002; // public static final int LAYER_ACHIEVEMENTS = 900; // public static final int LAYER_STRUCTURES = -1; // public static final int LAYER_STRUCTURES_FOREGROUND = 101; // // public static int CAMERA_ZOOM = 2; // public static final int SCREEN_WIDTH = SIMULATION_WIDTH * 2 * CAMERA_ZOOM; // private static int CARD_HEIGHT = 90; // private static int MARGIN_BETWEEN_CARD_AND_SIM = 10; // // public static int PLANET_X = (SIMULATION_WIDTH) - (SIMULATION_WIDTH / 2); // public static int PLANET_Y = MARGIN_BETWEEN_CARD_AND_SIM + CARD_HEIGHT; // private static final int MARGIN_BETWEEN_SIM_AND_ROOF = 20; // public static final int SCREEN_HEIGHT = (SIMULATION_HEIGHT + CARD_HEIGHT + MARGIN_BETWEEN_CARD_AND_SIM + MARGIN_BETWEEN_SIM_AND_ROOF) * CAMERA_ZOOM; // // public static final int PLANET_CENTER_X = PLANET_X + (SIMULATION_WIDTH / 2); // public static final int PLANET_CENTER_Y = PLANET_Y + (SIMULATION_HEIGHT / 2); // // public static final int GRADIENT_SCALE = 5; // public static float TOOL_HEIGHT = 50; // } // Path: html/src/net/mostlyoriginal/game/client/HtmlLauncher.java import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.backends.gwt.GwtApplication; import com.badlogic.gdx.backends.gwt.GwtApplicationConfiguration; import com.badlogic.gdx.backends.gwt.preloader.Preloader; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.Style; import com.google.gwt.user.client.ui.*; import net.mostlyoriginal.game.GdxArtemisGame; import net.mostlyoriginal.game.component.G; package net.mostlyoriginal.game.client; public class HtmlLauncher extends GwtApplication { @Override public GwtApplicationConfiguration getConfig() { GwtApplicationConfiguration configuration = new GwtApplicationConfiguration(G.SCREEN_WIDTH, G.SCREEN_HEIGHT); return configuration; } @Override public ApplicationListener createApplicationListener() {
return new GdxArtemisGame();
DaanVanYperen/odb-little-fortune-planet
components/src/net/mostlyoriginal/game/component/PlanetData.java
// Path: components/src/net/mostlyoriginal/game/component/PlanetCell.java // public class PlanetCell { // public static final int SPACE_AIR_STARTS_AT_DEPTH = 20; // public int x; // public int y; // public int color = 0; // public int down = -1; // public float height = 0; // public CellType type = CellType.STATIC; // // // public CellType nextType = null; // public int nextColor = -1; // // public static int[][] directions = { // {-1, -1}, // {0, -1}, // {1, -1}, // {1, 0}, // {1, 1}, // {0, 1}, // {-1, 1}, // {-1, 0} // }; // // public int sleep; // // public int up() { // return (down + 4) % 8; // } // // public int left() { // return (down + 6) % 8; // } // // public int right() { // return (down + 2) % 8; // } // // public int upL() { // return (down + 3) % 8; // } // // public int downL() { // return (down + 7) % 8; // } // // public int downR() { // return (down + 1) % 8; // } // // public int upR() { // return (down + 5) % 8; // } // // public void activateNextType() { // if (nextType != null) { // type = nextType; // nextType = null; // sleep=0; // } // if (nextColor != -1) { // color = nextColor; // nextColor = -1; // } // } // // public float depth() { // return ((G.SIMULATION_WIDTH / 2) - height); // } // // public enum CellType { // STATIC(null, false), // LAVA(5f, true), // WATER(1f, true), // AIR(0f, true), // ICE(null, false), // STEAM(-0.5f, true), // LAVA_CRUST(5f, true), // CLOUD(-0.7f, false), // FIRE(-0.7f, false), // NOTHING(-100f,false), // ORGANIC(null, false), ORGANIC_SPORE(-0.7f, false); // // public final Float density; // private boolean flows; // // CellType(Float density, boolean flows) { // this.density = density; // this.flows = flows; // } // // public boolean flows() { // return flows; // } // // public boolean isLighter(CellType type) { // return type.density != null && density != null && type.density < density; // } // } // // public boolean isSpaceAir() { // return depth() < SPACE_AIR_STARTS_AT_DEPTH && type == PlanetCell.CellType.AIR; // } // }
import net.mostlyoriginal.game.component.PlanetCell;
package net.mostlyoriginal.game.component; /** * @author Daan van Yperen */ public class PlanetData { public String id; public String comment; // not used. public String texture; public String backgroundTexture; public String dirtTexture; public CellType[] types; public String spaceBackgroundColor; public static class CellType { public String color; public String colorSecondary;
// Path: components/src/net/mostlyoriginal/game/component/PlanetCell.java // public class PlanetCell { // public static final int SPACE_AIR_STARTS_AT_DEPTH = 20; // public int x; // public int y; // public int color = 0; // public int down = -1; // public float height = 0; // public CellType type = CellType.STATIC; // // // public CellType nextType = null; // public int nextColor = -1; // // public static int[][] directions = { // {-1, -1}, // {0, -1}, // {1, -1}, // {1, 0}, // {1, 1}, // {0, 1}, // {-1, 1}, // {-1, 0} // }; // // public int sleep; // // public int up() { // return (down + 4) % 8; // } // // public int left() { // return (down + 6) % 8; // } // // public int right() { // return (down + 2) % 8; // } // // public int upL() { // return (down + 3) % 8; // } // // public int downL() { // return (down + 7) % 8; // } // // public int downR() { // return (down + 1) % 8; // } // // public int upR() { // return (down + 5) % 8; // } // // public void activateNextType() { // if (nextType != null) { // type = nextType; // nextType = null; // sleep=0; // } // if (nextColor != -1) { // color = nextColor; // nextColor = -1; // } // } // // public float depth() { // return ((G.SIMULATION_WIDTH / 2) - height); // } // // public enum CellType { // STATIC(null, false), // LAVA(5f, true), // WATER(1f, true), // AIR(0f, true), // ICE(null, false), // STEAM(-0.5f, true), // LAVA_CRUST(5f, true), // CLOUD(-0.7f, false), // FIRE(-0.7f, false), // NOTHING(-100f,false), // ORGANIC(null, false), ORGANIC_SPORE(-0.7f, false); // // public final Float density; // private boolean flows; // // CellType(Float density, boolean flows) { // this.density = density; // this.flows = flows; // } // // public boolean flows() { // return flows; // } // // public boolean isLighter(CellType type) { // return type.density != null && density != null && type.density < density; // } // } // // public boolean isSpaceAir() { // return depth() < SPACE_AIR_STARTS_AT_DEPTH && type == PlanetCell.CellType.AIR; // } // } // Path: components/src/net/mostlyoriginal/game/component/PlanetData.java import net.mostlyoriginal.game.component.PlanetCell; package net.mostlyoriginal.game.component; /** * @author Daan van Yperen */ public class PlanetData { public String id; public String comment; // not used. public String texture; public String backgroundTexture; public String dirtTexture; public CellType[] types; public String spaceBackgroundColor; public static class CellType { public String color; public String colorSecondary;
public PlanetCell.CellType type;
DaanVanYperen/odb-little-fortune-planet
core/src/net/mostlyoriginal/game/system/planet/cells/FireCellSimulator.java
// Path: components/src/net/mostlyoriginal/game/component/PlanetCell.java // public class PlanetCell { // public static final int SPACE_AIR_STARTS_AT_DEPTH = 20; // public int x; // public int y; // public int color = 0; // public int down = -1; // public float height = 0; // public CellType type = CellType.STATIC; // // // public CellType nextType = null; // public int nextColor = -1; // // public static int[][] directions = { // {-1, -1}, // {0, -1}, // {1, -1}, // {1, 0}, // {1, 1}, // {0, 1}, // {-1, 1}, // {-1, 0} // }; // // public int sleep; // // public int up() { // return (down + 4) % 8; // } // // public int left() { // return (down + 6) % 8; // } // // public int right() { // return (down + 2) % 8; // } // // public int upL() { // return (down + 3) % 8; // } // // public int downL() { // return (down + 7) % 8; // } // // public int downR() { // return (down + 1) % 8; // } // // public int upR() { // return (down + 5) % 8; // } // // public void activateNextType() { // if (nextType != null) { // type = nextType; // nextType = null; // sleep=0; // } // if (nextColor != -1) { // color = nextColor; // nextColor = -1; // } // } // // public float depth() { // return ((G.SIMULATION_WIDTH / 2) - height); // } // // public enum CellType { // STATIC(null, false), // LAVA(5f, true), // WATER(1f, true), // AIR(0f, true), // ICE(null, false), // STEAM(-0.5f, true), // LAVA_CRUST(5f, true), // CLOUD(-0.7f, false), // FIRE(-0.7f, false), // NOTHING(-100f,false), // ORGANIC(null, false), ORGANIC_SPORE(-0.7f, false); // // public final Float density; // private boolean flows; // // CellType(Float density, boolean flows) { // this.density = density; // this.flows = flows; // } // // public boolean flows() { // return flows; // } // // public boolean isLighter(CellType type) { // return type.density != null && density != null && type.density < density; // } // } // // public boolean isSpaceAir() { // return depth() < SPACE_AIR_STARTS_AT_DEPTH && type == PlanetCell.CellType.AIR; // } // }
import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.math.MathUtils; import net.mostlyoriginal.game.component.PlanetCell;
package net.mostlyoriginal.game.system.planet.cells; /** * @author Daan van Yperen */ public class FireCellSimulator implements CellSimulator { Color coldColor; Color aridColor; Color workColor = new Color(); @Override public void color(CellDecorator c, float delta) { if (aridColor == null) { coldColor = new Color(); aridColor = new Color();
// Path: components/src/net/mostlyoriginal/game/component/PlanetCell.java // public class PlanetCell { // public static final int SPACE_AIR_STARTS_AT_DEPTH = 20; // public int x; // public int y; // public int color = 0; // public int down = -1; // public float height = 0; // public CellType type = CellType.STATIC; // // // public CellType nextType = null; // public int nextColor = -1; // // public static int[][] directions = { // {-1, -1}, // {0, -1}, // {1, -1}, // {1, 0}, // {1, 1}, // {0, 1}, // {-1, 1}, // {-1, 0} // }; // // public int sleep; // // public int up() { // return (down + 4) % 8; // } // // public int left() { // return (down + 6) % 8; // } // // public int right() { // return (down + 2) % 8; // } // // public int upL() { // return (down + 3) % 8; // } // // public int downL() { // return (down + 7) % 8; // } // // public int downR() { // return (down + 1) % 8; // } // // public int upR() { // return (down + 5) % 8; // } // // public void activateNextType() { // if (nextType != null) { // type = nextType; // nextType = null; // sleep=0; // } // if (nextColor != -1) { // color = nextColor; // nextColor = -1; // } // } // // public float depth() { // return ((G.SIMULATION_WIDTH / 2) - height); // } // // public enum CellType { // STATIC(null, false), // LAVA(5f, true), // WATER(1f, true), // AIR(0f, true), // ICE(null, false), // STEAM(-0.5f, true), // LAVA_CRUST(5f, true), // CLOUD(-0.7f, false), // FIRE(-0.7f, false), // NOTHING(-100f,false), // ORGANIC(null, false), ORGANIC_SPORE(-0.7f, false); // // public final Float density; // private boolean flows; // // CellType(Float density, boolean flows) { // this.density = density; // this.flows = flows; // } // // public boolean flows() { // return flows; // } // // public boolean isLighter(CellType type) { // return type.density != null && density != null && type.density < density; // } // } // // public boolean isSpaceAir() { // return depth() < SPACE_AIR_STARTS_AT_DEPTH && type == PlanetCell.CellType.AIR; // } // } // Path: core/src/net/mostlyoriginal/game/system/planet/cells/FireCellSimulator.java import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.math.MathUtils; import net.mostlyoriginal.game.component.PlanetCell; package net.mostlyoriginal.game.system.planet.cells; /** * @author Daan van Yperen */ public class FireCellSimulator implements CellSimulator { Color coldColor; Color aridColor; Color workColor = new Color(); @Override public void color(CellDecorator c, float delta) { if (aridColor == null) { coldColor = new Color(); aridColor = new Color();
Color.rgba8888ToColor(coldColor, c.planet.cellColor[PlanetCell.CellType.FIRE.ordinal()]);
DaanVanYperen/odb-little-fortune-planet
core/src/net/mostlyoriginal/game/system/planet/cells/OrganicSporeCellSimulator.java
// Path: components/src/net/mostlyoriginal/game/component/PlanetCell.java // public class PlanetCell { // public static final int SPACE_AIR_STARTS_AT_DEPTH = 20; // public int x; // public int y; // public int color = 0; // public int down = -1; // public float height = 0; // public CellType type = CellType.STATIC; // // // public CellType nextType = null; // public int nextColor = -1; // // public static int[][] directions = { // {-1, -1}, // {0, -1}, // {1, -1}, // {1, 0}, // {1, 1}, // {0, 1}, // {-1, 1}, // {-1, 0} // }; // // public int sleep; // // public int up() { // return (down + 4) % 8; // } // // public int left() { // return (down + 6) % 8; // } // // public int right() { // return (down + 2) % 8; // } // // public int upL() { // return (down + 3) % 8; // } // // public int downL() { // return (down + 7) % 8; // } // // public int downR() { // return (down + 1) % 8; // } // // public int upR() { // return (down + 5) % 8; // } // // public void activateNextType() { // if (nextType != null) { // type = nextType; // nextType = null; // sleep=0; // } // if (nextColor != -1) { // color = nextColor; // nextColor = -1; // } // } // // public float depth() { // return ((G.SIMULATION_WIDTH / 2) - height); // } // // public enum CellType { // STATIC(null, false), // LAVA(5f, true), // WATER(1f, true), // AIR(0f, true), // ICE(null, false), // STEAM(-0.5f, true), // LAVA_CRUST(5f, true), // CLOUD(-0.7f, false), // FIRE(-0.7f, false), // NOTHING(-100f,false), // ORGANIC(null, false), ORGANIC_SPORE(-0.7f, false); // // public final Float density; // private boolean flows; // // CellType(Float density, boolean flows) { // this.density = density; // this.flows = flows; // } // // public boolean flows() { // return flows; // } // // public boolean isLighter(CellType type) { // return type.density != null && density != null && type.density < density; // } // } // // public boolean isSpaceAir() { // return depth() < SPACE_AIR_STARTS_AT_DEPTH && type == PlanetCell.CellType.AIR; // } // }
import net.mostlyoriginal.game.component.PlanetCell;
package net.mostlyoriginal.game.system.planet.cells; /** * @author Daan van Yperen */ public class OrganicSporeCellSimulator implements CellSimulator { @Override public void color(CellDecorator c, float delta) { c.cell.color = c.planet.cellColor[c.cell.type.ordinal()]; } @Override public void process(CellDecorator c, float delta) { if (c.cell.nextType == null) {
// Path: components/src/net/mostlyoriginal/game/component/PlanetCell.java // public class PlanetCell { // public static final int SPACE_AIR_STARTS_AT_DEPTH = 20; // public int x; // public int y; // public int color = 0; // public int down = -1; // public float height = 0; // public CellType type = CellType.STATIC; // // // public CellType nextType = null; // public int nextColor = -1; // // public static int[][] directions = { // {-1, -1}, // {0, -1}, // {1, -1}, // {1, 0}, // {1, 1}, // {0, 1}, // {-1, 1}, // {-1, 0} // }; // // public int sleep; // // public int up() { // return (down + 4) % 8; // } // // public int left() { // return (down + 6) % 8; // } // // public int right() { // return (down + 2) % 8; // } // // public int upL() { // return (down + 3) % 8; // } // // public int downL() { // return (down + 7) % 8; // } // // public int downR() { // return (down + 1) % 8; // } // // public int upR() { // return (down + 5) % 8; // } // // public void activateNextType() { // if (nextType != null) { // type = nextType; // nextType = null; // sleep=0; // } // if (nextColor != -1) { // color = nextColor; // nextColor = -1; // } // } // // public float depth() { // return ((G.SIMULATION_WIDTH / 2) - height); // } // // public enum CellType { // STATIC(null, false), // LAVA(5f, true), // WATER(1f, true), // AIR(0f, true), // ICE(null, false), // STEAM(-0.5f, true), // LAVA_CRUST(5f, true), // CLOUD(-0.7f, false), // FIRE(-0.7f, false), // NOTHING(-100f,false), // ORGANIC(null, false), ORGANIC_SPORE(-0.7f, false); // // public final Float density; // private boolean flows; // // CellType(Float density, boolean flows) { // this.density = density; // this.flows = flows; // } // // public boolean flows() { // return flows; // } // // public boolean isLighter(CellType type) { // return type.density != null && density != null && type.density < density; // } // } // // public boolean isSpaceAir() { // return depth() < SPACE_AIR_STARTS_AT_DEPTH && type == PlanetCell.CellType.AIR; // } // } // Path: core/src/net/mostlyoriginal/game/system/planet/cells/OrganicSporeCellSimulator.java import net.mostlyoriginal.game.component.PlanetCell; package net.mostlyoriginal.game.system.planet.cells; /** * @author Daan van Yperen */ public class OrganicSporeCellSimulator implements CellSimulator { @Override public void color(CellDecorator c, float delta) { c.cell.color = c.planet.cellColor[c.cell.type.ordinal()]; } @Override public void process(CellDecorator c, float delta) { if (c.cell.nextType == null) {
if (c.getNeighbour(PlanetCell.CellType.FIRE, PlanetCell.CellType.LAVA, PlanetCell.CellType.LAVA_CRUST) != null) {
DaanVanYperen/odb-little-fortune-planet
core/src/net/mostlyoriginal/game/system/StarEffectSystem.java
// Path: components/src/net/mostlyoriginal/game/component/G.java // public class G { // // public static final int LOGO_WIDTH = 280; // public static final int LOGO_HEIGHT = 221; // public static final int LAYER_CURSOR = 2000; // // public static final boolean PRODUCTION = false; // // public static final boolean INTERLACING_SIMULATION = true; // // public static final boolean DEBUG_SKIP_INTRO = (!PRODUCTION && false); // public static final boolean DEBUG_ACHIEVEMENTS = (!PRODUCTION && false); // public static final boolean DEBUG_DRAWING = (!PRODUCTION && true); // public static final boolean DEBUG_NO_MUSIC =(!PRODUCTION && false); // public static final boolean DEBUG_NO_ENTITY_RENDERING =(!PRODUCTION && false); // public static final boolean DEBUG_NO_SECOND_PASS =(!PRODUCTION && false); // public static final boolean DEBUG_NO_ACHIEVEMENTS = (!PRODUCTION && true); // public static boolean DEBUG_NO_FLOW = (!PRODUCTION && false); // public static boolean DEBUG_AIR_PLANET = (!PRODUCTION && false); // public static boolean DEBUG_NAIVE_GRAVITY = (!PRODUCTION && false); // public static boolean DEBUG_NO_CARDS = (!PRODUCTION && true); // // public static final float CARD_X = 5; // public static final float CARD_Y = 5; // // // public static final int SIMULATION_WIDTH = 220 + 50; // public static final int SIMULATION_HEIGHT = 220 + 50; // public static final int MARGIN_BETWEEN_CARDS = 5; // // public static final int LAYER_STAR = -50; // public static final int LAYER_STRUCTURES_BACKGROUND = -2; // public static final int LAYER_PLANET = 0; // public static final int LAYER_DUDES = 99; // public static final int LAYER_GHOST = 100; // public static final int LAYER_CARDS = 1000; // public static final int LAYER_CARDS_HOVER = 1001; // public static final int LAYER_CARDS_FLYING = 1002; // public static final int LAYER_ACHIEVEMENTS = 900; // public static final int LAYER_STRUCTURES = -1; // public static final int LAYER_STRUCTURES_FOREGROUND = 101; // // public static int CAMERA_ZOOM = 2; // public static final int SCREEN_WIDTH = SIMULATION_WIDTH * 2 * CAMERA_ZOOM; // private static int CARD_HEIGHT = 90; // private static int MARGIN_BETWEEN_CARD_AND_SIM = 10; // // public static int PLANET_X = (SIMULATION_WIDTH) - (SIMULATION_WIDTH / 2); // public static int PLANET_Y = MARGIN_BETWEEN_CARD_AND_SIM + CARD_HEIGHT; // private static final int MARGIN_BETWEEN_SIM_AND_ROOF = 20; // public static final int SCREEN_HEIGHT = (SIMULATION_HEIGHT + CARD_HEIGHT + MARGIN_BETWEEN_CARD_AND_SIM + MARGIN_BETWEEN_SIM_AND_ROOF) * CAMERA_ZOOM; // // public static final int PLANET_CENTER_X = PLANET_X + (SIMULATION_WIDTH / 2); // public static final int PLANET_CENTER_Y = PLANET_Y + (SIMULATION_HEIGHT / 2); // // public static final int GRADIENT_SCALE = 5; // public static float TOOL_HEIGHT = 50; // } // // Path: components/src/net/mostlyoriginal/game/component/Star.java // public class Star extends Component { // public Star() { // } // public final String animId[] = new String[6]; // public final float speedFactor = 1f + MathUtils.random(-0.2f,0.5f); // public float blinkTimer = MathUtils.random(0f,10f); // // public void set(int kind) { // animId[0] = "star-" + kind + "-0"; // animId[1] = "star-" + kind + "-1"; // animId[2] = "star-" + kind + "-2"; // animId[3] = "star-" + kind + "-3"; // animId[4] = "star-" + kind + "-4"; // animId[5] = "star-" + kind + "-5"; // } // } // // Path: core/src/net/mostlyoriginal/game/system/common/FluidIteratingSystem.java // public abstract class FluidIteratingSystem extends IteratingSystem { // // public FluidIteratingSystem(Aspect.Builder aspect) { // super(aspect); // } // // @Override // protected void process(int id) { // process(E(id)); // } // // protected abstract void process(E e); // // // protected EBag allEntitiesMatching(Aspect.Builder scope) { // return new EBag(world.getAspectSubscriptionManager().get(scope).getEntities()); // } // // protected EBag allEntitiesWith(Class<? extends Component> scope) { // return new EBag(world.getAspectSubscriptionManager().get(Aspect.all(scope)).getEntities()); // } // }
import com.artemis.Aspect; import com.artemis.ComponentMapper; import com.artemis.E; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.math.MathUtils; import net.mostlyoriginal.api.component.basic.Pos; import net.mostlyoriginal.api.component.graphics.Anim; import net.mostlyoriginal.game.component.G; import net.mostlyoriginal.game.component.Star; import net.mostlyoriginal.game.system.common.FluidIteratingSystem; import static com.artemis.E.E;
package net.mostlyoriginal.game.system; /** * @author Daan van Yperen */ public class StarEffectSystem extends FluidIteratingSystem { public static final int BIGGEST_STAR_WIDTH = 100; /** * speed factor of ship. */ private float timer; public float speedFactor; public boolean active=false;
// Path: components/src/net/mostlyoriginal/game/component/G.java // public class G { // // public static final int LOGO_WIDTH = 280; // public static final int LOGO_HEIGHT = 221; // public static final int LAYER_CURSOR = 2000; // // public static final boolean PRODUCTION = false; // // public static final boolean INTERLACING_SIMULATION = true; // // public static final boolean DEBUG_SKIP_INTRO = (!PRODUCTION && false); // public static final boolean DEBUG_ACHIEVEMENTS = (!PRODUCTION && false); // public static final boolean DEBUG_DRAWING = (!PRODUCTION && true); // public static final boolean DEBUG_NO_MUSIC =(!PRODUCTION && false); // public static final boolean DEBUG_NO_ENTITY_RENDERING =(!PRODUCTION && false); // public static final boolean DEBUG_NO_SECOND_PASS =(!PRODUCTION && false); // public static final boolean DEBUG_NO_ACHIEVEMENTS = (!PRODUCTION && true); // public static boolean DEBUG_NO_FLOW = (!PRODUCTION && false); // public static boolean DEBUG_AIR_PLANET = (!PRODUCTION && false); // public static boolean DEBUG_NAIVE_GRAVITY = (!PRODUCTION && false); // public static boolean DEBUG_NO_CARDS = (!PRODUCTION && true); // // public static final float CARD_X = 5; // public static final float CARD_Y = 5; // // // public static final int SIMULATION_WIDTH = 220 + 50; // public static final int SIMULATION_HEIGHT = 220 + 50; // public static final int MARGIN_BETWEEN_CARDS = 5; // // public static final int LAYER_STAR = -50; // public static final int LAYER_STRUCTURES_BACKGROUND = -2; // public static final int LAYER_PLANET = 0; // public static final int LAYER_DUDES = 99; // public static final int LAYER_GHOST = 100; // public static final int LAYER_CARDS = 1000; // public static final int LAYER_CARDS_HOVER = 1001; // public static final int LAYER_CARDS_FLYING = 1002; // public static final int LAYER_ACHIEVEMENTS = 900; // public static final int LAYER_STRUCTURES = -1; // public static final int LAYER_STRUCTURES_FOREGROUND = 101; // // public static int CAMERA_ZOOM = 2; // public static final int SCREEN_WIDTH = SIMULATION_WIDTH * 2 * CAMERA_ZOOM; // private static int CARD_HEIGHT = 90; // private static int MARGIN_BETWEEN_CARD_AND_SIM = 10; // // public static int PLANET_X = (SIMULATION_WIDTH) - (SIMULATION_WIDTH / 2); // public static int PLANET_Y = MARGIN_BETWEEN_CARD_AND_SIM + CARD_HEIGHT; // private static final int MARGIN_BETWEEN_SIM_AND_ROOF = 20; // public static final int SCREEN_HEIGHT = (SIMULATION_HEIGHT + CARD_HEIGHT + MARGIN_BETWEEN_CARD_AND_SIM + MARGIN_BETWEEN_SIM_AND_ROOF) * CAMERA_ZOOM; // // public static final int PLANET_CENTER_X = PLANET_X + (SIMULATION_WIDTH / 2); // public static final int PLANET_CENTER_Y = PLANET_Y + (SIMULATION_HEIGHT / 2); // // public static final int GRADIENT_SCALE = 5; // public static float TOOL_HEIGHT = 50; // } // // Path: components/src/net/mostlyoriginal/game/component/Star.java // public class Star extends Component { // public Star() { // } // public final String animId[] = new String[6]; // public final float speedFactor = 1f + MathUtils.random(-0.2f,0.5f); // public float blinkTimer = MathUtils.random(0f,10f); // // public void set(int kind) { // animId[0] = "star-" + kind + "-0"; // animId[1] = "star-" + kind + "-1"; // animId[2] = "star-" + kind + "-2"; // animId[3] = "star-" + kind + "-3"; // animId[4] = "star-" + kind + "-4"; // animId[5] = "star-" + kind + "-5"; // } // } // // Path: core/src/net/mostlyoriginal/game/system/common/FluidIteratingSystem.java // public abstract class FluidIteratingSystem extends IteratingSystem { // // public FluidIteratingSystem(Aspect.Builder aspect) { // super(aspect); // } // // @Override // protected void process(int id) { // process(E(id)); // } // // protected abstract void process(E e); // // // protected EBag allEntitiesMatching(Aspect.Builder scope) { // return new EBag(world.getAspectSubscriptionManager().get(scope).getEntities()); // } // // protected EBag allEntitiesWith(Class<? extends Component> scope) { // return new EBag(world.getAspectSubscriptionManager().get(Aspect.all(scope)).getEntities()); // } // } // Path: core/src/net/mostlyoriginal/game/system/StarEffectSystem.java import com.artemis.Aspect; import com.artemis.ComponentMapper; import com.artemis.E; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.math.MathUtils; import net.mostlyoriginal.api.component.basic.Pos; import net.mostlyoriginal.api.component.graphics.Anim; import net.mostlyoriginal.game.component.G; import net.mostlyoriginal.game.component.Star; import net.mostlyoriginal.game.system.common.FluidIteratingSystem; import static com.artemis.E.E; package net.mostlyoriginal.game.system; /** * @author Daan van Yperen */ public class StarEffectSystem extends FluidIteratingSystem { public static final int BIGGEST_STAR_WIDTH = 100; /** * speed factor of ship. */ private float timer; public float speedFactor; public boolean active=false;
protected ComponentMapper<Star> mStar;
DaanVanYperen/odb-little-fortune-planet
core/src/net/mostlyoriginal/game/system/StarEffectSystem.java
// Path: components/src/net/mostlyoriginal/game/component/G.java // public class G { // // public static final int LOGO_WIDTH = 280; // public static final int LOGO_HEIGHT = 221; // public static final int LAYER_CURSOR = 2000; // // public static final boolean PRODUCTION = false; // // public static final boolean INTERLACING_SIMULATION = true; // // public static final boolean DEBUG_SKIP_INTRO = (!PRODUCTION && false); // public static final boolean DEBUG_ACHIEVEMENTS = (!PRODUCTION && false); // public static final boolean DEBUG_DRAWING = (!PRODUCTION && true); // public static final boolean DEBUG_NO_MUSIC =(!PRODUCTION && false); // public static final boolean DEBUG_NO_ENTITY_RENDERING =(!PRODUCTION && false); // public static final boolean DEBUG_NO_SECOND_PASS =(!PRODUCTION && false); // public static final boolean DEBUG_NO_ACHIEVEMENTS = (!PRODUCTION && true); // public static boolean DEBUG_NO_FLOW = (!PRODUCTION && false); // public static boolean DEBUG_AIR_PLANET = (!PRODUCTION && false); // public static boolean DEBUG_NAIVE_GRAVITY = (!PRODUCTION && false); // public static boolean DEBUG_NO_CARDS = (!PRODUCTION && true); // // public static final float CARD_X = 5; // public static final float CARD_Y = 5; // // // public static final int SIMULATION_WIDTH = 220 + 50; // public static final int SIMULATION_HEIGHT = 220 + 50; // public static final int MARGIN_BETWEEN_CARDS = 5; // // public static final int LAYER_STAR = -50; // public static final int LAYER_STRUCTURES_BACKGROUND = -2; // public static final int LAYER_PLANET = 0; // public static final int LAYER_DUDES = 99; // public static final int LAYER_GHOST = 100; // public static final int LAYER_CARDS = 1000; // public static final int LAYER_CARDS_HOVER = 1001; // public static final int LAYER_CARDS_FLYING = 1002; // public static final int LAYER_ACHIEVEMENTS = 900; // public static final int LAYER_STRUCTURES = -1; // public static final int LAYER_STRUCTURES_FOREGROUND = 101; // // public static int CAMERA_ZOOM = 2; // public static final int SCREEN_WIDTH = SIMULATION_WIDTH * 2 * CAMERA_ZOOM; // private static int CARD_HEIGHT = 90; // private static int MARGIN_BETWEEN_CARD_AND_SIM = 10; // // public static int PLANET_X = (SIMULATION_WIDTH) - (SIMULATION_WIDTH / 2); // public static int PLANET_Y = MARGIN_BETWEEN_CARD_AND_SIM + CARD_HEIGHT; // private static final int MARGIN_BETWEEN_SIM_AND_ROOF = 20; // public static final int SCREEN_HEIGHT = (SIMULATION_HEIGHT + CARD_HEIGHT + MARGIN_BETWEEN_CARD_AND_SIM + MARGIN_BETWEEN_SIM_AND_ROOF) * CAMERA_ZOOM; // // public static final int PLANET_CENTER_X = PLANET_X + (SIMULATION_WIDTH / 2); // public static final int PLANET_CENTER_Y = PLANET_Y + (SIMULATION_HEIGHT / 2); // // public static final int GRADIENT_SCALE = 5; // public static float TOOL_HEIGHT = 50; // } // // Path: components/src/net/mostlyoriginal/game/component/Star.java // public class Star extends Component { // public Star() { // } // public final String animId[] = new String[6]; // public final float speedFactor = 1f + MathUtils.random(-0.2f,0.5f); // public float blinkTimer = MathUtils.random(0f,10f); // // public void set(int kind) { // animId[0] = "star-" + kind + "-0"; // animId[1] = "star-" + kind + "-1"; // animId[2] = "star-" + kind + "-2"; // animId[3] = "star-" + kind + "-3"; // animId[4] = "star-" + kind + "-4"; // animId[5] = "star-" + kind + "-5"; // } // } // // Path: core/src/net/mostlyoriginal/game/system/common/FluidIteratingSystem.java // public abstract class FluidIteratingSystem extends IteratingSystem { // // public FluidIteratingSystem(Aspect.Builder aspect) { // super(aspect); // } // // @Override // protected void process(int id) { // process(E(id)); // } // // protected abstract void process(E e); // // // protected EBag allEntitiesMatching(Aspect.Builder scope) { // return new EBag(world.getAspectSubscriptionManager().get(scope).getEntities()); // } // // protected EBag allEntitiesWith(Class<? extends Component> scope) { // return new EBag(world.getAspectSubscriptionManager().get(Aspect.all(scope)).getEntities()); // } // }
import com.artemis.Aspect; import com.artemis.ComponentMapper; import com.artemis.E; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.math.MathUtils; import net.mostlyoriginal.api.component.basic.Pos; import net.mostlyoriginal.api.component.graphics.Anim; import net.mostlyoriginal.game.component.G; import net.mostlyoriginal.game.component.Star; import net.mostlyoriginal.game.system.common.FluidIteratingSystem; import static com.artemis.E.E;
package net.mostlyoriginal.game.system; /** * @author Daan van Yperen */ public class StarEffectSystem extends FluidIteratingSystem { public static final int BIGGEST_STAR_WIDTH = 100; /** * speed factor of ship. */ private float timer; public float speedFactor; public boolean active=false; protected ComponentMapper<Star> mStar; protected ComponentMapper<Anim> mAnim; protected ComponentMapper<Pos> mPos; private int animStage; private int playSoundState = 0; public StarEffectSystem() { super(Aspect.all(Star.class, Pos.class, Anim.class)); } @Override protected void initialize() { super.initialize(); for (int i = 0; i < 200; i++) {
// Path: components/src/net/mostlyoriginal/game/component/G.java // public class G { // // public static final int LOGO_WIDTH = 280; // public static final int LOGO_HEIGHT = 221; // public static final int LAYER_CURSOR = 2000; // // public static final boolean PRODUCTION = false; // // public static final boolean INTERLACING_SIMULATION = true; // // public static final boolean DEBUG_SKIP_INTRO = (!PRODUCTION && false); // public static final boolean DEBUG_ACHIEVEMENTS = (!PRODUCTION && false); // public static final boolean DEBUG_DRAWING = (!PRODUCTION && true); // public static final boolean DEBUG_NO_MUSIC =(!PRODUCTION && false); // public static final boolean DEBUG_NO_ENTITY_RENDERING =(!PRODUCTION && false); // public static final boolean DEBUG_NO_SECOND_PASS =(!PRODUCTION && false); // public static final boolean DEBUG_NO_ACHIEVEMENTS = (!PRODUCTION && true); // public static boolean DEBUG_NO_FLOW = (!PRODUCTION && false); // public static boolean DEBUG_AIR_PLANET = (!PRODUCTION && false); // public static boolean DEBUG_NAIVE_GRAVITY = (!PRODUCTION && false); // public static boolean DEBUG_NO_CARDS = (!PRODUCTION && true); // // public static final float CARD_X = 5; // public static final float CARD_Y = 5; // // // public static final int SIMULATION_WIDTH = 220 + 50; // public static final int SIMULATION_HEIGHT = 220 + 50; // public static final int MARGIN_BETWEEN_CARDS = 5; // // public static final int LAYER_STAR = -50; // public static final int LAYER_STRUCTURES_BACKGROUND = -2; // public static final int LAYER_PLANET = 0; // public static final int LAYER_DUDES = 99; // public static final int LAYER_GHOST = 100; // public static final int LAYER_CARDS = 1000; // public static final int LAYER_CARDS_HOVER = 1001; // public static final int LAYER_CARDS_FLYING = 1002; // public static final int LAYER_ACHIEVEMENTS = 900; // public static final int LAYER_STRUCTURES = -1; // public static final int LAYER_STRUCTURES_FOREGROUND = 101; // // public static int CAMERA_ZOOM = 2; // public static final int SCREEN_WIDTH = SIMULATION_WIDTH * 2 * CAMERA_ZOOM; // private static int CARD_HEIGHT = 90; // private static int MARGIN_BETWEEN_CARD_AND_SIM = 10; // // public static int PLANET_X = (SIMULATION_WIDTH) - (SIMULATION_WIDTH / 2); // public static int PLANET_Y = MARGIN_BETWEEN_CARD_AND_SIM + CARD_HEIGHT; // private static final int MARGIN_BETWEEN_SIM_AND_ROOF = 20; // public static final int SCREEN_HEIGHT = (SIMULATION_HEIGHT + CARD_HEIGHT + MARGIN_BETWEEN_CARD_AND_SIM + MARGIN_BETWEEN_SIM_AND_ROOF) * CAMERA_ZOOM; // // public static final int PLANET_CENTER_X = PLANET_X + (SIMULATION_WIDTH / 2); // public static final int PLANET_CENTER_Y = PLANET_Y + (SIMULATION_HEIGHT / 2); // // public static final int GRADIENT_SCALE = 5; // public static float TOOL_HEIGHT = 50; // } // // Path: components/src/net/mostlyoriginal/game/component/Star.java // public class Star extends Component { // public Star() { // } // public final String animId[] = new String[6]; // public final float speedFactor = 1f + MathUtils.random(-0.2f,0.5f); // public float blinkTimer = MathUtils.random(0f,10f); // // public void set(int kind) { // animId[0] = "star-" + kind + "-0"; // animId[1] = "star-" + kind + "-1"; // animId[2] = "star-" + kind + "-2"; // animId[3] = "star-" + kind + "-3"; // animId[4] = "star-" + kind + "-4"; // animId[5] = "star-" + kind + "-5"; // } // } // // Path: core/src/net/mostlyoriginal/game/system/common/FluidIteratingSystem.java // public abstract class FluidIteratingSystem extends IteratingSystem { // // public FluidIteratingSystem(Aspect.Builder aspect) { // super(aspect); // } // // @Override // protected void process(int id) { // process(E(id)); // } // // protected abstract void process(E e); // // // protected EBag allEntitiesMatching(Aspect.Builder scope) { // return new EBag(world.getAspectSubscriptionManager().get(scope).getEntities()); // } // // protected EBag allEntitiesWith(Class<? extends Component> scope) { // return new EBag(world.getAspectSubscriptionManager().get(Aspect.all(scope)).getEntities()); // } // } // Path: core/src/net/mostlyoriginal/game/system/StarEffectSystem.java import com.artemis.Aspect; import com.artemis.ComponentMapper; import com.artemis.E; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.math.MathUtils; import net.mostlyoriginal.api.component.basic.Pos; import net.mostlyoriginal.api.component.graphics.Anim; import net.mostlyoriginal.game.component.G; import net.mostlyoriginal.game.component.Star; import net.mostlyoriginal.game.system.common.FluidIteratingSystem; import static com.artemis.E.E; package net.mostlyoriginal.game.system; /** * @author Daan van Yperen */ public class StarEffectSystem extends FluidIteratingSystem { public static final int BIGGEST_STAR_WIDTH = 100; /** * speed factor of ship. */ private float timer; public float speedFactor; public boolean active=false; protected ComponentMapper<Star> mStar; protected ComponentMapper<Anim> mAnim; protected ComponentMapper<Pos> mPos; private int animStage; private int playSoundState = 0; public StarEffectSystem() { super(Aspect.all(Star.class, Pos.class, Anim.class)); } @Override protected void initialize() { super.initialize(); for (int i = 0; i < 200; i++) {
spawnStar(randomStarX(), MathUtils.random(0, G.SCREEN_HEIGHT + BIGGEST_STAR_WIDTH), MathUtils.random(100) < 20 ? 1 : MathUtils.random(100) < 20 ? 0 : 2);
DaanVanYperen/odb-little-fortune-planet
core/src/net/mostlyoriginal/game/system/planet/cells/LavaCellSimulator.java
// Path: components/src/net/mostlyoriginal/game/component/PlanetCell.java // public class PlanetCell { // public static final int SPACE_AIR_STARTS_AT_DEPTH = 20; // public int x; // public int y; // public int color = 0; // public int down = -1; // public float height = 0; // public CellType type = CellType.STATIC; // // // public CellType nextType = null; // public int nextColor = -1; // // public static int[][] directions = { // {-1, -1}, // {0, -1}, // {1, -1}, // {1, 0}, // {1, 1}, // {0, 1}, // {-1, 1}, // {-1, 0} // }; // // public int sleep; // // public int up() { // return (down + 4) % 8; // } // // public int left() { // return (down + 6) % 8; // } // // public int right() { // return (down + 2) % 8; // } // // public int upL() { // return (down + 3) % 8; // } // // public int downL() { // return (down + 7) % 8; // } // // public int downR() { // return (down + 1) % 8; // } // // public int upR() { // return (down + 5) % 8; // } // // public void activateNextType() { // if (nextType != null) { // type = nextType; // nextType = null; // sleep=0; // } // if (nextColor != -1) { // color = nextColor; // nextColor = -1; // } // } // // public float depth() { // return ((G.SIMULATION_WIDTH / 2) - height); // } // // public enum CellType { // STATIC(null, false), // LAVA(5f, true), // WATER(1f, true), // AIR(0f, true), // ICE(null, false), // STEAM(-0.5f, true), // LAVA_CRUST(5f, true), // CLOUD(-0.7f, false), // FIRE(-0.7f, false), // NOTHING(-100f,false), // ORGANIC(null, false), ORGANIC_SPORE(-0.7f, false); // // public final Float density; // private boolean flows; // // CellType(Float density, boolean flows) { // this.density = density; // this.flows = flows; // } // // public boolean flows() { // return flows; // } // // public boolean isLighter(CellType type) { // return type.density != null && density != null && type.density < density; // } // } // // public boolean isSpaceAir() { // return depth() < SPACE_AIR_STARTS_AT_DEPTH && type == PlanetCell.CellType.AIR; // } // } // // Path: components/src/net/mostlyoriginal/game/component/StatusMask.java // public class StatusMask { // public static final float ARID_TEMPERATURE = 300; // public static float MAX_TEMPERATURE = 300; // public float temperature=0; // // public void reset() { // temperature=0; // } // }
import com.badlogic.gdx.math.MathUtils; import net.mostlyoriginal.game.component.PlanetCell; import net.mostlyoriginal.game.component.StatusMask;
package net.mostlyoriginal.game.system.planet.cells; /** * @author Daan van Yperen */ public class LavaCellSimulator implements CellSimulator { @Override public void color(CellDecorator c, float delta) { c.cell.color = c.planet.cellColor[c.cell.type.ordinal()]; } @Override public void process(CellDecorator c, float delta) { // releave pressure. if (c.cell.nextType == null) { if (c.planet.lavaPressure > 0 && FauxRng.random(5000) < c.planet.lavaPressure && (c.cell.depth() > 50 || FauxRng.random(100) < 5)) { if (attemptReleavePressure(c, c.getNeighbourDown())) return; boolean b = FauxRng.randomBoolean(); // flip direction randomly. if (attemptReleavePressure(c, b ? c.getNeighbourLeft() : c.getNeighbourRight())) return; if (attemptReleavePressure(c, !b ? c.getNeighbourLeft() : c.getNeighbourRight())) return; if (attemptReleavePressure(c, b ? c.getNeighbourAboveL() : c.getNeighbourAboveR())) return; if (attemptReleavePressure(c, !b ? c.getNeighbourAboveL() : c.getNeighbourAboveR())) return;
// Path: components/src/net/mostlyoriginal/game/component/PlanetCell.java // public class PlanetCell { // public static final int SPACE_AIR_STARTS_AT_DEPTH = 20; // public int x; // public int y; // public int color = 0; // public int down = -1; // public float height = 0; // public CellType type = CellType.STATIC; // // // public CellType nextType = null; // public int nextColor = -1; // // public static int[][] directions = { // {-1, -1}, // {0, -1}, // {1, -1}, // {1, 0}, // {1, 1}, // {0, 1}, // {-1, 1}, // {-1, 0} // }; // // public int sleep; // // public int up() { // return (down + 4) % 8; // } // // public int left() { // return (down + 6) % 8; // } // // public int right() { // return (down + 2) % 8; // } // // public int upL() { // return (down + 3) % 8; // } // // public int downL() { // return (down + 7) % 8; // } // // public int downR() { // return (down + 1) % 8; // } // // public int upR() { // return (down + 5) % 8; // } // // public void activateNextType() { // if (nextType != null) { // type = nextType; // nextType = null; // sleep=0; // } // if (nextColor != -1) { // color = nextColor; // nextColor = -1; // } // } // // public float depth() { // return ((G.SIMULATION_WIDTH / 2) - height); // } // // public enum CellType { // STATIC(null, false), // LAVA(5f, true), // WATER(1f, true), // AIR(0f, true), // ICE(null, false), // STEAM(-0.5f, true), // LAVA_CRUST(5f, true), // CLOUD(-0.7f, false), // FIRE(-0.7f, false), // NOTHING(-100f,false), // ORGANIC(null, false), ORGANIC_SPORE(-0.7f, false); // // public final Float density; // private boolean flows; // // CellType(Float density, boolean flows) { // this.density = density; // this.flows = flows; // } // // public boolean flows() { // return flows; // } // // public boolean isLighter(CellType type) { // return type.density != null && density != null && type.density < density; // } // } // // public boolean isSpaceAir() { // return depth() < SPACE_AIR_STARTS_AT_DEPTH && type == PlanetCell.CellType.AIR; // } // } // // Path: components/src/net/mostlyoriginal/game/component/StatusMask.java // public class StatusMask { // public static final float ARID_TEMPERATURE = 300; // public static float MAX_TEMPERATURE = 300; // public float temperature=0; // // public void reset() { // temperature=0; // } // } // Path: core/src/net/mostlyoriginal/game/system/planet/cells/LavaCellSimulator.java import com.badlogic.gdx.math.MathUtils; import net.mostlyoriginal.game.component.PlanetCell; import net.mostlyoriginal.game.component.StatusMask; package net.mostlyoriginal.game.system.planet.cells; /** * @author Daan van Yperen */ public class LavaCellSimulator implements CellSimulator { @Override public void color(CellDecorator c, float delta) { c.cell.color = c.planet.cellColor[c.cell.type.ordinal()]; } @Override public void process(CellDecorator c, float delta) { // releave pressure. if (c.cell.nextType == null) { if (c.planet.lavaPressure > 0 && FauxRng.random(5000) < c.planet.lavaPressure && (c.cell.depth() > 50 || FauxRng.random(100) < 5)) { if (attemptReleavePressure(c, c.getNeighbourDown())) return; boolean b = FauxRng.randomBoolean(); // flip direction randomly. if (attemptReleavePressure(c, b ? c.getNeighbourLeft() : c.getNeighbourRight())) return; if (attemptReleavePressure(c, !b ? c.getNeighbourLeft() : c.getNeighbourRight())) return; if (attemptReleavePressure(c, b ? c.getNeighbourAboveL() : c.getNeighbourAboveR())) return; if (attemptReleavePressure(c, !b ? c.getNeighbourAboveL() : c.getNeighbourAboveR())) return;
if (attemptReleavePressure(c, c.getNeighbour(PlanetCell.CellType.AIR))) return;
DaanVanYperen/odb-little-fortune-planet
core/src/net/mostlyoriginal/game/system/planet/cells/LavaCellSimulator.java
// Path: components/src/net/mostlyoriginal/game/component/PlanetCell.java // public class PlanetCell { // public static final int SPACE_AIR_STARTS_AT_DEPTH = 20; // public int x; // public int y; // public int color = 0; // public int down = -1; // public float height = 0; // public CellType type = CellType.STATIC; // // // public CellType nextType = null; // public int nextColor = -1; // // public static int[][] directions = { // {-1, -1}, // {0, -1}, // {1, -1}, // {1, 0}, // {1, 1}, // {0, 1}, // {-1, 1}, // {-1, 0} // }; // // public int sleep; // // public int up() { // return (down + 4) % 8; // } // // public int left() { // return (down + 6) % 8; // } // // public int right() { // return (down + 2) % 8; // } // // public int upL() { // return (down + 3) % 8; // } // // public int downL() { // return (down + 7) % 8; // } // // public int downR() { // return (down + 1) % 8; // } // // public int upR() { // return (down + 5) % 8; // } // // public void activateNextType() { // if (nextType != null) { // type = nextType; // nextType = null; // sleep=0; // } // if (nextColor != -1) { // color = nextColor; // nextColor = -1; // } // } // // public float depth() { // return ((G.SIMULATION_WIDTH / 2) - height); // } // // public enum CellType { // STATIC(null, false), // LAVA(5f, true), // WATER(1f, true), // AIR(0f, true), // ICE(null, false), // STEAM(-0.5f, true), // LAVA_CRUST(5f, true), // CLOUD(-0.7f, false), // FIRE(-0.7f, false), // NOTHING(-100f,false), // ORGANIC(null, false), ORGANIC_SPORE(-0.7f, false); // // public final Float density; // private boolean flows; // // CellType(Float density, boolean flows) { // this.density = density; // this.flows = flows; // } // // public boolean flows() { // return flows; // } // // public boolean isLighter(CellType type) { // return type.density != null && density != null && type.density < density; // } // } // // public boolean isSpaceAir() { // return depth() < SPACE_AIR_STARTS_AT_DEPTH && type == PlanetCell.CellType.AIR; // } // } // // Path: components/src/net/mostlyoriginal/game/component/StatusMask.java // public class StatusMask { // public static final float ARID_TEMPERATURE = 300; // public static float MAX_TEMPERATURE = 300; // public float temperature=0; // // public void reset() { // temperature=0; // } // }
import com.badlogic.gdx.math.MathUtils; import net.mostlyoriginal.game.component.PlanetCell; import net.mostlyoriginal.game.component.StatusMask;
if (attemptReleavePressure(c, c.getNeighbour(PlanetCell.CellType.AIR))) return; } } // crust or not! if (c.cell.nextType == null) { int nonLavaNeighbours = c.countNonLavaNeighbour(); if (c.cell.type == PlanetCell.CellType.LAVA_CRUST && nonLavaNeighbours == 0) { c.setNextType(PlanetCell.CellType.LAVA); } if (c.cell.type == PlanetCell.CellType.LAVA && nonLavaNeighbours > 0) { c.setNextType(PlanetCell.CellType.LAVA_CRUST); } } if (c.cell.nextType == null) { c.flow(); } } private boolean attemptReleavePressure(CellDecorator c, PlanetCell neighbour) { if (neighbour != null && neighbour.nextType == null && neighbour.type == PlanetCell.CellType.AIR) { neighbour.nextType = PlanetCell.CellType.LAVA; c.planet.lavaPressure--; return true; } return false; } @Override public void updateMask(CellDecorator c, float delta) {
// Path: components/src/net/mostlyoriginal/game/component/PlanetCell.java // public class PlanetCell { // public static final int SPACE_AIR_STARTS_AT_DEPTH = 20; // public int x; // public int y; // public int color = 0; // public int down = -1; // public float height = 0; // public CellType type = CellType.STATIC; // // // public CellType nextType = null; // public int nextColor = -1; // // public static int[][] directions = { // {-1, -1}, // {0, -1}, // {1, -1}, // {1, 0}, // {1, 1}, // {0, 1}, // {-1, 1}, // {-1, 0} // }; // // public int sleep; // // public int up() { // return (down + 4) % 8; // } // // public int left() { // return (down + 6) % 8; // } // // public int right() { // return (down + 2) % 8; // } // // public int upL() { // return (down + 3) % 8; // } // // public int downL() { // return (down + 7) % 8; // } // // public int downR() { // return (down + 1) % 8; // } // // public int upR() { // return (down + 5) % 8; // } // // public void activateNextType() { // if (nextType != null) { // type = nextType; // nextType = null; // sleep=0; // } // if (nextColor != -1) { // color = nextColor; // nextColor = -1; // } // } // // public float depth() { // return ((G.SIMULATION_WIDTH / 2) - height); // } // // public enum CellType { // STATIC(null, false), // LAVA(5f, true), // WATER(1f, true), // AIR(0f, true), // ICE(null, false), // STEAM(-0.5f, true), // LAVA_CRUST(5f, true), // CLOUD(-0.7f, false), // FIRE(-0.7f, false), // NOTHING(-100f,false), // ORGANIC(null, false), ORGANIC_SPORE(-0.7f, false); // // public final Float density; // private boolean flows; // // CellType(Float density, boolean flows) { // this.density = density; // this.flows = flows; // } // // public boolean flows() { // return flows; // } // // public boolean isLighter(CellType type) { // return type.density != null && density != null && type.density < density; // } // } // // public boolean isSpaceAir() { // return depth() < SPACE_AIR_STARTS_AT_DEPTH && type == PlanetCell.CellType.AIR; // } // } // // Path: components/src/net/mostlyoriginal/game/component/StatusMask.java // public class StatusMask { // public static final float ARID_TEMPERATURE = 300; // public static float MAX_TEMPERATURE = 300; // public float temperature=0; // // public void reset() { // temperature=0; // } // } // Path: core/src/net/mostlyoriginal/game/system/planet/cells/LavaCellSimulator.java import com.badlogic.gdx.math.MathUtils; import net.mostlyoriginal.game.component.PlanetCell; import net.mostlyoriginal.game.component.StatusMask; if (attemptReleavePressure(c, c.getNeighbour(PlanetCell.CellType.AIR))) return; } } // crust or not! if (c.cell.nextType == null) { int nonLavaNeighbours = c.countNonLavaNeighbour(); if (c.cell.type == PlanetCell.CellType.LAVA_CRUST && nonLavaNeighbours == 0) { c.setNextType(PlanetCell.CellType.LAVA); } if (c.cell.type == PlanetCell.CellType.LAVA && nonLavaNeighbours > 0) { c.setNextType(PlanetCell.CellType.LAVA_CRUST); } } if (c.cell.nextType == null) { c.flow(); } } private boolean attemptReleavePressure(CellDecorator c, PlanetCell neighbour) { if (neighbour != null && neighbour.nextType == null && neighbour.type == PlanetCell.CellType.AIR) { neighbour.nextType = PlanetCell.CellType.LAVA; c.planet.lavaPressure--; return true; } return false; } @Override public void updateMask(CellDecorator c, float delta) {
StatusMask mask = c.mask();
DaanVanYperen/odb-little-fortune-planet
core/src/net/mostlyoriginal/game/system/planet/physics/GravitySystem.java
// Path: components/src/net/mostlyoriginal/game/component/Mass.java // public class Mass extends Component { // public Mass() { // } // public Mass(float density) { // this.density=density; // } // public float density=1f; // public boolean inverse=false; // } // // Path: components/src/net/mostlyoriginal/game/component/PlanetCell.java // public class PlanetCell { // public static final int SPACE_AIR_STARTS_AT_DEPTH = 20; // public int x; // public int y; // public int color = 0; // public int down = -1; // public float height = 0; // public CellType type = CellType.STATIC; // // // public CellType nextType = null; // public int nextColor = -1; // // public static int[][] directions = { // {-1, -1}, // {0, -1}, // {1, -1}, // {1, 0}, // {1, 1}, // {0, 1}, // {-1, 1}, // {-1, 0} // }; // // public int sleep; // // public int up() { // return (down + 4) % 8; // } // // public int left() { // return (down + 6) % 8; // } // // public int right() { // return (down + 2) % 8; // } // // public int upL() { // return (down + 3) % 8; // } // // public int downL() { // return (down + 7) % 8; // } // // public int downR() { // return (down + 1) % 8; // } // // public int upR() { // return (down + 5) % 8; // } // // public void activateNextType() { // if (nextType != null) { // type = nextType; // nextType = null; // sleep=0; // } // if (nextColor != -1) { // color = nextColor; // nextColor = -1; // } // } // // public float depth() { // return ((G.SIMULATION_WIDTH / 2) - height); // } // // public enum CellType { // STATIC(null, false), // LAVA(5f, true), // WATER(1f, true), // AIR(0f, true), // ICE(null, false), // STEAM(-0.5f, true), // LAVA_CRUST(5f, true), // CLOUD(-0.7f, false), // FIRE(-0.7f, false), // NOTHING(-100f,false), // ORGANIC(null, false), ORGANIC_SPORE(-0.7f, false); // // public final Float density; // private boolean flows; // // CellType(Float density, boolean flows) { // this.density = density; // this.flows = flows; // } // // public boolean flows() { // return flows; // } // // public boolean isLighter(CellType type) { // return type.density != null && density != null && type.density < density; // } // } // // public boolean isSpaceAir() { // return depth() < SPACE_AIR_STARTS_AT_DEPTH && type == PlanetCell.CellType.AIR; // } // } // // Path: components/src/net/mostlyoriginal/game/component/Planetbound.java // public class Planetbound extends Component { // public Planetbound() { // } // // public PlanetCell cell; // public Vector2 gravity = new Vector2(); // } // // Path: core/src/net/mostlyoriginal/game/system/common/FluidIteratingSystem.java // public abstract class FluidIteratingSystem extends IteratingSystem { // // public FluidIteratingSystem(Aspect.Builder aspect) { // super(aspect); // } // // @Override // protected void process(int id) { // process(E(id)); // } // // protected abstract void process(E e); // // // protected EBag allEntitiesMatching(Aspect.Builder scope) { // return new EBag(world.getAspectSubscriptionManager().get(scope).getEntities()); // } // // protected EBag allEntitiesWith(Class<? extends Component> scope) { // return new EBag(world.getAspectSubscriptionManager().get(Aspect.all(scope)).getEntities()); // } // }
import com.artemis.Aspect; import com.artemis.E; import com.artemis.managers.TagManager; import com.badlogic.gdx.math.Vector2; import net.mostlyoriginal.api.component.basic.Angle; import net.mostlyoriginal.api.component.basic.Pos; import net.mostlyoriginal.api.component.physics.Physics; import net.mostlyoriginal.game.component.Mass; import net.mostlyoriginal.game.component.PlanetCell; import net.mostlyoriginal.game.component.Planetbound; import net.mostlyoriginal.game.system.common.FluidIteratingSystem;
package net.mostlyoriginal.game.system.planet.physics; /** * @author Daan van Yperen */ public class GravitySystem extends FluidIteratingSystem { private TagManager tagManager; public GravitySystem() {
// Path: components/src/net/mostlyoriginal/game/component/Mass.java // public class Mass extends Component { // public Mass() { // } // public Mass(float density) { // this.density=density; // } // public float density=1f; // public boolean inverse=false; // } // // Path: components/src/net/mostlyoriginal/game/component/PlanetCell.java // public class PlanetCell { // public static final int SPACE_AIR_STARTS_AT_DEPTH = 20; // public int x; // public int y; // public int color = 0; // public int down = -1; // public float height = 0; // public CellType type = CellType.STATIC; // // // public CellType nextType = null; // public int nextColor = -1; // // public static int[][] directions = { // {-1, -1}, // {0, -1}, // {1, -1}, // {1, 0}, // {1, 1}, // {0, 1}, // {-1, 1}, // {-1, 0} // }; // // public int sleep; // // public int up() { // return (down + 4) % 8; // } // // public int left() { // return (down + 6) % 8; // } // // public int right() { // return (down + 2) % 8; // } // // public int upL() { // return (down + 3) % 8; // } // // public int downL() { // return (down + 7) % 8; // } // // public int downR() { // return (down + 1) % 8; // } // // public int upR() { // return (down + 5) % 8; // } // // public void activateNextType() { // if (nextType != null) { // type = nextType; // nextType = null; // sleep=0; // } // if (nextColor != -1) { // color = nextColor; // nextColor = -1; // } // } // // public float depth() { // return ((G.SIMULATION_WIDTH / 2) - height); // } // // public enum CellType { // STATIC(null, false), // LAVA(5f, true), // WATER(1f, true), // AIR(0f, true), // ICE(null, false), // STEAM(-0.5f, true), // LAVA_CRUST(5f, true), // CLOUD(-0.7f, false), // FIRE(-0.7f, false), // NOTHING(-100f,false), // ORGANIC(null, false), ORGANIC_SPORE(-0.7f, false); // // public final Float density; // private boolean flows; // // CellType(Float density, boolean flows) { // this.density = density; // this.flows = flows; // } // // public boolean flows() { // return flows; // } // // public boolean isLighter(CellType type) { // return type.density != null && density != null && type.density < density; // } // } // // public boolean isSpaceAir() { // return depth() < SPACE_AIR_STARTS_AT_DEPTH && type == PlanetCell.CellType.AIR; // } // } // // Path: components/src/net/mostlyoriginal/game/component/Planetbound.java // public class Planetbound extends Component { // public Planetbound() { // } // // public PlanetCell cell; // public Vector2 gravity = new Vector2(); // } // // Path: core/src/net/mostlyoriginal/game/system/common/FluidIteratingSystem.java // public abstract class FluidIteratingSystem extends IteratingSystem { // // public FluidIteratingSystem(Aspect.Builder aspect) { // super(aspect); // } // // @Override // protected void process(int id) { // process(E(id)); // } // // protected abstract void process(E e); // // // protected EBag allEntitiesMatching(Aspect.Builder scope) { // return new EBag(world.getAspectSubscriptionManager().get(scope).getEntities()); // } // // protected EBag allEntitiesWith(Class<? extends Component> scope) { // return new EBag(world.getAspectSubscriptionManager().get(Aspect.all(scope)).getEntities()); // } // } // Path: core/src/net/mostlyoriginal/game/system/planet/physics/GravitySystem.java import com.artemis.Aspect; import com.artemis.E; import com.artemis.managers.TagManager; import com.badlogic.gdx.math.Vector2; import net.mostlyoriginal.api.component.basic.Angle; import net.mostlyoriginal.api.component.basic.Pos; import net.mostlyoriginal.api.component.physics.Physics; import net.mostlyoriginal.game.component.Mass; import net.mostlyoriginal.game.component.PlanetCell; import net.mostlyoriginal.game.component.Planetbound; import net.mostlyoriginal.game.system.common.FluidIteratingSystem; package net.mostlyoriginal.game.system.planet.physics; /** * @author Daan van Yperen */ public class GravitySystem extends FluidIteratingSystem { private TagManager tagManager; public GravitySystem() {
super(Aspect.all(Pos.class, Planetbound.class, Mass.class, Angle.class));
DaanVanYperen/odb-little-fortune-planet
core/src/net/mostlyoriginal/game/system/planet/physics/GravitySystem.java
// Path: components/src/net/mostlyoriginal/game/component/Mass.java // public class Mass extends Component { // public Mass() { // } // public Mass(float density) { // this.density=density; // } // public float density=1f; // public boolean inverse=false; // } // // Path: components/src/net/mostlyoriginal/game/component/PlanetCell.java // public class PlanetCell { // public static final int SPACE_AIR_STARTS_AT_DEPTH = 20; // public int x; // public int y; // public int color = 0; // public int down = -1; // public float height = 0; // public CellType type = CellType.STATIC; // // // public CellType nextType = null; // public int nextColor = -1; // // public static int[][] directions = { // {-1, -1}, // {0, -1}, // {1, -1}, // {1, 0}, // {1, 1}, // {0, 1}, // {-1, 1}, // {-1, 0} // }; // // public int sleep; // // public int up() { // return (down + 4) % 8; // } // // public int left() { // return (down + 6) % 8; // } // // public int right() { // return (down + 2) % 8; // } // // public int upL() { // return (down + 3) % 8; // } // // public int downL() { // return (down + 7) % 8; // } // // public int downR() { // return (down + 1) % 8; // } // // public int upR() { // return (down + 5) % 8; // } // // public void activateNextType() { // if (nextType != null) { // type = nextType; // nextType = null; // sleep=0; // } // if (nextColor != -1) { // color = nextColor; // nextColor = -1; // } // } // // public float depth() { // return ((G.SIMULATION_WIDTH / 2) - height); // } // // public enum CellType { // STATIC(null, false), // LAVA(5f, true), // WATER(1f, true), // AIR(0f, true), // ICE(null, false), // STEAM(-0.5f, true), // LAVA_CRUST(5f, true), // CLOUD(-0.7f, false), // FIRE(-0.7f, false), // NOTHING(-100f,false), // ORGANIC(null, false), ORGANIC_SPORE(-0.7f, false); // // public final Float density; // private boolean flows; // // CellType(Float density, boolean flows) { // this.density = density; // this.flows = flows; // } // // public boolean flows() { // return flows; // } // // public boolean isLighter(CellType type) { // return type.density != null && density != null && type.density < density; // } // } // // public boolean isSpaceAir() { // return depth() < SPACE_AIR_STARTS_AT_DEPTH && type == PlanetCell.CellType.AIR; // } // } // // Path: components/src/net/mostlyoriginal/game/component/Planetbound.java // public class Planetbound extends Component { // public Planetbound() { // } // // public PlanetCell cell; // public Vector2 gravity = new Vector2(); // } // // Path: core/src/net/mostlyoriginal/game/system/common/FluidIteratingSystem.java // public abstract class FluidIteratingSystem extends IteratingSystem { // // public FluidIteratingSystem(Aspect.Builder aspect) { // super(aspect); // } // // @Override // protected void process(int id) { // process(E(id)); // } // // protected abstract void process(E e); // // // protected EBag allEntitiesMatching(Aspect.Builder scope) { // return new EBag(world.getAspectSubscriptionManager().get(scope).getEntities()); // } // // protected EBag allEntitiesWith(Class<? extends Component> scope) { // return new EBag(world.getAspectSubscriptionManager().get(Aspect.all(scope)).getEntities()); // } // }
import com.artemis.Aspect; import com.artemis.E; import com.artemis.managers.TagManager; import com.badlogic.gdx.math.Vector2; import net.mostlyoriginal.api.component.basic.Angle; import net.mostlyoriginal.api.component.basic.Pos; import net.mostlyoriginal.api.component.physics.Physics; import net.mostlyoriginal.game.component.Mass; import net.mostlyoriginal.game.component.PlanetCell; import net.mostlyoriginal.game.component.Planetbound; import net.mostlyoriginal.game.system.common.FluidIteratingSystem;
package net.mostlyoriginal.game.system.planet.physics; /** * @author Daan van Yperen */ public class GravitySystem extends FluidIteratingSystem { private TagManager tagManager; public GravitySystem() {
// Path: components/src/net/mostlyoriginal/game/component/Mass.java // public class Mass extends Component { // public Mass() { // } // public Mass(float density) { // this.density=density; // } // public float density=1f; // public boolean inverse=false; // } // // Path: components/src/net/mostlyoriginal/game/component/PlanetCell.java // public class PlanetCell { // public static final int SPACE_AIR_STARTS_AT_DEPTH = 20; // public int x; // public int y; // public int color = 0; // public int down = -1; // public float height = 0; // public CellType type = CellType.STATIC; // // // public CellType nextType = null; // public int nextColor = -1; // // public static int[][] directions = { // {-1, -1}, // {0, -1}, // {1, -1}, // {1, 0}, // {1, 1}, // {0, 1}, // {-1, 1}, // {-1, 0} // }; // // public int sleep; // // public int up() { // return (down + 4) % 8; // } // // public int left() { // return (down + 6) % 8; // } // // public int right() { // return (down + 2) % 8; // } // // public int upL() { // return (down + 3) % 8; // } // // public int downL() { // return (down + 7) % 8; // } // // public int downR() { // return (down + 1) % 8; // } // // public int upR() { // return (down + 5) % 8; // } // // public void activateNextType() { // if (nextType != null) { // type = nextType; // nextType = null; // sleep=0; // } // if (nextColor != -1) { // color = nextColor; // nextColor = -1; // } // } // // public float depth() { // return ((G.SIMULATION_WIDTH / 2) - height); // } // // public enum CellType { // STATIC(null, false), // LAVA(5f, true), // WATER(1f, true), // AIR(0f, true), // ICE(null, false), // STEAM(-0.5f, true), // LAVA_CRUST(5f, true), // CLOUD(-0.7f, false), // FIRE(-0.7f, false), // NOTHING(-100f,false), // ORGANIC(null, false), ORGANIC_SPORE(-0.7f, false); // // public final Float density; // private boolean flows; // // CellType(Float density, boolean flows) { // this.density = density; // this.flows = flows; // } // // public boolean flows() { // return flows; // } // // public boolean isLighter(CellType type) { // return type.density != null && density != null && type.density < density; // } // } // // public boolean isSpaceAir() { // return depth() < SPACE_AIR_STARTS_AT_DEPTH && type == PlanetCell.CellType.AIR; // } // } // // Path: components/src/net/mostlyoriginal/game/component/Planetbound.java // public class Planetbound extends Component { // public Planetbound() { // } // // public PlanetCell cell; // public Vector2 gravity = new Vector2(); // } // // Path: core/src/net/mostlyoriginal/game/system/common/FluidIteratingSystem.java // public abstract class FluidIteratingSystem extends IteratingSystem { // // public FluidIteratingSystem(Aspect.Builder aspect) { // super(aspect); // } // // @Override // protected void process(int id) { // process(E(id)); // } // // protected abstract void process(E e); // // // protected EBag allEntitiesMatching(Aspect.Builder scope) { // return new EBag(world.getAspectSubscriptionManager().get(scope).getEntities()); // } // // protected EBag allEntitiesWith(Class<? extends Component> scope) { // return new EBag(world.getAspectSubscriptionManager().get(Aspect.all(scope)).getEntities()); // } // } // Path: core/src/net/mostlyoriginal/game/system/planet/physics/GravitySystem.java import com.artemis.Aspect; import com.artemis.E; import com.artemis.managers.TagManager; import com.badlogic.gdx.math.Vector2; import net.mostlyoriginal.api.component.basic.Angle; import net.mostlyoriginal.api.component.basic.Pos; import net.mostlyoriginal.api.component.physics.Physics; import net.mostlyoriginal.game.component.Mass; import net.mostlyoriginal.game.component.PlanetCell; import net.mostlyoriginal.game.component.Planetbound; import net.mostlyoriginal.game.system.common.FluidIteratingSystem; package net.mostlyoriginal.game.system.planet.physics; /** * @author Daan van Yperen */ public class GravitySystem extends FluidIteratingSystem { private TagManager tagManager; public GravitySystem() {
super(Aspect.all(Pos.class, Planetbound.class, Mass.class, Angle.class));
DaanVanYperen/odb-little-fortune-planet
core/src/net/mostlyoriginal/game/system/planet/physics/GravitySystem.java
// Path: components/src/net/mostlyoriginal/game/component/Mass.java // public class Mass extends Component { // public Mass() { // } // public Mass(float density) { // this.density=density; // } // public float density=1f; // public boolean inverse=false; // } // // Path: components/src/net/mostlyoriginal/game/component/PlanetCell.java // public class PlanetCell { // public static final int SPACE_AIR_STARTS_AT_DEPTH = 20; // public int x; // public int y; // public int color = 0; // public int down = -1; // public float height = 0; // public CellType type = CellType.STATIC; // // // public CellType nextType = null; // public int nextColor = -1; // // public static int[][] directions = { // {-1, -1}, // {0, -1}, // {1, -1}, // {1, 0}, // {1, 1}, // {0, 1}, // {-1, 1}, // {-1, 0} // }; // // public int sleep; // // public int up() { // return (down + 4) % 8; // } // // public int left() { // return (down + 6) % 8; // } // // public int right() { // return (down + 2) % 8; // } // // public int upL() { // return (down + 3) % 8; // } // // public int downL() { // return (down + 7) % 8; // } // // public int downR() { // return (down + 1) % 8; // } // // public int upR() { // return (down + 5) % 8; // } // // public void activateNextType() { // if (nextType != null) { // type = nextType; // nextType = null; // sleep=0; // } // if (nextColor != -1) { // color = nextColor; // nextColor = -1; // } // } // // public float depth() { // return ((G.SIMULATION_WIDTH / 2) - height); // } // // public enum CellType { // STATIC(null, false), // LAVA(5f, true), // WATER(1f, true), // AIR(0f, true), // ICE(null, false), // STEAM(-0.5f, true), // LAVA_CRUST(5f, true), // CLOUD(-0.7f, false), // FIRE(-0.7f, false), // NOTHING(-100f,false), // ORGANIC(null, false), ORGANIC_SPORE(-0.7f, false); // // public final Float density; // private boolean flows; // // CellType(Float density, boolean flows) { // this.density = density; // this.flows = flows; // } // // public boolean flows() { // return flows; // } // // public boolean isLighter(CellType type) { // return type.density != null && density != null && type.density < density; // } // } // // public boolean isSpaceAir() { // return depth() < SPACE_AIR_STARTS_AT_DEPTH && type == PlanetCell.CellType.AIR; // } // } // // Path: components/src/net/mostlyoriginal/game/component/Planetbound.java // public class Planetbound extends Component { // public Planetbound() { // } // // public PlanetCell cell; // public Vector2 gravity = new Vector2(); // } // // Path: core/src/net/mostlyoriginal/game/system/common/FluidIteratingSystem.java // public abstract class FluidIteratingSystem extends IteratingSystem { // // public FluidIteratingSystem(Aspect.Builder aspect) { // super(aspect); // } // // @Override // protected void process(int id) { // process(E(id)); // } // // protected abstract void process(E e); // // // protected EBag allEntitiesMatching(Aspect.Builder scope) { // return new EBag(world.getAspectSubscriptionManager().get(scope).getEntities()); // } // // protected EBag allEntitiesWith(Class<? extends Component> scope) { // return new EBag(world.getAspectSubscriptionManager().get(Aspect.all(scope)).getEntities()); // } // }
import com.artemis.Aspect; import com.artemis.E; import com.artemis.managers.TagManager; import com.badlogic.gdx.math.Vector2; import net.mostlyoriginal.api.component.basic.Angle; import net.mostlyoriginal.api.component.basic.Pos; import net.mostlyoriginal.api.component.physics.Physics; import net.mostlyoriginal.game.component.Mass; import net.mostlyoriginal.game.component.PlanetCell; import net.mostlyoriginal.game.component.Planetbound; import net.mostlyoriginal.game.system.common.FluidIteratingSystem;
package net.mostlyoriginal.game.system.planet.physics; /** * @author Daan van Yperen */ public class GravitySystem extends FluidIteratingSystem { private TagManager tagManager; public GravitySystem() { super(Aspect.all(Pos.class, Planetbound.class, Mass.class, Angle.class)); } Vector2 v = new Vector2(); @Override protected void process(E e) { Vector2 gravityVector = v.set(e.planetboundGravity()); if (e.massInverse()) { gravityVector.rotate(180); } // apply gravity. Physics physics = e.getPhysics(); // don't move through solid matter.
// Path: components/src/net/mostlyoriginal/game/component/Mass.java // public class Mass extends Component { // public Mass() { // } // public Mass(float density) { // this.density=density; // } // public float density=1f; // public boolean inverse=false; // } // // Path: components/src/net/mostlyoriginal/game/component/PlanetCell.java // public class PlanetCell { // public static final int SPACE_AIR_STARTS_AT_DEPTH = 20; // public int x; // public int y; // public int color = 0; // public int down = -1; // public float height = 0; // public CellType type = CellType.STATIC; // // // public CellType nextType = null; // public int nextColor = -1; // // public static int[][] directions = { // {-1, -1}, // {0, -1}, // {1, -1}, // {1, 0}, // {1, 1}, // {0, 1}, // {-1, 1}, // {-1, 0} // }; // // public int sleep; // // public int up() { // return (down + 4) % 8; // } // // public int left() { // return (down + 6) % 8; // } // // public int right() { // return (down + 2) % 8; // } // // public int upL() { // return (down + 3) % 8; // } // // public int downL() { // return (down + 7) % 8; // } // // public int downR() { // return (down + 1) % 8; // } // // public int upR() { // return (down + 5) % 8; // } // // public void activateNextType() { // if (nextType != null) { // type = nextType; // nextType = null; // sleep=0; // } // if (nextColor != -1) { // color = nextColor; // nextColor = -1; // } // } // // public float depth() { // return ((G.SIMULATION_WIDTH / 2) - height); // } // // public enum CellType { // STATIC(null, false), // LAVA(5f, true), // WATER(1f, true), // AIR(0f, true), // ICE(null, false), // STEAM(-0.5f, true), // LAVA_CRUST(5f, true), // CLOUD(-0.7f, false), // FIRE(-0.7f, false), // NOTHING(-100f,false), // ORGANIC(null, false), ORGANIC_SPORE(-0.7f, false); // // public final Float density; // private boolean flows; // // CellType(Float density, boolean flows) { // this.density = density; // this.flows = flows; // } // // public boolean flows() { // return flows; // } // // public boolean isLighter(CellType type) { // return type.density != null && density != null && type.density < density; // } // } // // public boolean isSpaceAir() { // return depth() < SPACE_AIR_STARTS_AT_DEPTH && type == PlanetCell.CellType.AIR; // } // } // // Path: components/src/net/mostlyoriginal/game/component/Planetbound.java // public class Planetbound extends Component { // public Planetbound() { // } // // public PlanetCell cell; // public Vector2 gravity = new Vector2(); // } // // Path: core/src/net/mostlyoriginal/game/system/common/FluidIteratingSystem.java // public abstract class FluidIteratingSystem extends IteratingSystem { // // public FluidIteratingSystem(Aspect.Builder aspect) { // super(aspect); // } // // @Override // protected void process(int id) { // process(E(id)); // } // // protected abstract void process(E e); // // // protected EBag allEntitiesMatching(Aspect.Builder scope) { // return new EBag(world.getAspectSubscriptionManager().get(scope).getEntities()); // } // // protected EBag allEntitiesWith(Class<? extends Component> scope) { // return new EBag(world.getAspectSubscriptionManager().get(Aspect.all(scope)).getEntities()); // } // } // Path: core/src/net/mostlyoriginal/game/system/planet/physics/GravitySystem.java import com.artemis.Aspect; import com.artemis.E; import com.artemis.managers.TagManager; import com.badlogic.gdx.math.Vector2; import net.mostlyoriginal.api.component.basic.Angle; import net.mostlyoriginal.api.component.basic.Pos; import net.mostlyoriginal.api.component.physics.Physics; import net.mostlyoriginal.game.component.Mass; import net.mostlyoriginal.game.component.PlanetCell; import net.mostlyoriginal.game.component.Planetbound; import net.mostlyoriginal.game.system.common.FluidIteratingSystem; package net.mostlyoriginal.game.system.planet.physics; /** * @author Daan van Yperen */ public class GravitySystem extends FluidIteratingSystem { private TagManager tagManager; public GravitySystem() { super(Aspect.all(Pos.class, Planetbound.class, Mass.class, Angle.class)); } Vector2 v = new Vector2(); @Override protected void process(E e) { Vector2 gravityVector = v.set(e.planetboundGravity()); if (e.massInverse()) { gravityVector.rotate(180); } // apply gravity. Physics physics = e.getPhysics(); // don't move through solid matter.
PlanetCell cell = e.planetboundCell();
DaanVanYperen/odb-little-fortune-planet
core/src/net/mostlyoriginal/game/system/view/GameScreenAssetSystem.java
// Path: components/src/net/mostlyoriginal/game/component/G.java // public class G { // // public static final int LOGO_WIDTH = 280; // public static final int LOGO_HEIGHT = 221; // public static final int LAYER_CURSOR = 2000; // // public static final boolean PRODUCTION = false; // // public static final boolean INTERLACING_SIMULATION = true; // // public static final boolean DEBUG_SKIP_INTRO = (!PRODUCTION && false); // public static final boolean DEBUG_ACHIEVEMENTS = (!PRODUCTION && false); // public static final boolean DEBUG_DRAWING = (!PRODUCTION && true); // public static final boolean DEBUG_NO_MUSIC =(!PRODUCTION && false); // public static final boolean DEBUG_NO_ENTITY_RENDERING =(!PRODUCTION && false); // public static final boolean DEBUG_NO_SECOND_PASS =(!PRODUCTION && false); // public static final boolean DEBUG_NO_ACHIEVEMENTS = (!PRODUCTION && true); // public static boolean DEBUG_NO_FLOW = (!PRODUCTION && false); // public static boolean DEBUG_AIR_PLANET = (!PRODUCTION && false); // public static boolean DEBUG_NAIVE_GRAVITY = (!PRODUCTION && false); // public static boolean DEBUG_NO_CARDS = (!PRODUCTION && true); // // public static final float CARD_X = 5; // public static final float CARD_Y = 5; // // // public static final int SIMULATION_WIDTH = 220 + 50; // public static final int SIMULATION_HEIGHT = 220 + 50; // public static final int MARGIN_BETWEEN_CARDS = 5; // // public static final int LAYER_STAR = -50; // public static final int LAYER_STRUCTURES_BACKGROUND = -2; // public static final int LAYER_PLANET = 0; // public static final int LAYER_DUDES = 99; // public static final int LAYER_GHOST = 100; // public static final int LAYER_CARDS = 1000; // public static final int LAYER_CARDS_HOVER = 1001; // public static final int LAYER_CARDS_FLYING = 1002; // public static final int LAYER_ACHIEVEMENTS = 900; // public static final int LAYER_STRUCTURES = -1; // public static final int LAYER_STRUCTURES_FOREGROUND = 101; // // public static int CAMERA_ZOOM = 2; // public static final int SCREEN_WIDTH = SIMULATION_WIDTH * 2 * CAMERA_ZOOM; // private static int CARD_HEIGHT = 90; // private static int MARGIN_BETWEEN_CARD_AND_SIM = 10; // // public static int PLANET_X = (SIMULATION_WIDTH) - (SIMULATION_WIDTH / 2); // public static int PLANET_Y = MARGIN_BETWEEN_CARD_AND_SIM + CARD_HEIGHT; // private static final int MARGIN_BETWEEN_SIM_AND_ROOF = 20; // public static final int SCREEN_HEIGHT = (SIMULATION_HEIGHT + CARD_HEIGHT + MARGIN_BETWEEN_CARD_AND_SIM + MARGIN_BETWEEN_SIM_AND_ROOF) * CAMERA_ZOOM; // // public static final int PLANET_CENTER_X = PLANET_X + (SIMULATION_WIDTH / 2); // public static final int PLANET_CENTER_Y = PLANET_Y + (SIMULATION_HEIGHT / 2); // // public static final int GRADIENT_SCALE = 5; // public static float TOOL_HEIGHT = 50; // } // // Path: components/src/net/mostlyoriginal/game/component/SpriteData.java // public class SpriteData implements Serializable { // // public String id; // public String comment; // not used. // // public int x; // public int y; // public int width; // public int height; // public int countX = 1; // public int countY = 1; // // public SpriteData() { // } // } // // Path: core/src/net/mostlyoriginal/game/system/dilemma/CardLibrary.java // public class CardLibrary { // public CardData[] cards; // // public CardLibrary() { // } // // Map<String, List<CardData>> grouped = new HashMap<String, List<CardData>>(); // // /** // * Return dilemma, or <code>null</code> if empty. // */ // public CardData getById(String id) { // for (CardData card : cards) { // if (card.id != null && card.id.equals(id)) return card; // } // return null; // } // // public CardData random() { // CardData result = null; // while (result == null || result.manual) { // result = cards[MathUtils.random(0, cards.length - 1)]; // } // return result; // } // } // // Path: core/src/net/mostlyoriginal/game/system/planet/SpriteLibrary.java // public class SpriteLibrary implements Serializable { // public net.mostlyoriginal.game.component.SpriteData[] sprites; // // public SpriteLibrary() { // } // // /** // * Return dilemma, or <code>null</code> if empty. // */ // public SpriteData getById(String id) { // for (SpriteData sprite : sprites) { // if (sprite.id != null && sprite.id.equals(id)) return sprite; // } // return null; // } // } // // Path: components/src/net/mostlyoriginal/game/component/G.java // public static final boolean DEBUG_NO_MUSIC =(!PRODUCTION && false);
import com.artemis.E; import com.artemis.annotations.Wire; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Animation; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.utils.Json; import net.mostlyoriginal.api.manager.AbstractAssetSystem; import net.mostlyoriginal.game.component.G; import net.mostlyoriginal.game.component.SpriteData; import net.mostlyoriginal.game.system.dilemma.CardLibrary; import net.mostlyoriginal.game.system.planet.SpriteLibrary; import static net.mostlyoriginal.game.component.G.DEBUG_NO_MUSIC;
package net.mostlyoriginal.game.system.view; /** * @author Daan van Yperen */ @Wire public class GameScreenAssetSystem extends AbstractAssetSystem {
// Path: components/src/net/mostlyoriginal/game/component/G.java // public class G { // // public static final int LOGO_WIDTH = 280; // public static final int LOGO_HEIGHT = 221; // public static final int LAYER_CURSOR = 2000; // // public static final boolean PRODUCTION = false; // // public static final boolean INTERLACING_SIMULATION = true; // // public static final boolean DEBUG_SKIP_INTRO = (!PRODUCTION && false); // public static final boolean DEBUG_ACHIEVEMENTS = (!PRODUCTION && false); // public static final boolean DEBUG_DRAWING = (!PRODUCTION && true); // public static final boolean DEBUG_NO_MUSIC =(!PRODUCTION && false); // public static final boolean DEBUG_NO_ENTITY_RENDERING =(!PRODUCTION && false); // public static final boolean DEBUG_NO_SECOND_PASS =(!PRODUCTION && false); // public static final boolean DEBUG_NO_ACHIEVEMENTS = (!PRODUCTION && true); // public static boolean DEBUG_NO_FLOW = (!PRODUCTION && false); // public static boolean DEBUG_AIR_PLANET = (!PRODUCTION && false); // public static boolean DEBUG_NAIVE_GRAVITY = (!PRODUCTION && false); // public static boolean DEBUG_NO_CARDS = (!PRODUCTION && true); // // public static final float CARD_X = 5; // public static final float CARD_Y = 5; // // // public static final int SIMULATION_WIDTH = 220 + 50; // public static final int SIMULATION_HEIGHT = 220 + 50; // public static final int MARGIN_BETWEEN_CARDS = 5; // // public static final int LAYER_STAR = -50; // public static final int LAYER_STRUCTURES_BACKGROUND = -2; // public static final int LAYER_PLANET = 0; // public static final int LAYER_DUDES = 99; // public static final int LAYER_GHOST = 100; // public static final int LAYER_CARDS = 1000; // public static final int LAYER_CARDS_HOVER = 1001; // public static final int LAYER_CARDS_FLYING = 1002; // public static final int LAYER_ACHIEVEMENTS = 900; // public static final int LAYER_STRUCTURES = -1; // public static final int LAYER_STRUCTURES_FOREGROUND = 101; // // public static int CAMERA_ZOOM = 2; // public static final int SCREEN_WIDTH = SIMULATION_WIDTH * 2 * CAMERA_ZOOM; // private static int CARD_HEIGHT = 90; // private static int MARGIN_BETWEEN_CARD_AND_SIM = 10; // // public static int PLANET_X = (SIMULATION_WIDTH) - (SIMULATION_WIDTH / 2); // public static int PLANET_Y = MARGIN_BETWEEN_CARD_AND_SIM + CARD_HEIGHT; // private static final int MARGIN_BETWEEN_SIM_AND_ROOF = 20; // public static final int SCREEN_HEIGHT = (SIMULATION_HEIGHT + CARD_HEIGHT + MARGIN_BETWEEN_CARD_AND_SIM + MARGIN_BETWEEN_SIM_AND_ROOF) * CAMERA_ZOOM; // // public static final int PLANET_CENTER_X = PLANET_X + (SIMULATION_WIDTH / 2); // public static final int PLANET_CENTER_Y = PLANET_Y + (SIMULATION_HEIGHT / 2); // // public static final int GRADIENT_SCALE = 5; // public static float TOOL_HEIGHT = 50; // } // // Path: components/src/net/mostlyoriginal/game/component/SpriteData.java // public class SpriteData implements Serializable { // // public String id; // public String comment; // not used. // // public int x; // public int y; // public int width; // public int height; // public int countX = 1; // public int countY = 1; // // public SpriteData() { // } // } // // Path: core/src/net/mostlyoriginal/game/system/dilemma/CardLibrary.java // public class CardLibrary { // public CardData[] cards; // // public CardLibrary() { // } // // Map<String, List<CardData>> grouped = new HashMap<String, List<CardData>>(); // // /** // * Return dilemma, or <code>null</code> if empty. // */ // public CardData getById(String id) { // for (CardData card : cards) { // if (card.id != null && card.id.equals(id)) return card; // } // return null; // } // // public CardData random() { // CardData result = null; // while (result == null || result.manual) { // result = cards[MathUtils.random(0, cards.length - 1)]; // } // return result; // } // } // // Path: core/src/net/mostlyoriginal/game/system/planet/SpriteLibrary.java // public class SpriteLibrary implements Serializable { // public net.mostlyoriginal.game.component.SpriteData[] sprites; // // public SpriteLibrary() { // } // // /** // * Return dilemma, or <code>null</code> if empty. // */ // public SpriteData getById(String id) { // for (SpriteData sprite : sprites) { // if (sprite.id != null && sprite.id.equals(id)) return sprite; // } // return null; // } // } // // Path: components/src/net/mostlyoriginal/game/component/G.java // public static final boolean DEBUG_NO_MUSIC =(!PRODUCTION && false); // Path: core/src/net/mostlyoriginal/game/system/view/GameScreenAssetSystem.java import com.artemis.E; import com.artemis.annotations.Wire; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Animation; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.utils.Json; import net.mostlyoriginal.api.manager.AbstractAssetSystem; import net.mostlyoriginal.game.component.G; import net.mostlyoriginal.game.component.SpriteData; import net.mostlyoriginal.game.system.dilemma.CardLibrary; import net.mostlyoriginal.game.system.planet.SpriteLibrary; import static net.mostlyoriginal.game.component.G.DEBUG_NO_MUSIC; package net.mostlyoriginal.game.system.view; /** * @author Daan van Yperen */ @Wire public class GameScreenAssetSystem extends AbstractAssetSystem {
private SpriteLibrary spriteLibrary;
google/physical-web
android/PhysicalWeb/app/src/main/java/org/physical_web/physicalweb/DemosFragment.java
// Path: android/PhysicalWeb/app/src/main/java/org/physical_web/demos/Demo.java // public interface Demo { // // /** // * @return The summary of the demo. // */ // String getSummary(); // // /** // * @return The title of the demo. // */ // String getTitle(); // // /** // * Checks to see if the demo is running. // * @return True if the demo has been started and not stopped. // */ // boolean isDemoStarted(); // // /** // * Starts the demo. // */ // void startDemo(); // // /** // * Stops the demo. // */ // void stopDemo(); // } // // Path: android/PhysicalWeb/app/src/main/java/org/physical_web/demos/FatBeaconHelloWorld.java // public class FatBeaconHelloWorld implements Demo { // private static final String TAG = FatBeaconHelloWorld.class.getSimpleName(); // private static boolean mIsDemoStarted = false; // private Context mContext; // // public FatBeaconHelloWorld(Context context) { // mContext = context; // } // // @Override // public String getSummary() { // return mContext.getString(R.string.fat_beacon_demo_summary); // } // // @Override // public String getTitle() { // return mContext.getString(R.string.fat_beacon_demo_title); // } // // @Override // public boolean isDemoStarted() { // return mIsDemoStarted; // } // // @Override // public void startDemo() { // Intent intent = new Intent(mContext, FatBeaconBroadcastService.class); // intent.putExtra(FatBeaconBroadcastService.TITLE_KEY, "Hello World"); // String uriString = ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + // mContext.getPackageName() + "/" + R.raw.fatbeacon_default_webpage; // intent.putExtra(FatBeaconBroadcastService.URI_KEY, uriString); // mContext.startService(intent); // mIsDemoStarted = true; // } // // @Override // public void stopDemo() { // mContext.stopService(new Intent(mContext, FatBeaconBroadcastService.class)); // mIsDemoStarted = false; // } // } // // Path: android/PhysicalWeb/app/src/main/java/org/physical_web/demos/WifiDirectHelloWorld.java // public class WifiDirectHelloWorld implements Demo { // private static final String TAG = WifiDirectHelloWorld.class.getSimpleName(); // private static boolean mIsDemoStarted = false; // private final Context mContext; // // public WifiDirectHelloWorld(Context context) { // mContext = context; // } // // @Override // public String getSummary() { // return mContext.getString(R.string.wifi_direct_demo_summary); // } // // @Override // public String getTitle() { // return mContext.getString(R.string.wifi_direct_demo_title); // } // // @Override // public boolean isDemoStarted() { // return mIsDemoStarted; // } // // @Override // public void startDemo() { // Intent intent = new Intent(mContext, FileBroadcastService.class); // String uriString = ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + // mContext.getPackageName() + "/" + R.raw.wifi_direct_default_webpage; // intent.putExtra(FileBroadcastService.FILE_KEY, uriString); // intent.putExtra(FileBroadcastService.MIME_TYPE_KEY, "text/html"); // intent.putExtra(FileBroadcastService.TITLE_KEY, "Hello World"); // mContext.startService(intent); // mIsDemoStarted = true; // } // // @Override // public void stopDemo() { // mContext.stopService(new Intent(mContext, FileBroadcastService.class)); // mIsDemoStarted = false; // } // }
import android.widget.TextView; import java.util.ArrayList; import java.util.List; import org.physical_web.demos.Demo; import org.physical_web.demos.FatBeaconHelloWorld; import org.physical_web.demos.WifiDirectHelloWorld; import android.app.ListFragment; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListView;
/* * Copyright 2016 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.physical_web.physicalweb; /** * This class shows a list of demos. */ public class DemosFragment extends ListFragment { private static final String TAG = DemosFragment.class.getSimpleName(); private DemosAdapter mAdapter; @Override public View onCreateView(LayoutInflater layoutInflater, ViewGroup container, Bundle savedInstanceState) { setHasOptionsMenu(true); getActivity().getActionBar().setDisplayHomeAsUpEnabled(true); View rootView = layoutInflater.inflate(R.layout.fragment_demos, container, false); mAdapter = new DemosAdapter(); setListAdapter(mAdapter); initialize(); return rootView; } @Override public void onResume() { super.onResume(); getActivity().getActionBar().setTitle(R.string.demos); } @Override public void onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); Utils.hideAllMenuItems(menu); } @Override public void onListItemClick(ListView l, View v, int position, long id) {
// Path: android/PhysicalWeb/app/src/main/java/org/physical_web/demos/Demo.java // public interface Demo { // // /** // * @return The summary of the demo. // */ // String getSummary(); // // /** // * @return The title of the demo. // */ // String getTitle(); // // /** // * Checks to see if the demo is running. // * @return True if the demo has been started and not stopped. // */ // boolean isDemoStarted(); // // /** // * Starts the demo. // */ // void startDemo(); // // /** // * Stops the demo. // */ // void stopDemo(); // } // // Path: android/PhysicalWeb/app/src/main/java/org/physical_web/demos/FatBeaconHelloWorld.java // public class FatBeaconHelloWorld implements Demo { // private static final String TAG = FatBeaconHelloWorld.class.getSimpleName(); // private static boolean mIsDemoStarted = false; // private Context mContext; // // public FatBeaconHelloWorld(Context context) { // mContext = context; // } // // @Override // public String getSummary() { // return mContext.getString(R.string.fat_beacon_demo_summary); // } // // @Override // public String getTitle() { // return mContext.getString(R.string.fat_beacon_demo_title); // } // // @Override // public boolean isDemoStarted() { // return mIsDemoStarted; // } // // @Override // public void startDemo() { // Intent intent = new Intent(mContext, FatBeaconBroadcastService.class); // intent.putExtra(FatBeaconBroadcastService.TITLE_KEY, "Hello World"); // String uriString = ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + // mContext.getPackageName() + "/" + R.raw.fatbeacon_default_webpage; // intent.putExtra(FatBeaconBroadcastService.URI_KEY, uriString); // mContext.startService(intent); // mIsDemoStarted = true; // } // // @Override // public void stopDemo() { // mContext.stopService(new Intent(mContext, FatBeaconBroadcastService.class)); // mIsDemoStarted = false; // } // } // // Path: android/PhysicalWeb/app/src/main/java/org/physical_web/demos/WifiDirectHelloWorld.java // public class WifiDirectHelloWorld implements Demo { // private static final String TAG = WifiDirectHelloWorld.class.getSimpleName(); // private static boolean mIsDemoStarted = false; // private final Context mContext; // // public WifiDirectHelloWorld(Context context) { // mContext = context; // } // // @Override // public String getSummary() { // return mContext.getString(R.string.wifi_direct_demo_summary); // } // // @Override // public String getTitle() { // return mContext.getString(R.string.wifi_direct_demo_title); // } // // @Override // public boolean isDemoStarted() { // return mIsDemoStarted; // } // // @Override // public void startDemo() { // Intent intent = new Intent(mContext, FileBroadcastService.class); // String uriString = ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + // mContext.getPackageName() + "/" + R.raw.wifi_direct_default_webpage; // intent.putExtra(FileBroadcastService.FILE_KEY, uriString); // intent.putExtra(FileBroadcastService.MIME_TYPE_KEY, "text/html"); // intent.putExtra(FileBroadcastService.TITLE_KEY, "Hello World"); // mContext.startService(intent); // mIsDemoStarted = true; // } // // @Override // public void stopDemo() { // mContext.stopService(new Intent(mContext, FileBroadcastService.class)); // mIsDemoStarted = false; // } // } // Path: android/PhysicalWeb/app/src/main/java/org/physical_web/physicalweb/DemosFragment.java import android.widget.TextView; import java.util.ArrayList; import java.util.List; import org.physical_web.demos.Demo; import org.physical_web.demos.FatBeaconHelloWorld; import org.physical_web.demos.WifiDirectHelloWorld; import android.app.ListFragment; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListView; /* * Copyright 2016 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.physical_web.physicalweb; /** * This class shows a list of demos. */ public class DemosFragment extends ListFragment { private static final String TAG = DemosFragment.class.getSimpleName(); private DemosAdapter mAdapter; @Override public View onCreateView(LayoutInflater layoutInflater, ViewGroup container, Bundle savedInstanceState) { setHasOptionsMenu(true); getActivity().getActionBar().setDisplayHomeAsUpEnabled(true); View rootView = layoutInflater.inflate(R.layout.fragment_demos, container, false); mAdapter = new DemosAdapter(); setListAdapter(mAdapter); initialize(); return rootView; } @Override public void onResume() { super.onResume(); getActivity().getActionBar().setTitle(R.string.demos); } @Override public void onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); Utils.hideAllMenuItems(menu); } @Override public void onListItemClick(ListView l, View v, int position, long id) {
Demo demo = mAdapter.getItem(position);
google/physical-web
android/PhysicalWeb/app/src/main/java/org/physical_web/physicalweb/DemosFragment.java
// Path: android/PhysicalWeb/app/src/main/java/org/physical_web/demos/Demo.java // public interface Demo { // // /** // * @return The summary of the demo. // */ // String getSummary(); // // /** // * @return The title of the demo. // */ // String getTitle(); // // /** // * Checks to see if the demo is running. // * @return True if the demo has been started and not stopped. // */ // boolean isDemoStarted(); // // /** // * Starts the demo. // */ // void startDemo(); // // /** // * Stops the demo. // */ // void stopDemo(); // } // // Path: android/PhysicalWeb/app/src/main/java/org/physical_web/demos/FatBeaconHelloWorld.java // public class FatBeaconHelloWorld implements Demo { // private static final String TAG = FatBeaconHelloWorld.class.getSimpleName(); // private static boolean mIsDemoStarted = false; // private Context mContext; // // public FatBeaconHelloWorld(Context context) { // mContext = context; // } // // @Override // public String getSummary() { // return mContext.getString(R.string.fat_beacon_demo_summary); // } // // @Override // public String getTitle() { // return mContext.getString(R.string.fat_beacon_demo_title); // } // // @Override // public boolean isDemoStarted() { // return mIsDemoStarted; // } // // @Override // public void startDemo() { // Intent intent = new Intent(mContext, FatBeaconBroadcastService.class); // intent.putExtra(FatBeaconBroadcastService.TITLE_KEY, "Hello World"); // String uriString = ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + // mContext.getPackageName() + "/" + R.raw.fatbeacon_default_webpage; // intent.putExtra(FatBeaconBroadcastService.URI_KEY, uriString); // mContext.startService(intent); // mIsDemoStarted = true; // } // // @Override // public void stopDemo() { // mContext.stopService(new Intent(mContext, FatBeaconBroadcastService.class)); // mIsDemoStarted = false; // } // } // // Path: android/PhysicalWeb/app/src/main/java/org/physical_web/demos/WifiDirectHelloWorld.java // public class WifiDirectHelloWorld implements Demo { // private static final String TAG = WifiDirectHelloWorld.class.getSimpleName(); // private static boolean mIsDemoStarted = false; // private final Context mContext; // // public WifiDirectHelloWorld(Context context) { // mContext = context; // } // // @Override // public String getSummary() { // return mContext.getString(R.string.wifi_direct_demo_summary); // } // // @Override // public String getTitle() { // return mContext.getString(R.string.wifi_direct_demo_title); // } // // @Override // public boolean isDemoStarted() { // return mIsDemoStarted; // } // // @Override // public void startDemo() { // Intent intent = new Intent(mContext, FileBroadcastService.class); // String uriString = ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + // mContext.getPackageName() + "/" + R.raw.wifi_direct_default_webpage; // intent.putExtra(FileBroadcastService.FILE_KEY, uriString); // intent.putExtra(FileBroadcastService.MIME_TYPE_KEY, "text/html"); // intent.putExtra(FileBroadcastService.TITLE_KEY, "Hello World"); // mContext.startService(intent); // mIsDemoStarted = true; // } // // @Override // public void stopDemo() { // mContext.stopService(new Intent(mContext, FileBroadcastService.class)); // mIsDemoStarted = false; // } // }
import android.widget.TextView; import java.util.ArrayList; import java.util.List; import org.physical_web.demos.Demo; import org.physical_web.demos.FatBeaconHelloWorld; import org.physical_web.demos.WifiDirectHelloWorld; import android.app.ListFragment; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListView;
setListAdapter(mAdapter); initialize(); return rootView; } @Override public void onResume() { super.onResume(); getActivity().getActionBar().setTitle(R.string.demos); } @Override public void onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); Utils.hideAllMenuItems(menu); } @Override public void onListItemClick(ListView l, View v, int position, long id) { Demo demo = mAdapter.getItem(position); if (demo.isDemoStarted()) { demo.stopDemo(); } else { demo.startDemo(); } setBackgroundColor(v, demo.isDemoStarted()); } private void initialize() { if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
// Path: android/PhysicalWeb/app/src/main/java/org/physical_web/demos/Demo.java // public interface Demo { // // /** // * @return The summary of the demo. // */ // String getSummary(); // // /** // * @return The title of the demo. // */ // String getTitle(); // // /** // * Checks to see if the demo is running. // * @return True if the demo has been started and not stopped. // */ // boolean isDemoStarted(); // // /** // * Starts the demo. // */ // void startDemo(); // // /** // * Stops the demo. // */ // void stopDemo(); // } // // Path: android/PhysicalWeb/app/src/main/java/org/physical_web/demos/FatBeaconHelloWorld.java // public class FatBeaconHelloWorld implements Demo { // private static final String TAG = FatBeaconHelloWorld.class.getSimpleName(); // private static boolean mIsDemoStarted = false; // private Context mContext; // // public FatBeaconHelloWorld(Context context) { // mContext = context; // } // // @Override // public String getSummary() { // return mContext.getString(R.string.fat_beacon_demo_summary); // } // // @Override // public String getTitle() { // return mContext.getString(R.string.fat_beacon_demo_title); // } // // @Override // public boolean isDemoStarted() { // return mIsDemoStarted; // } // // @Override // public void startDemo() { // Intent intent = new Intent(mContext, FatBeaconBroadcastService.class); // intent.putExtra(FatBeaconBroadcastService.TITLE_KEY, "Hello World"); // String uriString = ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + // mContext.getPackageName() + "/" + R.raw.fatbeacon_default_webpage; // intent.putExtra(FatBeaconBroadcastService.URI_KEY, uriString); // mContext.startService(intent); // mIsDemoStarted = true; // } // // @Override // public void stopDemo() { // mContext.stopService(new Intent(mContext, FatBeaconBroadcastService.class)); // mIsDemoStarted = false; // } // } // // Path: android/PhysicalWeb/app/src/main/java/org/physical_web/demos/WifiDirectHelloWorld.java // public class WifiDirectHelloWorld implements Demo { // private static final String TAG = WifiDirectHelloWorld.class.getSimpleName(); // private static boolean mIsDemoStarted = false; // private final Context mContext; // // public WifiDirectHelloWorld(Context context) { // mContext = context; // } // // @Override // public String getSummary() { // return mContext.getString(R.string.wifi_direct_demo_summary); // } // // @Override // public String getTitle() { // return mContext.getString(R.string.wifi_direct_demo_title); // } // // @Override // public boolean isDemoStarted() { // return mIsDemoStarted; // } // // @Override // public void startDemo() { // Intent intent = new Intent(mContext, FileBroadcastService.class); // String uriString = ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + // mContext.getPackageName() + "/" + R.raw.wifi_direct_default_webpage; // intent.putExtra(FileBroadcastService.FILE_KEY, uriString); // intent.putExtra(FileBroadcastService.MIME_TYPE_KEY, "text/html"); // intent.putExtra(FileBroadcastService.TITLE_KEY, "Hello World"); // mContext.startService(intent); // mIsDemoStarted = true; // } // // @Override // public void stopDemo() { // mContext.stopService(new Intent(mContext, FileBroadcastService.class)); // mIsDemoStarted = false; // } // } // Path: android/PhysicalWeb/app/src/main/java/org/physical_web/physicalweb/DemosFragment.java import android.widget.TextView; import java.util.ArrayList; import java.util.List; import org.physical_web.demos.Demo; import org.physical_web.demos.FatBeaconHelloWorld; import org.physical_web.demos.WifiDirectHelloWorld; import android.app.ListFragment; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListView; setListAdapter(mAdapter); initialize(); return rootView; } @Override public void onResume() { super.onResume(); getActivity().getActionBar().setTitle(R.string.demos); } @Override public void onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); Utils.hideAllMenuItems(menu); } @Override public void onListItemClick(ListView l, View v, int position, long id) { Demo demo = mAdapter.getItem(position); if (demo.isDemoStarted()) { demo.stopDemo(); } else { demo.startDemo(); } setBackgroundColor(v, demo.isDemoStarted()); } private void initialize() { if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
mAdapter.addItem(new FatBeaconHelloWorld(getActivity()));
google/physical-web
android/PhysicalWeb/app/src/main/java/org/physical_web/physicalweb/DemosFragment.java
// Path: android/PhysicalWeb/app/src/main/java/org/physical_web/demos/Demo.java // public interface Demo { // // /** // * @return The summary of the demo. // */ // String getSummary(); // // /** // * @return The title of the demo. // */ // String getTitle(); // // /** // * Checks to see if the demo is running. // * @return True if the demo has been started and not stopped. // */ // boolean isDemoStarted(); // // /** // * Starts the demo. // */ // void startDemo(); // // /** // * Stops the demo. // */ // void stopDemo(); // } // // Path: android/PhysicalWeb/app/src/main/java/org/physical_web/demos/FatBeaconHelloWorld.java // public class FatBeaconHelloWorld implements Demo { // private static final String TAG = FatBeaconHelloWorld.class.getSimpleName(); // private static boolean mIsDemoStarted = false; // private Context mContext; // // public FatBeaconHelloWorld(Context context) { // mContext = context; // } // // @Override // public String getSummary() { // return mContext.getString(R.string.fat_beacon_demo_summary); // } // // @Override // public String getTitle() { // return mContext.getString(R.string.fat_beacon_demo_title); // } // // @Override // public boolean isDemoStarted() { // return mIsDemoStarted; // } // // @Override // public void startDemo() { // Intent intent = new Intent(mContext, FatBeaconBroadcastService.class); // intent.putExtra(FatBeaconBroadcastService.TITLE_KEY, "Hello World"); // String uriString = ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + // mContext.getPackageName() + "/" + R.raw.fatbeacon_default_webpage; // intent.putExtra(FatBeaconBroadcastService.URI_KEY, uriString); // mContext.startService(intent); // mIsDemoStarted = true; // } // // @Override // public void stopDemo() { // mContext.stopService(new Intent(mContext, FatBeaconBroadcastService.class)); // mIsDemoStarted = false; // } // } // // Path: android/PhysicalWeb/app/src/main/java/org/physical_web/demos/WifiDirectHelloWorld.java // public class WifiDirectHelloWorld implements Demo { // private static final String TAG = WifiDirectHelloWorld.class.getSimpleName(); // private static boolean mIsDemoStarted = false; // private final Context mContext; // // public WifiDirectHelloWorld(Context context) { // mContext = context; // } // // @Override // public String getSummary() { // return mContext.getString(R.string.wifi_direct_demo_summary); // } // // @Override // public String getTitle() { // return mContext.getString(R.string.wifi_direct_demo_title); // } // // @Override // public boolean isDemoStarted() { // return mIsDemoStarted; // } // // @Override // public void startDemo() { // Intent intent = new Intent(mContext, FileBroadcastService.class); // String uriString = ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + // mContext.getPackageName() + "/" + R.raw.wifi_direct_default_webpage; // intent.putExtra(FileBroadcastService.FILE_KEY, uriString); // intent.putExtra(FileBroadcastService.MIME_TYPE_KEY, "text/html"); // intent.putExtra(FileBroadcastService.TITLE_KEY, "Hello World"); // mContext.startService(intent); // mIsDemoStarted = true; // } // // @Override // public void stopDemo() { // mContext.stopService(new Intent(mContext, FileBroadcastService.class)); // mIsDemoStarted = false; // } // }
import android.widget.TextView; import java.util.ArrayList; import java.util.List; import org.physical_web.demos.Demo; import org.physical_web.demos.FatBeaconHelloWorld; import org.physical_web.demos.WifiDirectHelloWorld; import android.app.ListFragment; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListView;
return rootView; } @Override public void onResume() { super.onResume(); getActivity().getActionBar().setTitle(R.string.demos); } @Override public void onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); Utils.hideAllMenuItems(menu); } @Override public void onListItemClick(ListView l, View v, int position, long id) { Demo demo = mAdapter.getItem(position); if (demo.isDemoStarted()) { demo.stopDemo(); } else { demo.startDemo(); } setBackgroundColor(v, demo.isDemoStarted()); } private void initialize() { if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { mAdapter.addItem(new FatBeaconHelloWorld(getActivity())); }
// Path: android/PhysicalWeb/app/src/main/java/org/physical_web/demos/Demo.java // public interface Demo { // // /** // * @return The summary of the demo. // */ // String getSummary(); // // /** // * @return The title of the demo. // */ // String getTitle(); // // /** // * Checks to see if the demo is running. // * @return True if the demo has been started and not stopped. // */ // boolean isDemoStarted(); // // /** // * Starts the demo. // */ // void startDemo(); // // /** // * Stops the demo. // */ // void stopDemo(); // } // // Path: android/PhysicalWeb/app/src/main/java/org/physical_web/demos/FatBeaconHelloWorld.java // public class FatBeaconHelloWorld implements Demo { // private static final String TAG = FatBeaconHelloWorld.class.getSimpleName(); // private static boolean mIsDemoStarted = false; // private Context mContext; // // public FatBeaconHelloWorld(Context context) { // mContext = context; // } // // @Override // public String getSummary() { // return mContext.getString(R.string.fat_beacon_demo_summary); // } // // @Override // public String getTitle() { // return mContext.getString(R.string.fat_beacon_demo_title); // } // // @Override // public boolean isDemoStarted() { // return mIsDemoStarted; // } // // @Override // public void startDemo() { // Intent intent = new Intent(mContext, FatBeaconBroadcastService.class); // intent.putExtra(FatBeaconBroadcastService.TITLE_KEY, "Hello World"); // String uriString = ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + // mContext.getPackageName() + "/" + R.raw.fatbeacon_default_webpage; // intent.putExtra(FatBeaconBroadcastService.URI_KEY, uriString); // mContext.startService(intent); // mIsDemoStarted = true; // } // // @Override // public void stopDemo() { // mContext.stopService(new Intent(mContext, FatBeaconBroadcastService.class)); // mIsDemoStarted = false; // } // } // // Path: android/PhysicalWeb/app/src/main/java/org/physical_web/demos/WifiDirectHelloWorld.java // public class WifiDirectHelloWorld implements Demo { // private static final String TAG = WifiDirectHelloWorld.class.getSimpleName(); // private static boolean mIsDemoStarted = false; // private final Context mContext; // // public WifiDirectHelloWorld(Context context) { // mContext = context; // } // // @Override // public String getSummary() { // return mContext.getString(R.string.wifi_direct_demo_summary); // } // // @Override // public String getTitle() { // return mContext.getString(R.string.wifi_direct_demo_title); // } // // @Override // public boolean isDemoStarted() { // return mIsDemoStarted; // } // // @Override // public void startDemo() { // Intent intent = new Intent(mContext, FileBroadcastService.class); // String uriString = ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + // mContext.getPackageName() + "/" + R.raw.wifi_direct_default_webpage; // intent.putExtra(FileBroadcastService.FILE_KEY, uriString); // intent.putExtra(FileBroadcastService.MIME_TYPE_KEY, "text/html"); // intent.putExtra(FileBroadcastService.TITLE_KEY, "Hello World"); // mContext.startService(intent); // mIsDemoStarted = true; // } // // @Override // public void stopDemo() { // mContext.stopService(new Intent(mContext, FileBroadcastService.class)); // mIsDemoStarted = false; // } // } // Path: android/PhysicalWeb/app/src/main/java/org/physical_web/physicalweb/DemosFragment.java import android.widget.TextView; import java.util.ArrayList; import java.util.List; import org.physical_web.demos.Demo; import org.physical_web.demos.FatBeaconHelloWorld; import org.physical_web.demos.WifiDirectHelloWorld; import android.app.ListFragment; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListView; return rootView; } @Override public void onResume() { super.onResume(); getActivity().getActionBar().setTitle(R.string.demos); } @Override public void onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); Utils.hideAllMenuItems(menu); } @Override public void onListItemClick(ListView l, View v, int position, long id) { Demo demo = mAdapter.getItem(position); if (demo.isDemoStarted()) { demo.stopDemo(); } else { demo.startDemo(); } setBackgroundColor(v, demo.isDemoStarted()); } private void initialize() { if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { mAdapter.addItem(new FatBeaconHelloWorld(getActivity())); }
mAdapter.addItem(new WifiDirectHelloWorld(getActivity()));
eing/moet
java/AddressBookTest/src/app/addressbook/test/impl/AndroidImpl.java
// Path: java/AddressBookTest/src/app/addressbook/test/Contact.java // public class Contact // { // public static enum PhoneLabel // { mobile, iPhone, home, work, main, // home_fax, work_fax, other_fax, pager, other }; // // public static enum EmailLabel { home, work, other }; // // private String firstname = null; // private String lastname = null; // private String phone = null; // private String email = null; // private EmailLabel emailLabel; // private PhoneLabel phoneLabel; // // public Contact(String firstname, String lastname) // { // this.firstname = firstname; // this.lastname = lastname; // } // // public Contact() {} // // /** // * @return the firstname // */ // public String getFirstname() { // return firstname; // } // // /** // * @param firstname the firstname to set // */ // public void setFirstname(String firstname) { // this.firstname = firstname; // } // // /** // * @return the lastname // */ // public String getLastname() { // return lastname; // } // // /** // * @param lastname the lastname to set // */ // public void setLastname(String lastname) { // this.lastname = lastname; // } // // /** // * @return the phone // */ // public String getPhone() { // return phone; // } // // /** // * @param phone the phone to set // */ // public void setPhone(String phone) { // this.phone = phone; // } // // /** // * @return the email1 // */ // public String getEmail() { // return email; // } // // /** // * @param email1 the email1 to set // */ // public void setEmail(String email) { // this.email = email; // } // // /** // * @return the emailLabel // */ // public EmailLabel getEmailLabel() { // return emailLabel; // } // // /** // * @param emailLabel the emailLabel to set // */ // public void setEmailLabel(EmailLabel emailLabel) { // this.emailLabel = emailLabel; // } // // /** // * @return the phoneLabel // */ // public PhoneLabel getPhoneLabel() { // return phoneLabel; // } // // /** // * @param phoneLabel the phoneLabel to set // */ // public void setPhoneLabel(PhoneLabel phoneLabel) { // this.phoneLabel = phoneLabel; // } // // }
import java.io.File; import java.util.logging.Logger; import app.addressbook.test.Contact; import com.intuit.moet.Android; import com.intuit.moet.IDevice; import com.intuit.moet.ImageKit; import com.intuit.moet.Settings;
name = name.toLowerCase(); device.scroll("up", 2); Thread.sleep(1000); if (name.contains("phone")) { device.scroll("left", 3); } else if (name.contains("contacts")) { device.scroll("right", 4); device.scroll("left", 1); } else if (name.contains("fav")) { device.scroll("right", 4); } else { device.scroll("left", 4); device.scroll("right", 1); } } /** * Add contact to address book app. * @param contact Contact info object * @return true if success * @throws Exception exception */
// Path: java/AddressBookTest/src/app/addressbook/test/Contact.java // public class Contact // { // public static enum PhoneLabel // { mobile, iPhone, home, work, main, // home_fax, work_fax, other_fax, pager, other }; // // public static enum EmailLabel { home, work, other }; // // private String firstname = null; // private String lastname = null; // private String phone = null; // private String email = null; // private EmailLabel emailLabel; // private PhoneLabel phoneLabel; // // public Contact(String firstname, String lastname) // { // this.firstname = firstname; // this.lastname = lastname; // } // // public Contact() {} // // /** // * @return the firstname // */ // public String getFirstname() { // return firstname; // } // // /** // * @param firstname the firstname to set // */ // public void setFirstname(String firstname) { // this.firstname = firstname; // } // // /** // * @return the lastname // */ // public String getLastname() { // return lastname; // } // // /** // * @param lastname the lastname to set // */ // public void setLastname(String lastname) { // this.lastname = lastname; // } // // /** // * @return the phone // */ // public String getPhone() { // return phone; // } // // /** // * @param phone the phone to set // */ // public void setPhone(String phone) { // this.phone = phone; // } // // /** // * @return the email1 // */ // public String getEmail() { // return email; // } // // /** // * @param email1 the email1 to set // */ // public void setEmail(String email) { // this.email = email; // } // // /** // * @return the emailLabel // */ // public EmailLabel getEmailLabel() { // return emailLabel; // } // // /** // * @param emailLabel the emailLabel to set // */ // public void setEmailLabel(EmailLabel emailLabel) { // this.emailLabel = emailLabel; // } // // /** // * @return the phoneLabel // */ // public PhoneLabel getPhoneLabel() { // return phoneLabel; // } // // /** // * @param phoneLabel the phoneLabel to set // */ // public void setPhoneLabel(PhoneLabel phoneLabel) { // this.phoneLabel = phoneLabel; // } // // } // Path: java/AddressBookTest/src/app/addressbook/test/impl/AndroidImpl.java import java.io.File; import java.util.logging.Logger; import app.addressbook.test.Contact; import com.intuit.moet.Android; import com.intuit.moet.IDevice; import com.intuit.moet.ImageKit; import com.intuit.moet.Settings; name = name.toLowerCase(); device.scroll("up", 2); Thread.sleep(1000); if (name.contains("phone")) { device.scroll("left", 3); } else if (name.contains("contacts")) { device.scroll("right", 4); device.scroll("left", 1); } else if (name.contains("fav")) { device.scroll("right", 4); } else { device.scroll("left", 4); device.scroll("right", 1); } } /** * Add contact to address book app. * @param contact Contact info object * @return true if success * @throws Exception exception */
public boolean addContact(Contact contact) throws Exception
eing/moet
java/AddressBookTest/src/app/addressbook/test/impl/iPhoneImpl.java
// Path: java/AddressBookTest/src/app/addressbook/test/Contact.java // public class Contact // { // public static enum PhoneLabel // { mobile, iPhone, home, work, main, // home_fax, work_fax, other_fax, pager, other }; // // public static enum EmailLabel { home, work, other }; // // private String firstname = null; // private String lastname = null; // private String phone = null; // private String email = null; // private EmailLabel emailLabel; // private PhoneLabel phoneLabel; // // public Contact(String firstname, String lastname) // { // this.firstname = firstname; // this.lastname = lastname; // } // // public Contact() {} // // /** // * @return the firstname // */ // public String getFirstname() { // return firstname; // } // // /** // * @param firstname the firstname to set // */ // public void setFirstname(String firstname) { // this.firstname = firstname; // } // // /** // * @return the lastname // */ // public String getLastname() { // return lastname; // } // // /** // * @param lastname the lastname to set // */ // public void setLastname(String lastname) { // this.lastname = lastname; // } // // /** // * @return the phone // */ // public String getPhone() { // return phone; // } // // /** // * @param phone the phone to set // */ // public void setPhone(String phone) { // this.phone = phone; // } // // /** // * @return the email1 // */ // public String getEmail() { // return email; // } // // /** // * @param email1 the email1 to set // */ // public void setEmail(String email) { // this.email = email; // } // // /** // * @return the emailLabel // */ // public EmailLabel getEmailLabel() { // return emailLabel; // } // // /** // * @param emailLabel the emailLabel to set // */ // public void setEmailLabel(EmailLabel emailLabel) { // this.emailLabel = emailLabel; // } // // /** // * @return the phoneLabel // */ // public PhoneLabel getPhoneLabel() { // return phoneLabel; // } // // /** // * @param phoneLabel the phoneLabel to set // */ // public void setPhoneLabel(PhoneLabel phoneLabel) { // this.phoneLabel = phoneLabel; // } // // } // // Path: java/AddressBookTest/src/app/addressbook/test/Contact.java // public static enum EmailLabel { home, work, other }; // // Path: java/AddressBookTest/src/app/addressbook/test/Contact.java // public static enum PhoneLabel // { mobile, iPhone, home, work, main, // home_fax, work_fax, other_fax, pager, other };
import java.util.logging.Logger; import app.addressbook.test.Contact; import app.addressbook.test.Contact.EmailLabel; import app.addressbook.test.Contact.PhoneLabel; import com.intuit.moet.IDevice; import com.intuit.moet.ImageKit; import com.intuit.moet.ImageObject; import com.intuit.moet.Settings; import com.intuit.moet.iPhone;
private void resetToHomeScreen() throws Exception { if (ImageKit.findImage(device, ICON_CANCEL)) { device.tapImage(ICON_CANCEL); } if (ImageKit.findImage(device, BUTTON_SEARCH)) { device.tapImage(BUTTON_SEARCH); } if (ImageKit.findImage(device, BUTTON_CANCEL)) { device.tapImage(BUTTON_CANCEL); } else if (ImageKit.findImage(device, BUTTON_ALL_CONTACTS)) { device.tapImage(BUTTON_ALL_CONTACTS); } Thread.sleep(SLEEP_INTERVAL); } /** * Add contact to address book app. * @param contact Contact info object * @return true if success * @throws Exception exception */
// Path: java/AddressBookTest/src/app/addressbook/test/Contact.java // public class Contact // { // public static enum PhoneLabel // { mobile, iPhone, home, work, main, // home_fax, work_fax, other_fax, pager, other }; // // public static enum EmailLabel { home, work, other }; // // private String firstname = null; // private String lastname = null; // private String phone = null; // private String email = null; // private EmailLabel emailLabel; // private PhoneLabel phoneLabel; // // public Contact(String firstname, String lastname) // { // this.firstname = firstname; // this.lastname = lastname; // } // // public Contact() {} // // /** // * @return the firstname // */ // public String getFirstname() { // return firstname; // } // // /** // * @param firstname the firstname to set // */ // public void setFirstname(String firstname) { // this.firstname = firstname; // } // // /** // * @return the lastname // */ // public String getLastname() { // return lastname; // } // // /** // * @param lastname the lastname to set // */ // public void setLastname(String lastname) { // this.lastname = lastname; // } // // /** // * @return the phone // */ // public String getPhone() { // return phone; // } // // /** // * @param phone the phone to set // */ // public void setPhone(String phone) { // this.phone = phone; // } // // /** // * @return the email1 // */ // public String getEmail() { // return email; // } // // /** // * @param email1 the email1 to set // */ // public void setEmail(String email) { // this.email = email; // } // // /** // * @return the emailLabel // */ // public EmailLabel getEmailLabel() { // return emailLabel; // } // // /** // * @param emailLabel the emailLabel to set // */ // public void setEmailLabel(EmailLabel emailLabel) { // this.emailLabel = emailLabel; // } // // /** // * @return the phoneLabel // */ // public PhoneLabel getPhoneLabel() { // return phoneLabel; // } // // /** // * @param phoneLabel the phoneLabel to set // */ // public void setPhoneLabel(PhoneLabel phoneLabel) { // this.phoneLabel = phoneLabel; // } // // } // // Path: java/AddressBookTest/src/app/addressbook/test/Contact.java // public static enum EmailLabel { home, work, other }; // // Path: java/AddressBookTest/src/app/addressbook/test/Contact.java // public static enum PhoneLabel // { mobile, iPhone, home, work, main, // home_fax, work_fax, other_fax, pager, other }; // Path: java/AddressBookTest/src/app/addressbook/test/impl/iPhoneImpl.java import java.util.logging.Logger; import app.addressbook.test.Contact; import app.addressbook.test.Contact.EmailLabel; import app.addressbook.test.Contact.PhoneLabel; import com.intuit.moet.IDevice; import com.intuit.moet.ImageKit; import com.intuit.moet.ImageObject; import com.intuit.moet.Settings; import com.intuit.moet.iPhone; private void resetToHomeScreen() throws Exception { if (ImageKit.findImage(device, ICON_CANCEL)) { device.tapImage(ICON_CANCEL); } if (ImageKit.findImage(device, BUTTON_SEARCH)) { device.tapImage(BUTTON_SEARCH); } if (ImageKit.findImage(device, BUTTON_CANCEL)) { device.tapImage(BUTTON_CANCEL); } else if (ImageKit.findImage(device, BUTTON_ALL_CONTACTS)) { device.tapImage(BUTTON_ALL_CONTACTS); } Thread.sleep(SLEEP_INTERVAL); } /** * Add contact to address book app. * @param contact Contact info object * @return true if success * @throws Exception exception */
public boolean addContact(Contact contact) throws Exception
eing/moet
java/AddressBookTest/src/app/addressbook/test/impl/iPhoneImpl.java
// Path: java/AddressBookTest/src/app/addressbook/test/Contact.java // public class Contact // { // public static enum PhoneLabel // { mobile, iPhone, home, work, main, // home_fax, work_fax, other_fax, pager, other }; // // public static enum EmailLabel { home, work, other }; // // private String firstname = null; // private String lastname = null; // private String phone = null; // private String email = null; // private EmailLabel emailLabel; // private PhoneLabel phoneLabel; // // public Contact(String firstname, String lastname) // { // this.firstname = firstname; // this.lastname = lastname; // } // // public Contact() {} // // /** // * @return the firstname // */ // public String getFirstname() { // return firstname; // } // // /** // * @param firstname the firstname to set // */ // public void setFirstname(String firstname) { // this.firstname = firstname; // } // // /** // * @return the lastname // */ // public String getLastname() { // return lastname; // } // // /** // * @param lastname the lastname to set // */ // public void setLastname(String lastname) { // this.lastname = lastname; // } // // /** // * @return the phone // */ // public String getPhone() { // return phone; // } // // /** // * @param phone the phone to set // */ // public void setPhone(String phone) { // this.phone = phone; // } // // /** // * @return the email1 // */ // public String getEmail() { // return email; // } // // /** // * @param email1 the email1 to set // */ // public void setEmail(String email) { // this.email = email; // } // // /** // * @return the emailLabel // */ // public EmailLabel getEmailLabel() { // return emailLabel; // } // // /** // * @param emailLabel the emailLabel to set // */ // public void setEmailLabel(EmailLabel emailLabel) { // this.emailLabel = emailLabel; // } // // /** // * @return the phoneLabel // */ // public PhoneLabel getPhoneLabel() { // return phoneLabel; // } // // /** // * @param phoneLabel the phoneLabel to set // */ // public void setPhoneLabel(PhoneLabel phoneLabel) { // this.phoneLabel = phoneLabel; // } // // } // // Path: java/AddressBookTest/src/app/addressbook/test/Contact.java // public static enum EmailLabel { home, work, other }; // // Path: java/AddressBookTest/src/app/addressbook/test/Contact.java // public static enum PhoneLabel // { mobile, iPhone, home, work, main, // home_fax, work_fax, other_fax, pager, other };
import java.util.logging.Logger; import app.addressbook.test.Contact; import app.addressbook.test.Contact.EmailLabel; import app.addressbook.test.Contact.PhoneLabel; import com.intuit.moet.IDevice; import com.intuit.moet.ImageKit; import com.intuit.moet.ImageObject; import com.intuit.moet.Settings; import com.intuit.moet.iPhone;
} /** * Add contact to address book app. * @param contact Contact info object * @return true if success * @throws Exception exception */ public boolean addContact(Contact contact) throws Exception { resetToHomeScreen(); device.tapImage(ICON_ADD_CONTACT); Thread.sleep(SLEEP_INTERVAL); System.out.println(device.getText()); if (contact.getFirstname() != null) { device.tap("First"); device.enter(contact.getFirstname()); } if (contact.getLastname() != null) { device.tap("Last"); device.enter(contact.getLastname()); } if (contact.getPhone() != null) { device.tap("Phone"); device.enter(contact.getPhone());
// Path: java/AddressBookTest/src/app/addressbook/test/Contact.java // public class Contact // { // public static enum PhoneLabel // { mobile, iPhone, home, work, main, // home_fax, work_fax, other_fax, pager, other }; // // public static enum EmailLabel { home, work, other }; // // private String firstname = null; // private String lastname = null; // private String phone = null; // private String email = null; // private EmailLabel emailLabel; // private PhoneLabel phoneLabel; // // public Contact(String firstname, String lastname) // { // this.firstname = firstname; // this.lastname = lastname; // } // // public Contact() {} // // /** // * @return the firstname // */ // public String getFirstname() { // return firstname; // } // // /** // * @param firstname the firstname to set // */ // public void setFirstname(String firstname) { // this.firstname = firstname; // } // // /** // * @return the lastname // */ // public String getLastname() { // return lastname; // } // // /** // * @param lastname the lastname to set // */ // public void setLastname(String lastname) { // this.lastname = lastname; // } // // /** // * @return the phone // */ // public String getPhone() { // return phone; // } // // /** // * @param phone the phone to set // */ // public void setPhone(String phone) { // this.phone = phone; // } // // /** // * @return the email1 // */ // public String getEmail() { // return email; // } // // /** // * @param email1 the email1 to set // */ // public void setEmail(String email) { // this.email = email; // } // // /** // * @return the emailLabel // */ // public EmailLabel getEmailLabel() { // return emailLabel; // } // // /** // * @param emailLabel the emailLabel to set // */ // public void setEmailLabel(EmailLabel emailLabel) { // this.emailLabel = emailLabel; // } // // /** // * @return the phoneLabel // */ // public PhoneLabel getPhoneLabel() { // return phoneLabel; // } // // /** // * @param phoneLabel the phoneLabel to set // */ // public void setPhoneLabel(PhoneLabel phoneLabel) { // this.phoneLabel = phoneLabel; // } // // } // // Path: java/AddressBookTest/src/app/addressbook/test/Contact.java // public static enum EmailLabel { home, work, other }; // // Path: java/AddressBookTest/src/app/addressbook/test/Contact.java // public static enum PhoneLabel // { mobile, iPhone, home, work, main, // home_fax, work_fax, other_fax, pager, other }; // Path: java/AddressBookTest/src/app/addressbook/test/impl/iPhoneImpl.java import java.util.logging.Logger; import app.addressbook.test.Contact; import app.addressbook.test.Contact.EmailLabel; import app.addressbook.test.Contact.PhoneLabel; import com.intuit.moet.IDevice; import com.intuit.moet.ImageKit; import com.intuit.moet.ImageObject; import com.intuit.moet.Settings; import com.intuit.moet.iPhone; } /** * Add contact to address book app. * @param contact Contact info object * @return true if success * @throws Exception exception */ public boolean addContact(Contact contact) throws Exception { resetToHomeScreen(); device.tapImage(ICON_ADD_CONTACT); Thread.sleep(SLEEP_INTERVAL); System.out.println(device.getText()); if (contact.getFirstname() != null) { device.tap("First"); device.enter(contact.getFirstname()); } if (contact.getLastname() != null) { device.tap("Last"); device.enter(contact.getLastname()); } if (contact.getPhone() != null) { device.tap("Phone"); device.enter(contact.getPhone());
if (contact.getPhoneLabel() != PhoneLabel.mobile)
eing/moet
java/AddressBookTest/src/app/addressbook/test/impl/iPhoneImpl.java
// Path: java/AddressBookTest/src/app/addressbook/test/Contact.java // public class Contact // { // public static enum PhoneLabel // { mobile, iPhone, home, work, main, // home_fax, work_fax, other_fax, pager, other }; // // public static enum EmailLabel { home, work, other }; // // private String firstname = null; // private String lastname = null; // private String phone = null; // private String email = null; // private EmailLabel emailLabel; // private PhoneLabel phoneLabel; // // public Contact(String firstname, String lastname) // { // this.firstname = firstname; // this.lastname = lastname; // } // // public Contact() {} // // /** // * @return the firstname // */ // public String getFirstname() { // return firstname; // } // // /** // * @param firstname the firstname to set // */ // public void setFirstname(String firstname) { // this.firstname = firstname; // } // // /** // * @return the lastname // */ // public String getLastname() { // return lastname; // } // // /** // * @param lastname the lastname to set // */ // public void setLastname(String lastname) { // this.lastname = lastname; // } // // /** // * @return the phone // */ // public String getPhone() { // return phone; // } // // /** // * @param phone the phone to set // */ // public void setPhone(String phone) { // this.phone = phone; // } // // /** // * @return the email1 // */ // public String getEmail() { // return email; // } // // /** // * @param email1 the email1 to set // */ // public void setEmail(String email) { // this.email = email; // } // // /** // * @return the emailLabel // */ // public EmailLabel getEmailLabel() { // return emailLabel; // } // // /** // * @param emailLabel the emailLabel to set // */ // public void setEmailLabel(EmailLabel emailLabel) { // this.emailLabel = emailLabel; // } // // /** // * @return the phoneLabel // */ // public PhoneLabel getPhoneLabel() { // return phoneLabel; // } // // /** // * @param phoneLabel the phoneLabel to set // */ // public void setPhoneLabel(PhoneLabel phoneLabel) { // this.phoneLabel = phoneLabel; // } // // } // // Path: java/AddressBookTest/src/app/addressbook/test/Contact.java // public static enum EmailLabel { home, work, other }; // // Path: java/AddressBookTest/src/app/addressbook/test/Contact.java // public static enum PhoneLabel // { mobile, iPhone, home, work, main, // home_fax, work_fax, other_fax, pager, other };
import java.util.logging.Logger; import app.addressbook.test.Contact; import app.addressbook.test.Contact.EmailLabel; import app.addressbook.test.Contact.PhoneLabel; import com.intuit.moet.IDevice; import com.intuit.moet.ImageKit; import com.intuit.moet.ImageObject; import com.intuit.moet.Settings; import com.intuit.moet.iPhone;
device.tapImage(ICON_ADD_CONTACT); Thread.sleep(SLEEP_INTERVAL); System.out.println(device.getText()); if (contact.getFirstname() != null) { device.tap("First"); device.enter(contact.getFirstname()); } if (contact.getLastname() != null) { device.tap("Last"); device.enter(contact.getLastname()); } if (contact.getPhone() != null) { device.tap("Phone"); device.enter(contact.getPhone()); if (contact.getPhoneLabel() != PhoneLabel.mobile) { device.tap("mobile"); System.out.println(device.getText()); device.tap(contact.getPhoneLabel().name()); } } if (contact.getEmail() != null) { device.tap("Email"); device.enter(contact.getEmail());
// Path: java/AddressBookTest/src/app/addressbook/test/Contact.java // public class Contact // { // public static enum PhoneLabel // { mobile, iPhone, home, work, main, // home_fax, work_fax, other_fax, pager, other }; // // public static enum EmailLabel { home, work, other }; // // private String firstname = null; // private String lastname = null; // private String phone = null; // private String email = null; // private EmailLabel emailLabel; // private PhoneLabel phoneLabel; // // public Contact(String firstname, String lastname) // { // this.firstname = firstname; // this.lastname = lastname; // } // // public Contact() {} // // /** // * @return the firstname // */ // public String getFirstname() { // return firstname; // } // // /** // * @param firstname the firstname to set // */ // public void setFirstname(String firstname) { // this.firstname = firstname; // } // // /** // * @return the lastname // */ // public String getLastname() { // return lastname; // } // // /** // * @param lastname the lastname to set // */ // public void setLastname(String lastname) { // this.lastname = lastname; // } // // /** // * @return the phone // */ // public String getPhone() { // return phone; // } // // /** // * @param phone the phone to set // */ // public void setPhone(String phone) { // this.phone = phone; // } // // /** // * @return the email1 // */ // public String getEmail() { // return email; // } // // /** // * @param email1 the email1 to set // */ // public void setEmail(String email) { // this.email = email; // } // // /** // * @return the emailLabel // */ // public EmailLabel getEmailLabel() { // return emailLabel; // } // // /** // * @param emailLabel the emailLabel to set // */ // public void setEmailLabel(EmailLabel emailLabel) { // this.emailLabel = emailLabel; // } // // /** // * @return the phoneLabel // */ // public PhoneLabel getPhoneLabel() { // return phoneLabel; // } // // /** // * @param phoneLabel the phoneLabel to set // */ // public void setPhoneLabel(PhoneLabel phoneLabel) { // this.phoneLabel = phoneLabel; // } // // } // // Path: java/AddressBookTest/src/app/addressbook/test/Contact.java // public static enum EmailLabel { home, work, other }; // // Path: java/AddressBookTest/src/app/addressbook/test/Contact.java // public static enum PhoneLabel // { mobile, iPhone, home, work, main, // home_fax, work_fax, other_fax, pager, other }; // Path: java/AddressBookTest/src/app/addressbook/test/impl/iPhoneImpl.java import java.util.logging.Logger; import app.addressbook.test.Contact; import app.addressbook.test.Contact.EmailLabel; import app.addressbook.test.Contact.PhoneLabel; import com.intuit.moet.IDevice; import com.intuit.moet.ImageKit; import com.intuit.moet.ImageObject; import com.intuit.moet.Settings; import com.intuit.moet.iPhone; device.tapImage(ICON_ADD_CONTACT); Thread.sleep(SLEEP_INTERVAL); System.out.println(device.getText()); if (contact.getFirstname() != null) { device.tap("First"); device.enter(contact.getFirstname()); } if (contact.getLastname() != null) { device.tap("Last"); device.enter(contact.getLastname()); } if (contact.getPhone() != null) { device.tap("Phone"); device.enter(contact.getPhone()); if (contact.getPhoneLabel() != PhoneLabel.mobile) { device.tap("mobile"); System.out.println(device.getText()); device.tap(contact.getPhoneLabel().name()); } } if (contact.getEmail() != null) { device.tap("Email"); device.enter(contact.getEmail());
if (contact.getEmailLabel() != EmailLabel.home)
eing/moet
java/AddressBookTest/src/app/addressbook/test/impl/IAddressBook.java
// Path: java/AddressBookTest/src/app/addressbook/test/Contact.java // public class Contact // { // public static enum PhoneLabel // { mobile, iPhone, home, work, main, // home_fax, work_fax, other_fax, pager, other }; // // public static enum EmailLabel { home, work, other }; // // private String firstname = null; // private String lastname = null; // private String phone = null; // private String email = null; // private EmailLabel emailLabel; // private PhoneLabel phoneLabel; // // public Contact(String firstname, String lastname) // { // this.firstname = firstname; // this.lastname = lastname; // } // // public Contact() {} // // /** // * @return the firstname // */ // public String getFirstname() { // return firstname; // } // // /** // * @param firstname the firstname to set // */ // public void setFirstname(String firstname) { // this.firstname = firstname; // } // // /** // * @return the lastname // */ // public String getLastname() { // return lastname; // } // // /** // * @param lastname the lastname to set // */ // public void setLastname(String lastname) { // this.lastname = lastname; // } // // /** // * @return the phone // */ // public String getPhone() { // return phone; // } // // /** // * @param phone the phone to set // */ // public void setPhone(String phone) { // this.phone = phone; // } // // /** // * @return the email1 // */ // public String getEmail() { // return email; // } // // /** // * @param email1 the email1 to set // */ // public void setEmail(String email) { // this.email = email; // } // // /** // * @return the emailLabel // */ // public EmailLabel getEmailLabel() { // return emailLabel; // } // // /** // * @param emailLabel the emailLabel to set // */ // public void setEmailLabel(EmailLabel emailLabel) { // this.emailLabel = emailLabel; // } // // /** // * @return the phoneLabel // */ // public PhoneLabel getPhoneLabel() { // return phoneLabel; // } // // /** // * @param phoneLabel the phoneLabel to set // */ // public void setPhoneLabel(PhoneLabel phoneLabel) { // this.phoneLabel = phoneLabel; // } // // }
import app.addressbook.test.Contact;
package app.addressbook.test.impl; /** * Application APIs to test. * @author eong * */ public interface IAddressBook { /** * Add contact to address book app. * @param contact Contact info object * @return true if success * @throws Exception exception */
// Path: java/AddressBookTest/src/app/addressbook/test/Contact.java // public class Contact // { // public static enum PhoneLabel // { mobile, iPhone, home, work, main, // home_fax, work_fax, other_fax, pager, other }; // // public static enum EmailLabel { home, work, other }; // // private String firstname = null; // private String lastname = null; // private String phone = null; // private String email = null; // private EmailLabel emailLabel; // private PhoneLabel phoneLabel; // // public Contact(String firstname, String lastname) // { // this.firstname = firstname; // this.lastname = lastname; // } // // public Contact() {} // // /** // * @return the firstname // */ // public String getFirstname() { // return firstname; // } // // /** // * @param firstname the firstname to set // */ // public void setFirstname(String firstname) { // this.firstname = firstname; // } // // /** // * @return the lastname // */ // public String getLastname() { // return lastname; // } // // /** // * @param lastname the lastname to set // */ // public void setLastname(String lastname) { // this.lastname = lastname; // } // // /** // * @return the phone // */ // public String getPhone() { // return phone; // } // // /** // * @param phone the phone to set // */ // public void setPhone(String phone) { // this.phone = phone; // } // // /** // * @return the email1 // */ // public String getEmail() { // return email; // } // // /** // * @param email1 the email1 to set // */ // public void setEmail(String email) { // this.email = email; // } // // /** // * @return the emailLabel // */ // public EmailLabel getEmailLabel() { // return emailLabel; // } // // /** // * @param emailLabel the emailLabel to set // */ // public void setEmailLabel(EmailLabel emailLabel) { // this.emailLabel = emailLabel; // } // // /** // * @return the phoneLabel // */ // public PhoneLabel getPhoneLabel() { // return phoneLabel; // } // // /** // * @param phoneLabel the phoneLabel to set // */ // public void setPhoneLabel(PhoneLabel phoneLabel) { // this.phoneLabel = phoneLabel; // } // // } // Path: java/AddressBookTest/src/app/addressbook/test/impl/IAddressBook.java import app.addressbook.test.Contact; package app.addressbook.test.impl; /** * Application APIs to test. * @author eong * */ public interface IAddressBook { /** * Add contact to address book app. * @param contact Contact info object * @return true if success * @throws Exception exception */
public boolean addContact(Contact contact) throws Exception;
eing/moet
java/AddressBookTest/src/app/addressbook/test/BaseTest.java
// Path: java/AddressBookTest/src/app/addressbook/test/impl/IAddressBook.java // public interface IAddressBook // { // /** // * Add contact to address book app. // * @param contact Contact info object // * @return true if success // * @throws Exception exception // */ // public boolean addContact(Contact contact) throws Exception; // // /** // * Find contact to address book app. // * @param contact Contact info object // * @return true if success // * @throws Exception exception // */ // public boolean findContact(Contact contact) throws Exception; // // /** // * Delete contact to address book app. // * @param contact Contact info object // * @return true if success // * @throws Exception exception // */ // public boolean deleteContact(Contact contact) throws Exception; // // }
import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.rules.TestName; import app.addressbook.test.impl.IAddressBook; import com.intuit.moet.IDevice; import com.intuit.moet.ImageKit; import com.intuit.moet.ImageObject; import com.intuit.moet.Settings; import com.intuit.moet.StatusEnum; import com.intuit.moet.iPhone;
package app.addressbook.test; /** * Base class for all tests to extend. * Reads in application properties as well as obtain device and app for testing. * @author eong * */ public class BaseTest { private static final String APP_ICON_PNG = "appIcon.png"; @Rule public TestName name = new TestName(); Properties userProperties = new Properties(); public static IDevice device;
// Path: java/AddressBookTest/src/app/addressbook/test/impl/IAddressBook.java // public interface IAddressBook // { // /** // * Add contact to address book app. // * @param contact Contact info object // * @return true if success // * @throws Exception exception // */ // public boolean addContact(Contact contact) throws Exception; // // /** // * Find contact to address book app. // * @param contact Contact info object // * @return true if success // * @throws Exception exception // */ // public boolean findContact(Contact contact) throws Exception; // // /** // * Delete contact to address book app. // * @param contact Contact info object // * @return true if success // * @throws Exception exception // */ // public boolean deleteContact(Contact contact) throws Exception; // // } // Path: java/AddressBookTest/src/app/addressbook/test/BaseTest.java import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.rules.TestName; import app.addressbook.test.impl.IAddressBook; import com.intuit.moet.IDevice; import com.intuit.moet.ImageKit; import com.intuit.moet.ImageObject; import com.intuit.moet.Settings; import com.intuit.moet.StatusEnum; import com.intuit.moet.iPhone; package app.addressbook.test; /** * Base class for all tests to extend. * Reads in application properties as well as obtain device and app for testing. * @author eong * */ public class BaseTest { private static final String APP_ICON_PNG = "appIcon.png"; @Rule public TestName name = new TestName(); Properties userProperties = new Properties(); public static IDevice device;
public IAddressBook addressbook;
co-stig/phpbb-crawler
phpbb-parser/src/net/kulak/psy/statistics/StatTriads.java
// Path: phpbb-parser/src/net/kulak/psy/data/converters/MatrixConverter.java // public class MatrixConverter { // // public static boolean[][] toAdjacencyMatrix(Map<String, Map<String, Integer>> reciprocity, Set<String> users, int minMessages) { // int sz = users.size(); // boolean[][] res = new boolean[sz][sz]; // for (int i = 0; i < sz; ++i) { // for (int j = 0; j < sz; ++j) { // res[i][j] = false; // } // } // // int i = 0; // int j = 0; // for (String u: users) { // j = 0; // for (String v: users) { // Map<String, Integer> t = reciprocity.get(u); // if (t != null) { // Integer n = t.get(v); // if (n != null && n >= minMessages) { // res[i][j] = true; // } // } // ++j; // } // ++i; // } // // return res; // } // // } // // Path: phpbb-parser/src/net/kulak/psy/data/schema/Interaction.java // @XmlRootElement // public class Interaction { // // private final static DateFormat TIMESTAMP_FORMAT = // SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT); // // private Integer sequence; // private Date timestamp; // private String topicId; // private String fromUserId; // private String toUserId; // private String quoteText; // private Integer quotes; // private String rawText; // private String text; // private List<Payload> payloads; // // public String getRawText() { // return rawText; // } // // public void setRawText(String rawText) { // this.rawText = rawText; // } // // public String getQuoteText() { // return quoteText; // } // // public void setQuoteText(String quoteText) { // this.quoteText = quoteText; // } // // public Integer getQuotes() { // return quotes; // } // // @Override // public String toString() { // return "Interaction [timestamp=" + TIMESTAMP_FORMAT.format(timestamp) + ", topicId=" + topicId // + ", fromUserId=" + fromUserId + ", toUserId=" + toUserId // + ", text=" + text + ", sequence=" + sequence + ", quotes=" // + quotes + ", payloads=" + payloads + "]"; // } // // public void setQuotes(Integer quotes) { // this.quotes = quotes; // } // // public List<Payload> getPayloads() { // if (payloads == null) { // payloads = new ArrayList<Payload>(); // } // return payloads; // } // // public void setPayloads(List<Payload> payloads) { // this.payloads = payloads; // } // // public Integer getSequence() { // return sequence; // } // // public void setSequence(Integer sequence) { // this.sequence = sequence; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public Date getTimestamp() { // return timestamp; // } // // public String formatTimestamp() { // return TIMESTAMP_FORMAT.format(timestamp); // } // // public void setTimestamp(Date timestamp) { // this.timestamp = timestamp; // } // // public String getTopicId() { // return topicId; // } // // public void setTopicId(String topicId) { // this.topicId = topicId; // } // // public String getFromUserId() { // return fromUserId; // } // // public void setFromUserId(String fromUserId) { // this.fromUserId = fromUserId; // } // // public String getToUserId() { // return toUserId; // } // // public void setToUserId(String toUserId) { // this.toUserId = toUserId; // } // }
import java.io.IOException; import java.sql.SQLException; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.Set; import java.util.TreeSet; import net.kulak.psy.data.converters.MatrixConverter; import net.kulak.psy.data.schema.Interaction;
package net.kulak.psy.statistics; /** * Triad significance profile (TSP) statistics. Will output a TSV with 11 rows * and 13 columns in each. Each column corresponds to one of the triads. The * first row is calculated for the original network, while the rest 10 are * calculated against the random graphs with the same degree distribution. * Calculation can take considerable time, depending on the network size. No TSV * header is included in output. */ public class StatTriads extends AbstractStatistics { public StatTriads(String[] args) throws Exception { super(args); } public static void main(String[] args) throws Exception { new StatTriads(args).run(0); } private static final Random RAND = new Random(); public void run(int minMessages) throws SQLException, ClassNotFoundException, IOException {
// Path: phpbb-parser/src/net/kulak/psy/data/converters/MatrixConverter.java // public class MatrixConverter { // // public static boolean[][] toAdjacencyMatrix(Map<String, Map<String, Integer>> reciprocity, Set<String> users, int minMessages) { // int sz = users.size(); // boolean[][] res = new boolean[sz][sz]; // for (int i = 0; i < sz; ++i) { // for (int j = 0; j < sz; ++j) { // res[i][j] = false; // } // } // // int i = 0; // int j = 0; // for (String u: users) { // j = 0; // for (String v: users) { // Map<String, Integer> t = reciprocity.get(u); // if (t != null) { // Integer n = t.get(v); // if (n != null && n >= minMessages) { // res[i][j] = true; // } // } // ++j; // } // ++i; // } // // return res; // } // // } // // Path: phpbb-parser/src/net/kulak/psy/data/schema/Interaction.java // @XmlRootElement // public class Interaction { // // private final static DateFormat TIMESTAMP_FORMAT = // SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT); // // private Integer sequence; // private Date timestamp; // private String topicId; // private String fromUserId; // private String toUserId; // private String quoteText; // private Integer quotes; // private String rawText; // private String text; // private List<Payload> payloads; // // public String getRawText() { // return rawText; // } // // public void setRawText(String rawText) { // this.rawText = rawText; // } // // public String getQuoteText() { // return quoteText; // } // // public void setQuoteText(String quoteText) { // this.quoteText = quoteText; // } // // public Integer getQuotes() { // return quotes; // } // // @Override // public String toString() { // return "Interaction [timestamp=" + TIMESTAMP_FORMAT.format(timestamp) + ", topicId=" + topicId // + ", fromUserId=" + fromUserId + ", toUserId=" + toUserId // + ", text=" + text + ", sequence=" + sequence + ", quotes=" // + quotes + ", payloads=" + payloads + "]"; // } // // public void setQuotes(Integer quotes) { // this.quotes = quotes; // } // // public List<Payload> getPayloads() { // if (payloads == null) { // payloads = new ArrayList<Payload>(); // } // return payloads; // } // // public void setPayloads(List<Payload> payloads) { // this.payloads = payloads; // } // // public Integer getSequence() { // return sequence; // } // // public void setSequence(Integer sequence) { // this.sequence = sequence; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public Date getTimestamp() { // return timestamp; // } // // public String formatTimestamp() { // return TIMESTAMP_FORMAT.format(timestamp); // } // // public void setTimestamp(Date timestamp) { // this.timestamp = timestamp; // } // // public String getTopicId() { // return topicId; // } // // public void setTopicId(String topicId) { // this.topicId = topicId; // } // // public String getFromUserId() { // return fromUserId; // } // // public void setFromUserId(String fromUserId) { // this.fromUserId = fromUserId; // } // // public String getToUserId() { // return toUserId; // } // // public void setToUserId(String toUserId) { // this.toUserId = toUserId; // } // } // Path: phpbb-parser/src/net/kulak/psy/statistics/StatTriads.java import java.io.IOException; import java.sql.SQLException; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.Set; import java.util.TreeSet; import net.kulak.psy.data.converters.MatrixConverter; import net.kulak.psy.data.schema.Interaction; package net.kulak.psy.statistics; /** * Triad significance profile (TSP) statistics. Will output a TSV with 11 rows * and 13 columns in each. Each column corresponds to one of the triads. The * first row is calculated for the original network, while the rest 10 are * calculated against the random graphs with the same degree distribution. * Calculation can take considerable time, depending on the network size. No TSV * header is included in output. */ public class StatTriads extends AbstractStatistics { public StatTriads(String[] args) throws Exception { super(args); } public static void main(String[] args) throws Exception { new StatTriads(args).run(0); } private static final Random RAND = new Random(); public void run(int minMessages) throws SQLException, ClassNotFoundException, IOException {
List<Interaction> inters = getDatabase().getAllInteractionsForPeriod(new Date(0), new Date(), 0);
co-stig/phpbb-crawler
phpbb-parser/src/net/kulak/psy/statistics/StatTriads.java
// Path: phpbb-parser/src/net/kulak/psy/data/converters/MatrixConverter.java // public class MatrixConverter { // // public static boolean[][] toAdjacencyMatrix(Map<String, Map<String, Integer>> reciprocity, Set<String> users, int minMessages) { // int sz = users.size(); // boolean[][] res = new boolean[sz][sz]; // for (int i = 0; i < sz; ++i) { // for (int j = 0; j < sz; ++j) { // res[i][j] = false; // } // } // // int i = 0; // int j = 0; // for (String u: users) { // j = 0; // for (String v: users) { // Map<String, Integer> t = reciprocity.get(u); // if (t != null) { // Integer n = t.get(v); // if (n != null && n >= minMessages) { // res[i][j] = true; // } // } // ++j; // } // ++i; // } // // return res; // } // // } // // Path: phpbb-parser/src/net/kulak/psy/data/schema/Interaction.java // @XmlRootElement // public class Interaction { // // private final static DateFormat TIMESTAMP_FORMAT = // SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT); // // private Integer sequence; // private Date timestamp; // private String topicId; // private String fromUserId; // private String toUserId; // private String quoteText; // private Integer quotes; // private String rawText; // private String text; // private List<Payload> payloads; // // public String getRawText() { // return rawText; // } // // public void setRawText(String rawText) { // this.rawText = rawText; // } // // public String getQuoteText() { // return quoteText; // } // // public void setQuoteText(String quoteText) { // this.quoteText = quoteText; // } // // public Integer getQuotes() { // return quotes; // } // // @Override // public String toString() { // return "Interaction [timestamp=" + TIMESTAMP_FORMAT.format(timestamp) + ", topicId=" + topicId // + ", fromUserId=" + fromUserId + ", toUserId=" + toUserId // + ", text=" + text + ", sequence=" + sequence + ", quotes=" // + quotes + ", payloads=" + payloads + "]"; // } // // public void setQuotes(Integer quotes) { // this.quotes = quotes; // } // // public List<Payload> getPayloads() { // if (payloads == null) { // payloads = new ArrayList<Payload>(); // } // return payloads; // } // // public void setPayloads(List<Payload> payloads) { // this.payloads = payloads; // } // // public Integer getSequence() { // return sequence; // } // // public void setSequence(Integer sequence) { // this.sequence = sequence; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public Date getTimestamp() { // return timestamp; // } // // public String formatTimestamp() { // return TIMESTAMP_FORMAT.format(timestamp); // } // // public void setTimestamp(Date timestamp) { // this.timestamp = timestamp; // } // // public String getTopicId() { // return topicId; // } // // public void setTopicId(String topicId) { // this.topicId = topicId; // } // // public String getFromUserId() { // return fromUserId; // } // // public void setFromUserId(String fromUserId) { // this.fromUserId = fromUserId; // } // // public String getToUserId() { // return toUserId; // } // // public void setToUserId(String toUserId) { // this.toUserId = toUserId; // } // }
import java.io.IOException; import java.sql.SQLException; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.Set; import java.util.TreeSet; import net.kulak.psy.data.converters.MatrixConverter; import net.kulak.psy.data.schema.Interaction;
package net.kulak.psy.statistics; /** * Triad significance profile (TSP) statistics. Will output a TSV with 11 rows * and 13 columns in each. Each column corresponds to one of the triads. The * first row is calculated for the original network, while the rest 10 are * calculated against the random graphs with the same degree distribution. * Calculation can take considerable time, depending on the network size. No TSV * header is included in output. */ public class StatTriads extends AbstractStatistics { public StatTriads(String[] args) throws Exception { super(args); } public static void main(String[] args) throws Exception { new StatTriads(args).run(0); } private static final Random RAND = new Random(); public void run(int minMessages) throws SQLException, ClassNotFoundException, IOException { List<Interaction> inters = getDatabase().getAllInteractionsForPeriod(new Date(0), new Date(), 0); Set<String> usersAll = getDatabase().getAllUsers(); Map<String, Map<String, Integer>> rec = calculateReciprocity(inters, usersAll); // Limit number of iterated users Set<String> users = new TreeSet<String>(); for (Entry<String, Map<String, Integer>> e: rec.entrySet()) { for (Entry<String, Integer> f: e.getValue().entrySet()) { if (f.getValue() >= minMessages) { users.add(f.getKey()); users.add(e.getKey()); } } }
// Path: phpbb-parser/src/net/kulak/psy/data/converters/MatrixConverter.java // public class MatrixConverter { // // public static boolean[][] toAdjacencyMatrix(Map<String, Map<String, Integer>> reciprocity, Set<String> users, int minMessages) { // int sz = users.size(); // boolean[][] res = new boolean[sz][sz]; // for (int i = 0; i < sz; ++i) { // for (int j = 0; j < sz; ++j) { // res[i][j] = false; // } // } // // int i = 0; // int j = 0; // for (String u: users) { // j = 0; // for (String v: users) { // Map<String, Integer> t = reciprocity.get(u); // if (t != null) { // Integer n = t.get(v); // if (n != null && n >= minMessages) { // res[i][j] = true; // } // } // ++j; // } // ++i; // } // // return res; // } // // } // // Path: phpbb-parser/src/net/kulak/psy/data/schema/Interaction.java // @XmlRootElement // public class Interaction { // // private final static DateFormat TIMESTAMP_FORMAT = // SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT); // // private Integer sequence; // private Date timestamp; // private String topicId; // private String fromUserId; // private String toUserId; // private String quoteText; // private Integer quotes; // private String rawText; // private String text; // private List<Payload> payloads; // // public String getRawText() { // return rawText; // } // // public void setRawText(String rawText) { // this.rawText = rawText; // } // // public String getQuoteText() { // return quoteText; // } // // public void setQuoteText(String quoteText) { // this.quoteText = quoteText; // } // // public Integer getQuotes() { // return quotes; // } // // @Override // public String toString() { // return "Interaction [timestamp=" + TIMESTAMP_FORMAT.format(timestamp) + ", topicId=" + topicId // + ", fromUserId=" + fromUserId + ", toUserId=" + toUserId // + ", text=" + text + ", sequence=" + sequence + ", quotes=" // + quotes + ", payloads=" + payloads + "]"; // } // // public void setQuotes(Integer quotes) { // this.quotes = quotes; // } // // public List<Payload> getPayloads() { // if (payloads == null) { // payloads = new ArrayList<Payload>(); // } // return payloads; // } // // public void setPayloads(List<Payload> payloads) { // this.payloads = payloads; // } // // public Integer getSequence() { // return sequence; // } // // public void setSequence(Integer sequence) { // this.sequence = sequence; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public Date getTimestamp() { // return timestamp; // } // // public String formatTimestamp() { // return TIMESTAMP_FORMAT.format(timestamp); // } // // public void setTimestamp(Date timestamp) { // this.timestamp = timestamp; // } // // public String getTopicId() { // return topicId; // } // // public void setTopicId(String topicId) { // this.topicId = topicId; // } // // public String getFromUserId() { // return fromUserId; // } // // public void setFromUserId(String fromUserId) { // this.fromUserId = fromUserId; // } // // public String getToUserId() { // return toUserId; // } // // public void setToUserId(String toUserId) { // this.toUserId = toUserId; // } // } // Path: phpbb-parser/src/net/kulak/psy/statistics/StatTriads.java import java.io.IOException; import java.sql.SQLException; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.Set; import java.util.TreeSet; import net.kulak.psy.data.converters.MatrixConverter; import net.kulak.psy.data.schema.Interaction; package net.kulak.psy.statistics; /** * Triad significance profile (TSP) statistics. Will output a TSV with 11 rows * and 13 columns in each. Each column corresponds to one of the triads. The * first row is calculated for the original network, while the rest 10 are * calculated against the random graphs with the same degree distribution. * Calculation can take considerable time, depending on the network size. No TSV * header is included in output. */ public class StatTriads extends AbstractStatistics { public StatTriads(String[] args) throws Exception { super(args); } public static void main(String[] args) throws Exception { new StatTriads(args).run(0); } private static final Random RAND = new Random(); public void run(int minMessages) throws SQLException, ClassNotFoundException, IOException { List<Interaction> inters = getDatabase().getAllInteractionsForPeriod(new Date(0), new Date(), 0); Set<String> usersAll = getDatabase().getAllUsers(); Map<String, Map<String, Integer>> rec = calculateReciprocity(inters, usersAll); // Limit number of iterated users Set<String> users = new TreeSet<String>(); for (Entry<String, Map<String, Integer>> e: rec.entrySet()) { for (Entry<String, Integer> f: e.getValue().entrySet()) { if (f.getValue() >= minMessages) { users.add(f.getKey()); users.add(e.getKey()); } } }
boolean[][] adj = MatrixConverter.toAdjacencyMatrix(rec, users, 0);
co-stig/phpbb-crawler
phpbb-parser/src/net/kulak/psy/statistics/StatReciprocity.java
// Path: phpbb-parser/src/net/kulak/psy/data/schema/Interaction.java // @XmlRootElement // public class Interaction { // // private final static DateFormat TIMESTAMP_FORMAT = // SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT); // // private Integer sequence; // private Date timestamp; // private String topicId; // private String fromUserId; // private String toUserId; // private String quoteText; // private Integer quotes; // private String rawText; // private String text; // private List<Payload> payloads; // // public String getRawText() { // return rawText; // } // // public void setRawText(String rawText) { // this.rawText = rawText; // } // // public String getQuoteText() { // return quoteText; // } // // public void setQuoteText(String quoteText) { // this.quoteText = quoteText; // } // // public Integer getQuotes() { // return quotes; // } // // @Override // public String toString() { // return "Interaction [timestamp=" + TIMESTAMP_FORMAT.format(timestamp) + ", topicId=" + topicId // + ", fromUserId=" + fromUserId + ", toUserId=" + toUserId // + ", text=" + text + ", sequence=" + sequence + ", quotes=" // + quotes + ", payloads=" + payloads + "]"; // } // // public void setQuotes(Integer quotes) { // this.quotes = quotes; // } // // public List<Payload> getPayloads() { // if (payloads == null) { // payloads = new ArrayList<Payload>(); // } // return payloads; // } // // public void setPayloads(List<Payload> payloads) { // this.payloads = payloads; // } // // public Integer getSequence() { // return sequence; // } // // public void setSequence(Integer sequence) { // this.sequence = sequence; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public Date getTimestamp() { // return timestamp; // } // // public String formatTimestamp() { // return TIMESTAMP_FORMAT.format(timestamp); // } // // public void setTimestamp(Date timestamp) { // this.timestamp = timestamp; // } // // public String getTopicId() { // return topicId; // } // // public void setTopicId(String topicId) { // this.topicId = topicId; // } // // public String getFromUserId() { // return fromUserId; // } // // public void setFromUserId(String fromUserId) { // this.fromUserId = fromUserId; // } // // public String getToUserId() { // return toUserId; // } // // public void setToUserId(String toUserId) { // this.toUserId = toUserId; // } // }
import java.io.IOException; import java.sql.SQLException; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeSet; import net.kulak.psy.data.schema.Interaction;
package net.kulak.psy.statistics; /** * Reciprocity statistics. Will output a TSV with 4 columns: from (username A), * to (username B), number of messages from A to B, number of messages from B to * A. Each pair of users will be listed only once. No header is included in * output. */ public class StatReciprocity extends AbstractStatistics { public StatReciprocity(String[] args) throws Exception { super(args); } public static void main(String[] args) throws Exception { new StatReciprocity(args).run(); } public void run() throws SQLException, ClassNotFoundException, IOException {
// Path: phpbb-parser/src/net/kulak/psy/data/schema/Interaction.java // @XmlRootElement // public class Interaction { // // private final static DateFormat TIMESTAMP_FORMAT = // SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT); // // private Integer sequence; // private Date timestamp; // private String topicId; // private String fromUserId; // private String toUserId; // private String quoteText; // private Integer quotes; // private String rawText; // private String text; // private List<Payload> payloads; // // public String getRawText() { // return rawText; // } // // public void setRawText(String rawText) { // this.rawText = rawText; // } // // public String getQuoteText() { // return quoteText; // } // // public void setQuoteText(String quoteText) { // this.quoteText = quoteText; // } // // public Integer getQuotes() { // return quotes; // } // // @Override // public String toString() { // return "Interaction [timestamp=" + TIMESTAMP_FORMAT.format(timestamp) + ", topicId=" + topicId // + ", fromUserId=" + fromUserId + ", toUserId=" + toUserId // + ", text=" + text + ", sequence=" + sequence + ", quotes=" // + quotes + ", payloads=" + payloads + "]"; // } // // public void setQuotes(Integer quotes) { // this.quotes = quotes; // } // // public List<Payload> getPayloads() { // if (payloads == null) { // payloads = new ArrayList<Payload>(); // } // return payloads; // } // // public void setPayloads(List<Payload> payloads) { // this.payloads = payloads; // } // // public Integer getSequence() { // return sequence; // } // // public void setSequence(Integer sequence) { // this.sequence = sequence; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public Date getTimestamp() { // return timestamp; // } // // public String formatTimestamp() { // return TIMESTAMP_FORMAT.format(timestamp); // } // // public void setTimestamp(Date timestamp) { // this.timestamp = timestamp; // } // // public String getTopicId() { // return topicId; // } // // public void setTopicId(String topicId) { // this.topicId = topicId; // } // // public String getFromUserId() { // return fromUserId; // } // // public void setFromUserId(String fromUserId) { // this.fromUserId = fromUserId; // } // // public String getToUserId() { // return toUserId; // } // // public void setToUserId(String toUserId) { // this.toUserId = toUserId; // } // } // Path: phpbb-parser/src/net/kulak/psy/statistics/StatReciprocity.java import java.io.IOException; import java.sql.SQLException; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeSet; import net.kulak.psy.data.schema.Interaction; package net.kulak.psy.statistics; /** * Reciprocity statistics. Will output a TSV with 4 columns: from (username A), * to (username B), number of messages from A to B, number of messages from B to * A. Each pair of users will be listed only once. No header is included in * output. */ public class StatReciprocity extends AbstractStatistics { public StatReciprocity(String[] args) throws Exception { super(args); } public static void main(String[] args) throws Exception { new StatReciprocity(args).run(); } public void run() throws SQLException, ClassNotFoundException, IOException {
List<Interaction> inters = getDatabase().getAllInteractionsForPeriod(new Date(0), new Date(), 0);
co-stig/phpbb-crawler
phpbb-parser/src/net/kulak/psy/semantic/PlainTextAnalyzer.java
// Path: phpbb-parser/src/net/kulak/psy/data/schema/Payload.java // @XmlRootElement // public class Payload { // // @Override // public String toString() { // return "Payload [topicId=" + topicId + ", sequence=" // + sequence + ", timestamp=" // + TIMESTAMP_FORMAT.format(timestamp) + ", type=" + type // + ", value=" + value + "]"; // } // // public String getTopicId() { // return topicId; // } // // public void setTopicId(String topicId) { // this.topicId = topicId; // } // // public Integer getSequence() { // return sequence; // } // // public void setSequence(Integer sequence) { // this.sequence = sequence; // } // // public Date getTimestamp() { // return timestamp; // } // // public void setTimestamp(Date timestamp) { // this.timestamp = timestamp; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getValue() { // return value; // } // // public void setValue(String value) { // this.value = value; // } // // private final static DateFormat TIMESTAMP_FORMAT = SimpleDateFormat // .getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT); // // private String topicId; // private Integer sequence; // private Date timestamp; // private String type; // private String value; // }
import java.util.Date; import net.kulak.psy.data.schema.Payload;
package net.kulak.psy.semantic; public class PlainTextAnalyzer extends InteractionAnalyzer { private final InteractionAnalyzer analyzer; public PlainTextAnalyzer(InteractionAnalyzer analyzer) { this.analyzer = analyzer; }
// Path: phpbb-parser/src/net/kulak/psy/data/schema/Payload.java // @XmlRootElement // public class Payload { // // @Override // public String toString() { // return "Payload [topicId=" + topicId + ", sequence=" // + sequence + ", timestamp=" // + TIMESTAMP_FORMAT.format(timestamp) + ", type=" + type // + ", value=" + value + "]"; // } // // public String getTopicId() { // return topicId; // } // // public void setTopicId(String topicId) { // this.topicId = topicId; // } // // public Integer getSequence() { // return sequence; // } // // public void setSequence(Integer sequence) { // this.sequence = sequence; // } // // public Date getTimestamp() { // return timestamp; // } // // public void setTimestamp(Date timestamp) { // this.timestamp = timestamp; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getValue() { // return value; // } // // public void setValue(String value) { // this.value = value; // } // // private final static DateFormat TIMESTAMP_FORMAT = SimpleDateFormat // .getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT); // // private String topicId; // private Integer sequence; // private Date timestamp; // private String type; // private String value; // } // Path: phpbb-parser/src/net/kulak/psy/semantic/PlainTextAnalyzer.java import java.util.Date; import net.kulak.psy.data.schema.Payload; package net.kulak.psy.semantic; public class PlainTextAnalyzer extends InteractionAnalyzer { private final InteractionAnalyzer analyzer; public PlainTextAnalyzer(InteractionAnalyzer analyzer) { this.analyzer = analyzer; }
public Payload analyze(String text) {
co-stig/phpbb-crawler
phpbb-parser/src/net/kulak/psy/statistics/StatDistance.java
// Path: phpbb-parser/src/net/kulak/psy/data/converters/MatrixConverter.java // public class MatrixConverter { // // public static boolean[][] toAdjacencyMatrix(Map<String, Map<String, Integer>> reciprocity, Set<String> users, int minMessages) { // int sz = users.size(); // boolean[][] res = new boolean[sz][sz]; // for (int i = 0; i < sz; ++i) { // for (int j = 0; j < sz; ++j) { // res[i][j] = false; // } // } // // int i = 0; // int j = 0; // for (String u: users) { // j = 0; // for (String v: users) { // Map<String, Integer> t = reciprocity.get(u); // if (t != null) { // Integer n = t.get(v); // if (n != null && n >= minMessages) { // res[i][j] = true; // } // } // ++j; // } // ++i; // } // // return res; // } // // } // // Path: phpbb-parser/src/net/kulak/psy/data/schema/Interaction.java // @XmlRootElement // public class Interaction { // // private final static DateFormat TIMESTAMP_FORMAT = // SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT); // // private Integer sequence; // private Date timestamp; // private String topicId; // private String fromUserId; // private String toUserId; // private String quoteText; // private Integer quotes; // private String rawText; // private String text; // private List<Payload> payloads; // // public String getRawText() { // return rawText; // } // // public void setRawText(String rawText) { // this.rawText = rawText; // } // // public String getQuoteText() { // return quoteText; // } // // public void setQuoteText(String quoteText) { // this.quoteText = quoteText; // } // // public Integer getQuotes() { // return quotes; // } // // @Override // public String toString() { // return "Interaction [timestamp=" + TIMESTAMP_FORMAT.format(timestamp) + ", topicId=" + topicId // + ", fromUserId=" + fromUserId + ", toUserId=" + toUserId // + ", text=" + text + ", sequence=" + sequence + ", quotes=" // + quotes + ", payloads=" + payloads + "]"; // } // // public void setQuotes(Integer quotes) { // this.quotes = quotes; // } // // public List<Payload> getPayloads() { // if (payloads == null) { // payloads = new ArrayList<Payload>(); // } // return payloads; // } // // public void setPayloads(List<Payload> payloads) { // this.payloads = payloads; // } // // public Integer getSequence() { // return sequence; // } // // public void setSequence(Integer sequence) { // this.sequence = sequence; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public Date getTimestamp() { // return timestamp; // } // // public String formatTimestamp() { // return TIMESTAMP_FORMAT.format(timestamp); // } // // public void setTimestamp(Date timestamp) { // this.timestamp = timestamp; // } // // public String getTopicId() { // return topicId; // } // // public void setTopicId(String topicId) { // this.topicId = topicId; // } // // public String getFromUserId() { // return fromUserId; // } // // public void setFromUserId(String fromUserId) { // this.fromUserId = fromUserId; // } // // public String getToUserId() { // return toUserId; // } // // public void setToUserId(String toUserId) { // this.toUserId = toUserId; // } // }
import java.sql.SQLException; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; import net.kulak.psy.data.converters.MatrixConverter; import net.kulak.psy.data.schema.Interaction;
package net.kulak.psy.statistics; /** * Distance distribution statistics. Outputs an adjacency matrix for the * relationship graph in TSV format. The actual distance calculation is * performed later in Mathematica. */ public class StatDistance extends AbstractStatistics { public StatDistance(String[] args) throws Exception { super(args); } public static void main(String[] args) throws Exception { new StatDistance(args).run(); } public void run() throws SQLException {
// Path: phpbb-parser/src/net/kulak/psy/data/converters/MatrixConverter.java // public class MatrixConverter { // // public static boolean[][] toAdjacencyMatrix(Map<String, Map<String, Integer>> reciprocity, Set<String> users, int minMessages) { // int sz = users.size(); // boolean[][] res = new boolean[sz][sz]; // for (int i = 0; i < sz; ++i) { // for (int j = 0; j < sz; ++j) { // res[i][j] = false; // } // } // // int i = 0; // int j = 0; // for (String u: users) { // j = 0; // for (String v: users) { // Map<String, Integer> t = reciprocity.get(u); // if (t != null) { // Integer n = t.get(v); // if (n != null && n >= minMessages) { // res[i][j] = true; // } // } // ++j; // } // ++i; // } // // return res; // } // // } // // Path: phpbb-parser/src/net/kulak/psy/data/schema/Interaction.java // @XmlRootElement // public class Interaction { // // private final static DateFormat TIMESTAMP_FORMAT = // SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT); // // private Integer sequence; // private Date timestamp; // private String topicId; // private String fromUserId; // private String toUserId; // private String quoteText; // private Integer quotes; // private String rawText; // private String text; // private List<Payload> payloads; // // public String getRawText() { // return rawText; // } // // public void setRawText(String rawText) { // this.rawText = rawText; // } // // public String getQuoteText() { // return quoteText; // } // // public void setQuoteText(String quoteText) { // this.quoteText = quoteText; // } // // public Integer getQuotes() { // return quotes; // } // // @Override // public String toString() { // return "Interaction [timestamp=" + TIMESTAMP_FORMAT.format(timestamp) + ", topicId=" + topicId // + ", fromUserId=" + fromUserId + ", toUserId=" + toUserId // + ", text=" + text + ", sequence=" + sequence + ", quotes=" // + quotes + ", payloads=" + payloads + "]"; // } // // public void setQuotes(Integer quotes) { // this.quotes = quotes; // } // // public List<Payload> getPayloads() { // if (payloads == null) { // payloads = new ArrayList<Payload>(); // } // return payloads; // } // // public void setPayloads(List<Payload> payloads) { // this.payloads = payloads; // } // // public Integer getSequence() { // return sequence; // } // // public void setSequence(Integer sequence) { // this.sequence = sequence; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public Date getTimestamp() { // return timestamp; // } // // public String formatTimestamp() { // return TIMESTAMP_FORMAT.format(timestamp); // } // // public void setTimestamp(Date timestamp) { // this.timestamp = timestamp; // } // // public String getTopicId() { // return topicId; // } // // public void setTopicId(String topicId) { // this.topicId = topicId; // } // // public String getFromUserId() { // return fromUserId; // } // // public void setFromUserId(String fromUserId) { // this.fromUserId = fromUserId; // } // // public String getToUserId() { // return toUserId; // } // // public void setToUserId(String toUserId) { // this.toUserId = toUserId; // } // } // Path: phpbb-parser/src/net/kulak/psy/statistics/StatDistance.java import java.sql.SQLException; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; import net.kulak.psy.data.converters.MatrixConverter; import net.kulak.psy.data.schema.Interaction; package net.kulak.psy.statistics; /** * Distance distribution statistics. Outputs an adjacency matrix for the * relationship graph in TSV format. The actual distance calculation is * performed later in Mathematica. */ public class StatDistance extends AbstractStatistics { public StatDistance(String[] args) throws Exception { super(args); } public static void main(String[] args) throws Exception { new StatDistance(args).run(); } public void run() throws SQLException {
List<Interaction> inters = getDatabase().getAllInteractionsForPeriod(new Date(0), new Date(), 0);
co-stig/phpbb-crawler
phpbb-parser/src/net/kulak/psy/statistics/StatDistance.java
// Path: phpbb-parser/src/net/kulak/psy/data/converters/MatrixConverter.java // public class MatrixConverter { // // public static boolean[][] toAdjacencyMatrix(Map<String, Map<String, Integer>> reciprocity, Set<String> users, int minMessages) { // int sz = users.size(); // boolean[][] res = new boolean[sz][sz]; // for (int i = 0; i < sz; ++i) { // for (int j = 0; j < sz; ++j) { // res[i][j] = false; // } // } // // int i = 0; // int j = 0; // for (String u: users) { // j = 0; // for (String v: users) { // Map<String, Integer> t = reciprocity.get(u); // if (t != null) { // Integer n = t.get(v); // if (n != null && n >= minMessages) { // res[i][j] = true; // } // } // ++j; // } // ++i; // } // // return res; // } // // } // // Path: phpbb-parser/src/net/kulak/psy/data/schema/Interaction.java // @XmlRootElement // public class Interaction { // // private final static DateFormat TIMESTAMP_FORMAT = // SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT); // // private Integer sequence; // private Date timestamp; // private String topicId; // private String fromUserId; // private String toUserId; // private String quoteText; // private Integer quotes; // private String rawText; // private String text; // private List<Payload> payloads; // // public String getRawText() { // return rawText; // } // // public void setRawText(String rawText) { // this.rawText = rawText; // } // // public String getQuoteText() { // return quoteText; // } // // public void setQuoteText(String quoteText) { // this.quoteText = quoteText; // } // // public Integer getQuotes() { // return quotes; // } // // @Override // public String toString() { // return "Interaction [timestamp=" + TIMESTAMP_FORMAT.format(timestamp) + ", topicId=" + topicId // + ", fromUserId=" + fromUserId + ", toUserId=" + toUserId // + ", text=" + text + ", sequence=" + sequence + ", quotes=" // + quotes + ", payloads=" + payloads + "]"; // } // // public void setQuotes(Integer quotes) { // this.quotes = quotes; // } // // public List<Payload> getPayloads() { // if (payloads == null) { // payloads = new ArrayList<Payload>(); // } // return payloads; // } // // public void setPayloads(List<Payload> payloads) { // this.payloads = payloads; // } // // public Integer getSequence() { // return sequence; // } // // public void setSequence(Integer sequence) { // this.sequence = sequence; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public Date getTimestamp() { // return timestamp; // } // // public String formatTimestamp() { // return TIMESTAMP_FORMAT.format(timestamp); // } // // public void setTimestamp(Date timestamp) { // this.timestamp = timestamp; // } // // public String getTopicId() { // return topicId; // } // // public void setTopicId(String topicId) { // this.topicId = topicId; // } // // public String getFromUserId() { // return fromUserId; // } // // public void setFromUserId(String fromUserId) { // this.fromUserId = fromUserId; // } // // public String getToUserId() { // return toUserId; // } // // public void setToUserId(String toUserId) { // this.toUserId = toUserId; // } // }
import java.sql.SQLException; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; import net.kulak.psy.data.converters.MatrixConverter; import net.kulak.psy.data.schema.Interaction;
package net.kulak.psy.statistics; /** * Distance distribution statistics. Outputs an adjacency matrix for the * relationship graph in TSV format. The actual distance calculation is * performed later in Mathematica. */ public class StatDistance extends AbstractStatistics { public StatDistance(String[] args) throws Exception { super(args); } public static void main(String[] args) throws Exception { new StatDistance(args).run(); } public void run() throws SQLException { List<Interaction> inters = getDatabase().getAllInteractionsForPeriod(new Date(0), new Date(), 0); Set<String> users = getDatabase().getAllUsers(); Map<String, Map<String, Integer>> rec = calculateReciprocity(inters, users);
// Path: phpbb-parser/src/net/kulak/psy/data/converters/MatrixConverter.java // public class MatrixConverter { // // public static boolean[][] toAdjacencyMatrix(Map<String, Map<String, Integer>> reciprocity, Set<String> users, int minMessages) { // int sz = users.size(); // boolean[][] res = new boolean[sz][sz]; // for (int i = 0; i < sz; ++i) { // for (int j = 0; j < sz; ++j) { // res[i][j] = false; // } // } // // int i = 0; // int j = 0; // for (String u: users) { // j = 0; // for (String v: users) { // Map<String, Integer> t = reciprocity.get(u); // if (t != null) { // Integer n = t.get(v); // if (n != null && n >= minMessages) { // res[i][j] = true; // } // } // ++j; // } // ++i; // } // // return res; // } // // } // // Path: phpbb-parser/src/net/kulak/psy/data/schema/Interaction.java // @XmlRootElement // public class Interaction { // // private final static DateFormat TIMESTAMP_FORMAT = // SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT); // // private Integer sequence; // private Date timestamp; // private String topicId; // private String fromUserId; // private String toUserId; // private String quoteText; // private Integer quotes; // private String rawText; // private String text; // private List<Payload> payloads; // // public String getRawText() { // return rawText; // } // // public void setRawText(String rawText) { // this.rawText = rawText; // } // // public String getQuoteText() { // return quoteText; // } // // public void setQuoteText(String quoteText) { // this.quoteText = quoteText; // } // // public Integer getQuotes() { // return quotes; // } // // @Override // public String toString() { // return "Interaction [timestamp=" + TIMESTAMP_FORMAT.format(timestamp) + ", topicId=" + topicId // + ", fromUserId=" + fromUserId + ", toUserId=" + toUserId // + ", text=" + text + ", sequence=" + sequence + ", quotes=" // + quotes + ", payloads=" + payloads + "]"; // } // // public void setQuotes(Integer quotes) { // this.quotes = quotes; // } // // public List<Payload> getPayloads() { // if (payloads == null) { // payloads = new ArrayList<Payload>(); // } // return payloads; // } // // public void setPayloads(List<Payload> payloads) { // this.payloads = payloads; // } // // public Integer getSequence() { // return sequence; // } // // public void setSequence(Integer sequence) { // this.sequence = sequence; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public Date getTimestamp() { // return timestamp; // } // // public String formatTimestamp() { // return TIMESTAMP_FORMAT.format(timestamp); // } // // public void setTimestamp(Date timestamp) { // this.timestamp = timestamp; // } // // public String getTopicId() { // return topicId; // } // // public void setTopicId(String topicId) { // this.topicId = topicId; // } // // public String getFromUserId() { // return fromUserId; // } // // public void setFromUserId(String fromUserId) { // this.fromUserId = fromUserId; // } // // public String getToUserId() { // return toUserId; // } // // public void setToUserId(String toUserId) { // this.toUserId = toUserId; // } // } // Path: phpbb-parser/src/net/kulak/psy/statistics/StatDistance.java import java.sql.SQLException; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; import net.kulak.psy.data.converters.MatrixConverter; import net.kulak.psy.data.schema.Interaction; package net.kulak.psy.statistics; /** * Distance distribution statistics. Outputs an adjacency matrix for the * relationship graph in TSV format. The actual distance calculation is * performed later in Mathematica. */ public class StatDistance extends AbstractStatistics { public StatDistance(String[] args) throws Exception { super(args); } public static void main(String[] args) throws Exception { new StatDistance(args).run(); } public void run() throws SQLException { List<Interaction> inters = getDatabase().getAllInteractionsForPeriod(new Date(0), new Date(), 0); Set<String> users = getDatabase().getAllUsers(); Map<String, Map<String, Integer>> rec = calculateReciprocity(inters, users);
boolean[][] adj = MatrixConverter.toAdjacencyMatrix(rec, users, 0);
co-stig/phpbb-crawler
phpbb-parser/src/net/kulak/psy/semantic/RegexpInteractionAnalyzer.java
// Path: phpbb-parser/src/net/kulak/psy/data/schema/Payload.java // @XmlRootElement // public class Payload { // // @Override // public String toString() { // return "Payload [topicId=" + topicId + ", sequence=" // + sequence + ", timestamp=" // + TIMESTAMP_FORMAT.format(timestamp) + ", type=" + type // + ", value=" + value + "]"; // } // // public String getTopicId() { // return topicId; // } // // public void setTopicId(String topicId) { // this.topicId = topicId; // } // // public Integer getSequence() { // return sequence; // } // // public void setSequence(Integer sequence) { // this.sequence = sequence; // } // // public Date getTimestamp() { // return timestamp; // } // // public void setTimestamp(Date timestamp) { // this.timestamp = timestamp; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getValue() { // return value; // } // // public void setValue(String value) { // this.value = value; // } // // private final static DateFormat TIMESTAMP_FORMAT = SimpleDateFormat // .getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT); // // private String topicId; // private Integer sequence; // private Date timestamp; // private String type; // private String value; // }
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.regex.Pattern; import net.kulak.psy.data.schema.Payload;
package net.kulak.psy.semantic; public class RegexpInteractionAnalyzer extends InteractionAnalyzer { private List<Pattern> patternsPositive = new ArrayList<Pattern>(); private List<Pattern> patternsNegative = new ArrayList<Pattern>(); private List<Pattern> patternsExtremelyNegative = new ArrayList<Pattern>(); private void readPatterns(String resource, List<Pattern> target) throws IOException { BufferedReader br = null; try { br = new BufferedReader(new FileReader( getClass().getResource(resource).getFile() )); String pattern; while ((pattern = br.readLine()) != null) { target.add(Pattern.compile(pattern)); } } finally { if (br != null) { br.close(); } } } public RegexpInteractionAnalyzer() throws IOException { readPatterns("/net/kulak/psy/semantic/semantic-positive.txt", patternsPositive); readPatterns("/net/kulak/psy/semantic/semantic-negative.txt", patternsNegative); readPatterns("/net/kulak/psy/semantic/semantic-extremely-negative.txt", patternsExtremelyNegative); }
// Path: phpbb-parser/src/net/kulak/psy/data/schema/Payload.java // @XmlRootElement // public class Payload { // // @Override // public String toString() { // return "Payload [topicId=" + topicId + ", sequence=" // + sequence + ", timestamp=" // + TIMESTAMP_FORMAT.format(timestamp) + ", type=" + type // + ", value=" + value + "]"; // } // // public String getTopicId() { // return topicId; // } // // public void setTopicId(String topicId) { // this.topicId = topicId; // } // // public Integer getSequence() { // return sequence; // } // // public void setSequence(Integer sequence) { // this.sequence = sequence; // } // // public Date getTimestamp() { // return timestamp; // } // // public void setTimestamp(Date timestamp) { // this.timestamp = timestamp; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getValue() { // return value; // } // // public void setValue(String value) { // this.value = value; // } // // private final static DateFormat TIMESTAMP_FORMAT = SimpleDateFormat // .getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT); // // private String topicId; // private Integer sequence; // private Date timestamp; // private String type; // private String value; // } // Path: phpbb-parser/src/net/kulak/psy/semantic/RegexpInteractionAnalyzer.java import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.regex.Pattern; import net.kulak.psy.data.schema.Payload; package net.kulak.psy.semantic; public class RegexpInteractionAnalyzer extends InteractionAnalyzer { private List<Pattern> patternsPositive = new ArrayList<Pattern>(); private List<Pattern> patternsNegative = new ArrayList<Pattern>(); private List<Pattern> patternsExtremelyNegative = new ArrayList<Pattern>(); private void readPatterns(String resource, List<Pattern> target) throws IOException { BufferedReader br = null; try { br = new BufferedReader(new FileReader( getClass().getResource(resource).getFile() )); String pattern; while ((pattern = br.readLine()) != null) { target.add(Pattern.compile(pattern)); } } finally { if (br != null) { br.close(); } } } public RegexpInteractionAnalyzer() throws IOException { readPatterns("/net/kulak/psy/semantic/semantic-positive.txt", patternsPositive); readPatterns("/net/kulak/psy/semantic/semantic-negative.txt", patternsNegative); readPatterns("/net/kulak/psy/semantic/semantic-extremely-negative.txt", patternsExtremelyNegative); }
public Payload analyze(String text) {
co-stig/phpbb-crawler
phpbb-parser/src/net/kulak/psy/statistics/StatUsers.java
// Path: phpbb-parser/src/net/kulak/psy/data/schema/UserStatistic.java // @XmlRootElement // public class UserStatistic implements Comparable<UserStatistic> { // // private final static DateFormat TIMESTAMP_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); // // private String name; // private Date firstMessage; // private Date lastMessage; // private Integer count; // // @Override // public String toString() { // return "UserStatistic [name=" + name + ", firstMessage=" // + TIMESTAMP_FORMAT.format(firstMessage) + ", lastMessage=" // + TIMESTAMP_FORMAT.format(lastMessage) + ", count=" + count // + "]"; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Date getFirstMessage() { // return firstMessage; // } // // public String getFirstMessageAsString() { // return TIMESTAMP_FORMAT.format(firstMessage); // } // // public void setFirstMessage(Date firstMessage) { // this.firstMessage = firstMessage; // } // // public Date getLastMessage() { // return lastMessage; // } // // public String getLastMessageAsString() { // return TIMESTAMP_FORMAT.format(lastMessage); // } // // public void setLastMessage(Date lastMessage) { // this.lastMessage = lastMessage; // } // // public Integer getCount() { // return count; // } // // public void setCount(Integer count) { // this.count = count; // } // // @Override // public int compareTo(UserStatistic user) { // return name.compareTo(user.getName()); // } // // }
import java.io.IOException; import java.sql.SQLException; import net.kulak.psy.data.schema.UserStatistic;
package net.kulak.psy.statistics; /** * Users statistics. Will output a TSV with 4 columns: user name, first message * date in format yyyy-MM-dd, last message in format yyyy-MM-dd, total number of * messages wrote by this user. No header is included in output. */ public class StatUsers extends AbstractStatistics { public StatUsers(String[] args) throws Exception { super(args); } public static void main(String[] args) throws Exception { new StatUsers(args).run(); } public void run() throws SQLException, ClassNotFoundException, IOException {
// Path: phpbb-parser/src/net/kulak/psy/data/schema/UserStatistic.java // @XmlRootElement // public class UserStatistic implements Comparable<UserStatistic> { // // private final static DateFormat TIMESTAMP_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); // // private String name; // private Date firstMessage; // private Date lastMessage; // private Integer count; // // @Override // public String toString() { // return "UserStatistic [name=" + name + ", firstMessage=" // + TIMESTAMP_FORMAT.format(firstMessage) + ", lastMessage=" // + TIMESTAMP_FORMAT.format(lastMessage) + ", count=" + count // + "]"; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Date getFirstMessage() { // return firstMessage; // } // // public String getFirstMessageAsString() { // return TIMESTAMP_FORMAT.format(firstMessage); // } // // public void setFirstMessage(Date firstMessage) { // this.firstMessage = firstMessage; // } // // public Date getLastMessage() { // return lastMessage; // } // // public String getLastMessageAsString() { // return TIMESTAMP_FORMAT.format(lastMessage); // } // // public void setLastMessage(Date lastMessage) { // this.lastMessage = lastMessage; // } // // public Integer getCount() { // return count; // } // // public void setCount(Integer count) { // this.count = count; // } // // @Override // public int compareTo(UserStatistic user) { // return name.compareTo(user.getName()); // } // // } // Path: phpbb-parser/src/net/kulak/psy/statistics/StatUsers.java import java.io.IOException; import java.sql.SQLException; import net.kulak.psy.data.schema.UserStatistic; package net.kulak.psy.statistics; /** * Users statistics. Will output a TSV with 4 columns: user name, first message * date in format yyyy-MM-dd, last message in format yyyy-MM-dd, total number of * messages wrote by this user. No header is included in output. */ public class StatUsers extends AbstractStatistics { public StatUsers(String[] args) throws Exception { super(args); } public static void main(String[] args) throws Exception { new StatUsers(args).run(); } public void run() throws SQLException, ClassNotFoundException, IOException {
for (UserStatistic us: getDatabase().statUsers()) {
co-stig/phpbb-crawler
phpbb-parser/src/net/kulak/psy/semantic/InteractionAnalyzer.java
// Path: phpbb-parser/src/net/kulak/psy/data/schema/Payload.java // @XmlRootElement // public class Payload { // // @Override // public String toString() { // return "Payload [topicId=" + topicId + ", sequence=" // + sequence + ", timestamp=" // + TIMESTAMP_FORMAT.format(timestamp) + ", type=" + type // + ", value=" + value + "]"; // } // // public String getTopicId() { // return topicId; // } // // public void setTopicId(String topicId) { // this.topicId = topicId; // } // // public Integer getSequence() { // return sequence; // } // // public void setSequence(Integer sequence) { // this.sequence = sequence; // } // // public Date getTimestamp() { // return timestamp; // } // // public void setTimestamp(Date timestamp) { // this.timestamp = timestamp; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getValue() { // return value; // } // // public void setValue(String value) { // this.value = value; // } // // private final static DateFormat TIMESTAMP_FORMAT = SimpleDateFormat // .getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT); // // private String topicId; // private Integer sequence; // private Date timestamp; // private String type; // private String value; // }
import java.io.IOException; import net.kulak.psy.data.schema.Payload;
package net.kulak.psy.semantic; public abstract class InteractionAnalyzer { private static InteractionAnalyzer inst; public static InteractionAnalyzer getInstance(boolean dummy) throws IOException { if (inst == null) { if (dummy) { inst = new DummyRandomInteractionAnalyzer(); } else { inst = new PlainTextAnalyzer(new RegexpInteractionAnalyzer()); } } return inst; }
// Path: phpbb-parser/src/net/kulak/psy/data/schema/Payload.java // @XmlRootElement // public class Payload { // // @Override // public String toString() { // return "Payload [topicId=" + topicId + ", sequence=" // + sequence + ", timestamp=" // + TIMESTAMP_FORMAT.format(timestamp) + ", type=" + type // + ", value=" + value + "]"; // } // // public String getTopicId() { // return topicId; // } // // public void setTopicId(String topicId) { // this.topicId = topicId; // } // // public Integer getSequence() { // return sequence; // } // // public void setSequence(Integer sequence) { // this.sequence = sequence; // } // // public Date getTimestamp() { // return timestamp; // } // // public void setTimestamp(Date timestamp) { // this.timestamp = timestamp; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getValue() { // return value; // } // // public void setValue(String value) { // this.value = value; // } // // private final static DateFormat TIMESTAMP_FORMAT = SimpleDateFormat // .getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT); // // private String topicId; // private Integer sequence; // private Date timestamp; // private String type; // private String value; // } // Path: phpbb-parser/src/net/kulak/psy/semantic/InteractionAnalyzer.java import java.io.IOException; import net.kulak.psy.data.schema.Payload; package net.kulak.psy.semantic; public abstract class InteractionAnalyzer { private static InteractionAnalyzer inst; public static InteractionAnalyzer getInstance(boolean dummy) throws IOException { if (inst == null) { if (dummy) { inst = new DummyRandomInteractionAnalyzer(); } else { inst = new PlainTextAnalyzer(new RegexpInteractionAnalyzer()); } } return inst; }
public abstract Payload analyze (String text);
tomayac/rest-describe-and-compile
src/com/google/code/apis/rest/client/Tree/GenericClosingItem.java
// Path: src/com/google/code/apis/rest/client/Util/SyntaxHighlighter.java // public class SyntaxHighlighter { // public SyntaxHighlighter() { // return; // } // // public static String toHtml(String code) { // code = encodeEntities(code); // // // <openTag> // String regExp = "(&lt;\\??\\w+)(.*?)(\\??/?&gt;)"; // code = code.replaceAll(regExp, "<span class=\"tag\">$1</span>$2<span class=\"tag\">$3</span>\n<br />"); // // // attrib = "string" // regExp = "([a-zA-Z0-9_:]+\\s*=)(\\s*[&quot;a-zA-Z0-9_:#\\/\\.\\-\\s\\(\\)\\+]+&quot;|[&#39;a-zA-Z0-9_:#\\/\\.\\-\\s\\(\\)\\+]+&#39;)"; // code = code.replaceAll(regExp, "<span class=\"attribute\">$1</span><span class=\"string\">$2</span>"); // // // </closeTag> // regExp = "(&lt;/\\w+&gt;)"; // code = code.replaceAll(regExp, "<span class=\"tag\">$1</span>\n<br />"); // // return code; // } // // public static String encodeEntities(String code) { // code = code.replaceAll("'", "&#39;"); // code = code.replaceAll("\"", "&quot;"); // code = code.replaceAll("<", "&lt;"); // code = code.replaceAll(">", "&gt;"); // return code; // } // // public static String htmlifyLineBreaksAndTabs(String code, int tabWidth) { // code = encodeEntities(code); // code = code.replaceAll("\n", "<br />"); // String tab = ""; // for (int i = 0; i < tabWidth; i++) tab += "&nbsp;"; // code = code.replaceAll("\t", tab); // return code; // } // // public static String highlight(String code) { // code = encodeEntities(code); // // complete tag // String regExp = "(^&lt;/?.*?&gt;$)"; // code = code.replaceAll(regExp, "<span class=\"tag\">$1</span>"); // // // opening tag // regExp = "(^&lt;.*?\\s)"; // code = code.replaceAll(regExp, "<span class=\"tag\">$1</span><span class=\"attribute\">"); // // // closing tag // regExp = "(/?&gt;$)"; // code = code.replaceAll(regExp, "</span><span class=\"tag\">$1</span>"); // // // attribute strings // regExp = "(.*?)(&quot;(.*?&quot;)*)"; // code = code.replaceAll(regExp, "<span class=\"attribute\">$1</span><span class=\"string\">$2</span>"); // regExp = "(&#39;.*?&#39;)"; // code = code.replaceAll(regExp, "<span class=\"attribute\">$1</span><span class=\"string\">$2</span>"); // // // xml comments // regExp = "(&lt;!--?.*?--&gt;)"; // code = code.replaceAll(regExp, "<span class=\"comment\">$1</span>"); // // return code; // } // }
import com.google.code.apis.rest.client.Util.SyntaxHighlighter; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.HTML;
package com.google.code.apis.rest.client.Tree; public class GenericClosingItem extends Composite { public GenericClosingItem(String tagName) {
// Path: src/com/google/code/apis/rest/client/Util/SyntaxHighlighter.java // public class SyntaxHighlighter { // public SyntaxHighlighter() { // return; // } // // public static String toHtml(String code) { // code = encodeEntities(code); // // // <openTag> // String regExp = "(&lt;\\??\\w+)(.*?)(\\??/?&gt;)"; // code = code.replaceAll(regExp, "<span class=\"tag\">$1</span>$2<span class=\"tag\">$3</span>\n<br />"); // // // attrib = "string" // regExp = "([a-zA-Z0-9_:]+\\s*=)(\\s*[&quot;a-zA-Z0-9_:#\\/\\.\\-\\s\\(\\)\\+]+&quot;|[&#39;a-zA-Z0-9_:#\\/\\.\\-\\s\\(\\)\\+]+&#39;)"; // code = code.replaceAll(regExp, "<span class=\"attribute\">$1</span><span class=\"string\">$2</span>"); // // // </closeTag> // regExp = "(&lt;/\\w+&gt;)"; // code = code.replaceAll(regExp, "<span class=\"tag\">$1</span>\n<br />"); // // return code; // } // // public static String encodeEntities(String code) { // code = code.replaceAll("'", "&#39;"); // code = code.replaceAll("\"", "&quot;"); // code = code.replaceAll("<", "&lt;"); // code = code.replaceAll(">", "&gt;"); // return code; // } // // public static String htmlifyLineBreaksAndTabs(String code, int tabWidth) { // code = encodeEntities(code); // code = code.replaceAll("\n", "<br />"); // String tab = ""; // for (int i = 0; i < tabWidth; i++) tab += "&nbsp;"; // code = code.replaceAll("\t", tab); // return code; // } // // public static String highlight(String code) { // code = encodeEntities(code); // // complete tag // String regExp = "(^&lt;/?.*?&gt;$)"; // code = code.replaceAll(regExp, "<span class=\"tag\">$1</span>"); // // // opening tag // regExp = "(^&lt;.*?\\s)"; // code = code.replaceAll(regExp, "<span class=\"tag\">$1</span><span class=\"attribute\">"); // // // closing tag // regExp = "(/?&gt;$)"; // code = code.replaceAll(regExp, "</span><span class=\"tag\">$1</span>"); // // // attribute strings // regExp = "(.*?)(&quot;(.*?&quot;)*)"; // code = code.replaceAll(regExp, "<span class=\"attribute\">$1</span><span class=\"string\">$2</span>"); // regExp = "(&#39;.*?&#39;)"; // code = code.replaceAll(regExp, "<span class=\"attribute\">$1</span><span class=\"string\">$2</span>"); // // // xml comments // regExp = "(&lt;!--?.*?--&gt;)"; // code = code.replaceAll(regExp, "<span class=\"comment\">$1</span>"); // // return code; // } // } // Path: src/com/google/code/apis/rest/client/Tree/GenericClosingItem.java import com.google.code.apis.rest.client.Util.SyntaxHighlighter; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.HTML; package com.google.code.apis.rest.client.Tree; public class GenericClosingItem extends Composite { public GenericClosingItem(String tagName) {
HTML tag = new HTML(SyntaxHighlighter.highlight("</" + tagName + ">"));
threerings/game-gardens
toybox/src/main/java/com/threerings/toybox/data/ToyBoxMarshaller.java
// Path: toybox/src/main/java/com/threerings/toybox/client/ToyBoxService.java // public interface ToyBoxService extends InvocationService<ClientObject> // { // /** // * Issues a request for the oid of the lobby associated with the // * specified game. // */ // public void getLobbyOid (int gameId, ResultListener rl); // }
import javax.annotation.Generated; import com.threerings.presents.client.InvocationService; import com.threerings.presents.data.ClientObject; import com.threerings.presents.data.InvocationMarshaller; import com.threerings.toybox.client.ToyBoxService;
// // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.data; /** * Provides the implementation of the {@link ToyBoxService} interface * that marshalls the arguments and delivers the request to the provider * on the server. Also provides an implementation of the response listener * interfaces that marshall the response arguments and deliver them back * to the requesting client. */ @Generated(value={"com.threerings.presents.tools.GenServiceTask"}, comments="Derived from ToyBoxService.java.") public class ToyBoxMarshaller extends InvocationMarshaller<ClientObject>
// Path: toybox/src/main/java/com/threerings/toybox/client/ToyBoxService.java // public interface ToyBoxService extends InvocationService<ClientObject> // { // /** // * Issues a request for the oid of the lobby associated with the // * specified game. // */ // public void getLobbyOid (int gameId, ResultListener rl); // } // Path: toybox/src/main/java/com/threerings/toybox/data/ToyBoxMarshaller.java import javax.annotation.Generated; import com.threerings.presents.client.InvocationService; import com.threerings.presents.data.ClientObject; import com.threerings.presents.data.InvocationMarshaller; import com.threerings.toybox.client.ToyBoxService; // // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.data; /** * Provides the implementation of the {@link ToyBoxService} interface * that marshalls the arguments and delivers the request to the provider * on the server. Also provides an implementation of the response listener * interfaces that marshall the response arguments and deliver them back * to the requesting client. */ @Generated(value={"com.threerings.presents.tools.GenServiceTask"}, comments="Derived from ToyBoxService.java.") public class ToyBoxMarshaller extends InvocationMarshaller<ClientObject>
implements ToyBoxService
threerings/game-gardens
client/src/main/java/com/threerings/gardens/client/GardensEntryPoint.java
// Path: core/src/main/java/com/threerings/gardens/distrib/GardensSerializer.java // public class GardensSerializer extends AbstractSerializer { // // public GardensSerializer () { // mapStreamer(new Streamer_GameConfig()); // mapStreamer(new Streamer_LobbyObject()); // mapStreamer(new Streamer_LobbyObject.Table()); // mapStreamer(new Streamer_LobbyObject.Game()); // mapStreamer(new Streamer_LobbyObject.Seat()); // mapStreamer(new Streamer_UserObject()); // mapStreamer(new Streamer_ChatMessage()); // mapService(new Factory_LobbyService(), LobbyService.class); // mapService(new Factory_UserService(), UserService.class); // } // }
import com.google.gwt.core.client.EntryPoint; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Style; import com.google.gwt.user.client.Cookies; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.Widget; import com.threerings.nexus.client.GWTClient; import com.threerings.nexus.client.NexusClient; import com.threerings.gardens.distrib.GardensSerializer;
// // Game Gardens - a platform for hosting simple multiplayer Java games // Copyright (c) 2005-2013, Three Rings Design, Inc. - All rights reserved. // https://github.com/threerings/game-gardens/blob/master/LICENSE package com.threerings.gardens.client; /** * The main entry point for the GWT/HTML5 client. */ public class GardensEntryPoint implements EntryPoint { @Override public void onModuleLoad () { ClientContext ctx = new ClientContext() { public NexusClient client () { return _client; } public String authToken () { return Cookies.getCookie("id_"); } public void setMainPanel (Widget main) { if (_main != null) { RootPanel.get(CLIENT_DIV).remove(_main); } RootPanel.get(CLIENT_DIV).add(_main = main); } protected NexusClient _client = GWTClient.create( 8080, /* TODO: get from deployment.properties */
// Path: core/src/main/java/com/threerings/gardens/distrib/GardensSerializer.java // public class GardensSerializer extends AbstractSerializer { // // public GardensSerializer () { // mapStreamer(new Streamer_GameConfig()); // mapStreamer(new Streamer_LobbyObject()); // mapStreamer(new Streamer_LobbyObject.Table()); // mapStreamer(new Streamer_LobbyObject.Game()); // mapStreamer(new Streamer_LobbyObject.Seat()); // mapStreamer(new Streamer_UserObject()); // mapStreamer(new Streamer_ChatMessage()); // mapService(new Factory_LobbyService(), LobbyService.class); // mapService(new Factory_UserService(), UserService.class); // } // } // Path: client/src/main/java/com/threerings/gardens/client/GardensEntryPoint.java import com.google.gwt.core.client.EntryPoint; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Style; import com.google.gwt.user.client.Cookies; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.Widget; import com.threerings.nexus.client.GWTClient; import com.threerings.nexus.client.NexusClient; import com.threerings.gardens.distrib.GardensSerializer; // // Game Gardens - a platform for hosting simple multiplayer Java games // Copyright (c) 2005-2013, Three Rings Design, Inc. - All rights reserved. // https://github.com/threerings/game-gardens/blob/master/LICENSE package com.threerings.gardens.client; /** * The main entry point for the GWT/HTML5 client. */ public class GardensEntryPoint implements EntryPoint { @Override public void onModuleLoad () { ClientContext ctx = new ClientContext() { public NexusClient client () { return _client; } public String authToken () { return Cookies.getCookie("id_"); } public void setMainPanel (Widget main) { if (_main != null) { RootPanel.get(CLIENT_DIV).remove(_main); } RootPanel.get(CLIENT_DIV).add(_main = main); } protected NexusClient _client = GWTClient.create( 8080, /* TODO: get from deployment.properties */
new GardensSerializer());
threerings/game-gardens
toybox/src/main/java/com/threerings/toybox/lobby/client/LobbyController.java
// Path: toybox/src/main/java/com/threerings/toybox/lobby/data/LobbyConfig.java // public class LobbyConfig extends PlaceConfig // { // /** // * A default constructor used when unserializing. // */ // public LobbyConfig () // { // } // // /** // * Creates the config for a new lobby that will match-make games with // * the specified configuration. // */ // public LobbyConfig (int gameId, GameDefinition gamedef) // { // _gameId = gameId; // _gamedef = gamedef; // } // // // documentation inherited // @Override // public PlaceController createController () // { // return new LobbyController(); // } // // // documentation inherited // @Override // public String getManagerClassName () // { // return "com.threerings.toybox.lobby.server.LobbyManager"; // } // // /** // * Returns this game's unique identifier. // */ // public int getGameId () // { // return _gameId; // } // // /** // * Returns the definition of the game we're matchmaking in this lobby. // */ // public GameDefinition getGameDefinition () // { // return _gamedef; // } // // // documentation inherited // @Override // protected void toString (StringBuilder buf) // { // super.toString(buf); // if (buf.length() > 1) { // buf.append(", "); // } // buf.append("gamedef=").append(_gamedef); // } // // /** The unique id for the game we'll be matchmaking. */ // protected int _gameId; // // /** The definition for the game we'll be matchmaking. */ // protected GameDefinition _gamedef; // } // // Path: toybox/src/main/java/com/threerings/toybox/util/ToyBoxContext.java // public abstract class ToyBoxContext implements ParlorContext // { // /** // * Returns a reference to the message manager used by the client to // * generate localized messages. // */ // public abstract MessageManager getMessageManager (); // // /** // * Returns a reference to our ToyBox director. // */ // public abstract ToyBoxDirector getToyBoxDirector (); // // /** // * Returns a reference to our frame manager (used for media services). // */ // public abstract FrameManager getFrameManager (); // // /** // * Returns a reference to our key dispatcher. // */ // public abstract KeyDispatcher getKeyDispatcher (); // // /** // * Returns the resource manager which is used to load media resources. // */ // public ResourceManager getResourceManager () // { // return getToyBoxDirector().getResourceManager(); // } // // /** // * Translates the specified message using the specified message bundle. // */ // public String xlate (String bundle, String message) // { // MessageBundle mb = getMessageManager().getBundle(bundle); // return (mb == null) ? message : mb.xlate(message); // } // // /** // * Convenience method to get the username of the currently logged on // * user. Returns null when we're not logged on. // */ // public Name getUsername () // { // BodyObject bobj = (BodyObject)getClient().getClientObject(); // return (bobj == null) ? null : bobj.getVisibleName(); // } // // /** // * Convenience method to load an image from our resource bundles. // */ // public BufferedImage loadImage (String rsrcPath) // { // try { // return getResourceManager().getImageResource(rsrcPath); // } catch (IOException ioe) { // log.warning("Unable to load image resource [path=" + rsrcPath + "].", ioe); // // cope; return an error image of abitrary size // return ImageUtil.createErrorImage(50, 50); // } // } // } // // Path: toybox/src/main/java/com/threerings/toybox/lobby/Log.java // public static Logger log = Logger.getLogger("com.threerings.toybox.lobby");
import static com.threerings.toybox.lobby.Log.log; import com.threerings.getdown.data.Resource; import com.threerings.getdown.net.Downloader; import com.threerings.crowd.client.PlaceController; import com.threerings.crowd.client.PlaceView; import com.threerings.crowd.data.PlaceConfig; import com.threerings.crowd.data.PlaceObject; import com.threerings.crowd.util.CrowdContext; import com.threerings.toybox.lobby.data.LobbyConfig; import com.threerings.toybox.util.ToyBoxContext;
// // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.lobby.client; /** * Handles the client side of the ToyBox match-making interface. */ public class LobbyController extends PlaceController { // documentation inherited @Override public void init (CrowdContext ctx, PlaceConfig config) { super.init(ctx, config); // cast our references
// Path: toybox/src/main/java/com/threerings/toybox/lobby/data/LobbyConfig.java // public class LobbyConfig extends PlaceConfig // { // /** // * A default constructor used when unserializing. // */ // public LobbyConfig () // { // } // // /** // * Creates the config for a new lobby that will match-make games with // * the specified configuration. // */ // public LobbyConfig (int gameId, GameDefinition gamedef) // { // _gameId = gameId; // _gamedef = gamedef; // } // // // documentation inherited // @Override // public PlaceController createController () // { // return new LobbyController(); // } // // // documentation inherited // @Override // public String getManagerClassName () // { // return "com.threerings.toybox.lobby.server.LobbyManager"; // } // // /** // * Returns this game's unique identifier. // */ // public int getGameId () // { // return _gameId; // } // // /** // * Returns the definition of the game we're matchmaking in this lobby. // */ // public GameDefinition getGameDefinition () // { // return _gamedef; // } // // // documentation inherited // @Override // protected void toString (StringBuilder buf) // { // super.toString(buf); // if (buf.length() > 1) { // buf.append(", "); // } // buf.append("gamedef=").append(_gamedef); // } // // /** The unique id for the game we'll be matchmaking. */ // protected int _gameId; // // /** The definition for the game we'll be matchmaking. */ // protected GameDefinition _gamedef; // } // // Path: toybox/src/main/java/com/threerings/toybox/util/ToyBoxContext.java // public abstract class ToyBoxContext implements ParlorContext // { // /** // * Returns a reference to the message manager used by the client to // * generate localized messages. // */ // public abstract MessageManager getMessageManager (); // // /** // * Returns a reference to our ToyBox director. // */ // public abstract ToyBoxDirector getToyBoxDirector (); // // /** // * Returns a reference to our frame manager (used for media services). // */ // public abstract FrameManager getFrameManager (); // // /** // * Returns a reference to our key dispatcher. // */ // public abstract KeyDispatcher getKeyDispatcher (); // // /** // * Returns the resource manager which is used to load media resources. // */ // public ResourceManager getResourceManager () // { // return getToyBoxDirector().getResourceManager(); // } // // /** // * Translates the specified message using the specified message bundle. // */ // public String xlate (String bundle, String message) // { // MessageBundle mb = getMessageManager().getBundle(bundle); // return (mb == null) ? message : mb.xlate(message); // } // // /** // * Convenience method to get the username of the currently logged on // * user. Returns null when we're not logged on. // */ // public Name getUsername () // { // BodyObject bobj = (BodyObject)getClient().getClientObject(); // return (bobj == null) ? null : bobj.getVisibleName(); // } // // /** // * Convenience method to load an image from our resource bundles. // */ // public BufferedImage loadImage (String rsrcPath) // { // try { // return getResourceManager().getImageResource(rsrcPath); // } catch (IOException ioe) { // log.warning("Unable to load image resource [path=" + rsrcPath + "].", ioe); // // cope; return an error image of abitrary size // return ImageUtil.createErrorImage(50, 50); // } // } // } // // Path: toybox/src/main/java/com/threerings/toybox/lobby/Log.java // public static Logger log = Logger.getLogger("com.threerings.toybox.lobby"); // Path: toybox/src/main/java/com/threerings/toybox/lobby/client/LobbyController.java import static com.threerings.toybox.lobby.Log.log; import com.threerings.getdown.data.Resource; import com.threerings.getdown.net.Downloader; import com.threerings.crowd.client.PlaceController; import com.threerings.crowd.client.PlaceView; import com.threerings.crowd.data.PlaceConfig; import com.threerings.crowd.data.PlaceObject; import com.threerings.crowd.util.CrowdContext; import com.threerings.toybox.lobby.data.LobbyConfig; import com.threerings.toybox.util.ToyBoxContext; // // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.lobby.client; /** * Handles the client side of the ToyBox match-making interface. */ public class LobbyController extends PlaceController { // documentation inherited @Override public void init (CrowdContext ctx, PlaceConfig config) { super.init(ctx, config); // cast our references
_ctx = (ToyBoxContext)ctx;
threerings/game-gardens
toybox/src/main/java/com/threerings/toybox/lobby/client/LobbyController.java
// Path: toybox/src/main/java/com/threerings/toybox/lobby/data/LobbyConfig.java // public class LobbyConfig extends PlaceConfig // { // /** // * A default constructor used when unserializing. // */ // public LobbyConfig () // { // } // // /** // * Creates the config for a new lobby that will match-make games with // * the specified configuration. // */ // public LobbyConfig (int gameId, GameDefinition gamedef) // { // _gameId = gameId; // _gamedef = gamedef; // } // // // documentation inherited // @Override // public PlaceController createController () // { // return new LobbyController(); // } // // // documentation inherited // @Override // public String getManagerClassName () // { // return "com.threerings.toybox.lobby.server.LobbyManager"; // } // // /** // * Returns this game's unique identifier. // */ // public int getGameId () // { // return _gameId; // } // // /** // * Returns the definition of the game we're matchmaking in this lobby. // */ // public GameDefinition getGameDefinition () // { // return _gamedef; // } // // // documentation inherited // @Override // protected void toString (StringBuilder buf) // { // super.toString(buf); // if (buf.length() > 1) { // buf.append(", "); // } // buf.append("gamedef=").append(_gamedef); // } // // /** The unique id for the game we'll be matchmaking. */ // protected int _gameId; // // /** The definition for the game we'll be matchmaking. */ // protected GameDefinition _gamedef; // } // // Path: toybox/src/main/java/com/threerings/toybox/util/ToyBoxContext.java // public abstract class ToyBoxContext implements ParlorContext // { // /** // * Returns a reference to the message manager used by the client to // * generate localized messages. // */ // public abstract MessageManager getMessageManager (); // // /** // * Returns a reference to our ToyBox director. // */ // public abstract ToyBoxDirector getToyBoxDirector (); // // /** // * Returns a reference to our frame manager (used for media services). // */ // public abstract FrameManager getFrameManager (); // // /** // * Returns a reference to our key dispatcher. // */ // public abstract KeyDispatcher getKeyDispatcher (); // // /** // * Returns the resource manager which is used to load media resources. // */ // public ResourceManager getResourceManager () // { // return getToyBoxDirector().getResourceManager(); // } // // /** // * Translates the specified message using the specified message bundle. // */ // public String xlate (String bundle, String message) // { // MessageBundle mb = getMessageManager().getBundle(bundle); // return (mb == null) ? message : mb.xlate(message); // } // // /** // * Convenience method to get the username of the currently logged on // * user. Returns null when we're not logged on. // */ // public Name getUsername () // { // BodyObject bobj = (BodyObject)getClient().getClientObject(); // return (bobj == null) ? null : bobj.getVisibleName(); // } // // /** // * Convenience method to load an image from our resource bundles. // */ // public BufferedImage loadImage (String rsrcPath) // { // try { // return getResourceManager().getImageResource(rsrcPath); // } catch (IOException ioe) { // log.warning("Unable to load image resource [path=" + rsrcPath + "].", ioe); // // cope; return an error image of abitrary size // return ImageUtil.createErrorImage(50, 50); // } // } // } // // Path: toybox/src/main/java/com/threerings/toybox/lobby/Log.java // public static Logger log = Logger.getLogger("com.threerings.toybox.lobby");
import static com.threerings.toybox.lobby.Log.log; import com.threerings.getdown.data.Resource; import com.threerings.getdown.net.Downloader; import com.threerings.crowd.client.PlaceController; import com.threerings.crowd.client.PlaceView; import com.threerings.crowd.data.PlaceConfig; import com.threerings.crowd.data.PlaceObject; import com.threerings.crowd.util.CrowdContext; import com.threerings.toybox.lobby.data.LobbyConfig; import com.threerings.toybox.util.ToyBoxContext;
// // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.lobby.client; /** * Handles the client side of the ToyBox match-making interface. */ public class LobbyController extends PlaceController { // documentation inherited @Override public void init (CrowdContext ctx, PlaceConfig config) { super.init(ctx, config); // cast our references _ctx = (ToyBoxContext)ctx;
// Path: toybox/src/main/java/com/threerings/toybox/lobby/data/LobbyConfig.java // public class LobbyConfig extends PlaceConfig // { // /** // * A default constructor used when unserializing. // */ // public LobbyConfig () // { // } // // /** // * Creates the config for a new lobby that will match-make games with // * the specified configuration. // */ // public LobbyConfig (int gameId, GameDefinition gamedef) // { // _gameId = gameId; // _gamedef = gamedef; // } // // // documentation inherited // @Override // public PlaceController createController () // { // return new LobbyController(); // } // // // documentation inherited // @Override // public String getManagerClassName () // { // return "com.threerings.toybox.lobby.server.LobbyManager"; // } // // /** // * Returns this game's unique identifier. // */ // public int getGameId () // { // return _gameId; // } // // /** // * Returns the definition of the game we're matchmaking in this lobby. // */ // public GameDefinition getGameDefinition () // { // return _gamedef; // } // // // documentation inherited // @Override // protected void toString (StringBuilder buf) // { // super.toString(buf); // if (buf.length() > 1) { // buf.append(", "); // } // buf.append("gamedef=").append(_gamedef); // } // // /** The unique id for the game we'll be matchmaking. */ // protected int _gameId; // // /** The definition for the game we'll be matchmaking. */ // protected GameDefinition _gamedef; // } // // Path: toybox/src/main/java/com/threerings/toybox/util/ToyBoxContext.java // public abstract class ToyBoxContext implements ParlorContext // { // /** // * Returns a reference to the message manager used by the client to // * generate localized messages. // */ // public abstract MessageManager getMessageManager (); // // /** // * Returns a reference to our ToyBox director. // */ // public abstract ToyBoxDirector getToyBoxDirector (); // // /** // * Returns a reference to our frame manager (used for media services). // */ // public abstract FrameManager getFrameManager (); // // /** // * Returns a reference to our key dispatcher. // */ // public abstract KeyDispatcher getKeyDispatcher (); // // /** // * Returns the resource manager which is used to load media resources. // */ // public ResourceManager getResourceManager () // { // return getToyBoxDirector().getResourceManager(); // } // // /** // * Translates the specified message using the specified message bundle. // */ // public String xlate (String bundle, String message) // { // MessageBundle mb = getMessageManager().getBundle(bundle); // return (mb == null) ? message : mb.xlate(message); // } // // /** // * Convenience method to get the username of the currently logged on // * user. Returns null when we're not logged on. // */ // public Name getUsername () // { // BodyObject bobj = (BodyObject)getClient().getClientObject(); // return (bobj == null) ? null : bobj.getVisibleName(); // } // // /** // * Convenience method to load an image from our resource bundles. // */ // public BufferedImage loadImage (String rsrcPath) // { // try { // return getResourceManager().getImageResource(rsrcPath); // } catch (IOException ioe) { // log.warning("Unable to load image resource [path=" + rsrcPath + "].", ioe); // // cope; return an error image of abitrary size // return ImageUtil.createErrorImage(50, 50); // } // } // } // // Path: toybox/src/main/java/com/threerings/toybox/lobby/Log.java // public static Logger log = Logger.getLogger("com.threerings.toybox.lobby"); // Path: toybox/src/main/java/com/threerings/toybox/lobby/client/LobbyController.java import static com.threerings.toybox.lobby.Log.log; import com.threerings.getdown.data.Resource; import com.threerings.getdown.net.Downloader; import com.threerings.crowd.client.PlaceController; import com.threerings.crowd.client.PlaceView; import com.threerings.crowd.data.PlaceConfig; import com.threerings.crowd.data.PlaceObject; import com.threerings.crowd.util.CrowdContext; import com.threerings.toybox.lobby.data.LobbyConfig; import com.threerings.toybox.util.ToyBoxContext; // // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.lobby.client; /** * Handles the client side of the ToyBox match-making interface. */ public class LobbyController extends PlaceController { // documentation inherited @Override public void init (CrowdContext ctx, PlaceConfig config) { super.init(ctx, config); // cast our references _ctx = (ToyBoxContext)ctx;
_config = (LobbyConfig)config;
threerings/game-gardens
toybox/src/main/java/com/threerings/toybox/lobby/client/LobbyController.java
// Path: toybox/src/main/java/com/threerings/toybox/lobby/data/LobbyConfig.java // public class LobbyConfig extends PlaceConfig // { // /** // * A default constructor used when unserializing. // */ // public LobbyConfig () // { // } // // /** // * Creates the config for a new lobby that will match-make games with // * the specified configuration. // */ // public LobbyConfig (int gameId, GameDefinition gamedef) // { // _gameId = gameId; // _gamedef = gamedef; // } // // // documentation inherited // @Override // public PlaceController createController () // { // return new LobbyController(); // } // // // documentation inherited // @Override // public String getManagerClassName () // { // return "com.threerings.toybox.lobby.server.LobbyManager"; // } // // /** // * Returns this game's unique identifier. // */ // public int getGameId () // { // return _gameId; // } // // /** // * Returns the definition of the game we're matchmaking in this lobby. // */ // public GameDefinition getGameDefinition () // { // return _gamedef; // } // // // documentation inherited // @Override // protected void toString (StringBuilder buf) // { // super.toString(buf); // if (buf.length() > 1) { // buf.append(", "); // } // buf.append("gamedef=").append(_gamedef); // } // // /** The unique id for the game we'll be matchmaking. */ // protected int _gameId; // // /** The definition for the game we'll be matchmaking. */ // protected GameDefinition _gamedef; // } // // Path: toybox/src/main/java/com/threerings/toybox/util/ToyBoxContext.java // public abstract class ToyBoxContext implements ParlorContext // { // /** // * Returns a reference to the message manager used by the client to // * generate localized messages. // */ // public abstract MessageManager getMessageManager (); // // /** // * Returns a reference to our ToyBox director. // */ // public abstract ToyBoxDirector getToyBoxDirector (); // // /** // * Returns a reference to our frame manager (used for media services). // */ // public abstract FrameManager getFrameManager (); // // /** // * Returns a reference to our key dispatcher. // */ // public abstract KeyDispatcher getKeyDispatcher (); // // /** // * Returns the resource manager which is used to load media resources. // */ // public ResourceManager getResourceManager () // { // return getToyBoxDirector().getResourceManager(); // } // // /** // * Translates the specified message using the specified message bundle. // */ // public String xlate (String bundle, String message) // { // MessageBundle mb = getMessageManager().getBundle(bundle); // return (mb == null) ? message : mb.xlate(message); // } // // /** // * Convenience method to get the username of the currently logged on // * user. Returns null when we're not logged on. // */ // public Name getUsername () // { // BodyObject bobj = (BodyObject)getClient().getClientObject(); // return (bobj == null) ? null : bobj.getVisibleName(); // } // // /** // * Convenience method to load an image from our resource bundles. // */ // public BufferedImage loadImage (String rsrcPath) // { // try { // return getResourceManager().getImageResource(rsrcPath); // } catch (IOException ioe) { // log.warning("Unable to load image resource [path=" + rsrcPath + "].", ioe); // // cope; return an error image of abitrary size // return ImageUtil.createErrorImage(50, 50); // } // } // } // // Path: toybox/src/main/java/com/threerings/toybox/lobby/Log.java // public static Logger log = Logger.getLogger("com.threerings.toybox.lobby");
import static com.threerings.toybox.lobby.Log.log; import com.threerings.getdown.data.Resource; import com.threerings.getdown.net.Downloader; import com.threerings.crowd.client.PlaceController; import com.threerings.crowd.client.PlaceView; import com.threerings.crowd.data.PlaceConfig; import com.threerings.crowd.data.PlaceObject; import com.threerings.crowd.util.CrowdContext; import com.threerings.toybox.lobby.data.LobbyConfig; import com.threerings.toybox.util.ToyBoxContext;
// // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.lobby.client; /** * Handles the client side of the ToyBox match-making interface. */ public class LobbyController extends PlaceController { // documentation inherited @Override public void init (CrowdContext ctx, PlaceConfig config) { super.init(ctx, config); // cast our references _ctx = (ToyBoxContext)ctx; _config = (LobbyConfig)config; } // documentation inherited @Override public void willEnterPlace (PlaceObject plobj) { super.willEnterPlace(plobj); // let the toybox director know that we're in _ctx.getToyBoxDirector().enteredLobby(_config); // TODO: hold off on creating the match making interface until the // resources are downloaded (indeed show the download progress in // that same location) // have the toybox director download this game's jar files Downloader.Observer obs = new Downloader.Observer() { public void resolvingDownloads () {
// Path: toybox/src/main/java/com/threerings/toybox/lobby/data/LobbyConfig.java // public class LobbyConfig extends PlaceConfig // { // /** // * A default constructor used when unserializing. // */ // public LobbyConfig () // { // } // // /** // * Creates the config for a new lobby that will match-make games with // * the specified configuration. // */ // public LobbyConfig (int gameId, GameDefinition gamedef) // { // _gameId = gameId; // _gamedef = gamedef; // } // // // documentation inherited // @Override // public PlaceController createController () // { // return new LobbyController(); // } // // // documentation inherited // @Override // public String getManagerClassName () // { // return "com.threerings.toybox.lobby.server.LobbyManager"; // } // // /** // * Returns this game's unique identifier. // */ // public int getGameId () // { // return _gameId; // } // // /** // * Returns the definition of the game we're matchmaking in this lobby. // */ // public GameDefinition getGameDefinition () // { // return _gamedef; // } // // // documentation inherited // @Override // protected void toString (StringBuilder buf) // { // super.toString(buf); // if (buf.length() > 1) { // buf.append(", "); // } // buf.append("gamedef=").append(_gamedef); // } // // /** The unique id for the game we'll be matchmaking. */ // protected int _gameId; // // /** The definition for the game we'll be matchmaking. */ // protected GameDefinition _gamedef; // } // // Path: toybox/src/main/java/com/threerings/toybox/util/ToyBoxContext.java // public abstract class ToyBoxContext implements ParlorContext // { // /** // * Returns a reference to the message manager used by the client to // * generate localized messages. // */ // public abstract MessageManager getMessageManager (); // // /** // * Returns a reference to our ToyBox director. // */ // public abstract ToyBoxDirector getToyBoxDirector (); // // /** // * Returns a reference to our frame manager (used for media services). // */ // public abstract FrameManager getFrameManager (); // // /** // * Returns a reference to our key dispatcher. // */ // public abstract KeyDispatcher getKeyDispatcher (); // // /** // * Returns the resource manager which is used to load media resources. // */ // public ResourceManager getResourceManager () // { // return getToyBoxDirector().getResourceManager(); // } // // /** // * Translates the specified message using the specified message bundle. // */ // public String xlate (String bundle, String message) // { // MessageBundle mb = getMessageManager().getBundle(bundle); // return (mb == null) ? message : mb.xlate(message); // } // // /** // * Convenience method to get the username of the currently logged on // * user. Returns null when we're not logged on. // */ // public Name getUsername () // { // BodyObject bobj = (BodyObject)getClient().getClientObject(); // return (bobj == null) ? null : bobj.getVisibleName(); // } // // /** // * Convenience method to load an image from our resource bundles. // */ // public BufferedImage loadImage (String rsrcPath) // { // try { // return getResourceManager().getImageResource(rsrcPath); // } catch (IOException ioe) { // log.warning("Unable to load image resource [path=" + rsrcPath + "].", ioe); // // cope; return an error image of abitrary size // return ImageUtil.createErrorImage(50, 50); // } // } // } // // Path: toybox/src/main/java/com/threerings/toybox/lobby/Log.java // public static Logger log = Logger.getLogger("com.threerings.toybox.lobby"); // Path: toybox/src/main/java/com/threerings/toybox/lobby/client/LobbyController.java import static com.threerings.toybox.lobby.Log.log; import com.threerings.getdown.data.Resource; import com.threerings.getdown.net.Downloader; import com.threerings.crowd.client.PlaceController; import com.threerings.crowd.client.PlaceView; import com.threerings.crowd.data.PlaceConfig; import com.threerings.crowd.data.PlaceObject; import com.threerings.crowd.util.CrowdContext; import com.threerings.toybox.lobby.data.LobbyConfig; import com.threerings.toybox.util.ToyBoxContext; // // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.lobby.client; /** * Handles the client side of the ToyBox match-making interface. */ public class LobbyController extends PlaceController { // documentation inherited @Override public void init (CrowdContext ctx, PlaceConfig config) { super.init(ctx, config); // cast our references _ctx = (ToyBoxContext)ctx; _config = (LobbyConfig)config; } // documentation inherited @Override public void willEnterPlace (PlaceObject plobj) { super.willEnterPlace(plobj); // let the toybox director know that we're in _ctx.getToyBoxDirector().enteredLobby(_config); // TODO: hold off on creating the match making interface until the // resources are downloaded (indeed show the download progress in // that same location) // have the toybox director download this game's jar files Downloader.Observer obs = new Downloader.Observer() { public void resolvingDownloads () {
log.info("Resolving downloads...");
threerings/game-gardens
toybox/src/main/java/com/threerings/toybox/server/ToyBoxServer.java
// Path: toybox/src/main/java/com/threerings/toybox/Log.java // public static Logger log = Logger.getLogger("com.threerings.toybox");
import java.io.File; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Singleton; import com.samskivert.depot.PersistenceContext; import com.samskivert.jdbc.ConnectionProvider; import com.samskivert.jdbc.StaticConnectionProvider; import com.samskivert.util.Config; import com.samskivert.util.Lifecycle; import com.samskivert.util.StringUtil; import com.threerings.util.Name; import com.threerings.presents.net.AuthRequest; import com.threerings.presents.server.Authenticator; import com.threerings.presents.server.ClientResolver; import com.threerings.presents.server.DummyAuthenticator; import com.threerings.presents.server.PresentsSession; import com.threerings.presents.server.SessionFactory; import com.threerings.crowd.data.PlaceConfig; import com.threerings.crowd.server.CrowdServer; import com.threerings.crowd.server.PlaceManager; import com.threerings.crowd.server.PlaceRegistry; import com.threerings.parlor.server.ParlorManager; import static com.threerings.toybox.Log.log;
// // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.server; /** * The main entry point and general organizer of everything that goes on * in the ToyBox game server process. */ public class ToyBoxServer extends CrowdServer { /** Configures dependencies needed by the ToyBox services. */ public static class ToyBoxModule extends CrowdServer.CrowdModule { @Override protected void configure () { super.configure(); bind(PlaceRegistry.class).to(ToyBoxPlaceRegistry.class); bind(ToyBoxConfig.class).toInstance(config()); bind(Authenticator.class).to(autherClass()); bind(ConnectionProvider.class).toInstance(conprov()); bind(PersistenceContext.class).toInstance(new PersistenceContext()); } protected ToyBoxConfig config () { return new ToyBoxConfig(new Config(ToyBoxConfig.testConfig())); } protected ConnectionProvider conprov () { return StaticConnectionProvider.forTest("gardens"); } protected Class<? extends Authenticator> autherClass () { return DummyAuthenticator.class; } } /** * Runs a ToyBox server in test configuration. */ public static void main (String[] args) { runServer(new ToyBoxModule(), new PresentsServerModule(ToyBoxServer.class)); } @Override // from CrowdServer public void init (Injector injector) throws Exception { super.init(injector); // configure the client manager to use the appropriate client class _clmgr.setDefaultSessionFactory(new SessionFactory() { @Override public Class<? extends PresentsSession> getSessionClass (AuthRequest areq) { return ToyBoxSession.class; } @Override public Class<? extends ClientResolver> getClientResolverClass (Name username) { return ToyBoxClientResolver.class; } }); // initialize our persistence context ConnectionProvider conprov = injector.getInstance(ConnectionProvider.class); injector.getInstance(PersistenceContext.class).init("gamedb", conprov, null); // pctx.initializeRepositories(true); // determine whether we've been run in test mode with a single game configuration String gconfig = System.getProperty("game_conf"); if (!StringUtil.isBlank(gconfig)) { _toymgr.setDevelopmentMode(new File(gconfig)); }
// Path: toybox/src/main/java/com/threerings/toybox/Log.java // public static Logger log = Logger.getLogger("com.threerings.toybox"); // Path: toybox/src/main/java/com/threerings/toybox/server/ToyBoxServer.java import java.io.File; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Singleton; import com.samskivert.depot.PersistenceContext; import com.samskivert.jdbc.ConnectionProvider; import com.samskivert.jdbc.StaticConnectionProvider; import com.samskivert.util.Config; import com.samskivert.util.Lifecycle; import com.samskivert.util.StringUtil; import com.threerings.util.Name; import com.threerings.presents.net.AuthRequest; import com.threerings.presents.server.Authenticator; import com.threerings.presents.server.ClientResolver; import com.threerings.presents.server.DummyAuthenticator; import com.threerings.presents.server.PresentsSession; import com.threerings.presents.server.SessionFactory; import com.threerings.crowd.data.PlaceConfig; import com.threerings.crowd.server.CrowdServer; import com.threerings.crowd.server.PlaceManager; import com.threerings.crowd.server.PlaceRegistry; import com.threerings.parlor.server.ParlorManager; import static com.threerings.toybox.Log.log; // // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.server; /** * The main entry point and general organizer of everything that goes on * in the ToyBox game server process. */ public class ToyBoxServer extends CrowdServer { /** Configures dependencies needed by the ToyBox services. */ public static class ToyBoxModule extends CrowdServer.CrowdModule { @Override protected void configure () { super.configure(); bind(PlaceRegistry.class).to(ToyBoxPlaceRegistry.class); bind(ToyBoxConfig.class).toInstance(config()); bind(Authenticator.class).to(autherClass()); bind(ConnectionProvider.class).toInstance(conprov()); bind(PersistenceContext.class).toInstance(new PersistenceContext()); } protected ToyBoxConfig config () { return new ToyBoxConfig(new Config(ToyBoxConfig.testConfig())); } protected ConnectionProvider conprov () { return StaticConnectionProvider.forTest("gardens"); } protected Class<? extends Authenticator> autherClass () { return DummyAuthenticator.class; } } /** * Runs a ToyBox server in test configuration. */ public static void main (String[] args) { runServer(new ToyBoxModule(), new PresentsServerModule(ToyBoxServer.class)); } @Override // from CrowdServer public void init (Injector injector) throws Exception { super.init(injector); // configure the client manager to use the appropriate client class _clmgr.setDefaultSessionFactory(new SessionFactory() { @Override public Class<? extends PresentsSession> getSessionClass (AuthRequest areq) { return ToyBoxSession.class; } @Override public Class<? extends ClientResolver> getClientResolverClass (Name username) { return ToyBoxClientResolver.class; } }); // initialize our persistence context ConnectionProvider conprov = injector.getInstance(ConnectionProvider.class); injector.getInstance(PersistenceContext.class).init("gamedb", conprov, null); // pctx.initializeRepositories(true); // determine whether we've been run in test mode with a single game configuration String gconfig = System.getProperty("game_conf"); if (!StringUtil.isBlank(gconfig)) { _toymgr.setDevelopmentMode(new File(gconfig)); }
log.info("ToyBox server initialized.");
threerings/game-gardens
toybox/src/main/java/com/threerings/toybox/server/ToyBoxConfig.java
// Path: toybox/src/main/java/com/threerings/toybox/Log.java // public static Logger log = Logger.getLogger("com.threerings.toybox");
import java.io.File; import java.util.Properties; import com.google.inject.Singleton; import com.samskivert.util.Config; import com.samskivert.util.StringUtil; import com.threerings.presents.client.Client; import static com.threerings.toybox.Log.log;
// // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.server; /** * Provides access to installation specific configuration parameters. */ @Singleton public class ToyBoxConfig { /** Creates a properties instance with test configurations. */ public static Properties testConfig () { String[] defprops = { "server_host", "localhost", "resource_dir", "server/target/web/games", "resource_url", "http://localhost:8080/games/", }; Properties props = new Properties(); for (int ii = 0; ii < defprops.length; ii += 2) { props.setProperty(defprops[ii], defprops[ii+1]); } return props; } public ToyBoxConfig (Config config) { _config = config; } /** Returns the main lobby server host. */ public String getServerHost () { return requireValue("server_host"); } /** Returns the port on which our game servers are listening. */ public int getServerPort () { return _config.getValue("server_port", Client.DEFAULT_SERVER_PORTS[0]); } /** Returns the directory under which all resources are stored. */ public File getResourceDir () { return new File(requireValue("resource_dir")); } /** Returns the base URL via which all resources are downloaded. */ public String getResourceURL () { return requireValue("resource_url"); } /** Returns the JDBC configuration for this installation. */ public Properties getJDBCConfig () { return _config.getSubProperties("db"); } /** Helper function for warning on undefined config elements. */ protected String requireValue (String key) { String value = _config.getValue(key, ""); if (StringUtil.isBlank(value)) {
// Path: toybox/src/main/java/com/threerings/toybox/Log.java // public static Logger log = Logger.getLogger("com.threerings.toybox"); // Path: toybox/src/main/java/com/threerings/toybox/server/ToyBoxConfig.java import java.io.File; import java.util.Properties; import com.google.inject.Singleton; import com.samskivert.util.Config; import com.samskivert.util.StringUtil; import com.threerings.presents.client.Client; import static com.threerings.toybox.Log.log; // // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.server; /** * Provides access to installation specific configuration parameters. */ @Singleton public class ToyBoxConfig { /** Creates a properties instance with test configurations. */ public static Properties testConfig () { String[] defprops = { "server_host", "localhost", "resource_dir", "server/target/web/games", "resource_url", "http://localhost:8080/games/", }; Properties props = new Properties(); for (int ii = 0; ii < defprops.length; ii += 2) { props.setProperty(defprops[ii], defprops[ii+1]); } return props; } public ToyBoxConfig (Config config) { _config = config; } /** Returns the main lobby server host. */ public String getServerHost () { return requireValue("server_host"); } /** Returns the port on which our game servers are listening. */ public int getServerPort () { return _config.getValue("server_port", Client.DEFAULT_SERVER_PORTS[0]); } /** Returns the directory under which all resources are stored. */ public File getResourceDir () { return new File(requireValue("resource_dir")); } /** Returns the base URL via which all resources are downloaded. */ public String getResourceURL () { return requireValue("resource_url"); } /** Returns the JDBC configuration for this installation. */ public Properties getJDBCConfig () { return _config.getSubProperties("db"); } /** Helper function for warning on undefined config elements. */ protected String requireValue (String key) { String value = _config.getValue(key, ""); if (StringUtil.isBlank(value)) {
log.warning("Missing required configuration '" + key + "'.");
threerings/game-gardens
toybox/src/main/java/com/threerings/toybox/client/ToyBoxApplet.java
// Path: toybox/src/main/java/com/threerings/toybox/Log.java // public static Logger log = Logger.getLogger("com.threerings.toybox");
import java.io.IOException; import java.net.URL; import com.threerings.media.FrameManager; import com.threerings.media.ManagedJApplet; import com.threerings.presents.client.Client; import static com.threerings.toybox.Log.log;
// // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.client; /** * Launches a ToyBox game from an applet. */ public class ToyBoxApplet extends ManagedJApplet implements ToyBoxClient.Shell { // from interface ToyBoxSession.Shell public void setTitle (String title) { // TODO } // from interface ToyBoxSession.Shell public void bindCloseAction (ToyBoxClient client) { // no need to do anything here } @Override // from Applet public void init () { super.init();
// Path: toybox/src/main/java/com/threerings/toybox/Log.java // public static Logger log = Logger.getLogger("com.threerings.toybox"); // Path: toybox/src/main/java/com/threerings/toybox/client/ToyBoxApplet.java import java.io.IOException; import java.net.URL; import com.threerings.media.FrameManager; import com.threerings.media.ManagedJApplet; import com.threerings.presents.client.Client; import static com.threerings.toybox.Log.log; // // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.client; /** * Launches a ToyBox game from an applet. */ public class ToyBoxApplet extends ManagedJApplet implements ToyBoxClient.Shell { // from interface ToyBoxSession.Shell public void setTitle (String title) { // TODO } // from interface ToyBoxSession.Shell public void bindCloseAction (ToyBoxClient client) { // no need to do anything here } @Override // from Applet public void init () { super.init();
log.info("Java: " + System.getProperty("java.version") +
threerings/game-gardens
toybox/src/main/java/com/threerings/toybox/util/ToyBoxClassLoader.java
// Path: toybox/src/main/java/com/threerings/toybox/Log.java // public static Logger log = Logger.getLogger("com.threerings.toybox");
import static com.threerings.toybox.Log.log; import java.io.File; import java.net.URL; import java.net.URLClassLoader;
// // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.util; /** * Provides class loading and appropriate permissions for ToyBox games. */ public class ToyBoxClassLoader extends URLClassLoader { public ToyBoxClassLoader (URL[] sources) { super(sources, ToyBoxClassLoader.class.getClassLoader()); _sources = sources; _lastModified = computeLastModified(); } /** * Returns true if none of the jar files referenced by this class * loader have changed since it was first created, false otherwise. */ public boolean isUpToDate () { long[] curModified = computeLastModified(); for (int ii = 0; ii < curModified.length; ii++) { if (curModified[ii] > _lastModified[ii]) {
// Path: toybox/src/main/java/com/threerings/toybox/Log.java // public static Logger log = Logger.getLogger("com.threerings.toybox"); // Path: toybox/src/main/java/com/threerings/toybox/util/ToyBoxClassLoader.java import static com.threerings.toybox.Log.log; import java.io.File; import java.net.URL; import java.net.URLClassLoader; // // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.util; /** * Provides class loading and appropriate permissions for ToyBox games. */ public class ToyBoxClassLoader extends URLClassLoader { public ToyBoxClassLoader (URL[] sources) { super(sources, ToyBoxClassLoader.class.getClassLoader()); _sources = sources; _lastModified = computeLastModified(); } /** * Returns true if none of the jar files referenced by this class * loader have changed since it was first created, false otherwise. */ public boolean isUpToDate () { long[] curModified = computeLastModified(); for (int ii = 0; ii < curModified.length; ii++) { if (curModified[ii] > _lastModified[ii]) {
log.info(_sources[ii] + " has changed.");
threerings/game-gardens
toybox/src/main/java/com/threerings/toybox/client/LogonPanel.java
// Path: toybox/src/main/java/com/threerings/toybox/util/ToyBoxContext.java // public abstract class ToyBoxContext implements ParlorContext // { // /** // * Returns a reference to the message manager used by the client to // * generate localized messages. // */ // public abstract MessageManager getMessageManager (); // // /** // * Returns a reference to our ToyBox director. // */ // public abstract ToyBoxDirector getToyBoxDirector (); // // /** // * Returns a reference to our frame manager (used for media services). // */ // public abstract FrameManager getFrameManager (); // // /** // * Returns a reference to our key dispatcher. // */ // public abstract KeyDispatcher getKeyDispatcher (); // // /** // * Returns the resource manager which is used to load media resources. // */ // public ResourceManager getResourceManager () // { // return getToyBoxDirector().getResourceManager(); // } // // /** // * Translates the specified message using the specified message bundle. // */ // public String xlate (String bundle, String message) // { // MessageBundle mb = getMessageManager().getBundle(bundle); // return (mb == null) ? message : mb.xlate(message); // } // // /** // * Convenience method to get the username of the currently logged on // * user. Returns null when we're not logged on. // */ // public Name getUsername () // { // BodyObject bobj = (BodyObject)getClient().getClientObject(); // return (bobj == null) ? null : bobj.getVisibleName(); // } // // /** // * Convenience method to load an image from our resource bundles. // */ // public BufferedImage loadImage (String rsrcPath) // { // try { // return getResourceManager().getImageResource(rsrcPath); // } catch (IOException ioe) { // log.warning("Unable to load image resource [path=" + rsrcPath + "].", ioe); // // cope; return an error image of abitrary size // return ImageUtil.createErrorImage(50, 50); // } // } // } // // Path: toybox/src/main/java/com/threerings/toybox/Log.java // public static Logger log = Logger.getLogger("com.threerings.toybox");
import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; import com.samskivert.servlet.user.Password; import com.samskivert.util.StringUtil; import com.samskivert.swing.GroupLayout; import com.samskivert.swing.HGroupLayout; import com.samskivert.swing.MultiLineLabel; import com.samskivert.swing.VGroupLayout; import com.threerings.media.image.BufferedMirage; import com.threerings.media.image.ImageUtil; import com.threerings.media.image.Mirage; import com.threerings.util.MessageBundle; import com.threerings.presents.client.Client; import com.threerings.presents.client.ClientObserver; import com.threerings.presents.client.LogonException; import com.threerings.toybox.util.ToyBoxContext; import static com.threerings.toybox.Log.log;
// // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.client; public class LogonPanel extends JPanel implements ActionListener, ClientObserver {
// Path: toybox/src/main/java/com/threerings/toybox/util/ToyBoxContext.java // public abstract class ToyBoxContext implements ParlorContext // { // /** // * Returns a reference to the message manager used by the client to // * generate localized messages. // */ // public abstract MessageManager getMessageManager (); // // /** // * Returns a reference to our ToyBox director. // */ // public abstract ToyBoxDirector getToyBoxDirector (); // // /** // * Returns a reference to our frame manager (used for media services). // */ // public abstract FrameManager getFrameManager (); // // /** // * Returns a reference to our key dispatcher. // */ // public abstract KeyDispatcher getKeyDispatcher (); // // /** // * Returns the resource manager which is used to load media resources. // */ // public ResourceManager getResourceManager () // { // return getToyBoxDirector().getResourceManager(); // } // // /** // * Translates the specified message using the specified message bundle. // */ // public String xlate (String bundle, String message) // { // MessageBundle mb = getMessageManager().getBundle(bundle); // return (mb == null) ? message : mb.xlate(message); // } // // /** // * Convenience method to get the username of the currently logged on // * user. Returns null when we're not logged on. // */ // public Name getUsername () // { // BodyObject bobj = (BodyObject)getClient().getClientObject(); // return (bobj == null) ? null : bobj.getVisibleName(); // } // // /** // * Convenience method to load an image from our resource bundles. // */ // public BufferedImage loadImage (String rsrcPath) // { // try { // return getResourceManager().getImageResource(rsrcPath); // } catch (IOException ioe) { // log.warning("Unable to load image resource [path=" + rsrcPath + "].", ioe); // // cope; return an error image of abitrary size // return ImageUtil.createErrorImage(50, 50); // } // } // } // // Path: toybox/src/main/java/com/threerings/toybox/Log.java // public static Logger log = Logger.getLogger("com.threerings.toybox"); // Path: toybox/src/main/java/com/threerings/toybox/client/LogonPanel.java import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; import com.samskivert.servlet.user.Password; import com.samskivert.util.StringUtil; import com.samskivert.swing.GroupLayout; import com.samskivert.swing.HGroupLayout; import com.samskivert.swing.MultiLineLabel; import com.samskivert.swing.VGroupLayout; import com.threerings.media.image.BufferedMirage; import com.threerings.media.image.ImageUtil; import com.threerings.media.image.Mirage; import com.threerings.util.MessageBundle; import com.threerings.presents.client.Client; import com.threerings.presents.client.ClientObserver; import com.threerings.presents.client.LogonException; import com.threerings.toybox.util.ToyBoxContext; import static com.threerings.toybox.Log.log; // // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.client; public class LogonPanel extends JPanel implements ActionListener, ClientObserver {
public LogonPanel (ToyBoxContext ctx, ToyBoxClient client)
threerings/game-gardens
toybox/src/main/java/com/threerings/toybox/client/LogonPanel.java
// Path: toybox/src/main/java/com/threerings/toybox/util/ToyBoxContext.java // public abstract class ToyBoxContext implements ParlorContext // { // /** // * Returns a reference to the message manager used by the client to // * generate localized messages. // */ // public abstract MessageManager getMessageManager (); // // /** // * Returns a reference to our ToyBox director. // */ // public abstract ToyBoxDirector getToyBoxDirector (); // // /** // * Returns a reference to our frame manager (used for media services). // */ // public abstract FrameManager getFrameManager (); // // /** // * Returns a reference to our key dispatcher. // */ // public abstract KeyDispatcher getKeyDispatcher (); // // /** // * Returns the resource manager which is used to load media resources. // */ // public ResourceManager getResourceManager () // { // return getToyBoxDirector().getResourceManager(); // } // // /** // * Translates the specified message using the specified message bundle. // */ // public String xlate (String bundle, String message) // { // MessageBundle mb = getMessageManager().getBundle(bundle); // return (mb == null) ? message : mb.xlate(message); // } // // /** // * Convenience method to get the username of the currently logged on // * user. Returns null when we're not logged on. // */ // public Name getUsername () // { // BodyObject bobj = (BodyObject)getClient().getClientObject(); // return (bobj == null) ? null : bobj.getVisibleName(); // } // // /** // * Convenience method to load an image from our resource bundles. // */ // public BufferedImage loadImage (String rsrcPath) // { // try { // return getResourceManager().getImageResource(rsrcPath); // } catch (IOException ioe) { // log.warning("Unable to load image resource [path=" + rsrcPath + "].", ioe); // // cope; return an error image of abitrary size // return ImageUtil.createErrorImage(50, 50); // } // } // } // // Path: toybox/src/main/java/com/threerings/toybox/Log.java // public static Logger log = Logger.getLogger("com.threerings.toybox");
import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; import com.samskivert.servlet.user.Password; import com.samskivert.util.StringUtil; import com.samskivert.swing.GroupLayout; import com.samskivert.swing.HGroupLayout; import com.samskivert.swing.MultiLineLabel; import com.samskivert.swing.VGroupLayout; import com.threerings.media.image.BufferedMirage; import com.threerings.media.image.ImageUtil; import com.threerings.media.image.Mirage; import com.threerings.util.MessageBundle; import com.threerings.presents.client.Client; import com.threerings.presents.client.ClientObserver; import com.threerings.presents.client.LogonException; import com.threerings.toybox.util.ToyBoxContext; import static com.threerings.toybox.Log.log;
_msgs = _ctx.getMessageManager().getBundle("client.logon"); setLayout(new VGroupLayout()); setBackground(ToyBoxUI.LIGHT_BLUE); // stick the logon components into a panel that will stretch them // to a sensible width JPanel box = new JPanel( new VGroupLayout(VGroupLayout.NONE, VGroupLayout.NONE, 5, VGroupLayout.CENTER)) { @Override public Dimension getPreferredSize () { Dimension psize = super.getPreferredSize(); psize.width = Math.max(psize.width, 300); return psize; } }; box.setOpaque(false); add(box); // load our background imagery try { _bgimg = ImageIO.read( getClass().getClassLoader().getResourceAsStream( "rsrc/media/logon_background.png")); _flowers = new BufferedMirage( ImageIO.read( getClass().getClassLoader().getResourceAsStream( "rsrc/media/lobby_background.png"))); } catch (Exception e) {
// Path: toybox/src/main/java/com/threerings/toybox/util/ToyBoxContext.java // public abstract class ToyBoxContext implements ParlorContext // { // /** // * Returns a reference to the message manager used by the client to // * generate localized messages. // */ // public abstract MessageManager getMessageManager (); // // /** // * Returns a reference to our ToyBox director. // */ // public abstract ToyBoxDirector getToyBoxDirector (); // // /** // * Returns a reference to our frame manager (used for media services). // */ // public abstract FrameManager getFrameManager (); // // /** // * Returns a reference to our key dispatcher. // */ // public abstract KeyDispatcher getKeyDispatcher (); // // /** // * Returns the resource manager which is used to load media resources. // */ // public ResourceManager getResourceManager () // { // return getToyBoxDirector().getResourceManager(); // } // // /** // * Translates the specified message using the specified message bundle. // */ // public String xlate (String bundle, String message) // { // MessageBundle mb = getMessageManager().getBundle(bundle); // return (mb == null) ? message : mb.xlate(message); // } // // /** // * Convenience method to get the username of the currently logged on // * user. Returns null when we're not logged on. // */ // public Name getUsername () // { // BodyObject bobj = (BodyObject)getClient().getClientObject(); // return (bobj == null) ? null : bobj.getVisibleName(); // } // // /** // * Convenience method to load an image from our resource bundles. // */ // public BufferedImage loadImage (String rsrcPath) // { // try { // return getResourceManager().getImageResource(rsrcPath); // } catch (IOException ioe) { // log.warning("Unable to load image resource [path=" + rsrcPath + "].", ioe); // // cope; return an error image of abitrary size // return ImageUtil.createErrorImage(50, 50); // } // } // } // // Path: toybox/src/main/java/com/threerings/toybox/Log.java // public static Logger log = Logger.getLogger("com.threerings.toybox"); // Path: toybox/src/main/java/com/threerings/toybox/client/LogonPanel.java import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; import com.samskivert.servlet.user.Password; import com.samskivert.util.StringUtil; import com.samskivert.swing.GroupLayout; import com.samskivert.swing.HGroupLayout; import com.samskivert.swing.MultiLineLabel; import com.samskivert.swing.VGroupLayout; import com.threerings.media.image.BufferedMirage; import com.threerings.media.image.ImageUtil; import com.threerings.media.image.Mirage; import com.threerings.util.MessageBundle; import com.threerings.presents.client.Client; import com.threerings.presents.client.ClientObserver; import com.threerings.presents.client.LogonException; import com.threerings.toybox.util.ToyBoxContext; import static com.threerings.toybox.Log.log; _msgs = _ctx.getMessageManager().getBundle("client.logon"); setLayout(new VGroupLayout()); setBackground(ToyBoxUI.LIGHT_BLUE); // stick the logon components into a panel that will stretch them // to a sensible width JPanel box = new JPanel( new VGroupLayout(VGroupLayout.NONE, VGroupLayout.NONE, 5, VGroupLayout.CENTER)) { @Override public Dimension getPreferredSize () { Dimension psize = super.getPreferredSize(); psize.width = Math.max(psize.width, 300); return psize; } }; box.setOpaque(false); add(box); // load our background imagery try { _bgimg = ImageIO.read( getClass().getClassLoader().getResourceAsStream( "rsrc/media/logon_background.png")); _flowers = new BufferedMirage( ImageIO.read( getClass().getClassLoader().getResourceAsStream( "rsrc/media/lobby_background.png"))); } catch (Exception e) {
log.warning("Failed to load background image.", e);
threerings/game-gardens
toybox/src/main/java/com/threerings/toybox/client/ToyBoxUI.java
// Path: toybox/src/main/java/com/threerings/toybox/util/ToyBoxContext.java // public abstract class ToyBoxContext implements ParlorContext // { // /** // * Returns a reference to the message manager used by the client to // * generate localized messages. // */ // public abstract MessageManager getMessageManager (); // // /** // * Returns a reference to our ToyBox director. // */ // public abstract ToyBoxDirector getToyBoxDirector (); // // /** // * Returns a reference to our frame manager (used for media services). // */ // public abstract FrameManager getFrameManager (); // // /** // * Returns a reference to our key dispatcher. // */ // public abstract KeyDispatcher getKeyDispatcher (); // // /** // * Returns the resource manager which is used to load media resources. // */ // public ResourceManager getResourceManager () // { // return getToyBoxDirector().getResourceManager(); // } // // /** // * Translates the specified message using the specified message bundle. // */ // public String xlate (String bundle, String message) // { // MessageBundle mb = getMessageManager().getBundle(bundle); // return (mb == null) ? message : mb.xlate(message); // } // // /** // * Convenience method to get the username of the currently logged on // * user. Returns null when we're not logged on. // */ // public Name getUsername () // { // BodyObject bobj = (BodyObject)getClient().getClientObject(); // return (bobj == null) ? null : bobj.getVisibleName(); // } // // /** // * Convenience method to load an image from our resource bundles. // */ // public BufferedImage loadImage (String rsrcPath) // { // try { // return getResourceManager().getImageResource(rsrcPath); // } catch (IOException ioe) { // log.warning("Unable to load image resource [path=" + rsrcPath + "].", ioe); // // cope; return an error image of abitrary size // return ImageUtil.createErrorImage(50, 50); // } // } // } // // Path: toybox/src/main/java/com/threerings/toybox/Log.java // public static Logger log = Logger.getLogger("com.threerings.toybox");
import java.awt.Color; import java.awt.Font; import java.io.InputStream; import com.threerings.toybox.util.ToyBoxContext; import static com.threerings.toybox.Log.log;
// // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.client; /** * Contains various bits needed for our look and feel. */ public class ToyBoxUI { /** The fancy cursive font we use to display game names. */ public static Font fancyFont; /** The nice blue background we use for scrolly bits. */ public static final Color LIGHT_BLUE = new Color(0xC8E1E9);
// Path: toybox/src/main/java/com/threerings/toybox/util/ToyBoxContext.java // public abstract class ToyBoxContext implements ParlorContext // { // /** // * Returns a reference to the message manager used by the client to // * generate localized messages. // */ // public abstract MessageManager getMessageManager (); // // /** // * Returns a reference to our ToyBox director. // */ // public abstract ToyBoxDirector getToyBoxDirector (); // // /** // * Returns a reference to our frame manager (used for media services). // */ // public abstract FrameManager getFrameManager (); // // /** // * Returns a reference to our key dispatcher. // */ // public abstract KeyDispatcher getKeyDispatcher (); // // /** // * Returns the resource manager which is used to load media resources. // */ // public ResourceManager getResourceManager () // { // return getToyBoxDirector().getResourceManager(); // } // // /** // * Translates the specified message using the specified message bundle. // */ // public String xlate (String bundle, String message) // { // MessageBundle mb = getMessageManager().getBundle(bundle); // return (mb == null) ? message : mb.xlate(message); // } // // /** // * Convenience method to get the username of the currently logged on // * user. Returns null when we're not logged on. // */ // public Name getUsername () // { // BodyObject bobj = (BodyObject)getClient().getClientObject(); // return (bobj == null) ? null : bobj.getVisibleName(); // } // // /** // * Convenience method to load an image from our resource bundles. // */ // public BufferedImage loadImage (String rsrcPath) // { // try { // return getResourceManager().getImageResource(rsrcPath); // } catch (IOException ioe) { // log.warning("Unable to load image resource [path=" + rsrcPath + "].", ioe); // // cope; return an error image of abitrary size // return ImageUtil.createErrorImage(50, 50); // } // } // } // // Path: toybox/src/main/java/com/threerings/toybox/Log.java // public static Logger log = Logger.getLogger("com.threerings.toybox"); // Path: toybox/src/main/java/com/threerings/toybox/client/ToyBoxUI.java import java.awt.Color; import java.awt.Font; import java.io.InputStream; import com.threerings.toybox.util.ToyBoxContext; import static com.threerings.toybox.Log.log; // // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.client; /** * Contains various bits needed for our look and feel. */ public class ToyBoxUI { /** The fancy cursive font we use to display game names. */ public static Font fancyFont; /** The nice blue background we use for scrolly bits. */ public static final Color LIGHT_BLUE = new Color(0xC8E1E9);
public static void init (ToyBoxContext ctx)
threerings/game-gardens
toybox/src/main/java/com/threerings/toybox/client/ToyBoxUI.java
// Path: toybox/src/main/java/com/threerings/toybox/util/ToyBoxContext.java // public abstract class ToyBoxContext implements ParlorContext // { // /** // * Returns a reference to the message manager used by the client to // * generate localized messages. // */ // public abstract MessageManager getMessageManager (); // // /** // * Returns a reference to our ToyBox director. // */ // public abstract ToyBoxDirector getToyBoxDirector (); // // /** // * Returns a reference to our frame manager (used for media services). // */ // public abstract FrameManager getFrameManager (); // // /** // * Returns a reference to our key dispatcher. // */ // public abstract KeyDispatcher getKeyDispatcher (); // // /** // * Returns the resource manager which is used to load media resources. // */ // public ResourceManager getResourceManager () // { // return getToyBoxDirector().getResourceManager(); // } // // /** // * Translates the specified message using the specified message bundle. // */ // public String xlate (String bundle, String message) // { // MessageBundle mb = getMessageManager().getBundle(bundle); // return (mb == null) ? message : mb.xlate(message); // } // // /** // * Convenience method to get the username of the currently logged on // * user. Returns null when we're not logged on. // */ // public Name getUsername () // { // BodyObject bobj = (BodyObject)getClient().getClientObject(); // return (bobj == null) ? null : bobj.getVisibleName(); // } // // /** // * Convenience method to load an image from our resource bundles. // */ // public BufferedImage loadImage (String rsrcPath) // { // try { // return getResourceManager().getImageResource(rsrcPath); // } catch (IOException ioe) { // log.warning("Unable to load image resource [path=" + rsrcPath + "].", ioe); // // cope; return an error image of abitrary size // return ImageUtil.createErrorImage(50, 50); // } // } // } // // Path: toybox/src/main/java/com/threerings/toybox/Log.java // public static Logger log = Logger.getLogger("com.threerings.toybox");
import java.awt.Color; import java.awt.Font; import java.io.InputStream; import com.threerings.toybox.util.ToyBoxContext; import static com.threerings.toybox.Log.log;
// // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.client; /** * Contains various bits needed for our look and feel. */ public class ToyBoxUI { /** The fancy cursive font we use to display game names. */ public static Font fancyFont; /** The nice blue background we use for scrolly bits. */ public static final Color LIGHT_BLUE = new Color(0xC8E1E9); public static void init (ToyBoxContext ctx) { _ctx = ctx; // try to load our fancy font try { InputStream in = ToyBoxUI.class.getClassLoader().getResourceAsStream("rsrc/media/porc.ttf"); fancyFont = Font.createFont(Font.TRUETYPE_FONT, in); fancyFont = fancyFont.deriveFont(Font.PLAIN, 52); in.close(); } catch (Exception e) {
// Path: toybox/src/main/java/com/threerings/toybox/util/ToyBoxContext.java // public abstract class ToyBoxContext implements ParlorContext // { // /** // * Returns a reference to the message manager used by the client to // * generate localized messages. // */ // public abstract MessageManager getMessageManager (); // // /** // * Returns a reference to our ToyBox director. // */ // public abstract ToyBoxDirector getToyBoxDirector (); // // /** // * Returns a reference to our frame manager (used for media services). // */ // public abstract FrameManager getFrameManager (); // // /** // * Returns a reference to our key dispatcher. // */ // public abstract KeyDispatcher getKeyDispatcher (); // // /** // * Returns the resource manager which is used to load media resources. // */ // public ResourceManager getResourceManager () // { // return getToyBoxDirector().getResourceManager(); // } // // /** // * Translates the specified message using the specified message bundle. // */ // public String xlate (String bundle, String message) // { // MessageBundle mb = getMessageManager().getBundle(bundle); // return (mb == null) ? message : mb.xlate(message); // } // // /** // * Convenience method to get the username of the currently logged on // * user. Returns null when we're not logged on. // */ // public Name getUsername () // { // BodyObject bobj = (BodyObject)getClient().getClientObject(); // return (bobj == null) ? null : bobj.getVisibleName(); // } // // /** // * Convenience method to load an image from our resource bundles. // */ // public BufferedImage loadImage (String rsrcPath) // { // try { // return getResourceManager().getImageResource(rsrcPath); // } catch (IOException ioe) { // log.warning("Unable to load image resource [path=" + rsrcPath + "].", ioe); // // cope; return an error image of abitrary size // return ImageUtil.createErrorImage(50, 50); // } // } // } // // Path: toybox/src/main/java/com/threerings/toybox/Log.java // public static Logger log = Logger.getLogger("com.threerings.toybox"); // Path: toybox/src/main/java/com/threerings/toybox/client/ToyBoxUI.java import java.awt.Color; import java.awt.Font; import java.io.InputStream; import com.threerings.toybox.util.ToyBoxContext; import static com.threerings.toybox.Log.log; // // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.client; /** * Contains various bits needed for our look and feel. */ public class ToyBoxUI { /** The fancy cursive font we use to display game names. */ public static Font fancyFont; /** The nice blue background we use for scrolly bits. */ public static final Color LIGHT_BLUE = new Color(0xC8E1E9); public static void init (ToyBoxContext ctx) { _ctx = ctx; // try to load our fancy font try { InputStream in = ToyBoxUI.class.getClassLoader().getResourceAsStream("rsrc/media/porc.ttf"); fancyFont = Font.createFont(Font.TRUETYPE_FONT, in); fancyFont = fancyFont.deriveFont(Font.PLAIN, 52); in.close(); } catch (Exception e) {
log.warning("Failed to load custom font, falling back to default.", e);
threerings/game-gardens
toybox/src/main/java/com/threerings/toybox/server/ToyBoxClientResolver.java
// Path: toybox/src/main/java/com/threerings/toybox/data/ToyBoxUserObject.java // public class ToyBoxUserObject extends BodyObject // { // // AUTO-GENERATED: FIELDS START // /** The field name of the <code>tokens</code> field. */ // @Generated(value={"com.threerings.presents.tools.GenDObjectTask"}) // public static final String TOKENS = "tokens"; // // AUTO-GENERATED: FIELDS END // // /** Indicates which access control tokens are held by this user. */ // public TokenRing tokens; // // @Override // from BodyObject // public TokenRing getTokens () // { // return tokens; // } // // // AUTO-GENERATED: METHODS START // /** // * Requests that the <code>tokens</code> field be set to the // * specified value. The local value will be updated immediately and an // * event will be propagated through the system to notify all listeners // * that the attribute did change. Proxied copies of this object (on // * clients) will apply the value change when they received the // * attribute changed notification. // */ // @Generated(value={"com.threerings.presents.tools.GenDObjectTask"}) // public void setTokens (TokenRing value) // { // TokenRing ovalue = this.tokens; // requestAttributeChange( // TOKENS, value, ovalue); // this.tokens = value; // } // // AUTO-GENERATED: METHODS END // }
import com.threerings.toybox.data.ToyBoxUserObject; import com.threerings.presents.data.ClientObject; import com.threerings.crowd.server.CrowdClientResolver;
// // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.server; /** * Customizes the client resolver to use our {@link ToyBoxUserObject}. */ public class ToyBoxClientResolver extends CrowdClientResolver { @Override // from CrowdClientResolver public ClientObject createClientObject () {
// Path: toybox/src/main/java/com/threerings/toybox/data/ToyBoxUserObject.java // public class ToyBoxUserObject extends BodyObject // { // // AUTO-GENERATED: FIELDS START // /** The field name of the <code>tokens</code> field. */ // @Generated(value={"com.threerings.presents.tools.GenDObjectTask"}) // public static final String TOKENS = "tokens"; // // AUTO-GENERATED: FIELDS END // // /** Indicates which access control tokens are held by this user. */ // public TokenRing tokens; // // @Override // from BodyObject // public TokenRing getTokens () // { // return tokens; // } // // // AUTO-GENERATED: METHODS START // /** // * Requests that the <code>tokens</code> field be set to the // * specified value. The local value will be updated immediately and an // * event will be propagated through the system to notify all listeners // * that the attribute did change. Proxied copies of this object (on // * clients) will apply the value change when they received the // * attribute changed notification. // */ // @Generated(value={"com.threerings.presents.tools.GenDObjectTask"}) // public void setTokens (TokenRing value) // { // TokenRing ovalue = this.tokens; // requestAttributeChange( // TOKENS, value, ovalue); // this.tokens = value; // } // // AUTO-GENERATED: METHODS END // } // Path: toybox/src/main/java/com/threerings/toybox/server/ToyBoxClientResolver.java import com.threerings.toybox.data.ToyBoxUserObject; import com.threerings.presents.data.ClientObject; import com.threerings.crowd.server.CrowdClientResolver; // // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.server; /** * Customizes the client resolver to use our {@link ToyBoxUserObject}. */ public class ToyBoxClientResolver extends CrowdClientResolver { @Override // from CrowdClientResolver public ClientObject createClientObject () {
return new ToyBoxUserObject();
threerings/game-gardens
toybox/src/main/java/com/threerings/toybox/lobby/data/LobbyConfig.java
// Path: toybox/src/main/java/com/threerings/toybox/data/GameDefinition.java // public class GameDefinition implements Streamable // { // /** A string identifier for the game. */ // public String ident; // // /** The class name of the <code>GameController</code> derivation that we use to bootstrap on // * the client. */ // public String controller; // // /** The class name of the <code>GameManager</code> derivation that we use to manage the game on // * the server. */ // public String manager; // // /** The MD5 digest of the game media file. */ // public String digest; // // /** The configuration of the match-making mechanism. */ // public MatchConfig match; // // /** Parameters used to configure the game itself. */ // public Parameter[] params; // // /** // * Provides the path to this game's media (a jar file). // * // * @param gameId the unique id of the game provided when this game definition was registered // * with the system, or -1 if we're running in test mode. // */ // public String getMediaPath (int gameId) // { // return (gameId == -1) ? ident + ".jar" : ident + "-" + gameId + ".jar"; // } // // /** // * Returns true if a single player can play this game (possibly against AI opponents), or if // * opponents are needed. // */ // public boolean isSinglePlayerPlayable () // { // // maybe it's just single player no problem // int minPlayers = 2; // if (match != null) { // minPlayers = match.getMinimumPlayers(); // if (minPlayers <= 1) { // return true; // } // } // // // or maybe it has AIs // int aiCount = 0; // for (Parameter param : params) { // if (param instanceof AIParameter) { // aiCount = ((AIParameter)param).maximum; // } // } // return (minPlayers - aiCount) <= 1; // } // // /** Called when parsing a game definition from XML. */ // @ActionScript(omit=true) // public void setParams (List<Parameter> list) // { // params = list.toArray(new Parameter[list.size()]); // } // // /** Generates a string representation of this instance. */ // @Override // public String toString () // { // return StringUtil.fieldsToString(this); // } // } // // Path: toybox/src/main/java/com/threerings/toybox/lobby/client/LobbyController.java // public class LobbyController extends PlaceController // { // // documentation inherited // @Override // public void init (CrowdContext ctx, PlaceConfig config) // { // super.init(ctx, config); // // // cast our references // _ctx = (ToyBoxContext)ctx; // _config = (LobbyConfig)config; // } // // // documentation inherited // @Override // public void willEnterPlace (PlaceObject plobj) // { // super.willEnterPlace(plobj); // // // let the toybox director know that we're in // _ctx.getToyBoxDirector().enteredLobby(_config); // // // TODO: hold off on creating the match making interface until the // // resources are downloaded (indeed show the download progress in // // that same location) // // // have the toybox director download this game's jar files // Downloader.Observer obs = new Downloader.Observer() { // public void resolvingDownloads () { // log.info("Resolving downloads..."); // // TODO: show download progress // } // public boolean downloadProgress (int percent, long remaining) { // log.info("Download progress: " + percent); // if (percent == 100) { // _panel.showMatchMakingView(_config); // } else { // // TODO: show download progress // } // return true; // } // public void downloadFailed (Resource rsrc, Exception e) { // log.info("Download failed [rsrc=" + rsrc + ", e=" + e + "]."); // // TODO: report warning // } // }; // _ctx.getToyBoxDirector().resolveResources( // _config.getGameId(), _config.getGameDefinition(), obs); // } // // // documentation inherited // @Override // protected PlaceView createPlaceView (CrowdContext ctx) // { // return (_panel = new LobbyPanel((ToyBoxContext)ctx)); // } // // protected ToyBoxContext _ctx; // protected LobbyConfig _config; // protected LobbyPanel _panel; // }
import com.threerings.toybox.data.GameDefinition; import com.threerings.toybox.lobby.client.LobbyController; import com.threerings.crowd.client.PlaceController; import com.threerings.crowd.data.PlaceConfig;
// // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.lobby.data; /** * Defines the configuration of a ToyBox match-making lobby. */ public class LobbyConfig extends PlaceConfig { /** * A default constructor used when unserializing. */ public LobbyConfig () { } /** * Creates the config for a new lobby that will match-make games with * the specified configuration. */
// Path: toybox/src/main/java/com/threerings/toybox/data/GameDefinition.java // public class GameDefinition implements Streamable // { // /** A string identifier for the game. */ // public String ident; // // /** The class name of the <code>GameController</code> derivation that we use to bootstrap on // * the client. */ // public String controller; // // /** The class name of the <code>GameManager</code> derivation that we use to manage the game on // * the server. */ // public String manager; // // /** The MD5 digest of the game media file. */ // public String digest; // // /** The configuration of the match-making mechanism. */ // public MatchConfig match; // // /** Parameters used to configure the game itself. */ // public Parameter[] params; // // /** // * Provides the path to this game's media (a jar file). // * // * @param gameId the unique id of the game provided when this game definition was registered // * with the system, or -1 if we're running in test mode. // */ // public String getMediaPath (int gameId) // { // return (gameId == -1) ? ident + ".jar" : ident + "-" + gameId + ".jar"; // } // // /** // * Returns true if a single player can play this game (possibly against AI opponents), or if // * opponents are needed. // */ // public boolean isSinglePlayerPlayable () // { // // maybe it's just single player no problem // int minPlayers = 2; // if (match != null) { // minPlayers = match.getMinimumPlayers(); // if (minPlayers <= 1) { // return true; // } // } // // // or maybe it has AIs // int aiCount = 0; // for (Parameter param : params) { // if (param instanceof AIParameter) { // aiCount = ((AIParameter)param).maximum; // } // } // return (minPlayers - aiCount) <= 1; // } // // /** Called when parsing a game definition from XML. */ // @ActionScript(omit=true) // public void setParams (List<Parameter> list) // { // params = list.toArray(new Parameter[list.size()]); // } // // /** Generates a string representation of this instance. */ // @Override // public String toString () // { // return StringUtil.fieldsToString(this); // } // } // // Path: toybox/src/main/java/com/threerings/toybox/lobby/client/LobbyController.java // public class LobbyController extends PlaceController // { // // documentation inherited // @Override // public void init (CrowdContext ctx, PlaceConfig config) // { // super.init(ctx, config); // // // cast our references // _ctx = (ToyBoxContext)ctx; // _config = (LobbyConfig)config; // } // // // documentation inherited // @Override // public void willEnterPlace (PlaceObject plobj) // { // super.willEnterPlace(plobj); // // // let the toybox director know that we're in // _ctx.getToyBoxDirector().enteredLobby(_config); // // // TODO: hold off on creating the match making interface until the // // resources are downloaded (indeed show the download progress in // // that same location) // // // have the toybox director download this game's jar files // Downloader.Observer obs = new Downloader.Observer() { // public void resolvingDownloads () { // log.info("Resolving downloads..."); // // TODO: show download progress // } // public boolean downloadProgress (int percent, long remaining) { // log.info("Download progress: " + percent); // if (percent == 100) { // _panel.showMatchMakingView(_config); // } else { // // TODO: show download progress // } // return true; // } // public void downloadFailed (Resource rsrc, Exception e) { // log.info("Download failed [rsrc=" + rsrc + ", e=" + e + "]."); // // TODO: report warning // } // }; // _ctx.getToyBoxDirector().resolveResources( // _config.getGameId(), _config.getGameDefinition(), obs); // } // // // documentation inherited // @Override // protected PlaceView createPlaceView (CrowdContext ctx) // { // return (_panel = new LobbyPanel((ToyBoxContext)ctx)); // } // // protected ToyBoxContext _ctx; // protected LobbyConfig _config; // protected LobbyPanel _panel; // } // Path: toybox/src/main/java/com/threerings/toybox/lobby/data/LobbyConfig.java import com.threerings.toybox.data.GameDefinition; import com.threerings.toybox.lobby.client.LobbyController; import com.threerings.crowd.client.PlaceController; import com.threerings.crowd.data.PlaceConfig; // // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.lobby.data; /** * Defines the configuration of a ToyBox match-making lobby. */ public class LobbyConfig extends PlaceConfig { /** * A default constructor used when unserializing. */ public LobbyConfig () { } /** * Creates the config for a new lobby that will match-make games with * the specified configuration. */
public LobbyConfig (int gameId, GameDefinition gamedef)
threerings/game-gardens
toybox/src/main/java/com/threerings/toybox/lobby/data/LobbyConfig.java
// Path: toybox/src/main/java/com/threerings/toybox/data/GameDefinition.java // public class GameDefinition implements Streamable // { // /** A string identifier for the game. */ // public String ident; // // /** The class name of the <code>GameController</code> derivation that we use to bootstrap on // * the client. */ // public String controller; // // /** The class name of the <code>GameManager</code> derivation that we use to manage the game on // * the server. */ // public String manager; // // /** The MD5 digest of the game media file. */ // public String digest; // // /** The configuration of the match-making mechanism. */ // public MatchConfig match; // // /** Parameters used to configure the game itself. */ // public Parameter[] params; // // /** // * Provides the path to this game's media (a jar file). // * // * @param gameId the unique id of the game provided when this game definition was registered // * with the system, or -1 if we're running in test mode. // */ // public String getMediaPath (int gameId) // { // return (gameId == -1) ? ident + ".jar" : ident + "-" + gameId + ".jar"; // } // // /** // * Returns true if a single player can play this game (possibly against AI opponents), or if // * opponents are needed. // */ // public boolean isSinglePlayerPlayable () // { // // maybe it's just single player no problem // int minPlayers = 2; // if (match != null) { // minPlayers = match.getMinimumPlayers(); // if (minPlayers <= 1) { // return true; // } // } // // // or maybe it has AIs // int aiCount = 0; // for (Parameter param : params) { // if (param instanceof AIParameter) { // aiCount = ((AIParameter)param).maximum; // } // } // return (minPlayers - aiCount) <= 1; // } // // /** Called when parsing a game definition from XML. */ // @ActionScript(omit=true) // public void setParams (List<Parameter> list) // { // params = list.toArray(new Parameter[list.size()]); // } // // /** Generates a string representation of this instance. */ // @Override // public String toString () // { // return StringUtil.fieldsToString(this); // } // } // // Path: toybox/src/main/java/com/threerings/toybox/lobby/client/LobbyController.java // public class LobbyController extends PlaceController // { // // documentation inherited // @Override // public void init (CrowdContext ctx, PlaceConfig config) // { // super.init(ctx, config); // // // cast our references // _ctx = (ToyBoxContext)ctx; // _config = (LobbyConfig)config; // } // // // documentation inherited // @Override // public void willEnterPlace (PlaceObject plobj) // { // super.willEnterPlace(plobj); // // // let the toybox director know that we're in // _ctx.getToyBoxDirector().enteredLobby(_config); // // // TODO: hold off on creating the match making interface until the // // resources are downloaded (indeed show the download progress in // // that same location) // // // have the toybox director download this game's jar files // Downloader.Observer obs = new Downloader.Observer() { // public void resolvingDownloads () { // log.info("Resolving downloads..."); // // TODO: show download progress // } // public boolean downloadProgress (int percent, long remaining) { // log.info("Download progress: " + percent); // if (percent == 100) { // _panel.showMatchMakingView(_config); // } else { // // TODO: show download progress // } // return true; // } // public void downloadFailed (Resource rsrc, Exception e) { // log.info("Download failed [rsrc=" + rsrc + ", e=" + e + "]."); // // TODO: report warning // } // }; // _ctx.getToyBoxDirector().resolveResources( // _config.getGameId(), _config.getGameDefinition(), obs); // } // // // documentation inherited // @Override // protected PlaceView createPlaceView (CrowdContext ctx) // { // return (_panel = new LobbyPanel((ToyBoxContext)ctx)); // } // // protected ToyBoxContext _ctx; // protected LobbyConfig _config; // protected LobbyPanel _panel; // }
import com.threerings.toybox.data.GameDefinition; import com.threerings.toybox.lobby.client.LobbyController; import com.threerings.crowd.client.PlaceController; import com.threerings.crowd.data.PlaceConfig;
// // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.lobby.data; /** * Defines the configuration of a ToyBox match-making lobby. */ public class LobbyConfig extends PlaceConfig { /** * A default constructor used when unserializing. */ public LobbyConfig () { } /** * Creates the config for a new lobby that will match-make games with * the specified configuration. */ public LobbyConfig (int gameId, GameDefinition gamedef) { _gameId = gameId; _gamedef = gamedef; } // documentation inherited @Override public PlaceController createController () {
// Path: toybox/src/main/java/com/threerings/toybox/data/GameDefinition.java // public class GameDefinition implements Streamable // { // /** A string identifier for the game. */ // public String ident; // // /** The class name of the <code>GameController</code> derivation that we use to bootstrap on // * the client. */ // public String controller; // // /** The class name of the <code>GameManager</code> derivation that we use to manage the game on // * the server. */ // public String manager; // // /** The MD5 digest of the game media file. */ // public String digest; // // /** The configuration of the match-making mechanism. */ // public MatchConfig match; // // /** Parameters used to configure the game itself. */ // public Parameter[] params; // // /** // * Provides the path to this game's media (a jar file). // * // * @param gameId the unique id of the game provided when this game definition was registered // * with the system, or -1 if we're running in test mode. // */ // public String getMediaPath (int gameId) // { // return (gameId == -1) ? ident + ".jar" : ident + "-" + gameId + ".jar"; // } // // /** // * Returns true if a single player can play this game (possibly against AI opponents), or if // * opponents are needed. // */ // public boolean isSinglePlayerPlayable () // { // // maybe it's just single player no problem // int minPlayers = 2; // if (match != null) { // minPlayers = match.getMinimumPlayers(); // if (minPlayers <= 1) { // return true; // } // } // // // or maybe it has AIs // int aiCount = 0; // for (Parameter param : params) { // if (param instanceof AIParameter) { // aiCount = ((AIParameter)param).maximum; // } // } // return (minPlayers - aiCount) <= 1; // } // // /** Called when parsing a game definition from XML. */ // @ActionScript(omit=true) // public void setParams (List<Parameter> list) // { // params = list.toArray(new Parameter[list.size()]); // } // // /** Generates a string representation of this instance. */ // @Override // public String toString () // { // return StringUtil.fieldsToString(this); // } // } // // Path: toybox/src/main/java/com/threerings/toybox/lobby/client/LobbyController.java // public class LobbyController extends PlaceController // { // // documentation inherited // @Override // public void init (CrowdContext ctx, PlaceConfig config) // { // super.init(ctx, config); // // // cast our references // _ctx = (ToyBoxContext)ctx; // _config = (LobbyConfig)config; // } // // // documentation inherited // @Override // public void willEnterPlace (PlaceObject plobj) // { // super.willEnterPlace(plobj); // // // let the toybox director know that we're in // _ctx.getToyBoxDirector().enteredLobby(_config); // // // TODO: hold off on creating the match making interface until the // // resources are downloaded (indeed show the download progress in // // that same location) // // // have the toybox director download this game's jar files // Downloader.Observer obs = new Downloader.Observer() { // public void resolvingDownloads () { // log.info("Resolving downloads..."); // // TODO: show download progress // } // public boolean downloadProgress (int percent, long remaining) { // log.info("Download progress: " + percent); // if (percent == 100) { // _panel.showMatchMakingView(_config); // } else { // // TODO: show download progress // } // return true; // } // public void downloadFailed (Resource rsrc, Exception e) { // log.info("Download failed [rsrc=" + rsrc + ", e=" + e + "]."); // // TODO: report warning // } // }; // _ctx.getToyBoxDirector().resolveResources( // _config.getGameId(), _config.getGameDefinition(), obs); // } // // // documentation inherited // @Override // protected PlaceView createPlaceView (CrowdContext ctx) // { // return (_panel = new LobbyPanel((ToyBoxContext)ctx)); // } // // protected ToyBoxContext _ctx; // protected LobbyConfig _config; // protected LobbyPanel _panel; // } // Path: toybox/src/main/java/com/threerings/toybox/lobby/data/LobbyConfig.java import com.threerings.toybox.data.GameDefinition; import com.threerings.toybox.lobby.client.LobbyController; import com.threerings.crowd.client.PlaceController; import com.threerings.crowd.data.PlaceConfig; // // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.lobby.data; /** * Defines the configuration of a ToyBox match-making lobby. */ public class LobbyConfig extends PlaceConfig { /** * A default constructor used when unserializing. */ public LobbyConfig () { } /** * Creates the config for a new lobby that will match-make games with * the specified configuration. */ public LobbyConfig (int gameId, GameDefinition gamedef) { _gameId = gameId; _gamedef = gamedef; } // documentation inherited @Override public PlaceController createController () {
return new LobbyController();
threerings/game-gardens
toybox/src/main/java/com/threerings/toybox/server/ToyBoxSession.java
// Path: toybox/src/main/java/com/threerings/toybox/data/ToyBoxUserObject.java // public class ToyBoxUserObject extends BodyObject // { // // AUTO-GENERATED: FIELDS START // /** The field name of the <code>tokens</code> field. */ // @Generated(value={"com.threerings.presents.tools.GenDObjectTask"}) // public static final String TOKENS = "tokens"; // // AUTO-GENERATED: FIELDS END // // /** Indicates which access control tokens are held by this user. */ // public TokenRing tokens; // // @Override // from BodyObject // public TokenRing getTokens () // { // return tokens; // } // // // AUTO-GENERATED: METHODS START // /** // * Requests that the <code>tokens</code> field be set to the // * specified value. The local value will be updated immediately and an // * event will be propagated through the system to notify all listeners // * that the attribute did change. Proxied copies of this object (on // * clients) will apply the value change when they received the // * attribute changed notification. // */ // @Generated(value={"com.threerings.presents.tools.GenDObjectTask"}) // public void setTokens (TokenRing value) // { // TokenRing ovalue = this.tokens; // requestAttributeChange( // TOKENS, value, ovalue); // this.tokens = value; // } // // AUTO-GENERATED: METHODS END // }
import com.threerings.toybox.data.ToyBoxUserObject; import com.threerings.crowd.data.TokenRing; import com.threerings.crowd.server.CrowdSession;
// // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.server; /** * Extends {@link CrowdSession} and customizes it for the ToyBox system. */ public class ToyBoxSession extends CrowdSession { // documentation inherited @Override protected void sessionWillStart () { super.sessionWillStart(); // if we have auth data in the form of a token ring, use it (we set things directly here // rather than use the setter methods because the user object is not yet out in the wild)
// Path: toybox/src/main/java/com/threerings/toybox/data/ToyBoxUserObject.java // public class ToyBoxUserObject extends BodyObject // { // // AUTO-GENERATED: FIELDS START // /** The field name of the <code>tokens</code> field. */ // @Generated(value={"com.threerings.presents.tools.GenDObjectTask"}) // public static final String TOKENS = "tokens"; // // AUTO-GENERATED: FIELDS END // // /** Indicates which access control tokens are held by this user. */ // public TokenRing tokens; // // @Override // from BodyObject // public TokenRing getTokens () // { // return tokens; // } // // // AUTO-GENERATED: METHODS START // /** // * Requests that the <code>tokens</code> field be set to the // * specified value. The local value will be updated immediately and an // * event will be propagated through the system to notify all listeners // * that the attribute did change. Proxied copies of this object (on // * clients) will apply the value change when they received the // * attribute changed notification. // */ // @Generated(value={"com.threerings.presents.tools.GenDObjectTask"}) // public void setTokens (TokenRing value) // { // TokenRing ovalue = this.tokens; // requestAttributeChange( // TOKENS, value, ovalue); // this.tokens = value; // } // // AUTO-GENERATED: METHODS END // } // Path: toybox/src/main/java/com/threerings/toybox/server/ToyBoxSession.java import com.threerings.toybox.data.ToyBoxUserObject; import com.threerings.crowd.data.TokenRing; import com.threerings.crowd.server.CrowdSession; // // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.server; /** * Extends {@link CrowdSession} and customizes it for the ToyBox system. */ public class ToyBoxSession extends CrowdSession { // documentation inherited @Override protected void sessionWillStart () { super.sessionWillStart(); // if we have auth data in the form of a token ring, use it (we set things directly here // rather than use the setter methods because the user object is not yet out in the wild)
ToyBoxUserObject user = (ToyBoxUserObject)_clobj;
threerings/game-gardens
toybox/src/main/java/com/threerings/toybox/util/ToyBoxUtil.java
// Path: toybox/src/main/java/com/threerings/toybox/data/GameDefinition.java // public class GameDefinition implements Streamable // { // /** A string identifier for the game. */ // public String ident; // // /** The class name of the <code>GameController</code> derivation that we use to bootstrap on // * the client. */ // public String controller; // // /** The class name of the <code>GameManager</code> derivation that we use to manage the game on // * the server. */ // public String manager; // // /** The MD5 digest of the game media file. */ // public String digest; // // /** The configuration of the match-making mechanism. */ // public MatchConfig match; // // /** Parameters used to configure the game itself. */ // public Parameter[] params; // // /** // * Provides the path to this game's media (a jar file). // * // * @param gameId the unique id of the game provided when this game definition was registered // * with the system, or -1 if we're running in test mode. // */ // public String getMediaPath (int gameId) // { // return (gameId == -1) ? ident + ".jar" : ident + "-" + gameId + ".jar"; // } // // /** // * Returns true if a single player can play this game (possibly against AI opponents), or if // * opponents are needed. // */ // public boolean isSinglePlayerPlayable () // { // // maybe it's just single player no problem // int minPlayers = 2; // if (match != null) { // minPlayers = match.getMinimumPlayers(); // if (minPlayers <= 1) { // return true; // } // } // // // or maybe it has AIs // int aiCount = 0; // for (Parameter param : params) { // if (param instanceof AIParameter) { // aiCount = ((AIParameter)param).maximum; // } // } // return (minPlayers - aiCount) <= 1; // } // // /** Called when parsing a game definition from XML. */ // @ActionScript(omit=true) // public void setParams (List<Parameter> list) // { // params = list.toArray(new Parameter[list.size()]); // } // // /** Generates a string representation of this instance. */ // @Override // public String toString () // { // return StringUtil.fieldsToString(this); // } // } // // Path: toybox/src/main/java/com/threerings/toybox/Log.java // public static Logger log = Logger.getLogger("com.threerings.toybox");
import java.io.File; import java.util.ArrayList; import java.net.URL; import com.google.common.collect.Lists; import com.threerings.toybox.data.GameDefinition; import static com.threerings.toybox.Log.log;
// // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.util; /** * Various ToyBox utility methods. */ public class ToyBoxUtil { /** * Creates a class loader with restricted permissions that loads classes from the game jar and * libraries specified by the supplied game definition. Those jar files will be assumed to live * relative to the specified root directory. */ public static ToyBoxClassLoader createClassLoader (
// Path: toybox/src/main/java/com/threerings/toybox/data/GameDefinition.java // public class GameDefinition implements Streamable // { // /** A string identifier for the game. */ // public String ident; // // /** The class name of the <code>GameController</code> derivation that we use to bootstrap on // * the client. */ // public String controller; // // /** The class name of the <code>GameManager</code> derivation that we use to manage the game on // * the server. */ // public String manager; // // /** The MD5 digest of the game media file. */ // public String digest; // // /** The configuration of the match-making mechanism. */ // public MatchConfig match; // // /** Parameters used to configure the game itself. */ // public Parameter[] params; // // /** // * Provides the path to this game's media (a jar file). // * // * @param gameId the unique id of the game provided when this game definition was registered // * with the system, or -1 if we're running in test mode. // */ // public String getMediaPath (int gameId) // { // return (gameId == -1) ? ident + ".jar" : ident + "-" + gameId + ".jar"; // } // // /** // * Returns true if a single player can play this game (possibly against AI opponents), or if // * opponents are needed. // */ // public boolean isSinglePlayerPlayable () // { // // maybe it's just single player no problem // int minPlayers = 2; // if (match != null) { // minPlayers = match.getMinimumPlayers(); // if (minPlayers <= 1) { // return true; // } // } // // // or maybe it has AIs // int aiCount = 0; // for (Parameter param : params) { // if (param instanceof AIParameter) { // aiCount = ((AIParameter)param).maximum; // } // } // return (minPlayers - aiCount) <= 1; // } // // /** Called when parsing a game definition from XML. */ // @ActionScript(omit=true) // public void setParams (List<Parameter> list) // { // params = list.toArray(new Parameter[list.size()]); // } // // /** Generates a string representation of this instance. */ // @Override // public String toString () // { // return StringUtil.fieldsToString(this); // } // } // // Path: toybox/src/main/java/com/threerings/toybox/Log.java // public static Logger log = Logger.getLogger("com.threerings.toybox"); // Path: toybox/src/main/java/com/threerings/toybox/util/ToyBoxUtil.java import java.io.File; import java.util.ArrayList; import java.net.URL; import com.google.common.collect.Lists; import com.threerings.toybox.data.GameDefinition; import static com.threerings.toybox.Log.log; // // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.util; /** * Various ToyBox utility methods. */ public class ToyBoxUtil { /** * Creates a class loader with restricted permissions that loads classes from the game jar and * libraries specified by the supplied game definition. Those jar files will be assumed to live * relative to the specified root directory. */ public static ToyBoxClassLoader createClassLoader (
File root, int gameId, GameDefinition gamedef)
threerings/game-gardens
toybox/src/main/java/com/threerings/toybox/util/ToyBoxUtil.java
// Path: toybox/src/main/java/com/threerings/toybox/data/GameDefinition.java // public class GameDefinition implements Streamable // { // /** A string identifier for the game. */ // public String ident; // // /** The class name of the <code>GameController</code> derivation that we use to bootstrap on // * the client. */ // public String controller; // // /** The class name of the <code>GameManager</code> derivation that we use to manage the game on // * the server. */ // public String manager; // // /** The MD5 digest of the game media file. */ // public String digest; // // /** The configuration of the match-making mechanism. */ // public MatchConfig match; // // /** Parameters used to configure the game itself. */ // public Parameter[] params; // // /** // * Provides the path to this game's media (a jar file). // * // * @param gameId the unique id of the game provided when this game definition was registered // * with the system, or -1 if we're running in test mode. // */ // public String getMediaPath (int gameId) // { // return (gameId == -1) ? ident + ".jar" : ident + "-" + gameId + ".jar"; // } // // /** // * Returns true if a single player can play this game (possibly against AI opponents), or if // * opponents are needed. // */ // public boolean isSinglePlayerPlayable () // { // // maybe it's just single player no problem // int minPlayers = 2; // if (match != null) { // minPlayers = match.getMinimumPlayers(); // if (minPlayers <= 1) { // return true; // } // } // // // or maybe it has AIs // int aiCount = 0; // for (Parameter param : params) { // if (param instanceof AIParameter) { // aiCount = ((AIParameter)param).maximum; // } // } // return (minPlayers - aiCount) <= 1; // } // // /** Called when parsing a game definition from XML. */ // @ActionScript(omit=true) // public void setParams (List<Parameter> list) // { // params = list.toArray(new Parameter[list.size()]); // } // // /** Generates a string representation of this instance. */ // @Override // public String toString () // { // return StringUtil.fieldsToString(this); // } // } // // Path: toybox/src/main/java/com/threerings/toybox/Log.java // public static Logger log = Logger.getLogger("com.threerings.toybox");
import java.io.File; import java.util.ArrayList; import java.net.URL; import com.google.common.collect.Lists; import com.threerings.toybox.data.GameDefinition; import static com.threerings.toybox.Log.log;
// // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.util; /** * Various ToyBox utility methods. */ public class ToyBoxUtil { /** * Creates a class loader with restricted permissions that loads classes from the game jar and * libraries specified by the supplied game definition. Those jar files will be assumed to live * relative to the specified root directory. */ public static ToyBoxClassLoader createClassLoader ( File root, int gameId, GameDefinition gamedef) { ArrayList<URL> ulist = Lists.newArrayList(); String path = ""; try { // add the game jar file path = "file:" + root + "/" + gamedef.getMediaPath(gameId); ulist.add(new URL(path)); } catch (Exception e) {
// Path: toybox/src/main/java/com/threerings/toybox/data/GameDefinition.java // public class GameDefinition implements Streamable // { // /** A string identifier for the game. */ // public String ident; // // /** The class name of the <code>GameController</code> derivation that we use to bootstrap on // * the client. */ // public String controller; // // /** The class name of the <code>GameManager</code> derivation that we use to manage the game on // * the server. */ // public String manager; // // /** The MD5 digest of the game media file. */ // public String digest; // // /** The configuration of the match-making mechanism. */ // public MatchConfig match; // // /** Parameters used to configure the game itself. */ // public Parameter[] params; // // /** // * Provides the path to this game's media (a jar file). // * // * @param gameId the unique id of the game provided when this game definition was registered // * with the system, or -1 if we're running in test mode. // */ // public String getMediaPath (int gameId) // { // return (gameId == -1) ? ident + ".jar" : ident + "-" + gameId + ".jar"; // } // // /** // * Returns true if a single player can play this game (possibly against AI opponents), or if // * opponents are needed. // */ // public boolean isSinglePlayerPlayable () // { // // maybe it's just single player no problem // int minPlayers = 2; // if (match != null) { // minPlayers = match.getMinimumPlayers(); // if (minPlayers <= 1) { // return true; // } // } // // // or maybe it has AIs // int aiCount = 0; // for (Parameter param : params) { // if (param instanceof AIParameter) { // aiCount = ((AIParameter)param).maximum; // } // } // return (minPlayers - aiCount) <= 1; // } // // /** Called when parsing a game definition from XML. */ // @ActionScript(omit=true) // public void setParams (List<Parameter> list) // { // params = list.toArray(new Parameter[list.size()]); // } // // /** Generates a string representation of this instance. */ // @Override // public String toString () // { // return StringUtil.fieldsToString(this); // } // } // // Path: toybox/src/main/java/com/threerings/toybox/Log.java // public static Logger log = Logger.getLogger("com.threerings.toybox"); // Path: toybox/src/main/java/com/threerings/toybox/util/ToyBoxUtil.java import java.io.File; import java.util.ArrayList; import java.net.URL; import com.google.common.collect.Lists; import com.threerings.toybox.data.GameDefinition; import static com.threerings.toybox.Log.log; // // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.util; /** * Various ToyBox utility methods. */ public class ToyBoxUtil { /** * Creates a class loader with restricted permissions that loads classes from the game jar and * libraries specified by the supplied game definition. Those jar files will be assumed to live * relative to the specified root directory. */ public static ToyBoxClassLoader createClassLoader ( File root, int gameId, GameDefinition gamedef) { ArrayList<URL> ulist = Lists.newArrayList(); String path = ""; try { // add the game jar file path = "file:" + root + "/" + gamedef.getMediaPath(gameId); ulist.add(new URL(path)); } catch (Exception e) {
log.warning("Failed to create URL for class loader", "root", root, "path", path, e);
threerings/game-gardens
toybox/src/main/java/com/threerings/toybox/client/ClientController.java
// Path: toybox/src/main/java/com/threerings/toybox/util/ToyBoxContext.java // public abstract class ToyBoxContext implements ParlorContext // { // /** // * Returns a reference to the message manager used by the client to // * generate localized messages. // */ // public abstract MessageManager getMessageManager (); // // /** // * Returns a reference to our ToyBox director. // */ // public abstract ToyBoxDirector getToyBoxDirector (); // // /** // * Returns a reference to our frame manager (used for media services). // */ // public abstract FrameManager getFrameManager (); // // /** // * Returns a reference to our key dispatcher. // */ // public abstract KeyDispatcher getKeyDispatcher (); // // /** // * Returns the resource manager which is used to load media resources. // */ // public ResourceManager getResourceManager () // { // return getToyBoxDirector().getResourceManager(); // } // // /** // * Translates the specified message using the specified message bundle. // */ // public String xlate (String bundle, String message) // { // MessageBundle mb = getMessageManager().getBundle(bundle); // return (mb == null) ? message : mb.xlate(message); // } // // /** // * Convenience method to get the username of the currently logged on // * user. Returns null when we're not logged on. // */ // public Name getUsername () // { // BodyObject bobj = (BodyObject)getClient().getClientObject(); // return (bobj == null) ? null : bobj.getVisibleName(); // } // // /** // * Convenience method to load an image from our resource bundles. // */ // public BufferedImage loadImage (String rsrcPath) // { // try { // return getResourceManager().getImageResource(rsrcPath); // } catch (IOException ioe) { // log.warning("Unable to load image resource [path=" + rsrcPath + "].", ioe); // // cope; return an error image of abitrary size // return ImageUtil.createErrorImage(50, 50); // } // } // } // // Path: toybox/src/main/java/com/threerings/toybox/Log.java // public static Logger log = Logger.getLogger("com.threerings.toybox");
import java.awt.event.ActionEvent; import com.samskivert.swing.Controller; import com.threerings.presents.client.Client; import com.threerings.presents.client.ClientAdapter; import com.threerings.toybox.util.ToyBoxContext; import static com.threerings.toybox.Log.log;
// // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.client; /** * Responsible for top-level control of the client user interface. */ public class ClientController extends Controller { /** * Creates a new client controller. The controller will set everything * up in preparation for logging on. */
// Path: toybox/src/main/java/com/threerings/toybox/util/ToyBoxContext.java // public abstract class ToyBoxContext implements ParlorContext // { // /** // * Returns a reference to the message manager used by the client to // * generate localized messages. // */ // public abstract MessageManager getMessageManager (); // // /** // * Returns a reference to our ToyBox director. // */ // public abstract ToyBoxDirector getToyBoxDirector (); // // /** // * Returns a reference to our frame manager (used for media services). // */ // public abstract FrameManager getFrameManager (); // // /** // * Returns a reference to our key dispatcher. // */ // public abstract KeyDispatcher getKeyDispatcher (); // // /** // * Returns the resource manager which is used to load media resources. // */ // public ResourceManager getResourceManager () // { // return getToyBoxDirector().getResourceManager(); // } // // /** // * Translates the specified message using the specified message bundle. // */ // public String xlate (String bundle, String message) // { // MessageBundle mb = getMessageManager().getBundle(bundle); // return (mb == null) ? message : mb.xlate(message); // } // // /** // * Convenience method to get the username of the currently logged on // * user. Returns null when we're not logged on. // */ // public Name getUsername () // { // BodyObject bobj = (BodyObject)getClient().getClientObject(); // return (bobj == null) ? null : bobj.getVisibleName(); // } // // /** // * Convenience method to load an image from our resource bundles. // */ // public BufferedImage loadImage (String rsrcPath) // { // try { // return getResourceManager().getImageResource(rsrcPath); // } catch (IOException ioe) { // log.warning("Unable to load image resource [path=" + rsrcPath + "].", ioe); // // cope; return an error image of abitrary size // return ImageUtil.createErrorImage(50, 50); // } // } // } // // Path: toybox/src/main/java/com/threerings/toybox/Log.java // public static Logger log = Logger.getLogger("com.threerings.toybox"); // Path: toybox/src/main/java/com/threerings/toybox/client/ClientController.java import java.awt.event.ActionEvent; import com.samskivert.swing.Controller; import com.threerings.presents.client.Client; import com.threerings.presents.client.ClientAdapter; import com.threerings.toybox.util.ToyBoxContext; import static com.threerings.toybox.Log.log; // // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.client; /** * Responsible for top-level control of the client user interface. */ public class ClientController extends Controller { /** * Creates a new client controller. The controller will set everything * up in preparation for logging on. */
public ClientController (ToyBoxContext ctx, ToyBoxClient client)
threerings/game-gardens
toybox/src/main/java/com/threerings/toybox/client/ClientController.java
// Path: toybox/src/main/java/com/threerings/toybox/util/ToyBoxContext.java // public abstract class ToyBoxContext implements ParlorContext // { // /** // * Returns a reference to the message manager used by the client to // * generate localized messages. // */ // public abstract MessageManager getMessageManager (); // // /** // * Returns a reference to our ToyBox director. // */ // public abstract ToyBoxDirector getToyBoxDirector (); // // /** // * Returns a reference to our frame manager (used for media services). // */ // public abstract FrameManager getFrameManager (); // // /** // * Returns a reference to our key dispatcher. // */ // public abstract KeyDispatcher getKeyDispatcher (); // // /** // * Returns the resource manager which is used to load media resources. // */ // public ResourceManager getResourceManager () // { // return getToyBoxDirector().getResourceManager(); // } // // /** // * Translates the specified message using the specified message bundle. // */ // public String xlate (String bundle, String message) // { // MessageBundle mb = getMessageManager().getBundle(bundle); // return (mb == null) ? message : mb.xlate(message); // } // // /** // * Convenience method to get the username of the currently logged on // * user. Returns null when we're not logged on. // */ // public Name getUsername () // { // BodyObject bobj = (BodyObject)getClient().getClientObject(); // return (bobj == null) ? null : bobj.getVisibleName(); // } // // /** // * Convenience method to load an image from our resource bundles. // */ // public BufferedImage loadImage (String rsrcPath) // { // try { // return getResourceManager().getImageResource(rsrcPath); // } catch (IOException ioe) { // log.warning("Unable to load image resource [path=" + rsrcPath + "].", ioe); // // cope; return an error image of abitrary size // return ImageUtil.createErrorImage(50, 50); // } // } // } // // Path: toybox/src/main/java/com/threerings/toybox/Log.java // public static Logger log = Logger.getLogger("com.threerings.toybox");
import java.awt.event.ActionEvent; import com.samskivert.swing.Controller; import com.threerings.presents.client.Client; import com.threerings.presents.client.ClientAdapter; import com.threerings.toybox.util.ToyBoxContext; import static com.threerings.toybox.Log.log;
// // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.client; /** * Responsible for top-level control of the client user interface. */ public class ClientController extends Controller { /** * Creates a new client controller. The controller will set everything * up in preparation for logging on. */ public ClientController (ToyBoxContext ctx, ToyBoxClient client) { // we'll want to keep these around _ctx = ctx; _client = client; // we want to know about logon/logoff _ctx.getClient().addClientObserver(new ClientAdapter() { @Override public void clientDidLogoff (Client client) { _client.setMainPanel(_logonPanel); } }); // create the logon panel and display it _logonPanel = new LogonPanel(_ctx, _client); _client.setMainPanel(_logonPanel); } /** * Returns a reference to the panel used to logon. */ public LogonPanel getLogonPanel () { return _logonPanel; } // documentation inherited @Override public boolean handleAction (ActionEvent action) { String cmd = action.getActionCommand(); if (cmd.equals("logoff")) { // request that we logoff _ctx.getClient().logoff(true); return true; }
// Path: toybox/src/main/java/com/threerings/toybox/util/ToyBoxContext.java // public abstract class ToyBoxContext implements ParlorContext // { // /** // * Returns a reference to the message manager used by the client to // * generate localized messages. // */ // public abstract MessageManager getMessageManager (); // // /** // * Returns a reference to our ToyBox director. // */ // public abstract ToyBoxDirector getToyBoxDirector (); // // /** // * Returns a reference to our frame manager (used for media services). // */ // public abstract FrameManager getFrameManager (); // // /** // * Returns a reference to our key dispatcher. // */ // public abstract KeyDispatcher getKeyDispatcher (); // // /** // * Returns the resource manager which is used to load media resources. // */ // public ResourceManager getResourceManager () // { // return getToyBoxDirector().getResourceManager(); // } // // /** // * Translates the specified message using the specified message bundle. // */ // public String xlate (String bundle, String message) // { // MessageBundle mb = getMessageManager().getBundle(bundle); // return (mb == null) ? message : mb.xlate(message); // } // // /** // * Convenience method to get the username of the currently logged on // * user. Returns null when we're not logged on. // */ // public Name getUsername () // { // BodyObject bobj = (BodyObject)getClient().getClientObject(); // return (bobj == null) ? null : bobj.getVisibleName(); // } // // /** // * Convenience method to load an image from our resource bundles. // */ // public BufferedImage loadImage (String rsrcPath) // { // try { // return getResourceManager().getImageResource(rsrcPath); // } catch (IOException ioe) { // log.warning("Unable to load image resource [path=" + rsrcPath + "].", ioe); // // cope; return an error image of abitrary size // return ImageUtil.createErrorImage(50, 50); // } // } // } // // Path: toybox/src/main/java/com/threerings/toybox/Log.java // public static Logger log = Logger.getLogger("com.threerings.toybox"); // Path: toybox/src/main/java/com/threerings/toybox/client/ClientController.java import java.awt.event.ActionEvent; import com.samskivert.swing.Controller; import com.threerings.presents.client.Client; import com.threerings.presents.client.ClientAdapter; import com.threerings.toybox.util.ToyBoxContext; import static com.threerings.toybox.Log.log; // // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.client; /** * Responsible for top-level control of the client user interface. */ public class ClientController extends Controller { /** * Creates a new client controller. The controller will set everything * up in preparation for logging on. */ public ClientController (ToyBoxContext ctx, ToyBoxClient client) { // we'll want to keep these around _ctx = ctx; _client = client; // we want to know about logon/logoff _ctx.getClient().addClientObserver(new ClientAdapter() { @Override public void clientDidLogoff (Client client) { _client.setMainPanel(_logonPanel); } }); // create the logon panel and display it _logonPanel = new LogonPanel(_ctx, _client); _client.setMainPanel(_logonPanel); } /** * Returns a reference to the panel used to logon. */ public LogonPanel getLogonPanel () { return _logonPanel; } // documentation inherited @Override public boolean handleAction (ActionEvent action) { String cmd = action.getActionCommand(); if (cmd.equals("logoff")) { // request that we logoff _ctx.getClient().logoff(true); return true; }
log.info("Unhandled action: " + action);
threerings/game-gardens
core/src/main/java/com/threerings/gardens/user/Factory_UserService.java
// Path: core/src/main/java/com/threerings/gardens/lobby/LobbyObject.java // public class LobbyObject extends NexusObject { // // /** Represents a table currently being match-made. */ // public static class Table implements Streamable { // public final int id; // public final int seats; // public final String gameName; // public final GameConfig config; // // public Table (int id, int seats, String gameName, GameConfig config) { // this.id = id; // this.seats = seats; // this.gameName = gameName; // this.config = config; // } // } // // /** Represents a game currently in progress. */ // public static class Game implements Streamable { // public final int id; // public final String gameName; // public final GameConfig config; // public String[] players; // // public Game (int id, String gameName, GameConfig config, String[] players) { // this.id = id; // this.gameName = gameName; // this.config = config; // this.players = players; // } // } // // /** Represents a seat at a particular table. */ // public static class Seat implements Streamable { // public final int tableId; // public final int seat; // // public Seat (int tableId, int seat) { // this.tableId = tableId; // this.seat = seat; // } // // @Override public int hashCode () { return tableId * 100 + seat; } // @Override public boolean equals (Object other) { // return other instanceof Seat && ((Seat)other).tableId == tableId && // ((Seat)other).seat == seat; // } // @Override public String toString () { return tableId + "@" + seat; } // } // // /** Provides access to lobby services. */ // public final DService<LobbyService> svc; // // /** Emitted when someone sends a chat event. */ // public final DSignal<ChatMessage> chat = DSignal.create(this); // // /** The occupants of the lobby as {@code id -> username}. */ // public final DMap<Integer,String> occupants = DMap.create(this); // // /** The tables currently being match-made, mapped by id. */ // public final DMap<Integer,Table> tables = DMap.create(this); // // /** The games currently in-progress, mapped by id. */ // public final DMap<Integer,Game> games = DMap.create(this); // // /** Contains a mapping from {table,seat} to occupant user id. */ // public final DMap<Seat,Integer> sitters = DMap.create(this); // // public LobbyObject (DService.Factory<LobbyService> svc) { // this.svc = svc.createService(this); // } // }
import com.threerings.nexus.distrib.Address; import com.threerings.nexus.distrib.DService; import com.threerings.nexus.distrib.NexusObject; import com.threerings.gardens.lobby.LobbyObject; import react.RFuture;
} @Override public RFuture<?> dispatchCall (short methodId, Object[] args) { RFuture<?> result = null; switch (methodId) { case 1: result = service.authenticate( this.<String>cast(args[0])); break; default: result = super.dispatchCall(methodId, args); } return result; } }; } }; } protected static class Marshaller extends DService<UserService> implements UserService { public Marshaller (NexusObject owner) { super(owner); } @Override public UserService get () { return this; } @Override public Class<UserService> getServiceClass () { return UserService.class; }
// Path: core/src/main/java/com/threerings/gardens/lobby/LobbyObject.java // public class LobbyObject extends NexusObject { // // /** Represents a table currently being match-made. */ // public static class Table implements Streamable { // public final int id; // public final int seats; // public final String gameName; // public final GameConfig config; // // public Table (int id, int seats, String gameName, GameConfig config) { // this.id = id; // this.seats = seats; // this.gameName = gameName; // this.config = config; // } // } // // /** Represents a game currently in progress. */ // public static class Game implements Streamable { // public final int id; // public final String gameName; // public final GameConfig config; // public String[] players; // // public Game (int id, String gameName, GameConfig config, String[] players) { // this.id = id; // this.gameName = gameName; // this.config = config; // this.players = players; // } // } // // /** Represents a seat at a particular table. */ // public static class Seat implements Streamable { // public final int tableId; // public final int seat; // // public Seat (int tableId, int seat) { // this.tableId = tableId; // this.seat = seat; // } // // @Override public int hashCode () { return tableId * 100 + seat; } // @Override public boolean equals (Object other) { // return other instanceof Seat && ((Seat)other).tableId == tableId && // ((Seat)other).seat == seat; // } // @Override public String toString () { return tableId + "@" + seat; } // } // // /** Provides access to lobby services. */ // public final DService<LobbyService> svc; // // /** Emitted when someone sends a chat event. */ // public final DSignal<ChatMessage> chat = DSignal.create(this); // // /** The occupants of the lobby as {@code id -> username}. */ // public final DMap<Integer,String> occupants = DMap.create(this); // // /** The tables currently being match-made, mapped by id. */ // public final DMap<Integer,Table> tables = DMap.create(this); // // /** The games currently in-progress, mapped by id. */ // public final DMap<Integer,Game> games = DMap.create(this); // // /** Contains a mapping from {table,seat} to occupant user id. */ // public final DMap<Seat,Integer> sitters = DMap.create(this); // // public LobbyObject (DService.Factory<LobbyService> svc) { // this.svc = svc.createService(this); // } // } // Path: core/src/main/java/com/threerings/gardens/user/Factory_UserService.java import com.threerings.nexus.distrib.Address; import com.threerings.nexus.distrib.DService; import com.threerings.nexus.distrib.NexusObject; import com.threerings.gardens.lobby.LobbyObject; import react.RFuture; } @Override public RFuture<?> dispatchCall (short methodId, Object[] args) { RFuture<?> result = null; switch (methodId) { case 1: result = service.authenticate( this.<String>cast(args[0])); break; default: result = super.dispatchCall(methodId, args); } return result; } }; } }; } protected static class Marshaller extends DService<UserService> implements UserService { public Marshaller (NexusObject owner) { super(owner); } @Override public UserService get () { return this; } @Override public Class<UserService> getServiceClass () { return UserService.class; }
@Override public RFuture<Address<LobbyObject>> authenticate (String sessionToken) {
threerings/game-gardens
toybox/src/main/java/com/threerings/toybox/client/GameSidePanel.java
// Path: toybox/src/main/java/com/threerings/toybox/util/ToyBoxContext.java // public abstract class ToyBoxContext implements ParlorContext // { // /** // * Returns a reference to the message manager used by the client to // * generate localized messages. // */ // public abstract MessageManager getMessageManager (); // // /** // * Returns a reference to our ToyBox director. // */ // public abstract ToyBoxDirector getToyBoxDirector (); // // /** // * Returns a reference to our frame manager (used for media services). // */ // public abstract FrameManager getFrameManager (); // // /** // * Returns a reference to our key dispatcher. // */ // public abstract KeyDispatcher getKeyDispatcher (); // // /** // * Returns the resource manager which is used to load media resources. // */ // public ResourceManager getResourceManager () // { // return getToyBoxDirector().getResourceManager(); // } // // /** // * Translates the specified message using the specified message bundle. // */ // public String xlate (String bundle, String message) // { // MessageBundle mb = getMessageManager().getBundle(bundle); // return (mb == null) ? message : mb.xlate(message); // } // // /** // * Convenience method to get the username of the currently logged on // * user. Returns null when we're not logged on. // */ // public Name getUsername () // { // BodyObject bobj = (BodyObject)getClient().getClientObject(); // return (bobj == null) ? null : bobj.getVisibleName(); // } // // /** // * Convenience method to load an image from our resource bundles. // */ // public BufferedImage loadImage (String rsrcPath) // { // try { // return getResourceManager().getImageResource(rsrcPath); // } catch (IOException ioe) { // log.warning("Unable to load image resource [path=" + rsrcPath + "].", ioe); // // cope; return an error image of abitrary size // return ImageUtil.createErrorImage(50, 50); // } // } // } // // Path: toybox/src/main/java/com/threerings/toybox/data/ToyBoxCodes.java // public static final String TOYBOX_MSGS = "toybox";
import com.threerings.media.SafeScrollPane; import com.threerings.util.MessageBundle; import com.threerings.toybox.util.ToyBoxContext; import static com.threerings.toybox.data.ToyBoxCodes.TOYBOX_MSGS; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTabbedPane;
// // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.client; /** * Contains standard widgets for a side panel in a game. */ public class GameSidePanel extends JPanel { /** * Create a standard-issue GameSidePanel. */
// Path: toybox/src/main/java/com/threerings/toybox/util/ToyBoxContext.java // public abstract class ToyBoxContext implements ParlorContext // { // /** // * Returns a reference to the message manager used by the client to // * generate localized messages. // */ // public abstract MessageManager getMessageManager (); // // /** // * Returns a reference to our ToyBox director. // */ // public abstract ToyBoxDirector getToyBoxDirector (); // // /** // * Returns a reference to our frame manager (used for media services). // */ // public abstract FrameManager getFrameManager (); // // /** // * Returns a reference to our key dispatcher. // */ // public abstract KeyDispatcher getKeyDispatcher (); // // /** // * Returns the resource manager which is used to load media resources. // */ // public ResourceManager getResourceManager () // { // return getToyBoxDirector().getResourceManager(); // } // // /** // * Translates the specified message using the specified message bundle. // */ // public String xlate (String bundle, String message) // { // MessageBundle mb = getMessageManager().getBundle(bundle); // return (mb == null) ? message : mb.xlate(message); // } // // /** // * Convenience method to get the username of the currently logged on // * user. Returns null when we're not logged on. // */ // public Name getUsername () // { // BodyObject bobj = (BodyObject)getClient().getClientObject(); // return (bobj == null) ? null : bobj.getVisibleName(); // } // // /** // * Convenience method to load an image from our resource bundles. // */ // public BufferedImage loadImage (String rsrcPath) // { // try { // return getResourceManager().getImageResource(rsrcPath); // } catch (IOException ioe) { // log.warning("Unable to load image resource [path=" + rsrcPath + "].", ioe); // // cope; return an error image of abitrary size // return ImageUtil.createErrorImage(50, 50); // } // } // } // // Path: toybox/src/main/java/com/threerings/toybox/data/ToyBoxCodes.java // public static final String TOYBOX_MSGS = "toybox"; // Path: toybox/src/main/java/com/threerings/toybox/client/GameSidePanel.java import com.threerings.media.SafeScrollPane; import com.threerings.util.MessageBundle; import com.threerings.toybox.util.ToyBoxContext; import static com.threerings.toybox.data.ToyBoxCodes.TOYBOX_MSGS; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTabbedPane; // // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.client; /** * Contains standard widgets for a side panel in a game. */ public class GameSidePanel extends JPanel { /** * Create a standard-issue GameSidePanel. */
public GameSidePanel (ToyBoxContext ctx)
threerings/game-gardens
toybox/src/main/java/com/threerings/toybox/client/GameSidePanel.java
// Path: toybox/src/main/java/com/threerings/toybox/util/ToyBoxContext.java // public abstract class ToyBoxContext implements ParlorContext // { // /** // * Returns a reference to the message manager used by the client to // * generate localized messages. // */ // public abstract MessageManager getMessageManager (); // // /** // * Returns a reference to our ToyBox director. // */ // public abstract ToyBoxDirector getToyBoxDirector (); // // /** // * Returns a reference to our frame manager (used for media services). // */ // public abstract FrameManager getFrameManager (); // // /** // * Returns a reference to our key dispatcher. // */ // public abstract KeyDispatcher getKeyDispatcher (); // // /** // * Returns the resource manager which is used to load media resources. // */ // public ResourceManager getResourceManager () // { // return getToyBoxDirector().getResourceManager(); // } // // /** // * Translates the specified message using the specified message bundle. // */ // public String xlate (String bundle, String message) // { // MessageBundle mb = getMessageManager().getBundle(bundle); // return (mb == null) ? message : mb.xlate(message); // } // // /** // * Convenience method to get the username of the currently logged on // * user. Returns null when we're not logged on. // */ // public Name getUsername () // { // BodyObject bobj = (BodyObject)getClient().getClientObject(); // return (bobj == null) ? null : bobj.getVisibleName(); // } // // /** // * Convenience method to load an image from our resource bundles. // */ // public BufferedImage loadImage (String rsrcPath) // { // try { // return getResourceManager().getImageResource(rsrcPath); // } catch (IOException ioe) { // log.warning("Unable to load image resource [path=" + rsrcPath + "].", ioe); // // cope; return an error image of abitrary size // return ImageUtil.createErrorImage(50, 50); // } // } // } // // Path: toybox/src/main/java/com/threerings/toybox/data/ToyBoxCodes.java // public static final String TOYBOX_MSGS = "toybox";
import com.threerings.media.SafeScrollPane; import com.threerings.util.MessageBundle; import com.threerings.toybox.util.ToyBoxContext; import static com.threerings.toybox.data.ToyBoxCodes.TOYBOX_MSGS; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTabbedPane;
// // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.client; /** * Contains standard widgets for a side panel in a game. */ public class GameSidePanel extends JPanel { /** * Create a standard-issue GameSidePanel. */ public GameSidePanel (ToyBoxContext ctx) { this(ctx, null); } /** * Create a standard-issue GameSidePanel with the specified pre-translated info text, which * may be HTML. */ public GameSidePanel (final ToyBoxContext ctx, String info) { super(new BorderLayout(10, 10)); setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
// Path: toybox/src/main/java/com/threerings/toybox/util/ToyBoxContext.java // public abstract class ToyBoxContext implements ParlorContext // { // /** // * Returns a reference to the message manager used by the client to // * generate localized messages. // */ // public abstract MessageManager getMessageManager (); // // /** // * Returns a reference to our ToyBox director. // */ // public abstract ToyBoxDirector getToyBoxDirector (); // // /** // * Returns a reference to our frame manager (used for media services). // */ // public abstract FrameManager getFrameManager (); // // /** // * Returns a reference to our key dispatcher. // */ // public abstract KeyDispatcher getKeyDispatcher (); // // /** // * Returns the resource manager which is used to load media resources. // */ // public ResourceManager getResourceManager () // { // return getToyBoxDirector().getResourceManager(); // } // // /** // * Translates the specified message using the specified message bundle. // */ // public String xlate (String bundle, String message) // { // MessageBundle mb = getMessageManager().getBundle(bundle); // return (mb == null) ? message : mb.xlate(message); // } // // /** // * Convenience method to get the username of the currently logged on // * user. Returns null when we're not logged on. // */ // public Name getUsername () // { // BodyObject bobj = (BodyObject)getClient().getClientObject(); // return (bobj == null) ? null : bobj.getVisibleName(); // } // // /** // * Convenience method to load an image from our resource bundles. // */ // public BufferedImage loadImage (String rsrcPath) // { // try { // return getResourceManager().getImageResource(rsrcPath); // } catch (IOException ioe) { // log.warning("Unable to load image resource [path=" + rsrcPath + "].", ioe); // // cope; return an error image of abitrary size // return ImageUtil.createErrorImage(50, 50); // } // } // } // // Path: toybox/src/main/java/com/threerings/toybox/data/ToyBoxCodes.java // public static final String TOYBOX_MSGS = "toybox"; // Path: toybox/src/main/java/com/threerings/toybox/client/GameSidePanel.java import com.threerings.media.SafeScrollPane; import com.threerings.util.MessageBundle; import com.threerings.toybox.util.ToyBoxContext; import static com.threerings.toybox.data.ToyBoxCodes.TOYBOX_MSGS; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTabbedPane; // // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.client; /** * Contains standard widgets for a side panel in a game. */ public class GameSidePanel extends JPanel { /** * Create a standard-issue GameSidePanel. */ public GameSidePanel (ToyBoxContext ctx) { this(ctx, null); } /** * Create a standard-issue GameSidePanel with the specified pre-translated info text, which * may be HTML. */ public GameSidePanel (final ToyBoxContext ctx, String info) { super(new BorderLayout(10, 10)); setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
MessageBundle msgs = ctx.getMessageManager().getBundle(TOYBOX_MSGS);
threerings/game-gardens
toybox/src/main/java/com/threerings/toybox/client/ChatPanel.java
// Path: toybox/src/main/java/com/threerings/toybox/data/ToyBoxCodes.java // public class ToyBoxCodes implements InvocationCodes // { // /** Defines our invocation services group. */ // public static final String TOYBOX_GROUP = "toybox"; // // /** Defines the general ToyBox translation message bundle.*/ // public static final String TOYBOX_MSGS = "toybox"; // // /** An error constant returned by the {@link ToyBoxService}. */ // public static final String ERR_NO_SUCH_GAME = // MessageUtil.qualify(TOYBOX_MSGS, "e.no_such_game"); // // /** An error constant indicating a malformed game definition. */ // public static final String ERR_MALFORMED_GAMEDEF = // MessageUtil.qualify(TOYBOX_MSGS, "e.malformed_gamedef"); // } // // Path: toybox/src/main/java/com/threerings/toybox/util/ToyBoxContext.java // public abstract class ToyBoxContext implements ParlorContext // { // /** // * Returns a reference to the message manager used by the client to // * generate localized messages. // */ // public abstract MessageManager getMessageManager (); // // /** // * Returns a reference to our ToyBox director. // */ // public abstract ToyBoxDirector getToyBoxDirector (); // // /** // * Returns a reference to our frame manager (used for media services). // */ // public abstract FrameManager getFrameManager (); // // /** // * Returns a reference to our key dispatcher. // */ // public abstract KeyDispatcher getKeyDispatcher (); // // /** // * Returns the resource manager which is used to load media resources. // */ // public ResourceManager getResourceManager () // { // return getToyBoxDirector().getResourceManager(); // } // // /** // * Translates the specified message using the specified message bundle. // */ // public String xlate (String bundle, String message) // { // MessageBundle mb = getMessageManager().getBundle(bundle); // return (mb == null) ? message : mb.xlate(message); // } // // /** // * Convenience method to get the username of the currently logged on // * user. Returns null when we're not logged on. // */ // public Name getUsername () // { // BodyObject bobj = (BodyObject)getClient().getClientObject(); // return (bobj == null) ? null : bobj.getVisibleName(); // } // // /** // * Convenience method to load an image from our resource bundles. // */ // public BufferedImage loadImage (String rsrcPath) // { // try { // return getResourceManager().getImageResource(rsrcPath); // } catch (IOException ioe) { // log.warning("Unable to load image resource [path=" + rsrcPath + "].", ioe); // // cope; return an error image of abitrary size // return ImageUtil.createErrorImage(50, 50); // } // } // } // // Path: toybox/src/main/java/com/threerings/toybox/Log.java // public static Logger log = Logger.getLogger("com.threerings.toybox");
import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.JTextPane; import javax.swing.JViewport; import javax.swing.event.AncestorEvent; import javax.swing.event.AncestorListener; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.Style; import javax.swing.text.StyleConstants; import javax.swing.text.StyleContext; import com.samskivert.swing.GroupLayout; import com.samskivert.swing.HGroupLayout; import com.samskivert.swing.VGroupLayout; import com.samskivert.swing.event.AncestorAdapter; import com.samskivert.util.StringUtil; import com.threerings.util.MessageBundle; import com.threerings.crowd.chat.client.ChatDirector; import com.threerings.crowd.chat.client.ChatDisplay; import com.threerings.crowd.chat.data.ChatCodes; import com.threerings.crowd.chat.data.ChatMessage; import com.threerings.crowd.chat.data.SystemMessage; import com.threerings.crowd.chat.data.TellFeedbackMessage; import com.threerings.crowd.chat.data.UserMessage; import com.threerings.crowd.client.OccupantObserver; import com.threerings.crowd.client.PlaceView; import com.threerings.crowd.data.OccupantInfo; import com.threerings.crowd.data.PlaceObject; import com.threerings.toybox.data.ToyBoxCodes; import com.threerings.toybox.util.ToyBoxContext; import static com.threerings.toybox.Log.log;
// // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.client; public class ChatPanel extends JPanel implements ActionListener, ChatDisplay, OccupantObserver, PlaceView { /** The message bundle identifier for chat translations. */ public static final String CHAT_MSGS = "client.chat";
// Path: toybox/src/main/java/com/threerings/toybox/data/ToyBoxCodes.java // public class ToyBoxCodes implements InvocationCodes // { // /** Defines our invocation services group. */ // public static final String TOYBOX_GROUP = "toybox"; // // /** Defines the general ToyBox translation message bundle.*/ // public static final String TOYBOX_MSGS = "toybox"; // // /** An error constant returned by the {@link ToyBoxService}. */ // public static final String ERR_NO_SUCH_GAME = // MessageUtil.qualify(TOYBOX_MSGS, "e.no_such_game"); // // /** An error constant indicating a malformed game definition. */ // public static final String ERR_MALFORMED_GAMEDEF = // MessageUtil.qualify(TOYBOX_MSGS, "e.malformed_gamedef"); // } // // Path: toybox/src/main/java/com/threerings/toybox/util/ToyBoxContext.java // public abstract class ToyBoxContext implements ParlorContext // { // /** // * Returns a reference to the message manager used by the client to // * generate localized messages. // */ // public abstract MessageManager getMessageManager (); // // /** // * Returns a reference to our ToyBox director. // */ // public abstract ToyBoxDirector getToyBoxDirector (); // // /** // * Returns a reference to our frame manager (used for media services). // */ // public abstract FrameManager getFrameManager (); // // /** // * Returns a reference to our key dispatcher. // */ // public abstract KeyDispatcher getKeyDispatcher (); // // /** // * Returns the resource manager which is used to load media resources. // */ // public ResourceManager getResourceManager () // { // return getToyBoxDirector().getResourceManager(); // } // // /** // * Translates the specified message using the specified message bundle. // */ // public String xlate (String bundle, String message) // { // MessageBundle mb = getMessageManager().getBundle(bundle); // return (mb == null) ? message : mb.xlate(message); // } // // /** // * Convenience method to get the username of the currently logged on // * user. Returns null when we're not logged on. // */ // public Name getUsername () // { // BodyObject bobj = (BodyObject)getClient().getClientObject(); // return (bobj == null) ? null : bobj.getVisibleName(); // } // // /** // * Convenience method to load an image from our resource bundles. // */ // public BufferedImage loadImage (String rsrcPath) // { // try { // return getResourceManager().getImageResource(rsrcPath); // } catch (IOException ioe) { // log.warning("Unable to load image resource [path=" + rsrcPath + "].", ioe); // // cope; return an error image of abitrary size // return ImageUtil.createErrorImage(50, 50); // } // } // } // // Path: toybox/src/main/java/com/threerings/toybox/Log.java // public static Logger log = Logger.getLogger("com.threerings.toybox"); // Path: toybox/src/main/java/com/threerings/toybox/client/ChatPanel.java import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.JTextPane; import javax.swing.JViewport; import javax.swing.event.AncestorEvent; import javax.swing.event.AncestorListener; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.Style; import javax.swing.text.StyleConstants; import javax.swing.text.StyleContext; import com.samskivert.swing.GroupLayout; import com.samskivert.swing.HGroupLayout; import com.samskivert.swing.VGroupLayout; import com.samskivert.swing.event.AncestorAdapter; import com.samskivert.util.StringUtil; import com.threerings.util.MessageBundle; import com.threerings.crowd.chat.client.ChatDirector; import com.threerings.crowd.chat.client.ChatDisplay; import com.threerings.crowd.chat.data.ChatCodes; import com.threerings.crowd.chat.data.ChatMessage; import com.threerings.crowd.chat.data.SystemMessage; import com.threerings.crowd.chat.data.TellFeedbackMessage; import com.threerings.crowd.chat.data.UserMessage; import com.threerings.crowd.client.OccupantObserver; import com.threerings.crowd.client.PlaceView; import com.threerings.crowd.data.OccupantInfo; import com.threerings.crowd.data.PlaceObject; import com.threerings.toybox.data.ToyBoxCodes; import com.threerings.toybox.util.ToyBoxContext; import static com.threerings.toybox.Log.log; // // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.client; public class ChatPanel extends JPanel implements ActionListener, ChatDisplay, OccupantObserver, PlaceView { /** The message bundle identifier for chat translations. */ public static final String CHAT_MSGS = "client.chat";
public ChatPanel (ToyBoxContext ctx)
threerings/game-gardens
toybox/src/main/java/com/threerings/toybox/client/ChatPanel.java
// Path: toybox/src/main/java/com/threerings/toybox/data/ToyBoxCodes.java // public class ToyBoxCodes implements InvocationCodes // { // /** Defines our invocation services group. */ // public static final String TOYBOX_GROUP = "toybox"; // // /** Defines the general ToyBox translation message bundle.*/ // public static final String TOYBOX_MSGS = "toybox"; // // /** An error constant returned by the {@link ToyBoxService}. */ // public static final String ERR_NO_SUCH_GAME = // MessageUtil.qualify(TOYBOX_MSGS, "e.no_such_game"); // // /** An error constant indicating a malformed game definition. */ // public static final String ERR_MALFORMED_GAMEDEF = // MessageUtil.qualify(TOYBOX_MSGS, "e.malformed_gamedef"); // } // // Path: toybox/src/main/java/com/threerings/toybox/util/ToyBoxContext.java // public abstract class ToyBoxContext implements ParlorContext // { // /** // * Returns a reference to the message manager used by the client to // * generate localized messages. // */ // public abstract MessageManager getMessageManager (); // // /** // * Returns a reference to our ToyBox director. // */ // public abstract ToyBoxDirector getToyBoxDirector (); // // /** // * Returns a reference to our frame manager (used for media services). // */ // public abstract FrameManager getFrameManager (); // // /** // * Returns a reference to our key dispatcher. // */ // public abstract KeyDispatcher getKeyDispatcher (); // // /** // * Returns the resource manager which is used to load media resources. // */ // public ResourceManager getResourceManager () // { // return getToyBoxDirector().getResourceManager(); // } // // /** // * Translates the specified message using the specified message bundle. // */ // public String xlate (String bundle, String message) // { // MessageBundle mb = getMessageManager().getBundle(bundle); // return (mb == null) ? message : mb.xlate(message); // } // // /** // * Convenience method to get the username of the currently logged on // * user. Returns null when we're not logged on. // */ // public Name getUsername () // { // BodyObject bobj = (BodyObject)getClient().getClientObject(); // return (bobj == null) ? null : bobj.getVisibleName(); // } // // /** // * Convenience method to load an image from our resource bundles. // */ // public BufferedImage loadImage (String rsrcPath) // { // try { // return getResourceManager().getImageResource(rsrcPath); // } catch (IOException ioe) { // log.warning("Unable to load image resource [path=" + rsrcPath + "].", ioe); // // cope; return an error image of abitrary size // return ImageUtil.createErrorImage(50, 50); // } // } // } // // Path: toybox/src/main/java/com/threerings/toybox/Log.java // public static Logger log = Logger.getLogger("com.threerings.toybox");
import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.JTextPane; import javax.swing.JViewport; import javax.swing.event.AncestorEvent; import javax.swing.event.AncestorListener; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.Style; import javax.swing.text.StyleConstants; import javax.swing.text.StyleContext; import com.samskivert.swing.GroupLayout; import com.samskivert.swing.HGroupLayout; import com.samskivert.swing.VGroupLayout; import com.samskivert.swing.event.AncestorAdapter; import com.samskivert.util.StringUtil; import com.threerings.util.MessageBundle; import com.threerings.crowd.chat.client.ChatDirector; import com.threerings.crowd.chat.client.ChatDisplay; import com.threerings.crowd.chat.data.ChatCodes; import com.threerings.crowd.chat.data.ChatMessage; import com.threerings.crowd.chat.data.SystemMessage; import com.threerings.crowd.chat.data.TellFeedbackMessage; import com.threerings.crowd.chat.data.UserMessage; import com.threerings.crowd.client.OccupantObserver; import com.threerings.crowd.client.PlaceView; import com.threerings.crowd.data.OccupantInfo; import com.threerings.crowd.data.PlaceObject; import com.threerings.toybox.data.ToyBoxCodes; import com.threerings.toybox.util.ToyBoxContext; import static com.threerings.toybox.Log.log;
} // documentation inherited from interface ChatDisplay public boolean displayMessage (ChatMessage message, boolean alreadyShown) { if (message instanceof UserMessage) { UserMessage msg = (UserMessage) message; String type = "m.chat_prefix_" + msg.mode; Style msgStyle = _msgStyle; if (msg.localtype == ChatCodes.USER_CHAT_TYPE) { type = "m.chat_prefix_tell"; } if (msg.mode == ChatCodes.BROADCAST_MODE) { msgStyle = _noticeStyle; } String speaker = MessageBundle.tcompose(type, msg.speaker); speaker = _ctx.xlate(CHAT_MSGS, speaker); appendAndScroll(speaker, msg.message, msgStyle); return true; } else if (message instanceof SystemMessage) { appendAndScroll(message.message, _noticeStyle); return true; } else if (message instanceof TellFeedbackMessage) { appendAndScroll(message.message, _feedbackStyle); return true; } else {
// Path: toybox/src/main/java/com/threerings/toybox/data/ToyBoxCodes.java // public class ToyBoxCodes implements InvocationCodes // { // /** Defines our invocation services group. */ // public static final String TOYBOX_GROUP = "toybox"; // // /** Defines the general ToyBox translation message bundle.*/ // public static final String TOYBOX_MSGS = "toybox"; // // /** An error constant returned by the {@link ToyBoxService}. */ // public static final String ERR_NO_SUCH_GAME = // MessageUtil.qualify(TOYBOX_MSGS, "e.no_such_game"); // // /** An error constant indicating a malformed game definition. */ // public static final String ERR_MALFORMED_GAMEDEF = // MessageUtil.qualify(TOYBOX_MSGS, "e.malformed_gamedef"); // } // // Path: toybox/src/main/java/com/threerings/toybox/util/ToyBoxContext.java // public abstract class ToyBoxContext implements ParlorContext // { // /** // * Returns a reference to the message manager used by the client to // * generate localized messages. // */ // public abstract MessageManager getMessageManager (); // // /** // * Returns a reference to our ToyBox director. // */ // public abstract ToyBoxDirector getToyBoxDirector (); // // /** // * Returns a reference to our frame manager (used for media services). // */ // public abstract FrameManager getFrameManager (); // // /** // * Returns a reference to our key dispatcher. // */ // public abstract KeyDispatcher getKeyDispatcher (); // // /** // * Returns the resource manager which is used to load media resources. // */ // public ResourceManager getResourceManager () // { // return getToyBoxDirector().getResourceManager(); // } // // /** // * Translates the specified message using the specified message bundle. // */ // public String xlate (String bundle, String message) // { // MessageBundle mb = getMessageManager().getBundle(bundle); // return (mb == null) ? message : mb.xlate(message); // } // // /** // * Convenience method to get the username of the currently logged on // * user. Returns null when we're not logged on. // */ // public Name getUsername () // { // BodyObject bobj = (BodyObject)getClient().getClientObject(); // return (bobj == null) ? null : bobj.getVisibleName(); // } // // /** // * Convenience method to load an image from our resource bundles. // */ // public BufferedImage loadImage (String rsrcPath) // { // try { // return getResourceManager().getImageResource(rsrcPath); // } catch (IOException ioe) { // log.warning("Unable to load image resource [path=" + rsrcPath + "].", ioe); // // cope; return an error image of abitrary size // return ImageUtil.createErrorImage(50, 50); // } // } // } // // Path: toybox/src/main/java/com/threerings/toybox/Log.java // public static Logger log = Logger.getLogger("com.threerings.toybox"); // Path: toybox/src/main/java/com/threerings/toybox/client/ChatPanel.java import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.JTextPane; import javax.swing.JViewport; import javax.swing.event.AncestorEvent; import javax.swing.event.AncestorListener; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.Style; import javax.swing.text.StyleConstants; import javax.swing.text.StyleContext; import com.samskivert.swing.GroupLayout; import com.samskivert.swing.HGroupLayout; import com.samskivert.swing.VGroupLayout; import com.samskivert.swing.event.AncestorAdapter; import com.samskivert.util.StringUtil; import com.threerings.util.MessageBundle; import com.threerings.crowd.chat.client.ChatDirector; import com.threerings.crowd.chat.client.ChatDisplay; import com.threerings.crowd.chat.data.ChatCodes; import com.threerings.crowd.chat.data.ChatMessage; import com.threerings.crowd.chat.data.SystemMessage; import com.threerings.crowd.chat.data.TellFeedbackMessage; import com.threerings.crowd.chat.data.UserMessage; import com.threerings.crowd.client.OccupantObserver; import com.threerings.crowd.client.PlaceView; import com.threerings.crowd.data.OccupantInfo; import com.threerings.crowd.data.PlaceObject; import com.threerings.toybox.data.ToyBoxCodes; import com.threerings.toybox.util.ToyBoxContext; import static com.threerings.toybox.Log.log; } // documentation inherited from interface ChatDisplay public boolean displayMessage (ChatMessage message, boolean alreadyShown) { if (message instanceof UserMessage) { UserMessage msg = (UserMessage) message; String type = "m.chat_prefix_" + msg.mode; Style msgStyle = _msgStyle; if (msg.localtype == ChatCodes.USER_CHAT_TYPE) { type = "m.chat_prefix_tell"; } if (msg.mode == ChatCodes.BROADCAST_MODE) { msgStyle = _noticeStyle; } String speaker = MessageBundle.tcompose(type, msg.speaker); speaker = _ctx.xlate(CHAT_MSGS, speaker); appendAndScroll(speaker, msg.message, msgStyle); return true; } else if (message instanceof SystemMessage) { appendAndScroll(message.message, _noticeStyle); return true; } else if (message instanceof TellFeedbackMessage) { appendAndScroll(message.message, _feedbackStyle); return true; } else {
log.warning("Received unknown message type", "message", message);
threerings/game-gardens
toybox/src/main/java/com/threerings/toybox/client/ToyBoxApp.java
// Path: toybox/src/main/java/com/threerings/toybox/Log.java // public static Logger log = Logger.getLogger("com.threerings.toybox");
import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.net.URL; import com.threerings.media.FrameManager; import com.threerings.presents.client.Client; import static com.threerings.toybox.Log.log;
// // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.client; /** * The launcher application for all ToyBox games. */ public class ToyBoxApp { public void init (String username, String gameId, String resourceURL) throws IOException { // create a frame _frame = new ToyBoxFrame("...", gameId, username); _framemgr = FrameManager.newInstance(_frame); // create and initialize our client instance _client = new ToyBoxClient(); _client.init(_frame); // configure our resource url ToyBoxDirector toydtr = _client.getContext().getToyBoxDirector(); try { toydtr.setResourceURL(new URL(resourceURL)); } catch (Exception e) {
// Path: toybox/src/main/java/com/threerings/toybox/Log.java // public static Logger log = Logger.getLogger("com.threerings.toybox"); // Path: toybox/src/main/java/com/threerings/toybox/client/ToyBoxApp.java import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.net.URL; import com.threerings.media.FrameManager; import com.threerings.presents.client.Client; import static com.threerings.toybox.Log.log; // // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.client; /** * The launcher application for all ToyBox games. */ public class ToyBoxApp { public void init (String username, String gameId, String resourceURL) throws IOException { // create a frame _frame = new ToyBoxFrame("...", gameId, username); _framemgr = FrameManager.newInstance(_frame); // create and initialize our client instance _client = new ToyBoxClient(); _client.init(_frame); // configure our resource url ToyBoxDirector toydtr = _client.getContext().getToyBoxDirector(); try { toydtr.setResourceURL(new URL(resourceURL)); } catch (Exception e) {
log.warning("Invalid resource_url '" + resourceURL + "': " + e + ".");
threerings/game-gardens
client/src/main/java/com/threerings/gardens/lobby/LobbyPanel.java
// Path: client/src/main/java/com/threerings/gardens/client/ClientContext.java // public interface ClientContext { // // /** Returns our Nexus client. */ // NexusClient client (); // // /** Returns our current auth token. */ // String authToken (); // // /** Replaces the main panel being displayed by the client. */ // void setMainPanel (Widget panel); // } // // Path: core/src/main/java/com/threerings/gardens/user/ChatMessage.java // public class ChatMessage implements Streamable { // // public final String sender; // public final String message; // // public ChatMessage (String sender, String message) { // this.sender = sender; // this.message = message; // } // }
import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.resources.client.CssResource; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.Widget; import react.Connection; import react.Slot; import com.threerings.nexus.distrib.DMap; import com.threerings.gwt.ui.EnterClickAdapter; import com.threerings.gwt.ui.Widgets; import com.threerings.gardens.client.ClientContext; import com.threerings.gardens.user.ChatMessage;
// // Game Gardens - a platform for hosting simple multiplayer Java games // Copyright (c) 2005-2013, Three Rings Design, Inc. - All rights reserved. // https://github.com/threerings/game-gardens/blob/master/LICENSE package com.threerings.gardens.lobby; public class LobbyPanel extends Composite { public LobbyPanel (ClientContext ctx, LobbyObject obj) { _ctx = ctx; _obj = obj; initWidget(_binder.createAndBindUi(this)); // wire up the occupants list display new MapViewer<Integer,String>(_people) { protected Widget createView (Integer id, String name) { return Widgets.newLabel(name); } }.connect(_obj.occupants); // wire up the pending tables display and create button new MapViewer<Integer,LobbyObject.Table>(_penders) { protected Widget createView (Integer id, LobbyObject.Table table) { return new TableView(table); } }.connect(_obj.tables); _newGame.addClickHandler(new ClickHandler() { public void onClick (ClickEvent event) { _obj.svc.get().createTable("test", new GameConfig(), 2); } }); // wire up the chat bits
// Path: client/src/main/java/com/threerings/gardens/client/ClientContext.java // public interface ClientContext { // // /** Returns our Nexus client. */ // NexusClient client (); // // /** Returns our current auth token. */ // String authToken (); // // /** Replaces the main panel being displayed by the client. */ // void setMainPanel (Widget panel); // } // // Path: core/src/main/java/com/threerings/gardens/user/ChatMessage.java // public class ChatMessage implements Streamable { // // public final String sender; // public final String message; // // public ChatMessage (String sender, String message) { // this.sender = sender; // this.message = message; // } // } // Path: client/src/main/java/com/threerings/gardens/lobby/LobbyPanel.java import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.resources.client.CssResource; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.Widget; import react.Connection; import react.Slot; import com.threerings.nexus.distrib.DMap; import com.threerings.gwt.ui.EnterClickAdapter; import com.threerings.gwt.ui.Widgets; import com.threerings.gardens.client.ClientContext; import com.threerings.gardens.user.ChatMessage; // // Game Gardens - a platform for hosting simple multiplayer Java games // Copyright (c) 2005-2013, Three Rings Design, Inc. - All rights reserved. // https://github.com/threerings/game-gardens/blob/master/LICENSE package com.threerings.gardens.lobby; public class LobbyPanel extends Composite { public LobbyPanel (ClientContext ctx, LobbyObject obj) { _ctx = ctx; _obj = obj; initWidget(_binder.createAndBindUi(this)); // wire up the occupants list display new MapViewer<Integer,String>(_people) { protected Widget createView (Integer id, String name) { return Widgets.newLabel(name); } }.connect(_obj.occupants); // wire up the pending tables display and create button new MapViewer<Integer,LobbyObject.Table>(_penders) { protected Widget createView (Integer id, LobbyObject.Table table) { return new TableView(table); } }.connect(_obj.tables); _newGame.addClickHandler(new ClickHandler() { public void onClick (ClickEvent event) { _obj.svc.get().createTable("test", new GameConfig(), 2); } }); // wire up the chat bits
_obj.chat.connect(new Slot<ChatMessage>() {
kontalk/tigase-extension
src/main/java/org/kontalk/xmppserver/registration/AbstractVerificationRepository.java
// Path: src/main/java/org/kontalk/xmppserver/util/Utils.java // public class Utils { // // public static String generateRandomNumericString(int length) { // StringBuilder buffer = new StringBuilder(); // final String characters = "1234567890"; // // int charactersLength = characters.length(); // // for (int i = 0; i < length; i++) { // double index = Math.random() * charactersLength; // buffer.append(characters.charAt((int) index)); // } // return buffer.toString(); // } // // // directly from OpenJDK 8 DatatypeConverterImpl // public static byte[] parseHexBinary(String s) { // int len = s.length(); // if (len % 2 != 0) { // throw new IllegalArgumentException("hexBinary needs to be even-length: " + s); // } // else { // byte[] out = new byte[len / 2]; // // for(int i = 0; i < len; i += 2) { // int h = hexToBin(s.charAt(i)); // int l = hexToBin(s.charAt(i + 1)); // if (h == -1 || l == -1) { // throw new IllegalArgumentException("contains illegal character for hexBinary: " + s); // } // // out[i / 2] = (byte)(h * 16 + l); // } // // return out; // } // } // // // directly from OpenJDK 8 DatatypeConverterImpl // private static int hexToBin(char ch) { // if ('0' <= ch && ch <= '9') { // return ch - 48; // } // else if ('A' <= ch && ch <= 'F') { // return ch - 65 + 10; // } // else { // return 'a' <= ch && ch <= 'f' ? ch - 97 + 10 : -1; // } // } // // }
import org.kontalk.xmppserver.util.Utils;
/* * Kontalk XMPP Tigase extension * Copyright (C) 2017 Kontalk Devteam <devteam@kontalk.org> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kontalk.xmppserver.registration; /** * Interface to a validation code repository. * @author Daniele Ricci */ public abstract class AbstractVerificationRepository implements VerificationRepository { protected String verificationCode() {
// Path: src/main/java/org/kontalk/xmppserver/util/Utils.java // public class Utils { // // public static String generateRandomNumericString(int length) { // StringBuilder buffer = new StringBuilder(); // final String characters = "1234567890"; // // int charactersLength = characters.length(); // // for (int i = 0; i < length; i++) { // double index = Math.random() * charactersLength; // buffer.append(characters.charAt((int) index)); // } // return buffer.toString(); // } // // // directly from OpenJDK 8 DatatypeConverterImpl // public static byte[] parseHexBinary(String s) { // int len = s.length(); // if (len % 2 != 0) { // throw new IllegalArgumentException("hexBinary needs to be even-length: " + s); // } // else { // byte[] out = new byte[len / 2]; // // for(int i = 0; i < len; i += 2) { // int h = hexToBin(s.charAt(i)); // int l = hexToBin(s.charAt(i + 1)); // if (h == -1 || l == -1) { // throw new IllegalArgumentException("contains illegal character for hexBinary: " + s); // } // // out[i / 2] = (byte)(h * 16 + l); // } // // return out; // } // } // // // directly from OpenJDK 8 DatatypeConverterImpl // private static int hexToBin(char ch) { // if ('0' <= ch && ch <= '9') { // return ch - 48; // } // else if ('A' <= ch && ch <= 'F') { // return ch - 65 + 10; // } // else { // return 'a' <= ch && ch <= 'f' ? ch - 97 + 10 : -1; // } // } // // } // Path: src/main/java/org/kontalk/xmppserver/registration/AbstractVerificationRepository.java import org.kontalk.xmppserver.util.Utils; /* * Kontalk XMPP Tigase extension * Copyright (C) 2017 Kontalk Devteam <devteam@kontalk.org> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kontalk.xmppserver.registration; /** * Interface to a validation code repository. * @author Daniele Ricci */ public abstract class AbstractVerificationRepository implements VerificationRepository { protected String verificationCode() {
return Utils.generateRandomNumericString(VERIFICATION_CODE_LENGTH);
kontalk/tigase-extension
src/main/java/org/kontalk/xmppserver/pgp/PGPUtils.java
// Path: src/main/java/org/kontalk/xmppserver/Security.java // public class Security { // // public static final String PROVIDER = "BC"; // // private static Security instance; // // private Security() { // java.security.Security.insertProviderAt(new BouncyCastleProvider(), 1); // } // // public static void init() { // if (instance == null) { // instance = new Security(); // } // } // // }
import org.bouncycastle.openpgp.*; import org.bouncycastle.openpgp.operator.bc.BcKeyFingerprintCalculator; import org.bouncycastle.openpgp.operator.bc.BcPGPContentVerifierBuilderProvider; import org.bouncycastle.openpgp.operator.jcajce.JcaPGPKeyConverter; import org.kontalk.xmppserver.Security; import tigase.xmpp.BareJID; import java.io.IOException; import java.io.InputStream; import java.security.PublicKey; import java.util.*;
/* * Kontalk XMPP Tigase extension * Copyright (C) 2017 Kontalk Devteam <devteam@kontalk.org> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kontalk.xmppserver.pgp; /** * PGP related utilities. * @author Daniele Ricci */ public class PGPUtils { static {
// Path: src/main/java/org/kontalk/xmppserver/Security.java // public class Security { // // public static final String PROVIDER = "BC"; // // private static Security instance; // // private Security() { // java.security.Security.insertProviderAt(new BouncyCastleProvider(), 1); // } // // public static void init() { // if (instance == null) { // instance = new Security(); // } // } // // } // Path: src/main/java/org/kontalk/xmppserver/pgp/PGPUtils.java import org.bouncycastle.openpgp.*; import org.bouncycastle.openpgp.operator.bc.BcKeyFingerprintCalculator; import org.bouncycastle.openpgp.operator.bc.BcPGPContentVerifierBuilderProvider; import org.bouncycastle.openpgp.operator.jcajce.JcaPGPKeyConverter; import org.kontalk.xmppserver.Security; import tigase.xmpp.BareJID; import java.io.IOException; import java.io.InputStream; import java.security.PublicKey; import java.util.*; /* * Kontalk XMPP Tigase extension * Copyright (C) 2017 Kontalk Devteam <devteam@kontalk.org> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kontalk.xmppserver.pgp; /** * PGP related utilities. * @author Daniele Ricci */ public class PGPUtils { static {
Security.init();
kontalk/tigase-extension
src/main/java/org/kontalk/xmppserver/presence/PublicKeyPresence.java
// Path: src/main/java/org/kontalk/xmppserver/auth/KontalkAuth.java // public class KontalkAuth { // private static final String NODE_AUTH = "kontalk/auth"; // private static final String KEY_FINGERPRINT = "fingerprint"; // // private static UserRepository userRepository = null; // // private KontalkAuth() {} // // public static UserRepository getUserRepository() throws TigaseDBException { // if (userRepository == null) { // try { // userRepository = RepositoryFactory.getUserRepository(null, null, null); // } // catch (Exception e) { // throw new TigaseDBException("Unable to get user repository instance", e); // } // } // return userRepository; // } // // public static String getUserFingerprint(XMPPResourceConnection session) // throws TigaseDBException, NotAuthorizedException { // return session.getData(NODE_AUTH, KEY_FINGERPRINT, null); // } // // public static String getUserFingerprint(XMPPResourceConnection session, BareJID jid) // throws TigaseDBException { // return getUserRepository().getData(jid, NODE_AUTH, KEY_FINGERPRINT, null); // } // // public static void setUserFingerprint(XMPPResourceConnection session, BareJID jid, String fingerprint) // throws TigaseDBException { // getUserRepository().setData(jid, NODE_AUTH, KEY_FINGERPRINT, fingerprint); // } // // public static KontalkKeyring getKeyring(XMPPResourceConnection session) throws IOException, PGPException { // return KontalkKeyring.getInstance(session.getDomainAsJID().toString()); // } // // public static String toUserId(String phone) { // return sha1(phone); // } // // public static JID toJID(String phone, String domain) { // return JID.jidInstanceNS(toUserId(phone), domain, null); // } // // public static BareJID toBareJID(String phone, String domain) { // return BareJID.bareJIDInstanceNS(toUserId(phone), domain); // } // // private static String sha1(String text) { // try { // MessageDigest md; // md = MessageDigest.getInstance("SHA-1"); // md.update(text.getBytes(), 0, text.length()); // // byte[] digest = md.digest(); // return Hex.toHexString(digest); // } // catch (NoSuchAlgorithmException e) { // // no SHA-1?? WWWHHHHAAAAAATTTT???!?!?!?!?! // throw new RuntimeException("no SHA-1 available. What the crap of a runtime do you have?"); // } // } // // // // } // // Path: src/main/java/org/kontalk/xmppserver/presence/PresenceSubscribePublicKey.java // public static final String ELEM_NAME = "pubkey"; // // Path: src/main/java/org/kontalk/xmppserver/presence/PresenceSubscribePublicKey.java // public static final String XMLNS = "urn:xmpp:pubkey:2";
import static org.kontalk.xmppserver.presence.PresenceSubscribePublicKey.ELEM_NAME; import static org.kontalk.xmppserver.presence.PresenceSubscribePublicKey.XMLNS; import org.kontalk.xmppserver.auth.KontalkAuth; import tigase.db.TigaseDBException; import tigase.db.UserNotFoundException; import tigase.server.Packet; import tigase.xml.Element; import tigase.xmpp.NotAuthorizedException; import tigase.xmpp.XMPPResourceConnection; import tigase.xmpp.impl.PresenceState; import java.util.Queue; import java.util.logging.Level; import java.util.logging.Logger;
/* * Kontalk XMPP Tigase extension * Copyright (C) 2017 Kontalk Devteam <devteam@kontalk.org> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kontalk.xmppserver.presence; /** * A presence extender for public key fingerprint element. * @author Daniele Ricci */ public class PublicKeyPresence implements PresenceState.ExtendedPresenceProcessorIfc { private static final Logger log = Logger.getLogger(PublicKeyPresence.class.getName()); @Override public Element extend(XMPPResourceConnection session, Queue<Packet> results) { if (session != null) { try {
// Path: src/main/java/org/kontalk/xmppserver/auth/KontalkAuth.java // public class KontalkAuth { // private static final String NODE_AUTH = "kontalk/auth"; // private static final String KEY_FINGERPRINT = "fingerprint"; // // private static UserRepository userRepository = null; // // private KontalkAuth() {} // // public static UserRepository getUserRepository() throws TigaseDBException { // if (userRepository == null) { // try { // userRepository = RepositoryFactory.getUserRepository(null, null, null); // } // catch (Exception e) { // throw new TigaseDBException("Unable to get user repository instance", e); // } // } // return userRepository; // } // // public static String getUserFingerprint(XMPPResourceConnection session) // throws TigaseDBException, NotAuthorizedException { // return session.getData(NODE_AUTH, KEY_FINGERPRINT, null); // } // // public static String getUserFingerprint(XMPPResourceConnection session, BareJID jid) // throws TigaseDBException { // return getUserRepository().getData(jid, NODE_AUTH, KEY_FINGERPRINT, null); // } // // public static void setUserFingerprint(XMPPResourceConnection session, BareJID jid, String fingerprint) // throws TigaseDBException { // getUserRepository().setData(jid, NODE_AUTH, KEY_FINGERPRINT, fingerprint); // } // // public static KontalkKeyring getKeyring(XMPPResourceConnection session) throws IOException, PGPException { // return KontalkKeyring.getInstance(session.getDomainAsJID().toString()); // } // // public static String toUserId(String phone) { // return sha1(phone); // } // // public static JID toJID(String phone, String domain) { // return JID.jidInstanceNS(toUserId(phone), domain, null); // } // // public static BareJID toBareJID(String phone, String domain) { // return BareJID.bareJIDInstanceNS(toUserId(phone), domain); // } // // private static String sha1(String text) { // try { // MessageDigest md; // md = MessageDigest.getInstance("SHA-1"); // md.update(text.getBytes(), 0, text.length()); // // byte[] digest = md.digest(); // return Hex.toHexString(digest); // } // catch (NoSuchAlgorithmException e) { // // no SHA-1?? WWWHHHHAAAAAATTTT???!?!?!?!?! // throw new RuntimeException("no SHA-1 available. What the crap of a runtime do you have?"); // } // } // // // // } // // Path: src/main/java/org/kontalk/xmppserver/presence/PresenceSubscribePublicKey.java // public static final String ELEM_NAME = "pubkey"; // // Path: src/main/java/org/kontalk/xmppserver/presence/PresenceSubscribePublicKey.java // public static final String XMLNS = "urn:xmpp:pubkey:2"; // Path: src/main/java/org/kontalk/xmppserver/presence/PublicKeyPresence.java import static org.kontalk.xmppserver.presence.PresenceSubscribePublicKey.ELEM_NAME; import static org.kontalk.xmppserver.presence.PresenceSubscribePublicKey.XMLNS; import org.kontalk.xmppserver.auth.KontalkAuth; import tigase.db.TigaseDBException; import tigase.db.UserNotFoundException; import tigase.server.Packet; import tigase.xml.Element; import tigase.xmpp.NotAuthorizedException; import tigase.xmpp.XMPPResourceConnection; import tigase.xmpp.impl.PresenceState; import java.util.Queue; import java.util.logging.Level; import java.util.logging.Logger; /* * Kontalk XMPP Tigase extension * Copyright (C) 2017 Kontalk Devteam <devteam@kontalk.org> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kontalk.xmppserver.presence; /** * A presence extender for public key fingerprint element. * @author Daniele Ricci */ public class PublicKeyPresence implements PresenceState.ExtendedPresenceProcessorIfc { private static final Logger log = Logger.getLogger(PublicKeyPresence.class.getName()); @Override public Element extend(XMPPResourceConnection session, Queue<Packet> results) { if (session != null) { try {
String fingerprint = KontalkAuth.getUserFingerprint(session);
kontalk/tigase-extension
src/main/java/org/kontalk/xmppserver/presence/PublicKeyPresence.java
// Path: src/main/java/org/kontalk/xmppserver/auth/KontalkAuth.java // public class KontalkAuth { // private static final String NODE_AUTH = "kontalk/auth"; // private static final String KEY_FINGERPRINT = "fingerprint"; // // private static UserRepository userRepository = null; // // private KontalkAuth() {} // // public static UserRepository getUserRepository() throws TigaseDBException { // if (userRepository == null) { // try { // userRepository = RepositoryFactory.getUserRepository(null, null, null); // } // catch (Exception e) { // throw new TigaseDBException("Unable to get user repository instance", e); // } // } // return userRepository; // } // // public static String getUserFingerprint(XMPPResourceConnection session) // throws TigaseDBException, NotAuthorizedException { // return session.getData(NODE_AUTH, KEY_FINGERPRINT, null); // } // // public static String getUserFingerprint(XMPPResourceConnection session, BareJID jid) // throws TigaseDBException { // return getUserRepository().getData(jid, NODE_AUTH, KEY_FINGERPRINT, null); // } // // public static void setUserFingerprint(XMPPResourceConnection session, BareJID jid, String fingerprint) // throws TigaseDBException { // getUserRepository().setData(jid, NODE_AUTH, KEY_FINGERPRINT, fingerprint); // } // // public static KontalkKeyring getKeyring(XMPPResourceConnection session) throws IOException, PGPException { // return KontalkKeyring.getInstance(session.getDomainAsJID().toString()); // } // // public static String toUserId(String phone) { // return sha1(phone); // } // // public static JID toJID(String phone, String domain) { // return JID.jidInstanceNS(toUserId(phone), domain, null); // } // // public static BareJID toBareJID(String phone, String domain) { // return BareJID.bareJIDInstanceNS(toUserId(phone), domain); // } // // private static String sha1(String text) { // try { // MessageDigest md; // md = MessageDigest.getInstance("SHA-1"); // md.update(text.getBytes(), 0, text.length()); // // byte[] digest = md.digest(); // return Hex.toHexString(digest); // } // catch (NoSuchAlgorithmException e) { // // no SHA-1?? WWWHHHHAAAAAATTTT???!?!?!?!?! // throw new RuntimeException("no SHA-1 available. What the crap of a runtime do you have?"); // } // } // // // // } // // Path: src/main/java/org/kontalk/xmppserver/presence/PresenceSubscribePublicKey.java // public static final String ELEM_NAME = "pubkey"; // // Path: src/main/java/org/kontalk/xmppserver/presence/PresenceSubscribePublicKey.java // public static final String XMLNS = "urn:xmpp:pubkey:2";
import static org.kontalk.xmppserver.presence.PresenceSubscribePublicKey.ELEM_NAME; import static org.kontalk.xmppserver.presence.PresenceSubscribePublicKey.XMLNS; import org.kontalk.xmppserver.auth.KontalkAuth; import tigase.db.TigaseDBException; import tigase.db.UserNotFoundException; import tigase.server.Packet; import tigase.xml.Element; import tigase.xmpp.NotAuthorizedException; import tigase.xmpp.XMPPResourceConnection; import tigase.xmpp.impl.PresenceState; import java.util.Queue; import java.util.logging.Level; import java.util.logging.Logger;
/* * Kontalk XMPP Tigase extension * Copyright (C) 2017 Kontalk Devteam <devteam@kontalk.org> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kontalk.xmppserver.presence; /** * A presence extender for public key fingerprint element. * @author Daniele Ricci */ public class PublicKeyPresence implements PresenceState.ExtendedPresenceProcessorIfc { private static final Logger log = Logger.getLogger(PublicKeyPresence.class.getName()); @Override public Element extend(XMPPResourceConnection session, Queue<Packet> results) { if (session != null) { try { String fingerprint = KontalkAuth.getUserFingerprint(session); if (fingerprint != null) {
// Path: src/main/java/org/kontalk/xmppserver/auth/KontalkAuth.java // public class KontalkAuth { // private static final String NODE_AUTH = "kontalk/auth"; // private static final String KEY_FINGERPRINT = "fingerprint"; // // private static UserRepository userRepository = null; // // private KontalkAuth() {} // // public static UserRepository getUserRepository() throws TigaseDBException { // if (userRepository == null) { // try { // userRepository = RepositoryFactory.getUserRepository(null, null, null); // } // catch (Exception e) { // throw new TigaseDBException("Unable to get user repository instance", e); // } // } // return userRepository; // } // // public static String getUserFingerprint(XMPPResourceConnection session) // throws TigaseDBException, NotAuthorizedException { // return session.getData(NODE_AUTH, KEY_FINGERPRINT, null); // } // // public static String getUserFingerprint(XMPPResourceConnection session, BareJID jid) // throws TigaseDBException { // return getUserRepository().getData(jid, NODE_AUTH, KEY_FINGERPRINT, null); // } // // public static void setUserFingerprint(XMPPResourceConnection session, BareJID jid, String fingerprint) // throws TigaseDBException { // getUserRepository().setData(jid, NODE_AUTH, KEY_FINGERPRINT, fingerprint); // } // // public static KontalkKeyring getKeyring(XMPPResourceConnection session) throws IOException, PGPException { // return KontalkKeyring.getInstance(session.getDomainAsJID().toString()); // } // // public static String toUserId(String phone) { // return sha1(phone); // } // // public static JID toJID(String phone, String domain) { // return JID.jidInstanceNS(toUserId(phone), domain, null); // } // // public static BareJID toBareJID(String phone, String domain) { // return BareJID.bareJIDInstanceNS(toUserId(phone), domain); // } // // private static String sha1(String text) { // try { // MessageDigest md; // md = MessageDigest.getInstance("SHA-1"); // md.update(text.getBytes(), 0, text.length()); // // byte[] digest = md.digest(); // return Hex.toHexString(digest); // } // catch (NoSuchAlgorithmException e) { // // no SHA-1?? WWWHHHHAAAAAATTTT???!?!?!?!?! // throw new RuntimeException("no SHA-1 available. What the crap of a runtime do you have?"); // } // } // // // // } // // Path: src/main/java/org/kontalk/xmppserver/presence/PresenceSubscribePublicKey.java // public static final String ELEM_NAME = "pubkey"; // // Path: src/main/java/org/kontalk/xmppserver/presence/PresenceSubscribePublicKey.java // public static final String XMLNS = "urn:xmpp:pubkey:2"; // Path: src/main/java/org/kontalk/xmppserver/presence/PublicKeyPresence.java import static org.kontalk.xmppserver.presence.PresenceSubscribePublicKey.ELEM_NAME; import static org.kontalk.xmppserver.presence.PresenceSubscribePublicKey.XMLNS; import org.kontalk.xmppserver.auth.KontalkAuth; import tigase.db.TigaseDBException; import tigase.db.UserNotFoundException; import tigase.server.Packet; import tigase.xml.Element; import tigase.xmpp.NotAuthorizedException; import tigase.xmpp.XMPPResourceConnection; import tigase.xmpp.impl.PresenceState; import java.util.Queue; import java.util.logging.Level; import java.util.logging.Logger; /* * Kontalk XMPP Tigase extension * Copyright (C) 2017 Kontalk Devteam <devteam@kontalk.org> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kontalk.xmppserver.presence; /** * A presence extender for public key fingerprint element. * @author Daniele Ricci */ public class PublicKeyPresence implements PresenceState.ExtendedPresenceProcessorIfc { private static final Logger log = Logger.getLogger(PublicKeyPresence.class.getName()); @Override public Element extend(XMPPResourceConnection session, Queue<Packet> results) { if (session != null) { try { String fingerprint = KontalkAuth.getUserFingerprint(session); if (fingerprint != null) {
Element pubkey = new Element(ELEM_NAME, new String[] { Packet.XMLNS_ATT }, new String[] { XMLNS });
kontalk/tigase-extension
src/main/java/org/kontalk/xmppserver/presence/PublicKeyPresence.java
// Path: src/main/java/org/kontalk/xmppserver/auth/KontalkAuth.java // public class KontalkAuth { // private static final String NODE_AUTH = "kontalk/auth"; // private static final String KEY_FINGERPRINT = "fingerprint"; // // private static UserRepository userRepository = null; // // private KontalkAuth() {} // // public static UserRepository getUserRepository() throws TigaseDBException { // if (userRepository == null) { // try { // userRepository = RepositoryFactory.getUserRepository(null, null, null); // } // catch (Exception e) { // throw new TigaseDBException("Unable to get user repository instance", e); // } // } // return userRepository; // } // // public static String getUserFingerprint(XMPPResourceConnection session) // throws TigaseDBException, NotAuthorizedException { // return session.getData(NODE_AUTH, KEY_FINGERPRINT, null); // } // // public static String getUserFingerprint(XMPPResourceConnection session, BareJID jid) // throws TigaseDBException { // return getUserRepository().getData(jid, NODE_AUTH, KEY_FINGERPRINT, null); // } // // public static void setUserFingerprint(XMPPResourceConnection session, BareJID jid, String fingerprint) // throws TigaseDBException { // getUserRepository().setData(jid, NODE_AUTH, KEY_FINGERPRINT, fingerprint); // } // // public static KontalkKeyring getKeyring(XMPPResourceConnection session) throws IOException, PGPException { // return KontalkKeyring.getInstance(session.getDomainAsJID().toString()); // } // // public static String toUserId(String phone) { // return sha1(phone); // } // // public static JID toJID(String phone, String domain) { // return JID.jidInstanceNS(toUserId(phone), domain, null); // } // // public static BareJID toBareJID(String phone, String domain) { // return BareJID.bareJIDInstanceNS(toUserId(phone), domain); // } // // private static String sha1(String text) { // try { // MessageDigest md; // md = MessageDigest.getInstance("SHA-1"); // md.update(text.getBytes(), 0, text.length()); // // byte[] digest = md.digest(); // return Hex.toHexString(digest); // } // catch (NoSuchAlgorithmException e) { // // no SHA-1?? WWWHHHHAAAAAATTTT???!?!?!?!?! // throw new RuntimeException("no SHA-1 available. What the crap of a runtime do you have?"); // } // } // // // // } // // Path: src/main/java/org/kontalk/xmppserver/presence/PresenceSubscribePublicKey.java // public static final String ELEM_NAME = "pubkey"; // // Path: src/main/java/org/kontalk/xmppserver/presence/PresenceSubscribePublicKey.java // public static final String XMLNS = "urn:xmpp:pubkey:2";
import static org.kontalk.xmppserver.presence.PresenceSubscribePublicKey.ELEM_NAME; import static org.kontalk.xmppserver.presence.PresenceSubscribePublicKey.XMLNS; import org.kontalk.xmppserver.auth.KontalkAuth; import tigase.db.TigaseDBException; import tigase.db.UserNotFoundException; import tigase.server.Packet; import tigase.xml.Element; import tigase.xmpp.NotAuthorizedException; import tigase.xmpp.XMPPResourceConnection; import tigase.xmpp.impl.PresenceState; import java.util.Queue; import java.util.logging.Level; import java.util.logging.Logger;
/* * Kontalk XMPP Tigase extension * Copyright (C) 2017 Kontalk Devteam <devteam@kontalk.org> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kontalk.xmppserver.presence; /** * A presence extender for public key fingerprint element. * @author Daniele Ricci */ public class PublicKeyPresence implements PresenceState.ExtendedPresenceProcessorIfc { private static final Logger log = Logger.getLogger(PublicKeyPresence.class.getName()); @Override public Element extend(XMPPResourceConnection session, Queue<Packet> results) { if (session != null) { try { String fingerprint = KontalkAuth.getUserFingerprint(session); if (fingerprint != null) {
// Path: src/main/java/org/kontalk/xmppserver/auth/KontalkAuth.java // public class KontalkAuth { // private static final String NODE_AUTH = "kontalk/auth"; // private static final String KEY_FINGERPRINT = "fingerprint"; // // private static UserRepository userRepository = null; // // private KontalkAuth() {} // // public static UserRepository getUserRepository() throws TigaseDBException { // if (userRepository == null) { // try { // userRepository = RepositoryFactory.getUserRepository(null, null, null); // } // catch (Exception e) { // throw new TigaseDBException("Unable to get user repository instance", e); // } // } // return userRepository; // } // // public static String getUserFingerprint(XMPPResourceConnection session) // throws TigaseDBException, NotAuthorizedException { // return session.getData(NODE_AUTH, KEY_FINGERPRINT, null); // } // // public static String getUserFingerprint(XMPPResourceConnection session, BareJID jid) // throws TigaseDBException { // return getUserRepository().getData(jid, NODE_AUTH, KEY_FINGERPRINT, null); // } // // public static void setUserFingerprint(XMPPResourceConnection session, BareJID jid, String fingerprint) // throws TigaseDBException { // getUserRepository().setData(jid, NODE_AUTH, KEY_FINGERPRINT, fingerprint); // } // // public static KontalkKeyring getKeyring(XMPPResourceConnection session) throws IOException, PGPException { // return KontalkKeyring.getInstance(session.getDomainAsJID().toString()); // } // // public static String toUserId(String phone) { // return sha1(phone); // } // // public static JID toJID(String phone, String domain) { // return JID.jidInstanceNS(toUserId(phone), domain, null); // } // // public static BareJID toBareJID(String phone, String domain) { // return BareJID.bareJIDInstanceNS(toUserId(phone), domain); // } // // private static String sha1(String text) { // try { // MessageDigest md; // md = MessageDigest.getInstance("SHA-1"); // md.update(text.getBytes(), 0, text.length()); // // byte[] digest = md.digest(); // return Hex.toHexString(digest); // } // catch (NoSuchAlgorithmException e) { // // no SHA-1?? WWWHHHHAAAAAATTTT???!?!?!?!?! // throw new RuntimeException("no SHA-1 available. What the crap of a runtime do you have?"); // } // } // // // // } // // Path: src/main/java/org/kontalk/xmppserver/presence/PresenceSubscribePublicKey.java // public static final String ELEM_NAME = "pubkey"; // // Path: src/main/java/org/kontalk/xmppserver/presence/PresenceSubscribePublicKey.java // public static final String XMLNS = "urn:xmpp:pubkey:2"; // Path: src/main/java/org/kontalk/xmppserver/presence/PublicKeyPresence.java import static org.kontalk.xmppserver.presence.PresenceSubscribePublicKey.ELEM_NAME; import static org.kontalk.xmppserver.presence.PresenceSubscribePublicKey.XMLNS; import org.kontalk.xmppserver.auth.KontalkAuth; import tigase.db.TigaseDBException; import tigase.db.UserNotFoundException; import tigase.server.Packet; import tigase.xml.Element; import tigase.xmpp.NotAuthorizedException; import tigase.xmpp.XMPPResourceConnection; import tigase.xmpp.impl.PresenceState; import java.util.Queue; import java.util.logging.Level; import java.util.logging.Logger; /* * Kontalk XMPP Tigase extension * Copyright (C) 2017 Kontalk Devteam <devteam@kontalk.org> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kontalk.xmppserver.presence; /** * A presence extender for public key fingerprint element. * @author Daniele Ricci */ public class PublicKeyPresence implements PresenceState.ExtendedPresenceProcessorIfc { private static final Logger log = Logger.getLogger(PublicKeyPresence.class.getName()); @Override public Element extend(XMPPResourceConnection session, Queue<Packet> results) { if (session != null) { try { String fingerprint = KontalkAuth.getUserFingerprint(session); if (fingerprint != null) {
Element pubkey = new Element(ELEM_NAME, new String[] { Packet.XMLNS_ATT }, new String[] { XMLNS });
kontalk/tigase-extension
src/main/java/org/kontalk/xmppserver/KontalkKeyring.java
// Path: src/main/java/org/kontalk/xmppserver/util/Utils.java // public class Utils { // // public static String generateRandomNumericString(int length) { // StringBuilder buffer = new StringBuilder(); // final String characters = "1234567890"; // // int charactersLength = characters.length(); // // for (int i = 0; i < length; i++) { // double index = Math.random() * charactersLength; // buffer.append(characters.charAt((int) index)); // } // return buffer.toString(); // } // // // directly from OpenJDK 8 DatatypeConverterImpl // public static byte[] parseHexBinary(String s) { // int len = s.length(); // if (len % 2 != 0) { // throw new IllegalArgumentException("hexBinary needs to be even-length: " + s); // } // else { // byte[] out = new byte[len / 2]; // // for(int i = 0; i < len; i += 2) { // int h = hexToBin(s.charAt(i)); // int l = hexToBin(s.charAt(i + 1)); // if (h == -1 || l == -1) { // throw new IllegalArgumentException("contains illegal character for hexBinary: " + s); // } // // out[i / 2] = (byte)(h * 16 + l); // } // // return out; // } // } // // // directly from OpenJDK 8 DatatypeConverterImpl // private static int hexToBin(char ch) { // if ('0' <= ch && ch <= '9') { // return ch - 48; // } // else if ('A' <= ch && ch <= 'F') { // return ch - 65 + 10; // } // else { // return 'a' <= ch && ch <= 'f' ? ch - 97 + 10 : -1; // } // } // // }
import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPPublicKey; import org.bouncycastle.openpgp.PGPPublicKeyRing; import org.kontalk.xmppserver.pgp.*; import org.kontalk.xmppserver.util.Utils; import tigase.xmpp.BareJID; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.Map;
/* * Kontalk XMPP Tigase extension * Copyright (C) 2017 Kontalk Devteam <devteam@kontalk.org> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kontalk.xmppserver; /** * Kontalk keyring singleton. * @author Daniele Ricci */ public class KontalkKeyring { private static final Map<String, KontalkKeyring> instances = new HashMap<>(); private final String domain; private final PGPLocalKeyring keyring; private final PGPPublicKey secretMasterKey; private final PGPPublicKeyRing secretPublicKeyring; private final String secretKeyFingerprint; /** Use {@link #getInstance(String)} instead. */ private KontalkKeyring(String domain, String secretPrivateKeyFile, String secretPublicKeyFile, String keyring) throws IOException, PGPException { this.domain = domain; this.keyring = new BerkeleyPGPLocalKeyring(keyring); // import into GnuPG GnuPGInterface.getInstance().importKey(secretPrivateKeyFile); GnuPGInterface.getInstance().importKey(secretPublicKeyFile); // calculate secret key fingerprint for signing secretPublicKeyring = PGPUtils.readPublicKeyring(new FileInputStream(secretPublicKeyFile)); secretMasterKey = PGPUtils.getMasterKey(secretPublicKeyring); secretKeyFingerprint = PGPUtils.getFingerprint(secretMasterKey); } public PGPPublicKeyRing getSecretPublicKey() { return secretPublicKeyring; } /** * Authenticates the given public key in Kontalk. * @param keyData public key data to check * @return a user instance with JID and public key fingerprint. */ public KontalkUser authenticate(byte[] keyData) throws IOException, PGPException { PGPPublicKeyRing key = keyring.importKey(keyData); BareJID jid = validate(key); return jid != null ? new KontalkUser(jid, PGPUtils.getFingerprint(key)) : null; } /** * Post-authentication step: verifies that the given user is allowed to * login by checking the old key. * @param user user object returned by {@link #authenticate} * @param oldFingerprint old key fingerprint, null if none present * @return true if the new key can be accepted. */ public boolean postAuthenticate(KontalkUser user, String oldFingerprint) throws IOException, PGPException { if (oldFingerprint == null || oldFingerprint.equalsIgnoreCase(user.getFingerprint())) { // no old fingerprint or same fingerprint -- access granted return true; } PGPPublicKeyRing oldKey = keyring.getKey(oldFingerprint); if (oldKey != null && validate(oldKey) != null) { // old key is still valid, check for timestamp PGPPublicKeyRing newKey = keyring.getKey(user.getFingerprint()); if (newKey != null && PGPUtils.isKeyNewer(oldKey, newKey)) { return true; } } return false; } /** * Imports the given revoked key and checks if fingerprint matches and * key is revoked correctly. */ public boolean revoked(byte[] keyData, String fingerprint) throws IOException, PGPException { PGPPublicKeyRing key = keyring.importKey(keyData); PGPPublicKey masterKey = PGPUtils.getMasterKey(key); return masterKey != null && PGPUtils.isRevoked(masterKey) &&
// Path: src/main/java/org/kontalk/xmppserver/util/Utils.java // public class Utils { // // public static String generateRandomNumericString(int length) { // StringBuilder buffer = new StringBuilder(); // final String characters = "1234567890"; // // int charactersLength = characters.length(); // // for (int i = 0; i < length; i++) { // double index = Math.random() * charactersLength; // buffer.append(characters.charAt((int) index)); // } // return buffer.toString(); // } // // // directly from OpenJDK 8 DatatypeConverterImpl // public static byte[] parseHexBinary(String s) { // int len = s.length(); // if (len % 2 != 0) { // throw new IllegalArgumentException("hexBinary needs to be even-length: " + s); // } // else { // byte[] out = new byte[len / 2]; // // for(int i = 0; i < len; i += 2) { // int h = hexToBin(s.charAt(i)); // int l = hexToBin(s.charAt(i + 1)); // if (h == -1 || l == -1) { // throw new IllegalArgumentException("contains illegal character for hexBinary: " + s); // } // // out[i / 2] = (byte)(h * 16 + l); // } // // return out; // } // } // // // directly from OpenJDK 8 DatatypeConverterImpl // private static int hexToBin(char ch) { // if ('0' <= ch && ch <= '9') { // return ch - 48; // } // else if ('A' <= ch && ch <= 'F') { // return ch - 65 + 10; // } // else { // return 'a' <= ch && ch <= 'f' ? ch - 97 + 10 : -1; // } // } // // } // Path: src/main/java/org/kontalk/xmppserver/KontalkKeyring.java import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPPublicKey; import org.bouncycastle.openpgp.PGPPublicKeyRing; import org.kontalk.xmppserver.pgp.*; import org.kontalk.xmppserver.util.Utils; import tigase.xmpp.BareJID; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; /* * Kontalk XMPP Tigase extension * Copyright (C) 2017 Kontalk Devteam <devteam@kontalk.org> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kontalk.xmppserver; /** * Kontalk keyring singleton. * @author Daniele Ricci */ public class KontalkKeyring { private static final Map<String, KontalkKeyring> instances = new HashMap<>(); private final String domain; private final PGPLocalKeyring keyring; private final PGPPublicKey secretMasterKey; private final PGPPublicKeyRing secretPublicKeyring; private final String secretKeyFingerprint; /** Use {@link #getInstance(String)} instead. */ private KontalkKeyring(String domain, String secretPrivateKeyFile, String secretPublicKeyFile, String keyring) throws IOException, PGPException { this.domain = domain; this.keyring = new BerkeleyPGPLocalKeyring(keyring); // import into GnuPG GnuPGInterface.getInstance().importKey(secretPrivateKeyFile); GnuPGInterface.getInstance().importKey(secretPublicKeyFile); // calculate secret key fingerprint for signing secretPublicKeyring = PGPUtils.readPublicKeyring(new FileInputStream(secretPublicKeyFile)); secretMasterKey = PGPUtils.getMasterKey(secretPublicKeyring); secretKeyFingerprint = PGPUtils.getFingerprint(secretMasterKey); } public PGPPublicKeyRing getSecretPublicKey() { return secretPublicKeyring; } /** * Authenticates the given public key in Kontalk. * @param keyData public key data to check * @return a user instance with JID and public key fingerprint. */ public KontalkUser authenticate(byte[] keyData) throws IOException, PGPException { PGPPublicKeyRing key = keyring.importKey(keyData); BareJID jid = validate(key); return jid != null ? new KontalkUser(jid, PGPUtils.getFingerprint(key)) : null; } /** * Post-authentication step: verifies that the given user is allowed to * login by checking the old key. * @param user user object returned by {@link #authenticate} * @param oldFingerprint old key fingerprint, null if none present * @return true if the new key can be accepted. */ public boolean postAuthenticate(KontalkUser user, String oldFingerprint) throws IOException, PGPException { if (oldFingerprint == null || oldFingerprint.equalsIgnoreCase(user.getFingerprint())) { // no old fingerprint or same fingerprint -- access granted return true; } PGPPublicKeyRing oldKey = keyring.getKey(oldFingerprint); if (oldKey != null && validate(oldKey) != null) { // old key is still valid, check for timestamp PGPPublicKeyRing newKey = keyring.getKey(user.getFingerprint()); if (newKey != null && PGPUtils.isKeyNewer(oldKey, newKey)) { return true; } } return false; } /** * Imports the given revoked key and checks if fingerprint matches and * key is revoked correctly. */ public boolean revoked(byte[] keyData, String fingerprint) throws IOException, PGPException { PGPPublicKeyRing key = keyring.importKey(keyData); PGPPublicKey masterKey = PGPUtils.getMasterKey(key); return masterKey != null && PGPUtils.isRevoked(masterKey) &&
Arrays.equals(Utils.parseHexBinary(fingerprint), masterKey.getFingerprint());
kontalk/tigase-extension
src/main/java/org/kontalk/xmppserver/registration/SMSDataStoreVerificationProvider.java
// Path: src/main/java/org/kontalk/xmppserver/auth/KontalkAuth.java // public class KontalkAuth { // private static final String NODE_AUTH = "kontalk/auth"; // private static final String KEY_FINGERPRINT = "fingerprint"; // // private static UserRepository userRepository = null; // // private KontalkAuth() {} // // public static UserRepository getUserRepository() throws TigaseDBException { // if (userRepository == null) { // try { // userRepository = RepositoryFactory.getUserRepository(null, null, null); // } // catch (Exception e) { // throw new TigaseDBException("Unable to get user repository instance", e); // } // } // return userRepository; // } // // public static String getUserFingerprint(XMPPResourceConnection session) // throws TigaseDBException, NotAuthorizedException { // return session.getData(NODE_AUTH, KEY_FINGERPRINT, null); // } // // public static String getUserFingerprint(XMPPResourceConnection session, BareJID jid) // throws TigaseDBException { // return getUserRepository().getData(jid, NODE_AUTH, KEY_FINGERPRINT, null); // } // // public static void setUserFingerprint(XMPPResourceConnection session, BareJID jid, String fingerprint) // throws TigaseDBException { // getUserRepository().setData(jid, NODE_AUTH, KEY_FINGERPRINT, fingerprint); // } // // public static KontalkKeyring getKeyring(XMPPResourceConnection session) throws IOException, PGPException { // return KontalkKeyring.getInstance(session.getDomainAsJID().toString()); // } // // public static String toUserId(String phone) { // return sha1(phone); // } // // public static JID toJID(String phone, String domain) { // return JID.jidInstanceNS(toUserId(phone), domain, null); // } // // public static BareJID toBareJID(String phone, String domain) { // return BareJID.bareJIDInstanceNS(toUserId(phone), domain); // } // // private static String sha1(String text) { // try { // MessageDigest md; // md = MessageDigest.getInstance("SHA-1"); // md.update(text.getBytes(), 0, text.length()); // // byte[] digest = md.digest(); // return Hex.toHexString(digest); // } // catch (NoSuchAlgorithmException e) { // // no SHA-1?? WWWHHHHAAAAAATTTT???!?!?!?!?! // throw new RuntimeException("no SHA-1 available. What the crap of a runtime do you have?"); // } // } // // // // }
import java.util.logging.Level; import java.util.logging.Logger; import org.kontalk.xmppserver.auth.KontalkAuth; import tigase.conf.ConfigurationException; import tigase.db.DBInitException; import tigase.db.TigaseDBException; import tigase.xmpp.BareJID; import tigase.xmpp.XMPPResourceConnection; import java.io.IOException; import java.sql.SQLException; import java.util.Map; import java.util.Timer; import java.util.TimerTask;
/* * Kontalk XMPP Tigase extension * Copyright (C) 2017 Kontalk Devteam <devteam@kontalk.org> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kontalk.xmppserver.registration; /** * Base class for a SMS verification provider based on a data store repository. * @author Daniele Ricci */ public abstract class SMSDataStoreVerificationProvider extends AbstractSMSVerificationProvider { private Logger log; /** Time in seconds between calls to {@link VerificationRepository#purge()}. */ private static final int EXPIRED_TIMEOUT = 60000; private VerificationRepository repo; protected void init(Logger log, Map<String, Object> settings) throws TigaseDBException, ConfigurationException { super.init(settings); this.log = log; // database parameters String dbUri = (String) settings.get("db-uri"); Object _timeout = settings.get("expire"); int timeout = (_timeout != null) ? (Integer) _timeout : 0; try { repo = createVerificationRepository(dbUri, timeout); } catch (ClassNotFoundException e) { throw new TigaseDBException("Repository class not found (uri=" + dbUri + ")", e); } catch (InstantiationException e) { throw new TigaseDBException("Unable to create instance for repository (uri=" + dbUri + ")", e); } catch (SQLException e) { throw new TigaseDBException("SQL exception (uri=" + dbUri + ")", e); } catch (IllegalAccessException e) { throw new TigaseDBException("Unknown error (uri=" + dbUri + ")", e); } if (timeout > 0) { // create a scheduler for our own use Timer timer = new Timer("SMSDataStoreVerification tasks", true); // setup looping task for verification codes expiration timer.scheduleAtFixedRate(new PurgeTask(log, repo), EXPIRED_TIMEOUT, EXPIRED_TIMEOUT); } } protected VerificationRepository createVerificationRepository(String dbUri, int timeout) throws ClassNotFoundException, DBInitException, InstantiationException, SQLException, IllegalAccessException { return new DataVerificationRepository(dbUri, timeout); } @Override public RegistrationRequest startVerification(String domain, String phoneNumber) throws IOException, VerificationRepository.AlreadyRegisteredException, TigaseDBException { // generate verification code
// Path: src/main/java/org/kontalk/xmppserver/auth/KontalkAuth.java // public class KontalkAuth { // private static final String NODE_AUTH = "kontalk/auth"; // private static final String KEY_FINGERPRINT = "fingerprint"; // // private static UserRepository userRepository = null; // // private KontalkAuth() {} // // public static UserRepository getUserRepository() throws TigaseDBException { // if (userRepository == null) { // try { // userRepository = RepositoryFactory.getUserRepository(null, null, null); // } // catch (Exception e) { // throw new TigaseDBException("Unable to get user repository instance", e); // } // } // return userRepository; // } // // public static String getUserFingerprint(XMPPResourceConnection session) // throws TigaseDBException, NotAuthorizedException { // return session.getData(NODE_AUTH, KEY_FINGERPRINT, null); // } // // public static String getUserFingerprint(XMPPResourceConnection session, BareJID jid) // throws TigaseDBException { // return getUserRepository().getData(jid, NODE_AUTH, KEY_FINGERPRINT, null); // } // // public static void setUserFingerprint(XMPPResourceConnection session, BareJID jid, String fingerprint) // throws TigaseDBException { // getUserRepository().setData(jid, NODE_AUTH, KEY_FINGERPRINT, fingerprint); // } // // public static KontalkKeyring getKeyring(XMPPResourceConnection session) throws IOException, PGPException { // return KontalkKeyring.getInstance(session.getDomainAsJID().toString()); // } // // public static String toUserId(String phone) { // return sha1(phone); // } // // public static JID toJID(String phone, String domain) { // return JID.jidInstanceNS(toUserId(phone), domain, null); // } // // public static BareJID toBareJID(String phone, String domain) { // return BareJID.bareJIDInstanceNS(toUserId(phone), domain); // } // // private static String sha1(String text) { // try { // MessageDigest md; // md = MessageDigest.getInstance("SHA-1"); // md.update(text.getBytes(), 0, text.length()); // // byte[] digest = md.digest(); // return Hex.toHexString(digest); // } // catch (NoSuchAlgorithmException e) { // // no SHA-1?? WWWHHHHAAAAAATTTT???!?!?!?!?! // throw new RuntimeException("no SHA-1 available. What the crap of a runtime do you have?"); // } // } // // // // } // Path: src/main/java/org/kontalk/xmppserver/registration/SMSDataStoreVerificationProvider.java import java.util.logging.Level; import java.util.logging.Logger; import org.kontalk.xmppserver.auth.KontalkAuth; import tigase.conf.ConfigurationException; import tigase.db.DBInitException; import tigase.db.TigaseDBException; import tigase.xmpp.BareJID; import tigase.xmpp.XMPPResourceConnection; import java.io.IOException; import java.sql.SQLException; import java.util.Map; import java.util.Timer; import java.util.TimerTask; /* * Kontalk XMPP Tigase extension * Copyright (C) 2017 Kontalk Devteam <devteam@kontalk.org> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kontalk.xmppserver.registration; /** * Base class for a SMS verification provider based on a data store repository. * @author Daniele Ricci */ public abstract class SMSDataStoreVerificationProvider extends AbstractSMSVerificationProvider { private Logger log; /** Time in seconds between calls to {@link VerificationRepository#purge()}. */ private static final int EXPIRED_TIMEOUT = 60000; private VerificationRepository repo; protected void init(Logger log, Map<String, Object> settings) throws TigaseDBException, ConfigurationException { super.init(settings); this.log = log; // database parameters String dbUri = (String) settings.get("db-uri"); Object _timeout = settings.get("expire"); int timeout = (_timeout != null) ? (Integer) _timeout : 0; try { repo = createVerificationRepository(dbUri, timeout); } catch (ClassNotFoundException e) { throw new TigaseDBException("Repository class not found (uri=" + dbUri + ")", e); } catch (InstantiationException e) { throw new TigaseDBException("Unable to create instance for repository (uri=" + dbUri + ")", e); } catch (SQLException e) { throw new TigaseDBException("SQL exception (uri=" + dbUri + ")", e); } catch (IllegalAccessException e) { throw new TigaseDBException("Unknown error (uri=" + dbUri + ")", e); } if (timeout > 0) { // create a scheduler for our own use Timer timer = new Timer("SMSDataStoreVerification tasks", true); // setup looping task for verification codes expiration timer.scheduleAtFixedRate(new PurgeTask(log, repo), EXPIRED_TIMEOUT, EXPIRED_TIMEOUT); } } protected VerificationRepository createVerificationRepository(String dbUri, int timeout) throws ClassNotFoundException, DBInitException, InstantiationException, SQLException, IllegalAccessException { return new DataVerificationRepository(dbUri, timeout); } @Override public RegistrationRequest startVerification(String domain, String phoneNumber) throws IOException, VerificationRepository.AlreadyRegisteredException, TigaseDBException { // generate verification code
BareJID jid = KontalkAuth.toBareJID(phoneNumber, domain);
kontalk/tigase-extension
src/main/java/org/kontalk/xmppserver/messages/OfflineMessages.java
// Path: src/main/java/org/kontalk/xmppserver/messages/OfflineMessages.java // protected static final String ID = "msgoffline2"; // // Path: src/main/java/org/kontalk/xmppserver/messages/OfflineMessages.java // protected static final String XMLNS = "jabber:client";
import tigase.db.NonAuthUserRepository; import tigase.db.TigaseDBException; import tigase.db.UserNotFoundException; import tigase.server.Packet; import tigase.util.DNSResolver; import tigase.util.TigaseStringprepException; import tigase.xml.Element; import tigase.xmpp.*; import tigase.xmpp.impl.C2SDeliveryErrorProcessor; import tigase.xmpp.impl.FlexibleOfflineMessageRetrieval; import tigase.xmpp.impl.Message; import tigase.xmpp.impl.PresenceState; import tigase.xmpp.impl.annotation.*; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import static org.kontalk.xmppserver.messages.OfflineMessages.ID; import static org.kontalk.xmppserver.messages.OfflineMessages.XMLNS;
/* * Kontalk XMPP Tigase extension * Copyright (C) 2017 Kontalk Devteam <devteam@kontalk.org> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kontalk.xmppserver.messages; /** * A more advanced offline messages implementation. * It uses an ad-hoc table and it is capable of expiring messages. * Inspired by the original OfflineMessages by Tigase. * @author Daniele Ricci */ @Id(ID) @Handles({
// Path: src/main/java/org/kontalk/xmppserver/messages/OfflineMessages.java // protected static final String ID = "msgoffline2"; // // Path: src/main/java/org/kontalk/xmppserver/messages/OfflineMessages.java // protected static final String XMLNS = "jabber:client"; // Path: src/main/java/org/kontalk/xmppserver/messages/OfflineMessages.java import tigase.db.NonAuthUserRepository; import tigase.db.TigaseDBException; import tigase.db.UserNotFoundException; import tigase.server.Packet; import tigase.util.DNSResolver; import tigase.util.TigaseStringprepException; import tigase.xml.Element; import tigase.xmpp.*; import tigase.xmpp.impl.C2SDeliveryErrorProcessor; import tigase.xmpp.impl.FlexibleOfflineMessageRetrieval; import tigase.xmpp.impl.Message; import tigase.xmpp.impl.PresenceState; import tigase.xmpp.impl.annotation.*; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import static org.kontalk.xmppserver.messages.OfflineMessages.ID; import static org.kontalk.xmppserver.messages.OfflineMessages.XMLNS; /* * Kontalk XMPP Tigase extension * Copyright (C) 2017 Kontalk Devteam <devteam@kontalk.org> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kontalk.xmppserver.messages; /** * A more advanced offline messages implementation. * It uses an ad-hoc table and it is capable of expiring messages. * Inspired by the original OfflineMessages by Tigase. * @author Daniele Ricci */ @Id(ID) @Handles({
@Handle(path={PresenceState.PRESENCE_ELEMENT_NAME},xmlns=XMLNS)
kontalk/tigase-extension
src/main/java/org/kontalk/xmppserver/KontalkLegacyFileUploadComponent.java
// Path: src/main/java/org/kontalk/xmppserver/upload/FileUploadProvider.java // public interface FileUploadProvider { // // void init(Map<String, Object> props) throws ConfigurationException; // // String getName(); // // // for service discovery // String getNode(); // String getDescription(); // // Element getServiceInfo(); // // } // // Path: src/main/java/org/kontalk/xmppserver/upload/KontalkDropboxProvider.java // public class KontalkDropboxProvider implements FileUploadProvider { // // public static final String PROVIDER_NAME = "kontalkbox"; // private static final String NODE_NAME = PROVIDER_NAME; // private static final String DESCRIPTION = "Kontalk dropbox service"; // // String uri; // // @Override // public void init(Map<String, Object> props) throws ConfigurationException { // uri = (String) props.get("uri"); // } // // @Override // public String getName() { // return PROVIDER_NAME; // } // // @Override // public String getNode() { // return NODE_NAME; // } // // @Override // public String getDescription() { // return DESCRIPTION; // } // // @Override // public Element getServiceInfo() { // return new Element("uri", uri); // } // // }
import java.util.List; import java.util.Map; import org.kontalk.xmppserver.upload.FileUploadProvider; import org.kontalk.xmppserver.upload.KontalkDropboxProvider; import tigase.conf.ConfigurationException; import tigase.server.AbstractMessageReceiver; import tigase.server.Iq; import tigase.server.Packet; import tigase.xml.Element; import tigase.xmpp.JID; import tigase.xmpp.StanzaType; import java.util.ArrayList; import java.util.Arrays;
/* * Kontalk XMPP Tigase extension * Copyright (C) 2017 Kontalk Devteam <devteam@kontalk.org> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kontalk.xmppserver; /** * Kontalk legacy file upload component. * https://github.com/kontalk/specs/wiki/XMPP-extensions#file-upload * @author Daniele Ricci */ public class KontalkLegacyFileUploadComponent extends AbstractMessageReceiver { //private static Logger log = Logger.getLogger(KontalkLegacyFileUploadComponent.class.getName()); private static final String DISCO_DESCRIPTION = "Legacy Kontalk file upload"; private static final String NODE = "http://kontalk.org/extensions/message#upload"; private static final String XMLNS = NODE; private static final Element top_feature = new Element("feature", new String[] { "var" }, new String[] { NODE }); private static final List<Element> DISCO_FEATURES = Arrays.asList(top_feature); private static final int NUM_THREADS = 20;
// Path: src/main/java/org/kontalk/xmppserver/upload/FileUploadProvider.java // public interface FileUploadProvider { // // void init(Map<String, Object> props) throws ConfigurationException; // // String getName(); // // // for service discovery // String getNode(); // String getDescription(); // // Element getServiceInfo(); // // } // // Path: src/main/java/org/kontalk/xmppserver/upload/KontalkDropboxProvider.java // public class KontalkDropboxProvider implements FileUploadProvider { // // public static final String PROVIDER_NAME = "kontalkbox"; // private static final String NODE_NAME = PROVIDER_NAME; // private static final String DESCRIPTION = "Kontalk dropbox service"; // // String uri; // // @Override // public void init(Map<String, Object> props) throws ConfigurationException { // uri = (String) props.get("uri"); // } // // @Override // public String getName() { // return PROVIDER_NAME; // } // // @Override // public String getNode() { // return NODE_NAME; // } // // @Override // public String getDescription() { // return DESCRIPTION; // } // // @Override // public Element getServiceInfo() { // return new Element("uri", uri); // } // // } // Path: src/main/java/org/kontalk/xmppserver/KontalkLegacyFileUploadComponent.java import java.util.List; import java.util.Map; import org.kontalk.xmppserver.upload.FileUploadProvider; import org.kontalk.xmppserver.upload.KontalkDropboxProvider; import tigase.conf.ConfigurationException; import tigase.server.AbstractMessageReceiver; import tigase.server.Iq; import tigase.server.Packet; import tigase.xml.Element; import tigase.xmpp.JID; import tigase.xmpp.StanzaType; import java.util.ArrayList; import java.util.Arrays; /* * Kontalk XMPP Tigase extension * Copyright (C) 2017 Kontalk Devteam <devteam@kontalk.org> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kontalk.xmppserver; /** * Kontalk legacy file upload component. * https://github.com/kontalk/specs/wiki/XMPP-extensions#file-upload * @author Daniele Ricci */ public class KontalkLegacyFileUploadComponent extends AbstractMessageReceiver { //private static Logger log = Logger.getLogger(KontalkLegacyFileUploadComponent.class.getName()); private static final String DISCO_DESCRIPTION = "Legacy Kontalk file upload"; private static final String NODE = "http://kontalk.org/extensions/message#upload"; private static final String XMLNS = NODE; private static final Element top_feature = new Element("feature", new String[] { "var" }, new String[] { NODE }); private static final List<Element> DISCO_FEATURES = Arrays.asList(top_feature); private static final int NUM_THREADS = 20;
private FileUploadProvider provider = new KontalkDropboxProvider();
kontalk/tigase-extension
src/main/java/org/kontalk/xmppserver/KontalkLegacyFileUploadComponent.java
// Path: src/main/java/org/kontalk/xmppserver/upload/FileUploadProvider.java // public interface FileUploadProvider { // // void init(Map<String, Object> props) throws ConfigurationException; // // String getName(); // // // for service discovery // String getNode(); // String getDescription(); // // Element getServiceInfo(); // // } // // Path: src/main/java/org/kontalk/xmppserver/upload/KontalkDropboxProvider.java // public class KontalkDropboxProvider implements FileUploadProvider { // // public static final String PROVIDER_NAME = "kontalkbox"; // private static final String NODE_NAME = PROVIDER_NAME; // private static final String DESCRIPTION = "Kontalk dropbox service"; // // String uri; // // @Override // public void init(Map<String, Object> props) throws ConfigurationException { // uri = (String) props.get("uri"); // } // // @Override // public String getName() { // return PROVIDER_NAME; // } // // @Override // public String getNode() { // return NODE_NAME; // } // // @Override // public String getDescription() { // return DESCRIPTION; // } // // @Override // public Element getServiceInfo() { // return new Element("uri", uri); // } // // }
import java.util.List; import java.util.Map; import org.kontalk.xmppserver.upload.FileUploadProvider; import org.kontalk.xmppserver.upload.KontalkDropboxProvider; import tigase.conf.ConfigurationException; import tigase.server.AbstractMessageReceiver; import tigase.server.Iq; import tigase.server.Packet; import tigase.xml.Element; import tigase.xmpp.JID; import tigase.xmpp.StanzaType; import java.util.ArrayList; import java.util.Arrays;
/* * Kontalk XMPP Tigase extension * Copyright (C) 2017 Kontalk Devteam <devteam@kontalk.org> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kontalk.xmppserver; /** * Kontalk legacy file upload component. * https://github.com/kontalk/specs/wiki/XMPP-extensions#file-upload * @author Daniele Ricci */ public class KontalkLegacyFileUploadComponent extends AbstractMessageReceiver { //private static Logger log = Logger.getLogger(KontalkLegacyFileUploadComponent.class.getName()); private static final String DISCO_DESCRIPTION = "Legacy Kontalk file upload"; private static final String NODE = "http://kontalk.org/extensions/message#upload"; private static final String XMLNS = NODE; private static final Element top_feature = new Element("feature", new String[] { "var" }, new String[] { NODE }); private static final List<Element> DISCO_FEATURES = Arrays.asList(top_feature); private static final int NUM_THREADS = 20;
// Path: src/main/java/org/kontalk/xmppserver/upload/FileUploadProvider.java // public interface FileUploadProvider { // // void init(Map<String, Object> props) throws ConfigurationException; // // String getName(); // // // for service discovery // String getNode(); // String getDescription(); // // Element getServiceInfo(); // // } // // Path: src/main/java/org/kontalk/xmppserver/upload/KontalkDropboxProvider.java // public class KontalkDropboxProvider implements FileUploadProvider { // // public static final String PROVIDER_NAME = "kontalkbox"; // private static final String NODE_NAME = PROVIDER_NAME; // private static final String DESCRIPTION = "Kontalk dropbox service"; // // String uri; // // @Override // public void init(Map<String, Object> props) throws ConfigurationException { // uri = (String) props.get("uri"); // } // // @Override // public String getName() { // return PROVIDER_NAME; // } // // @Override // public String getNode() { // return NODE_NAME; // } // // @Override // public String getDescription() { // return DESCRIPTION; // } // // @Override // public Element getServiceInfo() { // return new Element("uri", uri); // } // // } // Path: src/main/java/org/kontalk/xmppserver/KontalkLegacyFileUploadComponent.java import java.util.List; import java.util.Map; import org.kontalk.xmppserver.upload.FileUploadProvider; import org.kontalk.xmppserver.upload.KontalkDropboxProvider; import tigase.conf.ConfigurationException; import tigase.server.AbstractMessageReceiver; import tigase.server.Iq; import tigase.server.Packet; import tigase.xml.Element; import tigase.xmpp.JID; import tigase.xmpp.StanzaType; import java.util.ArrayList; import java.util.Arrays; /* * Kontalk XMPP Tigase extension * Copyright (C) 2017 Kontalk Devteam <devteam@kontalk.org> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kontalk.xmppserver; /** * Kontalk legacy file upload component. * https://github.com/kontalk/specs/wiki/XMPP-extensions#file-upload * @author Daniele Ricci */ public class KontalkLegacyFileUploadComponent extends AbstractMessageReceiver { //private static Logger log = Logger.getLogger(KontalkLegacyFileUploadComponent.class.getName()); private static final String DISCO_DESCRIPTION = "Legacy Kontalk file upload"; private static final String NODE = "http://kontalk.org/extensions/message#upload"; private static final String XMLNS = NODE; private static final Element top_feature = new Element("feature", new String[] { "var" }, new String[] { NODE }); private static final List<Element> DISCO_FEATURES = Arrays.asList(top_feature); private static final int NUM_THREADS = 20;
private FileUploadProvider provider = new KontalkDropboxProvider();
kontalk/tigase-extension
src/test/java/org/kontalk/xmppserver/registration/security/BaseThrottlingSecurityProviderTest.java
// Path: src/main/java/org/kontalk/xmppserver/registration/AbstractSMSVerificationProvider.java // public abstract class AbstractSMSVerificationProvider implements PhoneNumberVerificationProvider { // // protected String senderId; // protected String brandImageVector; // protected String brandImageSmall; // protected String brandImageMedium; // protected String brandImageLarge; // protected String brandImageHighDef; // protected String brandLink; // // @Override // public void init(Map<String, Object> settings) throws TigaseDBException, ConfigurationException { // senderId = (String) settings.get("sender"); // brandImageVector = (String) settings.get("brand-image-vector"); // brandImageSmall = (String) settings.get("brand-image-small"); // brandImageMedium = (String) settings.get("brand-image-medium"); // brandImageLarge = (String) settings.get("brand-image-large"); // brandImageHighDef = (String) settings.get("brand-image-hd"); // brandLink = (String) settings.get("brand-link"); // } // // @Override // public String getSenderId() { // return senderId; // } // // @Override // public String getBrandImageVector() { // return brandImageVector; // } // // @Override // public String getBrandImageSmall() { // return brandImageSmall; // } // // @Override // public String getBrandImageMedium() { // return brandImageMedium; // } // // @Override // public String getBrandImageLarge() { // return brandImageLarge; // } // // @Override // public String getBrandImageHighDef() { // return brandImageHighDef; // } // // @Override // public String getBrandLink() { // return brandLink; // } // // } // // Path: src/main/java/org/kontalk/xmppserver/registration/PhoneNumberVerificationProvider.java // public interface PhoneNumberVerificationProvider { // // /** Challenge the user with a verification PIN sent through a SMS or a told through a phone call. */ // String CHALLENGE_PIN = "pin"; // /** Challenge the user with a missed call from a random number and making the user guess the digits. */ // String CHALLENGE_MISSED_CALL = "missedcall"; // /** Challenge the user with the caller ID presented in a user-initiated call to a given phone number. */ // String CHALLENGE_CALLER_ID = "callerid"; // // void init(Map<String, Object> settings) throws TigaseDBException, ConfigurationException; // // String getSenderId(); // // String getAckInstructions(); // // /** // * Initiates a verification. // * @param phoneNumber the phone number being verified // * @return a request object of some kind that you will give to {@link #endVerification}. // */ // RegistrationRequest startVerification(String domain, String phoneNumber) // throws IOException, VerificationRepository.AlreadyRegisteredException, TigaseDBException; // // /** // * Ends a verification. // * @param request request object as returned by {@link #startVerification} // * @param proof the proof of the verification (e.g. verification code) // * @return true if verification succeded, false otherwise. // */ // boolean endVerification(XMPPResourceConnection session, RegistrationRequest request, String proof) throws IOException, TigaseDBException; // // /** Returns true if this provider supports this kind if registration request. */ // boolean supportsRequest(RegistrationRequest request); // // /** The challenge type implemented by this provider. */ // String getChallengeType(); // // /** The brand vector image logo for this provider, if any. */ // default String getBrandImageVector() { // return null; // } // // /** The brand small image logo for this provider, if any. */ // default String getBrandImageSmall() { // return null; // } // // /** The brand medium image logo for this provider, if any. */ // default String getBrandImageMedium() { // return null; // } // // /** The brand large image logo for this provider, if any. */ // default String getBrandImageLarge() { // return null; // } // // /** The brand HD image logo for this provider, if any. */ // default String getBrandImageHighDef() { // return null; // } // // /** The brand link the image logo will point to, if any. */ // default String getBrandLink() { // return null; // } // // } // // Path: src/main/java/org/kontalk/xmppserver/registration/RegistrationRequest.java // public interface RegistrationRequest { // // /** Returns the sender id of the call/SMS/whatever. */ // String getSenderId(); // // } // // Path: src/main/java/org/kontalk/xmppserver/registration/VerificationRepository.java // public interface VerificationRepository { // // /** Length of a verification code. */ // int VERIFICATION_CODE_LENGTH = 6; // // /** Registers a new verification code for the given user. */ // String generateVerificationCode(BareJID jid) throws AlreadyRegisteredException, TigaseDBException; // // /** Verifies and delete the given verification. */ // boolean verifyCode(BareJID jid, String code) throws TigaseDBException; // // /** Purges old verification entries from storage. */ // void purge() throws TigaseDBException; // // /** Exception thrown when the user has already tried to register recently. */ // final class AlreadyRegisteredException extends Exception { // private static final long serialVersionUID = 1L; // } // // }
import org.junit.Before; import org.junit.Test; import org.kontalk.xmppserver.registration.AbstractSMSVerificationProvider; import org.kontalk.xmppserver.registration.PhoneNumberVerificationProvider; import org.kontalk.xmppserver.registration.RegistrationRequest; import org.kontalk.xmppserver.registration.VerificationRepository; import tigase.db.TigaseDBException; import tigase.xmpp.XMPPResourceConnection; import java.io.IOException; import java.util.HashMap; import java.util.Map;
package org.kontalk.xmppserver.registration.security; public abstract class BaseThrottlingSecurityProviderTest { protected static final int DELAY_SECONDS = 1; protected static final int ATTEMPTS = 3; protected SecurityProvider provider;
// Path: src/main/java/org/kontalk/xmppserver/registration/AbstractSMSVerificationProvider.java // public abstract class AbstractSMSVerificationProvider implements PhoneNumberVerificationProvider { // // protected String senderId; // protected String brandImageVector; // protected String brandImageSmall; // protected String brandImageMedium; // protected String brandImageLarge; // protected String brandImageHighDef; // protected String brandLink; // // @Override // public void init(Map<String, Object> settings) throws TigaseDBException, ConfigurationException { // senderId = (String) settings.get("sender"); // brandImageVector = (String) settings.get("brand-image-vector"); // brandImageSmall = (String) settings.get("brand-image-small"); // brandImageMedium = (String) settings.get("brand-image-medium"); // brandImageLarge = (String) settings.get("brand-image-large"); // brandImageHighDef = (String) settings.get("brand-image-hd"); // brandLink = (String) settings.get("brand-link"); // } // // @Override // public String getSenderId() { // return senderId; // } // // @Override // public String getBrandImageVector() { // return brandImageVector; // } // // @Override // public String getBrandImageSmall() { // return brandImageSmall; // } // // @Override // public String getBrandImageMedium() { // return brandImageMedium; // } // // @Override // public String getBrandImageLarge() { // return brandImageLarge; // } // // @Override // public String getBrandImageHighDef() { // return brandImageHighDef; // } // // @Override // public String getBrandLink() { // return brandLink; // } // // } // // Path: src/main/java/org/kontalk/xmppserver/registration/PhoneNumberVerificationProvider.java // public interface PhoneNumberVerificationProvider { // // /** Challenge the user with a verification PIN sent through a SMS or a told through a phone call. */ // String CHALLENGE_PIN = "pin"; // /** Challenge the user with a missed call from a random number and making the user guess the digits. */ // String CHALLENGE_MISSED_CALL = "missedcall"; // /** Challenge the user with the caller ID presented in a user-initiated call to a given phone number. */ // String CHALLENGE_CALLER_ID = "callerid"; // // void init(Map<String, Object> settings) throws TigaseDBException, ConfigurationException; // // String getSenderId(); // // String getAckInstructions(); // // /** // * Initiates a verification. // * @param phoneNumber the phone number being verified // * @return a request object of some kind that you will give to {@link #endVerification}. // */ // RegistrationRequest startVerification(String domain, String phoneNumber) // throws IOException, VerificationRepository.AlreadyRegisteredException, TigaseDBException; // // /** // * Ends a verification. // * @param request request object as returned by {@link #startVerification} // * @param proof the proof of the verification (e.g. verification code) // * @return true if verification succeded, false otherwise. // */ // boolean endVerification(XMPPResourceConnection session, RegistrationRequest request, String proof) throws IOException, TigaseDBException; // // /** Returns true if this provider supports this kind if registration request. */ // boolean supportsRequest(RegistrationRequest request); // // /** The challenge type implemented by this provider. */ // String getChallengeType(); // // /** The brand vector image logo for this provider, if any. */ // default String getBrandImageVector() { // return null; // } // // /** The brand small image logo for this provider, if any. */ // default String getBrandImageSmall() { // return null; // } // // /** The brand medium image logo for this provider, if any. */ // default String getBrandImageMedium() { // return null; // } // // /** The brand large image logo for this provider, if any. */ // default String getBrandImageLarge() { // return null; // } // // /** The brand HD image logo for this provider, if any. */ // default String getBrandImageHighDef() { // return null; // } // // /** The brand link the image logo will point to, if any. */ // default String getBrandLink() { // return null; // } // // } // // Path: src/main/java/org/kontalk/xmppserver/registration/RegistrationRequest.java // public interface RegistrationRequest { // // /** Returns the sender id of the call/SMS/whatever. */ // String getSenderId(); // // } // // Path: src/main/java/org/kontalk/xmppserver/registration/VerificationRepository.java // public interface VerificationRepository { // // /** Length of a verification code. */ // int VERIFICATION_CODE_LENGTH = 6; // // /** Registers a new verification code for the given user. */ // String generateVerificationCode(BareJID jid) throws AlreadyRegisteredException, TigaseDBException; // // /** Verifies and delete the given verification. */ // boolean verifyCode(BareJID jid, String code) throws TigaseDBException; // // /** Purges old verification entries from storage. */ // void purge() throws TigaseDBException; // // /** Exception thrown when the user has already tried to register recently. */ // final class AlreadyRegisteredException extends Exception { // private static final long serialVersionUID = 1L; // } // // } // Path: src/test/java/org/kontalk/xmppserver/registration/security/BaseThrottlingSecurityProviderTest.java import org.junit.Before; import org.junit.Test; import org.kontalk.xmppserver.registration.AbstractSMSVerificationProvider; import org.kontalk.xmppserver.registration.PhoneNumberVerificationProvider; import org.kontalk.xmppserver.registration.RegistrationRequest; import org.kontalk.xmppserver.registration.VerificationRepository; import tigase.db.TigaseDBException; import tigase.xmpp.XMPPResourceConnection; import java.io.IOException; import java.util.HashMap; import java.util.Map; package org.kontalk.xmppserver.registration.security; public abstract class BaseThrottlingSecurityProviderTest { protected static final int DELAY_SECONDS = 1; protected static final int ATTEMPTS = 3; protected SecurityProvider provider;
protected PhoneNumberVerificationProvider verificationProvider;
kontalk/tigase-extension
src/test/java/org/kontalk/xmppserver/registration/security/BaseThrottlingSecurityProviderTest.java
// Path: src/main/java/org/kontalk/xmppserver/registration/AbstractSMSVerificationProvider.java // public abstract class AbstractSMSVerificationProvider implements PhoneNumberVerificationProvider { // // protected String senderId; // protected String brandImageVector; // protected String brandImageSmall; // protected String brandImageMedium; // protected String brandImageLarge; // protected String brandImageHighDef; // protected String brandLink; // // @Override // public void init(Map<String, Object> settings) throws TigaseDBException, ConfigurationException { // senderId = (String) settings.get("sender"); // brandImageVector = (String) settings.get("brand-image-vector"); // brandImageSmall = (String) settings.get("brand-image-small"); // brandImageMedium = (String) settings.get("brand-image-medium"); // brandImageLarge = (String) settings.get("brand-image-large"); // brandImageHighDef = (String) settings.get("brand-image-hd"); // brandLink = (String) settings.get("brand-link"); // } // // @Override // public String getSenderId() { // return senderId; // } // // @Override // public String getBrandImageVector() { // return brandImageVector; // } // // @Override // public String getBrandImageSmall() { // return brandImageSmall; // } // // @Override // public String getBrandImageMedium() { // return brandImageMedium; // } // // @Override // public String getBrandImageLarge() { // return brandImageLarge; // } // // @Override // public String getBrandImageHighDef() { // return brandImageHighDef; // } // // @Override // public String getBrandLink() { // return brandLink; // } // // } // // Path: src/main/java/org/kontalk/xmppserver/registration/PhoneNumberVerificationProvider.java // public interface PhoneNumberVerificationProvider { // // /** Challenge the user with a verification PIN sent through a SMS or a told through a phone call. */ // String CHALLENGE_PIN = "pin"; // /** Challenge the user with a missed call from a random number and making the user guess the digits. */ // String CHALLENGE_MISSED_CALL = "missedcall"; // /** Challenge the user with the caller ID presented in a user-initiated call to a given phone number. */ // String CHALLENGE_CALLER_ID = "callerid"; // // void init(Map<String, Object> settings) throws TigaseDBException, ConfigurationException; // // String getSenderId(); // // String getAckInstructions(); // // /** // * Initiates a verification. // * @param phoneNumber the phone number being verified // * @return a request object of some kind that you will give to {@link #endVerification}. // */ // RegistrationRequest startVerification(String domain, String phoneNumber) // throws IOException, VerificationRepository.AlreadyRegisteredException, TigaseDBException; // // /** // * Ends a verification. // * @param request request object as returned by {@link #startVerification} // * @param proof the proof of the verification (e.g. verification code) // * @return true if verification succeded, false otherwise. // */ // boolean endVerification(XMPPResourceConnection session, RegistrationRequest request, String proof) throws IOException, TigaseDBException; // // /** Returns true if this provider supports this kind if registration request. */ // boolean supportsRequest(RegistrationRequest request); // // /** The challenge type implemented by this provider. */ // String getChallengeType(); // // /** The brand vector image logo for this provider, if any. */ // default String getBrandImageVector() { // return null; // } // // /** The brand small image logo for this provider, if any. */ // default String getBrandImageSmall() { // return null; // } // // /** The brand medium image logo for this provider, if any. */ // default String getBrandImageMedium() { // return null; // } // // /** The brand large image logo for this provider, if any. */ // default String getBrandImageLarge() { // return null; // } // // /** The brand HD image logo for this provider, if any. */ // default String getBrandImageHighDef() { // return null; // } // // /** The brand link the image logo will point to, if any. */ // default String getBrandLink() { // return null; // } // // } // // Path: src/main/java/org/kontalk/xmppserver/registration/RegistrationRequest.java // public interface RegistrationRequest { // // /** Returns the sender id of the call/SMS/whatever. */ // String getSenderId(); // // } // // Path: src/main/java/org/kontalk/xmppserver/registration/VerificationRepository.java // public interface VerificationRepository { // // /** Length of a verification code. */ // int VERIFICATION_CODE_LENGTH = 6; // // /** Registers a new verification code for the given user. */ // String generateVerificationCode(BareJID jid) throws AlreadyRegisteredException, TigaseDBException; // // /** Verifies and delete the given verification. */ // boolean verifyCode(BareJID jid, String code) throws TigaseDBException; // // /** Purges old verification entries from storage. */ // void purge() throws TigaseDBException; // // /** Exception thrown when the user has already tried to register recently. */ // final class AlreadyRegisteredException extends Exception { // private static final long serialVersionUID = 1L; // } // // }
import org.junit.Before; import org.junit.Test; import org.kontalk.xmppserver.registration.AbstractSMSVerificationProvider; import org.kontalk.xmppserver.registration.PhoneNumberVerificationProvider; import org.kontalk.xmppserver.registration.RegistrationRequest; import org.kontalk.xmppserver.registration.VerificationRepository; import tigase.db.TigaseDBException; import tigase.xmpp.XMPPResourceConnection; import java.io.IOException; import java.util.HashMap; import java.util.Map;
protected abstract SecurityProvider buildSecurityProvider(); protected abstract void addConfiguration(Map<String, Object> settings); @Test public abstract void testPass(); @Test public abstract void testNotPass(); @Test public abstract void testNotPassExpire(); protected void sleep(long seconds) { try { Thread.sleep(seconds*1000); } catch (InterruptedException ignored) { } } private static final class MyVerificationProvider extends AbstractSMSVerificationProvider { @Override public String getAckInstructions() { return null; } @Override
// Path: src/main/java/org/kontalk/xmppserver/registration/AbstractSMSVerificationProvider.java // public abstract class AbstractSMSVerificationProvider implements PhoneNumberVerificationProvider { // // protected String senderId; // protected String brandImageVector; // protected String brandImageSmall; // protected String brandImageMedium; // protected String brandImageLarge; // protected String brandImageHighDef; // protected String brandLink; // // @Override // public void init(Map<String, Object> settings) throws TigaseDBException, ConfigurationException { // senderId = (String) settings.get("sender"); // brandImageVector = (String) settings.get("brand-image-vector"); // brandImageSmall = (String) settings.get("brand-image-small"); // brandImageMedium = (String) settings.get("brand-image-medium"); // brandImageLarge = (String) settings.get("brand-image-large"); // brandImageHighDef = (String) settings.get("brand-image-hd"); // brandLink = (String) settings.get("brand-link"); // } // // @Override // public String getSenderId() { // return senderId; // } // // @Override // public String getBrandImageVector() { // return brandImageVector; // } // // @Override // public String getBrandImageSmall() { // return brandImageSmall; // } // // @Override // public String getBrandImageMedium() { // return brandImageMedium; // } // // @Override // public String getBrandImageLarge() { // return brandImageLarge; // } // // @Override // public String getBrandImageHighDef() { // return brandImageHighDef; // } // // @Override // public String getBrandLink() { // return brandLink; // } // // } // // Path: src/main/java/org/kontalk/xmppserver/registration/PhoneNumberVerificationProvider.java // public interface PhoneNumberVerificationProvider { // // /** Challenge the user with a verification PIN sent through a SMS or a told through a phone call. */ // String CHALLENGE_PIN = "pin"; // /** Challenge the user with a missed call from a random number and making the user guess the digits. */ // String CHALLENGE_MISSED_CALL = "missedcall"; // /** Challenge the user with the caller ID presented in a user-initiated call to a given phone number. */ // String CHALLENGE_CALLER_ID = "callerid"; // // void init(Map<String, Object> settings) throws TigaseDBException, ConfigurationException; // // String getSenderId(); // // String getAckInstructions(); // // /** // * Initiates a verification. // * @param phoneNumber the phone number being verified // * @return a request object of some kind that you will give to {@link #endVerification}. // */ // RegistrationRequest startVerification(String domain, String phoneNumber) // throws IOException, VerificationRepository.AlreadyRegisteredException, TigaseDBException; // // /** // * Ends a verification. // * @param request request object as returned by {@link #startVerification} // * @param proof the proof of the verification (e.g. verification code) // * @return true if verification succeded, false otherwise. // */ // boolean endVerification(XMPPResourceConnection session, RegistrationRequest request, String proof) throws IOException, TigaseDBException; // // /** Returns true if this provider supports this kind if registration request. */ // boolean supportsRequest(RegistrationRequest request); // // /** The challenge type implemented by this provider. */ // String getChallengeType(); // // /** The brand vector image logo for this provider, if any. */ // default String getBrandImageVector() { // return null; // } // // /** The brand small image logo for this provider, if any. */ // default String getBrandImageSmall() { // return null; // } // // /** The brand medium image logo for this provider, if any. */ // default String getBrandImageMedium() { // return null; // } // // /** The brand large image logo for this provider, if any. */ // default String getBrandImageLarge() { // return null; // } // // /** The brand HD image logo for this provider, if any. */ // default String getBrandImageHighDef() { // return null; // } // // /** The brand link the image logo will point to, if any. */ // default String getBrandLink() { // return null; // } // // } // // Path: src/main/java/org/kontalk/xmppserver/registration/RegistrationRequest.java // public interface RegistrationRequest { // // /** Returns the sender id of the call/SMS/whatever. */ // String getSenderId(); // // } // // Path: src/main/java/org/kontalk/xmppserver/registration/VerificationRepository.java // public interface VerificationRepository { // // /** Length of a verification code. */ // int VERIFICATION_CODE_LENGTH = 6; // // /** Registers a new verification code for the given user. */ // String generateVerificationCode(BareJID jid) throws AlreadyRegisteredException, TigaseDBException; // // /** Verifies and delete the given verification. */ // boolean verifyCode(BareJID jid, String code) throws TigaseDBException; // // /** Purges old verification entries from storage. */ // void purge() throws TigaseDBException; // // /** Exception thrown when the user has already tried to register recently. */ // final class AlreadyRegisteredException extends Exception { // private static final long serialVersionUID = 1L; // } // // } // Path: src/test/java/org/kontalk/xmppserver/registration/security/BaseThrottlingSecurityProviderTest.java import org.junit.Before; import org.junit.Test; import org.kontalk.xmppserver.registration.AbstractSMSVerificationProvider; import org.kontalk.xmppserver.registration.PhoneNumberVerificationProvider; import org.kontalk.xmppserver.registration.RegistrationRequest; import org.kontalk.xmppserver.registration.VerificationRepository; import tigase.db.TigaseDBException; import tigase.xmpp.XMPPResourceConnection; import java.io.IOException; import java.util.HashMap; import java.util.Map; protected abstract SecurityProvider buildSecurityProvider(); protected abstract void addConfiguration(Map<String, Object> settings); @Test public abstract void testPass(); @Test public abstract void testNotPass(); @Test public abstract void testNotPassExpire(); protected void sleep(long seconds) { try { Thread.sleep(seconds*1000); } catch (InterruptedException ignored) { } } private static final class MyVerificationProvider extends AbstractSMSVerificationProvider { @Override public String getAckInstructions() { return null; } @Override
public RegistrationRequest startVerification(String domain, String phoneNumber) throws IOException, VerificationRepository.AlreadyRegisteredException, TigaseDBException {
kontalk/tigase-extension
src/test/java/org/kontalk/xmppserver/registration/security/BaseThrottlingSecurityProviderTest.java
// Path: src/main/java/org/kontalk/xmppserver/registration/AbstractSMSVerificationProvider.java // public abstract class AbstractSMSVerificationProvider implements PhoneNumberVerificationProvider { // // protected String senderId; // protected String brandImageVector; // protected String brandImageSmall; // protected String brandImageMedium; // protected String brandImageLarge; // protected String brandImageHighDef; // protected String brandLink; // // @Override // public void init(Map<String, Object> settings) throws TigaseDBException, ConfigurationException { // senderId = (String) settings.get("sender"); // brandImageVector = (String) settings.get("brand-image-vector"); // brandImageSmall = (String) settings.get("brand-image-small"); // brandImageMedium = (String) settings.get("brand-image-medium"); // brandImageLarge = (String) settings.get("brand-image-large"); // brandImageHighDef = (String) settings.get("brand-image-hd"); // brandLink = (String) settings.get("brand-link"); // } // // @Override // public String getSenderId() { // return senderId; // } // // @Override // public String getBrandImageVector() { // return brandImageVector; // } // // @Override // public String getBrandImageSmall() { // return brandImageSmall; // } // // @Override // public String getBrandImageMedium() { // return brandImageMedium; // } // // @Override // public String getBrandImageLarge() { // return brandImageLarge; // } // // @Override // public String getBrandImageHighDef() { // return brandImageHighDef; // } // // @Override // public String getBrandLink() { // return brandLink; // } // // } // // Path: src/main/java/org/kontalk/xmppserver/registration/PhoneNumberVerificationProvider.java // public interface PhoneNumberVerificationProvider { // // /** Challenge the user with a verification PIN sent through a SMS or a told through a phone call. */ // String CHALLENGE_PIN = "pin"; // /** Challenge the user with a missed call from a random number and making the user guess the digits. */ // String CHALLENGE_MISSED_CALL = "missedcall"; // /** Challenge the user with the caller ID presented in a user-initiated call to a given phone number. */ // String CHALLENGE_CALLER_ID = "callerid"; // // void init(Map<String, Object> settings) throws TigaseDBException, ConfigurationException; // // String getSenderId(); // // String getAckInstructions(); // // /** // * Initiates a verification. // * @param phoneNumber the phone number being verified // * @return a request object of some kind that you will give to {@link #endVerification}. // */ // RegistrationRequest startVerification(String domain, String phoneNumber) // throws IOException, VerificationRepository.AlreadyRegisteredException, TigaseDBException; // // /** // * Ends a verification. // * @param request request object as returned by {@link #startVerification} // * @param proof the proof of the verification (e.g. verification code) // * @return true if verification succeded, false otherwise. // */ // boolean endVerification(XMPPResourceConnection session, RegistrationRequest request, String proof) throws IOException, TigaseDBException; // // /** Returns true if this provider supports this kind if registration request. */ // boolean supportsRequest(RegistrationRequest request); // // /** The challenge type implemented by this provider. */ // String getChallengeType(); // // /** The brand vector image logo for this provider, if any. */ // default String getBrandImageVector() { // return null; // } // // /** The brand small image logo for this provider, if any. */ // default String getBrandImageSmall() { // return null; // } // // /** The brand medium image logo for this provider, if any. */ // default String getBrandImageMedium() { // return null; // } // // /** The brand large image logo for this provider, if any. */ // default String getBrandImageLarge() { // return null; // } // // /** The brand HD image logo for this provider, if any. */ // default String getBrandImageHighDef() { // return null; // } // // /** The brand link the image logo will point to, if any. */ // default String getBrandLink() { // return null; // } // // } // // Path: src/main/java/org/kontalk/xmppserver/registration/RegistrationRequest.java // public interface RegistrationRequest { // // /** Returns the sender id of the call/SMS/whatever. */ // String getSenderId(); // // } // // Path: src/main/java/org/kontalk/xmppserver/registration/VerificationRepository.java // public interface VerificationRepository { // // /** Length of a verification code. */ // int VERIFICATION_CODE_LENGTH = 6; // // /** Registers a new verification code for the given user. */ // String generateVerificationCode(BareJID jid) throws AlreadyRegisteredException, TigaseDBException; // // /** Verifies and delete the given verification. */ // boolean verifyCode(BareJID jid, String code) throws TigaseDBException; // // /** Purges old verification entries from storage. */ // void purge() throws TigaseDBException; // // /** Exception thrown when the user has already tried to register recently. */ // final class AlreadyRegisteredException extends Exception { // private static final long serialVersionUID = 1L; // } // // }
import org.junit.Before; import org.junit.Test; import org.kontalk.xmppserver.registration.AbstractSMSVerificationProvider; import org.kontalk.xmppserver.registration.PhoneNumberVerificationProvider; import org.kontalk.xmppserver.registration.RegistrationRequest; import org.kontalk.xmppserver.registration.VerificationRepository; import tigase.db.TigaseDBException; import tigase.xmpp.XMPPResourceConnection; import java.io.IOException; import java.util.HashMap; import java.util.Map;
protected abstract SecurityProvider buildSecurityProvider(); protected abstract void addConfiguration(Map<String, Object> settings); @Test public abstract void testPass(); @Test public abstract void testNotPass(); @Test public abstract void testNotPassExpire(); protected void sleep(long seconds) { try { Thread.sleep(seconds*1000); } catch (InterruptedException ignored) { } } private static final class MyVerificationProvider extends AbstractSMSVerificationProvider { @Override public String getAckInstructions() { return null; } @Override
// Path: src/main/java/org/kontalk/xmppserver/registration/AbstractSMSVerificationProvider.java // public abstract class AbstractSMSVerificationProvider implements PhoneNumberVerificationProvider { // // protected String senderId; // protected String brandImageVector; // protected String brandImageSmall; // protected String brandImageMedium; // protected String brandImageLarge; // protected String brandImageHighDef; // protected String brandLink; // // @Override // public void init(Map<String, Object> settings) throws TigaseDBException, ConfigurationException { // senderId = (String) settings.get("sender"); // brandImageVector = (String) settings.get("brand-image-vector"); // brandImageSmall = (String) settings.get("brand-image-small"); // brandImageMedium = (String) settings.get("brand-image-medium"); // brandImageLarge = (String) settings.get("brand-image-large"); // brandImageHighDef = (String) settings.get("brand-image-hd"); // brandLink = (String) settings.get("brand-link"); // } // // @Override // public String getSenderId() { // return senderId; // } // // @Override // public String getBrandImageVector() { // return brandImageVector; // } // // @Override // public String getBrandImageSmall() { // return brandImageSmall; // } // // @Override // public String getBrandImageMedium() { // return brandImageMedium; // } // // @Override // public String getBrandImageLarge() { // return brandImageLarge; // } // // @Override // public String getBrandImageHighDef() { // return brandImageHighDef; // } // // @Override // public String getBrandLink() { // return brandLink; // } // // } // // Path: src/main/java/org/kontalk/xmppserver/registration/PhoneNumberVerificationProvider.java // public interface PhoneNumberVerificationProvider { // // /** Challenge the user with a verification PIN sent through a SMS or a told through a phone call. */ // String CHALLENGE_PIN = "pin"; // /** Challenge the user with a missed call from a random number and making the user guess the digits. */ // String CHALLENGE_MISSED_CALL = "missedcall"; // /** Challenge the user with the caller ID presented in a user-initiated call to a given phone number. */ // String CHALLENGE_CALLER_ID = "callerid"; // // void init(Map<String, Object> settings) throws TigaseDBException, ConfigurationException; // // String getSenderId(); // // String getAckInstructions(); // // /** // * Initiates a verification. // * @param phoneNumber the phone number being verified // * @return a request object of some kind that you will give to {@link #endVerification}. // */ // RegistrationRequest startVerification(String domain, String phoneNumber) // throws IOException, VerificationRepository.AlreadyRegisteredException, TigaseDBException; // // /** // * Ends a verification. // * @param request request object as returned by {@link #startVerification} // * @param proof the proof of the verification (e.g. verification code) // * @return true if verification succeded, false otherwise. // */ // boolean endVerification(XMPPResourceConnection session, RegistrationRequest request, String proof) throws IOException, TigaseDBException; // // /** Returns true if this provider supports this kind if registration request. */ // boolean supportsRequest(RegistrationRequest request); // // /** The challenge type implemented by this provider. */ // String getChallengeType(); // // /** The brand vector image logo for this provider, if any. */ // default String getBrandImageVector() { // return null; // } // // /** The brand small image logo for this provider, if any. */ // default String getBrandImageSmall() { // return null; // } // // /** The brand medium image logo for this provider, if any. */ // default String getBrandImageMedium() { // return null; // } // // /** The brand large image logo for this provider, if any. */ // default String getBrandImageLarge() { // return null; // } // // /** The brand HD image logo for this provider, if any. */ // default String getBrandImageHighDef() { // return null; // } // // /** The brand link the image logo will point to, if any. */ // default String getBrandLink() { // return null; // } // // } // // Path: src/main/java/org/kontalk/xmppserver/registration/RegistrationRequest.java // public interface RegistrationRequest { // // /** Returns the sender id of the call/SMS/whatever. */ // String getSenderId(); // // } // // Path: src/main/java/org/kontalk/xmppserver/registration/VerificationRepository.java // public interface VerificationRepository { // // /** Length of a verification code. */ // int VERIFICATION_CODE_LENGTH = 6; // // /** Registers a new verification code for the given user. */ // String generateVerificationCode(BareJID jid) throws AlreadyRegisteredException, TigaseDBException; // // /** Verifies and delete the given verification. */ // boolean verifyCode(BareJID jid, String code) throws TigaseDBException; // // /** Purges old verification entries from storage. */ // void purge() throws TigaseDBException; // // /** Exception thrown when the user has already tried to register recently. */ // final class AlreadyRegisteredException extends Exception { // private static final long serialVersionUID = 1L; // } // // } // Path: src/test/java/org/kontalk/xmppserver/registration/security/BaseThrottlingSecurityProviderTest.java import org.junit.Before; import org.junit.Test; import org.kontalk.xmppserver.registration.AbstractSMSVerificationProvider; import org.kontalk.xmppserver.registration.PhoneNumberVerificationProvider; import org.kontalk.xmppserver.registration.RegistrationRequest; import org.kontalk.xmppserver.registration.VerificationRepository; import tigase.db.TigaseDBException; import tigase.xmpp.XMPPResourceConnection; import java.io.IOException; import java.util.HashMap; import java.util.Map; protected abstract SecurityProvider buildSecurityProvider(); protected abstract void addConfiguration(Map<String, Object> settings); @Test public abstract void testPass(); @Test public abstract void testNotPass(); @Test public abstract void testNotPassExpire(); protected void sleep(long seconds) { try { Thread.sleep(seconds*1000); } catch (InterruptedException ignored) { } } private static final class MyVerificationProvider extends AbstractSMSVerificationProvider { @Override public String getAckInstructions() { return null; } @Override
public RegistrationRequest startVerification(String domain, String phoneNumber) throws IOException, VerificationRepository.AlreadyRegisteredException, TigaseDBException {
kontalk/tigase-extension
src/main/java/org/kontalk/xmppserver/ServerListCommand.java
// Path: src/main/java/org/kontalk/xmppserver/probe/ServerlistRepository.java // public interface ServerlistRepository { // // void init(Map<String, Object> props) throws DBInitException; // // void reload() throws TigaseDBException; // // List<ServerInfo> getList(); // // boolean isNetworkDomain(String domain); // // class ServerInfo { // private String fingerprint; // private String host; // private boolean enabled; // // protected ServerInfo(String fingerprint, String host, boolean enabled) { // this.fingerprint = fingerprint; // this.host = host; // this.enabled = enabled; // } // // public String getFingerprint() { // return fingerprint; // } // // public String getHost() { // return host; // } // // public boolean isEnabled() { // return enabled; // } // } // // }
import org.kontalk.xmppserver.probe.ServerlistRepository; import tigase.component.adhoc.AdHocCommand; import tigase.component.adhoc.AdHocCommandException; import tigase.component.adhoc.AdHocResponse; import tigase.component.adhoc.AdhHocRequest; import tigase.xml.Element; import tigase.xmpp.JID; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger;
/* * Kontalk XMPP Tigase extension * Copyright (C) 2017 Kontalk Devteam <devteam@kontalk.org> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kontalk.xmppserver; /** * Server list ad-hoc command. * @author Daniele Ricci */ public class ServerListCommand implements AdHocCommand { private static final Logger log = Logger.getLogger(ServerListCommand.class.getName()); private static final String ELEM_NAME = "serverlist"; private static final String NAMESPACE = "http://kontalk.org/extensions/serverlist"; private final NetworkContext context; public ServerListCommand(NetworkContext context) { this.context = context; } @Override public void execute(AdhHocRequest request, AdHocResponse response) throws AdHocCommandException { log.log(Level.FINEST, "executing command " + request); Element list = new Element(ELEM_NAME); list.setXMLNS(NAMESPACE); // retrieve server list
// Path: src/main/java/org/kontalk/xmppserver/probe/ServerlistRepository.java // public interface ServerlistRepository { // // void init(Map<String, Object> props) throws DBInitException; // // void reload() throws TigaseDBException; // // List<ServerInfo> getList(); // // boolean isNetworkDomain(String domain); // // class ServerInfo { // private String fingerprint; // private String host; // private boolean enabled; // // protected ServerInfo(String fingerprint, String host, boolean enabled) { // this.fingerprint = fingerprint; // this.host = host; // this.enabled = enabled; // } // // public String getFingerprint() { // return fingerprint; // } // // public String getHost() { // return host; // } // // public boolean isEnabled() { // return enabled; // } // } // // } // Path: src/main/java/org/kontalk/xmppserver/ServerListCommand.java import org.kontalk.xmppserver.probe.ServerlistRepository; import tigase.component.adhoc.AdHocCommand; import tigase.component.adhoc.AdHocCommandException; import tigase.component.adhoc.AdHocResponse; import tigase.component.adhoc.AdhHocRequest; import tigase.xml.Element; import tigase.xmpp.JID; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /* * Kontalk XMPP Tigase extension * Copyright (C) 2017 Kontalk Devteam <devteam@kontalk.org> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kontalk.xmppserver; /** * Server list ad-hoc command. * @author Daniele Ricci */ public class ServerListCommand implements AdHocCommand { private static final Logger log = Logger.getLogger(ServerListCommand.class.getName()); private static final String ELEM_NAME = "serverlist"; private static final String NAMESPACE = "http://kontalk.org/extensions/serverlist"; private final NetworkContext context; public ServerListCommand(NetworkContext context) { this.context = context; } @Override public void execute(AdhHocRequest request, AdHocResponse response) throws AdHocCommandException { log.log(Level.FINEST, "executing command " + request); Element list = new Element(ELEM_NAME); list.setXMLNS(NAMESPACE); // retrieve server list
List<ServerlistRepository.ServerInfo> slist = context.getServerList();
kontalk/tigase-extension
src/main/java/org/kontalk/xmppserver/pgp/BerkeleyPGPLocalKeyring.java
// Path: src/main/java/org/kontalk/xmppserver/util/Utils.java // public class Utils { // // public static String generateRandomNumericString(int length) { // StringBuilder buffer = new StringBuilder(); // final String characters = "1234567890"; // // int charactersLength = characters.length(); // // for (int i = 0; i < length; i++) { // double index = Math.random() * charactersLength; // buffer.append(characters.charAt((int) index)); // } // return buffer.toString(); // } // // // directly from OpenJDK 8 DatatypeConverterImpl // public static byte[] parseHexBinary(String s) { // int len = s.length(); // if (len % 2 != 0) { // throw new IllegalArgumentException("hexBinary needs to be even-length: " + s); // } // else { // byte[] out = new byte[len / 2]; // // for(int i = 0; i < len; i += 2) { // int h = hexToBin(s.charAt(i)); // int l = hexToBin(s.charAt(i + 1)); // if (h == -1 || l == -1) { // throw new IllegalArgumentException("contains illegal character for hexBinary: " + s); // } // // out[i / 2] = (byte)(h * 16 + l); // } // // return out; // } // } // // // directly from OpenJDK 8 DatatypeConverterImpl // private static int hexToBin(char ch) { // if ('0' <= ch && ch <= '9') { // return ch - 48; // } // else if ('A' <= ch && ch <= 'F') { // return ch - 65 + 10; // } // else { // return 'a' <= ch && ch <= 'f' ? ch - 97 + 10 : -1; // } // } // // }
import com.sleepycat.je.*; import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPPublicKeyRing; import org.kontalk.xmppserver.util.Utils; import java.io.File; import java.io.IOException; import java.io.InputStream;
db.put(null, new DatabaseEntry(fingerprintKey(fpr)), new DatabaseEntry(newring.getEncoded())); } catch (DatabaseException e) { throw new IOException("Database error", e); } return newring; } @Override public void close() throws IOException { db.close(); } // TODO signKey method? private PGPPublicKeyRing getKey(byte[] fingerprint) throws IOException, PGPException { DatabaseEntry data = new DatabaseEntry(); try { if (db.get(null, new DatabaseEntry(fingerprint), data, LockMode.DEFAULT) == OperationStatus.SUCCESS) { return PGPUtils.readPublicKeyring(data.getData()); } } catch (DatabaseException e) { throw new IOException("Database error", e); } return null; } private byte[] fingerprintKey(String s) {
// Path: src/main/java/org/kontalk/xmppserver/util/Utils.java // public class Utils { // // public static String generateRandomNumericString(int length) { // StringBuilder buffer = new StringBuilder(); // final String characters = "1234567890"; // // int charactersLength = characters.length(); // // for (int i = 0; i < length; i++) { // double index = Math.random() * charactersLength; // buffer.append(characters.charAt((int) index)); // } // return buffer.toString(); // } // // // directly from OpenJDK 8 DatatypeConverterImpl // public static byte[] parseHexBinary(String s) { // int len = s.length(); // if (len % 2 != 0) { // throw new IllegalArgumentException("hexBinary needs to be even-length: " + s); // } // else { // byte[] out = new byte[len / 2]; // // for(int i = 0; i < len; i += 2) { // int h = hexToBin(s.charAt(i)); // int l = hexToBin(s.charAt(i + 1)); // if (h == -1 || l == -1) { // throw new IllegalArgumentException("contains illegal character for hexBinary: " + s); // } // // out[i / 2] = (byte)(h * 16 + l); // } // // return out; // } // } // // // directly from OpenJDK 8 DatatypeConverterImpl // private static int hexToBin(char ch) { // if ('0' <= ch && ch <= '9') { // return ch - 48; // } // else if ('A' <= ch && ch <= 'F') { // return ch - 65 + 10; // } // else { // return 'a' <= ch && ch <= 'f' ? ch - 97 + 10 : -1; // } // } // // } // Path: src/main/java/org/kontalk/xmppserver/pgp/BerkeleyPGPLocalKeyring.java import com.sleepycat.je.*; import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPPublicKeyRing; import org.kontalk.xmppserver.util.Utils; import java.io.File; import java.io.IOException; import java.io.InputStream; db.put(null, new DatabaseEntry(fingerprintKey(fpr)), new DatabaseEntry(newring.getEncoded())); } catch (DatabaseException e) { throw new IOException("Database error", e); } return newring; } @Override public void close() throws IOException { db.close(); } // TODO signKey method? private PGPPublicKeyRing getKey(byte[] fingerprint) throws IOException, PGPException { DatabaseEntry data = new DatabaseEntry(); try { if (db.get(null, new DatabaseEntry(fingerprint), data, LockMode.DEFAULT) == OperationStatus.SUCCESS) { return PGPUtils.readPublicKeyring(data.getData()); } } catch (DatabaseException e) { throw new IOException("Database error", e); } return null; } private byte[] fingerprintKey(String s) {
return Utils.parseHexBinary(s);
kontalk/tigase-extension
src/main/java/org/kontalk/xmppserver/registration/security/AbstractThrottlingSecurityProvider.java
// Path: src/main/java/org/kontalk/xmppserver/registration/PhoneNumberVerificationProvider.java // public interface PhoneNumberVerificationProvider { // // /** Challenge the user with a verification PIN sent through a SMS or a told through a phone call. */ // String CHALLENGE_PIN = "pin"; // /** Challenge the user with a missed call from a random number and making the user guess the digits. */ // String CHALLENGE_MISSED_CALL = "missedcall"; // /** Challenge the user with the caller ID presented in a user-initiated call to a given phone number. */ // String CHALLENGE_CALLER_ID = "callerid"; // // void init(Map<String, Object> settings) throws TigaseDBException, ConfigurationException; // // String getSenderId(); // // String getAckInstructions(); // // /** // * Initiates a verification. // * @param phoneNumber the phone number being verified // * @return a request object of some kind that you will give to {@link #endVerification}. // */ // RegistrationRequest startVerification(String domain, String phoneNumber) // throws IOException, VerificationRepository.AlreadyRegisteredException, TigaseDBException; // // /** // * Ends a verification. // * @param request request object as returned by {@link #startVerification} // * @param proof the proof of the verification (e.g. verification code) // * @return true if verification succeded, false otherwise. // */ // boolean endVerification(XMPPResourceConnection session, RegistrationRequest request, String proof) throws IOException, TigaseDBException; // // /** Returns true if this provider supports this kind if registration request. */ // boolean supportsRequest(RegistrationRequest request); // // /** The challenge type implemented by this provider. */ // String getChallengeType(); // // /** The brand vector image logo for this provider, if any. */ // default String getBrandImageVector() { // return null; // } // // /** The brand small image logo for this provider, if any. */ // default String getBrandImageSmall() { // return null; // } // // /** The brand medium image logo for this provider, if any. */ // default String getBrandImageMedium() { // return null; // } // // /** The brand large image logo for this provider, if any. */ // default String getBrandImageLarge() { // return null; // } // // /** The brand HD image logo for this provider, if any. */ // default String getBrandImageHighDef() { // return null; // } // // /** The brand link the image logo will point to, if any. */ // default String getBrandLink() { // return null; // } // // }
import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import org.kontalk.xmppserver.registration.PhoneNumberVerificationProvider; import tigase.conf.ConfigurationException; import tigase.db.TigaseDBException; import tigase.xmpp.BareJID; import tigase.xmpp.JID; import java.util.Map; import java.util.concurrent.TimeUnit;
/* * Kontalk XMPP Tigase extension * Copyright (C) 2017 Kontalk Devteam <devteam@kontalk.org> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kontalk.xmppserver.registration.security; /** * Security provider for phone-based throttling. * @author Daniele Ricci */ public abstract class AbstractThrottlingSecurityProvider implements SecurityProvider { private static final int DEFAULT_THROTTLING_ATTEMPTS = 3; private static final long DEFAULT_THROTTLING_DELAY = TimeUnit.MINUTES.toSeconds(30); /** Stores useful data for detecting registration throttling. */ private static final class LastRegisterRequest { /** Number of requests so far. */ public int attempts; /** Timestamp of last request. */ public long lastTimestamp; } private Cache<String, LastRegisterRequest> throttlingRequests; private int delayMillis; private int triggerAttempts; /** * Child classes should return the identifier to use as a key for throttling purposes. * @return an identifier to use as throttling key or null to pass automatically. */ protected abstract String getIdentifier(JID connectionId, BareJID jid, String phone); @Override public void init(Map<String, Object> settings) throws TigaseDBException, ConfigurationException { delayMillis = (int) settings.getOrDefault("delay", DEFAULT_THROTTLING_DELAY) * 1000; triggerAttempts = (int) settings.getOrDefault("trigger-attempts", DEFAULT_THROTTLING_ATTEMPTS); throttlingRequests = CacheBuilder.newBuilder() .expireAfterAccess(delayMillis, TimeUnit.MILLISECONDS) .maximumSize(100000) .build(); } @Override
// Path: src/main/java/org/kontalk/xmppserver/registration/PhoneNumberVerificationProvider.java // public interface PhoneNumberVerificationProvider { // // /** Challenge the user with a verification PIN sent through a SMS or a told through a phone call. */ // String CHALLENGE_PIN = "pin"; // /** Challenge the user with a missed call from a random number and making the user guess the digits. */ // String CHALLENGE_MISSED_CALL = "missedcall"; // /** Challenge the user with the caller ID presented in a user-initiated call to a given phone number. */ // String CHALLENGE_CALLER_ID = "callerid"; // // void init(Map<String, Object> settings) throws TigaseDBException, ConfigurationException; // // String getSenderId(); // // String getAckInstructions(); // // /** // * Initiates a verification. // * @param phoneNumber the phone number being verified // * @return a request object of some kind that you will give to {@link #endVerification}. // */ // RegistrationRequest startVerification(String domain, String phoneNumber) // throws IOException, VerificationRepository.AlreadyRegisteredException, TigaseDBException; // // /** // * Ends a verification. // * @param request request object as returned by {@link #startVerification} // * @param proof the proof of the verification (e.g. verification code) // * @return true if verification succeded, false otherwise. // */ // boolean endVerification(XMPPResourceConnection session, RegistrationRequest request, String proof) throws IOException, TigaseDBException; // // /** Returns true if this provider supports this kind if registration request. */ // boolean supportsRequest(RegistrationRequest request); // // /** The challenge type implemented by this provider. */ // String getChallengeType(); // // /** The brand vector image logo for this provider, if any. */ // default String getBrandImageVector() { // return null; // } // // /** The brand small image logo for this provider, if any. */ // default String getBrandImageSmall() { // return null; // } // // /** The brand medium image logo for this provider, if any. */ // default String getBrandImageMedium() { // return null; // } // // /** The brand large image logo for this provider, if any. */ // default String getBrandImageLarge() { // return null; // } // // /** The brand HD image logo for this provider, if any. */ // default String getBrandImageHighDef() { // return null; // } // // /** The brand link the image logo will point to, if any. */ // default String getBrandLink() { // return null; // } // // } // Path: src/main/java/org/kontalk/xmppserver/registration/security/AbstractThrottlingSecurityProvider.java import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import org.kontalk.xmppserver.registration.PhoneNumberVerificationProvider; import tigase.conf.ConfigurationException; import tigase.db.TigaseDBException; import tigase.xmpp.BareJID; import tigase.xmpp.JID; import java.util.Map; import java.util.concurrent.TimeUnit; /* * Kontalk XMPP Tigase extension * Copyright (C) 2017 Kontalk Devteam <devteam@kontalk.org> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kontalk.xmppserver.registration.security; /** * Security provider for phone-based throttling. * @author Daniele Ricci */ public abstract class AbstractThrottlingSecurityProvider implements SecurityProvider { private static final int DEFAULT_THROTTLING_ATTEMPTS = 3; private static final long DEFAULT_THROTTLING_DELAY = TimeUnit.MINUTES.toSeconds(30); /** Stores useful data for detecting registration throttling. */ private static final class LastRegisterRequest { /** Number of requests so far. */ public int attempts; /** Timestamp of last request. */ public long lastTimestamp; } private Cache<String, LastRegisterRequest> throttlingRequests; private int delayMillis; private int triggerAttempts; /** * Child classes should return the identifier to use as a key for throttling purposes. * @return an identifier to use as throttling key or null to pass automatically. */ protected abstract String getIdentifier(JID connectionId, BareJID jid, String phone); @Override public void init(Map<String, Object> settings) throws TigaseDBException, ConfigurationException { delayMillis = (int) settings.getOrDefault("delay", DEFAULT_THROTTLING_DELAY) * 1000; triggerAttempts = (int) settings.getOrDefault("trigger-attempts", DEFAULT_THROTTLING_ATTEMPTS); throttlingRequests = CacheBuilder.newBuilder() .expireAfterAccess(delayMillis, TimeUnit.MILLISECONDS) .maximumSize(100000) .build(); } @Override
public boolean pass(JID connectionId, BareJID jid, String phone, PhoneNumberVerificationProvider provider) {
kontalk/tigase-extension
src/main/java/org/kontalk/xmppserver/pgp/KyotoPGPLocalKeyring.java
// Path: src/main/java/org/kontalk/xmppserver/util/Utils.java // public class Utils { // // public static String generateRandomNumericString(int length) { // StringBuilder buffer = new StringBuilder(); // final String characters = "1234567890"; // // int charactersLength = characters.length(); // // for (int i = 0; i < length; i++) { // double index = Math.random() * charactersLength; // buffer.append(characters.charAt((int) index)); // } // return buffer.toString(); // } // // // directly from OpenJDK 8 DatatypeConverterImpl // public static byte[] parseHexBinary(String s) { // int len = s.length(); // if (len % 2 != 0) { // throw new IllegalArgumentException("hexBinary needs to be even-length: " + s); // } // else { // byte[] out = new byte[len / 2]; // // for(int i = 0; i < len; i += 2) { // int h = hexToBin(s.charAt(i)); // int l = hexToBin(s.charAt(i + 1)); // if (h == -1 || l == -1) { // throw new IllegalArgumentException("contains illegal character for hexBinary: " + s); // } // // out[i / 2] = (byte)(h * 16 + l); // } // // return out; // } // } // // // directly from OpenJDK 8 DatatypeConverterImpl // private static int hexToBin(char ch) { // if ('0' <= ch && ch <= '9') { // return ch - 48; // } // else if ('A' <= ch && ch <= 'F') { // return ch - 65 + 10; // } // else { // return 'a' <= ch && ch <= 'f' ? ch - 97 + 10 : -1; // } // } // // }
import java.io.IOException; import java.io.InputStream; import fm.last.commons.kyoto.DbType; import fm.last.commons.kyoto.KyotoDb; import fm.last.commons.kyoto.ReadOnlyVisitor; import fm.last.commons.kyoto.factory.KyotoDbBuilder; import fm.last.commons.kyoto.factory.Mode; import fm.last.commons.lang.units.JedecByteUnit; import org.apache.log4j.BasicConfigurator; import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPPublicKeyRing; import org.kontalk.xmppserver.util.Utils; import java.io.File;
String fpr = PGPUtils.getFingerprint(keyring); PGPPublicKeyRing newring; PGPPublicKeyRing oldring = getKey(fpr); if (oldring != null) { newring = PGPUtils.merge(oldring, keyring); } else { newring = keyring; } db.set(fingerprintKey(fpr), newring.getEncoded()); return newring; } @Override public void close() throws IOException { db.close(); } // TODO signKey method? private PGPPublicKeyRing getKey(byte[] fingerprint) throws IOException, PGPException { byte[] data = db.get(fingerprint); if (data != null) return PGPUtils.readPublicKeyring(data); return null; } private byte[] fingerprintKey(String s) {
// Path: src/main/java/org/kontalk/xmppserver/util/Utils.java // public class Utils { // // public static String generateRandomNumericString(int length) { // StringBuilder buffer = new StringBuilder(); // final String characters = "1234567890"; // // int charactersLength = characters.length(); // // for (int i = 0; i < length; i++) { // double index = Math.random() * charactersLength; // buffer.append(characters.charAt((int) index)); // } // return buffer.toString(); // } // // // directly from OpenJDK 8 DatatypeConverterImpl // public static byte[] parseHexBinary(String s) { // int len = s.length(); // if (len % 2 != 0) { // throw new IllegalArgumentException("hexBinary needs to be even-length: " + s); // } // else { // byte[] out = new byte[len / 2]; // // for(int i = 0; i < len; i += 2) { // int h = hexToBin(s.charAt(i)); // int l = hexToBin(s.charAt(i + 1)); // if (h == -1 || l == -1) { // throw new IllegalArgumentException("contains illegal character for hexBinary: " + s); // } // // out[i / 2] = (byte)(h * 16 + l); // } // // return out; // } // } // // // directly from OpenJDK 8 DatatypeConverterImpl // private static int hexToBin(char ch) { // if ('0' <= ch && ch <= '9') { // return ch - 48; // } // else if ('A' <= ch && ch <= 'F') { // return ch - 65 + 10; // } // else { // return 'a' <= ch && ch <= 'f' ? ch - 97 + 10 : -1; // } // } // // } // Path: src/main/java/org/kontalk/xmppserver/pgp/KyotoPGPLocalKeyring.java import java.io.IOException; import java.io.InputStream; import fm.last.commons.kyoto.DbType; import fm.last.commons.kyoto.KyotoDb; import fm.last.commons.kyoto.ReadOnlyVisitor; import fm.last.commons.kyoto.factory.KyotoDbBuilder; import fm.last.commons.kyoto.factory.Mode; import fm.last.commons.lang.units.JedecByteUnit; import org.apache.log4j.BasicConfigurator; import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPPublicKeyRing; import org.kontalk.xmppserver.util.Utils; import java.io.File; String fpr = PGPUtils.getFingerprint(keyring); PGPPublicKeyRing newring; PGPPublicKeyRing oldring = getKey(fpr); if (oldring != null) { newring = PGPUtils.merge(oldring, keyring); } else { newring = keyring; } db.set(fingerprintKey(fpr), newring.getEncoded()); return newring; } @Override public void close() throws IOException { db.close(); } // TODO signKey method? private PGPPublicKeyRing getKey(byte[] fingerprint) throws IOException, PGPException { byte[] data = db.get(fingerprint); if (data != null) return PGPUtils.readPublicKeyring(data); return null; } private byte[] fingerprintKey(String s) {
return Utils.parseHexBinary(s);
kontalk/tigase-extension
src/main/java/org/kontalk/xmppserver/NetworkComponent.java
// Path: src/main/java/org/kontalk/xmppserver/probe/DataServerlistRepository.java // public class DataServerlistRepository implements ServerlistRepository { // // private static final String SELECT_QUERY_SQL = "SELECT fingerprint, host, enabled FROM servers"; // // private DataRepository repo; // private List<ServerInfo> serverlist; // // @Override // public void init(Map<String, Object> props) throws DBInitException { // try { // String dbUri = (String) props.get("db-uri"); // if (dbUri == null) { // // fallback on user database // dbUri = System.getProperty(RepositoryFactory.GEN_USER_DB_URI_PROP_KEY); // } // if (dbUri != null) { // repo = RepositoryFactory.getDataRepository(null, dbUri, null); // } // } // catch (Exception e) { // throw new DBInitException("error initializing push data storage", e); // } // } // // @Override // public List<ServerInfo> getList() { // return serverlist; // } // // @Override // public boolean isNetworkDomain(String domain) { // if (serverlist != null) { // for (ServerInfo server : serverlist) { // if (server.getHost().equalsIgnoreCase(domain)) // return true; // } // } // return false; // } // // @Override // public void reload() throws TigaseDBException { // Statement stm = null; // ResultSet rs = null; // try { // stm = repo.createStatement(null); // rs = stm.executeQuery(SELECT_QUERY_SQL); // serverlist = new LinkedList<ServerInfo>(); // while (rs.next()) { // String fpr = rs.getString(1); // String host = rs.getString(2); // int enabled = rs.getInt(3); // serverlist.add(new ServerInfo(fpr, host, enabled != 0)); // } // } // catch (SQLException e) { // throw new TigaseDBException(e.getMessage(), e); // } // finally { // repo.release(stm, rs); // } // } // // } // // Path: src/main/java/org/kontalk/xmppserver/probe/ServerlistRepository.java // public interface ServerlistRepository { // // void init(Map<String, Object> props) throws DBInitException; // // void reload() throws TigaseDBException; // // List<ServerInfo> getList(); // // boolean isNetworkDomain(String domain); // // class ServerInfo { // private String fingerprint; // private String host; // private boolean enabled; // // protected ServerInfo(String fingerprint, String host, boolean enabled) { // this.fingerprint = fingerprint; // this.host = host; // this.enabled = enabled; // } // // public String getFingerprint() { // return fingerprint; // } // // public String getHost() { // return host; // } // // public boolean isEnabled() { // return enabled; // } // } // // }
import java.util.List; import java.util.Map; import org.kontalk.xmppserver.probe.DataServerlistRepository; import org.kontalk.xmppserver.probe.ServerlistRepository; import tigase.component.AbstractComponent; import tigase.component.AbstractContext; import tigase.component.modules.Module; import tigase.component.modules.impl.AdHocCommandModule; import tigase.component.modules.impl.DiscoveryModule; import tigase.component.modules.impl.JabberVersionModule; import tigase.component.modules.impl.XmppPingModule; import tigase.conf.ConfigurationException; import java.util.HashMap;
/* * Kontalk XMPP Tigase extension * Copyright (C) 2017 Kontalk Devteam <devteam@kontalk.org> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kontalk.xmppserver; /** * Component that handles commands for the network (e.g. server list). * @author Daniele Ricci */ public class NetworkComponent extends AbstractComponent<NetworkContext> { private DataServerlistRepository serverListRepo; private class NetworkContextImpl extends AbstractContext implements NetworkContext { public NetworkContextImpl(AbstractComponent<?> component) { super(component); } @Override
// Path: src/main/java/org/kontalk/xmppserver/probe/DataServerlistRepository.java // public class DataServerlistRepository implements ServerlistRepository { // // private static final String SELECT_QUERY_SQL = "SELECT fingerprint, host, enabled FROM servers"; // // private DataRepository repo; // private List<ServerInfo> serverlist; // // @Override // public void init(Map<String, Object> props) throws DBInitException { // try { // String dbUri = (String) props.get("db-uri"); // if (dbUri == null) { // // fallback on user database // dbUri = System.getProperty(RepositoryFactory.GEN_USER_DB_URI_PROP_KEY); // } // if (dbUri != null) { // repo = RepositoryFactory.getDataRepository(null, dbUri, null); // } // } // catch (Exception e) { // throw new DBInitException("error initializing push data storage", e); // } // } // // @Override // public List<ServerInfo> getList() { // return serverlist; // } // // @Override // public boolean isNetworkDomain(String domain) { // if (serverlist != null) { // for (ServerInfo server : serverlist) { // if (server.getHost().equalsIgnoreCase(domain)) // return true; // } // } // return false; // } // // @Override // public void reload() throws TigaseDBException { // Statement stm = null; // ResultSet rs = null; // try { // stm = repo.createStatement(null); // rs = stm.executeQuery(SELECT_QUERY_SQL); // serverlist = new LinkedList<ServerInfo>(); // while (rs.next()) { // String fpr = rs.getString(1); // String host = rs.getString(2); // int enabled = rs.getInt(3); // serverlist.add(new ServerInfo(fpr, host, enabled != 0)); // } // } // catch (SQLException e) { // throw new TigaseDBException(e.getMessage(), e); // } // finally { // repo.release(stm, rs); // } // } // // } // // Path: src/main/java/org/kontalk/xmppserver/probe/ServerlistRepository.java // public interface ServerlistRepository { // // void init(Map<String, Object> props) throws DBInitException; // // void reload() throws TigaseDBException; // // List<ServerInfo> getList(); // // boolean isNetworkDomain(String domain); // // class ServerInfo { // private String fingerprint; // private String host; // private boolean enabled; // // protected ServerInfo(String fingerprint, String host, boolean enabled) { // this.fingerprint = fingerprint; // this.host = host; // this.enabled = enabled; // } // // public String getFingerprint() { // return fingerprint; // } // // public String getHost() { // return host; // } // // public boolean isEnabled() { // return enabled; // } // } // // } // Path: src/main/java/org/kontalk/xmppserver/NetworkComponent.java import java.util.List; import java.util.Map; import org.kontalk.xmppserver.probe.DataServerlistRepository; import org.kontalk.xmppserver.probe.ServerlistRepository; import tigase.component.AbstractComponent; import tigase.component.AbstractContext; import tigase.component.modules.Module; import tigase.component.modules.impl.AdHocCommandModule; import tigase.component.modules.impl.DiscoveryModule; import tigase.component.modules.impl.JabberVersionModule; import tigase.component.modules.impl.XmppPingModule; import tigase.conf.ConfigurationException; import java.util.HashMap; /* * Kontalk XMPP Tigase extension * Copyright (C) 2017 Kontalk Devteam <devteam@kontalk.org> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kontalk.xmppserver; /** * Component that handles commands for the network (e.g. server list). * @author Daniele Ricci */ public class NetworkComponent extends AbstractComponent<NetworkContext> { private DataServerlistRepository serverListRepo; private class NetworkContextImpl extends AbstractContext implements NetworkContext { public NetworkContextImpl(AbstractComponent<?> component) { super(component); } @Override
public List<ServerlistRepository.ServerInfo> getServerList() {
kontalk/tigase-extension
src/main/java/org/kontalk/xmppserver/registration/security/SecurityProvider.java
// Path: src/main/java/org/kontalk/xmppserver/registration/PhoneNumberVerificationProvider.java // public interface PhoneNumberVerificationProvider { // // /** Challenge the user with a verification PIN sent through a SMS or a told through a phone call. */ // String CHALLENGE_PIN = "pin"; // /** Challenge the user with a missed call from a random number and making the user guess the digits. */ // String CHALLENGE_MISSED_CALL = "missedcall"; // /** Challenge the user with the caller ID presented in a user-initiated call to a given phone number. */ // String CHALLENGE_CALLER_ID = "callerid"; // // void init(Map<String, Object> settings) throws TigaseDBException, ConfigurationException; // // String getSenderId(); // // String getAckInstructions(); // // /** // * Initiates a verification. // * @param phoneNumber the phone number being verified // * @return a request object of some kind that you will give to {@link #endVerification}. // */ // RegistrationRequest startVerification(String domain, String phoneNumber) // throws IOException, VerificationRepository.AlreadyRegisteredException, TigaseDBException; // // /** // * Ends a verification. // * @param request request object as returned by {@link #startVerification} // * @param proof the proof of the verification (e.g. verification code) // * @return true if verification succeded, false otherwise. // */ // boolean endVerification(XMPPResourceConnection session, RegistrationRequest request, String proof) throws IOException, TigaseDBException; // // /** Returns true if this provider supports this kind if registration request. */ // boolean supportsRequest(RegistrationRequest request); // // /** The challenge type implemented by this provider. */ // String getChallengeType(); // // /** The brand vector image logo for this provider, if any. */ // default String getBrandImageVector() { // return null; // } // // /** The brand small image logo for this provider, if any. */ // default String getBrandImageSmall() { // return null; // } // // /** The brand medium image logo for this provider, if any. */ // default String getBrandImageMedium() { // return null; // } // // /** The brand large image logo for this provider, if any. */ // default String getBrandImageLarge() { // return null; // } // // /** The brand HD image logo for this provider, if any. */ // default String getBrandImageHighDef() { // return null; // } // // /** The brand link the image logo will point to, if any. */ // default String getBrandLink() { // return null; // } // // }
import org.kontalk.xmppserver.registration.PhoneNumberVerificationProvider; import tigase.conf.ConfigurationException; import tigase.db.TigaseDBException; import tigase.xmpp.BareJID; import tigase.xmpp.JID; import java.util.Map;
/* * Kontalk XMPP Tigase extension * Copyright (C) 2017 Kontalk Devteam <devteam@kontalk.org> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kontalk.xmppserver.registration.security; /** * Security provider interface. * Currently somewhat tied to the concept of throttling, but once we have more security features we'll adapt it. * @author Daniele Ricci */ public interface SecurityProvider { void init(Map<String, Object> settings) throws TigaseDBException, ConfigurationException; /** * Check if the registration may pass. * @return false to block the registration attempt as unsafe. */
// Path: src/main/java/org/kontalk/xmppserver/registration/PhoneNumberVerificationProvider.java // public interface PhoneNumberVerificationProvider { // // /** Challenge the user with a verification PIN sent through a SMS or a told through a phone call. */ // String CHALLENGE_PIN = "pin"; // /** Challenge the user with a missed call from a random number and making the user guess the digits. */ // String CHALLENGE_MISSED_CALL = "missedcall"; // /** Challenge the user with the caller ID presented in a user-initiated call to a given phone number. */ // String CHALLENGE_CALLER_ID = "callerid"; // // void init(Map<String, Object> settings) throws TigaseDBException, ConfigurationException; // // String getSenderId(); // // String getAckInstructions(); // // /** // * Initiates a verification. // * @param phoneNumber the phone number being verified // * @return a request object of some kind that you will give to {@link #endVerification}. // */ // RegistrationRequest startVerification(String domain, String phoneNumber) // throws IOException, VerificationRepository.AlreadyRegisteredException, TigaseDBException; // // /** // * Ends a verification. // * @param request request object as returned by {@link #startVerification} // * @param proof the proof of the verification (e.g. verification code) // * @return true if verification succeded, false otherwise. // */ // boolean endVerification(XMPPResourceConnection session, RegistrationRequest request, String proof) throws IOException, TigaseDBException; // // /** Returns true if this provider supports this kind if registration request. */ // boolean supportsRequest(RegistrationRequest request); // // /** The challenge type implemented by this provider. */ // String getChallengeType(); // // /** The brand vector image logo for this provider, if any. */ // default String getBrandImageVector() { // return null; // } // // /** The brand small image logo for this provider, if any. */ // default String getBrandImageSmall() { // return null; // } // // /** The brand medium image logo for this provider, if any. */ // default String getBrandImageMedium() { // return null; // } // // /** The brand large image logo for this provider, if any. */ // default String getBrandImageLarge() { // return null; // } // // /** The brand HD image logo for this provider, if any. */ // default String getBrandImageHighDef() { // return null; // } // // /** The brand link the image logo will point to, if any. */ // default String getBrandLink() { // return null; // } // // } // Path: src/main/java/org/kontalk/xmppserver/registration/security/SecurityProvider.java import org.kontalk.xmppserver.registration.PhoneNumberVerificationProvider; import tigase.conf.ConfigurationException; import tigase.db.TigaseDBException; import tigase.xmpp.BareJID; import tigase.xmpp.JID; import java.util.Map; /* * Kontalk XMPP Tigase extension * Copyright (C) 2017 Kontalk Devteam <devteam@kontalk.org> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kontalk.xmppserver.registration.security; /** * Security provider interface. * Currently somewhat tied to the concept of throttling, but once we have more security features we'll adapt it. * @author Daniele Ricci */ public interface SecurityProvider { void init(Map<String, Object> settings) throws TigaseDBException, ConfigurationException; /** * Check if the registration may pass. * @return false to block the registration attempt as unsafe. */
boolean pass(JID connectionId, BareJID jid, String phone, PhoneNumberVerificationProvider provider);
iFarSeer/TodoFluxArchitecture
app/src/main/java/com/farseer/todo/flux/database/DatabaseValuer.java
// Path: app/src/main/java/com/farseer/todo/flux/database/table/TBTodoItem.java // public final class TBTodoItem { // // /** // * TodoItem表名称. // */ // public static final String TABLE_NAME = "todo_item"; // // /** // * 字段id. // */ // public static final String ID = "_id"; // /** // * 字段description. // */ // public static final String DESCRIPTION = "description"; // // /** // * 字段is_complete. // */ // public static final String IS_COMPLETE = "is_complete"; // /** // * 字段is_star. // */ // public static final String IS_STAR = "is_star"; // // /** // * 创建表SQL语句. // */ // public static final String CREATE_SQL_V1 = "" // + "CREATE TABLE " + TBTodoItem.TABLE_NAME + "(" // + TBTodoItem.ID + " INTEGER NOT NULL PRIMARY KEY," // + TBTodoItem.DESCRIPTION + " TEXT NOT NULL," // + TBTodoItem.IS_COMPLETE + " INTEGER NOT NULL DEFAULT 0," // + TBTodoItem.IS_STAR + " INTEGER NOT NULL DEFAULT 0" // + ")"; // // /** // * 建立索引SQL语句. // */ // public static final String INDEX_SQL_V1 = "" // + "CREATE INDEX if not exists INDEX_" + TABLE_NAME + " on " // + TABLE_NAME + "(" // + ID + "," // + IS_COMPLETE + "," // + IS_STAR // + ");"; // // private TBTodoItem() { // //not called // } // } // // Path: app/src/main/java/com/farseer/todo/flux/pojo/TodoItem.java // public class TodoItem { // private Long id; // private String description; // private boolean completed; // private boolean stared; // // /** // * 构造Todo事项. // * @param id id // * @param description 描述 // */ // public TodoItem(Long id, String description) { // this(id, description, false, false); // } // // /** // * 构造Todo事项. // * @param id 构造Todo事项 // * @param description 描述 // * @param completed 是否已完成 // */ // public TodoItem(Long id, String description, boolean completed) { // this(id, description, completed, false); // } // // /** // * 构造Todo事项. // * @param id id // * @param description 描述 // * @param completed 是否已完成 // * @param stared 是否重要 // */ // public TodoItem(Long id, String description, boolean completed, boolean stared) { // this.stared = stared; // this.completed = completed; // this.description = description; // this.id = id; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public boolean isCompleted() { // return completed; // } // // public void setCompleted(boolean completed) { // this.completed = completed; // } // // public boolean isStared() { // return stared; // } // // public void setStared(boolean stared) { // this.stared = stared; // } // // @Override // public String toString() { // return "TodoItem{" // + "id=" // + id // + ", description='" // + description // + ", isCompleted=" // + completed // + ", isStared=" // + stared // + "}"; // } // }
import android.content.ContentValues; import com.farseer.todo.flux.database.table.TBTodoItem; import com.farseer.todo.flux.pojo.TodoItem;
/* * * Copyright 2016 zhaosc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.farseer.todo.flux.database; /** * DatabaseValuer * * @author zhaosc * @version 1.0.0 * @since 2016-05-05 */ public final class DatabaseValuer { private DatabaseValuer() { //not called } /** * 把TodoItem转换成ContentValues. * * @param item Item事项 * @return ContentValues */
// Path: app/src/main/java/com/farseer/todo/flux/database/table/TBTodoItem.java // public final class TBTodoItem { // // /** // * TodoItem表名称. // */ // public static final String TABLE_NAME = "todo_item"; // // /** // * 字段id. // */ // public static final String ID = "_id"; // /** // * 字段description. // */ // public static final String DESCRIPTION = "description"; // // /** // * 字段is_complete. // */ // public static final String IS_COMPLETE = "is_complete"; // /** // * 字段is_star. // */ // public static final String IS_STAR = "is_star"; // // /** // * 创建表SQL语句. // */ // public static final String CREATE_SQL_V1 = "" // + "CREATE TABLE " + TBTodoItem.TABLE_NAME + "(" // + TBTodoItem.ID + " INTEGER NOT NULL PRIMARY KEY," // + TBTodoItem.DESCRIPTION + " TEXT NOT NULL," // + TBTodoItem.IS_COMPLETE + " INTEGER NOT NULL DEFAULT 0," // + TBTodoItem.IS_STAR + " INTEGER NOT NULL DEFAULT 0" // + ")"; // // /** // * 建立索引SQL语句. // */ // public static final String INDEX_SQL_V1 = "" // + "CREATE INDEX if not exists INDEX_" + TABLE_NAME + " on " // + TABLE_NAME + "(" // + ID + "," // + IS_COMPLETE + "," // + IS_STAR // + ");"; // // private TBTodoItem() { // //not called // } // } // // Path: app/src/main/java/com/farseer/todo/flux/pojo/TodoItem.java // public class TodoItem { // private Long id; // private String description; // private boolean completed; // private boolean stared; // // /** // * 构造Todo事项. // * @param id id // * @param description 描述 // */ // public TodoItem(Long id, String description) { // this(id, description, false, false); // } // // /** // * 构造Todo事项. // * @param id 构造Todo事项 // * @param description 描述 // * @param completed 是否已完成 // */ // public TodoItem(Long id, String description, boolean completed) { // this(id, description, completed, false); // } // // /** // * 构造Todo事项. // * @param id id // * @param description 描述 // * @param completed 是否已完成 // * @param stared 是否重要 // */ // public TodoItem(Long id, String description, boolean completed, boolean stared) { // this.stared = stared; // this.completed = completed; // this.description = description; // this.id = id; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public boolean isCompleted() { // return completed; // } // // public void setCompleted(boolean completed) { // this.completed = completed; // } // // public boolean isStared() { // return stared; // } // // public void setStared(boolean stared) { // this.stared = stared; // } // // @Override // public String toString() { // return "TodoItem{" // + "id=" // + id // + ", description='" // + description // + ", isCompleted=" // + completed // + ", isStared=" // + stared // + "}"; // } // } // Path: app/src/main/java/com/farseer/todo/flux/database/DatabaseValuer.java import android.content.ContentValues; import com.farseer.todo.flux.database.table.TBTodoItem; import com.farseer.todo.flux.pojo.TodoItem; /* * * Copyright 2016 zhaosc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.farseer.todo.flux.database; /** * DatabaseValuer * * @author zhaosc * @version 1.0.0 * @since 2016-05-05 */ public final class DatabaseValuer { private DatabaseValuer() { //not called } /** * 把TodoItem转换成ContentValues. * * @param item Item事项 * @return ContentValues */
public static ContentValues todoItemValues(TodoItem item) {
iFarSeer/TodoFluxArchitecture
app/src/main/java/com/farseer/todo/flux/database/DatabaseValuer.java
// Path: app/src/main/java/com/farseer/todo/flux/database/table/TBTodoItem.java // public final class TBTodoItem { // // /** // * TodoItem表名称. // */ // public static final String TABLE_NAME = "todo_item"; // // /** // * 字段id. // */ // public static final String ID = "_id"; // /** // * 字段description. // */ // public static final String DESCRIPTION = "description"; // // /** // * 字段is_complete. // */ // public static final String IS_COMPLETE = "is_complete"; // /** // * 字段is_star. // */ // public static final String IS_STAR = "is_star"; // // /** // * 创建表SQL语句. // */ // public static final String CREATE_SQL_V1 = "" // + "CREATE TABLE " + TBTodoItem.TABLE_NAME + "(" // + TBTodoItem.ID + " INTEGER NOT NULL PRIMARY KEY," // + TBTodoItem.DESCRIPTION + " TEXT NOT NULL," // + TBTodoItem.IS_COMPLETE + " INTEGER NOT NULL DEFAULT 0," // + TBTodoItem.IS_STAR + " INTEGER NOT NULL DEFAULT 0" // + ")"; // // /** // * 建立索引SQL语句. // */ // public static final String INDEX_SQL_V1 = "" // + "CREATE INDEX if not exists INDEX_" + TABLE_NAME + " on " // + TABLE_NAME + "(" // + ID + "," // + IS_COMPLETE + "," // + IS_STAR // + ");"; // // private TBTodoItem() { // //not called // } // } // // Path: app/src/main/java/com/farseer/todo/flux/pojo/TodoItem.java // public class TodoItem { // private Long id; // private String description; // private boolean completed; // private boolean stared; // // /** // * 构造Todo事项. // * @param id id // * @param description 描述 // */ // public TodoItem(Long id, String description) { // this(id, description, false, false); // } // // /** // * 构造Todo事项. // * @param id 构造Todo事项 // * @param description 描述 // * @param completed 是否已完成 // */ // public TodoItem(Long id, String description, boolean completed) { // this(id, description, completed, false); // } // // /** // * 构造Todo事项. // * @param id id // * @param description 描述 // * @param completed 是否已完成 // * @param stared 是否重要 // */ // public TodoItem(Long id, String description, boolean completed, boolean stared) { // this.stared = stared; // this.completed = completed; // this.description = description; // this.id = id; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public boolean isCompleted() { // return completed; // } // // public void setCompleted(boolean completed) { // this.completed = completed; // } // // public boolean isStared() { // return stared; // } // // public void setStared(boolean stared) { // this.stared = stared; // } // // @Override // public String toString() { // return "TodoItem{" // + "id=" // + id // + ", description='" // + description // + ", isCompleted=" // + completed // + ", isStared=" // + stared // + "}"; // } // }
import android.content.ContentValues; import com.farseer.todo.flux.database.table.TBTodoItem; import com.farseer.todo.flux.pojo.TodoItem;
/* * * Copyright 2016 zhaosc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.farseer.todo.flux.database; /** * DatabaseValuer * * @author zhaosc * @version 1.0.0 * @since 2016-05-05 */ public final class DatabaseValuer { private DatabaseValuer() { //not called } /** * 把TodoItem转换成ContentValues. * * @param item Item事项 * @return ContentValues */ public static ContentValues todoItemValues(TodoItem item) { ContentValues values = new ContentValues();
// Path: app/src/main/java/com/farseer/todo/flux/database/table/TBTodoItem.java // public final class TBTodoItem { // // /** // * TodoItem表名称. // */ // public static final String TABLE_NAME = "todo_item"; // // /** // * 字段id. // */ // public static final String ID = "_id"; // /** // * 字段description. // */ // public static final String DESCRIPTION = "description"; // // /** // * 字段is_complete. // */ // public static final String IS_COMPLETE = "is_complete"; // /** // * 字段is_star. // */ // public static final String IS_STAR = "is_star"; // // /** // * 创建表SQL语句. // */ // public static final String CREATE_SQL_V1 = "" // + "CREATE TABLE " + TBTodoItem.TABLE_NAME + "(" // + TBTodoItem.ID + " INTEGER NOT NULL PRIMARY KEY," // + TBTodoItem.DESCRIPTION + " TEXT NOT NULL," // + TBTodoItem.IS_COMPLETE + " INTEGER NOT NULL DEFAULT 0," // + TBTodoItem.IS_STAR + " INTEGER NOT NULL DEFAULT 0" // + ")"; // // /** // * 建立索引SQL语句. // */ // public static final String INDEX_SQL_V1 = "" // + "CREATE INDEX if not exists INDEX_" + TABLE_NAME + " on " // + TABLE_NAME + "(" // + ID + "," // + IS_COMPLETE + "," // + IS_STAR // + ");"; // // private TBTodoItem() { // //not called // } // } // // Path: app/src/main/java/com/farseer/todo/flux/pojo/TodoItem.java // public class TodoItem { // private Long id; // private String description; // private boolean completed; // private boolean stared; // // /** // * 构造Todo事项. // * @param id id // * @param description 描述 // */ // public TodoItem(Long id, String description) { // this(id, description, false, false); // } // // /** // * 构造Todo事项. // * @param id 构造Todo事项 // * @param description 描述 // * @param completed 是否已完成 // */ // public TodoItem(Long id, String description, boolean completed) { // this(id, description, completed, false); // } // // /** // * 构造Todo事项. // * @param id id // * @param description 描述 // * @param completed 是否已完成 // * @param stared 是否重要 // */ // public TodoItem(Long id, String description, boolean completed, boolean stared) { // this.stared = stared; // this.completed = completed; // this.description = description; // this.id = id; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public boolean isCompleted() { // return completed; // } // // public void setCompleted(boolean completed) { // this.completed = completed; // } // // public boolean isStared() { // return stared; // } // // public void setStared(boolean stared) { // this.stared = stared; // } // // @Override // public String toString() { // return "TodoItem{" // + "id=" // + id // + ", description='" // + description // + ", isCompleted=" // + completed // + ", isStared=" // + stared // + "}"; // } // } // Path: app/src/main/java/com/farseer/todo/flux/database/DatabaseValuer.java import android.content.ContentValues; import com.farseer.todo.flux.database.table.TBTodoItem; import com.farseer.todo.flux.pojo.TodoItem; /* * * Copyright 2016 zhaosc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.farseer.todo.flux.database; /** * DatabaseValuer * * @author zhaosc * @version 1.0.0 * @since 2016-05-05 */ public final class DatabaseValuer { private DatabaseValuer() { //not called } /** * 把TodoItem转换成ContentValues. * * @param item Item事项 * @return ContentValues */ public static ContentValues todoItemValues(TodoItem item) { ContentValues values = new ContentValues();
values.put(TBTodoItem.ID, item.getId());
iFarSeer/TodoFluxArchitecture
app/src/main/java/com/farseer/todo/flux/di/module/ActivityModule.java
// Path: app/src/main/java/com/farseer/todo/flux/view/base/BaseActivity.java // public abstract class BaseActivity extends AppCompatActivity { // // /** // * 设置Toolbar的title. // * // * @param toolbar toolbar // * @param resId title的resId // */ // protected void setTitleTextView(Toolbar toolbar, @StringRes int resId) { // setTitleTextView(toolbar, getString(resId)); // } // // /** // * 设置ToolBar的title. // * // * @param toolbar toolbar // * @param text title的内容 // */ // protected void setTitleTextView(Toolbar toolbar, String text) { // TextView titleTextView = ButterKnife.findById(toolbar, R.id.titleTextView); // if (titleTextView != null) { // titleTextView.setText(text); // titleTextView.setVisibility(View.VISIBLE); // } // } // // /** // * 设置toolbar最右侧按钮的图片,以及点击事件. // * // * @param toolbar toolbar // * @param resId 图片的resId // * @param onClickListener 点击事件监听 // */ // protected void setActionImageView(Toolbar toolbar, @DrawableRes int resId, View.OnClickListener onClickListener) { // View actionView = ButterKnife.findById(toolbar, R.id.actionView); // ImageView actionImageView = ButterKnife.findById(toolbar, R.id.actionImageView); // if (actionImageView != null) { // actionView.setVisibility(View.VISIBLE); // actionImageView.setImageResource(resId); // actionView.setOnClickListener(onClickListener); // } // } // // /** // * 设置toolbar次右侧按钮的图片,以及点击事件. // * // * @param toolbar toolbar // * @param resId 图片的resId // * @param onClickListener 点击事件监听 // */ // protected void setOtherActionImageView(Toolbar toolbar, @DrawableRes int resId, View.OnClickListener onClickListener) { // View otherActionView = ButterKnife.findById(toolbar, R.id.otherActionView); // ImageView otherActionImageView = ButterKnife.findById(toolbar, R.id.otherActionImageView); // if (otherActionImageView != null) { // otherActionView.setVisibility(View.VISIBLE); // otherActionImageView.setImageResource(resId); // otherActionView.setOnClickListener(onClickListener); // } // } // // }
import com.farseer.todo.flux.di.PerActivity; import com.farseer.todo.flux.view.base.BaseActivity; import dagger.Module; import dagger.Provides;
/* * * Copyright 2016 zhaosc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.farseer.todo.flux.di.module; /** * Activity Module. * * @author zhaosc * @version 1.0.0 * @since 2016-04-19 */ @Module public class ActivityModule {
// Path: app/src/main/java/com/farseer/todo/flux/view/base/BaseActivity.java // public abstract class BaseActivity extends AppCompatActivity { // // /** // * 设置Toolbar的title. // * // * @param toolbar toolbar // * @param resId title的resId // */ // protected void setTitleTextView(Toolbar toolbar, @StringRes int resId) { // setTitleTextView(toolbar, getString(resId)); // } // // /** // * 设置ToolBar的title. // * // * @param toolbar toolbar // * @param text title的内容 // */ // protected void setTitleTextView(Toolbar toolbar, String text) { // TextView titleTextView = ButterKnife.findById(toolbar, R.id.titleTextView); // if (titleTextView != null) { // titleTextView.setText(text); // titleTextView.setVisibility(View.VISIBLE); // } // } // // /** // * 设置toolbar最右侧按钮的图片,以及点击事件. // * // * @param toolbar toolbar // * @param resId 图片的resId // * @param onClickListener 点击事件监听 // */ // protected void setActionImageView(Toolbar toolbar, @DrawableRes int resId, View.OnClickListener onClickListener) { // View actionView = ButterKnife.findById(toolbar, R.id.actionView); // ImageView actionImageView = ButterKnife.findById(toolbar, R.id.actionImageView); // if (actionImageView != null) { // actionView.setVisibility(View.VISIBLE); // actionImageView.setImageResource(resId); // actionView.setOnClickListener(onClickListener); // } // } // // /** // * 设置toolbar次右侧按钮的图片,以及点击事件. // * // * @param toolbar toolbar // * @param resId 图片的resId // * @param onClickListener 点击事件监听 // */ // protected void setOtherActionImageView(Toolbar toolbar, @DrawableRes int resId, View.OnClickListener onClickListener) { // View otherActionView = ButterKnife.findById(toolbar, R.id.otherActionView); // ImageView otherActionImageView = ButterKnife.findById(toolbar, R.id.otherActionImageView); // if (otherActionImageView != null) { // otherActionView.setVisibility(View.VISIBLE); // otherActionImageView.setImageResource(resId); // otherActionView.setOnClickListener(onClickListener); // } // } // // } // Path: app/src/main/java/com/farseer/todo/flux/di/module/ActivityModule.java import com.farseer.todo.flux.di.PerActivity; import com.farseer.todo.flux.view.base.BaseActivity; import dagger.Module; import dagger.Provides; /* * * Copyright 2016 zhaosc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.farseer.todo.flux.di.module; /** * Activity Module. * * @author zhaosc * @version 1.0.0 * @since 2016-04-19 */ @Module public class ActivityModule {
private final BaseActivity activity;
iFarSeer/TodoFluxArchitecture
app/src/main/java/com/farseer/todo/flux/database/DatabaseSQL.java
// Path: app/src/main/java/com/farseer/todo/flux/database/table/TBTodoItem.java // public final class TBTodoItem { // // /** // * TodoItem表名称. // */ // public static final String TABLE_NAME = "todo_item"; // // /** // * 字段id. // */ // public static final String ID = "_id"; // /** // * 字段description. // */ // public static final String DESCRIPTION = "description"; // // /** // * 字段is_complete. // */ // public static final String IS_COMPLETE = "is_complete"; // /** // * 字段is_star. // */ // public static final String IS_STAR = "is_star"; // // /** // * 创建表SQL语句. // */ // public static final String CREATE_SQL_V1 = "" // + "CREATE TABLE " + TBTodoItem.TABLE_NAME + "(" // + TBTodoItem.ID + " INTEGER NOT NULL PRIMARY KEY," // + TBTodoItem.DESCRIPTION + " TEXT NOT NULL," // + TBTodoItem.IS_COMPLETE + " INTEGER NOT NULL DEFAULT 0," // + TBTodoItem.IS_STAR + " INTEGER NOT NULL DEFAULT 0" // + ")"; // // /** // * 建立索引SQL语句. // */ // public static final String INDEX_SQL_V1 = "" // + "CREATE INDEX if not exists INDEX_" + TABLE_NAME + " on " // + TABLE_NAME + "(" // + ID + "," // + IS_COMPLETE + "," // + IS_STAR // + ");"; // // private TBTodoItem() { // //not called // } // }
import com.farseer.todo.flux.database.table.TBTodoItem;
/* * * Copyright 2016 zhaosc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.farseer.todo.flux.database; /** * DatabaseSQL * * @author zhaosc * @version 1.0.0 * @since 2016-04-18 */ public final class DatabaseSQL { /** * 数据第一版本的SQL. */ public static final String[] SQL_ALL_V1 = {
// Path: app/src/main/java/com/farseer/todo/flux/database/table/TBTodoItem.java // public final class TBTodoItem { // // /** // * TodoItem表名称. // */ // public static final String TABLE_NAME = "todo_item"; // // /** // * 字段id. // */ // public static final String ID = "_id"; // /** // * 字段description. // */ // public static final String DESCRIPTION = "description"; // // /** // * 字段is_complete. // */ // public static final String IS_COMPLETE = "is_complete"; // /** // * 字段is_star. // */ // public static final String IS_STAR = "is_star"; // // /** // * 创建表SQL语句. // */ // public static final String CREATE_SQL_V1 = "" // + "CREATE TABLE " + TBTodoItem.TABLE_NAME + "(" // + TBTodoItem.ID + " INTEGER NOT NULL PRIMARY KEY," // + TBTodoItem.DESCRIPTION + " TEXT NOT NULL," // + TBTodoItem.IS_COMPLETE + " INTEGER NOT NULL DEFAULT 0," // + TBTodoItem.IS_STAR + " INTEGER NOT NULL DEFAULT 0" // + ")"; // // /** // * 建立索引SQL语句. // */ // public static final String INDEX_SQL_V1 = "" // + "CREATE INDEX if not exists INDEX_" + TABLE_NAME + " on " // + TABLE_NAME + "(" // + ID + "," // + IS_COMPLETE + "," // + IS_STAR // + ");"; // // private TBTodoItem() { // //not called // } // } // Path: app/src/main/java/com/farseer/todo/flux/database/DatabaseSQL.java import com.farseer.todo.flux.database.table.TBTodoItem; /* * * Copyright 2016 zhaosc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.farseer.todo.flux.database; /** * DatabaseSQL * * @author zhaosc * @version 1.0.0 * @since 2016-04-18 */ public final class DatabaseSQL { /** * 数据第一版本的SQL. */ public static final String[] SQL_ALL_V1 = {
TBTodoItem.CREATE_SQL_V1, TBTodoItem.INDEX_SQL_V1
iFarSeer/TodoFluxArchitecture
app/src/main/java/com/farseer/todo/flux/action/TodoItemAction.java
// Path: app/src/main/java/com/farseer/todo/flux/action/base/Action.java // public abstract class Action<A extends ActionType, D extends DataKey> { // // /** // * 事件类型. // */ // protected A type; // /** // * 事件需要传递的数据. // */ // protected DataBundle<D> dataBundle; // // /** // * 获得事件类型. // * // * @return type // */ // public A getType() { // return type; // } // // /** // * 获得事件需要传递的数据. // * // * @return dataBundle // */ // public DataBundle<D> getDataBundle() { // return dataBundle; // } // // @Override // public String toString() { // return "Action{" // + "type=" // + type // + ", dataBundle=" // + dataBundle.toString() // + "}"; // } // } // // Path: app/src/main/java/com/farseer/todo/flux/action/base/ActionType.java // public interface ActionType { // } // // Path: app/src/main/java/com/farseer/todo/flux/action/base/DataBundle.java // public class DataBundle<T extends DataKey> { // // private Map<T, Object> map; // // /** // * 构造DataBundle. // */ // public DataBundle() { // map = new HashMap<>(); // } // // /** // * 添加数据key-data. // * // * @param key 数据key // * @param data 数据内容 // */ // public void put(T key, Object data) { // map.put(key, data); // } // // /** // * 获得key对应的数据data. // * // * @param key 数据key // * @param defaultValue 默认返回data // * @return object // */ // public Object get(T key, Object defaultValue) { // Object obj = map.get(key); // if (obj == null) { // obj = defaultValue; // } // // return obj; // } // // /** // * 获得Map. // * // * @return 数据集合 // */ // public Map<T, Object> getMap() { // return map; // } // // /** // * 设置map. // * // * @param map map // */ // public void setMap(Map<T, Object> map) { // this.map = map; // } // // @Override // public String toString() { // return "DataBundle{" // + "map=" // + map // + "}"; // } // } // // Path: app/src/main/java/com/farseer/todo/flux/action/base/DataKey.java // public interface DataKey { // }
import com.farseer.todo.flux.action.base.Action; import com.farseer.todo.flux.action.base.ActionType; import com.farseer.todo.flux.action.base.DataBundle; import com.farseer.todo.flux.action.base.DataKey;
/* * * Copyright 2016 zhaosc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.farseer.todo.flux.action; /** * Todo数据相关Action. * * @author zhaosc * @version 1.0.0 * @since 2016-04-19 */ public class TodoItemAction extends Action { /** * 构造单个todo事项事件. * * @param type 事件类型 */ public TodoItemAction(final Type type) { this.type = type;
// Path: app/src/main/java/com/farseer/todo/flux/action/base/Action.java // public abstract class Action<A extends ActionType, D extends DataKey> { // // /** // * 事件类型. // */ // protected A type; // /** // * 事件需要传递的数据. // */ // protected DataBundle<D> dataBundle; // // /** // * 获得事件类型. // * // * @return type // */ // public A getType() { // return type; // } // // /** // * 获得事件需要传递的数据. // * // * @return dataBundle // */ // public DataBundle<D> getDataBundle() { // return dataBundle; // } // // @Override // public String toString() { // return "Action{" // + "type=" // + type // + ", dataBundle=" // + dataBundle.toString() // + "}"; // } // } // // Path: app/src/main/java/com/farseer/todo/flux/action/base/ActionType.java // public interface ActionType { // } // // Path: app/src/main/java/com/farseer/todo/flux/action/base/DataBundle.java // public class DataBundle<T extends DataKey> { // // private Map<T, Object> map; // // /** // * 构造DataBundle. // */ // public DataBundle() { // map = new HashMap<>(); // } // // /** // * 添加数据key-data. // * // * @param key 数据key // * @param data 数据内容 // */ // public void put(T key, Object data) { // map.put(key, data); // } // // /** // * 获得key对应的数据data. // * // * @param key 数据key // * @param defaultValue 默认返回data // * @return object // */ // public Object get(T key, Object defaultValue) { // Object obj = map.get(key); // if (obj == null) { // obj = defaultValue; // } // // return obj; // } // // /** // * 获得Map. // * // * @return 数据集合 // */ // public Map<T, Object> getMap() { // return map; // } // // /** // * 设置map. // * // * @param map map // */ // public void setMap(Map<T, Object> map) { // this.map = map; // } // // @Override // public String toString() { // return "DataBundle{" // + "map=" // + map // + "}"; // } // } // // Path: app/src/main/java/com/farseer/todo/flux/action/base/DataKey.java // public interface DataKey { // } // Path: app/src/main/java/com/farseer/todo/flux/action/TodoItemAction.java import com.farseer.todo.flux.action.base.Action; import com.farseer.todo.flux.action.base.ActionType; import com.farseer.todo.flux.action.base.DataBundle; import com.farseer.todo.flux.action.base.DataKey; /* * * Copyright 2016 zhaosc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.farseer.todo.flux.action; /** * Todo数据相关Action. * * @author zhaosc * @version 1.0.0 * @since 2016-04-19 */ public class TodoItemAction extends Action { /** * 构造单个todo事项事件. * * @param type 事件类型 */ public TodoItemAction(final Type type) { this.type = type;
this.dataBundle = new DataBundle<>();
iFarSeer/TodoFluxArchitecture
app/src/main/java/com/farseer/todo/flux/action/TodoItemAction.java
// Path: app/src/main/java/com/farseer/todo/flux/action/base/Action.java // public abstract class Action<A extends ActionType, D extends DataKey> { // // /** // * 事件类型. // */ // protected A type; // /** // * 事件需要传递的数据. // */ // protected DataBundle<D> dataBundle; // // /** // * 获得事件类型. // * // * @return type // */ // public A getType() { // return type; // } // // /** // * 获得事件需要传递的数据. // * // * @return dataBundle // */ // public DataBundle<D> getDataBundle() { // return dataBundle; // } // // @Override // public String toString() { // return "Action{" // + "type=" // + type // + ", dataBundle=" // + dataBundle.toString() // + "}"; // } // } // // Path: app/src/main/java/com/farseer/todo/flux/action/base/ActionType.java // public interface ActionType { // } // // Path: app/src/main/java/com/farseer/todo/flux/action/base/DataBundle.java // public class DataBundle<T extends DataKey> { // // private Map<T, Object> map; // // /** // * 构造DataBundle. // */ // public DataBundle() { // map = new HashMap<>(); // } // // /** // * 添加数据key-data. // * // * @param key 数据key // * @param data 数据内容 // */ // public void put(T key, Object data) { // map.put(key, data); // } // // /** // * 获得key对应的数据data. // * // * @param key 数据key // * @param defaultValue 默认返回data // * @return object // */ // public Object get(T key, Object defaultValue) { // Object obj = map.get(key); // if (obj == null) { // obj = defaultValue; // } // // return obj; // } // // /** // * 获得Map. // * // * @return 数据集合 // */ // public Map<T, Object> getMap() { // return map; // } // // /** // * 设置map. // * // * @param map map // */ // public void setMap(Map<T, Object> map) { // this.map = map; // } // // @Override // public String toString() { // return "DataBundle{" // + "map=" // + map // + "}"; // } // } // // Path: app/src/main/java/com/farseer/todo/flux/action/base/DataKey.java // public interface DataKey { // }
import com.farseer.todo.flux.action.base.Action; import com.farseer.todo.flux.action.base.ActionType; import com.farseer.todo.flux.action.base.DataBundle; import com.farseer.todo.flux.action.base.DataKey;
/* * * Copyright 2016 zhaosc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.farseer.todo.flux.action; /** * Todo数据相关Action. * * @author zhaosc * @version 1.0.0 * @since 2016-04-19 */ public class TodoItemAction extends Action { /** * 构造单个todo事项事件. * * @param type 事件类型 */ public TodoItemAction(final Type type) { this.type = type; this.dataBundle = new DataBundle<>(); } /** * 构造单个todo事项事件. * * @param type 事件类型 * @param data 事件数据 */ public TodoItemAction(final Type type, final DataBundle<Key> data) { this.type = type; this.dataBundle = data; } /** * 事件类型. */
// Path: app/src/main/java/com/farseer/todo/flux/action/base/Action.java // public abstract class Action<A extends ActionType, D extends DataKey> { // // /** // * 事件类型. // */ // protected A type; // /** // * 事件需要传递的数据. // */ // protected DataBundle<D> dataBundle; // // /** // * 获得事件类型. // * // * @return type // */ // public A getType() { // return type; // } // // /** // * 获得事件需要传递的数据. // * // * @return dataBundle // */ // public DataBundle<D> getDataBundle() { // return dataBundle; // } // // @Override // public String toString() { // return "Action{" // + "type=" // + type // + ", dataBundle=" // + dataBundle.toString() // + "}"; // } // } // // Path: app/src/main/java/com/farseer/todo/flux/action/base/ActionType.java // public interface ActionType { // } // // Path: app/src/main/java/com/farseer/todo/flux/action/base/DataBundle.java // public class DataBundle<T extends DataKey> { // // private Map<T, Object> map; // // /** // * 构造DataBundle. // */ // public DataBundle() { // map = new HashMap<>(); // } // // /** // * 添加数据key-data. // * // * @param key 数据key // * @param data 数据内容 // */ // public void put(T key, Object data) { // map.put(key, data); // } // // /** // * 获得key对应的数据data. // * // * @param key 数据key // * @param defaultValue 默认返回data // * @return object // */ // public Object get(T key, Object defaultValue) { // Object obj = map.get(key); // if (obj == null) { // obj = defaultValue; // } // // return obj; // } // // /** // * 获得Map. // * // * @return 数据集合 // */ // public Map<T, Object> getMap() { // return map; // } // // /** // * 设置map. // * // * @param map map // */ // public void setMap(Map<T, Object> map) { // this.map = map; // } // // @Override // public String toString() { // return "DataBundle{" // + "map=" // + map // + "}"; // } // } // // Path: app/src/main/java/com/farseer/todo/flux/action/base/DataKey.java // public interface DataKey { // } // Path: app/src/main/java/com/farseer/todo/flux/action/TodoItemAction.java import com.farseer.todo.flux.action.base.Action; import com.farseer.todo.flux.action.base.ActionType; import com.farseer.todo.flux.action.base.DataBundle; import com.farseer.todo.flux.action.base.DataKey; /* * * Copyright 2016 zhaosc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.farseer.todo.flux.action; /** * Todo数据相关Action. * * @author zhaosc * @version 1.0.0 * @since 2016-04-19 */ public class TodoItemAction extends Action { /** * 构造单个todo事项事件. * * @param type 事件类型 */ public TodoItemAction(final Type type) { this.type = type; this.dataBundle = new DataBundle<>(); } /** * 构造单个todo事项事件. * * @param type 事件类型 * @param data 事件数据 */ public TodoItemAction(final Type type, final DataBundle<Key> data) { this.type = type; this.dataBundle = data; } /** * 事件类型. */
public enum Type implements ActionType {
iFarSeer/TodoFluxArchitecture
app/src/main/java/com/farseer/todo/flux/action/TodoItemAction.java
// Path: app/src/main/java/com/farseer/todo/flux/action/base/Action.java // public abstract class Action<A extends ActionType, D extends DataKey> { // // /** // * 事件类型. // */ // protected A type; // /** // * 事件需要传递的数据. // */ // protected DataBundle<D> dataBundle; // // /** // * 获得事件类型. // * // * @return type // */ // public A getType() { // return type; // } // // /** // * 获得事件需要传递的数据. // * // * @return dataBundle // */ // public DataBundle<D> getDataBundle() { // return dataBundle; // } // // @Override // public String toString() { // return "Action{" // + "type=" // + type // + ", dataBundle=" // + dataBundle.toString() // + "}"; // } // } // // Path: app/src/main/java/com/farseer/todo/flux/action/base/ActionType.java // public interface ActionType { // } // // Path: app/src/main/java/com/farseer/todo/flux/action/base/DataBundle.java // public class DataBundle<T extends DataKey> { // // private Map<T, Object> map; // // /** // * 构造DataBundle. // */ // public DataBundle() { // map = new HashMap<>(); // } // // /** // * 添加数据key-data. // * // * @param key 数据key // * @param data 数据内容 // */ // public void put(T key, Object data) { // map.put(key, data); // } // // /** // * 获得key对应的数据data. // * // * @param key 数据key // * @param defaultValue 默认返回data // * @return object // */ // public Object get(T key, Object defaultValue) { // Object obj = map.get(key); // if (obj == null) { // obj = defaultValue; // } // // return obj; // } // // /** // * 获得Map. // * // * @return 数据集合 // */ // public Map<T, Object> getMap() { // return map; // } // // /** // * 设置map. // * // * @param map map // */ // public void setMap(Map<T, Object> map) { // this.map = map; // } // // @Override // public String toString() { // return "DataBundle{" // + "map=" // + map // + "}"; // } // } // // Path: app/src/main/java/com/farseer/todo/flux/action/base/DataKey.java // public interface DataKey { // }
import com.farseer.todo.flux.action.base.Action; import com.farseer.todo.flux.action.base.ActionType; import com.farseer.todo.flux.action.base.DataBundle; import com.farseer.todo.flux.action.base.DataKey;
/* * * Copyright 2016 zhaosc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.farseer.todo.flux.action; /** * Todo数据相关Action. * * @author zhaosc * @version 1.0.0 * @since 2016-04-19 */ public class TodoItemAction extends Action { /** * 构造单个todo事项事件. * * @param type 事件类型 */ public TodoItemAction(final Type type) { this.type = type; this.dataBundle = new DataBundle<>(); } /** * 构造单个todo事项事件. * * @param type 事件类型 * @param data 事件数据 */ public TodoItemAction(final Type type, final DataBundle<Key> data) { this.type = type; this.dataBundle = data; } /** * 事件类型. */ public enum Type implements ActionType { /** * 创建todo事项. */ NEW, /** * 编辑todo事项. */ EDIT, /** * 删除todo事项. */ DELETE, } /** * 数据key. */
// Path: app/src/main/java/com/farseer/todo/flux/action/base/Action.java // public abstract class Action<A extends ActionType, D extends DataKey> { // // /** // * 事件类型. // */ // protected A type; // /** // * 事件需要传递的数据. // */ // protected DataBundle<D> dataBundle; // // /** // * 获得事件类型. // * // * @return type // */ // public A getType() { // return type; // } // // /** // * 获得事件需要传递的数据. // * // * @return dataBundle // */ // public DataBundle<D> getDataBundle() { // return dataBundle; // } // // @Override // public String toString() { // return "Action{" // + "type=" // + type // + ", dataBundle=" // + dataBundle.toString() // + "}"; // } // } // // Path: app/src/main/java/com/farseer/todo/flux/action/base/ActionType.java // public interface ActionType { // } // // Path: app/src/main/java/com/farseer/todo/flux/action/base/DataBundle.java // public class DataBundle<T extends DataKey> { // // private Map<T, Object> map; // // /** // * 构造DataBundle. // */ // public DataBundle() { // map = new HashMap<>(); // } // // /** // * 添加数据key-data. // * // * @param key 数据key // * @param data 数据内容 // */ // public void put(T key, Object data) { // map.put(key, data); // } // // /** // * 获得key对应的数据data. // * // * @param key 数据key // * @param defaultValue 默认返回data // * @return object // */ // public Object get(T key, Object defaultValue) { // Object obj = map.get(key); // if (obj == null) { // obj = defaultValue; // } // // return obj; // } // // /** // * 获得Map. // * // * @return 数据集合 // */ // public Map<T, Object> getMap() { // return map; // } // // /** // * 设置map. // * // * @param map map // */ // public void setMap(Map<T, Object> map) { // this.map = map; // } // // @Override // public String toString() { // return "DataBundle{" // + "map=" // + map // + "}"; // } // } // // Path: app/src/main/java/com/farseer/todo/flux/action/base/DataKey.java // public interface DataKey { // } // Path: app/src/main/java/com/farseer/todo/flux/action/TodoItemAction.java import com.farseer.todo.flux.action.base.Action; import com.farseer.todo.flux.action.base.ActionType; import com.farseer.todo.flux.action.base.DataBundle; import com.farseer.todo.flux.action.base.DataKey; /* * * Copyright 2016 zhaosc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.farseer.todo.flux.action; /** * Todo数据相关Action. * * @author zhaosc * @version 1.0.0 * @since 2016-04-19 */ public class TodoItemAction extends Action { /** * 构造单个todo事项事件. * * @param type 事件类型 */ public TodoItemAction(final Type type) { this.type = type; this.dataBundle = new DataBundle<>(); } /** * 构造单个todo事项事件. * * @param type 事件类型 * @param data 事件数据 */ public TodoItemAction(final Type type, final DataBundle<Key> data) { this.type = type; this.dataBundle = data; } /** * 事件类型. */ public enum Type implements ActionType { /** * 创建todo事项. */ NEW, /** * 编辑todo事项. */ EDIT, /** * 删除todo事项. */ DELETE, } /** * 数据key. */
public enum Key implements DataKey {
iFarSeer/TodoFluxArchitecture
app/src/main/java/com/farseer/todo/flux/action/TodoListAction.java
// Path: app/src/main/java/com/farseer/todo/flux/action/base/Action.java // public abstract class Action<A extends ActionType, D extends DataKey> { // // /** // * 事件类型. // */ // protected A type; // /** // * 事件需要传递的数据. // */ // protected DataBundle<D> dataBundle; // // /** // * 获得事件类型. // * // * @return type // */ // public A getType() { // return type; // } // // /** // * 获得事件需要传递的数据. // * // * @return dataBundle // */ // public DataBundle<D> getDataBundle() { // return dataBundle; // } // // @Override // public String toString() { // return "Action{" // + "type=" // + type // + ", dataBundle=" // + dataBundle.toString() // + "}"; // } // } // // Path: app/src/main/java/com/farseer/todo/flux/action/base/ActionType.java // public interface ActionType { // } // // Path: app/src/main/java/com/farseer/todo/flux/action/base/DataBundle.java // public class DataBundle<T extends DataKey> { // // private Map<T, Object> map; // // /** // * 构造DataBundle. // */ // public DataBundle() { // map = new HashMap<>(); // } // // /** // * 添加数据key-data. // * // * @param key 数据key // * @param data 数据内容 // */ // public void put(T key, Object data) { // map.put(key, data); // } // // /** // * 获得key对应的数据data. // * // * @param key 数据key // * @param defaultValue 默认返回data // * @return object // */ // public Object get(T key, Object defaultValue) { // Object obj = map.get(key); // if (obj == null) { // obj = defaultValue; // } // // return obj; // } // // /** // * 获得Map. // * // * @return 数据集合 // */ // public Map<T, Object> getMap() { // return map; // } // // /** // * 设置map. // * // * @param map map // */ // public void setMap(Map<T, Object> map) { // this.map = map; // } // // @Override // public String toString() { // return "DataBundle{" // + "map=" // + map // + "}"; // } // } // // Path: app/src/main/java/com/farseer/todo/flux/action/base/DataKey.java // public interface DataKey { // }
import com.farseer.todo.flux.action.base.Action; import com.farseer.todo.flux.action.base.ActionType; import com.farseer.todo.flux.action.base.DataBundle; import com.farseer.todo.flux.action.base.DataKey;
/* * * Copyright 2016 zhaosc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.farseer.todo.flux.action; /** * Todo视图相关Action. * * @author zhaosc * @version 1.0.0 * @since 2016-04-19 */ public class TodoListAction extends Action { /** * 构造todo事项列表事件. * * @param type 事件类型 */ public TodoListAction(Type type) { this.type = type;
// Path: app/src/main/java/com/farseer/todo/flux/action/base/Action.java // public abstract class Action<A extends ActionType, D extends DataKey> { // // /** // * 事件类型. // */ // protected A type; // /** // * 事件需要传递的数据. // */ // protected DataBundle<D> dataBundle; // // /** // * 获得事件类型. // * // * @return type // */ // public A getType() { // return type; // } // // /** // * 获得事件需要传递的数据. // * // * @return dataBundle // */ // public DataBundle<D> getDataBundle() { // return dataBundle; // } // // @Override // public String toString() { // return "Action{" // + "type=" // + type // + ", dataBundle=" // + dataBundle.toString() // + "}"; // } // } // // Path: app/src/main/java/com/farseer/todo/flux/action/base/ActionType.java // public interface ActionType { // } // // Path: app/src/main/java/com/farseer/todo/flux/action/base/DataBundle.java // public class DataBundle<T extends DataKey> { // // private Map<T, Object> map; // // /** // * 构造DataBundle. // */ // public DataBundle() { // map = new HashMap<>(); // } // // /** // * 添加数据key-data. // * // * @param key 数据key // * @param data 数据内容 // */ // public void put(T key, Object data) { // map.put(key, data); // } // // /** // * 获得key对应的数据data. // * // * @param key 数据key // * @param defaultValue 默认返回data // * @return object // */ // public Object get(T key, Object defaultValue) { // Object obj = map.get(key); // if (obj == null) { // obj = defaultValue; // } // // return obj; // } // // /** // * 获得Map. // * // * @return 数据集合 // */ // public Map<T, Object> getMap() { // return map; // } // // /** // * 设置map. // * // * @param map map // */ // public void setMap(Map<T, Object> map) { // this.map = map; // } // // @Override // public String toString() { // return "DataBundle{" // + "map=" // + map // + "}"; // } // } // // Path: app/src/main/java/com/farseer/todo/flux/action/base/DataKey.java // public interface DataKey { // } // Path: app/src/main/java/com/farseer/todo/flux/action/TodoListAction.java import com.farseer.todo.flux.action.base.Action; import com.farseer.todo.flux.action.base.ActionType; import com.farseer.todo.flux.action.base.DataBundle; import com.farseer.todo.flux.action.base.DataKey; /* * * Copyright 2016 zhaosc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.farseer.todo.flux.action; /** * Todo视图相关Action. * * @author zhaosc * @version 1.0.0 * @since 2016-04-19 */ public class TodoListAction extends Action { /** * 构造todo事项列表事件. * * @param type 事件类型 */ public TodoListAction(Type type) { this.type = type;
this.dataBundle = new DataBundle<>();
iFarSeer/TodoFluxArchitecture
app/src/main/java/com/farseer/todo/flux/action/TodoListAction.java
// Path: app/src/main/java/com/farseer/todo/flux/action/base/Action.java // public abstract class Action<A extends ActionType, D extends DataKey> { // // /** // * 事件类型. // */ // protected A type; // /** // * 事件需要传递的数据. // */ // protected DataBundle<D> dataBundle; // // /** // * 获得事件类型. // * // * @return type // */ // public A getType() { // return type; // } // // /** // * 获得事件需要传递的数据. // * // * @return dataBundle // */ // public DataBundle<D> getDataBundle() { // return dataBundle; // } // // @Override // public String toString() { // return "Action{" // + "type=" // + type // + ", dataBundle=" // + dataBundle.toString() // + "}"; // } // } // // Path: app/src/main/java/com/farseer/todo/flux/action/base/ActionType.java // public interface ActionType { // } // // Path: app/src/main/java/com/farseer/todo/flux/action/base/DataBundle.java // public class DataBundle<T extends DataKey> { // // private Map<T, Object> map; // // /** // * 构造DataBundle. // */ // public DataBundle() { // map = new HashMap<>(); // } // // /** // * 添加数据key-data. // * // * @param key 数据key // * @param data 数据内容 // */ // public void put(T key, Object data) { // map.put(key, data); // } // // /** // * 获得key对应的数据data. // * // * @param key 数据key // * @param defaultValue 默认返回data // * @return object // */ // public Object get(T key, Object defaultValue) { // Object obj = map.get(key); // if (obj == null) { // obj = defaultValue; // } // // return obj; // } // // /** // * 获得Map. // * // * @return 数据集合 // */ // public Map<T, Object> getMap() { // return map; // } // // /** // * 设置map. // * // * @param map map // */ // public void setMap(Map<T, Object> map) { // this.map = map; // } // // @Override // public String toString() { // return "DataBundle{" // + "map=" // + map // + "}"; // } // } // // Path: app/src/main/java/com/farseer/todo/flux/action/base/DataKey.java // public interface DataKey { // }
import com.farseer.todo.flux.action.base.Action; import com.farseer.todo.flux.action.base.ActionType; import com.farseer.todo.flux.action.base.DataBundle; import com.farseer.todo.flux.action.base.DataKey;
/* * * Copyright 2016 zhaosc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.farseer.todo.flux.action; /** * Todo视图相关Action. * * @author zhaosc * @version 1.0.0 * @since 2016-04-19 */ public class TodoListAction extends Action { /** * 构造todo事项列表事件. * * @param type 事件类型 */ public TodoListAction(Type type) { this.type = type; this.dataBundle = new DataBundle<>(); } /** * 构造todo事项列表事件. * * @param type 事件类型 * @param bundle 事件数据 */ public TodoListAction(Type type, DataBundle<Key> bundle) { this.type = type; this.dataBundle = bundle; } /** * todo事项列表事件类型. */
// Path: app/src/main/java/com/farseer/todo/flux/action/base/Action.java // public abstract class Action<A extends ActionType, D extends DataKey> { // // /** // * 事件类型. // */ // protected A type; // /** // * 事件需要传递的数据. // */ // protected DataBundle<D> dataBundle; // // /** // * 获得事件类型. // * // * @return type // */ // public A getType() { // return type; // } // // /** // * 获得事件需要传递的数据. // * // * @return dataBundle // */ // public DataBundle<D> getDataBundle() { // return dataBundle; // } // // @Override // public String toString() { // return "Action{" // + "type=" // + type // + ", dataBundle=" // + dataBundle.toString() // + "}"; // } // } // // Path: app/src/main/java/com/farseer/todo/flux/action/base/ActionType.java // public interface ActionType { // } // // Path: app/src/main/java/com/farseer/todo/flux/action/base/DataBundle.java // public class DataBundle<T extends DataKey> { // // private Map<T, Object> map; // // /** // * 构造DataBundle. // */ // public DataBundle() { // map = new HashMap<>(); // } // // /** // * 添加数据key-data. // * // * @param key 数据key // * @param data 数据内容 // */ // public void put(T key, Object data) { // map.put(key, data); // } // // /** // * 获得key对应的数据data. // * // * @param key 数据key // * @param defaultValue 默认返回data // * @return object // */ // public Object get(T key, Object defaultValue) { // Object obj = map.get(key); // if (obj == null) { // obj = defaultValue; // } // // return obj; // } // // /** // * 获得Map. // * // * @return 数据集合 // */ // public Map<T, Object> getMap() { // return map; // } // // /** // * 设置map. // * // * @param map map // */ // public void setMap(Map<T, Object> map) { // this.map = map; // } // // @Override // public String toString() { // return "DataBundle{" // + "map=" // + map // + "}"; // } // } // // Path: app/src/main/java/com/farseer/todo/flux/action/base/DataKey.java // public interface DataKey { // } // Path: app/src/main/java/com/farseer/todo/flux/action/TodoListAction.java import com.farseer.todo.flux.action.base.Action; import com.farseer.todo.flux.action.base.ActionType; import com.farseer.todo.flux.action.base.DataBundle; import com.farseer.todo.flux.action.base.DataKey; /* * * Copyright 2016 zhaosc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.farseer.todo.flux.action; /** * Todo视图相关Action. * * @author zhaosc * @version 1.0.0 * @since 2016-04-19 */ public class TodoListAction extends Action { /** * 构造todo事项列表事件. * * @param type 事件类型 */ public TodoListAction(Type type) { this.type = type; this.dataBundle = new DataBundle<>(); } /** * 构造todo事项列表事件. * * @param type 事件类型 * @param bundle 事件数据 */ public TodoListAction(Type type, DataBundle<Key> bundle) { this.type = type; this.dataBundle = bundle; } /** * todo事项列表事件类型. */
public enum Type implements ActionType {
iFarSeer/TodoFluxArchitecture
app/src/main/java/com/farseer/todo/flux/action/TodoListAction.java
// Path: app/src/main/java/com/farseer/todo/flux/action/base/Action.java // public abstract class Action<A extends ActionType, D extends DataKey> { // // /** // * 事件类型. // */ // protected A type; // /** // * 事件需要传递的数据. // */ // protected DataBundle<D> dataBundle; // // /** // * 获得事件类型. // * // * @return type // */ // public A getType() { // return type; // } // // /** // * 获得事件需要传递的数据. // * // * @return dataBundle // */ // public DataBundle<D> getDataBundle() { // return dataBundle; // } // // @Override // public String toString() { // return "Action{" // + "type=" // + type // + ", dataBundle=" // + dataBundle.toString() // + "}"; // } // } // // Path: app/src/main/java/com/farseer/todo/flux/action/base/ActionType.java // public interface ActionType { // } // // Path: app/src/main/java/com/farseer/todo/flux/action/base/DataBundle.java // public class DataBundle<T extends DataKey> { // // private Map<T, Object> map; // // /** // * 构造DataBundle. // */ // public DataBundle() { // map = new HashMap<>(); // } // // /** // * 添加数据key-data. // * // * @param key 数据key // * @param data 数据内容 // */ // public void put(T key, Object data) { // map.put(key, data); // } // // /** // * 获得key对应的数据data. // * // * @param key 数据key // * @param defaultValue 默认返回data // * @return object // */ // public Object get(T key, Object defaultValue) { // Object obj = map.get(key); // if (obj == null) { // obj = defaultValue; // } // // return obj; // } // // /** // * 获得Map. // * // * @return 数据集合 // */ // public Map<T, Object> getMap() { // return map; // } // // /** // * 设置map. // * // * @param map map // */ // public void setMap(Map<T, Object> map) { // this.map = map; // } // // @Override // public String toString() { // return "DataBundle{" // + "map=" // + map // + "}"; // } // } // // Path: app/src/main/java/com/farseer/todo/flux/action/base/DataKey.java // public interface DataKey { // }
import com.farseer.todo.flux.action.base.Action; import com.farseer.todo.flux.action.base.ActionType; import com.farseer.todo.flux.action.base.DataBundle; import com.farseer.todo.flux.action.base.DataKey;
/* * * Copyright 2016 zhaosc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.farseer.todo.flux.action; /** * Todo视图相关Action. * * @author zhaosc * @version 1.0.0 * @since 2016-04-19 */ public class TodoListAction extends Action { /** * 构造todo事项列表事件. * * @param type 事件类型 */ public TodoListAction(Type type) { this.type = type; this.dataBundle = new DataBundle<>(); } /** * 构造todo事项列表事件. * * @param type 事件类型 * @param bundle 事件数据 */ public TodoListAction(Type type, DataBundle<Key> bundle) { this.type = type; this.dataBundle = bundle; } /** * todo事项列表事件类型. */ public enum Type implements ActionType { /** * 加载类型. */ LOAD, /** * 显示全部类型. */ SHOW_ALL, /** * 显示已完成类型. */ SHOW_COMPLETED, /** * 显示重要类型. */ SHOW_STARED } /** * 数据key. */
// Path: app/src/main/java/com/farseer/todo/flux/action/base/Action.java // public abstract class Action<A extends ActionType, D extends DataKey> { // // /** // * 事件类型. // */ // protected A type; // /** // * 事件需要传递的数据. // */ // protected DataBundle<D> dataBundle; // // /** // * 获得事件类型. // * // * @return type // */ // public A getType() { // return type; // } // // /** // * 获得事件需要传递的数据. // * // * @return dataBundle // */ // public DataBundle<D> getDataBundle() { // return dataBundle; // } // // @Override // public String toString() { // return "Action{" // + "type=" // + type // + ", dataBundle=" // + dataBundle.toString() // + "}"; // } // } // // Path: app/src/main/java/com/farseer/todo/flux/action/base/ActionType.java // public interface ActionType { // } // // Path: app/src/main/java/com/farseer/todo/flux/action/base/DataBundle.java // public class DataBundle<T extends DataKey> { // // private Map<T, Object> map; // // /** // * 构造DataBundle. // */ // public DataBundle() { // map = new HashMap<>(); // } // // /** // * 添加数据key-data. // * // * @param key 数据key // * @param data 数据内容 // */ // public void put(T key, Object data) { // map.put(key, data); // } // // /** // * 获得key对应的数据data. // * // * @param key 数据key // * @param defaultValue 默认返回data // * @return object // */ // public Object get(T key, Object defaultValue) { // Object obj = map.get(key); // if (obj == null) { // obj = defaultValue; // } // // return obj; // } // // /** // * 获得Map. // * // * @return 数据集合 // */ // public Map<T, Object> getMap() { // return map; // } // // /** // * 设置map. // * // * @param map map // */ // public void setMap(Map<T, Object> map) { // this.map = map; // } // // @Override // public String toString() { // return "DataBundle{" // + "map=" // + map // + "}"; // } // } // // Path: app/src/main/java/com/farseer/todo/flux/action/base/DataKey.java // public interface DataKey { // } // Path: app/src/main/java/com/farseer/todo/flux/action/TodoListAction.java import com.farseer.todo.flux.action.base.Action; import com.farseer.todo.flux.action.base.ActionType; import com.farseer.todo.flux.action.base.DataBundle; import com.farseer.todo.flux.action.base.DataKey; /* * * Copyright 2016 zhaosc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.farseer.todo.flux.action; /** * Todo视图相关Action. * * @author zhaosc * @version 1.0.0 * @since 2016-04-19 */ public class TodoListAction extends Action { /** * 构造todo事项列表事件. * * @param type 事件类型 */ public TodoListAction(Type type) { this.type = type; this.dataBundle = new DataBundle<>(); } /** * 构造todo事项列表事件. * * @param type 事件类型 * @param bundle 事件数据 */ public TodoListAction(Type type, DataBundle<Key> bundle) { this.type = type; this.dataBundle = bundle; } /** * todo事项列表事件类型. */ public enum Type implements ActionType { /** * 加载类型. */ LOAD, /** * 显示全部类型. */ SHOW_ALL, /** * 显示已完成类型. */ SHOW_COMPLETED, /** * 显示重要类型. */ SHOW_STARED } /** * 数据key. */
public enum Key implements DataKey {
wodzuu/JSONschema4-mapper
src/test/java/pl/zientarski/GenericTypeHandlerTest.java
// Path: src/main/java/pl/zientarski/typehandler/TypeHandler.java // public interface TypeHandler { // boolean accepts(Type type); // // JSONObject process(TypeDescription typeDescription, MapperContext mapperContext); // }
import com.google.common.collect.Lists; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import pl.zientarski.typehandler.TypeHandler; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Iterator; import java.util.Set; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue;
package pl.zientarski; public class GenericTypeHandlerTest { private SchemaMapper mapper; private Type type; class SomeType { } class Hamster<T> { private T someField; public T getSomeField() { return someField; } } public Hamster<SomeType> helperMethod() { return null; } @Before public void before() throws NoSuchMethodException, SecurityException { mapper = new SchemaMapper(); type = GenericTypeHandlerTest.class.getDeclaredMethod("helperMethod").getGenericReturnType(); } @Test public void typeHandlerTest() throws Exception { //given
// Path: src/main/java/pl/zientarski/typehandler/TypeHandler.java // public interface TypeHandler { // boolean accepts(Type type); // // JSONObject process(TypeDescription typeDescription, MapperContext mapperContext); // } // Path: src/test/java/pl/zientarski/GenericTypeHandlerTest.java import com.google.common.collect.Lists; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import pl.zientarski.typehandler.TypeHandler; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Iterator; import java.util.Set; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; package pl.zientarski; public class GenericTypeHandlerTest { private SchemaMapper mapper; private Type type; class SomeType { } class Hamster<T> { private T someField; public T getSomeField() { return someField; } } public Hamster<SomeType> helperMethod() { return null; } @Before public void before() throws NoSuchMethodException, SecurityException { mapper = new SchemaMapper(); type = GenericTypeHandlerTest.class.getDeclaredMethod("helperMethod").getGenericReturnType(); } @Test public void typeHandlerTest() throws Exception { //given
mapper.addTypeHandler(new TypeHandler() {
wodzuu/JSONschema4-mapper
src/main/java/pl/zientarski/SchemaMapper.java
// Path: src/main/java/pl/zientarski/Utils.java // public static boolean isParameterizedType(final Type type) { // return type instanceof ParameterizedType; // }
import org.json.JSONObject; import pl.zientarski.typehandler.*; import java.lang.annotation.Annotation; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.util.*; import static pl.zientarski.Utils.isParameterizedType;
public void setPropertyDiscoveryMode(final PropertyDiscoveryMode propertyDiscoveryMode) { mapperContext.setPropertyDiscoveryMode(propertyDiscoveryMode); } public void setDateTimeFormat(final String format) { mapperContext.setDateTimeFormat(format); } public void setRelaxedMode(final boolean isRelaxed) { mapperContext.setStrict(!isRelaxed); } public void setRequiredFieldAnnotations(final List<Class<? extends Annotation>> annotations) { mapperContext.setRequiredFieldAnnotation(annotations); } public void addTypeHandler(final TypeHandler typeHandler) { typeHandlers.add(0, typeHandler); } public void setDescriptionProvider(DescriptionProvider descriptionProvider) { mapperContext.setDescriptionProvider(descriptionProvider); } public Iterator<Type> getDependencies() { return mapperContext.getDependencies(); } public JSONObject toJsonSchema4(final Type type) {
// Path: src/main/java/pl/zientarski/Utils.java // public static boolean isParameterizedType(final Type type) { // return type instanceof ParameterizedType; // } // Path: src/main/java/pl/zientarski/SchemaMapper.java import org.json.JSONObject; import pl.zientarski.typehandler.*; import java.lang.annotation.Annotation; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.util.*; import static pl.zientarski.Utils.isParameterizedType; public void setPropertyDiscoveryMode(final PropertyDiscoveryMode propertyDiscoveryMode) { mapperContext.setPropertyDiscoveryMode(propertyDiscoveryMode); } public void setDateTimeFormat(final String format) { mapperContext.setDateTimeFormat(format); } public void setRelaxedMode(final boolean isRelaxed) { mapperContext.setStrict(!isRelaxed); } public void setRequiredFieldAnnotations(final List<Class<? extends Annotation>> annotations) { mapperContext.setRequiredFieldAnnotation(annotations); } public void addTypeHandler(final TypeHandler typeHandler) { typeHandlers.add(0, typeHandler); } public void setDescriptionProvider(DescriptionProvider descriptionProvider) { mapperContext.setDescriptionProvider(descriptionProvider); } public Iterator<Type> getDependencies() { return mapperContext.getDependencies(); } public JSONObject toJsonSchema4(final Type type) {
if (isParameterizedType(type)) {
wodzuu/JSONschema4-mapper
src/test/java/pl/zientarski/EnumTest.java
// Path: src/test/java/pl/zientarski/TestUtils.java // public static Set<String> toStringSet(final JSONArray jsonArray) { // final Set<String> result = new HashSet<>(); // for (int i = 0; i < jsonArray.length(); i++) { // result.add(jsonArray.getString(i)); // } // return result; // }
import org.json.JSONArray; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import java.util.Set; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasItem; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static pl.zientarski.TestUtils.toStringSet;
package pl.zientarski; public class EnumTest { private SchemaMapper mapper; enum HangarType { SMALL, MEDIUM, BIG } @Before public void before() { mapper = new SchemaMapper(); } @Test public void enumPropertyTest() throws Exception { //given //when final JSONObject schema = mapper.toJsonSchema4(HangarType.class); //then assertTrue(schema.has("enum")); } @Test public void enumElementsTest() throws Exception { //given //when final JSONObject schema = mapper.toJsonSchema4(HangarType.class); //then final JSONArray hangarTypes = schema.getJSONArray("enum"); assertThat(hangarTypes.length(), equalTo(3));
// Path: src/test/java/pl/zientarski/TestUtils.java // public static Set<String> toStringSet(final JSONArray jsonArray) { // final Set<String> result = new HashSet<>(); // for (int i = 0; i < jsonArray.length(); i++) { // result.add(jsonArray.getString(i)); // } // return result; // } // Path: src/test/java/pl/zientarski/EnumTest.java import org.json.JSONArray; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import java.util.Set; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasItem; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static pl.zientarski.TestUtils.toStringSet; package pl.zientarski; public class EnumTest { private SchemaMapper mapper; enum HangarType { SMALL, MEDIUM, BIG } @Before public void before() { mapper = new SchemaMapper(); } @Test public void enumPropertyTest() throws Exception { //given //when final JSONObject schema = mapper.toJsonSchema4(HangarType.class); //then assertTrue(schema.has("enum")); } @Test public void enumElementsTest() throws Exception { //given //when final JSONObject schema = mapper.toJsonSchema4(HangarType.class); //then final JSONArray hangarTypes = schema.getJSONArray("enum"); assertThat(hangarTypes.length(), equalTo(3));
final Set<String> types = toStringSet(hangarTypes);
wodzuu/JSONschema4-mapper
src/test/java/pl/zientarski/TypeHandlerTest.java
// Path: src/main/java/pl/zientarski/typehandler/TypeHandler.java // public interface TypeHandler { // boolean accepts(Type type); // // JSONObject process(TypeDescription typeDescription, MapperContext mapperContext); // }
import com.google.common.collect.Lists; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import pl.zientarski.typehandler.TypeHandler; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Iterator; import java.util.Set; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue;
package pl.zientarski; public class TypeHandlerTest { private SchemaMapper mapper; class SomeType { } class Hamster { private SomeType someField; public SomeType getSomeField() { return someField; } } @Before public void before() { mapper = new SchemaMapper(); } @Test public void typeHandlerTest() throws Exception { //given
// Path: src/main/java/pl/zientarski/typehandler/TypeHandler.java // public interface TypeHandler { // boolean accepts(Type type); // // JSONObject process(TypeDescription typeDescription, MapperContext mapperContext); // } // Path: src/test/java/pl/zientarski/TypeHandlerTest.java import com.google.common.collect.Lists; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import pl.zientarski.typehandler.TypeHandler; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Iterator; import java.util.Set; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; package pl.zientarski; public class TypeHandlerTest { private SchemaMapper mapper; class SomeType { } class Hamster { private SomeType someField; public SomeType getSomeField() { return someField; } } @Before public void before() { mapper = new SchemaMapper(); } @Test public void typeHandlerTest() throws Exception { //given
mapper.addTypeHandler(new TypeHandler() {