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
coil-lighting/udder
udder/src/main/java/com/coillighting/udder/effect/TextureEffectState.java
// Path: udder/src/main/java/com/coillighting/udder/geometry/ControlQuad.java // public class ControlQuad { // // // Distortion quad for Stretch.stretchXY // public Point2D.Double sw = null; // public Point2D.Double se = null; // public Point2D.Double nw = null; // public Point2D.Double ne = null; // // public ControlQuad(double[][] corners) { // this.reset(); // this.setCorners(corners); // } // // /** Set this ControlQuad to the given four points. // * Incorporate the four values by copy. // */ // public ControlQuad(Point2D.Double sw, Point2D.Double se, // Point2D.Double nw, Point2D.Double ne) // { // this.reset(); // this.setCorners(sw, se, nw, ne); // } // // public ControlQuad() { // this.reset(); // } // // public void setCorners(double[][] corners) { // if(corners != null) { // if(corners.length != 4) { // throw new IllegalArgumentException("A ControlQuad requires exactly 4 corners."); // } else { // final int X = 0; // final int Y = 1; // this.sw.x = corners[0][X]; // this.sw.y = corners[0][Y]; // this.se.x = corners[1][X]; // this.se.y = corners[1][Y]; // this.nw.x = corners[2][X]; // this.nw.y = corners[2][Y]; // this.ne.x = corners[3][X]; // this.ne.y = corners[3][Y]; // } // } // } // // public void setCorners(Point2D.Double sw, Point2D.Double se, // Point2D.Double nw, Point2D.Double ne) // { // this.sw.x = sw.x; // this.sw.y = sw.y; // this.se.x = se.x; // this.se.y = se.y; // this.nw.x = nw.x; // this.nw.y = nw.y; // this.ne.x = ne.x; // this.ne.y = ne.y; // // } // // /** Set this ControlQuad to the unit square, which // * encodes the identity transform for StretchXY. // * (Re)allocate all four points. // */ // public void reset() { // sw = new Point2D.Double(0.0, 0.0); // se = new Point2D.Double(1.0, 0.0); // nw = new Point2D.Double(0.0, 1.0); // ne = new Point2D.Double(1.0, 1.0); // } // // /** Take the other's corner values and set them on this ControlQuad. // * If the other sends a value as null instead of a double, ignore // * it and keep the old value. Use this to eliminate boilerplate from the // * simple act of keeping this ControlQuad in a valid state for stretching. // */ // public void setDoubleValues(ControlQuad other) { // if(other != null) { // if(other.sw != null) { // sw.x = other.sw.x; // sw.y = other.sw.y; // } // if(other.se != null) { // se.x = other.se.x; // se.y = other.se.y; // } // if(other.nw != null) { // nw.x = other.nw.x; // nw.y = other.nw.y; // } // if(other.ne != null) { // ne.x = other.ne.x; // ne.y = other.ne.y; // } // } // } // // public Point2D.Double stretchXY(Point2D.Double xy) { // return Stretch.stretchXY(xy, sw, se, nw, ne); // } // // /** In JSON-compatible format. */ // public String toString() { // return "[["+sw.x+","+sw.y+"],["+se.x+","+se.y+"],["+nw.x+","+nw.y+"],["+ne.x+","+ne.y+"]]"; // } // }
import com.coillighting.udder.geometry.ControlQuad;
package com.coillighting.udder.effect; /** Convey public parameters to and from TextureEffect instances. * This class serves as a JSON mapping target for Boon. */ public class TextureEffectState { /** Map this texture onto the rig. Normally we store these in * udder/udder/images, so a typical fileName looks like * "images/my_file_name.png". Several common RGB and ARGB image types are * theoretically supported, however we have tested only PNG and JPG. Consult * the Java API docs for ImageIO.read() for details. * TextureEffect will reload the file when this value changes. * Send null or the empty string for this value to be ignored, so you keep * showing the current file. */ protected String filename = null; /** If true, automatically stretch and squeeze the image over the rig. * If false, distort the image map according to the four corners in * controlQuad. */ protected boolean automatic = true; /** If automatic is true, then vary the stretching and squeezing motion * this often or faster. (We randomly vary step time from 1 ms at the * fast end to maxTempoMillis at the slow end, and each corner steps * indepdently, so on average you'll see some change in your show * about 4x this often, although many such random changes are subtle * or even invisible.) A good value is 18000 (18 seconds). * Send <=0 for this value to be ignored, retaining the current tempo. */ protected int maxTempoMillis = 0; /** If automatic is false, then don't heed maxTempoMillis; simply obey * the mapping specified here. See Stretch.stretchXY for implementation. * Set to null to keep the current controlQuad. */
// Path: udder/src/main/java/com/coillighting/udder/geometry/ControlQuad.java // public class ControlQuad { // // // Distortion quad for Stretch.stretchXY // public Point2D.Double sw = null; // public Point2D.Double se = null; // public Point2D.Double nw = null; // public Point2D.Double ne = null; // // public ControlQuad(double[][] corners) { // this.reset(); // this.setCorners(corners); // } // // /** Set this ControlQuad to the given four points. // * Incorporate the four values by copy. // */ // public ControlQuad(Point2D.Double sw, Point2D.Double se, // Point2D.Double nw, Point2D.Double ne) // { // this.reset(); // this.setCorners(sw, se, nw, ne); // } // // public ControlQuad() { // this.reset(); // } // // public void setCorners(double[][] corners) { // if(corners != null) { // if(corners.length != 4) { // throw new IllegalArgumentException("A ControlQuad requires exactly 4 corners."); // } else { // final int X = 0; // final int Y = 1; // this.sw.x = corners[0][X]; // this.sw.y = corners[0][Y]; // this.se.x = corners[1][X]; // this.se.y = corners[1][Y]; // this.nw.x = corners[2][X]; // this.nw.y = corners[2][Y]; // this.ne.x = corners[3][X]; // this.ne.y = corners[3][Y]; // } // } // } // // public void setCorners(Point2D.Double sw, Point2D.Double se, // Point2D.Double nw, Point2D.Double ne) // { // this.sw.x = sw.x; // this.sw.y = sw.y; // this.se.x = se.x; // this.se.y = se.y; // this.nw.x = nw.x; // this.nw.y = nw.y; // this.ne.x = ne.x; // this.ne.y = ne.y; // // } // // /** Set this ControlQuad to the unit square, which // * encodes the identity transform for StretchXY. // * (Re)allocate all four points. // */ // public void reset() { // sw = new Point2D.Double(0.0, 0.0); // se = new Point2D.Double(1.0, 0.0); // nw = new Point2D.Double(0.0, 1.0); // ne = new Point2D.Double(1.0, 1.0); // } // // /** Take the other's corner values and set them on this ControlQuad. // * If the other sends a value as null instead of a double, ignore // * it and keep the old value. Use this to eliminate boilerplate from the // * simple act of keeping this ControlQuad in a valid state for stretching. // */ // public void setDoubleValues(ControlQuad other) { // if(other != null) { // if(other.sw != null) { // sw.x = other.sw.x; // sw.y = other.sw.y; // } // if(other.se != null) { // se.x = other.se.x; // se.y = other.se.y; // } // if(other.nw != null) { // nw.x = other.nw.x; // nw.y = other.nw.y; // } // if(other.ne != null) { // ne.x = other.ne.x; // ne.y = other.ne.y; // } // } // } // // public Point2D.Double stretchXY(Point2D.Double xy) { // return Stretch.stretchXY(xy, sw, se, nw, ne); // } // // /** In JSON-compatible format. */ // public String toString() { // return "[["+sw.x+","+sw.y+"],["+se.x+","+se.y+"],["+nw.x+","+nw.y+"],["+ne.x+","+ne.y+"]]"; // } // } // Path: udder/src/main/java/com/coillighting/udder/effect/TextureEffectState.java import com.coillighting.udder.geometry.ControlQuad; package com.coillighting.udder.effect; /** Convey public parameters to and from TextureEffect instances. * This class serves as a JSON mapping target for Boon. */ public class TextureEffectState { /** Map this texture onto the rig. Normally we store these in * udder/udder/images, so a typical fileName looks like * "images/my_file_name.png". Several common RGB and ARGB image types are * theoretically supported, however we have tested only PNG and JPG. Consult * the Java API docs for ImageIO.read() for details. * TextureEffect will reload the file when this value changes. * Send null or the empty string for this value to be ignored, so you keep * showing the current file. */ protected String filename = null; /** If true, automatically stretch and squeeze the image over the rig. * If false, distort the image map according to the four corners in * controlQuad. */ protected boolean automatic = true; /** If automatic is true, then vary the stretching and squeezing motion * this often or faster. (We randomly vary step time from 1 ms at the * fast end to maxTempoMillis at the slow end, and each corner steps * indepdently, so on average you'll see some change in your show * about 4x this often, although many such random changes are subtle * or even invisible.) A good value is 18000 (18 seconds). * Send <=0 for this value to be ignored, retaining the current tempo. */ protected int maxTempoMillis = 0; /** If automatic is false, then don't heed maxTempoMillis; simply obey * the mapping specified here. See Stretch.stretchXY for implementation. * Set to null to keep the current controlQuad. */
protected ControlQuad controlQuad = null;
coil-lighting/udder
udder/src/main/java/com/coillighting/udder/model/Device.java
// Path: udder/src/main/java/com/coillighting/udder/geometry/BoundingCube.java // public class BoundingCube { // // protected double minX = 0.0; // protected double minY = 0.0; // protected double minZ = 0.0; // // protected double maxX = 0.0; // protected double maxY = 0.0; // protected double maxZ = 0.0; // // protected double width = 0.0; // protected double height = 0.0; // protected double depth = 0.0; // // /** Create a 3D bounding box with the given location and dimensions. */ // public BoundingCube(double minX, double minY, double minZ, // double width, double height, double depth) // { // this.minX = minX; // this.minY = minY; // this.minZ = minZ; // // this.width = width; // this.height = height; // this.depth = depth; // // this.maxX = width + minX; // this.maxY = height + minY; // this.maxZ = depth + minZ; // } // // /** Create a 2D bounding box as a BoundingCube in the XY plane. */ // public BoundingCube(double minX, double minY, // double width, double height) // { // this(minX, minY, 0.0, width, height, 0.0); // } // // public final boolean isEmpty() { // return width < 0.0 || height < 0.0 || depth < 0.0; // } // // public final boolean contains(double x, double y, double z) { // if(this.isEmpty()) { // return false; // } else { // return x >= minX && x <= maxX // && y >= minY && y <= maxY // && z >= minZ && z <= maxZ; // } // } // // public final boolean contains(Point3D pt) { // if(pt != null) { // return this.contains(pt.getX(), pt.getY(), pt.getZ()); // } else { // return false; // } // } // // public String toString() { // return "x:[" + minX + ", " + maxX + "] y:[" + minY + ", " + maxY + "] z:[" + minZ + ", " + maxZ + "] w:" + width + " h:" + height + " d:" + depth + "w/h:" + (width/height); // } // // public final double getMinX() { // return minX; // } // // public final void setMinX(double minX) { // this.minX = minX; // } // // public final double getMinY() { // return minY; // } // // public final void setMinY(double minY) { // this.minY = minY; // } // // public final double getMinZ() { // return minZ; // } // // public final void setMinZ(double minZ) { // this.minZ = minZ; // } // // public final double getWidth() { // return width; // } // // public final void setWidth(double width) { // this.width = width; // } // // public final double getHeight() { // return height; // } // // public final void setHeight(double height) { // this.height = height; // } // // public final double getDepth() { // return depth; // } // // public final void setDepth(double depth) { // this.depth = depth; // } // // public final double getMaxX() { // return minX + width; // } // // public final double getMaxY() { // return minY + height; // } // // public final double getMaxZ() { // return minZ + depth; // } // } // // Path: udder/src/main/java/com/coillighting/udder/geometry/Point3D.java // public class Point3D { // // public double x = 0.0; // public double y = 0.0; // public double z = 0.0; // // public Point3D(double x, double y, double z) { // this.x = x; // this.y = y; // this.z = z; // } // // public final double getX() { // return x; // } // // public final double getY() { // return y; // } // // public final double getZ() { // return z; // } // // public final void setX(double x) { // this.x = x; // } // // public final void setY(double y) { // this.y = y; // } // // public final void setZ(double z) { // this.z = z; // } // // }
import com.coillighting.udder.geometry.BoundingCube; import com.coillighting.udder.geometry.Point3D;
public Device(int addr, int group, double x, double y, double z) { if(addr < 0) { throw new IllegalArgumentException("Invalid Device address: " + addr); } else if(group < 0) { throw new IllegalArgumentException("Negative group index: " + addr); } this.addr = addr; this.group = group; this.x = x; this.y = y; this.z = z; } public String toString() { return "Device @"+addr+" ["+group+"] ("+x+","+y+","+z+")"; } public int getAddr() { return this.addr; } public int getGroup() { return this.group; } // TODO refactor x, y and z as a double[] for consistency with other classes? or refactor as a Point3D (see below). We should standardize here. public double[] getPoint() { return new double[]{x, y, z}; }
// Path: udder/src/main/java/com/coillighting/udder/geometry/BoundingCube.java // public class BoundingCube { // // protected double minX = 0.0; // protected double minY = 0.0; // protected double minZ = 0.0; // // protected double maxX = 0.0; // protected double maxY = 0.0; // protected double maxZ = 0.0; // // protected double width = 0.0; // protected double height = 0.0; // protected double depth = 0.0; // // /** Create a 3D bounding box with the given location and dimensions. */ // public BoundingCube(double minX, double minY, double minZ, // double width, double height, double depth) // { // this.minX = minX; // this.minY = minY; // this.minZ = minZ; // // this.width = width; // this.height = height; // this.depth = depth; // // this.maxX = width + minX; // this.maxY = height + minY; // this.maxZ = depth + minZ; // } // // /** Create a 2D bounding box as a BoundingCube in the XY plane. */ // public BoundingCube(double minX, double minY, // double width, double height) // { // this(minX, minY, 0.0, width, height, 0.0); // } // // public final boolean isEmpty() { // return width < 0.0 || height < 0.0 || depth < 0.0; // } // // public final boolean contains(double x, double y, double z) { // if(this.isEmpty()) { // return false; // } else { // return x >= minX && x <= maxX // && y >= minY && y <= maxY // && z >= minZ && z <= maxZ; // } // } // // public final boolean contains(Point3D pt) { // if(pt != null) { // return this.contains(pt.getX(), pt.getY(), pt.getZ()); // } else { // return false; // } // } // // public String toString() { // return "x:[" + minX + ", " + maxX + "] y:[" + minY + ", " + maxY + "] z:[" + minZ + ", " + maxZ + "] w:" + width + " h:" + height + " d:" + depth + "w/h:" + (width/height); // } // // public final double getMinX() { // return minX; // } // // public final void setMinX(double minX) { // this.minX = minX; // } // // public final double getMinY() { // return minY; // } // // public final void setMinY(double minY) { // this.minY = minY; // } // // public final double getMinZ() { // return minZ; // } // // public final void setMinZ(double minZ) { // this.minZ = minZ; // } // // public final double getWidth() { // return width; // } // // public final void setWidth(double width) { // this.width = width; // } // // public final double getHeight() { // return height; // } // // public final void setHeight(double height) { // this.height = height; // } // // public final double getDepth() { // return depth; // } // // public final void setDepth(double depth) { // this.depth = depth; // } // // public final double getMaxX() { // return minX + width; // } // // public final double getMaxY() { // return minY + height; // } // // public final double getMaxZ() { // return minZ + depth; // } // } // // Path: udder/src/main/java/com/coillighting/udder/geometry/Point3D.java // public class Point3D { // // public double x = 0.0; // public double y = 0.0; // public double z = 0.0; // // public Point3D(double x, double y, double z) { // this.x = x; // this.y = y; // this.z = z; // } // // public final double getX() { // return x; // } // // public final double getY() { // return y; // } // // public final double getZ() { // return z; // } // // public final void setX(double x) { // this.x = x; // } // // public final void setY(double y) { // this.y = y; // } // // public final void setZ(double z) { // this.z = z; // } // // } // Path: udder/src/main/java/com/coillighting/udder/model/Device.java import com.coillighting.udder.geometry.BoundingCube; import com.coillighting.udder.geometry.Point3D; public Device(int addr, int group, double x, double y, double z) { if(addr < 0) { throw new IllegalArgumentException("Invalid Device address: " + addr); } else if(group < 0) { throw new IllegalArgumentException("Negative group index: " + addr); } this.addr = addr; this.group = group; this.x = x; this.y = y; this.z = z; } public String toString() { return "Device @"+addr+" ["+group+"] ("+x+","+y+","+z+")"; } public int getAddr() { return this.addr; } public int getGroup() { return this.group; } // TODO refactor x, y and z as a double[] for consistency with other classes? or refactor as a Point3D (see below). We should standardize here. public double[] getPoint() { return new double[]{x, y, z}; }
public Point3D getPoint3D() {
coil-lighting/udder
udder/src/main/java/com/coillighting/udder/model/Device.java
// Path: udder/src/main/java/com/coillighting/udder/geometry/BoundingCube.java // public class BoundingCube { // // protected double minX = 0.0; // protected double minY = 0.0; // protected double minZ = 0.0; // // protected double maxX = 0.0; // protected double maxY = 0.0; // protected double maxZ = 0.0; // // protected double width = 0.0; // protected double height = 0.0; // protected double depth = 0.0; // // /** Create a 3D bounding box with the given location and dimensions. */ // public BoundingCube(double minX, double minY, double minZ, // double width, double height, double depth) // { // this.minX = minX; // this.minY = minY; // this.minZ = minZ; // // this.width = width; // this.height = height; // this.depth = depth; // // this.maxX = width + minX; // this.maxY = height + minY; // this.maxZ = depth + minZ; // } // // /** Create a 2D bounding box as a BoundingCube in the XY plane. */ // public BoundingCube(double minX, double minY, // double width, double height) // { // this(minX, minY, 0.0, width, height, 0.0); // } // // public final boolean isEmpty() { // return width < 0.0 || height < 0.0 || depth < 0.0; // } // // public final boolean contains(double x, double y, double z) { // if(this.isEmpty()) { // return false; // } else { // return x >= minX && x <= maxX // && y >= minY && y <= maxY // && z >= minZ && z <= maxZ; // } // } // // public final boolean contains(Point3D pt) { // if(pt != null) { // return this.contains(pt.getX(), pt.getY(), pt.getZ()); // } else { // return false; // } // } // // public String toString() { // return "x:[" + minX + ", " + maxX + "] y:[" + minY + ", " + maxY + "] z:[" + minZ + ", " + maxZ + "] w:" + width + " h:" + height + " d:" + depth + "w/h:" + (width/height); // } // // public final double getMinX() { // return minX; // } // // public final void setMinX(double minX) { // this.minX = minX; // } // // public final double getMinY() { // return minY; // } // // public final void setMinY(double minY) { // this.minY = minY; // } // // public final double getMinZ() { // return minZ; // } // // public final void setMinZ(double minZ) { // this.minZ = minZ; // } // // public final double getWidth() { // return width; // } // // public final void setWidth(double width) { // this.width = width; // } // // public final double getHeight() { // return height; // } // // public final void setHeight(double height) { // this.height = height; // } // // public final double getDepth() { // return depth; // } // // public final void setDepth(double depth) { // this.depth = depth; // } // // public final double getMaxX() { // return minX + width; // } // // public final double getMaxY() { // return minY + height; // } // // public final double getMaxZ() { // return minZ + depth; // } // } // // Path: udder/src/main/java/com/coillighting/udder/geometry/Point3D.java // public class Point3D { // // public double x = 0.0; // public double y = 0.0; // public double z = 0.0; // // public Point3D(double x, double y, double z) { // this.x = x; // this.y = y; // this.z = z; // } // // public final double getX() { // return x; // } // // public final double getY() { // return y; // } // // public final double getZ() { // return z; // } // // public final void setX(double x) { // this.x = x; // } // // public final void setY(double y) { // this.y = y; // } // // public final void setZ(double z) { // this.z = z; // } // // }
import com.coillighting.udder.geometry.BoundingCube; import com.coillighting.udder.geometry.Point3D;
} this.addr = addr; this.group = group; this.x = x; this.y = y; this.z = z; } public String toString() { return "Device @"+addr+" ["+group+"] ("+x+","+y+","+z+")"; } public int getAddr() { return this.addr; } public int getGroup() { return this.group; } // TODO refactor x, y and z as a double[] for consistency with other classes? or refactor as a Point3D (see below). We should standardize here. public double[] getPoint() { return new double[]{x, y, z}; } public Point3D getPoint3D() { return new Point3D(x, y, z); } /** Return the 3D bounding box for the given devices. */
// Path: udder/src/main/java/com/coillighting/udder/geometry/BoundingCube.java // public class BoundingCube { // // protected double minX = 0.0; // protected double minY = 0.0; // protected double minZ = 0.0; // // protected double maxX = 0.0; // protected double maxY = 0.0; // protected double maxZ = 0.0; // // protected double width = 0.0; // protected double height = 0.0; // protected double depth = 0.0; // // /** Create a 3D bounding box with the given location and dimensions. */ // public BoundingCube(double minX, double minY, double minZ, // double width, double height, double depth) // { // this.minX = minX; // this.minY = minY; // this.minZ = minZ; // // this.width = width; // this.height = height; // this.depth = depth; // // this.maxX = width + minX; // this.maxY = height + minY; // this.maxZ = depth + minZ; // } // // /** Create a 2D bounding box as a BoundingCube in the XY plane. */ // public BoundingCube(double minX, double minY, // double width, double height) // { // this(minX, minY, 0.0, width, height, 0.0); // } // // public final boolean isEmpty() { // return width < 0.0 || height < 0.0 || depth < 0.0; // } // // public final boolean contains(double x, double y, double z) { // if(this.isEmpty()) { // return false; // } else { // return x >= minX && x <= maxX // && y >= minY && y <= maxY // && z >= minZ && z <= maxZ; // } // } // // public final boolean contains(Point3D pt) { // if(pt != null) { // return this.contains(pt.getX(), pt.getY(), pt.getZ()); // } else { // return false; // } // } // // public String toString() { // return "x:[" + minX + ", " + maxX + "] y:[" + minY + ", " + maxY + "] z:[" + minZ + ", " + maxZ + "] w:" + width + " h:" + height + " d:" + depth + "w/h:" + (width/height); // } // // public final double getMinX() { // return minX; // } // // public final void setMinX(double minX) { // this.minX = minX; // } // // public final double getMinY() { // return minY; // } // // public final void setMinY(double minY) { // this.minY = minY; // } // // public final double getMinZ() { // return minZ; // } // // public final void setMinZ(double minZ) { // this.minZ = minZ; // } // // public final double getWidth() { // return width; // } // // public final void setWidth(double width) { // this.width = width; // } // // public final double getHeight() { // return height; // } // // public final void setHeight(double height) { // this.height = height; // } // // public final double getDepth() { // return depth; // } // // public final void setDepth(double depth) { // this.depth = depth; // } // // public final double getMaxX() { // return minX + width; // } // // public final double getMaxY() { // return minY + height; // } // // public final double getMaxZ() { // return minZ + depth; // } // } // // Path: udder/src/main/java/com/coillighting/udder/geometry/Point3D.java // public class Point3D { // // public double x = 0.0; // public double y = 0.0; // public double z = 0.0; // // public Point3D(double x, double y, double z) { // this.x = x; // this.y = y; // this.z = z; // } // // public final double getX() { // return x; // } // // public final double getY() { // return y; // } // // public final double getZ() { // return z; // } // // public final void setX(double x) { // this.x = x; // } // // public final void setY(double y) { // this.y = y; // } // // public final void setZ(double z) { // this.z = z; // } // // } // Path: udder/src/main/java/com/coillighting/udder/model/Device.java import com.coillighting.udder.geometry.BoundingCube; import com.coillighting.udder.geometry.Point3D; } this.addr = addr; this.group = group; this.x = x; this.y = y; this.z = z; } public String toString() { return "Device @"+addr+" ["+group+"] ("+x+","+y+","+z+")"; } public int getAddr() { return this.addr; } public int getGroup() { return this.group; } // TODO refactor x, y and z as a double[] for consistency with other classes? or refactor as a Point3D (see below). We should standardize here. public double[] getPoint() { return new double[]{x, y, z}; } public Point3D getPoint3D() { return new Point3D(x, y, z); } /** Return the 3D bounding box for the given devices. */
public static BoundingCube getDeviceBoundingCube(Device[] devices) {
coil-lighting/udder
udder/src/main/java/com/coillighting/udder/geometry/wave/SharkfinFloatWave.java
// Path: udder/src/main/java/com/coillighting/udder/geometry/Crossfade.java // public class Crossfade { // // /** Linearly interpolate x, a value between 0 and 1, between two points, // * (0, y0) and (1, y1). If you supply an x that is out of range, the // * result will likewise be out of range. // */ // public static final double linear(double x, double y0, double y1) { // return y0 + x * (y1 - y0); // } // // /** A 32-bit version of Crossfade.linear. */ // public static final float linear(float x, float y0, float y1) { // return y0 + x * (y1 - y0); // } // // /** For a fast attack followed by a slower follow-through, try an exponent // * of 0.5 or 0.25. For a gradual attack with an accelerating follow-up, // * try an exponent of 2-5. This is not really the shapliest easing curve // * curve out there, but it's good to have in the arsenal. // */ // public static final double exponential(double x, double exponent, double y0, double y1) { // double balance = Reshape.exponential(x, exponent); // return linear(balance, y0, y1); // } // // /** A mostly 32-bit version of Crossfade.exponential. */ // public static final float exponential(float x, float exponent, float y0, float y1) { // float balance = Reshape.exponential(x, exponent); // return linear(balance, y0, y1); // } // // /** Use a sinewave to approximate a sigmoidal cross-fade curve. // * Submit this expression to wolframalpha.com to see the resulting curve: // * 0.5*(1 + (sin((pi*(x-0.5))))) // * Direct link: // * http://www.wolframalpha.com/input/?i=0.5*%281+%2B+%28sin%28%28pi*%28x-0.5%29%29%29%29%29+from+-0.25+to+1.5 // */ // public static final double sinusoidal(double x, double y0, double y1) { // double balance = Reshape.sinusoidal(x); // return linear(balance, y0, y1); // } // // /** A mostly 32-bit version of crossfadeExponential. */ // public static final float sinusoidal(float x, float y0, float y1) { // float balance = Reshape.sinusoidal(x); // return linear(balance, y0, y1); // } // // // TODO logarithmic mode! // // }
import com.coillighting.udder.geometry.Crossfade;
package com.coillighting.udder.geometry.wave; /** A sinusoidally interpolated signal that continuously oscillates from start * to end, then discontinuously jumps back to the start value. */ public class SharkfinFloatWave extends FloatWaveBase { public SharkfinFloatWave(float start, float end, long period) { super(start, end, period); } public float interpolate(float x) {
// Path: udder/src/main/java/com/coillighting/udder/geometry/Crossfade.java // public class Crossfade { // // /** Linearly interpolate x, a value between 0 and 1, between two points, // * (0, y0) and (1, y1). If you supply an x that is out of range, the // * result will likewise be out of range. // */ // public static final double linear(double x, double y0, double y1) { // return y0 + x * (y1 - y0); // } // // /** A 32-bit version of Crossfade.linear. */ // public static final float linear(float x, float y0, float y1) { // return y0 + x * (y1 - y0); // } // // /** For a fast attack followed by a slower follow-through, try an exponent // * of 0.5 or 0.25. For a gradual attack with an accelerating follow-up, // * try an exponent of 2-5. This is not really the shapliest easing curve // * curve out there, but it's good to have in the arsenal. // */ // public static final double exponential(double x, double exponent, double y0, double y1) { // double balance = Reshape.exponential(x, exponent); // return linear(balance, y0, y1); // } // // /** A mostly 32-bit version of Crossfade.exponential. */ // public static final float exponential(float x, float exponent, float y0, float y1) { // float balance = Reshape.exponential(x, exponent); // return linear(balance, y0, y1); // } // // /** Use a sinewave to approximate a sigmoidal cross-fade curve. // * Submit this expression to wolframalpha.com to see the resulting curve: // * 0.5*(1 + (sin((pi*(x-0.5))))) // * Direct link: // * http://www.wolframalpha.com/input/?i=0.5*%281+%2B+%28sin%28%28pi*%28x-0.5%29%29%29%29%29+from+-0.25+to+1.5 // */ // public static final double sinusoidal(double x, double y0, double y1) { // double balance = Reshape.sinusoidal(x); // return linear(balance, y0, y1); // } // // /** A mostly 32-bit version of crossfadeExponential. */ // public static final float sinusoidal(float x, float y0, float y1) { // float balance = Reshape.sinusoidal(x); // return linear(balance, y0, y1); // } // // // TODO logarithmic mode! // // } // Path: udder/src/main/java/com/coillighting/udder/geometry/wave/SharkfinFloatWave.java import com.coillighting.udder.geometry.Crossfade; package com.coillighting.udder.geometry.wave; /** A sinusoidally interpolated signal that continuously oscillates from start * to end, then discontinuously jumps back to the start value. */ public class SharkfinFloatWave extends FloatWaveBase { public SharkfinFloatWave(float start, float end, long period) { super(start, end, period); } public float interpolate(float x) {
return Crossfade.sinusoidal(x, start, end);
coil-lighting/udder
udder/src/main/java/com/coillighting/udder/effect/woven/CueBase.java
// Path: udder/src/main/java/com/coillighting/udder/mix/TimePoint.java // public class TimePoint { // // /** The nomimally "real" time at which this frame was initialized. Although // * this time is required by some animations which need to synchronize their // * effects with the outside world -- a dusk/dawn almanac scheduler, for // * instance -- you should ordinarily never refer to the realTimeMillis in // * your animation functions. Instead, use TimePoint.sceneTimeMillis in // * order to give the user the opportunity to apply timebase distortions. // * Initialized with System.currentTimeMillis(). // * // * Not to be confused with TimePoint.sceneTimeMillis. // */ // private long realTimeMillis = 0; // // /** The reference time for all elements of the current scene. By using this // * offset as the current time for timebase calculations in your animators, // * you allow the user to apply timebase distortions, a powerful creative // * tool. For ideas of what you might do with timebase distortions, sit // * down with an old Invisibl Skratch Piklz, then imagine stretching and // * reversing your graphical animations as if they were audio, at high rez. // * This time is compatible with, but not necessarily identical to, the // * "real" millisecond time offset returned by System.currentTimeMillis(). // * When a show is playing back in nominally real time, with no timebase // * transformations or distortions, then this value will by convention // * equal TimePoint.realTimeMillis minus the realTimeMillis when the show // * started, and then this value will count up monotonically thereafter. // * However, there is no guarantee that the user will choose to follow such // * a straightforward path through time. // * // * Not to be confused with TimePoint.realTimeMillis. // */ // private long sceneTimeMillis = 0; // // /** An integer counting the current frame. Normally a show begins at frame // * 0 and proceeds to count up, +1 per frame, but there is no guarantee that // * a user will configure a show to count incrementally. There is even no // * guarantee that frameIndex will monotonically increase. However, a normal // * show which doesn't replay its own history will by convention simply // * start from 0 and monotonically increment +1 per animation loop. // */ // private long frameIndex = 0; // // public TimePoint(long realTimeMillis, long sceneTimeMillis, long frameIndex) { // this.realTimeMillis = realTimeMillis; // this.sceneTimeMillis = sceneTimeMillis; // this.frameIndex = frameIndex; // } // // /** Copy constructor. */ // public TimePoint(TimePoint timePoint) { // this.realTimeMillis = timePoint.realTimeMillis; // this.sceneTimeMillis = timePoint.sceneTimeMillis; // this.frameIndex = timePoint.frameIndex; // } // // /** Initialize a TimePoint with the current system time as its nominally // * "real" time offset. Start counting the scene time from 0 and frameIndex // * at 0. // */ // public TimePoint() { // this.realTimeMillis = System.currentTimeMillis(); // this.sceneTimeMillis = 0; // this.frameIndex = 0; // } // // /** Return a new immutable TimePoint, incrementing frameIndex and updating // * realTimeMillis and sceneTimeMillis on the assumption that the show is // * taking a straightforward and undistorted path through time. // */ // public TimePoint next() { // long realTime = System.currentTimeMillis(); // long sceneTimeOffsetMillis = this.realTimeMillis - this.sceneTimeMillis; // return new TimePoint( // realTime, // realTime - sceneTimeOffsetMillis, // 1 + this.frameIndex); // } // // public long realTimeMillis() { // return this.realTimeMillis; // } // // public long sceneTimeMillis() { // return this.sceneTimeMillis; // } // // public long getFrameIndex() { // return this.frameIndex; // } // // public String toString() { // return "" + this.sceneTimeMillis + "ms [#" + this.frameIndex + ']'; // } // // }
import com.coillighting.udder.mix.TimePoint;
package com.coillighting.udder.effect.woven; public class CueBase implements Cue { protected CueFadeStateEnum fadeState = null; /** Target duration in milliseconds. */ protected long duration = 0; protected long startTime = 0; /** Rasters we might want to draw on for this cue. */ protected WovenFrame frame = null; public CueBase(long duration, WovenFrame frame) { this.setDuration(duration); this.setFrame(frame); } public void setFadeState(CueFadeStateEnum fadeState) { this.fadeState = fadeState; } public CueFadeStateEnum getFadeState() { return fadeState; } public void setDuration(long duration) { if(duration <= 0) { this.duration = 0; } else { this.duration = duration; } } public long getDuration() { return this.duration; }
// Path: udder/src/main/java/com/coillighting/udder/mix/TimePoint.java // public class TimePoint { // // /** The nomimally "real" time at which this frame was initialized. Although // * this time is required by some animations which need to synchronize their // * effects with the outside world -- a dusk/dawn almanac scheduler, for // * instance -- you should ordinarily never refer to the realTimeMillis in // * your animation functions. Instead, use TimePoint.sceneTimeMillis in // * order to give the user the opportunity to apply timebase distortions. // * Initialized with System.currentTimeMillis(). // * // * Not to be confused with TimePoint.sceneTimeMillis. // */ // private long realTimeMillis = 0; // // /** The reference time for all elements of the current scene. By using this // * offset as the current time for timebase calculations in your animators, // * you allow the user to apply timebase distortions, a powerful creative // * tool. For ideas of what you might do with timebase distortions, sit // * down with an old Invisibl Skratch Piklz, then imagine stretching and // * reversing your graphical animations as if they were audio, at high rez. // * This time is compatible with, but not necessarily identical to, the // * "real" millisecond time offset returned by System.currentTimeMillis(). // * When a show is playing back in nominally real time, with no timebase // * transformations or distortions, then this value will by convention // * equal TimePoint.realTimeMillis minus the realTimeMillis when the show // * started, and then this value will count up monotonically thereafter. // * However, there is no guarantee that the user will choose to follow such // * a straightforward path through time. // * // * Not to be confused with TimePoint.realTimeMillis. // */ // private long sceneTimeMillis = 0; // // /** An integer counting the current frame. Normally a show begins at frame // * 0 and proceeds to count up, +1 per frame, but there is no guarantee that // * a user will configure a show to count incrementally. There is even no // * guarantee that frameIndex will monotonically increase. However, a normal // * show which doesn't replay its own history will by convention simply // * start from 0 and monotonically increment +1 per animation loop. // */ // private long frameIndex = 0; // // public TimePoint(long realTimeMillis, long sceneTimeMillis, long frameIndex) { // this.realTimeMillis = realTimeMillis; // this.sceneTimeMillis = sceneTimeMillis; // this.frameIndex = frameIndex; // } // // /** Copy constructor. */ // public TimePoint(TimePoint timePoint) { // this.realTimeMillis = timePoint.realTimeMillis; // this.sceneTimeMillis = timePoint.sceneTimeMillis; // this.frameIndex = timePoint.frameIndex; // } // // /** Initialize a TimePoint with the current system time as its nominally // * "real" time offset. Start counting the scene time from 0 and frameIndex // * at 0. // */ // public TimePoint() { // this.realTimeMillis = System.currentTimeMillis(); // this.sceneTimeMillis = 0; // this.frameIndex = 0; // } // // /** Return a new immutable TimePoint, incrementing frameIndex and updating // * realTimeMillis and sceneTimeMillis on the assumption that the show is // * taking a straightforward and undistorted path through time. // */ // public TimePoint next() { // long realTime = System.currentTimeMillis(); // long sceneTimeOffsetMillis = this.realTimeMillis - this.sceneTimeMillis; // return new TimePoint( // realTime, // realTime - sceneTimeOffsetMillis, // 1 + this.frameIndex); // } // // public long realTimeMillis() { // return this.realTimeMillis; // } // // public long sceneTimeMillis() { // return this.sceneTimeMillis; // } // // public long getFrameIndex() { // return this.frameIndex; // } // // public String toString() { // return "" + this.sceneTimeMillis + "ms [#" + this.frameIndex + ']'; // } // // } // Path: udder/src/main/java/com/coillighting/udder/effect/woven/CueBase.java import com.coillighting.udder.mix.TimePoint; package com.coillighting.udder.effect.woven; public class CueBase implements Cue { protected CueFadeStateEnum fadeState = null; /** Target duration in milliseconds. */ protected long duration = 0; protected long startTime = 0; /** Rasters we might want to draw on for this cue. */ protected WovenFrame frame = null; public CueBase(long duration, WovenFrame frame) { this.setDuration(duration); this.setFrame(frame); } public void setFadeState(CueFadeStateEnum fadeState) { this.fadeState = fadeState; } public CueFadeStateEnum getFadeState() { return fadeState; } public void setDuration(long duration) { if(duration <= 0) { this.duration = 0; } else { this.duration = duration; } } public long getDuration() { return this.duration; }
public static double computeFractionElapsed(TimePoint timePoint,
coil-lighting/udder
udder/src/main/java/com/coillighting/udder/infrastructure/OpcLayoutPoint.java
// Path: udder/src/main/java/com/coillighting/udder/model/Device.java // public class Device extends Object { // // /** This Device's address in some arbitrary address space. For the dairy, // * this address is in the space of a single OPC channel. // * // * FUTURE Multiple channels/universes. // * // * Not public because no effects should be computed on the basis of a // * Device's address. // */ // protected int addr = 0; // // /** A dirt simple grouping mechanism. Each Device belongs to exactly one // * group (for now). For the Dairy installation, this will indicate gate // * 0 or gate 1, in case an Animator cares which group the Device is in. // * // * Public because device group computations happen in the hottest inner loop. // */ // public int group=0; // // /** Position in model space. Public because device positional // * computations happen in the hottest inner loop. // */ // public double x = 0.0; // public double y = 0.0; // public double z = 0.0; // // public Device(int addr, int group, double x, double y, double z) { // if(addr < 0) { // throw new IllegalArgumentException("Invalid Device address: " + addr); // } else if(group < 0) { // throw new IllegalArgumentException("Negative group index: " + addr); // } // this.addr = addr; // this.group = group; // this.x = x; // this.y = y; // this.z = z; // } // // public String toString() { // return "Device @"+addr+" ["+group+"] ("+x+","+y+","+z+")"; // } // // public int getAddr() { // return this.addr; // } // // public int getGroup() { // return this.group; // } // // // TODO refactor x, y and z as a double[] for consistency with other classes? or refactor as a Point3D (see below). We should standardize here. // public double[] getPoint() { // return new double[]{x, y, z}; // } // // public Point3D getPoint3D() { // return new Point3D(x, y, z); // } // // /** Return the 3D bounding box for the given devices. */ // public static BoundingCube getDeviceBoundingCube(Device[] devices) { // if(devices==null) { // return null; // } else { // // FIXME: determine the real min and max values that will compare properly. // // A seed value of Double.MAX_VALUE did not work with all comparisons here. WTF? // // For now you must place your devices within this cube, sorry: // final double MAX_VALUE = 999999999.0; // final double MIN_VALUE = -999999999.0; // // double minx=MAX_VALUE; // double maxx=MIN_VALUE; // double miny=MAX_VALUE; // double maxy=MIN_VALUE; // double minz=MAX_VALUE; // double maxz=MIN_VALUE; // // for(Device d: devices) { // double x = d.x; // double y = d.y; // double z = d.z; // if(x < minx) minx = x; // if(x > maxx) maxx = x; // if(y < miny) miny = y; // if(y > maxy) maxy = y; // if(z < minz) minz = z; // if(z > maxz) maxz = z; // } // return new BoundingCube(minx, miny, minz, // maxx-minx, maxy-miny, maxz-minz); // } // } // }
import com.coillighting.udder.model.Device; import java.util.ArrayList; import java.util.List;
package com.coillighting.udder.infrastructure; /** Data structure representing a 3D point in an Open Pixel Control layout * file. We will serialize this as an element in a JSON array. For details * on this dirt simple file format, see the following URL: * * https://github.com/zestyping/openpixelcontrol/tree/master/layouts * * Example output consisting of three JSON-serialized OpcLayoutPoints: * * [ * {"point": [1.32, 0.00, 1.32]}, * {"point": [1.32, 0.00, 1.21]}, * {"point": [1.32, 0.00, 1.10]} * ] * * Like Command and PatchElement, this class is structured for compatibility * with the Boon JsonFactory, which automatically binds JSON bidirectionally * to Java classes which adhere to its preferred (bean-style) layout. * * After you serialize your JSON layout, you can use it to run the barebones * OpenGL server that comes with Open Pixel Control. Invoke it like this: * * $ path/to/bin/gl_server path/to/udder/udder/conf/opc_layout.json * * For the Dairy project, we recommend trying Eric Miller's visualizer: * * https://github.com/patternleaf/archway */ public class OpcLayoutPoint { private double[] point; public OpcLayoutPoint(double[] point) { if(point == null) { throw new NullPointerException("point is null"); } else if(point.length != 3) { throw new IllegalArgumentException("invalid point length " + point.length); } this.point = point; } public double[] getPoint() { return this.point; } public void scale(double factor) { for(int i=0; i<point.length; i++) { point[i] *= factor; } } /** Return a list associating OPC address with spatial coordinates. * The Open Pixel Control's gl_server consumes this list and presents * a very simple 3D view of your show, which you can use as a monitor. * See https://github.com/patternleaf/archway for a fine example of how to * create a much snazzier 3D monitor in your browser. */ public static List<OpcLayoutPoint> createOpcLayoutPoints(PatchSheet patchSheet) { // We occasionally skip scaling when debugging. final boolean autoscale = true; // Shrink the layout, which at the Dairy arrived in inches, to fit the // limited viewport of the OPC gl model. // TODO: automatically compute a decent scale, since the GL viewport // lacks auto zoom -- or implement autozoom for gl_server. final double glViewportScale = 3.0; final double [] origin = {0.0, 0.0, 0.0};
// Path: udder/src/main/java/com/coillighting/udder/model/Device.java // public class Device extends Object { // // /** This Device's address in some arbitrary address space. For the dairy, // * this address is in the space of a single OPC channel. // * // * FUTURE Multiple channels/universes. // * // * Not public because no effects should be computed on the basis of a // * Device's address. // */ // protected int addr = 0; // // /** A dirt simple grouping mechanism. Each Device belongs to exactly one // * group (for now). For the Dairy installation, this will indicate gate // * 0 or gate 1, in case an Animator cares which group the Device is in. // * // * Public because device group computations happen in the hottest inner loop. // */ // public int group=0; // // /** Position in model space. Public because device positional // * computations happen in the hottest inner loop. // */ // public double x = 0.0; // public double y = 0.0; // public double z = 0.0; // // public Device(int addr, int group, double x, double y, double z) { // if(addr < 0) { // throw new IllegalArgumentException("Invalid Device address: " + addr); // } else if(group < 0) { // throw new IllegalArgumentException("Negative group index: " + addr); // } // this.addr = addr; // this.group = group; // this.x = x; // this.y = y; // this.z = z; // } // // public String toString() { // return "Device @"+addr+" ["+group+"] ("+x+","+y+","+z+")"; // } // // public int getAddr() { // return this.addr; // } // // public int getGroup() { // return this.group; // } // // // TODO refactor x, y and z as a double[] for consistency with other classes? or refactor as a Point3D (see below). We should standardize here. // public double[] getPoint() { // return new double[]{x, y, z}; // } // // public Point3D getPoint3D() { // return new Point3D(x, y, z); // } // // /** Return the 3D bounding box for the given devices. */ // public static BoundingCube getDeviceBoundingCube(Device[] devices) { // if(devices==null) { // return null; // } else { // // FIXME: determine the real min and max values that will compare properly. // // A seed value of Double.MAX_VALUE did not work with all comparisons here. WTF? // // For now you must place your devices within this cube, sorry: // final double MAX_VALUE = 999999999.0; // final double MIN_VALUE = -999999999.0; // // double minx=MAX_VALUE; // double maxx=MIN_VALUE; // double miny=MAX_VALUE; // double maxy=MIN_VALUE; // double minz=MAX_VALUE; // double maxz=MIN_VALUE; // // for(Device d: devices) { // double x = d.x; // double y = d.y; // double z = d.z; // if(x < minx) minx = x; // if(x > maxx) maxx = x; // if(y < miny) miny = y; // if(y > maxy) maxy = y; // if(z < minz) minz = z; // if(z > maxz) maxz = z; // } // return new BoundingCube(minx, miny, minz, // maxx-minx, maxy-miny, maxz-minz); // } // } // } // Path: udder/src/main/java/com/coillighting/udder/infrastructure/OpcLayoutPoint.java import com.coillighting.udder.model.Device; import java.util.ArrayList; import java.util.List; package com.coillighting.udder.infrastructure; /** Data structure representing a 3D point in an Open Pixel Control layout * file. We will serialize this as an element in a JSON array. For details * on this dirt simple file format, see the following URL: * * https://github.com/zestyping/openpixelcontrol/tree/master/layouts * * Example output consisting of three JSON-serialized OpcLayoutPoints: * * [ * {"point": [1.32, 0.00, 1.32]}, * {"point": [1.32, 0.00, 1.21]}, * {"point": [1.32, 0.00, 1.10]} * ] * * Like Command and PatchElement, this class is structured for compatibility * with the Boon JsonFactory, which automatically binds JSON bidirectionally * to Java classes which adhere to its preferred (bean-style) layout. * * After you serialize your JSON layout, you can use it to run the barebones * OpenGL server that comes with Open Pixel Control. Invoke it like this: * * $ path/to/bin/gl_server path/to/udder/udder/conf/opc_layout.json * * For the Dairy project, we recommend trying Eric Miller's visualizer: * * https://github.com/patternleaf/archway */ public class OpcLayoutPoint { private double[] point; public OpcLayoutPoint(double[] point) { if(point == null) { throw new NullPointerException("point is null"); } else if(point.length != 3) { throw new IllegalArgumentException("invalid point length " + point.length); } this.point = point; } public double[] getPoint() { return this.point; } public void scale(double factor) { for(int i=0; i<point.length; i++) { point[i] *= factor; } } /** Return a list associating OPC address with spatial coordinates. * The Open Pixel Control's gl_server consumes this list and presents * a very simple 3D view of your show, which you can use as a monitor. * See https://github.com/patternleaf/archway for a fine example of how to * create a much snazzier 3D monitor in your browser. */ public static List<OpcLayoutPoint> createOpcLayoutPoints(PatchSheet patchSheet) { // We occasionally skip scaling when debugging. final boolean autoscale = true; // Shrink the layout, which at the Dairy arrived in inches, to fit the // limited viewport of the OPC gl model. // TODO: automatically compute a decent scale, since the GL viewport // lacks auto zoom -- or implement autozoom for gl_server. final double glViewportScale = 3.0; final double [] origin = {0.0, 0.0, 0.0};
final Device[] devices = patchSheet.getModelSpaceDevices();
coil-lighting/udder
udder/src/main/java/com/coillighting/udder/geometry/wave/SharkfinWave.java
// Path: udder/src/main/java/com/coillighting/udder/geometry/Crossfade.java // public class Crossfade { // // /** Linearly interpolate x, a value between 0 and 1, between two points, // * (0, y0) and (1, y1). If you supply an x that is out of range, the // * result will likewise be out of range. // */ // public static final double linear(double x, double y0, double y1) { // return y0 + x * (y1 - y0); // } // // /** A 32-bit version of Crossfade.linear. */ // public static final float linear(float x, float y0, float y1) { // return y0 + x * (y1 - y0); // } // // /** For a fast attack followed by a slower follow-through, try an exponent // * of 0.5 or 0.25. For a gradual attack with an accelerating follow-up, // * try an exponent of 2-5. This is not really the shapliest easing curve // * curve out there, but it's good to have in the arsenal. // */ // public static final double exponential(double x, double exponent, double y0, double y1) { // double balance = Reshape.exponential(x, exponent); // return linear(balance, y0, y1); // } // // /** A mostly 32-bit version of Crossfade.exponential. */ // public static final float exponential(float x, float exponent, float y0, float y1) { // float balance = Reshape.exponential(x, exponent); // return linear(balance, y0, y1); // } // // /** Use a sinewave to approximate a sigmoidal cross-fade curve. // * Submit this expression to wolframalpha.com to see the resulting curve: // * 0.5*(1 + (sin((pi*(x-0.5))))) // * Direct link: // * http://www.wolframalpha.com/input/?i=0.5*%281+%2B+%28sin%28%28pi*%28x-0.5%29%29%29%29%29+from+-0.25+to+1.5 // */ // public static final double sinusoidal(double x, double y0, double y1) { // double balance = Reshape.sinusoidal(x); // return linear(balance, y0, y1); // } // // /** A mostly 32-bit version of crossfadeExponential. */ // public static final float sinusoidal(float x, float y0, float y1) { // float balance = Reshape.sinusoidal(x); // return linear(balance, y0, y1); // } // // // TODO logarithmic mode! // // }
import com.coillighting.udder.geometry.Crossfade;
package com.coillighting.udder.geometry.wave; /** A sinusoidally interpolated signal that continuously oscillates from start * to end, then discontinuously jumps back to the start value. */ public class SharkfinWave extends WaveBase { public SharkfinWave(double start, double end, long period) { super(start, end, period); } public double interpolate(double x) {
// Path: udder/src/main/java/com/coillighting/udder/geometry/Crossfade.java // public class Crossfade { // // /** Linearly interpolate x, a value between 0 and 1, between two points, // * (0, y0) and (1, y1). If you supply an x that is out of range, the // * result will likewise be out of range. // */ // public static final double linear(double x, double y0, double y1) { // return y0 + x * (y1 - y0); // } // // /** A 32-bit version of Crossfade.linear. */ // public static final float linear(float x, float y0, float y1) { // return y0 + x * (y1 - y0); // } // // /** For a fast attack followed by a slower follow-through, try an exponent // * of 0.5 or 0.25. For a gradual attack with an accelerating follow-up, // * try an exponent of 2-5. This is not really the shapliest easing curve // * curve out there, but it's good to have in the arsenal. // */ // public static final double exponential(double x, double exponent, double y0, double y1) { // double balance = Reshape.exponential(x, exponent); // return linear(balance, y0, y1); // } // // /** A mostly 32-bit version of Crossfade.exponential. */ // public static final float exponential(float x, float exponent, float y0, float y1) { // float balance = Reshape.exponential(x, exponent); // return linear(balance, y0, y1); // } // // /** Use a sinewave to approximate a sigmoidal cross-fade curve. // * Submit this expression to wolframalpha.com to see the resulting curve: // * 0.5*(1 + (sin((pi*(x-0.5))))) // * Direct link: // * http://www.wolframalpha.com/input/?i=0.5*%281+%2B+%28sin%28%28pi*%28x-0.5%29%29%29%29%29+from+-0.25+to+1.5 // */ // public static final double sinusoidal(double x, double y0, double y1) { // double balance = Reshape.sinusoidal(x); // return linear(balance, y0, y1); // } // // /** A mostly 32-bit version of crossfadeExponential. */ // public static final float sinusoidal(float x, float y0, float y1) { // float balance = Reshape.sinusoidal(x); // return linear(balance, y0, y1); // } // // // TODO logarithmic mode! // // } // Path: udder/src/main/java/com/coillighting/udder/geometry/wave/SharkfinWave.java import com.coillighting.udder.geometry.Crossfade; package com.coillighting.udder.geometry.wave; /** A sinusoidally interpolated signal that continuously oscillates from start * to end, then discontinuously jumps back to the start value. */ public class SharkfinWave extends WaveBase { public SharkfinWave(double start, double end, long period) { super(start, end, period); } public double interpolate(double x) {
return Crossfade.sinusoidal(x, start, end);
coil-lighting/udder
udder/src/main/java/com/coillighting/udder/geometry/wave/SinusoidalWave.java
// Path: udder/src/main/java/com/coillighting/udder/geometry/Crossfade.java // public class Crossfade { // // /** Linearly interpolate x, a value between 0 and 1, between two points, // * (0, y0) and (1, y1). If you supply an x that is out of range, the // * result will likewise be out of range. // */ // public static final double linear(double x, double y0, double y1) { // return y0 + x * (y1 - y0); // } // // /** A 32-bit version of Crossfade.linear. */ // public static final float linear(float x, float y0, float y1) { // return y0 + x * (y1 - y0); // } // // /** For a fast attack followed by a slower follow-through, try an exponent // * of 0.5 or 0.25. For a gradual attack with an accelerating follow-up, // * try an exponent of 2-5. This is not really the shapliest easing curve // * curve out there, but it's good to have in the arsenal. // */ // public static final double exponential(double x, double exponent, double y0, double y1) { // double balance = Reshape.exponential(x, exponent); // return linear(balance, y0, y1); // } // // /** A mostly 32-bit version of Crossfade.exponential. */ // public static final float exponential(float x, float exponent, float y0, float y1) { // float balance = Reshape.exponential(x, exponent); // return linear(balance, y0, y1); // } // // /** Use a sinewave to approximate a sigmoidal cross-fade curve. // * Submit this expression to wolframalpha.com to see the resulting curve: // * 0.5*(1 + (sin((pi*(x-0.5))))) // * Direct link: // * http://www.wolframalpha.com/input/?i=0.5*%281+%2B+%28sin%28%28pi*%28x-0.5%29%29%29%29%29+from+-0.25+to+1.5 // */ // public static final double sinusoidal(double x, double y0, double y1) { // double balance = Reshape.sinusoidal(x); // return linear(balance, y0, y1); // } // // /** A mostly 32-bit version of crossfadeExponential. */ // public static final float sinusoidal(float x, float y0, float y1) { // float balance = Reshape.sinusoidal(x); // return linear(balance, y0, y1); // } // // // TODO logarithmic mode! // // }
import com.coillighting.udder.geometry.Crossfade;
package com.coillighting.udder.geometry.wave; /** A sinusoidally interpolated signal that continuously oscillates between two * values, with smooth corners at the values themselves. */ public class SinusoidalWave extends WaveBase { public SinusoidalWave(double start, double end, long period) { super(start, end, period); } public double interpolate(double x) { // This is a funny way to implement this, but I want to give // crossfadeSinusoidal a little exercise before simplifying it. // Alternately, I might add a ramp-up balance/ramp-down balance // param to this class, for use as a simple impulse envelope. (FUTURE) double x0; double x1; if(x <= 0.5) { x0 = start; x1 = end; } else { x -= -0.5; x0 = end; x1 = start; } x *= 2.0;
// Path: udder/src/main/java/com/coillighting/udder/geometry/Crossfade.java // public class Crossfade { // // /** Linearly interpolate x, a value between 0 and 1, between two points, // * (0, y0) and (1, y1). If you supply an x that is out of range, the // * result will likewise be out of range. // */ // public static final double linear(double x, double y0, double y1) { // return y0 + x * (y1 - y0); // } // // /** A 32-bit version of Crossfade.linear. */ // public static final float linear(float x, float y0, float y1) { // return y0 + x * (y1 - y0); // } // // /** For a fast attack followed by a slower follow-through, try an exponent // * of 0.5 or 0.25. For a gradual attack with an accelerating follow-up, // * try an exponent of 2-5. This is not really the shapliest easing curve // * curve out there, but it's good to have in the arsenal. // */ // public static final double exponential(double x, double exponent, double y0, double y1) { // double balance = Reshape.exponential(x, exponent); // return linear(balance, y0, y1); // } // // /** A mostly 32-bit version of Crossfade.exponential. */ // public static final float exponential(float x, float exponent, float y0, float y1) { // float balance = Reshape.exponential(x, exponent); // return linear(balance, y0, y1); // } // // /** Use a sinewave to approximate a sigmoidal cross-fade curve. // * Submit this expression to wolframalpha.com to see the resulting curve: // * 0.5*(1 + (sin((pi*(x-0.5))))) // * Direct link: // * http://www.wolframalpha.com/input/?i=0.5*%281+%2B+%28sin%28%28pi*%28x-0.5%29%29%29%29%29+from+-0.25+to+1.5 // */ // public static final double sinusoidal(double x, double y0, double y1) { // double balance = Reshape.sinusoidal(x); // return linear(balance, y0, y1); // } // // /** A mostly 32-bit version of crossfadeExponential. */ // public static final float sinusoidal(float x, float y0, float y1) { // float balance = Reshape.sinusoidal(x); // return linear(balance, y0, y1); // } // // // TODO logarithmic mode! // // } // Path: udder/src/main/java/com/coillighting/udder/geometry/wave/SinusoidalWave.java import com.coillighting.udder.geometry.Crossfade; package com.coillighting.udder.geometry.wave; /** A sinusoidally interpolated signal that continuously oscillates between two * values, with smooth corners at the values themselves. */ public class SinusoidalWave extends WaveBase { public SinusoidalWave(double start, double end, long period) { super(start, end, period); } public double interpolate(double x) { // This is a funny way to implement this, but I want to give // crossfadeSinusoidal a little exercise before simplifying it. // Alternately, I might add a ramp-up balance/ramp-down balance // param to this class, for use as a simple impulse envelope. (FUTURE) double x0; double x1; if(x <= 0.5) { x0 = start; x1 = end; } else { x -= -0.5; x0 = end; x1 = start; } x *= 2.0;
return Crossfade.sinusoidal(x, x0, x1);
coil-lighting/udder
udder/src/main/java/com/coillighting/udder/geometry/wave/WaveBase.java
// Path: udder/src/main/java/com/coillighting/udder/mix/TimePoint.java // public class TimePoint { // // /** The nomimally "real" time at which this frame was initialized. Although // * this time is required by some animations which need to synchronize their // * effects with the outside world -- a dusk/dawn almanac scheduler, for // * instance -- you should ordinarily never refer to the realTimeMillis in // * your animation functions. Instead, use TimePoint.sceneTimeMillis in // * order to give the user the opportunity to apply timebase distortions. // * Initialized with System.currentTimeMillis(). // * // * Not to be confused with TimePoint.sceneTimeMillis. // */ // private long realTimeMillis = 0; // // /** The reference time for all elements of the current scene. By using this // * offset as the current time for timebase calculations in your animators, // * you allow the user to apply timebase distortions, a powerful creative // * tool. For ideas of what you might do with timebase distortions, sit // * down with an old Invisibl Skratch Piklz, then imagine stretching and // * reversing your graphical animations as if they were audio, at high rez. // * This time is compatible with, but not necessarily identical to, the // * "real" millisecond time offset returned by System.currentTimeMillis(). // * When a show is playing back in nominally real time, with no timebase // * transformations or distortions, then this value will by convention // * equal TimePoint.realTimeMillis minus the realTimeMillis when the show // * started, and then this value will count up monotonically thereafter. // * However, there is no guarantee that the user will choose to follow such // * a straightforward path through time. // * // * Not to be confused with TimePoint.realTimeMillis. // */ // private long sceneTimeMillis = 0; // // /** An integer counting the current frame. Normally a show begins at frame // * 0 and proceeds to count up, +1 per frame, but there is no guarantee that // * a user will configure a show to count incrementally. There is even no // * guarantee that frameIndex will monotonically increase. However, a normal // * show which doesn't replay its own history will by convention simply // * start from 0 and monotonically increment +1 per animation loop. // */ // private long frameIndex = 0; // // public TimePoint(long realTimeMillis, long sceneTimeMillis, long frameIndex) { // this.realTimeMillis = realTimeMillis; // this.sceneTimeMillis = sceneTimeMillis; // this.frameIndex = frameIndex; // } // // /** Copy constructor. */ // public TimePoint(TimePoint timePoint) { // this.realTimeMillis = timePoint.realTimeMillis; // this.sceneTimeMillis = timePoint.sceneTimeMillis; // this.frameIndex = timePoint.frameIndex; // } // // /** Initialize a TimePoint with the current system time as its nominally // * "real" time offset. Start counting the scene time from 0 and frameIndex // * at 0. // */ // public TimePoint() { // this.realTimeMillis = System.currentTimeMillis(); // this.sceneTimeMillis = 0; // this.frameIndex = 0; // } // // /** Return a new immutable TimePoint, incrementing frameIndex and updating // * realTimeMillis and sceneTimeMillis on the assumption that the show is // * taking a straightforward and undistorted path through time. // */ // public TimePoint next() { // long realTime = System.currentTimeMillis(); // long sceneTimeOffsetMillis = this.realTimeMillis - this.sceneTimeMillis; // return new TimePoint( // realTime, // realTime - sceneTimeOffsetMillis, // 1 + this.frameIndex); // } // // public long realTimeMillis() { // return this.realTimeMillis; // } // // public long sceneTimeMillis() { // return this.sceneTimeMillis; // } // // public long getFrameIndex() { // return this.frameIndex; // } // // public String toString() { // return "" + this.sceneTimeMillis + "ms [#" + this.frameIndex + ']'; // } // // }
import com.coillighting.udder.mix.TimePoint;
package com.coillighting.udder.geometry.wave; /** Abstract base class for removing boilerplate from the implementation of * periodic, high-resolution floating-point signal generators. */ public abstract class WaveBase implements Wave<Double> { protected double start = 0.0; protected double end = 0.0; protected long period = 0; public WaveBase(Double start, double end, long period) { this.start = start; this.end = end; this.period = period; }
// Path: udder/src/main/java/com/coillighting/udder/mix/TimePoint.java // public class TimePoint { // // /** The nomimally "real" time at which this frame was initialized. Although // * this time is required by some animations which need to synchronize their // * effects with the outside world -- a dusk/dawn almanac scheduler, for // * instance -- you should ordinarily never refer to the realTimeMillis in // * your animation functions. Instead, use TimePoint.sceneTimeMillis in // * order to give the user the opportunity to apply timebase distortions. // * Initialized with System.currentTimeMillis(). // * // * Not to be confused with TimePoint.sceneTimeMillis. // */ // private long realTimeMillis = 0; // // /** The reference time for all elements of the current scene. By using this // * offset as the current time for timebase calculations in your animators, // * you allow the user to apply timebase distortions, a powerful creative // * tool. For ideas of what you might do with timebase distortions, sit // * down with an old Invisibl Skratch Piklz, then imagine stretching and // * reversing your graphical animations as if they were audio, at high rez. // * This time is compatible with, but not necessarily identical to, the // * "real" millisecond time offset returned by System.currentTimeMillis(). // * When a show is playing back in nominally real time, with no timebase // * transformations or distortions, then this value will by convention // * equal TimePoint.realTimeMillis minus the realTimeMillis when the show // * started, and then this value will count up monotonically thereafter. // * However, there is no guarantee that the user will choose to follow such // * a straightforward path through time. // * // * Not to be confused with TimePoint.realTimeMillis. // */ // private long sceneTimeMillis = 0; // // /** An integer counting the current frame. Normally a show begins at frame // * 0 and proceeds to count up, +1 per frame, but there is no guarantee that // * a user will configure a show to count incrementally. There is even no // * guarantee that frameIndex will monotonically increase. However, a normal // * show which doesn't replay its own history will by convention simply // * start from 0 and monotonically increment +1 per animation loop. // */ // private long frameIndex = 0; // // public TimePoint(long realTimeMillis, long sceneTimeMillis, long frameIndex) { // this.realTimeMillis = realTimeMillis; // this.sceneTimeMillis = sceneTimeMillis; // this.frameIndex = frameIndex; // } // // /** Copy constructor. */ // public TimePoint(TimePoint timePoint) { // this.realTimeMillis = timePoint.realTimeMillis; // this.sceneTimeMillis = timePoint.sceneTimeMillis; // this.frameIndex = timePoint.frameIndex; // } // // /** Initialize a TimePoint with the current system time as its nominally // * "real" time offset. Start counting the scene time from 0 and frameIndex // * at 0. // */ // public TimePoint() { // this.realTimeMillis = System.currentTimeMillis(); // this.sceneTimeMillis = 0; // this.frameIndex = 0; // } // // /** Return a new immutable TimePoint, incrementing frameIndex and updating // * realTimeMillis and sceneTimeMillis on the assumption that the show is // * taking a straightforward and undistorted path through time. // */ // public TimePoint next() { // long realTime = System.currentTimeMillis(); // long sceneTimeOffsetMillis = this.realTimeMillis - this.sceneTimeMillis; // return new TimePoint( // realTime, // realTime - sceneTimeOffsetMillis, // 1 + this.frameIndex); // } // // public long realTimeMillis() { // return this.realTimeMillis; // } // // public long sceneTimeMillis() { // return this.sceneTimeMillis; // } // // public long getFrameIndex() { // return this.frameIndex; // } // // public String toString() { // return "" + this.sceneTimeMillis + "ms [#" + this.frameIndex + ']'; // } // // } // Path: udder/src/main/java/com/coillighting/udder/geometry/wave/WaveBase.java import com.coillighting.udder.mix.TimePoint; package com.coillighting.udder.geometry.wave; /** Abstract base class for removing boilerplate from the implementation of * periodic, high-resolution floating-point signal generators. */ public abstract class WaveBase implements Wave<Double> { protected double start = 0.0; protected double end = 0.0; protected long period = 0; public WaveBase(Double start, double end, long period) { this.start = start; this.end = end; this.period = period; }
public Double getValue(TimePoint time) {
coil-lighting/udder
udder/src/main/java/com/coillighting/udder/geometry/wave/SawtoothFloatWave.java
// Path: udder/src/main/java/com/coillighting/udder/geometry/Crossfade.java // public class Crossfade { // // /** Linearly interpolate x, a value between 0 and 1, between two points, // * (0, y0) and (1, y1). If you supply an x that is out of range, the // * result will likewise be out of range. // */ // public static final double linear(double x, double y0, double y1) { // return y0 + x * (y1 - y0); // } // // /** A 32-bit version of Crossfade.linear. */ // public static final float linear(float x, float y0, float y1) { // return y0 + x * (y1 - y0); // } // // /** For a fast attack followed by a slower follow-through, try an exponent // * of 0.5 or 0.25. For a gradual attack with an accelerating follow-up, // * try an exponent of 2-5. This is not really the shapliest easing curve // * curve out there, but it's good to have in the arsenal. // */ // public static final double exponential(double x, double exponent, double y0, double y1) { // double balance = Reshape.exponential(x, exponent); // return linear(balance, y0, y1); // } // // /** A mostly 32-bit version of Crossfade.exponential. */ // public static final float exponential(float x, float exponent, float y0, float y1) { // float balance = Reshape.exponential(x, exponent); // return linear(balance, y0, y1); // } // // /** Use a sinewave to approximate a sigmoidal cross-fade curve. // * Submit this expression to wolframalpha.com to see the resulting curve: // * 0.5*(1 + (sin((pi*(x-0.5))))) // * Direct link: // * http://www.wolframalpha.com/input/?i=0.5*%281+%2B+%28sin%28%28pi*%28x-0.5%29%29%29%29%29+from+-0.25+to+1.5 // */ // public static final double sinusoidal(double x, double y0, double y1) { // double balance = Reshape.sinusoidal(x); // return linear(balance, y0, y1); // } // // /** A mostly 32-bit version of crossfadeExponential. */ // public static final float sinusoidal(float x, float y0, float y1) { // float balance = Reshape.sinusoidal(x); // return linear(balance, y0, y1); // } // // // TODO logarithmic mode! // // }
import com.coillighting.udder.geometry.Crossfade;
package com.coillighting.udder.geometry.wave; /** A linearly interpolated signal that continuously oscillates from start to * end, looping back discontinuously to the start value when the period has * elapsed. */ public class SawtoothFloatWave extends FloatWaveBase { public SawtoothFloatWave(float start, float end, long period) { super(start, end, period); } public float interpolate(float x) {
// Path: udder/src/main/java/com/coillighting/udder/geometry/Crossfade.java // public class Crossfade { // // /** Linearly interpolate x, a value between 0 and 1, between two points, // * (0, y0) and (1, y1). If you supply an x that is out of range, the // * result will likewise be out of range. // */ // public static final double linear(double x, double y0, double y1) { // return y0 + x * (y1 - y0); // } // // /** A 32-bit version of Crossfade.linear. */ // public static final float linear(float x, float y0, float y1) { // return y0 + x * (y1 - y0); // } // // /** For a fast attack followed by a slower follow-through, try an exponent // * of 0.5 or 0.25. For a gradual attack with an accelerating follow-up, // * try an exponent of 2-5. This is not really the shapliest easing curve // * curve out there, but it's good to have in the arsenal. // */ // public static final double exponential(double x, double exponent, double y0, double y1) { // double balance = Reshape.exponential(x, exponent); // return linear(balance, y0, y1); // } // // /** A mostly 32-bit version of Crossfade.exponential. */ // public static final float exponential(float x, float exponent, float y0, float y1) { // float balance = Reshape.exponential(x, exponent); // return linear(balance, y0, y1); // } // // /** Use a sinewave to approximate a sigmoidal cross-fade curve. // * Submit this expression to wolframalpha.com to see the resulting curve: // * 0.5*(1 + (sin((pi*(x-0.5))))) // * Direct link: // * http://www.wolframalpha.com/input/?i=0.5*%281+%2B+%28sin%28%28pi*%28x-0.5%29%29%29%29%29+from+-0.25+to+1.5 // */ // public static final double sinusoidal(double x, double y0, double y1) { // double balance = Reshape.sinusoidal(x); // return linear(balance, y0, y1); // } // // /** A mostly 32-bit version of crossfadeExponential. */ // public static final float sinusoidal(float x, float y0, float y1) { // float balance = Reshape.sinusoidal(x); // return linear(balance, y0, y1); // } // // // TODO logarithmic mode! // // } // Path: udder/src/main/java/com/coillighting/udder/geometry/wave/SawtoothFloatWave.java import com.coillighting.udder.geometry.Crossfade; package com.coillighting.udder.geometry.wave; /** A linearly interpolated signal that continuously oscillates from start to * end, looping back discontinuously to the start value when the period has * elapsed. */ public class SawtoothFloatWave extends FloatWaveBase { public SawtoothFloatWave(float start, float end, long period) { super(start, end, period); } public float interpolate(float x) {
return Crossfade.linear(x, start, end);
arteam/jdit
src/test/java/com/github/arteam/jdit/TestAlternateDBIFactory.java
// Path: src/test/java/com/github/arteam/jdit/domain/PlayerSqlObject.java // @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) // public interface PlayerSqlObject { // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName, // @Bind("birth_date") Date birthDate, @Bind("height") int height, // @Bind("weight") int weight); // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@PlayerBinder Player player); // // @SqlQuery("select last_name from players order by last_name") // List<String> getLastNames(); // // @SqlQuery("select count(*) from players where extract(year from birth_date) = :year") // int getAmountPlayersBornInYear(@Bind("year") int year); // // @SqlQuery("select * from players where birth_date > :date") // List<Player> getPlayersBornAfter(@Bind("date") DateTime date); // // @SqlQuery("select birth_date from players where first_name=:first_name and last_name=:last_name") // DateTime getPlayerBirthDate(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select distinct extract(year from birth_date) player_year from players order by player_year") // Set<Integer> getBornYears(); // // @SqlQuery("select * from players where first_name=:first_name and last_name=:last_name") // Optional<Player> findPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select * from players where weight <> :weight") // List<Player> getPlayersByWeight(@Bind("weight") Optional<Integer> weight); // // @SqlQuery("select first_name from players") // ImmutableSet<String> getFirstNames(); // // @Retention(RetentionPolicy.RUNTIME) // @Target({ElementType.PARAMETER}) // @SqlStatementCustomizingAnnotation(PlayerBinder.Factory.class) // @interface PlayerBinder { // // class Factory implements SqlStatementCustomizerFactory { // // @Override // public SqlStatementParameterCustomizer createForParameter(Annotation annotation, Class<?> sqlObjectType, // Method method, Parameter param, int index, // Type type) { // return (stmt, arg) -> { // Player p = (Player) arg; // stmt.bind("first_name", p.firstName); // stmt.bind("last_name", p.lastName); // stmt.bind("birth_date", p.birthDate); // stmt.bind("weight", p.weight); // stmt.bind("height", p.height); // }; // } // } // } // // class PlayerMapper implements RowMapper<Player> { // @Override // public Player map(ResultSet r, StatementContext ctx) throws SQLException { // int height = r.getInt("height"); // int weight = r.getInt("weight"); // return new Player(Optional.of(r.getLong("id")), r.getString("first_name"), r.getString("last_name"), // r.getTimestamp("birth_date"), // height != 0 ? Optional.of(height) : Optional.empty(), // weight != 0 ? Optional.of(weight) : Optional.empty()); // } // } // }
import com.github.arteam.jdit.annotations.DBIHandle; import com.github.arteam.jdit.annotations.JditProperties; import com.github.arteam.jdit.annotations.TestedSqlObject; import com.github.arteam.jdit.domain.PlayerSqlObject; import org.jdbi.v3.core.Handle; import org.junit.Test; import org.junit.runner.RunWith; import java.text.SimpleDateFormat; import static org.assertj.core.api.Assertions.assertThat;
package com.github.arteam.jdit; @JditProperties("jdit-alternate-factory.properties") @RunWith(DBIRunner.class) public class TestAlternateDBIFactory { @DBIHandle Handle handle; @TestedSqlObject
// Path: src/test/java/com/github/arteam/jdit/domain/PlayerSqlObject.java // @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) // public interface PlayerSqlObject { // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName, // @Bind("birth_date") Date birthDate, @Bind("height") int height, // @Bind("weight") int weight); // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@PlayerBinder Player player); // // @SqlQuery("select last_name from players order by last_name") // List<String> getLastNames(); // // @SqlQuery("select count(*) from players where extract(year from birth_date) = :year") // int getAmountPlayersBornInYear(@Bind("year") int year); // // @SqlQuery("select * from players where birth_date > :date") // List<Player> getPlayersBornAfter(@Bind("date") DateTime date); // // @SqlQuery("select birth_date from players where first_name=:first_name and last_name=:last_name") // DateTime getPlayerBirthDate(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select distinct extract(year from birth_date) player_year from players order by player_year") // Set<Integer> getBornYears(); // // @SqlQuery("select * from players where first_name=:first_name and last_name=:last_name") // Optional<Player> findPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select * from players where weight <> :weight") // List<Player> getPlayersByWeight(@Bind("weight") Optional<Integer> weight); // // @SqlQuery("select first_name from players") // ImmutableSet<String> getFirstNames(); // // @Retention(RetentionPolicy.RUNTIME) // @Target({ElementType.PARAMETER}) // @SqlStatementCustomizingAnnotation(PlayerBinder.Factory.class) // @interface PlayerBinder { // // class Factory implements SqlStatementCustomizerFactory { // // @Override // public SqlStatementParameterCustomizer createForParameter(Annotation annotation, Class<?> sqlObjectType, // Method method, Parameter param, int index, // Type type) { // return (stmt, arg) -> { // Player p = (Player) arg; // stmt.bind("first_name", p.firstName); // stmt.bind("last_name", p.lastName); // stmt.bind("birth_date", p.birthDate); // stmt.bind("weight", p.weight); // stmt.bind("height", p.height); // }; // } // } // } // // class PlayerMapper implements RowMapper<Player> { // @Override // public Player map(ResultSet r, StatementContext ctx) throws SQLException { // int height = r.getInt("height"); // int weight = r.getInt("weight"); // return new Player(Optional.of(r.getLong("id")), r.getString("first_name"), r.getString("last_name"), // r.getTimestamp("birth_date"), // height != 0 ? Optional.of(height) : Optional.empty(), // weight != 0 ? Optional.of(weight) : Optional.empty()); // } // } // } // Path: src/test/java/com/github/arteam/jdit/TestAlternateDBIFactory.java import com.github.arteam.jdit.annotations.DBIHandle; import com.github.arteam.jdit.annotations.JditProperties; import com.github.arteam.jdit.annotations.TestedSqlObject; import com.github.arteam.jdit.domain.PlayerSqlObject; import org.jdbi.v3.core.Handle; import org.junit.Test; import org.junit.runner.RunWith; import java.text.SimpleDateFormat; import static org.assertj.core.api.Assertions.assertThat; package com.github.arteam.jdit; @JditProperties("jdit-alternate-factory.properties") @RunWith(DBIRunner.class) public class TestAlternateDBIFactory { @DBIHandle Handle handle; @TestedSqlObject
PlayerSqlObject playerDao;
arteam/jdit
src/test/java/com/github/arteam/jdit/domain/TeamSqlObject.java
// Path: src/test/java/com/github/arteam/jdit/domain/entity/Division.java // public enum Division { // PACIFIC, // CENTRAL, // METROPOLITAN, // ATLANTIC // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Player.java // public class Player { // // public final Optional<Long> id; // public final String firstName; // public final String lastName; // public final Date birthDate; // public final Optional<Integer> height; // public final Optional<Integer> weight; // // public Player(Optional<Long> id, String firstName, String lastName, Date birthDate, // Optional<Integer> height, Optional<Integer> weight) { // this.id = id; // this.firstName = firstName; // this.lastName = lastName; // this.birthDate = birthDate; // this.height = height; // this.weight = weight; // } // // public Player(String firstName, String lastName, Date birthDate, int height, int weight) { // this(Optional.<Long>empty(), firstName, lastName, birthDate, Optional.of(height), Optional.of(weight)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .omitNullValues() // .add("id", id.orElse(null)) // .add("firstName", firstName) // .add("lastName", lastName) // .add("birthDate", birthDate) // .add("height", height.orElse(null)) // .add("weight", weight.orElse(null)) // .toString(); // } // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Team.java // public class Team { // // public final Optional<Long> id; // public final String name; // public final Division division; // // public Team(Optional<Long> id, String name, Division division) { // this.id = id; // this.name = name; // this.division = division; // } // // public Team(String name, Division division) { // this.name = name; // this.division = division; // this.id = Optional.empty(); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("id", id) // .add("name", name) // .add("division", division) // .toString(); // } // }
import com.github.arteam.jdit.domain.entity.Division; import com.github.arteam.jdit.domain.entity.Player; import com.github.arteam.jdit.domain.entity.Team; import org.jdbi.v3.sqlobject.CreateSqlObject; import org.jdbi.v3.sqlobject.config.RegisterRowMapper; import org.jdbi.v3.sqlobject.customizer.Bind; import org.jdbi.v3.sqlobject.statement.GetGeneratedKeys; import org.jdbi.v3.sqlobject.statement.SqlQuery; import org.jdbi.v3.sqlobject.statement.SqlUpdate; import org.jdbi.v3.sqlobject.transaction.Transaction; import java.util.List;
package com.github.arteam.jdit.domain; /** * Date: 2/7/15 * Time: 4:57 PM * * @author Artem Prigoda */ @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) public interface TeamSqlObject { @CreateSqlObject PlayerSqlObject playerDao(); @SqlUpdate("insert into teams(name, division) values (:name, :division)") @GetGeneratedKeys
// Path: src/test/java/com/github/arteam/jdit/domain/entity/Division.java // public enum Division { // PACIFIC, // CENTRAL, // METROPOLITAN, // ATLANTIC // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Player.java // public class Player { // // public final Optional<Long> id; // public final String firstName; // public final String lastName; // public final Date birthDate; // public final Optional<Integer> height; // public final Optional<Integer> weight; // // public Player(Optional<Long> id, String firstName, String lastName, Date birthDate, // Optional<Integer> height, Optional<Integer> weight) { // this.id = id; // this.firstName = firstName; // this.lastName = lastName; // this.birthDate = birthDate; // this.height = height; // this.weight = weight; // } // // public Player(String firstName, String lastName, Date birthDate, int height, int weight) { // this(Optional.<Long>empty(), firstName, lastName, birthDate, Optional.of(height), Optional.of(weight)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .omitNullValues() // .add("id", id.orElse(null)) // .add("firstName", firstName) // .add("lastName", lastName) // .add("birthDate", birthDate) // .add("height", height.orElse(null)) // .add("weight", weight.orElse(null)) // .toString(); // } // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Team.java // public class Team { // // public final Optional<Long> id; // public final String name; // public final Division division; // // public Team(Optional<Long> id, String name, Division division) { // this.id = id; // this.name = name; // this.division = division; // } // // public Team(String name, Division division) { // this.name = name; // this.division = division; // this.id = Optional.empty(); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("id", id) // .add("name", name) // .add("division", division) // .toString(); // } // } // Path: src/test/java/com/github/arteam/jdit/domain/TeamSqlObject.java import com.github.arteam.jdit.domain.entity.Division; import com.github.arteam.jdit.domain.entity.Player; import com.github.arteam.jdit.domain.entity.Team; import org.jdbi.v3.sqlobject.CreateSqlObject; import org.jdbi.v3.sqlobject.config.RegisterRowMapper; import org.jdbi.v3.sqlobject.customizer.Bind; import org.jdbi.v3.sqlobject.statement.GetGeneratedKeys; import org.jdbi.v3.sqlobject.statement.SqlQuery; import org.jdbi.v3.sqlobject.statement.SqlUpdate; import org.jdbi.v3.sqlobject.transaction.Transaction; import java.util.List; package com.github.arteam.jdit.domain; /** * Date: 2/7/15 * Time: 4:57 PM * * @author Artem Prigoda */ @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) public interface TeamSqlObject { @CreateSqlObject PlayerSqlObject playerDao(); @SqlUpdate("insert into teams(name, division) values (:name, :division)") @GetGeneratedKeys
long createTeam(@Bind("name") String name, @Bind("division") Division division);
arteam/jdit
src/test/java/com/github/arteam/jdit/domain/TeamSqlObject.java
// Path: src/test/java/com/github/arteam/jdit/domain/entity/Division.java // public enum Division { // PACIFIC, // CENTRAL, // METROPOLITAN, // ATLANTIC // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Player.java // public class Player { // // public final Optional<Long> id; // public final String firstName; // public final String lastName; // public final Date birthDate; // public final Optional<Integer> height; // public final Optional<Integer> weight; // // public Player(Optional<Long> id, String firstName, String lastName, Date birthDate, // Optional<Integer> height, Optional<Integer> weight) { // this.id = id; // this.firstName = firstName; // this.lastName = lastName; // this.birthDate = birthDate; // this.height = height; // this.weight = weight; // } // // public Player(String firstName, String lastName, Date birthDate, int height, int weight) { // this(Optional.<Long>empty(), firstName, lastName, birthDate, Optional.of(height), Optional.of(weight)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .omitNullValues() // .add("id", id.orElse(null)) // .add("firstName", firstName) // .add("lastName", lastName) // .add("birthDate", birthDate) // .add("height", height.orElse(null)) // .add("weight", weight.orElse(null)) // .toString(); // } // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Team.java // public class Team { // // public final Optional<Long> id; // public final String name; // public final Division division; // // public Team(Optional<Long> id, String name, Division division) { // this.id = id; // this.name = name; // this.division = division; // } // // public Team(String name, Division division) { // this.name = name; // this.division = division; // this.id = Optional.empty(); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("id", id) // .add("name", name) // .add("division", division) // .toString(); // } // }
import com.github.arteam.jdit.domain.entity.Division; import com.github.arteam.jdit.domain.entity.Player; import com.github.arteam.jdit.domain.entity.Team; import org.jdbi.v3.sqlobject.CreateSqlObject; import org.jdbi.v3.sqlobject.config.RegisterRowMapper; import org.jdbi.v3.sqlobject.customizer.Bind; import org.jdbi.v3.sqlobject.statement.GetGeneratedKeys; import org.jdbi.v3.sqlobject.statement.SqlQuery; import org.jdbi.v3.sqlobject.statement.SqlUpdate; import org.jdbi.v3.sqlobject.transaction.Transaction; import java.util.List;
package com.github.arteam.jdit.domain; /** * Date: 2/7/15 * Time: 4:57 PM * * @author Artem Prigoda */ @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) public interface TeamSqlObject { @CreateSqlObject PlayerSqlObject playerDao(); @SqlUpdate("insert into teams(name, division) values (:name, :division)") @GetGeneratedKeys long createTeam(@Bind("name") String name, @Bind("division") Division division); @SqlUpdate("insert into roster(team_id, player_id) values (:team_id, :player_id)") void addPlayerToTeam(@Bind("team_id") long teamId, @Bind("player_id") long playerId); @Transaction
// Path: src/test/java/com/github/arteam/jdit/domain/entity/Division.java // public enum Division { // PACIFIC, // CENTRAL, // METROPOLITAN, // ATLANTIC // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Player.java // public class Player { // // public final Optional<Long> id; // public final String firstName; // public final String lastName; // public final Date birthDate; // public final Optional<Integer> height; // public final Optional<Integer> weight; // // public Player(Optional<Long> id, String firstName, String lastName, Date birthDate, // Optional<Integer> height, Optional<Integer> weight) { // this.id = id; // this.firstName = firstName; // this.lastName = lastName; // this.birthDate = birthDate; // this.height = height; // this.weight = weight; // } // // public Player(String firstName, String lastName, Date birthDate, int height, int weight) { // this(Optional.<Long>empty(), firstName, lastName, birthDate, Optional.of(height), Optional.of(weight)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .omitNullValues() // .add("id", id.orElse(null)) // .add("firstName", firstName) // .add("lastName", lastName) // .add("birthDate", birthDate) // .add("height", height.orElse(null)) // .add("weight", weight.orElse(null)) // .toString(); // } // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Team.java // public class Team { // // public final Optional<Long> id; // public final String name; // public final Division division; // // public Team(Optional<Long> id, String name, Division division) { // this.id = id; // this.name = name; // this.division = division; // } // // public Team(String name, Division division) { // this.name = name; // this.division = division; // this.id = Optional.empty(); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("id", id) // .add("name", name) // .add("division", division) // .toString(); // } // } // Path: src/test/java/com/github/arteam/jdit/domain/TeamSqlObject.java import com.github.arteam.jdit.domain.entity.Division; import com.github.arteam.jdit.domain.entity.Player; import com.github.arteam.jdit.domain.entity.Team; import org.jdbi.v3.sqlobject.CreateSqlObject; import org.jdbi.v3.sqlobject.config.RegisterRowMapper; import org.jdbi.v3.sqlobject.customizer.Bind; import org.jdbi.v3.sqlobject.statement.GetGeneratedKeys; import org.jdbi.v3.sqlobject.statement.SqlQuery; import org.jdbi.v3.sqlobject.statement.SqlUpdate; import org.jdbi.v3.sqlobject.transaction.Transaction; import java.util.List; package com.github.arteam.jdit.domain; /** * Date: 2/7/15 * Time: 4:57 PM * * @author Artem Prigoda */ @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) public interface TeamSqlObject { @CreateSqlObject PlayerSqlObject playerDao(); @SqlUpdate("insert into teams(name, division) values (:name, :division)") @GetGeneratedKeys long createTeam(@Bind("name") String name, @Bind("division") Division division); @SqlUpdate("insert into roster(team_id, player_id) values (:team_id, :player_id)") void addPlayerToTeam(@Bind("team_id") long teamId, @Bind("player_id") long playerId); @Transaction
default void addTeam(Team team, List<Player> players) {
arteam/jdit
src/test/java/com/github/arteam/jdit/domain/TeamSqlObject.java
// Path: src/test/java/com/github/arteam/jdit/domain/entity/Division.java // public enum Division { // PACIFIC, // CENTRAL, // METROPOLITAN, // ATLANTIC // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Player.java // public class Player { // // public final Optional<Long> id; // public final String firstName; // public final String lastName; // public final Date birthDate; // public final Optional<Integer> height; // public final Optional<Integer> weight; // // public Player(Optional<Long> id, String firstName, String lastName, Date birthDate, // Optional<Integer> height, Optional<Integer> weight) { // this.id = id; // this.firstName = firstName; // this.lastName = lastName; // this.birthDate = birthDate; // this.height = height; // this.weight = weight; // } // // public Player(String firstName, String lastName, Date birthDate, int height, int weight) { // this(Optional.<Long>empty(), firstName, lastName, birthDate, Optional.of(height), Optional.of(weight)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .omitNullValues() // .add("id", id.orElse(null)) // .add("firstName", firstName) // .add("lastName", lastName) // .add("birthDate", birthDate) // .add("height", height.orElse(null)) // .add("weight", weight.orElse(null)) // .toString(); // } // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Team.java // public class Team { // // public final Optional<Long> id; // public final String name; // public final Division division; // // public Team(Optional<Long> id, String name, Division division) { // this.id = id; // this.name = name; // this.division = division; // } // // public Team(String name, Division division) { // this.name = name; // this.division = division; // this.id = Optional.empty(); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("id", id) // .add("name", name) // .add("division", division) // .toString(); // } // }
import com.github.arteam.jdit.domain.entity.Division; import com.github.arteam.jdit.domain.entity.Player; import com.github.arteam.jdit.domain.entity.Team; import org.jdbi.v3.sqlobject.CreateSqlObject; import org.jdbi.v3.sqlobject.config.RegisterRowMapper; import org.jdbi.v3.sqlobject.customizer.Bind; import org.jdbi.v3.sqlobject.statement.GetGeneratedKeys; import org.jdbi.v3.sqlobject.statement.SqlQuery; import org.jdbi.v3.sqlobject.statement.SqlUpdate; import org.jdbi.v3.sqlobject.transaction.Transaction; import java.util.List;
package com.github.arteam.jdit.domain; /** * Date: 2/7/15 * Time: 4:57 PM * * @author Artem Prigoda */ @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) public interface TeamSqlObject { @CreateSqlObject PlayerSqlObject playerDao(); @SqlUpdate("insert into teams(name, division) values (:name, :division)") @GetGeneratedKeys long createTeam(@Bind("name") String name, @Bind("division") Division division); @SqlUpdate("insert into roster(team_id, player_id) values (:team_id, :player_id)") void addPlayerToTeam(@Bind("team_id") long teamId, @Bind("player_id") long playerId); @Transaction
// Path: src/test/java/com/github/arteam/jdit/domain/entity/Division.java // public enum Division { // PACIFIC, // CENTRAL, // METROPOLITAN, // ATLANTIC // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Player.java // public class Player { // // public final Optional<Long> id; // public final String firstName; // public final String lastName; // public final Date birthDate; // public final Optional<Integer> height; // public final Optional<Integer> weight; // // public Player(Optional<Long> id, String firstName, String lastName, Date birthDate, // Optional<Integer> height, Optional<Integer> weight) { // this.id = id; // this.firstName = firstName; // this.lastName = lastName; // this.birthDate = birthDate; // this.height = height; // this.weight = weight; // } // // public Player(String firstName, String lastName, Date birthDate, int height, int weight) { // this(Optional.<Long>empty(), firstName, lastName, birthDate, Optional.of(height), Optional.of(weight)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .omitNullValues() // .add("id", id.orElse(null)) // .add("firstName", firstName) // .add("lastName", lastName) // .add("birthDate", birthDate) // .add("height", height.orElse(null)) // .add("weight", weight.orElse(null)) // .toString(); // } // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Team.java // public class Team { // // public final Optional<Long> id; // public final String name; // public final Division division; // // public Team(Optional<Long> id, String name, Division division) { // this.id = id; // this.name = name; // this.division = division; // } // // public Team(String name, Division division) { // this.name = name; // this.division = division; // this.id = Optional.empty(); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("id", id) // .add("name", name) // .add("division", division) // .toString(); // } // } // Path: src/test/java/com/github/arteam/jdit/domain/TeamSqlObject.java import com.github.arteam.jdit.domain.entity.Division; import com.github.arteam.jdit.domain.entity.Player; import com.github.arteam.jdit.domain.entity.Team; import org.jdbi.v3.sqlobject.CreateSqlObject; import org.jdbi.v3.sqlobject.config.RegisterRowMapper; import org.jdbi.v3.sqlobject.customizer.Bind; import org.jdbi.v3.sqlobject.statement.GetGeneratedKeys; import org.jdbi.v3.sqlobject.statement.SqlQuery; import org.jdbi.v3.sqlobject.statement.SqlUpdate; import org.jdbi.v3.sqlobject.transaction.Transaction; import java.util.List; package com.github.arteam.jdit.domain; /** * Date: 2/7/15 * Time: 4:57 PM * * @author Artem Prigoda */ @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) public interface TeamSqlObject { @CreateSqlObject PlayerSqlObject playerDao(); @SqlUpdate("insert into teams(name, division) values (:name, :division)") @GetGeneratedKeys long createTeam(@Bind("name") String name, @Bind("division") Division division); @SqlUpdate("insert into roster(team_id, player_id) values (:team_id, :player_id)") void addPlayerToTeam(@Bind("team_id") long teamId, @Bind("player_id") long playerId); @Transaction
default void addTeam(Team team, List<Player> players) {
arteam/jdit
src/test/java/com/github/arteam/jdit/domain/PlayerSqlObject.java
// Path: src/test/java/com/github/arteam/jdit/domain/entity/Player.java // public class Player { // // public final Optional<Long> id; // public final String firstName; // public final String lastName; // public final Date birthDate; // public final Optional<Integer> height; // public final Optional<Integer> weight; // // public Player(Optional<Long> id, String firstName, String lastName, Date birthDate, // Optional<Integer> height, Optional<Integer> weight) { // this.id = id; // this.firstName = firstName; // this.lastName = lastName; // this.birthDate = birthDate; // this.height = height; // this.weight = weight; // } // // public Player(String firstName, String lastName, Date birthDate, int height, int weight) { // this(Optional.<Long>empty(), firstName, lastName, birthDate, Optional.of(height), Optional.of(weight)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .omitNullValues() // .add("id", id.orElse(null)) // .add("firstName", firstName) // .add("lastName", lastName) // .add("birthDate", birthDate) // .add("height", height.orElse(null)) // .add("weight", weight.orElse(null)) // .toString(); // } // }
import com.github.arteam.jdit.domain.entity.Player; import com.google.common.collect.ImmutableSet; import org.jdbi.v3.core.mapper.RowMapper; import org.jdbi.v3.core.statement.StatementContext; import org.jdbi.v3.sqlobject.config.RegisterRowMapper; import org.jdbi.v3.sqlobject.customizer.*; import org.jdbi.v3.sqlobject.statement.GetGeneratedKeys; import org.jdbi.v3.sqlobject.statement.SqlQuery; import org.jdbi.v3.sqlobject.statement.SqlUpdate; import org.joda.time.DateTime; import java.lang.annotation.*; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.lang.reflect.Type; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Date; import java.util.List; import java.util.Optional; import java.util.Set;
package com.github.arteam.jdit.domain; /** * Date: 1/25/15 * Time: 11:26 PM * * @author Artem Prigoda */ @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) public interface PlayerSqlObject { @GetGeneratedKeys @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + "(:first_name, :last_name, :birth_date, :weight, :height)") Long createPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName, @Bind("birth_date") Date birthDate, @Bind("height") int height, @Bind("weight") int weight); @GetGeneratedKeys @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + "(:first_name, :last_name, :birth_date, :weight, :height)")
// Path: src/test/java/com/github/arteam/jdit/domain/entity/Player.java // public class Player { // // public final Optional<Long> id; // public final String firstName; // public final String lastName; // public final Date birthDate; // public final Optional<Integer> height; // public final Optional<Integer> weight; // // public Player(Optional<Long> id, String firstName, String lastName, Date birthDate, // Optional<Integer> height, Optional<Integer> weight) { // this.id = id; // this.firstName = firstName; // this.lastName = lastName; // this.birthDate = birthDate; // this.height = height; // this.weight = weight; // } // // public Player(String firstName, String lastName, Date birthDate, int height, int weight) { // this(Optional.<Long>empty(), firstName, lastName, birthDate, Optional.of(height), Optional.of(weight)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .omitNullValues() // .add("id", id.orElse(null)) // .add("firstName", firstName) // .add("lastName", lastName) // .add("birthDate", birthDate) // .add("height", height.orElse(null)) // .add("weight", weight.orElse(null)) // .toString(); // } // } // Path: src/test/java/com/github/arteam/jdit/domain/PlayerSqlObject.java import com.github.arteam.jdit.domain.entity.Player; import com.google.common.collect.ImmutableSet; import org.jdbi.v3.core.mapper.RowMapper; import org.jdbi.v3.core.statement.StatementContext; import org.jdbi.v3.sqlobject.config.RegisterRowMapper; import org.jdbi.v3.sqlobject.customizer.*; import org.jdbi.v3.sqlobject.statement.GetGeneratedKeys; import org.jdbi.v3.sqlobject.statement.SqlQuery; import org.jdbi.v3.sqlobject.statement.SqlUpdate; import org.joda.time.DateTime; import java.lang.annotation.*; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.lang.reflect.Type; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Date; import java.util.List; import java.util.Optional; import java.util.Set; package com.github.arteam.jdit.domain; /** * Date: 1/25/15 * Time: 11:26 PM * * @author Artem Prigoda */ @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) public interface PlayerSqlObject { @GetGeneratedKeys @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + "(:first_name, :last_name, :birth_date, :weight, :height)") Long createPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName, @Bind("birth_date") Date birthDate, @Bind("height") int height, @Bind("weight") int weight); @GetGeneratedKeys @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + "(:first_name, :last_name, :birth_date, :weight, :height)")
Long createPlayer(@PlayerBinder Player player);
arteam/jdit
src/test/java/com/github/arteam/jdit/AlternateDatabaseTest.java
// Path: src/test/java/com/github/arteam/jdit/domain/PlayerSqlObject.java // @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) // public interface PlayerSqlObject { // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName, // @Bind("birth_date") Date birthDate, @Bind("height") int height, // @Bind("weight") int weight); // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@PlayerBinder Player player); // // @SqlQuery("select last_name from players order by last_name") // List<String> getLastNames(); // // @SqlQuery("select count(*) from players where extract(year from birth_date) = :year") // int getAmountPlayersBornInYear(@Bind("year") int year); // // @SqlQuery("select * from players where birth_date > :date") // List<Player> getPlayersBornAfter(@Bind("date") DateTime date); // // @SqlQuery("select birth_date from players where first_name=:first_name and last_name=:last_name") // DateTime getPlayerBirthDate(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select distinct extract(year from birth_date) player_year from players order by player_year") // Set<Integer> getBornYears(); // // @SqlQuery("select * from players where first_name=:first_name and last_name=:last_name") // Optional<Player> findPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select * from players where weight <> :weight") // List<Player> getPlayersByWeight(@Bind("weight") Optional<Integer> weight); // // @SqlQuery("select first_name from players") // ImmutableSet<String> getFirstNames(); // // @Retention(RetentionPolicy.RUNTIME) // @Target({ElementType.PARAMETER}) // @SqlStatementCustomizingAnnotation(PlayerBinder.Factory.class) // @interface PlayerBinder { // // class Factory implements SqlStatementCustomizerFactory { // // @Override // public SqlStatementParameterCustomizer createForParameter(Annotation annotation, Class<?> sqlObjectType, // Method method, Parameter param, int index, // Type type) { // return (stmt, arg) -> { // Player p = (Player) arg; // stmt.bind("first_name", p.firstName); // stmt.bind("last_name", p.lastName); // stmt.bind("birth_date", p.birthDate); // stmt.bind("weight", p.weight); // stmt.bind("height", p.height); // }; // } // } // } // // class PlayerMapper implements RowMapper<Player> { // @Override // public Player map(ResultSet r, StatementContext ctx) throws SQLException { // int height = r.getInt("height"); // int weight = r.getInt("weight"); // return new Player(Optional.of(r.getLong("id")), r.getString("first_name"), r.getString("last_name"), // r.getTimestamp("birth_date"), // height != 0 ? Optional.of(height) : Optional.empty(), // weight != 0 ? Optional.of(weight) : Optional.empty()); // } // } // }
import com.github.arteam.jdit.annotations.DBIHandle; import com.github.arteam.jdit.annotations.DataSet; import com.github.arteam.jdit.annotations.TestedSqlObject; import com.github.arteam.jdit.domain.PlayerSqlObject; import org.jdbi.v3.core.Handle; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; import org.junit.Test; import org.junit.runner.RunWith; import static org.assertj.core.api.Assertions.assertThat;
package com.github.arteam.jdit; @RunWith(DBIRunner.class) public abstract class AlternateDatabaseTest { private static final DateTimeFormatter fmt = ISODateTimeFormat.date(); @TestedSqlObject
// Path: src/test/java/com/github/arteam/jdit/domain/PlayerSqlObject.java // @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) // public interface PlayerSqlObject { // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName, // @Bind("birth_date") Date birthDate, @Bind("height") int height, // @Bind("weight") int weight); // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@PlayerBinder Player player); // // @SqlQuery("select last_name from players order by last_name") // List<String> getLastNames(); // // @SqlQuery("select count(*) from players where extract(year from birth_date) = :year") // int getAmountPlayersBornInYear(@Bind("year") int year); // // @SqlQuery("select * from players where birth_date > :date") // List<Player> getPlayersBornAfter(@Bind("date") DateTime date); // // @SqlQuery("select birth_date from players where first_name=:first_name and last_name=:last_name") // DateTime getPlayerBirthDate(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select distinct extract(year from birth_date) player_year from players order by player_year") // Set<Integer> getBornYears(); // // @SqlQuery("select * from players where first_name=:first_name and last_name=:last_name") // Optional<Player> findPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select * from players where weight <> :weight") // List<Player> getPlayersByWeight(@Bind("weight") Optional<Integer> weight); // // @SqlQuery("select first_name from players") // ImmutableSet<String> getFirstNames(); // // @Retention(RetentionPolicy.RUNTIME) // @Target({ElementType.PARAMETER}) // @SqlStatementCustomizingAnnotation(PlayerBinder.Factory.class) // @interface PlayerBinder { // // class Factory implements SqlStatementCustomizerFactory { // // @Override // public SqlStatementParameterCustomizer createForParameter(Annotation annotation, Class<?> sqlObjectType, // Method method, Parameter param, int index, // Type type) { // return (stmt, arg) -> { // Player p = (Player) arg; // stmt.bind("first_name", p.firstName); // stmt.bind("last_name", p.lastName); // stmt.bind("birth_date", p.birthDate); // stmt.bind("weight", p.weight); // stmt.bind("height", p.height); // }; // } // } // } // // class PlayerMapper implements RowMapper<Player> { // @Override // public Player map(ResultSet r, StatementContext ctx) throws SQLException { // int height = r.getInt("height"); // int weight = r.getInt("weight"); // return new Player(Optional.of(r.getLong("id")), r.getString("first_name"), r.getString("last_name"), // r.getTimestamp("birth_date"), // height != 0 ? Optional.of(height) : Optional.empty(), // weight != 0 ? Optional.of(weight) : Optional.empty()); // } // } // } // Path: src/test/java/com/github/arteam/jdit/AlternateDatabaseTest.java import com.github.arteam.jdit.annotations.DBIHandle; import com.github.arteam.jdit.annotations.DataSet; import com.github.arteam.jdit.annotations.TestedSqlObject; import com.github.arteam.jdit.domain.PlayerSqlObject; import org.jdbi.v3.core.Handle; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; import org.junit.Test; import org.junit.runner.RunWith; import static org.assertj.core.api.Assertions.assertThat; package com.github.arteam.jdit; @RunWith(DBIRunner.class) public abstract class AlternateDatabaseTest { private static final DateTimeFormatter fmt = ISODateTimeFormat.date(); @TestedSqlObject
PlayerSqlObject playerDao;
arteam/jdit
src/test/java/com/github/arteam/jdit/TestDirectoryMigration.java
// Path: src/test/java/com/github/arteam/jdit/domain/TeamSqlObject.java // @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) // public interface TeamSqlObject { // // @CreateSqlObject // PlayerSqlObject playerDao(); // // @SqlUpdate("insert into teams(name, division) values (:name, :division)") // @GetGeneratedKeys // long createTeam(@Bind("name") String name, @Bind("division") Division division); // // @SqlUpdate("insert into roster(team_id, player_id) values (:team_id, :player_id)") // void addPlayerToTeam(@Bind("team_id") long teamId, @Bind("player_id") long playerId); // // @Transaction // default void addTeam(Team team, List<Player> players) { // long teamId = createTeam(team.name, team.division); // for (Player player : players) { // long playerId = playerDao().createPlayer(player); // addPlayerToTeam(teamId, playerId); // } // } // // @SqlQuery("select * from players p " + // "inner join roster r on r.player_id=p.id " + // "inner join teams t on r.team_id=t.id " + // "where t.name = :team_name " + // "order by p.last_name") // List<Player> getPlayers(@Bind("team_name") String teamName); // }
import com.github.arteam.jdit.annotations.DataSet; import com.github.arteam.jdit.annotations.JditProperties; import com.github.arteam.jdit.annotations.TestedSqlObject; import com.github.arteam.jdit.domain.TeamSqlObject; import org.junit.Test; import org.junit.runner.RunWith; import static org.assertj.core.api.Assertions.assertThat;
package com.github.arteam.jdit; @RunWith(DBIRunner.class) @JditProperties("jdit-schema-directory.properties") public class TestDirectoryMigration { @TestedSqlObject
// Path: src/test/java/com/github/arteam/jdit/domain/TeamSqlObject.java // @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) // public interface TeamSqlObject { // // @CreateSqlObject // PlayerSqlObject playerDao(); // // @SqlUpdate("insert into teams(name, division) values (:name, :division)") // @GetGeneratedKeys // long createTeam(@Bind("name") String name, @Bind("division") Division division); // // @SqlUpdate("insert into roster(team_id, player_id) values (:team_id, :player_id)") // void addPlayerToTeam(@Bind("team_id") long teamId, @Bind("player_id") long playerId); // // @Transaction // default void addTeam(Team team, List<Player> players) { // long teamId = createTeam(team.name, team.division); // for (Player player : players) { // long playerId = playerDao().createPlayer(player); // addPlayerToTeam(teamId, playerId); // } // } // // @SqlQuery("select * from players p " + // "inner join roster r on r.player_id=p.id " + // "inner join teams t on r.team_id=t.id " + // "where t.name = :team_name " + // "order by p.last_name") // List<Player> getPlayers(@Bind("team_name") String teamName); // } // Path: src/test/java/com/github/arteam/jdit/TestDirectoryMigration.java import com.github.arteam.jdit.annotations.DataSet; import com.github.arteam.jdit.annotations.JditProperties; import com.github.arteam.jdit.annotations.TestedSqlObject; import com.github.arteam.jdit.domain.TeamSqlObject; import org.junit.Test; import org.junit.runner.RunWith; import static org.assertj.core.api.Assertions.assertThat; package com.github.arteam.jdit; @RunWith(DBIRunner.class) @JditProperties("jdit-schema-directory.properties") public class TestDirectoryMigration { @TestedSqlObject
TeamSqlObject teamSqlObject;
arteam/jdit
src/main/java/com/github/arteam/jdit/DBIContext.java
// Path: src/main/java/com/github/arteam/jdit/maintenance/DatabaseMaintenance.java // public interface DatabaseMaintenance { // // /** // * Drop all tables and sequences // */ // void dropTablesAndSequences(); // // /** // * Sweep data from the DB, but don't drop the schema. // * Also restart sequences, so tests can rely on their predictability. // */ // void sweepData(); // } // // Path: src/main/java/com/github/arteam/jdit/maintenance/DatabaseMaintenanceFactory.java // public final class DatabaseMaintenanceFactory { // // private static final String POSTGRESQL = "PostgreSQL"; // private static final String HSQLDB = "HSQL Database Engine"; // private static final String H2 = "H2"; // private static final String MYSQL = "MySQL"; // // private DatabaseMaintenanceFactory() { // } // // public static DatabaseMaintenance create(Handle handle) { // String databaseVendor = getDatabaseVendor(handle); // switch (databaseVendor) { // case POSTGRESQL: // return new PostgresDatabaseMaintenance(handle); // case HSQLDB: // return new HsqlDatabaseMaintenance(handle); // case H2: // return new H2DatabaseMaintenance(handle); // case MYSQL: // return new MySqlDatabaseMaintenance(handle); // default: // throw new UnsupportedOperationException(databaseVendor + " is not supported"); // } // } // // private static String getDatabaseVendor(Handle handle) { // try { // return handle.getConnection().getMetaData().getDatabaseProductName(); // } catch (SQLException e) { // throw new RuntimeException(e); // } // } // }
import com.github.arteam.jdit.maintenance.DatabaseMaintenance; import com.github.arteam.jdit.maintenance.DatabaseMaintenanceFactory; import org.jdbi.v3.core.Handle; import org.jdbi.v3.core.Jdbi; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Arrays; import java.util.Comparator; import java.util.Map; import java.util.Properties;
} @SuppressWarnings("unchecked") private Comparator<String> createFilesComparator(Properties properties) { try { if (!properties.containsKey("schema.migration.file.comparator")) { return null; } return (Comparator<String>) Class.forName(properties.getProperty("schema.migration.file.comparator")) .newInstance(); } catch (Exception e) { throw new IllegalStateException("Unable to create a comparator", e); } } /** * Migrate the DB schema * * @param properties configuration of schema migration */ private void migrateSchema(Properties properties) { String property = properties.getProperty("schema.migration.enabled"); if (property != null && !Boolean.parseBoolean(property)) { return; } try (Handle handle = dbi.open()) { String schemaLocation = properties.getProperty("schema.migration.location"); if (schemaLocation == null) { schemaLocation = DEFAULT_SCHEMA_LOCATION; }
// Path: src/main/java/com/github/arteam/jdit/maintenance/DatabaseMaintenance.java // public interface DatabaseMaintenance { // // /** // * Drop all tables and sequences // */ // void dropTablesAndSequences(); // // /** // * Sweep data from the DB, but don't drop the schema. // * Also restart sequences, so tests can rely on their predictability. // */ // void sweepData(); // } // // Path: src/main/java/com/github/arteam/jdit/maintenance/DatabaseMaintenanceFactory.java // public final class DatabaseMaintenanceFactory { // // private static final String POSTGRESQL = "PostgreSQL"; // private static final String HSQLDB = "HSQL Database Engine"; // private static final String H2 = "H2"; // private static final String MYSQL = "MySQL"; // // private DatabaseMaintenanceFactory() { // } // // public static DatabaseMaintenance create(Handle handle) { // String databaseVendor = getDatabaseVendor(handle); // switch (databaseVendor) { // case POSTGRESQL: // return new PostgresDatabaseMaintenance(handle); // case HSQLDB: // return new HsqlDatabaseMaintenance(handle); // case H2: // return new H2DatabaseMaintenance(handle); // case MYSQL: // return new MySqlDatabaseMaintenance(handle); // default: // throw new UnsupportedOperationException(databaseVendor + " is not supported"); // } // } // // private static String getDatabaseVendor(Handle handle) { // try { // return handle.getConnection().getMetaData().getDatabaseProductName(); // } catch (SQLException e) { // throw new RuntimeException(e); // } // } // } // Path: src/main/java/com/github/arteam/jdit/DBIContext.java import com.github.arteam.jdit.maintenance.DatabaseMaintenance; import com.github.arteam.jdit.maintenance.DatabaseMaintenanceFactory; import org.jdbi.v3.core.Handle; import org.jdbi.v3.core.Jdbi; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Arrays; import java.util.Comparator; import java.util.Map; import java.util.Properties; } @SuppressWarnings("unchecked") private Comparator<String> createFilesComparator(Properties properties) { try { if (!properties.containsKey("schema.migration.file.comparator")) { return null; } return (Comparator<String>) Class.forName(properties.getProperty("schema.migration.file.comparator")) .newInstance(); } catch (Exception e) { throw new IllegalStateException("Unable to create a comparator", e); } } /** * Migrate the DB schema * * @param properties configuration of schema migration */ private void migrateSchema(Properties properties) { String property = properties.getProperty("schema.migration.enabled"); if (property != null && !Boolean.parseBoolean(property)) { return; } try (Handle handle = dbi.open()) { String schemaLocation = properties.getProperty("schema.migration.location"); if (schemaLocation == null) { schemaLocation = DEFAULT_SCHEMA_LOCATION; }
DatabaseMaintenance databaseMaintenance = DatabaseMaintenanceFactory.create(handle);
arteam/jdit
src/main/java/com/github/arteam/jdit/DBIContext.java
// Path: src/main/java/com/github/arteam/jdit/maintenance/DatabaseMaintenance.java // public interface DatabaseMaintenance { // // /** // * Drop all tables and sequences // */ // void dropTablesAndSequences(); // // /** // * Sweep data from the DB, but don't drop the schema. // * Also restart sequences, so tests can rely on their predictability. // */ // void sweepData(); // } // // Path: src/main/java/com/github/arteam/jdit/maintenance/DatabaseMaintenanceFactory.java // public final class DatabaseMaintenanceFactory { // // private static final String POSTGRESQL = "PostgreSQL"; // private static final String HSQLDB = "HSQL Database Engine"; // private static final String H2 = "H2"; // private static final String MYSQL = "MySQL"; // // private DatabaseMaintenanceFactory() { // } // // public static DatabaseMaintenance create(Handle handle) { // String databaseVendor = getDatabaseVendor(handle); // switch (databaseVendor) { // case POSTGRESQL: // return new PostgresDatabaseMaintenance(handle); // case HSQLDB: // return new HsqlDatabaseMaintenance(handle); // case H2: // return new H2DatabaseMaintenance(handle); // case MYSQL: // return new MySqlDatabaseMaintenance(handle); // default: // throw new UnsupportedOperationException(databaseVendor + " is not supported"); // } // } // // private static String getDatabaseVendor(Handle handle) { // try { // return handle.getConnection().getMetaData().getDatabaseProductName(); // } catch (SQLException e) { // throw new RuntimeException(e); // } // } // }
import com.github.arteam.jdit.maintenance.DatabaseMaintenance; import com.github.arteam.jdit.maintenance.DatabaseMaintenanceFactory; import org.jdbi.v3.core.Handle; import org.jdbi.v3.core.Jdbi; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Arrays; import java.util.Comparator; import java.util.Map; import java.util.Properties;
} @SuppressWarnings("unchecked") private Comparator<String> createFilesComparator(Properties properties) { try { if (!properties.containsKey("schema.migration.file.comparator")) { return null; } return (Comparator<String>) Class.forName(properties.getProperty("schema.migration.file.comparator")) .newInstance(); } catch (Exception e) { throw new IllegalStateException("Unable to create a comparator", e); } } /** * Migrate the DB schema * * @param properties configuration of schema migration */ private void migrateSchema(Properties properties) { String property = properties.getProperty("schema.migration.enabled"); if (property != null && !Boolean.parseBoolean(property)) { return; } try (Handle handle = dbi.open()) { String schemaLocation = properties.getProperty("schema.migration.location"); if (schemaLocation == null) { schemaLocation = DEFAULT_SCHEMA_LOCATION; }
// Path: src/main/java/com/github/arteam/jdit/maintenance/DatabaseMaintenance.java // public interface DatabaseMaintenance { // // /** // * Drop all tables and sequences // */ // void dropTablesAndSequences(); // // /** // * Sweep data from the DB, but don't drop the schema. // * Also restart sequences, so tests can rely on their predictability. // */ // void sweepData(); // } // // Path: src/main/java/com/github/arteam/jdit/maintenance/DatabaseMaintenanceFactory.java // public final class DatabaseMaintenanceFactory { // // private static final String POSTGRESQL = "PostgreSQL"; // private static final String HSQLDB = "HSQL Database Engine"; // private static final String H2 = "H2"; // private static final String MYSQL = "MySQL"; // // private DatabaseMaintenanceFactory() { // } // // public static DatabaseMaintenance create(Handle handle) { // String databaseVendor = getDatabaseVendor(handle); // switch (databaseVendor) { // case POSTGRESQL: // return new PostgresDatabaseMaintenance(handle); // case HSQLDB: // return new HsqlDatabaseMaintenance(handle); // case H2: // return new H2DatabaseMaintenance(handle); // case MYSQL: // return new MySqlDatabaseMaintenance(handle); // default: // throw new UnsupportedOperationException(databaseVendor + " is not supported"); // } // } // // private static String getDatabaseVendor(Handle handle) { // try { // return handle.getConnection().getMetaData().getDatabaseProductName(); // } catch (SQLException e) { // throw new RuntimeException(e); // } // } // } // Path: src/main/java/com/github/arteam/jdit/DBIContext.java import com.github.arteam.jdit.maintenance.DatabaseMaintenance; import com.github.arteam.jdit.maintenance.DatabaseMaintenanceFactory; import org.jdbi.v3.core.Handle; import org.jdbi.v3.core.Jdbi; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Arrays; import java.util.Comparator; import java.util.Map; import java.util.Properties; } @SuppressWarnings("unchecked") private Comparator<String> createFilesComparator(Properties properties) { try { if (!properties.containsKey("schema.migration.file.comparator")) { return null; } return (Comparator<String>) Class.forName(properties.getProperty("schema.migration.file.comparator")) .newInstance(); } catch (Exception e) { throw new IllegalStateException("Unable to create a comparator", e); } } /** * Migrate the DB schema * * @param properties configuration of schema migration */ private void migrateSchema(Properties properties) { String property = properties.getProperty("schema.migration.enabled"); if (property != null && !Boolean.parseBoolean(property)) { return; } try (Handle handle = dbi.open()) { String schemaLocation = properties.getProperty("schema.migration.location"); if (schemaLocation == null) { schemaLocation = DEFAULT_SCHEMA_LOCATION; }
DatabaseMaintenance databaseMaintenance = DatabaseMaintenanceFactory.create(handle);
arteam/jdit
src/test/java/com/github/arteam/jdit/TestDataSet.java
// Path: src/test/java/com/github/arteam/jdit/domain/PlayerSqlObject.java // @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) // public interface PlayerSqlObject { // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName, // @Bind("birth_date") Date birthDate, @Bind("height") int height, // @Bind("weight") int weight); // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@PlayerBinder Player player); // // @SqlQuery("select last_name from players order by last_name") // List<String> getLastNames(); // // @SqlQuery("select count(*) from players where extract(year from birth_date) = :year") // int getAmountPlayersBornInYear(@Bind("year") int year); // // @SqlQuery("select * from players where birth_date > :date") // List<Player> getPlayersBornAfter(@Bind("date") DateTime date); // // @SqlQuery("select birth_date from players where first_name=:first_name and last_name=:last_name") // DateTime getPlayerBirthDate(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select distinct extract(year from birth_date) player_year from players order by player_year") // Set<Integer> getBornYears(); // // @SqlQuery("select * from players where first_name=:first_name and last_name=:last_name") // Optional<Player> findPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select * from players where weight <> :weight") // List<Player> getPlayersByWeight(@Bind("weight") Optional<Integer> weight); // // @SqlQuery("select first_name from players") // ImmutableSet<String> getFirstNames(); // // @Retention(RetentionPolicy.RUNTIME) // @Target({ElementType.PARAMETER}) // @SqlStatementCustomizingAnnotation(PlayerBinder.Factory.class) // @interface PlayerBinder { // // class Factory implements SqlStatementCustomizerFactory { // // @Override // public SqlStatementParameterCustomizer createForParameter(Annotation annotation, Class<?> sqlObjectType, // Method method, Parameter param, int index, // Type type) { // return (stmt, arg) -> { // Player p = (Player) arg; // stmt.bind("first_name", p.firstName); // stmt.bind("last_name", p.lastName); // stmt.bind("birth_date", p.birthDate); // stmt.bind("weight", p.weight); // stmt.bind("height", p.height); // }; // } // } // } // // class PlayerMapper implements RowMapper<Player> { // @Override // public Player map(ResultSet r, StatementContext ctx) throws SQLException { // int height = r.getInt("height"); // int weight = r.getInt("weight"); // return new Player(Optional.of(r.getLong("id")), r.getString("first_name"), r.getString("last_name"), // r.getTimestamp("birth_date"), // height != 0 ? Optional.of(height) : Optional.empty(), // weight != 0 ? Optional.of(weight) : Optional.empty()); // } // } // }
import com.github.arteam.jdit.annotations.DataSet; import com.github.arteam.jdit.annotations.TestedSqlObject; import com.github.arteam.jdit.domain.PlayerSqlObject; import org.junit.Test; import org.junit.runner.RunWith; import static org.assertj.core.api.Assertions.assertThat;
package com.github.arteam.jdit; @RunWith(DBIRunner.class) public class TestDataSet { @TestedSqlObject
// Path: src/test/java/com/github/arteam/jdit/domain/PlayerSqlObject.java // @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) // public interface PlayerSqlObject { // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName, // @Bind("birth_date") Date birthDate, @Bind("height") int height, // @Bind("weight") int weight); // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@PlayerBinder Player player); // // @SqlQuery("select last_name from players order by last_name") // List<String> getLastNames(); // // @SqlQuery("select count(*) from players where extract(year from birth_date) = :year") // int getAmountPlayersBornInYear(@Bind("year") int year); // // @SqlQuery("select * from players where birth_date > :date") // List<Player> getPlayersBornAfter(@Bind("date") DateTime date); // // @SqlQuery("select birth_date from players where first_name=:first_name and last_name=:last_name") // DateTime getPlayerBirthDate(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select distinct extract(year from birth_date) player_year from players order by player_year") // Set<Integer> getBornYears(); // // @SqlQuery("select * from players where first_name=:first_name and last_name=:last_name") // Optional<Player> findPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select * from players where weight <> :weight") // List<Player> getPlayersByWeight(@Bind("weight") Optional<Integer> weight); // // @SqlQuery("select first_name from players") // ImmutableSet<String> getFirstNames(); // // @Retention(RetentionPolicy.RUNTIME) // @Target({ElementType.PARAMETER}) // @SqlStatementCustomizingAnnotation(PlayerBinder.Factory.class) // @interface PlayerBinder { // // class Factory implements SqlStatementCustomizerFactory { // // @Override // public SqlStatementParameterCustomizer createForParameter(Annotation annotation, Class<?> sqlObjectType, // Method method, Parameter param, int index, // Type type) { // return (stmt, arg) -> { // Player p = (Player) arg; // stmt.bind("first_name", p.firstName); // stmt.bind("last_name", p.lastName); // stmt.bind("birth_date", p.birthDate); // stmt.bind("weight", p.weight); // stmt.bind("height", p.height); // }; // } // } // } // // class PlayerMapper implements RowMapper<Player> { // @Override // public Player map(ResultSet r, StatementContext ctx) throws SQLException { // int height = r.getInt("height"); // int weight = r.getInt("weight"); // return new Player(Optional.of(r.getLong("id")), r.getString("first_name"), r.getString("last_name"), // r.getTimestamp("birth_date"), // height != 0 ? Optional.of(height) : Optional.empty(), // weight != 0 ? Optional.of(weight) : Optional.empty()); // } // } // } // Path: src/test/java/com/github/arteam/jdit/TestDataSet.java import com.github.arteam.jdit.annotations.DataSet; import com.github.arteam.jdit.annotations.TestedSqlObject; import com.github.arteam.jdit.domain.PlayerSqlObject; import org.junit.Test; import org.junit.runner.RunWith; import static org.assertj.core.api.Assertions.assertThat; package com.github.arteam.jdit; @RunWith(DBIRunner.class) public class TestDataSet { @TestedSqlObject
PlayerSqlObject playerDao;
arteam/jdit
src/main/java/com/github/arteam/jdit/DBIRunner.java
// Path: src/main/java/com/github/arteam/jdit/maintenance/DatabaseMaintenance.java // public interface DatabaseMaintenance { // // /** // * Drop all tables and sequences // */ // void dropTablesAndSequences(); // // /** // * Sweep data from the DB, but don't drop the schema. // * Also restart sequences, so tests can rely on their predictability. // */ // void sweepData(); // } // // Path: src/main/java/com/github/arteam/jdit/maintenance/DatabaseMaintenanceFactory.java // public final class DatabaseMaintenanceFactory { // // private static final String POSTGRESQL = "PostgreSQL"; // private static final String HSQLDB = "HSQL Database Engine"; // private static final String H2 = "H2"; // private static final String MYSQL = "MySQL"; // // private DatabaseMaintenanceFactory() { // } // // public static DatabaseMaintenance create(Handle handle) { // String databaseVendor = getDatabaseVendor(handle); // switch (databaseVendor) { // case POSTGRESQL: // return new PostgresDatabaseMaintenance(handle); // case HSQLDB: // return new HsqlDatabaseMaintenance(handle); // case H2: // return new H2DatabaseMaintenance(handle); // case MYSQL: // return new MySqlDatabaseMaintenance(handle); // default: // throw new UnsupportedOperationException(databaseVendor + " is not supported"); // } // } // // private static String getDatabaseVendor(Handle handle) { // try { // return handle.getConnection().getMetaData().getDatabaseProductName(); // } catch (SQLException e) { // throw new RuntimeException(e); // } // } // }
import com.github.arteam.jdit.annotations.JditProperties; import com.github.arteam.jdit.maintenance.DatabaseMaintenance; import com.github.arteam.jdit.maintenance.DatabaseMaintenanceFactory; import org.jdbi.v3.core.Handle; import org.jdbi.v3.core.Jdbi; import org.junit.runner.notification.RunNotifier; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; import org.junit.runners.model.Statement;
package com.github.arteam.jdit; /** * <p> * Tests runner which: * <ul> * <li>Injects DBI related tested instances to the tests. * <p>Supports {@link Handle}, {@link Jdbi}, SQLObject and DBI DAO. * </li> * <li>Injects data to the DB from a script for a specific * method or a test</li> * <li>Sweeps data from the DB after every tests, so every * test starts with an empty schema</li> * </ul> */ public class DBIRunner extends BlockJUnit4ClassRunner { private DatabaseMaintenance databaseMaintenance; private TestObjectsInjector injector; private DataSetInjector dataSetInjector; private Class<?> klass; public DBIRunner(Class<?> klass) throws InitializationError { super(klass); this.klass = klass; } @Override protected Object createTest() throws Exception { Object test = super.createTest(); // Now we can inject tested instances to the current test injector.injectTestedInstances(test); return test; } @Override protected Statement classBlock(RunNotifier notifier) { final Statement statement = super.classBlock(notifier); return new Statement() { @Override public void evaluate() throws Throwable { // Open a new handle for every test // It affords to avoid creating a static state which makes tests more independent JditProperties jditProperties = klass.getAnnotation(JditProperties.class); Jdbi dbi = jditProperties != null ? DBIContextFactory.getDBI(jditProperties.value()) : DBIContextFactory.getDBI(); try (Handle handle = dbi.open()) { injector = new TestObjectsInjector(dbi, handle);
// Path: src/main/java/com/github/arteam/jdit/maintenance/DatabaseMaintenance.java // public interface DatabaseMaintenance { // // /** // * Drop all tables and sequences // */ // void dropTablesAndSequences(); // // /** // * Sweep data from the DB, but don't drop the schema. // * Also restart sequences, so tests can rely on their predictability. // */ // void sweepData(); // } // // Path: src/main/java/com/github/arteam/jdit/maintenance/DatabaseMaintenanceFactory.java // public final class DatabaseMaintenanceFactory { // // private static final String POSTGRESQL = "PostgreSQL"; // private static final String HSQLDB = "HSQL Database Engine"; // private static final String H2 = "H2"; // private static final String MYSQL = "MySQL"; // // private DatabaseMaintenanceFactory() { // } // // public static DatabaseMaintenance create(Handle handle) { // String databaseVendor = getDatabaseVendor(handle); // switch (databaseVendor) { // case POSTGRESQL: // return new PostgresDatabaseMaintenance(handle); // case HSQLDB: // return new HsqlDatabaseMaintenance(handle); // case H2: // return new H2DatabaseMaintenance(handle); // case MYSQL: // return new MySqlDatabaseMaintenance(handle); // default: // throw new UnsupportedOperationException(databaseVendor + " is not supported"); // } // } // // private static String getDatabaseVendor(Handle handle) { // try { // return handle.getConnection().getMetaData().getDatabaseProductName(); // } catch (SQLException e) { // throw new RuntimeException(e); // } // } // } // Path: src/main/java/com/github/arteam/jdit/DBIRunner.java import com.github.arteam.jdit.annotations.JditProperties; import com.github.arteam.jdit.maintenance.DatabaseMaintenance; import com.github.arteam.jdit.maintenance.DatabaseMaintenanceFactory; import org.jdbi.v3.core.Handle; import org.jdbi.v3.core.Jdbi; import org.junit.runner.notification.RunNotifier; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; import org.junit.runners.model.Statement; package com.github.arteam.jdit; /** * <p> * Tests runner which: * <ul> * <li>Injects DBI related tested instances to the tests. * <p>Supports {@link Handle}, {@link Jdbi}, SQLObject and DBI DAO. * </li> * <li>Injects data to the DB from a script for a specific * method or a test</li> * <li>Sweeps data from the DB after every tests, so every * test starts with an empty schema</li> * </ul> */ public class DBIRunner extends BlockJUnit4ClassRunner { private DatabaseMaintenance databaseMaintenance; private TestObjectsInjector injector; private DataSetInjector dataSetInjector; private Class<?> klass; public DBIRunner(Class<?> klass) throws InitializationError { super(klass); this.klass = klass; } @Override protected Object createTest() throws Exception { Object test = super.createTest(); // Now we can inject tested instances to the current test injector.injectTestedInstances(test); return test; } @Override protected Statement classBlock(RunNotifier notifier) { final Statement statement = super.classBlock(notifier); return new Statement() { @Override public void evaluate() throws Throwable { // Open a new handle for every test // It affords to avoid creating a static state which makes tests more independent JditProperties jditProperties = klass.getAnnotation(JditProperties.class); Jdbi dbi = jditProperties != null ? DBIContextFactory.getDBI(jditProperties.value()) : DBIContextFactory.getDBI(); try (Handle handle = dbi.open()) { injector = new TestObjectsInjector(dbi, handle);
databaseMaintenance = DatabaseMaintenanceFactory.create(handle);
arteam/jdit
src/test/java/com/github/arteam/jdit/TestDataSetOnClassLevel.java
// Path: src/test/java/com/github/arteam/jdit/domain/PlayerSqlObject.java // @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) // public interface PlayerSqlObject { // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName, // @Bind("birth_date") Date birthDate, @Bind("height") int height, // @Bind("weight") int weight); // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@PlayerBinder Player player); // // @SqlQuery("select last_name from players order by last_name") // List<String> getLastNames(); // // @SqlQuery("select count(*) from players where extract(year from birth_date) = :year") // int getAmountPlayersBornInYear(@Bind("year") int year); // // @SqlQuery("select * from players where birth_date > :date") // List<Player> getPlayersBornAfter(@Bind("date") DateTime date); // // @SqlQuery("select birth_date from players where first_name=:first_name and last_name=:last_name") // DateTime getPlayerBirthDate(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select distinct extract(year from birth_date) player_year from players order by player_year") // Set<Integer> getBornYears(); // // @SqlQuery("select * from players where first_name=:first_name and last_name=:last_name") // Optional<Player> findPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select * from players where weight <> :weight") // List<Player> getPlayersByWeight(@Bind("weight") Optional<Integer> weight); // // @SqlQuery("select first_name from players") // ImmutableSet<String> getFirstNames(); // // @Retention(RetentionPolicy.RUNTIME) // @Target({ElementType.PARAMETER}) // @SqlStatementCustomizingAnnotation(PlayerBinder.Factory.class) // @interface PlayerBinder { // // class Factory implements SqlStatementCustomizerFactory { // // @Override // public SqlStatementParameterCustomizer createForParameter(Annotation annotation, Class<?> sqlObjectType, // Method method, Parameter param, int index, // Type type) { // return (stmt, arg) -> { // Player p = (Player) arg; // stmt.bind("first_name", p.firstName); // stmt.bind("last_name", p.lastName); // stmt.bind("birth_date", p.birthDate); // stmt.bind("weight", p.weight); // stmt.bind("height", p.height); // }; // } // } // } // // class PlayerMapper implements RowMapper<Player> { // @Override // public Player map(ResultSet r, StatementContext ctx) throws SQLException { // int height = r.getInt("height"); // int weight = r.getInt("weight"); // return new Player(Optional.of(r.getLong("id")), r.getString("first_name"), r.getString("last_name"), // r.getTimestamp("birth_date"), // height != 0 ? Optional.of(height) : Optional.empty(), // weight != 0 ? Optional.of(weight) : Optional.empty()); // } // } // }
import com.github.arteam.jdit.annotations.DataSet; import com.github.arteam.jdit.annotations.TestedSqlObject; import com.github.arteam.jdit.domain.PlayerSqlObject; import org.junit.Test; import org.junit.runner.RunWith; import java.util.List; import java.util.Set; import static org.assertj.core.api.Assertions.assertThat;
package com.github.arteam.jdit; @RunWith(DBIRunner.class) @DataSet("/playerDao/getInitials.sql") public class TestDataSetOnClassLevel { @TestedSqlObject
// Path: src/test/java/com/github/arteam/jdit/domain/PlayerSqlObject.java // @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) // public interface PlayerSqlObject { // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName, // @Bind("birth_date") Date birthDate, @Bind("height") int height, // @Bind("weight") int weight); // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@PlayerBinder Player player); // // @SqlQuery("select last_name from players order by last_name") // List<String> getLastNames(); // // @SqlQuery("select count(*) from players where extract(year from birth_date) = :year") // int getAmountPlayersBornInYear(@Bind("year") int year); // // @SqlQuery("select * from players where birth_date > :date") // List<Player> getPlayersBornAfter(@Bind("date") DateTime date); // // @SqlQuery("select birth_date from players where first_name=:first_name and last_name=:last_name") // DateTime getPlayerBirthDate(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select distinct extract(year from birth_date) player_year from players order by player_year") // Set<Integer> getBornYears(); // // @SqlQuery("select * from players where first_name=:first_name and last_name=:last_name") // Optional<Player> findPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select * from players where weight <> :weight") // List<Player> getPlayersByWeight(@Bind("weight") Optional<Integer> weight); // // @SqlQuery("select first_name from players") // ImmutableSet<String> getFirstNames(); // // @Retention(RetentionPolicy.RUNTIME) // @Target({ElementType.PARAMETER}) // @SqlStatementCustomizingAnnotation(PlayerBinder.Factory.class) // @interface PlayerBinder { // // class Factory implements SqlStatementCustomizerFactory { // // @Override // public SqlStatementParameterCustomizer createForParameter(Annotation annotation, Class<?> sqlObjectType, // Method method, Parameter param, int index, // Type type) { // return (stmt, arg) -> { // Player p = (Player) arg; // stmt.bind("first_name", p.firstName); // stmt.bind("last_name", p.lastName); // stmt.bind("birth_date", p.birthDate); // stmt.bind("weight", p.weight); // stmt.bind("height", p.height); // }; // } // } // } // // class PlayerMapper implements RowMapper<Player> { // @Override // public Player map(ResultSet r, StatementContext ctx) throws SQLException { // int height = r.getInt("height"); // int weight = r.getInt("weight"); // return new Player(Optional.of(r.getLong("id")), r.getString("first_name"), r.getString("last_name"), // r.getTimestamp("birth_date"), // height != 0 ? Optional.of(height) : Optional.empty(), // weight != 0 ? Optional.of(weight) : Optional.empty()); // } // } // } // Path: src/test/java/com/github/arteam/jdit/TestDataSetOnClassLevel.java import com.github.arteam.jdit.annotations.DataSet; import com.github.arteam.jdit.annotations.TestedSqlObject; import com.github.arteam.jdit.domain.PlayerSqlObject; import org.junit.Test; import org.junit.runner.RunWith; import java.util.List; import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; package com.github.arteam.jdit; @RunWith(DBIRunner.class) @DataSet("/playerDao/getInitials.sql") public class TestDataSetOnClassLevel { @TestedSqlObject
PlayerSqlObject playerDao;
arteam/jdit
src/test/java/com/github/arteam/jdit/DBISqlObjectTest.java
// Path: src/test/java/com/github/arteam/jdit/domain/PlayerSqlObject.java // @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) // public interface PlayerSqlObject { // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName, // @Bind("birth_date") Date birthDate, @Bind("height") int height, // @Bind("weight") int weight); // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@PlayerBinder Player player); // // @SqlQuery("select last_name from players order by last_name") // List<String> getLastNames(); // // @SqlQuery("select count(*) from players where extract(year from birth_date) = :year") // int getAmountPlayersBornInYear(@Bind("year") int year); // // @SqlQuery("select * from players where birth_date > :date") // List<Player> getPlayersBornAfter(@Bind("date") DateTime date); // // @SqlQuery("select birth_date from players where first_name=:first_name and last_name=:last_name") // DateTime getPlayerBirthDate(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select distinct extract(year from birth_date) player_year from players order by player_year") // Set<Integer> getBornYears(); // // @SqlQuery("select * from players where first_name=:first_name and last_name=:last_name") // Optional<Player> findPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select * from players where weight <> :weight") // List<Player> getPlayersByWeight(@Bind("weight") Optional<Integer> weight); // // @SqlQuery("select first_name from players") // ImmutableSet<String> getFirstNames(); // // @Retention(RetentionPolicy.RUNTIME) // @Target({ElementType.PARAMETER}) // @SqlStatementCustomizingAnnotation(PlayerBinder.Factory.class) // @interface PlayerBinder { // // class Factory implements SqlStatementCustomizerFactory { // // @Override // public SqlStatementParameterCustomizer createForParameter(Annotation annotation, Class<?> sqlObjectType, // Method method, Parameter param, int index, // Type type) { // return (stmt, arg) -> { // Player p = (Player) arg; // stmt.bind("first_name", p.firstName); // stmt.bind("last_name", p.lastName); // stmt.bind("birth_date", p.birthDate); // stmt.bind("weight", p.weight); // stmt.bind("height", p.height); // }; // } // } // } // // class PlayerMapper implements RowMapper<Player> { // @Override // public Player map(ResultSet r, StatementContext ctx) throws SQLException { // int height = r.getInt("height"); // int weight = r.getInt("weight"); // return new Player(Optional.of(r.getLong("id")), r.getString("first_name"), r.getString("last_name"), // r.getTimestamp("birth_date"), // height != 0 ? Optional.of(height) : Optional.empty(), // weight != 0 ? Optional.of(weight) : Optional.empty()); // } // } // }
import com.github.arteam.jdit.annotations.DBIHandle; import com.github.arteam.jdit.annotations.TestedSqlObject; import com.github.arteam.jdit.domain.PlayerSqlObject; import org.jdbi.v3.core.Handle; import org.junit.Test; import org.junit.runner.RunWith; import java.text.SimpleDateFormat; import static org.assertj.core.api.Assertions.assertThat;
package com.github.arteam.jdit; @RunWith(DBIRunner.class) public class DBISqlObjectTest { @DBIHandle Handle handle; @TestedSqlObject
// Path: src/test/java/com/github/arteam/jdit/domain/PlayerSqlObject.java // @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) // public interface PlayerSqlObject { // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName, // @Bind("birth_date") Date birthDate, @Bind("height") int height, // @Bind("weight") int weight); // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@PlayerBinder Player player); // // @SqlQuery("select last_name from players order by last_name") // List<String> getLastNames(); // // @SqlQuery("select count(*) from players where extract(year from birth_date) = :year") // int getAmountPlayersBornInYear(@Bind("year") int year); // // @SqlQuery("select * from players where birth_date > :date") // List<Player> getPlayersBornAfter(@Bind("date") DateTime date); // // @SqlQuery("select birth_date from players where first_name=:first_name and last_name=:last_name") // DateTime getPlayerBirthDate(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select distinct extract(year from birth_date) player_year from players order by player_year") // Set<Integer> getBornYears(); // // @SqlQuery("select * from players where first_name=:first_name and last_name=:last_name") // Optional<Player> findPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select * from players where weight <> :weight") // List<Player> getPlayersByWeight(@Bind("weight") Optional<Integer> weight); // // @SqlQuery("select first_name from players") // ImmutableSet<String> getFirstNames(); // // @Retention(RetentionPolicy.RUNTIME) // @Target({ElementType.PARAMETER}) // @SqlStatementCustomizingAnnotation(PlayerBinder.Factory.class) // @interface PlayerBinder { // // class Factory implements SqlStatementCustomizerFactory { // // @Override // public SqlStatementParameterCustomizer createForParameter(Annotation annotation, Class<?> sqlObjectType, // Method method, Parameter param, int index, // Type type) { // return (stmt, arg) -> { // Player p = (Player) arg; // stmt.bind("first_name", p.firstName); // stmt.bind("last_name", p.lastName); // stmt.bind("birth_date", p.birthDate); // stmt.bind("weight", p.weight); // stmt.bind("height", p.height); // }; // } // } // } // // class PlayerMapper implements RowMapper<Player> { // @Override // public Player map(ResultSet r, StatementContext ctx) throws SQLException { // int height = r.getInt("height"); // int weight = r.getInt("weight"); // return new Player(Optional.of(r.getLong("id")), r.getString("first_name"), r.getString("last_name"), // r.getTimestamp("birth_date"), // height != 0 ? Optional.of(height) : Optional.empty(), // weight != 0 ? Optional.of(weight) : Optional.empty()); // } // } // } // Path: src/test/java/com/github/arteam/jdit/DBISqlObjectTest.java import com.github.arteam.jdit.annotations.DBIHandle; import com.github.arteam.jdit.annotations.TestedSqlObject; import com.github.arteam.jdit.domain.PlayerSqlObject; import org.jdbi.v3.core.Handle; import org.junit.Test; import org.junit.runner.RunWith; import java.text.SimpleDateFormat; import static org.assertj.core.api.Assertions.assertThat; package com.github.arteam.jdit; @RunWith(DBIRunner.class) public class DBISqlObjectTest { @DBIHandle Handle handle; @TestedSqlObject
PlayerSqlObject playerDao;
arteam/jdit
src/test/java/com/github/arteam/jdit/DBIComplexSqlObjectTest.java
// Path: src/test/java/com/github/arteam/jdit/domain/TeamSqlObject.java // @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) // public interface TeamSqlObject { // // @CreateSqlObject // PlayerSqlObject playerDao(); // // @SqlUpdate("insert into teams(name, division) values (:name, :division)") // @GetGeneratedKeys // long createTeam(@Bind("name") String name, @Bind("division") Division division); // // @SqlUpdate("insert into roster(team_id, player_id) values (:team_id, :player_id)") // void addPlayerToTeam(@Bind("team_id") long teamId, @Bind("player_id") long playerId); // // @Transaction // default void addTeam(Team team, List<Player> players) { // long teamId = createTeam(team.name, team.division); // for (Player player : players) { // long playerId = playerDao().createPlayer(player); // addPlayerToTeam(teamId, playerId); // } // } // // @SqlQuery("select * from players p " + // "inner join roster r on r.player_id=p.id " + // "inner join teams t on r.team_id=t.id " + // "where t.name = :team_name " + // "order by p.last_name") // List<Player> getPlayers(@Bind("team_name") String teamName); // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Division.java // public enum Division { // PACIFIC, // CENTRAL, // METROPOLITAN, // ATLANTIC // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Player.java // public class Player { // // public final Optional<Long> id; // public final String firstName; // public final String lastName; // public final Date birthDate; // public final Optional<Integer> height; // public final Optional<Integer> weight; // // public Player(Optional<Long> id, String firstName, String lastName, Date birthDate, // Optional<Integer> height, Optional<Integer> weight) { // this.id = id; // this.firstName = firstName; // this.lastName = lastName; // this.birthDate = birthDate; // this.height = height; // this.weight = weight; // } // // public Player(String firstName, String lastName, Date birthDate, int height, int weight) { // this(Optional.<Long>empty(), firstName, lastName, birthDate, Optional.of(height), Optional.of(weight)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .omitNullValues() // .add("id", id.orElse(null)) // .add("firstName", firstName) // .add("lastName", lastName) // .add("birthDate", birthDate) // .add("height", height.orElse(null)) // .add("weight", weight.orElse(null)) // .toString(); // } // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Team.java // public class Team { // // public final Optional<Long> id; // public final String name; // public final Division division; // // public Team(Optional<Long> id, String name, Division division) { // this.id = id; // this.name = name; // this.division = division; // } // // public Team(String name, Division division) { // this.name = name; // this.division = division; // this.id = Optional.empty(); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("id", id) // .add("name", name) // .add("division", division) // .toString(); // } // }
import com.github.arteam.jdit.annotations.DataSet; import com.github.arteam.jdit.annotations.TestedSqlObject; import com.github.arteam.jdit.domain.TeamSqlObject; import com.github.arteam.jdit.domain.entity.Division; import com.github.arteam.jdit.domain.entity.Player; import com.github.arteam.jdit.domain.entity.Team; import com.google.common.collect.ImmutableList; import org.joda.time.format.ISODateTimeFormat; import org.junit.Test; import org.junit.runner.RunWith; import java.util.Date; import java.util.List; import static org.assertj.core.api.Assertions.assertThat;
package com.github.arteam.jdit; @RunWith(DBIRunner.class) @DataSet("teamDao/insert-divisions.sql") public class DBIComplexSqlObjectTest { @TestedSqlObject
// Path: src/test/java/com/github/arteam/jdit/domain/TeamSqlObject.java // @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) // public interface TeamSqlObject { // // @CreateSqlObject // PlayerSqlObject playerDao(); // // @SqlUpdate("insert into teams(name, division) values (:name, :division)") // @GetGeneratedKeys // long createTeam(@Bind("name") String name, @Bind("division") Division division); // // @SqlUpdate("insert into roster(team_id, player_id) values (:team_id, :player_id)") // void addPlayerToTeam(@Bind("team_id") long teamId, @Bind("player_id") long playerId); // // @Transaction // default void addTeam(Team team, List<Player> players) { // long teamId = createTeam(team.name, team.division); // for (Player player : players) { // long playerId = playerDao().createPlayer(player); // addPlayerToTeam(teamId, playerId); // } // } // // @SqlQuery("select * from players p " + // "inner join roster r on r.player_id=p.id " + // "inner join teams t on r.team_id=t.id " + // "where t.name = :team_name " + // "order by p.last_name") // List<Player> getPlayers(@Bind("team_name") String teamName); // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Division.java // public enum Division { // PACIFIC, // CENTRAL, // METROPOLITAN, // ATLANTIC // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Player.java // public class Player { // // public final Optional<Long> id; // public final String firstName; // public final String lastName; // public final Date birthDate; // public final Optional<Integer> height; // public final Optional<Integer> weight; // // public Player(Optional<Long> id, String firstName, String lastName, Date birthDate, // Optional<Integer> height, Optional<Integer> weight) { // this.id = id; // this.firstName = firstName; // this.lastName = lastName; // this.birthDate = birthDate; // this.height = height; // this.weight = weight; // } // // public Player(String firstName, String lastName, Date birthDate, int height, int weight) { // this(Optional.<Long>empty(), firstName, lastName, birthDate, Optional.of(height), Optional.of(weight)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .omitNullValues() // .add("id", id.orElse(null)) // .add("firstName", firstName) // .add("lastName", lastName) // .add("birthDate", birthDate) // .add("height", height.orElse(null)) // .add("weight", weight.orElse(null)) // .toString(); // } // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Team.java // public class Team { // // public final Optional<Long> id; // public final String name; // public final Division division; // // public Team(Optional<Long> id, String name, Division division) { // this.id = id; // this.name = name; // this.division = division; // } // // public Team(String name, Division division) { // this.name = name; // this.division = division; // this.id = Optional.empty(); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("id", id) // .add("name", name) // .add("division", division) // .toString(); // } // } // Path: src/test/java/com/github/arteam/jdit/DBIComplexSqlObjectTest.java import com.github.arteam.jdit.annotations.DataSet; import com.github.arteam.jdit.annotations.TestedSqlObject; import com.github.arteam.jdit.domain.TeamSqlObject; import com.github.arteam.jdit.domain.entity.Division; import com.github.arteam.jdit.domain.entity.Player; import com.github.arteam.jdit.domain.entity.Team; import com.google.common.collect.ImmutableList; import org.joda.time.format.ISODateTimeFormat; import org.junit.Test; import org.junit.runner.RunWith; import java.util.Date; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; package com.github.arteam.jdit; @RunWith(DBIRunner.class) @DataSet("teamDao/insert-divisions.sql") public class DBIComplexSqlObjectTest { @TestedSqlObject
TeamSqlObject teamSqlObject;
arteam/jdit
src/test/java/com/github/arteam/jdit/DBIComplexSqlObjectTest.java
// Path: src/test/java/com/github/arteam/jdit/domain/TeamSqlObject.java // @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) // public interface TeamSqlObject { // // @CreateSqlObject // PlayerSqlObject playerDao(); // // @SqlUpdate("insert into teams(name, division) values (:name, :division)") // @GetGeneratedKeys // long createTeam(@Bind("name") String name, @Bind("division") Division division); // // @SqlUpdate("insert into roster(team_id, player_id) values (:team_id, :player_id)") // void addPlayerToTeam(@Bind("team_id") long teamId, @Bind("player_id") long playerId); // // @Transaction // default void addTeam(Team team, List<Player> players) { // long teamId = createTeam(team.name, team.division); // for (Player player : players) { // long playerId = playerDao().createPlayer(player); // addPlayerToTeam(teamId, playerId); // } // } // // @SqlQuery("select * from players p " + // "inner join roster r on r.player_id=p.id " + // "inner join teams t on r.team_id=t.id " + // "where t.name = :team_name " + // "order by p.last_name") // List<Player> getPlayers(@Bind("team_name") String teamName); // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Division.java // public enum Division { // PACIFIC, // CENTRAL, // METROPOLITAN, // ATLANTIC // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Player.java // public class Player { // // public final Optional<Long> id; // public final String firstName; // public final String lastName; // public final Date birthDate; // public final Optional<Integer> height; // public final Optional<Integer> weight; // // public Player(Optional<Long> id, String firstName, String lastName, Date birthDate, // Optional<Integer> height, Optional<Integer> weight) { // this.id = id; // this.firstName = firstName; // this.lastName = lastName; // this.birthDate = birthDate; // this.height = height; // this.weight = weight; // } // // public Player(String firstName, String lastName, Date birthDate, int height, int weight) { // this(Optional.<Long>empty(), firstName, lastName, birthDate, Optional.of(height), Optional.of(weight)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .omitNullValues() // .add("id", id.orElse(null)) // .add("firstName", firstName) // .add("lastName", lastName) // .add("birthDate", birthDate) // .add("height", height.orElse(null)) // .add("weight", weight.orElse(null)) // .toString(); // } // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Team.java // public class Team { // // public final Optional<Long> id; // public final String name; // public final Division division; // // public Team(Optional<Long> id, String name, Division division) { // this.id = id; // this.name = name; // this.division = division; // } // // public Team(String name, Division division) { // this.name = name; // this.division = division; // this.id = Optional.empty(); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("id", id) // .add("name", name) // .add("division", division) // .toString(); // } // }
import com.github.arteam.jdit.annotations.DataSet; import com.github.arteam.jdit.annotations.TestedSqlObject; import com.github.arteam.jdit.domain.TeamSqlObject; import com.github.arteam.jdit.domain.entity.Division; import com.github.arteam.jdit.domain.entity.Player; import com.github.arteam.jdit.domain.entity.Team; import com.google.common.collect.ImmutableList; import org.joda.time.format.ISODateTimeFormat; import org.junit.Test; import org.junit.runner.RunWith; import java.util.Date; import java.util.List; import static org.assertj.core.api.Assertions.assertThat;
package com.github.arteam.jdit; @RunWith(DBIRunner.class) @DataSet("teamDao/insert-divisions.sql") public class DBIComplexSqlObjectTest { @TestedSqlObject TeamSqlObject teamSqlObject; @Test public void testBulkInsert() throws Exception {
// Path: src/test/java/com/github/arteam/jdit/domain/TeamSqlObject.java // @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) // public interface TeamSqlObject { // // @CreateSqlObject // PlayerSqlObject playerDao(); // // @SqlUpdate("insert into teams(name, division) values (:name, :division)") // @GetGeneratedKeys // long createTeam(@Bind("name") String name, @Bind("division") Division division); // // @SqlUpdate("insert into roster(team_id, player_id) values (:team_id, :player_id)") // void addPlayerToTeam(@Bind("team_id") long teamId, @Bind("player_id") long playerId); // // @Transaction // default void addTeam(Team team, List<Player> players) { // long teamId = createTeam(team.name, team.division); // for (Player player : players) { // long playerId = playerDao().createPlayer(player); // addPlayerToTeam(teamId, playerId); // } // } // // @SqlQuery("select * from players p " + // "inner join roster r on r.player_id=p.id " + // "inner join teams t on r.team_id=t.id " + // "where t.name = :team_name " + // "order by p.last_name") // List<Player> getPlayers(@Bind("team_name") String teamName); // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Division.java // public enum Division { // PACIFIC, // CENTRAL, // METROPOLITAN, // ATLANTIC // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Player.java // public class Player { // // public final Optional<Long> id; // public final String firstName; // public final String lastName; // public final Date birthDate; // public final Optional<Integer> height; // public final Optional<Integer> weight; // // public Player(Optional<Long> id, String firstName, String lastName, Date birthDate, // Optional<Integer> height, Optional<Integer> weight) { // this.id = id; // this.firstName = firstName; // this.lastName = lastName; // this.birthDate = birthDate; // this.height = height; // this.weight = weight; // } // // public Player(String firstName, String lastName, Date birthDate, int height, int weight) { // this(Optional.<Long>empty(), firstName, lastName, birthDate, Optional.of(height), Optional.of(weight)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .omitNullValues() // .add("id", id.orElse(null)) // .add("firstName", firstName) // .add("lastName", lastName) // .add("birthDate", birthDate) // .add("height", height.orElse(null)) // .add("weight", weight.orElse(null)) // .toString(); // } // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Team.java // public class Team { // // public final Optional<Long> id; // public final String name; // public final Division division; // // public Team(Optional<Long> id, String name, Division division) { // this.id = id; // this.name = name; // this.division = division; // } // // public Team(String name, Division division) { // this.name = name; // this.division = division; // this.id = Optional.empty(); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("id", id) // .add("name", name) // .add("division", division) // .toString(); // } // } // Path: src/test/java/com/github/arteam/jdit/DBIComplexSqlObjectTest.java import com.github.arteam.jdit.annotations.DataSet; import com.github.arteam.jdit.annotations.TestedSqlObject; import com.github.arteam.jdit.domain.TeamSqlObject; import com.github.arteam.jdit.domain.entity.Division; import com.github.arteam.jdit.domain.entity.Player; import com.github.arteam.jdit.domain.entity.Team; import com.google.common.collect.ImmutableList; import org.joda.time.format.ISODateTimeFormat; import org.junit.Test; import org.junit.runner.RunWith; import java.util.Date; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; package com.github.arteam.jdit; @RunWith(DBIRunner.class) @DataSet("teamDao/insert-divisions.sql") public class DBIComplexSqlObjectTest { @TestedSqlObject TeamSqlObject teamSqlObject; @Test public void testBulkInsert() throws Exception {
teamSqlObject.addTeam(new Team("St. Louis", Division.CENTRAL), ImmutableList.of(
arteam/jdit
src/test/java/com/github/arteam/jdit/DBIComplexSqlObjectTest.java
// Path: src/test/java/com/github/arteam/jdit/domain/TeamSqlObject.java // @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) // public interface TeamSqlObject { // // @CreateSqlObject // PlayerSqlObject playerDao(); // // @SqlUpdate("insert into teams(name, division) values (:name, :division)") // @GetGeneratedKeys // long createTeam(@Bind("name") String name, @Bind("division") Division division); // // @SqlUpdate("insert into roster(team_id, player_id) values (:team_id, :player_id)") // void addPlayerToTeam(@Bind("team_id") long teamId, @Bind("player_id") long playerId); // // @Transaction // default void addTeam(Team team, List<Player> players) { // long teamId = createTeam(team.name, team.division); // for (Player player : players) { // long playerId = playerDao().createPlayer(player); // addPlayerToTeam(teamId, playerId); // } // } // // @SqlQuery("select * from players p " + // "inner join roster r on r.player_id=p.id " + // "inner join teams t on r.team_id=t.id " + // "where t.name = :team_name " + // "order by p.last_name") // List<Player> getPlayers(@Bind("team_name") String teamName); // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Division.java // public enum Division { // PACIFIC, // CENTRAL, // METROPOLITAN, // ATLANTIC // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Player.java // public class Player { // // public final Optional<Long> id; // public final String firstName; // public final String lastName; // public final Date birthDate; // public final Optional<Integer> height; // public final Optional<Integer> weight; // // public Player(Optional<Long> id, String firstName, String lastName, Date birthDate, // Optional<Integer> height, Optional<Integer> weight) { // this.id = id; // this.firstName = firstName; // this.lastName = lastName; // this.birthDate = birthDate; // this.height = height; // this.weight = weight; // } // // public Player(String firstName, String lastName, Date birthDate, int height, int weight) { // this(Optional.<Long>empty(), firstName, lastName, birthDate, Optional.of(height), Optional.of(weight)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .omitNullValues() // .add("id", id.orElse(null)) // .add("firstName", firstName) // .add("lastName", lastName) // .add("birthDate", birthDate) // .add("height", height.orElse(null)) // .add("weight", weight.orElse(null)) // .toString(); // } // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Team.java // public class Team { // // public final Optional<Long> id; // public final String name; // public final Division division; // // public Team(Optional<Long> id, String name, Division division) { // this.id = id; // this.name = name; // this.division = division; // } // // public Team(String name, Division division) { // this.name = name; // this.division = division; // this.id = Optional.empty(); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("id", id) // .add("name", name) // .add("division", division) // .toString(); // } // }
import com.github.arteam.jdit.annotations.DataSet; import com.github.arteam.jdit.annotations.TestedSqlObject; import com.github.arteam.jdit.domain.TeamSqlObject; import com.github.arteam.jdit.domain.entity.Division; import com.github.arteam.jdit.domain.entity.Player; import com.github.arteam.jdit.domain.entity.Team; import com.google.common.collect.ImmutableList; import org.joda.time.format.ISODateTimeFormat; import org.junit.Test; import org.junit.runner.RunWith; import java.util.Date; import java.util.List; import static org.assertj.core.api.Assertions.assertThat;
package com.github.arteam.jdit; @RunWith(DBIRunner.class) @DataSet("teamDao/insert-divisions.sql") public class DBIComplexSqlObjectTest { @TestedSqlObject TeamSqlObject teamSqlObject; @Test public void testBulkInsert() throws Exception {
// Path: src/test/java/com/github/arteam/jdit/domain/TeamSqlObject.java // @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) // public interface TeamSqlObject { // // @CreateSqlObject // PlayerSqlObject playerDao(); // // @SqlUpdate("insert into teams(name, division) values (:name, :division)") // @GetGeneratedKeys // long createTeam(@Bind("name") String name, @Bind("division") Division division); // // @SqlUpdate("insert into roster(team_id, player_id) values (:team_id, :player_id)") // void addPlayerToTeam(@Bind("team_id") long teamId, @Bind("player_id") long playerId); // // @Transaction // default void addTeam(Team team, List<Player> players) { // long teamId = createTeam(team.name, team.division); // for (Player player : players) { // long playerId = playerDao().createPlayer(player); // addPlayerToTeam(teamId, playerId); // } // } // // @SqlQuery("select * from players p " + // "inner join roster r on r.player_id=p.id " + // "inner join teams t on r.team_id=t.id " + // "where t.name = :team_name " + // "order by p.last_name") // List<Player> getPlayers(@Bind("team_name") String teamName); // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Division.java // public enum Division { // PACIFIC, // CENTRAL, // METROPOLITAN, // ATLANTIC // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Player.java // public class Player { // // public final Optional<Long> id; // public final String firstName; // public final String lastName; // public final Date birthDate; // public final Optional<Integer> height; // public final Optional<Integer> weight; // // public Player(Optional<Long> id, String firstName, String lastName, Date birthDate, // Optional<Integer> height, Optional<Integer> weight) { // this.id = id; // this.firstName = firstName; // this.lastName = lastName; // this.birthDate = birthDate; // this.height = height; // this.weight = weight; // } // // public Player(String firstName, String lastName, Date birthDate, int height, int weight) { // this(Optional.<Long>empty(), firstName, lastName, birthDate, Optional.of(height), Optional.of(weight)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .omitNullValues() // .add("id", id.orElse(null)) // .add("firstName", firstName) // .add("lastName", lastName) // .add("birthDate", birthDate) // .add("height", height.orElse(null)) // .add("weight", weight.orElse(null)) // .toString(); // } // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Team.java // public class Team { // // public final Optional<Long> id; // public final String name; // public final Division division; // // public Team(Optional<Long> id, String name, Division division) { // this.id = id; // this.name = name; // this.division = division; // } // // public Team(String name, Division division) { // this.name = name; // this.division = division; // this.id = Optional.empty(); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("id", id) // .add("name", name) // .add("division", division) // .toString(); // } // } // Path: src/test/java/com/github/arteam/jdit/DBIComplexSqlObjectTest.java import com.github.arteam.jdit.annotations.DataSet; import com.github.arteam.jdit.annotations.TestedSqlObject; import com.github.arteam.jdit.domain.TeamSqlObject; import com.github.arteam.jdit.domain.entity.Division; import com.github.arteam.jdit.domain.entity.Player; import com.github.arteam.jdit.domain.entity.Team; import com.google.common.collect.ImmutableList; import org.joda.time.format.ISODateTimeFormat; import org.junit.Test; import org.junit.runner.RunWith; import java.util.Date; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; package com.github.arteam.jdit; @RunWith(DBIRunner.class) @DataSet("teamDao/insert-divisions.sql") public class DBIComplexSqlObjectTest { @TestedSqlObject TeamSqlObject teamSqlObject; @Test public void testBulkInsert() throws Exception {
teamSqlObject.addTeam(new Team("St. Louis", Division.CENTRAL), ImmutableList.of(
arteam/jdit
src/test/java/com/github/arteam/jdit/DBIComplexSqlObjectTest.java
// Path: src/test/java/com/github/arteam/jdit/domain/TeamSqlObject.java // @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) // public interface TeamSqlObject { // // @CreateSqlObject // PlayerSqlObject playerDao(); // // @SqlUpdate("insert into teams(name, division) values (:name, :division)") // @GetGeneratedKeys // long createTeam(@Bind("name") String name, @Bind("division") Division division); // // @SqlUpdate("insert into roster(team_id, player_id) values (:team_id, :player_id)") // void addPlayerToTeam(@Bind("team_id") long teamId, @Bind("player_id") long playerId); // // @Transaction // default void addTeam(Team team, List<Player> players) { // long teamId = createTeam(team.name, team.division); // for (Player player : players) { // long playerId = playerDao().createPlayer(player); // addPlayerToTeam(teamId, playerId); // } // } // // @SqlQuery("select * from players p " + // "inner join roster r on r.player_id=p.id " + // "inner join teams t on r.team_id=t.id " + // "where t.name = :team_name " + // "order by p.last_name") // List<Player> getPlayers(@Bind("team_name") String teamName); // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Division.java // public enum Division { // PACIFIC, // CENTRAL, // METROPOLITAN, // ATLANTIC // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Player.java // public class Player { // // public final Optional<Long> id; // public final String firstName; // public final String lastName; // public final Date birthDate; // public final Optional<Integer> height; // public final Optional<Integer> weight; // // public Player(Optional<Long> id, String firstName, String lastName, Date birthDate, // Optional<Integer> height, Optional<Integer> weight) { // this.id = id; // this.firstName = firstName; // this.lastName = lastName; // this.birthDate = birthDate; // this.height = height; // this.weight = weight; // } // // public Player(String firstName, String lastName, Date birthDate, int height, int weight) { // this(Optional.<Long>empty(), firstName, lastName, birthDate, Optional.of(height), Optional.of(weight)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .omitNullValues() // .add("id", id.orElse(null)) // .add("firstName", firstName) // .add("lastName", lastName) // .add("birthDate", birthDate) // .add("height", height.orElse(null)) // .add("weight", weight.orElse(null)) // .toString(); // } // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Team.java // public class Team { // // public final Optional<Long> id; // public final String name; // public final Division division; // // public Team(Optional<Long> id, String name, Division division) { // this.id = id; // this.name = name; // this.division = division; // } // // public Team(String name, Division division) { // this.name = name; // this.division = division; // this.id = Optional.empty(); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("id", id) // .add("name", name) // .add("division", division) // .toString(); // } // }
import com.github.arteam.jdit.annotations.DataSet; import com.github.arteam.jdit.annotations.TestedSqlObject; import com.github.arteam.jdit.domain.TeamSqlObject; import com.github.arteam.jdit.domain.entity.Division; import com.github.arteam.jdit.domain.entity.Player; import com.github.arteam.jdit.domain.entity.Team; import com.google.common.collect.ImmutableList; import org.joda.time.format.ISODateTimeFormat; import org.junit.Test; import org.junit.runner.RunWith; import java.util.Date; import java.util.List; import static org.assertj.core.api.Assertions.assertThat;
package com.github.arteam.jdit; @RunWith(DBIRunner.class) @DataSet("teamDao/insert-divisions.sql") public class DBIComplexSqlObjectTest { @TestedSqlObject TeamSqlObject teamSqlObject; @Test public void testBulkInsert() throws Exception { teamSqlObject.addTeam(new Team("St. Louis", Division.CENTRAL), ImmutableList.of(
// Path: src/test/java/com/github/arteam/jdit/domain/TeamSqlObject.java // @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) // public interface TeamSqlObject { // // @CreateSqlObject // PlayerSqlObject playerDao(); // // @SqlUpdate("insert into teams(name, division) values (:name, :division)") // @GetGeneratedKeys // long createTeam(@Bind("name") String name, @Bind("division") Division division); // // @SqlUpdate("insert into roster(team_id, player_id) values (:team_id, :player_id)") // void addPlayerToTeam(@Bind("team_id") long teamId, @Bind("player_id") long playerId); // // @Transaction // default void addTeam(Team team, List<Player> players) { // long teamId = createTeam(team.name, team.division); // for (Player player : players) { // long playerId = playerDao().createPlayer(player); // addPlayerToTeam(teamId, playerId); // } // } // // @SqlQuery("select * from players p " + // "inner join roster r on r.player_id=p.id " + // "inner join teams t on r.team_id=t.id " + // "where t.name = :team_name " + // "order by p.last_name") // List<Player> getPlayers(@Bind("team_name") String teamName); // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Division.java // public enum Division { // PACIFIC, // CENTRAL, // METROPOLITAN, // ATLANTIC // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Player.java // public class Player { // // public final Optional<Long> id; // public final String firstName; // public final String lastName; // public final Date birthDate; // public final Optional<Integer> height; // public final Optional<Integer> weight; // // public Player(Optional<Long> id, String firstName, String lastName, Date birthDate, // Optional<Integer> height, Optional<Integer> weight) { // this.id = id; // this.firstName = firstName; // this.lastName = lastName; // this.birthDate = birthDate; // this.height = height; // this.weight = weight; // } // // public Player(String firstName, String lastName, Date birthDate, int height, int weight) { // this(Optional.<Long>empty(), firstName, lastName, birthDate, Optional.of(height), Optional.of(weight)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .omitNullValues() // .add("id", id.orElse(null)) // .add("firstName", firstName) // .add("lastName", lastName) // .add("birthDate", birthDate) // .add("height", height.orElse(null)) // .add("weight", weight.orElse(null)) // .toString(); // } // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Team.java // public class Team { // // public final Optional<Long> id; // public final String name; // public final Division division; // // public Team(Optional<Long> id, String name, Division division) { // this.id = id; // this.name = name; // this.division = division; // } // // public Team(String name, Division division) { // this.name = name; // this.division = division; // this.id = Optional.empty(); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("id", id) // .add("name", name) // .add("division", division) // .toString(); // } // } // Path: src/test/java/com/github/arteam/jdit/DBIComplexSqlObjectTest.java import com.github.arteam.jdit.annotations.DataSet; import com.github.arteam.jdit.annotations.TestedSqlObject; import com.github.arteam.jdit.domain.TeamSqlObject; import com.github.arteam.jdit.domain.entity.Division; import com.github.arteam.jdit.domain.entity.Player; import com.github.arteam.jdit.domain.entity.Team; import com.google.common.collect.ImmutableList; import org.joda.time.format.ISODateTimeFormat; import org.junit.Test; import org.junit.runner.RunWith; import java.util.Date; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; package com.github.arteam.jdit; @RunWith(DBIRunner.class) @DataSet("teamDao/insert-divisions.sql") public class DBIComplexSqlObjectTest { @TestedSqlObject TeamSqlObject teamSqlObject; @Test public void testBulkInsert() throws Exception { teamSqlObject.addTeam(new Team("St. Louis", Division.CENTRAL), ImmutableList.of(
new Player("Vladimir", "Tarasenko", date("1991-04-01"), 184, 90),
arteam/jdit
src/test/java/com/github/arteam/jdit/domain/AdvancedPlayerSqlObject.java
// Path: src/test/java/com/github/arteam/jdit/domain/entity/Player.java // public class Player { // // public final Optional<Long> id; // public final String firstName; // public final String lastName; // public final Date birthDate; // public final Optional<Integer> height; // public final Optional<Integer> weight; // // public Player(Optional<Long> id, String firstName, String lastName, Date birthDate, // Optional<Integer> height, Optional<Integer> weight) { // this.id = id; // this.firstName = firstName; // this.lastName = lastName; // this.birthDate = birthDate; // this.height = height; // this.weight = weight; // } // // public Player(String firstName, String lastName, Date birthDate, int height, int weight) { // this(Optional.<Long>empty(), firstName, lastName, birthDate, Optional.of(height), Optional.of(weight)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .omitNullValues() // .add("id", id.orElse(null)) // .add("firstName", firstName) // .add("lastName", lastName) // .add("birthDate", birthDate) // .add("height", height.orElse(null)) // .add("weight", weight.orElse(null)) // .toString(); // } // }
import com.github.arteam.jdit.domain.entity.Player; import org.jdbi.v3.core.mapper.RowMapper; import org.jdbi.v3.core.statement.StatementContext; import org.jdbi.v3.sqlobject.config.RegisterRowMapper; import org.jdbi.v3.sqlobject.customizer.Bind; import org.jdbi.v3.sqlobject.customizer.Define; import org.jdbi.v3.sqlobject.statement.SqlQuery; import org.jdbi.v3.stringtemplate4.UseStringTemplateSqlLocator; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.Optional;
package com.github.arteam.jdit.domain; /** * Date: 1/25/15 * Time: 11:26 PM * * @author Artem Prigoda */ @RegisterRowMapper(AdvancedPlayerSqlObject.PlayerMapper.class) @UseStringTemplateSqlLocator public interface AdvancedPlayerSqlObject { @SqlQuery
// Path: src/test/java/com/github/arteam/jdit/domain/entity/Player.java // public class Player { // // public final Optional<Long> id; // public final String firstName; // public final String lastName; // public final Date birthDate; // public final Optional<Integer> height; // public final Optional<Integer> weight; // // public Player(Optional<Long> id, String firstName, String lastName, Date birthDate, // Optional<Integer> height, Optional<Integer> weight) { // this.id = id; // this.firstName = firstName; // this.lastName = lastName; // this.birthDate = birthDate; // this.height = height; // this.weight = weight; // } // // public Player(String firstName, String lastName, Date birthDate, int height, int weight) { // this(Optional.<Long>empty(), firstName, lastName, birthDate, Optional.of(height), Optional.of(weight)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .omitNullValues() // .add("id", id.orElse(null)) // .add("firstName", firstName) // .add("lastName", lastName) // .add("birthDate", birthDate) // .add("height", height.orElse(null)) // .add("weight", weight.orElse(null)) // .toString(); // } // } // Path: src/test/java/com/github/arteam/jdit/domain/AdvancedPlayerSqlObject.java import com.github.arteam.jdit.domain.entity.Player; import org.jdbi.v3.core.mapper.RowMapper; import org.jdbi.v3.core.statement.StatementContext; import org.jdbi.v3.sqlobject.config.RegisterRowMapper; import org.jdbi.v3.sqlobject.customizer.Bind; import org.jdbi.v3.sqlobject.customizer.Define; import org.jdbi.v3.sqlobject.statement.SqlQuery; import org.jdbi.v3.stringtemplate4.UseStringTemplateSqlLocator; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.Optional; package com.github.arteam.jdit.domain; /** * Date: 1/25/15 * Time: 11:26 PM * * @author Artem Prigoda */ @RegisterRowMapper(AdvancedPlayerSqlObject.PlayerMapper.class) @UseStringTemplateSqlLocator public interface AdvancedPlayerSqlObject { @SqlQuery
List<Player> getPlayers(@Define("isFirstName") boolean isFirstName, @Bind("firstName") String firstName,
arteam/jdit
src/test/java/com/github/arteam/jdit/SqlLocatorTest.java
// Path: src/test/java/com/github/arteam/jdit/domain/AdvancedPlayerSqlObject.java // @RegisterRowMapper(AdvancedPlayerSqlObject.PlayerMapper.class) // @UseStringTemplateSqlLocator // public interface AdvancedPlayerSqlObject { // // @SqlQuery // List<Player> getPlayers(@Define("isFirstName") boolean isFirstName, @Bind("firstName") String firstName, // @Define("isFirstName") boolean isLastName, @Bind("lastName") String lastName, // @Define("isSort") boolean isSort, @Define("sortBy") String sortBy, // @Define("isSortDesc") boolean isSortDesc, // @Define("isLimit") boolean isLimit, @Define("limit") int limit, // @Define("isOffset") boolean isOffset, @Define("offset") int offset); // // class PlayerMapper implements RowMapper<Player> { // @Override // public Player map(ResultSet r, StatementContext ctx) throws SQLException { // int height = r.getInt("height"); // int weight = r.getInt("weight"); // return new Player(Optional.of(r.getLong("id")), r.getString("first_name"), r.getString("last_name"), // r.getTimestamp("birth_date"), // height != 0 ? Optional.of(height) : Optional.empty(), // weight != 0 ? Optional.of(weight) : Optional.empty()); // } // } // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Player.java // public class Player { // // public final Optional<Long> id; // public final String firstName; // public final String lastName; // public final Date birthDate; // public final Optional<Integer> height; // public final Optional<Integer> weight; // // public Player(Optional<Long> id, String firstName, String lastName, Date birthDate, // Optional<Integer> height, Optional<Integer> weight) { // this.id = id; // this.firstName = firstName; // this.lastName = lastName; // this.birthDate = birthDate; // this.height = height; // this.weight = weight; // } // // public Player(String firstName, String lastName, Date birthDate, int height, int weight) { // this(Optional.<Long>empty(), firstName, lastName, birthDate, Optional.of(height), Optional.of(weight)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .omitNullValues() // .add("id", id.orElse(null)) // .add("firstName", firstName) // .add("lastName", lastName) // .add("birthDate", birthDate) // .add("height", height.orElse(null)) // .add("weight", weight.orElse(null)) // .toString(); // } // }
import com.github.arteam.jdit.annotations.DataSet; import com.github.arteam.jdit.annotations.JditProperties; import com.github.arteam.jdit.annotations.TestedSqlObject; import com.github.arteam.jdit.domain.AdvancedPlayerSqlObject; import com.github.arteam.jdit.domain.entity.Player; import org.junit.Test; import org.junit.runner.RunWith; import java.util.List; import static org.assertj.core.api.Assertions.assertThat;
package com.github.arteam.jdit; @RunWith(DBIRunner.class) @JditProperties("jdit-h2.properties") public class SqlLocatorTest { @TestedSqlObject
// Path: src/test/java/com/github/arteam/jdit/domain/AdvancedPlayerSqlObject.java // @RegisterRowMapper(AdvancedPlayerSqlObject.PlayerMapper.class) // @UseStringTemplateSqlLocator // public interface AdvancedPlayerSqlObject { // // @SqlQuery // List<Player> getPlayers(@Define("isFirstName") boolean isFirstName, @Bind("firstName") String firstName, // @Define("isFirstName") boolean isLastName, @Bind("lastName") String lastName, // @Define("isSort") boolean isSort, @Define("sortBy") String sortBy, // @Define("isSortDesc") boolean isSortDesc, // @Define("isLimit") boolean isLimit, @Define("limit") int limit, // @Define("isOffset") boolean isOffset, @Define("offset") int offset); // // class PlayerMapper implements RowMapper<Player> { // @Override // public Player map(ResultSet r, StatementContext ctx) throws SQLException { // int height = r.getInt("height"); // int weight = r.getInt("weight"); // return new Player(Optional.of(r.getLong("id")), r.getString("first_name"), r.getString("last_name"), // r.getTimestamp("birth_date"), // height != 0 ? Optional.of(height) : Optional.empty(), // weight != 0 ? Optional.of(weight) : Optional.empty()); // } // } // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Player.java // public class Player { // // public final Optional<Long> id; // public final String firstName; // public final String lastName; // public final Date birthDate; // public final Optional<Integer> height; // public final Optional<Integer> weight; // // public Player(Optional<Long> id, String firstName, String lastName, Date birthDate, // Optional<Integer> height, Optional<Integer> weight) { // this.id = id; // this.firstName = firstName; // this.lastName = lastName; // this.birthDate = birthDate; // this.height = height; // this.weight = weight; // } // // public Player(String firstName, String lastName, Date birthDate, int height, int weight) { // this(Optional.<Long>empty(), firstName, lastName, birthDate, Optional.of(height), Optional.of(weight)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .omitNullValues() // .add("id", id.orElse(null)) // .add("firstName", firstName) // .add("lastName", lastName) // .add("birthDate", birthDate) // .add("height", height.orElse(null)) // .add("weight", weight.orElse(null)) // .toString(); // } // } // Path: src/test/java/com/github/arteam/jdit/SqlLocatorTest.java import com.github.arteam.jdit.annotations.DataSet; import com.github.arteam.jdit.annotations.JditProperties; import com.github.arteam.jdit.annotations.TestedSqlObject; import com.github.arteam.jdit.domain.AdvancedPlayerSqlObject; import com.github.arteam.jdit.domain.entity.Player; import org.junit.Test; import org.junit.runner.RunWith; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; package com.github.arteam.jdit; @RunWith(DBIRunner.class) @JditProperties("jdit-h2.properties") public class SqlLocatorTest { @TestedSqlObject
AdvancedPlayerSqlObject playerDao;
arteam/jdit
src/test/java/com/github/arteam/jdit/SqlLocatorTest.java
// Path: src/test/java/com/github/arteam/jdit/domain/AdvancedPlayerSqlObject.java // @RegisterRowMapper(AdvancedPlayerSqlObject.PlayerMapper.class) // @UseStringTemplateSqlLocator // public interface AdvancedPlayerSqlObject { // // @SqlQuery // List<Player> getPlayers(@Define("isFirstName") boolean isFirstName, @Bind("firstName") String firstName, // @Define("isFirstName") boolean isLastName, @Bind("lastName") String lastName, // @Define("isSort") boolean isSort, @Define("sortBy") String sortBy, // @Define("isSortDesc") boolean isSortDesc, // @Define("isLimit") boolean isLimit, @Define("limit") int limit, // @Define("isOffset") boolean isOffset, @Define("offset") int offset); // // class PlayerMapper implements RowMapper<Player> { // @Override // public Player map(ResultSet r, StatementContext ctx) throws SQLException { // int height = r.getInt("height"); // int weight = r.getInt("weight"); // return new Player(Optional.of(r.getLong("id")), r.getString("first_name"), r.getString("last_name"), // r.getTimestamp("birth_date"), // height != 0 ? Optional.of(height) : Optional.empty(), // weight != 0 ? Optional.of(weight) : Optional.empty()); // } // } // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Player.java // public class Player { // // public final Optional<Long> id; // public final String firstName; // public final String lastName; // public final Date birthDate; // public final Optional<Integer> height; // public final Optional<Integer> weight; // // public Player(Optional<Long> id, String firstName, String lastName, Date birthDate, // Optional<Integer> height, Optional<Integer> weight) { // this.id = id; // this.firstName = firstName; // this.lastName = lastName; // this.birthDate = birthDate; // this.height = height; // this.weight = weight; // } // // public Player(String firstName, String lastName, Date birthDate, int height, int weight) { // this(Optional.<Long>empty(), firstName, lastName, birthDate, Optional.of(height), Optional.of(weight)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .omitNullValues() // .add("id", id.orElse(null)) // .add("firstName", firstName) // .add("lastName", lastName) // .add("birthDate", birthDate) // .add("height", height.orElse(null)) // .add("weight", weight.orElse(null)) // .toString(); // } // }
import com.github.arteam.jdit.annotations.DataSet; import com.github.arteam.jdit.annotations.JditProperties; import com.github.arteam.jdit.annotations.TestedSqlObject; import com.github.arteam.jdit.domain.AdvancedPlayerSqlObject; import com.github.arteam.jdit.domain.entity.Player; import org.junit.Test; import org.junit.runner.RunWith; import java.util.List; import static org.assertj.core.api.Assertions.assertThat;
package com.github.arteam.jdit; @RunWith(DBIRunner.class) @JditProperties("jdit-h2.properties") public class SqlLocatorTest { @TestedSqlObject AdvancedPlayerSqlObject playerDao; @Test @DataSet("playerDao/players.sql") public void getPlayerBySeveralAtributes() {
// Path: src/test/java/com/github/arteam/jdit/domain/AdvancedPlayerSqlObject.java // @RegisterRowMapper(AdvancedPlayerSqlObject.PlayerMapper.class) // @UseStringTemplateSqlLocator // public interface AdvancedPlayerSqlObject { // // @SqlQuery // List<Player> getPlayers(@Define("isFirstName") boolean isFirstName, @Bind("firstName") String firstName, // @Define("isFirstName") boolean isLastName, @Bind("lastName") String lastName, // @Define("isSort") boolean isSort, @Define("sortBy") String sortBy, // @Define("isSortDesc") boolean isSortDesc, // @Define("isLimit") boolean isLimit, @Define("limit") int limit, // @Define("isOffset") boolean isOffset, @Define("offset") int offset); // // class PlayerMapper implements RowMapper<Player> { // @Override // public Player map(ResultSet r, StatementContext ctx) throws SQLException { // int height = r.getInt("height"); // int weight = r.getInt("weight"); // return new Player(Optional.of(r.getLong("id")), r.getString("first_name"), r.getString("last_name"), // r.getTimestamp("birth_date"), // height != 0 ? Optional.of(height) : Optional.empty(), // weight != 0 ? Optional.of(weight) : Optional.empty()); // } // } // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Player.java // public class Player { // // public final Optional<Long> id; // public final String firstName; // public final String lastName; // public final Date birthDate; // public final Optional<Integer> height; // public final Optional<Integer> weight; // // public Player(Optional<Long> id, String firstName, String lastName, Date birthDate, // Optional<Integer> height, Optional<Integer> weight) { // this.id = id; // this.firstName = firstName; // this.lastName = lastName; // this.birthDate = birthDate; // this.height = height; // this.weight = weight; // } // // public Player(String firstName, String lastName, Date birthDate, int height, int weight) { // this(Optional.<Long>empty(), firstName, lastName, birthDate, Optional.of(height), Optional.of(weight)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .omitNullValues() // .add("id", id.orElse(null)) // .add("firstName", firstName) // .add("lastName", lastName) // .add("birthDate", birthDate) // .add("height", height.orElse(null)) // .add("weight", weight.orElse(null)) // .toString(); // } // } // Path: src/test/java/com/github/arteam/jdit/SqlLocatorTest.java import com.github.arteam.jdit.annotations.DataSet; import com.github.arteam.jdit.annotations.JditProperties; import com.github.arteam.jdit.annotations.TestedSqlObject; import com.github.arteam.jdit.domain.AdvancedPlayerSqlObject; import com.github.arteam.jdit.domain.entity.Player; import org.junit.Test; import org.junit.runner.RunWith; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; package com.github.arteam.jdit; @RunWith(DBIRunner.class) @JditProperties("jdit-h2.properties") public class SqlLocatorTest { @TestedSqlObject AdvancedPlayerSqlObject playerDao; @Test @DataSet("playerDao/players.sql") public void getPlayerBySeveralAtributes() {
List<Player> players = playerDao.getPlayers(true, "John", true, "Tavares", true, "last_name", true,
arteam/jdit
src/test/java/com/github/arteam/jdit/TestJodaTime.java
// Path: src/test/java/com/github/arteam/jdit/domain/PlayerSqlObject.java // @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) // public interface PlayerSqlObject { // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName, // @Bind("birth_date") Date birthDate, @Bind("height") int height, // @Bind("weight") int weight); // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@PlayerBinder Player player); // // @SqlQuery("select last_name from players order by last_name") // List<String> getLastNames(); // // @SqlQuery("select count(*) from players where extract(year from birth_date) = :year") // int getAmountPlayersBornInYear(@Bind("year") int year); // // @SqlQuery("select * from players where birth_date > :date") // List<Player> getPlayersBornAfter(@Bind("date") DateTime date); // // @SqlQuery("select birth_date from players where first_name=:first_name and last_name=:last_name") // DateTime getPlayerBirthDate(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select distinct extract(year from birth_date) player_year from players order by player_year") // Set<Integer> getBornYears(); // // @SqlQuery("select * from players where first_name=:first_name and last_name=:last_name") // Optional<Player> findPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select * from players where weight <> :weight") // List<Player> getPlayersByWeight(@Bind("weight") Optional<Integer> weight); // // @SqlQuery("select first_name from players") // ImmutableSet<String> getFirstNames(); // // @Retention(RetentionPolicy.RUNTIME) // @Target({ElementType.PARAMETER}) // @SqlStatementCustomizingAnnotation(PlayerBinder.Factory.class) // @interface PlayerBinder { // // class Factory implements SqlStatementCustomizerFactory { // // @Override // public SqlStatementParameterCustomizer createForParameter(Annotation annotation, Class<?> sqlObjectType, // Method method, Parameter param, int index, // Type type) { // return (stmt, arg) -> { // Player p = (Player) arg; // stmt.bind("first_name", p.firstName); // stmt.bind("last_name", p.lastName); // stmt.bind("birth_date", p.birthDate); // stmt.bind("weight", p.weight); // stmt.bind("height", p.height); // }; // } // } // } // // class PlayerMapper implements RowMapper<Player> { // @Override // public Player map(ResultSet r, StatementContext ctx) throws SQLException { // int height = r.getInt("height"); // int weight = r.getInt("weight"); // return new Player(Optional.of(r.getLong("id")), r.getString("first_name"), r.getString("last_name"), // r.getTimestamp("birth_date"), // height != 0 ? Optional.of(height) : Optional.empty(), // weight != 0 ? Optional.of(weight) : Optional.empty()); // } // } // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Player.java // public class Player { // // public final Optional<Long> id; // public final String firstName; // public final String lastName; // public final Date birthDate; // public final Optional<Integer> height; // public final Optional<Integer> weight; // // public Player(Optional<Long> id, String firstName, String lastName, Date birthDate, // Optional<Integer> height, Optional<Integer> weight) { // this.id = id; // this.firstName = firstName; // this.lastName = lastName; // this.birthDate = birthDate; // this.height = height; // this.weight = weight; // } // // public Player(String firstName, String lastName, Date birthDate, int height, int weight) { // this(Optional.<Long>empty(), firstName, lastName, birthDate, Optional.of(height), Optional.of(weight)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .omitNullValues() // .add("id", id.orElse(null)) // .add("firstName", firstName) // .add("lastName", lastName) // .add("birthDate", birthDate) // .add("height", height.orElse(null)) // .add("weight", weight.orElse(null)) // .toString(); // } // }
import com.github.arteam.jdit.annotations.DataSet; import com.github.arteam.jdit.annotations.TestedSqlObject; import com.github.arteam.jdit.domain.PlayerSqlObject; import com.github.arteam.jdit.domain.entity.Player; import org.joda.time.DateTime; import org.joda.time.format.ISODateTimeFormat; import org.junit.Test; import org.junit.runner.RunWith; import java.util.List; import static org.assertj.core.api.Assertions.assertThat;
package com.github.arteam.jdit; @RunWith(DBIRunner.class) @DataSet("playerDao/players.sql") public class TestJodaTime { @TestedSqlObject
// Path: src/test/java/com/github/arteam/jdit/domain/PlayerSqlObject.java // @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) // public interface PlayerSqlObject { // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName, // @Bind("birth_date") Date birthDate, @Bind("height") int height, // @Bind("weight") int weight); // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@PlayerBinder Player player); // // @SqlQuery("select last_name from players order by last_name") // List<String> getLastNames(); // // @SqlQuery("select count(*) from players where extract(year from birth_date) = :year") // int getAmountPlayersBornInYear(@Bind("year") int year); // // @SqlQuery("select * from players where birth_date > :date") // List<Player> getPlayersBornAfter(@Bind("date") DateTime date); // // @SqlQuery("select birth_date from players where first_name=:first_name and last_name=:last_name") // DateTime getPlayerBirthDate(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select distinct extract(year from birth_date) player_year from players order by player_year") // Set<Integer> getBornYears(); // // @SqlQuery("select * from players where first_name=:first_name and last_name=:last_name") // Optional<Player> findPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select * from players where weight <> :weight") // List<Player> getPlayersByWeight(@Bind("weight") Optional<Integer> weight); // // @SqlQuery("select first_name from players") // ImmutableSet<String> getFirstNames(); // // @Retention(RetentionPolicy.RUNTIME) // @Target({ElementType.PARAMETER}) // @SqlStatementCustomizingAnnotation(PlayerBinder.Factory.class) // @interface PlayerBinder { // // class Factory implements SqlStatementCustomizerFactory { // // @Override // public SqlStatementParameterCustomizer createForParameter(Annotation annotation, Class<?> sqlObjectType, // Method method, Parameter param, int index, // Type type) { // return (stmt, arg) -> { // Player p = (Player) arg; // stmt.bind("first_name", p.firstName); // stmt.bind("last_name", p.lastName); // stmt.bind("birth_date", p.birthDate); // stmt.bind("weight", p.weight); // stmt.bind("height", p.height); // }; // } // } // } // // class PlayerMapper implements RowMapper<Player> { // @Override // public Player map(ResultSet r, StatementContext ctx) throws SQLException { // int height = r.getInt("height"); // int weight = r.getInt("weight"); // return new Player(Optional.of(r.getLong("id")), r.getString("first_name"), r.getString("last_name"), // r.getTimestamp("birth_date"), // height != 0 ? Optional.of(height) : Optional.empty(), // weight != 0 ? Optional.of(weight) : Optional.empty()); // } // } // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Player.java // public class Player { // // public final Optional<Long> id; // public final String firstName; // public final String lastName; // public final Date birthDate; // public final Optional<Integer> height; // public final Optional<Integer> weight; // // public Player(Optional<Long> id, String firstName, String lastName, Date birthDate, // Optional<Integer> height, Optional<Integer> weight) { // this.id = id; // this.firstName = firstName; // this.lastName = lastName; // this.birthDate = birthDate; // this.height = height; // this.weight = weight; // } // // public Player(String firstName, String lastName, Date birthDate, int height, int weight) { // this(Optional.<Long>empty(), firstName, lastName, birthDate, Optional.of(height), Optional.of(weight)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .omitNullValues() // .add("id", id.orElse(null)) // .add("firstName", firstName) // .add("lastName", lastName) // .add("birthDate", birthDate) // .add("height", height.orElse(null)) // .add("weight", weight.orElse(null)) // .toString(); // } // } // Path: src/test/java/com/github/arteam/jdit/TestJodaTime.java import com.github.arteam.jdit.annotations.DataSet; import com.github.arteam.jdit.annotations.TestedSqlObject; import com.github.arteam.jdit.domain.PlayerSqlObject; import com.github.arteam.jdit.domain.entity.Player; import org.joda.time.DateTime; import org.joda.time.format.ISODateTimeFormat; import org.junit.Test; import org.junit.runner.RunWith; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; package com.github.arteam.jdit; @RunWith(DBIRunner.class) @DataSet("playerDao/players.sql") public class TestJodaTime { @TestedSqlObject
PlayerSqlObject playerDao;
arteam/jdit
src/test/java/com/github/arteam/jdit/TestJodaTime.java
// Path: src/test/java/com/github/arteam/jdit/domain/PlayerSqlObject.java // @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) // public interface PlayerSqlObject { // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName, // @Bind("birth_date") Date birthDate, @Bind("height") int height, // @Bind("weight") int weight); // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@PlayerBinder Player player); // // @SqlQuery("select last_name from players order by last_name") // List<String> getLastNames(); // // @SqlQuery("select count(*) from players where extract(year from birth_date) = :year") // int getAmountPlayersBornInYear(@Bind("year") int year); // // @SqlQuery("select * from players where birth_date > :date") // List<Player> getPlayersBornAfter(@Bind("date") DateTime date); // // @SqlQuery("select birth_date from players where first_name=:first_name and last_name=:last_name") // DateTime getPlayerBirthDate(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select distinct extract(year from birth_date) player_year from players order by player_year") // Set<Integer> getBornYears(); // // @SqlQuery("select * from players where first_name=:first_name and last_name=:last_name") // Optional<Player> findPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select * from players where weight <> :weight") // List<Player> getPlayersByWeight(@Bind("weight") Optional<Integer> weight); // // @SqlQuery("select first_name from players") // ImmutableSet<String> getFirstNames(); // // @Retention(RetentionPolicy.RUNTIME) // @Target({ElementType.PARAMETER}) // @SqlStatementCustomizingAnnotation(PlayerBinder.Factory.class) // @interface PlayerBinder { // // class Factory implements SqlStatementCustomizerFactory { // // @Override // public SqlStatementParameterCustomizer createForParameter(Annotation annotation, Class<?> sqlObjectType, // Method method, Parameter param, int index, // Type type) { // return (stmt, arg) -> { // Player p = (Player) arg; // stmt.bind("first_name", p.firstName); // stmt.bind("last_name", p.lastName); // stmt.bind("birth_date", p.birthDate); // stmt.bind("weight", p.weight); // stmt.bind("height", p.height); // }; // } // } // } // // class PlayerMapper implements RowMapper<Player> { // @Override // public Player map(ResultSet r, StatementContext ctx) throws SQLException { // int height = r.getInt("height"); // int weight = r.getInt("weight"); // return new Player(Optional.of(r.getLong("id")), r.getString("first_name"), r.getString("last_name"), // r.getTimestamp("birth_date"), // height != 0 ? Optional.of(height) : Optional.empty(), // weight != 0 ? Optional.of(weight) : Optional.empty()); // } // } // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Player.java // public class Player { // // public final Optional<Long> id; // public final String firstName; // public final String lastName; // public final Date birthDate; // public final Optional<Integer> height; // public final Optional<Integer> weight; // // public Player(Optional<Long> id, String firstName, String lastName, Date birthDate, // Optional<Integer> height, Optional<Integer> weight) { // this.id = id; // this.firstName = firstName; // this.lastName = lastName; // this.birthDate = birthDate; // this.height = height; // this.weight = weight; // } // // public Player(String firstName, String lastName, Date birthDate, int height, int weight) { // this(Optional.<Long>empty(), firstName, lastName, birthDate, Optional.of(height), Optional.of(weight)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .omitNullValues() // .add("id", id.orElse(null)) // .add("firstName", firstName) // .add("lastName", lastName) // .add("birthDate", birthDate) // .add("height", height.orElse(null)) // .add("weight", weight.orElse(null)) // .toString(); // } // }
import com.github.arteam.jdit.annotations.DataSet; import com.github.arteam.jdit.annotations.TestedSqlObject; import com.github.arteam.jdit.domain.PlayerSqlObject; import com.github.arteam.jdit.domain.entity.Player; import org.joda.time.DateTime; import org.joda.time.format.ISODateTimeFormat; import org.junit.Test; import org.junit.runner.RunWith; import java.util.List; import static org.assertj.core.api.Assertions.assertThat;
package com.github.arteam.jdit; @RunWith(DBIRunner.class) @DataSet("playerDao/players.sql") public class TestJodaTime { @TestedSqlObject PlayerSqlObject playerDao; @Test public void testDateTimeParameter() { DateTime dateTime = ISODateTimeFormat.date().withZoneUTC().parseDateTime("1991-04-01");
// Path: src/test/java/com/github/arteam/jdit/domain/PlayerSqlObject.java // @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) // public interface PlayerSqlObject { // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName, // @Bind("birth_date") Date birthDate, @Bind("height") int height, // @Bind("weight") int weight); // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@PlayerBinder Player player); // // @SqlQuery("select last_name from players order by last_name") // List<String> getLastNames(); // // @SqlQuery("select count(*) from players where extract(year from birth_date) = :year") // int getAmountPlayersBornInYear(@Bind("year") int year); // // @SqlQuery("select * from players where birth_date > :date") // List<Player> getPlayersBornAfter(@Bind("date") DateTime date); // // @SqlQuery("select birth_date from players where first_name=:first_name and last_name=:last_name") // DateTime getPlayerBirthDate(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select distinct extract(year from birth_date) player_year from players order by player_year") // Set<Integer> getBornYears(); // // @SqlQuery("select * from players where first_name=:first_name and last_name=:last_name") // Optional<Player> findPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select * from players where weight <> :weight") // List<Player> getPlayersByWeight(@Bind("weight") Optional<Integer> weight); // // @SqlQuery("select first_name from players") // ImmutableSet<String> getFirstNames(); // // @Retention(RetentionPolicy.RUNTIME) // @Target({ElementType.PARAMETER}) // @SqlStatementCustomizingAnnotation(PlayerBinder.Factory.class) // @interface PlayerBinder { // // class Factory implements SqlStatementCustomizerFactory { // // @Override // public SqlStatementParameterCustomizer createForParameter(Annotation annotation, Class<?> sqlObjectType, // Method method, Parameter param, int index, // Type type) { // return (stmt, arg) -> { // Player p = (Player) arg; // stmt.bind("first_name", p.firstName); // stmt.bind("last_name", p.lastName); // stmt.bind("birth_date", p.birthDate); // stmt.bind("weight", p.weight); // stmt.bind("height", p.height); // }; // } // } // } // // class PlayerMapper implements RowMapper<Player> { // @Override // public Player map(ResultSet r, StatementContext ctx) throws SQLException { // int height = r.getInt("height"); // int weight = r.getInt("weight"); // return new Player(Optional.of(r.getLong("id")), r.getString("first_name"), r.getString("last_name"), // r.getTimestamp("birth_date"), // height != 0 ? Optional.of(height) : Optional.empty(), // weight != 0 ? Optional.of(weight) : Optional.empty()); // } // } // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Player.java // public class Player { // // public final Optional<Long> id; // public final String firstName; // public final String lastName; // public final Date birthDate; // public final Optional<Integer> height; // public final Optional<Integer> weight; // // public Player(Optional<Long> id, String firstName, String lastName, Date birthDate, // Optional<Integer> height, Optional<Integer> weight) { // this.id = id; // this.firstName = firstName; // this.lastName = lastName; // this.birthDate = birthDate; // this.height = height; // this.weight = weight; // } // // public Player(String firstName, String lastName, Date birthDate, int height, int weight) { // this(Optional.<Long>empty(), firstName, lastName, birthDate, Optional.of(height), Optional.of(weight)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .omitNullValues() // .add("id", id.orElse(null)) // .add("firstName", firstName) // .add("lastName", lastName) // .add("birthDate", birthDate) // .add("height", height.orElse(null)) // .add("weight", weight.orElse(null)) // .toString(); // } // } // Path: src/test/java/com/github/arteam/jdit/TestJodaTime.java import com.github.arteam.jdit.annotations.DataSet; import com.github.arteam.jdit.annotations.TestedSqlObject; import com.github.arteam.jdit.domain.PlayerSqlObject; import com.github.arteam.jdit.domain.entity.Player; import org.joda.time.DateTime; import org.joda.time.format.ISODateTimeFormat; import org.junit.Test; import org.junit.runner.RunWith; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; package com.github.arteam.jdit; @RunWith(DBIRunner.class) @DataSet("playerDao/players.sql") public class TestJodaTime { @TestedSqlObject PlayerSqlObject playerDao; @Test public void testDateTimeParameter() { DateTime dateTime = ISODateTimeFormat.date().withZoneUTC().parseDateTime("1991-04-01");
List<Player> players = playerDao.getPlayersBornAfter(dateTime);
arteam/jdit
src/test/java/com/github/arteam/jdit/TestOptionals.java
// Path: src/test/java/com/github/arteam/jdit/domain/PlayerSqlObject.java // @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) // public interface PlayerSqlObject { // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName, // @Bind("birth_date") Date birthDate, @Bind("height") int height, // @Bind("weight") int weight); // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@PlayerBinder Player player); // // @SqlQuery("select last_name from players order by last_name") // List<String> getLastNames(); // // @SqlQuery("select count(*) from players where extract(year from birth_date) = :year") // int getAmountPlayersBornInYear(@Bind("year") int year); // // @SqlQuery("select * from players where birth_date > :date") // List<Player> getPlayersBornAfter(@Bind("date") DateTime date); // // @SqlQuery("select birth_date from players where first_name=:first_name and last_name=:last_name") // DateTime getPlayerBirthDate(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select distinct extract(year from birth_date) player_year from players order by player_year") // Set<Integer> getBornYears(); // // @SqlQuery("select * from players where first_name=:first_name and last_name=:last_name") // Optional<Player> findPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select * from players where weight <> :weight") // List<Player> getPlayersByWeight(@Bind("weight") Optional<Integer> weight); // // @SqlQuery("select first_name from players") // ImmutableSet<String> getFirstNames(); // // @Retention(RetentionPolicy.RUNTIME) // @Target({ElementType.PARAMETER}) // @SqlStatementCustomizingAnnotation(PlayerBinder.Factory.class) // @interface PlayerBinder { // // class Factory implements SqlStatementCustomizerFactory { // // @Override // public SqlStatementParameterCustomizer createForParameter(Annotation annotation, Class<?> sqlObjectType, // Method method, Parameter param, int index, // Type type) { // return (stmt, arg) -> { // Player p = (Player) arg; // stmt.bind("first_name", p.firstName); // stmt.bind("last_name", p.lastName); // stmt.bind("birth_date", p.birthDate); // stmt.bind("weight", p.weight); // stmt.bind("height", p.height); // }; // } // } // } // // class PlayerMapper implements RowMapper<Player> { // @Override // public Player map(ResultSet r, StatementContext ctx) throws SQLException { // int height = r.getInt("height"); // int weight = r.getInt("weight"); // return new Player(Optional.of(r.getLong("id")), r.getString("first_name"), r.getString("last_name"), // r.getTimestamp("birth_date"), // height != 0 ? Optional.of(height) : Optional.empty(), // weight != 0 ? Optional.of(weight) : Optional.empty()); // } // } // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Player.java // public class Player { // // public final Optional<Long> id; // public final String firstName; // public final String lastName; // public final Date birthDate; // public final Optional<Integer> height; // public final Optional<Integer> weight; // // public Player(Optional<Long> id, String firstName, String lastName, Date birthDate, // Optional<Integer> height, Optional<Integer> weight) { // this.id = id; // this.firstName = firstName; // this.lastName = lastName; // this.birthDate = birthDate; // this.height = height; // this.weight = weight; // } // // public Player(String firstName, String lastName, Date birthDate, int height, int weight) { // this(Optional.<Long>empty(), firstName, lastName, birthDate, Optional.of(height), Optional.of(weight)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .omitNullValues() // .add("id", id.orElse(null)) // .add("firstName", firstName) // .add("lastName", lastName) // .add("birthDate", birthDate) // .add("height", height.orElse(null)) // .add("weight", weight.orElse(null)) // .toString(); // } // }
import com.github.arteam.jdit.annotations.DataSet; import com.github.arteam.jdit.annotations.TestedSqlObject; import com.github.arteam.jdit.domain.PlayerSqlObject; import com.github.arteam.jdit.domain.entity.Player; import org.junit.Test; import org.junit.runner.RunWith; import java.util.List; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat;
package com.github.arteam.jdit; @RunWith(DBIRunner.class) @DataSet("playerDao/players.sql") public class TestOptionals { @TestedSqlObject
// Path: src/test/java/com/github/arteam/jdit/domain/PlayerSqlObject.java // @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) // public interface PlayerSqlObject { // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName, // @Bind("birth_date") Date birthDate, @Bind("height") int height, // @Bind("weight") int weight); // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@PlayerBinder Player player); // // @SqlQuery("select last_name from players order by last_name") // List<String> getLastNames(); // // @SqlQuery("select count(*) from players where extract(year from birth_date) = :year") // int getAmountPlayersBornInYear(@Bind("year") int year); // // @SqlQuery("select * from players where birth_date > :date") // List<Player> getPlayersBornAfter(@Bind("date") DateTime date); // // @SqlQuery("select birth_date from players where first_name=:first_name and last_name=:last_name") // DateTime getPlayerBirthDate(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select distinct extract(year from birth_date) player_year from players order by player_year") // Set<Integer> getBornYears(); // // @SqlQuery("select * from players where first_name=:first_name and last_name=:last_name") // Optional<Player> findPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select * from players where weight <> :weight") // List<Player> getPlayersByWeight(@Bind("weight") Optional<Integer> weight); // // @SqlQuery("select first_name from players") // ImmutableSet<String> getFirstNames(); // // @Retention(RetentionPolicy.RUNTIME) // @Target({ElementType.PARAMETER}) // @SqlStatementCustomizingAnnotation(PlayerBinder.Factory.class) // @interface PlayerBinder { // // class Factory implements SqlStatementCustomizerFactory { // // @Override // public SqlStatementParameterCustomizer createForParameter(Annotation annotation, Class<?> sqlObjectType, // Method method, Parameter param, int index, // Type type) { // return (stmt, arg) -> { // Player p = (Player) arg; // stmt.bind("first_name", p.firstName); // stmt.bind("last_name", p.lastName); // stmt.bind("birth_date", p.birthDate); // stmt.bind("weight", p.weight); // stmt.bind("height", p.height); // }; // } // } // } // // class PlayerMapper implements RowMapper<Player> { // @Override // public Player map(ResultSet r, StatementContext ctx) throws SQLException { // int height = r.getInt("height"); // int weight = r.getInt("weight"); // return new Player(Optional.of(r.getLong("id")), r.getString("first_name"), r.getString("last_name"), // r.getTimestamp("birth_date"), // height != 0 ? Optional.of(height) : Optional.empty(), // weight != 0 ? Optional.of(weight) : Optional.empty()); // } // } // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Player.java // public class Player { // // public final Optional<Long> id; // public final String firstName; // public final String lastName; // public final Date birthDate; // public final Optional<Integer> height; // public final Optional<Integer> weight; // // public Player(Optional<Long> id, String firstName, String lastName, Date birthDate, // Optional<Integer> height, Optional<Integer> weight) { // this.id = id; // this.firstName = firstName; // this.lastName = lastName; // this.birthDate = birthDate; // this.height = height; // this.weight = weight; // } // // public Player(String firstName, String lastName, Date birthDate, int height, int weight) { // this(Optional.<Long>empty(), firstName, lastName, birthDate, Optional.of(height), Optional.of(weight)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .omitNullValues() // .add("id", id.orElse(null)) // .add("firstName", firstName) // .add("lastName", lastName) // .add("birthDate", birthDate) // .add("height", height.orElse(null)) // .add("weight", weight.orElse(null)) // .toString(); // } // } // Path: src/test/java/com/github/arteam/jdit/TestOptionals.java import com.github.arteam.jdit.annotations.DataSet; import com.github.arteam.jdit.annotations.TestedSqlObject; import com.github.arteam.jdit.domain.PlayerSqlObject; import com.github.arteam.jdit.domain.entity.Player; import org.junit.Test; import org.junit.runner.RunWith; import java.util.List; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; package com.github.arteam.jdit; @RunWith(DBIRunner.class) @DataSet("playerDao/players.sql") public class TestOptionals { @TestedSqlObject
PlayerSqlObject playerSqlObject;
arteam/jdit
src/test/java/com/github/arteam/jdit/TestOptionals.java
// Path: src/test/java/com/github/arteam/jdit/domain/PlayerSqlObject.java // @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) // public interface PlayerSqlObject { // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName, // @Bind("birth_date") Date birthDate, @Bind("height") int height, // @Bind("weight") int weight); // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@PlayerBinder Player player); // // @SqlQuery("select last_name from players order by last_name") // List<String> getLastNames(); // // @SqlQuery("select count(*) from players where extract(year from birth_date) = :year") // int getAmountPlayersBornInYear(@Bind("year") int year); // // @SqlQuery("select * from players where birth_date > :date") // List<Player> getPlayersBornAfter(@Bind("date") DateTime date); // // @SqlQuery("select birth_date from players where first_name=:first_name and last_name=:last_name") // DateTime getPlayerBirthDate(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select distinct extract(year from birth_date) player_year from players order by player_year") // Set<Integer> getBornYears(); // // @SqlQuery("select * from players where first_name=:first_name and last_name=:last_name") // Optional<Player> findPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select * from players where weight <> :weight") // List<Player> getPlayersByWeight(@Bind("weight") Optional<Integer> weight); // // @SqlQuery("select first_name from players") // ImmutableSet<String> getFirstNames(); // // @Retention(RetentionPolicy.RUNTIME) // @Target({ElementType.PARAMETER}) // @SqlStatementCustomizingAnnotation(PlayerBinder.Factory.class) // @interface PlayerBinder { // // class Factory implements SqlStatementCustomizerFactory { // // @Override // public SqlStatementParameterCustomizer createForParameter(Annotation annotation, Class<?> sqlObjectType, // Method method, Parameter param, int index, // Type type) { // return (stmt, arg) -> { // Player p = (Player) arg; // stmt.bind("first_name", p.firstName); // stmt.bind("last_name", p.lastName); // stmt.bind("birth_date", p.birthDate); // stmt.bind("weight", p.weight); // stmt.bind("height", p.height); // }; // } // } // } // // class PlayerMapper implements RowMapper<Player> { // @Override // public Player map(ResultSet r, StatementContext ctx) throws SQLException { // int height = r.getInt("height"); // int weight = r.getInt("weight"); // return new Player(Optional.of(r.getLong("id")), r.getString("first_name"), r.getString("last_name"), // r.getTimestamp("birth_date"), // height != 0 ? Optional.of(height) : Optional.empty(), // weight != 0 ? Optional.of(weight) : Optional.empty()); // } // } // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Player.java // public class Player { // // public final Optional<Long> id; // public final String firstName; // public final String lastName; // public final Date birthDate; // public final Optional<Integer> height; // public final Optional<Integer> weight; // // public Player(Optional<Long> id, String firstName, String lastName, Date birthDate, // Optional<Integer> height, Optional<Integer> weight) { // this.id = id; // this.firstName = firstName; // this.lastName = lastName; // this.birthDate = birthDate; // this.height = height; // this.weight = weight; // } // // public Player(String firstName, String lastName, Date birthDate, int height, int weight) { // this(Optional.<Long>empty(), firstName, lastName, birthDate, Optional.of(height), Optional.of(weight)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .omitNullValues() // .add("id", id.orElse(null)) // .add("firstName", firstName) // .add("lastName", lastName) // .add("birthDate", birthDate) // .add("height", height.orElse(null)) // .add("weight", weight.orElse(null)) // .toString(); // } // }
import com.github.arteam.jdit.annotations.DataSet; import com.github.arteam.jdit.annotations.TestedSqlObject; import com.github.arteam.jdit.domain.PlayerSqlObject; import com.github.arteam.jdit.domain.entity.Player; import org.junit.Test; import org.junit.runner.RunWith; import java.util.List; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat;
package com.github.arteam.jdit; @RunWith(DBIRunner.class) @DataSet("playerDao/players.sql") public class TestOptionals { @TestedSqlObject PlayerSqlObject playerSqlObject; @Test public void testExistOptional() {
// Path: src/test/java/com/github/arteam/jdit/domain/PlayerSqlObject.java // @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) // public interface PlayerSqlObject { // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName, // @Bind("birth_date") Date birthDate, @Bind("height") int height, // @Bind("weight") int weight); // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@PlayerBinder Player player); // // @SqlQuery("select last_name from players order by last_name") // List<String> getLastNames(); // // @SqlQuery("select count(*) from players where extract(year from birth_date) = :year") // int getAmountPlayersBornInYear(@Bind("year") int year); // // @SqlQuery("select * from players where birth_date > :date") // List<Player> getPlayersBornAfter(@Bind("date") DateTime date); // // @SqlQuery("select birth_date from players where first_name=:first_name and last_name=:last_name") // DateTime getPlayerBirthDate(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select distinct extract(year from birth_date) player_year from players order by player_year") // Set<Integer> getBornYears(); // // @SqlQuery("select * from players where first_name=:first_name and last_name=:last_name") // Optional<Player> findPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select * from players where weight <> :weight") // List<Player> getPlayersByWeight(@Bind("weight") Optional<Integer> weight); // // @SqlQuery("select first_name from players") // ImmutableSet<String> getFirstNames(); // // @Retention(RetentionPolicy.RUNTIME) // @Target({ElementType.PARAMETER}) // @SqlStatementCustomizingAnnotation(PlayerBinder.Factory.class) // @interface PlayerBinder { // // class Factory implements SqlStatementCustomizerFactory { // // @Override // public SqlStatementParameterCustomizer createForParameter(Annotation annotation, Class<?> sqlObjectType, // Method method, Parameter param, int index, // Type type) { // return (stmt, arg) -> { // Player p = (Player) arg; // stmt.bind("first_name", p.firstName); // stmt.bind("last_name", p.lastName); // stmt.bind("birth_date", p.birthDate); // stmt.bind("weight", p.weight); // stmt.bind("height", p.height); // }; // } // } // } // // class PlayerMapper implements RowMapper<Player> { // @Override // public Player map(ResultSet r, StatementContext ctx) throws SQLException { // int height = r.getInt("height"); // int weight = r.getInt("weight"); // return new Player(Optional.of(r.getLong("id")), r.getString("first_name"), r.getString("last_name"), // r.getTimestamp("birth_date"), // height != 0 ? Optional.of(height) : Optional.empty(), // weight != 0 ? Optional.of(weight) : Optional.empty()); // } // } // } // // Path: src/test/java/com/github/arteam/jdit/domain/entity/Player.java // public class Player { // // public final Optional<Long> id; // public final String firstName; // public final String lastName; // public final Date birthDate; // public final Optional<Integer> height; // public final Optional<Integer> weight; // // public Player(Optional<Long> id, String firstName, String lastName, Date birthDate, // Optional<Integer> height, Optional<Integer> weight) { // this.id = id; // this.firstName = firstName; // this.lastName = lastName; // this.birthDate = birthDate; // this.height = height; // this.weight = weight; // } // // public Player(String firstName, String lastName, Date birthDate, int height, int weight) { // this(Optional.<Long>empty(), firstName, lastName, birthDate, Optional.of(height), Optional.of(weight)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .omitNullValues() // .add("id", id.orElse(null)) // .add("firstName", firstName) // .add("lastName", lastName) // .add("birthDate", birthDate) // .add("height", height.orElse(null)) // .add("weight", weight.orElse(null)) // .toString(); // } // } // Path: src/test/java/com/github/arteam/jdit/TestOptionals.java import com.github.arteam.jdit.annotations.DataSet; import com.github.arteam.jdit.annotations.TestedSqlObject; import com.github.arteam.jdit.domain.PlayerSqlObject; import com.github.arteam.jdit.domain.entity.Player; import org.junit.Test; import org.junit.runner.RunWith; import java.util.List; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; package com.github.arteam.jdit; @RunWith(DBIRunner.class) @DataSet("playerDao/players.sql") public class TestOptionals { @TestedSqlObject PlayerSqlObject playerSqlObject; @Test public void testExistOptional() {
Optional<Player> player = playerSqlObject.findPlayer("Vladimir", "Tarasenko");
arteam/jdit
src/test/java/com/github/arteam/jdit/TestImmutables.java
// Path: src/test/java/com/github/arteam/jdit/domain/PlayerSqlObject.java // @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) // public interface PlayerSqlObject { // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName, // @Bind("birth_date") Date birthDate, @Bind("height") int height, // @Bind("weight") int weight); // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@PlayerBinder Player player); // // @SqlQuery("select last_name from players order by last_name") // List<String> getLastNames(); // // @SqlQuery("select count(*) from players where extract(year from birth_date) = :year") // int getAmountPlayersBornInYear(@Bind("year") int year); // // @SqlQuery("select * from players where birth_date > :date") // List<Player> getPlayersBornAfter(@Bind("date") DateTime date); // // @SqlQuery("select birth_date from players where first_name=:first_name and last_name=:last_name") // DateTime getPlayerBirthDate(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select distinct extract(year from birth_date) player_year from players order by player_year") // Set<Integer> getBornYears(); // // @SqlQuery("select * from players where first_name=:first_name and last_name=:last_name") // Optional<Player> findPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select * from players where weight <> :weight") // List<Player> getPlayersByWeight(@Bind("weight") Optional<Integer> weight); // // @SqlQuery("select first_name from players") // ImmutableSet<String> getFirstNames(); // // @Retention(RetentionPolicy.RUNTIME) // @Target({ElementType.PARAMETER}) // @SqlStatementCustomizingAnnotation(PlayerBinder.Factory.class) // @interface PlayerBinder { // // class Factory implements SqlStatementCustomizerFactory { // // @Override // public SqlStatementParameterCustomizer createForParameter(Annotation annotation, Class<?> sqlObjectType, // Method method, Parameter param, int index, // Type type) { // return (stmt, arg) -> { // Player p = (Player) arg; // stmt.bind("first_name", p.firstName); // stmt.bind("last_name", p.lastName); // stmt.bind("birth_date", p.birthDate); // stmt.bind("weight", p.weight); // stmt.bind("height", p.height); // }; // } // } // } // // class PlayerMapper implements RowMapper<Player> { // @Override // public Player map(ResultSet r, StatementContext ctx) throws SQLException { // int height = r.getInt("height"); // int weight = r.getInt("weight"); // return new Player(Optional.of(r.getLong("id")), r.getString("first_name"), r.getString("last_name"), // r.getTimestamp("birth_date"), // height != 0 ? Optional.of(height) : Optional.empty(), // weight != 0 ? Optional.of(weight) : Optional.empty()); // } // } // }
import com.github.arteam.jdit.annotations.DataSet; import com.github.arteam.jdit.annotations.TestedSqlObject; import com.github.arteam.jdit.domain.PlayerSqlObject; import org.junit.Test; import org.junit.runner.RunWith; import static org.assertj.core.api.Assertions.assertThat;
package com.github.arteam.jdit; @DataSet("playerDao/players.sql") @RunWith(DBIRunner.class) public class TestImmutables { @TestedSqlObject
// Path: src/test/java/com/github/arteam/jdit/domain/PlayerSqlObject.java // @RegisterRowMapper(PlayerSqlObject.PlayerMapper.class) // public interface PlayerSqlObject { // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName, // @Bind("birth_date") Date birthDate, @Bind("height") int height, // @Bind("weight") int weight); // // @GetGeneratedKeys // @SqlUpdate("insert into players(first_name, last_name, birth_date, weight, height) values" + // "(:first_name, :last_name, :birth_date, :weight, :height)") // Long createPlayer(@PlayerBinder Player player); // // @SqlQuery("select last_name from players order by last_name") // List<String> getLastNames(); // // @SqlQuery("select count(*) from players where extract(year from birth_date) = :year") // int getAmountPlayersBornInYear(@Bind("year") int year); // // @SqlQuery("select * from players where birth_date > :date") // List<Player> getPlayersBornAfter(@Bind("date") DateTime date); // // @SqlQuery("select birth_date from players where first_name=:first_name and last_name=:last_name") // DateTime getPlayerBirthDate(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select distinct extract(year from birth_date) player_year from players order by player_year") // Set<Integer> getBornYears(); // // @SqlQuery("select * from players where first_name=:first_name and last_name=:last_name") // Optional<Player> findPlayer(@Bind("first_name") String firstName, @Bind("last_name") String lastName); // // @SqlQuery("select * from players where weight <> :weight") // List<Player> getPlayersByWeight(@Bind("weight") Optional<Integer> weight); // // @SqlQuery("select first_name from players") // ImmutableSet<String> getFirstNames(); // // @Retention(RetentionPolicy.RUNTIME) // @Target({ElementType.PARAMETER}) // @SqlStatementCustomizingAnnotation(PlayerBinder.Factory.class) // @interface PlayerBinder { // // class Factory implements SqlStatementCustomizerFactory { // // @Override // public SqlStatementParameterCustomizer createForParameter(Annotation annotation, Class<?> sqlObjectType, // Method method, Parameter param, int index, // Type type) { // return (stmt, arg) -> { // Player p = (Player) arg; // stmt.bind("first_name", p.firstName); // stmt.bind("last_name", p.lastName); // stmt.bind("birth_date", p.birthDate); // stmt.bind("weight", p.weight); // stmt.bind("height", p.height); // }; // } // } // } // // class PlayerMapper implements RowMapper<Player> { // @Override // public Player map(ResultSet r, StatementContext ctx) throws SQLException { // int height = r.getInt("height"); // int weight = r.getInt("weight"); // return new Player(Optional.of(r.getLong("id")), r.getString("first_name"), r.getString("last_name"), // r.getTimestamp("birth_date"), // height != 0 ? Optional.of(height) : Optional.empty(), // weight != 0 ? Optional.of(weight) : Optional.empty()); // } // } // } // Path: src/test/java/com/github/arteam/jdit/TestImmutables.java import com.github.arteam.jdit.annotations.DataSet; import com.github.arteam.jdit.annotations.TestedSqlObject; import com.github.arteam.jdit.domain.PlayerSqlObject; import org.junit.Test; import org.junit.runner.RunWith; import static org.assertj.core.api.Assertions.assertThat; package com.github.arteam.jdit; @DataSet("playerDao/players.sql") @RunWith(DBIRunner.class) public class TestImmutables { @TestedSqlObject
PlayerSqlObject playerDao;
arteam/jdit
src/test/java/com/github/arteam/jdit/AbstractDbiDaoTest.java
// Path: src/test/java/com/github/arteam/jdit/domain/PlayerDao.java // public class PlayerDao extends BasePlayerDao { // // private Jdbi dbi; // // @Override // public Jdbi dbi() { // return dbi; // } // }
import com.github.arteam.jdit.annotations.DBIHandle; import com.github.arteam.jdit.annotations.TestedDao; import com.github.arteam.jdit.domain.PlayerDao; import org.jdbi.v3.core.Handle; import org.junit.Test; import java.text.SimpleDateFormat; import static org.assertj.core.api.Assertions.assertThat;
package com.github.arteam.jdit; public abstract class AbstractDbiDaoTest { @DBIHandle Handle handle; @TestedDao
// Path: src/test/java/com/github/arteam/jdit/domain/PlayerDao.java // public class PlayerDao extends BasePlayerDao { // // private Jdbi dbi; // // @Override // public Jdbi dbi() { // return dbi; // } // } // Path: src/test/java/com/github/arteam/jdit/AbstractDbiDaoTest.java import com.github.arteam.jdit.annotations.DBIHandle; import com.github.arteam.jdit.annotations.TestedDao; import com.github.arteam.jdit.domain.PlayerDao; import org.jdbi.v3.core.Handle; import org.junit.Test; import java.text.SimpleDateFormat; import static org.assertj.core.api.Assertions.assertThat; package com.github.arteam.jdit; public abstract class AbstractDbiDaoTest { @DBIHandle Handle handle; @TestedDao
PlayerDao playerDao;
arteam/jdit
src/test/java/com/github/arteam/jdit/DBIDaoWithConstructorTest.java
// Path: src/test/java/com/github/arteam/jdit/domain/PlayerDaoWithConstructor.java // public class PlayerDaoWithConstructor extends BasePlayerDao { // // private Jdbi dbi; // // public PlayerDaoWithConstructor(Jdbi dbi) { // this.dbi = dbi; // } // // @Override // public Jdbi dbi() { // return dbi; // } // }
import com.github.arteam.jdit.annotations.DBIHandle; import com.github.arteam.jdit.annotations.TestedDao; import com.github.arteam.jdit.domain.PlayerDaoWithConstructor; import org.jdbi.v3.core.Handle; import org.junit.Test; import org.junit.runner.RunWith; import java.text.SimpleDateFormat; import static org.assertj.core.api.Assertions.assertThat;
package com.github.arteam.jdit; @RunWith(DBIRunner.class) public class DBIDaoWithConstructorTest { @DBIHandle Handle handle; @TestedDao
// Path: src/test/java/com/github/arteam/jdit/domain/PlayerDaoWithConstructor.java // public class PlayerDaoWithConstructor extends BasePlayerDao { // // private Jdbi dbi; // // public PlayerDaoWithConstructor(Jdbi dbi) { // this.dbi = dbi; // } // // @Override // public Jdbi dbi() { // return dbi; // } // } // Path: src/test/java/com/github/arteam/jdit/DBIDaoWithConstructorTest.java import com.github.arteam.jdit.annotations.DBIHandle; import com.github.arteam.jdit.annotations.TestedDao; import com.github.arteam.jdit.domain.PlayerDaoWithConstructor; import org.jdbi.v3.core.Handle; import org.junit.Test; import org.junit.runner.RunWith; import java.text.SimpleDateFormat; import static org.assertj.core.api.Assertions.assertThat; package com.github.arteam.jdit; @RunWith(DBIRunner.class) public class DBIDaoWithConstructorTest { @DBIHandle Handle handle; @TestedDao
PlayerDaoWithConstructor playerDao;
YugengWang/OneWeather
app/src/main/java/com/yoga/oneweather/util/JSONHandleUtil.java
// Path: app/src/main/java/com/yoga/oneweather/MyApplication.java // public class MyApplication extends Application { // // private static Context context; // private static Gson mGson = new Gson(); // // // // @Override // public void onCreate() { // super.onCreate(); // context = getApplicationContext(); // LitePal.initialize(context); // DBManager.getInstance().copyCitysToDB(); // // // // } // // public static Gson getGson() { // return mGson; // } // // public static Context getContext() { // return context; // } // } // // Path: app/src/main/java/com/yoga/oneweather/model/entity/city/City.java // public class City { // public String cityName; // @SerializedName("county") // public List<County> counties; // } // // Path: app/src/main/java/com/yoga/oneweather/model/entity/city/County.java // public class County { // // public String countyName; // public String countyNo; // public String countyPY; // } // // Path: app/src/main/java/com/yoga/oneweather/model/entity/city/Province.java // public class Province { // public String provinceName; // @SerializedName("city") // public List<City> cities; // // // } // // Path: app/src/main/java/com/yoga/oneweather/model/entity/weather/Weather.java // public class Weather { // public String status; // public AQI aqi; // public Basic basic; // @SerializedName("daily_forecast") // public List<Forecast> forecastList; // public Now now; // public Suggestion suggestion; // }
import com.google.gson.reflect.TypeToken; import com.yoga.oneweather.MyApplication; import com.yoga.oneweather.model.entity.city.City; import com.yoga.oneweather.model.entity.city.County; import com.yoga.oneweather.model.entity.city.Province; import com.yoga.oneweather.model.entity.weather.Weather; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List;
package com.yoga.oneweather.util; /** * Created by wyg on 2017/7/29. */ public class JSONHandleUtil { public static Weather handleWeatherResponse(String response){ try { JSONObject jsonObject = new JSONObject(response); JSONArray jsonArray = jsonObject.getJSONArray("HeWeather5"); String weatherString = jsonArray.getJSONObject(0).toString();
// Path: app/src/main/java/com/yoga/oneweather/MyApplication.java // public class MyApplication extends Application { // // private static Context context; // private static Gson mGson = new Gson(); // // // // @Override // public void onCreate() { // super.onCreate(); // context = getApplicationContext(); // LitePal.initialize(context); // DBManager.getInstance().copyCitysToDB(); // // // // } // // public static Gson getGson() { // return mGson; // } // // public static Context getContext() { // return context; // } // } // // Path: app/src/main/java/com/yoga/oneweather/model/entity/city/City.java // public class City { // public String cityName; // @SerializedName("county") // public List<County> counties; // } // // Path: app/src/main/java/com/yoga/oneweather/model/entity/city/County.java // public class County { // // public String countyName; // public String countyNo; // public String countyPY; // } // // Path: app/src/main/java/com/yoga/oneweather/model/entity/city/Province.java // public class Province { // public String provinceName; // @SerializedName("city") // public List<City> cities; // // // } // // Path: app/src/main/java/com/yoga/oneweather/model/entity/weather/Weather.java // public class Weather { // public String status; // public AQI aqi; // public Basic basic; // @SerializedName("daily_forecast") // public List<Forecast> forecastList; // public Now now; // public Suggestion suggestion; // } // Path: app/src/main/java/com/yoga/oneweather/util/JSONHandleUtil.java import com.google.gson.reflect.TypeToken; import com.yoga.oneweather.MyApplication; import com.yoga.oneweather.model.entity.city.City; import com.yoga.oneweather.model.entity.city.County; import com.yoga.oneweather.model.entity.city.Province; import com.yoga.oneweather.model.entity.weather.Weather; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; package com.yoga.oneweather.util; /** * Created by wyg on 2017/7/29. */ public class JSONHandleUtil { public static Weather handleWeatherResponse(String response){ try { JSONObject jsonObject = new JSONObject(response); JSONArray jsonArray = jsonObject.getJSONArray("HeWeather5"); String weatherString = jsonArray.getJSONObject(0).toString();
return MyApplication.getGson().fromJson(weatherString,Weather.class);
YugengWang/OneWeather
app/src/main/java/com/yoga/oneweather/util/JSONHandleUtil.java
// Path: app/src/main/java/com/yoga/oneweather/MyApplication.java // public class MyApplication extends Application { // // private static Context context; // private static Gson mGson = new Gson(); // // // // @Override // public void onCreate() { // super.onCreate(); // context = getApplicationContext(); // LitePal.initialize(context); // DBManager.getInstance().copyCitysToDB(); // // // // } // // public static Gson getGson() { // return mGson; // } // // public static Context getContext() { // return context; // } // } // // Path: app/src/main/java/com/yoga/oneweather/model/entity/city/City.java // public class City { // public String cityName; // @SerializedName("county") // public List<County> counties; // } // // Path: app/src/main/java/com/yoga/oneweather/model/entity/city/County.java // public class County { // // public String countyName; // public String countyNo; // public String countyPY; // } // // Path: app/src/main/java/com/yoga/oneweather/model/entity/city/Province.java // public class Province { // public String provinceName; // @SerializedName("city") // public List<City> cities; // // // } // // Path: app/src/main/java/com/yoga/oneweather/model/entity/weather/Weather.java // public class Weather { // public String status; // public AQI aqi; // public Basic basic; // @SerializedName("daily_forecast") // public List<Forecast> forecastList; // public Now now; // public Suggestion suggestion; // }
import com.google.gson.reflect.TypeToken; import com.yoga.oneweather.MyApplication; import com.yoga.oneweather.model.entity.city.City; import com.yoga.oneweather.model.entity.city.County; import com.yoga.oneweather.model.entity.city.Province; import com.yoga.oneweather.model.entity.weather.Weather; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List;
package com.yoga.oneweather.util; /** * Created by wyg on 2017/7/29. */ public class JSONHandleUtil { public static Weather handleWeatherResponse(String response){ try { JSONObject jsonObject = new JSONObject(response); JSONArray jsonArray = jsonObject.getJSONArray("HeWeather5"); String weatherString = jsonArray.getJSONObject(0).toString(); return MyApplication.getGson().fromJson(weatherString,Weather.class); } catch (JSONException e) { e.printStackTrace(); } return null; }
// Path: app/src/main/java/com/yoga/oneweather/MyApplication.java // public class MyApplication extends Application { // // private static Context context; // private static Gson mGson = new Gson(); // // // // @Override // public void onCreate() { // super.onCreate(); // context = getApplicationContext(); // LitePal.initialize(context); // DBManager.getInstance().copyCitysToDB(); // // // // } // // public static Gson getGson() { // return mGson; // } // // public static Context getContext() { // return context; // } // } // // Path: app/src/main/java/com/yoga/oneweather/model/entity/city/City.java // public class City { // public String cityName; // @SerializedName("county") // public List<County> counties; // } // // Path: app/src/main/java/com/yoga/oneweather/model/entity/city/County.java // public class County { // // public String countyName; // public String countyNo; // public String countyPY; // } // // Path: app/src/main/java/com/yoga/oneweather/model/entity/city/Province.java // public class Province { // public String provinceName; // @SerializedName("city") // public List<City> cities; // // // } // // Path: app/src/main/java/com/yoga/oneweather/model/entity/weather/Weather.java // public class Weather { // public String status; // public AQI aqi; // public Basic basic; // @SerializedName("daily_forecast") // public List<Forecast> forecastList; // public Now now; // public Suggestion suggestion; // } // Path: app/src/main/java/com/yoga/oneweather/util/JSONHandleUtil.java import com.google.gson.reflect.TypeToken; import com.yoga.oneweather.MyApplication; import com.yoga.oneweather.model.entity.city.City; import com.yoga.oneweather.model.entity.city.County; import com.yoga.oneweather.model.entity.city.Province; import com.yoga.oneweather.model.entity.weather.Weather; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; package com.yoga.oneweather.util; /** * Created by wyg on 2017/7/29. */ public class JSONHandleUtil { public static Weather handleWeatherResponse(String response){ try { JSONObject jsonObject = new JSONObject(response); JSONArray jsonArray = jsonObject.getJSONArray("HeWeather5"); String weatherString = jsonArray.getJSONObject(0).toString(); return MyApplication.getGson().fromJson(weatherString,Weather.class); } catch (JSONException e) { e.printStackTrace(); } return null; }
public static List<County> handleCitiesJSONData(String allCities){
YugengWang/OneWeather
app/src/main/java/com/yoga/oneweather/util/JSONHandleUtil.java
// Path: app/src/main/java/com/yoga/oneweather/MyApplication.java // public class MyApplication extends Application { // // private static Context context; // private static Gson mGson = new Gson(); // // // // @Override // public void onCreate() { // super.onCreate(); // context = getApplicationContext(); // LitePal.initialize(context); // DBManager.getInstance().copyCitysToDB(); // // // // } // // public static Gson getGson() { // return mGson; // } // // public static Context getContext() { // return context; // } // } // // Path: app/src/main/java/com/yoga/oneweather/model/entity/city/City.java // public class City { // public String cityName; // @SerializedName("county") // public List<County> counties; // } // // Path: app/src/main/java/com/yoga/oneweather/model/entity/city/County.java // public class County { // // public String countyName; // public String countyNo; // public String countyPY; // } // // Path: app/src/main/java/com/yoga/oneweather/model/entity/city/Province.java // public class Province { // public String provinceName; // @SerializedName("city") // public List<City> cities; // // // } // // Path: app/src/main/java/com/yoga/oneweather/model/entity/weather/Weather.java // public class Weather { // public String status; // public AQI aqi; // public Basic basic; // @SerializedName("daily_forecast") // public List<Forecast> forecastList; // public Now now; // public Suggestion suggestion; // }
import com.google.gson.reflect.TypeToken; import com.yoga.oneweather.MyApplication; import com.yoga.oneweather.model.entity.city.City; import com.yoga.oneweather.model.entity.city.County; import com.yoga.oneweather.model.entity.city.Province; import com.yoga.oneweather.model.entity.weather.Weather; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List;
package com.yoga.oneweather.util; /** * Created by wyg on 2017/7/29. */ public class JSONHandleUtil { public static Weather handleWeatherResponse(String response){ try { JSONObject jsonObject = new JSONObject(response); JSONArray jsonArray = jsonObject.getJSONArray("HeWeather5"); String weatherString = jsonArray.getJSONObject(0).toString(); return MyApplication.getGson().fromJson(weatherString,Weather.class); } catch (JSONException e) { e.printStackTrace(); } return null; } public static List<County> handleCitiesJSONData(String allCities){ try { List<County> countyList = new ArrayList<>(); JSONArray jsonArray = new JSONArray(allCities);//省份组合
// Path: app/src/main/java/com/yoga/oneweather/MyApplication.java // public class MyApplication extends Application { // // private static Context context; // private static Gson mGson = new Gson(); // // // // @Override // public void onCreate() { // super.onCreate(); // context = getApplicationContext(); // LitePal.initialize(context); // DBManager.getInstance().copyCitysToDB(); // // // // } // // public static Gson getGson() { // return mGson; // } // // public static Context getContext() { // return context; // } // } // // Path: app/src/main/java/com/yoga/oneweather/model/entity/city/City.java // public class City { // public String cityName; // @SerializedName("county") // public List<County> counties; // } // // Path: app/src/main/java/com/yoga/oneweather/model/entity/city/County.java // public class County { // // public String countyName; // public String countyNo; // public String countyPY; // } // // Path: app/src/main/java/com/yoga/oneweather/model/entity/city/Province.java // public class Province { // public String provinceName; // @SerializedName("city") // public List<City> cities; // // // } // // Path: app/src/main/java/com/yoga/oneweather/model/entity/weather/Weather.java // public class Weather { // public String status; // public AQI aqi; // public Basic basic; // @SerializedName("daily_forecast") // public List<Forecast> forecastList; // public Now now; // public Suggestion suggestion; // } // Path: app/src/main/java/com/yoga/oneweather/util/JSONHandleUtil.java import com.google.gson.reflect.TypeToken; import com.yoga.oneweather.MyApplication; import com.yoga.oneweather.model.entity.city.City; import com.yoga.oneweather.model.entity.city.County; import com.yoga.oneweather.model.entity.city.Province; import com.yoga.oneweather.model.entity.weather.Weather; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; package com.yoga.oneweather.util; /** * Created by wyg on 2017/7/29. */ public class JSONHandleUtil { public static Weather handleWeatherResponse(String response){ try { JSONObject jsonObject = new JSONObject(response); JSONArray jsonArray = jsonObject.getJSONArray("HeWeather5"); String weatherString = jsonArray.getJSONObject(0).toString(); return MyApplication.getGson().fromJson(weatherString,Weather.class); } catch (JSONException e) { e.printStackTrace(); } return null; } public static List<County> handleCitiesJSONData(String allCities){ try { List<County> countyList = new ArrayList<>(); JSONArray jsonArray = new JSONArray(allCities);//省份组合
List<Province> provinceList = MyApplication.getGson().fromJson(jsonArray.toString(),new TypeToken<List<Province>>(){}.getType());
YugengWang/OneWeather
app/src/main/java/com/yoga/oneweather/util/JSONHandleUtil.java
// Path: app/src/main/java/com/yoga/oneweather/MyApplication.java // public class MyApplication extends Application { // // private static Context context; // private static Gson mGson = new Gson(); // // // // @Override // public void onCreate() { // super.onCreate(); // context = getApplicationContext(); // LitePal.initialize(context); // DBManager.getInstance().copyCitysToDB(); // // // // } // // public static Gson getGson() { // return mGson; // } // // public static Context getContext() { // return context; // } // } // // Path: app/src/main/java/com/yoga/oneweather/model/entity/city/City.java // public class City { // public String cityName; // @SerializedName("county") // public List<County> counties; // } // // Path: app/src/main/java/com/yoga/oneweather/model/entity/city/County.java // public class County { // // public String countyName; // public String countyNo; // public String countyPY; // } // // Path: app/src/main/java/com/yoga/oneweather/model/entity/city/Province.java // public class Province { // public String provinceName; // @SerializedName("city") // public List<City> cities; // // // } // // Path: app/src/main/java/com/yoga/oneweather/model/entity/weather/Weather.java // public class Weather { // public String status; // public AQI aqi; // public Basic basic; // @SerializedName("daily_forecast") // public List<Forecast> forecastList; // public Now now; // public Suggestion suggestion; // }
import com.google.gson.reflect.TypeToken; import com.yoga.oneweather.MyApplication; import com.yoga.oneweather.model.entity.city.City; import com.yoga.oneweather.model.entity.city.County; import com.yoga.oneweather.model.entity.city.Province; import com.yoga.oneweather.model.entity.weather.Weather; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List;
package com.yoga.oneweather.util; /** * Created by wyg on 2017/7/29. */ public class JSONHandleUtil { public static Weather handleWeatherResponse(String response){ try { JSONObject jsonObject = new JSONObject(response); JSONArray jsonArray = jsonObject.getJSONArray("HeWeather5"); String weatherString = jsonArray.getJSONObject(0).toString(); return MyApplication.getGson().fromJson(weatherString,Weather.class); } catch (JSONException e) { e.printStackTrace(); } return null; } public static List<County> handleCitiesJSONData(String allCities){ try { List<County> countyList = new ArrayList<>(); JSONArray jsonArray = new JSONArray(allCities);//省份组合 List<Province> provinceList = MyApplication.getGson().fromJson(jsonArray.toString(),new TypeToken<List<Province>>(){}.getType()); for(Province province : provinceList){
// Path: app/src/main/java/com/yoga/oneweather/MyApplication.java // public class MyApplication extends Application { // // private static Context context; // private static Gson mGson = new Gson(); // // // // @Override // public void onCreate() { // super.onCreate(); // context = getApplicationContext(); // LitePal.initialize(context); // DBManager.getInstance().copyCitysToDB(); // // // // } // // public static Gson getGson() { // return mGson; // } // // public static Context getContext() { // return context; // } // } // // Path: app/src/main/java/com/yoga/oneweather/model/entity/city/City.java // public class City { // public String cityName; // @SerializedName("county") // public List<County> counties; // } // // Path: app/src/main/java/com/yoga/oneweather/model/entity/city/County.java // public class County { // // public String countyName; // public String countyNo; // public String countyPY; // } // // Path: app/src/main/java/com/yoga/oneweather/model/entity/city/Province.java // public class Province { // public String provinceName; // @SerializedName("city") // public List<City> cities; // // // } // // Path: app/src/main/java/com/yoga/oneweather/model/entity/weather/Weather.java // public class Weather { // public String status; // public AQI aqi; // public Basic basic; // @SerializedName("daily_forecast") // public List<Forecast> forecastList; // public Now now; // public Suggestion suggestion; // } // Path: app/src/main/java/com/yoga/oneweather/util/JSONHandleUtil.java import com.google.gson.reflect.TypeToken; import com.yoga.oneweather.MyApplication; import com.yoga.oneweather.model.entity.city.City; import com.yoga.oneweather.model.entity.city.County; import com.yoga.oneweather.model.entity.city.Province; import com.yoga.oneweather.model.entity.weather.Weather; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; package com.yoga.oneweather.util; /** * Created by wyg on 2017/7/29. */ public class JSONHandleUtil { public static Weather handleWeatherResponse(String response){ try { JSONObject jsonObject = new JSONObject(response); JSONArray jsonArray = jsonObject.getJSONArray("HeWeather5"); String weatherString = jsonArray.getJSONObject(0).toString(); return MyApplication.getGson().fromJson(weatherString,Weather.class); } catch (JSONException e) { e.printStackTrace(); } return null; } public static List<County> handleCitiesJSONData(String allCities){ try { List<County> countyList = new ArrayList<>(); JSONArray jsonArray = new JSONArray(allCities);//省份组合 List<Province> provinceList = MyApplication.getGson().fromJson(jsonArray.toString(),new TypeToken<List<Province>>(){}.getType()); for(Province province : provinceList){
for(City city : province.cities){
YugengWang/OneWeather
app/src/main/java/com/yoga/oneweather/widget/SunriseSunset.java
// Path: app/src/main/java/com/yoga/oneweather/util/LogUtil.java // public class LogUtil { // public static final int VERBOSE = 1; // public static final int DEBUG = 2 ; // public static final int INFO = 3 ; // public static final int WARN = 4 ; // public static final int ERROR = 5 ; // public static final int NOTHING = 6 ; // // public static int level = VERBOSE ; // public static void v(String tag, String msg){ // if(level == VERBOSE){ // Log.v(tag, msg); // } // } // public static void d(String tag,String msg){ // if(level <= DEBUG){ // Log.d(tag, msg); // } // } // // public static void i(String tag,String msg){ // if(level <= INFO){ // Log.i(tag, msg); // } // } // // // public static void w(String tag,String msg){ // if(level <= WARN){ // Log.w(tag, msg); // } // } // // public static void e(String tag,String msg){ // if(level <= ERROR){ // Log.e(tag, msg); // } // } // // } // // Path: app/src/main/java/com/yoga/oneweather/util/MiscUtil.java // public class MiscUtil { // /** // * 测量 view // * @param measureSpec // * @param defaultSize View的默认大小 // * @return // */ // public static int measure(int measureSpec ,int defaultSize){ // int result = defaultSize; // int specMode = View.MeasureSpec.getMode(measureSpec); // int specSize = View.MeasureSpec.getSize(measureSpec); // if(specMode == View.MeasureSpec.EXACTLY){ // result = specSize; // }else if(specMode == View.MeasureSpec.AT_MOST){ // result = Math.min(result,specSize); // } // return result; // } // // /** // * dp 转 px // * @param context // * @param dip // * @return // */ // public static int dipToPx(Context context, float dip){ // float density = context.getResources().getDisplayMetrics().density; // return (int) (dip * density + 0.5f * (dip >= 0 ? 1 : -1)); // } // // // /** // * 获取数值精度格式化字符串 // * @param precision // * @return // */ // public static String getPrecisionFormat(int precision){ // return "%."+precision+"f" ; // } // // // // /** // * 测量文字高度 // */ // public static float measureTextHeight(Paint paint){ // Paint .FontMetrics fontMetrics = paint.getFontMetrics(); // return (Math.abs(fontMetrics.ascent) + fontMetrics.descent); // } // // // }
import android.animation.ObjectAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.DashPathEffect; import android.graphics.Paint; import android.graphics.Point; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.RectF; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; import android.view.animation.LinearInterpolator; import com.yoga.oneweather.R; import com.yoga.oneweather.util.LogUtil; import com.yoga.oneweather.util.MiscUtil; import static java.lang.Math.PI; import static java.lang.Math.cos; import static java.lang.Math.sin;
private ObjectAnimator mAnimator; private Paint mSunPaint; private Paint mTimePaint; private int lineColor; private int sunColor; private int timeTextColor; private float timeTextSize; private String mSunriseTime = "6:00"; private String mSunsetTime = "19:00"; private Bitmap mSunriseBitmap; private Bitmap mSunsetBitmap; private float percent = 0; private int mTotalTime; private boolean isSetTime = false; private int mNowTime; private static final String TAG = "SunriseSunset"; public SunriseSunset(Context context) { this(context,null); } public SunriseSunset(Context context, @Nullable AttributeSet attrs) { this(context, attrs,0); } public SunriseSunset(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mContext = context;
// Path: app/src/main/java/com/yoga/oneweather/util/LogUtil.java // public class LogUtil { // public static final int VERBOSE = 1; // public static final int DEBUG = 2 ; // public static final int INFO = 3 ; // public static final int WARN = 4 ; // public static final int ERROR = 5 ; // public static final int NOTHING = 6 ; // // public static int level = VERBOSE ; // public static void v(String tag, String msg){ // if(level == VERBOSE){ // Log.v(tag, msg); // } // } // public static void d(String tag,String msg){ // if(level <= DEBUG){ // Log.d(tag, msg); // } // } // // public static void i(String tag,String msg){ // if(level <= INFO){ // Log.i(tag, msg); // } // } // // // public static void w(String tag,String msg){ // if(level <= WARN){ // Log.w(tag, msg); // } // } // // public static void e(String tag,String msg){ // if(level <= ERROR){ // Log.e(tag, msg); // } // } // // } // // Path: app/src/main/java/com/yoga/oneweather/util/MiscUtil.java // public class MiscUtil { // /** // * 测量 view // * @param measureSpec // * @param defaultSize View的默认大小 // * @return // */ // public static int measure(int measureSpec ,int defaultSize){ // int result = defaultSize; // int specMode = View.MeasureSpec.getMode(measureSpec); // int specSize = View.MeasureSpec.getSize(measureSpec); // if(specMode == View.MeasureSpec.EXACTLY){ // result = specSize; // }else if(specMode == View.MeasureSpec.AT_MOST){ // result = Math.min(result,specSize); // } // return result; // } // // /** // * dp 转 px // * @param context // * @param dip // * @return // */ // public static int dipToPx(Context context, float dip){ // float density = context.getResources().getDisplayMetrics().density; // return (int) (dip * density + 0.5f * (dip >= 0 ? 1 : -1)); // } // // // /** // * 获取数值精度格式化字符串 // * @param precision // * @return // */ // public static String getPrecisionFormat(int precision){ // return "%."+precision+"f" ; // } // // // // /** // * 测量文字高度 // */ // public static float measureTextHeight(Paint paint){ // Paint .FontMetrics fontMetrics = paint.getFontMetrics(); // return (Math.abs(fontMetrics.ascent) + fontMetrics.descent); // } // // // } // Path: app/src/main/java/com/yoga/oneweather/widget/SunriseSunset.java import android.animation.ObjectAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.DashPathEffect; import android.graphics.Paint; import android.graphics.Point; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.RectF; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; import android.view.animation.LinearInterpolator; import com.yoga.oneweather.R; import com.yoga.oneweather.util.LogUtil; import com.yoga.oneweather.util.MiscUtil; import static java.lang.Math.PI; import static java.lang.Math.cos; import static java.lang.Math.sin; private ObjectAnimator mAnimator; private Paint mSunPaint; private Paint mTimePaint; private int lineColor; private int sunColor; private int timeTextColor; private float timeTextSize; private String mSunriseTime = "6:00"; private String mSunsetTime = "19:00"; private Bitmap mSunriseBitmap; private Bitmap mSunsetBitmap; private float percent = 0; private int mTotalTime; private boolean isSetTime = false; private int mNowTime; private static final String TAG = "SunriseSunset"; public SunriseSunset(Context context) { this(context,null); } public SunriseSunset(Context context, @Nullable AttributeSet attrs) { this(context, attrs,0); } public SunriseSunset(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mContext = context;
mDefaultSize = MiscUtil.dipToPx(mContext,DEFAULT_SIZE);//默认300
YugengWang/OneWeather
app/src/main/java/com/yoga/oneweather/widget/SunriseSunset.java
// Path: app/src/main/java/com/yoga/oneweather/util/LogUtil.java // public class LogUtil { // public static final int VERBOSE = 1; // public static final int DEBUG = 2 ; // public static final int INFO = 3 ; // public static final int WARN = 4 ; // public static final int ERROR = 5 ; // public static final int NOTHING = 6 ; // // public static int level = VERBOSE ; // public static void v(String tag, String msg){ // if(level == VERBOSE){ // Log.v(tag, msg); // } // } // public static void d(String tag,String msg){ // if(level <= DEBUG){ // Log.d(tag, msg); // } // } // // public static void i(String tag,String msg){ // if(level <= INFO){ // Log.i(tag, msg); // } // } // // // public static void w(String tag,String msg){ // if(level <= WARN){ // Log.w(tag, msg); // } // } // // public static void e(String tag,String msg){ // if(level <= ERROR){ // Log.e(tag, msg); // } // } // // } // // Path: app/src/main/java/com/yoga/oneweather/util/MiscUtil.java // public class MiscUtil { // /** // * 测量 view // * @param measureSpec // * @param defaultSize View的默认大小 // * @return // */ // public static int measure(int measureSpec ,int defaultSize){ // int result = defaultSize; // int specMode = View.MeasureSpec.getMode(measureSpec); // int specSize = View.MeasureSpec.getSize(measureSpec); // if(specMode == View.MeasureSpec.EXACTLY){ // result = specSize; // }else if(specMode == View.MeasureSpec.AT_MOST){ // result = Math.min(result,specSize); // } // return result; // } // // /** // * dp 转 px // * @param context // * @param dip // * @return // */ // public static int dipToPx(Context context, float dip){ // float density = context.getResources().getDisplayMetrics().density; // return (int) (dip * density + 0.5f * (dip >= 0 ? 1 : -1)); // } // // // /** // * 获取数值精度格式化字符串 // * @param precision // * @return // */ // public static String getPrecisionFormat(int precision){ // return "%."+precision+"f" ; // } // // // // /** // * 测量文字高度 // */ // public static float measureTextHeight(Paint paint){ // Paint .FontMetrics fontMetrics = paint.getFontMetrics(); // return (Math.abs(fontMetrics.ascent) + fontMetrics.descent); // } // // // }
import android.animation.ObjectAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.DashPathEffect; import android.graphics.Paint; import android.graphics.Point; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.RectF; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; import android.view.animation.LinearInterpolator; import com.yoga.oneweather.R; import com.yoga.oneweather.util.LogUtil; import com.yoga.oneweather.util.MiscUtil; import static java.lang.Math.PI; import static java.lang.Math.cos; import static java.lang.Math.sin;
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(MiscUtil.measure(widthMeasureSpec,mDefaultSize),MiscUtil.measure(heightMeasureSpec, (int) (mDefaultSize * 0.55))); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); width = w - getPaddingLeft() - getPaddingRight(); height = h - getPaddingBottom() - getPaddingTop(); mRadius = ((width / 2) < height ? (width/2) : height) - MiscUtil.dipToPx(mContext,15);//留出一定空间 mCenterPoint.x = width/2; mCenterPoint.y = height; mRectF.left = mCenterPoint.x - mRadius; mRectF.top = mCenterPoint.y - mRadius; mRectF.right = mCenterPoint.x + mRadius; mRectF.bottom = mCenterPoint.y + mRadius; lineYLocate = (float) (mCenterPoint.y - mRadius * sin(PI/180*(180 - sweepAngle)/2)); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.save(); drawArc(canvas); drawText(canvas); canvas.restore();
// Path: app/src/main/java/com/yoga/oneweather/util/LogUtil.java // public class LogUtil { // public static final int VERBOSE = 1; // public static final int DEBUG = 2 ; // public static final int INFO = 3 ; // public static final int WARN = 4 ; // public static final int ERROR = 5 ; // public static final int NOTHING = 6 ; // // public static int level = VERBOSE ; // public static void v(String tag, String msg){ // if(level == VERBOSE){ // Log.v(tag, msg); // } // } // public static void d(String tag,String msg){ // if(level <= DEBUG){ // Log.d(tag, msg); // } // } // // public static void i(String tag,String msg){ // if(level <= INFO){ // Log.i(tag, msg); // } // } // // // public static void w(String tag,String msg){ // if(level <= WARN){ // Log.w(tag, msg); // } // } // // public static void e(String tag,String msg){ // if(level <= ERROR){ // Log.e(tag, msg); // } // } // // } // // Path: app/src/main/java/com/yoga/oneweather/util/MiscUtil.java // public class MiscUtil { // /** // * 测量 view // * @param measureSpec // * @param defaultSize View的默认大小 // * @return // */ // public static int measure(int measureSpec ,int defaultSize){ // int result = defaultSize; // int specMode = View.MeasureSpec.getMode(measureSpec); // int specSize = View.MeasureSpec.getSize(measureSpec); // if(specMode == View.MeasureSpec.EXACTLY){ // result = specSize; // }else if(specMode == View.MeasureSpec.AT_MOST){ // result = Math.min(result,specSize); // } // return result; // } // // /** // * dp 转 px // * @param context // * @param dip // * @return // */ // public static int dipToPx(Context context, float dip){ // float density = context.getResources().getDisplayMetrics().density; // return (int) (dip * density + 0.5f * (dip >= 0 ? 1 : -1)); // } // // // /** // * 获取数值精度格式化字符串 // * @param precision // * @return // */ // public static String getPrecisionFormat(int precision){ // return "%."+precision+"f" ; // } // // // // /** // * 测量文字高度 // */ // public static float measureTextHeight(Paint paint){ // Paint .FontMetrics fontMetrics = paint.getFontMetrics(); // return (Math.abs(fontMetrics.ascent) + fontMetrics.descent); // } // // // } // Path: app/src/main/java/com/yoga/oneweather/widget/SunriseSunset.java import android.animation.ObjectAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.DashPathEffect; import android.graphics.Paint; import android.graphics.Point; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.RectF; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; import android.view.animation.LinearInterpolator; import com.yoga.oneweather.R; import com.yoga.oneweather.util.LogUtil; import com.yoga.oneweather.util.MiscUtil; import static java.lang.Math.PI; import static java.lang.Math.cos; import static java.lang.Math.sin; @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(MiscUtil.measure(widthMeasureSpec,mDefaultSize),MiscUtil.measure(heightMeasureSpec, (int) (mDefaultSize * 0.55))); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); width = w - getPaddingLeft() - getPaddingRight(); height = h - getPaddingBottom() - getPaddingTop(); mRadius = ((width / 2) < height ? (width/2) : height) - MiscUtil.dipToPx(mContext,15);//留出一定空间 mCenterPoint.x = width/2; mCenterPoint.y = height; mRectF.left = mCenterPoint.x - mRadius; mRectF.top = mCenterPoint.y - mRadius; mRectF.right = mCenterPoint.x + mRadius; mRectF.bottom = mCenterPoint.y + mRadius; lineYLocate = (float) (mCenterPoint.y - mRadius * sin(PI/180*(180 - sweepAngle)/2)); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.save(); drawArc(canvas); drawText(canvas); canvas.restore();
LogUtil.d(TAG, "onDraw: ");
YugengWang/OneWeather
app/src/main/java/com/yoga/oneweather/widget/Windmill.java
// Path: app/src/main/java/com/yoga/oneweather/util/LogUtil.java // public class LogUtil { // public static final int VERBOSE = 1; // public static final int DEBUG = 2 ; // public static final int INFO = 3 ; // public static final int WARN = 4 ; // public static final int ERROR = 5 ; // public static final int NOTHING = 6 ; // // public static int level = VERBOSE ; // public static void v(String tag, String msg){ // if(level == VERBOSE){ // Log.v(tag, msg); // } // } // public static void d(String tag,String msg){ // if(level <= DEBUG){ // Log.d(tag, msg); // } // } // // public static void i(String tag,String msg){ // if(level <= INFO){ // Log.i(tag, msg); // } // } // // // public static void w(String tag,String msg){ // if(level <= WARN){ // Log.w(tag, msg); // } // } // // public static void e(String tag,String msg){ // if(level <= ERROR){ // Log.e(tag, msg); // } // } // // } // // Path: app/src/main/java/com/yoga/oneweather/util/MiscUtil.java // public class MiscUtil { // /** // * 测量 view // * @param measureSpec // * @param defaultSize View的默认大小 // * @return // */ // public static int measure(int measureSpec ,int defaultSize){ // int result = defaultSize; // int specMode = View.MeasureSpec.getMode(measureSpec); // int specSize = View.MeasureSpec.getSize(measureSpec); // if(specMode == View.MeasureSpec.EXACTLY){ // result = specSize; // }else if(specMode == View.MeasureSpec.AT_MOST){ // result = Math.min(result,specSize); // } // return result; // } // // /** // * dp 转 px // * @param context // * @param dip // * @return // */ // public static int dipToPx(Context context, float dip){ // float density = context.getResources().getDisplayMetrics().density; // return (int) (dip * density + 0.5f * (dip >= 0 ? 1 : -1)); // } // // // /** // * 获取数值精度格式化字符串 // * @param precision // * @return // */ // public static String getPrecisionFormat(int precision){ // return "%."+precision+"f" ; // } // // // // /** // * 测量文字高度 // */ // public static float measureTextHeight(Paint paint){ // Paint .FontMetrics fontMetrics = paint.getFontMetrics(); // return (Math.abs(fontMetrics.ascent) + fontMetrics.descent); // } // // // }
import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Point; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; import android.view.animation.LinearInterpolator; import com.yoga.oneweather.R; import com.yoga.oneweather.util.LogUtil; import com.yoga.oneweather.util.MiscUtil; import static java.lang.Math.PI; import static java.lang.Math.atan;
package com.yoga.oneweather.widget; /** * Created by wyg on 2017/8/1. */ public class Windmill extends View { private Paint mWindmillPaint; //支柱画笔 private Path mWindPath; private Path mPillarPath; private int width,height; private int mWindmillColor;//风车颜色 private float mWindLengthPercent;//扇叶长度 private Point mCenterPoint;//圆心 private float x1,y1,x2,y2,x3,y3,x4,y4,x5,y5;//扇叶的点 private double rad1,rad2,rad3,rad4;//弧度 private double r1,r2,r3,r4;//斜边 private ObjectAnimator mAnimator;//动画 private float angle;//旋转角度 private int windSpeed = 1; private int mDefualtSize; private Context mContext; private static final float DEFAULT_DIP = 120; private static final String TAG = "Windmill"; public Windmill(Context context) { this(context,null); } public Windmill(Context context, @Nullable AttributeSet attrs) { this(context, attrs,0); } public Windmill(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr);
// Path: app/src/main/java/com/yoga/oneweather/util/LogUtil.java // public class LogUtil { // public static final int VERBOSE = 1; // public static final int DEBUG = 2 ; // public static final int INFO = 3 ; // public static final int WARN = 4 ; // public static final int ERROR = 5 ; // public static final int NOTHING = 6 ; // // public static int level = VERBOSE ; // public static void v(String tag, String msg){ // if(level == VERBOSE){ // Log.v(tag, msg); // } // } // public static void d(String tag,String msg){ // if(level <= DEBUG){ // Log.d(tag, msg); // } // } // // public static void i(String tag,String msg){ // if(level <= INFO){ // Log.i(tag, msg); // } // } // // // public static void w(String tag,String msg){ // if(level <= WARN){ // Log.w(tag, msg); // } // } // // public static void e(String tag,String msg){ // if(level <= ERROR){ // Log.e(tag, msg); // } // } // // } // // Path: app/src/main/java/com/yoga/oneweather/util/MiscUtil.java // public class MiscUtil { // /** // * 测量 view // * @param measureSpec // * @param defaultSize View的默认大小 // * @return // */ // public static int measure(int measureSpec ,int defaultSize){ // int result = defaultSize; // int specMode = View.MeasureSpec.getMode(measureSpec); // int specSize = View.MeasureSpec.getSize(measureSpec); // if(specMode == View.MeasureSpec.EXACTLY){ // result = specSize; // }else if(specMode == View.MeasureSpec.AT_MOST){ // result = Math.min(result,specSize); // } // return result; // } // // /** // * dp 转 px // * @param context // * @param dip // * @return // */ // public static int dipToPx(Context context, float dip){ // float density = context.getResources().getDisplayMetrics().density; // return (int) (dip * density + 0.5f * (dip >= 0 ? 1 : -1)); // } // // // /** // * 获取数值精度格式化字符串 // * @param precision // * @return // */ // public static String getPrecisionFormat(int precision){ // return "%."+precision+"f" ; // } // // // // /** // * 测量文字高度 // */ // public static float measureTextHeight(Paint paint){ // Paint .FontMetrics fontMetrics = paint.getFontMetrics(); // return (Math.abs(fontMetrics.ascent) + fontMetrics.descent); // } // // // } // Path: app/src/main/java/com/yoga/oneweather/widget/Windmill.java import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Point; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; import android.view.animation.LinearInterpolator; import com.yoga.oneweather.R; import com.yoga.oneweather.util.LogUtil; import com.yoga.oneweather.util.MiscUtil; import static java.lang.Math.PI; import static java.lang.Math.atan; package com.yoga.oneweather.widget; /** * Created by wyg on 2017/8/1. */ public class Windmill extends View { private Paint mWindmillPaint; //支柱画笔 private Path mWindPath; private Path mPillarPath; private int width,height; private int mWindmillColor;//风车颜色 private float mWindLengthPercent;//扇叶长度 private Point mCenterPoint;//圆心 private float x1,y1,x2,y2,x3,y3,x4,y4,x5,y5;//扇叶的点 private double rad1,rad2,rad3,rad4;//弧度 private double r1,r2,r3,r4;//斜边 private ObjectAnimator mAnimator;//动画 private float angle;//旋转角度 private int windSpeed = 1; private int mDefualtSize; private Context mContext; private static final float DEFAULT_DIP = 120; private static final String TAG = "Windmill"; public Windmill(Context context) { this(context,null); } public Windmill(Context context, @Nullable AttributeSet attrs) { this(context, attrs,0); } public Windmill(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr);
LogUtil.d(TAG, "Windmill: "+"构造函数");
YugengWang/OneWeather
app/src/main/java/com/yoga/oneweather/widget/Windmill.java
// Path: app/src/main/java/com/yoga/oneweather/util/LogUtil.java // public class LogUtil { // public static final int VERBOSE = 1; // public static final int DEBUG = 2 ; // public static final int INFO = 3 ; // public static final int WARN = 4 ; // public static final int ERROR = 5 ; // public static final int NOTHING = 6 ; // // public static int level = VERBOSE ; // public static void v(String tag, String msg){ // if(level == VERBOSE){ // Log.v(tag, msg); // } // } // public static void d(String tag,String msg){ // if(level <= DEBUG){ // Log.d(tag, msg); // } // } // // public static void i(String tag,String msg){ // if(level <= INFO){ // Log.i(tag, msg); // } // } // // // public static void w(String tag,String msg){ // if(level <= WARN){ // Log.w(tag, msg); // } // } // // public static void e(String tag,String msg){ // if(level <= ERROR){ // Log.e(tag, msg); // } // } // // } // // Path: app/src/main/java/com/yoga/oneweather/util/MiscUtil.java // public class MiscUtil { // /** // * 测量 view // * @param measureSpec // * @param defaultSize View的默认大小 // * @return // */ // public static int measure(int measureSpec ,int defaultSize){ // int result = defaultSize; // int specMode = View.MeasureSpec.getMode(measureSpec); // int specSize = View.MeasureSpec.getSize(measureSpec); // if(specMode == View.MeasureSpec.EXACTLY){ // result = specSize; // }else if(specMode == View.MeasureSpec.AT_MOST){ // result = Math.min(result,specSize); // } // return result; // } // // /** // * dp 转 px // * @param context // * @param dip // * @return // */ // public static int dipToPx(Context context, float dip){ // float density = context.getResources().getDisplayMetrics().density; // return (int) (dip * density + 0.5f * (dip >= 0 ? 1 : -1)); // } // // // /** // * 获取数值精度格式化字符串 // * @param precision // * @return // */ // public static String getPrecisionFormat(int precision){ // return "%."+precision+"f" ; // } // // // // /** // * 测量文字高度 // */ // public static float measureTextHeight(Paint paint){ // Paint .FontMetrics fontMetrics = paint.getFontMetrics(); // return (Math.abs(fontMetrics.ascent) + fontMetrics.descent); // } // // // }
import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Point; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; import android.view.animation.LinearInterpolator; import com.yoga.oneweather.R; import com.yoga.oneweather.util.LogUtil; import com.yoga.oneweather.util.MiscUtil; import static java.lang.Math.PI; import static java.lang.Math.atan;
public Windmill(Context context, @Nullable AttributeSet attrs) { this(context, attrs,0); } public Windmill(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); LogUtil.d(TAG, "Windmill: "+"构造函数"); mContext = context; init(attrs); } private void init(AttributeSet attrs) { initAttrs(attrs); mWindmillPaint = new Paint(); mCenterPoint = new Point(); mWindmillPaint.setStyle(Paint.Style.FILL); mWindmillPaint.setStrokeWidth(2);//设置画笔粗细 mWindmillPaint.setAntiAlias(true); mWindmillPaint.setColor(mWindmillColor); mAnimator = ObjectAnimator.ofFloat(this,"angle",0,(float)(2*PI));// mAnimator.setRepeatCount(ValueAnimator.INFINITE); mAnimator.setInterpolator(new LinearInterpolator()); } private void initAttrs(AttributeSet attrs){
// Path: app/src/main/java/com/yoga/oneweather/util/LogUtil.java // public class LogUtil { // public static final int VERBOSE = 1; // public static final int DEBUG = 2 ; // public static final int INFO = 3 ; // public static final int WARN = 4 ; // public static final int ERROR = 5 ; // public static final int NOTHING = 6 ; // // public static int level = VERBOSE ; // public static void v(String tag, String msg){ // if(level == VERBOSE){ // Log.v(tag, msg); // } // } // public static void d(String tag,String msg){ // if(level <= DEBUG){ // Log.d(tag, msg); // } // } // // public static void i(String tag,String msg){ // if(level <= INFO){ // Log.i(tag, msg); // } // } // // // public static void w(String tag,String msg){ // if(level <= WARN){ // Log.w(tag, msg); // } // } // // public static void e(String tag,String msg){ // if(level <= ERROR){ // Log.e(tag, msg); // } // } // // } // // Path: app/src/main/java/com/yoga/oneweather/util/MiscUtil.java // public class MiscUtil { // /** // * 测量 view // * @param measureSpec // * @param defaultSize View的默认大小 // * @return // */ // public static int measure(int measureSpec ,int defaultSize){ // int result = defaultSize; // int specMode = View.MeasureSpec.getMode(measureSpec); // int specSize = View.MeasureSpec.getSize(measureSpec); // if(specMode == View.MeasureSpec.EXACTLY){ // result = specSize; // }else if(specMode == View.MeasureSpec.AT_MOST){ // result = Math.min(result,specSize); // } // return result; // } // // /** // * dp 转 px // * @param context // * @param dip // * @return // */ // public static int dipToPx(Context context, float dip){ // float density = context.getResources().getDisplayMetrics().density; // return (int) (dip * density + 0.5f * (dip >= 0 ? 1 : -1)); // } // // // /** // * 获取数值精度格式化字符串 // * @param precision // * @return // */ // public static String getPrecisionFormat(int precision){ // return "%."+precision+"f" ; // } // // // // /** // * 测量文字高度 // */ // public static float measureTextHeight(Paint paint){ // Paint .FontMetrics fontMetrics = paint.getFontMetrics(); // return (Math.abs(fontMetrics.ascent) + fontMetrics.descent); // } // // // } // Path: app/src/main/java/com/yoga/oneweather/widget/Windmill.java import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Point; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; import android.view.animation.LinearInterpolator; import com.yoga.oneweather.R; import com.yoga.oneweather.util.LogUtil; import com.yoga.oneweather.util.MiscUtil; import static java.lang.Math.PI; import static java.lang.Math.atan; public Windmill(Context context, @Nullable AttributeSet attrs) { this(context, attrs,0); } public Windmill(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); LogUtil.d(TAG, "Windmill: "+"构造函数"); mContext = context; init(attrs); } private void init(AttributeSet attrs) { initAttrs(attrs); mWindmillPaint = new Paint(); mCenterPoint = new Point(); mWindmillPaint.setStyle(Paint.Style.FILL); mWindmillPaint.setStrokeWidth(2);//设置画笔粗细 mWindmillPaint.setAntiAlias(true); mWindmillPaint.setColor(mWindmillColor); mAnimator = ObjectAnimator.ofFloat(this,"angle",0,(float)(2*PI));// mAnimator.setRepeatCount(ValueAnimator.INFINITE); mAnimator.setInterpolator(new LinearInterpolator()); } private void initAttrs(AttributeSet attrs){
mDefualtSize = MiscUtil.dipToPx(mContext,DEFAULT_DIP);
YugengWang/OneWeather
app/src/main/java/com/yoga/oneweather/ui/SettingFragment.java
// Path: app/src/main/java/com/yoga/oneweather/util/LogUtil.java // public class LogUtil { // public static final int VERBOSE = 1; // public static final int DEBUG = 2 ; // public static final int INFO = 3 ; // public static final int WARN = 4 ; // public static final int ERROR = 5 ; // public static final int NOTHING = 6 ; // // public static int level = VERBOSE ; // public static void v(String tag, String msg){ // if(level == VERBOSE){ // Log.v(tag, msg); // } // } // public static void d(String tag,String msg){ // if(level <= DEBUG){ // Log.d(tag, msg); // } // } // // public static void i(String tag,String msg){ // if(level <= INFO){ // Log.i(tag, msg); // } // } // // // public static void w(String tag,String msg){ // if(level <= WARN){ // Log.w(tag, msg); // } // } // // public static void e(String tag,String msg){ // if(level <= ERROR){ // Log.e(tag, msg); // } // } // // }
import android.content.SharedPreferences; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceFragment; import android.support.annotation.Nullable; import com.yoga.oneweather.R; import com.yoga.oneweather.util.LogUtil;
package com.yoga.oneweather.ui; /** * Created by wyg on 2017/8/12. */ public class SettingFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener{ @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.setting); } @Override public void onResume() { super.onResume(); getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); } @Override public void onPause() { super.onPause(); getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if("auto_update_rate".equals(key)){ Preference update_rate = findPreference(key); update_rate.setSummary(sharedPreferences.getString(key,"6")+"小时");
// Path: app/src/main/java/com/yoga/oneweather/util/LogUtil.java // public class LogUtil { // public static final int VERBOSE = 1; // public static final int DEBUG = 2 ; // public static final int INFO = 3 ; // public static final int WARN = 4 ; // public static final int ERROR = 5 ; // public static final int NOTHING = 6 ; // // public static int level = VERBOSE ; // public static void v(String tag, String msg){ // if(level == VERBOSE){ // Log.v(tag, msg); // } // } // public static void d(String tag,String msg){ // if(level <= DEBUG){ // Log.d(tag, msg); // } // } // // public static void i(String tag,String msg){ // if(level <= INFO){ // Log.i(tag, msg); // } // } // // // public static void w(String tag,String msg){ // if(level <= WARN){ // Log.w(tag, msg); // } // } // // public static void e(String tag,String msg){ // if(level <= ERROR){ // Log.e(tag, msg); // } // } // // } // Path: app/src/main/java/com/yoga/oneweather/ui/SettingFragment.java import android.content.SharedPreferences; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceFragment; import android.support.annotation.Nullable; import com.yoga.oneweather.R; import com.yoga.oneweather.util.LogUtil; package com.yoga.oneweather.ui; /** * Created by wyg on 2017/8/12. */ public class SettingFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener{ @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.setting); } @Override public void onResume() { super.onResume(); getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); } @Override public void onPause() { super.onPause(); getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if("auto_update_rate".equals(key)){ Preference update_rate = findPreference(key); update_rate.setSummary(sharedPreferences.getString(key,"6")+"小时");
LogUtil.d("SettingFragment", "onSharedPreferenceChanged: ");
YugengWang/OneWeather
app/src/main/java/com/yoga/oneweather/util/PreferencesUtil.java
// Path: app/src/main/java/com/yoga/oneweather/MyApplication.java // public class MyApplication extends Application { // // private static Context context; // private static Gson mGson = new Gson(); // // // // @Override // public void onCreate() { // super.onCreate(); // context = getApplicationContext(); // LitePal.initialize(context); // DBManager.getInstance().copyCitysToDB(); // // // // } // // public static Gson getGson() { // return mGson; // } // // public static Context getContext() { // return context; // } // }
import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.yoga.oneweather.MyApplication;
package com.yoga.oneweather.util; /** * Created by wyg on 2017/7/26. */ public class PreferencesUtil { public static SharedPreferences getPreferences(){
// Path: app/src/main/java/com/yoga/oneweather/MyApplication.java // public class MyApplication extends Application { // // private static Context context; // private static Gson mGson = new Gson(); // // // // @Override // public void onCreate() { // super.onCreate(); // context = getApplicationContext(); // LitePal.initialize(context); // DBManager.getInstance().copyCitysToDB(); // // // // } // // public static Gson getGson() { // return mGson; // } // // public static Context getContext() { // return context; // } // } // Path: app/src/main/java/com/yoga/oneweather/util/PreferencesUtil.java import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.yoga.oneweather.MyApplication; package com.yoga.oneweather.util; /** * Created by wyg on 2017/7/26. */ public class PreferencesUtil { public static SharedPreferences getPreferences(){
return PreferenceManager.getDefaultSharedPreferences(MyApplication.getContext());
YugengWang/OneWeather
app/src/main/java/com/yoga/oneweather/city/HeaderHolder.java
// Path: app/src/main/java/com/yoga/oneweather/MyApplication.java // public class MyApplication extends Application { // // private static Context context; // private static Gson mGson = new Gson(); // // // // @Override // public void onCreate() { // super.onCreate(); // context = getApplicationContext(); // LitePal.initialize(context); // DBManager.getInstance().copyCitysToDB(); // // // // } // // public static Gson getGson() { // return mGson; // } // // public static Context getContext() { // return context; // } // }
import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.TextView; import com.yoga.oneweather.MyApplication; import com.yoga.oneweather.R;
package com.yoga.oneweather.city; /** * Created by wyg on 2017/7/24. */ public class HeaderHolder extends RecyclerView.ViewHolder { RecyclerView header_recyclerView; TextView locateText; public HeaderHolder(View itemView) { super(itemView); header_recyclerView = (RecyclerView) itemView.findViewById(R.id.header_recyclerView); locateText = (TextView) itemView.findViewById(R.id.located_city);
// Path: app/src/main/java/com/yoga/oneweather/MyApplication.java // public class MyApplication extends Application { // // private static Context context; // private static Gson mGson = new Gson(); // // // // @Override // public void onCreate() { // super.onCreate(); // context = getApplicationContext(); // LitePal.initialize(context); // DBManager.getInstance().copyCitysToDB(); // // // // } // // public static Gson getGson() { // return mGson; // } // // public static Context getContext() { // return context; // } // } // Path: app/src/main/java/com/yoga/oneweather/city/HeaderHolder.java import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.TextView; import com.yoga.oneweather.MyApplication; import com.yoga.oneweather.R; package com.yoga.oneweather.city; /** * Created by wyg on 2017/7/24. */ public class HeaderHolder extends RecyclerView.ViewHolder { RecyclerView header_recyclerView; TextView locateText; public HeaderHolder(View itemView) { super(itemView); header_recyclerView = (RecyclerView) itemView.findViewById(R.id.header_recyclerView); locateText = (TextView) itemView.findViewById(R.id.located_city);
header_recyclerView.setLayoutManager(new GridLayoutManager(MyApplication.getContext(),3));
YugengWang/OneWeather
app/src/main/java/com/yoga/oneweather/city/SearchViewAdapter.java
// Path: app/src/main/java/com/yoga/oneweather/model/db/CityDao.java // public class CityDao extends DataSupport { // /** // * city_unselected : 南子岛 // * cnty : 中国 // * cityID : CN101310230 // * lat : 11.26 // * lon : 114.20 // * prov : 海南 // */ // @Column(ignore = true) // private String mInitial = "#"; // // private String cityName; // private String cityId; // private String pinyin; // // // public String getmInitial() { // return mInitial; // } // // public void setmInitial(String mInitial) { // this.mInitial = mInitial; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getCityId() { // return cityId; // } // // public void setCityId(String id) { // this.cityId = id; // } // // public String getPinyin() { // return pinyin; // } // // public void setPinyin(String pinyin) { // this.pinyin = pinyin; // } // }
import android.support.v4.util.Pair; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.yoga.oneweather.R; import com.yoga.oneweather.model.db.CityDao; import java.util.ArrayList; import java.util.List;
package com.yoga.oneweather.city; /** * Created by wyg on 2017/7/24. */ public class SearchViewAdapter extends RecyclerView.Adapter { private final int ITEM_HEADER = 0; private final int ITEM_CITY = 1; public final static int LOCATE_SUCCESS = 111; public final static int LOCATE_ING = 222; public final static int LOCATE_FAILED = 333; private int locateState = LOCATE_ING;
// Path: app/src/main/java/com/yoga/oneweather/model/db/CityDao.java // public class CityDao extends DataSupport { // /** // * city_unselected : 南子岛 // * cnty : 中国 // * cityID : CN101310230 // * lat : 11.26 // * lon : 114.20 // * prov : 海南 // */ // @Column(ignore = true) // private String mInitial = "#"; // // private String cityName; // private String cityId; // private String pinyin; // // // public String getmInitial() { // return mInitial; // } // // public void setmInitial(String mInitial) { // this.mInitial = mInitial; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getCityId() { // return cityId; // } // // public void setCityId(String id) { // this.cityId = id; // } // // public String getPinyin() { // return pinyin; // } // // public void setPinyin(String pinyin) { // this.pinyin = pinyin; // } // } // Path: app/src/main/java/com/yoga/oneweather/city/SearchViewAdapter.java import android.support.v4.util.Pair; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.yoga.oneweather.R; import com.yoga.oneweather.model.db.CityDao; import java.util.ArrayList; import java.util.List; package com.yoga.oneweather.city; /** * Created by wyg on 2017/7/24. */ public class SearchViewAdapter extends RecyclerView.Adapter { private final int ITEM_HEADER = 0; private final int ITEM_CITY = 1; public final static int LOCATE_SUCCESS = 111; public final static int LOCATE_ING = 222; public final static int LOCATE_FAILED = 333; private int locateState = LOCATE_ING;
private List<CityDao> cityDaoList;//所有城市
YugengWang/OneWeather
app/src/main/java/com/yoga/oneweather/widget/CircleProgress.java
// Path: app/src/main/java/com/yoga/oneweather/util/Constant.java // public class Constant { // // public static final boolean ANTI_ALIAS = true; // // public static final int DEFAULT_SIZE = 150; // public static final int DEFAULT_START_ANGLE = 270; // public static final int DEFAULT_SWEEP_ANGLE = 360; // // public static final int DEFAULT_ANIM_TIME = 1500; // // public static final int DEFAULT_MAX_VALUE = 100; // public static final int DEFAULT_VALUE = 50; // // public static final int DEFAULT_HINT_SIZE = 25; // public static final int DEFAULT_UNIT_SIZE = 30; // public static final int DEFAULT_VALUE_SIZE = 40; // public static final int DEFAULT_TEXT_SIZE = 30; // // public static final int DEFAULT_ARC_WIDTH = 15; // // // public static final String WEATHER_URL = "https://free-api.heweather.com/v5/"; // public static final String LOCATE_KEY = "dc60aaa882c6854f93ac7e3d55516f58"; // public static final String WEATHER_KEY = "1c8bebce635648809e98babb820856c9"; // public static final String BASE_URL = "http://oy5qvvdsx.bkt.clouddn.com/oneweather/"; // public static final String CONDITION_ICON = BASE_URL + "condition_icon/"; // public static final String BACKGROUD_IAMGE = BASE_URL + "image/jpg/"; // // } // // Path: app/src/main/java/com/yoga/oneweather/util/LogUtil.java // public class LogUtil { // public static final int VERBOSE = 1; // public static final int DEBUG = 2 ; // public static final int INFO = 3 ; // public static final int WARN = 4 ; // public static final int ERROR = 5 ; // public static final int NOTHING = 6 ; // // public static int level = VERBOSE ; // public static void v(String tag, String msg){ // if(level == VERBOSE){ // Log.v(tag, msg); // } // } // public static void d(String tag,String msg){ // if(level <= DEBUG){ // Log.d(tag, msg); // } // } // // public static void i(String tag,String msg){ // if(level <= INFO){ // Log.i(tag, msg); // } // } // // // public static void w(String tag,String msg){ // if(level <= WARN){ // Log.w(tag, msg); // } // } // // public static void e(String tag,String msg){ // if(level <= ERROR){ // Log.e(tag, msg); // } // } // // } // // Path: app/src/main/java/com/yoga/oneweather/util/MiscUtil.java // public class MiscUtil { // /** // * 测量 view // * @param measureSpec // * @param defaultSize View的默认大小 // * @return // */ // public static int measure(int measureSpec ,int defaultSize){ // int result = defaultSize; // int specMode = View.MeasureSpec.getMode(measureSpec); // int specSize = View.MeasureSpec.getSize(measureSpec); // if(specMode == View.MeasureSpec.EXACTLY){ // result = specSize; // }else if(specMode == View.MeasureSpec.AT_MOST){ // result = Math.min(result,specSize); // } // return result; // } // // /** // * dp 转 px // * @param context // * @param dip // * @return // */ // public static int dipToPx(Context context, float dip){ // float density = context.getResources().getDisplayMetrics().density; // return (int) (dip * density + 0.5f * (dip >= 0 ? 1 : -1)); // } // // // /** // * 获取数值精度格式化字符串 // * @param precision // * @return // */ // public static String getPrecisionFormat(int precision){ // return "%."+precision+"f" ; // } // // // // /** // * 测量文字高度 // */ // public static float measureTextHeight(Paint paint){ // Paint .FontMetrics fontMetrics = paint.getFontMetrics(); // return (Math.abs(fontMetrics.ascent) + fontMetrics.descent); // } // // // }
import android.animation.ValueAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Point; import android.graphics.RectF; import android.graphics.SweepGradient; import android.graphics.Typeface; import android.support.v4.content.ContextCompat; import android.text.TextPaint; import android.util.AttributeSet; import android.view.View; import com.yoga.oneweather.BuildConfig; import com.yoga.oneweather.R; import com.yoga.oneweather.util.Constant; import com.yoga.oneweather.util.LogUtil; import com.yoga.oneweather.util.MiscUtil;
private float mArcWidth; private float mStartAngle,mSweepAngle; private RectF mRectF; //渐变的角度是360度,如果只显示270度,会缺失一段颜色 private SweepGradient mSweepGradient; private int[] mGradientColors = {Color.GREEN,Color.YELLOW,Color.RED}; //当前进度 private float mPercent; //动画时间 private long mAnimTime; //属性动画 private ValueAnimator mAnimator; //绘制背景圆弧 private Paint mBgArcPaint; private int mBgArcColor; private float mBgArcWidth; //圆心坐标,半径 private Point mCenterPoint; private float mRadius; private float mTextOffsetPercentInRadius; public CircleProgress(Context context, AttributeSet attrs){ super(context,attrs); init(context,attrs); } private void init(Context context, AttributeSet attrs){ mContext = context;
// Path: app/src/main/java/com/yoga/oneweather/util/Constant.java // public class Constant { // // public static final boolean ANTI_ALIAS = true; // // public static final int DEFAULT_SIZE = 150; // public static final int DEFAULT_START_ANGLE = 270; // public static final int DEFAULT_SWEEP_ANGLE = 360; // // public static final int DEFAULT_ANIM_TIME = 1500; // // public static final int DEFAULT_MAX_VALUE = 100; // public static final int DEFAULT_VALUE = 50; // // public static final int DEFAULT_HINT_SIZE = 25; // public static final int DEFAULT_UNIT_SIZE = 30; // public static final int DEFAULT_VALUE_SIZE = 40; // public static final int DEFAULT_TEXT_SIZE = 30; // // public static final int DEFAULT_ARC_WIDTH = 15; // // // public static final String WEATHER_URL = "https://free-api.heweather.com/v5/"; // public static final String LOCATE_KEY = "dc60aaa882c6854f93ac7e3d55516f58"; // public static final String WEATHER_KEY = "1c8bebce635648809e98babb820856c9"; // public static final String BASE_URL = "http://oy5qvvdsx.bkt.clouddn.com/oneweather/"; // public static final String CONDITION_ICON = BASE_URL + "condition_icon/"; // public static final String BACKGROUD_IAMGE = BASE_URL + "image/jpg/"; // // } // // Path: app/src/main/java/com/yoga/oneweather/util/LogUtil.java // public class LogUtil { // public static final int VERBOSE = 1; // public static final int DEBUG = 2 ; // public static final int INFO = 3 ; // public static final int WARN = 4 ; // public static final int ERROR = 5 ; // public static final int NOTHING = 6 ; // // public static int level = VERBOSE ; // public static void v(String tag, String msg){ // if(level == VERBOSE){ // Log.v(tag, msg); // } // } // public static void d(String tag,String msg){ // if(level <= DEBUG){ // Log.d(tag, msg); // } // } // // public static void i(String tag,String msg){ // if(level <= INFO){ // Log.i(tag, msg); // } // } // // // public static void w(String tag,String msg){ // if(level <= WARN){ // Log.w(tag, msg); // } // } // // public static void e(String tag,String msg){ // if(level <= ERROR){ // Log.e(tag, msg); // } // } // // } // // Path: app/src/main/java/com/yoga/oneweather/util/MiscUtil.java // public class MiscUtil { // /** // * 测量 view // * @param measureSpec // * @param defaultSize View的默认大小 // * @return // */ // public static int measure(int measureSpec ,int defaultSize){ // int result = defaultSize; // int specMode = View.MeasureSpec.getMode(measureSpec); // int specSize = View.MeasureSpec.getSize(measureSpec); // if(specMode == View.MeasureSpec.EXACTLY){ // result = specSize; // }else if(specMode == View.MeasureSpec.AT_MOST){ // result = Math.min(result,specSize); // } // return result; // } // // /** // * dp 转 px // * @param context // * @param dip // * @return // */ // public static int dipToPx(Context context, float dip){ // float density = context.getResources().getDisplayMetrics().density; // return (int) (dip * density + 0.5f * (dip >= 0 ? 1 : -1)); // } // // // /** // * 获取数值精度格式化字符串 // * @param precision // * @return // */ // public static String getPrecisionFormat(int precision){ // return "%."+precision+"f" ; // } // // // // /** // * 测量文字高度 // */ // public static float measureTextHeight(Paint paint){ // Paint .FontMetrics fontMetrics = paint.getFontMetrics(); // return (Math.abs(fontMetrics.ascent) + fontMetrics.descent); // } // // // } // Path: app/src/main/java/com/yoga/oneweather/widget/CircleProgress.java import android.animation.ValueAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Point; import android.graphics.RectF; import android.graphics.SweepGradient; import android.graphics.Typeface; import android.support.v4.content.ContextCompat; import android.text.TextPaint; import android.util.AttributeSet; import android.view.View; import com.yoga.oneweather.BuildConfig; import com.yoga.oneweather.R; import com.yoga.oneweather.util.Constant; import com.yoga.oneweather.util.LogUtil; import com.yoga.oneweather.util.MiscUtil; private float mArcWidth; private float mStartAngle,mSweepAngle; private RectF mRectF; //渐变的角度是360度,如果只显示270度,会缺失一段颜色 private SweepGradient mSweepGradient; private int[] mGradientColors = {Color.GREEN,Color.YELLOW,Color.RED}; //当前进度 private float mPercent; //动画时间 private long mAnimTime; //属性动画 private ValueAnimator mAnimator; //绘制背景圆弧 private Paint mBgArcPaint; private int mBgArcColor; private float mBgArcWidth; //圆心坐标,半径 private Point mCenterPoint; private float mRadius; private float mTextOffsetPercentInRadius; public CircleProgress(Context context, AttributeSet attrs){ super(context,attrs); init(context,attrs); } private void init(Context context, AttributeSet attrs){ mContext = context;
mDefaultSize = MiscUtil.dipToPx(mContext, Constant.DEFAULT_SIZE);
YugengWang/OneWeather
app/src/main/java/com/yoga/oneweather/widget/CircleProgress.java
// Path: app/src/main/java/com/yoga/oneweather/util/Constant.java // public class Constant { // // public static final boolean ANTI_ALIAS = true; // // public static final int DEFAULT_SIZE = 150; // public static final int DEFAULT_START_ANGLE = 270; // public static final int DEFAULT_SWEEP_ANGLE = 360; // // public static final int DEFAULT_ANIM_TIME = 1500; // // public static final int DEFAULT_MAX_VALUE = 100; // public static final int DEFAULT_VALUE = 50; // // public static final int DEFAULT_HINT_SIZE = 25; // public static final int DEFAULT_UNIT_SIZE = 30; // public static final int DEFAULT_VALUE_SIZE = 40; // public static final int DEFAULT_TEXT_SIZE = 30; // // public static final int DEFAULT_ARC_WIDTH = 15; // // // public static final String WEATHER_URL = "https://free-api.heweather.com/v5/"; // public static final String LOCATE_KEY = "dc60aaa882c6854f93ac7e3d55516f58"; // public static final String WEATHER_KEY = "1c8bebce635648809e98babb820856c9"; // public static final String BASE_URL = "http://oy5qvvdsx.bkt.clouddn.com/oneweather/"; // public static final String CONDITION_ICON = BASE_URL + "condition_icon/"; // public static final String BACKGROUD_IAMGE = BASE_URL + "image/jpg/"; // // } // // Path: app/src/main/java/com/yoga/oneweather/util/LogUtil.java // public class LogUtil { // public static final int VERBOSE = 1; // public static final int DEBUG = 2 ; // public static final int INFO = 3 ; // public static final int WARN = 4 ; // public static final int ERROR = 5 ; // public static final int NOTHING = 6 ; // // public static int level = VERBOSE ; // public static void v(String tag, String msg){ // if(level == VERBOSE){ // Log.v(tag, msg); // } // } // public static void d(String tag,String msg){ // if(level <= DEBUG){ // Log.d(tag, msg); // } // } // // public static void i(String tag,String msg){ // if(level <= INFO){ // Log.i(tag, msg); // } // } // // // public static void w(String tag,String msg){ // if(level <= WARN){ // Log.w(tag, msg); // } // } // // public static void e(String tag,String msg){ // if(level <= ERROR){ // Log.e(tag, msg); // } // } // // } // // Path: app/src/main/java/com/yoga/oneweather/util/MiscUtil.java // public class MiscUtil { // /** // * 测量 view // * @param measureSpec // * @param defaultSize View的默认大小 // * @return // */ // public static int measure(int measureSpec ,int defaultSize){ // int result = defaultSize; // int specMode = View.MeasureSpec.getMode(measureSpec); // int specSize = View.MeasureSpec.getSize(measureSpec); // if(specMode == View.MeasureSpec.EXACTLY){ // result = specSize; // }else if(specMode == View.MeasureSpec.AT_MOST){ // result = Math.min(result,specSize); // } // return result; // } // // /** // * dp 转 px // * @param context // * @param dip // * @return // */ // public static int dipToPx(Context context, float dip){ // float density = context.getResources().getDisplayMetrics().density; // return (int) (dip * density + 0.5f * (dip >= 0 ? 1 : -1)); // } // // // /** // * 获取数值精度格式化字符串 // * @param precision // * @return // */ // public static String getPrecisionFormat(int precision){ // return "%."+precision+"f" ; // } // // // // /** // * 测量文字高度 // */ // public static float measureTextHeight(Paint paint){ // Paint .FontMetrics fontMetrics = paint.getFontMetrics(); // return (Math.abs(fontMetrics.ascent) + fontMetrics.descent); // } // // // }
import android.animation.ValueAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Point; import android.graphics.RectF; import android.graphics.SweepGradient; import android.graphics.Typeface; import android.support.v4.content.ContextCompat; import android.text.TextPaint; import android.util.AttributeSet; import android.view.View; import com.yoga.oneweather.BuildConfig; import com.yoga.oneweather.R; import com.yoga.oneweather.util.Constant; import com.yoga.oneweather.util.LogUtil; import com.yoga.oneweather.util.MiscUtil;
private float mArcWidth; private float mStartAngle,mSweepAngle; private RectF mRectF; //渐变的角度是360度,如果只显示270度,会缺失一段颜色 private SweepGradient mSweepGradient; private int[] mGradientColors = {Color.GREEN,Color.YELLOW,Color.RED}; //当前进度 private float mPercent; //动画时间 private long mAnimTime; //属性动画 private ValueAnimator mAnimator; //绘制背景圆弧 private Paint mBgArcPaint; private int mBgArcColor; private float mBgArcWidth; //圆心坐标,半径 private Point mCenterPoint; private float mRadius; private float mTextOffsetPercentInRadius; public CircleProgress(Context context, AttributeSet attrs){ super(context,attrs); init(context,attrs); } private void init(Context context, AttributeSet attrs){ mContext = context;
// Path: app/src/main/java/com/yoga/oneweather/util/Constant.java // public class Constant { // // public static final boolean ANTI_ALIAS = true; // // public static final int DEFAULT_SIZE = 150; // public static final int DEFAULT_START_ANGLE = 270; // public static final int DEFAULT_SWEEP_ANGLE = 360; // // public static final int DEFAULT_ANIM_TIME = 1500; // // public static final int DEFAULT_MAX_VALUE = 100; // public static final int DEFAULT_VALUE = 50; // // public static final int DEFAULT_HINT_SIZE = 25; // public static final int DEFAULT_UNIT_SIZE = 30; // public static final int DEFAULT_VALUE_SIZE = 40; // public static final int DEFAULT_TEXT_SIZE = 30; // // public static final int DEFAULT_ARC_WIDTH = 15; // // // public static final String WEATHER_URL = "https://free-api.heweather.com/v5/"; // public static final String LOCATE_KEY = "dc60aaa882c6854f93ac7e3d55516f58"; // public static final String WEATHER_KEY = "1c8bebce635648809e98babb820856c9"; // public static final String BASE_URL = "http://oy5qvvdsx.bkt.clouddn.com/oneweather/"; // public static final String CONDITION_ICON = BASE_URL + "condition_icon/"; // public static final String BACKGROUD_IAMGE = BASE_URL + "image/jpg/"; // // } // // Path: app/src/main/java/com/yoga/oneweather/util/LogUtil.java // public class LogUtil { // public static final int VERBOSE = 1; // public static final int DEBUG = 2 ; // public static final int INFO = 3 ; // public static final int WARN = 4 ; // public static final int ERROR = 5 ; // public static final int NOTHING = 6 ; // // public static int level = VERBOSE ; // public static void v(String tag, String msg){ // if(level == VERBOSE){ // Log.v(tag, msg); // } // } // public static void d(String tag,String msg){ // if(level <= DEBUG){ // Log.d(tag, msg); // } // } // // public static void i(String tag,String msg){ // if(level <= INFO){ // Log.i(tag, msg); // } // } // // // public static void w(String tag,String msg){ // if(level <= WARN){ // Log.w(tag, msg); // } // } // // public static void e(String tag,String msg){ // if(level <= ERROR){ // Log.e(tag, msg); // } // } // // } // // Path: app/src/main/java/com/yoga/oneweather/util/MiscUtil.java // public class MiscUtil { // /** // * 测量 view // * @param measureSpec // * @param defaultSize View的默认大小 // * @return // */ // public static int measure(int measureSpec ,int defaultSize){ // int result = defaultSize; // int specMode = View.MeasureSpec.getMode(measureSpec); // int specSize = View.MeasureSpec.getSize(measureSpec); // if(specMode == View.MeasureSpec.EXACTLY){ // result = specSize; // }else if(specMode == View.MeasureSpec.AT_MOST){ // result = Math.min(result,specSize); // } // return result; // } // // /** // * dp 转 px // * @param context // * @param dip // * @return // */ // public static int dipToPx(Context context, float dip){ // float density = context.getResources().getDisplayMetrics().density; // return (int) (dip * density + 0.5f * (dip >= 0 ? 1 : -1)); // } // // // /** // * 获取数值精度格式化字符串 // * @param precision // * @return // */ // public static String getPrecisionFormat(int precision){ // return "%."+precision+"f" ; // } // // // // /** // * 测量文字高度 // */ // public static float measureTextHeight(Paint paint){ // Paint .FontMetrics fontMetrics = paint.getFontMetrics(); // return (Math.abs(fontMetrics.ascent) + fontMetrics.descent); // } // // // } // Path: app/src/main/java/com/yoga/oneweather/widget/CircleProgress.java import android.animation.ValueAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Point; import android.graphics.RectF; import android.graphics.SweepGradient; import android.graphics.Typeface; import android.support.v4.content.ContextCompat; import android.text.TextPaint; import android.util.AttributeSet; import android.view.View; import com.yoga.oneweather.BuildConfig; import com.yoga.oneweather.R; import com.yoga.oneweather.util.Constant; import com.yoga.oneweather.util.LogUtil; import com.yoga.oneweather.util.MiscUtil; private float mArcWidth; private float mStartAngle,mSweepAngle; private RectF mRectF; //渐变的角度是360度,如果只显示270度,会缺失一段颜色 private SweepGradient mSweepGradient; private int[] mGradientColors = {Color.GREEN,Color.YELLOW,Color.RED}; //当前进度 private float mPercent; //动画时间 private long mAnimTime; //属性动画 private ValueAnimator mAnimator; //绘制背景圆弧 private Paint mBgArcPaint; private int mBgArcColor; private float mBgArcWidth; //圆心坐标,半径 private Point mCenterPoint; private float mRadius; private float mTextOffsetPercentInRadius; public CircleProgress(Context context, AttributeSet attrs){ super(context,attrs); init(context,attrs); } private void init(Context context, AttributeSet attrs){ mContext = context;
mDefaultSize = MiscUtil.dipToPx(mContext, Constant.DEFAULT_SIZE);
PEMapModder/PocketMine-GUI
src/main/java/com/github/pemapmodder/pocketminegui/gui/startup/installer/cards/ChooseLocationCard.java
// Path: src/main/java/com/github/pemapmodder/pocketminegui/gui/startup/installer/InstallServerActivity.java // public class InstallServerActivity extends CardActivity{ // @Getter private File selectedHome; // @Getter @Setter private File phpBinaries; // @Getter @Setter private Release selectedRelease; // // public InstallServerActivity(Activity parent){ // super("Install server", parent); // setExtendedState(MAXIMIZED_BOTH); // } // // @Override // public Card[] getDefaultCards(){ // return new Card[]{ // new ChooseLocationCard(this), // new ChooseVersionCard(this), // new DownloadProgressCard(this), // new PhpInstallerCard(this), // new ServerSetupCard(this), // }; // } // // public void setSelectedHome(File selectedHome){ // this.selectedHome = selectedHome; // selectedHome.mkdirs(); // } // // @Override // protected void setCard(int index, int exitType){ // super.setCard(index, exitType); // setExtendedState(MAXIMIZED_BOTH); // } // // @Override // protected void onFinish(){ // super.onFinish(); // getParent().initNewActivity(new ServerMainActivity(selectedHome, phpBinaries)); // } // } // // Path: src/main/java/com/github/pemapmodder/pocketminegui/lib/card/Card.java // public abstract class Card extends JPanel{ // /** // * The {@link CardActivity} is closed. // */ // public final static int EXIT_CLOSE = 0; // /** // * The "Back" button is triggered. // */ // public final static int EXIT_BACK = 1; // /** // * The "Next" button is triggered. // */ // public final static int EXIT_NEXT = 2; // // public void onEntry(){ // } // // /** // * Triggered when card is swapped // * // * @param type one of {@link #EXIT_CLOSE}, {@link #EXIT_BACK} and {@link #EXIT_NEXT} // * @return whether to allow this action // */ // public boolean onExit(int type){ // return true; // } // // public abstract String getCardName(); // // public void onStop(){ // } // }
import com.github.pemapmodder.pocketminegui.gui.startup.installer.InstallServerActivity; import com.github.pemapmodder.pocketminegui.lib.card.Card; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File;
package com.github.pemapmodder.pocketminegui.gui.startup.installer.cards; /* * This file is part of PocketMine-GUI. * * PocketMine-GUI is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PocketMine-GUI 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 PocketMine-GUI. If not, see <http://www.gnu.org/licenses/>. */ public class ChooseLocationCard extends Card implements ActionListener{ private final JTextField pathField;
// Path: src/main/java/com/github/pemapmodder/pocketminegui/gui/startup/installer/InstallServerActivity.java // public class InstallServerActivity extends CardActivity{ // @Getter private File selectedHome; // @Getter @Setter private File phpBinaries; // @Getter @Setter private Release selectedRelease; // // public InstallServerActivity(Activity parent){ // super("Install server", parent); // setExtendedState(MAXIMIZED_BOTH); // } // // @Override // public Card[] getDefaultCards(){ // return new Card[]{ // new ChooseLocationCard(this), // new ChooseVersionCard(this), // new DownloadProgressCard(this), // new PhpInstallerCard(this), // new ServerSetupCard(this), // }; // } // // public void setSelectedHome(File selectedHome){ // this.selectedHome = selectedHome; // selectedHome.mkdirs(); // } // // @Override // protected void setCard(int index, int exitType){ // super.setCard(index, exitType); // setExtendedState(MAXIMIZED_BOTH); // } // // @Override // protected void onFinish(){ // super.onFinish(); // getParent().initNewActivity(new ServerMainActivity(selectedHome, phpBinaries)); // } // } // // Path: src/main/java/com/github/pemapmodder/pocketminegui/lib/card/Card.java // public abstract class Card extends JPanel{ // /** // * The {@link CardActivity} is closed. // */ // public final static int EXIT_CLOSE = 0; // /** // * The "Back" button is triggered. // */ // public final static int EXIT_BACK = 1; // /** // * The "Next" button is triggered. // */ // public final static int EXIT_NEXT = 2; // // public void onEntry(){ // } // // /** // * Triggered when card is swapped // * // * @param type one of {@link #EXIT_CLOSE}, {@link #EXIT_BACK} and {@link #EXIT_NEXT} // * @return whether to allow this action // */ // public boolean onExit(int type){ // return true; // } // // public abstract String getCardName(); // // public void onStop(){ // } // } // Path: src/main/java/com/github/pemapmodder/pocketminegui/gui/startup/installer/cards/ChooseLocationCard.java import com.github.pemapmodder.pocketminegui.gui.startup.installer.InstallServerActivity; import com.github.pemapmodder.pocketminegui.lib.card.Card; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; package com.github.pemapmodder.pocketminegui.gui.startup.installer.cards; /* * This file is part of PocketMine-GUI. * * PocketMine-GUI is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PocketMine-GUI 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 PocketMine-GUI. If not, see <http://www.gnu.org/licenses/>. */ public class ChooseLocationCard extends Card implements ActionListener{ private final JTextField pathField;
private final InstallServerActivity activity;
PEMapModder/PocketMine-GUI
src/main/java/com/github/pemapmodder/pocketminegui/lib/Activity.java
// Path: src/main/java/com/github/pemapmodder/pocketminegui/PocketMineGUI.java // public class PocketMineGUI{ // public static Activity CURRENT_ROOT_ACTIVITY = null; // // public static void main(String[] args){ // new ChooseServerActivity().init(); // } // }
import com.github.pemapmodder.pocketminegui.PocketMineGUI; import lombok.Getter; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.Border; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent;
package com.github.pemapmodder.pocketminegui.lib; /* * This file is part of PocketMine-GUI. * * PocketMine-GUI is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PocketMine-GUI 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 PocketMine-GUI. If not, see <http://www.gnu.org/licenses/>. */ public abstract class Activity extends JFrame{ @Getter private Activity parent, child = null; private boolean hasNewActivity = false; private boolean onStopCalled = false; public Activity(String title){ this(title, null); } public Activity(String title, Activity parent){ super(title); this.parent = parent; if(parent != null){ parent.setChild(this); } } public final void init(){ if(!hasParent()){
// Path: src/main/java/com/github/pemapmodder/pocketminegui/PocketMineGUI.java // public class PocketMineGUI{ // public static Activity CURRENT_ROOT_ACTIVITY = null; // // public static void main(String[] args){ // new ChooseServerActivity().init(); // } // } // Path: src/main/java/com/github/pemapmodder/pocketminegui/lib/Activity.java import com.github.pemapmodder.pocketminegui.PocketMineGUI; import lombok.Getter; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.Border; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; package com.github.pemapmodder.pocketminegui.lib; /* * This file is part of PocketMine-GUI. * * PocketMine-GUI is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PocketMine-GUI 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 PocketMine-GUI. If not, see <http://www.gnu.org/licenses/>. */ public abstract class Activity extends JFrame{ @Getter private Activity parent, child = null; private boolean hasNewActivity = false; private boolean onStopCalled = false; public Activity(String title){ this(title, null); } public Activity(String title, Activity parent){ super(title); this.parent = parent; if(parent != null){ parent.setChild(this); } } public final void init(){ if(!hasParent()){
if(PocketMineGUI.CURRENT_ROOT_ACTIVITY != null){
PEMapModder/PocketMine-GUI
src/main/java/com/github/pemapmodder/pocketminegui/gui/server/ServerLifetime.java
// Path: src/main/java/com/github/pemapmodder/pocketminegui/gui/server/ServerMainActivity.java // public enum ServerState{ // STATE_STOPPED("Start"), // STATE_STARTING("Starting..."), // STATE_RUNNING("Stop"), // STATE_STOPPING("Stopping..."); // // @Getter private String buttonName; // // ServerState(String buttonName){ // this.buttonName = buttonName; // } // }
import com.github.pemapmodder.pocketminegui.gui.server.ServerMainActivity.ServerState; import lombok.Getter; import lombok.RequiredArgsConstructor; import javax.swing.JButton; import java.awt.event.ActionEvent; import java.io.IOException;
package com.github.pemapmodder.pocketminegui.gui.server; /* * This file is part of PocketMine-GUI. * * PocketMine-GUI is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PocketMine-GUI 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 PocketMine-GUI. If not, see <http://www.gnu.org/licenses/>. */ @RequiredArgsConstructor public class ServerLifetime{ @Getter private final ServerMainActivity activity;
// Path: src/main/java/com/github/pemapmodder/pocketminegui/gui/server/ServerMainActivity.java // public enum ServerState{ // STATE_STOPPED("Start"), // STATE_STARTING("Starting..."), // STATE_RUNNING("Stop"), // STATE_STOPPING("Stopping..."); // // @Getter private String buttonName; // // ServerState(String buttonName){ // this.buttonName = buttonName; // } // } // Path: src/main/java/com/github/pemapmodder/pocketminegui/gui/server/ServerLifetime.java import com.github.pemapmodder.pocketminegui.gui.server.ServerMainActivity.ServerState; import lombok.Getter; import lombok.RequiredArgsConstructor; import javax.swing.JButton; import java.awt.event.ActionEvent; import java.io.IOException; package com.github.pemapmodder.pocketminegui.gui.server; /* * This file is part of PocketMine-GUI. * * PocketMine-GUI is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PocketMine-GUI 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 PocketMine-GUI. If not, see <http://www.gnu.org/licenses/>. */ @RequiredArgsConstructor public class ServerLifetime{ @Getter private final ServerMainActivity activity;
@Getter private ServerState state = ServerState.STATE_STOPPED;
PEMapModder/PocketMine-GUI
src/main/java/com/github/pemapmodder/pocketminegui/gui/startup/installer/FetchVersionsThread.java
// Path: src/main/java/com/github/pemapmodder/pocketminegui/gui/startup/installer/cards/ChooseVersionCard.java // public class ChooseVersionCard extends Card{ // private final InstallServerActivity activity; // @Getter // private final FetchVersionsThread versionFetch; // @Getter // private int nextIndex = 0; // @Getter // private Timer timer; // private final ButtonGroup typeRadios; // private final JLabel loadingLabel; // private final JPanel cardPanel; // private final CardLayout cardLayout; // private int choosenType = ReleaseType.STABLE.getTypeId(); // private final JList[] lists = new JList[ReleaseType.values().length]; // private final DefaultListModel[] listModels = new DefaultListModel[ReleaseType.values().length]; // @Getter // private Release selectedRelease = null; // // public ChooseVersionCard(InstallServerActivity activity){ // this.activity = activity; // typeRadios = new ButtonGroup(); // JPanel radioPanel = new JPanel(); // cardPanel = new JPanel(cardLayout = new CardLayout()); // for(ReleaseType type : ReleaseType.values()){ // JRadioButton button = new JRadioButton(type.getName()); // button.setMnemonic(type.getMnemonic()); // if(type == ReleaseType.STABLE){ // button.setSelected(true); // } // button.addActionListener(e -> onRadioClicked(type)); // typeRadios.add(button); // radioPanel.add(button); // // int id = type.getTypeId(); // JScrollPane pane = new JScrollPane(); // DefaultListModel<Release> model = new DefaultListModel<>(); // listModels[type.getTypeId()] = model; // JList<String> list = new JList<>(); // list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // list.addListSelectionListener(e -> { // Release release = model.get(list.getSelectedIndex()); // activity.setSelectedRelease(release); // activity.getNextButton().setEnabled(true); // }); // pane.getViewport().add(lists[type.getTypeId()] = list); // cardPanel.add(pane, type.getName()); // } // cardLayout.show(cardPanel, ReleaseType.STABLE.getName()); // setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); // add(radioPanel); // add(loadingLabel = new JLabel("Loading...")); // add(cardPanel); // // versionFetch = new FetchVersionsThread(this); // versionFetch.start(); // timer = new Timer(100, e -> updateVersions()); // timer.start(); // } // // private void onRadioClicked(ReleaseType type){ // cardLayout.show(cardPanel, type.getName()); // choosenType = type.getTypeId(); // activity.getNextButton().setEnabled(lists[choosenType].getSelectedIndex() != -1); // } // // private void updateVersions(){ // List<Release> releases = versionFetch.getReleases(); // int size = releases.size(); // for(int i = nextIndex; i < size; i++){ // Release release = releases.get(i); // addRelease(release); // } // nextIndex = size; // if(versionFetch.isDone()){ // if(timer != null){ // timer.stop(); // timer = null; // loadingLabel.setText(""); // } // } // } // // @SuppressWarnings("unchecked") // private void addRelease(final Release release){ // int id = release.getType().getTypeId(); // listModels[id].addElement(release); // lists[id].setModel(listModels[id]); // lists[id].revalidate(); // lists[id].repaint(); // } // // @Override // public void onEntry(){ // activity.getNextButton().setText("Install"); // activity.getNextButton().setEnabled(false); // activity.revalidate(); // } // // @Override // public boolean onExit(int type){ // activity.getNextButton().setText("Next"); // activity.revalidate(); // activity.getNextButton().setEnabled(true); // return true; // } // // @Override // public void onStop(){ // if(timer != null){ // timer.stop(); // timer = null; // } // } // // @Override // public String getCardName(){ // return "Choose PocketMine-MP version"; // } // }
import java.util.ArrayList; import java.util.List; import com.github.pemapmodder.pocketminegui.gui.startup.installer.cards.ChooseVersionCard; import lombok.Getter; import org.apache.commons.io.IOUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat;
package com.github.pemapmodder.pocketminegui.gui.startup.installer; /* * This file is part of PocketMine-GUI. * * PocketMine-GUI is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PocketMine-GUI 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 PocketMine-GUI. If not, see <http://www.gnu.org/licenses/>. */ public class FetchVersionsThread extends Thread{ @Getter
// Path: src/main/java/com/github/pemapmodder/pocketminegui/gui/startup/installer/cards/ChooseVersionCard.java // public class ChooseVersionCard extends Card{ // private final InstallServerActivity activity; // @Getter // private final FetchVersionsThread versionFetch; // @Getter // private int nextIndex = 0; // @Getter // private Timer timer; // private final ButtonGroup typeRadios; // private final JLabel loadingLabel; // private final JPanel cardPanel; // private final CardLayout cardLayout; // private int choosenType = ReleaseType.STABLE.getTypeId(); // private final JList[] lists = new JList[ReleaseType.values().length]; // private final DefaultListModel[] listModels = new DefaultListModel[ReleaseType.values().length]; // @Getter // private Release selectedRelease = null; // // public ChooseVersionCard(InstallServerActivity activity){ // this.activity = activity; // typeRadios = new ButtonGroup(); // JPanel radioPanel = new JPanel(); // cardPanel = new JPanel(cardLayout = new CardLayout()); // for(ReleaseType type : ReleaseType.values()){ // JRadioButton button = new JRadioButton(type.getName()); // button.setMnemonic(type.getMnemonic()); // if(type == ReleaseType.STABLE){ // button.setSelected(true); // } // button.addActionListener(e -> onRadioClicked(type)); // typeRadios.add(button); // radioPanel.add(button); // // int id = type.getTypeId(); // JScrollPane pane = new JScrollPane(); // DefaultListModel<Release> model = new DefaultListModel<>(); // listModels[type.getTypeId()] = model; // JList<String> list = new JList<>(); // list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // list.addListSelectionListener(e -> { // Release release = model.get(list.getSelectedIndex()); // activity.setSelectedRelease(release); // activity.getNextButton().setEnabled(true); // }); // pane.getViewport().add(lists[type.getTypeId()] = list); // cardPanel.add(pane, type.getName()); // } // cardLayout.show(cardPanel, ReleaseType.STABLE.getName()); // setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); // add(radioPanel); // add(loadingLabel = new JLabel("Loading...")); // add(cardPanel); // // versionFetch = new FetchVersionsThread(this); // versionFetch.start(); // timer = new Timer(100, e -> updateVersions()); // timer.start(); // } // // private void onRadioClicked(ReleaseType type){ // cardLayout.show(cardPanel, type.getName()); // choosenType = type.getTypeId(); // activity.getNextButton().setEnabled(lists[choosenType].getSelectedIndex() != -1); // } // // private void updateVersions(){ // List<Release> releases = versionFetch.getReleases(); // int size = releases.size(); // for(int i = nextIndex; i < size; i++){ // Release release = releases.get(i); // addRelease(release); // } // nextIndex = size; // if(versionFetch.isDone()){ // if(timer != null){ // timer.stop(); // timer = null; // loadingLabel.setText(""); // } // } // } // // @SuppressWarnings("unchecked") // private void addRelease(final Release release){ // int id = release.getType().getTypeId(); // listModels[id].addElement(release); // lists[id].setModel(listModels[id]); // lists[id].revalidate(); // lists[id].repaint(); // } // // @Override // public void onEntry(){ // activity.getNextButton().setText("Install"); // activity.getNextButton().setEnabled(false); // activity.revalidate(); // } // // @Override // public boolean onExit(int type){ // activity.getNextButton().setText("Next"); // activity.revalidate(); // activity.getNextButton().setEnabled(true); // return true; // } // // @Override // public void onStop(){ // if(timer != null){ // timer.stop(); // timer = null; // } // } // // @Override // public String getCardName(){ // return "Choose PocketMine-MP version"; // } // } // Path: src/main/java/com/github/pemapmodder/pocketminegui/gui/startup/installer/FetchVersionsThread.java import java.util.ArrayList; import java.util.List; import com.github.pemapmodder.pocketminegui.gui.startup.installer.cards.ChooseVersionCard; import lombok.Getter; import org.apache.commons.io.IOUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; package com.github.pemapmodder.pocketminegui.gui.startup.installer; /* * This file is part of PocketMine-GUI. * * PocketMine-GUI is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PocketMine-GUI 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 PocketMine-GUI. If not, see <http://www.gnu.org/licenses/>. */ public class FetchVersionsThread extends Thread{ @Getter
private final ChooseVersionCard card;
PEMapModder/PocketMine-GUI
src/main/java/com/github/pemapmodder/pocketminegui/gui/startup/installer/cards/DownloadProgressCard.java
// Path: src/main/java/com/github/pemapmodder/pocketminegui/gui/startup/installer/InstallServerActivity.java // public class InstallServerActivity extends CardActivity{ // @Getter private File selectedHome; // @Getter @Setter private File phpBinaries; // @Getter @Setter private Release selectedRelease; // // public InstallServerActivity(Activity parent){ // super("Install server", parent); // setExtendedState(MAXIMIZED_BOTH); // } // // @Override // public Card[] getDefaultCards(){ // return new Card[]{ // new ChooseLocationCard(this), // new ChooseVersionCard(this), // new DownloadProgressCard(this), // new PhpInstallerCard(this), // new ServerSetupCard(this), // }; // } // // public void setSelectedHome(File selectedHome){ // this.selectedHome = selectedHome; // selectedHome.mkdirs(); // } // // @Override // protected void setCard(int index, int exitType){ // super.setCard(index, exitType); // setExtendedState(MAXIMIZED_BOTH); // } // // @Override // protected void onFinish(){ // super.onFinish(); // getParent().initNewActivity(new ServerMainActivity(selectedHome, phpBinaries)); // } // } // // Path: src/main/java/com/github/pemapmodder/pocketminegui/lib/card/Card.java // public abstract class Card extends JPanel{ // /** // * The {@link CardActivity} is closed. // */ // public final static int EXIT_CLOSE = 0; // /** // * The "Back" button is triggered. // */ // public final static int EXIT_BACK = 1; // /** // * The "Next" button is triggered. // */ // public final static int EXIT_NEXT = 2; // // public void onEntry(){ // } // // /** // * Triggered when card is swapped // * // * @param type one of {@link #EXIT_CLOSE}, {@link #EXIT_BACK} and {@link #EXIT_NEXT} // * @return whether to allow this action // */ // public boolean onExit(int type){ // return true; // } // // public abstract String getCardName(); // // public void onStop(){ // } // } // // Path: src/main/java/com/github/pemapmodder/pocketminegui/utils/GetUrlThread.java // public class GetUrlThread extends AsyncTask{ // private final static int STEP = 512; // // private final URL url; // // public byte[] array; // // public GetUrlThread(URL url){ // this.url = url; // } // // @Override // public void run(){ // try{ // URLConnection conn = url.openConnection(); // setMax(conn.getContentLength()); // array = new byte[getMax()]; // try(InputStream is = conn.getInputStream()){ // int progress = 0; // int step = 0; // int pointer = 0; // while(true){ // byte[] buffer = new byte[STEP]; // int read = is.read(buffer); // if(read == -1){ // setProgress(getMax()); // return; // } // System.arraycopy(buffer, 0, array, pointer, read); // pointer += read; // setProgress(progress += STEP); // step++; // } // } // }catch(IOException e){ // e.printStackTrace(); // } // } // }
import com.github.pemapmodder.pocketminegui.gui.startup.installer.InstallServerActivity; import com.github.pemapmodder.pocketminegui.lib.card.Card; import com.github.pemapmodder.pocketminegui.utils.GetUrlThread; import javax.swing.JLabel; import javax.swing.JProgressBar; import javax.swing.Timer; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL;
package com.github.pemapmodder.pocketminegui.gui.startup.installer.cards; /* * This file is part of PocketMine-GUI. * * PocketMine-GUI is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PocketMine-GUI 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 PocketMine-GUI. If not, see <http://www.gnu.org/licenses/>. */ public class DownloadProgressCard extends Card{ private final InstallServerActivity activity; private final JProgressBar progressBar; private final JLabel progressLabel; private boolean maxSet = false; private Timer progressCheck;
// Path: src/main/java/com/github/pemapmodder/pocketminegui/gui/startup/installer/InstallServerActivity.java // public class InstallServerActivity extends CardActivity{ // @Getter private File selectedHome; // @Getter @Setter private File phpBinaries; // @Getter @Setter private Release selectedRelease; // // public InstallServerActivity(Activity parent){ // super("Install server", parent); // setExtendedState(MAXIMIZED_BOTH); // } // // @Override // public Card[] getDefaultCards(){ // return new Card[]{ // new ChooseLocationCard(this), // new ChooseVersionCard(this), // new DownloadProgressCard(this), // new PhpInstallerCard(this), // new ServerSetupCard(this), // }; // } // // public void setSelectedHome(File selectedHome){ // this.selectedHome = selectedHome; // selectedHome.mkdirs(); // } // // @Override // protected void setCard(int index, int exitType){ // super.setCard(index, exitType); // setExtendedState(MAXIMIZED_BOTH); // } // // @Override // protected void onFinish(){ // super.onFinish(); // getParent().initNewActivity(new ServerMainActivity(selectedHome, phpBinaries)); // } // } // // Path: src/main/java/com/github/pemapmodder/pocketminegui/lib/card/Card.java // public abstract class Card extends JPanel{ // /** // * The {@link CardActivity} is closed. // */ // public final static int EXIT_CLOSE = 0; // /** // * The "Back" button is triggered. // */ // public final static int EXIT_BACK = 1; // /** // * The "Next" button is triggered. // */ // public final static int EXIT_NEXT = 2; // // public void onEntry(){ // } // // /** // * Triggered when card is swapped // * // * @param type one of {@link #EXIT_CLOSE}, {@link #EXIT_BACK} and {@link #EXIT_NEXT} // * @return whether to allow this action // */ // public boolean onExit(int type){ // return true; // } // // public abstract String getCardName(); // // public void onStop(){ // } // } // // Path: src/main/java/com/github/pemapmodder/pocketminegui/utils/GetUrlThread.java // public class GetUrlThread extends AsyncTask{ // private final static int STEP = 512; // // private final URL url; // // public byte[] array; // // public GetUrlThread(URL url){ // this.url = url; // } // // @Override // public void run(){ // try{ // URLConnection conn = url.openConnection(); // setMax(conn.getContentLength()); // array = new byte[getMax()]; // try(InputStream is = conn.getInputStream()){ // int progress = 0; // int step = 0; // int pointer = 0; // while(true){ // byte[] buffer = new byte[STEP]; // int read = is.read(buffer); // if(read == -1){ // setProgress(getMax()); // return; // } // System.arraycopy(buffer, 0, array, pointer, read); // pointer += read; // setProgress(progress += STEP); // step++; // } // } // }catch(IOException e){ // e.printStackTrace(); // } // } // } // Path: src/main/java/com/github/pemapmodder/pocketminegui/gui/startup/installer/cards/DownloadProgressCard.java import com.github.pemapmodder.pocketminegui.gui.startup.installer.InstallServerActivity; import com.github.pemapmodder.pocketminegui.lib.card.Card; import com.github.pemapmodder.pocketminegui.utils.GetUrlThread; import javax.swing.JLabel; import javax.swing.JProgressBar; import javax.swing.Timer; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; package com.github.pemapmodder.pocketminegui.gui.startup.installer.cards; /* * This file is part of PocketMine-GUI. * * PocketMine-GUI is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PocketMine-GUI 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 PocketMine-GUI. If not, see <http://www.gnu.org/licenses/>. */ public class DownloadProgressCard extends Card{ private final InstallServerActivity activity; private final JProgressBar progressBar; private final JLabel progressLabel; private boolean maxSet = false; private Timer progressCheck;
private GetUrlThread thread;
dmtan90/Sense-Hub-Android-Things
app/src/main/java/com/agrhub/sensehub/components/mqtt/cloudiot/MqttPublisher.java
// Path: app/src/main/java/com/agrhub/sensehub/components/mqtt/MessagePayload.java // public class MessagePayload { // // /** // * Serialize a List of SensorData objects into a JSON string, for sending to the cloud // * @param data List of SensorData objects to serialize // * @return JSON String // */ // public static String createMessagePayload(String data) { // try { // StringBuffer mBuffer = new StringBuffer(""); // mBuffer.append("data=" + data); // return mBuffer.toString(); // } catch (Exception e) { // throw new IllegalArgumentException("Invalid message"); // } // } // }
import android.content.Context; import android.util.Log; import com.agrhub.sensehub.components.mqtt.MessagePayload; import org.apache.commons.io.IOUtils; import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; import org.eclipse.paho.client.mqttv3.MqttCallback; import org.eclipse.paho.client.mqttv3.MqttClient; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.util.concurrent.atomic.AtomicBoolean; import javax.annotation.Nonnull;
public AtomicBoolean mReady = new AtomicBoolean(false); public MqttPublisher(){ } public MqttPublisher(@Nonnull MqttOptions options, @Nonnull Context ctx){ mContext = ctx; mMqttOptions = options; try{ initializeMqttClient(); }catch (Exception e){ e.printStackTrace(); } } @Override public void publish(String data) { Log.i(TAG, "publish data=" + data); try { if (isReady()) { if (mqttClient != null && !mqttClient.isConnected()) { // if for some reason the mqtt client has disconnected, we should try to connect // it again. try { initializeMqttClient(); } catch (MqttException | IOException | GeneralSecurityException e) { throw new IllegalArgumentException("Could not initialize MQTT", e); } }
// Path: app/src/main/java/com/agrhub/sensehub/components/mqtt/MessagePayload.java // public class MessagePayload { // // /** // * Serialize a List of SensorData objects into a JSON string, for sending to the cloud // * @param data List of SensorData objects to serialize // * @return JSON String // */ // public static String createMessagePayload(String data) { // try { // StringBuffer mBuffer = new StringBuffer(""); // mBuffer.append("data=" + data); // return mBuffer.toString(); // } catch (Exception e) { // throw new IllegalArgumentException("Invalid message"); // } // } // } // Path: app/src/main/java/com/agrhub/sensehub/components/mqtt/cloudiot/MqttPublisher.java import android.content.Context; import android.util.Log; import com.agrhub.sensehub.components.mqtt.MessagePayload; import org.apache.commons.io.IOUtils; import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; import org.eclipse.paho.client.mqttv3.MqttCallback; import org.eclipse.paho.client.mqttv3.MqttClient; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.util.concurrent.atomic.AtomicBoolean; import javax.annotation.Nonnull; public AtomicBoolean mReady = new AtomicBoolean(false); public MqttPublisher(){ } public MqttPublisher(@Nonnull MqttOptions options, @Nonnull Context ctx){ mContext = ctx; mMqttOptions = options; try{ initializeMqttClient(); }catch (Exception e){ e.printStackTrace(); } } @Override public void publish(String data) { Log.i(TAG, "publish data=" + data); try { if (isReady()) { if (mqttClient != null && !mqttClient.isConnected()) { // if for some reason the mqtt client has disconnected, we should try to connect // it again. try { initializeMqttClient(); } catch (MqttException | IOException | GeneralSecurityException e) { throw new IllegalArgumentException("Could not initialize MQTT", e); } }
String payload = MessagePayload.createMessagePayload(data);
dmtan90/Sense-Hub-Android-Things
app/src/main/java/com/agrhub/sensehub/components/mqtt/cloudiot/CloudIotCoreOptions.java
// Path: app/src/main/java/com/agrhub/sensehub/components/util/ConfigHelper.java // public class ConfigHelper { // private static final String TAG = "Helper"; // // /* // * open config file: assets/configs/config_mqtt.properties and add some values: // // api_url=http://url.to.api/v1/ // api_key=123456 // * */ // public static String getConfigValue(Context context, String fileName, String name) { // try { // InputStream rawResource = context.getAssets().open(fileName); // Properties properties = new Properties(); // properties.load(rawResource); // return properties.getProperty(name); // } catch (Resources.NotFoundException e) { // Log.e(TAG, "Unable to find the config file: " + e.getMessage()); // } catch (IOException e) { // Log.e(TAG, "Failed to open config file."); // } // // return null; // } // // /* // * In your AndroidManifest.xml add something like: // ... // <application ...> // ... // // <meta-data android:name="api_url" android:value="http://url.to.api/v1/"/> // <meta-data android:name="api_key" android:value="123456"/> // </application> // * */ // public static String getMetaData(Context context, String name) { // try { // ApplicationInfo ai = context.getPackageManager().getApplicationInfo(context.getPackageName(), // PackageManager.GET_META_DATA); // Bundle bundle = ai.metaData; // return bundle.getString(name); // } catch (PackageManager.NameNotFoundException e) { // Log.e(TAG, "Unable to load meta-data: " + e.getMessage()); // } // return null; // } // }
import android.content.Context; import android.text.TextUtils; import com.agrhub.sensehub.components.util.ConfigHelper; import java.util.Locale; import javax.annotation.Nonnull;
public String getCloudRegion() { return cloudRegion; } public String getBridgeHostname() { return bridgeHostname; } public short getBridgePort() { return bridgePort; } private CloudIotCoreOptions() { } public boolean isValid() { return !TextUtils.isEmpty(projectId) && !TextUtils.isEmpty(registryId) && !TextUtils.isEmpty(deviceId) && !TextUtils.isEmpty(cloudRegion) && !TextUtils.isEmpty(bridgeHostname); } /** * Construct a CloudIotCoreOptions object from SharedPreferences. */ public static CloudIotCoreOptions fromConfigFile(@Nonnull Context context) { try { String fileName = "configs/config_iot_core.properties"; CloudIotCoreOptions options = new CloudIotCoreOptions();
// Path: app/src/main/java/com/agrhub/sensehub/components/util/ConfigHelper.java // public class ConfigHelper { // private static final String TAG = "Helper"; // // /* // * open config file: assets/configs/config_mqtt.properties and add some values: // // api_url=http://url.to.api/v1/ // api_key=123456 // * */ // public static String getConfigValue(Context context, String fileName, String name) { // try { // InputStream rawResource = context.getAssets().open(fileName); // Properties properties = new Properties(); // properties.load(rawResource); // return properties.getProperty(name); // } catch (Resources.NotFoundException e) { // Log.e(TAG, "Unable to find the config file: " + e.getMessage()); // } catch (IOException e) { // Log.e(TAG, "Failed to open config file."); // } // // return null; // } // // /* // * In your AndroidManifest.xml add something like: // ... // <application ...> // ... // // <meta-data android:name="api_url" android:value="http://url.to.api/v1/"/> // <meta-data android:name="api_key" android:value="123456"/> // </application> // * */ // public static String getMetaData(Context context, String name) { // try { // ApplicationInfo ai = context.getPackageManager().getApplicationInfo(context.getPackageName(), // PackageManager.GET_META_DATA); // Bundle bundle = ai.metaData; // return bundle.getString(name); // } catch (PackageManager.NameNotFoundException e) { // Log.e(TAG, "Unable to load meta-data: " + e.getMessage()); // } // return null; // } // } // Path: app/src/main/java/com/agrhub/sensehub/components/mqtt/cloudiot/CloudIotCoreOptions.java import android.content.Context; import android.text.TextUtils; import com.agrhub.sensehub.components.util.ConfigHelper; import java.util.Locale; import javax.annotation.Nonnull; public String getCloudRegion() { return cloudRegion; } public String getBridgeHostname() { return bridgeHostname; } public short getBridgePort() { return bridgePort; } private CloudIotCoreOptions() { } public boolean isValid() { return !TextUtils.isEmpty(projectId) && !TextUtils.isEmpty(registryId) && !TextUtils.isEmpty(deviceId) && !TextUtils.isEmpty(cloudRegion) && !TextUtils.isEmpty(bridgeHostname); } /** * Construct a CloudIotCoreOptions object from SharedPreferences. */ public static CloudIotCoreOptions fromConfigFile(@Nonnull Context context) { try { String fileName = "configs/config_iot_core.properties"; CloudIotCoreOptions options = new CloudIotCoreOptions();
options.projectId = ConfigHelper.getConfigValue(context, fileName,"PROJECT_ID");
dmtan90/Sense-Hub-Android-Things
app/src/main/java/com/agrhub/sensehub/components/mqtt/cloudiot/MqttIoTPublisher.java
// Path: app/src/main/java/com/agrhub/sensehub/components/mqtt/MessagePayload.java // public class MessagePayload { // // /** // * Serialize a List of SensorData objects into a JSON string, for sending to the cloud // * @param data List of SensorData objects to serialize // * @return JSON String // */ // public static String createMessagePayload(String data) { // try { // StringBuffer mBuffer = new StringBuffer(""); // mBuffer.append("data=" + data); // return mBuffer.toString(); // } catch (Exception e) { // throw new IllegalArgumentException("Invalid message"); // } // } // }
import javax.annotation.Nonnull; import android.content.Context; import android.util.Log; import com.agrhub.sensehub.components.mqtt.MessagePayload; import org.eclipse.paho.client.mqttv3.MqttClient; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException;
try { Log.i(TAG, "Device Configuration:"); Log.i(TAG, " Project ID: " + mMqttOptions.getProjectId()); Log.i(TAG, " Region ID: " + mMqttOptions.getCloudRegion()); Log.i(TAG, "Registry ID: " + mMqttOptions.getRegistryId()); Log.i(TAG, " Device ID: " + mMqttOptions.getDeviceId()); Log.i(TAG, "MQTT Configuration:"); Log.i(TAG, "Broker: " + mMqttOptions.getBridgeHostname() + ":" + mMqttOptions.getBridgePort()); Log.i(TAG, "Publishing to topic: " + mMqttOptions.getTopicName()); mqttAuth = new MqttAuthentication(mContext); mqttAuth.initialize(); initializeMqttClient(); } catch (MqttException | IOException | GeneralSecurityException e) { throw new IllegalArgumentException("Could not initialize MQTT : " + e.getMessage(), e); } } @Override public void publish(String data) { try { if (isReady()) { if (mqttClient != null && !mqttClient.isConnected()) { // if for some reason the mqtt client has disconnected, we should try to connect // it again. try { initializeMqttClient(); } catch (MqttException | IOException | GeneralSecurityException e) { throw new IllegalArgumentException("Could not initialize MQTT", e); } }
// Path: app/src/main/java/com/agrhub/sensehub/components/mqtt/MessagePayload.java // public class MessagePayload { // // /** // * Serialize a List of SensorData objects into a JSON string, for sending to the cloud // * @param data List of SensorData objects to serialize // * @return JSON String // */ // public static String createMessagePayload(String data) { // try { // StringBuffer mBuffer = new StringBuffer(""); // mBuffer.append("data=" + data); // return mBuffer.toString(); // } catch (Exception e) { // throw new IllegalArgumentException("Invalid message"); // } // } // } // Path: app/src/main/java/com/agrhub/sensehub/components/mqtt/cloudiot/MqttIoTPublisher.java import javax.annotation.Nonnull; import android.content.Context; import android.util.Log; import com.agrhub.sensehub.components.mqtt.MessagePayload; import org.eclipse.paho.client.mqttv3.MqttClient; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; try { Log.i(TAG, "Device Configuration:"); Log.i(TAG, " Project ID: " + mMqttOptions.getProjectId()); Log.i(TAG, " Region ID: " + mMqttOptions.getCloudRegion()); Log.i(TAG, "Registry ID: " + mMqttOptions.getRegistryId()); Log.i(TAG, " Device ID: " + mMqttOptions.getDeviceId()); Log.i(TAG, "MQTT Configuration:"); Log.i(TAG, "Broker: " + mMqttOptions.getBridgeHostname() + ":" + mMqttOptions.getBridgePort()); Log.i(TAG, "Publishing to topic: " + mMqttOptions.getTopicName()); mqttAuth = new MqttAuthentication(mContext); mqttAuth.initialize(); initializeMqttClient(); } catch (MqttException | IOException | GeneralSecurityException e) { throw new IllegalArgumentException("Could not initialize MQTT : " + e.getMessage(), e); } } @Override public void publish(String data) { try { if (isReady()) { if (mqttClient != null && !mqttClient.isConnected()) { // if for some reason the mqtt client has disconnected, we should try to connect // it again. try { initializeMqttClient(); } catch (MqttException | IOException | GeneralSecurityException e) { throw new IllegalArgumentException("Could not initialize MQTT", e); } }
String payload = MessagePayload.createMessagePayload(data);
dmtan90/Sense-Hub-Android-Things
app/src/main/java/com/agrhub/sensehub/components/connector/Sp3Connector.java
// Path: app/src/main/java/com/agrhub/sensehub/components/util/PacketData.java // public class PacketData { // private static final String TAG = PacketData.class.getSimpleName(); // public static int MAX_LENGTH = 4096; // private byte[] mBuffer; // private int mLength; // // public PacketData(){ // mLength = MAX_LENGTH; // mBuffer = new byte[mLength]; // } // // public PacketData(byte[] buffer, int length){ // this.mBuffer = buffer; // this.mLength = length; // } // // public PacketData(int[] buffer, int length){ // this.mBuffer = ConvertToByteArray(buffer); // this.mLength = this.mBuffer.length; // } // // public byte[] getBuffer() { // return mBuffer; // } // // public int[] getIntBuffer() { // return ConvertToIntArray(mBuffer); // } // // public void setBuffer(byte[] mBuffer) { // this.mBuffer = mBuffer; // } // // public void setIntBuffer(int[] mBuffer) { // this.mBuffer = ConvertToByteArray(mBuffer); // } // // public int getLength() { // return mLength; // } // // public void setLength(int mLength) { // this.mLength = mLength; // } // // public static byte[] ConvertToByteArray(int[] input){ // /*ByteBuffer byteBuffer = ByteBuffer.allocate(input.length*4); // IntBuffer intBuffer = byteBuffer.asIntBuffer(); // intBuffer.put(input);*/ // byte[] output = new byte[input.length]; // for(int i = 0; i < input.length; i++){ // output[i] = (byte)input[i]; // } // // //byte[] output = byteBuffer.array(); // return output; // } // // public static int[] ConvertToIntArray(byte[] input){ // IntBuffer intBuf = // ByteBuffer.wrap(input) // .order(ByteOrder.BIG_ENDIAN) // .asIntBuffer(); // int[] output = new int[intBuf.remaining()]; // intBuf.get(output); // return output; // } // // public static void PrintPacket(int[] input){ // StringBuffer buffer = new StringBuffer(); // for(int i : input){ // buffer.append(String.format("%02X\t", i)); // } // Log.d(TAG, "PrintPacket: " + buffer.toString()); // } // // public static void PrintPacket(byte[] input){ // StringBuffer buffer = new StringBuffer(); // for(byte b : input){ // buffer.append(String.format("%02X\t", b)); // } // Log.d(TAG, "PrintPacket: " + buffer.toString()); // } // }
import android.util.Log; import com.agrhub.sensehub.components.util.PacketData; import java.util.Arrays;
package com.agrhub.sensehub.components.connector; /** * Created by tanca on 10/28/2017. */ public class Sp3Connector extends BroadlinkConnector { private String TAG = getClass().getSimpleName(); private final int SP3_CMD_SET_STATE = 0x6a; private final int SP3_CMD_GET_STATE = 0x6a; private boolean mState; public boolean setState(boolean state){ Log.i(TAG, "setState=" + state); int len = 16; byte[] packet = new byte[len]; Arrays.fill(packet, (byte)0x00); packet[0] = 2; packet[4] = (byte)((state == true ? 1 : 0));
// Path: app/src/main/java/com/agrhub/sensehub/components/util/PacketData.java // public class PacketData { // private static final String TAG = PacketData.class.getSimpleName(); // public static int MAX_LENGTH = 4096; // private byte[] mBuffer; // private int mLength; // // public PacketData(){ // mLength = MAX_LENGTH; // mBuffer = new byte[mLength]; // } // // public PacketData(byte[] buffer, int length){ // this.mBuffer = buffer; // this.mLength = length; // } // // public PacketData(int[] buffer, int length){ // this.mBuffer = ConvertToByteArray(buffer); // this.mLength = this.mBuffer.length; // } // // public byte[] getBuffer() { // return mBuffer; // } // // public int[] getIntBuffer() { // return ConvertToIntArray(mBuffer); // } // // public void setBuffer(byte[] mBuffer) { // this.mBuffer = mBuffer; // } // // public void setIntBuffer(int[] mBuffer) { // this.mBuffer = ConvertToByteArray(mBuffer); // } // // public int getLength() { // return mLength; // } // // public void setLength(int mLength) { // this.mLength = mLength; // } // // public static byte[] ConvertToByteArray(int[] input){ // /*ByteBuffer byteBuffer = ByteBuffer.allocate(input.length*4); // IntBuffer intBuffer = byteBuffer.asIntBuffer(); // intBuffer.put(input);*/ // byte[] output = new byte[input.length]; // for(int i = 0; i < input.length; i++){ // output[i] = (byte)input[i]; // } // // //byte[] output = byteBuffer.array(); // return output; // } // // public static int[] ConvertToIntArray(byte[] input){ // IntBuffer intBuf = // ByteBuffer.wrap(input) // .order(ByteOrder.BIG_ENDIAN) // .asIntBuffer(); // int[] output = new int[intBuf.remaining()]; // intBuf.get(output); // return output; // } // // public static void PrintPacket(int[] input){ // StringBuffer buffer = new StringBuffer(); // for(int i : input){ // buffer.append(String.format("%02X\t", i)); // } // Log.d(TAG, "PrintPacket: " + buffer.toString()); // } // // public static void PrintPacket(byte[] input){ // StringBuffer buffer = new StringBuffer(); // for(byte b : input){ // buffer.append(String.format("%02X\t", b)); // } // Log.d(TAG, "PrintPacket: " + buffer.toString()); // } // } // Path: app/src/main/java/com/agrhub/sensehub/components/connector/Sp3Connector.java import android.util.Log; import com.agrhub.sensehub.components.util.PacketData; import java.util.Arrays; package com.agrhub.sensehub.components.connector; /** * Created by tanca on 10/28/2017. */ public class Sp3Connector extends BroadlinkConnector { private String TAG = getClass().getSimpleName(); private final int SP3_CMD_SET_STATE = 0x6a; private final int SP3_CMD_GET_STATE = 0x6a; private boolean mState; public boolean setState(boolean state){ Log.i(TAG, "setState=" + state); int len = 16; byte[] packet = new byte[len]; Arrays.fill(packet, (byte)0x00); packet[0] = 2; packet[4] = (byte)((state == true ? 1 : 0));
PacketData inputPacket = new PacketData(packet, len);
dmtan90/Sense-Hub-Android-Things
app/src/main/java/com/agrhub/sensehub/components/entity/Entity.java
// Path: app/src/main/java/com/agrhub/sensehub/components/util/DeviceName.java // public enum DeviceName { // DB_DEVICE_NAME_UNKNOWN(0), // DB_DEVICE_NAME_SP3_SMART_PLUG(1), // DB_DEVICE_NAME_SONOFF_SMART_PLUG(2), // DB_DEVICE_NAME_XIAOMI_SMART_PLUG(3), // DB_DEVICE_NAME_MI_FLORA(4), // DB_DEVICE_NAME_AXAET_AIR_SENSOR(5), // DB_DEVICE_NAME_TI_TAG_SENSOR(6), // DB_DEVICE_NAME_FIOT_SMART_TANK(7), // DB_DEVICE_NAME_RM3_SMART_REMOTE(8), // DB_DEVICE_NAME_GATEWAY(9), // DB_DEVICE_NAME_NRF51822_SENSOR(10), // DB_DEVICE_NAME_GATEWAY_ANDROID_THINGS(11); // // private final int value; // private DeviceName(int value) { // this.value = value; // } // // public int getValue() { // return value; // } // } // // Path: app/src/main/java/com/agrhub/sensehub/components/util/DeviceState.java // public enum DeviceState { // DEVICE_CONNECTED(0), // DEVICE_DISCONNECTED(1), // DEVICE_ERROR(2); // // private final int value; // private DeviceState(int value) { // this.value = value; // } // // public int getValue() { // return value; // } // } // // Path: app/src/main/java/com/agrhub/sensehub/components/util/DeviceType.java // public enum DeviceType { // DB_DEVICE_TYPE_UNKNOWN(0), // DB_DEVICE_TYPE_SENSOR(1), // DB_DEVICE_TYPE_CONTROLLER(2), // DB_DEVICE_TYPE_CONTAINER(3), // DB_DEVICE_TYPE_GATEWAY(4); // // private final int value; // private DeviceType(int value) { // this.value = value; // } // // public int getValue() { // return value; // } // } // // Path: app/src/main/java/com/agrhub/sensehub/components/util/SensorType.java // public enum SensorType { // SENSOR_TYPE_UNKNOWN(0), // SENSOR_TYPE_LIGHT(1), // SENSOR_TYPE_AIR_TEMP(2), // SENSOR_TYPE_AIR_HUMIDITY(3), // SENSOR_TYPE_SOIL_TEMP(4), // SENSOR_TYPE_SOIL_HUMIDITY(5), // SENSOR_TYPE_SOIL_EC(6), // SENSOR_TYPE_SOIL_PH(7), // SENSOR_TYPE_WATER_TEMP(8), // SENSOR_TYPE_WATER_EC(9), // SENSOR_TYPE_WATER_PH(10), // SENSOR_TYPE_WATER_ORP(11), // SENSOR_TYPE_BAT(12), // SENSOR_TYPE_CO2(13), // SENSOR_TYPE_WATER_LEVEL(14), // SENSOR_TYPE_WATER_DETECT(15), // SENSOR_TYPE_ERROR_DETECT(16); // // private final int value; // private SensorType(int value) { // this.value = value; // } // // public int getValue() { // return value; // } // }
import android.content.Context; import com.agrhub.sensehub.components.util.DeviceName; import com.agrhub.sensehub.components.util.DeviceState; import com.agrhub.sensehub.components.util.DeviceType; import com.agrhub.sensehub.components.util.SensorType;
package com.agrhub.sensehub.components.entity; /** * Created by tanca on 10/19/2017. */ public abstract class Entity { private String mMacAddress;
// Path: app/src/main/java/com/agrhub/sensehub/components/util/DeviceName.java // public enum DeviceName { // DB_DEVICE_NAME_UNKNOWN(0), // DB_DEVICE_NAME_SP3_SMART_PLUG(1), // DB_DEVICE_NAME_SONOFF_SMART_PLUG(2), // DB_DEVICE_NAME_XIAOMI_SMART_PLUG(3), // DB_DEVICE_NAME_MI_FLORA(4), // DB_DEVICE_NAME_AXAET_AIR_SENSOR(5), // DB_DEVICE_NAME_TI_TAG_SENSOR(6), // DB_DEVICE_NAME_FIOT_SMART_TANK(7), // DB_DEVICE_NAME_RM3_SMART_REMOTE(8), // DB_DEVICE_NAME_GATEWAY(9), // DB_DEVICE_NAME_NRF51822_SENSOR(10), // DB_DEVICE_NAME_GATEWAY_ANDROID_THINGS(11); // // private final int value; // private DeviceName(int value) { // this.value = value; // } // // public int getValue() { // return value; // } // } // // Path: app/src/main/java/com/agrhub/sensehub/components/util/DeviceState.java // public enum DeviceState { // DEVICE_CONNECTED(0), // DEVICE_DISCONNECTED(1), // DEVICE_ERROR(2); // // private final int value; // private DeviceState(int value) { // this.value = value; // } // // public int getValue() { // return value; // } // } // // Path: app/src/main/java/com/agrhub/sensehub/components/util/DeviceType.java // public enum DeviceType { // DB_DEVICE_TYPE_UNKNOWN(0), // DB_DEVICE_TYPE_SENSOR(1), // DB_DEVICE_TYPE_CONTROLLER(2), // DB_DEVICE_TYPE_CONTAINER(3), // DB_DEVICE_TYPE_GATEWAY(4); // // private final int value; // private DeviceType(int value) { // this.value = value; // } // // public int getValue() { // return value; // } // } // // Path: app/src/main/java/com/agrhub/sensehub/components/util/SensorType.java // public enum SensorType { // SENSOR_TYPE_UNKNOWN(0), // SENSOR_TYPE_LIGHT(1), // SENSOR_TYPE_AIR_TEMP(2), // SENSOR_TYPE_AIR_HUMIDITY(3), // SENSOR_TYPE_SOIL_TEMP(4), // SENSOR_TYPE_SOIL_HUMIDITY(5), // SENSOR_TYPE_SOIL_EC(6), // SENSOR_TYPE_SOIL_PH(7), // SENSOR_TYPE_WATER_TEMP(8), // SENSOR_TYPE_WATER_EC(9), // SENSOR_TYPE_WATER_PH(10), // SENSOR_TYPE_WATER_ORP(11), // SENSOR_TYPE_BAT(12), // SENSOR_TYPE_CO2(13), // SENSOR_TYPE_WATER_LEVEL(14), // SENSOR_TYPE_WATER_DETECT(15), // SENSOR_TYPE_ERROR_DETECT(16); // // private final int value; // private SensorType(int value) { // this.value = value; // } // // public int getValue() { // return value; // } // } // Path: app/src/main/java/com/agrhub/sensehub/components/entity/Entity.java import android.content.Context; import com.agrhub.sensehub.components.util.DeviceName; import com.agrhub.sensehub.components.util.DeviceState; import com.agrhub.sensehub.components.util.DeviceType; import com.agrhub.sensehub.components.util.SensorType; package com.agrhub.sensehub.components.entity; /** * Created by tanca on 10/19/2017. */ public abstract class Entity { private String mMacAddress;
private DeviceName mDeviceName;
dmtan90/Sense-Hub-Android-Things
app/src/main/java/com/agrhub/sensehub/components/entity/Entity.java
// Path: app/src/main/java/com/agrhub/sensehub/components/util/DeviceName.java // public enum DeviceName { // DB_DEVICE_NAME_UNKNOWN(0), // DB_DEVICE_NAME_SP3_SMART_PLUG(1), // DB_DEVICE_NAME_SONOFF_SMART_PLUG(2), // DB_DEVICE_NAME_XIAOMI_SMART_PLUG(3), // DB_DEVICE_NAME_MI_FLORA(4), // DB_DEVICE_NAME_AXAET_AIR_SENSOR(5), // DB_DEVICE_NAME_TI_TAG_SENSOR(6), // DB_DEVICE_NAME_FIOT_SMART_TANK(7), // DB_DEVICE_NAME_RM3_SMART_REMOTE(8), // DB_DEVICE_NAME_GATEWAY(9), // DB_DEVICE_NAME_NRF51822_SENSOR(10), // DB_DEVICE_NAME_GATEWAY_ANDROID_THINGS(11); // // private final int value; // private DeviceName(int value) { // this.value = value; // } // // public int getValue() { // return value; // } // } // // Path: app/src/main/java/com/agrhub/sensehub/components/util/DeviceState.java // public enum DeviceState { // DEVICE_CONNECTED(0), // DEVICE_DISCONNECTED(1), // DEVICE_ERROR(2); // // private final int value; // private DeviceState(int value) { // this.value = value; // } // // public int getValue() { // return value; // } // } // // Path: app/src/main/java/com/agrhub/sensehub/components/util/DeviceType.java // public enum DeviceType { // DB_DEVICE_TYPE_UNKNOWN(0), // DB_DEVICE_TYPE_SENSOR(1), // DB_DEVICE_TYPE_CONTROLLER(2), // DB_DEVICE_TYPE_CONTAINER(3), // DB_DEVICE_TYPE_GATEWAY(4); // // private final int value; // private DeviceType(int value) { // this.value = value; // } // // public int getValue() { // return value; // } // } // // Path: app/src/main/java/com/agrhub/sensehub/components/util/SensorType.java // public enum SensorType { // SENSOR_TYPE_UNKNOWN(0), // SENSOR_TYPE_LIGHT(1), // SENSOR_TYPE_AIR_TEMP(2), // SENSOR_TYPE_AIR_HUMIDITY(3), // SENSOR_TYPE_SOIL_TEMP(4), // SENSOR_TYPE_SOIL_HUMIDITY(5), // SENSOR_TYPE_SOIL_EC(6), // SENSOR_TYPE_SOIL_PH(7), // SENSOR_TYPE_WATER_TEMP(8), // SENSOR_TYPE_WATER_EC(9), // SENSOR_TYPE_WATER_PH(10), // SENSOR_TYPE_WATER_ORP(11), // SENSOR_TYPE_BAT(12), // SENSOR_TYPE_CO2(13), // SENSOR_TYPE_WATER_LEVEL(14), // SENSOR_TYPE_WATER_DETECT(15), // SENSOR_TYPE_ERROR_DETECT(16); // // private final int value; // private SensorType(int value) { // this.value = value; // } // // public int getValue() { // return value; // } // }
import android.content.Context; import com.agrhub.sensehub.components.util.DeviceName; import com.agrhub.sensehub.components.util.DeviceState; import com.agrhub.sensehub.components.util.DeviceType; import com.agrhub.sensehub.components.util.SensorType;
package com.agrhub.sensehub.components.entity; /** * Created by tanca on 10/19/2017. */ public abstract class Entity { private String mMacAddress; private DeviceName mDeviceName;
// Path: app/src/main/java/com/agrhub/sensehub/components/util/DeviceName.java // public enum DeviceName { // DB_DEVICE_NAME_UNKNOWN(0), // DB_DEVICE_NAME_SP3_SMART_PLUG(1), // DB_DEVICE_NAME_SONOFF_SMART_PLUG(2), // DB_DEVICE_NAME_XIAOMI_SMART_PLUG(3), // DB_DEVICE_NAME_MI_FLORA(4), // DB_DEVICE_NAME_AXAET_AIR_SENSOR(5), // DB_DEVICE_NAME_TI_TAG_SENSOR(6), // DB_DEVICE_NAME_FIOT_SMART_TANK(7), // DB_DEVICE_NAME_RM3_SMART_REMOTE(8), // DB_DEVICE_NAME_GATEWAY(9), // DB_DEVICE_NAME_NRF51822_SENSOR(10), // DB_DEVICE_NAME_GATEWAY_ANDROID_THINGS(11); // // private final int value; // private DeviceName(int value) { // this.value = value; // } // // public int getValue() { // return value; // } // } // // Path: app/src/main/java/com/agrhub/sensehub/components/util/DeviceState.java // public enum DeviceState { // DEVICE_CONNECTED(0), // DEVICE_DISCONNECTED(1), // DEVICE_ERROR(2); // // private final int value; // private DeviceState(int value) { // this.value = value; // } // // public int getValue() { // return value; // } // } // // Path: app/src/main/java/com/agrhub/sensehub/components/util/DeviceType.java // public enum DeviceType { // DB_DEVICE_TYPE_UNKNOWN(0), // DB_DEVICE_TYPE_SENSOR(1), // DB_DEVICE_TYPE_CONTROLLER(2), // DB_DEVICE_TYPE_CONTAINER(3), // DB_DEVICE_TYPE_GATEWAY(4); // // private final int value; // private DeviceType(int value) { // this.value = value; // } // // public int getValue() { // return value; // } // } // // Path: app/src/main/java/com/agrhub/sensehub/components/util/SensorType.java // public enum SensorType { // SENSOR_TYPE_UNKNOWN(0), // SENSOR_TYPE_LIGHT(1), // SENSOR_TYPE_AIR_TEMP(2), // SENSOR_TYPE_AIR_HUMIDITY(3), // SENSOR_TYPE_SOIL_TEMP(4), // SENSOR_TYPE_SOIL_HUMIDITY(5), // SENSOR_TYPE_SOIL_EC(6), // SENSOR_TYPE_SOIL_PH(7), // SENSOR_TYPE_WATER_TEMP(8), // SENSOR_TYPE_WATER_EC(9), // SENSOR_TYPE_WATER_PH(10), // SENSOR_TYPE_WATER_ORP(11), // SENSOR_TYPE_BAT(12), // SENSOR_TYPE_CO2(13), // SENSOR_TYPE_WATER_LEVEL(14), // SENSOR_TYPE_WATER_DETECT(15), // SENSOR_TYPE_ERROR_DETECT(16); // // private final int value; // private SensorType(int value) { // this.value = value; // } // // public int getValue() { // return value; // } // } // Path: app/src/main/java/com/agrhub/sensehub/components/entity/Entity.java import android.content.Context; import com.agrhub.sensehub.components.util.DeviceName; import com.agrhub.sensehub.components.util.DeviceState; import com.agrhub.sensehub.components.util.DeviceType; import com.agrhub.sensehub.components.util.SensorType; package com.agrhub.sensehub.components.entity; /** * Created by tanca on 10/19/2017. */ public abstract class Entity { private String mMacAddress; private DeviceName mDeviceName;
private DeviceType mDeviceType;
dmtan90/Sense-Hub-Android-Things
app/src/main/java/com/agrhub/sensehub/components/entity/Entity.java
// Path: app/src/main/java/com/agrhub/sensehub/components/util/DeviceName.java // public enum DeviceName { // DB_DEVICE_NAME_UNKNOWN(0), // DB_DEVICE_NAME_SP3_SMART_PLUG(1), // DB_DEVICE_NAME_SONOFF_SMART_PLUG(2), // DB_DEVICE_NAME_XIAOMI_SMART_PLUG(3), // DB_DEVICE_NAME_MI_FLORA(4), // DB_DEVICE_NAME_AXAET_AIR_SENSOR(5), // DB_DEVICE_NAME_TI_TAG_SENSOR(6), // DB_DEVICE_NAME_FIOT_SMART_TANK(7), // DB_DEVICE_NAME_RM3_SMART_REMOTE(8), // DB_DEVICE_NAME_GATEWAY(9), // DB_DEVICE_NAME_NRF51822_SENSOR(10), // DB_DEVICE_NAME_GATEWAY_ANDROID_THINGS(11); // // private final int value; // private DeviceName(int value) { // this.value = value; // } // // public int getValue() { // return value; // } // } // // Path: app/src/main/java/com/agrhub/sensehub/components/util/DeviceState.java // public enum DeviceState { // DEVICE_CONNECTED(0), // DEVICE_DISCONNECTED(1), // DEVICE_ERROR(2); // // private final int value; // private DeviceState(int value) { // this.value = value; // } // // public int getValue() { // return value; // } // } // // Path: app/src/main/java/com/agrhub/sensehub/components/util/DeviceType.java // public enum DeviceType { // DB_DEVICE_TYPE_UNKNOWN(0), // DB_DEVICE_TYPE_SENSOR(1), // DB_DEVICE_TYPE_CONTROLLER(2), // DB_DEVICE_TYPE_CONTAINER(3), // DB_DEVICE_TYPE_GATEWAY(4); // // private final int value; // private DeviceType(int value) { // this.value = value; // } // // public int getValue() { // return value; // } // } // // Path: app/src/main/java/com/agrhub/sensehub/components/util/SensorType.java // public enum SensorType { // SENSOR_TYPE_UNKNOWN(0), // SENSOR_TYPE_LIGHT(1), // SENSOR_TYPE_AIR_TEMP(2), // SENSOR_TYPE_AIR_HUMIDITY(3), // SENSOR_TYPE_SOIL_TEMP(4), // SENSOR_TYPE_SOIL_HUMIDITY(5), // SENSOR_TYPE_SOIL_EC(6), // SENSOR_TYPE_SOIL_PH(7), // SENSOR_TYPE_WATER_TEMP(8), // SENSOR_TYPE_WATER_EC(9), // SENSOR_TYPE_WATER_PH(10), // SENSOR_TYPE_WATER_ORP(11), // SENSOR_TYPE_BAT(12), // SENSOR_TYPE_CO2(13), // SENSOR_TYPE_WATER_LEVEL(14), // SENSOR_TYPE_WATER_DETECT(15), // SENSOR_TYPE_ERROR_DETECT(16); // // private final int value; // private SensorType(int value) { // this.value = value; // } // // public int getValue() { // return value; // } // }
import android.content.Context; import com.agrhub.sensehub.components.util.DeviceName; import com.agrhub.sensehub.components.util.DeviceState; import com.agrhub.sensehub.components.util.DeviceType; import com.agrhub.sensehub.components.util.SensorType;
package com.agrhub.sensehub.components.entity; /** * Created by tanca on 10/19/2017. */ public abstract class Entity { private String mMacAddress; private DeviceName mDeviceName; private DeviceType mDeviceType;
// Path: app/src/main/java/com/agrhub/sensehub/components/util/DeviceName.java // public enum DeviceName { // DB_DEVICE_NAME_UNKNOWN(0), // DB_DEVICE_NAME_SP3_SMART_PLUG(1), // DB_DEVICE_NAME_SONOFF_SMART_PLUG(2), // DB_DEVICE_NAME_XIAOMI_SMART_PLUG(3), // DB_DEVICE_NAME_MI_FLORA(4), // DB_DEVICE_NAME_AXAET_AIR_SENSOR(5), // DB_DEVICE_NAME_TI_TAG_SENSOR(6), // DB_DEVICE_NAME_FIOT_SMART_TANK(7), // DB_DEVICE_NAME_RM3_SMART_REMOTE(8), // DB_DEVICE_NAME_GATEWAY(9), // DB_DEVICE_NAME_NRF51822_SENSOR(10), // DB_DEVICE_NAME_GATEWAY_ANDROID_THINGS(11); // // private final int value; // private DeviceName(int value) { // this.value = value; // } // // public int getValue() { // return value; // } // } // // Path: app/src/main/java/com/agrhub/sensehub/components/util/DeviceState.java // public enum DeviceState { // DEVICE_CONNECTED(0), // DEVICE_DISCONNECTED(1), // DEVICE_ERROR(2); // // private final int value; // private DeviceState(int value) { // this.value = value; // } // // public int getValue() { // return value; // } // } // // Path: app/src/main/java/com/agrhub/sensehub/components/util/DeviceType.java // public enum DeviceType { // DB_DEVICE_TYPE_UNKNOWN(0), // DB_DEVICE_TYPE_SENSOR(1), // DB_DEVICE_TYPE_CONTROLLER(2), // DB_DEVICE_TYPE_CONTAINER(3), // DB_DEVICE_TYPE_GATEWAY(4); // // private final int value; // private DeviceType(int value) { // this.value = value; // } // // public int getValue() { // return value; // } // } // // Path: app/src/main/java/com/agrhub/sensehub/components/util/SensorType.java // public enum SensorType { // SENSOR_TYPE_UNKNOWN(0), // SENSOR_TYPE_LIGHT(1), // SENSOR_TYPE_AIR_TEMP(2), // SENSOR_TYPE_AIR_HUMIDITY(3), // SENSOR_TYPE_SOIL_TEMP(4), // SENSOR_TYPE_SOIL_HUMIDITY(5), // SENSOR_TYPE_SOIL_EC(6), // SENSOR_TYPE_SOIL_PH(7), // SENSOR_TYPE_WATER_TEMP(8), // SENSOR_TYPE_WATER_EC(9), // SENSOR_TYPE_WATER_PH(10), // SENSOR_TYPE_WATER_ORP(11), // SENSOR_TYPE_BAT(12), // SENSOR_TYPE_CO2(13), // SENSOR_TYPE_WATER_LEVEL(14), // SENSOR_TYPE_WATER_DETECT(15), // SENSOR_TYPE_ERROR_DETECT(16); // // private final int value; // private SensorType(int value) { // this.value = value; // } // // public int getValue() { // return value; // } // } // Path: app/src/main/java/com/agrhub/sensehub/components/entity/Entity.java import android.content.Context; import com.agrhub.sensehub.components.util.DeviceName; import com.agrhub.sensehub.components.util.DeviceState; import com.agrhub.sensehub.components.util.DeviceType; import com.agrhub.sensehub.components.util.SensorType; package com.agrhub.sensehub.components.entity; /** * Created by tanca on 10/19/2017. */ public abstract class Entity { private String mMacAddress; private DeviceName mDeviceName; private DeviceType mDeviceType;
private DeviceState mDeviceState;
dmtan90/Sense-Hub-Android-Things
app/src/main/java/com/agrhub/sensehub/components/config/Config.java
// Path: app/src/main/java/com/agrhub/sensehub/components/util/UpdateState.java // public enum UpdateState { // SW_UPDATE_MODE_DEVELOPING(0), // SW_UPDATE_MODE_ALPHA(1), // SW_UPDATE_MODE_BETA(2), // SW_UPDATE_MODE_STABLE(3); // // private final int value; // private UpdateState(int value) { // this.value = value; // } // // public int getValue() { // return value; // } // }
import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import com.agrhub.sensehub.components.util.UpdateState;
package com.agrhub.sensehub.components.config; /** * Created by tanca on 10/19/2017. */ public enum Config { instance; private Context mContext = null; private String mStaSSID = ""; private String mStaPwd = ""; private String mApSSID = ""; private String mApPwd = "";
// Path: app/src/main/java/com/agrhub/sensehub/components/util/UpdateState.java // public enum UpdateState { // SW_UPDATE_MODE_DEVELOPING(0), // SW_UPDATE_MODE_ALPHA(1), // SW_UPDATE_MODE_BETA(2), // SW_UPDATE_MODE_STABLE(3); // // private final int value; // private UpdateState(int value) { // this.value = value; // } // // public int getValue() { // return value; // } // } // Path: app/src/main/java/com/agrhub/sensehub/components/config/Config.java import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import com.agrhub.sensehub.components.util.UpdateState; package com.agrhub.sensehub.components.config; /** * Created by tanca on 10/19/2017. */ public enum Config { instance; private Context mContext = null; private String mStaSSID = ""; private String mStaPwd = ""; private String mApSSID = ""; private String mApPwd = "";
private UpdateState mUpdateState = UpdateState.SW_UPDATE_MODE_STABLE;
jackyhung/consumer-dispatcher
src/main/java/com/thenetcircle/comsumerdispatcher/jmx/ConsumerDispatcherMonitor.java
// Path: src/main/java/com/thenetcircle/comsumerdispatcher/config/DispatcherConfig.java // public class DispatcherConfig { // // private static DispatcherConfig _self = null; // private List<JobExecutor> allJobs = null; // private Map<String, QueueConf> servers = null; // private MonitorConf monitorConf = null; // // public static synchronized DispatcherConfig getInstance() { // if (null == _self) { // _self = new DispatcherConfig(); // } // return _self; // } // // public void loadConfig(String configFilePath) throws Exception { // ConfigLoader cLoader = null; // if (null == configFilePath) { // cLoader = new DistributedConfigLoader(DistributionManager.getInstance().getZk()); // } else { // cLoader = new FileConfigLoader(configFilePath); // } // // setServers(cLoader.loadServers());// go first // setAllJobs(cLoader.loadAllJobs()); // setMonitorConf(cLoader.loadJmxConfig()); // } // // public List<JobExecutor> getAllJobs() { // return this.allJobs; // } // // public Map<String, QueueConf> getServers() { // return this.servers; // } // // public MonitorConf getMonitorConf() { // return monitorConf; // } // // public void setAllJobs(List<JobExecutor> allJobs) { // this.allJobs = allJobs; // } // // public void setServers(Map<String, QueueConf> servers) { // this.servers = servers; // } // // public void setMonitorConf(MonitorConf monitorConf) { // this.monitorConf = monitorConf; // } // // private DispatcherConfig() { // } // } // // Path: src/main/java/com/thenetcircle/comsumerdispatcher/config/MonitorConf.java // public class MonitorConf { // // jmx config // private String jmxRmiHost = null; // private int jmxRmiPort; // private String jmxHttpHost = null; // private int jmxHttpPort; // // public String getJmxRmiHost() { // return jmxRmiHost; // } // // public int getJmxRmiPort() { // return jmxRmiPort; // } // // public String getJmxHttpHost() { // return jmxHttpHost; // } // // public int getJmxHttpPort() { // return jmxHttpPort; // } // // public void setJmxRmiHost(String jmxRmiHost) { // this.jmxRmiHost = jmxRmiHost; // } // // public void setJmxRmiPort(int jmxRmiPort) { // this.jmxRmiPort = jmxRmiPort; // } // // public void setJmxHttpHost(String jmxHttpHost) { // this.jmxHttpHost = jmxHttpHost; // } // // public void setJmxHttpPort(int jmxHttpPort) { // this.jmxHttpPort = jmxHttpPort; // } // // // }
import java.io.IOException; import java.lang.management.ManagementFactory; import java.rmi.registry.LocateRegistry; import javax.management.MBeanServer; import javax.management.ObjectName; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.thenetcircle.comsumerdispatcher.config.DispatcherConfig; import com.thenetcircle.comsumerdispatcher.config.MonitorConf;
package com.thenetcircle.comsumerdispatcher.jmx; public class ConsumerDispatcherMonitor { private static Log _logger = LogFactory.getLog(ConsumerDispatcherMonitor.class); private static final String fmtUrl = "service:jmx:rmi:///jndi/rmi://%s:%d/jmxrmi"; public static void enableMonitor() { try { enableJMXRmi(); } catch (IOException e) { e.printStackTrace(); } maybeEnableJMXHttp(); } protected static void enableJMXRmi() throws IOException {
// Path: src/main/java/com/thenetcircle/comsumerdispatcher/config/DispatcherConfig.java // public class DispatcherConfig { // // private static DispatcherConfig _self = null; // private List<JobExecutor> allJobs = null; // private Map<String, QueueConf> servers = null; // private MonitorConf monitorConf = null; // // public static synchronized DispatcherConfig getInstance() { // if (null == _self) { // _self = new DispatcherConfig(); // } // return _self; // } // // public void loadConfig(String configFilePath) throws Exception { // ConfigLoader cLoader = null; // if (null == configFilePath) { // cLoader = new DistributedConfigLoader(DistributionManager.getInstance().getZk()); // } else { // cLoader = new FileConfigLoader(configFilePath); // } // // setServers(cLoader.loadServers());// go first // setAllJobs(cLoader.loadAllJobs()); // setMonitorConf(cLoader.loadJmxConfig()); // } // // public List<JobExecutor> getAllJobs() { // return this.allJobs; // } // // public Map<String, QueueConf> getServers() { // return this.servers; // } // // public MonitorConf getMonitorConf() { // return monitorConf; // } // // public void setAllJobs(List<JobExecutor> allJobs) { // this.allJobs = allJobs; // } // // public void setServers(Map<String, QueueConf> servers) { // this.servers = servers; // } // // public void setMonitorConf(MonitorConf monitorConf) { // this.monitorConf = monitorConf; // } // // private DispatcherConfig() { // } // } // // Path: src/main/java/com/thenetcircle/comsumerdispatcher/config/MonitorConf.java // public class MonitorConf { // // jmx config // private String jmxRmiHost = null; // private int jmxRmiPort; // private String jmxHttpHost = null; // private int jmxHttpPort; // // public String getJmxRmiHost() { // return jmxRmiHost; // } // // public int getJmxRmiPort() { // return jmxRmiPort; // } // // public String getJmxHttpHost() { // return jmxHttpHost; // } // // public int getJmxHttpPort() { // return jmxHttpPort; // } // // public void setJmxRmiHost(String jmxRmiHost) { // this.jmxRmiHost = jmxRmiHost; // } // // public void setJmxRmiPort(int jmxRmiPort) { // this.jmxRmiPort = jmxRmiPort; // } // // public void setJmxHttpHost(String jmxHttpHost) { // this.jmxHttpHost = jmxHttpHost; // } // // public void setJmxHttpPort(int jmxHttpPort) { // this.jmxHttpPort = jmxHttpPort; // } // // // } // Path: src/main/java/com/thenetcircle/comsumerdispatcher/jmx/ConsumerDispatcherMonitor.java import java.io.IOException; import java.lang.management.ManagementFactory; import java.rmi.registry.LocateRegistry; import javax.management.MBeanServer; import javax.management.ObjectName; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.thenetcircle.comsumerdispatcher.config.DispatcherConfig; import com.thenetcircle.comsumerdispatcher.config.MonitorConf; package com.thenetcircle.comsumerdispatcher.jmx; public class ConsumerDispatcherMonitor { private static Log _logger = LogFactory.getLog(ConsumerDispatcherMonitor.class); private static final String fmtUrl = "service:jmx:rmi:///jndi/rmi://%s:%d/jmxrmi"; public static void enableMonitor() { try { enableJMXRmi(); } catch (IOException e) { e.printStackTrace(); } maybeEnableJMXHttp(); } protected static void enableJMXRmi() throws IOException {
MonitorConf config = DispatcherConfig.getInstance().getMonitorConf();
jackyhung/consumer-dispatcher
src/main/java/com/thenetcircle/comsumerdispatcher/jmx/ConsumerDispatcherMonitor.java
// Path: src/main/java/com/thenetcircle/comsumerdispatcher/config/DispatcherConfig.java // public class DispatcherConfig { // // private static DispatcherConfig _self = null; // private List<JobExecutor> allJobs = null; // private Map<String, QueueConf> servers = null; // private MonitorConf monitorConf = null; // // public static synchronized DispatcherConfig getInstance() { // if (null == _self) { // _self = new DispatcherConfig(); // } // return _self; // } // // public void loadConfig(String configFilePath) throws Exception { // ConfigLoader cLoader = null; // if (null == configFilePath) { // cLoader = new DistributedConfigLoader(DistributionManager.getInstance().getZk()); // } else { // cLoader = new FileConfigLoader(configFilePath); // } // // setServers(cLoader.loadServers());// go first // setAllJobs(cLoader.loadAllJobs()); // setMonitorConf(cLoader.loadJmxConfig()); // } // // public List<JobExecutor> getAllJobs() { // return this.allJobs; // } // // public Map<String, QueueConf> getServers() { // return this.servers; // } // // public MonitorConf getMonitorConf() { // return monitorConf; // } // // public void setAllJobs(List<JobExecutor> allJobs) { // this.allJobs = allJobs; // } // // public void setServers(Map<String, QueueConf> servers) { // this.servers = servers; // } // // public void setMonitorConf(MonitorConf monitorConf) { // this.monitorConf = monitorConf; // } // // private DispatcherConfig() { // } // } // // Path: src/main/java/com/thenetcircle/comsumerdispatcher/config/MonitorConf.java // public class MonitorConf { // // jmx config // private String jmxRmiHost = null; // private int jmxRmiPort; // private String jmxHttpHost = null; // private int jmxHttpPort; // // public String getJmxRmiHost() { // return jmxRmiHost; // } // // public int getJmxRmiPort() { // return jmxRmiPort; // } // // public String getJmxHttpHost() { // return jmxHttpHost; // } // // public int getJmxHttpPort() { // return jmxHttpPort; // } // // public void setJmxRmiHost(String jmxRmiHost) { // this.jmxRmiHost = jmxRmiHost; // } // // public void setJmxRmiPort(int jmxRmiPort) { // this.jmxRmiPort = jmxRmiPort; // } // // public void setJmxHttpHost(String jmxHttpHost) { // this.jmxHttpHost = jmxHttpHost; // } // // public void setJmxHttpPort(int jmxHttpPort) { // this.jmxHttpPort = jmxHttpPort; // } // // // }
import java.io.IOException; import java.lang.management.ManagementFactory; import java.rmi.registry.LocateRegistry; import javax.management.MBeanServer; import javax.management.ObjectName; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.thenetcircle.comsumerdispatcher.config.DispatcherConfig; import com.thenetcircle.comsumerdispatcher.config.MonitorConf;
package com.thenetcircle.comsumerdispatcher.jmx; public class ConsumerDispatcherMonitor { private static Log _logger = LogFactory.getLog(ConsumerDispatcherMonitor.class); private static final String fmtUrl = "service:jmx:rmi:///jndi/rmi://%s:%d/jmxrmi"; public static void enableMonitor() { try { enableJMXRmi(); } catch (IOException e) { e.printStackTrace(); } maybeEnableJMXHttp(); } protected static void enableJMXRmi() throws IOException {
// Path: src/main/java/com/thenetcircle/comsumerdispatcher/config/DispatcherConfig.java // public class DispatcherConfig { // // private static DispatcherConfig _self = null; // private List<JobExecutor> allJobs = null; // private Map<String, QueueConf> servers = null; // private MonitorConf monitorConf = null; // // public static synchronized DispatcherConfig getInstance() { // if (null == _self) { // _self = new DispatcherConfig(); // } // return _self; // } // // public void loadConfig(String configFilePath) throws Exception { // ConfigLoader cLoader = null; // if (null == configFilePath) { // cLoader = new DistributedConfigLoader(DistributionManager.getInstance().getZk()); // } else { // cLoader = new FileConfigLoader(configFilePath); // } // // setServers(cLoader.loadServers());// go first // setAllJobs(cLoader.loadAllJobs()); // setMonitorConf(cLoader.loadJmxConfig()); // } // // public List<JobExecutor> getAllJobs() { // return this.allJobs; // } // // public Map<String, QueueConf> getServers() { // return this.servers; // } // // public MonitorConf getMonitorConf() { // return monitorConf; // } // // public void setAllJobs(List<JobExecutor> allJobs) { // this.allJobs = allJobs; // } // // public void setServers(Map<String, QueueConf> servers) { // this.servers = servers; // } // // public void setMonitorConf(MonitorConf monitorConf) { // this.monitorConf = monitorConf; // } // // private DispatcherConfig() { // } // } // // Path: src/main/java/com/thenetcircle/comsumerdispatcher/config/MonitorConf.java // public class MonitorConf { // // jmx config // private String jmxRmiHost = null; // private int jmxRmiPort; // private String jmxHttpHost = null; // private int jmxHttpPort; // // public String getJmxRmiHost() { // return jmxRmiHost; // } // // public int getJmxRmiPort() { // return jmxRmiPort; // } // // public String getJmxHttpHost() { // return jmxHttpHost; // } // // public int getJmxHttpPort() { // return jmxHttpPort; // } // // public void setJmxRmiHost(String jmxRmiHost) { // this.jmxRmiHost = jmxRmiHost; // } // // public void setJmxRmiPort(int jmxRmiPort) { // this.jmxRmiPort = jmxRmiPort; // } // // public void setJmxHttpHost(String jmxHttpHost) { // this.jmxHttpHost = jmxHttpHost; // } // // public void setJmxHttpPort(int jmxHttpPort) { // this.jmxHttpPort = jmxHttpPort; // } // // // } // Path: src/main/java/com/thenetcircle/comsumerdispatcher/jmx/ConsumerDispatcherMonitor.java import java.io.IOException; import java.lang.management.ManagementFactory; import java.rmi.registry.LocateRegistry; import javax.management.MBeanServer; import javax.management.ObjectName; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.thenetcircle.comsumerdispatcher.config.DispatcherConfig; import com.thenetcircle.comsumerdispatcher.config.MonitorConf; package com.thenetcircle.comsumerdispatcher.jmx; public class ConsumerDispatcherMonitor { private static Log _logger = LogFactory.getLog(ConsumerDispatcherMonitor.class); private static final String fmtUrl = "service:jmx:rmi:///jndi/rmi://%s:%d/jmxrmi"; public static void enableMonitor() { try { enableJMXRmi(); } catch (IOException e) { e.printStackTrace(); } maybeEnableJMXHttp(); } protected static void enableJMXRmi() throws IOException {
MonitorConf config = DispatcherConfig.getInstance().getMonitorConf();
jackyhung/consumer-dispatcher
src/main/java/com/thenetcircle/comsumerdispatcher/distribution/DistributionManager.java
// Path: src/main/java/com/thenetcircle/comsumerdispatcher/util/HttpUtil.java // public class HttpUtil { // private static Log _logger = LogFactory.getLog(HttpUtil.class); // // public static String sendHttpPost(String url, String host, Map<String, String> parameters, int timeout) throws Exception { // DefaultHttpClient httpclient = getDefaultHttpClient(host); // UrlEncodedFormEntity formEntity = null; // try { // formEntity = new UrlEncodedFormEntity(getParamsList(parameters), HTTP.UTF_8); // } catch (UnsupportedEncodingException e) { // throw e; // } // HttpPost hp = new HttpPost(url); // hp.setEntity(formEntity); // if(host !=null && host.length() > 0) // hp.setHeader("Host", host); // // String responseStr = null; // try { // HttpResponse response = httpclient.execute(hp); // if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // HttpEntity entity = response.getEntity(); // responseStr = new String(EntityUtils.toByteArray(entity)); // } else { // responseStr = "get the response status:" + response.getStatusLine().getStatusCode(); // } // } catch (Exception e) { // _logger.error(e, e); // return null; // } finally { // abortConnection(hp, httpclient); // } // return responseStr; // } // // private static void abortConnection(final HttpRequestBase hrb, final HttpClient httpclient) { // if (hrb != null) { // hrb.abort(); // } // if (httpclient != null) { // httpclient.getConnectionManager().shutdown(); // } // } // // private static DefaultHttpClient getDefaultHttpClient(String host) { // DefaultHttpClient httpclient = new DefaultHttpClient(); // httpclient.getParams().setParameter( // CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); // httpclient.getParams().setParameter("Host", host); // // return httpclient; // } // // private static List<NameValuePair> getParamsList(Map<String, String> paramsMap) { // if (paramsMap == null || paramsMap.size() == 0) { // return null; // } // List<NameValuePair> params = new ArrayList<NameValuePair>(); // for (Map.Entry<String, String> map : paramsMap.entrySet()) { // params.add(new BasicNameValuePair(map.getKey(), map.getValue())); // } // return params; // } // // public static String convertUrlToHostNameAsNodeName(String url) throws MalformedURLException { // String host = new URL(url).getHost().replace('.', '-'); // return host; // } // // public static String getLocalHostName() { // String hostname = null; // try { // InetAddress addr = InetAddress.getLocalHost(); // //byte[] ipAddr = addr.getAddress(); // hostname = addr.getHostName(); // } catch (UnknownHostException e) { // _logger.error(e, e); // } // return hostname; // } // }
import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.ZooDefs.Ids; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.server.ServerConfig; import org.apache.zookeeper.server.ZooKeeperServerMain; import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException; import com.thenetcircle.comsumerdispatcher.util.HttpUtil;
if (clientConfigPath != null) { _logger.info("[Distribution] starts up as client, will laod data from distribution server...."); runType = RUNTYPE_DIST_CLIENT; initZkConnection(clientConfigPath); while(getLivingJoinedMemberNum() < 1) { _logger.info("[Distribution] seems master is not up. wait for master to finishe starting up...."); try { Thread.sleep(1000); } catch (InterruptedException e) { } } } else if (serverConfigPath != null) { _logger.info("[Distribution] starts up as master, needs to start distribution server and populate data to server ...."); runType = RUNTYPE_DIST_SERVER; // this is master, need to start distribution server and populate data to server loadDistributionServerConfig(serverConfigPath); startupServer(); initZkConnection(sc.getClientPortAddress().getHostName() + ":" + sc.getClientPortAddress().getPort()); // populate data to server populateDataTree(); } updateJoinedMemberNode(); } protected void updateJoinedMemberNode() {
// Path: src/main/java/com/thenetcircle/comsumerdispatcher/util/HttpUtil.java // public class HttpUtil { // private static Log _logger = LogFactory.getLog(HttpUtil.class); // // public static String sendHttpPost(String url, String host, Map<String, String> parameters, int timeout) throws Exception { // DefaultHttpClient httpclient = getDefaultHttpClient(host); // UrlEncodedFormEntity formEntity = null; // try { // formEntity = new UrlEncodedFormEntity(getParamsList(parameters), HTTP.UTF_8); // } catch (UnsupportedEncodingException e) { // throw e; // } // HttpPost hp = new HttpPost(url); // hp.setEntity(formEntity); // if(host !=null && host.length() > 0) // hp.setHeader("Host", host); // // String responseStr = null; // try { // HttpResponse response = httpclient.execute(hp); // if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // HttpEntity entity = response.getEntity(); // responseStr = new String(EntityUtils.toByteArray(entity)); // } else { // responseStr = "get the response status:" + response.getStatusLine().getStatusCode(); // } // } catch (Exception e) { // _logger.error(e, e); // return null; // } finally { // abortConnection(hp, httpclient); // } // return responseStr; // } // // private static void abortConnection(final HttpRequestBase hrb, final HttpClient httpclient) { // if (hrb != null) { // hrb.abort(); // } // if (httpclient != null) { // httpclient.getConnectionManager().shutdown(); // } // } // // private static DefaultHttpClient getDefaultHttpClient(String host) { // DefaultHttpClient httpclient = new DefaultHttpClient(); // httpclient.getParams().setParameter( // CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); // httpclient.getParams().setParameter("Host", host); // // return httpclient; // } // // private static List<NameValuePair> getParamsList(Map<String, String> paramsMap) { // if (paramsMap == null || paramsMap.size() == 0) { // return null; // } // List<NameValuePair> params = new ArrayList<NameValuePair>(); // for (Map.Entry<String, String> map : paramsMap.entrySet()) { // params.add(new BasicNameValuePair(map.getKey(), map.getValue())); // } // return params; // } // // public static String convertUrlToHostNameAsNodeName(String url) throws MalformedURLException { // String host = new URL(url).getHost().replace('.', '-'); // return host; // } // // public static String getLocalHostName() { // String hostname = null; // try { // InetAddress addr = InetAddress.getLocalHost(); // //byte[] ipAddr = addr.getAddress(); // hostname = addr.getHostName(); // } catch (UnknownHostException e) { // _logger.error(e, e); // } // return hostname; // } // } // Path: src/main/java/com/thenetcircle/comsumerdispatcher/distribution/DistributionManager.java import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.ZooDefs.Ids; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.server.ServerConfig; import org.apache.zookeeper.server.ZooKeeperServerMain; import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException; import com.thenetcircle.comsumerdispatcher.util.HttpUtil; if (clientConfigPath != null) { _logger.info("[Distribution] starts up as client, will laod data from distribution server...."); runType = RUNTYPE_DIST_CLIENT; initZkConnection(clientConfigPath); while(getLivingJoinedMemberNum() < 1) { _logger.info("[Distribution] seems master is not up. wait for master to finishe starting up...."); try { Thread.sleep(1000); } catch (InterruptedException e) { } } } else if (serverConfigPath != null) { _logger.info("[Distribution] starts up as master, needs to start distribution server and populate data to server ...."); runType = RUNTYPE_DIST_SERVER; // this is master, need to start distribution server and populate data to server loadDistributionServerConfig(serverConfigPath); startupServer(); initZkConnection(sc.getClientPortAddress().getHostName() + ":" + sc.getClientPortAddress().getPort()); // populate data to server populateDataTree(); } updateJoinedMemberNode(); } protected void updateJoinedMemberNode() {
String hostname = HttpUtil.getLocalHostName();
zeevy/grblcontroller
app/src/main/java/in/co/gorest/grblcontroller/network/GoRestService.java
// Path: app/src/main/java/in/co/gorest/grblcontroller/model/FcmToken.java // public class FcmToken { // // @SerializedName("app_name") // private String appName; // // @SerializedName("app_version") // private String appVersion; // // @SerializedName("token") // private String token; // // @SerializedName("device_name") // private String deviceName; // // @SerializedName("os_version") // private String osVersion; // // public FcmToken(){ // // } // // public FcmToken(String token){ // this.token = token; // this.appName = BuildConfig.APPLICATION_ID; // this.appVersion = String.valueOf(BuildConfig.VERSION_CODE); // this.deviceName = Build.MODEL; // this.osVersion = Build.VERSION.RELEASE; // } // // public String getAppName() { // return appName; // } // // public void setAppName(String appName) { // this.appName = appName; // } // // public String getAppVersion() { // return appVersion; // } // // public void setAppVersion(String appVersion) { // this.appVersion = appVersion; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // // public String getDeviceName() { // return deviceName; // } // // public void setDeviceName(String deviceName) { // this.deviceName = deviceName; // } // // public String getOsVersion() { // return osVersion; // } // // public void setOsVersion(String osVersion) { // this.osVersion = osVersion; // } // }
import com.google.gson.JsonObject; import in.co.gorest.grblcontroller.model.FcmToken; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.POST;
/* * * * /** * * * Copyright (C) 2017 Grbl Controller Contributors * * * * * * This program is free software; you can redistribute it and/or modify * * * it under the terms of the GNU General Public License as published by * * * the Free Software Foundation; either version 2 of the License, or * * * (at your option) any later version. * * * * * * This program is distributed in the hope that it will be useful, * * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * * GNU General Public License for more details. * * * * * * You should have received a copy of the GNU General Public License along * * * with this program; if not, write to the Free Software Foundation, Inc., * * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * * <http://www.gnu.org/licenses/> * * * */ package in.co.gorest.grblcontroller.network; public interface GoRestService { @POST("/fcm-registration.html")
// Path: app/src/main/java/in/co/gorest/grblcontroller/model/FcmToken.java // public class FcmToken { // // @SerializedName("app_name") // private String appName; // // @SerializedName("app_version") // private String appVersion; // // @SerializedName("token") // private String token; // // @SerializedName("device_name") // private String deviceName; // // @SerializedName("os_version") // private String osVersion; // // public FcmToken(){ // // } // // public FcmToken(String token){ // this.token = token; // this.appName = BuildConfig.APPLICATION_ID; // this.appVersion = String.valueOf(BuildConfig.VERSION_CODE); // this.deviceName = Build.MODEL; // this.osVersion = Build.VERSION.RELEASE; // } // // public String getAppName() { // return appName; // } // // public void setAppName(String appName) { // this.appName = appName; // } // // public String getAppVersion() { // return appVersion; // } // // public void setAppVersion(String appVersion) { // this.appVersion = appVersion; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // // public String getDeviceName() { // return deviceName; // } // // public void setDeviceName(String deviceName) { // this.deviceName = deviceName; // } // // public String getOsVersion() { // return osVersion; // } // // public void setOsVersion(String osVersion) { // this.osVersion = osVersion; // } // } // Path: app/src/main/java/in/co/gorest/grblcontroller/network/GoRestService.java import com.google.gson.JsonObject; import in.co.gorest.grblcontroller.model.FcmToken; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.POST; /* * * * /** * * * Copyright (C) 2017 Grbl Controller Contributors * * * * * * This program is free software; you can redistribute it and/or modify * * * it under the terms of the GNU General Public License as published by * * * the Free Software Foundation; either version 2 of the License, or * * * (at your option) any later version. * * * * * * This program is distributed in the hope that it will be useful, * * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * * GNU General Public License for more details. * * * * * * You should have received a copy of the GNU General Public License along * * * with this program; if not, write to the Free Software Foundation, Inc., * * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * * <http://www.gnu.org/licenses/> * * * */ package in.co.gorest.grblcontroller.network; public interface GoRestService { @POST("/fcm-registration.html")
Call<JsonObject> postFcmToken(@Body FcmToken fcmToken);
zeevy/grblcontroller
app/src/main/java/in/co/gorest/grblcontroller/events/GrblErrorEvent.java
// Path: app/src/main/java/in/co/gorest/grblcontroller/GrblController.java // public class GrblController extends SugarApp { // // private final String TAG = GrblController.class.getSimpleName(); // private static GrblController grblController; // private GoRestService goRestService; // // @Override // public void onCreate() { // super.onCreate(); // // configureCrashReporting(); // // grblController = this; // // // Picasso.Builder builder = new Picasso.Builder(this); // // builder.downloader(new OkHttp3Downloader(this, Integer.MAX_VALUE)); // // Picasso picasso = builder.build(); // // picasso.setIndicatorsEnabled(BuildConfig.DEBUG); // // picasso.setLoggingEnabled(BuildConfig.DEBUG); // // Picasso.setSingletonInstance(picasso); // // AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); // Iconify.with(new FontAwesomeModule()); // } // // public static synchronized GrblController getInstance(){ // return grblController; // } // // private void configureCrashReporting(){ // // } // // public GoRestService getRetrofit(){ // if(goRestService == null){ // Retrofit retrofit = new Retrofit.Builder() // .baseUrl("https://gorest.co.in") // .addConverterFactory(GsonConverterFactory.create()) // .build(); // // goRestService = retrofit.create(GoRestService.class); // } // // return goRestService; // } // // } // // Path: app/src/main/java/in/co/gorest/grblcontroller/util/GrblLookups.java // public class GrblLookups { // // private final HashMap<String,String[]> lookups = new HashMap<>(); // // public GrblLookups(Context context, String prefix) { // String filename = prefix + ".csv"; // // try { // try (BufferedReader br = new BufferedReader( // new InputStreamReader(context.getAssets().open(filename)))) { // String line; // while ((line = br.readLine()) != null) { // String[] parts = line.split(","); // lookups.put(parts[0], parts); // } // } // } catch (IOException ex) { // System.out.println("Unable to load GRBL resources."); // ex.printStackTrace(); // } // } // // public String[] lookup(String idx){ // return lookups.get(idx); // } // // }
import in.co.gorest.grblcontroller.GrblController; import in.co.gorest.grblcontroller.R; import in.co.gorest.grblcontroller.util.GrblLookups;
/* * /** * * Copyright (C) 2017 Grbl Controller Contributors * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along * * with this program; if not, write to the Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * <http://www.gnu.org/licenses/> * */ package in.co.gorest.grblcontroller.events; public class GrblErrorEvent { private final String message; private int errorCode; private String errorName; private String errorDescription;
// Path: app/src/main/java/in/co/gorest/grblcontroller/GrblController.java // public class GrblController extends SugarApp { // // private final String TAG = GrblController.class.getSimpleName(); // private static GrblController grblController; // private GoRestService goRestService; // // @Override // public void onCreate() { // super.onCreate(); // // configureCrashReporting(); // // grblController = this; // // // Picasso.Builder builder = new Picasso.Builder(this); // // builder.downloader(new OkHttp3Downloader(this, Integer.MAX_VALUE)); // // Picasso picasso = builder.build(); // // picasso.setIndicatorsEnabled(BuildConfig.DEBUG); // // picasso.setLoggingEnabled(BuildConfig.DEBUG); // // Picasso.setSingletonInstance(picasso); // // AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); // Iconify.with(new FontAwesomeModule()); // } // // public static synchronized GrblController getInstance(){ // return grblController; // } // // private void configureCrashReporting(){ // // } // // public GoRestService getRetrofit(){ // if(goRestService == null){ // Retrofit retrofit = new Retrofit.Builder() // .baseUrl("https://gorest.co.in") // .addConverterFactory(GsonConverterFactory.create()) // .build(); // // goRestService = retrofit.create(GoRestService.class); // } // // return goRestService; // } // // } // // Path: app/src/main/java/in/co/gorest/grblcontroller/util/GrblLookups.java // public class GrblLookups { // // private final HashMap<String,String[]> lookups = new HashMap<>(); // // public GrblLookups(Context context, String prefix) { // String filename = prefix + ".csv"; // // try { // try (BufferedReader br = new BufferedReader( // new InputStreamReader(context.getAssets().open(filename)))) { // String line; // while ((line = br.readLine()) != null) { // String[] parts = line.split(","); // lookups.put(parts[0], parts); // } // } // } catch (IOException ex) { // System.out.println("Unable to load GRBL resources."); // ex.printStackTrace(); // } // } // // public String[] lookup(String idx){ // return lookups.get(idx); // } // // } // Path: app/src/main/java/in/co/gorest/grblcontroller/events/GrblErrorEvent.java import in.co.gorest.grblcontroller.GrblController; import in.co.gorest.grblcontroller.R; import in.co.gorest.grblcontroller.util.GrblLookups; /* * /** * * Copyright (C) 2017 Grbl Controller Contributors * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along * * with this program; if not, write to the Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * <http://www.gnu.org/licenses/> * */ package in.co.gorest.grblcontroller.events; public class GrblErrorEvent { private final String message; private int errorCode; private String errorName; private String errorDescription;
public GrblErrorEvent(GrblLookups lookups, String message){
zeevy/grblcontroller
app/src/main/java/in/co/gorest/grblcontroller/events/GrblErrorEvent.java
// Path: app/src/main/java/in/co/gorest/grblcontroller/GrblController.java // public class GrblController extends SugarApp { // // private final String TAG = GrblController.class.getSimpleName(); // private static GrblController grblController; // private GoRestService goRestService; // // @Override // public void onCreate() { // super.onCreate(); // // configureCrashReporting(); // // grblController = this; // // // Picasso.Builder builder = new Picasso.Builder(this); // // builder.downloader(new OkHttp3Downloader(this, Integer.MAX_VALUE)); // // Picasso picasso = builder.build(); // // picasso.setIndicatorsEnabled(BuildConfig.DEBUG); // // picasso.setLoggingEnabled(BuildConfig.DEBUG); // // Picasso.setSingletonInstance(picasso); // // AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); // Iconify.with(new FontAwesomeModule()); // } // // public static synchronized GrblController getInstance(){ // return grblController; // } // // private void configureCrashReporting(){ // // } // // public GoRestService getRetrofit(){ // if(goRestService == null){ // Retrofit retrofit = new Retrofit.Builder() // .baseUrl("https://gorest.co.in") // .addConverterFactory(GsonConverterFactory.create()) // .build(); // // goRestService = retrofit.create(GoRestService.class); // } // // return goRestService; // } // // } // // Path: app/src/main/java/in/co/gorest/grblcontroller/util/GrblLookups.java // public class GrblLookups { // // private final HashMap<String,String[]> lookups = new HashMap<>(); // // public GrblLookups(Context context, String prefix) { // String filename = prefix + ".csv"; // // try { // try (BufferedReader br = new BufferedReader( // new InputStreamReader(context.getAssets().open(filename)))) { // String line; // while ((line = br.readLine()) != null) { // String[] parts = line.split(","); // lookups.put(parts[0], parts); // } // } // } catch (IOException ex) { // System.out.println("Unable to load GRBL resources."); // ex.printStackTrace(); // } // } // // public String[] lookup(String idx){ // return lookups.get(idx); // } // // }
import in.co.gorest.grblcontroller.GrblController; import in.co.gorest.grblcontroller.R; import in.co.gorest.grblcontroller.util.GrblLookups;
/* * /** * * Copyright (C) 2017 Grbl Controller Contributors * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along * * with this program; if not, write to the Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * <http://www.gnu.org/licenses/> * */ package in.co.gorest.grblcontroller.events; public class GrblErrorEvent { private final String message; private int errorCode; private String errorName; private String errorDescription; public GrblErrorEvent(GrblLookups lookups, String message){ this.message = message; String inputParts[] = message.split(":"); if(inputParts.length == 2){ String[] lookup = lookups.lookup(inputParts[1].trim()); if(lookup != null){ this.errorCode = Integer.parseInt(lookup[0]); this.errorName = lookup[1]; this.errorDescription = lookup[2]; } } } @Override public String toString(){
// Path: app/src/main/java/in/co/gorest/grblcontroller/GrblController.java // public class GrblController extends SugarApp { // // private final String TAG = GrblController.class.getSimpleName(); // private static GrblController grblController; // private GoRestService goRestService; // // @Override // public void onCreate() { // super.onCreate(); // // configureCrashReporting(); // // grblController = this; // // // Picasso.Builder builder = new Picasso.Builder(this); // // builder.downloader(new OkHttp3Downloader(this, Integer.MAX_VALUE)); // // Picasso picasso = builder.build(); // // picasso.setIndicatorsEnabled(BuildConfig.DEBUG); // // picasso.setLoggingEnabled(BuildConfig.DEBUG); // // Picasso.setSingletonInstance(picasso); // // AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); // Iconify.with(new FontAwesomeModule()); // } // // public static synchronized GrblController getInstance(){ // return grblController; // } // // private void configureCrashReporting(){ // // } // // public GoRestService getRetrofit(){ // if(goRestService == null){ // Retrofit retrofit = new Retrofit.Builder() // .baseUrl("https://gorest.co.in") // .addConverterFactory(GsonConverterFactory.create()) // .build(); // // goRestService = retrofit.create(GoRestService.class); // } // // return goRestService; // } // // } // // Path: app/src/main/java/in/co/gorest/grblcontroller/util/GrblLookups.java // public class GrblLookups { // // private final HashMap<String,String[]> lookups = new HashMap<>(); // // public GrblLookups(Context context, String prefix) { // String filename = prefix + ".csv"; // // try { // try (BufferedReader br = new BufferedReader( // new InputStreamReader(context.getAssets().open(filename)))) { // String line; // while ((line = br.readLine()) != null) { // String[] parts = line.split(","); // lookups.put(parts[0], parts); // } // } // } catch (IOException ex) { // System.out.println("Unable to load GRBL resources."); // ex.printStackTrace(); // } // } // // public String[] lookup(String idx){ // return lookups.get(idx); // } // // } // Path: app/src/main/java/in/co/gorest/grblcontroller/events/GrblErrorEvent.java import in.co.gorest.grblcontroller.GrblController; import in.co.gorest.grblcontroller.R; import in.co.gorest.grblcontroller.util.GrblLookups; /* * /** * * Copyright (C) 2017 Grbl Controller Contributors * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along * * with this program; if not, write to the Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * <http://www.gnu.org/licenses/> * */ package in.co.gorest.grblcontroller.events; public class GrblErrorEvent { private final String message; private int errorCode; private String errorName; private String errorDescription; public GrblErrorEvent(GrblLookups lookups, String message){ this.message = message; String inputParts[] = message.split(":"); if(inputParts.length == 2){ String[] lookup = lookups.lookup(inputParts[1].trim()); if(lookup != null){ this.errorCode = Integer.parseInt(lookup[0]); this.errorName = lookup[1]; this.errorDescription = lookup[2]; } } } @Override public String toString(){
return GrblController.getInstance().getString(R.string.text_grbl_error_format, errorCode, errorDescription);
zeevy/grblcontroller
app/src/main/java/in/co/gorest/grblcontroller/DeviceListActivity.java
// Path: app/src/main/java/in/co/gorest/grblcontroller/events/UiToastEvent.java // public class UiToastEvent { // // private String message; // private Boolean longToast; // private Boolean isWarning; // // public UiToastEvent(String message){ // this.message = message; // this.longToast = false; // this.isWarning = false; // } // // public UiToastEvent(String message, Boolean longToast){ // this.message = message; // this.longToast = longToast; // this.isWarning = false; // } // // public UiToastEvent(String message, Boolean longToast, Boolean isWarning){ // this.message = message; // this.longToast = longToast; // this.isWarning = isWarning; // } // // public String getMessage(){ return this.message; } // public void setMessage(String message){ this.message = message; } // // public Boolean getLongToast(){ return this.longToast; } // public void setLongToast(Boolean longToast){ this.longToast = longToast; } // // public Boolean getIsWarning(){ return this.isWarning; } // public void setIsWarning(boolean isWarning){ // this.isWarning = isWarning; // } // // }
import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import androidx.appcompat.app.AppCompatDelegate; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import org.greenrobot.eventbus.EventBus; import java.util.Collections; import java.util.Set; import in.co.gorest.grblcontroller.events.UiToastEvent;
/* * /** * * Copyright (C) 2017 Grbl Controller Contributors * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along * * with this program; if not, write to the Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * <http://www.gnu.org/licenses/> * */ package in.co.gorest.grblcontroller; public class DeviceListActivity extends Activity { static { AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); } public static final String EXTRA_DEVICE_ADDRESS = "device_address"; private BluetoothAdapter mBtAdapter; private ArrayAdapter<String> mNewDevicesArrayAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mBtAdapter = BluetoothAdapter.getDefaultAdapter(); if(mBtAdapter == null){
// Path: app/src/main/java/in/co/gorest/grblcontroller/events/UiToastEvent.java // public class UiToastEvent { // // private String message; // private Boolean longToast; // private Boolean isWarning; // // public UiToastEvent(String message){ // this.message = message; // this.longToast = false; // this.isWarning = false; // } // // public UiToastEvent(String message, Boolean longToast){ // this.message = message; // this.longToast = longToast; // this.isWarning = false; // } // // public UiToastEvent(String message, Boolean longToast, Boolean isWarning){ // this.message = message; // this.longToast = longToast; // this.isWarning = isWarning; // } // // public String getMessage(){ return this.message; } // public void setMessage(String message){ this.message = message; } // // public Boolean getLongToast(){ return this.longToast; } // public void setLongToast(Boolean longToast){ this.longToast = longToast; } // // public Boolean getIsWarning(){ return this.isWarning; } // public void setIsWarning(boolean isWarning){ // this.isWarning = isWarning; // } // // } // Path: app/src/main/java/in/co/gorest/grblcontroller/DeviceListActivity.java import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import androidx.appcompat.app.AppCompatDelegate; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import org.greenrobot.eventbus.EventBus; import java.util.Collections; import java.util.Set; import in.co.gorest.grblcontroller.events.UiToastEvent; /* * /** * * Copyright (C) 2017 Grbl Controller Contributors * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along * * with this program; if not, write to the Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * <http://www.gnu.org/licenses/> * */ package in.co.gorest.grblcontroller; public class DeviceListActivity extends Activity { static { AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); } public static final String EXTRA_DEVICE_ADDRESS = "device_address"; private BluetoothAdapter mBtAdapter; private ArrayAdapter<String> mNewDevicesArrayAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mBtAdapter = BluetoothAdapter.getDefaultAdapter(); if(mBtAdapter == null){
EventBus.getDefault().post(new UiToastEvent(getString(R.string.text_bluetooth_adapter_error), true, true));
zeevy/grblcontroller
app/src/main/java/in/co/gorest/grblcontroller/events/GrblProbeEvent.java
// Path: app/src/main/java/in/co/gorest/grblcontroller/model/Position.java // public class Position { // private final Double cordX; // private final Double cordY; // private final Double cordZ; // // // private static final NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.ENGLISH); // private static final DecimalFormat decimalFormat = (DecimalFormat) numberFormat; // // public Position(double x, double y, double z){ // this.cordX = x; this.cordY = y; this.cordZ = z; // decimalFormat.applyPattern("#0.###"); // } // // public Double getCordX(){ return this.cordX; } // public Double getCordY(){ return this.cordY; } // public Double getCordZ(){ return this.cordZ; } // // private Double roundDouble(Double value){ // String s = decimalFormat.format(value); // return Double.parseDouble(s); // } // // public boolean hasChanged(Position position){ // return (position.getCordX().compareTo(this.cordX) != 0) || (position.getCordY().compareTo(this.cordY) != 0) || (position.getCordZ().compareTo(this.cordZ) != 0); // } // // public boolean atZero(){ // return Math.abs(this.cordX) == 0 && Math.abs(this.cordY) == 0 && Math.abs(this.cordZ) == 0; // } // // }
import in.co.gorest.grblcontroller.model.Position;
/* * /** * * Copyright (C) 2017 Grbl Controller Contributors * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along * * with this program; if not, write to the Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * <http://www.gnu.org/licenses/> * */ package in.co.gorest.grblcontroller.events; public class GrblProbeEvent { private final String probeString;
// Path: app/src/main/java/in/co/gorest/grblcontroller/model/Position.java // public class Position { // private final Double cordX; // private final Double cordY; // private final Double cordZ; // // // private static final NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.ENGLISH); // private static final DecimalFormat decimalFormat = (DecimalFormat) numberFormat; // // public Position(double x, double y, double z){ // this.cordX = x; this.cordY = y; this.cordZ = z; // decimalFormat.applyPattern("#0.###"); // } // // public Double getCordX(){ return this.cordX; } // public Double getCordY(){ return this.cordY; } // public Double getCordZ(){ return this.cordZ; } // // private Double roundDouble(Double value){ // String s = decimalFormat.format(value); // return Double.parseDouble(s); // } // // public boolean hasChanged(Position position){ // return (position.getCordX().compareTo(this.cordX) != 0) || (position.getCordY().compareTo(this.cordY) != 0) || (position.getCordZ().compareTo(this.cordZ) != 0); // } // // public boolean atZero(){ // return Math.abs(this.cordX) == 0 && Math.abs(this.cordY) == 0 && Math.abs(this.cordZ) == 0; // } // // } // Path: app/src/main/java/in/co/gorest/grblcontroller/events/GrblProbeEvent.java import in.co.gorest.grblcontroller.model.Position; /* * /** * * Copyright (C) 2017 Grbl Controller Contributors * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along * * with this program; if not, write to the Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * <http://www.gnu.org/licenses/> * */ package in.co.gorest.grblcontroller.events; public class GrblProbeEvent { private final String probeString;
private Position probePosition;
zeevy/grblcontroller
app/src/main/java/com/joanzapata/iconify/internal/ParsingUtil.java
// Path: app/src/main/java/com/joanzapata/iconify/Icon.java // public interface Icon { // // /** The key of icon, for example 'fa-ok' */ // String key(); // // /** The character matching the key in the font, for example '\u4354' */ // char character(); // // } // // Path: app/src/main/java/com/joanzapata/iconify/internal/HasOnViewAttachListener.java // interface OnViewAttachListener { // void onAttach(); // // void onDetach(); // }
import java.util.List; import android.content.Context; import android.content.res.Resources; import android.graphics.Color; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.util.TypedValue; import android.widget.TextView; import androidx.core.view.ViewCompat; import com.joanzapata.iconify.Icon; import com.joanzapata.iconify.internal.HasOnViewAttachListener.OnViewAttachListener;
package com.joanzapata.iconify.internal; public final class ParsingUtil { private static final String ANDROID_PACKAGE_NAME = "android"; // Prevents instantiation private ParsingUtil() {} public static CharSequence parse( Context context, List<IconFontDescriptorWrapper> iconFontDescriptors, CharSequence text, final TextView target) { context = context.getApplicationContext(); // Don't do anything related to iconify if text is null if (text == null) return text; // Analyse the text and replace {} blocks with the appropriate character // Retain all transformations in the accumulator final SpannableStringBuilder spannableBuilder = new SpannableStringBuilder(text); recursivePrepareSpannableIndexes(context, text.toString(), spannableBuilder, iconFontDescriptors, 0); boolean isAnimated = hasAnimatedSpans(spannableBuilder); // If animated, periodically invalidate the TextView so that the // CustomTypefaceSpan can redraw itself if (isAnimated) { if (target == null) throw new IllegalArgumentException("You can't use \"spin\" without providing the target TextView."); if (!(target instanceof HasOnViewAttachListener)) throw new IllegalArgumentException(target.getClass().getSimpleName() + " does not implement " + "HasOnViewAttachListener. Please use IconTextView, IconButton or IconToggleButton.");
// Path: app/src/main/java/com/joanzapata/iconify/Icon.java // public interface Icon { // // /** The key of icon, for example 'fa-ok' */ // String key(); // // /** The character matching the key in the font, for example '\u4354' */ // char character(); // // } // // Path: app/src/main/java/com/joanzapata/iconify/internal/HasOnViewAttachListener.java // interface OnViewAttachListener { // void onAttach(); // // void onDetach(); // } // Path: app/src/main/java/com/joanzapata/iconify/internal/ParsingUtil.java import java.util.List; import android.content.Context; import android.content.res.Resources; import android.graphics.Color; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.util.TypedValue; import android.widget.TextView; import androidx.core.view.ViewCompat; import com.joanzapata.iconify.Icon; import com.joanzapata.iconify.internal.HasOnViewAttachListener.OnViewAttachListener; package com.joanzapata.iconify.internal; public final class ParsingUtil { private static final String ANDROID_PACKAGE_NAME = "android"; // Prevents instantiation private ParsingUtil() {} public static CharSequence parse( Context context, List<IconFontDescriptorWrapper> iconFontDescriptors, CharSequence text, final TextView target) { context = context.getApplicationContext(); // Don't do anything related to iconify if text is null if (text == null) return text; // Analyse the text and replace {} blocks with the appropriate character // Retain all transformations in the accumulator final SpannableStringBuilder spannableBuilder = new SpannableStringBuilder(text); recursivePrepareSpannableIndexes(context, text.toString(), spannableBuilder, iconFontDescriptors, 0); boolean isAnimated = hasAnimatedSpans(spannableBuilder); // If animated, periodically invalidate the TextView so that the // CustomTypefaceSpan can redraw itself if (isAnimated) { if (target == null) throw new IllegalArgumentException("You can't use \"spin\" without providing the target TextView."); if (!(target instanceof HasOnViewAttachListener)) throw new IllegalArgumentException(target.getClass().getSimpleName() + " does not implement " + "HasOnViewAttachListener. Please use IconTextView, IconButton or IconToggleButton.");
((HasOnViewAttachListener) target).setOnViewAttachListener(new OnViewAttachListener() {
zeevy/grblcontroller
app/src/main/java/com/joanzapata/iconify/internal/ParsingUtil.java
// Path: app/src/main/java/com/joanzapata/iconify/Icon.java // public interface Icon { // // /** The key of icon, for example 'fa-ok' */ // String key(); // // /** The character matching the key in the font, for example '\u4354' */ // char character(); // // } // // Path: app/src/main/java/com/joanzapata/iconify/internal/HasOnViewAttachListener.java // interface OnViewAttachListener { // void onAttach(); // // void onDetach(); // }
import java.util.List; import android.content.Context; import android.content.res.Resources; import android.graphics.Color; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.util.TypedValue; import android.widget.TextView; import androidx.core.view.ViewCompat; import com.joanzapata.iconify.Icon; import com.joanzapata.iconify.internal.HasOnViewAttachListener.OnViewAttachListener;
private static boolean hasAnimatedSpans(SpannableStringBuilder spannableBuilder) { CustomTypefaceSpan[] spans = spannableBuilder.getSpans(0, spannableBuilder.length(), CustomTypefaceSpan.class); for (CustomTypefaceSpan span : spans) { if (span.isAnimated()) return true; } return false; } private static void recursivePrepareSpannableIndexes( Context context, String fullText, SpannableStringBuilder text, List<IconFontDescriptorWrapper> iconFontDescriptors, int start) { // Try to find a {...} in the string and extract expression from it String stringText = text.toString(); int startIndex = stringText.indexOf("{", start); if (startIndex == -1) return; int endIndex = stringText.indexOf("}", startIndex) + 1; if (endIndex == -1) return; String expression = stringText.substring(startIndex + 1, endIndex - 1); // Split the expression and retrieve the icon key String[] strokes = expression.split(" "); String key = strokes[0]; // Loop through the descriptors to find a key match IconFontDescriptorWrapper iconFontDescriptor = null;
// Path: app/src/main/java/com/joanzapata/iconify/Icon.java // public interface Icon { // // /** The key of icon, for example 'fa-ok' */ // String key(); // // /** The character matching the key in the font, for example '\u4354' */ // char character(); // // } // // Path: app/src/main/java/com/joanzapata/iconify/internal/HasOnViewAttachListener.java // interface OnViewAttachListener { // void onAttach(); // // void onDetach(); // } // Path: app/src/main/java/com/joanzapata/iconify/internal/ParsingUtil.java import java.util.List; import android.content.Context; import android.content.res.Resources; import android.graphics.Color; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.util.TypedValue; import android.widget.TextView; import androidx.core.view.ViewCompat; import com.joanzapata.iconify.Icon; import com.joanzapata.iconify.internal.HasOnViewAttachListener.OnViewAttachListener; private static boolean hasAnimatedSpans(SpannableStringBuilder spannableBuilder) { CustomTypefaceSpan[] spans = spannableBuilder.getSpans(0, spannableBuilder.length(), CustomTypefaceSpan.class); for (CustomTypefaceSpan span : spans) { if (span.isAnimated()) return true; } return false; } private static void recursivePrepareSpannableIndexes( Context context, String fullText, SpannableStringBuilder text, List<IconFontDescriptorWrapper> iconFontDescriptors, int start) { // Try to find a {...} in the string and extract expression from it String stringText = text.toString(); int startIndex = stringText.indexOf("{", start); if (startIndex == -1) return; int endIndex = stringText.indexOf("}", startIndex) + 1; if (endIndex == -1) return; String expression = stringText.substring(startIndex + 1, endIndex - 1); // Split the expression and retrieve the icon key String[] strokes = expression.split(" "); String key = strokes[0]; // Loop through the descriptors to find a key match IconFontDescriptorWrapper iconFontDescriptor = null;
Icon icon = null;
zeevy/grblcontroller
app/src/main/java/com/joanzapata/iconify/internal/IconFontDescriptorWrapper.java
// Path: app/src/main/java/com/joanzapata/iconify/Icon.java // public interface Icon { // // /** The key of icon, for example 'fa-ok' */ // String key(); // // /** The character matching the key in the font, for example '\u4354' */ // char character(); // // } // // Path: app/src/main/java/com/joanzapata/iconify/IconFontDescriptor.java // public interface IconFontDescriptor { // // /** // * The TTF file name. // * @return a name with no slash, present in the assets. // */ // String ttfFileName(); // // Icon[] characters(); // // }
import android.content.Context; import android.graphics.Typeface; import com.joanzapata.iconify.Icon; import com.joanzapata.iconify.IconFontDescriptor; import java.util.HashMap; import java.util.Map;
package com.joanzapata.iconify.internal; public class IconFontDescriptorWrapper { private final IconFontDescriptor iconFontDescriptor;
// Path: app/src/main/java/com/joanzapata/iconify/Icon.java // public interface Icon { // // /** The key of icon, for example 'fa-ok' */ // String key(); // // /** The character matching the key in the font, for example '\u4354' */ // char character(); // // } // // Path: app/src/main/java/com/joanzapata/iconify/IconFontDescriptor.java // public interface IconFontDescriptor { // // /** // * The TTF file name. // * @return a name with no slash, present in the assets. // */ // String ttfFileName(); // // Icon[] characters(); // // } // Path: app/src/main/java/com/joanzapata/iconify/internal/IconFontDescriptorWrapper.java import android.content.Context; import android.graphics.Typeface; import com.joanzapata.iconify.Icon; import com.joanzapata.iconify.IconFontDescriptor; import java.util.HashMap; import java.util.Map; package com.joanzapata.iconify.internal; public class IconFontDescriptorWrapper { private final IconFontDescriptor iconFontDescriptor;
private final Map<String, Icon> iconsByKey;
zeevy/grblcontroller
app/src/main/java/com/joanzapata/iconify/IconDrawable.java
// Path: app/src/main/java/com/joanzapata/iconify/internal/IconFontDescriptorWrapper.java // public class IconFontDescriptorWrapper { // // private final IconFontDescriptor iconFontDescriptor; // // private final Map<String, Icon> iconsByKey; // // private Typeface cachedTypeface; // // public IconFontDescriptorWrapper(IconFontDescriptor iconFontDescriptor) { // this.iconFontDescriptor = iconFontDescriptor; // iconsByKey = new HashMap<String, Icon>(); // Icon[] characters = iconFontDescriptor.characters(); // for (int i = 0, charactersLength = characters.length; i < charactersLength; i++) { // Icon icon = characters[i]; // iconsByKey.put(icon.key(), icon); // } // } // // public Icon getIcon(String key) { // return iconsByKey.get(key); // } // // public IconFontDescriptor getIconFontDescriptor() { // return iconFontDescriptor; // } // // public Typeface getTypeface(Context context) { // if (cachedTypeface != null) return cachedTypeface; // synchronized (this) { // if (cachedTypeface != null) return cachedTypeface; // cachedTypeface = Typeface.createFromAsset(context.getAssets(), iconFontDescriptor.ttfFileName()); // return cachedTypeface; // } // } // // public boolean hasIcon(Icon icon) { // return iconsByKey.values().contains(icon); // } // }
import android.content.Context; import android.graphics.*; import android.graphics.drawable.Drawable; import android.text.TextPaint; import android.util.TypedValue; import com.joanzapata.iconify.internal.IconFontDescriptorWrapper; import static android.util.TypedValue.COMPLEX_UNIT_DIP;
package com.joanzapata.iconify; /** * Embed an icon into a Drawable that can be used as TextView icons, or ActionBar icons. * <pre> * new IconDrawable(context, IconValue.icon_star) * .colorRes(R.color.white) * .actionBarSize(); * </pre> * If you don't set the size of the drawable, it will use the size * that is given to him. Note that in an ActionBar, if you don't * set the size explicitly it uses 0, so please use actionBarSize(). */ public class IconDrawable extends Drawable { public static final int ANDROID_ACTIONBAR_ICON_SIZE_DP = 24; private Context context; private Icon icon; private TextPaint paint; private int size = -1; private int alpha = 255; /** * Create an IconDrawable. * @param context Your activity or application context. * @param iconKey The icon key you want this drawable to display. * @throws IllegalArgumentException if the key doesn't match any icon. */ public IconDrawable(Context context, String iconKey) { Icon icon = Iconify.findIconForKey(iconKey); if (icon == null) { throw new IllegalArgumentException("No icon with that key \"" + iconKey + "\"."); } init(context, icon); } /** * Create an IconDrawable. * @param context Your activity or application context. * @param icon The icon you want this drawable to display. */ public IconDrawable(Context context, Icon icon) { init(context, icon); } private void init(Context context, Icon icon) { this.context = context; this.icon = icon; paint = new TextPaint();
// Path: app/src/main/java/com/joanzapata/iconify/internal/IconFontDescriptorWrapper.java // public class IconFontDescriptorWrapper { // // private final IconFontDescriptor iconFontDescriptor; // // private final Map<String, Icon> iconsByKey; // // private Typeface cachedTypeface; // // public IconFontDescriptorWrapper(IconFontDescriptor iconFontDescriptor) { // this.iconFontDescriptor = iconFontDescriptor; // iconsByKey = new HashMap<String, Icon>(); // Icon[] characters = iconFontDescriptor.characters(); // for (int i = 0, charactersLength = characters.length; i < charactersLength; i++) { // Icon icon = characters[i]; // iconsByKey.put(icon.key(), icon); // } // } // // public Icon getIcon(String key) { // return iconsByKey.get(key); // } // // public IconFontDescriptor getIconFontDescriptor() { // return iconFontDescriptor; // } // // public Typeface getTypeface(Context context) { // if (cachedTypeface != null) return cachedTypeface; // synchronized (this) { // if (cachedTypeface != null) return cachedTypeface; // cachedTypeface = Typeface.createFromAsset(context.getAssets(), iconFontDescriptor.ttfFileName()); // return cachedTypeface; // } // } // // public boolean hasIcon(Icon icon) { // return iconsByKey.values().contains(icon); // } // } // Path: app/src/main/java/com/joanzapata/iconify/IconDrawable.java import android.content.Context; import android.graphics.*; import android.graphics.drawable.Drawable; import android.text.TextPaint; import android.util.TypedValue; import com.joanzapata.iconify.internal.IconFontDescriptorWrapper; import static android.util.TypedValue.COMPLEX_UNIT_DIP; package com.joanzapata.iconify; /** * Embed an icon into a Drawable that can be used as TextView icons, or ActionBar icons. * <pre> * new IconDrawable(context, IconValue.icon_star) * .colorRes(R.color.white) * .actionBarSize(); * </pre> * If you don't set the size of the drawable, it will use the size * that is given to him. Note that in an ActionBar, if you don't * set the size explicitly it uses 0, so please use actionBarSize(). */ public class IconDrawable extends Drawable { public static final int ANDROID_ACTIONBAR_ICON_SIZE_DP = 24; private Context context; private Icon icon; private TextPaint paint; private int size = -1; private int alpha = 255; /** * Create an IconDrawable. * @param context Your activity or application context. * @param iconKey The icon key you want this drawable to display. * @throws IllegalArgumentException if the key doesn't match any icon. */ public IconDrawable(Context context, String iconKey) { Icon icon = Iconify.findIconForKey(iconKey); if (icon == null) { throw new IllegalArgumentException("No icon with that key \"" + iconKey + "\"."); } init(context, icon); } /** * Create an IconDrawable. * @param context Your activity or application context. * @param icon The icon you want this drawable to display. */ public IconDrawable(Context context, Icon icon) { init(context, icon); } private void init(Context context, Icon icon) { this.context = context; this.icon = icon; paint = new TextPaint();
IconFontDescriptorWrapper descriptor = Iconify.findTypefaceOf(icon);
zeevy/grblcontroller
app/src/main/java/com/joanzapata/iconify/internal/CustomTypefaceSpan.java
// Path: app/src/main/java/com/joanzapata/iconify/Icon.java // public interface Icon { // // /** The key of icon, for example 'fa-ok' */ // String key(); // // /** The character matching the key in the font, for example '\u4354' */ // char character(); // // }
import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Typeface; import android.text.style.ReplacementSpan; import com.joanzapata.iconify.Icon;
package com.joanzapata.iconify.internal; public class CustomTypefaceSpan extends ReplacementSpan { private static final int ROTATION_DURATION = 2000; private static final Rect TEXT_BOUNDS = new Rect(); private static final Paint LOCAL_PAINT = new Paint(); private static final float BASELINE_RATIO = 1 / 7f; private final String icon; private final Typeface type; private final float iconSizePx; private final float iconSizeRatio; private final int iconColor; private final boolean rotate; private final boolean baselineAligned; private final long rotationStartTime;
// Path: app/src/main/java/com/joanzapata/iconify/Icon.java // public interface Icon { // // /** The key of icon, for example 'fa-ok' */ // String key(); // // /** The character matching the key in the font, for example '\u4354' */ // char character(); // // } // Path: app/src/main/java/com/joanzapata/iconify/internal/CustomTypefaceSpan.java import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Typeface; import android.text.style.ReplacementSpan; import com.joanzapata.iconify.Icon; package com.joanzapata.iconify.internal; public class CustomTypefaceSpan extends ReplacementSpan { private static final int ROTATION_DURATION = 2000; private static final Rect TEXT_BOUNDS = new Rect(); private static final Paint LOCAL_PAINT = new Paint(); private static final float BASELINE_RATIO = 1 / 7f; private final String icon; private final Typeface type; private final float iconSizePx; private final float iconSizeRatio; private final int iconColor; private final boolean rotate; private final boolean baselineAligned; private final long rotationStartTime;
public CustomTypefaceSpan(Icon icon, Typeface type,
zeevy/grblcontroller
app/src/main/java/in/co/gorest/grblcontroller/listeners/MachineStatusListener.java
// Path: app/src/main/java/in/co/gorest/grblcontroller/model/Constants.java // public interface Constants { // // double MIN_SUPPORTED_VERSION = 1.1; // // long GRBL_STATUS_UPDATE_INTERVAL = 150; // String USB_BAUD_RATE = "115200"; // // // Message types sent from the BluetoothService Handler // int MESSAGE_STATE_CHANGE = 1; // int MESSAGE_READ = 2; // int MESSAGE_WRITE = 3; // int MESSAGE_DEVICE_NAME = 4; // int MESSAGE_TOAST = 5; // int REQUEST_READ_PERMISSIONS = 6; // int PROBE_TYPE_NORMAL = 7; // int PROBE_TYPE_TOOL_OFFSET = 8; // int CONNECT_DEVICE_SECURE = 9; // int CONNECT_DEVICE_INSECURE = 10; // int FILE_PICKER_REQUEST_CODE = 11; // // int CONSOLE_LOGGER_MAX_SIZE = 256; // double DEFAULT_JOGGING_FEED_RATE = 2400.0; // int DEFAULT_PLANNER_BUFFER = 15; // int DEFAULT_SERIAL_RX_BUFFER = 128; // int PROBING_FEED_RATE = 50; // int PROBING_PLATE_THICKNESS = 20; // int PROBING_DISTANCE = 15; // // String MACHINE_STATUS_IDLE = "Idle"; // String MACHINE_STATUS_JOG = "Jog"; // String MACHINE_STATUS_RUN = "Run"; // String MACHINE_STATUS_HOLD = "Hold"; // String MACHINE_STATUS_ALARM = "Alarm"; // String MACHINE_STATUS_CHECK = "Check"; // String MACHINE_STATUS_SLEEP = "Sleep"; // String MACHINE_STATUS_DOOR = "Door"; // String MACHINE_STATUS_HOME = "Home"; // String MACHINE_STATUS_NOT_CONNECTED = "Unknown"; // // String[] SUPPORTED_FILE_TYPES = {".tap",".gcode", ".nc", ".ngc", ".fnc", ".txt"}; // String SUPPORTED_FILE_TYPES_STRING = "^.*\\.(tap|gcode|nc|ngc|cnc|txt|ncc|fnc|dnc|fan|gc|txt|ncg|ncp|fgc)$"; // // String JUST_STOP_STREAMING = "0"; // String STOP_STREAMING_AND_RESET = "1"; // String DEVICE_NAME = "device_name"; // String TOAST = "toast"; // // String SERIAL_CONNECTION_TYPE_BLUETOOTH = "bluetooth"; // String SERIAL_CONNECTION_TYPE_USB_OTG = "usbotg"; // // int BLUETOOTH_SERVICE_NOTIFICATION_ID = 100; // int FILE_STREAMING_NOTIFICATION_ID = 101; // int USB_OTG_SERVICE_NOTIFICATION_ID = 102; // // String TEXT_CATEGORY_UPDATE = "update"; // String TEXT_CATEGORY_LINK = "link"; // String TEXT_CATEGORY_PROMOTION = "promotion"; // // } // // Path: app/src/main/java/in/co/gorest/grblcontroller/model/Position.java // public class Position { // private final Double cordX; // private final Double cordY; // private final Double cordZ; // // // private static final NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.ENGLISH); // private static final DecimalFormat decimalFormat = (DecimalFormat) numberFormat; // // public Position(double x, double y, double z){ // this.cordX = x; this.cordY = y; this.cordZ = z; // decimalFormat.applyPattern("#0.###"); // } // // public Double getCordX(){ return this.cordX; } // public Double getCordY(){ return this.cordY; } // public Double getCordZ(){ return this.cordZ; } // // private Double roundDouble(Double value){ // String s = decimalFormat.format(value); // return Double.parseDouble(s); // } // // public boolean hasChanged(Position position){ // return (position.getCordX().compareTo(this.cordX) != 0) || (position.getCordY().compareTo(this.cordY) != 0) || (position.getCordZ().compareTo(this.cordZ) != 0); // } // // public boolean atZero(){ // return Math.abs(this.cordX) == 0 && Math.abs(this.cordY) == 0 && Math.abs(this.cordZ) == 0; // } // // }
import androidx.databinding.BaseObservable; import androidx.databinding.Bindable; import in.co.gorest.grblcontroller.BR; import in.co.gorest.grblcontroller.model.Constants; import in.co.gorest.grblcontroller.model.Position;
/* * /** * * Copyright (C) 2017 Grbl Controller Contributors * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along * * with this program; if not, write to the Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * <http://www.gnu.org/licenses/> * */ package in.co.gorest.grblcontroller.listeners; public class MachineStatusListener extends BaseObservable { private static final String TAG = MachineStatusListener.class.getSimpleName(); private final String emptyString = "";
// Path: app/src/main/java/in/co/gorest/grblcontroller/model/Constants.java // public interface Constants { // // double MIN_SUPPORTED_VERSION = 1.1; // // long GRBL_STATUS_UPDATE_INTERVAL = 150; // String USB_BAUD_RATE = "115200"; // // // Message types sent from the BluetoothService Handler // int MESSAGE_STATE_CHANGE = 1; // int MESSAGE_READ = 2; // int MESSAGE_WRITE = 3; // int MESSAGE_DEVICE_NAME = 4; // int MESSAGE_TOAST = 5; // int REQUEST_READ_PERMISSIONS = 6; // int PROBE_TYPE_NORMAL = 7; // int PROBE_TYPE_TOOL_OFFSET = 8; // int CONNECT_DEVICE_SECURE = 9; // int CONNECT_DEVICE_INSECURE = 10; // int FILE_PICKER_REQUEST_CODE = 11; // // int CONSOLE_LOGGER_MAX_SIZE = 256; // double DEFAULT_JOGGING_FEED_RATE = 2400.0; // int DEFAULT_PLANNER_BUFFER = 15; // int DEFAULT_SERIAL_RX_BUFFER = 128; // int PROBING_FEED_RATE = 50; // int PROBING_PLATE_THICKNESS = 20; // int PROBING_DISTANCE = 15; // // String MACHINE_STATUS_IDLE = "Idle"; // String MACHINE_STATUS_JOG = "Jog"; // String MACHINE_STATUS_RUN = "Run"; // String MACHINE_STATUS_HOLD = "Hold"; // String MACHINE_STATUS_ALARM = "Alarm"; // String MACHINE_STATUS_CHECK = "Check"; // String MACHINE_STATUS_SLEEP = "Sleep"; // String MACHINE_STATUS_DOOR = "Door"; // String MACHINE_STATUS_HOME = "Home"; // String MACHINE_STATUS_NOT_CONNECTED = "Unknown"; // // String[] SUPPORTED_FILE_TYPES = {".tap",".gcode", ".nc", ".ngc", ".fnc", ".txt"}; // String SUPPORTED_FILE_TYPES_STRING = "^.*\\.(tap|gcode|nc|ngc|cnc|txt|ncc|fnc|dnc|fan|gc|txt|ncg|ncp|fgc)$"; // // String JUST_STOP_STREAMING = "0"; // String STOP_STREAMING_AND_RESET = "1"; // String DEVICE_NAME = "device_name"; // String TOAST = "toast"; // // String SERIAL_CONNECTION_TYPE_BLUETOOTH = "bluetooth"; // String SERIAL_CONNECTION_TYPE_USB_OTG = "usbotg"; // // int BLUETOOTH_SERVICE_NOTIFICATION_ID = 100; // int FILE_STREAMING_NOTIFICATION_ID = 101; // int USB_OTG_SERVICE_NOTIFICATION_ID = 102; // // String TEXT_CATEGORY_UPDATE = "update"; // String TEXT_CATEGORY_LINK = "link"; // String TEXT_CATEGORY_PROMOTION = "promotion"; // // } // // Path: app/src/main/java/in/co/gorest/grblcontroller/model/Position.java // public class Position { // private final Double cordX; // private final Double cordY; // private final Double cordZ; // // // private static final NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.ENGLISH); // private static final DecimalFormat decimalFormat = (DecimalFormat) numberFormat; // // public Position(double x, double y, double z){ // this.cordX = x; this.cordY = y; this.cordZ = z; // decimalFormat.applyPattern("#0.###"); // } // // public Double getCordX(){ return this.cordX; } // public Double getCordY(){ return this.cordY; } // public Double getCordZ(){ return this.cordZ; } // // private Double roundDouble(Double value){ // String s = decimalFormat.format(value); // return Double.parseDouble(s); // } // // public boolean hasChanged(Position position){ // return (position.getCordX().compareTo(this.cordX) != 0) || (position.getCordY().compareTo(this.cordY) != 0) || (position.getCordZ().compareTo(this.cordZ) != 0); // } // // public boolean atZero(){ // return Math.abs(this.cordX) == 0 && Math.abs(this.cordY) == 0 && Math.abs(this.cordZ) == 0; // } // // } // Path: app/src/main/java/in/co/gorest/grblcontroller/listeners/MachineStatusListener.java import androidx.databinding.BaseObservable; import androidx.databinding.Bindable; import in.co.gorest.grblcontroller.BR; import in.co.gorest.grblcontroller.model.Constants; import in.co.gorest.grblcontroller.model.Position; /* * /** * * Copyright (C) 2017 Grbl Controller Contributors * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along * * with this program; if not, write to the Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * <http://www.gnu.org/licenses/> * */ package in.co.gorest.grblcontroller.listeners; public class MachineStatusListener extends BaseObservable { private static final String TAG = MachineStatusListener.class.getSimpleName(); private final String emptyString = "";
private final Double DEFAULT_FEED_RATE = Constants.DEFAULT_JOGGING_FEED_RATE;
zeevy/grblcontroller
app/src/main/java/com/joanzapata/iconify/fonts/FontAwesomeModule.java
// Path: app/src/main/java/com/joanzapata/iconify/Icon.java // public interface Icon { // // /** The key of icon, for example 'fa-ok' */ // String key(); // // /** The character matching the key in the font, for example '\u4354' */ // char character(); // // } // // Path: app/src/main/java/com/joanzapata/iconify/IconFontDescriptor.java // public interface IconFontDescriptor { // // /** // * The TTF file name. // * @return a name with no slash, present in the assets. // */ // String ttfFileName(); // // Icon[] characters(); // // }
import com.joanzapata.iconify.Icon; import com.joanzapata.iconify.IconFontDescriptor;
package com.joanzapata.iconify.fonts; public class FontAwesomeModule implements IconFontDescriptor { @Override public String ttfFileName() { return "iconify/android-iconify-fontawesome.ttf"; } @Override
// Path: app/src/main/java/com/joanzapata/iconify/Icon.java // public interface Icon { // // /** The key of icon, for example 'fa-ok' */ // String key(); // // /** The character matching the key in the font, for example '\u4354' */ // char character(); // // } // // Path: app/src/main/java/com/joanzapata/iconify/IconFontDescriptor.java // public interface IconFontDescriptor { // // /** // * The TTF file name. // * @return a name with no slash, present in the assets. // */ // String ttfFileName(); // // Icon[] characters(); // // } // Path: app/src/main/java/com/joanzapata/iconify/fonts/FontAwesomeModule.java import com.joanzapata.iconify.Icon; import com.joanzapata.iconify.IconFontDescriptor; package com.joanzapata.iconify.fonts; public class FontAwesomeModule implements IconFontDescriptor { @Override public String ttfFileName() { return "iconify/android-iconify-fontawesome.ttf"; } @Override
public Icon[] characters() {
zeevy/grblcontroller
app/src/main/java/in/co/gorest/grblcontroller/GrblController.java
// Path: app/src/main/java/com/joanzapata/iconify/Iconify.java // public class Iconify { // // /** List of icon font descriptors */ // private static List<IconFontDescriptorWrapper> iconFontDescriptors = new ArrayList<IconFontDescriptorWrapper>(); // // /** // * Add support for a new icon font. // * @param iconFontDescriptor The IconDescriptor holding the ttf file reference and its mappings. // * @return An initializer instance for chain calls. // */ // public static IconifyInitializer with(IconFontDescriptor iconFontDescriptor) { // return new IconifyInitializer(iconFontDescriptor); // } // // /** // * Replace "{}" tags in the given text views with actual icons, requesting the IconFontDescriptors // * one after the others.<p> // * <strong>This is a one time call.</strong> If you call {@link TextView#setText(CharSequence)} after this, // * you'll need to call it again. // * @param textViews The TextView(s) to enhance. // */ // public static void addIcons(TextView... textViews) { // for (TextView textView : textViews) { // if (textView == null) continue; // textView.setText(compute(textView.getContext(), textView.getText(), textView)); // } // } // // private static void addIconFontDescriptor(IconFontDescriptor iconFontDescriptor) { // // // Prevent duplicates // for (IconFontDescriptorWrapper wrapper : iconFontDescriptors) { // if (wrapper.getIconFontDescriptor().ttfFileName() // .equals(iconFontDescriptor.ttfFileName())) { // return; // } // } // // // Add to the list // iconFontDescriptors.add(new IconFontDescriptorWrapper(iconFontDescriptor)); // // } // // public static CharSequence compute(Context context, CharSequence text) { // return compute(context, text, null); // } // // public static CharSequence compute(Context context, CharSequence text, TextView target) { // return ParsingUtil.parse(context, iconFontDescriptors, text, target); // } // // /** // * Allows chain calls on {@link Iconify#with(IconFontDescriptor)}. // */ // public static class IconifyInitializer { // // public IconifyInitializer(IconFontDescriptor iconFontDescriptor) { // Iconify.addIconFontDescriptor(iconFontDescriptor); // } // // /** // * Add support for a new icon font. // * @param iconFontDescriptor The IconDescriptor holding the ttf file reference and its mappings. // * @return An initializer instance for chain calls. // */ // public IconifyInitializer with(IconFontDescriptor iconFontDescriptor) { // Iconify.addIconFontDescriptor(iconFontDescriptor); // return this; // } // } // // /** // * Finds the Typeface to apply for a given icon. // * @param icon The icon for which you need the typeface. // * @return The font descriptor which contains info about the typeface to apply, or null // * if the icon cannot be found. In that case, check that you properly added the modules // * using {@link #with(IconFontDescriptor)}} prior to calling this method. // */ // public static IconFontDescriptorWrapper findTypefaceOf(Icon icon) { // for (IconFontDescriptorWrapper iconFontDescriptor : iconFontDescriptors) { // if (iconFontDescriptor.hasIcon(icon)) { // return iconFontDescriptor; // } // } // return null; // } // // // /** // * Retrieve an icon from a key, // * @return The icon, or null if no icon matches the key. // */ // public static Icon findIconForKey(String iconKey) { // for (int i = 0, iconFontDescriptorsSize = iconFontDescriptors.size(); i < iconFontDescriptorsSize; i++) { // IconFontDescriptorWrapper iconFontDescriptor = iconFontDescriptors.get(i); // Icon icon = iconFontDescriptor.getIcon(iconKey); // if (icon != null) return icon; // } // return null; // } // } // // Path: app/src/main/java/com/joanzapata/iconify/fonts/FontAwesomeModule.java // public class FontAwesomeModule implements IconFontDescriptor { // // @Override // public String ttfFileName() { // return "iconify/android-iconify-fontawesome.ttf"; // } // // @Override // public Icon[] characters() { // return FontAwesomeIcons.values(); // } // } // // Path: app/src/main/java/in/co/gorest/grblcontroller/network/GoRestService.java // public interface GoRestService { // // // @POST("/fcm-registration.html") // Call<JsonObject> postFcmToken(@Body FcmToken fcmToken); // // // // }
import androidx.appcompat.app.AppCompatDelegate; import com.joanzapata.iconify.Iconify; import com.joanzapata.iconify.fonts.FontAwesomeModule; import com.orm.SugarApp; import in.co.gorest.grblcontroller.network.GoRestService; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory;
/* * /** * * Copyright (C) 2017 Grbl Controller Contributors * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along * * with this program; if not, write to the Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * <http://www.gnu.org/licenses/> * */ package in.co.gorest.grblcontroller; public class GrblController extends SugarApp { private final String TAG = GrblController.class.getSimpleName(); private static GrblController grblController;
// Path: app/src/main/java/com/joanzapata/iconify/Iconify.java // public class Iconify { // // /** List of icon font descriptors */ // private static List<IconFontDescriptorWrapper> iconFontDescriptors = new ArrayList<IconFontDescriptorWrapper>(); // // /** // * Add support for a new icon font. // * @param iconFontDescriptor The IconDescriptor holding the ttf file reference and its mappings. // * @return An initializer instance for chain calls. // */ // public static IconifyInitializer with(IconFontDescriptor iconFontDescriptor) { // return new IconifyInitializer(iconFontDescriptor); // } // // /** // * Replace "{}" tags in the given text views with actual icons, requesting the IconFontDescriptors // * one after the others.<p> // * <strong>This is a one time call.</strong> If you call {@link TextView#setText(CharSequence)} after this, // * you'll need to call it again. // * @param textViews The TextView(s) to enhance. // */ // public static void addIcons(TextView... textViews) { // for (TextView textView : textViews) { // if (textView == null) continue; // textView.setText(compute(textView.getContext(), textView.getText(), textView)); // } // } // // private static void addIconFontDescriptor(IconFontDescriptor iconFontDescriptor) { // // // Prevent duplicates // for (IconFontDescriptorWrapper wrapper : iconFontDescriptors) { // if (wrapper.getIconFontDescriptor().ttfFileName() // .equals(iconFontDescriptor.ttfFileName())) { // return; // } // } // // // Add to the list // iconFontDescriptors.add(new IconFontDescriptorWrapper(iconFontDescriptor)); // // } // // public static CharSequence compute(Context context, CharSequence text) { // return compute(context, text, null); // } // // public static CharSequence compute(Context context, CharSequence text, TextView target) { // return ParsingUtil.parse(context, iconFontDescriptors, text, target); // } // // /** // * Allows chain calls on {@link Iconify#with(IconFontDescriptor)}. // */ // public static class IconifyInitializer { // // public IconifyInitializer(IconFontDescriptor iconFontDescriptor) { // Iconify.addIconFontDescriptor(iconFontDescriptor); // } // // /** // * Add support for a new icon font. // * @param iconFontDescriptor The IconDescriptor holding the ttf file reference and its mappings. // * @return An initializer instance for chain calls. // */ // public IconifyInitializer with(IconFontDescriptor iconFontDescriptor) { // Iconify.addIconFontDescriptor(iconFontDescriptor); // return this; // } // } // // /** // * Finds the Typeface to apply for a given icon. // * @param icon The icon for which you need the typeface. // * @return The font descriptor which contains info about the typeface to apply, or null // * if the icon cannot be found. In that case, check that you properly added the modules // * using {@link #with(IconFontDescriptor)}} prior to calling this method. // */ // public static IconFontDescriptorWrapper findTypefaceOf(Icon icon) { // for (IconFontDescriptorWrapper iconFontDescriptor : iconFontDescriptors) { // if (iconFontDescriptor.hasIcon(icon)) { // return iconFontDescriptor; // } // } // return null; // } // // // /** // * Retrieve an icon from a key, // * @return The icon, or null if no icon matches the key. // */ // public static Icon findIconForKey(String iconKey) { // for (int i = 0, iconFontDescriptorsSize = iconFontDescriptors.size(); i < iconFontDescriptorsSize; i++) { // IconFontDescriptorWrapper iconFontDescriptor = iconFontDescriptors.get(i); // Icon icon = iconFontDescriptor.getIcon(iconKey); // if (icon != null) return icon; // } // return null; // } // } // // Path: app/src/main/java/com/joanzapata/iconify/fonts/FontAwesomeModule.java // public class FontAwesomeModule implements IconFontDescriptor { // // @Override // public String ttfFileName() { // return "iconify/android-iconify-fontawesome.ttf"; // } // // @Override // public Icon[] characters() { // return FontAwesomeIcons.values(); // } // } // // Path: app/src/main/java/in/co/gorest/grblcontroller/network/GoRestService.java // public interface GoRestService { // // // @POST("/fcm-registration.html") // Call<JsonObject> postFcmToken(@Body FcmToken fcmToken); // // // // } // Path: app/src/main/java/in/co/gorest/grblcontroller/GrblController.java import androidx.appcompat.app.AppCompatDelegate; import com.joanzapata.iconify.Iconify; import com.joanzapata.iconify.fonts.FontAwesomeModule; import com.orm.SugarApp; import in.co.gorest.grblcontroller.network.GoRestService; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; /* * /** * * Copyright (C) 2017 Grbl Controller Contributors * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along * * with this program; if not, write to the Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * <http://www.gnu.org/licenses/> * */ package in.co.gorest.grblcontroller; public class GrblController extends SugarApp { private final String TAG = GrblController.class.getSimpleName(); private static GrblController grblController;
private GoRestService goRestService;
zeevy/grblcontroller
app/src/main/java/in/co/gorest/grblcontroller/util/GrblUtils.java
// Path: app/src/main/java/in/co/gorest/grblcontroller/listeners/MachineStatusListener.java // public static class CompileTimeOptions{ // // public final boolean variableSpindle; // public final boolean lineNumbers; // public final boolean mistCoolant; // public final boolean coreXY; // public final boolean parkingMotion; // public final boolean homingForceOrigin; // public final boolean homingSingleAxis; // public final boolean twoLimitSwitchesOnAxis; // public final boolean feedRageOverrideInProbeCycles; // public final boolean restoreAllRom; // public final boolean restoreRomSettings; // public final boolean restoreRomParameterData; // public final boolean writeUserString; // public final boolean forceSyncOnRomWrite; // public final boolean forceSyncOnCoordinateChange; // public final boolean homingInitLock; // public final int plannerBuffer; // public final int serialRxBuffer; // // public CompileTimeOptions(String enabled, int plannerBf, int serialRxBf){ // String enabledUpper = enabled.toUpperCase(); // // variableSpindle = enabledUpper.contains("V"); // lineNumbers = enabledUpper.contains("N"); // mistCoolant = enabledUpper.contains("M"); // coreXY = enabledUpper.contains("C"); // parkingMotion = enabledUpper.contains("P"); // homingForceOrigin = enabledUpper.contains("Z"); // homingSingleAxis = enabledUpper.contains("H"); // twoLimitSwitchesOnAxis = enabledUpper.contains("T"); // feedRageOverrideInProbeCycles = enabledUpper.contains("A"); // restoreAllRom = enabledUpper.contains("*"); // restoreRomSettings = enabledUpper.contains("$"); // restoreRomParameterData = enabledUpper.contains("#"); // writeUserString = enabledUpper.contains("I"); // forceSyncOnRomWrite = enabledUpper.contains("E"); // forceSyncOnCoordinateChange = enabledUpper.contains("W"); // homingInitLock = enabledUpper.contains("L"); // plannerBuffer = plannerBf; // serialRxBuffer = serialRxBf; // } // // } // // Path: app/src/main/java/in/co/gorest/grblcontroller/model/Overrides.java // public enum Overrides { // CMD_FEED_OVR_RESET, // 0x90 // CMD_FEED_OVR_COARSE_PLUS, // 0x91 // CMD_FEED_OVR_COARSE_MINUS, // 0x92 // CMD_FEED_OVR_FINE_PLUS , // 0x93 // CMD_FEED_OVR_FINE_MINUS , // 0x94 // CMD_RAPID_OVR_RESET, // 0x95 // CMD_RAPID_OVR_MEDIUM, // 0x96 // CMD_RAPID_OVR_LOW, // 0x97 // CMD_SPINDLE_OVR_RESET, // 0x99 // CMD_SPINDLE_OVR_COARSE_PLUS, // 0x9A // CMD_SPINDLE_OVR_COARSE_MINUS, // 0x9B // CMD_SPINDLE_OVR_FINE_PLUS, // 0x9C // CMD_SPINDLE_OVR_FINE_MINUS, // 0x9D // CMD_TOGGLE_SPINDLE, // 0x9E // CMD_TOGGLE_FLOOD_COOLANT, // 0xA0 // CMD_TOGGLE_MIST_COOLANT, // 0xA1 // } // // Path: app/src/main/java/in/co/gorest/grblcontroller/model/Position.java // public class Position { // private final Double cordX; // private final Double cordY; // private final Double cordZ; // // // private static final NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.ENGLISH); // private static final DecimalFormat decimalFormat = (DecimalFormat) numberFormat; // // public Position(double x, double y, double z){ // this.cordX = x; this.cordY = y; this.cordZ = z; // decimalFormat.applyPattern("#0.###"); // } // // public Double getCordX(){ return this.cordX; } // public Double getCordY(){ return this.cordY; } // public Double getCordZ(){ return this.cordZ; } // // private Double roundDouble(Double value){ // String s = decimalFormat.format(value); // return Double.parseDouble(s); // } // // public boolean hasChanged(Position position){ // return (position.getCordX().compareTo(this.cordX) != 0) || (position.getCordY().compareTo(this.cordY) != 0) || (position.getCordZ().compareTo(this.cordZ) != 0); // } // // public boolean atZero(){ // return Math.abs(this.cordX) == 0 && Math.abs(this.cordY) == 0 && Math.abs(this.cordZ) == 0; // } // // }
import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; import in.co.gorest.grblcontroller.listeners.MachineStatusListener.CompileTimeOptions; import in.co.gorest.grblcontroller.model.Overrides; import in.co.gorest.grblcontroller.model.Position;
String[] parts = buildOptions.split(","); if (parts.length >= 3) { int tmpPBuffer = Integer.parseInt(parts[1]); if (tmpPBuffer > 0) plannerBuffer = tmpPBuffer; int tmpRxBuffer = Integer.parseInt(parts[2]); if (tmpRxBuffer > 0) serialRxBuffer = tmpRxBuffer; } } return new CompileTimeOptions(buildOptions, plannerBuffer, serialRxBuffer); } private final static String EEPROM_COMMAND_PATTERN = "G10|G28|G30|\\$x=|\\$I|\\$N|\\$RST=|G5[456789]|\\$\\$|\\$#"; private final static Pattern EEPROM_COMMAND = Pattern.compile(EEPROM_COMMAND_PATTERN, Pattern.CASE_INSENSITIVE); public static boolean hasRomAccess(String command){ return EEPROM_COMMAND.matcher(command).find(); } public static String implode(String glue, String[] array) { if(array == null || array.length == 0) return ""; StringBuilder sb = new StringBuilder(); sb.append(array[0]); for(int i = 1; i < array.length; i++) sb.append(glue).append(array[i]); return sb.toString(); }
// Path: app/src/main/java/in/co/gorest/grblcontroller/listeners/MachineStatusListener.java // public static class CompileTimeOptions{ // // public final boolean variableSpindle; // public final boolean lineNumbers; // public final boolean mistCoolant; // public final boolean coreXY; // public final boolean parkingMotion; // public final boolean homingForceOrigin; // public final boolean homingSingleAxis; // public final boolean twoLimitSwitchesOnAxis; // public final boolean feedRageOverrideInProbeCycles; // public final boolean restoreAllRom; // public final boolean restoreRomSettings; // public final boolean restoreRomParameterData; // public final boolean writeUserString; // public final boolean forceSyncOnRomWrite; // public final boolean forceSyncOnCoordinateChange; // public final boolean homingInitLock; // public final int plannerBuffer; // public final int serialRxBuffer; // // public CompileTimeOptions(String enabled, int plannerBf, int serialRxBf){ // String enabledUpper = enabled.toUpperCase(); // // variableSpindle = enabledUpper.contains("V"); // lineNumbers = enabledUpper.contains("N"); // mistCoolant = enabledUpper.contains("M"); // coreXY = enabledUpper.contains("C"); // parkingMotion = enabledUpper.contains("P"); // homingForceOrigin = enabledUpper.contains("Z"); // homingSingleAxis = enabledUpper.contains("H"); // twoLimitSwitchesOnAxis = enabledUpper.contains("T"); // feedRageOverrideInProbeCycles = enabledUpper.contains("A"); // restoreAllRom = enabledUpper.contains("*"); // restoreRomSettings = enabledUpper.contains("$"); // restoreRomParameterData = enabledUpper.contains("#"); // writeUserString = enabledUpper.contains("I"); // forceSyncOnRomWrite = enabledUpper.contains("E"); // forceSyncOnCoordinateChange = enabledUpper.contains("W"); // homingInitLock = enabledUpper.contains("L"); // plannerBuffer = plannerBf; // serialRxBuffer = serialRxBf; // } // // } // // Path: app/src/main/java/in/co/gorest/grblcontroller/model/Overrides.java // public enum Overrides { // CMD_FEED_OVR_RESET, // 0x90 // CMD_FEED_OVR_COARSE_PLUS, // 0x91 // CMD_FEED_OVR_COARSE_MINUS, // 0x92 // CMD_FEED_OVR_FINE_PLUS , // 0x93 // CMD_FEED_OVR_FINE_MINUS , // 0x94 // CMD_RAPID_OVR_RESET, // 0x95 // CMD_RAPID_OVR_MEDIUM, // 0x96 // CMD_RAPID_OVR_LOW, // 0x97 // CMD_SPINDLE_OVR_RESET, // 0x99 // CMD_SPINDLE_OVR_COARSE_PLUS, // 0x9A // CMD_SPINDLE_OVR_COARSE_MINUS, // 0x9B // CMD_SPINDLE_OVR_FINE_PLUS, // 0x9C // CMD_SPINDLE_OVR_FINE_MINUS, // 0x9D // CMD_TOGGLE_SPINDLE, // 0x9E // CMD_TOGGLE_FLOOD_COOLANT, // 0xA0 // CMD_TOGGLE_MIST_COOLANT, // 0xA1 // } // // Path: app/src/main/java/in/co/gorest/grblcontroller/model/Position.java // public class Position { // private final Double cordX; // private final Double cordY; // private final Double cordZ; // // // private static final NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.ENGLISH); // private static final DecimalFormat decimalFormat = (DecimalFormat) numberFormat; // // public Position(double x, double y, double z){ // this.cordX = x; this.cordY = y; this.cordZ = z; // decimalFormat.applyPattern("#0.###"); // } // // public Double getCordX(){ return this.cordX; } // public Double getCordY(){ return this.cordY; } // public Double getCordZ(){ return this.cordZ; } // // private Double roundDouble(Double value){ // String s = decimalFormat.format(value); // return Double.parseDouble(s); // } // // public boolean hasChanged(Position position){ // return (position.getCordX().compareTo(this.cordX) != 0) || (position.getCordY().compareTo(this.cordY) != 0) || (position.getCordZ().compareTo(this.cordZ) != 0); // } // // public boolean atZero(){ // return Math.abs(this.cordX) == 0 && Math.abs(this.cordY) == 0 && Math.abs(this.cordZ) == 0; // } // // } // Path: app/src/main/java/in/co/gorest/grblcontroller/util/GrblUtils.java import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; import in.co.gorest.grblcontroller.listeners.MachineStatusListener.CompileTimeOptions; import in.co.gorest.grblcontroller.model.Overrides; import in.co.gorest.grblcontroller.model.Position; String[] parts = buildOptions.split(","); if (parts.length >= 3) { int tmpPBuffer = Integer.parseInt(parts[1]); if (tmpPBuffer > 0) plannerBuffer = tmpPBuffer; int tmpRxBuffer = Integer.parseInt(parts[2]); if (tmpRxBuffer > 0) serialRxBuffer = tmpRxBuffer; } } return new CompileTimeOptions(buildOptions, plannerBuffer, serialRxBuffer); } private final static String EEPROM_COMMAND_PATTERN = "G10|G28|G30|\\$x=|\\$I|\\$N|\\$RST=|G5[456789]|\\$\\$|\\$#"; private final static Pattern EEPROM_COMMAND = Pattern.compile(EEPROM_COMMAND_PATTERN, Pattern.CASE_INSENSITIVE); public static boolean hasRomAccess(String command){ return EEPROM_COMMAND.matcher(command).find(); } public static String implode(String glue, String[] array) { if(array == null || array.length == 0) return ""; StringBuilder sb = new StringBuilder(); sb.append(array[0]); for(int i = 1; i < array.length; i++) sb.append(glue).append(array[i]); return sb.toString(); }
static public Byte getOverrideForEnum(final Overrides command) {
zeevy/grblcontroller
app/src/main/java/in/co/gorest/grblcontroller/listeners/ConsoleLoggerListener.java
// Path: app/src/main/java/in/co/gorest/grblcontroller/model/Constants.java // public interface Constants { // // double MIN_SUPPORTED_VERSION = 1.1; // // long GRBL_STATUS_UPDATE_INTERVAL = 150; // String USB_BAUD_RATE = "115200"; // // // Message types sent from the BluetoothService Handler // int MESSAGE_STATE_CHANGE = 1; // int MESSAGE_READ = 2; // int MESSAGE_WRITE = 3; // int MESSAGE_DEVICE_NAME = 4; // int MESSAGE_TOAST = 5; // int REQUEST_READ_PERMISSIONS = 6; // int PROBE_TYPE_NORMAL = 7; // int PROBE_TYPE_TOOL_OFFSET = 8; // int CONNECT_DEVICE_SECURE = 9; // int CONNECT_DEVICE_INSECURE = 10; // int FILE_PICKER_REQUEST_CODE = 11; // // int CONSOLE_LOGGER_MAX_SIZE = 256; // double DEFAULT_JOGGING_FEED_RATE = 2400.0; // int DEFAULT_PLANNER_BUFFER = 15; // int DEFAULT_SERIAL_RX_BUFFER = 128; // int PROBING_FEED_RATE = 50; // int PROBING_PLATE_THICKNESS = 20; // int PROBING_DISTANCE = 15; // // String MACHINE_STATUS_IDLE = "Idle"; // String MACHINE_STATUS_JOG = "Jog"; // String MACHINE_STATUS_RUN = "Run"; // String MACHINE_STATUS_HOLD = "Hold"; // String MACHINE_STATUS_ALARM = "Alarm"; // String MACHINE_STATUS_CHECK = "Check"; // String MACHINE_STATUS_SLEEP = "Sleep"; // String MACHINE_STATUS_DOOR = "Door"; // String MACHINE_STATUS_HOME = "Home"; // String MACHINE_STATUS_NOT_CONNECTED = "Unknown"; // // String[] SUPPORTED_FILE_TYPES = {".tap",".gcode", ".nc", ".ngc", ".fnc", ".txt"}; // String SUPPORTED_FILE_TYPES_STRING = "^.*\\.(tap|gcode|nc|ngc|cnc|txt|ncc|fnc|dnc|fan|gc|txt|ncg|ncp|fgc)$"; // // String JUST_STOP_STREAMING = "0"; // String STOP_STREAMING_AND_RESET = "1"; // String DEVICE_NAME = "device_name"; // String TOAST = "toast"; // // String SERIAL_CONNECTION_TYPE_BLUETOOTH = "bluetooth"; // String SERIAL_CONNECTION_TYPE_USB_OTG = "usbotg"; // // int BLUETOOTH_SERVICE_NOTIFICATION_ID = 100; // int FILE_STREAMING_NOTIFICATION_ID = 101; // int USB_OTG_SERVICE_NOTIFICATION_ID = 102; // // String TEXT_CATEGORY_UPDATE = "update"; // String TEXT_CATEGORY_LINK = "link"; // String TEXT_CATEGORY_PROMOTION = "promotion"; // // }
import androidx.databinding.BaseObservable; import androidx.databinding.Bindable; import org.apache.commons.collections4.queue.CircularFifoQueue; import in.co.gorest.grblcontroller.BR; import in.co.gorest.grblcontroller.model.Constants;
/* * /** * * Copyright (C) 2017 Grbl Controller Contributors * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along * * with this program; if not, write to the Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * <http://www.gnu.org/licenses/> * */ package in.co.gorest.grblcontroller.listeners; public class ConsoleLoggerListener extends BaseObservable{ @Bindable private final CircularFifoQueue<String> loggedMessagesQueue; private String messages; private static ConsoleLoggerListener consoleLoggerListener = null; public static ConsoleLoggerListener getInstance(){ if(consoleLoggerListener == null) consoleLoggerListener = new ConsoleLoggerListener(); return consoleLoggerListener; } public static void resetClass(){ consoleLoggerListener = new ConsoleLoggerListener(); } private ConsoleLoggerListener(){
// Path: app/src/main/java/in/co/gorest/grblcontroller/model/Constants.java // public interface Constants { // // double MIN_SUPPORTED_VERSION = 1.1; // // long GRBL_STATUS_UPDATE_INTERVAL = 150; // String USB_BAUD_RATE = "115200"; // // // Message types sent from the BluetoothService Handler // int MESSAGE_STATE_CHANGE = 1; // int MESSAGE_READ = 2; // int MESSAGE_WRITE = 3; // int MESSAGE_DEVICE_NAME = 4; // int MESSAGE_TOAST = 5; // int REQUEST_READ_PERMISSIONS = 6; // int PROBE_TYPE_NORMAL = 7; // int PROBE_TYPE_TOOL_OFFSET = 8; // int CONNECT_DEVICE_SECURE = 9; // int CONNECT_DEVICE_INSECURE = 10; // int FILE_PICKER_REQUEST_CODE = 11; // // int CONSOLE_LOGGER_MAX_SIZE = 256; // double DEFAULT_JOGGING_FEED_RATE = 2400.0; // int DEFAULT_PLANNER_BUFFER = 15; // int DEFAULT_SERIAL_RX_BUFFER = 128; // int PROBING_FEED_RATE = 50; // int PROBING_PLATE_THICKNESS = 20; // int PROBING_DISTANCE = 15; // // String MACHINE_STATUS_IDLE = "Idle"; // String MACHINE_STATUS_JOG = "Jog"; // String MACHINE_STATUS_RUN = "Run"; // String MACHINE_STATUS_HOLD = "Hold"; // String MACHINE_STATUS_ALARM = "Alarm"; // String MACHINE_STATUS_CHECK = "Check"; // String MACHINE_STATUS_SLEEP = "Sleep"; // String MACHINE_STATUS_DOOR = "Door"; // String MACHINE_STATUS_HOME = "Home"; // String MACHINE_STATUS_NOT_CONNECTED = "Unknown"; // // String[] SUPPORTED_FILE_TYPES = {".tap",".gcode", ".nc", ".ngc", ".fnc", ".txt"}; // String SUPPORTED_FILE_TYPES_STRING = "^.*\\.(tap|gcode|nc|ngc|cnc|txt|ncc|fnc|dnc|fan|gc|txt|ncg|ncp|fgc)$"; // // String JUST_STOP_STREAMING = "0"; // String STOP_STREAMING_AND_RESET = "1"; // String DEVICE_NAME = "device_name"; // String TOAST = "toast"; // // String SERIAL_CONNECTION_TYPE_BLUETOOTH = "bluetooth"; // String SERIAL_CONNECTION_TYPE_USB_OTG = "usbotg"; // // int BLUETOOTH_SERVICE_NOTIFICATION_ID = 100; // int FILE_STREAMING_NOTIFICATION_ID = 101; // int USB_OTG_SERVICE_NOTIFICATION_ID = 102; // // String TEXT_CATEGORY_UPDATE = "update"; // String TEXT_CATEGORY_LINK = "link"; // String TEXT_CATEGORY_PROMOTION = "promotion"; // // } // Path: app/src/main/java/in/co/gorest/grblcontroller/listeners/ConsoleLoggerListener.java import androidx.databinding.BaseObservable; import androidx.databinding.Bindable; import org.apache.commons.collections4.queue.CircularFifoQueue; import in.co.gorest.grblcontroller.BR; import in.co.gorest.grblcontroller.model.Constants; /* * /** * * Copyright (C) 2017 Grbl Controller Contributors * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along * * with this program; if not, write to the Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * <http://www.gnu.org/licenses/> * */ package in.co.gorest.grblcontroller.listeners; public class ConsoleLoggerListener extends BaseObservable{ @Bindable private final CircularFifoQueue<String> loggedMessagesQueue; private String messages; private static ConsoleLoggerListener consoleLoggerListener = null; public static ConsoleLoggerListener getInstance(){ if(consoleLoggerListener == null) consoleLoggerListener = new ConsoleLoggerListener(); return consoleLoggerListener; } public static void resetClass(){ consoleLoggerListener = new ConsoleLoggerListener(); } private ConsoleLoggerListener(){
this.loggedMessagesQueue = new CircularFifoQueue<>(Constants.CONSOLE_LOGGER_MAX_SIZE);
zeevy/grblcontroller
app/src/main/java/in/co/gorest/grblcontroller/events/GrblAlarmEvent.java
// Path: app/src/main/java/in/co/gorest/grblcontroller/GrblController.java // public class GrblController extends SugarApp { // // private final String TAG = GrblController.class.getSimpleName(); // private static GrblController grblController; // private GoRestService goRestService; // // @Override // public void onCreate() { // super.onCreate(); // // configureCrashReporting(); // // grblController = this; // // // Picasso.Builder builder = new Picasso.Builder(this); // // builder.downloader(new OkHttp3Downloader(this, Integer.MAX_VALUE)); // // Picasso picasso = builder.build(); // // picasso.setIndicatorsEnabled(BuildConfig.DEBUG); // // picasso.setLoggingEnabled(BuildConfig.DEBUG); // // Picasso.setSingletonInstance(picasso); // // AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); // Iconify.with(new FontAwesomeModule()); // } // // public static synchronized GrblController getInstance(){ // return grblController; // } // // private void configureCrashReporting(){ // // } // // public GoRestService getRetrofit(){ // if(goRestService == null){ // Retrofit retrofit = new Retrofit.Builder() // .baseUrl("https://gorest.co.in") // .addConverterFactory(GsonConverterFactory.create()) // .build(); // // goRestService = retrofit.create(GoRestService.class); // } // // return goRestService; // } // // } // // Path: app/src/main/java/in/co/gorest/grblcontroller/util/GrblLookups.java // public class GrblLookups { // // private final HashMap<String,String[]> lookups = new HashMap<>(); // // public GrblLookups(Context context, String prefix) { // String filename = prefix + ".csv"; // // try { // try (BufferedReader br = new BufferedReader( // new InputStreamReader(context.getAssets().open(filename)))) { // String line; // while ((line = br.readLine()) != null) { // String[] parts = line.split(","); // lookups.put(parts[0], parts); // } // } // } catch (IOException ex) { // System.out.println("Unable to load GRBL resources."); // ex.printStackTrace(); // } // } // // public String[] lookup(String idx){ // return lookups.get(idx); // } // // }
import in.co.gorest.grblcontroller.GrblController; import in.co.gorest.grblcontroller.R; import in.co.gorest.grblcontroller.util.GrblLookups;
/* * /** * * Copyright (C) 2017 Grbl Controller Contributors * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along * * with this program; if not, write to the Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * <http://www.gnu.org/licenses/> * */ package in.co.gorest.grblcontroller.events; public class GrblAlarmEvent { private final String message; private int alarmCode; private String alarmName; private String alarmDescription;
// Path: app/src/main/java/in/co/gorest/grblcontroller/GrblController.java // public class GrblController extends SugarApp { // // private final String TAG = GrblController.class.getSimpleName(); // private static GrblController grblController; // private GoRestService goRestService; // // @Override // public void onCreate() { // super.onCreate(); // // configureCrashReporting(); // // grblController = this; // // // Picasso.Builder builder = new Picasso.Builder(this); // // builder.downloader(new OkHttp3Downloader(this, Integer.MAX_VALUE)); // // Picasso picasso = builder.build(); // // picasso.setIndicatorsEnabled(BuildConfig.DEBUG); // // picasso.setLoggingEnabled(BuildConfig.DEBUG); // // Picasso.setSingletonInstance(picasso); // // AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); // Iconify.with(new FontAwesomeModule()); // } // // public static synchronized GrblController getInstance(){ // return grblController; // } // // private void configureCrashReporting(){ // // } // // public GoRestService getRetrofit(){ // if(goRestService == null){ // Retrofit retrofit = new Retrofit.Builder() // .baseUrl("https://gorest.co.in") // .addConverterFactory(GsonConverterFactory.create()) // .build(); // // goRestService = retrofit.create(GoRestService.class); // } // // return goRestService; // } // // } // // Path: app/src/main/java/in/co/gorest/grblcontroller/util/GrblLookups.java // public class GrblLookups { // // private final HashMap<String,String[]> lookups = new HashMap<>(); // // public GrblLookups(Context context, String prefix) { // String filename = prefix + ".csv"; // // try { // try (BufferedReader br = new BufferedReader( // new InputStreamReader(context.getAssets().open(filename)))) { // String line; // while ((line = br.readLine()) != null) { // String[] parts = line.split(","); // lookups.put(parts[0], parts); // } // } // } catch (IOException ex) { // System.out.println("Unable to load GRBL resources."); // ex.printStackTrace(); // } // } // // public String[] lookup(String idx){ // return lookups.get(idx); // } // // } // Path: app/src/main/java/in/co/gorest/grblcontroller/events/GrblAlarmEvent.java import in.co.gorest.grblcontroller.GrblController; import in.co.gorest.grblcontroller.R; import in.co.gorest.grblcontroller.util.GrblLookups; /* * /** * * Copyright (C) 2017 Grbl Controller Contributors * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along * * with this program; if not, write to the Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * <http://www.gnu.org/licenses/> * */ package in.co.gorest.grblcontroller.events; public class GrblAlarmEvent { private final String message; private int alarmCode; private String alarmName; private String alarmDescription;
public GrblAlarmEvent(GrblLookups lookups, String message){
zeevy/grblcontroller
app/src/main/java/in/co/gorest/grblcontroller/events/GrblAlarmEvent.java
// Path: app/src/main/java/in/co/gorest/grblcontroller/GrblController.java // public class GrblController extends SugarApp { // // private final String TAG = GrblController.class.getSimpleName(); // private static GrblController grblController; // private GoRestService goRestService; // // @Override // public void onCreate() { // super.onCreate(); // // configureCrashReporting(); // // grblController = this; // // // Picasso.Builder builder = new Picasso.Builder(this); // // builder.downloader(new OkHttp3Downloader(this, Integer.MAX_VALUE)); // // Picasso picasso = builder.build(); // // picasso.setIndicatorsEnabled(BuildConfig.DEBUG); // // picasso.setLoggingEnabled(BuildConfig.DEBUG); // // Picasso.setSingletonInstance(picasso); // // AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); // Iconify.with(new FontAwesomeModule()); // } // // public static synchronized GrblController getInstance(){ // return grblController; // } // // private void configureCrashReporting(){ // // } // // public GoRestService getRetrofit(){ // if(goRestService == null){ // Retrofit retrofit = new Retrofit.Builder() // .baseUrl("https://gorest.co.in") // .addConverterFactory(GsonConverterFactory.create()) // .build(); // // goRestService = retrofit.create(GoRestService.class); // } // // return goRestService; // } // // } // // Path: app/src/main/java/in/co/gorest/grblcontroller/util/GrblLookups.java // public class GrblLookups { // // private final HashMap<String,String[]> lookups = new HashMap<>(); // // public GrblLookups(Context context, String prefix) { // String filename = prefix + ".csv"; // // try { // try (BufferedReader br = new BufferedReader( // new InputStreamReader(context.getAssets().open(filename)))) { // String line; // while ((line = br.readLine()) != null) { // String[] parts = line.split(","); // lookups.put(parts[0], parts); // } // } // } catch (IOException ex) { // System.out.println("Unable to load GRBL resources."); // ex.printStackTrace(); // } // } // // public String[] lookup(String idx){ // return lookups.get(idx); // } // // }
import in.co.gorest.grblcontroller.GrblController; import in.co.gorest.grblcontroller.R; import in.co.gorest.grblcontroller.util.GrblLookups;
/* * /** * * Copyright (C) 2017 Grbl Controller Contributors * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along * * with this program; if not, write to the Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * <http://www.gnu.org/licenses/> * */ package in.co.gorest.grblcontroller.events; public class GrblAlarmEvent { private final String message; private int alarmCode; private String alarmName; private String alarmDescription; public GrblAlarmEvent(GrblLookups lookups, String message){ this.message = message; String inputParts[] = message.split(":"); if(inputParts.length == 2){ String[] lookup = lookups.lookup(inputParts[1].trim()); if(lookup != null){ this.alarmCode = Integer.parseInt(lookup[0]); this.alarmName = lookup[1]; this.alarmDescription = lookup[2]; } } } @Override public String toString(){
// Path: app/src/main/java/in/co/gorest/grblcontroller/GrblController.java // public class GrblController extends SugarApp { // // private final String TAG = GrblController.class.getSimpleName(); // private static GrblController grblController; // private GoRestService goRestService; // // @Override // public void onCreate() { // super.onCreate(); // // configureCrashReporting(); // // grblController = this; // // // Picasso.Builder builder = new Picasso.Builder(this); // // builder.downloader(new OkHttp3Downloader(this, Integer.MAX_VALUE)); // // Picasso picasso = builder.build(); // // picasso.setIndicatorsEnabled(BuildConfig.DEBUG); // // picasso.setLoggingEnabled(BuildConfig.DEBUG); // // Picasso.setSingletonInstance(picasso); // // AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); // Iconify.with(new FontAwesomeModule()); // } // // public static synchronized GrblController getInstance(){ // return grblController; // } // // private void configureCrashReporting(){ // // } // // public GoRestService getRetrofit(){ // if(goRestService == null){ // Retrofit retrofit = new Retrofit.Builder() // .baseUrl("https://gorest.co.in") // .addConverterFactory(GsonConverterFactory.create()) // .build(); // // goRestService = retrofit.create(GoRestService.class); // } // // return goRestService; // } // // } // // Path: app/src/main/java/in/co/gorest/grblcontroller/util/GrblLookups.java // public class GrblLookups { // // private final HashMap<String,String[]> lookups = new HashMap<>(); // // public GrblLookups(Context context, String prefix) { // String filename = prefix + ".csv"; // // try { // try (BufferedReader br = new BufferedReader( // new InputStreamReader(context.getAssets().open(filename)))) { // String line; // while ((line = br.readLine()) != null) { // String[] parts = line.split(","); // lookups.put(parts[0], parts); // } // } // } catch (IOException ex) { // System.out.println("Unable to load GRBL resources."); // ex.printStackTrace(); // } // } // // public String[] lookup(String idx){ // return lookups.get(idx); // } // // } // Path: app/src/main/java/in/co/gorest/grblcontroller/events/GrblAlarmEvent.java import in.co.gorest.grblcontroller.GrblController; import in.co.gorest.grblcontroller.R; import in.co.gorest.grblcontroller.util.GrblLookups; /* * /** * * Copyright (C) 2017 Grbl Controller Contributors * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along * * with this program; if not, write to the Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * <http://www.gnu.org/licenses/> * */ package in.co.gorest.grblcontroller.events; public class GrblAlarmEvent { private final String message; private int alarmCode; private String alarmName; private String alarmDescription; public GrblAlarmEvent(GrblLookups lookups, String message){ this.message = message; String inputParts[] = message.split(":"); if(inputParts.length == 2){ String[] lookup = lookups.lookup(inputParts[1].trim()); if(lookup != null){ this.alarmCode = Integer.parseInt(lookup[0]); this.alarmName = lookup[1]; this.alarmDescription = lookup[2]; } } } @Override public String toString(){
return GrblController.getInstance().getString(R.string.text_grbl_alarm_format, alarmCode, alarmDescription);
henryblue/TeaCup
app/src/main/java/com/app/teacup/adapter/ReactViewPagerAdapter.java
// Path: app/src/main/java/com/app/teacup/ui/ReactViewPager.java // public class ReactViewPager extends CenterViewPager { // // public ReactViewPager(Context context) { // this(context, null); // } // // public ReactViewPager(Context context, AttributeSet attrs) { // super(context, attrs); // } // // @Override // protected void onAttachedToWindow() { // super.onAttachedToWindow(); // try { // Field mFirstLayout = ViewPager.class.getDeclaredField("mFirstLayout"); // mFirstLayout.setAccessible(true); // mFirstLayout.set(this, false); // if (getAdapter() != null) { // getAdapter().notifyDataSetChanged(); // } // setCurrentItem(getCurrentItem(), true); // } catch (Exception e) { // e.printStackTrace(); // } // } // // @Override // protected void onDetachedFromWindow() { // if (((Activity) getContext()).isFinishing()) { // super.onDetachedFromWindow(); // } // } // }
import android.annotation.SuppressLint; import android.os.Handler; import android.os.Message; import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import com.app.teacup.ui.ReactViewPager; import java.util.List;
package com.app.teacup.adapter; public class ReactViewPagerAdapter extends PagerAdapter { private final List<View> mViewList;
// Path: app/src/main/java/com/app/teacup/ui/ReactViewPager.java // public class ReactViewPager extends CenterViewPager { // // public ReactViewPager(Context context) { // this(context, null); // } // // public ReactViewPager(Context context, AttributeSet attrs) { // super(context, attrs); // } // // @Override // protected void onAttachedToWindow() { // super.onAttachedToWindow(); // try { // Field mFirstLayout = ViewPager.class.getDeclaredField("mFirstLayout"); // mFirstLayout.setAccessible(true); // mFirstLayout.set(this, false); // if (getAdapter() != null) { // getAdapter().notifyDataSetChanged(); // } // setCurrentItem(getCurrentItem(), true); // } catch (Exception e) { // e.printStackTrace(); // } // } // // @Override // protected void onDetachedFromWindow() { // if (((Activity) getContext()).isFinishing()) { // super.onDetachedFromWindow(); // } // } // } // Path: app/src/main/java/com/app/teacup/adapter/ReactViewPagerAdapter.java import android.annotation.SuppressLint; import android.os.Handler; import android.os.Message; import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import com.app.teacup.ui.ReactViewPager; import java.util.List; package com.app.teacup.adapter; public class ReactViewPagerAdapter extends PagerAdapter { private final List<View> mViewList;
private final ReactViewPager mViewPager;
salesforce/grpc-java-contrib
demos/grpc-java-contrib-demo/time-service-demo/src/main/java/com/salesforce/servicelibs/timeserver/TimeServiceImpl.java
// Path: contrib/grpc-contrib/src/main/java/com/salesforce/grpc/contrib/MoreTimestamps.java // public final class MoreTimestamps { // private MoreTimestamps() { // // private static constructor // } // // public static Instant toInstantUtc(@Nonnull Timestamp timestamp) { // checkNotNull(timestamp, "timestamp"); // return Instant.ofEpochSecond(timestamp.getSeconds(), timestamp.getNanos()); // } // // public static OffsetDateTime toOffsetDateTimeUtc(@Nonnull Timestamp timestamp) { // checkNotNull(timestamp, "timestamp"); // return toInstantUtc(timestamp).atOffset(ZoneOffset.UTC); // } // // public static ZonedDateTime toZonedDateTimeUtc(@Nonnull Timestamp timestamp) { // checkNotNull(timestamp, "timestamp"); // return toOffsetDateTimeUtc(timestamp).toZonedDateTime(); // } // // public static Timestamp fromInstantUtc(@Nonnull Instant instant) { // checkNotNull(instant, "instant"); // return Timestamp.newBuilder() // .setSeconds(instant.getEpochSecond()) // .setNanos(instant.getNano()) // .build(); // } // // public static Timestamp fromOffsetDateTimeUtc(@Nonnull OffsetDateTime offsetDateTime) { // checkNotNull(offsetDateTime, "offsetDateTime"); // return fromInstantUtc(offsetDateTime.toInstant()); // } // // public static Timestamp fromZonedDateTimeUtc(@Nonnull ZonedDateTime zonedDateTime) { // checkNotNull(zonedDateTime, "zonedDateTime"); // return fromOffsetDateTimeUtc(zonedDateTime.toOffsetDateTime()); // } // }
import com.google.protobuf.Empty; import com.google.protobuf.Timestamp; import com.salesforce.grpc.contrib.MoreTimestamps; import com.salesforce.grpc.contrib.spring.GrpcService; import com.salesforce.servicelibs.TimeReply; import com.salesforce.servicelibs.TimeServiceGrpc; import io.grpc.stub.StreamObserver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.Instant;
/* * Copyright (c) 2019, Salesforce.com, Inc. * All rights reserved. * Licensed under the BSD 3-Clause license. * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ package com.salesforce.servicelibs.timeserver; /** * Implements TimeService.proto. */ @GrpcService public class TimeServiceImpl extends TimeServiceGrpc.TimeServiceImplBase { private final Logger logger = LoggerFactory.getLogger(TimeServiceImpl.class); @Override public void getTime(Empty request, StreamObserver<TimeReply> responseObserver) { // JDK8 type Instant now = Instant.now(); logger.info("Reporting the time " + now); // Protobuf type
// Path: contrib/grpc-contrib/src/main/java/com/salesforce/grpc/contrib/MoreTimestamps.java // public final class MoreTimestamps { // private MoreTimestamps() { // // private static constructor // } // // public static Instant toInstantUtc(@Nonnull Timestamp timestamp) { // checkNotNull(timestamp, "timestamp"); // return Instant.ofEpochSecond(timestamp.getSeconds(), timestamp.getNanos()); // } // // public static OffsetDateTime toOffsetDateTimeUtc(@Nonnull Timestamp timestamp) { // checkNotNull(timestamp, "timestamp"); // return toInstantUtc(timestamp).atOffset(ZoneOffset.UTC); // } // // public static ZonedDateTime toZonedDateTimeUtc(@Nonnull Timestamp timestamp) { // checkNotNull(timestamp, "timestamp"); // return toOffsetDateTimeUtc(timestamp).toZonedDateTime(); // } // // public static Timestamp fromInstantUtc(@Nonnull Instant instant) { // checkNotNull(instant, "instant"); // return Timestamp.newBuilder() // .setSeconds(instant.getEpochSecond()) // .setNanos(instant.getNano()) // .build(); // } // // public static Timestamp fromOffsetDateTimeUtc(@Nonnull OffsetDateTime offsetDateTime) { // checkNotNull(offsetDateTime, "offsetDateTime"); // return fromInstantUtc(offsetDateTime.toInstant()); // } // // public static Timestamp fromZonedDateTimeUtc(@Nonnull ZonedDateTime zonedDateTime) { // checkNotNull(zonedDateTime, "zonedDateTime"); // return fromOffsetDateTimeUtc(zonedDateTime.toOffsetDateTime()); // } // } // Path: demos/grpc-java-contrib-demo/time-service-demo/src/main/java/com/salesforce/servicelibs/timeserver/TimeServiceImpl.java import com.google.protobuf.Empty; import com.google.protobuf.Timestamp; import com.salesforce.grpc.contrib.MoreTimestamps; import com.salesforce.grpc.contrib.spring.GrpcService; import com.salesforce.servicelibs.TimeReply; import com.salesforce.servicelibs.TimeServiceGrpc; import io.grpc.stub.StreamObserver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.Instant; /* * Copyright (c) 2019, Salesforce.com, Inc. * All rights reserved. * Licensed under the BSD 3-Clause license. * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ package com.salesforce.servicelibs.timeserver; /** * Implements TimeService.proto. */ @GrpcService public class TimeServiceImpl extends TimeServiceGrpc.TimeServiceImplBase { private final Logger logger = LoggerFactory.getLogger(TimeServiceImpl.class); @Override public void getTime(Empty request, StreamObserver<TimeReply> responseObserver) { // JDK8 type Instant now = Instant.now(); logger.info("Reporting the time " + now); // Protobuf type
Timestamp protoNow = MoreTimestamps.fromInstantUtc(now);
salesforce/grpc-java-contrib
contrib/grpc-contrib/src/test/java/com/salesforce/grpc/contrib/instancemode/PerCallServiceTest.java
// Path: contrib/grpc-contrib/src/main/java/com/salesforce/grpc/contrib/instancemode/PerCallService.java // public class PerCallService<T extends BindableService> implements BindableService { // private ServerServiceDefinition perCallBinding; // // /** // * Create a {@code PerCallService} for a provided service implementation class, generated by a factory method. // * // * @param factory A factory that will initialize a new service implementation object for every call. // */ // public PerCallService(Supplier<T> factory) { // perCallBinding = bindService(factory); // } // // /** // * Create a {@code PerCallService} for a provided service implementation class. The provided class must have a // * default constructor. // * // * @param clazz The service implementation class to decorate. // */ // public PerCallService(Class<T> clazz) { // this (() -> { // try { // return clazz.newInstance(); // } catch (ReflectiveOperationException e) { // throw new IllegalArgumentException("Class " + clazz.getName() + " must have a public default constructor", e); // } // }); // } // // @SuppressWarnings("unchecked") // private ServerServiceDefinition bindService(Supplier<T> factory) { // ServerServiceDefinition baseDefinition = factory.get().bindService(); // ServiceDescriptor descriptor = baseDefinition.getServiceDescriptor(); // Collection<ServerMethodDefinition<?, ?>> methods = baseDefinition.getMethods(); // // ServerServiceDefinition.Builder builder = ServerServiceDefinition.builder(descriptor); // methods.forEach(method -> builder.addMethod(ServerMethodDefinition.create(method.getMethodDescriptor(), new PerCallServerCallHandler(factory)))); // return builder.build(); // } // // @Override // public ServerServiceDefinition bindService() { // return perCallBinding; // } // // /** // * Internal class implementing the per-call service pattern. // */ // private class PerCallServerCallHandler implements ServerCallHandler { // private Supplier<T> factory; // // PerCallServerCallHandler(Supplier<T> factory) { // this.factory = factory; // } // // @Override // @SuppressWarnings("unchecked") // public ServerCall.Listener startCall(ServerCall call, Metadata headers) { // BindableService instance = factory.get(); // ServerServiceDefinition definition = instance.bindService(); // ServerMethodDefinition method = definition.getMethod(call.getMethodDescriptor().getFullMethodName()); // // return new ForwardingServerCallListener.SimpleForwardingServerCallListener<T>(method.getServerCallHandler().startCall(call, headers)) { // @Override // public void onCancel() { // super.onCancel(); // close(); // } // // @Override // public void onComplete() { // super.onComplete(); // close(); // } // // private void close() { // if (instance instanceof AutoCloseable) { // try { // ((AutoCloseable) instance).close(); // } catch (Throwable t) { // throw new RuntimeException(t); // } // } // } // }; // } // } // }
import com.salesforce.grpc.contrib.GreeterGrpc; import com.salesforce.grpc.contrib.HelloRequest; import com.salesforce.grpc.contrib.HelloResponse; import com.salesforce.grpc.contrib.instancemode.PerCallService; import io.grpc.stub.StreamObserver; import io.grpc.testing.GrpcServerRule; import org.junit.Rule; import org.junit.Test; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy;
package com.salesforce.grpc.contrib.instancemode; public class PerCallServiceTest { @Rule public final GrpcServerRule serverRule = new GrpcServerRule(); @Test public void perCallShouldInstantiateMultipleInstances() throws Exception { AtomicInteger closeCount = new AtomicInteger(0); class TestService extends GreeterGrpc.GreeterImplBase implements AutoCloseable { public TestService() {} @Override public void sayHello(HelloRequest request, StreamObserver<HelloResponse> responseObserver) { responseObserver.onNext(HelloResponse.newBuilder().setMessage(Integer.toString(System.identityHashCode(this))).build()); responseObserver.onCompleted(); } @Override public void close() { closeCount.incrementAndGet(); } }
// Path: contrib/grpc-contrib/src/main/java/com/salesforce/grpc/contrib/instancemode/PerCallService.java // public class PerCallService<T extends BindableService> implements BindableService { // private ServerServiceDefinition perCallBinding; // // /** // * Create a {@code PerCallService} for a provided service implementation class, generated by a factory method. // * // * @param factory A factory that will initialize a new service implementation object for every call. // */ // public PerCallService(Supplier<T> factory) { // perCallBinding = bindService(factory); // } // // /** // * Create a {@code PerCallService} for a provided service implementation class. The provided class must have a // * default constructor. // * // * @param clazz The service implementation class to decorate. // */ // public PerCallService(Class<T> clazz) { // this (() -> { // try { // return clazz.newInstance(); // } catch (ReflectiveOperationException e) { // throw new IllegalArgumentException("Class " + clazz.getName() + " must have a public default constructor", e); // } // }); // } // // @SuppressWarnings("unchecked") // private ServerServiceDefinition bindService(Supplier<T> factory) { // ServerServiceDefinition baseDefinition = factory.get().bindService(); // ServiceDescriptor descriptor = baseDefinition.getServiceDescriptor(); // Collection<ServerMethodDefinition<?, ?>> methods = baseDefinition.getMethods(); // // ServerServiceDefinition.Builder builder = ServerServiceDefinition.builder(descriptor); // methods.forEach(method -> builder.addMethod(ServerMethodDefinition.create(method.getMethodDescriptor(), new PerCallServerCallHandler(factory)))); // return builder.build(); // } // // @Override // public ServerServiceDefinition bindService() { // return perCallBinding; // } // // /** // * Internal class implementing the per-call service pattern. // */ // private class PerCallServerCallHandler implements ServerCallHandler { // private Supplier<T> factory; // // PerCallServerCallHandler(Supplier<T> factory) { // this.factory = factory; // } // // @Override // @SuppressWarnings("unchecked") // public ServerCall.Listener startCall(ServerCall call, Metadata headers) { // BindableService instance = factory.get(); // ServerServiceDefinition definition = instance.bindService(); // ServerMethodDefinition method = definition.getMethod(call.getMethodDescriptor().getFullMethodName()); // // return new ForwardingServerCallListener.SimpleForwardingServerCallListener<T>(method.getServerCallHandler().startCall(call, headers)) { // @Override // public void onCancel() { // super.onCancel(); // close(); // } // // @Override // public void onComplete() { // super.onComplete(); // close(); // } // // private void close() { // if (instance instanceof AutoCloseable) { // try { // ((AutoCloseable) instance).close(); // } catch (Throwable t) { // throw new RuntimeException(t); // } // } // } // }; // } // } // } // Path: contrib/grpc-contrib/src/test/java/com/salesforce/grpc/contrib/instancemode/PerCallServiceTest.java import com.salesforce.grpc.contrib.GreeterGrpc; import com.salesforce.grpc.contrib.HelloRequest; import com.salesforce.grpc.contrib.HelloResponse; import com.salesforce.grpc.contrib.instancemode.PerCallService; import io.grpc.stub.StreamObserver; import io.grpc.testing.GrpcServerRule; import org.junit.Rule; import org.junit.Test; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; package com.salesforce.grpc.contrib.instancemode; public class PerCallServiceTest { @Rule public final GrpcServerRule serverRule = new GrpcServerRule(); @Test public void perCallShouldInstantiateMultipleInstances() throws Exception { AtomicInteger closeCount = new AtomicInteger(0); class TestService extends GreeterGrpc.GreeterImplBase implements AutoCloseable { public TestService() {} @Override public void sayHello(HelloRequest request, StreamObserver<HelloResponse> responseObserver) { responseObserver.onNext(HelloResponse.newBuilder().setMessage(Integer.toString(System.identityHashCode(this))).build()); responseObserver.onCompleted(); } @Override public void close() { closeCount.incrementAndGet(); } }
serverRule.getServiceRegistry().addService(new PerCallService<TestService>(() -> new TestService()));
salesforce/grpc-java-contrib
contrib/grpc-testing-contrib/src/main/java/com/salesforce/grpc/testing/contrib/NettyGrpcServerRule.java
// Path: contrib/grpc-contrib/src/main/java/com/salesforce/grpc/contrib/Servers.java // public final class Servers { // // /** // * Attempt to {@link Server#shutdown()} the {@link Server} gracefully. If the max wait time is exceeded, give up and // * perform a hard {@link Server#shutdownNow()}. // * // * @param server the server to be shutdown // * @param maxWaitTimeInMillis the max amount of time to wait for graceful shutdown to occur // * @return the given server // * @throws InterruptedException if waiting for termination is interrupted // */ // public static Server shutdownGracefully(Server server, long maxWaitTimeInMillis) throws InterruptedException { // return shutdownGracefully(server, maxWaitTimeInMillis, TimeUnit.MILLISECONDS); // } // // /** // * Attempt to {@link Server#shutdown()} the {@link Server} gracefully. If the max wait time is exceeded, give up and // * perform a hard {@link Server#shutdownNow()}. // * // * @param server the server to be shutdown // * @param timeout the max amount of time to wait for graceful shutdown to occur // * @param unit the time unit denominating the shutdown timeout // * @return the given server // * @throws InterruptedException if waiting for termination is interrupted // */ // public static Server shutdownGracefully(Server server, long timeout, TimeUnit unit) throws InterruptedException { // Preconditions.checkNotNull(server, "server"); // Preconditions.checkArgument(timeout > 0, "timeout must be greater than 0"); // Preconditions.checkNotNull(unit, "unit"); // // server.shutdown(); // // try { // server.awaitTermination(timeout, unit); // } finally { // server.shutdownNow(); // } // // return server; // } // // /** // * Attempt to {@link Server#shutdown()} the {@link Server} gracefully when the JVM terminates. If the max wait time // * is exceeded, give up and perform a hard {@link Server#shutdownNow()}. // * // * @param server the server to be shutdown // * @param maxWaitTimeInMillis the max amount of time to wait for graceful shutdown to occur // * @return the given server // */ // public static Server shutdownWithJvm(Server server, long maxWaitTimeInMillis) { // Runtime.getRuntime().addShutdownHook(new Thread(() -> { // try { // shutdownGracefully(server, maxWaitTimeInMillis); // } catch (InterruptedException ex) { // // do nothing // } // })); // // return server; // } // // private Servers() { } // }
import com.salesforce.grpc.contrib.Servers; import io.grpc.ManagedChannel; import io.grpc.Server; import io.grpc.netty.NettyChannelBuilder; import io.grpc.netty.NettyServerBuilder; import io.grpc.util.MutableHandlerRegistry; import org.junit.rules.ExternalResource; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState;
NettyServerBuilder serverBuilder = NettyServerBuilder .forPort(0) .fallbackHandlerRegistry(serviceRegistry); if (useDirectExecutor) { serverBuilder.directExecutor(); } configureServerBuilder.accept(serverBuilder); server = serverBuilder.build().start(); port = server.getPort(); NettyChannelBuilder channelBuilder = NettyChannelBuilder.forAddress("localhost", port).usePlaintext(true); configureChannelBuilder.accept(channelBuilder); channel = channelBuilder.build(); } /** * After the test has completed, clean up the channel and server. */ @Override protected void after() { serviceRegistry = null; channel.shutdown(); channel = null; port = 0; try {
// Path: contrib/grpc-contrib/src/main/java/com/salesforce/grpc/contrib/Servers.java // public final class Servers { // // /** // * Attempt to {@link Server#shutdown()} the {@link Server} gracefully. If the max wait time is exceeded, give up and // * perform a hard {@link Server#shutdownNow()}. // * // * @param server the server to be shutdown // * @param maxWaitTimeInMillis the max amount of time to wait for graceful shutdown to occur // * @return the given server // * @throws InterruptedException if waiting for termination is interrupted // */ // public static Server shutdownGracefully(Server server, long maxWaitTimeInMillis) throws InterruptedException { // return shutdownGracefully(server, maxWaitTimeInMillis, TimeUnit.MILLISECONDS); // } // // /** // * Attempt to {@link Server#shutdown()} the {@link Server} gracefully. If the max wait time is exceeded, give up and // * perform a hard {@link Server#shutdownNow()}. // * // * @param server the server to be shutdown // * @param timeout the max amount of time to wait for graceful shutdown to occur // * @param unit the time unit denominating the shutdown timeout // * @return the given server // * @throws InterruptedException if waiting for termination is interrupted // */ // public static Server shutdownGracefully(Server server, long timeout, TimeUnit unit) throws InterruptedException { // Preconditions.checkNotNull(server, "server"); // Preconditions.checkArgument(timeout > 0, "timeout must be greater than 0"); // Preconditions.checkNotNull(unit, "unit"); // // server.shutdown(); // // try { // server.awaitTermination(timeout, unit); // } finally { // server.shutdownNow(); // } // // return server; // } // // /** // * Attempt to {@link Server#shutdown()} the {@link Server} gracefully when the JVM terminates. If the max wait time // * is exceeded, give up and perform a hard {@link Server#shutdownNow()}. // * // * @param server the server to be shutdown // * @param maxWaitTimeInMillis the max amount of time to wait for graceful shutdown to occur // * @return the given server // */ // public static Server shutdownWithJvm(Server server, long maxWaitTimeInMillis) { // Runtime.getRuntime().addShutdownHook(new Thread(() -> { // try { // shutdownGracefully(server, maxWaitTimeInMillis); // } catch (InterruptedException ex) { // // do nothing // } // })); // // return server; // } // // private Servers() { } // } // Path: contrib/grpc-testing-contrib/src/main/java/com/salesforce/grpc/testing/contrib/NettyGrpcServerRule.java import com.salesforce.grpc.contrib.Servers; import io.grpc.ManagedChannel; import io.grpc.Server; import io.grpc.netty.NettyChannelBuilder; import io.grpc.netty.NettyServerBuilder; import io.grpc.util.MutableHandlerRegistry; import org.junit.rules.ExternalResource; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; NettyServerBuilder serverBuilder = NettyServerBuilder .forPort(0) .fallbackHandlerRegistry(serviceRegistry); if (useDirectExecutor) { serverBuilder.directExecutor(); } configureServerBuilder.accept(serverBuilder); server = serverBuilder.build().start(); port = server.getPort(); NettyChannelBuilder channelBuilder = NettyChannelBuilder.forAddress("localhost", port).usePlaintext(true); configureChannelBuilder.accept(channelBuilder); channel = channelBuilder.build(); } /** * After the test has completed, clean up the channel and server. */ @Override protected void after() { serviceRegistry = null; channel.shutdown(); channel = null; port = 0; try {
Servers.shutdownGracefully(server, 1, TimeUnit.MINUTES);
salesforce/grpc-java-contrib
contrib/grpc-contrib/src/test/java/com/salesforce/grpc/contrib/interceptor/DebugInterceptorTest.java
// Path: contrib/grpc-contrib/src/main/java/com/salesforce/grpc/contrib/interceptor/DebugClientInterceptor.java // public enum Level { // STATUS, HEADERS, MESSAGE // }
import static org.assertj.core.api.Assertions.assertThat; import java.util.LinkedList; import org.junit.Rule; import org.junit.Test; import com.salesforce.grpc.contrib.GreeterGrpc; import com.salesforce.grpc.contrib.HelloRequest; import com.salesforce.grpc.contrib.HelloResponse; import com.salesforce.grpc.contrib.interceptor.DebugClientInterceptor.Level; import io.grpc.ForwardingServerCall.SimpleForwardingServerCall; import io.grpc.Metadata; import io.grpc.ServerCall; import io.grpc.ServerCall.Listener; import io.grpc.ServerCallHandler; import io.grpc.ServerInterceptor; import io.grpc.ServerInterceptors; import io.grpc.stub.MetadataUtils; import io.grpc.stub.StreamObserver; import io.grpc.testing.GrpcServerRule;
private GreeterGrpc.GreeterImplBase svc = new GreeterGrpc.GreeterImplBase() { @Override public void sayHello(HelloRequest request, StreamObserver<HelloResponse> responseObserver) { responseObserver.onNext(HelloResponse.newBuilder().setMessage("Hello " + request.getName()).build()); responseObserver.onCompleted(); } }; @Test public void debugClientInterceptTest() { LinkedList<String> logs = new LinkedList<String>(); Metadata requestHeaders = new Metadata(); requestHeaders.put(Metadata.Key.of("request_header", Metadata.ASCII_STRING_MARSHALLER), "request_header_value"); // Setup serverRule.getServiceRegistry().addService(ServerInterceptors.intercept(svc, new ServerInterceptor() { @Override public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) { return next.startCall(new SimpleForwardingServerCall<ReqT, RespT>(call) { @Override public void sendHeaders(Metadata responseHeaders) { responseHeaders.put(Metadata.Key.of("response_header", Metadata.ASCII_STRING_MARSHALLER), "response_header_value"); super.sendHeaders(responseHeaders); } }, headers); } })); GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(serverRule.getChannel())
// Path: contrib/grpc-contrib/src/main/java/com/salesforce/grpc/contrib/interceptor/DebugClientInterceptor.java // public enum Level { // STATUS, HEADERS, MESSAGE // } // Path: contrib/grpc-contrib/src/test/java/com/salesforce/grpc/contrib/interceptor/DebugInterceptorTest.java import static org.assertj.core.api.Assertions.assertThat; import java.util.LinkedList; import org.junit.Rule; import org.junit.Test; import com.salesforce.grpc.contrib.GreeterGrpc; import com.salesforce.grpc.contrib.HelloRequest; import com.salesforce.grpc.contrib.HelloResponse; import com.salesforce.grpc.contrib.interceptor.DebugClientInterceptor.Level; import io.grpc.ForwardingServerCall.SimpleForwardingServerCall; import io.grpc.Metadata; import io.grpc.ServerCall; import io.grpc.ServerCall.Listener; import io.grpc.ServerCallHandler; import io.grpc.ServerInterceptor; import io.grpc.ServerInterceptors; import io.grpc.stub.MetadataUtils; import io.grpc.stub.StreamObserver; import io.grpc.testing.GrpcServerRule; private GreeterGrpc.GreeterImplBase svc = new GreeterGrpc.GreeterImplBase() { @Override public void sayHello(HelloRequest request, StreamObserver<HelloResponse> responseObserver) { responseObserver.onNext(HelloResponse.newBuilder().setMessage("Hello " + request.getName()).build()); responseObserver.onCompleted(); } }; @Test public void debugClientInterceptTest() { LinkedList<String> logs = new LinkedList<String>(); Metadata requestHeaders = new Metadata(); requestHeaders.put(Metadata.Key.of("request_header", Metadata.ASCII_STRING_MARSHALLER), "request_header_value"); // Setup serverRule.getServiceRegistry().addService(ServerInterceptors.intercept(svc, new ServerInterceptor() { @Override public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) { return next.startCall(new SimpleForwardingServerCall<ReqT, RespT>(call) { @Override public void sendHeaders(Metadata responseHeaders) { responseHeaders.put(Metadata.Key.of("response_header", Metadata.ASCII_STRING_MARSHALLER), "response_header_value"); super.sendHeaders(responseHeaders); } }, headers); } })); GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(serverRule.getChannel())
.withInterceptors(new DebugClientInterceptor(Level.STATUS, Level.HEADERS, Level.MESSAGE) {
salesforce/grpc-java-contrib
contrib/grpc-spring/src/test/java/com/salesforce/grpc/contrib/spring/GrpcServerHostTest.java
// Path: contrib/grpc-spring/src/main/java/com/salesforce/grpc/contrib/spring/GrpcServerHost.java // static final int MAX_PORT = 65535; // // Path: contrib/grpc-spring/src/main/java/com/salesforce/grpc/contrib/spring/GrpcServerHost.java // static final int MIN_PORT = 0;
import com.google.common.collect.ImmutableMap; import io.grpc.BindableService; import io.grpc.Server; import org.assertj.core.api.Condition; import org.junit.Test; import org.mockito.internal.stubbing.defaultanswers.TriesToReturnSelf; import org.springframework.context.ApplicationContext; import java.io.IOException; import java.util.Map; import java.util.UUID; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import java.util.stream.IntStream; import static com.salesforce.grpc.contrib.spring.GrpcServerHost.MAX_PORT; import static com.salesforce.grpc.contrib.spring.GrpcServerHost.MIN_PORT; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.*;
/* * Copyright (c) 2019, Salesforce.com, Inc. * All rights reserved. * Licensed under the BSD 3-Clause license. * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ package com.salesforce.grpc.contrib.spring;/* * Copyright, 1999-2017, SALESFORCE.com * All Rights Reserved * Company Confidential */ public class GrpcServerHostTest { @Test public void constructorThrowsForPortLessThanMin() {
// Path: contrib/grpc-spring/src/main/java/com/salesforce/grpc/contrib/spring/GrpcServerHost.java // static final int MAX_PORT = 65535; // // Path: contrib/grpc-spring/src/main/java/com/salesforce/grpc/contrib/spring/GrpcServerHost.java // static final int MIN_PORT = 0; // Path: contrib/grpc-spring/src/test/java/com/salesforce/grpc/contrib/spring/GrpcServerHostTest.java import com.google.common.collect.ImmutableMap; import io.grpc.BindableService; import io.grpc.Server; import org.assertj.core.api.Condition; import org.junit.Test; import org.mockito.internal.stubbing.defaultanswers.TriesToReturnSelf; import org.springframework.context.ApplicationContext; import java.io.IOException; import java.util.Map; import java.util.UUID; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import java.util.stream.IntStream; import static com.salesforce.grpc.contrib.spring.GrpcServerHost.MAX_PORT; import static com.salesforce.grpc.contrib.spring.GrpcServerHost.MIN_PORT; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.*; /* * Copyright (c) 2019, Salesforce.com, Inc. * All rights reserved. * Licensed under the BSD 3-Clause license. * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ package com.salesforce.grpc.contrib.spring;/* * Copyright, 1999-2017, SALESFORCE.com * All Rights Reserved * Company Confidential */ public class GrpcServerHostTest { @Test public void constructorThrowsForPortLessThanMin() {
final int port = ThreadLocalRandom.current().nextInt(Integer.MIN_VALUE, MIN_PORT);
salesforce/grpc-java-contrib
contrib/grpc-spring/src/test/java/com/salesforce/grpc/contrib/spring/GrpcServerHostTest.java
// Path: contrib/grpc-spring/src/main/java/com/salesforce/grpc/contrib/spring/GrpcServerHost.java // static final int MAX_PORT = 65535; // // Path: contrib/grpc-spring/src/main/java/com/salesforce/grpc/contrib/spring/GrpcServerHost.java // static final int MIN_PORT = 0;
import com.google.common.collect.ImmutableMap; import io.grpc.BindableService; import io.grpc.Server; import org.assertj.core.api.Condition; import org.junit.Test; import org.mockito.internal.stubbing.defaultanswers.TriesToReturnSelf; import org.springframework.context.ApplicationContext; import java.io.IOException; import java.util.Map; import java.util.UUID; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import java.util.stream.IntStream; import static com.salesforce.grpc.contrib.spring.GrpcServerHost.MAX_PORT; import static com.salesforce.grpc.contrib.spring.GrpcServerHost.MIN_PORT; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.*;
/* * Copyright (c) 2019, Salesforce.com, Inc. * All rights reserved. * Licensed under the BSD 3-Clause license. * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ package com.salesforce.grpc.contrib.spring;/* * Copyright, 1999-2017, SALESFORCE.com * All Rights Reserved * Company Confidential */ public class GrpcServerHostTest { @Test public void constructorThrowsForPortLessThanMin() { final int port = ThreadLocalRandom.current().nextInt(Integer.MIN_VALUE, MIN_PORT); final long shutdownWaitTimeInMillis = ThreadLocalRandom.current().nextLong(1000, 10000); assertThatThrownBy(() -> new GrpcServerHost(port, shutdownWaitTimeInMillis)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("port"); } @Test public void constructorThrowsForPortGreaterThanMax() {
// Path: contrib/grpc-spring/src/main/java/com/salesforce/grpc/contrib/spring/GrpcServerHost.java // static final int MAX_PORT = 65535; // // Path: contrib/grpc-spring/src/main/java/com/salesforce/grpc/contrib/spring/GrpcServerHost.java // static final int MIN_PORT = 0; // Path: contrib/grpc-spring/src/test/java/com/salesforce/grpc/contrib/spring/GrpcServerHostTest.java import com.google.common.collect.ImmutableMap; import io.grpc.BindableService; import io.grpc.Server; import org.assertj.core.api.Condition; import org.junit.Test; import org.mockito.internal.stubbing.defaultanswers.TriesToReturnSelf; import org.springframework.context.ApplicationContext; import java.io.IOException; import java.util.Map; import java.util.UUID; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import java.util.stream.IntStream; import static com.salesforce.grpc.contrib.spring.GrpcServerHost.MAX_PORT; import static com.salesforce.grpc.contrib.spring.GrpcServerHost.MIN_PORT; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.*; /* * Copyright (c) 2019, Salesforce.com, Inc. * All rights reserved. * Licensed under the BSD 3-Clause license. * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ package com.salesforce.grpc.contrib.spring;/* * Copyright, 1999-2017, SALESFORCE.com * All Rights Reserved * Company Confidential */ public class GrpcServerHostTest { @Test public void constructorThrowsForPortLessThanMin() { final int port = ThreadLocalRandom.current().nextInt(Integer.MIN_VALUE, MIN_PORT); final long shutdownWaitTimeInMillis = ThreadLocalRandom.current().nextLong(1000, 10000); assertThatThrownBy(() -> new GrpcServerHost(port, shutdownWaitTimeInMillis)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("port"); } @Test public void constructorThrowsForPortGreaterThanMax() {
final int port = ThreadLocalRandom.current().nextInt(MAX_PORT, Integer.MAX_VALUE);
salesforce/grpc-java-contrib
contrib/grpc-contrib/src/test/java/com/salesforce/grpc/contrib/context/AmbientContextEnforcerTest.java
// Path: contrib/grpc-contrib/src/main/java/com/salesforce/grpc/contrib/Statuses.java // public final class Statuses { // private Statuses() { } // // /** // * Evaluates a throwable to determine it if has a gRPC status. Particularly, is this throwable a // * {@code StatusException} or a {@code StatusRuntimeException}. // * // * @param t A throwable to evaluate // * @return {@code true} if {@code t} is a {@code StatusException} or a {@code StatusRuntimeException} // */ // public static boolean hasStatus(Throwable t) { // return t instanceof StatusException || t instanceof StatusRuntimeException; // } // // /** // * Evaluates a throwable to determine if it has a gRPC status, and then if so, evaluates the throwable's // * status code. // * // * @param t A throwable to evaluate // * @param code A {@code Status.Code} to look for // * @return {@code true} if {@code t} is a {@code StatusException} or a {@code StatusRuntimeException} with // * {@code Status.Code} equal to {@code code} // */ // public static boolean hasStatusCode(Throwable t, Status.Code code) { // if (!hasStatus(t)) { // return false; // } else { // return doWithStatus(t, (status, metadata) -> status.getCode() == code); // } // } // // /** // * Executes an action on a {@code StatusException} or a {@code StatusRuntimeException}, passing in the exception's // * metadata and trailers. // * // * @param t a {@code StatusException} or a {@code StatusRuntimeException} // * @param action the action to execute, given the exception's status and trailers // * // * @throws IllegalArgumentException if {@code t} is not a {@code StatusException} or a {@code StatusRuntimeException} // */ // public static void doWithStatus(Throwable t, BiConsumer<Status, Metadata> action) { // doWithStatus(t, (status, metadata) -> { // action.accept(status, metadata); // return true; // }); // } // // /** // * Executes a function on a {@code StatusException} or a {@code StatusRuntimeException}, passing in the exception's // * metadata and trailers. // * // * @param t a {@code StatusException} or a {@code StatusRuntimeException} // * @param function the function to execute, given the exception's status and trailers // * @param <T> the function's return type // * // * @throws IllegalArgumentException if {@code t} is not a {@code StatusException} or a {@code StatusRuntimeException} // */ // public static <T> T doWithStatus(Throwable t, BiFunction<Status, Metadata, T> function) { // if (t instanceof StatusException) { // return function.apply(((StatusException) t).getStatus(), ((StatusException) t).getTrailers()); // } // if (t instanceof StatusRuntimeException) { // return function.apply(((StatusRuntimeException) t).getStatus(), ((StatusRuntimeException) t).getTrailers()); // } // // throw new IllegalArgumentException("Throwable " + t.getClass().getSimpleName() + " is neither a " + // "StatusException nor a StatusRuntimeException"); // } // }
import com.salesforce.grpc.contrib.GreeterGrpc; import com.salesforce.grpc.contrib.HelloRequest; import com.salesforce.grpc.contrib.HelloResponse; import com.salesforce.grpc.contrib.Statuses; import io.grpc.*; import io.grpc.stub.StreamObserver; import io.grpc.testing.GrpcServerRule; import org.assertj.core.api.Condition; import org.junit.Rule; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThatThrownBy;
GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc .newBlockingStub(serverRule.getChannel()) .withInterceptors(new AmbientContextClientInterceptor("ctx-")); // Test AmbientContext.initialize(Context.current()).run(() -> { Metadata.Key<String> k = Metadata.Key.of("ctx-test", Metadata.ASCII_STRING_MARSHALLER); AmbientContext.current().put(k, "v"); stub.sayHello(HelloRequest.newBuilder().setName("World").build()); }); } @Test public void serverEnforcerFailsMissing() { // Plumbing serverRule.getServiceRegistry().addService(ServerInterceptors.interceptForward(svc, new AmbientContextServerInterceptor("ctx-"), new AmbientContextEnforcerServerInterceptor("ctx-test") )); GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc .newBlockingStub(serverRule.getChannel()) .withInterceptors(new AmbientContextClientInterceptor("ctx-")); // Test assertThatThrownBy(() -> stub.sayHello(HelloRequest.newBuilder().setName("World").build())) .isInstanceOfAny(StatusRuntimeException.class) .has(new Condition<Throwable>() { @Override public boolean matches(Throwable throwable) {
// Path: contrib/grpc-contrib/src/main/java/com/salesforce/grpc/contrib/Statuses.java // public final class Statuses { // private Statuses() { } // // /** // * Evaluates a throwable to determine it if has a gRPC status. Particularly, is this throwable a // * {@code StatusException} or a {@code StatusRuntimeException}. // * // * @param t A throwable to evaluate // * @return {@code true} if {@code t} is a {@code StatusException} or a {@code StatusRuntimeException} // */ // public static boolean hasStatus(Throwable t) { // return t instanceof StatusException || t instanceof StatusRuntimeException; // } // // /** // * Evaluates a throwable to determine if it has a gRPC status, and then if so, evaluates the throwable's // * status code. // * // * @param t A throwable to evaluate // * @param code A {@code Status.Code} to look for // * @return {@code true} if {@code t} is a {@code StatusException} or a {@code StatusRuntimeException} with // * {@code Status.Code} equal to {@code code} // */ // public static boolean hasStatusCode(Throwable t, Status.Code code) { // if (!hasStatus(t)) { // return false; // } else { // return doWithStatus(t, (status, metadata) -> status.getCode() == code); // } // } // // /** // * Executes an action on a {@code StatusException} or a {@code StatusRuntimeException}, passing in the exception's // * metadata and trailers. // * // * @param t a {@code StatusException} or a {@code StatusRuntimeException} // * @param action the action to execute, given the exception's status and trailers // * // * @throws IllegalArgumentException if {@code t} is not a {@code StatusException} or a {@code StatusRuntimeException} // */ // public static void doWithStatus(Throwable t, BiConsumer<Status, Metadata> action) { // doWithStatus(t, (status, metadata) -> { // action.accept(status, metadata); // return true; // }); // } // // /** // * Executes a function on a {@code StatusException} or a {@code StatusRuntimeException}, passing in the exception's // * metadata and trailers. // * // * @param t a {@code StatusException} or a {@code StatusRuntimeException} // * @param function the function to execute, given the exception's status and trailers // * @param <T> the function's return type // * // * @throws IllegalArgumentException if {@code t} is not a {@code StatusException} or a {@code StatusRuntimeException} // */ // public static <T> T doWithStatus(Throwable t, BiFunction<Status, Metadata, T> function) { // if (t instanceof StatusException) { // return function.apply(((StatusException) t).getStatus(), ((StatusException) t).getTrailers()); // } // if (t instanceof StatusRuntimeException) { // return function.apply(((StatusRuntimeException) t).getStatus(), ((StatusRuntimeException) t).getTrailers()); // } // // throw new IllegalArgumentException("Throwable " + t.getClass().getSimpleName() + " is neither a " + // "StatusException nor a StatusRuntimeException"); // } // } // Path: contrib/grpc-contrib/src/test/java/com/salesforce/grpc/contrib/context/AmbientContextEnforcerTest.java import com.salesforce.grpc.contrib.GreeterGrpc; import com.salesforce.grpc.contrib.HelloRequest; import com.salesforce.grpc.contrib.HelloResponse; import com.salesforce.grpc.contrib.Statuses; import io.grpc.*; import io.grpc.stub.StreamObserver; import io.grpc.testing.GrpcServerRule; import org.assertj.core.api.Condition; import org.junit.Rule; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThatThrownBy; GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc .newBlockingStub(serverRule.getChannel()) .withInterceptors(new AmbientContextClientInterceptor("ctx-")); // Test AmbientContext.initialize(Context.current()).run(() -> { Metadata.Key<String> k = Metadata.Key.of("ctx-test", Metadata.ASCII_STRING_MARSHALLER); AmbientContext.current().put(k, "v"); stub.sayHello(HelloRequest.newBuilder().setName("World").build()); }); } @Test public void serverEnforcerFailsMissing() { // Plumbing serverRule.getServiceRegistry().addService(ServerInterceptors.interceptForward(svc, new AmbientContextServerInterceptor("ctx-"), new AmbientContextEnforcerServerInterceptor("ctx-test") )); GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc .newBlockingStub(serverRule.getChannel()) .withInterceptors(new AmbientContextClientInterceptor("ctx-")); // Test assertThatThrownBy(() -> stub.sayHello(HelloRequest.newBuilder().setName("World").build())) .isInstanceOfAny(StatusRuntimeException.class) .has(new Condition<Throwable>() { @Override public boolean matches(Throwable throwable) {
return Statuses.hasStatusCode(throwable, Status.Code.FAILED_PRECONDITION);
googleads/googleads-mobile-flutter
packages/google_mobile_ads/android/src/main/java/io/flutter/plugins/googlemobileads/GoogleMobileAdsPlugin.java
// Path: packages/google_mobile_ads/android/src/main/java/io/flutter/plugins/googlemobileads/FlutterAd.java // abstract static class FlutterOverlayAd extends FlutterAd { // abstract void show(); // // abstract void setImmersiveMode(boolean immersiveModeEnabled); // // FlutterOverlayAd(int adId) { // super(adId); // } // }
import android.content.Context; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import com.google.android.gms.ads.AdSize; import com.google.android.gms.ads.MobileAds; import com.google.android.gms.ads.RequestConfiguration; import com.google.android.gms.ads.initialization.InitializationStatus; import com.google.android.gms.ads.initialization.OnInitializationCompleteListener; import com.google.android.gms.ads.nativead.NativeAd; import com.google.android.gms.ads.nativead.NativeAdView; import io.flutter.embedding.engine.FlutterEngine; import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.embedding.engine.plugins.activity.ActivityAware; import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugin.common.MethodChannel.MethodCallHandler; import io.flutter.plugin.common.MethodChannel.Result; import io.flutter.plugin.common.StandardMethodCodec; import io.flutter.plugins.googlemobileads.FlutterAd.FlutterOverlayAd; import java.util.HashMap; import java.util.List; import java.util.Map;
case "showAdWithoutView": final boolean adShown = instanceManager.showAdWithId(call.<Integer>argument("adId")); if (!adShown) { result.error("AdShowError", "Ad failed to show.", null); break; } result.success(null); break; case "AdSize#getAnchoredAdaptiveBannerAdSize": final FlutterAdSize.AnchoredAdaptiveBannerAdSize size = new FlutterAdSize.AnchoredAdaptiveBannerAdSize( context, new FlutterAdSize.AdSizeFactory(), call.<String>argument("orientation"), call.<Integer>argument("width")); if (AdSize.INVALID.equals(size.size)) { result.success(null); } else { result.success(size.height); } break; case "MobileAds#setAppMuted": flutterMobileAds.setAppMuted(call.<Boolean>argument("muted")); result.success(null); break; case "MobileAds#setAppVolume": flutterMobileAds.setAppVolume(call.<Double>argument("volume")); result.success(null); break; case "setImmersiveMode":
// Path: packages/google_mobile_ads/android/src/main/java/io/flutter/plugins/googlemobileads/FlutterAd.java // abstract static class FlutterOverlayAd extends FlutterAd { // abstract void show(); // // abstract void setImmersiveMode(boolean immersiveModeEnabled); // // FlutterOverlayAd(int adId) { // super(adId); // } // } // Path: packages/google_mobile_ads/android/src/main/java/io/flutter/plugins/googlemobileads/GoogleMobileAdsPlugin.java import android.content.Context; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import com.google.android.gms.ads.AdSize; import com.google.android.gms.ads.MobileAds; import com.google.android.gms.ads.RequestConfiguration; import com.google.android.gms.ads.initialization.InitializationStatus; import com.google.android.gms.ads.initialization.OnInitializationCompleteListener; import com.google.android.gms.ads.nativead.NativeAd; import com.google.android.gms.ads.nativead.NativeAdView; import io.flutter.embedding.engine.FlutterEngine; import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.embedding.engine.plugins.activity.ActivityAware; import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugin.common.MethodChannel.MethodCallHandler; import io.flutter.plugin.common.MethodChannel.Result; import io.flutter.plugin.common.StandardMethodCodec; import io.flutter.plugins.googlemobileads.FlutterAd.FlutterOverlayAd; import java.util.HashMap; import java.util.List; import java.util.Map; case "showAdWithoutView": final boolean adShown = instanceManager.showAdWithId(call.<Integer>argument("adId")); if (!adShown) { result.error("AdShowError", "Ad failed to show.", null); break; } result.success(null); break; case "AdSize#getAnchoredAdaptiveBannerAdSize": final FlutterAdSize.AnchoredAdaptiveBannerAdSize size = new FlutterAdSize.AnchoredAdaptiveBannerAdSize( context, new FlutterAdSize.AdSizeFactory(), call.<String>argument("orientation"), call.<Integer>argument("width")); if (AdSize.INVALID.equals(size.size)) { result.success(null); } else { result.success(size.height); } break; case "MobileAds#setAppMuted": flutterMobileAds.setAppMuted(call.<Boolean>argument("muted")); result.success(null); break; case "MobileAds#setAppVolume": flutterMobileAds.setAppVolume(call.<Double>argument("volume")); result.success(null); break; case "setImmersiveMode":
((FlutterOverlayAd) instanceManager.adForId(call.<Integer>argument("adId")))
googleads/googleads-mobile-flutter
packages/google_mobile_ads/android/src/main/java/io/flutter/plugins/googlemobileads/AdInstanceManager.java
// Path: packages/google_mobile_ads/android/src/main/java/io/flutter/plugins/googlemobileads/FlutterAd.java // static class FlutterAdError { // final int code; // @NonNull final String domain; // @NonNull final String message; // // FlutterAdError(@NonNull AdError error) { // code = error.getCode(); // domain = error.getDomain(); // message = error.getMessage(); // } // // FlutterAdError(int code, @NonNull String domain, @NonNull String message) { // this.code = code; // this.domain = domain; // this.message = message; // } // // @Override // public boolean equals(Object object) { // if (this == object) { // return true; // } else if (!(object instanceof FlutterAdError)) { // return false; // } // // final FlutterAdError that = (FlutterAdError) object; // // if (code != that.code) { // return false; // } else if (!domain.equals(that.domain)) { // return false; // } // return message.equals(that.message); // } // // @Override // public int hashCode() { // return Objects.hash(code, domain, message); // } // } // // Path: packages/google_mobile_ads/android/src/main/java/io/flutter/plugins/googlemobileads/FlutterAd.java // static class FlutterResponseInfo { // // @Nullable private final String responseId; // @Nullable private final String mediationAdapterClassName; // @NonNull private final List<FlutterAdapterResponseInfo> adapterResponses; // // FlutterResponseInfo(@NonNull ResponseInfo responseInfo) { // this.responseId = responseInfo.getResponseId(); // this.mediationAdapterClassName = responseInfo.getMediationAdapterClassName(); // final List<FlutterAdapterResponseInfo> adapterResponseInfos = new ArrayList<>(); // for (AdapterResponseInfo adapterInfo : responseInfo.getAdapterResponses()) { // adapterResponseInfos.add(new FlutterAdapterResponseInfo(adapterInfo)); // } // this.adapterResponses = adapterResponseInfos; // } // // FlutterResponseInfo( // @Nullable String responseId, // @Nullable String mediationAdapterClassName, // @NonNull List<FlutterAdapterResponseInfo> adapterResponseInfos) { // this.responseId = responseId; // this.mediationAdapterClassName = mediationAdapterClassName; // this.adapterResponses = adapterResponseInfos; // } // // @Nullable // String getResponseId() { // return responseId; // } // // @Nullable // String getMediationAdapterClassName() { // return mediationAdapterClassName; // } // // @NonNull // List<FlutterAdapterResponseInfo> getAdapterResponses() { // return adapterResponses; // } // // @Override // public boolean equals(@Nullable Object obj) { // if (obj == this) { // return true; // } else if (!(obj instanceof FlutterResponseInfo)) { // return false; // } // // FlutterResponseInfo that = (FlutterResponseInfo) obj; // return Objects.equals(responseId, that.responseId) // && Objects.equals(mediationAdapterClassName, that.mediationAdapterClassName) // && Objects.equals(adapterResponses, that.adapterResponses); // } // // @Override // public int hashCode() { // return Objects.hash(responseId, mediationAdapterClassName); // } // }
import android.app.Activity; import android.os.Handler; import android.os.Looper; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.android.gms.ads.AdError; import com.google.android.gms.ads.ResponseInfo; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugins.googlemobileads.FlutterAd.FlutterAdError; import io.flutter.plugins.googlemobileads.FlutterAd.FlutterResponseInfo; import java.util.HashMap; import java.util.Map;
throw new IllegalArgumentException( String.format("Ad for following adId already exists: %d", adId)); } ads.put(adId, ad); } void disposeAd(int adId) { if (!ads.containsKey(adId)) { return; } FlutterAd ad = ads.get(adId); if (ad != null) { ad.dispose(); } ads.remove(adId); } void disposeAllAds() { for (Map.Entry<Integer, FlutterAd> entry : ads.entrySet()) { if (entry.getValue() != null) { entry.getValue().dispose(); } } ads.clear(); } void onAdLoaded(int adId, @Nullable ResponseInfo responseInfo) { Map<Object, Object> arguments = new HashMap<>(); arguments.put("adId", adId); arguments.put("eventName", "onAdLoaded");
// Path: packages/google_mobile_ads/android/src/main/java/io/flutter/plugins/googlemobileads/FlutterAd.java // static class FlutterAdError { // final int code; // @NonNull final String domain; // @NonNull final String message; // // FlutterAdError(@NonNull AdError error) { // code = error.getCode(); // domain = error.getDomain(); // message = error.getMessage(); // } // // FlutterAdError(int code, @NonNull String domain, @NonNull String message) { // this.code = code; // this.domain = domain; // this.message = message; // } // // @Override // public boolean equals(Object object) { // if (this == object) { // return true; // } else if (!(object instanceof FlutterAdError)) { // return false; // } // // final FlutterAdError that = (FlutterAdError) object; // // if (code != that.code) { // return false; // } else if (!domain.equals(that.domain)) { // return false; // } // return message.equals(that.message); // } // // @Override // public int hashCode() { // return Objects.hash(code, domain, message); // } // } // // Path: packages/google_mobile_ads/android/src/main/java/io/flutter/plugins/googlemobileads/FlutterAd.java // static class FlutterResponseInfo { // // @Nullable private final String responseId; // @Nullable private final String mediationAdapterClassName; // @NonNull private final List<FlutterAdapterResponseInfo> adapterResponses; // // FlutterResponseInfo(@NonNull ResponseInfo responseInfo) { // this.responseId = responseInfo.getResponseId(); // this.mediationAdapterClassName = responseInfo.getMediationAdapterClassName(); // final List<FlutterAdapterResponseInfo> adapterResponseInfos = new ArrayList<>(); // for (AdapterResponseInfo adapterInfo : responseInfo.getAdapterResponses()) { // adapterResponseInfos.add(new FlutterAdapterResponseInfo(adapterInfo)); // } // this.adapterResponses = adapterResponseInfos; // } // // FlutterResponseInfo( // @Nullable String responseId, // @Nullable String mediationAdapterClassName, // @NonNull List<FlutterAdapterResponseInfo> adapterResponseInfos) { // this.responseId = responseId; // this.mediationAdapterClassName = mediationAdapterClassName; // this.adapterResponses = adapterResponseInfos; // } // // @Nullable // String getResponseId() { // return responseId; // } // // @Nullable // String getMediationAdapterClassName() { // return mediationAdapterClassName; // } // // @NonNull // List<FlutterAdapterResponseInfo> getAdapterResponses() { // return adapterResponses; // } // // @Override // public boolean equals(@Nullable Object obj) { // if (obj == this) { // return true; // } else if (!(obj instanceof FlutterResponseInfo)) { // return false; // } // // FlutterResponseInfo that = (FlutterResponseInfo) obj; // return Objects.equals(responseId, that.responseId) // && Objects.equals(mediationAdapterClassName, that.mediationAdapterClassName) // && Objects.equals(adapterResponses, that.adapterResponses); // } // // @Override // public int hashCode() { // return Objects.hash(responseId, mediationAdapterClassName); // } // } // Path: packages/google_mobile_ads/android/src/main/java/io/flutter/plugins/googlemobileads/AdInstanceManager.java import android.app.Activity; import android.os.Handler; import android.os.Looper; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.android.gms.ads.AdError; import com.google.android.gms.ads.ResponseInfo; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugins.googlemobileads.FlutterAd.FlutterAdError; import io.flutter.plugins.googlemobileads.FlutterAd.FlutterResponseInfo; import java.util.HashMap; import java.util.Map; throw new IllegalArgumentException( String.format("Ad for following adId already exists: %d", adId)); } ads.put(adId, ad); } void disposeAd(int adId) { if (!ads.containsKey(adId)) { return; } FlutterAd ad = ads.get(adId); if (ad != null) { ad.dispose(); } ads.remove(adId); } void disposeAllAds() { for (Map.Entry<Integer, FlutterAd> entry : ads.entrySet()) { if (entry.getValue() != null) { entry.getValue().dispose(); } } ads.clear(); } void onAdLoaded(int adId, @Nullable ResponseInfo responseInfo) { Map<Object, Object> arguments = new HashMap<>(); arguments.put("adId", adId); arguments.put("eventName", "onAdLoaded");
FlutterResponseInfo flutterResponseInfo =
googleads/googleads-mobile-flutter
packages/google_mobile_ads/android/src/main/java/io/flutter/plugins/googlemobileads/AdInstanceManager.java
// Path: packages/google_mobile_ads/android/src/main/java/io/flutter/plugins/googlemobileads/FlutterAd.java // static class FlutterAdError { // final int code; // @NonNull final String domain; // @NonNull final String message; // // FlutterAdError(@NonNull AdError error) { // code = error.getCode(); // domain = error.getDomain(); // message = error.getMessage(); // } // // FlutterAdError(int code, @NonNull String domain, @NonNull String message) { // this.code = code; // this.domain = domain; // this.message = message; // } // // @Override // public boolean equals(Object object) { // if (this == object) { // return true; // } else if (!(object instanceof FlutterAdError)) { // return false; // } // // final FlutterAdError that = (FlutterAdError) object; // // if (code != that.code) { // return false; // } else if (!domain.equals(that.domain)) { // return false; // } // return message.equals(that.message); // } // // @Override // public int hashCode() { // return Objects.hash(code, domain, message); // } // } // // Path: packages/google_mobile_ads/android/src/main/java/io/flutter/plugins/googlemobileads/FlutterAd.java // static class FlutterResponseInfo { // // @Nullable private final String responseId; // @Nullable private final String mediationAdapterClassName; // @NonNull private final List<FlutterAdapterResponseInfo> adapterResponses; // // FlutterResponseInfo(@NonNull ResponseInfo responseInfo) { // this.responseId = responseInfo.getResponseId(); // this.mediationAdapterClassName = responseInfo.getMediationAdapterClassName(); // final List<FlutterAdapterResponseInfo> adapterResponseInfos = new ArrayList<>(); // for (AdapterResponseInfo adapterInfo : responseInfo.getAdapterResponses()) { // adapterResponseInfos.add(new FlutterAdapterResponseInfo(adapterInfo)); // } // this.adapterResponses = adapterResponseInfos; // } // // FlutterResponseInfo( // @Nullable String responseId, // @Nullable String mediationAdapterClassName, // @NonNull List<FlutterAdapterResponseInfo> adapterResponseInfos) { // this.responseId = responseId; // this.mediationAdapterClassName = mediationAdapterClassName; // this.adapterResponses = adapterResponseInfos; // } // // @Nullable // String getResponseId() { // return responseId; // } // // @Nullable // String getMediationAdapterClassName() { // return mediationAdapterClassName; // } // // @NonNull // List<FlutterAdapterResponseInfo> getAdapterResponses() { // return adapterResponses; // } // // @Override // public boolean equals(@Nullable Object obj) { // if (obj == this) { // return true; // } else if (!(obj instanceof FlutterResponseInfo)) { // return false; // } // // FlutterResponseInfo that = (FlutterResponseInfo) obj; // return Objects.equals(responseId, that.responseId) // && Objects.equals(mediationAdapterClassName, that.mediationAdapterClassName) // && Objects.equals(adapterResponses, that.adapterResponses); // } // // @Override // public int hashCode() { // return Objects.hash(responseId, mediationAdapterClassName); // } // }
import android.app.Activity; import android.os.Handler; import android.os.Looper; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.android.gms.ads.AdError; import com.google.android.gms.ads.ResponseInfo; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugins.googlemobileads.FlutterAd.FlutterAdError; import io.flutter.plugins.googlemobileads.FlutterAd.FlutterResponseInfo; import java.util.HashMap; import java.util.Map;
final Map<Object, Object> arguments = new HashMap<>(); arguments.put("adId", adId); arguments.put("eventName", "onRewardedAdUserEarnedReward"); arguments.put("rewardItem", reward); invokeOnAdEvent(arguments); } void onRewardedInterstitialAdUserEarnedReward( int adId, @NonNull FlutterRewardedAd.FlutterRewardItem reward) { final Map<Object, Object> arguments = new HashMap<>(); arguments.put("adId", adId); arguments.put("eventName", "onRewardedInterstitialAdUserEarnedReward"); arguments.put("rewardItem", reward); invokeOnAdEvent(arguments); } void onPaidEvent(@NonNull FlutterAd ad, @NonNull FlutterAdValue adValue) { final Map<Object, Object> arguments = new HashMap<>(); arguments.put("adId", adIdFor(ad)); arguments.put("eventName", "onPaidEvent"); arguments.put("valueMicros", adValue.valueMicros); arguments.put("precision", adValue.precisionType); arguments.put("currencyCode", adValue.currencyCode); invokeOnAdEvent(arguments); } void onFailedToShowFullScreenContent(int adId, @NonNull AdError error) { final Map<Object, Object> arguments = new HashMap<>(); arguments.put("adId", adId); arguments.put("eventName", "onFailedToShowFullScreenContent");
// Path: packages/google_mobile_ads/android/src/main/java/io/flutter/plugins/googlemobileads/FlutterAd.java // static class FlutterAdError { // final int code; // @NonNull final String domain; // @NonNull final String message; // // FlutterAdError(@NonNull AdError error) { // code = error.getCode(); // domain = error.getDomain(); // message = error.getMessage(); // } // // FlutterAdError(int code, @NonNull String domain, @NonNull String message) { // this.code = code; // this.domain = domain; // this.message = message; // } // // @Override // public boolean equals(Object object) { // if (this == object) { // return true; // } else if (!(object instanceof FlutterAdError)) { // return false; // } // // final FlutterAdError that = (FlutterAdError) object; // // if (code != that.code) { // return false; // } else if (!domain.equals(that.domain)) { // return false; // } // return message.equals(that.message); // } // // @Override // public int hashCode() { // return Objects.hash(code, domain, message); // } // } // // Path: packages/google_mobile_ads/android/src/main/java/io/flutter/plugins/googlemobileads/FlutterAd.java // static class FlutterResponseInfo { // // @Nullable private final String responseId; // @Nullable private final String mediationAdapterClassName; // @NonNull private final List<FlutterAdapterResponseInfo> adapterResponses; // // FlutterResponseInfo(@NonNull ResponseInfo responseInfo) { // this.responseId = responseInfo.getResponseId(); // this.mediationAdapterClassName = responseInfo.getMediationAdapterClassName(); // final List<FlutterAdapterResponseInfo> adapterResponseInfos = new ArrayList<>(); // for (AdapterResponseInfo adapterInfo : responseInfo.getAdapterResponses()) { // adapterResponseInfos.add(new FlutterAdapterResponseInfo(adapterInfo)); // } // this.adapterResponses = adapterResponseInfos; // } // // FlutterResponseInfo( // @Nullable String responseId, // @Nullable String mediationAdapterClassName, // @NonNull List<FlutterAdapterResponseInfo> adapterResponseInfos) { // this.responseId = responseId; // this.mediationAdapterClassName = mediationAdapterClassName; // this.adapterResponses = adapterResponseInfos; // } // // @Nullable // String getResponseId() { // return responseId; // } // // @Nullable // String getMediationAdapterClassName() { // return mediationAdapterClassName; // } // // @NonNull // List<FlutterAdapterResponseInfo> getAdapterResponses() { // return adapterResponses; // } // // @Override // public boolean equals(@Nullable Object obj) { // if (obj == this) { // return true; // } else if (!(obj instanceof FlutterResponseInfo)) { // return false; // } // // FlutterResponseInfo that = (FlutterResponseInfo) obj; // return Objects.equals(responseId, that.responseId) // && Objects.equals(mediationAdapterClassName, that.mediationAdapterClassName) // && Objects.equals(adapterResponses, that.adapterResponses); // } // // @Override // public int hashCode() { // return Objects.hash(responseId, mediationAdapterClassName); // } // } // Path: packages/google_mobile_ads/android/src/main/java/io/flutter/plugins/googlemobileads/AdInstanceManager.java import android.app.Activity; import android.os.Handler; import android.os.Looper; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.android.gms.ads.AdError; import com.google.android.gms.ads.ResponseInfo; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugins.googlemobileads.FlutterAd.FlutterAdError; import io.flutter.plugins.googlemobileads.FlutterAd.FlutterResponseInfo; import java.util.HashMap; import java.util.Map; final Map<Object, Object> arguments = new HashMap<>(); arguments.put("adId", adId); arguments.put("eventName", "onRewardedAdUserEarnedReward"); arguments.put("rewardItem", reward); invokeOnAdEvent(arguments); } void onRewardedInterstitialAdUserEarnedReward( int adId, @NonNull FlutterRewardedAd.FlutterRewardItem reward) { final Map<Object, Object> arguments = new HashMap<>(); arguments.put("adId", adId); arguments.put("eventName", "onRewardedInterstitialAdUserEarnedReward"); arguments.put("rewardItem", reward); invokeOnAdEvent(arguments); } void onPaidEvent(@NonNull FlutterAd ad, @NonNull FlutterAdValue adValue) { final Map<Object, Object> arguments = new HashMap<>(); arguments.put("adId", adIdFor(ad)); arguments.put("eventName", "onPaidEvent"); arguments.put("valueMicros", adValue.valueMicros); arguments.put("precision", adValue.precisionType); arguments.put("currencyCode", adValue.currencyCode); invokeOnAdEvent(arguments); } void onFailedToShowFullScreenContent(int adId, @NonNull AdError error) { final Map<Object, Object> arguments = new HashMap<>(); arguments.put("adId", adId); arguments.put("eventName", "onFailedToShowFullScreenContent");
arguments.put("error", new FlutterAdError(error));
caiovidaln/ifcalc
app/src/main/java/ifcalc/beta/model/Anotacao.java
// Path: app/src/main/java/ifcalc/beta/database/DbHelper.java // public class DbHelper extends SQLiteOpenHelper { // // public static final String ID = "_id"; // // public static final String DISCIPLINA = "DISCIPLINA"; // public static final String TITULO = "materia"; // public static final String NOTAB1 = "bimest1"; // public static final String NOTAB2 = "bimest2"; // public static final String NOTAB3 = "bimest3"; // public static final String NOTAB4 = "bimest4"; // public static final String MEDIA = "media1"; // public static final String PROVA_FINAL = "provafinal"; // public static final String SITUACAO = "situacao"; // public static final String TIPO_DISCI = "tipodisci"; // public static final String ID_SUAP = "id_web"; // // public static final String ANOTACAO = "ANOTACAO"; // public static final String TITULO_ANOTACAO = "titulo"; // public static final String CORPO = "corpo"; // public static final String DATETIME = "datetime"; // // private static final String DB_NAME = "materiasatt.db"; // private static final int DB_VERSION = 6; // // public DbHelper(Context context) { // super(context, DB_NAME, null, DB_VERSION); // } // // @Override // public void onCreate(SQLiteDatabase database) { // createTables(database); // } // // @Override // public void onUpgrade(SQLiteDatabase dataBase, int oldVersion, int newVersion) { // try { // if(oldVersion < 4) { // dataBase.execSQL("ALTER TABLE lista RENAME TO " + DISCIPLINA); // dataBase.execSQL("ALTER TABLE " + DISCIPLINA + " ADD COLUMN " + ID_SUAP + " TEXT NOT NULL;"); // } else if(oldVersion == 4) { // dataBase.execSQL("CREATE TABLE IF NOT EXISTS " + DISCIPLINA + " (_id INTEGER PRIMARY KEY AUTOINCREMENT," + // TITULO + " TEXT NOT NULL, " + NOTAB1 + " NUMBER NOT NULL, " + NOTAB2 + " NUMBER NOT NULL, " // + NOTAB3 + " NUMBER NOT NULL, " + NOTAB4 + " NUMBER NOT NULL, " + PROVA_FINAL + " NUMBER NOT NULL, " // + MEDIA + " NUMBER NOT NULL, " + SITUACAO + " TEXT NOT NULL, " + TIPO_DISCI + " TEXT NOT NULL);"); // // dataBase.execSQL("CREATE TABLE IF NOT EXISTS " + ANOTACAO + " (_id INTEGER PRIMARY KEY AUTOINCREMENT," + // TITULO_ANOTACAO + " TEXT NOT NULL, " + CORPO + " TEXT NOT NULL, " + DATETIME + " TEXT NOT NULL);"); // // dataBase.execSQL("INSERT INTO " + DISCIPLINA + " SELECT " + TITULO + ", " + // NOTAB1 + ", " + NOTAB2 + ", " + NOTAB3 + ", " + // NOTAB4 + ", " + PROVA_FINAL + ", " + MEDIA + ", " + SITUACAO + ", " + // TIPO_DISCI + " FROM disciplinasnew;"); // // dataBase.execSQL("DROP TABLE IF EXISTS disciplinasnew;"); // // dataBase.execSQL("ALTER TABLE " + DISCIPLINA + " ADD COLUMN " + ID_SUAP + " TEXT NOT NULL;"); // } // } catch (Exception e) { // dataBase.execSQL("DROP TABLE IF EXISTS lista;"); // dataBase.execSQL("DROP TABLE IF EXISTS disciplinasnew;"); // dataBase.execSQL("DROP TABLE IF EXISTS " + DISCIPLINA + ";"); // dataBase.execSQL("DROP TABLE IF EXISTS " + ANOTACAO + ";"); // createTables(dataBase); // } // dataBase.setVersion(newVersion); // } // /** Method to create the table in the database // * @param dataBase // */ // private void createTables(SQLiteDatabase dataBase) { // Log.i(DB_NAME, "Criando Tabelas do Banco de Dados"); // // dataBase.execSQL("CREATE TABLE IF NOT EXISTS " + DISCIPLINA + " (_id INTEGER PRIMARY KEY AUTOINCREMENT," + // TITULO + " TEXT NOT NULL, " + NOTAB1 + " NUMBER NOT NULL, " + NOTAB2 + " NUMBER NOT NULL, " // + NOTAB3 + " NUMBER NOT NULL, " + NOTAB4 + " NUMBER NOT NULL, " + PROVA_FINAL + " NUMBER NOT NULL, " // + MEDIA + " NUMBER NOT NULL, " + SITUACAO + " TEXT NOT NULL, " + TIPO_DISCI + " TEXT NOT NULL, " // + ID_SUAP + " TEXT NOT NULL);"); // // dataBase.execSQL("CREATE TABLE IF NOT EXISTS " + ANOTACAO + " (_id INTEGER PRIMARY KEY AUTOINCREMENT," + // TITULO_ANOTACAO + " TEXT NOT NULL, " + CORPO + " TEXT NOT NULL, " + DATETIME + " TEXT NOT NULL);"); // // } // // public static final String[] COLUNAS_DISCIPLINA = new String [] { // ID, TITULO, NOTAB1, NOTAB2, NOTAB3, NOTAB4, PROVA_FINAL, MEDIA, SITUACAO, TIPO_DISCI, ID_SUAP // }; // // public static final String[] COLUNAS_ANOTACAO = new String [] { // ID, TITULO_ANOTACAO, CORPO, DATETIME // }; // }
import android.content.ContentValues; import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; import ifcalc.beta.database.DbHelper;
} public void setTitulo(String titulo) { this.titulo = titulo; } public String getCorpo() { return corpo; } public void setCorpo(String corpo) { this.corpo = corpo; } public Date getData() { return data; } public String getFormattedDate(String format) { SimpleDateFormat formt = new SimpleDateFormat(format); return formt.format(this.data); } public void setData(Date data) { this.data = data; } public ContentValues getContentValues() { ContentValues valores = new ContentValues();
// Path: app/src/main/java/ifcalc/beta/database/DbHelper.java // public class DbHelper extends SQLiteOpenHelper { // // public static final String ID = "_id"; // // public static final String DISCIPLINA = "DISCIPLINA"; // public static final String TITULO = "materia"; // public static final String NOTAB1 = "bimest1"; // public static final String NOTAB2 = "bimest2"; // public static final String NOTAB3 = "bimest3"; // public static final String NOTAB4 = "bimest4"; // public static final String MEDIA = "media1"; // public static final String PROVA_FINAL = "provafinal"; // public static final String SITUACAO = "situacao"; // public static final String TIPO_DISCI = "tipodisci"; // public static final String ID_SUAP = "id_web"; // // public static final String ANOTACAO = "ANOTACAO"; // public static final String TITULO_ANOTACAO = "titulo"; // public static final String CORPO = "corpo"; // public static final String DATETIME = "datetime"; // // private static final String DB_NAME = "materiasatt.db"; // private static final int DB_VERSION = 6; // // public DbHelper(Context context) { // super(context, DB_NAME, null, DB_VERSION); // } // // @Override // public void onCreate(SQLiteDatabase database) { // createTables(database); // } // // @Override // public void onUpgrade(SQLiteDatabase dataBase, int oldVersion, int newVersion) { // try { // if(oldVersion < 4) { // dataBase.execSQL("ALTER TABLE lista RENAME TO " + DISCIPLINA); // dataBase.execSQL("ALTER TABLE " + DISCIPLINA + " ADD COLUMN " + ID_SUAP + " TEXT NOT NULL;"); // } else if(oldVersion == 4) { // dataBase.execSQL("CREATE TABLE IF NOT EXISTS " + DISCIPLINA + " (_id INTEGER PRIMARY KEY AUTOINCREMENT," + // TITULO + " TEXT NOT NULL, " + NOTAB1 + " NUMBER NOT NULL, " + NOTAB2 + " NUMBER NOT NULL, " // + NOTAB3 + " NUMBER NOT NULL, " + NOTAB4 + " NUMBER NOT NULL, " + PROVA_FINAL + " NUMBER NOT NULL, " // + MEDIA + " NUMBER NOT NULL, " + SITUACAO + " TEXT NOT NULL, " + TIPO_DISCI + " TEXT NOT NULL);"); // // dataBase.execSQL("CREATE TABLE IF NOT EXISTS " + ANOTACAO + " (_id INTEGER PRIMARY KEY AUTOINCREMENT," + // TITULO_ANOTACAO + " TEXT NOT NULL, " + CORPO + " TEXT NOT NULL, " + DATETIME + " TEXT NOT NULL);"); // // dataBase.execSQL("INSERT INTO " + DISCIPLINA + " SELECT " + TITULO + ", " + // NOTAB1 + ", " + NOTAB2 + ", " + NOTAB3 + ", " + // NOTAB4 + ", " + PROVA_FINAL + ", " + MEDIA + ", " + SITUACAO + ", " + // TIPO_DISCI + " FROM disciplinasnew;"); // // dataBase.execSQL("DROP TABLE IF EXISTS disciplinasnew;"); // // dataBase.execSQL("ALTER TABLE " + DISCIPLINA + " ADD COLUMN " + ID_SUAP + " TEXT NOT NULL;"); // } // } catch (Exception e) { // dataBase.execSQL("DROP TABLE IF EXISTS lista;"); // dataBase.execSQL("DROP TABLE IF EXISTS disciplinasnew;"); // dataBase.execSQL("DROP TABLE IF EXISTS " + DISCIPLINA + ";"); // dataBase.execSQL("DROP TABLE IF EXISTS " + ANOTACAO + ";"); // createTables(dataBase); // } // dataBase.setVersion(newVersion); // } // /** Method to create the table in the database // * @param dataBase // */ // private void createTables(SQLiteDatabase dataBase) { // Log.i(DB_NAME, "Criando Tabelas do Banco de Dados"); // // dataBase.execSQL("CREATE TABLE IF NOT EXISTS " + DISCIPLINA + " (_id INTEGER PRIMARY KEY AUTOINCREMENT," + // TITULO + " TEXT NOT NULL, " + NOTAB1 + " NUMBER NOT NULL, " + NOTAB2 + " NUMBER NOT NULL, " // + NOTAB3 + " NUMBER NOT NULL, " + NOTAB4 + " NUMBER NOT NULL, " + PROVA_FINAL + " NUMBER NOT NULL, " // + MEDIA + " NUMBER NOT NULL, " + SITUACAO + " TEXT NOT NULL, " + TIPO_DISCI + " TEXT NOT NULL, " // + ID_SUAP + " TEXT NOT NULL);"); // // dataBase.execSQL("CREATE TABLE IF NOT EXISTS " + ANOTACAO + " (_id INTEGER PRIMARY KEY AUTOINCREMENT," + // TITULO_ANOTACAO + " TEXT NOT NULL, " + CORPO + " TEXT NOT NULL, " + DATETIME + " TEXT NOT NULL);"); // // } // // public static final String[] COLUNAS_DISCIPLINA = new String [] { // ID, TITULO, NOTAB1, NOTAB2, NOTAB3, NOTAB4, PROVA_FINAL, MEDIA, SITUACAO, TIPO_DISCI, ID_SUAP // }; // // public static final String[] COLUNAS_ANOTACAO = new String [] { // ID, TITULO_ANOTACAO, CORPO, DATETIME // }; // } // Path: app/src/main/java/ifcalc/beta/model/Anotacao.java import android.content.ContentValues; import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; import ifcalc.beta.database.DbHelper; } public void setTitulo(String titulo) { this.titulo = titulo; } public String getCorpo() { return corpo; } public void setCorpo(String corpo) { this.corpo = corpo; } public Date getData() { return data; } public String getFormattedDate(String format) { SimpleDateFormat formt = new SimpleDateFormat(format); return formt.format(this.data); } public void setData(Date data) { this.data = data; } public ContentValues getContentValues() { ContentValues valores = new ContentValues();
valores.put(DbHelper.TITULO_ANOTACAO, this.getTitulo());
caiovidaln/ifcalc
app/src/main/java/ifcalc/beta/model/Disciplina.java
// Path: app/src/main/java/ifcalc/beta/database/DbHelper.java // public class DbHelper extends SQLiteOpenHelper { // // public static final String ID = "_id"; // // public static final String DISCIPLINA = "DISCIPLINA"; // public static final String TITULO = "materia"; // public static final String NOTAB1 = "bimest1"; // public static final String NOTAB2 = "bimest2"; // public static final String NOTAB3 = "bimest3"; // public static final String NOTAB4 = "bimest4"; // public static final String MEDIA = "media1"; // public static final String PROVA_FINAL = "provafinal"; // public static final String SITUACAO = "situacao"; // public static final String TIPO_DISCI = "tipodisci"; // public static final String ID_SUAP = "id_web"; // // public static final String ANOTACAO = "ANOTACAO"; // public static final String TITULO_ANOTACAO = "titulo"; // public static final String CORPO = "corpo"; // public static final String DATETIME = "datetime"; // // private static final String DB_NAME = "materiasatt.db"; // private static final int DB_VERSION = 6; // // public DbHelper(Context context) { // super(context, DB_NAME, null, DB_VERSION); // } // // @Override // public void onCreate(SQLiteDatabase database) { // createTables(database); // } // // @Override // public void onUpgrade(SQLiteDatabase dataBase, int oldVersion, int newVersion) { // try { // if(oldVersion < 4) { // dataBase.execSQL("ALTER TABLE lista RENAME TO " + DISCIPLINA); // dataBase.execSQL("ALTER TABLE " + DISCIPLINA + " ADD COLUMN " + ID_SUAP + " TEXT NOT NULL;"); // } else if(oldVersion == 4) { // dataBase.execSQL("CREATE TABLE IF NOT EXISTS " + DISCIPLINA + " (_id INTEGER PRIMARY KEY AUTOINCREMENT," + // TITULO + " TEXT NOT NULL, " + NOTAB1 + " NUMBER NOT NULL, " + NOTAB2 + " NUMBER NOT NULL, " // + NOTAB3 + " NUMBER NOT NULL, " + NOTAB4 + " NUMBER NOT NULL, " + PROVA_FINAL + " NUMBER NOT NULL, " // + MEDIA + " NUMBER NOT NULL, " + SITUACAO + " TEXT NOT NULL, " + TIPO_DISCI + " TEXT NOT NULL);"); // // dataBase.execSQL("CREATE TABLE IF NOT EXISTS " + ANOTACAO + " (_id INTEGER PRIMARY KEY AUTOINCREMENT," + // TITULO_ANOTACAO + " TEXT NOT NULL, " + CORPO + " TEXT NOT NULL, " + DATETIME + " TEXT NOT NULL);"); // // dataBase.execSQL("INSERT INTO " + DISCIPLINA + " SELECT " + TITULO + ", " + // NOTAB1 + ", " + NOTAB2 + ", " + NOTAB3 + ", " + // NOTAB4 + ", " + PROVA_FINAL + ", " + MEDIA + ", " + SITUACAO + ", " + // TIPO_DISCI + " FROM disciplinasnew;"); // // dataBase.execSQL("DROP TABLE IF EXISTS disciplinasnew;"); // // dataBase.execSQL("ALTER TABLE " + DISCIPLINA + " ADD COLUMN " + ID_SUAP + " TEXT NOT NULL;"); // } // } catch (Exception e) { // dataBase.execSQL("DROP TABLE IF EXISTS lista;"); // dataBase.execSQL("DROP TABLE IF EXISTS disciplinasnew;"); // dataBase.execSQL("DROP TABLE IF EXISTS " + DISCIPLINA + ";"); // dataBase.execSQL("DROP TABLE IF EXISTS " + ANOTACAO + ";"); // createTables(dataBase); // } // dataBase.setVersion(newVersion); // } // /** Method to create the table in the database // * @param dataBase // */ // private void createTables(SQLiteDatabase dataBase) { // Log.i(DB_NAME, "Criando Tabelas do Banco de Dados"); // // dataBase.execSQL("CREATE TABLE IF NOT EXISTS " + DISCIPLINA + " (_id INTEGER PRIMARY KEY AUTOINCREMENT," + // TITULO + " TEXT NOT NULL, " + NOTAB1 + " NUMBER NOT NULL, " + NOTAB2 + " NUMBER NOT NULL, " // + NOTAB3 + " NUMBER NOT NULL, " + NOTAB4 + " NUMBER NOT NULL, " + PROVA_FINAL + " NUMBER NOT NULL, " // + MEDIA + " NUMBER NOT NULL, " + SITUACAO + " TEXT NOT NULL, " + TIPO_DISCI + " TEXT NOT NULL, " // + ID_SUAP + " TEXT NOT NULL);"); // // dataBase.execSQL("CREATE TABLE IF NOT EXISTS " + ANOTACAO + " (_id INTEGER PRIMARY KEY AUTOINCREMENT," + // TITULO_ANOTACAO + " TEXT NOT NULL, " + CORPO + " TEXT NOT NULL, " + DATETIME + " TEXT NOT NULL);"); // // } // // public static final String[] COLUNAS_DISCIPLINA = new String [] { // ID, TITULO, NOTAB1, NOTAB2, NOTAB3, NOTAB4, PROVA_FINAL, MEDIA, SITUACAO, TIPO_DISCI, ID_SUAP // }; // // public static final String[] COLUNAS_ANOTACAO = new String [] { // ID, TITULO_ANOTACAO, CORPO, DATETIME // }; // }
import android.content.ContentValues; import java.math.BigDecimal; import java.math.RoundingMode; import ifcalc.beta.database.DbHelper;
public void setProvaFinal(Double provaFinal) { this.provaFinal = provaFinal; } public Double getMedia() { return media; } public String getMedia(boolean zeroACem) { BigDecimal mediaDecimal = new BigDecimal(media).setScale(1, RoundingMode.HALF_EVEN); return (zeroACem) ? String.valueOf((int) (Math.round(media))) : String.valueOf(mediaDecimal.doubleValue()); } public void setMedia(Double media) { this.media = media; } public TipoDisciplina getTipoDisciplina() { return tipoDisciplina; } public void setTipoDisciplina(TipoDisciplina tipoDisciplina) { this.tipoDisciplina = tipoDisciplina; } public ContentValues getContentValues() { ContentValues valores = new ContentValues(); if(this.getTipoDisciplina() == TipoDisciplina.ANUAL) {
// Path: app/src/main/java/ifcalc/beta/database/DbHelper.java // public class DbHelper extends SQLiteOpenHelper { // // public static final String ID = "_id"; // // public static final String DISCIPLINA = "DISCIPLINA"; // public static final String TITULO = "materia"; // public static final String NOTAB1 = "bimest1"; // public static final String NOTAB2 = "bimest2"; // public static final String NOTAB3 = "bimest3"; // public static final String NOTAB4 = "bimest4"; // public static final String MEDIA = "media1"; // public static final String PROVA_FINAL = "provafinal"; // public static final String SITUACAO = "situacao"; // public static final String TIPO_DISCI = "tipodisci"; // public static final String ID_SUAP = "id_web"; // // public static final String ANOTACAO = "ANOTACAO"; // public static final String TITULO_ANOTACAO = "titulo"; // public static final String CORPO = "corpo"; // public static final String DATETIME = "datetime"; // // private static final String DB_NAME = "materiasatt.db"; // private static final int DB_VERSION = 6; // // public DbHelper(Context context) { // super(context, DB_NAME, null, DB_VERSION); // } // // @Override // public void onCreate(SQLiteDatabase database) { // createTables(database); // } // // @Override // public void onUpgrade(SQLiteDatabase dataBase, int oldVersion, int newVersion) { // try { // if(oldVersion < 4) { // dataBase.execSQL("ALTER TABLE lista RENAME TO " + DISCIPLINA); // dataBase.execSQL("ALTER TABLE " + DISCIPLINA + " ADD COLUMN " + ID_SUAP + " TEXT NOT NULL;"); // } else if(oldVersion == 4) { // dataBase.execSQL("CREATE TABLE IF NOT EXISTS " + DISCIPLINA + " (_id INTEGER PRIMARY KEY AUTOINCREMENT," + // TITULO + " TEXT NOT NULL, " + NOTAB1 + " NUMBER NOT NULL, " + NOTAB2 + " NUMBER NOT NULL, " // + NOTAB3 + " NUMBER NOT NULL, " + NOTAB4 + " NUMBER NOT NULL, " + PROVA_FINAL + " NUMBER NOT NULL, " // + MEDIA + " NUMBER NOT NULL, " + SITUACAO + " TEXT NOT NULL, " + TIPO_DISCI + " TEXT NOT NULL);"); // // dataBase.execSQL("CREATE TABLE IF NOT EXISTS " + ANOTACAO + " (_id INTEGER PRIMARY KEY AUTOINCREMENT," + // TITULO_ANOTACAO + " TEXT NOT NULL, " + CORPO + " TEXT NOT NULL, " + DATETIME + " TEXT NOT NULL);"); // // dataBase.execSQL("INSERT INTO " + DISCIPLINA + " SELECT " + TITULO + ", " + // NOTAB1 + ", " + NOTAB2 + ", " + NOTAB3 + ", " + // NOTAB4 + ", " + PROVA_FINAL + ", " + MEDIA + ", " + SITUACAO + ", " + // TIPO_DISCI + " FROM disciplinasnew;"); // // dataBase.execSQL("DROP TABLE IF EXISTS disciplinasnew;"); // // dataBase.execSQL("ALTER TABLE " + DISCIPLINA + " ADD COLUMN " + ID_SUAP + " TEXT NOT NULL;"); // } // } catch (Exception e) { // dataBase.execSQL("DROP TABLE IF EXISTS lista;"); // dataBase.execSQL("DROP TABLE IF EXISTS disciplinasnew;"); // dataBase.execSQL("DROP TABLE IF EXISTS " + DISCIPLINA + ";"); // dataBase.execSQL("DROP TABLE IF EXISTS " + ANOTACAO + ";"); // createTables(dataBase); // } // dataBase.setVersion(newVersion); // } // /** Method to create the table in the database // * @param dataBase // */ // private void createTables(SQLiteDatabase dataBase) { // Log.i(DB_NAME, "Criando Tabelas do Banco de Dados"); // // dataBase.execSQL("CREATE TABLE IF NOT EXISTS " + DISCIPLINA + " (_id INTEGER PRIMARY KEY AUTOINCREMENT," + // TITULO + " TEXT NOT NULL, " + NOTAB1 + " NUMBER NOT NULL, " + NOTAB2 + " NUMBER NOT NULL, " // + NOTAB3 + " NUMBER NOT NULL, " + NOTAB4 + " NUMBER NOT NULL, " + PROVA_FINAL + " NUMBER NOT NULL, " // + MEDIA + " NUMBER NOT NULL, " + SITUACAO + " TEXT NOT NULL, " + TIPO_DISCI + " TEXT NOT NULL, " // + ID_SUAP + " TEXT NOT NULL);"); // // dataBase.execSQL("CREATE TABLE IF NOT EXISTS " + ANOTACAO + " (_id INTEGER PRIMARY KEY AUTOINCREMENT," + // TITULO_ANOTACAO + " TEXT NOT NULL, " + CORPO + " TEXT NOT NULL, " + DATETIME + " TEXT NOT NULL);"); // // } // // public static final String[] COLUNAS_DISCIPLINA = new String [] { // ID, TITULO, NOTAB1, NOTAB2, NOTAB3, NOTAB4, PROVA_FINAL, MEDIA, SITUACAO, TIPO_DISCI, ID_SUAP // }; // // public static final String[] COLUNAS_ANOTACAO = new String [] { // ID, TITULO_ANOTACAO, CORPO, DATETIME // }; // } // Path: app/src/main/java/ifcalc/beta/model/Disciplina.java import android.content.ContentValues; import java.math.BigDecimal; import java.math.RoundingMode; import ifcalc.beta.database.DbHelper; public void setProvaFinal(Double provaFinal) { this.provaFinal = provaFinal; } public Double getMedia() { return media; } public String getMedia(boolean zeroACem) { BigDecimal mediaDecimal = new BigDecimal(media).setScale(1, RoundingMode.HALF_EVEN); return (zeroACem) ? String.valueOf((int) (Math.round(media))) : String.valueOf(mediaDecimal.doubleValue()); } public void setMedia(Double media) { this.media = media; } public TipoDisciplina getTipoDisciplina() { return tipoDisciplina; } public void setTipoDisciplina(TipoDisciplina tipoDisciplina) { this.tipoDisciplina = tipoDisciplina; } public ContentValues getContentValues() { ContentValues valores = new ContentValues(); if(this.getTipoDisciplina() == TipoDisciplina.ANUAL) {
valores.put(DbHelper.TIPO_DISCI, 1);
caiovidaln/ifcalc
app/src/main/java/ifcalc/beta/model/NotasCalculadoraSemestral.java
// Path: app/src/main/java/ifcalc/beta/util/ResultadoCalculo.java // public class ResultadoCalculo implements Comparable { // private String situacao; // private String mensagem; // private double mediaFinal; // private double notaNecessaria; // // public ResultadoCalculo() { // } // // public ResultadoCalculo(String situacao, String mensagem, double mediaFinal, double notaNecessaria) { // this.situacao = situacao; // this.mensagem = mensagem; // this.mediaFinal = mediaFinal; // this.notaNecessaria = notaNecessaria; // } // public String getSituacao() { // return situacao; // } // // public void setSituacao(String situacao) { // this.situacao = situacao; // } // // public String getMensagem() { // return mensagem; // } // // public void setMensagem(String mensagem) { // this.mensagem = mensagem; // } // // public double getMediaFinal() { // return mediaFinal; // } // // public void setMediaFinal(double mediaFinal) { // this.mediaFinal = mediaFinal; // } // // public double getNotaNecessaria() { // return notaNecessaria; // } // // public void setNotaNecessaria(double notaNecessaria) { // this.notaNecessaria = notaNecessaria; // } // // @Override // public int compareTo(Object object) { // if (object instanceof ResultadoCalculo) { // ResultadoCalculo rest = (ResultadoCalculo) object; // if(this.getMediaFinal() >= rest.getMediaFinal()) // return 1; // else // return -1; // } // return 0; // } // }
import java.math.BigDecimal; import java.math.RoundingMode; import ifcalc.beta.util.ResultadoCalculo;
package ifcalc.beta.model; public class NotasCalculadoraSemestral extends NotasCalculadora { public NotasCalculadoraSemestral(boolean zeroAcem, Double nota1, Double nota2, Double notaProvaFinal) { super(zeroAcem, nota1, nota2, notaProvaFinal); } @Override
// Path: app/src/main/java/ifcalc/beta/util/ResultadoCalculo.java // public class ResultadoCalculo implements Comparable { // private String situacao; // private String mensagem; // private double mediaFinal; // private double notaNecessaria; // // public ResultadoCalculo() { // } // // public ResultadoCalculo(String situacao, String mensagem, double mediaFinal, double notaNecessaria) { // this.situacao = situacao; // this.mensagem = mensagem; // this.mediaFinal = mediaFinal; // this.notaNecessaria = notaNecessaria; // } // public String getSituacao() { // return situacao; // } // // public void setSituacao(String situacao) { // this.situacao = situacao; // } // // public String getMensagem() { // return mensagem; // } // // public void setMensagem(String mensagem) { // this.mensagem = mensagem; // } // // public double getMediaFinal() { // return mediaFinal; // } // // public void setMediaFinal(double mediaFinal) { // this.mediaFinal = mediaFinal; // } // // public double getNotaNecessaria() { // return notaNecessaria; // } // // public void setNotaNecessaria(double notaNecessaria) { // this.notaNecessaria = notaNecessaria; // } // // @Override // public int compareTo(Object object) { // if (object instanceof ResultadoCalculo) { // ResultadoCalculo rest = (ResultadoCalculo) object; // if(this.getMediaFinal() >= rest.getMediaFinal()) // return 1; // else // return -1; // } // return 0; // } // } // Path: app/src/main/java/ifcalc/beta/model/NotasCalculadoraSemestral.java import java.math.BigDecimal; import java.math.RoundingMode; import ifcalc.beta.util.ResultadoCalculo; package ifcalc.beta.model; public class NotasCalculadoraSemestral extends NotasCalculadora { public NotasCalculadoraSemestral(boolean zeroAcem, Double nota1, Double nota2, Double notaProvaFinal) { super(zeroAcem, nota1, nota2, notaProvaFinal); } @Override
public ResultadoCalculo calculaNotas(ConfiguracoesDisciplinas configuracoesDisciplinas) {
caiovidaln/ifcalc
app/src/main/java/ifcalc/beta/model/NotasCalculadora.java
// Path: app/src/main/java/ifcalc/beta/util/ResultadoCalculo.java // public class ResultadoCalculo implements Comparable { // private String situacao; // private String mensagem; // private double mediaFinal; // private double notaNecessaria; // // public ResultadoCalculo() { // } // // public ResultadoCalculo(String situacao, String mensagem, double mediaFinal, double notaNecessaria) { // this.situacao = situacao; // this.mensagem = mensagem; // this.mediaFinal = mediaFinal; // this.notaNecessaria = notaNecessaria; // } // public String getSituacao() { // return situacao; // } // // public void setSituacao(String situacao) { // this.situacao = situacao; // } // // public String getMensagem() { // return mensagem; // } // // public void setMensagem(String mensagem) { // this.mensagem = mensagem; // } // // public double getMediaFinal() { // return mediaFinal; // } // // public void setMediaFinal(double mediaFinal) { // this.mediaFinal = mediaFinal; // } // // public double getNotaNecessaria() { // return notaNecessaria; // } // // public void setNotaNecessaria(double notaNecessaria) { // this.notaNecessaria = notaNecessaria; // } // // @Override // public int compareTo(Object object) { // if (object instanceof ResultadoCalculo) { // ResultadoCalculo rest = (ResultadoCalculo) object; // if(this.getMediaFinal() >= rest.getMediaFinal()) // return 1; // else // return -1; // } // return 0; // } // }
import java.math.BigDecimal; import java.math.RoundingMode; import ifcalc.beta.util.ResultadoCalculo;
package ifcalc.beta.model; public abstract class NotasCalculadora { protected Double nota1; protected Double nota2; protected Double nota3; protected Double nota4; protected Double notaProvaFinal; protected int pesoB1; protected int pesoB2; protected int pesoB3; protected int pesoB4; protected int somaPesos; protected int mediaNecessaria; protected int notaNecessariaTotal; protected int notaMax; protected boolean zeroACem; public NotasCalculadora(boolean zeroAcem, Double nota1, Double nota2, Double notaProvaFinal) { notaMax = zeroAcem ? 100 : 10; this.zeroACem = zeroAcem; this.nota1 = nota1; this.nota2 = nota2; this.notaProvaFinal = notaProvaFinal; }
// Path: app/src/main/java/ifcalc/beta/util/ResultadoCalculo.java // public class ResultadoCalculo implements Comparable { // private String situacao; // private String mensagem; // private double mediaFinal; // private double notaNecessaria; // // public ResultadoCalculo() { // } // // public ResultadoCalculo(String situacao, String mensagem, double mediaFinal, double notaNecessaria) { // this.situacao = situacao; // this.mensagem = mensagem; // this.mediaFinal = mediaFinal; // this.notaNecessaria = notaNecessaria; // } // public String getSituacao() { // return situacao; // } // // public void setSituacao(String situacao) { // this.situacao = situacao; // } // // public String getMensagem() { // return mensagem; // } // // public void setMensagem(String mensagem) { // this.mensagem = mensagem; // } // // public double getMediaFinal() { // return mediaFinal; // } // // public void setMediaFinal(double mediaFinal) { // this.mediaFinal = mediaFinal; // } // // public double getNotaNecessaria() { // return notaNecessaria; // } // // public void setNotaNecessaria(double notaNecessaria) { // this.notaNecessaria = notaNecessaria; // } // // @Override // public int compareTo(Object object) { // if (object instanceof ResultadoCalculo) { // ResultadoCalculo rest = (ResultadoCalculo) object; // if(this.getMediaFinal() >= rest.getMediaFinal()) // return 1; // else // return -1; // } // return 0; // } // } // Path: app/src/main/java/ifcalc/beta/model/NotasCalculadora.java import java.math.BigDecimal; import java.math.RoundingMode; import ifcalc.beta.util.ResultadoCalculo; package ifcalc.beta.model; public abstract class NotasCalculadora { protected Double nota1; protected Double nota2; protected Double nota3; protected Double nota4; protected Double notaProvaFinal; protected int pesoB1; protected int pesoB2; protected int pesoB3; protected int pesoB4; protected int somaPesos; protected int mediaNecessaria; protected int notaNecessariaTotal; protected int notaMax; protected boolean zeroACem; public NotasCalculadora(boolean zeroAcem, Double nota1, Double nota2, Double notaProvaFinal) { notaMax = zeroAcem ? 100 : 10; this.zeroACem = zeroAcem; this.nota1 = nota1; this.nota2 = nota2; this.notaProvaFinal = notaProvaFinal; }
public abstract ResultadoCalculo calculaNotas(ConfiguracoesDisciplinas configuracoesDisciplinas);
caiovidaln/ifcalc
app/src/main/java/ifcalc/beta/model/NotasCalculadoraAnual.java
// Path: app/src/main/java/ifcalc/beta/util/ResultadoCalculo.java // public class ResultadoCalculo implements Comparable { // private String situacao; // private String mensagem; // private double mediaFinal; // private double notaNecessaria; // // public ResultadoCalculo() { // } // // public ResultadoCalculo(String situacao, String mensagem, double mediaFinal, double notaNecessaria) { // this.situacao = situacao; // this.mensagem = mensagem; // this.mediaFinal = mediaFinal; // this.notaNecessaria = notaNecessaria; // } // public String getSituacao() { // return situacao; // } // // public void setSituacao(String situacao) { // this.situacao = situacao; // } // // public String getMensagem() { // return mensagem; // } // // public void setMensagem(String mensagem) { // this.mensagem = mensagem; // } // // public double getMediaFinal() { // return mediaFinal; // } // // public void setMediaFinal(double mediaFinal) { // this.mediaFinal = mediaFinal; // } // // public double getNotaNecessaria() { // return notaNecessaria; // } // // public void setNotaNecessaria(double notaNecessaria) { // this.notaNecessaria = notaNecessaria; // } // // @Override // public int compareTo(Object object) { // if (object instanceof ResultadoCalculo) { // ResultadoCalculo rest = (ResultadoCalculo) object; // if(this.getMediaFinal() >= rest.getMediaFinal()) // return 1; // else // return -1; // } // return 0; // } // }
import java.math.BigDecimal; import java.math.RoundingMode; import ifcalc.beta.util.ResultadoCalculo;
package ifcalc.beta.model; public class NotasCalculadoraAnual extends NotasCalculadora { public NotasCalculadoraAnual(boolean zeroAcem, Double nota1, Double nota2, Double nota3, Double nota4, Double notaProvaFinal) { super(zeroAcem, nota1, nota2, notaProvaFinal); this.nota3 = nota3; this.nota4 = nota4; } @Override
// Path: app/src/main/java/ifcalc/beta/util/ResultadoCalculo.java // public class ResultadoCalculo implements Comparable { // private String situacao; // private String mensagem; // private double mediaFinal; // private double notaNecessaria; // // public ResultadoCalculo() { // } // // public ResultadoCalculo(String situacao, String mensagem, double mediaFinal, double notaNecessaria) { // this.situacao = situacao; // this.mensagem = mensagem; // this.mediaFinal = mediaFinal; // this.notaNecessaria = notaNecessaria; // } // public String getSituacao() { // return situacao; // } // // public void setSituacao(String situacao) { // this.situacao = situacao; // } // // public String getMensagem() { // return mensagem; // } // // public void setMensagem(String mensagem) { // this.mensagem = mensagem; // } // // public double getMediaFinal() { // return mediaFinal; // } // // public void setMediaFinal(double mediaFinal) { // this.mediaFinal = mediaFinal; // } // // public double getNotaNecessaria() { // return notaNecessaria; // } // // public void setNotaNecessaria(double notaNecessaria) { // this.notaNecessaria = notaNecessaria; // } // // @Override // public int compareTo(Object object) { // if (object instanceof ResultadoCalculo) { // ResultadoCalculo rest = (ResultadoCalculo) object; // if(this.getMediaFinal() >= rest.getMediaFinal()) // return 1; // else // return -1; // } // return 0; // } // } // Path: app/src/main/java/ifcalc/beta/model/NotasCalculadoraAnual.java import java.math.BigDecimal; import java.math.RoundingMode; import ifcalc.beta.util.ResultadoCalculo; package ifcalc.beta.model; public class NotasCalculadoraAnual extends NotasCalculadora { public NotasCalculadoraAnual(boolean zeroAcem, Double nota1, Double nota2, Double nota3, Double nota4, Double notaProvaFinal) { super(zeroAcem, nota1, nota2, notaProvaFinal); this.nota3 = nota3; this.nota4 = nota4; } @Override
public ResultadoCalculo calculaNotas(ConfiguracoesDisciplinas configuracoesDisciplinas) {